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.
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/parser.h"
17 #include "src/scopes.h"
22 #define __ ACCESS_MASM(masm_)
25 class JumpPatchSite BASE_EMBEDDED {
27 explicit JumpPatchSite(MacroAssembler* masm) : masm_(masm) {
29 info_emitted_ = false;
34 DCHECK(patch_site_.is_bound() == info_emitted_);
37 void EmitJumpIfNotSmi(Register reg,
39 Label::Distance distance = Label::kFar) {
40 __ test(reg, Immediate(kSmiTagMask));
41 EmitJump(not_carry, target, distance); // Always taken before patched.
44 void EmitJumpIfSmi(Register reg,
46 Label::Distance distance = Label::kFar) {
47 __ test(reg, Immediate(kSmiTagMask));
48 EmitJump(carry, target, distance); // Never taken before patched.
51 void EmitPatchInfo() {
52 if (patch_site_.is_bound()) {
53 int delta_to_patch_site = masm_->SizeOfCodeGeneratedSince(&patch_site_);
54 DCHECK(is_uint8(delta_to_patch_site));
55 __ test(eax, Immediate(delta_to_patch_site));
60 __ nop(); // Signals no inlined code.
65 // jc will be patched with jz, jnc will become jnz.
66 void EmitJump(Condition cc, Label* target, Label::Distance distance) {
67 DCHECK(!patch_site_.is_bound() && !info_emitted_);
68 DCHECK(cc == carry || cc == not_carry);
69 __ bind(&patch_site_);
70 __ j(cc, target, distance);
73 MacroAssembler* masm_;
81 // Generate code for a JS function. On entry to the function the receiver
82 // and arguments have been pushed on the stack left to right, with the
83 // return address on top of them. The actual argument count matches the
84 // formal parameter count expected by the function.
86 // The live registers are:
87 // o edi: the JS function object being called (i.e. ourselves)
89 // o ebp: our caller's frame pointer
90 // o esp: stack pointer (pointing to return address)
92 // The function builds a JS frame. Please see JavaScriptFrameConstants in
93 // frames-x87.h for its layout.
94 void FullCodeGenerator::Generate() {
95 CompilationInfo* info = info_;
97 Handle<HandlerTable>::cast(isolate()->factory()->NewFixedArray(
98 HandlerTable::LengthForRange(function()->handler_count()), TENURED));
100 profiling_counter_ = isolate()->factory()->NewCell(
101 Handle<Smi>(Smi::FromInt(FLAG_interrupt_budget), isolate()));
102 SetFunctionPosition(function());
103 Comment cmnt(masm_, "[ function compiled by full code generator");
105 ProfileEntryHookStub::MaybeCallEntryHook(masm_);
108 if (strlen(FLAG_stop_at) > 0 &&
109 info->function()->name()->IsUtf8EqualTo(CStrVector(FLAG_stop_at))) {
114 // Sloppy mode functions and builtins need to replace the receiver with the
115 // global proxy when called as functions (without an explicit receiver
117 if (is_sloppy(info->language_mode()) && !info->is_native() &&
118 info->MayUseThis()) {
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 if (info->scope()->num_heap_slots() > 0) {
188 Comment cmnt(masm_, "[ Allocate context");
189 bool need_write_barrier = true;
190 int slots = info->scope()->num_heap_slots() - Context::MIN_CONTEXT_SLOTS;
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 (slots <= FastNewContextStub::kMaximumSlots) {
197 FastNewContextStub stub(isolate(), 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 int first_parameter = info->scope()->has_this_declaration() ? -1 : 0;
214 for (int i = first_parameter; i < num_parameters; i++) {
215 Variable* var = (i == -1) ? scope()->receiver() : scope()->parameter(i);
216 if (var->IsContextSlot()) {
217 int parameter_offset = StandardFrameConstants::kCallerSPOffset +
218 (num_parameters - 1 - i) * kPointerSize;
219 // Load parameter from stack.
220 __ mov(eax, Operand(ebp, parameter_offset));
221 // Store it in the context.
222 int context_offset = Context::SlotOffset(var->index());
223 __ mov(Operand(esi, context_offset), eax);
224 // Update the write barrier. This clobbers eax and ebx.
225 if (need_write_barrier) {
226 __ RecordWriteContextSlot(esi, context_offset, eax, ebx,
228 } else if (FLAG_debug_code) {
230 __ JumpIfInNewSpace(esi, eax, &done, Label::kNear);
231 __ Abort(kExpectedNewSpaceObject);
238 ArgumentsAccessStub::HasNewTarget has_new_target =
239 IsSubclassConstructor(info->function()->kind())
240 ? ArgumentsAccessStub::HAS_NEW_TARGET
241 : ArgumentsAccessStub::NO_NEW_TARGET;
243 // Possibly allocate RestParameters
245 Variable* rest_param = scope()->rest_parameter(&rest_index);
247 Comment cmnt(masm_, "[ Allocate rest parameter array");
249 int num_parameters = info->scope()->num_parameters();
250 int offset = num_parameters * kPointerSize;
251 if (has_new_target == ArgumentsAccessStub::HAS_NEW_TARGET) {
257 Operand(ebp, StandardFrameConstants::kCallerSPOffset + offset));
259 __ push(Immediate(Smi::FromInt(num_parameters)));
260 __ push(Immediate(Smi::FromInt(rest_index)));
261 __ push(Immediate(Smi::FromInt(language_mode())));
263 RestParamAccessStub stub(isolate());
266 SetVar(rest_param, eax, ebx, edx);
269 Variable* arguments = scope()->arguments();
270 if (arguments != NULL) {
271 // Function uses arguments object.
272 Comment cmnt(masm_, "[ Allocate arguments object");
273 if (function_in_register) {
276 __ push(Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
278 // Receiver is just before the parameters on the caller's stack.
279 int num_parameters = info->scope()->num_parameters();
280 int offset = num_parameters * kPointerSize;
282 Operand(ebp, StandardFrameConstants::kCallerSPOffset + offset));
284 __ push(Immediate(Smi::FromInt(num_parameters)));
285 // Arguments to ArgumentsAccessStub:
286 // function, receiver address, parameter count.
287 // The stub will rewrite receiver and parameter count if the previous
288 // stack frame was an arguments adapter frame.
289 ArgumentsAccessStub::Type type;
290 if (is_strict(language_mode()) || !is_simple_parameter_list()) {
291 type = ArgumentsAccessStub::NEW_STRICT;
292 } else if (function()->has_duplicate_parameters()) {
293 type = ArgumentsAccessStub::NEW_SLOPPY_SLOW;
295 type = ArgumentsAccessStub::NEW_SLOPPY_FAST;
298 ArgumentsAccessStub stub(isolate(), type, has_new_target);
301 SetVar(arguments, eax, ebx, edx);
305 __ CallRuntime(Runtime::kTraceEnter, 0);
308 // Visit the declarations and body unless there is an illegal
310 if (scope()->HasIllegalRedeclaration()) {
311 Comment cmnt(masm_, "[ Declarations");
312 scope()->VisitIllegalRedeclaration(this);
315 PrepareForBailoutForId(BailoutId::FunctionEntry(), NO_REGISTERS);
316 { Comment cmnt(masm_, "[ Declarations");
317 // For named function expressions, declare the function name as a
319 if (scope()->is_function_scope() && scope()->function() != NULL) {
320 VariableDeclaration* function = scope()->function();
321 DCHECK(function->proxy()->var()->mode() == CONST ||
322 function->proxy()->var()->mode() == CONST_LEGACY);
323 DCHECK(function->proxy()->var()->location() != Variable::UNALLOCATED);
324 VisitVariableDeclaration(function);
326 VisitDeclarations(scope()->declarations());
329 { Comment cmnt(masm_, "[ Stack check");
330 PrepareForBailoutForId(BailoutId::Declarations(), NO_REGISTERS);
332 ExternalReference stack_limit
333 = ExternalReference::address_of_stack_limit(isolate());
334 __ cmp(esp, Operand::StaticVariable(stack_limit));
335 __ j(above_equal, &ok, Label::kNear);
336 __ call(isolate()->builtins()->StackCheck(), RelocInfo::CODE_TARGET);
340 { Comment cmnt(masm_, "[ Body");
341 DCHECK(loop_depth() == 0);
342 VisitStatements(function()->body());
343 DCHECK(loop_depth() == 0);
347 // Always emit a 'return undefined' in case control fell off the end of
349 { Comment cmnt(masm_, "[ return <undefined>;");
350 __ mov(eax, isolate()->factory()->undefined_value());
351 EmitReturnSequence();
356 void FullCodeGenerator::ClearAccumulator() {
357 __ Move(eax, Immediate(Smi::FromInt(0)));
361 void FullCodeGenerator::EmitProfilingCounterDecrement(int delta) {
362 __ mov(ebx, Immediate(profiling_counter_));
363 __ sub(FieldOperand(ebx, Cell::kValueOffset),
364 Immediate(Smi::FromInt(delta)));
368 void FullCodeGenerator::EmitProfilingCounterReset() {
369 int reset_value = FLAG_interrupt_budget;
370 __ mov(ebx, Immediate(profiling_counter_));
371 __ mov(FieldOperand(ebx, Cell::kValueOffset),
372 Immediate(Smi::FromInt(reset_value)));
376 void FullCodeGenerator::EmitBackEdgeBookkeeping(IterationStatement* stmt,
377 Label* back_edge_target) {
378 Comment cmnt(masm_, "[ Back edge bookkeeping");
381 DCHECK(back_edge_target->is_bound());
382 int distance = masm_->SizeOfCodeGeneratedSince(back_edge_target);
383 int weight = Min(kMaxBackEdgeWeight,
384 Max(1, distance / kCodeSizeMultiplier));
385 EmitProfilingCounterDecrement(weight);
386 __ j(positive, &ok, Label::kNear);
387 __ call(isolate()->builtins()->InterruptCheck(), RelocInfo::CODE_TARGET);
389 // Record a mapping of this PC offset to the OSR id. This is used to find
390 // the AST id from the unoptimized code in order to use it as a key into
391 // the deoptimization input data found in the optimized code.
392 RecordBackEdge(stmt->OsrEntryId());
394 EmitProfilingCounterReset();
397 PrepareForBailoutForId(stmt->EntryId(), NO_REGISTERS);
398 // Record a mapping of the OSR id to this PC. This is used if the OSR
399 // entry becomes the target of a bailout. We don't expect it to be, but
400 // we want it to work if it is.
401 PrepareForBailoutForId(stmt->OsrEntryId(), NO_REGISTERS);
405 void FullCodeGenerator::EmitReturnSequence() {
406 Comment cmnt(masm_, "[ Return sequence");
407 if (return_label_.is_bound()) {
408 __ jmp(&return_label_);
410 // Common return label
411 __ bind(&return_label_);
414 __ CallRuntime(Runtime::kTraceExit, 1);
416 // Pretend that the exit is a backwards jump to the entry.
418 if (info_->ShouldSelfOptimize()) {
419 weight = FLAG_interrupt_budget / FLAG_self_opt_count;
421 int distance = masm_->pc_offset();
422 weight = Min(kMaxBackEdgeWeight,
423 Max(1, distance / kCodeSizeMultiplier));
425 EmitProfilingCounterDecrement(weight);
427 __ j(positive, &ok, Label::kNear);
429 __ call(isolate()->builtins()->InterruptCheck(),
430 RelocInfo::CODE_TARGET);
432 EmitProfilingCounterReset();
435 // Add a label for checking the size of the code used for returning.
436 Label check_exit_codesize;
437 masm_->bind(&check_exit_codesize);
439 SetSourcePosition(function()->end_position() - 1);
441 // Do not use the leave instruction here because it is too short to
442 // patch with the code required by the debugger.
444 int no_frame_start = masm_->pc_offset();
447 int arg_count = info_->scope()->num_parameters() + 1;
448 if (IsSubclassConstructor(info_->function()->kind())) {
451 int arguments_bytes = arg_count * kPointerSize;
452 __ Ret(arguments_bytes, ecx);
453 // Check that the size of the code used for returning is large enough
454 // for the debugger's requirements.
455 DCHECK(Assembler::kJSReturnSequenceLength <=
456 masm_->SizeOfCodeGeneratedSince(&check_exit_codesize));
457 info_->AddNoFrameRange(no_frame_start, masm_->pc_offset());
462 void FullCodeGenerator::EffectContext::Plug(Variable* var) const {
463 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
467 void FullCodeGenerator::AccumulatorValueContext::Plug(Variable* var) const {
468 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
469 codegen()->GetVar(result_register(), var);
473 void FullCodeGenerator::StackValueContext::Plug(Variable* var) const {
474 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
475 MemOperand operand = codegen()->VarOperand(var, result_register());
476 // Memory operands can be pushed directly.
481 void FullCodeGenerator::TestContext::Plug(Variable* var) const {
482 // For simplicity we always test the accumulator register.
483 codegen()->GetVar(result_register(), var);
484 codegen()->PrepareForBailoutBeforeSplit(condition(), false, NULL, NULL);
485 codegen()->DoTest(this);
489 void FullCodeGenerator::EffectContext::Plug(Heap::RootListIndex index) const {
490 UNREACHABLE(); // Not used on X87.
494 void FullCodeGenerator::AccumulatorValueContext::Plug(
495 Heap::RootListIndex index) const {
496 UNREACHABLE(); // Not used on X87.
500 void FullCodeGenerator::StackValueContext::Plug(
501 Heap::RootListIndex index) const {
502 UNREACHABLE(); // Not used on X87.
506 void FullCodeGenerator::TestContext::Plug(Heap::RootListIndex index) const {
507 UNREACHABLE(); // Not used on X87.
511 void FullCodeGenerator::EffectContext::Plug(Handle<Object> lit) const {
515 void FullCodeGenerator::AccumulatorValueContext::Plug(
516 Handle<Object> lit) const {
518 __ SafeMove(result_register(), Immediate(lit));
520 __ Move(result_register(), Immediate(lit));
525 void FullCodeGenerator::StackValueContext::Plug(Handle<Object> lit) const {
527 __ SafePush(Immediate(lit));
529 __ push(Immediate(lit));
534 void FullCodeGenerator::TestContext::Plug(Handle<Object> lit) const {
535 codegen()->PrepareForBailoutBeforeSplit(condition(),
539 DCHECK(!lit->IsUndetectableObject()); // There are no undetectable literals.
540 if (lit->IsUndefined() || lit->IsNull() || lit->IsFalse()) {
541 if (false_label_ != fall_through_) __ jmp(false_label_);
542 } else if (lit->IsTrue() || lit->IsJSObject()) {
543 if (true_label_ != fall_through_) __ jmp(true_label_);
544 } else if (lit->IsString()) {
545 if (String::cast(*lit)->length() == 0) {
546 if (false_label_ != fall_through_) __ jmp(false_label_);
548 if (true_label_ != fall_through_) __ jmp(true_label_);
550 } else if (lit->IsSmi()) {
551 if (Smi::cast(*lit)->value() == 0) {
552 if (false_label_ != fall_through_) __ jmp(false_label_);
554 if (true_label_ != fall_through_) __ jmp(true_label_);
557 // For simplicity we always test the accumulator register.
558 __ mov(result_register(), lit);
559 codegen()->DoTest(this);
564 void FullCodeGenerator::EffectContext::DropAndPlug(int count,
565 Register reg) const {
571 void FullCodeGenerator::AccumulatorValueContext::DropAndPlug(
573 Register reg) const {
576 __ Move(result_register(), reg);
580 void FullCodeGenerator::StackValueContext::DropAndPlug(int count,
581 Register reg) const {
583 if (count > 1) __ Drop(count - 1);
584 __ mov(Operand(esp, 0), reg);
588 void FullCodeGenerator::TestContext::DropAndPlug(int count,
589 Register reg) const {
591 // For simplicity we always test the accumulator register.
593 __ Move(result_register(), reg);
594 codegen()->PrepareForBailoutBeforeSplit(condition(), false, NULL, NULL);
595 codegen()->DoTest(this);
599 void FullCodeGenerator::EffectContext::Plug(Label* materialize_true,
600 Label* materialize_false) const {
601 DCHECK(materialize_true == materialize_false);
602 __ bind(materialize_true);
606 void FullCodeGenerator::AccumulatorValueContext::Plug(
607 Label* materialize_true,
608 Label* materialize_false) const {
610 __ bind(materialize_true);
611 __ mov(result_register(), isolate()->factory()->true_value());
612 __ jmp(&done, Label::kNear);
613 __ bind(materialize_false);
614 __ mov(result_register(), isolate()->factory()->false_value());
619 void FullCodeGenerator::StackValueContext::Plug(
620 Label* materialize_true,
621 Label* materialize_false) const {
623 __ bind(materialize_true);
624 __ push(Immediate(isolate()->factory()->true_value()));
625 __ jmp(&done, Label::kNear);
626 __ bind(materialize_false);
627 __ push(Immediate(isolate()->factory()->false_value()));
632 void FullCodeGenerator::TestContext::Plug(Label* materialize_true,
633 Label* materialize_false) const {
634 DCHECK(materialize_true == true_label_);
635 DCHECK(materialize_false == false_label_);
639 void FullCodeGenerator::EffectContext::Plug(bool flag) const {
643 void FullCodeGenerator::AccumulatorValueContext::Plug(bool flag) const {
644 Handle<Object> value = flag
645 ? isolate()->factory()->true_value()
646 : isolate()->factory()->false_value();
647 __ mov(result_register(), value);
651 void FullCodeGenerator::StackValueContext::Plug(bool flag) const {
652 Handle<Object> value = flag
653 ? isolate()->factory()->true_value()
654 : isolate()->factory()->false_value();
655 __ push(Immediate(value));
659 void FullCodeGenerator::TestContext::Plug(bool flag) const {
660 codegen()->PrepareForBailoutBeforeSplit(condition(),
665 if (true_label_ != fall_through_) __ jmp(true_label_);
667 if (false_label_ != fall_through_) __ jmp(false_label_);
672 void FullCodeGenerator::DoTest(Expression* condition,
675 Label* fall_through) {
676 Handle<Code> ic = ToBooleanStub::GetUninitialized(isolate());
677 CallIC(ic, condition->test_id());
678 __ test(result_register(), result_register());
679 // The stub returns nonzero for true.
680 Split(not_zero, if_true, if_false, fall_through);
684 void FullCodeGenerator::Split(Condition cc,
687 Label* fall_through) {
688 if (if_false == fall_through) {
690 } else if (if_true == fall_through) {
691 __ j(NegateCondition(cc), if_false);
699 MemOperand FullCodeGenerator::StackOperand(Variable* var) {
700 DCHECK(var->IsStackAllocated());
701 // Offset is negative because higher indexes are at lower addresses.
702 int offset = -var->index() * kPointerSize;
703 // Adjust by a (parameter or local) base offset.
704 if (var->IsParameter()) {
705 offset += (info_->scope()->num_parameters() + 1) * kPointerSize;
707 offset += JavaScriptFrameConstants::kLocal0Offset;
709 return Operand(ebp, offset);
713 MemOperand FullCodeGenerator::VarOperand(Variable* var, Register scratch) {
714 DCHECK(var->IsContextSlot() || var->IsStackAllocated());
715 if (var->IsContextSlot()) {
716 int context_chain_length = scope()->ContextChainLength(var->scope());
717 __ LoadContext(scratch, context_chain_length);
718 return ContextOperand(scratch, var->index());
720 return StackOperand(var);
725 void FullCodeGenerator::GetVar(Register dest, Variable* var) {
726 DCHECK(var->IsContextSlot() || var->IsStackAllocated());
727 MemOperand location = VarOperand(var, dest);
728 __ mov(dest, location);
732 void FullCodeGenerator::SetVar(Variable* var,
736 DCHECK(var->IsContextSlot() || var->IsStackAllocated());
737 DCHECK(!scratch0.is(src));
738 DCHECK(!scratch0.is(scratch1));
739 DCHECK(!scratch1.is(src));
740 MemOperand location = VarOperand(var, scratch0);
741 __ mov(location, src);
743 // Emit the write barrier code if the location is in the heap.
744 if (var->IsContextSlot()) {
745 int offset = Context::SlotOffset(var->index());
746 DCHECK(!scratch0.is(esi) && !src.is(esi) && !scratch1.is(esi));
747 __ RecordWriteContextSlot(scratch0, offset, src, scratch1, kDontSaveFPRegs);
752 void FullCodeGenerator::PrepareForBailoutBeforeSplit(Expression* expr,
753 bool should_normalize,
756 // Only prepare for bailouts before splits if we're in a test
757 // context. Otherwise, we let the Visit function deal with the
758 // preparation to avoid preparing with the same AST id twice.
759 if (!context()->IsTest() || !info_->IsOptimizable()) return;
762 if (should_normalize) __ jmp(&skip, Label::kNear);
763 PrepareForBailout(expr, TOS_REG);
764 if (should_normalize) {
765 __ cmp(eax, isolate()->factory()->true_value());
766 Split(equal, if_true, if_false, NULL);
772 void FullCodeGenerator::EmitDebugCheckDeclarationContext(Variable* variable) {
773 // The variable in the declaration always resides in the current context.
774 DCHECK_EQ(0, scope()->ContextChainLength(variable->scope()));
775 if (generate_debug_code_) {
776 // Check that we're not inside a with or catch context.
777 __ mov(ebx, FieldOperand(esi, HeapObject::kMapOffset));
778 __ cmp(ebx, isolate()->factory()->with_context_map());
779 __ Check(not_equal, kDeclarationInWithContext);
780 __ cmp(ebx, isolate()->factory()->catch_context_map());
781 __ Check(not_equal, kDeclarationInCatchContext);
786 void FullCodeGenerator::VisitVariableDeclaration(
787 VariableDeclaration* declaration) {
788 // If it was not possible to allocate the variable at compile time, we
789 // need to "declare" it at runtime to make sure it actually exists in the
791 VariableProxy* proxy = declaration->proxy();
792 VariableMode mode = declaration->mode();
793 Variable* variable = proxy->var();
794 bool hole_init = mode == LET || mode == CONST || mode == CONST_LEGACY;
795 switch (variable->location()) {
796 case Variable::UNALLOCATED:
797 globals_->Add(variable->name(), zone());
798 globals_->Add(variable->binding_needs_init()
799 ? isolate()->factory()->the_hole_value()
800 : isolate()->factory()->undefined_value(), zone());
803 case Variable::PARAMETER:
804 case Variable::LOCAL:
806 Comment cmnt(masm_, "[ VariableDeclaration");
807 __ mov(StackOperand(variable),
808 Immediate(isolate()->factory()->the_hole_value()));
812 case Variable::CONTEXT:
814 Comment cmnt(masm_, "[ VariableDeclaration");
815 EmitDebugCheckDeclarationContext(variable);
816 __ mov(ContextOperand(esi, variable->index()),
817 Immediate(isolate()->factory()->the_hole_value()));
818 // No write barrier since the hole value is in old space.
819 PrepareForBailoutForId(proxy->id(), NO_REGISTERS);
823 case Variable::LOOKUP: {
824 Comment cmnt(masm_, "[ VariableDeclaration");
826 __ push(Immediate(variable->name()));
827 // VariableDeclaration nodes are always introduced in one of four modes.
828 DCHECK(IsDeclaredVariableMode(mode));
829 PropertyAttributes attr =
830 IsImmutableVariableMode(mode) ? READ_ONLY : NONE;
831 __ push(Immediate(Smi::FromInt(attr)));
832 // Push initial value, if any.
833 // Note: For variables we must not push an initial value (such as
834 // 'undefined') because we may have a (legal) redeclaration and we
835 // must not destroy the current value.
837 __ push(Immediate(isolate()->factory()->the_hole_value()));
839 __ push(Immediate(Smi::FromInt(0))); // Indicates no initial value.
841 __ CallRuntime(Runtime::kDeclareLookupSlot, 4);
848 void FullCodeGenerator::VisitFunctionDeclaration(
849 FunctionDeclaration* declaration) {
850 VariableProxy* proxy = declaration->proxy();
851 Variable* variable = proxy->var();
852 switch (variable->location()) {
853 case Variable::UNALLOCATED: {
854 globals_->Add(variable->name(), zone());
855 Handle<SharedFunctionInfo> function =
856 Compiler::BuildFunctionInfo(declaration->fun(), script(), info_);
857 // Check for stack-overflow exception.
858 if (function.is_null()) return SetStackOverflow();
859 globals_->Add(function, zone());
863 case Variable::PARAMETER:
864 case Variable::LOCAL: {
865 Comment cmnt(masm_, "[ FunctionDeclaration");
866 VisitForAccumulatorValue(declaration->fun());
867 __ mov(StackOperand(variable), result_register());
871 case Variable::CONTEXT: {
872 Comment cmnt(masm_, "[ FunctionDeclaration");
873 EmitDebugCheckDeclarationContext(variable);
874 VisitForAccumulatorValue(declaration->fun());
875 __ mov(ContextOperand(esi, variable->index()), result_register());
876 // We know that we have written a function, which is not a smi.
877 __ RecordWriteContextSlot(esi, Context::SlotOffset(variable->index()),
878 result_register(), ecx, kDontSaveFPRegs,
879 EMIT_REMEMBERED_SET, OMIT_SMI_CHECK);
880 PrepareForBailoutForId(proxy->id(), NO_REGISTERS);
884 case Variable::LOOKUP: {
885 Comment cmnt(masm_, "[ FunctionDeclaration");
887 __ push(Immediate(variable->name()));
888 __ push(Immediate(Smi::FromInt(NONE)));
889 VisitForStackValue(declaration->fun());
890 __ CallRuntime(Runtime::kDeclareLookupSlot, 4);
897 void FullCodeGenerator::VisitImportDeclaration(ImportDeclaration* declaration) {
898 VariableProxy* proxy = declaration->proxy();
899 Variable* variable = proxy->var();
900 switch (variable->location()) {
901 case Variable::UNALLOCATED:
905 case Variable::CONTEXT: {
906 Comment cmnt(masm_, "[ ImportDeclaration");
907 EmitDebugCheckDeclarationContext(variable);
912 case Variable::PARAMETER:
913 case Variable::LOCAL:
914 case Variable::LOOKUP:
920 void FullCodeGenerator::VisitExportDeclaration(ExportDeclaration* declaration) {
925 void FullCodeGenerator::DeclareGlobals(Handle<FixedArray> pairs) {
926 // Call the runtime to declare the globals.
927 __ push(esi); // The context is the first argument.
929 __ Push(Smi::FromInt(DeclareGlobalsFlags()));
930 __ CallRuntime(Runtime::kDeclareGlobals, 3);
931 // Return value is ignored.
935 void FullCodeGenerator::DeclareModules(Handle<FixedArray> descriptions) {
936 // Call the runtime to declare the modules.
937 __ Push(descriptions);
938 __ CallRuntime(Runtime::kDeclareModules, 1);
939 // Return value is ignored.
943 void FullCodeGenerator::VisitSwitchStatement(SwitchStatement* stmt) {
944 Comment cmnt(masm_, "[ SwitchStatement");
945 Breakable nested_statement(this, stmt);
946 SetStatementPosition(stmt);
948 // Keep the switch value on the stack until a case matches.
949 VisitForStackValue(stmt->tag());
950 PrepareForBailoutForId(stmt->EntryId(), NO_REGISTERS);
952 ZoneList<CaseClause*>* clauses = stmt->cases();
953 CaseClause* default_clause = NULL; // Can occur anywhere in the list.
955 Label next_test; // Recycled for each test.
956 // Compile all the tests with branches to their bodies.
957 for (int i = 0; i < clauses->length(); i++) {
958 CaseClause* clause = clauses->at(i);
959 clause->body_target()->Unuse();
961 // The default is not a test, but remember it as final fall through.
962 if (clause->is_default()) {
963 default_clause = clause;
967 Comment cmnt(masm_, "[ Case comparison");
971 // Compile the label expression.
972 VisitForAccumulatorValue(clause->label());
974 // Perform the comparison as if via '==='.
975 __ mov(edx, Operand(esp, 0)); // Switch value.
976 bool inline_smi_code = ShouldInlineSmiCase(Token::EQ_STRICT);
977 JumpPatchSite patch_site(masm_);
978 if (inline_smi_code) {
982 patch_site.EmitJumpIfNotSmi(ecx, &slow_case, Label::kNear);
985 __ j(not_equal, &next_test);
986 __ Drop(1); // Switch value is no longer needed.
987 __ jmp(clause->body_target());
991 // Record position before stub call for type feedback.
992 SetSourcePosition(clause->position());
993 Handle<Code> ic = CodeFactory::CompareIC(isolate(), Token::EQ_STRICT,
994 language_mode()).code();
995 CallIC(ic, clause->CompareId());
996 patch_site.EmitPatchInfo();
999 __ jmp(&skip, Label::kNear);
1000 PrepareForBailout(clause, TOS_REG);
1001 __ cmp(eax, isolate()->factory()->true_value());
1002 __ j(not_equal, &next_test);
1004 __ jmp(clause->body_target());
1008 __ j(not_equal, &next_test);
1009 __ Drop(1); // Switch value is no longer needed.
1010 __ jmp(clause->body_target());
1013 // Discard the test value and jump to the default if present, otherwise to
1014 // the end of the statement.
1015 __ bind(&next_test);
1016 __ Drop(1); // Switch value is no longer needed.
1017 if (default_clause == NULL) {
1018 __ jmp(nested_statement.break_label());
1020 __ jmp(default_clause->body_target());
1023 // Compile all the case bodies.
1024 for (int i = 0; i < clauses->length(); i++) {
1025 Comment cmnt(masm_, "[ Case body");
1026 CaseClause* clause = clauses->at(i);
1027 __ bind(clause->body_target());
1028 PrepareForBailoutForId(clause->EntryId(), NO_REGISTERS);
1029 VisitStatements(clause->statements());
1032 __ bind(nested_statement.break_label());
1033 PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1037 void FullCodeGenerator::VisitForInStatement(ForInStatement* stmt) {
1038 Comment cmnt(masm_, "[ ForInStatement");
1039 FeedbackVectorSlot slot = stmt->ForInFeedbackSlot();
1041 SetStatementPosition(stmt);
1044 ForIn loop_statement(this, stmt);
1045 increment_loop_depth();
1047 // Get the object to enumerate over. If the object is null or undefined, skip
1048 // over the loop. See ECMA-262 version 5, section 12.6.4.
1049 SetExpressionPosition(stmt->enumerable());
1050 VisitForAccumulatorValue(stmt->enumerable());
1051 __ cmp(eax, isolate()->factory()->undefined_value());
1053 __ cmp(eax, isolate()->factory()->null_value());
1056 PrepareForBailoutForId(stmt->PrepareId(), TOS_REG);
1058 // Convert the object to a JS object.
1059 Label convert, done_convert;
1060 __ JumpIfSmi(eax, &convert, Label::kNear);
1061 __ CmpObjectType(eax, FIRST_SPEC_OBJECT_TYPE, ecx);
1062 __ j(above_equal, &done_convert, Label::kNear);
1065 __ InvokeBuiltin(Builtins::TO_OBJECT, CALL_FUNCTION);
1066 __ bind(&done_convert);
1067 PrepareForBailoutForId(stmt->ToObjectId(), TOS_REG);
1070 // Check for proxies.
1071 Label call_runtime, use_cache, fixed_array;
1072 STATIC_ASSERT(FIRST_JS_PROXY_TYPE == FIRST_SPEC_OBJECT_TYPE);
1073 __ CmpObjectType(eax, LAST_JS_PROXY_TYPE, ecx);
1074 __ j(below_equal, &call_runtime);
1076 // Check cache validity in generated code. This is a fast case for
1077 // the JSObject::IsSimpleEnum cache validity checks. If we cannot
1078 // guarantee cache validity, call the runtime system to check cache
1079 // validity or get the property names in a fixed array.
1080 __ CheckEnumCache(&call_runtime);
1082 __ mov(eax, FieldOperand(eax, HeapObject::kMapOffset));
1083 __ jmp(&use_cache, Label::kNear);
1085 // Get the set of properties to enumerate.
1086 __ bind(&call_runtime);
1088 __ CallRuntime(Runtime::kGetPropertyNamesFast, 1);
1089 PrepareForBailoutForId(stmt->EnumId(), TOS_REG);
1090 __ cmp(FieldOperand(eax, HeapObject::kMapOffset),
1091 isolate()->factory()->meta_map());
1092 __ j(not_equal, &fixed_array);
1095 // We got a map in register eax. Get the enumeration cache from it.
1096 Label no_descriptors;
1097 __ bind(&use_cache);
1099 __ EnumLength(edx, eax);
1100 __ cmp(edx, Immediate(Smi::FromInt(0)));
1101 __ j(equal, &no_descriptors);
1103 __ LoadInstanceDescriptors(eax, ecx);
1104 __ mov(ecx, FieldOperand(ecx, DescriptorArray::kEnumCacheOffset));
1105 __ mov(ecx, FieldOperand(ecx, DescriptorArray::kEnumCacheBridgeCacheOffset));
1107 // Set up the four remaining stack slots.
1108 __ push(eax); // Map.
1109 __ push(ecx); // Enumeration cache.
1110 __ push(edx); // Number of valid entries for the map in the enum cache.
1111 __ push(Immediate(Smi::FromInt(0))); // Initial index.
1114 __ bind(&no_descriptors);
1115 __ add(esp, Immediate(kPointerSize));
1118 // We got a fixed array in register eax. Iterate through that.
1120 __ bind(&fixed_array);
1122 // No need for a write barrier, we are storing a Smi in the feedback vector.
1123 __ LoadHeapObject(ebx, FeedbackVector());
1124 int vector_index = FeedbackVector()->GetIndex(slot);
1125 __ mov(FieldOperand(ebx, FixedArray::OffsetOfElementAt(vector_index)),
1126 Immediate(TypeFeedbackVector::MegamorphicSentinel(isolate())));
1128 __ mov(ebx, Immediate(Smi::FromInt(1))); // Smi indicates slow check
1129 __ mov(ecx, Operand(esp, 0 * kPointerSize)); // Get enumerated object
1130 STATIC_ASSERT(FIRST_JS_PROXY_TYPE == FIRST_SPEC_OBJECT_TYPE);
1131 __ CmpObjectType(ecx, LAST_JS_PROXY_TYPE, ecx);
1132 __ j(above, &non_proxy);
1133 __ Move(ebx, Immediate(Smi::FromInt(0))); // Zero indicates proxy
1134 __ bind(&non_proxy);
1135 __ push(ebx); // Smi
1136 __ push(eax); // Array
1137 __ mov(eax, FieldOperand(eax, FixedArray::kLengthOffset));
1138 __ push(eax); // Fixed array length (as smi).
1139 __ push(Immediate(Smi::FromInt(0))); // Initial index.
1141 // Generate code for doing the condition check.
1142 PrepareForBailoutForId(stmt->BodyId(), NO_REGISTERS);
1144 SetExpressionPosition(stmt->each());
1146 __ mov(eax, Operand(esp, 0 * kPointerSize)); // Get the current index.
1147 __ cmp(eax, Operand(esp, 1 * kPointerSize)); // Compare to the array length.
1148 __ j(above_equal, loop_statement.break_label());
1150 // Get the current entry of the array into register ebx.
1151 __ mov(ebx, Operand(esp, 2 * kPointerSize));
1152 __ mov(ebx, FieldOperand(ebx, eax, times_2, FixedArray::kHeaderSize));
1154 // Get the expected map from the stack or a smi in the
1155 // permanent slow case into register edx.
1156 __ mov(edx, Operand(esp, 3 * kPointerSize));
1158 // Check if the expected map still matches that of the enumerable.
1159 // If not, we may have to filter the key.
1161 __ mov(ecx, Operand(esp, 4 * kPointerSize));
1162 __ cmp(edx, FieldOperand(ecx, HeapObject::kMapOffset));
1163 __ j(equal, &update_each, Label::kNear);
1165 // For proxies, no filtering is done.
1166 // TODO(rossberg): What if only a prototype is a proxy? Not specified yet.
1167 DCHECK(Smi::FromInt(0) == 0);
1169 __ j(zero, &update_each);
1171 // Convert the entry to a string or null if it isn't a property
1172 // anymore. If the property has been removed while iterating, we
1174 __ push(ecx); // Enumerable.
1175 __ push(ebx); // Current entry.
1176 __ CallRuntime(Runtime::kForInFilter, 2);
1177 PrepareForBailoutForId(stmt->FilterId(), TOS_REG);
1178 __ cmp(eax, isolate()->factory()->undefined_value());
1179 __ j(equal, loop_statement.continue_label());
1182 // Update the 'each' property or variable from the possibly filtered
1183 // entry in register ebx.
1184 __ bind(&update_each);
1185 __ mov(result_register(), ebx);
1186 // Perform the assignment as if via '='.
1187 { EffectContext context(this);
1188 EmitAssignment(stmt->each(), stmt->EachFeedbackSlot());
1189 PrepareForBailoutForId(stmt->AssignmentId(), NO_REGISTERS);
1192 // Generate code for the body of the loop.
1193 Visit(stmt->body());
1195 // Generate code for going to the next element by incrementing the
1196 // index (smi) stored on top of the stack.
1197 __ bind(loop_statement.continue_label());
1198 __ add(Operand(esp, 0 * kPointerSize), Immediate(Smi::FromInt(1)));
1200 EmitBackEdgeBookkeeping(stmt, &loop);
1203 // Remove the pointers stored on the stack.
1204 __ bind(loop_statement.break_label());
1205 __ add(esp, Immediate(5 * kPointerSize));
1207 // Exit and decrement the loop depth.
1208 PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1210 decrement_loop_depth();
1214 void FullCodeGenerator::EmitNewClosure(Handle<SharedFunctionInfo> info,
1216 // Use the fast case closure allocation code that allocates in new
1217 // space for nested functions that don't need literals cloning. If
1218 // we're running with the --always-opt or the --prepare-always-opt
1219 // flag, we need to use the runtime function so that the new function
1220 // we are creating here gets a chance to have its code optimized and
1221 // doesn't just get a copy of the existing unoptimized code.
1222 if (!FLAG_always_opt &&
1223 !FLAG_prepare_always_opt &&
1225 scope()->is_function_scope() &&
1226 info->num_literals() == 0) {
1227 FastNewClosureStub stub(isolate(), info->language_mode(), info->kind());
1228 __ mov(ebx, Immediate(info));
1232 __ push(Immediate(info));
1233 __ push(Immediate(pretenure
1234 ? isolate()->factory()->true_value()
1235 : isolate()->factory()->false_value()));
1236 __ CallRuntime(Runtime::kNewClosure, 3);
1238 context()->Plug(eax);
1242 void FullCodeGenerator::VisitVariableProxy(VariableProxy* expr) {
1243 Comment cmnt(masm_, "[ VariableProxy");
1244 EmitVariableLoad(expr);
1248 void FullCodeGenerator::EmitSetHomeObjectIfNeeded(Expression* initializer,
1250 FeedbackVectorICSlot slot) {
1251 if (NeedsHomeObject(initializer)) {
1252 __ mov(StoreDescriptor::ReceiverRegister(), Operand(esp, 0));
1253 __ mov(StoreDescriptor::NameRegister(),
1254 Immediate(isolate()->factory()->home_object_symbol()));
1255 __ mov(StoreDescriptor::ValueRegister(),
1256 Operand(esp, offset * kPointerSize));
1257 if (FLAG_vector_stores) EmitLoadStoreICSlot(slot);
1263 void FullCodeGenerator::EmitLoadGlobalCheckExtensions(VariableProxy* proxy,
1264 TypeofState typeof_state,
1266 Register context = esi;
1267 Register temp = edx;
1271 if (s->num_heap_slots() > 0) {
1272 if (s->calls_sloppy_eval()) {
1273 // Check that extension is NULL.
1274 __ cmp(ContextOperand(context, Context::EXTENSION_INDEX),
1276 __ j(not_equal, slow);
1278 // Load next context in chain.
1279 __ mov(temp, ContextOperand(context, Context::PREVIOUS_INDEX));
1280 // Walk the rest of the chain without clobbering esi.
1283 // If no outer scope calls eval, we do not need to check more
1284 // context extensions. If we have reached an eval scope, we check
1285 // all extensions from this point.
1286 if (!s->outer_scope_calls_sloppy_eval() || s->is_eval_scope()) break;
1287 s = s->outer_scope();
1290 if (s != NULL && s->is_eval_scope()) {
1291 // Loop up the context chain. There is no frame effect so it is
1292 // safe to use raw labels here.
1294 if (!context.is(temp)) {
1295 __ mov(temp, context);
1298 // Terminate at native context.
1299 __ cmp(FieldOperand(temp, HeapObject::kMapOffset),
1300 Immediate(isolate()->factory()->native_context_map()));
1301 __ j(equal, &fast, Label::kNear);
1302 // Check that extension is NULL.
1303 __ cmp(ContextOperand(temp, Context::EXTENSION_INDEX), Immediate(0));
1304 __ j(not_equal, slow);
1305 // Load next context in chain.
1306 __ mov(temp, ContextOperand(temp, Context::PREVIOUS_INDEX));
1311 // All extension objects were empty and it is safe to use a global
1313 __ mov(LoadDescriptor::ReceiverRegister(), GlobalObjectOperand());
1314 __ mov(LoadDescriptor::NameRegister(), proxy->var()->name());
1315 __ mov(LoadDescriptor::SlotRegister(),
1316 Immediate(SmiFromSlot(proxy->VariableFeedbackSlot())));
1318 ContextualMode mode = (typeof_state == INSIDE_TYPEOF)
1326 MemOperand FullCodeGenerator::ContextSlotOperandCheckExtensions(Variable* var,
1328 DCHECK(var->IsContextSlot());
1329 Register context = esi;
1330 Register temp = ebx;
1332 for (Scope* s = scope(); s != var->scope(); s = s->outer_scope()) {
1333 if (s->num_heap_slots() > 0) {
1334 if (s->calls_sloppy_eval()) {
1335 // Check that extension is NULL.
1336 __ cmp(ContextOperand(context, Context::EXTENSION_INDEX),
1338 __ j(not_equal, slow);
1340 __ mov(temp, ContextOperand(context, Context::PREVIOUS_INDEX));
1341 // Walk the rest of the chain without clobbering esi.
1345 // Check that last extension is NULL.
1346 __ cmp(ContextOperand(context, Context::EXTENSION_INDEX), Immediate(0));
1347 __ j(not_equal, slow);
1349 // This function is used only for loads, not stores, so it's safe to
1350 // return an esi-based operand (the write barrier cannot be allowed to
1351 // destroy the esi register).
1352 return ContextOperand(context, var->index());
1356 void FullCodeGenerator::EmitDynamicLookupFastCase(VariableProxy* proxy,
1357 TypeofState typeof_state,
1360 // Generate fast-case code for variables that might be shadowed by
1361 // eval-introduced variables. Eval is used a lot without
1362 // introducing variables. In those cases, we do not want to
1363 // perform a runtime call for all variables in the scope
1364 // containing the eval.
1365 Variable* var = proxy->var();
1366 if (var->mode() == DYNAMIC_GLOBAL) {
1367 EmitLoadGlobalCheckExtensions(proxy, typeof_state, slow);
1369 } else if (var->mode() == DYNAMIC_LOCAL) {
1370 Variable* local = var->local_if_not_shadowed();
1371 __ mov(eax, ContextSlotOperandCheckExtensions(local, slow));
1372 if (local->mode() == LET || local->mode() == CONST ||
1373 local->mode() == CONST_LEGACY) {
1374 __ cmp(eax, isolate()->factory()->the_hole_value());
1375 __ j(not_equal, done);
1376 if (local->mode() == CONST_LEGACY) {
1377 __ mov(eax, isolate()->factory()->undefined_value());
1378 } else { // LET || CONST
1379 __ push(Immediate(var->name()));
1380 __ CallRuntime(Runtime::kThrowReferenceError, 1);
1388 void FullCodeGenerator::EmitVariableLoad(VariableProxy* proxy) {
1389 // Record position before possible IC call.
1390 SetSourcePosition(proxy->position());
1391 PrepareForBailoutForId(proxy->BeforeId(), NO_REGISTERS);
1392 Variable* var = proxy->var();
1394 // Three cases: global variables, lookup variables, and all other types of
1396 switch (var->location()) {
1397 case Variable::UNALLOCATED: {
1398 Comment cmnt(masm_, "[ Global variable");
1399 __ mov(LoadDescriptor::ReceiverRegister(), GlobalObjectOperand());
1400 __ mov(LoadDescriptor::NameRegister(), var->name());
1401 __ mov(LoadDescriptor::SlotRegister(),
1402 Immediate(SmiFromSlot(proxy->VariableFeedbackSlot())));
1403 CallGlobalLoadIC(var->name());
1404 context()->Plug(eax);
1408 case Variable::PARAMETER:
1409 case Variable::LOCAL:
1410 case Variable::CONTEXT: {
1411 Comment cmnt(masm_, var->IsContextSlot() ? "[ Context variable"
1412 : "[ Stack variable");
1413 if (var->binding_needs_init()) {
1414 // var->scope() may be NULL when the proxy is located in eval code and
1415 // refers to a potential outside binding. Currently those bindings are
1416 // always looked up dynamically, i.e. in that case
1417 // var->location() == LOOKUP.
1419 DCHECK(var->scope() != NULL);
1421 // Check if the binding really needs an initialization check. The check
1422 // can be skipped in the following situation: we have a LET or CONST
1423 // binding in harmony mode, both the Variable and the VariableProxy have
1424 // the same declaration scope (i.e. they are both in global code, in the
1425 // same function or in the same eval code) and the VariableProxy is in
1426 // the source physically located after the initializer of the variable.
1428 // We cannot skip any initialization checks for CONST in non-harmony
1429 // mode because const variables may be declared but never initialized:
1430 // if (false) { const x; }; var y = x;
1432 // The condition on the declaration scopes is a conservative check for
1433 // nested functions that access a binding and are called before the
1434 // binding is initialized:
1435 // function() { f(); let x = 1; function f() { x = 2; } }
1437 bool skip_init_check;
1438 if (var->scope()->DeclarationScope() != scope()->DeclarationScope()) {
1439 skip_init_check = false;
1440 } else if (var->is_this()) {
1441 CHECK(info_->function() != nullptr &&
1442 (info_->function()->kind() & kSubclassConstructor) != 0);
1443 // TODO(dslomov): implement 'this' hole check elimination.
1444 skip_init_check = false;
1446 // Check that we always have valid source position.
1447 DCHECK(var->initializer_position() != RelocInfo::kNoPosition);
1448 DCHECK(proxy->position() != RelocInfo::kNoPosition);
1449 skip_init_check = var->mode() != CONST_LEGACY &&
1450 var->initializer_position() < proxy->position();
1453 if (!skip_init_check) {
1454 // Let and const need a read barrier.
1457 __ cmp(eax, isolate()->factory()->the_hole_value());
1458 __ j(not_equal, &done, Label::kNear);
1459 if (var->mode() == LET || var->mode() == CONST) {
1460 // Throw a reference error when using an uninitialized let/const
1461 // binding in harmony mode.
1462 __ push(Immediate(var->name()));
1463 __ CallRuntime(Runtime::kThrowReferenceError, 1);
1465 // Uninitalized const bindings outside of harmony mode are unholed.
1466 DCHECK(var->mode() == CONST_LEGACY);
1467 __ mov(eax, isolate()->factory()->undefined_value());
1470 context()->Plug(eax);
1474 context()->Plug(var);
1478 case Variable::LOOKUP: {
1479 Comment cmnt(masm_, "[ Lookup variable");
1481 // Generate code for loading from variables potentially shadowed
1482 // by eval-introduced variables.
1483 EmitDynamicLookupFastCase(proxy, NOT_INSIDE_TYPEOF, &slow, &done);
1485 __ push(esi); // Context.
1486 __ push(Immediate(var->name()));
1487 __ CallRuntime(Runtime::kLoadLookupSlot, 2);
1489 context()->Plug(eax);
1496 void FullCodeGenerator::VisitRegExpLiteral(RegExpLiteral* expr) {
1497 Comment cmnt(masm_, "[ RegExpLiteral");
1499 // Registers will be used as follows:
1500 // edi = JS function.
1501 // ecx = literals array.
1502 // ebx = regexp literal.
1503 // eax = regexp literal clone.
1504 __ mov(edi, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
1505 __ mov(ecx, FieldOperand(edi, JSFunction::kLiteralsOffset));
1506 int literal_offset =
1507 FixedArray::kHeaderSize + expr->literal_index() * kPointerSize;
1508 __ mov(ebx, FieldOperand(ecx, literal_offset));
1509 __ cmp(ebx, isolate()->factory()->undefined_value());
1510 __ j(not_equal, &materialized, Label::kNear);
1512 // Create regexp literal using runtime function
1513 // Result will be in eax.
1515 __ push(Immediate(Smi::FromInt(expr->literal_index())));
1516 __ push(Immediate(expr->pattern()));
1517 __ push(Immediate(expr->flags()));
1518 __ CallRuntime(Runtime::kMaterializeRegExpLiteral, 4);
1521 __ bind(&materialized);
1522 int size = JSRegExp::kSize + JSRegExp::kInObjectFieldCount * kPointerSize;
1523 Label allocated, runtime_allocate;
1524 __ Allocate(size, eax, ecx, edx, &runtime_allocate, TAG_OBJECT);
1527 __ bind(&runtime_allocate);
1529 __ push(Immediate(Smi::FromInt(size)));
1530 __ CallRuntime(Runtime::kAllocateInNewSpace, 1);
1533 __ bind(&allocated);
1534 // Copy the content into the newly allocated memory.
1535 // (Unroll copy loop once for better throughput).
1536 for (int i = 0; i < size - kPointerSize; i += 2 * kPointerSize) {
1537 __ mov(edx, FieldOperand(ebx, i));
1538 __ mov(ecx, FieldOperand(ebx, i + kPointerSize));
1539 __ mov(FieldOperand(eax, i), edx);
1540 __ mov(FieldOperand(eax, i + kPointerSize), ecx);
1542 if ((size % (2 * kPointerSize)) != 0) {
1543 __ mov(edx, FieldOperand(ebx, size - kPointerSize));
1544 __ mov(FieldOperand(eax, size - kPointerSize), edx);
1546 context()->Plug(eax);
1550 void FullCodeGenerator::EmitAccessor(Expression* expression) {
1551 if (expression == NULL) {
1552 __ push(Immediate(isolate()->factory()->null_value()));
1554 VisitForStackValue(expression);
1559 void FullCodeGenerator::VisitObjectLiteral(ObjectLiteral* expr) {
1560 Comment cmnt(masm_, "[ ObjectLiteral");
1562 expr->BuildConstantProperties(isolate());
1563 Handle<FixedArray> constant_properties = expr->constant_properties();
1564 int flags = expr->ComputeFlags();
1565 // If any of the keys would store to the elements array, then we shouldn't
1567 if (MustCreateObjectLiteralWithRuntime(expr)) {
1568 __ mov(edi, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
1569 __ push(FieldOperand(edi, JSFunction::kLiteralsOffset));
1570 __ push(Immediate(Smi::FromInt(expr->literal_index())));
1571 __ push(Immediate(constant_properties));
1572 __ push(Immediate(Smi::FromInt(flags)));
1573 __ CallRuntime(Runtime::kCreateObjectLiteral, 4);
1575 __ mov(edi, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
1576 __ mov(eax, FieldOperand(edi, JSFunction::kLiteralsOffset));
1577 __ mov(ebx, Immediate(Smi::FromInt(expr->literal_index())));
1578 __ mov(ecx, Immediate(constant_properties));
1579 __ mov(edx, Immediate(Smi::FromInt(flags)));
1580 FastCloneShallowObjectStub stub(isolate(), expr->properties_count());
1583 PrepareForBailoutForId(expr->CreateLiteralId(), TOS_REG);
1585 // If result_saved is true the result is on top of the stack. If
1586 // result_saved is false the result is in eax.
1587 bool result_saved = false;
1589 AccessorTable accessor_table(zone());
1590 int property_index = 0;
1591 // store_slot_index points to the vector ic slot for the next store ic used.
1592 // ObjectLiteral::ComputeFeedbackRequirements controls the allocation of slots
1593 // and must be updated if the number of store ics emitted here changes.
1594 int store_slot_index = 0;
1595 for (; property_index < expr->properties()->length(); property_index++) {
1596 ObjectLiteral::Property* property = expr->properties()->at(property_index);
1597 if (property->is_computed_name()) break;
1598 if (property->IsCompileTimeValue()) continue;
1600 Literal* key = property->key()->AsLiteral();
1601 Expression* value = property->value();
1602 if (!result_saved) {
1603 __ push(eax); // Save result on the stack
1604 result_saved = true;
1606 switch (property->kind()) {
1607 case ObjectLiteral::Property::CONSTANT:
1609 case ObjectLiteral::Property::MATERIALIZED_LITERAL:
1610 DCHECK(!CompileTimeValue::IsCompileTimeValue(value));
1612 case ObjectLiteral::Property::COMPUTED:
1613 // It is safe to use [[Put]] here because the boilerplate already
1614 // contains computed properties with an uninitialized value.
1615 if (key->value()->IsInternalizedString()) {
1616 if (property->emit_store()) {
1617 VisitForAccumulatorValue(value);
1618 DCHECK(StoreDescriptor::ValueRegister().is(eax));
1619 __ mov(StoreDescriptor::NameRegister(), Immediate(key->value()));
1620 __ mov(StoreDescriptor::ReceiverRegister(), Operand(esp, 0));
1621 if (FLAG_vector_stores) {
1622 EmitLoadStoreICSlot(expr->GetNthSlot(store_slot_index++));
1625 CallStoreIC(key->LiteralFeedbackId());
1627 PrepareForBailoutForId(key->id(), NO_REGISTERS);
1629 if (NeedsHomeObject(value)) {
1630 __ mov(StoreDescriptor::ReceiverRegister(), eax);
1631 __ mov(StoreDescriptor::NameRegister(),
1632 Immediate(isolate()->factory()->home_object_symbol()));
1633 __ mov(StoreDescriptor::ValueRegister(), Operand(esp, 0));
1634 if (FLAG_vector_stores) {
1635 EmitLoadStoreICSlot(expr->GetNthSlot(store_slot_index++));
1640 VisitForEffect(value);
1644 __ push(Operand(esp, 0)); // Duplicate receiver.
1645 VisitForStackValue(key);
1646 VisitForStackValue(value);
1647 if (property->emit_store()) {
1648 EmitSetHomeObjectIfNeeded(
1649 value, 2, expr->SlotForHomeObject(value, &store_slot_index));
1650 __ push(Immediate(Smi::FromInt(SLOPPY))); // Language mode
1651 __ CallRuntime(Runtime::kSetProperty, 4);
1656 case ObjectLiteral::Property::PROTOTYPE:
1657 __ push(Operand(esp, 0)); // Duplicate receiver.
1658 VisitForStackValue(value);
1659 DCHECK(property->emit_store());
1660 __ CallRuntime(Runtime::kInternalSetPrototype, 2);
1662 case ObjectLiteral::Property::GETTER:
1663 if (property->emit_store()) {
1664 accessor_table.lookup(key)->second->getter = value;
1667 case ObjectLiteral::Property::SETTER:
1668 if (property->emit_store()) {
1669 accessor_table.lookup(key)->second->setter = value;
1675 // Emit code to define accessors, using only a single call to the runtime for
1676 // each pair of corresponding getters and setters.
1677 for (AccessorTable::Iterator it = accessor_table.begin();
1678 it != accessor_table.end();
1680 __ push(Operand(esp, 0)); // Duplicate receiver.
1681 VisitForStackValue(it->first);
1682 EmitAccessor(it->second->getter);
1683 EmitSetHomeObjectIfNeeded(
1684 it->second->getter, 2,
1685 expr->SlotForHomeObject(it->second->getter, &store_slot_index));
1687 EmitAccessor(it->second->setter);
1688 EmitSetHomeObjectIfNeeded(
1689 it->second->setter, 3,
1690 expr->SlotForHomeObject(it->second->setter, &store_slot_index));
1692 __ push(Immediate(Smi::FromInt(NONE)));
1693 __ CallRuntime(Runtime::kDefineAccessorPropertyUnchecked, 5);
1696 // Object literals have two parts. The "static" part on the left contains no
1697 // computed property names, and so we can compute its map ahead of time; see
1698 // runtime.cc::CreateObjectLiteralBoilerplate. The second "dynamic" part
1699 // starts with the first computed property name, and continues with all
1700 // properties to its right. All the code from above initializes the static
1701 // component of the object literal, and arranges for the map of the result to
1702 // reflect the static order in which the keys appear. For the dynamic
1703 // properties, we compile them into a series of "SetOwnProperty" runtime
1704 // calls. This will preserve insertion order.
1705 for (; property_index < expr->properties()->length(); property_index++) {
1706 ObjectLiteral::Property* property = expr->properties()->at(property_index);
1708 Expression* value = property->value();
1709 if (!result_saved) {
1710 __ push(eax); // Save result on the stack
1711 result_saved = true;
1714 __ push(Operand(esp, 0)); // Duplicate receiver.
1716 if (property->kind() == ObjectLiteral::Property::PROTOTYPE) {
1717 DCHECK(!property->is_computed_name());
1718 VisitForStackValue(value);
1719 DCHECK(property->emit_store());
1720 __ CallRuntime(Runtime::kInternalSetPrototype, 2);
1722 EmitPropertyKey(property, expr->GetIdForProperty(property_index));
1723 VisitForStackValue(value);
1724 EmitSetHomeObjectIfNeeded(
1725 value, 2, expr->SlotForHomeObject(value, &store_slot_index));
1727 switch (property->kind()) {
1728 case ObjectLiteral::Property::CONSTANT:
1729 case ObjectLiteral::Property::MATERIALIZED_LITERAL:
1730 case ObjectLiteral::Property::COMPUTED:
1731 if (property->emit_store()) {
1732 __ push(Immediate(Smi::FromInt(NONE)));
1733 __ CallRuntime(Runtime::kDefineDataPropertyUnchecked, 4);
1739 case ObjectLiteral::Property::PROTOTYPE:
1743 case ObjectLiteral::Property::GETTER:
1744 __ push(Immediate(Smi::FromInt(NONE)));
1745 __ CallRuntime(Runtime::kDefineGetterPropertyUnchecked, 4);
1748 case ObjectLiteral::Property::SETTER:
1749 __ push(Immediate(Smi::FromInt(NONE)));
1750 __ CallRuntime(Runtime::kDefineSetterPropertyUnchecked, 4);
1756 if (expr->has_function()) {
1757 DCHECK(result_saved);
1758 __ push(Operand(esp, 0));
1759 __ CallRuntime(Runtime::kToFastProperties, 1);
1763 context()->PlugTOS();
1765 context()->Plug(eax);
1768 // Verify that compilation exactly consumed the number of store ic slots that
1769 // the ObjectLiteral node had to offer.
1770 DCHECK(!FLAG_vector_stores || store_slot_index == expr->slot_count());
1774 void FullCodeGenerator::VisitArrayLiteral(ArrayLiteral* expr) {
1775 Comment cmnt(masm_, "[ ArrayLiteral");
1777 expr->BuildConstantElements(isolate());
1778 Handle<FixedArray> constant_elements = expr->constant_elements();
1779 bool has_constant_fast_elements =
1780 IsFastObjectElementsKind(expr->constant_elements_kind());
1782 AllocationSiteMode allocation_site_mode = TRACK_ALLOCATION_SITE;
1783 if (has_constant_fast_elements && !FLAG_allocation_site_pretenuring) {
1784 // If the only customer of allocation sites is transitioning, then
1785 // we can turn it off if we don't have anywhere else to transition to.
1786 allocation_site_mode = DONT_TRACK_ALLOCATION_SITE;
1789 if (MustCreateArrayLiteralWithRuntime(expr)) {
1790 __ mov(ebx, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
1791 __ push(FieldOperand(ebx, JSFunction::kLiteralsOffset));
1792 __ push(Immediate(Smi::FromInt(expr->literal_index())));
1793 __ push(Immediate(constant_elements));
1794 __ push(Immediate(Smi::FromInt(expr->ComputeFlags())));
1795 __ CallRuntime(Runtime::kCreateArrayLiteral, 4);
1797 __ mov(ebx, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
1798 __ mov(eax, FieldOperand(ebx, JSFunction::kLiteralsOffset));
1799 __ mov(ebx, Immediate(Smi::FromInt(expr->literal_index())));
1800 __ mov(ecx, Immediate(constant_elements));
1801 FastCloneShallowArrayStub stub(isolate(), allocation_site_mode);
1804 PrepareForBailoutForId(expr->CreateLiteralId(), TOS_REG);
1806 bool result_saved = false; // Is the result saved to the stack?
1807 ZoneList<Expression*>* subexprs = expr->values();
1808 int length = subexprs->length();
1810 // Emit code to evaluate all the non-constant subexpressions and to store
1811 // them into the newly cloned array.
1812 int array_index = 0;
1813 for (; array_index < length; array_index++) {
1814 Expression* subexpr = subexprs->at(array_index);
1815 if (subexpr->IsSpread()) break;
1817 // If the subexpression is a literal or a simple materialized literal it
1818 // is already set in the cloned array.
1819 if (CompileTimeValue::IsCompileTimeValue(subexpr)) continue;
1821 if (!result_saved) {
1822 __ push(eax); // array literal.
1823 __ push(Immediate(Smi::FromInt(expr->literal_index())));
1824 result_saved = true;
1826 VisitForAccumulatorValue(subexpr);
1828 if (has_constant_fast_elements) {
1829 // Fast-case array literal with ElementsKind of FAST_*_ELEMENTS, they
1830 // cannot transition and don't need to call the runtime stub.
1831 int offset = FixedArray::kHeaderSize + (array_index * kPointerSize);
1832 __ mov(ebx, Operand(esp, kPointerSize)); // Copy of array literal.
1833 __ mov(ebx, FieldOperand(ebx, JSObject::kElementsOffset));
1834 // Store the subexpression value in the array's elements.
1835 __ mov(FieldOperand(ebx, offset), result_register());
1836 // Update the write barrier for the array store.
1837 __ RecordWriteField(ebx, offset, result_register(), ecx, kDontSaveFPRegs,
1838 EMIT_REMEMBERED_SET, INLINE_SMI_CHECK);
1840 // Store the subexpression value in the array's elements.
1841 __ mov(ecx, Immediate(Smi::FromInt(array_index)));
1842 StoreArrayLiteralElementStub stub(isolate());
1846 PrepareForBailoutForId(expr->GetIdForElement(array_index), NO_REGISTERS);
1849 // In case the array literal contains spread expressions it has two parts. The
1850 // first part is the "static" array which has a literal index is handled
1851 // above. The second part is the part after the first spread expression
1852 // (inclusive) and these elements gets appended to the array. Note that the
1853 // number elements an iterable produces is unknown ahead of time.
1854 if (array_index < length && result_saved) {
1855 __ Drop(1); // literal index
1857 result_saved = false;
1859 for (; array_index < length; array_index++) {
1860 Expression* subexpr = subexprs->at(array_index);
1863 if (subexpr->IsSpread()) {
1864 VisitForStackValue(subexpr->AsSpread()->expression());
1865 __ InvokeBuiltin(Builtins::CONCAT_ITERABLE_TO_ARRAY, CALL_FUNCTION);
1867 VisitForStackValue(subexpr);
1868 __ CallRuntime(Runtime::kAppendElement, 2);
1871 PrepareForBailoutForId(expr->GetIdForElement(array_index), NO_REGISTERS);
1875 __ Drop(1); // literal index
1876 context()->PlugTOS();
1878 context()->Plug(eax);
1883 void FullCodeGenerator::VisitAssignment(Assignment* expr) {
1884 DCHECK(expr->target()->IsValidReferenceExpression());
1886 Comment cmnt(masm_, "[ Assignment");
1888 Property* property = expr->target()->AsProperty();
1889 LhsKind assign_type = Property::GetAssignType(property);
1891 // Evaluate LHS expression.
1892 switch (assign_type) {
1894 // Nothing to do here.
1896 case NAMED_SUPER_PROPERTY:
1897 VisitForStackValue(property->obj()->AsSuperReference()->this_var());
1898 VisitForAccumulatorValue(
1899 property->obj()->AsSuperReference()->home_object());
1900 __ push(result_register());
1901 if (expr->is_compound()) {
1902 __ push(MemOperand(esp, kPointerSize));
1903 __ push(result_register());
1906 case NAMED_PROPERTY:
1907 if (expr->is_compound()) {
1908 // We need the receiver both on the stack and in the register.
1909 VisitForStackValue(property->obj());
1910 __ mov(LoadDescriptor::ReceiverRegister(), Operand(esp, 0));
1912 VisitForStackValue(property->obj());
1915 case KEYED_SUPER_PROPERTY:
1916 VisitForStackValue(property->obj()->AsSuperReference()->this_var());
1917 VisitForStackValue(property->obj()->AsSuperReference()->home_object());
1918 VisitForAccumulatorValue(property->key());
1919 __ Push(result_register());
1920 if (expr->is_compound()) {
1921 __ push(MemOperand(esp, 2 * kPointerSize));
1922 __ push(MemOperand(esp, 2 * kPointerSize));
1923 __ push(result_register());
1926 case KEYED_PROPERTY: {
1927 if (expr->is_compound()) {
1928 VisitForStackValue(property->obj());
1929 VisitForStackValue(property->key());
1930 __ mov(LoadDescriptor::ReceiverRegister(), Operand(esp, kPointerSize));
1931 __ mov(LoadDescriptor::NameRegister(), Operand(esp, 0));
1933 VisitForStackValue(property->obj());
1934 VisitForStackValue(property->key());
1940 // For compound assignments we need another deoptimization point after the
1941 // variable/property load.
1942 if (expr->is_compound()) {
1943 AccumulatorValueContext result_context(this);
1944 { AccumulatorValueContext left_operand_context(this);
1945 switch (assign_type) {
1947 EmitVariableLoad(expr->target()->AsVariableProxy());
1948 PrepareForBailout(expr->target(), TOS_REG);
1950 case NAMED_SUPER_PROPERTY:
1951 EmitNamedSuperPropertyLoad(property);
1952 PrepareForBailoutForId(property->LoadId(), TOS_REG);
1954 case NAMED_PROPERTY:
1955 EmitNamedPropertyLoad(property);
1956 PrepareForBailoutForId(property->LoadId(), TOS_REG);
1958 case KEYED_SUPER_PROPERTY:
1959 EmitKeyedSuperPropertyLoad(property);
1960 PrepareForBailoutForId(property->LoadId(), TOS_REG);
1962 case KEYED_PROPERTY:
1963 EmitKeyedPropertyLoad(property);
1964 PrepareForBailoutForId(property->LoadId(), TOS_REG);
1969 Token::Value op = expr->binary_op();
1970 __ push(eax); // Left operand goes on the stack.
1971 VisitForAccumulatorValue(expr->value());
1973 SetSourcePosition(expr->position() + 1);
1974 if (ShouldInlineSmiCase(op)) {
1975 EmitInlineSmiBinaryOp(expr->binary_operation(),
1980 EmitBinaryOp(expr->binary_operation(), op);
1983 // Deoptimization point in case the binary operation may have side effects.
1984 PrepareForBailout(expr->binary_operation(), TOS_REG);
1986 VisitForAccumulatorValue(expr->value());
1989 // Record source position before possible IC call.
1990 SetSourcePosition(expr->position());
1993 switch (assign_type) {
1995 EmitVariableAssignment(expr->target()->AsVariableProxy()->var(),
1996 expr->op(), expr->AssignmentSlot());
1997 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
1998 context()->Plug(eax);
2000 case NAMED_PROPERTY:
2001 EmitNamedPropertyAssignment(expr);
2003 case NAMED_SUPER_PROPERTY:
2004 EmitNamedSuperPropertyStore(property);
2005 context()->Plug(result_register());
2007 case KEYED_SUPER_PROPERTY:
2008 EmitKeyedSuperPropertyStore(property);
2009 context()->Plug(result_register());
2011 case KEYED_PROPERTY:
2012 EmitKeyedPropertyAssignment(expr);
2018 void FullCodeGenerator::VisitYield(Yield* expr) {
2019 Comment cmnt(masm_, "[ Yield");
2020 // Evaluate yielded value first; the initial iterator definition depends on
2021 // this. It stays on the stack while we update the iterator.
2022 VisitForStackValue(expr->expression());
2024 switch (expr->yield_kind()) {
2025 case Yield::kSuspend:
2026 // Pop value from top-of-stack slot; box result into result register.
2027 EmitCreateIteratorResult(false);
2028 __ push(result_register());
2030 case Yield::kInitial: {
2031 Label suspend, continuation, post_runtime, resume;
2035 __ bind(&continuation);
2039 VisitForAccumulatorValue(expr->generator_object());
2040 DCHECK(continuation.pos() > 0 && Smi::IsValid(continuation.pos()));
2041 __ mov(FieldOperand(eax, JSGeneratorObject::kContinuationOffset),
2042 Immediate(Smi::FromInt(continuation.pos())));
2043 __ mov(FieldOperand(eax, JSGeneratorObject::kContextOffset), esi);
2045 __ RecordWriteField(eax, JSGeneratorObject::kContextOffset, ecx, edx,
2047 __ lea(ebx, Operand(ebp, StandardFrameConstants::kExpressionsOffset));
2049 __ j(equal, &post_runtime);
2050 __ push(eax); // generator object
2051 __ CallRuntime(Runtime::kSuspendJSGeneratorObject, 1);
2052 __ mov(context_register(),
2053 Operand(ebp, StandardFrameConstants::kContextOffset));
2054 __ bind(&post_runtime);
2055 __ pop(result_register());
2056 EmitReturnSequence();
2059 context()->Plug(result_register());
2063 case Yield::kFinal: {
2064 VisitForAccumulatorValue(expr->generator_object());
2065 __ mov(FieldOperand(result_register(),
2066 JSGeneratorObject::kContinuationOffset),
2067 Immediate(Smi::FromInt(JSGeneratorObject::kGeneratorClosed)));
2068 // Pop value from top-of-stack slot, box result into result register.
2069 EmitCreateIteratorResult(true);
2070 EmitUnwindBeforeReturn();
2071 EmitReturnSequence();
2075 case Yield::kDelegating: {
2076 VisitForStackValue(expr->generator_object());
2078 // Initial stack layout is as follows:
2079 // [sp + 1 * kPointerSize] iter
2080 // [sp + 0 * kPointerSize] g
2082 Label l_catch, l_try, l_suspend, l_continuation, l_resume;
2083 Label l_next, l_call, l_loop;
2084 Register load_receiver = LoadDescriptor::ReceiverRegister();
2085 Register load_name = LoadDescriptor::NameRegister();
2087 // Initial send value is undefined.
2088 __ mov(eax, isolate()->factory()->undefined_value());
2091 // catch (e) { receiver = iter; f = 'throw'; arg = e; goto l_call; }
2093 __ mov(load_name, isolate()->factory()->throw_string()); // "throw"
2094 __ push(load_name); // "throw"
2095 __ push(Operand(esp, 2 * kPointerSize)); // iter
2096 __ push(eax); // exception
2099 // try { received = %yield result }
2100 // Shuffle the received result above a try handler and yield it without
2103 __ pop(eax); // result
2104 EnterTryBlock(expr->index(), &l_catch);
2105 const int try_block_size = TryCatch::kElementCount * kPointerSize;
2106 __ push(eax); // result
2108 __ bind(&l_continuation);
2110 __ bind(&l_suspend);
2111 const int generator_object_depth = kPointerSize + try_block_size;
2112 __ mov(eax, Operand(esp, generator_object_depth));
2114 __ push(Immediate(Smi::FromInt(expr->index()))); // handler-index
2115 DCHECK(l_continuation.pos() > 0 && Smi::IsValid(l_continuation.pos()));
2116 __ mov(FieldOperand(eax, JSGeneratorObject::kContinuationOffset),
2117 Immediate(Smi::FromInt(l_continuation.pos())));
2118 __ mov(FieldOperand(eax, JSGeneratorObject::kContextOffset), esi);
2120 __ RecordWriteField(eax, JSGeneratorObject::kContextOffset, ecx, edx,
2122 __ CallRuntime(Runtime::kSuspendJSGeneratorObject, 2);
2123 __ mov(context_register(),
2124 Operand(ebp, StandardFrameConstants::kContextOffset));
2125 __ pop(eax); // result
2126 EmitReturnSequence();
2127 __ bind(&l_resume); // received in eax
2128 ExitTryBlock(expr->index());
2130 // receiver = iter; f = iter.next; arg = received;
2133 __ mov(load_name, isolate()->factory()->next_string());
2134 __ push(load_name); // "next"
2135 __ push(Operand(esp, 2 * kPointerSize)); // iter
2136 __ push(eax); // received
2138 // result = receiver[f](arg);
2140 __ mov(load_receiver, Operand(esp, kPointerSize));
2141 __ mov(LoadDescriptor::SlotRegister(),
2142 Immediate(SmiFromSlot(expr->KeyedLoadFeedbackSlot())));
2143 Handle<Code> ic = CodeFactory::KeyedLoadIC(isolate()).code();
2144 CallIC(ic, TypeFeedbackId::None());
2146 __ mov(Operand(esp, 2 * kPointerSize), edi);
2147 CallFunctionStub stub(isolate(), 1, CALL_AS_METHOD);
2150 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
2151 __ Drop(1); // The function is still on the stack; drop it.
2153 // if (!result.done) goto l_try;
2155 __ push(eax); // save result
2156 __ Move(load_receiver, eax); // result
2158 isolate()->factory()->done_string()); // "done"
2159 __ mov(LoadDescriptor::SlotRegister(),
2160 Immediate(SmiFromSlot(expr->DoneFeedbackSlot())));
2161 CallLoadIC(NOT_CONTEXTUAL); // result.done in eax
2162 Handle<Code> bool_ic = ToBooleanStub::GetUninitialized(isolate());
2168 __ pop(load_receiver); // result
2170 isolate()->factory()->value_string()); // "value"
2171 __ mov(LoadDescriptor::SlotRegister(),
2172 Immediate(SmiFromSlot(expr->ValueFeedbackSlot())));
2173 CallLoadIC(NOT_CONTEXTUAL); // result.value in eax
2174 context()->DropAndPlug(2, eax); // drop iter and g
2181 void FullCodeGenerator::EmitGeneratorResume(Expression *generator,
2183 JSGeneratorObject::ResumeMode resume_mode) {
2184 // The value stays in eax, and is ultimately read by the resumed generator, as
2185 // if CallRuntime(Runtime::kSuspendJSGeneratorObject) returned it. Or it
2186 // is read to throw the value when the resumed generator is already closed.
2187 // ebx will hold the generator object until the activation has been resumed.
2188 VisitForStackValue(generator);
2189 VisitForAccumulatorValue(value);
2192 // Load suspended function and context.
2193 __ mov(esi, FieldOperand(ebx, JSGeneratorObject::kContextOffset));
2194 __ mov(edi, FieldOperand(ebx, JSGeneratorObject::kFunctionOffset));
2197 __ push(FieldOperand(ebx, JSGeneratorObject::kReceiverOffset));
2199 // Push holes for arguments to generator function.
2200 __ mov(edx, FieldOperand(edi, JSFunction::kSharedFunctionInfoOffset));
2202 FieldOperand(edx, SharedFunctionInfo::kFormalParameterCountOffset));
2203 __ mov(ecx, isolate()->factory()->the_hole_value());
2204 Label push_argument_holes, push_frame;
2205 __ bind(&push_argument_holes);
2206 __ sub(edx, Immediate(Smi::FromInt(1)));
2207 __ j(carry, &push_frame);
2209 __ jmp(&push_argument_holes);
2211 // Enter a new JavaScript frame, and initialize its slots as they were when
2212 // the generator was suspended.
2213 Label resume_frame, done;
2214 __ bind(&push_frame);
2215 __ call(&resume_frame);
2217 __ bind(&resume_frame);
2218 __ push(ebp); // Caller's frame pointer.
2220 __ push(esi); // Callee's context.
2221 __ push(edi); // Callee's JS Function.
2223 // Load the operand stack size.
2224 __ mov(edx, FieldOperand(ebx, JSGeneratorObject::kOperandStackOffset));
2225 __ mov(edx, FieldOperand(edx, FixedArray::kLengthOffset));
2228 // If we are sending a value and there is no operand stack, we can jump back
2230 if (resume_mode == JSGeneratorObject::NEXT) {
2232 __ cmp(edx, Immediate(0));
2233 __ j(not_zero, &slow_resume);
2234 __ mov(edx, FieldOperand(edi, JSFunction::kCodeEntryOffset));
2235 __ mov(ecx, FieldOperand(ebx, JSGeneratorObject::kContinuationOffset));
2238 __ mov(FieldOperand(ebx, JSGeneratorObject::kContinuationOffset),
2239 Immediate(Smi::FromInt(JSGeneratorObject::kGeneratorExecuting)));
2241 __ bind(&slow_resume);
2244 // Otherwise, we push holes for the operand stack and call the runtime to fix
2245 // up the stack and the handlers.
2246 Label push_operand_holes, call_resume;
2247 __ bind(&push_operand_holes);
2248 __ sub(edx, Immediate(1));
2249 __ j(carry, &call_resume);
2251 __ jmp(&push_operand_holes);
2252 __ bind(&call_resume);
2254 __ push(result_register());
2255 __ Push(Smi::FromInt(resume_mode));
2256 __ CallRuntime(Runtime::kResumeJSGeneratorObject, 3);
2257 // Not reached: the runtime call returns elsewhere.
2258 __ Abort(kGeneratorFailedToResume);
2261 context()->Plug(result_register());
2265 void FullCodeGenerator::EmitCreateIteratorResult(bool done) {
2269 const int instance_size = 5 * kPointerSize;
2270 DCHECK_EQ(isolate()->native_context()->iterator_result_map()->instance_size(),
2273 __ Allocate(instance_size, eax, ecx, edx, &gc_required, TAG_OBJECT);
2276 __ bind(&gc_required);
2277 __ Push(Smi::FromInt(instance_size));
2278 __ CallRuntime(Runtime::kAllocateInNewSpace, 1);
2279 __ mov(context_register(),
2280 Operand(ebp, StandardFrameConstants::kContextOffset));
2282 __ bind(&allocated);
2283 __ mov(ebx, Operand(esi, Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX)));
2284 __ mov(ebx, FieldOperand(ebx, GlobalObject::kNativeContextOffset));
2285 __ mov(ebx, ContextOperand(ebx, Context::ITERATOR_RESULT_MAP_INDEX));
2287 __ mov(edx, isolate()->factory()->ToBoolean(done));
2288 __ mov(FieldOperand(eax, HeapObject::kMapOffset), ebx);
2289 __ mov(FieldOperand(eax, JSObject::kPropertiesOffset),
2290 isolate()->factory()->empty_fixed_array());
2291 __ mov(FieldOperand(eax, JSObject::kElementsOffset),
2292 isolate()->factory()->empty_fixed_array());
2293 __ mov(FieldOperand(eax, JSGeneratorObject::kResultValuePropertyOffset), ecx);
2294 __ mov(FieldOperand(eax, JSGeneratorObject::kResultDonePropertyOffset), edx);
2296 // Only the value field needs a write barrier, as the other values are in the
2298 __ RecordWriteField(eax, JSGeneratorObject::kResultValuePropertyOffset, ecx,
2299 edx, kDontSaveFPRegs);
2303 void FullCodeGenerator::EmitNamedPropertyLoad(Property* prop) {
2304 SetSourcePosition(prop->position());
2305 Literal* key = prop->key()->AsLiteral();
2306 DCHECK(!key->value()->IsSmi());
2307 DCHECK(!prop->IsSuperAccess());
2309 __ mov(LoadDescriptor::NameRegister(), Immediate(key->value()));
2310 __ mov(LoadDescriptor::SlotRegister(),
2311 Immediate(SmiFromSlot(prop->PropertyFeedbackSlot())));
2312 CallLoadIC(NOT_CONTEXTUAL);
2316 void FullCodeGenerator::EmitNamedSuperPropertyLoad(Property* prop) {
2317 // Stack: receiver, home_object.
2318 SetSourcePosition(prop->position());
2319 Literal* key = prop->key()->AsLiteral();
2320 DCHECK(!key->value()->IsSmi());
2321 DCHECK(prop->IsSuperAccess());
2323 __ push(Immediate(key->value()));
2324 __ CallRuntime(Runtime::kLoadFromSuper, 3);
2328 void FullCodeGenerator::EmitKeyedPropertyLoad(Property* prop) {
2329 SetSourcePosition(prop->position());
2330 Handle<Code> ic = CodeFactory::KeyedLoadIC(isolate()).code();
2331 __ mov(LoadDescriptor::SlotRegister(),
2332 Immediate(SmiFromSlot(prop->PropertyFeedbackSlot())));
2337 void FullCodeGenerator::EmitKeyedSuperPropertyLoad(Property* prop) {
2338 // Stack: receiver, home_object, key.
2339 SetSourcePosition(prop->position());
2341 __ CallRuntime(Runtime::kLoadKeyedFromSuper, 3);
2345 void FullCodeGenerator::EmitInlineSmiBinaryOp(BinaryOperation* expr,
2348 Expression* right) {
2349 // Do combined smi check of the operands. Left operand is on the
2350 // stack. Right operand is in eax.
2351 Label smi_case, done, stub_call;
2355 JumpPatchSite patch_site(masm_);
2356 patch_site.EmitJumpIfSmi(eax, &smi_case, Label::kNear);
2358 __ bind(&stub_call);
2360 Handle<Code> code = CodeFactory::BinaryOpIC(
2361 isolate(), op, language_mode()).code();
2362 CallIC(code, expr->BinaryOperationFeedbackId());
2363 patch_site.EmitPatchInfo();
2364 __ jmp(&done, Label::kNear);
2368 __ mov(eax, edx); // Copy left operand in case of a stub call.
2373 __ sar_cl(eax); // No checks of result necessary
2374 __ and_(eax, Immediate(~kSmiTagMask));
2381 // Check that the *signed* result fits in a smi.
2382 __ cmp(eax, 0xc0000000);
2383 __ j(positive, &result_ok);
2386 __ bind(&result_ok);
2395 __ test(eax, Immediate(0xc0000000));
2396 __ j(zero, &result_ok);
2399 __ bind(&result_ok);
2405 __ j(overflow, &stub_call);
2409 __ j(overflow, &stub_call);
2414 __ j(overflow, &stub_call);
2416 __ j(not_zero, &done, Label::kNear);
2419 __ j(negative, &stub_call);
2425 case Token::BIT_AND:
2428 case Token::BIT_XOR:
2436 context()->Plug(eax);
2440 void FullCodeGenerator::EmitClassDefineProperties(ClassLiteral* lit) {
2441 // Constructor is in eax.
2442 DCHECK(lit != NULL);
2445 // No access check is needed here since the constructor is created by the
2447 Register scratch = ebx;
2448 __ mov(scratch, FieldOperand(eax, JSFunction::kPrototypeOrInitialMapOffset));
2451 for (int i = 0; i < lit->properties()->length(); i++) {
2452 ObjectLiteral::Property* property = lit->properties()->at(i);
2453 Expression* value = property->value();
2455 if (property->is_static()) {
2456 __ push(Operand(esp, kPointerSize)); // constructor
2458 __ push(Operand(esp, 0)); // prototype
2460 EmitPropertyKey(property, lit->GetIdForProperty(i));
2462 // The static prototype property is read only. We handle the non computed
2463 // property name case in the parser. Since this is the only case where we
2464 // need to check for an own read only property we special case this so we do
2465 // not need to do this for every property.
2466 if (property->is_static() && property->is_computed_name()) {
2467 __ CallRuntime(Runtime::kThrowIfStaticPrototype, 1);
2471 VisitForStackValue(value);
2472 EmitSetHomeObjectIfNeeded(value, 2);
2474 switch (property->kind()) {
2475 case ObjectLiteral::Property::CONSTANT:
2476 case ObjectLiteral::Property::MATERIALIZED_LITERAL:
2477 case ObjectLiteral::Property::PROTOTYPE:
2479 case ObjectLiteral::Property::COMPUTED:
2480 __ CallRuntime(Runtime::kDefineClassMethod, 3);
2483 case ObjectLiteral::Property::GETTER:
2484 __ push(Immediate(Smi::FromInt(DONT_ENUM)));
2485 __ CallRuntime(Runtime::kDefineGetterPropertyUnchecked, 4);
2488 case ObjectLiteral::Property::SETTER:
2489 __ push(Immediate(Smi::FromInt(DONT_ENUM)));
2490 __ CallRuntime(Runtime::kDefineSetterPropertyUnchecked, 4);
2496 __ CallRuntime(Runtime::kToFastProperties, 1);
2499 __ CallRuntime(Runtime::kToFastProperties, 1);
2503 void FullCodeGenerator::EmitBinaryOp(BinaryOperation* expr, Token::Value op) {
2505 Handle<Code> code = CodeFactory::BinaryOpIC(
2506 isolate(), op, language_mode()).code();
2507 JumpPatchSite patch_site(masm_); // unbound, signals no inlined smi code.
2508 CallIC(code, expr->BinaryOperationFeedbackId());
2509 patch_site.EmitPatchInfo();
2510 context()->Plug(eax);
2514 void FullCodeGenerator::EmitAssignment(Expression* expr,
2515 FeedbackVectorICSlot slot) {
2516 DCHECK(expr->IsValidReferenceExpression());
2518 Property* prop = expr->AsProperty();
2519 LhsKind assign_type = Property::GetAssignType(prop);
2521 switch (assign_type) {
2523 Variable* var = expr->AsVariableProxy()->var();
2524 EffectContext context(this);
2525 EmitVariableAssignment(var, Token::ASSIGN, slot);
2528 case NAMED_PROPERTY: {
2529 __ push(eax); // Preserve value.
2530 VisitForAccumulatorValue(prop->obj());
2531 __ Move(StoreDescriptor::ReceiverRegister(), eax);
2532 __ pop(StoreDescriptor::ValueRegister()); // Restore value.
2533 __ mov(StoreDescriptor::NameRegister(),
2534 prop->key()->AsLiteral()->value());
2535 if (FLAG_vector_stores) EmitLoadStoreICSlot(slot);
2539 case NAMED_SUPER_PROPERTY: {
2541 VisitForStackValue(prop->obj()->AsSuperReference()->this_var());
2542 VisitForAccumulatorValue(prop->obj()->AsSuperReference()->home_object());
2543 // stack: value, this; eax: home_object
2544 Register scratch = ecx;
2545 Register scratch2 = edx;
2546 __ mov(scratch, result_register()); // home_object
2547 __ mov(eax, MemOperand(esp, kPointerSize)); // value
2548 __ mov(scratch2, MemOperand(esp, 0)); // this
2549 __ mov(MemOperand(esp, kPointerSize), scratch2); // this
2550 __ mov(MemOperand(esp, 0), scratch); // home_object
2551 // stack: this, home_object. eax: value
2552 EmitNamedSuperPropertyStore(prop);
2555 case KEYED_SUPER_PROPERTY: {
2557 VisitForStackValue(prop->obj()->AsSuperReference()->this_var());
2558 VisitForStackValue(prop->obj()->AsSuperReference()->home_object());
2559 VisitForAccumulatorValue(prop->key());
2560 Register scratch = ecx;
2561 Register scratch2 = edx;
2562 __ mov(scratch2, MemOperand(esp, 2 * kPointerSize)); // value
2563 // stack: value, this, home_object; eax: key, edx: value
2564 __ mov(scratch, MemOperand(esp, kPointerSize)); // this
2565 __ mov(MemOperand(esp, 2 * kPointerSize), scratch);
2566 __ mov(scratch, MemOperand(esp, 0)); // home_object
2567 __ mov(MemOperand(esp, kPointerSize), scratch);
2568 __ mov(MemOperand(esp, 0), eax);
2569 __ mov(eax, scratch2);
2570 // stack: this, home_object, key; eax: value.
2571 EmitKeyedSuperPropertyStore(prop);
2574 case KEYED_PROPERTY: {
2575 __ push(eax); // Preserve value.
2576 VisitForStackValue(prop->obj());
2577 VisitForAccumulatorValue(prop->key());
2578 __ Move(StoreDescriptor::NameRegister(), eax);
2579 __ pop(StoreDescriptor::ReceiverRegister()); // Receiver.
2580 __ pop(StoreDescriptor::ValueRegister()); // Restore value.
2581 if (FLAG_vector_stores) EmitLoadStoreICSlot(slot);
2583 CodeFactory::KeyedStoreIC(isolate(), language_mode()).code();
2588 context()->Plug(eax);
2592 void FullCodeGenerator::EmitStoreToStackLocalOrContextSlot(
2593 Variable* var, MemOperand location) {
2594 __ mov(location, eax);
2595 if (var->IsContextSlot()) {
2597 int offset = Context::SlotOffset(var->index());
2598 __ RecordWriteContextSlot(ecx, offset, edx, ebx, kDontSaveFPRegs);
2603 void FullCodeGenerator::EmitVariableAssignment(Variable* var, Token::Value op,
2604 FeedbackVectorICSlot slot) {
2605 if (var->IsUnallocated()) {
2606 // Global var, const, or let.
2607 __ mov(StoreDescriptor::NameRegister(), var->name());
2608 __ mov(StoreDescriptor::ReceiverRegister(), GlobalObjectOperand());
2609 if (FLAG_vector_stores) EmitLoadStoreICSlot(slot);
2612 } else if (var->mode() == LET && op != Token::INIT_LET) {
2613 // Non-initializing assignment to let variable needs a write barrier.
2614 DCHECK(!var->IsLookupSlot());
2615 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
2617 MemOperand location = VarOperand(var, ecx);
2618 __ mov(edx, location);
2619 __ cmp(edx, isolate()->factory()->the_hole_value());
2620 __ j(not_equal, &assign, Label::kNear);
2621 __ push(Immediate(var->name()));
2622 __ CallRuntime(Runtime::kThrowReferenceError, 1);
2624 EmitStoreToStackLocalOrContextSlot(var, location);
2626 } else if (var->mode() == CONST && op != Token::INIT_CONST) {
2627 // Assignment to const variable needs a write barrier.
2628 DCHECK(!var->IsLookupSlot());
2629 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
2631 MemOperand location = VarOperand(var, ecx);
2632 __ mov(edx, location);
2633 __ cmp(edx, isolate()->factory()->the_hole_value());
2634 __ j(not_equal, &const_error, Label::kNear);
2635 __ push(Immediate(var->name()));
2636 __ CallRuntime(Runtime::kThrowReferenceError, 1);
2637 __ bind(&const_error);
2638 __ CallRuntime(Runtime::kThrowConstAssignError, 0);
2640 } else if (!var->is_const_mode() || op == Token::INIT_CONST) {
2641 if (var->IsLookupSlot()) {
2642 // Assignment to var.
2643 __ push(eax); // Value.
2644 __ push(esi); // Context.
2645 __ push(Immediate(var->name()));
2646 __ push(Immediate(Smi::FromInt(language_mode())));
2647 __ CallRuntime(Runtime::kStoreLookupSlot, 4);
2649 // Assignment to var or initializing assignment to let/const in harmony
2651 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
2652 MemOperand location = VarOperand(var, ecx);
2653 if (generate_debug_code_ && op == Token::INIT_LET) {
2654 // Check for an uninitialized let binding.
2655 __ mov(edx, location);
2656 __ cmp(edx, isolate()->factory()->the_hole_value());
2657 __ Check(equal, kLetBindingReInitialization);
2659 EmitStoreToStackLocalOrContextSlot(var, location);
2662 } else if (op == Token::INIT_CONST_LEGACY) {
2663 // Const initializers need a write barrier.
2664 DCHECK(var->mode() == CONST_LEGACY);
2665 DCHECK(!var->IsParameter()); // No const parameters.
2666 if (var->IsLookupSlot()) {
2669 __ push(Immediate(var->name()));
2670 __ CallRuntime(Runtime::kInitializeLegacyConstLookupSlot, 3);
2672 DCHECK(var->IsStackLocal() || var->IsContextSlot());
2674 MemOperand location = VarOperand(var, ecx);
2675 __ mov(edx, location);
2676 __ cmp(edx, isolate()->factory()->the_hole_value());
2677 __ j(not_equal, &skip, Label::kNear);
2678 EmitStoreToStackLocalOrContextSlot(var, location);
2683 DCHECK(var->mode() == CONST_LEGACY && op != Token::INIT_CONST_LEGACY);
2684 if (is_strict(language_mode())) {
2685 __ CallRuntime(Runtime::kThrowConstAssignError, 0);
2687 // Silently ignore store in sloppy mode.
2692 void FullCodeGenerator::EmitNamedPropertyAssignment(Assignment* expr) {
2693 // Assignment to a property, using a named store IC.
2695 // esp[0] : receiver
2697 Property* prop = expr->target()->AsProperty();
2698 DCHECK(prop != NULL);
2699 DCHECK(prop->key()->IsLiteral());
2701 // Record source code position before IC call.
2702 SetSourcePosition(expr->position());
2703 __ mov(StoreDescriptor::NameRegister(), prop->key()->AsLiteral()->value());
2704 __ pop(StoreDescriptor::ReceiverRegister());
2705 if (FLAG_vector_stores) {
2706 EmitLoadStoreICSlot(expr->AssignmentSlot());
2709 CallStoreIC(expr->AssignmentFeedbackId());
2711 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
2712 context()->Plug(eax);
2716 void FullCodeGenerator::EmitNamedSuperPropertyStore(Property* prop) {
2717 // Assignment to named property of super.
2719 // stack : receiver ('this'), home_object
2720 DCHECK(prop != NULL);
2721 Literal* key = prop->key()->AsLiteral();
2722 DCHECK(key != NULL);
2724 __ push(Immediate(key->value()));
2726 __ CallRuntime((is_strict(language_mode()) ? Runtime::kStoreToSuper_Strict
2727 : Runtime::kStoreToSuper_Sloppy),
2732 void FullCodeGenerator::EmitKeyedSuperPropertyStore(Property* prop) {
2733 // Assignment to named property of super.
2735 // stack : receiver ('this'), home_object, key
2739 (is_strict(language_mode()) ? Runtime::kStoreKeyedToSuper_Strict
2740 : Runtime::kStoreKeyedToSuper_Sloppy),
2745 void FullCodeGenerator::EmitKeyedPropertyAssignment(Assignment* expr) {
2746 // Assignment to a property, using a keyed store IC.
2749 // esp[kPointerSize] : receiver
2751 __ pop(StoreDescriptor::NameRegister()); // Key.
2752 __ pop(StoreDescriptor::ReceiverRegister());
2753 DCHECK(StoreDescriptor::ValueRegister().is(eax));
2754 // Record source code position before IC call.
2755 SetSourcePosition(expr->position());
2757 CodeFactory::KeyedStoreIC(isolate(), language_mode()).code();
2758 if (FLAG_vector_stores) {
2759 EmitLoadStoreICSlot(expr->AssignmentSlot());
2762 CallIC(ic, expr->AssignmentFeedbackId());
2765 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
2766 context()->Plug(eax);
2770 void FullCodeGenerator::VisitProperty(Property* expr) {
2771 Comment cmnt(masm_, "[ Property");
2772 Expression* key = expr->key();
2774 if (key->IsPropertyName()) {
2775 if (!expr->IsSuperAccess()) {
2776 VisitForAccumulatorValue(expr->obj());
2777 __ Move(LoadDescriptor::ReceiverRegister(), result_register());
2778 EmitNamedPropertyLoad(expr);
2780 VisitForStackValue(expr->obj()->AsSuperReference()->this_var());
2781 VisitForStackValue(expr->obj()->AsSuperReference()->home_object());
2782 EmitNamedSuperPropertyLoad(expr);
2785 if (!expr->IsSuperAccess()) {
2786 VisitForStackValue(expr->obj());
2787 VisitForAccumulatorValue(expr->key());
2788 __ pop(LoadDescriptor::ReceiverRegister()); // Object.
2789 __ Move(LoadDescriptor::NameRegister(), result_register()); // Key.
2790 EmitKeyedPropertyLoad(expr);
2792 VisitForStackValue(expr->obj()->AsSuperReference()->this_var());
2793 VisitForStackValue(expr->obj()->AsSuperReference()->home_object());
2794 VisitForStackValue(expr->key());
2795 EmitKeyedSuperPropertyLoad(expr);
2798 PrepareForBailoutForId(expr->LoadId(), TOS_REG);
2799 context()->Plug(eax);
2803 void FullCodeGenerator::CallIC(Handle<Code> code,
2804 TypeFeedbackId ast_id) {
2806 __ call(code, RelocInfo::CODE_TARGET, ast_id);
2810 // Code common for calls using the IC.
2811 void FullCodeGenerator::EmitCallWithLoadIC(Call* expr) {
2812 Expression* callee = expr->expression();
2814 CallICState::CallType call_type =
2815 callee->IsVariableProxy() ? CallICState::FUNCTION : CallICState::METHOD;
2816 // Get the target function.
2817 if (call_type == CallICState::FUNCTION) {
2818 { StackValueContext context(this);
2819 EmitVariableLoad(callee->AsVariableProxy());
2820 PrepareForBailout(callee, NO_REGISTERS);
2822 // Push undefined as receiver. This is patched in the method prologue if it
2823 // is a sloppy mode method.
2824 __ push(Immediate(isolate()->factory()->undefined_value()));
2826 // Load the function from the receiver.
2827 DCHECK(callee->IsProperty());
2828 DCHECK(!callee->AsProperty()->IsSuperAccess());
2829 __ mov(LoadDescriptor::ReceiverRegister(), Operand(esp, 0));
2830 EmitNamedPropertyLoad(callee->AsProperty());
2831 PrepareForBailoutForId(callee->AsProperty()->LoadId(), TOS_REG);
2832 // Push the target function under the receiver.
2833 __ push(Operand(esp, 0));
2834 __ mov(Operand(esp, kPointerSize), eax);
2837 EmitCall(expr, call_type);
2841 void FullCodeGenerator::EmitSuperCallWithLoadIC(Call* expr) {
2842 Expression* callee = expr->expression();
2843 DCHECK(callee->IsProperty());
2844 Property* prop = callee->AsProperty();
2845 DCHECK(prop->IsSuperAccess());
2847 SetSourcePosition(prop->position());
2848 Literal* key = prop->key()->AsLiteral();
2849 DCHECK(!key->value()->IsSmi());
2850 // Load the function from the receiver.
2851 SuperReference* super_ref = callee->AsProperty()->obj()->AsSuperReference();
2852 VisitForStackValue(super_ref->home_object());
2853 VisitForAccumulatorValue(super_ref->this_var());
2856 __ push(Operand(esp, kPointerSize * 2));
2857 __ push(Immediate(key->value()));
2860 // - this (receiver)
2861 // - this (receiver) <-- LoadFromSuper will pop here and below.
2864 __ CallRuntime(Runtime::kLoadFromSuper, 3);
2866 // Replace home_object with target function.
2867 __ mov(Operand(esp, kPointerSize), eax);
2870 // - target function
2871 // - this (receiver)
2872 EmitCall(expr, CallICState::METHOD);
2876 // Code common for calls using the IC.
2877 void FullCodeGenerator::EmitKeyedCallWithLoadIC(Call* expr,
2880 VisitForAccumulatorValue(key);
2882 Expression* callee = expr->expression();
2884 // Load the function from the receiver.
2885 DCHECK(callee->IsProperty());
2886 __ mov(LoadDescriptor::ReceiverRegister(), Operand(esp, 0));
2887 __ mov(LoadDescriptor::NameRegister(), eax);
2888 EmitKeyedPropertyLoad(callee->AsProperty());
2889 PrepareForBailoutForId(callee->AsProperty()->LoadId(), TOS_REG);
2891 // Push the target function under the receiver.
2892 __ push(Operand(esp, 0));
2893 __ mov(Operand(esp, kPointerSize), eax);
2895 EmitCall(expr, CallICState::METHOD);
2899 void FullCodeGenerator::EmitKeyedSuperCallWithLoadIC(Call* expr) {
2900 Expression* callee = expr->expression();
2901 DCHECK(callee->IsProperty());
2902 Property* prop = callee->AsProperty();
2903 DCHECK(prop->IsSuperAccess());
2905 SetSourcePosition(prop->position());
2906 // Load the function from the receiver.
2907 SuperReference* super_ref = callee->AsProperty()->obj()->AsSuperReference();
2908 VisitForStackValue(super_ref->home_object());
2909 VisitForAccumulatorValue(super_ref->this_var());
2912 __ push(Operand(esp, kPointerSize * 2));
2913 VisitForStackValue(prop->key());
2916 // - this (receiver)
2917 // - this (receiver) <-- LoadKeyedFromSuper will pop here and below.
2920 __ CallRuntime(Runtime::kLoadKeyedFromSuper, 3);
2922 // Replace home_object with target function.
2923 __ mov(Operand(esp, kPointerSize), eax);
2926 // - target function
2927 // - this (receiver)
2928 EmitCall(expr, CallICState::METHOD);
2932 void FullCodeGenerator::EmitCall(Call* expr, CallICState::CallType call_type) {
2933 // Load the arguments.
2934 ZoneList<Expression*>* args = expr->arguments();
2935 int arg_count = args->length();
2936 { PreservePositionScope scope(masm()->positions_recorder());
2937 for (int i = 0; i < arg_count; i++) {
2938 VisitForStackValue(args->at(i));
2942 // Record source position of the IC call.
2943 SetSourcePosition(expr->position());
2944 Handle<Code> ic = CodeFactory::CallIC(isolate(), arg_count, call_type).code();
2945 __ Move(edx, Immediate(SmiFromSlot(expr->CallFeedbackICSlot())));
2946 __ mov(edi, Operand(esp, (arg_count + 1) * kPointerSize));
2947 // Don't assign a type feedback id to the IC, since type feedback is provided
2948 // by the vector above.
2951 RecordJSReturnSite(expr);
2953 // Restore context register.
2954 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
2956 context()->DropAndPlug(1, eax);
2960 void FullCodeGenerator::EmitResolvePossiblyDirectEval(int arg_count) {
2961 // Push copy of the first argument or undefined if it doesn't exist.
2962 if (arg_count > 0) {
2963 __ push(Operand(esp, arg_count * kPointerSize));
2965 __ push(Immediate(isolate()->factory()->undefined_value()));
2968 // Push the enclosing function.
2969 __ push(Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
2970 // Push the receiver of the enclosing function.
2971 Variable* this_var = scope()->LookupThis();
2972 DCHECK_NOT_NULL(this_var);
2973 __ push(VarOperand(this_var, ecx));
2974 // Push the language mode.
2975 __ push(Immediate(Smi::FromInt(language_mode())));
2977 // Push the start position of the scope the calls resides in.
2978 __ push(Immediate(Smi::FromInt(scope()->start_position())));
2980 // Do the runtime call.
2981 __ CallRuntime(Runtime::kResolvePossiblyDirectEval, 6);
2985 void FullCodeGenerator::EmitLoadSuperConstructor() {
2986 __ push(Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
2987 __ CallRuntime(Runtime::kGetPrototype, 1);
2991 void FullCodeGenerator::EmitInitializeThisAfterSuper(
2992 SuperReference* super_ref, FeedbackVectorICSlot slot) {
2993 Variable* this_var = super_ref->this_var()->var();
2994 GetVar(ecx, this_var);
2995 __ cmp(ecx, isolate()->factory()->the_hole_value());
2996 Label uninitialized_this;
2997 __ j(equal, &uninitialized_this);
2998 __ push(Immediate(this_var->name()));
2999 __ CallRuntime(Runtime::kThrowReferenceError, 1);
3000 __ bind(&uninitialized_this);
3002 EmitVariableAssignment(this_var, Token::INIT_CONST, slot);
3006 void FullCodeGenerator::VisitCall(Call* expr) {
3008 // We want to verify that RecordJSReturnSite gets called on all paths
3009 // through this function. Avoid early returns.
3010 expr->return_is_recorded_ = false;
3013 Comment cmnt(masm_, "[ Call");
3014 Expression* callee = expr->expression();
3015 Call::CallType call_type = expr->GetCallType(isolate());
3017 if (call_type == Call::POSSIBLY_EVAL_CALL) {
3018 // In a call to eval, we first call RuntimeHidden_ResolvePossiblyDirectEval
3019 // to resolve the function we need to call and the receiver of the call.
3020 // Then we call the resolved function using the given arguments.
3021 ZoneList<Expression*>* args = expr->arguments();
3022 int arg_count = args->length();
3023 { PreservePositionScope pos_scope(masm()->positions_recorder());
3024 VisitForStackValue(callee);
3025 // Reserved receiver slot.
3026 __ push(Immediate(isolate()->factory()->undefined_value()));
3027 // Push the arguments.
3028 for (int i = 0; i < arg_count; i++) {
3029 VisitForStackValue(args->at(i));
3032 // Push a copy of the function (found below the arguments) and
3034 __ push(Operand(esp, (arg_count + 1) * kPointerSize));
3035 EmitResolvePossiblyDirectEval(arg_count);
3037 // The runtime call returns a pair of values in eax (function) and
3038 // edx (receiver). Touch up the stack with the right values.
3039 __ mov(Operand(esp, (arg_count + 0) * kPointerSize), edx);
3040 __ mov(Operand(esp, (arg_count + 1) * kPointerSize), eax);
3042 PrepareForBailoutForId(expr->EvalOrLookupId(), NO_REGISTERS);
3044 // Record source position for debugger.
3045 SetSourcePosition(expr->position());
3046 CallFunctionStub stub(isolate(), arg_count, NO_CALL_FUNCTION_FLAGS);
3047 __ mov(edi, Operand(esp, (arg_count + 1) * kPointerSize));
3049 RecordJSReturnSite(expr);
3050 // Restore context register.
3051 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
3052 context()->DropAndPlug(1, eax);
3054 } else if (call_type == Call::GLOBAL_CALL) {
3055 EmitCallWithLoadIC(expr);
3056 } else if (call_type == Call::LOOKUP_SLOT_CALL) {
3057 // Call to a lookup slot (dynamically introduced variable).
3058 VariableProxy* proxy = callee->AsVariableProxy();
3060 { PreservePositionScope scope(masm()->positions_recorder());
3061 // Generate code for loading from variables potentially shadowed by
3062 // eval-introduced variables.
3063 EmitDynamicLookupFastCase(proxy, NOT_INSIDE_TYPEOF, &slow, &done);
3066 // Call the runtime to find the function to call (returned in eax) and
3067 // the object holding it (returned in edx).
3068 __ push(context_register());
3069 __ push(Immediate(proxy->name()));
3070 __ CallRuntime(Runtime::kLoadLookupSlot, 2);
3071 __ push(eax); // Function.
3072 __ push(edx); // Receiver.
3073 PrepareForBailoutForId(expr->EvalOrLookupId(), NO_REGISTERS);
3075 // If fast case code has been generated, emit code to push the function
3076 // and receiver and have the slow path jump around this code.
3077 if (done.is_linked()) {
3079 __ jmp(&call, Label::kNear);
3083 // The receiver is implicitly the global receiver. Indicate this by
3084 // passing the hole to the call function stub.
3085 __ push(Immediate(isolate()->factory()->undefined_value()));
3089 // The receiver is either the global receiver or an object found by
3093 } else if (call_type == Call::PROPERTY_CALL) {
3094 Property* property = callee->AsProperty();
3095 bool is_named_call = property->key()->IsPropertyName();
3096 if (property->IsSuperAccess()) {
3097 if (is_named_call) {
3098 EmitSuperCallWithLoadIC(expr);
3100 EmitKeyedSuperCallWithLoadIC(expr);
3104 PreservePositionScope scope(masm()->positions_recorder());
3105 VisitForStackValue(property->obj());
3107 if (is_named_call) {
3108 EmitCallWithLoadIC(expr);
3110 EmitKeyedCallWithLoadIC(expr, property->key());
3113 } else if (call_type == Call::SUPER_CALL) {
3114 EmitSuperConstructorCall(expr);
3116 DCHECK(call_type == Call::OTHER_CALL);
3117 // Call to an arbitrary expression not handled specially above.
3118 { PreservePositionScope scope(masm()->positions_recorder());
3119 VisitForStackValue(callee);
3121 __ push(Immediate(isolate()->factory()->undefined_value()));
3122 // Emit function call.
3127 // RecordJSReturnSite should have been called.
3128 DCHECK(expr->return_is_recorded_);
3133 void FullCodeGenerator::VisitCallNew(CallNew* expr) {
3134 Comment cmnt(masm_, "[ CallNew");
3135 // According to ECMA-262, section 11.2.2, page 44, the function
3136 // expression in new calls must be evaluated before the
3139 // Push constructor on the stack. If it's not a function it's used as
3140 // receiver for CALL_NON_FUNCTION, otherwise the value on the stack is
3142 DCHECK(!expr->expression()->IsSuperReference());
3143 VisitForStackValue(expr->expression());
3145 // Push the arguments ("left-to-right") on the stack.
3146 ZoneList<Expression*>* args = expr->arguments();
3147 int arg_count = args->length();
3148 for (int i = 0; i < arg_count; i++) {
3149 VisitForStackValue(args->at(i));
3152 // Call the construct call builtin that handles allocation and
3153 // constructor invocation.
3154 SetSourcePosition(expr->position());
3156 // Load function and argument count into edi and eax.
3157 __ Move(eax, Immediate(arg_count));
3158 __ mov(edi, Operand(esp, arg_count * kPointerSize));
3160 // Record call targets in unoptimized code.
3161 if (FLAG_pretenuring_call_new) {
3162 EnsureSlotContainsAllocationSite(expr->AllocationSiteFeedbackSlot());
3163 DCHECK(expr->AllocationSiteFeedbackSlot().ToInt() ==
3164 expr->CallNewFeedbackSlot().ToInt() + 1);
3167 __ LoadHeapObject(ebx, FeedbackVector());
3168 __ mov(edx, Immediate(SmiFromSlot(expr->CallNewFeedbackSlot())));
3170 CallConstructStub stub(isolate(), RECORD_CONSTRUCTOR_TARGET);
3171 __ call(stub.GetCode(), RelocInfo::CONSTRUCT_CALL);
3172 PrepareForBailoutForId(expr->ReturnId(), TOS_REG);
3173 context()->Plug(eax);
3177 void FullCodeGenerator::EmitSuperConstructorCall(Call* expr) {
3178 Variable* new_target_var = scope()->DeclarationScope()->new_target_var();
3179 GetVar(eax, new_target_var);
3182 EmitLoadSuperConstructor();
3183 __ push(result_register());
3185 // Push the arguments ("left-to-right") on the stack.
3186 ZoneList<Expression*>* args = expr->arguments();
3187 int arg_count = args->length();
3188 for (int i = 0; i < arg_count; i++) {
3189 VisitForStackValue(args->at(i));
3192 // Call the construct call builtin that handles allocation and
3193 // constructor invocation.
3194 SetSourcePosition(expr->position());
3196 // Load function and argument count into edi and eax.
3197 __ Move(eax, Immediate(arg_count));
3198 __ mov(edi, Operand(esp, arg_count * kPointerSize));
3200 // Record call targets in unoptimized code.
3201 if (FLAG_pretenuring_call_new) {
3203 /* TODO(dslomov): support pretenuring.
3204 EnsureSlotContainsAllocationSite(expr->AllocationSiteFeedbackSlot());
3205 DCHECK(expr->AllocationSiteFeedbackSlot().ToInt() ==
3206 expr->CallNewFeedbackSlot().ToInt() + 1);
3210 __ LoadHeapObject(ebx, FeedbackVector());
3211 __ mov(edx, Immediate(SmiFromSlot(expr->CallFeedbackSlot())));
3213 CallConstructStub stub(isolate(), SUPER_CALL_RECORD_TARGET);
3214 __ call(stub.GetCode(), RelocInfo::CONSTRUCT_CALL);
3218 RecordJSReturnSite(expr);
3220 EmitInitializeThisAfterSuper(expr->expression()->AsSuperReference(),
3221 expr->CallFeedbackICSlot());
3222 context()->Plug(eax);
3226 void FullCodeGenerator::EmitIsSmi(CallRuntime* expr) {
3227 ZoneList<Expression*>* args = expr->arguments();
3228 DCHECK(args->length() == 1);
3230 VisitForAccumulatorValue(args->at(0));
3232 Label materialize_true, materialize_false;
3233 Label* if_true = NULL;
3234 Label* if_false = NULL;
3235 Label* fall_through = NULL;
3236 context()->PrepareTest(&materialize_true, &materialize_false,
3237 &if_true, &if_false, &fall_through);
3239 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3240 __ test(eax, Immediate(kSmiTagMask));
3241 Split(zero, if_true, if_false, fall_through);
3243 context()->Plug(if_true, if_false);
3247 void FullCodeGenerator::EmitIsNonNegativeSmi(CallRuntime* expr) {
3248 ZoneList<Expression*>* args = expr->arguments();
3249 DCHECK(args->length() == 1);
3251 VisitForAccumulatorValue(args->at(0));
3253 Label materialize_true, materialize_false;
3254 Label* if_true = NULL;
3255 Label* if_false = NULL;
3256 Label* fall_through = NULL;
3257 context()->PrepareTest(&materialize_true, &materialize_false,
3258 &if_true, &if_false, &fall_through);
3260 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3261 __ test(eax, Immediate(kSmiTagMask | 0x80000000));
3262 Split(zero, if_true, if_false, fall_through);
3264 context()->Plug(if_true, if_false);
3268 void FullCodeGenerator::EmitIsObject(CallRuntime* expr) {
3269 ZoneList<Expression*>* args = expr->arguments();
3270 DCHECK(args->length() == 1);
3272 VisitForAccumulatorValue(args->at(0));
3274 Label materialize_true, materialize_false;
3275 Label* if_true = NULL;
3276 Label* if_false = NULL;
3277 Label* fall_through = NULL;
3278 context()->PrepareTest(&materialize_true, &materialize_false,
3279 &if_true, &if_false, &fall_through);
3281 __ JumpIfSmi(eax, if_false);
3282 __ cmp(eax, isolate()->factory()->null_value());
3283 __ j(equal, if_true);
3284 __ mov(ebx, FieldOperand(eax, HeapObject::kMapOffset));
3285 // Undetectable objects behave like undefined when tested with typeof.
3286 __ movzx_b(ecx, FieldOperand(ebx, Map::kBitFieldOffset));
3287 __ test(ecx, Immediate(1 << Map::kIsUndetectable));
3288 __ j(not_zero, if_false);
3289 __ movzx_b(ecx, FieldOperand(ebx, Map::kInstanceTypeOffset));
3290 __ cmp(ecx, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE);
3291 __ j(below, if_false);
3292 __ cmp(ecx, LAST_NONCALLABLE_SPEC_OBJECT_TYPE);
3293 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3294 Split(below_equal, if_true, if_false, fall_through);
3296 context()->Plug(if_true, if_false);
3300 void FullCodeGenerator::EmitIsSpecObject(CallRuntime* expr) {
3301 ZoneList<Expression*>* args = expr->arguments();
3302 DCHECK(args->length() == 1);
3304 VisitForAccumulatorValue(args->at(0));
3306 Label materialize_true, materialize_false;
3307 Label* if_true = NULL;
3308 Label* if_false = NULL;
3309 Label* fall_through = NULL;
3310 context()->PrepareTest(&materialize_true, &materialize_false,
3311 &if_true, &if_false, &fall_through);
3313 __ JumpIfSmi(eax, if_false);
3314 __ CmpObjectType(eax, FIRST_SPEC_OBJECT_TYPE, ebx);
3315 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3316 Split(above_equal, if_true, if_false, fall_through);
3318 context()->Plug(if_true, if_false);
3322 void FullCodeGenerator::EmitIsUndetectableObject(CallRuntime* expr) {
3323 ZoneList<Expression*>* args = expr->arguments();
3324 DCHECK(args->length() == 1);
3326 VisitForAccumulatorValue(args->at(0));
3328 Label materialize_true, materialize_false;
3329 Label* if_true = NULL;
3330 Label* if_false = NULL;
3331 Label* fall_through = NULL;
3332 context()->PrepareTest(&materialize_true, &materialize_false,
3333 &if_true, &if_false, &fall_through);
3335 __ JumpIfSmi(eax, if_false);
3336 __ mov(ebx, FieldOperand(eax, HeapObject::kMapOffset));
3337 __ movzx_b(ebx, FieldOperand(ebx, Map::kBitFieldOffset));
3338 __ test(ebx, Immediate(1 << Map::kIsUndetectable));
3339 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3340 Split(not_zero, if_true, if_false, fall_through);
3342 context()->Plug(if_true, if_false);
3346 void FullCodeGenerator::EmitIsStringWrapperSafeForDefaultValueOf(
3347 CallRuntime* expr) {
3348 ZoneList<Expression*>* args = expr->arguments();
3349 DCHECK(args->length() == 1);
3351 VisitForAccumulatorValue(args->at(0));
3353 Label materialize_true, materialize_false, skip_lookup;
3354 Label* if_true = NULL;
3355 Label* if_false = NULL;
3356 Label* fall_through = NULL;
3357 context()->PrepareTest(&materialize_true, &materialize_false,
3358 &if_true, &if_false, &fall_through);
3360 __ AssertNotSmi(eax);
3362 // Check whether this map has already been checked to be safe for default
3364 __ mov(ebx, FieldOperand(eax, HeapObject::kMapOffset));
3365 __ test_b(FieldOperand(ebx, Map::kBitField2Offset),
3366 1 << Map::kStringWrapperSafeForDefaultValueOf);
3367 __ j(not_zero, &skip_lookup);
3369 // Check for fast case object. Return false for slow case objects.
3370 __ mov(ecx, FieldOperand(eax, JSObject::kPropertiesOffset));
3371 __ mov(ecx, FieldOperand(ecx, HeapObject::kMapOffset));
3372 __ cmp(ecx, isolate()->factory()->hash_table_map());
3373 __ j(equal, if_false);
3375 // Look for valueOf string in the descriptor array, and indicate false if
3376 // found. Since we omit an enumeration index check, if it is added via a
3377 // transition that shares its descriptor array, this is a false positive.
3378 Label entry, loop, done;
3380 // Skip loop if no descriptors are valid.
3381 __ NumberOfOwnDescriptors(ecx, ebx);
3385 __ LoadInstanceDescriptors(ebx, ebx);
3386 // ebx: descriptor array.
3387 // ecx: valid entries in the descriptor array.
3388 // Calculate the end of the descriptor array.
3389 STATIC_ASSERT(kSmiTag == 0);
3390 STATIC_ASSERT(kSmiTagSize == 1);
3391 STATIC_ASSERT(kPointerSize == 4);
3392 __ imul(ecx, ecx, DescriptorArray::kDescriptorSize);
3393 __ lea(ecx, Operand(ebx, ecx, times_4, DescriptorArray::kFirstOffset));
3394 // Calculate location of the first key name.
3395 __ add(ebx, Immediate(DescriptorArray::kFirstOffset));
3396 // Loop through all the keys in the descriptor array. If one of these is the
3397 // internalized string "valueOf" the result is false.
3400 __ mov(edx, FieldOperand(ebx, 0));
3401 __ cmp(edx, isolate()->factory()->value_of_string());
3402 __ j(equal, if_false);
3403 __ add(ebx, Immediate(DescriptorArray::kDescriptorSize * kPointerSize));
3406 __ j(not_equal, &loop);
3410 // Reload map as register ebx was used as temporary above.
3411 __ mov(ebx, FieldOperand(eax, HeapObject::kMapOffset));
3413 // Set the bit in the map to indicate that there is no local valueOf field.
3414 __ or_(FieldOperand(ebx, Map::kBitField2Offset),
3415 Immediate(1 << Map::kStringWrapperSafeForDefaultValueOf));
3417 __ bind(&skip_lookup);
3419 // If a valueOf property is not found on the object check that its
3420 // prototype is the un-modified String prototype. If not result is false.
3421 __ mov(ecx, FieldOperand(ebx, Map::kPrototypeOffset));
3422 __ JumpIfSmi(ecx, if_false);
3423 __ mov(ecx, FieldOperand(ecx, HeapObject::kMapOffset));
3424 __ mov(edx, Operand(esi, Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX)));
3426 FieldOperand(edx, GlobalObject::kNativeContextOffset));
3429 Context::STRING_FUNCTION_PROTOTYPE_MAP_INDEX));
3430 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3431 Split(equal, if_true, if_false, fall_through);
3433 context()->Plug(if_true, if_false);
3437 void FullCodeGenerator::EmitIsFunction(CallRuntime* expr) {
3438 ZoneList<Expression*>* args = expr->arguments();
3439 DCHECK(args->length() == 1);
3441 VisitForAccumulatorValue(args->at(0));
3443 Label materialize_true, materialize_false;
3444 Label* if_true = NULL;
3445 Label* if_false = NULL;
3446 Label* fall_through = NULL;
3447 context()->PrepareTest(&materialize_true, &materialize_false,
3448 &if_true, &if_false, &fall_through);
3450 __ JumpIfSmi(eax, if_false);
3451 __ CmpObjectType(eax, JS_FUNCTION_TYPE, ebx);
3452 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3453 Split(equal, if_true, if_false, fall_through);
3455 context()->Plug(if_true, if_false);
3459 void FullCodeGenerator::EmitIsMinusZero(CallRuntime* expr) {
3460 ZoneList<Expression*>* args = expr->arguments();
3461 DCHECK(args->length() == 1);
3463 VisitForAccumulatorValue(args->at(0));
3465 Label materialize_true, materialize_false;
3466 Label* if_true = NULL;
3467 Label* if_false = NULL;
3468 Label* fall_through = NULL;
3469 context()->PrepareTest(&materialize_true, &materialize_false,
3470 &if_true, &if_false, &fall_through);
3472 Handle<Map> map = masm()->isolate()->factory()->heap_number_map();
3473 __ CheckMap(eax, map, if_false, DO_SMI_CHECK);
3474 // Check if the exponent half is 0x80000000. Comparing against 1 and
3475 // checking for overflow is the shortest possible encoding.
3476 __ cmp(FieldOperand(eax, HeapNumber::kExponentOffset), Immediate(0x1));
3477 __ j(no_overflow, if_false);
3478 __ cmp(FieldOperand(eax, HeapNumber::kMantissaOffset), Immediate(0x0));
3479 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3480 Split(equal, if_true, if_false, fall_through);
3482 context()->Plug(if_true, if_false);
3487 void FullCodeGenerator::EmitIsArray(CallRuntime* expr) {
3488 ZoneList<Expression*>* args = expr->arguments();
3489 DCHECK(args->length() == 1);
3491 VisitForAccumulatorValue(args->at(0));
3493 Label materialize_true, materialize_false;
3494 Label* if_true = NULL;
3495 Label* if_false = NULL;
3496 Label* fall_through = NULL;
3497 context()->PrepareTest(&materialize_true, &materialize_false,
3498 &if_true, &if_false, &fall_through);
3500 __ JumpIfSmi(eax, if_false);
3501 __ CmpObjectType(eax, JS_ARRAY_TYPE, ebx);
3502 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3503 Split(equal, if_true, if_false, fall_through);
3505 context()->Plug(if_true, if_false);
3509 void FullCodeGenerator::EmitIsRegExp(CallRuntime* expr) {
3510 ZoneList<Expression*>* args = expr->arguments();
3511 DCHECK(args->length() == 1);
3513 VisitForAccumulatorValue(args->at(0));
3515 Label materialize_true, materialize_false;
3516 Label* if_true = NULL;
3517 Label* if_false = NULL;
3518 Label* fall_through = NULL;
3519 context()->PrepareTest(&materialize_true, &materialize_false,
3520 &if_true, &if_false, &fall_through);
3522 __ JumpIfSmi(eax, if_false);
3523 __ CmpObjectType(eax, JS_REGEXP_TYPE, ebx);
3524 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3525 Split(equal, if_true, if_false, fall_through);
3527 context()->Plug(if_true, if_false);
3531 void FullCodeGenerator::EmitIsJSProxy(CallRuntime* expr) {
3532 ZoneList<Expression*>* args = expr->arguments();
3533 DCHECK(args->length() == 1);
3535 VisitForAccumulatorValue(args->at(0));
3537 Label materialize_true, materialize_false;
3538 Label* if_true = NULL;
3539 Label* if_false = NULL;
3540 Label* fall_through = NULL;
3541 context()->PrepareTest(&materialize_true, &materialize_false, &if_true,
3542 &if_false, &fall_through);
3544 __ JumpIfSmi(eax, if_false);
3546 __ mov(map, FieldOperand(eax, HeapObject::kMapOffset));
3547 __ CmpInstanceType(map, FIRST_JS_PROXY_TYPE);
3548 __ j(less, if_false);
3549 __ CmpInstanceType(map, LAST_JS_PROXY_TYPE);
3550 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3551 Split(less_equal, if_true, if_false, fall_through);
3553 context()->Plug(if_true, if_false);
3557 void FullCodeGenerator::EmitIsConstructCall(CallRuntime* expr) {
3558 DCHECK(expr->arguments()->length() == 0);
3560 Label materialize_true, materialize_false;
3561 Label* if_true = NULL;
3562 Label* if_false = NULL;
3563 Label* fall_through = NULL;
3564 context()->PrepareTest(&materialize_true, &materialize_false,
3565 &if_true, &if_false, &fall_through);
3567 // Get the frame pointer for the calling frame.
3568 __ mov(eax, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3570 // Skip the arguments adaptor frame if it exists.
3571 Label check_frame_marker;
3572 __ cmp(Operand(eax, StandardFrameConstants::kContextOffset),
3573 Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
3574 __ j(not_equal, &check_frame_marker);
3575 __ mov(eax, Operand(eax, StandardFrameConstants::kCallerFPOffset));
3577 // Check the marker in the calling frame.
3578 __ bind(&check_frame_marker);
3579 __ cmp(Operand(eax, StandardFrameConstants::kMarkerOffset),
3580 Immediate(Smi::FromInt(StackFrame::CONSTRUCT)));
3581 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3582 Split(equal, if_true, if_false, fall_through);
3584 context()->Plug(if_true, if_false);
3588 void FullCodeGenerator::EmitObjectEquals(CallRuntime* expr) {
3589 ZoneList<Expression*>* args = expr->arguments();
3590 DCHECK(args->length() == 2);
3592 // Load the two objects into registers and perform the comparison.
3593 VisitForStackValue(args->at(0));
3594 VisitForAccumulatorValue(args->at(1));
3596 Label materialize_true, materialize_false;
3597 Label* if_true = NULL;
3598 Label* if_false = NULL;
3599 Label* fall_through = NULL;
3600 context()->PrepareTest(&materialize_true, &materialize_false,
3601 &if_true, &if_false, &fall_through);
3605 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3606 Split(equal, if_true, if_false, fall_through);
3608 context()->Plug(if_true, if_false);
3612 void FullCodeGenerator::EmitArguments(CallRuntime* expr) {
3613 ZoneList<Expression*>* args = expr->arguments();
3614 DCHECK(args->length() == 1);
3616 // ArgumentsAccessStub expects the key in edx and the formal
3617 // parameter count in eax.
3618 VisitForAccumulatorValue(args->at(0));
3620 __ Move(eax, Immediate(Smi::FromInt(info_->scope()->num_parameters())));
3621 ArgumentsAccessStub stub(isolate(), ArgumentsAccessStub::READ_ELEMENT);
3623 context()->Plug(eax);
3627 void FullCodeGenerator::EmitArgumentsLength(CallRuntime* expr) {
3628 DCHECK(expr->arguments()->length() == 0);
3631 // Get the number of formal parameters.
3632 __ Move(eax, Immediate(Smi::FromInt(info_->scope()->num_parameters())));
3634 // Check if the calling frame is an arguments adaptor frame.
3635 __ mov(ebx, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3636 __ cmp(Operand(ebx, StandardFrameConstants::kContextOffset),
3637 Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
3638 __ j(not_equal, &exit);
3640 // Arguments adaptor case: Read the arguments length from the
3642 __ mov(eax, Operand(ebx, ArgumentsAdaptorFrameConstants::kLengthOffset));
3646 context()->Plug(eax);
3650 void FullCodeGenerator::EmitClassOf(CallRuntime* expr) {
3651 ZoneList<Expression*>* args = expr->arguments();
3652 DCHECK(args->length() == 1);
3653 Label done, null, function, non_function_constructor;
3655 VisitForAccumulatorValue(args->at(0));
3657 // If the object is a smi, we return null.
3658 __ JumpIfSmi(eax, &null);
3660 // Check that the object is a JS object but take special care of JS
3661 // functions to make sure they have 'Function' as their class.
3662 // Assume that there are only two callable types, and one of them is at
3663 // either end of the type range for JS object types. Saves extra comparisons.
3664 STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
3665 __ CmpObjectType(eax, FIRST_SPEC_OBJECT_TYPE, eax);
3666 // Map is now in eax.
3668 STATIC_ASSERT(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE ==
3669 FIRST_SPEC_OBJECT_TYPE + 1);
3670 __ j(equal, &function);
3672 __ CmpInstanceType(eax, LAST_SPEC_OBJECT_TYPE);
3673 STATIC_ASSERT(LAST_NONCALLABLE_SPEC_OBJECT_TYPE ==
3674 LAST_SPEC_OBJECT_TYPE - 1);
3675 __ j(equal, &function);
3676 // Assume that there is no larger type.
3677 STATIC_ASSERT(LAST_NONCALLABLE_SPEC_OBJECT_TYPE == LAST_TYPE - 1);
3679 // Check if the constructor in the map is a JS function.
3680 __ GetMapConstructor(eax, eax, ebx);
3681 __ CmpInstanceType(ebx, JS_FUNCTION_TYPE);
3682 __ j(not_equal, &non_function_constructor);
3684 // eax now contains the constructor function. Grab the
3685 // instance class name from there.
3686 __ mov(eax, FieldOperand(eax, JSFunction::kSharedFunctionInfoOffset));
3687 __ mov(eax, FieldOperand(eax, SharedFunctionInfo::kInstanceClassNameOffset));
3690 // Functions have class 'Function'.
3692 __ mov(eax, isolate()->factory()->Function_string());
3695 // Objects with a non-function constructor have class 'Object'.
3696 __ bind(&non_function_constructor);
3697 __ mov(eax, isolate()->factory()->Object_string());
3700 // Non-JS objects have class null.
3702 __ mov(eax, isolate()->factory()->null_value());
3707 context()->Plug(eax);
3711 void FullCodeGenerator::EmitSubString(CallRuntime* expr) {
3712 // Load the arguments on the stack and call the stub.
3713 SubStringStub stub(isolate());
3714 ZoneList<Expression*>* args = expr->arguments();
3715 DCHECK(args->length() == 3);
3716 VisitForStackValue(args->at(0));
3717 VisitForStackValue(args->at(1));
3718 VisitForStackValue(args->at(2));
3720 context()->Plug(eax);
3724 void FullCodeGenerator::EmitRegExpExec(CallRuntime* expr) {
3725 // Load the arguments on the stack and call the stub.
3726 RegExpExecStub stub(isolate());
3727 ZoneList<Expression*>* args = expr->arguments();
3728 DCHECK(args->length() == 4);
3729 VisitForStackValue(args->at(0));
3730 VisitForStackValue(args->at(1));
3731 VisitForStackValue(args->at(2));
3732 VisitForStackValue(args->at(3));
3734 context()->Plug(eax);
3738 void FullCodeGenerator::EmitValueOf(CallRuntime* expr) {
3739 ZoneList<Expression*>* args = expr->arguments();
3740 DCHECK(args->length() == 1);
3742 VisitForAccumulatorValue(args->at(0)); // Load the object.
3745 // If the object is a smi return the object.
3746 __ JumpIfSmi(eax, &done, Label::kNear);
3747 // If the object is not a value type, return the object.
3748 __ CmpObjectType(eax, JS_VALUE_TYPE, ebx);
3749 __ j(not_equal, &done, Label::kNear);
3750 __ mov(eax, FieldOperand(eax, JSValue::kValueOffset));
3753 context()->Plug(eax);
3757 void FullCodeGenerator::EmitDateField(CallRuntime* expr) {
3758 ZoneList<Expression*>* args = expr->arguments();
3759 DCHECK(args->length() == 2);
3760 DCHECK_NOT_NULL(args->at(1)->AsLiteral());
3761 Smi* index = Smi::cast(*(args->at(1)->AsLiteral()->value()));
3763 VisitForAccumulatorValue(args->at(0)); // Load the object.
3765 Label runtime, done, not_date_object;
3766 Register object = eax;
3767 Register result = eax;
3768 Register scratch = ecx;
3770 __ JumpIfSmi(object, ¬_date_object);
3771 __ CmpObjectType(object, JS_DATE_TYPE, scratch);
3772 __ j(not_equal, ¬_date_object);
3774 if (index->value() == 0) {
3775 __ mov(result, FieldOperand(object, JSDate::kValueOffset));
3778 if (index->value() < JSDate::kFirstUncachedField) {
3779 ExternalReference stamp = ExternalReference::date_cache_stamp(isolate());
3780 __ mov(scratch, Operand::StaticVariable(stamp));
3781 __ cmp(scratch, FieldOperand(object, JSDate::kCacheStampOffset));
3782 __ j(not_equal, &runtime, Label::kNear);
3783 __ mov(result, FieldOperand(object, JSDate::kValueOffset +
3784 kPointerSize * index->value()));
3788 __ PrepareCallCFunction(2, scratch);
3789 __ mov(Operand(esp, 0), object);
3790 __ mov(Operand(esp, 1 * kPointerSize), Immediate(index));
3791 __ CallCFunction(ExternalReference::get_date_field_function(isolate()), 2);
3795 __ bind(¬_date_object);
3796 __ CallRuntime(Runtime::kThrowNotDateError, 0);
3798 context()->Plug(result);
3802 void FullCodeGenerator::EmitOneByteSeqStringSetChar(CallRuntime* expr) {
3803 ZoneList<Expression*>* args = expr->arguments();
3804 DCHECK_EQ(3, args->length());
3806 Register string = eax;
3807 Register index = ebx;
3808 Register value = ecx;
3810 VisitForStackValue(args->at(0)); // index
3811 VisitForStackValue(args->at(1)); // value
3812 VisitForAccumulatorValue(args->at(2)); // string
3817 if (FLAG_debug_code) {
3818 __ test(value, Immediate(kSmiTagMask));
3819 __ Check(zero, kNonSmiValue);
3820 __ test(index, Immediate(kSmiTagMask));
3821 __ Check(zero, kNonSmiValue);
3827 if (FLAG_debug_code) {
3828 static const uint32_t one_byte_seq_type = kSeqStringTag | kOneByteStringTag;
3829 __ EmitSeqStringSetCharCheck(string, index, value, one_byte_seq_type);
3832 __ mov_b(FieldOperand(string, index, times_1, SeqOneByteString::kHeaderSize),
3834 context()->Plug(string);
3838 void FullCodeGenerator::EmitTwoByteSeqStringSetChar(CallRuntime* expr) {
3839 ZoneList<Expression*>* args = expr->arguments();
3840 DCHECK_EQ(3, args->length());
3842 Register string = eax;
3843 Register index = ebx;
3844 Register value = ecx;
3846 VisitForStackValue(args->at(0)); // index
3847 VisitForStackValue(args->at(1)); // value
3848 VisitForAccumulatorValue(args->at(2)); // string
3852 if (FLAG_debug_code) {
3853 __ test(value, Immediate(kSmiTagMask));
3854 __ Check(zero, kNonSmiValue);
3855 __ test(index, Immediate(kSmiTagMask));
3856 __ Check(zero, kNonSmiValue);
3858 static const uint32_t two_byte_seq_type = kSeqStringTag | kTwoByteStringTag;
3859 __ EmitSeqStringSetCharCheck(string, index, value, two_byte_seq_type);
3864 // No need to untag a smi for two-byte addressing.
3865 __ mov_w(FieldOperand(string, index, times_1, SeqTwoByteString::kHeaderSize),
3867 context()->Plug(string);
3871 void FullCodeGenerator::EmitMathPow(CallRuntime* expr) {
3872 // Load the arguments on the stack and call the runtime function.
3873 ZoneList<Expression*>* args = expr->arguments();
3874 DCHECK(args->length() == 2);
3875 VisitForStackValue(args->at(0));
3876 VisitForStackValue(args->at(1));
3878 __ CallRuntime(Runtime::kMathPowSlow, 2);
3879 context()->Plug(eax);
3883 void FullCodeGenerator::EmitSetValueOf(CallRuntime* expr) {
3884 ZoneList<Expression*>* args = expr->arguments();
3885 DCHECK(args->length() == 2);
3887 VisitForStackValue(args->at(0)); // Load the object.
3888 VisitForAccumulatorValue(args->at(1)); // Load the value.
3889 __ pop(ebx); // eax = value. ebx = object.
3892 // If the object is a smi, return the value.
3893 __ JumpIfSmi(ebx, &done, Label::kNear);
3895 // If the object is not a value type, return the value.
3896 __ CmpObjectType(ebx, JS_VALUE_TYPE, ecx);
3897 __ j(not_equal, &done, Label::kNear);
3900 __ mov(FieldOperand(ebx, JSValue::kValueOffset), eax);
3902 // Update the write barrier. Save the value as it will be
3903 // overwritten by the write barrier code and is needed afterward.
3905 __ RecordWriteField(ebx, JSValue::kValueOffset, edx, ecx, kDontSaveFPRegs);
3908 context()->Plug(eax);
3912 void FullCodeGenerator::EmitNumberToString(CallRuntime* expr) {
3913 ZoneList<Expression*>* args = expr->arguments();
3914 DCHECK_EQ(args->length(), 1);
3916 // Load the argument into eax and call the stub.
3917 VisitForAccumulatorValue(args->at(0));
3919 NumberToStringStub stub(isolate());
3921 context()->Plug(eax);
3925 void FullCodeGenerator::EmitStringCharFromCode(CallRuntime* expr) {
3926 ZoneList<Expression*>* args = expr->arguments();
3927 DCHECK(args->length() == 1);
3929 VisitForAccumulatorValue(args->at(0));
3932 StringCharFromCodeGenerator generator(eax, ebx);
3933 generator.GenerateFast(masm_);
3936 NopRuntimeCallHelper call_helper;
3937 generator.GenerateSlow(masm_, call_helper);
3940 context()->Plug(ebx);
3944 void FullCodeGenerator::EmitStringCharCodeAt(CallRuntime* expr) {
3945 ZoneList<Expression*>* args = expr->arguments();
3946 DCHECK(args->length() == 2);
3948 VisitForStackValue(args->at(0));
3949 VisitForAccumulatorValue(args->at(1));
3951 Register object = ebx;
3952 Register index = eax;
3953 Register result = edx;
3957 Label need_conversion;
3958 Label index_out_of_range;
3960 StringCharCodeAtGenerator generator(object,
3965 &index_out_of_range,
3966 STRING_INDEX_IS_NUMBER);
3967 generator.GenerateFast(masm_);
3970 __ bind(&index_out_of_range);
3971 // When the index is out of range, the spec requires us to return
3973 __ Move(result, Immediate(isolate()->factory()->nan_value()));
3976 __ bind(&need_conversion);
3977 // Move the undefined value into the result register, which will
3978 // trigger conversion.
3979 __ Move(result, Immediate(isolate()->factory()->undefined_value()));
3982 NopRuntimeCallHelper call_helper;
3983 generator.GenerateSlow(masm_, NOT_PART_OF_IC_HANDLER, call_helper);
3986 context()->Plug(result);
3990 void FullCodeGenerator::EmitStringCharAt(CallRuntime* expr) {
3991 ZoneList<Expression*>* args = expr->arguments();
3992 DCHECK(args->length() == 2);
3994 VisitForStackValue(args->at(0));
3995 VisitForAccumulatorValue(args->at(1));
3997 Register object = ebx;
3998 Register index = eax;
3999 Register scratch = edx;
4000 Register result = eax;
4004 Label need_conversion;
4005 Label index_out_of_range;
4007 StringCharAtGenerator generator(object,
4013 &index_out_of_range,
4014 STRING_INDEX_IS_NUMBER);
4015 generator.GenerateFast(masm_);
4018 __ bind(&index_out_of_range);
4019 // When the index is out of range, the spec requires us to return
4020 // the empty string.
4021 __ Move(result, Immediate(isolate()->factory()->empty_string()));
4024 __ bind(&need_conversion);
4025 // Move smi zero into the result register, which will trigger
4027 __ Move(result, Immediate(Smi::FromInt(0)));
4030 NopRuntimeCallHelper call_helper;
4031 generator.GenerateSlow(masm_, NOT_PART_OF_IC_HANDLER, call_helper);
4034 context()->Plug(result);
4038 void FullCodeGenerator::EmitStringAdd(CallRuntime* expr) {
4039 ZoneList<Expression*>* args = expr->arguments();
4040 DCHECK_EQ(2, args->length());
4041 VisitForStackValue(args->at(0));
4042 VisitForAccumulatorValue(args->at(1));
4045 StringAddStub stub(isolate(), STRING_ADD_CHECK_BOTH, NOT_TENURED);
4047 context()->Plug(eax);
4051 void FullCodeGenerator::EmitStringCompare(CallRuntime* expr) {
4052 ZoneList<Expression*>* args = expr->arguments();
4053 DCHECK_EQ(2, args->length());
4055 VisitForStackValue(args->at(0));
4056 VisitForStackValue(args->at(1));
4058 StringCompareStub stub(isolate());
4060 context()->Plug(eax);
4064 void FullCodeGenerator::EmitCallFunction(CallRuntime* expr) {
4065 ZoneList<Expression*>* args = expr->arguments();
4066 DCHECK(args->length() >= 2);
4068 int arg_count = args->length() - 2; // 2 ~ receiver and function.
4069 for (int i = 0; i < arg_count + 1; ++i) {
4070 VisitForStackValue(args->at(i));
4072 VisitForAccumulatorValue(args->last()); // Function.
4074 Label runtime, done;
4075 // Check for non-function argument (including proxy).
4076 __ JumpIfSmi(eax, &runtime);
4077 __ CmpObjectType(eax, JS_FUNCTION_TYPE, ebx);
4078 __ j(not_equal, &runtime);
4080 // InvokeFunction requires the function in edi. Move it in there.
4081 __ mov(edi, result_register());
4082 ParameterCount count(arg_count);
4083 __ InvokeFunction(edi, count, CALL_FUNCTION, NullCallWrapper());
4084 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4089 __ CallRuntime(Runtime::kCall, args->length());
4092 context()->Plug(eax);
4096 void FullCodeGenerator::EmitDefaultConstructorCallSuper(CallRuntime* expr) {
4097 Variable* new_target_var = scope()->DeclarationScope()->new_target_var();
4098 GetVar(eax, new_target_var);
4101 EmitLoadSuperConstructor();
4102 __ push(result_register());
4104 // Check if the calling frame is an arguments adaptor frame.
4105 Label adaptor_frame, args_set_up, runtime;
4106 __ mov(edx, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
4107 __ mov(ecx, Operand(edx, StandardFrameConstants::kContextOffset));
4108 __ cmp(ecx, Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
4109 __ j(equal, &adaptor_frame);
4110 // default constructor has no arguments, so no adaptor frame means no args.
4111 __ mov(eax, Immediate(0));
4112 __ jmp(&args_set_up);
4114 // Copy arguments from adaptor frame.
4116 __ bind(&adaptor_frame);
4117 __ mov(ecx, Operand(edx, ArgumentsAdaptorFrameConstants::kLengthOffset));
4120 // Subtract 1 from arguments count, for new.target.
4121 __ sub(ecx, Immediate(1));
4123 __ lea(edx, Operand(edx, ecx, times_pointer_size,
4124 StandardFrameConstants::kCallerSPOffset));
4127 __ push(Operand(edx, -1 * kPointerSize));
4128 __ sub(edx, Immediate(kPointerSize));
4130 __ j(not_zero, &loop);
4133 __ bind(&args_set_up);
4135 __ mov(edi, Operand(esp, eax, times_pointer_size, 0));
4136 __ mov(ebx, Immediate(isolate()->factory()->undefined_value()));
4137 CallConstructStub stub(isolate(), SUPER_CONSTRUCTOR_CALL);
4138 __ call(stub.GetCode(), RelocInfo::CONSTRUCT_CALL);
4142 context()->Plug(eax);
4146 void FullCodeGenerator::EmitRegExpConstructResult(CallRuntime* expr) {
4147 // Load the arguments on the stack and call the stub.
4148 RegExpConstructResultStub stub(isolate());
4149 ZoneList<Expression*>* args = expr->arguments();
4150 DCHECK(args->length() == 3);
4151 VisitForStackValue(args->at(0));
4152 VisitForStackValue(args->at(1));
4153 VisitForAccumulatorValue(args->at(2));
4157 context()->Plug(eax);
4161 void FullCodeGenerator::EmitGetFromCache(CallRuntime* expr) {
4162 ZoneList<Expression*>* args = expr->arguments();
4163 DCHECK_EQ(2, args->length());
4165 DCHECK_NOT_NULL(args->at(0)->AsLiteral());
4166 int cache_id = Smi::cast(*(args->at(0)->AsLiteral()->value()))->value();
4168 Handle<FixedArray> jsfunction_result_caches(
4169 isolate()->native_context()->jsfunction_result_caches());
4170 if (jsfunction_result_caches->length() <= cache_id) {
4171 __ Abort(kAttemptToUseUndefinedCache);
4172 __ mov(eax, isolate()->factory()->undefined_value());
4173 context()->Plug(eax);
4177 VisitForAccumulatorValue(args->at(1));
4180 Register cache = ebx;
4182 __ mov(cache, ContextOperand(esi, Context::GLOBAL_OBJECT_INDEX));
4184 FieldOperand(cache, GlobalObject::kNativeContextOffset));
4185 __ mov(cache, ContextOperand(cache, Context::JSFUNCTION_RESULT_CACHES_INDEX));
4187 FieldOperand(cache, FixedArray::OffsetOfElementAt(cache_id)));
4189 Label done, not_found;
4190 STATIC_ASSERT(kSmiTag == 0 && kSmiTagSize == 1);
4191 __ mov(tmp, FieldOperand(cache, JSFunctionResultCache::kFingerOffset));
4192 // tmp now holds finger offset as a smi.
4193 __ cmp(key, FixedArrayElementOperand(cache, tmp));
4194 __ j(not_equal, ¬_found);
4196 __ mov(eax, FixedArrayElementOperand(cache, tmp, 1));
4199 __ bind(¬_found);
4200 // Call runtime to perform the lookup.
4203 __ CallRuntime(Runtime::kGetFromCacheRT, 2);
4206 context()->Plug(eax);
4210 void FullCodeGenerator::EmitHasCachedArrayIndex(CallRuntime* expr) {
4211 ZoneList<Expression*>* args = expr->arguments();
4212 DCHECK(args->length() == 1);
4214 VisitForAccumulatorValue(args->at(0));
4216 __ AssertString(eax);
4218 Label materialize_true, materialize_false;
4219 Label* if_true = NULL;
4220 Label* if_false = NULL;
4221 Label* fall_through = NULL;
4222 context()->PrepareTest(&materialize_true, &materialize_false,
4223 &if_true, &if_false, &fall_through);
4225 __ test(FieldOperand(eax, String::kHashFieldOffset),
4226 Immediate(String::kContainsCachedArrayIndexMask));
4227 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
4228 Split(zero, if_true, if_false, fall_through);
4230 context()->Plug(if_true, if_false);
4234 void FullCodeGenerator::EmitGetCachedArrayIndex(CallRuntime* expr) {
4235 ZoneList<Expression*>* args = expr->arguments();
4236 DCHECK(args->length() == 1);
4237 VisitForAccumulatorValue(args->at(0));
4239 __ AssertString(eax);
4241 __ mov(eax, FieldOperand(eax, String::kHashFieldOffset));
4242 __ IndexFromHash(eax, eax);
4244 context()->Plug(eax);
4248 void FullCodeGenerator::EmitFastOneByteArrayJoin(CallRuntime* expr) {
4249 Label bailout, done, one_char_separator, long_separator,
4250 non_trivial_array, not_size_one_array, loop,
4251 loop_1, loop_1_condition, loop_2, loop_2_entry, loop_3, loop_3_entry;
4253 ZoneList<Expression*>* args = expr->arguments();
4254 DCHECK(args->length() == 2);
4255 // We will leave the separator on the stack until the end of the function.
4256 VisitForStackValue(args->at(1));
4257 // Load this to eax (= array)
4258 VisitForAccumulatorValue(args->at(0));
4259 // All aliases of the same register have disjoint lifetimes.
4260 Register array = eax;
4261 Register elements = no_reg; // Will be eax.
4263 Register index = edx;
4265 Register string_length = ecx;
4267 Register string = esi;
4269 Register scratch = ebx;
4271 Register array_length = edi;
4272 Register result_pos = no_reg; // Will be edi.
4274 // Separator operand is already pushed.
4275 Operand separator_operand = Operand(esp, 2 * kPointerSize);
4276 Operand result_operand = Operand(esp, 1 * kPointerSize);
4277 Operand array_length_operand = Operand(esp, 0);
4278 __ sub(esp, Immediate(2 * kPointerSize));
4280 // Check that the array is a JSArray
4281 __ JumpIfSmi(array, &bailout);
4282 __ CmpObjectType(array, JS_ARRAY_TYPE, scratch);
4283 __ j(not_equal, &bailout);
4285 // Check that the array has fast elements.
4286 __ CheckFastElements(scratch, &bailout);
4288 // If the array has length zero, return the empty string.
4289 __ mov(array_length, FieldOperand(array, JSArray::kLengthOffset));
4290 __ SmiUntag(array_length);
4291 __ j(not_zero, &non_trivial_array);
4292 __ mov(result_operand, isolate()->factory()->empty_string());
4295 // Save the array length.
4296 __ bind(&non_trivial_array);
4297 __ mov(array_length_operand, array_length);
4299 // Save the FixedArray containing array's elements.
4300 // End of array's live range.
4302 __ mov(elements, FieldOperand(array, JSArray::kElementsOffset));
4306 // Check that all array elements are sequential one-byte strings, and
4307 // accumulate the sum of their lengths, as a smi-encoded value.
4308 __ Move(index, Immediate(0));
4309 __ Move(string_length, Immediate(0));
4310 // Loop condition: while (index < length).
4311 // Live loop registers: index, array_length, string,
4312 // scratch, string_length, elements.
4313 if (generate_debug_code_) {
4314 __ cmp(index, array_length);
4315 __ Assert(less, kNoEmptyArraysHereInEmitFastOneByteArrayJoin);
4318 __ mov(string, FieldOperand(elements,
4321 FixedArray::kHeaderSize));
4322 __ JumpIfSmi(string, &bailout);
4323 __ mov(scratch, FieldOperand(string, HeapObject::kMapOffset));
4324 __ movzx_b(scratch, FieldOperand(scratch, Map::kInstanceTypeOffset));
4325 __ and_(scratch, Immediate(
4326 kIsNotStringMask | kStringEncodingMask | kStringRepresentationMask));
4327 __ cmp(scratch, kStringTag | kOneByteStringTag | kSeqStringTag);
4328 __ j(not_equal, &bailout);
4329 __ add(string_length,
4330 FieldOperand(string, SeqOneByteString::kLengthOffset));
4331 __ j(overflow, &bailout);
4332 __ add(index, Immediate(1));
4333 __ cmp(index, array_length);
4336 // If array_length is 1, return elements[0], a string.
4337 __ cmp(array_length, 1);
4338 __ j(not_equal, ¬_size_one_array);
4339 __ mov(scratch, FieldOperand(elements, FixedArray::kHeaderSize));
4340 __ mov(result_operand, scratch);
4343 __ bind(¬_size_one_array);
4345 // End of array_length live range.
4346 result_pos = array_length;
4347 array_length = no_reg;
4350 // string_length: Sum of string lengths, as a smi.
4351 // elements: FixedArray of strings.
4353 // Check that the separator is a flat one-byte string.
4354 __ mov(string, separator_operand);
4355 __ JumpIfSmi(string, &bailout);
4356 __ mov(scratch, FieldOperand(string, HeapObject::kMapOffset));
4357 __ movzx_b(scratch, FieldOperand(scratch, Map::kInstanceTypeOffset));
4358 __ and_(scratch, Immediate(
4359 kIsNotStringMask | kStringEncodingMask | kStringRepresentationMask));
4360 __ cmp(scratch, kStringTag | kOneByteStringTag | kSeqStringTag);
4361 __ j(not_equal, &bailout);
4363 // Add (separator length times array_length) - separator length
4364 // to string_length.
4365 __ mov(scratch, separator_operand);
4366 __ mov(scratch, FieldOperand(scratch, SeqOneByteString::kLengthOffset));
4367 __ sub(string_length, scratch); // May be negative, temporarily.
4368 __ imul(scratch, array_length_operand);
4369 __ j(overflow, &bailout);
4370 __ add(string_length, scratch);
4371 __ j(overflow, &bailout);
4373 __ shr(string_length, 1);
4374 // Live registers and stack values:
4377 __ AllocateOneByteString(result_pos, string_length, scratch, index, string,
4379 __ mov(result_operand, result_pos);
4380 __ lea(result_pos, FieldOperand(result_pos, SeqOneByteString::kHeaderSize));
4383 __ mov(string, separator_operand);
4384 __ cmp(FieldOperand(string, SeqOneByteString::kLengthOffset),
4385 Immediate(Smi::FromInt(1)));
4386 __ j(equal, &one_char_separator);
4387 __ j(greater, &long_separator);
4390 // Empty separator case
4391 __ mov(index, Immediate(0));
4392 __ jmp(&loop_1_condition);
4393 // Loop condition: while (index < length).
4395 // Each iteration of the loop concatenates one string to the result.
4396 // Live values in registers:
4397 // index: which element of the elements array we are adding to the result.
4398 // result_pos: the position to which we are currently copying characters.
4399 // elements: the FixedArray of strings we are joining.
4401 // Get string = array[index].
4402 __ mov(string, FieldOperand(elements, index,
4404 FixedArray::kHeaderSize));
4405 __ mov(string_length,
4406 FieldOperand(string, String::kLengthOffset));
4407 __ shr(string_length, 1);
4409 FieldOperand(string, SeqOneByteString::kHeaderSize));
4410 __ CopyBytes(string, result_pos, string_length, scratch);
4411 __ add(index, Immediate(1));
4412 __ bind(&loop_1_condition);
4413 __ cmp(index, array_length_operand);
4414 __ j(less, &loop_1); // End while (index < length).
4419 // One-character separator case
4420 __ bind(&one_char_separator);
4421 // Replace separator with its one-byte character value.
4422 __ mov_b(scratch, FieldOperand(string, SeqOneByteString::kHeaderSize));
4423 __ mov_b(separator_operand, scratch);
4425 __ Move(index, Immediate(0));
4426 // Jump into the loop after the code that copies the separator, so the first
4427 // element is not preceded by a separator
4428 __ jmp(&loop_2_entry);
4429 // Loop condition: while (index < length).
4431 // Each iteration of the loop concatenates one string to the result.
4432 // Live values in registers:
4433 // index: which element of the elements array we are adding to the result.
4434 // result_pos: the position to which we are currently copying characters.
4436 // Copy the separator character to the result.
4437 __ mov_b(scratch, separator_operand);
4438 __ mov_b(Operand(result_pos, 0), scratch);
4441 __ bind(&loop_2_entry);
4442 // Get string = array[index].
4443 __ mov(string, FieldOperand(elements, index,
4445 FixedArray::kHeaderSize));
4446 __ mov(string_length,
4447 FieldOperand(string, String::kLengthOffset));
4448 __ shr(string_length, 1);
4450 FieldOperand(string, SeqOneByteString::kHeaderSize));
4451 __ CopyBytes(string, result_pos, string_length, scratch);
4452 __ add(index, Immediate(1));
4454 __ cmp(index, array_length_operand);
4455 __ j(less, &loop_2); // End while (index < length).
4459 // Long separator case (separator is more than one character).
4460 __ bind(&long_separator);
4462 __ Move(index, Immediate(0));
4463 // Jump into the loop after the code that copies the separator, so the first
4464 // element is not preceded by a separator
4465 __ jmp(&loop_3_entry);
4466 // Loop condition: while (index < length).
4468 // Each iteration of the loop concatenates one string to the result.
4469 // Live values in registers:
4470 // index: which element of the elements array we are adding to the result.
4471 // result_pos: the position to which we are currently copying characters.
4473 // Copy the separator to the result.
4474 __ mov(string, separator_operand);
4475 __ mov(string_length,
4476 FieldOperand(string, String::kLengthOffset));
4477 __ shr(string_length, 1);
4479 FieldOperand(string, SeqOneByteString::kHeaderSize));
4480 __ CopyBytes(string, result_pos, string_length, scratch);
4482 __ bind(&loop_3_entry);
4483 // Get string = array[index].
4484 __ mov(string, FieldOperand(elements, index,
4486 FixedArray::kHeaderSize));
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);
4493 __ add(index, Immediate(1));
4495 __ cmp(index, array_length_operand);
4496 __ j(less, &loop_3); // End while (index < length).
4501 __ mov(result_operand, isolate()->factory()->undefined_value());
4503 __ mov(eax, result_operand);
4504 // Drop temp values from the stack, and restore context register.
4505 __ add(esp, Immediate(3 * kPointerSize));
4507 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4508 context()->Plug(eax);
4512 void FullCodeGenerator::EmitDebugIsActive(CallRuntime* expr) {
4513 DCHECK(expr->arguments()->length() == 0);
4514 ExternalReference debug_is_active =
4515 ExternalReference::debug_is_active_address(isolate());
4516 __ movzx_b(eax, Operand::StaticVariable(debug_is_active));
4518 context()->Plug(eax);
4522 void FullCodeGenerator::EmitCallSuperWithSpread(CallRuntime* expr) {
4523 // Assert: expr == CallRuntime("ReflectConstruct")
4524 CallRuntime* call = expr->arguments()->at(0)->AsCallRuntime();
4525 ZoneList<Expression*>* args = call->arguments();
4526 DCHECK_EQ(3, args->length());
4528 SuperReference* super_reference = args->at(0)->AsSuperReference();
4530 // Load ReflectConstruct function
4531 EmitLoadJSRuntimeFunction(call);
4533 // Push the target function under the receiver
4534 __ push(Operand(esp, 0));
4535 __ mov(Operand(esp, kPointerSize), eax);
4538 EmitLoadSuperConstructor();
4539 __ Push(result_register());
4541 // Push arguments array
4542 VisitForStackValue(args->at(1));
4545 DCHECK(args->at(2)->IsVariableProxy());
4546 VisitForStackValue(args->at(2));
4548 EmitCallJSRuntimeFunction(call);
4550 // Restore context register.
4551 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4552 context()->DropAndPlug(1, eax);
4554 // TODO(mvstanton): with FLAG_vector_stores this needs a slot id.
4555 EmitInitializeThisAfterSuper(super_reference);
4559 void FullCodeGenerator::EmitLoadJSRuntimeFunction(CallRuntime* expr) {
4560 // Push the builtins object as receiver.
4561 __ mov(eax, GlobalObjectOperand());
4562 __ push(FieldOperand(eax, GlobalObject::kBuiltinsOffset));
4564 // Load the function from the receiver.
4565 __ mov(LoadDescriptor::ReceiverRegister(), Operand(esp, 0));
4566 __ mov(LoadDescriptor::NameRegister(), Immediate(expr->name()));
4567 __ mov(LoadDescriptor::SlotRegister(),
4568 Immediate(SmiFromSlot(expr->CallRuntimeFeedbackSlot())));
4569 CallLoadIC(NOT_CONTEXTUAL);
4573 void FullCodeGenerator::EmitCallJSRuntimeFunction(CallRuntime* expr) {
4574 ZoneList<Expression*>* args = expr->arguments();
4575 int arg_count = args->length();
4577 // Record source position of the IC call.
4578 SetSourcePosition(expr->position());
4579 CallFunctionStub stub(isolate(), arg_count, NO_CALL_FUNCTION_FLAGS);
4580 __ mov(edi, Operand(esp, (arg_count + 1) * kPointerSize));
4585 void FullCodeGenerator::VisitCallRuntime(CallRuntime* expr) {
4586 ZoneList<Expression*>* args = expr->arguments();
4587 int arg_count = args->length();
4589 if (expr->is_jsruntime()) {
4590 Comment cmnt(masm_, "[ CallRuntime");
4591 EmitLoadJSRuntimeFunction(expr);
4593 // Push the target function under the receiver.
4594 __ push(Operand(esp, 0));
4595 __ mov(Operand(esp, kPointerSize), eax);
4597 // Push the arguments ("left-to-right").
4598 for (int i = 0; i < arg_count; i++) {
4599 VisitForStackValue(args->at(i));
4602 EmitCallJSRuntimeFunction(expr);
4604 // Restore context register.
4605 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4606 context()->DropAndPlug(1, eax);
4609 const Runtime::Function* function = expr->function();
4610 switch (function->function_id) {
4611 #define CALL_INTRINSIC_GENERATOR(Name) \
4612 case Runtime::kInline##Name: { \
4613 Comment cmnt(masm_, "[ Inline" #Name); \
4614 return Emit##Name(expr); \
4616 FOR_EACH_FULL_CODE_INTRINSIC(CALL_INTRINSIC_GENERATOR)
4617 #undef CALL_INTRINSIC_GENERATOR
4619 Comment cmnt(masm_, "[ CallRuntime for unhandled intrinsic");
4620 // Push the arguments ("left-to-right").
4621 for (int i = 0; i < arg_count; i++) {
4622 VisitForStackValue(args->at(i));
4625 // Call the C runtime function.
4626 __ CallRuntime(expr->function(), arg_count);
4627 context()->Plug(eax);
4634 void FullCodeGenerator::VisitUnaryOperation(UnaryOperation* expr) {
4635 switch (expr->op()) {
4636 case Token::DELETE: {
4637 Comment cmnt(masm_, "[ UnaryOperation (DELETE)");
4638 Property* property = expr->expression()->AsProperty();
4639 VariableProxy* proxy = expr->expression()->AsVariableProxy();
4641 if (property != NULL) {
4642 VisitForStackValue(property->obj());
4643 VisitForStackValue(property->key());
4644 __ push(Immediate(Smi::FromInt(language_mode())));
4645 __ InvokeBuiltin(Builtins::DELETE, CALL_FUNCTION);
4646 context()->Plug(eax);
4647 } else if (proxy != NULL) {
4648 Variable* var = proxy->var();
4649 // Delete of an unqualified identifier is disallowed in strict mode
4650 // but "delete this" is allowed.
4651 DCHECK(is_sloppy(language_mode()) || var->is_this());
4652 if (var->IsUnallocated()) {
4653 __ push(GlobalObjectOperand());
4654 __ push(Immediate(var->name()));
4655 __ push(Immediate(Smi::FromInt(SLOPPY)));
4656 __ InvokeBuiltin(Builtins::DELETE, CALL_FUNCTION);
4657 context()->Plug(eax);
4658 } else if (var->IsStackAllocated() || var->IsContextSlot()) {
4659 // Result of deleting non-global variables is false. 'this' is
4660 // not really a variable, though we implement it as one. The
4661 // subexpression does not have side effects.
4662 context()->Plug(var->is_this());
4664 // Non-global variable. Call the runtime to try to delete from the
4665 // context where the variable was introduced.
4666 __ push(context_register());
4667 __ push(Immediate(var->name()));
4668 __ CallRuntime(Runtime::kDeleteLookupSlot, 2);
4669 context()->Plug(eax);
4672 // Result of deleting non-property, non-variable reference is true.
4673 // The subexpression may have side effects.
4674 VisitForEffect(expr->expression());
4675 context()->Plug(true);
4681 Comment cmnt(masm_, "[ UnaryOperation (VOID)");
4682 VisitForEffect(expr->expression());
4683 context()->Plug(isolate()->factory()->undefined_value());
4688 Comment cmnt(masm_, "[ UnaryOperation (NOT)");
4689 if (context()->IsEffect()) {
4690 // Unary NOT has no side effects so it's only necessary to visit the
4691 // subexpression. Match the optimizing compiler by not branching.
4692 VisitForEffect(expr->expression());
4693 } else if (context()->IsTest()) {
4694 const TestContext* test = TestContext::cast(context());
4695 // The labels are swapped for the recursive call.
4696 VisitForControl(expr->expression(),
4697 test->false_label(),
4699 test->fall_through());
4700 context()->Plug(test->true_label(), test->false_label());
4702 // We handle value contexts explicitly rather than simply visiting
4703 // for control and plugging the control flow into the context,
4704 // because we need to prepare a pair of extra administrative AST ids
4705 // for the optimizing compiler.
4706 DCHECK(context()->IsAccumulatorValue() || context()->IsStackValue());
4707 Label materialize_true, materialize_false, done;
4708 VisitForControl(expr->expression(),
4712 __ bind(&materialize_true);
4713 PrepareForBailoutForId(expr->MaterializeTrueId(), NO_REGISTERS);
4714 if (context()->IsAccumulatorValue()) {
4715 __ mov(eax, isolate()->factory()->true_value());
4717 __ Push(isolate()->factory()->true_value());
4719 __ jmp(&done, Label::kNear);
4720 __ bind(&materialize_false);
4721 PrepareForBailoutForId(expr->MaterializeFalseId(), NO_REGISTERS);
4722 if (context()->IsAccumulatorValue()) {
4723 __ mov(eax, isolate()->factory()->false_value());
4725 __ Push(isolate()->factory()->false_value());
4732 case Token::TYPEOF: {
4733 Comment cmnt(masm_, "[ UnaryOperation (TYPEOF)");
4735 AccumulatorValueContext context(this);
4736 VisitForTypeofValue(expr->expression());
4739 TypeofStub typeof_stub(isolate());
4740 __ CallStub(&typeof_stub);
4741 context()->Plug(eax);
4751 void FullCodeGenerator::VisitCountOperation(CountOperation* expr) {
4752 DCHECK(expr->expression()->IsValidReferenceExpression());
4754 Comment cmnt(masm_, "[ CountOperation");
4755 SetSourcePosition(expr->position());
4757 Property* prop = expr->expression()->AsProperty();
4758 LhsKind assign_type = Property::GetAssignType(prop);
4760 // Evaluate expression and get value.
4761 if (assign_type == VARIABLE) {
4762 DCHECK(expr->expression()->AsVariableProxy()->var() != NULL);
4763 AccumulatorValueContext context(this);
4764 EmitVariableLoad(expr->expression()->AsVariableProxy());
4766 // Reserve space for result of postfix operation.
4767 if (expr->is_postfix() && !context()->IsEffect()) {
4768 __ push(Immediate(Smi::FromInt(0)));
4770 switch (assign_type) {
4771 case NAMED_PROPERTY: {
4772 // Put the object both on the stack and in the register.
4773 VisitForStackValue(prop->obj());
4774 __ mov(LoadDescriptor::ReceiverRegister(), Operand(esp, 0));
4775 EmitNamedPropertyLoad(prop);
4779 case NAMED_SUPER_PROPERTY: {
4780 VisitForStackValue(prop->obj()->AsSuperReference()->this_var());
4781 VisitForAccumulatorValue(
4782 prop->obj()->AsSuperReference()->home_object());
4783 __ push(result_register());
4784 __ push(MemOperand(esp, kPointerSize));
4785 __ push(result_register());
4786 EmitNamedSuperPropertyLoad(prop);
4790 case KEYED_SUPER_PROPERTY: {
4791 VisitForStackValue(prop->obj()->AsSuperReference()->this_var());
4792 VisitForStackValue(prop->obj()->AsSuperReference()->home_object());
4793 VisitForAccumulatorValue(prop->key());
4794 __ push(result_register());
4795 __ push(MemOperand(esp, 2 * kPointerSize));
4796 __ push(MemOperand(esp, 2 * kPointerSize));
4797 __ push(result_register());
4798 EmitKeyedSuperPropertyLoad(prop);
4802 case KEYED_PROPERTY: {
4803 VisitForStackValue(prop->obj());
4804 VisitForStackValue(prop->key());
4805 __ mov(LoadDescriptor::ReceiverRegister(),
4806 Operand(esp, kPointerSize)); // Object.
4807 __ mov(LoadDescriptor::NameRegister(), Operand(esp, 0)); // Key.
4808 EmitKeyedPropertyLoad(prop);
4817 // We need a second deoptimization point after loading the value
4818 // in case evaluating the property load my have a side effect.
4819 if (assign_type == VARIABLE) {
4820 PrepareForBailout(expr->expression(), TOS_REG);
4822 PrepareForBailoutForId(prop->LoadId(), TOS_REG);
4825 // Inline smi case if we are in a loop.
4826 Label done, stub_call;
4827 JumpPatchSite patch_site(masm_);
4828 if (ShouldInlineSmiCase(expr->op())) {
4830 patch_site.EmitJumpIfNotSmi(eax, &slow, Label::kNear);
4832 // Save result for postfix expressions.
4833 if (expr->is_postfix()) {
4834 if (!context()->IsEffect()) {
4835 // Save the result on the stack. If we have a named or keyed property
4836 // we store the result under the receiver that is currently on top
4838 switch (assign_type) {
4842 case NAMED_PROPERTY:
4843 __ mov(Operand(esp, kPointerSize), eax);
4845 case NAMED_SUPER_PROPERTY:
4846 __ mov(Operand(esp, 2 * kPointerSize), eax);
4848 case KEYED_PROPERTY:
4849 __ mov(Operand(esp, 2 * kPointerSize), eax);
4851 case KEYED_SUPER_PROPERTY:
4852 __ mov(Operand(esp, 3 * kPointerSize), eax);
4858 if (expr->op() == Token::INC) {
4859 __ add(eax, Immediate(Smi::FromInt(1)));
4861 __ sub(eax, Immediate(Smi::FromInt(1)));
4863 __ j(no_overflow, &done, Label::kNear);
4864 // Call stub. Undo operation first.
4865 if (expr->op() == Token::INC) {
4866 __ sub(eax, Immediate(Smi::FromInt(1)));
4868 __ add(eax, Immediate(Smi::FromInt(1)));
4870 __ jmp(&stub_call, Label::kNear);
4873 ToNumberStub convert_stub(isolate());
4874 __ CallStub(&convert_stub);
4875 PrepareForBailoutForId(expr->ToNumberId(), TOS_REG);
4877 // Save result for postfix expressions.
4878 if (expr->is_postfix()) {
4879 if (!context()->IsEffect()) {
4880 // Save the result on the stack. If we have a named or keyed property
4881 // we store the result under the receiver that is currently on top
4883 switch (assign_type) {
4887 case NAMED_PROPERTY:
4888 __ mov(Operand(esp, kPointerSize), eax);
4890 case NAMED_SUPER_PROPERTY:
4891 __ mov(Operand(esp, 2 * kPointerSize), eax);
4893 case KEYED_PROPERTY:
4894 __ mov(Operand(esp, 2 * kPointerSize), eax);
4896 case KEYED_SUPER_PROPERTY:
4897 __ mov(Operand(esp, 3 * kPointerSize), eax);
4903 // Record position before stub call.
4904 SetSourcePosition(expr->position());
4906 // Call stub for +1/-1.
4907 __ bind(&stub_call);
4909 __ mov(eax, Immediate(Smi::FromInt(1)));
4911 CodeFactory::BinaryOpIC(
4912 isolate(), expr->binary_op(), language_mode()).code();
4913 CallIC(code, expr->CountBinOpFeedbackId());
4914 patch_site.EmitPatchInfo();
4917 // Store the value returned in eax.
4918 switch (assign_type) {
4920 if (expr->is_postfix()) {
4921 // Perform the assignment as if via '='.
4922 { EffectContext context(this);
4923 EmitVariableAssignment(expr->expression()->AsVariableProxy()->var(),
4924 Token::ASSIGN, expr->CountSlot());
4925 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
4928 // For all contexts except EffectContext We have the result on
4929 // top of the stack.
4930 if (!context()->IsEffect()) {
4931 context()->PlugTOS();
4934 // Perform the assignment as if via '='.
4935 EmitVariableAssignment(expr->expression()->AsVariableProxy()->var(),
4936 Token::ASSIGN, expr->CountSlot());
4937 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
4938 context()->Plug(eax);
4941 case NAMED_PROPERTY: {
4942 __ mov(StoreDescriptor::NameRegister(),
4943 prop->key()->AsLiteral()->value());
4944 __ pop(StoreDescriptor::ReceiverRegister());
4945 if (FLAG_vector_stores) {
4946 EmitLoadStoreICSlot(expr->CountSlot());
4949 CallStoreIC(expr->CountStoreFeedbackId());
4951 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
4952 if (expr->is_postfix()) {
4953 if (!context()->IsEffect()) {
4954 context()->PlugTOS();
4957 context()->Plug(eax);
4961 case NAMED_SUPER_PROPERTY: {
4962 EmitNamedSuperPropertyStore(prop);
4963 if (expr->is_postfix()) {
4964 if (!context()->IsEffect()) {
4965 context()->PlugTOS();
4968 context()->Plug(eax);
4972 case KEYED_SUPER_PROPERTY: {
4973 EmitKeyedSuperPropertyStore(prop);
4974 if (expr->is_postfix()) {
4975 if (!context()->IsEffect()) {
4976 context()->PlugTOS();
4979 context()->Plug(eax);
4983 case KEYED_PROPERTY: {
4984 __ pop(StoreDescriptor::NameRegister());
4985 __ pop(StoreDescriptor::ReceiverRegister());
4987 CodeFactory::KeyedStoreIC(isolate(), language_mode()).code();
4988 if (FLAG_vector_stores) {
4989 EmitLoadStoreICSlot(expr->CountSlot());
4992 CallIC(ic, expr->CountStoreFeedbackId());
4994 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
4995 if (expr->is_postfix()) {
4996 // Result is on the stack
4997 if (!context()->IsEffect()) {
4998 context()->PlugTOS();
5001 context()->Plug(eax);
5009 void FullCodeGenerator::VisitForTypeofValue(Expression* expr) {
5010 VariableProxy* proxy = expr->AsVariableProxy();
5011 DCHECK(!context()->IsEffect());
5012 DCHECK(!context()->IsTest());
5014 if (proxy != NULL && proxy->var()->IsUnallocated()) {
5015 Comment cmnt(masm_, "[ Global variable");
5016 __ mov(LoadDescriptor::ReceiverRegister(), GlobalObjectOperand());
5017 __ mov(LoadDescriptor::NameRegister(), Immediate(proxy->name()));
5018 __ mov(LoadDescriptor::SlotRegister(),
5019 Immediate(SmiFromSlot(proxy->VariableFeedbackSlot())));
5020 // Use a regular load, not a contextual load, to avoid a reference
5022 CallLoadIC(NOT_CONTEXTUAL);
5023 PrepareForBailout(expr, TOS_REG);
5024 context()->Plug(eax);
5025 } else if (proxy != NULL && proxy->var()->IsLookupSlot()) {
5026 Comment cmnt(masm_, "[ Lookup slot");
5029 // Generate code for loading from variables potentially shadowed
5030 // by eval-introduced variables.
5031 EmitDynamicLookupFastCase(proxy, INSIDE_TYPEOF, &slow, &done);
5035 __ push(Immediate(proxy->name()));
5036 __ CallRuntime(Runtime::kLoadLookupSlotNoReferenceError, 2);
5037 PrepareForBailout(expr, TOS_REG);
5040 context()->Plug(eax);
5042 // This expression cannot throw a reference error at the top level.
5043 VisitInDuplicateContext(expr);
5048 void FullCodeGenerator::EmitLiteralCompareTypeof(Expression* expr,
5049 Expression* sub_expr,
5050 Handle<String> check) {
5051 Label materialize_true, materialize_false;
5052 Label* if_true = NULL;
5053 Label* if_false = NULL;
5054 Label* fall_through = NULL;
5055 context()->PrepareTest(&materialize_true, &materialize_false,
5056 &if_true, &if_false, &fall_through);
5058 { AccumulatorValueContext context(this);
5059 VisitForTypeofValue(sub_expr);
5061 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
5063 Factory* factory = isolate()->factory();
5064 if (String::Equals(check, factory->number_string())) {
5065 __ JumpIfSmi(eax, if_true);
5066 __ cmp(FieldOperand(eax, HeapObject::kMapOffset),
5067 isolate()->factory()->heap_number_map());
5068 Split(equal, if_true, if_false, fall_through);
5069 } else if (String::Equals(check, factory->string_string())) {
5070 __ JumpIfSmi(eax, if_false);
5071 __ CmpObjectType(eax, FIRST_NONSTRING_TYPE, edx);
5072 __ j(above_equal, if_false);
5073 // Check for undetectable objects => false.
5074 __ test_b(FieldOperand(edx, Map::kBitFieldOffset),
5075 1 << Map::kIsUndetectable);
5076 Split(zero, if_true, if_false, fall_through);
5077 } else if (String::Equals(check, factory->symbol_string())) {
5078 __ JumpIfSmi(eax, if_false);
5079 __ CmpObjectType(eax, SYMBOL_TYPE, edx);
5080 Split(equal, if_true, if_false, fall_through);
5081 } else if (String::Equals(check, factory->boolean_string())) {
5082 __ cmp(eax, isolate()->factory()->true_value());
5083 __ j(equal, if_true);
5084 __ cmp(eax, isolate()->factory()->false_value());
5085 Split(equal, if_true, if_false, fall_through);
5086 } else if (String::Equals(check, factory->undefined_string())) {
5087 __ cmp(eax, isolate()->factory()->undefined_value());
5088 __ j(equal, if_true);
5089 __ JumpIfSmi(eax, if_false);
5090 // Check for undetectable objects => true.
5091 __ mov(edx, FieldOperand(eax, HeapObject::kMapOffset));
5092 __ movzx_b(ecx, FieldOperand(edx, Map::kBitFieldOffset));
5093 __ test(ecx, Immediate(1 << Map::kIsUndetectable));
5094 Split(not_zero, if_true, if_false, fall_through);
5095 } else if (String::Equals(check, factory->function_string())) {
5096 __ JumpIfSmi(eax, if_false);
5097 STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
5098 __ CmpObjectType(eax, JS_FUNCTION_TYPE, edx);
5099 __ j(equal, if_true);
5100 __ CmpInstanceType(edx, JS_FUNCTION_PROXY_TYPE);
5101 Split(equal, if_true, if_false, fall_through);
5102 } else if (String::Equals(check, factory->object_string())) {
5103 __ JumpIfSmi(eax, if_false);
5104 __ cmp(eax, isolate()->factory()->null_value());
5105 __ j(equal, if_true);
5106 __ CmpObjectType(eax, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE, edx);
5107 __ j(below, if_false);
5108 __ CmpInstanceType(edx, LAST_NONCALLABLE_SPEC_OBJECT_TYPE);
5109 __ j(above, if_false);
5110 // Check for undetectable objects => false.
5111 __ test_b(FieldOperand(edx, Map::kBitFieldOffset),
5112 1 << Map::kIsUndetectable);
5113 Split(zero, if_true, if_false, fall_through);
5115 if (if_false != fall_through) __ jmp(if_false);
5117 context()->Plug(if_true, if_false);
5121 void FullCodeGenerator::VisitCompareOperation(CompareOperation* expr) {
5122 Comment cmnt(masm_, "[ CompareOperation");
5123 SetSourcePosition(expr->position());
5125 // First we try a fast inlined version of the compare when one of
5126 // the operands is a literal.
5127 if (TryLiteralCompare(expr)) return;
5129 // Always perform the comparison for its control flow. Pack the result
5130 // into the expression's context after the comparison is performed.
5131 Label materialize_true, materialize_false;
5132 Label* if_true = NULL;
5133 Label* if_false = NULL;
5134 Label* fall_through = NULL;
5135 context()->PrepareTest(&materialize_true, &materialize_false,
5136 &if_true, &if_false, &fall_through);
5138 Token::Value op = expr->op();
5139 VisitForStackValue(expr->left());
5142 VisitForStackValue(expr->right());
5143 __ InvokeBuiltin(Builtins::IN, CALL_FUNCTION);
5144 PrepareForBailoutBeforeSplit(expr, false, NULL, NULL);
5145 __ cmp(eax, isolate()->factory()->true_value());
5146 Split(equal, if_true, if_false, fall_through);
5149 case Token::INSTANCEOF: {
5150 VisitForStackValue(expr->right());
5151 InstanceofStub stub(isolate(), InstanceofStub::kNoFlags);
5153 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
5155 // The stub returns 0 for true.
5156 Split(zero, if_true, if_false, fall_through);
5161 VisitForAccumulatorValue(expr->right());
5162 Condition cc = CompareIC::ComputeCondition(op);
5165 bool inline_smi_code = ShouldInlineSmiCase(op);
5166 JumpPatchSite patch_site(masm_);
5167 if (inline_smi_code) {
5171 patch_site.EmitJumpIfNotSmi(ecx, &slow_case, Label::kNear);
5173 Split(cc, if_true, if_false, NULL);
5174 __ bind(&slow_case);
5177 // Record position and call the compare IC.
5178 SetSourcePosition(expr->position());
5180 CodeFactory::CompareIC(isolate(), op, language_mode()).code();
5181 CallIC(ic, expr->CompareOperationFeedbackId());
5182 patch_site.EmitPatchInfo();
5184 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
5186 Split(cc, if_true, if_false, fall_through);
5190 // Convert the result of the comparison into one expected for this
5191 // expression's context.
5192 context()->Plug(if_true, if_false);
5196 void FullCodeGenerator::EmitLiteralCompareNil(CompareOperation* expr,
5197 Expression* sub_expr,
5199 Label materialize_true, materialize_false;
5200 Label* if_true = NULL;
5201 Label* if_false = NULL;
5202 Label* fall_through = NULL;
5203 context()->PrepareTest(&materialize_true, &materialize_false,
5204 &if_true, &if_false, &fall_through);
5206 VisitForAccumulatorValue(sub_expr);
5207 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
5209 Handle<Object> nil_value = nil == kNullValue
5210 ? isolate()->factory()->null_value()
5211 : isolate()->factory()->undefined_value();
5212 if (expr->op() == Token::EQ_STRICT) {
5213 __ cmp(eax, nil_value);
5214 Split(equal, if_true, if_false, fall_through);
5216 Handle<Code> ic = CompareNilICStub::GetUninitialized(isolate(), nil);
5217 CallIC(ic, expr->CompareOperationFeedbackId());
5219 Split(not_zero, if_true, if_false, fall_through);
5221 context()->Plug(if_true, if_false);
5225 void FullCodeGenerator::VisitThisFunction(ThisFunction* expr) {
5226 __ mov(eax, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
5227 context()->Plug(eax);
5231 Register FullCodeGenerator::result_register() {
5236 Register FullCodeGenerator::context_register() {
5241 void FullCodeGenerator::StoreToFrameField(int frame_offset, Register value) {
5242 DCHECK_EQ(POINTER_SIZE_ALIGN(frame_offset), frame_offset);
5243 __ mov(Operand(ebp, frame_offset), value);
5247 void FullCodeGenerator::LoadContextField(Register dst, int context_index) {
5248 __ mov(dst, ContextOperand(esi, context_index));
5252 void FullCodeGenerator::PushFunctionArgumentForContextAllocation() {
5253 Scope* declaration_scope = scope()->DeclarationScope();
5254 if (declaration_scope->is_script_scope() ||
5255 declaration_scope->is_module_scope()) {
5256 // Contexts nested in the native context have a canonical empty function
5257 // as their closure, not the anonymous closure containing the global
5258 // code. Pass a smi sentinel and let the runtime look up the empty
5260 __ push(Immediate(Smi::FromInt(0)));
5261 } else if (declaration_scope->is_eval_scope()) {
5262 // Contexts nested inside eval code have the same closure as the context
5263 // calling eval, not the anonymous closure containing the eval code.
5264 // Fetch it from the context.
5265 __ push(ContextOperand(esi, Context::CLOSURE_INDEX));
5267 DCHECK(declaration_scope->is_function_scope());
5268 __ push(Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
5273 // ----------------------------------------------------------------------------
5274 // Non-local control flow support.
5276 void FullCodeGenerator::EnterFinallyBlock() {
5277 // Cook return address on top of stack (smi encoded Code* delta)
5278 DCHECK(!result_register().is(edx));
5280 __ sub(edx, Immediate(masm_->CodeObject()));
5281 STATIC_ASSERT(kSmiTagSize + kSmiShiftSize == 1);
5282 STATIC_ASSERT(kSmiTag == 0);
5286 // Store result register while executing finally block.
5287 __ push(result_register());
5289 // Store pending message while executing finally block.
5290 ExternalReference pending_message_obj =
5291 ExternalReference::address_of_pending_message_obj(isolate());
5292 __ mov(edx, Operand::StaticVariable(pending_message_obj));
5295 ClearPendingMessage();
5299 void FullCodeGenerator::ExitFinallyBlock() {
5300 DCHECK(!result_register().is(edx));
5301 // Restore pending message from stack.
5303 ExternalReference pending_message_obj =
5304 ExternalReference::address_of_pending_message_obj(isolate());
5305 __ mov(Operand::StaticVariable(pending_message_obj), edx);
5307 // Restore result register from stack.
5308 __ pop(result_register());
5310 // Uncook return address.
5313 __ add(edx, Immediate(masm_->CodeObject()));
5318 void FullCodeGenerator::ClearPendingMessage() {
5319 DCHECK(!result_register().is(edx));
5320 ExternalReference pending_message_obj =
5321 ExternalReference::address_of_pending_message_obj(isolate());
5322 __ mov(edx, Immediate(isolate()->factory()->the_hole_value()));
5323 __ mov(Operand::StaticVariable(pending_message_obj), edx);
5327 void FullCodeGenerator::EmitLoadStoreICSlot(FeedbackVectorICSlot slot) {
5328 DCHECK(FLAG_vector_stores && !slot.IsInvalid());
5329 __ mov(VectorStoreICTrampolineDescriptor::SlotRegister(),
5330 Immediate(SmiFromSlot(slot)));
5337 static const byte kJnsInstruction = 0x79;
5338 static const byte kJnsOffset = 0x11;
5339 static const byte kNopByteOne = 0x66;
5340 static const byte kNopByteTwo = 0x90;
5342 static const byte kCallInstruction = 0xe8;
5346 void BackEdgeTable::PatchAt(Code* unoptimized_code,
5348 BackEdgeState target_state,
5349 Code* replacement_code) {
5350 Address call_target_address = pc - kIntSize;
5351 Address jns_instr_address = call_target_address - 3;
5352 Address jns_offset_address = call_target_address - 2;
5354 switch (target_state) {
5356 // sub <profiling_counter>, <delta> ;; Not changed
5358 // call <interrupt stub>
5360 *jns_instr_address = kJnsInstruction;
5361 *jns_offset_address = kJnsOffset;
5363 case ON_STACK_REPLACEMENT:
5364 case OSR_AFTER_STACK_CHECK:
5365 // sub <profiling_counter>, <delta> ;; Not changed
5368 // call <on-stack replacment>
5370 *jns_instr_address = kNopByteOne;
5371 *jns_offset_address = kNopByteTwo;
5375 Assembler::set_target_address_at(call_target_address,
5377 replacement_code->entry());
5378 unoptimized_code->GetHeap()->incremental_marking()->RecordCodeTargetPatch(
5379 unoptimized_code, call_target_address, replacement_code);
5383 BackEdgeTable::BackEdgeState BackEdgeTable::GetBackEdgeState(
5385 Code* unoptimized_code,
5387 Address call_target_address = pc - kIntSize;
5388 Address jns_instr_address = call_target_address - 3;
5389 DCHECK_EQ(kCallInstruction, *(call_target_address - 1));
5391 if (*jns_instr_address == kJnsInstruction) {
5392 DCHECK_EQ(kJnsOffset, *(call_target_address - 2));
5393 DCHECK_EQ(isolate->builtins()->InterruptCheck()->entry(),
5394 Assembler::target_address_at(call_target_address,
5399 DCHECK_EQ(kNopByteOne, *jns_instr_address);
5400 DCHECK_EQ(kNopByteTwo, *(call_target_address - 2));
5402 if (Assembler::target_address_at(call_target_address, unoptimized_code) ==
5403 isolate->builtins()->OnStackReplacement()->entry()) {
5404 return ON_STACK_REPLACEMENT;
5407 DCHECK_EQ(isolate->builtins()->OsrAfterStackCheck()->entry(),
5408 Assembler::target_address_at(call_target_address,
5410 return OSR_AFTER_STACK_CHECK;
5414 } // namespace internal
5417 #endif // V8_TARGET_ARCH_X87