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.
7 #if V8_TARGET_ARCH_IA32
9 #include "src/code-factory.h"
10 #include "src/code-stubs.h"
11 #include "src/codegen.h"
12 #include "src/compiler.h"
13 #include "src/debug.h"
14 #include "src/full-codegen.h"
15 #include "src/ic/ic.h"
16 #include "src/isolate-inl.h"
17 #include "src/parser.h"
18 #include "src/scopes.h"
23 #define __ ACCESS_MASM(masm_)
26 class JumpPatchSite BASE_EMBEDDED {
28 explicit JumpPatchSite(MacroAssembler* masm) : masm_(masm) {
30 info_emitted_ = false;
35 DCHECK(patch_site_.is_bound() == info_emitted_);
38 void EmitJumpIfNotSmi(Register reg,
40 Label::Distance distance = Label::kFar) {
41 __ test(reg, Immediate(kSmiTagMask));
42 EmitJump(not_carry, target, distance); // Always taken before patched.
45 void EmitJumpIfSmi(Register reg,
47 Label::Distance distance = Label::kFar) {
48 __ test(reg, Immediate(kSmiTagMask));
49 EmitJump(carry, target, distance); // Never taken before patched.
52 void EmitPatchInfo() {
53 if (patch_site_.is_bound()) {
54 int delta_to_patch_site = masm_->SizeOfCodeGeneratedSince(&patch_site_);
55 DCHECK(is_uint8(delta_to_patch_site));
56 __ test(eax, Immediate(delta_to_patch_site));
61 __ nop(); // Signals no inlined code.
66 // jc will be patched with jz, jnc will become jnz.
67 void EmitJump(Condition cc, Label* target, Label::Distance distance) {
68 DCHECK(!patch_site_.is_bound() && !info_emitted_);
69 DCHECK(cc == carry || cc == not_carry);
70 __ bind(&patch_site_);
71 __ j(cc, target, distance);
74 MacroAssembler* masm_;
82 // Generate code for a JS function. On entry to the function the receiver
83 // and arguments have been pushed on the stack left to right, with the
84 // return address on top of them. The actual argument count matches the
85 // formal parameter count expected by the function.
87 // The live registers are:
88 // o edi: the JS function object being called (i.e. ourselves)
90 // o ebp: our caller's frame pointer
91 // o esp: stack pointer (pointing to return address)
93 // The function builds a JS frame. Please see JavaScriptFrameConstants in
94 // frames-ia32.h for its layout.
95 void FullCodeGenerator::Generate() {
96 CompilationInfo* info = info_;
98 Handle<HandlerTable>::cast(isolate()->factory()->NewFixedArray(
99 HandlerTable::LengthForRange(function()->handler_count()), TENURED));
101 profiling_counter_ = isolate()->factory()->NewCell(
102 Handle<Smi>(Smi::FromInt(FLAG_interrupt_budget), isolate()));
103 SetFunctionPosition(function());
104 Comment cmnt(masm_, "[ function compiled by full code generator");
106 ProfileEntryHookStub::MaybeCallEntryHook(masm_);
109 if (strlen(FLAG_stop_at) > 0 &&
110 info->function()->name()->IsUtf8EqualTo(CStrVector(FLAG_stop_at))) {
115 // Sloppy mode functions and builtins need to replace the receiver with the
116 // global proxy when called as functions (without an explicit receiver
118 if (is_sloppy(info->language_mode()) && !info->is_native()) {
120 // +1 for return address.
121 int receiver_offset = (info->scope()->num_parameters() + 1) * kPointerSize;
122 __ mov(ecx, Operand(esp, receiver_offset));
124 __ cmp(ecx, isolate()->factory()->undefined_value());
125 __ j(not_equal, &ok, Label::kNear);
127 __ mov(ecx, GlobalObjectOperand());
128 __ mov(ecx, FieldOperand(ecx, GlobalObject::kGlobalProxyOffset));
130 __ mov(Operand(esp, receiver_offset), ecx);
135 // Open a frame scope to indicate that there is a frame on the stack. The
136 // MANUAL indicates that the scope shouldn't actually generate code to set up
137 // the frame (that is done below).
138 FrameScope frame_scope(masm_, StackFrame::MANUAL);
140 info->set_prologue_offset(masm_->pc_offset());
141 __ Prologue(info->IsCodePreAgingActive());
142 info->AddNoFrameRange(0, masm_->pc_offset());
144 { Comment cmnt(masm_, "[ Allocate locals");
145 int locals_count = info->scope()->num_stack_slots();
146 // Generators allocate locals, if any, in context slots.
147 DCHECK(!IsGeneratorFunction(info->function()->kind()) || locals_count == 0);
148 if (locals_count == 1) {
149 __ push(Immediate(isolate()->factory()->undefined_value()));
150 } else if (locals_count > 1) {
151 if (locals_count >= 128) {
154 __ sub(ecx, Immediate(locals_count * kPointerSize));
155 ExternalReference stack_limit =
156 ExternalReference::address_of_real_stack_limit(isolate());
157 __ cmp(ecx, Operand::StaticVariable(stack_limit));
158 __ j(above_equal, &ok, Label::kNear);
159 __ InvokeBuiltin(Builtins::STACK_OVERFLOW, CALL_FUNCTION);
162 __ mov(eax, Immediate(isolate()->factory()->undefined_value()));
163 const int kMaxPushes = 32;
164 if (locals_count >= kMaxPushes) {
165 int loop_iterations = locals_count / kMaxPushes;
166 __ mov(ecx, loop_iterations);
168 __ bind(&loop_header);
170 for (int i = 0; i < kMaxPushes; i++) {
174 __ j(not_zero, &loop_header, Label::kNear);
176 int remaining = locals_count % kMaxPushes;
177 // Emit the remaining pushes.
178 for (int i = 0; i < remaining; i++) {
184 bool function_in_register = true;
186 // Possibly allocate a local context.
187 int heap_slots = info->scope()->num_heap_slots() - Context::MIN_CONTEXT_SLOTS;
188 if (heap_slots > 0) {
189 Comment cmnt(masm_, "[ Allocate context");
190 bool need_write_barrier = true;
191 // Argument to NewContext is the function, which is still in edi.
192 if (info->scope()->is_script_scope()) {
194 __ Push(info->scope()->GetScopeInfo(info->isolate()));
195 __ CallRuntime(Runtime::kNewScriptContext, 2);
196 } else if (heap_slots <= FastNewContextStub::kMaximumSlots) {
197 FastNewContextStub stub(isolate(), heap_slots);
199 // Result of FastNewContextStub is always in new space.
200 need_write_barrier = false;
203 __ CallRuntime(Runtime::kNewFunctionContext, 1);
205 function_in_register = false;
206 // Context is returned in eax. It replaces the context passed to us.
207 // It's saved in the stack and kept live in esi.
209 __ mov(Operand(ebp, StandardFrameConstants::kContextOffset), eax);
211 // Copy parameters into context if necessary.
212 int num_parameters = info->scope()->num_parameters();
213 for (int i = 0; i < num_parameters; i++) {
214 Variable* var = scope()->parameter(i);
215 if (var->IsContextSlot()) {
216 int parameter_offset = StandardFrameConstants::kCallerSPOffset +
217 (num_parameters - 1 - i) * kPointerSize;
218 // Load parameter from stack.
219 __ mov(eax, Operand(ebp, parameter_offset));
220 // Store it in the context.
221 int context_offset = Context::SlotOffset(var->index());
222 __ mov(Operand(esi, context_offset), eax);
223 // Update the write barrier. This clobbers eax and ebx.
224 if (need_write_barrier) {
225 __ RecordWriteContextSlot(esi,
230 } else if (FLAG_debug_code) {
232 __ JumpIfInNewSpace(esi, eax, &done, Label::kNear);
233 __ Abort(kExpectedNewSpaceObject);
240 ArgumentsAccessStub::HasNewTarget has_new_target =
241 IsSubclassConstructor(info->function()->kind())
242 ? ArgumentsAccessStub::HAS_NEW_TARGET
243 : ArgumentsAccessStub::NO_NEW_TARGET;
245 // Possibly allocate RestParameters
247 Variable* rest_param = scope()->rest_parameter(&rest_index);
249 Comment cmnt(masm_, "[ Allocate rest parameter array");
251 int num_parameters = info->scope()->num_parameters();
252 int offset = num_parameters * kPointerSize;
253 if (has_new_target == ArgumentsAccessStub::HAS_NEW_TARGET) {
259 Operand(ebp, StandardFrameConstants::kCallerSPOffset + offset));
261 __ push(Immediate(Smi::FromInt(num_parameters)));
262 __ push(Immediate(Smi::FromInt(rest_index)));
264 RestParamAccessStub stub(isolate());
267 SetVar(rest_param, eax, ebx, edx);
270 Variable* arguments = scope()->arguments();
271 if (arguments != NULL) {
272 // Function uses arguments object.
273 Comment cmnt(masm_, "[ Allocate arguments object");
274 if (function_in_register) {
277 __ push(Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
279 // Receiver is just before the parameters on the caller's stack.
280 int num_parameters = info->scope()->num_parameters();
281 int offset = num_parameters * kPointerSize;
283 Operand(ebp, StandardFrameConstants::kCallerSPOffset + offset));
285 __ push(Immediate(Smi::FromInt(num_parameters)));
286 // Arguments to ArgumentsAccessStub:
287 // function, receiver address, parameter count.
288 // The stub will rewrite receiver and parameter count if the previous
289 // stack frame was an arguments adapter frame.
290 ArgumentsAccessStub::Type type;
291 if (is_strict(language_mode()) || !is_simple_parameter_list()) {
292 type = ArgumentsAccessStub::NEW_STRICT;
293 } else if (function()->has_duplicate_parameters()) {
294 type = ArgumentsAccessStub::NEW_SLOPPY_SLOW;
296 type = ArgumentsAccessStub::NEW_SLOPPY_FAST;
299 ArgumentsAccessStub stub(isolate(), type, has_new_target);
302 SetVar(arguments, eax, ebx, edx);
306 __ CallRuntime(Runtime::kTraceEnter, 0);
309 // Visit the declarations and body unless there is an illegal
311 if (scope()->HasIllegalRedeclaration()) {
312 Comment cmnt(masm_, "[ Declarations");
313 scope()->VisitIllegalRedeclaration(this);
316 PrepareForBailoutForId(BailoutId::FunctionEntry(), NO_REGISTERS);
317 { Comment cmnt(masm_, "[ Declarations");
318 // For named function expressions, declare the function name as a
320 if (scope()->is_function_scope() && scope()->function() != NULL) {
321 VariableDeclaration* function = scope()->function();
322 DCHECK(function->proxy()->var()->mode() == CONST ||
323 function->proxy()->var()->mode() == CONST_LEGACY);
324 DCHECK(function->proxy()->var()->location() != Variable::UNALLOCATED);
325 VisitVariableDeclaration(function);
327 VisitDeclarations(scope()->declarations());
330 { Comment cmnt(masm_, "[ Stack check");
331 PrepareForBailoutForId(BailoutId::Declarations(), NO_REGISTERS);
333 ExternalReference stack_limit
334 = ExternalReference::address_of_stack_limit(isolate());
335 __ cmp(esp, Operand::StaticVariable(stack_limit));
336 __ j(above_equal, &ok, Label::kNear);
337 __ call(isolate()->builtins()->StackCheck(), RelocInfo::CODE_TARGET);
341 { Comment cmnt(masm_, "[ Body");
342 DCHECK(loop_depth() == 0);
343 VisitStatements(function()->body());
344 DCHECK(loop_depth() == 0);
348 // Always emit a 'return undefined' in case control fell off the end of
350 { Comment cmnt(masm_, "[ return <undefined>;");
351 __ mov(eax, isolate()->factory()->undefined_value());
352 EmitReturnSequence();
357 void FullCodeGenerator::ClearAccumulator() {
358 __ Move(eax, Immediate(Smi::FromInt(0)));
362 void FullCodeGenerator::EmitProfilingCounterDecrement(int delta) {
363 __ mov(ebx, Immediate(profiling_counter_));
364 __ sub(FieldOperand(ebx, Cell::kValueOffset),
365 Immediate(Smi::FromInt(delta)));
369 void FullCodeGenerator::EmitProfilingCounterReset() {
370 int reset_value = FLAG_interrupt_budget;
371 __ mov(ebx, Immediate(profiling_counter_));
372 __ mov(FieldOperand(ebx, Cell::kValueOffset),
373 Immediate(Smi::FromInt(reset_value)));
377 void FullCodeGenerator::EmitBackEdgeBookkeeping(IterationStatement* stmt,
378 Label* back_edge_target) {
379 Comment cmnt(masm_, "[ Back edge bookkeeping");
382 DCHECK(back_edge_target->is_bound());
383 int distance = masm_->SizeOfCodeGeneratedSince(back_edge_target);
384 int weight = Min(kMaxBackEdgeWeight,
385 Max(1, distance / kCodeSizeMultiplier));
386 EmitProfilingCounterDecrement(weight);
387 __ j(positive, &ok, Label::kNear);
388 __ call(isolate()->builtins()->InterruptCheck(), RelocInfo::CODE_TARGET);
390 // Record a mapping of this PC offset to the OSR id. This is used to find
391 // the AST id from the unoptimized code in order to use it as a key into
392 // the deoptimization input data found in the optimized code.
393 RecordBackEdge(stmt->OsrEntryId());
395 EmitProfilingCounterReset();
398 PrepareForBailoutForId(stmt->EntryId(), NO_REGISTERS);
399 // Record a mapping of the OSR id to this PC. This is used if the OSR
400 // entry becomes the target of a bailout. We don't expect it to be, but
401 // we want it to work if it is.
402 PrepareForBailoutForId(stmt->OsrEntryId(), NO_REGISTERS);
406 void FullCodeGenerator::EmitReturnSequence() {
407 Comment cmnt(masm_, "[ Return sequence");
408 if (return_label_.is_bound()) {
409 __ jmp(&return_label_);
411 // Common return label
412 __ bind(&return_label_);
415 __ CallRuntime(Runtime::kTraceExit, 1);
417 // Pretend that the exit is a backwards jump to the entry.
419 if (info_->ShouldSelfOptimize()) {
420 weight = FLAG_interrupt_budget / FLAG_self_opt_count;
422 int distance = masm_->pc_offset();
423 weight = Min(kMaxBackEdgeWeight,
424 Max(1, distance / kCodeSizeMultiplier));
426 EmitProfilingCounterDecrement(weight);
428 __ j(positive, &ok, Label::kNear);
430 __ call(isolate()->builtins()->InterruptCheck(),
431 RelocInfo::CODE_TARGET);
433 EmitProfilingCounterReset();
436 // Add a label for checking the size of the code used for returning.
437 Label check_exit_codesize;
438 masm_->bind(&check_exit_codesize);
440 SetSourcePosition(function()->end_position() - 1);
442 // Do not use the leave instruction here because it is too short to
443 // patch with the code required by the debugger.
445 int no_frame_start = masm_->pc_offset();
448 int arg_count = info_->scope()->num_parameters() + 1;
449 if (IsSubclassConstructor(info_->function()->kind())) {
452 int arguments_bytes = arg_count * kPointerSize;
453 __ Ret(arguments_bytes, ecx);
454 // Check that the size of the code used for returning is large enough
455 // for the debugger's requirements.
456 DCHECK(Assembler::kJSReturnSequenceLength <=
457 masm_->SizeOfCodeGeneratedSince(&check_exit_codesize));
458 info_->AddNoFrameRange(no_frame_start, masm_->pc_offset());
463 void FullCodeGenerator::EffectContext::Plug(Variable* var) const {
464 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
468 void FullCodeGenerator::AccumulatorValueContext::Plug(Variable* var) const {
469 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
470 codegen()->GetVar(result_register(), var);
474 void FullCodeGenerator::StackValueContext::Plug(Variable* var) const {
475 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
476 MemOperand operand = codegen()->VarOperand(var, result_register());
477 // Memory operands can be pushed directly.
482 void FullCodeGenerator::TestContext::Plug(Variable* var) const {
483 // For simplicity we always test the accumulator register.
484 codegen()->GetVar(result_register(), var);
485 codegen()->PrepareForBailoutBeforeSplit(condition(), false, NULL, NULL);
486 codegen()->DoTest(this);
490 void FullCodeGenerator::EffectContext::Plug(Heap::RootListIndex index) const {
491 UNREACHABLE(); // Not used on IA32.
495 void FullCodeGenerator::AccumulatorValueContext::Plug(
496 Heap::RootListIndex index) const {
497 UNREACHABLE(); // Not used on IA32.
501 void FullCodeGenerator::StackValueContext::Plug(
502 Heap::RootListIndex index) const {
503 UNREACHABLE(); // Not used on IA32.
507 void FullCodeGenerator::TestContext::Plug(Heap::RootListIndex index) const {
508 UNREACHABLE(); // Not used on IA32.
512 void FullCodeGenerator::EffectContext::Plug(Handle<Object> lit) const {
516 void FullCodeGenerator::AccumulatorValueContext::Plug(
517 Handle<Object> lit) const {
519 __ SafeMove(result_register(), Immediate(lit));
521 __ Move(result_register(), Immediate(lit));
526 void FullCodeGenerator::StackValueContext::Plug(Handle<Object> lit) const {
528 __ SafePush(Immediate(lit));
530 __ push(Immediate(lit));
535 void FullCodeGenerator::TestContext::Plug(Handle<Object> lit) const {
536 codegen()->PrepareForBailoutBeforeSplit(condition(),
540 DCHECK(!lit->IsUndetectableObject()); // There are no undetectable literals.
541 if (lit->IsUndefined() || lit->IsNull() || lit->IsFalse()) {
542 if (false_label_ != fall_through_) __ jmp(false_label_);
543 } else if (lit->IsTrue() || lit->IsJSObject()) {
544 if (true_label_ != fall_through_) __ jmp(true_label_);
545 } else if (lit->IsString()) {
546 if (String::cast(*lit)->length() == 0) {
547 if (false_label_ != fall_through_) __ jmp(false_label_);
549 if (true_label_ != fall_through_) __ jmp(true_label_);
551 } else if (lit->IsSmi()) {
552 if (Smi::cast(*lit)->value() == 0) {
553 if (false_label_ != fall_through_) __ jmp(false_label_);
555 if (true_label_ != fall_through_) __ jmp(true_label_);
558 // For simplicity we always test the accumulator register.
559 __ mov(result_register(), lit);
560 codegen()->DoTest(this);
565 void FullCodeGenerator::EffectContext::DropAndPlug(int count,
566 Register reg) const {
572 void FullCodeGenerator::AccumulatorValueContext::DropAndPlug(
574 Register reg) const {
577 __ Move(result_register(), reg);
581 void FullCodeGenerator::StackValueContext::DropAndPlug(int count,
582 Register reg) const {
584 if (count > 1) __ Drop(count - 1);
585 __ mov(Operand(esp, 0), reg);
589 void FullCodeGenerator::TestContext::DropAndPlug(int count,
590 Register reg) const {
592 // For simplicity we always test the accumulator register.
594 __ Move(result_register(), reg);
595 codegen()->PrepareForBailoutBeforeSplit(condition(), false, NULL, NULL);
596 codegen()->DoTest(this);
600 void FullCodeGenerator::EffectContext::Plug(Label* materialize_true,
601 Label* materialize_false) const {
602 DCHECK(materialize_true == materialize_false);
603 __ bind(materialize_true);
607 void FullCodeGenerator::AccumulatorValueContext::Plug(
608 Label* materialize_true,
609 Label* materialize_false) const {
611 __ bind(materialize_true);
612 __ mov(result_register(), isolate()->factory()->true_value());
613 __ jmp(&done, Label::kNear);
614 __ bind(materialize_false);
615 __ mov(result_register(), isolate()->factory()->false_value());
620 void FullCodeGenerator::StackValueContext::Plug(
621 Label* materialize_true,
622 Label* materialize_false) const {
624 __ bind(materialize_true);
625 __ push(Immediate(isolate()->factory()->true_value()));
626 __ jmp(&done, Label::kNear);
627 __ bind(materialize_false);
628 __ push(Immediate(isolate()->factory()->false_value()));
633 void FullCodeGenerator::TestContext::Plug(Label* materialize_true,
634 Label* materialize_false) const {
635 DCHECK(materialize_true == true_label_);
636 DCHECK(materialize_false == false_label_);
640 void FullCodeGenerator::EffectContext::Plug(bool flag) const {
644 void FullCodeGenerator::AccumulatorValueContext::Plug(bool flag) const {
645 Handle<Object> value = flag
646 ? isolate()->factory()->true_value()
647 : isolate()->factory()->false_value();
648 __ mov(result_register(), value);
652 void FullCodeGenerator::StackValueContext::Plug(bool flag) const {
653 Handle<Object> value = flag
654 ? isolate()->factory()->true_value()
655 : isolate()->factory()->false_value();
656 __ push(Immediate(value));
660 void FullCodeGenerator::TestContext::Plug(bool flag) const {
661 codegen()->PrepareForBailoutBeforeSplit(condition(),
666 if (true_label_ != fall_through_) __ jmp(true_label_);
668 if (false_label_ != fall_through_) __ jmp(false_label_);
673 void FullCodeGenerator::DoTest(Expression* condition,
676 Label* fall_through) {
677 Handle<Code> ic = ToBooleanStub::GetUninitialized(isolate());
678 CallIC(ic, condition->test_id());
679 __ test(result_register(), result_register());
680 // The stub returns nonzero for true.
681 Split(not_zero, if_true, if_false, fall_through);
685 void FullCodeGenerator::Split(Condition cc,
688 Label* fall_through) {
689 if (if_false == fall_through) {
691 } else if (if_true == fall_through) {
692 __ j(NegateCondition(cc), if_false);
700 MemOperand FullCodeGenerator::StackOperand(Variable* var) {
701 DCHECK(var->IsStackAllocated());
702 // Offset is negative because higher indexes are at lower addresses.
703 int offset = -var->index() * kPointerSize;
704 // Adjust by a (parameter or local) base offset.
705 if (var->IsParameter()) {
706 offset += (info_->scope()->num_parameters() + 1) * kPointerSize;
708 offset += JavaScriptFrameConstants::kLocal0Offset;
710 return Operand(ebp, offset);
714 MemOperand FullCodeGenerator::VarOperand(Variable* var, Register scratch) {
715 DCHECK(var->IsContextSlot() || var->IsStackAllocated());
716 if (var->IsContextSlot()) {
717 int context_chain_length = scope()->ContextChainLength(var->scope());
718 __ LoadContext(scratch, context_chain_length);
719 return ContextOperand(scratch, var->index());
721 return StackOperand(var);
726 void FullCodeGenerator::GetVar(Register dest, Variable* var) {
727 DCHECK(var->IsContextSlot() || var->IsStackAllocated());
728 MemOperand location = VarOperand(var, dest);
729 __ mov(dest, location);
733 void FullCodeGenerator::SetVar(Variable* var,
737 DCHECK(var->IsContextSlot() || var->IsStackAllocated());
738 DCHECK(!scratch0.is(src));
739 DCHECK(!scratch0.is(scratch1));
740 DCHECK(!scratch1.is(src));
741 MemOperand location = VarOperand(var, scratch0);
742 __ mov(location, src);
744 // Emit the write barrier code if the location is in the heap.
745 if (var->IsContextSlot()) {
746 int offset = Context::SlotOffset(var->index());
747 DCHECK(!scratch0.is(esi) && !src.is(esi) && !scratch1.is(esi));
748 __ RecordWriteContextSlot(scratch0, offset, src, scratch1, kDontSaveFPRegs);
753 void FullCodeGenerator::PrepareForBailoutBeforeSplit(Expression* expr,
754 bool should_normalize,
757 // Only prepare for bailouts before splits if we're in a test
758 // context. Otherwise, we let the Visit function deal with the
759 // preparation to avoid preparing with the same AST id twice.
760 if (!context()->IsTest() || !info_->IsOptimizable()) return;
763 if (should_normalize) __ jmp(&skip, Label::kNear);
764 PrepareForBailout(expr, TOS_REG);
765 if (should_normalize) {
766 __ cmp(eax, isolate()->factory()->true_value());
767 Split(equal, if_true, if_false, NULL);
773 void FullCodeGenerator::EmitDebugCheckDeclarationContext(Variable* variable) {
774 // The variable in the declaration always resides in the current context.
775 DCHECK_EQ(0, scope()->ContextChainLength(variable->scope()));
776 if (generate_debug_code_) {
777 // Check that we're not inside a with or catch context.
778 __ mov(ebx, FieldOperand(esi, HeapObject::kMapOffset));
779 __ cmp(ebx, isolate()->factory()->with_context_map());
780 __ Check(not_equal, kDeclarationInWithContext);
781 __ cmp(ebx, isolate()->factory()->catch_context_map());
782 __ Check(not_equal, kDeclarationInCatchContext);
787 void FullCodeGenerator::VisitVariableDeclaration(
788 VariableDeclaration* declaration) {
789 // If it was not possible to allocate the variable at compile time, we
790 // need to "declare" it at runtime to make sure it actually exists in the
792 VariableProxy* proxy = declaration->proxy();
793 VariableMode mode = declaration->mode();
794 Variable* variable = proxy->var();
795 bool hole_init = mode == LET || mode == CONST || mode == CONST_LEGACY;
796 switch (variable->location()) {
797 case Variable::UNALLOCATED:
798 globals_->Add(variable->name(), zone());
799 globals_->Add(variable->binding_needs_init()
800 ? isolate()->factory()->the_hole_value()
801 : isolate()->factory()->undefined_value(), zone());
804 case Variable::PARAMETER:
805 case Variable::LOCAL:
807 Comment cmnt(masm_, "[ VariableDeclaration");
808 __ mov(StackOperand(variable),
809 Immediate(isolate()->factory()->the_hole_value()));
813 case Variable::CONTEXT:
815 Comment cmnt(masm_, "[ VariableDeclaration");
816 EmitDebugCheckDeclarationContext(variable);
817 __ mov(ContextOperand(esi, variable->index()),
818 Immediate(isolate()->factory()->the_hole_value()));
819 // No write barrier since the hole value is in old space.
820 PrepareForBailoutForId(proxy->id(), NO_REGISTERS);
824 case Variable::LOOKUP: {
825 Comment cmnt(masm_, "[ VariableDeclaration");
827 __ push(Immediate(variable->name()));
828 // VariableDeclaration nodes are always introduced in one of four modes.
829 DCHECK(IsDeclaredVariableMode(mode));
830 PropertyAttributes attr =
831 IsImmutableVariableMode(mode) ? READ_ONLY : NONE;
832 __ push(Immediate(Smi::FromInt(attr)));
833 // Push initial value, if any.
834 // Note: For variables we must not push an initial value (such as
835 // 'undefined') because we may have a (legal) redeclaration and we
836 // must not destroy the current value.
838 __ push(Immediate(isolate()->factory()->the_hole_value()));
840 __ push(Immediate(Smi::FromInt(0))); // Indicates no initial value.
842 __ CallRuntime(Runtime::kDeclareLookupSlot, 4);
849 void FullCodeGenerator::VisitFunctionDeclaration(
850 FunctionDeclaration* declaration) {
851 VariableProxy* proxy = declaration->proxy();
852 Variable* variable = proxy->var();
853 switch (variable->location()) {
854 case Variable::UNALLOCATED: {
855 globals_->Add(variable->name(), zone());
856 Handle<SharedFunctionInfo> function =
857 Compiler::BuildFunctionInfo(declaration->fun(), script(), info_);
858 // Check for stack-overflow exception.
859 if (function.is_null()) return SetStackOverflow();
860 globals_->Add(function, zone());
864 case Variable::PARAMETER:
865 case Variable::LOCAL: {
866 Comment cmnt(masm_, "[ FunctionDeclaration");
867 VisitForAccumulatorValue(declaration->fun());
868 __ mov(StackOperand(variable), result_register());
872 case Variable::CONTEXT: {
873 Comment cmnt(masm_, "[ FunctionDeclaration");
874 EmitDebugCheckDeclarationContext(variable);
875 VisitForAccumulatorValue(declaration->fun());
876 __ mov(ContextOperand(esi, variable->index()), result_register());
877 // We know that we have written a function, which is not a smi.
878 __ RecordWriteContextSlot(esi,
879 Context::SlotOffset(variable->index()),
885 PrepareForBailoutForId(proxy->id(), NO_REGISTERS);
889 case Variable::LOOKUP: {
890 Comment cmnt(masm_, "[ FunctionDeclaration");
892 __ push(Immediate(variable->name()));
893 __ push(Immediate(Smi::FromInt(NONE)));
894 VisitForStackValue(declaration->fun());
895 __ CallRuntime(Runtime::kDeclareLookupSlot, 4);
902 void FullCodeGenerator::VisitModuleDeclaration(ModuleDeclaration* declaration) {
903 Variable* variable = declaration->proxy()->var();
904 ModuleDescriptor* descriptor = declaration->module()->descriptor();
905 DCHECK(variable->location() == Variable::CONTEXT);
906 DCHECK(descriptor->IsFrozen());
908 Comment cmnt(masm_, "[ ModuleDeclaration");
909 EmitDebugCheckDeclarationContext(variable);
911 // Load instance object.
912 __ LoadContext(eax, scope_->ContextChainLength(scope_->ScriptScope()));
913 __ mov(eax, ContextOperand(eax, descriptor->Index()));
914 __ mov(eax, ContextOperand(eax, Context::EXTENSION_INDEX));
917 __ mov(ContextOperand(esi, variable->index()), eax);
918 // We know that we have written a module, which is not a smi.
919 __ RecordWriteContextSlot(esi,
920 Context::SlotOffset(variable->index()),
926 PrepareForBailoutForId(declaration->proxy()->id(), NO_REGISTERS);
928 // Traverse into body.
929 Visit(declaration->module());
933 void FullCodeGenerator::VisitImportDeclaration(ImportDeclaration* declaration) {
934 VariableProxy* proxy = declaration->proxy();
935 Variable* variable = proxy->var();
936 switch (variable->location()) {
937 case Variable::UNALLOCATED:
941 case Variable::CONTEXT: {
942 Comment cmnt(masm_, "[ ImportDeclaration");
943 EmitDebugCheckDeclarationContext(variable);
948 case Variable::PARAMETER:
949 case Variable::LOCAL:
950 case Variable::LOOKUP:
956 void FullCodeGenerator::VisitExportDeclaration(ExportDeclaration* declaration) {
961 void FullCodeGenerator::DeclareGlobals(Handle<FixedArray> pairs) {
962 // Call the runtime to declare the globals.
963 __ push(esi); // The context is the first argument.
965 __ Push(Smi::FromInt(DeclareGlobalsFlags()));
966 __ CallRuntime(Runtime::kDeclareGlobals, 3);
967 // Return value is ignored.
971 void FullCodeGenerator::DeclareModules(Handle<FixedArray> descriptions) {
972 // Call the runtime to declare the modules.
973 __ Push(descriptions);
974 __ CallRuntime(Runtime::kDeclareModules, 1);
975 // Return value is ignored.
979 void FullCodeGenerator::VisitSwitchStatement(SwitchStatement* stmt) {
980 Comment cmnt(masm_, "[ SwitchStatement");
981 Breakable nested_statement(this, stmt);
982 SetStatementPosition(stmt);
984 // Keep the switch value on the stack until a case matches.
985 VisitForStackValue(stmt->tag());
986 PrepareForBailoutForId(stmt->EntryId(), NO_REGISTERS);
988 ZoneList<CaseClause*>* clauses = stmt->cases();
989 CaseClause* default_clause = NULL; // Can occur anywhere in the list.
991 Label next_test; // Recycled for each test.
992 // Compile all the tests with branches to their bodies.
993 for (int i = 0; i < clauses->length(); i++) {
994 CaseClause* clause = clauses->at(i);
995 clause->body_target()->Unuse();
997 // The default is not a test, but remember it as final fall through.
998 if (clause->is_default()) {
999 default_clause = clause;
1003 Comment cmnt(masm_, "[ Case comparison");
1004 __ bind(&next_test);
1007 // Compile the label expression.
1008 VisitForAccumulatorValue(clause->label());
1010 // Perform the comparison as if via '==='.
1011 __ mov(edx, Operand(esp, 0)); // Switch value.
1012 bool inline_smi_code = ShouldInlineSmiCase(Token::EQ_STRICT);
1013 JumpPatchSite patch_site(masm_);
1014 if (inline_smi_code) {
1018 patch_site.EmitJumpIfNotSmi(ecx, &slow_case, Label::kNear);
1021 __ j(not_equal, &next_test);
1022 __ Drop(1); // Switch value is no longer needed.
1023 __ jmp(clause->body_target());
1024 __ bind(&slow_case);
1027 // Record position before stub call for type feedback.
1028 SetSourcePosition(clause->position());
1030 CodeFactory::CompareIC(isolate(), Token::EQ_STRICT).code();
1031 CallIC(ic, clause->CompareId());
1032 patch_site.EmitPatchInfo();
1035 __ jmp(&skip, Label::kNear);
1036 PrepareForBailout(clause, TOS_REG);
1037 __ cmp(eax, isolate()->factory()->true_value());
1038 __ j(not_equal, &next_test);
1040 __ jmp(clause->body_target());
1044 __ j(not_equal, &next_test);
1045 __ Drop(1); // Switch value is no longer needed.
1046 __ jmp(clause->body_target());
1049 // Discard the test value and jump to the default if present, otherwise to
1050 // the end of the statement.
1051 __ bind(&next_test);
1052 __ Drop(1); // Switch value is no longer needed.
1053 if (default_clause == NULL) {
1054 __ jmp(nested_statement.break_label());
1056 __ jmp(default_clause->body_target());
1059 // Compile all the case bodies.
1060 for (int i = 0; i < clauses->length(); i++) {
1061 Comment cmnt(masm_, "[ Case body");
1062 CaseClause* clause = clauses->at(i);
1063 __ bind(clause->body_target());
1064 PrepareForBailoutForId(clause->EntryId(), NO_REGISTERS);
1065 VisitStatements(clause->statements());
1068 __ bind(nested_statement.break_label());
1069 PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1073 void FullCodeGenerator::VisitForInStatement(ForInStatement* stmt) {
1074 Comment cmnt(masm_, "[ ForInStatement");
1075 FeedbackVectorSlot slot = stmt->ForInFeedbackSlot();
1077 SetStatementPosition(stmt);
1080 ForIn loop_statement(this, stmt);
1081 increment_loop_depth();
1083 // Get the object to enumerate over. If the object is null or undefined, skip
1084 // over the loop. See ECMA-262 version 5, section 12.6.4.
1085 SetExpressionPosition(stmt->enumerable());
1086 VisitForAccumulatorValue(stmt->enumerable());
1087 __ cmp(eax, isolate()->factory()->undefined_value());
1089 __ cmp(eax, isolate()->factory()->null_value());
1092 PrepareForBailoutForId(stmt->PrepareId(), TOS_REG);
1094 // Convert the object to a JS object.
1095 Label convert, done_convert;
1096 __ JumpIfSmi(eax, &convert, Label::kNear);
1097 __ CmpObjectType(eax, FIRST_SPEC_OBJECT_TYPE, ecx);
1098 __ j(above_equal, &done_convert, Label::kNear);
1101 __ InvokeBuiltin(Builtins::TO_OBJECT, CALL_FUNCTION);
1102 __ bind(&done_convert);
1103 PrepareForBailoutForId(stmt->ToObjectId(), TOS_REG);
1106 // Check for proxies.
1107 Label call_runtime, use_cache, fixed_array;
1108 STATIC_ASSERT(FIRST_JS_PROXY_TYPE == FIRST_SPEC_OBJECT_TYPE);
1109 __ CmpObjectType(eax, LAST_JS_PROXY_TYPE, ecx);
1110 __ j(below_equal, &call_runtime);
1112 // Check cache validity in generated code. This is a fast case for
1113 // the JSObject::IsSimpleEnum cache validity checks. If we cannot
1114 // guarantee cache validity, call the runtime system to check cache
1115 // validity or get the property names in a fixed array.
1116 __ CheckEnumCache(&call_runtime);
1118 __ mov(eax, FieldOperand(eax, HeapObject::kMapOffset));
1119 __ jmp(&use_cache, Label::kNear);
1121 // Get the set of properties to enumerate.
1122 __ bind(&call_runtime);
1124 __ CallRuntime(Runtime::kGetPropertyNamesFast, 1);
1125 PrepareForBailoutForId(stmt->EnumId(), TOS_REG);
1126 __ cmp(FieldOperand(eax, HeapObject::kMapOffset),
1127 isolate()->factory()->meta_map());
1128 __ j(not_equal, &fixed_array);
1131 // We got a map in register eax. Get the enumeration cache from it.
1132 Label no_descriptors;
1133 __ bind(&use_cache);
1135 __ EnumLength(edx, eax);
1136 __ cmp(edx, Immediate(Smi::FromInt(0)));
1137 __ j(equal, &no_descriptors);
1139 __ LoadInstanceDescriptors(eax, ecx);
1140 __ mov(ecx, FieldOperand(ecx, DescriptorArray::kEnumCacheOffset));
1141 __ mov(ecx, FieldOperand(ecx, DescriptorArray::kEnumCacheBridgeCacheOffset));
1143 // Set up the four remaining stack slots.
1144 __ push(eax); // Map.
1145 __ push(ecx); // Enumeration cache.
1146 __ push(edx); // Number of valid entries for the map in the enum cache.
1147 __ push(Immediate(Smi::FromInt(0))); // Initial index.
1150 __ bind(&no_descriptors);
1151 __ add(esp, Immediate(kPointerSize));
1154 // We got a fixed array in register eax. Iterate through that.
1156 __ bind(&fixed_array);
1158 // No need for a write barrier, we are storing a Smi in the feedback vector.
1159 __ LoadHeapObject(ebx, FeedbackVector());
1160 int vector_index = FeedbackVector()->GetIndex(slot);
1161 __ mov(FieldOperand(ebx, FixedArray::OffsetOfElementAt(vector_index)),
1162 Immediate(TypeFeedbackVector::MegamorphicSentinel(isolate())));
1164 __ mov(ebx, Immediate(Smi::FromInt(1))); // Smi indicates slow check
1165 __ mov(ecx, Operand(esp, 0 * kPointerSize)); // Get enumerated object
1166 STATIC_ASSERT(FIRST_JS_PROXY_TYPE == FIRST_SPEC_OBJECT_TYPE);
1167 __ CmpObjectType(ecx, LAST_JS_PROXY_TYPE, ecx);
1168 __ j(above, &non_proxy);
1169 __ Move(ebx, Immediate(Smi::FromInt(0))); // Zero indicates proxy
1170 __ bind(&non_proxy);
1171 __ push(ebx); // Smi
1172 __ push(eax); // Array
1173 __ mov(eax, FieldOperand(eax, FixedArray::kLengthOffset));
1174 __ push(eax); // Fixed array length (as smi).
1175 __ push(Immediate(Smi::FromInt(0))); // Initial index.
1177 // Generate code for doing the condition check.
1178 PrepareForBailoutForId(stmt->BodyId(), NO_REGISTERS);
1180 SetExpressionPosition(stmt->each());
1182 __ mov(eax, Operand(esp, 0 * kPointerSize)); // Get the current index.
1183 __ cmp(eax, Operand(esp, 1 * kPointerSize)); // Compare to the array length.
1184 __ j(above_equal, loop_statement.break_label());
1186 // Get the current entry of the array into register ebx.
1187 __ mov(ebx, Operand(esp, 2 * kPointerSize));
1188 __ mov(ebx, FieldOperand(ebx, eax, times_2, FixedArray::kHeaderSize));
1190 // Get the expected map from the stack or a smi in the
1191 // permanent slow case into register edx.
1192 __ mov(edx, Operand(esp, 3 * kPointerSize));
1194 // Check if the expected map still matches that of the enumerable.
1195 // If not, we may have to filter the key.
1197 __ mov(ecx, Operand(esp, 4 * kPointerSize));
1198 __ cmp(edx, FieldOperand(ecx, HeapObject::kMapOffset));
1199 __ j(equal, &update_each, Label::kNear);
1201 // For proxies, no filtering is done.
1202 // TODO(rossberg): What if only a prototype is a proxy? Not specified yet.
1203 DCHECK(Smi::FromInt(0) == 0);
1205 __ j(zero, &update_each);
1207 // Convert the entry to a string or null if it isn't a property
1208 // anymore. If the property has been removed while iterating, we
1210 __ push(ecx); // Enumerable.
1211 __ push(ebx); // Current entry.
1212 __ InvokeBuiltin(Builtins::FILTER_KEY, CALL_FUNCTION);
1214 __ j(equal, loop_statement.continue_label());
1217 // Update the 'each' property or variable from the possibly filtered
1218 // entry in register ebx.
1219 __ bind(&update_each);
1220 __ mov(result_register(), ebx);
1221 // Perform the assignment as if via '='.
1222 { EffectContext context(this);
1223 EmitAssignment(stmt->each());
1224 PrepareForBailoutForId(stmt->AssignmentId(), NO_REGISTERS);
1227 // Generate code for the body of the loop.
1228 Visit(stmt->body());
1230 // Generate code for going to the next element by incrementing the
1231 // index (smi) stored on top of the stack.
1232 __ bind(loop_statement.continue_label());
1233 __ add(Operand(esp, 0 * kPointerSize), Immediate(Smi::FromInt(1)));
1235 EmitBackEdgeBookkeeping(stmt, &loop);
1238 // Remove the pointers stored on the stack.
1239 __ bind(loop_statement.break_label());
1240 __ add(esp, Immediate(5 * kPointerSize));
1242 // Exit and decrement the loop depth.
1243 PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1245 decrement_loop_depth();
1249 void FullCodeGenerator::EmitNewClosure(Handle<SharedFunctionInfo> info,
1251 // Use the fast case closure allocation code that allocates in new
1252 // space for nested functions that don't need literals cloning. If
1253 // we're running with the --always-opt or the --prepare-always-opt
1254 // flag, we need to use the runtime function so that the new function
1255 // we are creating here gets a chance to have its code optimized and
1256 // doesn't just get a copy of the existing unoptimized code.
1257 if (!FLAG_always_opt &&
1258 !FLAG_prepare_always_opt &&
1260 scope()->is_function_scope() &&
1261 info->num_literals() == 0) {
1262 FastNewClosureStub stub(isolate(), info->language_mode(), info->kind());
1263 __ mov(ebx, Immediate(info));
1267 __ push(Immediate(info));
1268 __ push(Immediate(pretenure
1269 ? isolate()->factory()->true_value()
1270 : isolate()->factory()->false_value()));
1271 __ CallRuntime(Runtime::kNewClosure, 3);
1273 context()->Plug(eax);
1277 void FullCodeGenerator::VisitVariableProxy(VariableProxy* expr) {
1278 Comment cmnt(masm_, "[ VariableProxy");
1279 EmitVariableLoad(expr);
1283 void FullCodeGenerator::EmitLoadHomeObject(SuperReference* expr) {
1284 Comment cnmt(masm_, "[ SuperReference ");
1286 __ mov(LoadDescriptor::ReceiverRegister(),
1287 Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
1289 Handle<Symbol> home_object_symbol(isolate()->heap()->home_object_symbol());
1290 __ mov(LoadDescriptor::NameRegister(), home_object_symbol);
1292 if (FLAG_vector_ics) {
1293 __ mov(VectorLoadICDescriptor::SlotRegister(),
1294 Immediate(SmiFromSlot(expr->HomeObjectFeedbackSlot())));
1295 CallLoadIC(NOT_CONTEXTUAL);
1297 CallLoadIC(NOT_CONTEXTUAL, expr->HomeObjectFeedbackId());
1300 __ cmp(eax, isolate()->factory()->undefined_value());
1302 __ j(not_equal, &done);
1303 __ CallRuntime(Runtime::kThrowNonMethodError, 0);
1308 void FullCodeGenerator::EmitSetHomeObjectIfNeeded(Expression* initializer,
1310 if (NeedsHomeObject(initializer)) {
1311 __ mov(StoreDescriptor::ReceiverRegister(), Operand(esp, 0));
1312 __ mov(StoreDescriptor::NameRegister(),
1313 Immediate(isolate()->factory()->home_object_symbol()));
1314 __ mov(StoreDescriptor::ValueRegister(),
1315 Operand(esp, offset * kPointerSize));
1321 void FullCodeGenerator::EmitLoadGlobalCheckExtensions(VariableProxy* proxy,
1322 TypeofState typeof_state,
1324 Register context = esi;
1325 Register temp = edx;
1329 if (s->num_heap_slots() > 0) {
1330 if (s->calls_sloppy_eval()) {
1331 // Check that extension is NULL.
1332 __ cmp(ContextOperand(context, Context::EXTENSION_INDEX),
1334 __ j(not_equal, slow);
1336 // Load next context in chain.
1337 __ mov(temp, ContextOperand(context, Context::PREVIOUS_INDEX));
1338 // Walk the rest of the chain without clobbering esi.
1341 // If no outer scope calls eval, we do not need to check more
1342 // context extensions. If we have reached an eval scope, we check
1343 // all extensions from this point.
1344 if (!s->outer_scope_calls_sloppy_eval() || s->is_eval_scope()) break;
1345 s = s->outer_scope();
1348 if (s != NULL && s->is_eval_scope()) {
1349 // Loop up the context chain. There is no frame effect so it is
1350 // safe to use raw labels here.
1352 if (!context.is(temp)) {
1353 __ mov(temp, context);
1356 // Terminate at native context.
1357 __ cmp(FieldOperand(temp, HeapObject::kMapOffset),
1358 Immediate(isolate()->factory()->native_context_map()));
1359 __ j(equal, &fast, Label::kNear);
1360 // Check that extension is NULL.
1361 __ cmp(ContextOperand(temp, Context::EXTENSION_INDEX), Immediate(0));
1362 __ j(not_equal, slow);
1363 // Load next context in chain.
1364 __ mov(temp, ContextOperand(temp, Context::PREVIOUS_INDEX));
1369 // All extension objects were empty and it is safe to use a global
1371 __ mov(LoadDescriptor::ReceiverRegister(), GlobalObjectOperand());
1372 __ mov(LoadDescriptor::NameRegister(), proxy->var()->name());
1373 if (FLAG_vector_ics) {
1374 __ mov(VectorLoadICDescriptor::SlotRegister(),
1375 Immediate(SmiFromSlot(proxy->VariableFeedbackSlot())));
1378 ContextualMode mode = (typeof_state == INSIDE_TYPEOF)
1386 MemOperand FullCodeGenerator::ContextSlotOperandCheckExtensions(Variable* var,
1388 DCHECK(var->IsContextSlot());
1389 Register context = esi;
1390 Register temp = ebx;
1392 for (Scope* s = scope(); s != var->scope(); s = s->outer_scope()) {
1393 if (s->num_heap_slots() > 0) {
1394 if (s->calls_sloppy_eval()) {
1395 // Check that extension is NULL.
1396 __ cmp(ContextOperand(context, Context::EXTENSION_INDEX),
1398 __ j(not_equal, slow);
1400 __ mov(temp, ContextOperand(context, Context::PREVIOUS_INDEX));
1401 // Walk the rest of the chain without clobbering esi.
1405 // Check that last extension is NULL.
1406 __ cmp(ContextOperand(context, Context::EXTENSION_INDEX), Immediate(0));
1407 __ j(not_equal, slow);
1409 // This function is used only for loads, not stores, so it's safe to
1410 // return an esi-based operand (the write barrier cannot be allowed to
1411 // destroy the esi register).
1412 return ContextOperand(context, var->index());
1416 void FullCodeGenerator::EmitDynamicLookupFastCase(VariableProxy* proxy,
1417 TypeofState typeof_state,
1420 // Generate fast-case code for variables that might be shadowed by
1421 // eval-introduced variables. Eval is used a lot without
1422 // introducing variables. In those cases, we do not want to
1423 // perform a runtime call for all variables in the scope
1424 // containing the eval.
1425 Variable* var = proxy->var();
1426 if (var->mode() == DYNAMIC_GLOBAL) {
1427 EmitLoadGlobalCheckExtensions(proxy, typeof_state, slow);
1429 } else if (var->mode() == DYNAMIC_LOCAL) {
1430 Variable* local = var->local_if_not_shadowed();
1431 __ mov(eax, ContextSlotOperandCheckExtensions(local, slow));
1432 if (local->mode() == LET || local->mode() == CONST ||
1433 local->mode() == CONST_LEGACY) {
1434 __ cmp(eax, isolate()->factory()->the_hole_value());
1435 __ j(not_equal, done);
1436 if (local->mode() == CONST_LEGACY) {
1437 __ mov(eax, isolate()->factory()->undefined_value());
1438 } else { // LET || CONST
1439 __ push(Immediate(var->name()));
1440 __ CallRuntime(Runtime::kThrowReferenceError, 1);
1448 void FullCodeGenerator::EmitVariableLoad(VariableProxy* proxy) {
1449 // Record position before possible IC call.
1450 SetSourcePosition(proxy->position());
1451 Variable* var = proxy->var();
1453 // Three cases: global variables, lookup variables, and all other types of
1455 switch (var->location()) {
1456 case Variable::UNALLOCATED: {
1457 Comment cmnt(masm_, "[ Global variable");
1458 __ mov(LoadDescriptor::ReceiverRegister(), GlobalObjectOperand());
1459 __ mov(LoadDescriptor::NameRegister(), var->name());
1460 if (FLAG_vector_ics) {
1461 __ mov(VectorLoadICDescriptor::SlotRegister(),
1462 Immediate(SmiFromSlot(proxy->VariableFeedbackSlot())));
1464 CallGlobalLoadIC(var->name());
1465 context()->Plug(eax);
1469 case Variable::PARAMETER:
1470 case Variable::LOCAL:
1471 case Variable::CONTEXT: {
1472 Comment cmnt(masm_, var->IsContextSlot() ? "[ Context variable"
1473 : "[ Stack variable");
1474 if (var->binding_needs_init()) {
1475 // var->scope() may be NULL when the proxy is located in eval code and
1476 // refers to a potential outside binding. Currently those bindings are
1477 // always looked up dynamically, i.e. in that case
1478 // var->location() == LOOKUP.
1480 DCHECK(var->scope() != NULL);
1482 // Check if the binding really needs an initialization check. The check
1483 // can be skipped in the following situation: we have a LET or CONST
1484 // binding in harmony mode, both the Variable and the VariableProxy have
1485 // the same declaration scope (i.e. they are both in global code, in the
1486 // same function or in the same eval code) and the VariableProxy is in
1487 // the source physically located after the initializer of the variable.
1489 // We cannot skip any initialization checks for CONST in non-harmony
1490 // mode because const variables may be declared but never initialized:
1491 // if (false) { const x; }; var y = x;
1493 // The condition on the declaration scopes is a conservative check for
1494 // nested functions that access a binding and are called before the
1495 // binding is initialized:
1496 // function() { f(); let x = 1; function f() { x = 2; } }
1498 bool skip_init_check;
1499 if (var->scope()->DeclarationScope() != scope()->DeclarationScope()) {
1500 skip_init_check = false;
1501 } else if (var->is_this()) {
1502 CHECK(info_->function() != nullptr &&
1503 (info_->function()->kind() & kSubclassConstructor) != 0);
1504 // TODO(dslomov): implement 'this' hole check elimination.
1505 skip_init_check = false;
1507 // Check that we always have valid source position.
1508 DCHECK(var->initializer_position() != RelocInfo::kNoPosition);
1509 DCHECK(proxy->position() != RelocInfo::kNoPosition);
1510 skip_init_check = var->mode() != CONST_LEGACY &&
1511 var->initializer_position() < proxy->position();
1514 if (!skip_init_check) {
1515 // Let and const need a read barrier.
1518 __ cmp(eax, isolate()->factory()->the_hole_value());
1519 __ j(not_equal, &done, Label::kNear);
1520 if (var->mode() == LET || var->mode() == CONST) {
1521 // Throw a reference error when using an uninitialized let/const
1522 // binding in harmony mode.
1523 __ push(Immediate(var->name()));
1524 __ CallRuntime(Runtime::kThrowReferenceError, 1);
1526 // Uninitalized const bindings outside of harmony mode are unholed.
1527 DCHECK(var->mode() == CONST_LEGACY);
1528 __ mov(eax, isolate()->factory()->undefined_value());
1531 context()->Plug(eax);
1535 context()->Plug(var);
1539 case Variable::LOOKUP: {
1540 Comment cmnt(masm_, "[ Lookup variable");
1542 // Generate code for loading from variables potentially shadowed
1543 // by eval-introduced variables.
1544 EmitDynamicLookupFastCase(proxy, NOT_INSIDE_TYPEOF, &slow, &done);
1546 __ push(esi); // Context.
1547 __ push(Immediate(var->name()));
1548 __ CallRuntime(Runtime::kLoadLookupSlot, 2);
1550 context()->Plug(eax);
1557 void FullCodeGenerator::VisitRegExpLiteral(RegExpLiteral* expr) {
1558 Comment cmnt(masm_, "[ RegExpLiteral");
1560 // Registers will be used as follows:
1561 // edi = JS function.
1562 // ecx = literals array.
1563 // ebx = regexp literal.
1564 // eax = regexp literal clone.
1565 __ mov(edi, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
1566 __ mov(ecx, FieldOperand(edi, JSFunction::kLiteralsOffset));
1567 int literal_offset =
1568 FixedArray::kHeaderSize + expr->literal_index() * kPointerSize;
1569 __ mov(ebx, FieldOperand(ecx, literal_offset));
1570 __ cmp(ebx, isolate()->factory()->undefined_value());
1571 __ j(not_equal, &materialized, Label::kNear);
1573 // Create regexp literal using runtime function
1574 // Result will be in eax.
1576 __ push(Immediate(Smi::FromInt(expr->literal_index())));
1577 __ push(Immediate(expr->pattern()));
1578 __ push(Immediate(expr->flags()));
1579 __ CallRuntime(Runtime::kMaterializeRegExpLiteral, 4);
1582 __ bind(&materialized);
1583 int size = JSRegExp::kSize + JSRegExp::kInObjectFieldCount * kPointerSize;
1584 Label allocated, runtime_allocate;
1585 __ Allocate(size, eax, ecx, edx, &runtime_allocate, TAG_OBJECT);
1588 __ bind(&runtime_allocate);
1590 __ push(Immediate(Smi::FromInt(size)));
1591 __ CallRuntime(Runtime::kAllocateInNewSpace, 1);
1594 __ bind(&allocated);
1595 // Copy the content into the newly allocated memory.
1596 // (Unroll copy loop once for better throughput).
1597 for (int i = 0; i < size - kPointerSize; i += 2 * kPointerSize) {
1598 __ mov(edx, FieldOperand(ebx, i));
1599 __ mov(ecx, FieldOperand(ebx, i + kPointerSize));
1600 __ mov(FieldOperand(eax, i), edx);
1601 __ mov(FieldOperand(eax, i + kPointerSize), ecx);
1603 if ((size % (2 * kPointerSize)) != 0) {
1604 __ mov(edx, FieldOperand(ebx, size - kPointerSize));
1605 __ mov(FieldOperand(eax, size - kPointerSize), edx);
1607 context()->Plug(eax);
1611 void FullCodeGenerator::EmitAccessor(Expression* expression) {
1612 if (expression == NULL) {
1613 __ push(Immediate(isolate()->factory()->null_value()));
1615 VisitForStackValue(expression);
1620 void FullCodeGenerator::VisitObjectLiteral(ObjectLiteral* expr) {
1621 Comment cmnt(masm_, "[ ObjectLiteral");
1623 expr->BuildConstantProperties(isolate());
1624 Handle<FixedArray> constant_properties = expr->constant_properties();
1625 int flags = expr->ComputeFlags();
1626 // If any of the keys would store to the elements array, then we shouldn't
1628 if (MustCreateObjectLiteralWithRuntime(expr)) {
1629 __ mov(edi, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
1630 __ push(FieldOperand(edi, JSFunction::kLiteralsOffset));
1631 __ push(Immediate(Smi::FromInt(expr->literal_index())));
1632 __ push(Immediate(constant_properties));
1633 __ push(Immediate(Smi::FromInt(flags)));
1634 __ CallRuntime(Runtime::kCreateObjectLiteral, 4);
1636 __ mov(edi, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
1637 __ mov(eax, FieldOperand(edi, JSFunction::kLiteralsOffset));
1638 __ mov(ebx, Immediate(Smi::FromInt(expr->literal_index())));
1639 __ mov(ecx, Immediate(constant_properties));
1640 __ mov(edx, Immediate(Smi::FromInt(flags)));
1641 FastCloneShallowObjectStub stub(isolate(), expr->properties_count());
1644 PrepareForBailoutForId(expr->CreateLiteralId(), TOS_REG);
1646 // If result_saved is true the result is on top of the stack. If
1647 // result_saved is false the result is in eax.
1648 bool result_saved = false;
1650 // Mark all computed expressions that are bound to a key that
1651 // is shadowed by a later occurrence of the same key. For the
1652 // marked expressions, no store code is emitted.
1653 expr->CalculateEmitStore(zone());
1655 AccessorTable accessor_table(zone());
1656 int property_index = 0;
1657 for (; property_index < expr->properties()->length(); property_index++) {
1658 ObjectLiteral::Property* property = expr->properties()->at(property_index);
1659 if (property->is_computed_name()) break;
1660 if (property->IsCompileTimeValue()) continue;
1662 Literal* key = property->key()->AsLiteral();
1663 Expression* value = property->value();
1664 if (!result_saved) {
1665 __ push(eax); // Save result on the stack
1666 result_saved = true;
1668 switch (property->kind()) {
1669 case ObjectLiteral::Property::CONSTANT:
1671 case ObjectLiteral::Property::MATERIALIZED_LITERAL:
1672 DCHECK(!CompileTimeValue::IsCompileTimeValue(value));
1674 case ObjectLiteral::Property::COMPUTED:
1675 // It is safe to use [[Put]] here because the boilerplate already
1676 // contains computed properties with an uninitialized value.
1677 if (key->value()->IsInternalizedString()) {
1678 if (property->emit_store()) {
1679 VisitForAccumulatorValue(value);
1680 DCHECK(StoreDescriptor::ValueRegister().is(eax));
1681 __ mov(StoreDescriptor::NameRegister(), Immediate(key->value()));
1682 __ mov(StoreDescriptor::ReceiverRegister(), Operand(esp, 0));
1683 CallStoreIC(key->LiteralFeedbackId());
1684 PrepareForBailoutForId(key->id(), NO_REGISTERS);
1686 if (NeedsHomeObject(value)) {
1687 __ mov(StoreDescriptor::ReceiverRegister(), eax);
1688 __ mov(StoreDescriptor::NameRegister(),
1689 Immediate(isolate()->factory()->home_object_symbol()));
1690 __ mov(StoreDescriptor::ValueRegister(), Operand(esp, 0));
1694 VisitForEffect(value);
1698 __ push(Operand(esp, 0)); // Duplicate receiver.
1699 VisitForStackValue(key);
1700 VisitForStackValue(value);
1701 if (property->emit_store()) {
1702 EmitSetHomeObjectIfNeeded(value, 2);
1703 __ push(Immediate(Smi::FromInt(SLOPPY))); // Language mode
1704 __ CallRuntime(Runtime::kSetProperty, 4);
1709 case ObjectLiteral::Property::PROTOTYPE:
1710 __ push(Operand(esp, 0)); // Duplicate receiver.
1711 VisitForStackValue(value);
1712 DCHECK(property->emit_store());
1713 __ CallRuntime(Runtime::kInternalSetPrototype, 2);
1715 case ObjectLiteral::Property::GETTER:
1716 if (property->emit_store()) {
1717 accessor_table.lookup(key)->second->getter = value;
1720 case ObjectLiteral::Property::SETTER:
1721 if (property->emit_store()) {
1722 accessor_table.lookup(key)->second->setter = value;
1728 // Emit code to define accessors, using only a single call to the runtime for
1729 // each pair of corresponding getters and setters.
1730 for (AccessorTable::Iterator it = accessor_table.begin();
1731 it != accessor_table.end();
1733 __ push(Operand(esp, 0)); // Duplicate receiver.
1734 VisitForStackValue(it->first);
1735 EmitAccessor(it->second->getter);
1736 EmitSetHomeObjectIfNeeded(it->second->getter, 2);
1737 EmitAccessor(it->second->setter);
1738 EmitSetHomeObjectIfNeeded(it->second->setter, 3);
1739 __ push(Immediate(Smi::FromInt(NONE)));
1740 __ CallRuntime(Runtime::kDefineAccessorPropertyUnchecked, 5);
1743 // Object literals have two parts. The "static" part on the left contains no
1744 // computed property names, and so we can compute its map ahead of time; see
1745 // runtime.cc::CreateObjectLiteralBoilerplate. The second "dynamic" part
1746 // starts with the first computed property name, and continues with all
1747 // properties to its right. All the code from above initializes the static
1748 // component of the object literal, and arranges for the map of the result to
1749 // reflect the static order in which the keys appear. For the dynamic
1750 // properties, we compile them into a series of "SetOwnProperty" runtime
1751 // calls. This will preserve insertion order.
1752 for (; property_index < expr->properties()->length(); property_index++) {
1753 ObjectLiteral::Property* property = expr->properties()->at(property_index);
1755 Expression* value = property->value();
1756 if (!result_saved) {
1757 __ push(eax); // Save result on the stack
1758 result_saved = true;
1761 __ push(Operand(esp, 0)); // Duplicate receiver.
1763 if (property->kind() == ObjectLiteral::Property::PROTOTYPE) {
1764 DCHECK(!property->is_computed_name());
1765 VisitForStackValue(value);
1766 DCHECK(property->emit_store());
1767 __ CallRuntime(Runtime::kInternalSetPrototype, 2);
1769 EmitPropertyKey(property, expr->GetIdForProperty(property_index));
1770 VisitForStackValue(value);
1771 EmitSetHomeObjectIfNeeded(value, 2);
1773 switch (property->kind()) {
1774 case ObjectLiteral::Property::CONSTANT:
1775 case ObjectLiteral::Property::MATERIALIZED_LITERAL:
1776 case ObjectLiteral::Property::COMPUTED:
1777 if (property->emit_store()) {
1778 __ push(Immediate(Smi::FromInt(NONE)));
1779 __ CallRuntime(Runtime::kDefineDataPropertyUnchecked, 4);
1785 case ObjectLiteral::Property::PROTOTYPE:
1789 case ObjectLiteral::Property::GETTER:
1790 __ push(Immediate(Smi::FromInt(NONE)));
1791 __ CallRuntime(Runtime::kDefineGetterPropertyUnchecked, 4);
1794 case ObjectLiteral::Property::SETTER:
1795 __ push(Immediate(Smi::FromInt(NONE)));
1796 __ CallRuntime(Runtime::kDefineSetterPropertyUnchecked, 4);
1802 if (expr->has_function()) {
1803 DCHECK(result_saved);
1804 __ push(Operand(esp, 0));
1805 __ CallRuntime(Runtime::kToFastProperties, 1);
1809 context()->PlugTOS();
1811 context()->Plug(eax);
1816 void FullCodeGenerator::VisitArrayLiteral(ArrayLiteral* expr) {
1817 Comment cmnt(masm_, "[ ArrayLiteral");
1819 expr->BuildConstantElements(isolate());
1820 Handle<FixedArray> constant_elements = expr->constant_elements();
1821 bool has_constant_fast_elements =
1822 IsFastObjectElementsKind(expr->constant_elements_kind());
1824 AllocationSiteMode allocation_site_mode = TRACK_ALLOCATION_SITE;
1825 if (has_constant_fast_elements && !FLAG_allocation_site_pretenuring) {
1826 // If the only customer of allocation sites is transitioning, then
1827 // we can turn it off if we don't have anywhere else to transition to.
1828 allocation_site_mode = DONT_TRACK_ALLOCATION_SITE;
1831 if (MustCreateArrayLiteralWithRuntime(expr)) {
1832 __ mov(ebx, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
1833 __ push(FieldOperand(ebx, JSFunction::kLiteralsOffset));
1834 __ push(Immediate(Smi::FromInt(expr->literal_index())));
1835 __ push(Immediate(constant_elements));
1836 __ push(Immediate(Smi::FromInt(expr->ComputeFlags())));
1837 __ CallRuntime(Runtime::kCreateArrayLiteral, 4);
1839 __ mov(ebx, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
1840 __ mov(eax, FieldOperand(ebx, JSFunction::kLiteralsOffset));
1841 __ mov(ebx, Immediate(Smi::FromInt(expr->literal_index())));
1842 __ mov(ecx, Immediate(constant_elements));
1843 FastCloneShallowArrayStub stub(isolate(), allocation_site_mode);
1846 PrepareForBailoutForId(expr->CreateLiteralId(), TOS_REG);
1848 bool result_saved = false; // Is the result saved to the stack?
1849 ZoneList<Expression*>* subexprs = expr->values();
1850 int length = subexprs->length();
1852 // Emit code to evaluate all the non-constant subexpressions and to store
1853 // them into the newly cloned array.
1854 for (int i = 0; i < length; i++) {
1855 Expression* subexpr = subexprs->at(i);
1856 // If the subexpression is a literal or a simple materialized literal it
1857 // is already set in the cloned array.
1858 if (CompileTimeValue::IsCompileTimeValue(subexpr)) continue;
1860 if (!result_saved) {
1861 __ push(eax); // array literal.
1862 __ push(Immediate(Smi::FromInt(expr->literal_index())));
1863 result_saved = true;
1865 VisitForAccumulatorValue(subexpr);
1867 if (has_constant_fast_elements) {
1868 // Fast-case array literal with ElementsKind of FAST_*_ELEMENTS, they
1869 // cannot transition and don't need to call the runtime stub.
1870 int offset = FixedArray::kHeaderSize + (i * kPointerSize);
1871 __ mov(ebx, Operand(esp, kPointerSize)); // Copy of array literal.
1872 __ mov(ebx, FieldOperand(ebx, JSObject::kElementsOffset));
1873 // Store the subexpression value in the array's elements.
1874 __ mov(FieldOperand(ebx, offset), result_register());
1875 // Update the write barrier for the array store.
1876 __ RecordWriteField(ebx, offset, result_register(), ecx,
1878 EMIT_REMEMBERED_SET,
1881 // Store the subexpression value in the array's elements.
1882 __ mov(ecx, Immediate(Smi::FromInt(i)));
1883 StoreArrayLiteralElementStub stub(isolate());
1887 PrepareForBailoutForId(expr->GetIdForElement(i), NO_REGISTERS);
1891 __ add(esp, Immediate(kPointerSize)); // literal index
1892 context()->PlugTOS();
1894 context()->Plug(eax);
1899 void FullCodeGenerator::VisitAssignment(Assignment* expr) {
1900 DCHECK(expr->target()->IsValidReferenceExpression());
1902 Comment cmnt(masm_, "[ Assignment");
1904 Property* property = expr->target()->AsProperty();
1905 LhsKind assign_type = GetAssignType(property);
1907 // Evaluate LHS expression.
1908 switch (assign_type) {
1910 // Nothing to do here.
1912 case NAMED_SUPER_PROPERTY:
1913 VisitForStackValue(property->obj()->AsSuperReference()->this_var());
1914 EmitLoadHomeObject(property->obj()->AsSuperReference());
1915 __ push(result_register());
1916 if (expr->is_compound()) {
1917 __ push(MemOperand(esp, kPointerSize));
1918 __ push(result_register());
1921 case NAMED_PROPERTY:
1922 if (expr->is_compound()) {
1923 // We need the receiver both on the stack and in the register.
1924 VisitForStackValue(property->obj());
1925 __ mov(LoadDescriptor::ReceiverRegister(), Operand(esp, 0));
1927 VisitForStackValue(property->obj());
1930 case KEYED_SUPER_PROPERTY:
1931 VisitForStackValue(property->obj()->AsSuperReference()->this_var());
1932 EmitLoadHomeObject(property->obj()->AsSuperReference());
1933 __ Push(result_register());
1934 VisitForAccumulatorValue(property->key());
1935 __ Push(result_register());
1936 if (expr->is_compound()) {
1937 __ push(MemOperand(esp, 2 * kPointerSize));
1938 __ push(MemOperand(esp, 2 * kPointerSize));
1939 __ push(result_register());
1942 case KEYED_PROPERTY: {
1943 if (expr->is_compound()) {
1944 VisitForStackValue(property->obj());
1945 VisitForStackValue(property->key());
1946 __ mov(LoadDescriptor::ReceiverRegister(), Operand(esp, kPointerSize));
1947 __ mov(LoadDescriptor::NameRegister(), Operand(esp, 0));
1949 VisitForStackValue(property->obj());
1950 VisitForStackValue(property->key());
1956 // For compound assignments we need another deoptimization point after the
1957 // variable/property load.
1958 if (expr->is_compound()) {
1959 AccumulatorValueContext result_context(this);
1960 { AccumulatorValueContext left_operand_context(this);
1961 switch (assign_type) {
1963 EmitVariableLoad(expr->target()->AsVariableProxy());
1964 PrepareForBailout(expr->target(), TOS_REG);
1966 case NAMED_SUPER_PROPERTY:
1967 EmitNamedSuperPropertyLoad(property);
1968 PrepareForBailoutForId(property->LoadId(), TOS_REG);
1970 case NAMED_PROPERTY:
1971 EmitNamedPropertyLoad(property);
1972 PrepareForBailoutForId(property->LoadId(), TOS_REG);
1974 case KEYED_SUPER_PROPERTY:
1975 EmitKeyedSuperPropertyLoad(property);
1976 PrepareForBailoutForId(property->LoadId(), TOS_REG);
1978 case KEYED_PROPERTY:
1979 EmitKeyedPropertyLoad(property);
1980 PrepareForBailoutForId(property->LoadId(), TOS_REG);
1985 Token::Value op = expr->binary_op();
1986 __ push(eax); // Left operand goes on the stack.
1987 VisitForAccumulatorValue(expr->value());
1989 SetSourcePosition(expr->position() + 1);
1990 if (ShouldInlineSmiCase(op)) {
1991 EmitInlineSmiBinaryOp(expr->binary_operation(),
1996 EmitBinaryOp(expr->binary_operation(), op);
1999 // Deoptimization point in case the binary operation may have side effects.
2000 PrepareForBailout(expr->binary_operation(), TOS_REG);
2002 VisitForAccumulatorValue(expr->value());
2005 // Record source position before possible IC call.
2006 SetSourcePosition(expr->position());
2009 switch (assign_type) {
2011 EmitVariableAssignment(expr->target()->AsVariableProxy()->var(),
2013 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
2014 context()->Plug(eax);
2016 case NAMED_PROPERTY:
2017 EmitNamedPropertyAssignment(expr);
2019 case NAMED_SUPER_PROPERTY:
2020 EmitNamedSuperPropertyStore(property);
2021 context()->Plug(result_register());
2023 case KEYED_SUPER_PROPERTY:
2024 EmitKeyedSuperPropertyStore(property);
2025 context()->Plug(result_register());
2027 case KEYED_PROPERTY:
2028 EmitKeyedPropertyAssignment(expr);
2034 void FullCodeGenerator::VisitYield(Yield* expr) {
2035 Comment cmnt(masm_, "[ Yield");
2036 // Evaluate yielded value first; the initial iterator definition depends on
2037 // this. It stays on the stack while we update the iterator.
2038 VisitForStackValue(expr->expression());
2040 switch (expr->yield_kind()) {
2041 case Yield::kSuspend:
2042 // Pop value from top-of-stack slot; box result into result register.
2043 EmitCreateIteratorResult(false);
2044 __ push(result_register());
2046 case Yield::kInitial: {
2047 Label suspend, continuation, post_runtime, resume;
2051 __ bind(&continuation);
2055 VisitForAccumulatorValue(expr->generator_object());
2056 DCHECK(continuation.pos() > 0 && Smi::IsValid(continuation.pos()));
2057 __ mov(FieldOperand(eax, JSGeneratorObject::kContinuationOffset),
2058 Immediate(Smi::FromInt(continuation.pos())));
2059 __ mov(FieldOperand(eax, JSGeneratorObject::kContextOffset), esi);
2061 __ RecordWriteField(eax, JSGeneratorObject::kContextOffset, ecx, edx,
2063 __ lea(ebx, Operand(ebp, StandardFrameConstants::kExpressionsOffset));
2065 __ j(equal, &post_runtime);
2066 __ push(eax); // generator object
2067 __ CallRuntime(Runtime::kSuspendJSGeneratorObject, 1);
2068 __ mov(context_register(),
2069 Operand(ebp, StandardFrameConstants::kContextOffset));
2070 __ bind(&post_runtime);
2071 __ pop(result_register());
2072 EmitReturnSequence();
2075 context()->Plug(result_register());
2079 case Yield::kFinal: {
2080 VisitForAccumulatorValue(expr->generator_object());
2081 __ mov(FieldOperand(result_register(),
2082 JSGeneratorObject::kContinuationOffset),
2083 Immediate(Smi::FromInt(JSGeneratorObject::kGeneratorClosed)));
2084 // Pop value from top-of-stack slot, box result into result register.
2085 EmitCreateIteratorResult(true);
2086 EmitUnwindBeforeReturn();
2087 EmitReturnSequence();
2091 case Yield::kDelegating: {
2092 VisitForStackValue(expr->generator_object());
2094 // Initial stack layout is as follows:
2095 // [sp + 1 * kPointerSize] iter
2096 // [sp + 0 * kPointerSize] g
2098 Label l_catch, l_try, l_suspend, l_continuation, l_resume;
2099 Label l_next, l_call, l_loop;
2100 Register load_receiver = LoadDescriptor::ReceiverRegister();
2101 Register load_name = LoadDescriptor::NameRegister();
2103 // Initial send value is undefined.
2104 __ mov(eax, isolate()->factory()->undefined_value());
2107 // catch (e) { receiver = iter; f = 'throw'; arg = e; goto l_call; }
2109 __ mov(load_name, isolate()->factory()->throw_string()); // "throw"
2110 __ push(load_name); // "throw"
2111 __ push(Operand(esp, 2 * kPointerSize)); // iter
2112 __ push(eax); // exception
2115 // try { received = %yield result }
2116 // Shuffle the received result above a try handler and yield it without
2119 __ pop(eax); // result
2120 EnterTryBlock(expr->index(), &l_catch);
2121 const int try_block_size = TryCatch::kElementCount * kPointerSize;
2122 __ push(eax); // result
2124 __ bind(&l_continuation);
2126 __ bind(&l_suspend);
2127 const int generator_object_depth = kPointerSize + try_block_size;
2128 __ mov(eax, Operand(esp, generator_object_depth));
2130 __ push(Immediate(Smi::FromInt(expr->index()))); // handler-index
2131 DCHECK(l_continuation.pos() > 0 && Smi::IsValid(l_continuation.pos()));
2132 __ mov(FieldOperand(eax, JSGeneratorObject::kContinuationOffset),
2133 Immediate(Smi::FromInt(l_continuation.pos())));
2134 __ mov(FieldOperand(eax, JSGeneratorObject::kContextOffset), esi);
2136 __ RecordWriteField(eax, JSGeneratorObject::kContextOffset, ecx, edx,
2138 __ CallRuntime(Runtime::kSuspendJSGeneratorObject, 2);
2139 __ mov(context_register(),
2140 Operand(ebp, StandardFrameConstants::kContextOffset));
2141 __ pop(eax); // result
2142 EmitReturnSequence();
2143 __ bind(&l_resume); // received in eax
2144 ExitTryBlock(expr->index());
2146 // receiver = iter; f = iter.next; arg = received;
2149 __ mov(load_name, isolate()->factory()->next_string());
2150 __ push(load_name); // "next"
2151 __ push(Operand(esp, 2 * kPointerSize)); // iter
2152 __ push(eax); // received
2154 // result = receiver[f](arg);
2156 __ mov(load_receiver, Operand(esp, kPointerSize));
2157 if (FLAG_vector_ics) {
2158 __ mov(VectorLoadICDescriptor::SlotRegister(),
2159 Immediate(SmiFromSlot(expr->KeyedLoadFeedbackSlot())));
2161 Handle<Code> ic = CodeFactory::KeyedLoadIC(isolate()).code();
2162 CallIC(ic, TypeFeedbackId::None());
2164 __ mov(Operand(esp, 2 * kPointerSize), edi);
2165 CallFunctionStub stub(isolate(), 1, CALL_AS_METHOD);
2168 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
2169 __ Drop(1); // The function is still on the stack; drop it.
2171 // if (!result.done) goto l_try;
2173 __ push(eax); // save result
2174 __ Move(load_receiver, eax); // result
2176 isolate()->factory()->done_string()); // "done"
2177 if (FLAG_vector_ics) {
2178 __ mov(VectorLoadICDescriptor::SlotRegister(),
2179 Immediate(SmiFromSlot(expr->DoneFeedbackSlot())));
2181 CallLoadIC(NOT_CONTEXTUAL); // result.done in eax
2182 Handle<Code> bool_ic = ToBooleanStub::GetUninitialized(isolate());
2188 __ pop(load_receiver); // result
2190 isolate()->factory()->value_string()); // "value"
2191 if (FLAG_vector_ics) {
2192 __ mov(VectorLoadICDescriptor::SlotRegister(),
2193 Immediate(SmiFromSlot(expr->ValueFeedbackSlot())));
2195 CallLoadIC(NOT_CONTEXTUAL); // result.value in eax
2196 context()->DropAndPlug(2, eax); // drop iter and g
2203 void FullCodeGenerator::EmitGeneratorResume(Expression *generator,
2205 JSGeneratorObject::ResumeMode resume_mode) {
2206 // The value stays in eax, and is ultimately read by the resumed generator, as
2207 // if CallRuntime(Runtime::kSuspendJSGeneratorObject) returned it. Or it
2208 // is read to throw the value when the resumed generator is already closed.
2209 // ebx will hold the generator object until the activation has been resumed.
2210 VisitForStackValue(generator);
2211 VisitForAccumulatorValue(value);
2214 // Load suspended function and context.
2215 __ mov(esi, FieldOperand(ebx, JSGeneratorObject::kContextOffset));
2216 __ mov(edi, FieldOperand(ebx, JSGeneratorObject::kFunctionOffset));
2219 __ push(FieldOperand(ebx, JSGeneratorObject::kReceiverOffset));
2221 // Push holes for arguments to generator function.
2222 __ mov(edx, FieldOperand(edi, JSFunction::kSharedFunctionInfoOffset));
2224 FieldOperand(edx, SharedFunctionInfo::kFormalParameterCountOffset));
2225 __ mov(ecx, isolate()->factory()->the_hole_value());
2226 Label push_argument_holes, push_frame;
2227 __ bind(&push_argument_holes);
2228 __ sub(edx, Immediate(Smi::FromInt(1)));
2229 __ j(carry, &push_frame);
2231 __ jmp(&push_argument_holes);
2233 // Enter a new JavaScript frame, and initialize its slots as they were when
2234 // the generator was suspended.
2235 Label resume_frame, done;
2236 __ bind(&push_frame);
2237 __ call(&resume_frame);
2239 __ bind(&resume_frame);
2240 __ push(ebp); // Caller's frame pointer.
2242 __ push(esi); // Callee's context.
2243 __ push(edi); // Callee's JS Function.
2245 // Load the operand stack size.
2246 __ mov(edx, FieldOperand(ebx, JSGeneratorObject::kOperandStackOffset));
2247 __ mov(edx, FieldOperand(edx, FixedArray::kLengthOffset));
2250 // If we are sending a value and there is no operand stack, we can jump back
2252 if (resume_mode == JSGeneratorObject::NEXT) {
2254 __ cmp(edx, Immediate(0));
2255 __ j(not_zero, &slow_resume);
2256 __ mov(edx, FieldOperand(edi, JSFunction::kCodeEntryOffset));
2257 __ mov(ecx, FieldOperand(ebx, JSGeneratorObject::kContinuationOffset));
2260 __ mov(FieldOperand(ebx, JSGeneratorObject::kContinuationOffset),
2261 Immediate(Smi::FromInt(JSGeneratorObject::kGeneratorExecuting)));
2263 __ bind(&slow_resume);
2266 // Otherwise, we push holes for the operand stack and call the runtime to fix
2267 // up the stack and the handlers.
2268 Label push_operand_holes, call_resume;
2269 __ bind(&push_operand_holes);
2270 __ sub(edx, Immediate(1));
2271 __ j(carry, &call_resume);
2273 __ jmp(&push_operand_holes);
2274 __ bind(&call_resume);
2276 __ push(result_register());
2277 __ Push(Smi::FromInt(resume_mode));
2278 __ CallRuntime(Runtime::kResumeJSGeneratorObject, 3);
2279 // Not reached: the runtime call returns elsewhere.
2280 __ Abort(kGeneratorFailedToResume);
2283 context()->Plug(result_register());
2287 void FullCodeGenerator::EmitCreateIteratorResult(bool done) {
2291 const int instance_size = 5 * kPointerSize;
2292 DCHECK_EQ(isolate()->native_context()->iterator_result_map()->instance_size(),
2295 __ Allocate(instance_size, eax, ecx, edx, &gc_required, TAG_OBJECT);
2298 __ bind(&gc_required);
2299 __ Push(Smi::FromInt(instance_size));
2300 __ CallRuntime(Runtime::kAllocateInNewSpace, 1);
2301 __ mov(context_register(),
2302 Operand(ebp, StandardFrameConstants::kContextOffset));
2304 __ bind(&allocated);
2305 __ mov(ebx, Operand(esi, Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX)));
2306 __ mov(ebx, FieldOperand(ebx, GlobalObject::kNativeContextOffset));
2307 __ mov(ebx, ContextOperand(ebx, Context::ITERATOR_RESULT_MAP_INDEX));
2309 __ mov(edx, isolate()->factory()->ToBoolean(done));
2310 __ mov(FieldOperand(eax, HeapObject::kMapOffset), ebx);
2311 __ mov(FieldOperand(eax, JSObject::kPropertiesOffset),
2312 isolate()->factory()->empty_fixed_array());
2313 __ mov(FieldOperand(eax, JSObject::kElementsOffset),
2314 isolate()->factory()->empty_fixed_array());
2315 __ mov(FieldOperand(eax, JSGeneratorObject::kResultValuePropertyOffset), ecx);
2316 __ mov(FieldOperand(eax, JSGeneratorObject::kResultDonePropertyOffset), edx);
2318 // Only the value field needs a write barrier, as the other values are in the
2320 __ RecordWriteField(eax, JSGeneratorObject::kResultValuePropertyOffset,
2321 ecx, edx, kDontSaveFPRegs);
2325 void FullCodeGenerator::EmitNamedPropertyLoad(Property* prop) {
2326 SetSourcePosition(prop->position());
2327 Literal* key = prop->key()->AsLiteral();
2328 DCHECK(!key->value()->IsSmi());
2329 DCHECK(!prop->IsSuperAccess());
2331 __ mov(LoadDescriptor::NameRegister(), Immediate(key->value()));
2332 if (FLAG_vector_ics) {
2333 __ mov(VectorLoadICDescriptor::SlotRegister(),
2334 Immediate(SmiFromSlot(prop->PropertyFeedbackSlot())));
2335 CallLoadIC(NOT_CONTEXTUAL);
2337 CallLoadIC(NOT_CONTEXTUAL, prop->PropertyFeedbackId());
2342 void FullCodeGenerator::EmitNamedSuperPropertyLoad(Property* prop) {
2343 // Stack: receiver, home_object.
2344 SetSourcePosition(prop->position());
2345 Literal* key = prop->key()->AsLiteral();
2346 DCHECK(!key->value()->IsSmi());
2347 DCHECK(prop->IsSuperAccess());
2349 __ push(Immediate(key->value()));
2350 __ CallRuntime(Runtime::kLoadFromSuper, 3);
2354 void FullCodeGenerator::EmitKeyedPropertyLoad(Property* prop) {
2355 SetSourcePosition(prop->position());
2356 Handle<Code> ic = CodeFactory::KeyedLoadIC(isolate()).code();
2357 if (FLAG_vector_ics) {
2358 __ mov(VectorLoadICDescriptor::SlotRegister(),
2359 Immediate(SmiFromSlot(prop->PropertyFeedbackSlot())));
2362 CallIC(ic, prop->PropertyFeedbackId());
2367 void FullCodeGenerator::EmitKeyedSuperPropertyLoad(Property* prop) {
2368 // Stack: receiver, home_object, key.
2369 SetSourcePosition(prop->position());
2371 __ CallRuntime(Runtime::kLoadKeyedFromSuper, 3);
2375 void FullCodeGenerator::EmitInlineSmiBinaryOp(BinaryOperation* expr,
2378 Expression* right) {
2379 // Do combined smi check of the operands. Left operand is on the
2380 // stack. Right operand is in eax.
2381 Label smi_case, done, stub_call;
2385 JumpPatchSite patch_site(masm_);
2386 patch_site.EmitJumpIfSmi(eax, &smi_case, Label::kNear);
2388 __ bind(&stub_call);
2390 Handle<Code> code = CodeFactory::BinaryOpIC(isolate(), op).code();
2391 CallIC(code, expr->BinaryOperationFeedbackId());
2392 patch_site.EmitPatchInfo();
2393 __ jmp(&done, Label::kNear);
2397 __ mov(eax, edx); // Copy left operand in case of a stub call.
2402 __ sar_cl(eax); // No checks of result necessary
2403 __ and_(eax, Immediate(~kSmiTagMask));
2410 // Check that the *signed* result fits in a smi.
2411 __ cmp(eax, 0xc0000000);
2412 __ j(positive, &result_ok);
2415 __ bind(&result_ok);
2424 __ test(eax, Immediate(0xc0000000));
2425 __ j(zero, &result_ok);
2428 __ bind(&result_ok);
2434 __ j(overflow, &stub_call);
2438 __ j(overflow, &stub_call);
2443 __ j(overflow, &stub_call);
2445 __ j(not_zero, &done, Label::kNear);
2448 __ j(negative, &stub_call);
2454 case Token::BIT_AND:
2457 case Token::BIT_XOR:
2465 context()->Plug(eax);
2469 void FullCodeGenerator::EmitClassDefineProperties(ClassLiteral* lit) {
2470 // Constructor is in eax.
2471 DCHECK(lit != NULL);
2474 // No access check is needed here since the constructor is created by the
2476 Register scratch = ebx;
2477 __ mov(scratch, FieldOperand(eax, JSFunction::kPrototypeOrInitialMapOffset));
2480 for (int i = 0; i < lit->properties()->length(); i++) {
2481 ObjectLiteral::Property* property = lit->properties()->at(i);
2482 Expression* value = property->value();
2484 if (property->is_static()) {
2485 __ push(Operand(esp, kPointerSize)); // constructor
2487 __ push(Operand(esp, 0)); // prototype
2489 EmitPropertyKey(property, lit->GetIdForProperty(i));
2491 // The static prototype property is read only. We handle the non computed
2492 // property name case in the parser. Since this is the only case where we
2493 // need to check for an own read only property we special case this so we do
2494 // not need to do this for every property.
2495 if (property->is_static() && property->is_computed_name()) {
2496 __ CallRuntime(Runtime::kThrowIfStaticPrototype, 1);
2500 VisitForStackValue(value);
2501 EmitSetHomeObjectIfNeeded(value, 2);
2503 switch (property->kind()) {
2504 case ObjectLiteral::Property::CONSTANT:
2505 case ObjectLiteral::Property::MATERIALIZED_LITERAL:
2506 case ObjectLiteral::Property::PROTOTYPE:
2508 case ObjectLiteral::Property::COMPUTED:
2509 __ CallRuntime(Runtime::kDefineClassMethod, 3);
2512 case ObjectLiteral::Property::GETTER:
2513 __ push(Immediate(Smi::FromInt(DONT_ENUM)));
2514 __ CallRuntime(Runtime::kDefineGetterPropertyUnchecked, 4);
2517 case ObjectLiteral::Property::SETTER:
2518 __ push(Immediate(Smi::FromInt(DONT_ENUM)));
2519 __ CallRuntime(Runtime::kDefineSetterPropertyUnchecked, 4);
2525 __ CallRuntime(Runtime::kToFastProperties, 1);
2528 __ CallRuntime(Runtime::kToFastProperties, 1);
2532 void FullCodeGenerator::EmitBinaryOp(BinaryOperation* expr, Token::Value op) {
2534 Handle<Code> code = CodeFactory::BinaryOpIC(isolate(), op).code();
2535 JumpPatchSite patch_site(masm_); // unbound, signals no inlined smi code.
2536 CallIC(code, expr->BinaryOperationFeedbackId());
2537 patch_site.EmitPatchInfo();
2538 context()->Plug(eax);
2542 void FullCodeGenerator::EmitAssignment(Expression* expr) {
2543 DCHECK(expr->IsValidReferenceExpression());
2545 Property* prop = expr->AsProperty();
2546 LhsKind assign_type = GetAssignType(prop);
2548 switch (assign_type) {
2550 Variable* var = expr->AsVariableProxy()->var();
2551 EffectContext context(this);
2552 EmitVariableAssignment(var, Token::ASSIGN);
2555 case NAMED_PROPERTY: {
2556 __ push(eax); // Preserve value.
2557 VisitForAccumulatorValue(prop->obj());
2558 __ Move(StoreDescriptor::ReceiverRegister(), eax);
2559 __ pop(StoreDescriptor::ValueRegister()); // Restore value.
2560 __ mov(StoreDescriptor::NameRegister(),
2561 prop->key()->AsLiteral()->value());
2565 case NAMED_SUPER_PROPERTY: {
2567 VisitForStackValue(prop->obj()->AsSuperReference()->this_var());
2568 EmitLoadHomeObject(prop->obj()->AsSuperReference());
2569 // stack: value, this; eax: home_object
2570 Register scratch = ecx;
2571 Register scratch2 = edx;
2572 __ mov(scratch, result_register()); // home_object
2573 __ mov(eax, MemOperand(esp, kPointerSize)); // value
2574 __ mov(scratch2, MemOperand(esp, 0)); // this
2575 __ mov(MemOperand(esp, kPointerSize), scratch2); // this
2576 __ mov(MemOperand(esp, 0), scratch); // home_object
2577 // stack: this, home_object. eax: value
2578 EmitNamedSuperPropertyStore(prop);
2581 case KEYED_SUPER_PROPERTY: {
2583 VisitForStackValue(prop->obj()->AsSuperReference()->this_var());
2584 EmitLoadHomeObject(prop->obj()->AsSuperReference());
2585 __ push(result_register());
2586 VisitForAccumulatorValue(prop->key());
2587 Register scratch = ecx;
2588 Register scratch2 = edx;
2589 __ mov(scratch2, MemOperand(esp, 2 * kPointerSize)); // value
2590 // stack: value, this, home_object; eax: key, edx: value
2591 __ mov(scratch, MemOperand(esp, kPointerSize)); // this
2592 __ mov(MemOperand(esp, 2 * kPointerSize), scratch);
2593 __ mov(scratch, MemOperand(esp, 0)); // home_object
2594 __ mov(MemOperand(esp, kPointerSize), scratch);
2595 __ mov(MemOperand(esp, 0), eax);
2596 __ mov(eax, scratch2);
2597 // stack: this, home_object, key; eax: value.
2598 EmitKeyedSuperPropertyStore(prop);
2601 case KEYED_PROPERTY: {
2602 __ push(eax); // Preserve value.
2603 VisitForStackValue(prop->obj());
2604 VisitForAccumulatorValue(prop->key());
2605 __ Move(StoreDescriptor::NameRegister(), eax);
2606 __ pop(StoreDescriptor::ReceiverRegister()); // Receiver.
2607 __ pop(StoreDescriptor::ValueRegister()); // Restore value.
2609 CodeFactory::KeyedStoreIC(isolate(), language_mode()).code();
2614 context()->Plug(eax);
2618 void FullCodeGenerator::EmitStoreToStackLocalOrContextSlot(
2619 Variable* var, MemOperand location) {
2620 __ mov(location, eax);
2621 if (var->IsContextSlot()) {
2623 int offset = Context::SlotOffset(var->index());
2624 __ RecordWriteContextSlot(ecx, offset, edx, ebx, kDontSaveFPRegs);
2629 void FullCodeGenerator::EmitVariableAssignment(Variable* var,
2631 if (var->IsUnallocated()) {
2632 // Global var, const, or let.
2633 __ mov(StoreDescriptor::NameRegister(), var->name());
2634 __ mov(StoreDescriptor::ReceiverRegister(), GlobalObjectOperand());
2637 } else if (var->mode() == LET && op != Token::INIT_LET) {
2638 // Non-initializing assignment to let variable needs a write barrier.
2639 DCHECK(!var->IsLookupSlot());
2640 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
2642 MemOperand location = VarOperand(var, ecx);
2643 __ mov(edx, location);
2644 __ cmp(edx, isolate()->factory()->the_hole_value());
2645 __ j(not_equal, &assign, Label::kNear);
2646 __ push(Immediate(var->name()));
2647 __ CallRuntime(Runtime::kThrowReferenceError, 1);
2649 EmitStoreToStackLocalOrContextSlot(var, location);
2651 } else if (var->mode() == CONST && op != Token::INIT_CONST) {
2652 // Assignment to const variable needs a write barrier.
2653 DCHECK(!var->IsLookupSlot());
2654 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
2656 MemOperand location = VarOperand(var, ecx);
2657 __ mov(edx, location);
2658 __ cmp(edx, isolate()->factory()->the_hole_value());
2659 __ j(not_equal, &const_error, Label::kNear);
2660 __ push(Immediate(var->name()));
2661 __ CallRuntime(Runtime::kThrowReferenceError, 1);
2662 __ bind(&const_error);
2663 __ CallRuntime(Runtime::kThrowConstAssignError, 0);
2665 } else if (!var->is_const_mode() || op == Token::INIT_CONST) {
2666 if (var->IsLookupSlot()) {
2667 // Assignment to var.
2668 __ push(eax); // Value.
2669 __ push(esi); // Context.
2670 __ push(Immediate(var->name()));
2671 __ push(Immediate(Smi::FromInt(language_mode())));
2672 __ CallRuntime(Runtime::kStoreLookupSlot, 4);
2674 // Assignment to var or initializing assignment to let/const in harmony
2676 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
2677 MemOperand location = VarOperand(var, ecx);
2678 if (generate_debug_code_ && op == Token::INIT_LET) {
2679 // Check for an uninitialized let binding.
2680 __ mov(edx, location);
2681 __ cmp(edx, isolate()->factory()->the_hole_value());
2682 __ Check(equal, kLetBindingReInitialization);
2684 EmitStoreToStackLocalOrContextSlot(var, location);
2687 } else if (op == Token::INIT_CONST_LEGACY) {
2688 // Const initializers need a write barrier.
2689 DCHECK(var->mode() == CONST_LEGACY);
2690 DCHECK(!var->IsParameter()); // No const parameters.
2691 if (var->IsLookupSlot()) {
2694 __ push(Immediate(var->name()));
2695 __ CallRuntime(Runtime::kInitializeLegacyConstLookupSlot, 3);
2697 DCHECK(var->IsStackLocal() || var->IsContextSlot());
2699 MemOperand location = VarOperand(var, ecx);
2700 __ mov(edx, location);
2701 __ cmp(edx, isolate()->factory()->the_hole_value());
2702 __ j(not_equal, &skip, Label::kNear);
2703 EmitStoreToStackLocalOrContextSlot(var, location);
2708 DCHECK(var->mode() == CONST_LEGACY && op != Token::INIT_CONST_LEGACY);
2709 if (is_strict(language_mode())) {
2710 __ CallRuntime(Runtime::kThrowConstAssignError, 0);
2712 // Silently ignore store in sloppy mode.
2717 void FullCodeGenerator::EmitNamedPropertyAssignment(Assignment* expr) {
2718 // Assignment to a property, using a named store IC.
2720 // esp[0] : receiver
2722 Property* prop = expr->target()->AsProperty();
2723 DCHECK(prop != NULL);
2724 DCHECK(prop->key()->IsLiteral());
2726 // Record source code position before IC call.
2727 SetSourcePosition(expr->position());
2728 __ mov(StoreDescriptor::NameRegister(), prop->key()->AsLiteral()->value());
2729 __ pop(StoreDescriptor::ReceiverRegister());
2730 CallStoreIC(expr->AssignmentFeedbackId());
2731 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
2732 context()->Plug(eax);
2736 void FullCodeGenerator::EmitNamedSuperPropertyStore(Property* prop) {
2737 // Assignment to named property of super.
2739 // stack : receiver ('this'), home_object
2740 DCHECK(prop != NULL);
2741 Literal* key = prop->key()->AsLiteral();
2742 DCHECK(key != NULL);
2744 __ push(Immediate(key->value()));
2746 __ CallRuntime((is_strict(language_mode()) ? Runtime::kStoreToSuper_Strict
2747 : Runtime::kStoreToSuper_Sloppy),
2752 void FullCodeGenerator::EmitKeyedSuperPropertyStore(Property* prop) {
2753 // Assignment to named property of super.
2755 // stack : receiver ('this'), home_object, key
2759 (is_strict(language_mode()) ? Runtime::kStoreKeyedToSuper_Strict
2760 : Runtime::kStoreKeyedToSuper_Sloppy),
2765 void FullCodeGenerator::EmitKeyedPropertyAssignment(Assignment* expr) {
2766 // Assignment to a property, using a keyed store IC.
2769 // esp[kPointerSize] : receiver
2771 __ pop(StoreDescriptor::NameRegister()); // Key.
2772 __ pop(StoreDescriptor::ReceiverRegister());
2773 DCHECK(StoreDescriptor::ValueRegister().is(eax));
2774 // Record source code position before IC call.
2775 SetSourcePosition(expr->position());
2777 CodeFactory::KeyedStoreIC(isolate(), language_mode()).code();
2778 CallIC(ic, expr->AssignmentFeedbackId());
2780 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
2781 context()->Plug(eax);
2785 void FullCodeGenerator::VisitProperty(Property* expr) {
2786 Comment cmnt(masm_, "[ Property");
2787 Expression* key = expr->key();
2789 if (key->IsPropertyName()) {
2790 if (!expr->IsSuperAccess()) {
2791 VisitForAccumulatorValue(expr->obj());
2792 __ Move(LoadDescriptor::ReceiverRegister(), result_register());
2793 EmitNamedPropertyLoad(expr);
2795 VisitForStackValue(expr->obj()->AsSuperReference()->this_var());
2796 EmitLoadHomeObject(expr->obj()->AsSuperReference());
2797 __ push(result_register());
2798 EmitNamedSuperPropertyLoad(expr);
2801 if (!expr->IsSuperAccess()) {
2802 VisitForStackValue(expr->obj());
2803 VisitForAccumulatorValue(expr->key());
2804 __ pop(LoadDescriptor::ReceiverRegister()); // Object.
2805 __ Move(LoadDescriptor::NameRegister(), result_register()); // Key.
2806 EmitKeyedPropertyLoad(expr);
2808 VisitForStackValue(expr->obj()->AsSuperReference()->this_var());
2809 EmitLoadHomeObject(expr->obj()->AsSuperReference());
2810 __ push(result_register());
2811 VisitForStackValue(expr->key());
2812 EmitKeyedSuperPropertyLoad(expr);
2815 PrepareForBailoutForId(expr->LoadId(), TOS_REG);
2816 context()->Plug(eax);
2820 void FullCodeGenerator::CallIC(Handle<Code> code,
2821 TypeFeedbackId ast_id) {
2823 __ call(code, RelocInfo::CODE_TARGET, ast_id);
2827 // Code common for calls using the IC.
2828 void FullCodeGenerator::EmitCallWithLoadIC(Call* expr) {
2829 Expression* callee = expr->expression();
2831 CallICState::CallType call_type =
2832 callee->IsVariableProxy() ? CallICState::FUNCTION : CallICState::METHOD;
2833 // Get the target function.
2834 if (call_type == CallICState::FUNCTION) {
2835 { StackValueContext context(this);
2836 EmitVariableLoad(callee->AsVariableProxy());
2837 PrepareForBailout(callee, NO_REGISTERS);
2839 // Push undefined as receiver. This is patched in the method prologue if it
2840 // is a sloppy mode method.
2841 __ push(Immediate(isolate()->factory()->undefined_value()));
2843 // Load the function from the receiver.
2844 DCHECK(callee->IsProperty());
2845 DCHECK(!callee->AsProperty()->IsSuperAccess());
2846 __ mov(LoadDescriptor::ReceiverRegister(), Operand(esp, 0));
2847 EmitNamedPropertyLoad(callee->AsProperty());
2848 PrepareForBailoutForId(callee->AsProperty()->LoadId(), TOS_REG);
2849 // Push the target function under the receiver.
2850 __ push(Operand(esp, 0));
2851 __ mov(Operand(esp, kPointerSize), eax);
2854 EmitCall(expr, call_type);
2858 void FullCodeGenerator::EmitSuperCallWithLoadIC(Call* expr) {
2859 Expression* callee = expr->expression();
2860 DCHECK(callee->IsProperty());
2861 Property* prop = callee->AsProperty();
2862 DCHECK(prop->IsSuperAccess());
2864 SetSourcePosition(prop->position());
2865 Literal* key = prop->key()->AsLiteral();
2866 DCHECK(!key->value()->IsSmi());
2867 // Load the function from the receiver.
2868 SuperReference* super_ref = callee->AsProperty()->obj()->AsSuperReference();
2869 EmitLoadHomeObject(super_ref);
2871 VisitForAccumulatorValue(super_ref->this_var());
2874 __ push(Operand(esp, kPointerSize * 2));
2875 __ push(Immediate(key->value()));
2878 // - this (receiver)
2879 // - this (receiver) <-- LoadFromSuper will pop here and below.
2882 __ CallRuntime(Runtime::kLoadFromSuper, 3);
2884 // Replace home_object with target function.
2885 __ mov(Operand(esp, kPointerSize), eax);
2888 // - target function
2889 // - this (receiver)
2890 EmitCall(expr, CallICState::METHOD);
2894 // Code common for calls using the IC.
2895 void FullCodeGenerator::EmitKeyedCallWithLoadIC(Call* expr,
2898 VisitForAccumulatorValue(key);
2900 Expression* callee = expr->expression();
2902 // Load the function from the receiver.
2903 DCHECK(callee->IsProperty());
2904 __ mov(LoadDescriptor::ReceiverRegister(), Operand(esp, 0));
2905 __ mov(LoadDescriptor::NameRegister(), eax);
2906 EmitKeyedPropertyLoad(callee->AsProperty());
2907 PrepareForBailoutForId(callee->AsProperty()->LoadId(), TOS_REG);
2909 // Push the target function under the receiver.
2910 __ push(Operand(esp, 0));
2911 __ mov(Operand(esp, kPointerSize), eax);
2913 EmitCall(expr, CallICState::METHOD);
2917 void FullCodeGenerator::EmitKeyedSuperCallWithLoadIC(Call* expr) {
2918 Expression* callee = expr->expression();
2919 DCHECK(callee->IsProperty());
2920 Property* prop = callee->AsProperty();
2921 DCHECK(prop->IsSuperAccess());
2923 SetSourcePosition(prop->position());
2924 // Load the function from the receiver.
2925 SuperReference* super_ref = callee->AsProperty()->obj()->AsSuperReference();
2926 EmitLoadHomeObject(super_ref);
2928 VisitForAccumulatorValue(super_ref->this_var());
2931 __ push(Operand(esp, kPointerSize * 2));
2932 VisitForStackValue(prop->key());
2935 // - this (receiver)
2936 // - this (receiver) <-- LoadKeyedFromSuper will pop here and below.
2939 __ CallRuntime(Runtime::kLoadKeyedFromSuper, 3);
2941 // Replace home_object with target function.
2942 __ mov(Operand(esp, kPointerSize), eax);
2945 // - target function
2946 // - this (receiver)
2947 EmitCall(expr, CallICState::METHOD);
2951 void FullCodeGenerator::EmitCall(Call* expr, CallICState::CallType call_type) {
2952 // Load the arguments.
2953 ZoneList<Expression*>* args = expr->arguments();
2954 int arg_count = args->length();
2955 { PreservePositionScope scope(masm()->positions_recorder());
2956 for (int i = 0; i < arg_count; i++) {
2957 VisitForStackValue(args->at(i));
2961 // Record source position of the IC call.
2962 SetSourcePosition(expr->position());
2963 Handle<Code> ic = CodeFactory::CallIC(isolate(), arg_count, call_type).code();
2964 __ Move(edx, Immediate(SmiFromSlot(expr->CallFeedbackICSlot())));
2965 __ mov(edi, Operand(esp, (arg_count + 1) * kPointerSize));
2966 // Don't assign a type feedback id to the IC, since type feedback is provided
2967 // by the vector above.
2970 RecordJSReturnSite(expr);
2972 // Restore context register.
2973 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
2975 context()->DropAndPlug(1, eax);
2979 void FullCodeGenerator::EmitResolvePossiblyDirectEval(int arg_count) {
2980 // Push copy of the first argument or undefined if it doesn't exist.
2981 if (arg_count > 0) {
2982 __ push(Operand(esp, arg_count * kPointerSize));
2984 __ push(Immediate(isolate()->factory()->undefined_value()));
2987 // Push the enclosing function.
2988 __ push(Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
2989 // Push the receiver of the enclosing function.
2990 __ push(Operand(ebp, (2 + info_->scope()->num_parameters()) * kPointerSize));
2991 // Push the language mode.
2992 __ push(Immediate(Smi::FromInt(language_mode())));
2994 // Push the start position of the scope the calls resides in.
2995 __ push(Immediate(Smi::FromInt(scope()->start_position())));
2997 // Do the runtime call.
2998 __ CallRuntime(Runtime::kResolvePossiblyDirectEval, 6);
3002 void FullCodeGenerator::EmitLoadSuperConstructor() {
3003 __ push(Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
3004 __ CallRuntime(Runtime::kGetPrototype, 1);
3008 void FullCodeGenerator::VisitCall(Call* expr) {
3010 // We want to verify that RecordJSReturnSite gets called on all paths
3011 // through this function. Avoid early returns.
3012 expr->return_is_recorded_ = false;
3015 Comment cmnt(masm_, "[ Call");
3016 Expression* callee = expr->expression();
3017 Call::CallType call_type = expr->GetCallType(isolate());
3019 if (call_type == Call::POSSIBLY_EVAL_CALL) {
3020 // In a call to eval, we first call RuntimeHidden_ResolvePossiblyDirectEval
3021 // to resolve the function we need to call and the receiver of the call.
3022 // Then we call the resolved function using the given arguments.
3023 ZoneList<Expression*>* args = expr->arguments();
3024 int arg_count = args->length();
3025 { PreservePositionScope pos_scope(masm()->positions_recorder());
3026 VisitForStackValue(callee);
3027 // Reserved receiver slot.
3028 __ push(Immediate(isolate()->factory()->undefined_value()));
3029 // Push the arguments.
3030 for (int i = 0; i < arg_count; i++) {
3031 VisitForStackValue(args->at(i));
3034 // Push a copy of the function (found below the arguments) and
3036 __ push(Operand(esp, (arg_count + 1) * kPointerSize));
3037 EmitResolvePossiblyDirectEval(arg_count);
3039 // The runtime call returns a pair of values in eax (function) and
3040 // edx (receiver). Touch up the stack with the right values.
3041 __ mov(Operand(esp, (arg_count + 0) * kPointerSize), edx);
3042 __ mov(Operand(esp, (arg_count + 1) * kPointerSize), eax);
3044 PrepareForBailoutForId(expr->EvalOrLookupId(), NO_REGISTERS);
3046 // Record source position for debugger.
3047 SetSourcePosition(expr->position());
3048 CallFunctionStub stub(isolate(), arg_count, NO_CALL_FUNCTION_FLAGS);
3049 __ mov(edi, Operand(esp, (arg_count + 1) * kPointerSize));
3051 RecordJSReturnSite(expr);
3052 // Restore context register.
3053 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
3054 context()->DropAndPlug(1, eax);
3056 } else if (call_type == Call::GLOBAL_CALL) {
3057 EmitCallWithLoadIC(expr);
3058 } else if (call_type == Call::LOOKUP_SLOT_CALL) {
3059 // Call to a lookup slot (dynamically introduced variable).
3060 VariableProxy* proxy = callee->AsVariableProxy();
3062 { PreservePositionScope scope(masm()->positions_recorder());
3063 // Generate code for loading from variables potentially shadowed by
3064 // eval-introduced variables.
3065 EmitDynamicLookupFastCase(proxy, NOT_INSIDE_TYPEOF, &slow, &done);
3068 // Call the runtime to find the function to call (returned in eax) and
3069 // the object holding it (returned in edx).
3070 __ push(context_register());
3071 __ push(Immediate(proxy->name()));
3072 __ CallRuntime(Runtime::kLoadLookupSlot, 2);
3073 __ push(eax); // Function.
3074 __ push(edx); // Receiver.
3075 PrepareForBailoutForId(expr->EvalOrLookupId(), NO_REGISTERS);
3077 // If fast case code has been generated, emit code to push the function
3078 // and receiver and have the slow path jump around this code.
3079 if (done.is_linked()) {
3081 __ jmp(&call, Label::kNear);
3085 // The receiver is implicitly the global receiver. Indicate this by
3086 // passing the hole to the call function stub.
3087 __ push(Immediate(isolate()->factory()->undefined_value()));
3091 // The receiver is either the global receiver or an object found by
3095 } else if (call_type == Call::PROPERTY_CALL) {
3096 Property* property = callee->AsProperty();
3097 bool is_named_call = property->key()->IsPropertyName();
3098 if (property->IsSuperAccess()) {
3099 if (is_named_call) {
3100 EmitSuperCallWithLoadIC(expr);
3102 EmitKeyedSuperCallWithLoadIC(expr);
3106 PreservePositionScope scope(masm()->positions_recorder());
3107 VisitForStackValue(property->obj());
3109 if (is_named_call) {
3110 EmitCallWithLoadIC(expr);
3112 EmitKeyedCallWithLoadIC(expr, property->key());
3115 } else if (call_type == Call::SUPER_CALL) {
3116 EmitSuperConstructorCall(expr);
3118 DCHECK(call_type == Call::OTHER_CALL);
3119 // Call to an arbitrary expression not handled specially above.
3120 { PreservePositionScope scope(masm()->positions_recorder());
3121 VisitForStackValue(callee);
3123 __ push(Immediate(isolate()->factory()->undefined_value()));
3124 // Emit function call.
3129 // RecordJSReturnSite should have been called.
3130 DCHECK(expr->return_is_recorded_);
3135 void FullCodeGenerator::VisitCallNew(CallNew* expr) {
3136 Comment cmnt(masm_, "[ CallNew");
3137 // According to ECMA-262, section 11.2.2, page 44, the function
3138 // expression in new calls must be evaluated before the
3141 // Push constructor on the stack. If it's not a function it's used as
3142 // receiver for CALL_NON_FUNCTION, otherwise the value on the stack is
3144 DCHECK(!expr->expression()->IsSuperReference());
3145 VisitForStackValue(expr->expression());
3147 // Push the arguments ("left-to-right") on the stack.
3148 ZoneList<Expression*>* args = expr->arguments();
3149 int arg_count = args->length();
3150 for (int i = 0; i < arg_count; i++) {
3151 VisitForStackValue(args->at(i));
3154 // Call the construct call builtin that handles allocation and
3155 // constructor invocation.
3156 SetSourcePosition(expr->position());
3158 // Load function and argument count into edi and eax.
3159 __ Move(eax, Immediate(arg_count));
3160 __ mov(edi, Operand(esp, arg_count * kPointerSize));
3162 // Record call targets in unoptimized code.
3163 if (FLAG_pretenuring_call_new) {
3164 EnsureSlotContainsAllocationSite(expr->AllocationSiteFeedbackSlot());
3165 DCHECK(expr->AllocationSiteFeedbackSlot().ToInt() ==
3166 expr->CallNewFeedbackSlot().ToInt() + 1);
3169 __ LoadHeapObject(ebx, FeedbackVector());
3170 __ mov(edx, Immediate(SmiFromSlot(expr->CallNewFeedbackSlot())));
3172 CallConstructStub stub(isolate(), RECORD_CONSTRUCTOR_TARGET);
3173 __ call(stub.GetCode(), RelocInfo::CONSTRUCT_CALL);
3174 PrepareForBailoutForId(expr->ReturnId(), TOS_REG);
3175 context()->Plug(eax);
3179 void FullCodeGenerator::EmitSuperConstructorCall(Call* expr) {
3180 Variable* new_target_var = scope()->DeclarationScope()->new_target_var();
3181 GetVar(eax, new_target_var);
3184 EmitLoadSuperConstructor();
3185 __ push(result_register());
3187 // Push the arguments ("left-to-right") on the stack.
3188 ZoneList<Expression*>* args = expr->arguments();
3189 int arg_count = args->length();
3190 for (int i = 0; i < arg_count; i++) {
3191 VisitForStackValue(args->at(i));
3194 // Call the construct call builtin that handles allocation and
3195 // constructor invocation.
3196 SetSourcePosition(expr->position());
3198 // Load function and argument count into edi and eax.
3199 __ Move(eax, Immediate(arg_count));
3200 __ mov(edi, Operand(esp, arg_count * kPointerSize));
3202 // Record call targets in unoptimized code.
3203 if (FLAG_pretenuring_call_new) {
3205 /* TODO(dslomov): support pretenuring.
3206 EnsureSlotContainsAllocationSite(expr->AllocationSiteFeedbackSlot());
3207 DCHECK(expr->AllocationSiteFeedbackSlot().ToInt() ==
3208 expr->CallNewFeedbackSlot().ToInt() + 1);
3212 __ LoadHeapObject(ebx, FeedbackVector());
3213 __ mov(edx, Immediate(SmiFromSlot(expr->CallFeedbackSlot())));
3215 CallConstructStub stub(isolate(), SUPER_CALL_RECORD_TARGET);
3216 __ call(stub.GetCode(), RelocInfo::CONSTRUCT_CALL);
3220 RecordJSReturnSite(expr);
3222 SuperReference* super_ref = expr->expression()->AsSuperReference();
3223 Variable* this_var = super_ref->this_var()->var();
3224 GetVar(ecx, this_var);
3225 __ cmp(ecx, isolate()->factory()->the_hole_value());
3226 Label uninitialized_this;
3227 __ j(equal, &uninitialized_this);
3228 __ push(Immediate(this_var->name()));
3229 __ CallRuntime(Runtime::kThrowReferenceError, 1);
3230 __ bind(&uninitialized_this);
3232 EmitVariableAssignment(this_var, Token::INIT_CONST);
3233 context()->Plug(eax);
3237 void FullCodeGenerator::EmitIsSmi(CallRuntime* expr) {
3238 ZoneList<Expression*>* args = expr->arguments();
3239 DCHECK(args->length() == 1);
3241 VisitForAccumulatorValue(args->at(0));
3243 Label materialize_true, materialize_false;
3244 Label* if_true = NULL;
3245 Label* if_false = NULL;
3246 Label* fall_through = NULL;
3247 context()->PrepareTest(&materialize_true, &materialize_false,
3248 &if_true, &if_false, &fall_through);
3250 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3251 __ test(eax, Immediate(kSmiTagMask));
3252 Split(zero, if_true, if_false, fall_through);
3254 context()->Plug(if_true, if_false);
3258 void FullCodeGenerator::EmitIsNonNegativeSmi(CallRuntime* expr) {
3259 ZoneList<Expression*>* args = expr->arguments();
3260 DCHECK(args->length() == 1);
3262 VisitForAccumulatorValue(args->at(0));
3264 Label materialize_true, materialize_false;
3265 Label* if_true = NULL;
3266 Label* if_false = NULL;
3267 Label* fall_through = NULL;
3268 context()->PrepareTest(&materialize_true, &materialize_false,
3269 &if_true, &if_false, &fall_through);
3271 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3272 __ test(eax, Immediate(kSmiTagMask | 0x80000000));
3273 Split(zero, if_true, if_false, fall_through);
3275 context()->Plug(if_true, if_false);
3279 void FullCodeGenerator::EmitIsObject(CallRuntime* expr) {
3280 ZoneList<Expression*>* args = expr->arguments();
3281 DCHECK(args->length() == 1);
3283 VisitForAccumulatorValue(args->at(0));
3285 Label materialize_true, materialize_false;
3286 Label* if_true = NULL;
3287 Label* if_false = NULL;
3288 Label* fall_through = NULL;
3289 context()->PrepareTest(&materialize_true, &materialize_false,
3290 &if_true, &if_false, &fall_through);
3292 __ JumpIfSmi(eax, if_false);
3293 __ cmp(eax, isolate()->factory()->null_value());
3294 __ j(equal, if_true);
3295 __ mov(ebx, FieldOperand(eax, HeapObject::kMapOffset));
3296 // Undetectable objects behave like undefined when tested with typeof.
3297 __ movzx_b(ecx, FieldOperand(ebx, Map::kBitFieldOffset));
3298 __ test(ecx, Immediate(1 << Map::kIsUndetectable));
3299 __ j(not_zero, if_false);
3300 __ movzx_b(ecx, FieldOperand(ebx, Map::kInstanceTypeOffset));
3301 __ cmp(ecx, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE);
3302 __ j(below, if_false);
3303 __ cmp(ecx, LAST_NONCALLABLE_SPEC_OBJECT_TYPE);
3304 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3305 Split(below_equal, if_true, if_false, fall_through);
3307 context()->Plug(if_true, if_false);
3311 void FullCodeGenerator::EmitIsSpecObject(CallRuntime* expr) {
3312 ZoneList<Expression*>* args = expr->arguments();
3313 DCHECK(args->length() == 1);
3315 VisitForAccumulatorValue(args->at(0));
3317 Label materialize_true, materialize_false;
3318 Label* if_true = NULL;
3319 Label* if_false = NULL;
3320 Label* fall_through = NULL;
3321 context()->PrepareTest(&materialize_true, &materialize_false,
3322 &if_true, &if_false, &fall_through);
3324 __ JumpIfSmi(eax, if_false);
3325 __ CmpObjectType(eax, FIRST_SPEC_OBJECT_TYPE, ebx);
3326 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3327 Split(above_equal, if_true, if_false, fall_through);
3329 context()->Plug(if_true, if_false);
3333 void FullCodeGenerator::EmitIsUndetectableObject(CallRuntime* expr) {
3334 ZoneList<Expression*>* args = expr->arguments();
3335 DCHECK(args->length() == 1);
3337 VisitForAccumulatorValue(args->at(0));
3339 Label materialize_true, materialize_false;
3340 Label* if_true = NULL;
3341 Label* if_false = NULL;
3342 Label* fall_through = NULL;
3343 context()->PrepareTest(&materialize_true, &materialize_false,
3344 &if_true, &if_false, &fall_through);
3346 __ JumpIfSmi(eax, if_false);
3347 __ mov(ebx, FieldOperand(eax, HeapObject::kMapOffset));
3348 __ movzx_b(ebx, FieldOperand(ebx, Map::kBitFieldOffset));
3349 __ test(ebx, Immediate(1 << Map::kIsUndetectable));
3350 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3351 Split(not_zero, if_true, if_false, fall_through);
3353 context()->Plug(if_true, if_false);
3357 void FullCodeGenerator::EmitIsStringWrapperSafeForDefaultValueOf(
3358 CallRuntime* expr) {
3359 ZoneList<Expression*>* args = expr->arguments();
3360 DCHECK(args->length() == 1);
3362 VisitForAccumulatorValue(args->at(0));
3364 Label materialize_true, materialize_false, skip_lookup;
3365 Label* if_true = NULL;
3366 Label* if_false = NULL;
3367 Label* fall_through = NULL;
3368 context()->PrepareTest(&materialize_true, &materialize_false,
3369 &if_true, &if_false, &fall_through);
3371 __ AssertNotSmi(eax);
3373 // Check whether this map has already been checked to be safe for default
3375 __ mov(ebx, FieldOperand(eax, HeapObject::kMapOffset));
3376 __ test_b(FieldOperand(ebx, Map::kBitField2Offset),
3377 1 << Map::kStringWrapperSafeForDefaultValueOf);
3378 __ j(not_zero, &skip_lookup);
3380 // Check for fast case object. Return false for slow case objects.
3381 __ mov(ecx, FieldOperand(eax, JSObject::kPropertiesOffset));
3382 __ mov(ecx, FieldOperand(ecx, HeapObject::kMapOffset));
3383 __ cmp(ecx, isolate()->factory()->hash_table_map());
3384 __ j(equal, if_false);
3386 // Look for valueOf string in the descriptor array, and indicate false if
3387 // found. Since we omit an enumeration index check, if it is added via a
3388 // transition that shares its descriptor array, this is a false positive.
3389 Label entry, loop, done;
3391 // Skip loop if no descriptors are valid.
3392 __ NumberOfOwnDescriptors(ecx, ebx);
3396 __ LoadInstanceDescriptors(ebx, ebx);
3397 // ebx: descriptor array.
3398 // ecx: valid entries in the descriptor array.
3399 // Calculate the end of the descriptor array.
3400 STATIC_ASSERT(kSmiTag == 0);
3401 STATIC_ASSERT(kSmiTagSize == 1);
3402 STATIC_ASSERT(kPointerSize == 4);
3403 __ imul(ecx, ecx, DescriptorArray::kDescriptorSize);
3404 __ lea(ecx, Operand(ebx, ecx, times_4, DescriptorArray::kFirstOffset));
3405 // Calculate location of the first key name.
3406 __ add(ebx, Immediate(DescriptorArray::kFirstOffset));
3407 // Loop through all the keys in the descriptor array. If one of these is the
3408 // internalized string "valueOf" the result is false.
3411 __ mov(edx, FieldOperand(ebx, 0));
3412 __ cmp(edx, isolate()->factory()->value_of_string());
3413 __ j(equal, if_false);
3414 __ add(ebx, Immediate(DescriptorArray::kDescriptorSize * kPointerSize));
3417 __ j(not_equal, &loop);
3421 // Reload map as register ebx was used as temporary above.
3422 __ mov(ebx, FieldOperand(eax, HeapObject::kMapOffset));
3424 // Set the bit in the map to indicate that there is no local valueOf field.
3425 __ or_(FieldOperand(ebx, Map::kBitField2Offset),
3426 Immediate(1 << Map::kStringWrapperSafeForDefaultValueOf));
3428 __ bind(&skip_lookup);
3430 // If a valueOf property is not found on the object check that its
3431 // prototype is the un-modified String prototype. If not result is false.
3432 __ mov(ecx, FieldOperand(ebx, Map::kPrototypeOffset));
3433 __ JumpIfSmi(ecx, if_false);
3434 __ mov(ecx, FieldOperand(ecx, HeapObject::kMapOffset));
3435 __ mov(edx, Operand(esi, Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX)));
3437 FieldOperand(edx, GlobalObject::kNativeContextOffset));
3440 Context::STRING_FUNCTION_PROTOTYPE_MAP_INDEX));
3441 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3442 Split(equal, if_true, if_false, fall_through);
3444 context()->Plug(if_true, if_false);
3448 void FullCodeGenerator::EmitIsFunction(CallRuntime* expr) {
3449 ZoneList<Expression*>* args = expr->arguments();
3450 DCHECK(args->length() == 1);
3452 VisitForAccumulatorValue(args->at(0));
3454 Label materialize_true, materialize_false;
3455 Label* if_true = NULL;
3456 Label* if_false = NULL;
3457 Label* fall_through = NULL;
3458 context()->PrepareTest(&materialize_true, &materialize_false,
3459 &if_true, &if_false, &fall_through);
3461 __ JumpIfSmi(eax, if_false);
3462 __ CmpObjectType(eax, JS_FUNCTION_TYPE, ebx);
3463 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3464 Split(equal, if_true, if_false, fall_through);
3466 context()->Plug(if_true, if_false);
3470 void FullCodeGenerator::EmitIsMinusZero(CallRuntime* expr) {
3471 ZoneList<Expression*>* args = expr->arguments();
3472 DCHECK(args->length() == 1);
3474 VisitForAccumulatorValue(args->at(0));
3476 Label materialize_true, materialize_false;
3477 Label* if_true = NULL;
3478 Label* if_false = NULL;
3479 Label* fall_through = NULL;
3480 context()->PrepareTest(&materialize_true, &materialize_false,
3481 &if_true, &if_false, &fall_through);
3483 Handle<Map> map = masm()->isolate()->factory()->heap_number_map();
3484 __ CheckMap(eax, map, if_false, DO_SMI_CHECK);
3485 // Check if the exponent half is 0x80000000. Comparing against 1 and
3486 // checking for overflow is the shortest possible encoding.
3487 __ cmp(FieldOperand(eax, HeapNumber::kExponentOffset), Immediate(0x1));
3488 __ j(no_overflow, if_false);
3489 __ cmp(FieldOperand(eax, HeapNumber::kMantissaOffset), Immediate(0x0));
3490 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3491 Split(equal, if_true, if_false, fall_through);
3493 context()->Plug(if_true, if_false);
3498 void FullCodeGenerator::EmitIsArray(CallRuntime* expr) {
3499 ZoneList<Expression*>* args = expr->arguments();
3500 DCHECK(args->length() == 1);
3502 VisitForAccumulatorValue(args->at(0));
3504 Label materialize_true, materialize_false;
3505 Label* if_true = NULL;
3506 Label* if_false = NULL;
3507 Label* fall_through = NULL;
3508 context()->PrepareTest(&materialize_true, &materialize_false,
3509 &if_true, &if_false, &fall_through);
3511 __ JumpIfSmi(eax, if_false);
3512 __ CmpObjectType(eax, JS_ARRAY_TYPE, ebx);
3513 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3514 Split(equal, if_true, if_false, fall_through);
3516 context()->Plug(if_true, if_false);
3520 void FullCodeGenerator::EmitIsRegExp(CallRuntime* expr) {
3521 ZoneList<Expression*>* args = expr->arguments();
3522 DCHECK(args->length() == 1);
3524 VisitForAccumulatorValue(args->at(0));
3526 Label materialize_true, materialize_false;
3527 Label* if_true = NULL;
3528 Label* if_false = NULL;
3529 Label* fall_through = NULL;
3530 context()->PrepareTest(&materialize_true, &materialize_false,
3531 &if_true, &if_false, &fall_through);
3533 __ JumpIfSmi(eax, if_false);
3534 __ CmpObjectType(eax, JS_REGEXP_TYPE, ebx);
3535 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3536 Split(equal, if_true, if_false, fall_through);
3538 context()->Plug(if_true, if_false);
3542 void FullCodeGenerator::EmitIsJSProxy(CallRuntime* expr) {
3543 ZoneList<Expression*>* args = expr->arguments();
3544 DCHECK(args->length() == 1);
3546 VisitForAccumulatorValue(args->at(0));
3548 Label materialize_true, materialize_false;
3549 Label* if_true = NULL;
3550 Label* if_false = NULL;
3551 Label* fall_through = NULL;
3552 context()->PrepareTest(&materialize_true, &materialize_false, &if_true,
3553 &if_false, &fall_through);
3555 __ JumpIfSmi(eax, if_false);
3557 __ mov(map, FieldOperand(eax, HeapObject::kMapOffset));
3558 __ CmpInstanceType(map, FIRST_JS_PROXY_TYPE);
3559 __ j(less, if_false);
3560 __ CmpInstanceType(map, LAST_JS_PROXY_TYPE);
3561 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3562 Split(less_equal, if_true, if_false, fall_through);
3564 context()->Plug(if_true, if_false);
3568 void FullCodeGenerator::EmitIsConstructCall(CallRuntime* expr) {
3569 DCHECK(expr->arguments()->length() == 0);
3571 Label materialize_true, materialize_false;
3572 Label* if_true = NULL;
3573 Label* if_false = NULL;
3574 Label* fall_through = NULL;
3575 context()->PrepareTest(&materialize_true, &materialize_false,
3576 &if_true, &if_false, &fall_through);
3578 // Get the frame pointer for the calling frame.
3579 __ mov(eax, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3581 // Skip the arguments adaptor frame if it exists.
3582 Label check_frame_marker;
3583 __ cmp(Operand(eax, StandardFrameConstants::kContextOffset),
3584 Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
3585 __ j(not_equal, &check_frame_marker);
3586 __ mov(eax, Operand(eax, StandardFrameConstants::kCallerFPOffset));
3588 // Check the marker in the calling frame.
3589 __ bind(&check_frame_marker);
3590 __ cmp(Operand(eax, StandardFrameConstants::kMarkerOffset),
3591 Immediate(Smi::FromInt(StackFrame::CONSTRUCT)));
3592 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3593 Split(equal, if_true, if_false, fall_through);
3595 context()->Plug(if_true, if_false);
3599 void FullCodeGenerator::EmitObjectEquals(CallRuntime* expr) {
3600 ZoneList<Expression*>* args = expr->arguments();
3601 DCHECK(args->length() == 2);
3603 // Load the two objects into registers and perform the comparison.
3604 VisitForStackValue(args->at(0));
3605 VisitForAccumulatorValue(args->at(1));
3607 Label materialize_true, materialize_false;
3608 Label* if_true = NULL;
3609 Label* if_false = NULL;
3610 Label* fall_through = NULL;
3611 context()->PrepareTest(&materialize_true, &materialize_false,
3612 &if_true, &if_false, &fall_through);
3616 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3617 Split(equal, if_true, if_false, fall_through);
3619 context()->Plug(if_true, if_false);
3623 void FullCodeGenerator::EmitArguments(CallRuntime* expr) {
3624 ZoneList<Expression*>* args = expr->arguments();
3625 DCHECK(args->length() == 1);
3627 // ArgumentsAccessStub expects the key in edx and the formal
3628 // parameter count in eax.
3629 VisitForAccumulatorValue(args->at(0));
3631 __ Move(eax, Immediate(Smi::FromInt(info_->scope()->num_parameters())));
3632 ArgumentsAccessStub stub(isolate(), ArgumentsAccessStub::READ_ELEMENT);
3634 context()->Plug(eax);
3638 void FullCodeGenerator::EmitArgumentsLength(CallRuntime* expr) {
3639 DCHECK(expr->arguments()->length() == 0);
3642 // Get the number of formal parameters.
3643 __ Move(eax, Immediate(Smi::FromInt(info_->scope()->num_parameters())));
3645 // Check if the calling frame is an arguments adaptor frame.
3646 __ mov(ebx, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3647 __ cmp(Operand(ebx, StandardFrameConstants::kContextOffset),
3648 Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
3649 __ j(not_equal, &exit);
3651 // Arguments adaptor case: Read the arguments length from the
3653 __ mov(eax, Operand(ebx, ArgumentsAdaptorFrameConstants::kLengthOffset));
3657 context()->Plug(eax);
3661 void FullCodeGenerator::EmitClassOf(CallRuntime* expr) {
3662 ZoneList<Expression*>* args = expr->arguments();
3663 DCHECK(args->length() == 1);
3664 Label done, null, function, non_function_constructor;
3666 VisitForAccumulatorValue(args->at(0));
3668 // If the object is a smi, we return null.
3669 __ JumpIfSmi(eax, &null);
3671 // Check that the object is a JS object but take special care of JS
3672 // functions to make sure they have 'Function' as their class.
3673 // Assume that there are only two callable types, and one of them is at
3674 // either end of the type range for JS object types. Saves extra comparisons.
3675 STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
3676 __ CmpObjectType(eax, FIRST_SPEC_OBJECT_TYPE, eax);
3677 // Map is now in eax.
3679 STATIC_ASSERT(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE ==
3680 FIRST_SPEC_OBJECT_TYPE + 1);
3681 __ j(equal, &function);
3683 __ CmpInstanceType(eax, LAST_SPEC_OBJECT_TYPE);
3684 STATIC_ASSERT(LAST_NONCALLABLE_SPEC_OBJECT_TYPE ==
3685 LAST_SPEC_OBJECT_TYPE - 1);
3686 __ j(equal, &function);
3687 // Assume that there is no larger type.
3688 STATIC_ASSERT(LAST_NONCALLABLE_SPEC_OBJECT_TYPE == LAST_TYPE - 1);
3690 // Check if the constructor in the map is a JS function.
3691 __ GetMapConstructor(eax, eax, ebx);
3692 __ CmpInstanceType(ebx, JS_FUNCTION_TYPE);
3693 __ j(not_equal, &non_function_constructor);
3695 // eax now contains the constructor function. Grab the
3696 // instance class name from there.
3697 __ mov(eax, FieldOperand(eax, JSFunction::kSharedFunctionInfoOffset));
3698 __ mov(eax, FieldOperand(eax, SharedFunctionInfo::kInstanceClassNameOffset));
3701 // Functions have class 'Function'.
3703 __ mov(eax, isolate()->factory()->Function_string());
3706 // Objects with a non-function constructor have class 'Object'.
3707 __ bind(&non_function_constructor);
3708 __ mov(eax, isolate()->factory()->Object_string());
3711 // Non-JS objects have class null.
3713 __ mov(eax, isolate()->factory()->null_value());
3718 context()->Plug(eax);
3722 void FullCodeGenerator::EmitSubString(CallRuntime* expr) {
3723 // Load the arguments on the stack and call the stub.
3724 SubStringStub stub(isolate());
3725 ZoneList<Expression*>* args = expr->arguments();
3726 DCHECK(args->length() == 3);
3727 VisitForStackValue(args->at(0));
3728 VisitForStackValue(args->at(1));
3729 VisitForStackValue(args->at(2));
3731 context()->Plug(eax);
3735 void FullCodeGenerator::EmitRegExpExec(CallRuntime* expr) {
3736 // Load the arguments on the stack and call the stub.
3737 RegExpExecStub stub(isolate());
3738 ZoneList<Expression*>* args = expr->arguments();
3739 DCHECK(args->length() == 4);
3740 VisitForStackValue(args->at(0));
3741 VisitForStackValue(args->at(1));
3742 VisitForStackValue(args->at(2));
3743 VisitForStackValue(args->at(3));
3745 context()->Plug(eax);
3749 void FullCodeGenerator::EmitValueOf(CallRuntime* expr) {
3750 ZoneList<Expression*>* args = expr->arguments();
3751 DCHECK(args->length() == 1);
3753 VisitForAccumulatorValue(args->at(0)); // Load the object.
3756 // If the object is a smi return the object.
3757 __ JumpIfSmi(eax, &done, Label::kNear);
3758 // If the object is not a value type, return the object.
3759 __ CmpObjectType(eax, JS_VALUE_TYPE, ebx);
3760 __ j(not_equal, &done, Label::kNear);
3761 __ mov(eax, FieldOperand(eax, JSValue::kValueOffset));
3764 context()->Plug(eax);
3768 void FullCodeGenerator::EmitDateField(CallRuntime* expr) {
3769 ZoneList<Expression*>* args = expr->arguments();
3770 DCHECK(args->length() == 2);
3771 DCHECK_NOT_NULL(args->at(1)->AsLiteral());
3772 Smi* index = Smi::cast(*(args->at(1)->AsLiteral()->value()));
3774 VisitForAccumulatorValue(args->at(0)); // Load the object.
3776 Label runtime, done, not_date_object;
3777 Register object = eax;
3778 Register result = eax;
3779 Register scratch = ecx;
3781 __ JumpIfSmi(object, ¬_date_object);
3782 __ CmpObjectType(object, JS_DATE_TYPE, scratch);
3783 __ j(not_equal, ¬_date_object);
3785 if (index->value() == 0) {
3786 __ mov(result, FieldOperand(object, JSDate::kValueOffset));
3789 if (index->value() < JSDate::kFirstUncachedField) {
3790 ExternalReference stamp = ExternalReference::date_cache_stamp(isolate());
3791 __ mov(scratch, Operand::StaticVariable(stamp));
3792 __ cmp(scratch, FieldOperand(object, JSDate::kCacheStampOffset));
3793 __ j(not_equal, &runtime, Label::kNear);
3794 __ mov(result, FieldOperand(object, JSDate::kValueOffset +
3795 kPointerSize * index->value()));
3799 __ PrepareCallCFunction(2, scratch);
3800 __ mov(Operand(esp, 0), object);
3801 __ mov(Operand(esp, 1 * kPointerSize), Immediate(index));
3802 __ CallCFunction(ExternalReference::get_date_field_function(isolate()), 2);
3806 __ bind(¬_date_object);
3807 __ CallRuntime(Runtime::kThrowNotDateError, 0);
3809 context()->Plug(result);
3813 void FullCodeGenerator::EmitOneByteSeqStringSetChar(CallRuntime* expr) {
3814 ZoneList<Expression*>* args = expr->arguments();
3815 DCHECK_EQ(3, args->length());
3817 Register string = eax;
3818 Register index = ebx;
3819 Register value = ecx;
3821 VisitForStackValue(args->at(0)); // index
3822 VisitForStackValue(args->at(1)); // value
3823 VisitForAccumulatorValue(args->at(2)); // string
3828 if (FLAG_debug_code) {
3829 __ test(value, Immediate(kSmiTagMask));
3830 __ Check(zero, kNonSmiValue);
3831 __ test(index, Immediate(kSmiTagMask));
3832 __ Check(zero, kNonSmiValue);
3838 if (FLAG_debug_code) {
3839 static const uint32_t one_byte_seq_type = kSeqStringTag | kOneByteStringTag;
3840 __ EmitSeqStringSetCharCheck(string, index, value, one_byte_seq_type);
3843 __ mov_b(FieldOperand(string, index, times_1, SeqOneByteString::kHeaderSize),
3845 context()->Plug(string);
3849 void FullCodeGenerator::EmitTwoByteSeqStringSetChar(CallRuntime* expr) {
3850 ZoneList<Expression*>* args = expr->arguments();
3851 DCHECK_EQ(3, args->length());
3853 Register string = eax;
3854 Register index = ebx;
3855 Register value = ecx;
3857 VisitForStackValue(args->at(0)); // index
3858 VisitForStackValue(args->at(1)); // value
3859 VisitForAccumulatorValue(args->at(2)); // string
3863 if (FLAG_debug_code) {
3864 __ test(value, Immediate(kSmiTagMask));
3865 __ Check(zero, kNonSmiValue);
3866 __ test(index, Immediate(kSmiTagMask));
3867 __ Check(zero, kNonSmiValue);
3869 static const uint32_t two_byte_seq_type = kSeqStringTag | kTwoByteStringTag;
3870 __ EmitSeqStringSetCharCheck(string, index, value, two_byte_seq_type);
3875 // No need to untag a smi for two-byte addressing.
3876 __ mov_w(FieldOperand(string, index, times_1, SeqTwoByteString::kHeaderSize),
3878 context()->Plug(string);
3882 void FullCodeGenerator::EmitMathPow(CallRuntime* expr) {
3883 // Load the arguments on the stack and call the runtime function.
3884 ZoneList<Expression*>* args = expr->arguments();
3885 DCHECK(args->length() == 2);
3886 VisitForStackValue(args->at(0));
3887 VisitForStackValue(args->at(1));
3889 MathPowStub stub(isolate(), MathPowStub::ON_STACK);
3891 context()->Plug(eax);
3895 void FullCodeGenerator::EmitSetValueOf(CallRuntime* expr) {
3896 ZoneList<Expression*>* args = expr->arguments();
3897 DCHECK(args->length() == 2);
3899 VisitForStackValue(args->at(0)); // Load the object.
3900 VisitForAccumulatorValue(args->at(1)); // Load the value.
3901 __ pop(ebx); // eax = value. ebx = object.
3904 // If the object is a smi, return the value.
3905 __ JumpIfSmi(ebx, &done, Label::kNear);
3907 // If the object is not a value type, return the value.
3908 __ CmpObjectType(ebx, JS_VALUE_TYPE, ecx);
3909 __ j(not_equal, &done, Label::kNear);
3912 __ mov(FieldOperand(ebx, JSValue::kValueOffset), eax);
3914 // Update the write barrier. Save the value as it will be
3915 // overwritten by the write barrier code and is needed afterward.
3917 __ RecordWriteField(ebx, JSValue::kValueOffset, edx, ecx, kDontSaveFPRegs);
3920 context()->Plug(eax);
3924 void FullCodeGenerator::EmitNumberToString(CallRuntime* expr) {
3925 ZoneList<Expression*>* args = expr->arguments();
3926 DCHECK_EQ(args->length(), 1);
3928 // Load the argument into eax and call the stub.
3929 VisitForAccumulatorValue(args->at(0));
3931 NumberToStringStub stub(isolate());
3933 context()->Plug(eax);
3937 void FullCodeGenerator::EmitStringCharFromCode(CallRuntime* expr) {
3938 ZoneList<Expression*>* args = expr->arguments();
3939 DCHECK(args->length() == 1);
3941 VisitForAccumulatorValue(args->at(0));
3944 StringCharFromCodeGenerator generator(eax, ebx);
3945 generator.GenerateFast(masm_);
3948 NopRuntimeCallHelper call_helper;
3949 generator.GenerateSlow(masm_, call_helper);
3952 context()->Plug(ebx);
3956 void FullCodeGenerator::EmitStringCharCodeAt(CallRuntime* expr) {
3957 ZoneList<Expression*>* args = expr->arguments();
3958 DCHECK(args->length() == 2);
3960 VisitForStackValue(args->at(0));
3961 VisitForAccumulatorValue(args->at(1));
3963 Register object = ebx;
3964 Register index = eax;
3965 Register result = edx;
3969 Label need_conversion;
3970 Label index_out_of_range;
3972 StringCharCodeAtGenerator generator(object,
3977 &index_out_of_range,
3978 STRING_INDEX_IS_NUMBER);
3979 generator.GenerateFast(masm_);
3982 __ bind(&index_out_of_range);
3983 // When the index is out of range, the spec requires us to return
3985 __ Move(result, Immediate(isolate()->factory()->nan_value()));
3988 __ bind(&need_conversion);
3989 // Move the undefined value into the result register, which will
3990 // trigger conversion.
3991 __ Move(result, Immediate(isolate()->factory()->undefined_value()));
3994 NopRuntimeCallHelper call_helper;
3995 generator.GenerateSlow(masm_, NOT_PART_OF_IC_HANDLER, call_helper);
3998 context()->Plug(result);
4002 void FullCodeGenerator::EmitStringCharAt(CallRuntime* expr) {
4003 ZoneList<Expression*>* args = expr->arguments();
4004 DCHECK(args->length() == 2);
4006 VisitForStackValue(args->at(0));
4007 VisitForAccumulatorValue(args->at(1));
4009 Register object = ebx;
4010 Register index = eax;
4011 Register scratch = edx;
4012 Register result = eax;
4016 Label need_conversion;
4017 Label index_out_of_range;
4019 StringCharAtGenerator generator(object,
4025 &index_out_of_range,
4026 STRING_INDEX_IS_NUMBER);
4027 generator.GenerateFast(masm_);
4030 __ bind(&index_out_of_range);
4031 // When the index is out of range, the spec requires us to return
4032 // the empty string.
4033 __ Move(result, Immediate(isolate()->factory()->empty_string()));
4036 __ bind(&need_conversion);
4037 // Move smi zero into the result register, which will trigger
4039 __ Move(result, Immediate(Smi::FromInt(0)));
4042 NopRuntimeCallHelper call_helper;
4043 generator.GenerateSlow(masm_, NOT_PART_OF_IC_HANDLER, call_helper);
4046 context()->Plug(result);
4050 void FullCodeGenerator::EmitStringAdd(CallRuntime* expr) {
4051 ZoneList<Expression*>* args = expr->arguments();
4052 DCHECK_EQ(2, args->length());
4053 VisitForStackValue(args->at(0));
4054 VisitForAccumulatorValue(args->at(1));
4057 StringAddStub stub(isolate(), STRING_ADD_CHECK_BOTH, NOT_TENURED);
4059 context()->Plug(eax);
4063 void FullCodeGenerator::EmitStringCompare(CallRuntime* expr) {
4064 ZoneList<Expression*>* args = expr->arguments();
4065 DCHECK_EQ(2, args->length());
4067 VisitForStackValue(args->at(0));
4068 VisitForStackValue(args->at(1));
4070 StringCompareStub stub(isolate());
4072 context()->Plug(eax);
4076 void FullCodeGenerator::EmitCallFunction(CallRuntime* expr) {
4077 ZoneList<Expression*>* args = expr->arguments();
4078 DCHECK(args->length() >= 2);
4080 int arg_count = args->length() - 2; // 2 ~ receiver and function.
4081 for (int i = 0; i < arg_count + 1; ++i) {
4082 VisitForStackValue(args->at(i));
4084 VisitForAccumulatorValue(args->last()); // Function.
4086 Label runtime, done;
4087 // Check for non-function argument (including proxy).
4088 __ JumpIfSmi(eax, &runtime);
4089 __ CmpObjectType(eax, JS_FUNCTION_TYPE, ebx);
4090 __ j(not_equal, &runtime);
4092 // InvokeFunction requires the function in edi. Move it in there.
4093 __ mov(edi, result_register());
4094 ParameterCount count(arg_count);
4095 __ InvokeFunction(edi, count, CALL_FUNCTION, NullCallWrapper());
4096 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4101 __ CallRuntime(Runtime::kCall, args->length());
4104 context()->Plug(eax);
4108 void FullCodeGenerator::EmitDefaultConstructorCallSuper(CallRuntime* expr) {
4109 Variable* new_target_var = scope()->DeclarationScope()->new_target_var();
4110 GetVar(eax, new_target_var);
4113 EmitLoadSuperConstructor();
4114 __ push(result_register());
4116 // Check if the calling frame is an arguments adaptor frame.
4117 Label adaptor_frame, args_set_up, runtime;
4118 __ mov(edx, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
4119 __ mov(ecx, Operand(edx, StandardFrameConstants::kContextOffset));
4120 __ cmp(ecx, Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
4121 __ j(equal, &adaptor_frame);
4122 // default constructor has no arguments, so no adaptor frame means no args.
4123 __ mov(eax, Immediate(0));
4124 __ jmp(&args_set_up);
4126 // Copy arguments from adaptor frame.
4128 __ bind(&adaptor_frame);
4129 __ mov(ecx, Operand(edx, ArgumentsAdaptorFrameConstants::kLengthOffset));
4132 // Subtract 1 from arguments count, for new.target.
4133 __ sub(ecx, Immediate(1));
4135 __ lea(edx, Operand(edx, ecx, times_pointer_size,
4136 StandardFrameConstants::kCallerSPOffset));
4139 __ push(Operand(edx, -1 * kPointerSize));
4140 __ sub(edx, Immediate(kPointerSize));
4142 __ j(not_zero, &loop);
4145 __ bind(&args_set_up);
4147 __ mov(edi, Operand(esp, eax, times_pointer_size, 0));
4148 __ mov(ebx, Immediate(isolate()->factory()->undefined_value()));
4149 CallConstructStub stub(isolate(), SUPER_CONSTRUCTOR_CALL);
4150 __ call(stub.GetCode(), RelocInfo::CONSTRUCT_CALL);
4154 context()->Plug(eax);
4158 void FullCodeGenerator::EmitRegExpConstructResult(CallRuntime* expr) {
4159 // Load the arguments on the stack and call the stub.
4160 RegExpConstructResultStub stub(isolate());
4161 ZoneList<Expression*>* args = expr->arguments();
4162 DCHECK(args->length() == 3);
4163 VisitForStackValue(args->at(0));
4164 VisitForStackValue(args->at(1));
4165 VisitForAccumulatorValue(args->at(2));
4169 context()->Plug(eax);
4173 void FullCodeGenerator::EmitGetFromCache(CallRuntime* expr) {
4174 ZoneList<Expression*>* args = expr->arguments();
4175 DCHECK_EQ(2, args->length());
4177 DCHECK_NOT_NULL(args->at(0)->AsLiteral());
4178 int cache_id = Smi::cast(*(args->at(0)->AsLiteral()->value()))->value();
4180 Handle<FixedArray> jsfunction_result_caches(
4181 isolate()->native_context()->jsfunction_result_caches());
4182 if (jsfunction_result_caches->length() <= cache_id) {
4183 __ Abort(kAttemptToUseUndefinedCache);
4184 __ mov(eax, isolate()->factory()->undefined_value());
4185 context()->Plug(eax);
4189 VisitForAccumulatorValue(args->at(1));
4192 Register cache = ebx;
4194 __ mov(cache, ContextOperand(esi, Context::GLOBAL_OBJECT_INDEX));
4196 FieldOperand(cache, GlobalObject::kNativeContextOffset));
4197 __ mov(cache, ContextOperand(cache, Context::JSFUNCTION_RESULT_CACHES_INDEX));
4199 FieldOperand(cache, FixedArray::OffsetOfElementAt(cache_id)));
4201 Label done, not_found;
4202 STATIC_ASSERT(kSmiTag == 0 && kSmiTagSize == 1);
4203 __ mov(tmp, FieldOperand(cache, JSFunctionResultCache::kFingerOffset));
4204 // tmp now holds finger offset as a smi.
4205 __ cmp(key, FixedArrayElementOperand(cache, tmp));
4206 __ j(not_equal, ¬_found);
4208 __ mov(eax, FixedArrayElementOperand(cache, tmp, 1));
4211 __ bind(¬_found);
4212 // Call runtime to perform the lookup.
4215 __ CallRuntime(Runtime::kGetFromCacheRT, 2);
4218 context()->Plug(eax);
4222 void FullCodeGenerator::EmitHasCachedArrayIndex(CallRuntime* expr) {
4223 ZoneList<Expression*>* args = expr->arguments();
4224 DCHECK(args->length() == 1);
4226 VisitForAccumulatorValue(args->at(0));
4228 __ AssertString(eax);
4230 Label materialize_true, materialize_false;
4231 Label* if_true = NULL;
4232 Label* if_false = NULL;
4233 Label* fall_through = NULL;
4234 context()->PrepareTest(&materialize_true, &materialize_false,
4235 &if_true, &if_false, &fall_through);
4237 __ test(FieldOperand(eax, String::kHashFieldOffset),
4238 Immediate(String::kContainsCachedArrayIndexMask));
4239 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
4240 Split(zero, if_true, if_false, fall_through);
4242 context()->Plug(if_true, if_false);
4246 void FullCodeGenerator::EmitGetCachedArrayIndex(CallRuntime* expr) {
4247 ZoneList<Expression*>* args = expr->arguments();
4248 DCHECK(args->length() == 1);
4249 VisitForAccumulatorValue(args->at(0));
4251 __ AssertString(eax);
4253 __ mov(eax, FieldOperand(eax, String::kHashFieldOffset));
4254 __ IndexFromHash(eax, eax);
4256 context()->Plug(eax);
4260 void FullCodeGenerator::EmitFastOneByteArrayJoin(CallRuntime* expr) {
4261 Label bailout, done, one_char_separator, long_separator,
4262 non_trivial_array, not_size_one_array, loop,
4263 loop_1, loop_1_condition, loop_2, loop_2_entry, loop_3, loop_3_entry;
4265 ZoneList<Expression*>* args = expr->arguments();
4266 DCHECK(args->length() == 2);
4267 // We will leave the separator on the stack until the end of the function.
4268 VisitForStackValue(args->at(1));
4269 // Load this to eax (= array)
4270 VisitForAccumulatorValue(args->at(0));
4271 // All aliases of the same register have disjoint lifetimes.
4272 Register array = eax;
4273 Register elements = no_reg; // Will be eax.
4275 Register index = edx;
4277 Register string_length = ecx;
4279 Register string = esi;
4281 Register scratch = ebx;
4283 Register array_length = edi;
4284 Register result_pos = no_reg; // Will be edi.
4286 // Separator operand is already pushed.
4287 Operand separator_operand = Operand(esp, 2 * kPointerSize);
4288 Operand result_operand = Operand(esp, 1 * kPointerSize);
4289 Operand array_length_operand = Operand(esp, 0);
4290 __ sub(esp, Immediate(2 * kPointerSize));
4292 // Check that the array is a JSArray
4293 __ JumpIfSmi(array, &bailout);
4294 __ CmpObjectType(array, JS_ARRAY_TYPE, scratch);
4295 __ j(not_equal, &bailout);
4297 // Check that the array has fast elements.
4298 __ CheckFastElements(scratch, &bailout);
4300 // If the array has length zero, return the empty string.
4301 __ mov(array_length, FieldOperand(array, JSArray::kLengthOffset));
4302 __ SmiUntag(array_length);
4303 __ j(not_zero, &non_trivial_array);
4304 __ mov(result_operand, isolate()->factory()->empty_string());
4307 // Save the array length.
4308 __ bind(&non_trivial_array);
4309 __ mov(array_length_operand, array_length);
4311 // Save the FixedArray containing array's elements.
4312 // End of array's live range.
4314 __ mov(elements, FieldOperand(array, JSArray::kElementsOffset));
4318 // Check that all array elements are sequential one-byte strings, and
4319 // accumulate the sum of their lengths, as a smi-encoded value.
4320 __ Move(index, Immediate(0));
4321 __ Move(string_length, Immediate(0));
4322 // Loop condition: while (index < length).
4323 // Live loop registers: index, array_length, string,
4324 // scratch, string_length, elements.
4325 if (generate_debug_code_) {
4326 __ cmp(index, array_length);
4327 __ Assert(less, kNoEmptyArraysHereInEmitFastOneByteArrayJoin);
4330 __ mov(string, FieldOperand(elements,
4333 FixedArray::kHeaderSize));
4334 __ JumpIfSmi(string, &bailout);
4335 __ mov(scratch, FieldOperand(string, HeapObject::kMapOffset));
4336 __ movzx_b(scratch, FieldOperand(scratch, Map::kInstanceTypeOffset));
4337 __ and_(scratch, Immediate(
4338 kIsNotStringMask | kStringEncodingMask | kStringRepresentationMask));
4339 __ cmp(scratch, kStringTag | kOneByteStringTag | kSeqStringTag);
4340 __ j(not_equal, &bailout);
4341 __ add(string_length,
4342 FieldOperand(string, SeqOneByteString::kLengthOffset));
4343 __ j(overflow, &bailout);
4344 __ add(index, Immediate(1));
4345 __ cmp(index, array_length);
4348 // If array_length is 1, return elements[0], a string.
4349 __ cmp(array_length, 1);
4350 __ j(not_equal, ¬_size_one_array);
4351 __ mov(scratch, FieldOperand(elements, FixedArray::kHeaderSize));
4352 __ mov(result_operand, scratch);
4355 __ bind(¬_size_one_array);
4357 // End of array_length live range.
4358 result_pos = array_length;
4359 array_length = no_reg;
4362 // string_length: Sum of string lengths, as a smi.
4363 // elements: FixedArray of strings.
4365 // Check that the separator is a flat one-byte string.
4366 __ mov(string, separator_operand);
4367 __ JumpIfSmi(string, &bailout);
4368 __ mov(scratch, FieldOperand(string, HeapObject::kMapOffset));
4369 __ movzx_b(scratch, FieldOperand(scratch, Map::kInstanceTypeOffset));
4370 __ and_(scratch, Immediate(
4371 kIsNotStringMask | kStringEncodingMask | kStringRepresentationMask));
4372 __ cmp(scratch, kStringTag | kOneByteStringTag | kSeqStringTag);
4373 __ j(not_equal, &bailout);
4375 // Add (separator length times array_length) - separator length
4376 // to string_length.
4377 __ mov(scratch, separator_operand);
4378 __ mov(scratch, FieldOperand(scratch, SeqOneByteString::kLengthOffset));
4379 __ sub(string_length, scratch); // May be negative, temporarily.
4380 __ imul(scratch, array_length_operand);
4381 __ j(overflow, &bailout);
4382 __ add(string_length, scratch);
4383 __ j(overflow, &bailout);
4385 __ shr(string_length, 1);
4386 // Live registers and stack values:
4389 __ AllocateOneByteString(result_pos, string_length, scratch, index, string,
4391 __ mov(result_operand, result_pos);
4392 __ lea(result_pos, FieldOperand(result_pos, SeqOneByteString::kHeaderSize));
4395 __ mov(string, separator_operand);
4396 __ cmp(FieldOperand(string, SeqOneByteString::kLengthOffset),
4397 Immediate(Smi::FromInt(1)));
4398 __ j(equal, &one_char_separator);
4399 __ j(greater, &long_separator);
4402 // Empty separator case
4403 __ mov(index, Immediate(0));
4404 __ jmp(&loop_1_condition);
4405 // Loop condition: while (index < length).
4407 // Each iteration of the loop concatenates one string to the result.
4408 // Live values in registers:
4409 // index: which element of the elements array we are adding to the result.
4410 // result_pos: the position to which we are currently copying characters.
4411 // elements: the FixedArray of strings we are joining.
4413 // Get string = array[index].
4414 __ mov(string, FieldOperand(elements, index,
4416 FixedArray::kHeaderSize));
4417 __ mov(string_length,
4418 FieldOperand(string, String::kLengthOffset));
4419 __ shr(string_length, 1);
4421 FieldOperand(string, SeqOneByteString::kHeaderSize));
4422 __ CopyBytes(string, result_pos, string_length, scratch);
4423 __ add(index, Immediate(1));
4424 __ bind(&loop_1_condition);
4425 __ cmp(index, array_length_operand);
4426 __ j(less, &loop_1); // End while (index < length).
4431 // One-character separator case
4432 __ bind(&one_char_separator);
4433 // Replace separator with its one-byte character value.
4434 __ mov_b(scratch, FieldOperand(string, SeqOneByteString::kHeaderSize));
4435 __ mov_b(separator_operand, scratch);
4437 __ Move(index, Immediate(0));
4438 // Jump into the loop after the code that copies the separator, so the first
4439 // element is not preceded by a separator
4440 __ jmp(&loop_2_entry);
4441 // Loop condition: while (index < length).
4443 // Each iteration of the loop concatenates one string to the result.
4444 // Live values in registers:
4445 // index: which element of the elements array we are adding to the result.
4446 // result_pos: the position to which we are currently copying characters.
4448 // Copy the separator character to the result.
4449 __ mov_b(scratch, separator_operand);
4450 __ mov_b(Operand(result_pos, 0), scratch);
4453 __ bind(&loop_2_entry);
4454 // Get string = array[index].
4455 __ mov(string, FieldOperand(elements, index,
4457 FixedArray::kHeaderSize));
4458 __ mov(string_length,
4459 FieldOperand(string, String::kLengthOffset));
4460 __ shr(string_length, 1);
4462 FieldOperand(string, SeqOneByteString::kHeaderSize));
4463 __ CopyBytes(string, result_pos, string_length, scratch);
4464 __ add(index, Immediate(1));
4466 __ cmp(index, array_length_operand);
4467 __ j(less, &loop_2); // End while (index < length).
4471 // Long separator case (separator is more than one character).
4472 __ bind(&long_separator);
4474 __ Move(index, Immediate(0));
4475 // Jump into the loop after the code that copies the separator, so the first
4476 // element is not preceded by a separator
4477 __ jmp(&loop_3_entry);
4478 // Loop condition: while (index < length).
4480 // Each iteration of the loop concatenates one string to the result.
4481 // Live values in registers:
4482 // index: which element of the elements array we are adding to the result.
4483 // result_pos: the position to which we are currently copying characters.
4485 // Copy the separator to the result.
4486 __ mov(string, separator_operand);
4487 __ mov(string_length,
4488 FieldOperand(string, String::kLengthOffset));
4489 __ shr(string_length, 1);
4491 FieldOperand(string, SeqOneByteString::kHeaderSize));
4492 __ CopyBytes(string, result_pos, string_length, scratch);
4494 __ bind(&loop_3_entry);
4495 // Get string = array[index].
4496 __ mov(string, FieldOperand(elements, index,
4498 FixedArray::kHeaderSize));
4499 __ mov(string_length,
4500 FieldOperand(string, String::kLengthOffset));
4501 __ shr(string_length, 1);
4503 FieldOperand(string, SeqOneByteString::kHeaderSize));
4504 __ CopyBytes(string, result_pos, string_length, scratch);
4505 __ add(index, Immediate(1));
4507 __ cmp(index, array_length_operand);
4508 __ j(less, &loop_3); // End while (index < length).
4513 __ mov(result_operand, isolate()->factory()->undefined_value());
4515 __ mov(eax, result_operand);
4516 // Drop temp values from the stack, and restore context register.
4517 __ add(esp, Immediate(3 * kPointerSize));
4519 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4520 context()->Plug(eax);
4524 void FullCodeGenerator::EmitDebugIsActive(CallRuntime* expr) {
4525 DCHECK(expr->arguments()->length() == 0);
4526 ExternalReference debug_is_active =
4527 ExternalReference::debug_is_active_address(isolate());
4528 __ movzx_b(eax, Operand::StaticVariable(debug_is_active));
4530 context()->Plug(eax);
4534 void FullCodeGenerator::VisitCallRuntime(CallRuntime* expr) {
4535 ZoneList<Expression*>* args = expr->arguments();
4536 int arg_count = args->length();
4538 if (expr->is_jsruntime()) {
4539 Comment cmnt(masm_, "[ CallRuntime");
4540 // Push the builtins object as receiver.
4541 __ mov(eax, GlobalObjectOperand());
4542 __ push(FieldOperand(eax, GlobalObject::kBuiltinsOffset));
4544 // Load the function from the receiver.
4545 __ mov(LoadDescriptor::ReceiverRegister(), Operand(esp, 0));
4546 __ mov(LoadDescriptor::NameRegister(), Immediate(expr->name()));
4547 if (FLAG_vector_ics) {
4548 __ mov(VectorLoadICDescriptor::SlotRegister(),
4549 Immediate(SmiFromSlot(expr->CallRuntimeFeedbackSlot())));
4550 CallLoadIC(NOT_CONTEXTUAL);
4552 CallLoadIC(NOT_CONTEXTUAL, expr->CallRuntimeFeedbackId());
4555 // Push the target function under the receiver.
4556 __ push(Operand(esp, 0));
4557 __ mov(Operand(esp, kPointerSize), eax);
4559 // Push the arguments ("left-to-right").
4560 for (int i = 0; i < arg_count; i++) {
4561 VisitForStackValue(args->at(i));
4564 // Record source position of the IC call.
4565 SetSourcePosition(expr->position());
4566 CallFunctionStub stub(isolate(), arg_count, NO_CALL_FUNCTION_FLAGS);
4567 __ mov(edi, Operand(esp, (arg_count + 1) * kPointerSize));
4570 // Restore context register.
4571 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4572 context()->DropAndPlug(1, eax);
4575 const Runtime::Function* function = expr->function();
4576 switch (function->function_id) {
4577 #define CALL_INTRINSIC_GENERATOR(Name) \
4578 case Runtime::kInline##Name: { \
4579 Comment cmnt(masm_, "[ Inline" #Name); \
4580 return Emit##Name(expr); \
4582 FOR_EACH_FULL_CODE_INTRINSIC(CALL_INTRINSIC_GENERATOR)
4583 #undef CALL_INTRINSIC_GENERATOR
4585 Comment cmnt(masm_, "[ CallRuntime for unhandled intrinsic");
4586 // Push the arguments ("left-to-right").
4587 for (int i = 0; i < arg_count; i++) {
4588 VisitForStackValue(args->at(i));
4591 // Call the C runtime function.
4592 __ CallRuntime(expr->function(), arg_count);
4593 context()->Plug(eax);
4600 void FullCodeGenerator::VisitUnaryOperation(UnaryOperation* expr) {
4601 switch (expr->op()) {
4602 case Token::DELETE: {
4603 Comment cmnt(masm_, "[ UnaryOperation (DELETE)");
4604 Property* property = expr->expression()->AsProperty();
4605 VariableProxy* proxy = expr->expression()->AsVariableProxy();
4607 if (property != NULL) {
4608 VisitForStackValue(property->obj());
4609 VisitForStackValue(property->key());
4610 __ push(Immediate(Smi::FromInt(language_mode())));
4611 __ InvokeBuiltin(Builtins::DELETE, CALL_FUNCTION);
4612 context()->Plug(eax);
4613 } else if (proxy != NULL) {
4614 Variable* var = proxy->var();
4615 // Delete of an unqualified identifier is disallowed in strict mode
4616 // but "delete this" is allowed.
4617 DCHECK(is_sloppy(language_mode()) || var->is_this());
4618 if (var->IsUnallocated()) {
4619 __ push(GlobalObjectOperand());
4620 __ push(Immediate(var->name()));
4621 __ push(Immediate(Smi::FromInt(SLOPPY)));
4622 __ InvokeBuiltin(Builtins::DELETE, CALL_FUNCTION);
4623 context()->Plug(eax);
4624 } else if (var->IsStackAllocated() || var->IsContextSlot()) {
4625 // Result of deleting non-global variables is false. 'this' is
4626 // not really a variable, though we implement it as one. The
4627 // subexpression does not have side effects.
4628 context()->Plug(var->is_this());
4630 // Non-global variable. Call the runtime to try to delete from the
4631 // context where the variable was introduced.
4632 __ push(context_register());
4633 __ push(Immediate(var->name()));
4634 __ CallRuntime(Runtime::kDeleteLookupSlot, 2);
4635 context()->Plug(eax);
4638 // Result of deleting non-property, non-variable reference is true.
4639 // The subexpression may have side effects.
4640 VisitForEffect(expr->expression());
4641 context()->Plug(true);
4647 Comment cmnt(masm_, "[ UnaryOperation (VOID)");
4648 VisitForEffect(expr->expression());
4649 context()->Plug(isolate()->factory()->undefined_value());
4654 Comment cmnt(masm_, "[ UnaryOperation (NOT)");
4655 if (context()->IsEffect()) {
4656 // Unary NOT has no side effects so it's only necessary to visit the
4657 // subexpression. Match the optimizing compiler by not branching.
4658 VisitForEffect(expr->expression());
4659 } else if (context()->IsTest()) {
4660 const TestContext* test = TestContext::cast(context());
4661 // The labels are swapped for the recursive call.
4662 VisitForControl(expr->expression(),
4663 test->false_label(),
4665 test->fall_through());
4666 context()->Plug(test->true_label(), test->false_label());
4668 // We handle value contexts explicitly rather than simply visiting
4669 // for control and plugging the control flow into the context,
4670 // because we need to prepare a pair of extra administrative AST ids
4671 // for the optimizing compiler.
4672 DCHECK(context()->IsAccumulatorValue() || context()->IsStackValue());
4673 Label materialize_true, materialize_false, done;
4674 VisitForControl(expr->expression(),
4678 __ bind(&materialize_true);
4679 PrepareForBailoutForId(expr->MaterializeTrueId(), NO_REGISTERS);
4680 if (context()->IsAccumulatorValue()) {
4681 __ mov(eax, isolate()->factory()->true_value());
4683 __ Push(isolate()->factory()->true_value());
4685 __ jmp(&done, Label::kNear);
4686 __ bind(&materialize_false);
4687 PrepareForBailoutForId(expr->MaterializeFalseId(), NO_REGISTERS);
4688 if (context()->IsAccumulatorValue()) {
4689 __ mov(eax, isolate()->factory()->false_value());
4691 __ Push(isolate()->factory()->false_value());
4698 case Token::TYPEOF: {
4699 Comment cmnt(masm_, "[ UnaryOperation (TYPEOF)");
4700 { StackValueContext context(this);
4701 VisitForTypeofValue(expr->expression());
4703 __ CallRuntime(Runtime::kTypeof, 1);
4704 context()->Plug(eax);
4714 void FullCodeGenerator::VisitCountOperation(CountOperation* expr) {
4715 DCHECK(expr->expression()->IsValidReferenceExpression());
4717 Comment cmnt(masm_, "[ CountOperation");
4718 SetSourcePosition(expr->position());
4720 Property* prop = expr->expression()->AsProperty();
4721 LhsKind assign_type = GetAssignType(prop);
4723 // Evaluate expression and get value.
4724 if (assign_type == VARIABLE) {
4725 DCHECK(expr->expression()->AsVariableProxy()->var() != NULL);
4726 AccumulatorValueContext context(this);
4727 EmitVariableLoad(expr->expression()->AsVariableProxy());
4729 // Reserve space for result of postfix operation.
4730 if (expr->is_postfix() && !context()->IsEffect()) {
4731 __ push(Immediate(Smi::FromInt(0)));
4733 switch (assign_type) {
4734 case NAMED_PROPERTY: {
4735 // Put the object both on the stack and in the register.
4736 VisitForStackValue(prop->obj());
4737 __ mov(LoadDescriptor::ReceiverRegister(), Operand(esp, 0));
4738 EmitNamedPropertyLoad(prop);
4742 case NAMED_SUPER_PROPERTY: {
4743 VisitForStackValue(prop->obj()->AsSuperReference()->this_var());
4744 EmitLoadHomeObject(prop->obj()->AsSuperReference());
4745 __ push(result_register());
4746 __ push(MemOperand(esp, kPointerSize));
4747 __ push(result_register());
4748 EmitNamedSuperPropertyLoad(prop);
4752 case KEYED_SUPER_PROPERTY: {
4753 VisitForStackValue(prop->obj()->AsSuperReference()->this_var());
4754 EmitLoadHomeObject(prop->obj()->AsSuperReference());
4755 __ push(result_register());
4756 VisitForAccumulatorValue(prop->key());
4757 __ push(result_register());
4758 __ push(MemOperand(esp, 2 * kPointerSize));
4759 __ push(MemOperand(esp, 2 * kPointerSize));
4760 __ push(result_register());
4761 EmitKeyedSuperPropertyLoad(prop);
4765 case KEYED_PROPERTY: {
4766 VisitForStackValue(prop->obj());
4767 VisitForStackValue(prop->key());
4768 __ mov(LoadDescriptor::ReceiverRegister(),
4769 Operand(esp, kPointerSize)); // Object.
4770 __ mov(LoadDescriptor::NameRegister(), Operand(esp, 0)); // Key.
4771 EmitKeyedPropertyLoad(prop);
4780 // We need a second deoptimization point after loading the value
4781 // in case evaluating the property load my have a side effect.
4782 if (assign_type == VARIABLE) {
4783 PrepareForBailout(expr->expression(), TOS_REG);
4785 PrepareForBailoutForId(prop->LoadId(), TOS_REG);
4788 // Inline smi case if we are in a loop.
4789 Label done, stub_call;
4790 JumpPatchSite patch_site(masm_);
4791 if (ShouldInlineSmiCase(expr->op())) {
4793 patch_site.EmitJumpIfNotSmi(eax, &slow, Label::kNear);
4795 // Save result for postfix expressions.
4796 if (expr->is_postfix()) {
4797 if (!context()->IsEffect()) {
4798 // Save the result on the stack. If we have a named or keyed property
4799 // we store the result under the receiver that is currently on top
4801 switch (assign_type) {
4805 case NAMED_PROPERTY:
4806 __ mov(Operand(esp, kPointerSize), eax);
4808 case NAMED_SUPER_PROPERTY:
4809 __ mov(Operand(esp, 2 * kPointerSize), eax);
4811 case KEYED_PROPERTY:
4812 __ mov(Operand(esp, 2 * kPointerSize), eax);
4814 case KEYED_SUPER_PROPERTY:
4815 __ mov(Operand(esp, 3 * kPointerSize), eax);
4821 if (expr->op() == Token::INC) {
4822 __ add(eax, Immediate(Smi::FromInt(1)));
4824 __ sub(eax, Immediate(Smi::FromInt(1)));
4826 __ j(no_overflow, &done, Label::kNear);
4827 // Call stub. Undo operation first.
4828 if (expr->op() == Token::INC) {
4829 __ sub(eax, Immediate(Smi::FromInt(1)));
4831 __ add(eax, Immediate(Smi::FromInt(1)));
4833 __ jmp(&stub_call, Label::kNear);
4836 ToNumberStub convert_stub(isolate());
4837 __ CallStub(&convert_stub);
4838 PrepareForBailoutForId(expr->ToNumberId(), TOS_REG);
4840 // Save result for postfix expressions.
4841 if (expr->is_postfix()) {
4842 if (!context()->IsEffect()) {
4843 // Save the result on the stack. If we have a named or keyed property
4844 // we store the result under the receiver that is currently on top
4846 switch (assign_type) {
4850 case NAMED_PROPERTY:
4851 __ mov(Operand(esp, kPointerSize), eax);
4853 case NAMED_SUPER_PROPERTY:
4854 __ mov(Operand(esp, 2 * kPointerSize), eax);
4856 case KEYED_PROPERTY:
4857 __ mov(Operand(esp, 2 * kPointerSize), eax);
4859 case KEYED_SUPER_PROPERTY:
4860 __ mov(Operand(esp, 3 * kPointerSize), eax);
4866 // Record position before stub call.
4867 SetSourcePosition(expr->position());
4869 // Call stub for +1/-1.
4870 __ bind(&stub_call);
4872 __ mov(eax, Immediate(Smi::FromInt(1)));
4874 CodeFactory::BinaryOpIC(isolate(), expr->binary_op()).code();
4875 CallIC(code, expr->CountBinOpFeedbackId());
4876 patch_site.EmitPatchInfo();
4879 // Store the value returned in eax.
4880 switch (assign_type) {
4882 if (expr->is_postfix()) {
4883 // Perform the assignment as if via '='.
4884 { EffectContext context(this);
4885 EmitVariableAssignment(expr->expression()->AsVariableProxy()->var(),
4887 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
4890 // For all contexts except EffectContext We have the result on
4891 // top of the stack.
4892 if (!context()->IsEffect()) {
4893 context()->PlugTOS();
4896 // Perform the assignment as if via '='.
4897 EmitVariableAssignment(expr->expression()->AsVariableProxy()->var(),
4899 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
4900 context()->Plug(eax);
4903 case NAMED_PROPERTY: {
4904 __ mov(StoreDescriptor::NameRegister(),
4905 prop->key()->AsLiteral()->value());
4906 __ pop(StoreDescriptor::ReceiverRegister());
4907 CallStoreIC(expr->CountStoreFeedbackId());
4908 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
4909 if (expr->is_postfix()) {
4910 if (!context()->IsEffect()) {
4911 context()->PlugTOS();
4914 context()->Plug(eax);
4918 case NAMED_SUPER_PROPERTY: {
4919 EmitNamedSuperPropertyStore(prop);
4920 if (expr->is_postfix()) {
4921 if (!context()->IsEffect()) {
4922 context()->PlugTOS();
4925 context()->Plug(eax);
4929 case KEYED_SUPER_PROPERTY: {
4930 EmitKeyedSuperPropertyStore(prop);
4931 if (expr->is_postfix()) {
4932 if (!context()->IsEffect()) {
4933 context()->PlugTOS();
4936 context()->Plug(eax);
4940 case KEYED_PROPERTY: {
4941 __ pop(StoreDescriptor::NameRegister());
4942 __ pop(StoreDescriptor::ReceiverRegister());
4944 CodeFactory::KeyedStoreIC(isolate(), language_mode()).code();
4945 CallIC(ic, expr->CountStoreFeedbackId());
4946 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
4947 if (expr->is_postfix()) {
4948 // Result is on the stack
4949 if (!context()->IsEffect()) {
4950 context()->PlugTOS();
4953 context()->Plug(eax);
4961 void FullCodeGenerator::VisitForTypeofValue(Expression* expr) {
4962 VariableProxy* proxy = expr->AsVariableProxy();
4963 DCHECK(!context()->IsEffect());
4964 DCHECK(!context()->IsTest());
4966 if (proxy != NULL && proxy->var()->IsUnallocated()) {
4967 Comment cmnt(masm_, "[ Global variable");
4968 __ mov(LoadDescriptor::ReceiverRegister(), GlobalObjectOperand());
4969 __ mov(LoadDescriptor::NameRegister(), Immediate(proxy->name()));
4970 if (FLAG_vector_ics) {
4971 __ mov(VectorLoadICDescriptor::SlotRegister(),
4972 Immediate(SmiFromSlot(proxy->VariableFeedbackSlot())));
4974 // Use a regular load, not a contextual load, to avoid a reference
4976 CallLoadIC(NOT_CONTEXTUAL);
4977 PrepareForBailout(expr, TOS_REG);
4978 context()->Plug(eax);
4979 } else if (proxy != NULL && proxy->var()->IsLookupSlot()) {
4980 Comment cmnt(masm_, "[ Lookup slot");
4983 // Generate code for loading from variables potentially shadowed
4984 // by eval-introduced variables.
4985 EmitDynamicLookupFastCase(proxy, INSIDE_TYPEOF, &slow, &done);
4989 __ push(Immediate(proxy->name()));
4990 __ CallRuntime(Runtime::kLoadLookupSlotNoReferenceError, 2);
4991 PrepareForBailout(expr, TOS_REG);
4994 context()->Plug(eax);
4996 // This expression cannot throw a reference error at the top level.
4997 VisitInDuplicateContext(expr);
5002 void FullCodeGenerator::EmitLiteralCompareTypeof(Expression* expr,
5003 Expression* sub_expr,
5004 Handle<String> check) {
5005 Label materialize_true, materialize_false;
5006 Label* if_true = NULL;
5007 Label* if_false = NULL;
5008 Label* fall_through = NULL;
5009 context()->PrepareTest(&materialize_true, &materialize_false,
5010 &if_true, &if_false, &fall_through);
5012 { AccumulatorValueContext context(this);
5013 VisitForTypeofValue(sub_expr);
5015 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
5017 Factory* factory = isolate()->factory();
5018 if (String::Equals(check, factory->number_string())) {
5019 __ JumpIfSmi(eax, if_true);
5020 __ cmp(FieldOperand(eax, HeapObject::kMapOffset),
5021 isolate()->factory()->heap_number_map());
5022 Split(equal, if_true, if_false, fall_through);
5023 } else if (String::Equals(check, factory->string_string())) {
5024 __ JumpIfSmi(eax, if_false);
5025 __ CmpObjectType(eax, FIRST_NONSTRING_TYPE, edx);
5026 __ j(above_equal, if_false);
5027 // Check for undetectable objects => false.
5028 __ test_b(FieldOperand(edx, Map::kBitFieldOffset),
5029 1 << Map::kIsUndetectable);
5030 Split(zero, if_true, if_false, fall_through);
5031 } else if (String::Equals(check, factory->symbol_string())) {
5032 __ JumpIfSmi(eax, if_false);
5033 __ CmpObjectType(eax, SYMBOL_TYPE, edx);
5034 Split(equal, if_true, if_false, fall_through);
5035 } else if (String::Equals(check, factory->boolean_string())) {
5036 __ cmp(eax, isolate()->factory()->true_value());
5037 __ j(equal, if_true);
5038 __ cmp(eax, isolate()->factory()->false_value());
5039 Split(equal, if_true, if_false, fall_through);
5040 } else if (String::Equals(check, factory->undefined_string())) {
5041 __ cmp(eax, isolate()->factory()->undefined_value());
5042 __ j(equal, if_true);
5043 __ JumpIfSmi(eax, if_false);
5044 // Check for undetectable objects => true.
5045 __ mov(edx, FieldOperand(eax, HeapObject::kMapOffset));
5046 __ movzx_b(ecx, FieldOperand(edx, Map::kBitFieldOffset));
5047 __ test(ecx, Immediate(1 << Map::kIsUndetectable));
5048 Split(not_zero, if_true, if_false, fall_through);
5049 } else if (String::Equals(check, factory->function_string())) {
5050 __ JumpIfSmi(eax, if_false);
5051 STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
5052 __ CmpObjectType(eax, JS_FUNCTION_TYPE, edx);
5053 __ j(equal, if_true);
5054 __ CmpInstanceType(edx, JS_FUNCTION_PROXY_TYPE);
5055 Split(equal, if_true, if_false, fall_through);
5056 } else if (String::Equals(check, factory->object_string())) {
5057 __ JumpIfSmi(eax, if_false);
5058 __ cmp(eax, isolate()->factory()->null_value());
5059 __ j(equal, if_true);
5060 __ CmpObjectType(eax, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE, edx);
5061 __ j(below, if_false);
5062 __ CmpInstanceType(edx, LAST_NONCALLABLE_SPEC_OBJECT_TYPE);
5063 __ j(above, if_false);
5064 // Check for undetectable objects => false.
5065 __ test_b(FieldOperand(edx, Map::kBitFieldOffset),
5066 1 << Map::kIsUndetectable);
5067 Split(zero, if_true, if_false, fall_through);
5069 if (if_false != fall_through) __ jmp(if_false);
5071 context()->Plug(if_true, if_false);
5075 void FullCodeGenerator::VisitCompareOperation(CompareOperation* expr) {
5076 Comment cmnt(masm_, "[ CompareOperation");
5077 SetSourcePosition(expr->position());
5079 // First we try a fast inlined version of the compare when one of
5080 // the operands is a literal.
5081 if (TryLiteralCompare(expr)) return;
5083 // Always perform the comparison for its control flow. Pack the result
5084 // into the expression's context after the comparison is performed.
5085 Label materialize_true, materialize_false;
5086 Label* if_true = NULL;
5087 Label* if_false = NULL;
5088 Label* fall_through = NULL;
5089 context()->PrepareTest(&materialize_true, &materialize_false,
5090 &if_true, &if_false, &fall_through);
5092 Token::Value op = expr->op();
5093 VisitForStackValue(expr->left());
5096 VisitForStackValue(expr->right());
5097 __ InvokeBuiltin(Builtins::IN, CALL_FUNCTION);
5098 PrepareForBailoutBeforeSplit(expr, false, NULL, NULL);
5099 __ cmp(eax, isolate()->factory()->true_value());
5100 Split(equal, if_true, if_false, fall_through);
5103 case Token::INSTANCEOF: {
5104 VisitForStackValue(expr->right());
5105 InstanceofStub stub(isolate(), InstanceofStub::kNoFlags);
5107 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
5109 // The stub returns 0 for true.
5110 Split(zero, if_true, if_false, fall_through);
5115 VisitForAccumulatorValue(expr->right());
5116 Condition cc = CompareIC::ComputeCondition(op);
5119 bool inline_smi_code = ShouldInlineSmiCase(op);
5120 JumpPatchSite patch_site(masm_);
5121 if (inline_smi_code) {
5125 patch_site.EmitJumpIfNotSmi(ecx, &slow_case, Label::kNear);
5127 Split(cc, if_true, if_false, NULL);
5128 __ bind(&slow_case);
5131 // Record position and call the compare IC.
5132 SetSourcePosition(expr->position());
5133 Handle<Code> ic = CodeFactory::CompareIC(isolate(), op).code();
5134 CallIC(ic, expr->CompareOperationFeedbackId());
5135 patch_site.EmitPatchInfo();
5137 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
5139 Split(cc, if_true, if_false, fall_through);
5143 // Convert the result of the comparison into one expected for this
5144 // expression's context.
5145 context()->Plug(if_true, if_false);
5149 void FullCodeGenerator::EmitLiteralCompareNil(CompareOperation* expr,
5150 Expression* sub_expr,
5152 Label materialize_true, materialize_false;
5153 Label* if_true = NULL;
5154 Label* if_false = NULL;
5155 Label* fall_through = NULL;
5156 context()->PrepareTest(&materialize_true, &materialize_false,
5157 &if_true, &if_false, &fall_through);
5159 VisitForAccumulatorValue(sub_expr);
5160 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
5162 Handle<Object> nil_value = nil == kNullValue
5163 ? isolate()->factory()->null_value()
5164 : isolate()->factory()->undefined_value();
5165 if (expr->op() == Token::EQ_STRICT) {
5166 __ cmp(eax, nil_value);
5167 Split(equal, if_true, if_false, fall_through);
5169 Handle<Code> ic = CompareNilICStub::GetUninitialized(isolate(), nil);
5170 CallIC(ic, expr->CompareOperationFeedbackId());
5172 Split(not_zero, if_true, if_false, fall_through);
5174 context()->Plug(if_true, if_false);
5178 void FullCodeGenerator::VisitThisFunction(ThisFunction* expr) {
5179 __ mov(eax, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
5180 context()->Plug(eax);
5184 Register FullCodeGenerator::result_register() {
5189 Register FullCodeGenerator::context_register() {
5194 void FullCodeGenerator::StoreToFrameField(int frame_offset, Register value) {
5195 DCHECK_EQ(POINTER_SIZE_ALIGN(frame_offset), frame_offset);
5196 __ mov(Operand(ebp, frame_offset), value);
5200 void FullCodeGenerator::LoadContextField(Register dst, int context_index) {
5201 __ mov(dst, ContextOperand(esi, context_index));
5205 void FullCodeGenerator::PushFunctionArgumentForContextAllocation() {
5206 Scope* declaration_scope = scope()->DeclarationScope();
5207 if (declaration_scope->is_script_scope() ||
5208 declaration_scope->is_module_scope()) {
5209 // Contexts nested in the native context have a canonical empty function
5210 // as their closure, not the anonymous closure containing the global
5211 // code. Pass a smi sentinel and let the runtime look up the empty
5213 __ push(Immediate(Smi::FromInt(0)));
5214 } else if (declaration_scope->is_eval_scope()) {
5215 // Contexts nested inside eval code have the same closure as the context
5216 // calling eval, not the anonymous closure containing the eval code.
5217 // Fetch it from the context.
5218 __ push(ContextOperand(esi, Context::CLOSURE_INDEX));
5220 DCHECK(declaration_scope->is_function_scope());
5221 __ push(Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
5226 // ----------------------------------------------------------------------------
5227 // Non-local control flow support.
5229 void FullCodeGenerator::EnterFinallyBlock() {
5230 // Cook return address on top of stack (smi encoded Code* delta)
5231 DCHECK(!result_register().is(edx));
5233 __ sub(edx, Immediate(masm_->CodeObject()));
5234 STATIC_ASSERT(kSmiTagSize + kSmiShiftSize == 1);
5235 STATIC_ASSERT(kSmiTag == 0);
5239 // Store result register while executing finally block.
5240 __ push(result_register());
5242 // Store pending message while executing finally block.
5243 ExternalReference pending_message_obj =
5244 ExternalReference::address_of_pending_message_obj(isolate());
5245 __ mov(edx, Operand::StaticVariable(pending_message_obj));
5250 void FullCodeGenerator::ExitFinallyBlock() {
5251 DCHECK(!result_register().is(edx));
5252 // Restore pending message from stack.
5254 ExternalReference pending_message_obj =
5255 ExternalReference::address_of_pending_message_obj(isolate());
5256 __ mov(Operand::StaticVariable(pending_message_obj), edx);
5258 // Restore result register from stack.
5259 __ pop(result_register());
5261 // Uncook return address.
5264 __ add(edx, Immediate(masm_->CodeObject()));
5272 static const byte kJnsInstruction = 0x79;
5273 static const byte kJnsOffset = 0x11;
5274 static const byte kNopByteOne = 0x66;
5275 static const byte kNopByteTwo = 0x90;
5277 static const byte kCallInstruction = 0xe8;
5281 void BackEdgeTable::PatchAt(Code* unoptimized_code,
5283 BackEdgeState target_state,
5284 Code* replacement_code) {
5285 Address call_target_address = pc - kIntSize;
5286 Address jns_instr_address = call_target_address - 3;
5287 Address jns_offset_address = call_target_address - 2;
5289 switch (target_state) {
5291 // sub <profiling_counter>, <delta> ;; Not changed
5293 // call <interrupt stub>
5295 *jns_instr_address = kJnsInstruction;
5296 *jns_offset_address = kJnsOffset;
5298 case ON_STACK_REPLACEMENT:
5299 case OSR_AFTER_STACK_CHECK:
5300 // sub <profiling_counter>, <delta> ;; Not changed
5303 // call <on-stack replacment>
5305 *jns_instr_address = kNopByteOne;
5306 *jns_offset_address = kNopByteTwo;
5310 Assembler::set_target_address_at(call_target_address,
5312 replacement_code->entry());
5313 unoptimized_code->GetHeap()->incremental_marking()->RecordCodeTargetPatch(
5314 unoptimized_code, call_target_address, replacement_code);
5318 BackEdgeTable::BackEdgeState BackEdgeTable::GetBackEdgeState(
5320 Code* unoptimized_code,
5322 Address call_target_address = pc - kIntSize;
5323 Address jns_instr_address = call_target_address - 3;
5324 DCHECK_EQ(kCallInstruction, *(call_target_address - 1));
5326 if (*jns_instr_address == kJnsInstruction) {
5327 DCHECK_EQ(kJnsOffset, *(call_target_address - 2));
5328 DCHECK_EQ(isolate->builtins()->InterruptCheck()->entry(),
5329 Assembler::target_address_at(call_target_address,
5334 DCHECK_EQ(kNopByteOne, *jns_instr_address);
5335 DCHECK_EQ(kNopByteTwo, *(call_target_address - 2));
5337 if (Assembler::target_address_at(call_target_address, unoptimized_code) ==
5338 isolate->builtins()->OnStackReplacement()->entry()) {
5339 return ON_STACK_REPLACEMENT;
5342 DCHECK_EQ(isolate->builtins()->OsrAfterStackCheck()->entry(),
5343 Assembler::target_address_at(call_target_address,
5345 return OSR_AFTER_STACK_CHECK;
5349 } } // namespace v8::internal
5351 #endif // V8_TARGET_ARCH_IA32