1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
7 #if V8_TARGET_ARCH_IA32
9 #include "src/code-factory.h"
10 #include "src/code-stubs.h"
11 #include "src/codegen.h"
12 #include "src/compiler.h"
13 #include "src/debug.h"
14 #include "src/full-codegen.h"
15 #include "src/ic/ic.h"
16 #include "src/isolate-inl.h"
17 #include "src/parser.h"
18 #include "src/scopes.h"
23 #define __ ACCESS_MASM(masm_)
26 class JumpPatchSite BASE_EMBEDDED {
28 explicit JumpPatchSite(MacroAssembler* masm) : masm_(masm) {
30 info_emitted_ = false;
35 DCHECK(patch_site_.is_bound() == info_emitted_);
38 void EmitJumpIfNotSmi(Register reg,
40 Label::Distance distance = Label::kFar) {
41 __ test(reg, Immediate(kSmiTagMask));
42 EmitJump(not_carry, target, distance); // Always taken before patched.
45 void EmitJumpIfSmi(Register reg,
47 Label::Distance distance = Label::kFar) {
48 __ test(reg, Immediate(kSmiTagMask));
49 EmitJump(carry, target, distance); // Never taken before patched.
52 void EmitPatchInfo() {
53 if (patch_site_.is_bound()) {
54 int delta_to_patch_site = masm_->SizeOfCodeGeneratedSince(&patch_site_);
55 DCHECK(is_uint8(delta_to_patch_site));
56 __ test(eax, Immediate(delta_to_patch_site));
61 __ nop(); // Signals no inlined code.
66 // jc will be patched with jz, jnc will become jnz.
67 void EmitJump(Condition cc, Label* target, Label::Distance distance) {
68 DCHECK(!patch_site_.is_bound() && !info_emitted_);
69 DCHECK(cc == carry || cc == not_carry);
70 __ bind(&patch_site_);
71 __ j(cc, target, distance);
74 MacroAssembler* masm_;
82 // Generate code for a JS function. On entry to the function the receiver
83 // and arguments have been pushed on the stack left to right, with the
84 // return address on top of them. The actual argument count matches the
85 // formal parameter count expected by the function.
87 // The live registers are:
88 // o edi: the JS function object being called (i.e. ourselves)
90 // o ebp: our caller's frame pointer
91 // o esp: stack pointer (pointing to return address)
93 // The function builds a JS frame. Please see JavaScriptFrameConstants in
94 // frames-ia32.h for its layout.
95 void FullCodeGenerator::Generate() {
96 CompilationInfo* info = info_;
98 isolate()->factory()->NewFixedArray(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 (info->strict_mode() == SLOPPY && !info->is_native()) {
119 // +1 for return address.
120 int receiver_offset = (info->scope()->num_parameters() + 1) * kPointerSize;
121 __ mov(ecx, Operand(esp, receiver_offset));
123 __ cmp(ecx, isolate()->factory()->undefined_value());
124 __ j(not_equal, &ok, Label::kNear);
126 __ mov(ecx, GlobalObjectOperand());
127 __ mov(ecx, FieldOperand(ecx, GlobalObject::kGlobalProxyOffset));
129 __ mov(Operand(esp, receiver_offset), ecx);
134 // Open a frame scope to indicate that there is a frame on the stack. The
135 // MANUAL indicates that the scope shouldn't actually generate code to set up
136 // the frame (that is done below).
137 FrameScope frame_scope(masm_, StackFrame::MANUAL);
139 info->set_prologue_offset(masm_->pc_offset());
140 __ Prologue(info->IsCodePreAgingActive());
141 info->AddNoFrameRange(0, masm_->pc_offset());
143 { Comment cmnt(masm_, "[ Allocate locals");
144 int locals_count = info->scope()->num_stack_slots();
145 // Generators allocate locals, if any, in context slots.
146 DCHECK(!info->function()->is_generator() || locals_count == 0);
147 if (locals_count == 1) {
148 __ push(Immediate(isolate()->factory()->undefined_value()));
149 } else if (locals_count > 1) {
150 if (locals_count >= 128) {
153 __ sub(ecx, Immediate(locals_count * kPointerSize));
154 ExternalReference stack_limit =
155 ExternalReference::address_of_real_stack_limit(isolate());
156 __ cmp(ecx, Operand::StaticVariable(stack_limit));
157 __ j(above_equal, &ok, Label::kNear);
158 __ InvokeBuiltin(Builtins::STACK_OVERFLOW, CALL_FUNCTION);
161 __ mov(eax, Immediate(isolate()->factory()->undefined_value()));
162 const int kMaxPushes = 32;
163 if (locals_count >= kMaxPushes) {
164 int loop_iterations = locals_count / kMaxPushes;
165 __ mov(ecx, loop_iterations);
167 __ bind(&loop_header);
169 for (int i = 0; i < kMaxPushes; i++) {
173 __ j(not_zero, &loop_header, Label::kNear);
175 int remaining = locals_count % kMaxPushes;
176 // Emit the remaining pushes.
177 for (int i = 0; i < remaining; i++) {
183 bool function_in_register = true;
185 // Possibly allocate a local context.
186 int heap_slots = info->scope()->num_heap_slots() - Context::MIN_CONTEXT_SLOTS;
187 if (heap_slots > 0) {
188 Comment cmnt(masm_, "[ Allocate context");
189 bool need_write_barrier = true;
190 // Argument to NewContext is the function, which is still in edi.
191 if (FLAG_harmony_scoping && info->scope()->is_global_scope()) {
193 __ Push(info->scope()->GetScopeInfo());
194 __ CallRuntime(Runtime::kNewGlobalContext, 2);
195 } else if (heap_slots <= FastNewContextStub::kMaximumSlots) {
196 FastNewContextStub stub(isolate(), heap_slots);
198 // Result of FastNewContextStub is always in new space.
199 need_write_barrier = false;
202 __ CallRuntime(Runtime::kNewFunctionContext, 1);
204 function_in_register = false;
205 // Context is returned in eax. It replaces the context passed to us.
206 // It's saved in the stack and kept live in esi.
208 __ mov(Operand(ebp, StandardFrameConstants::kContextOffset), eax);
210 // Copy parameters into context if necessary.
211 int num_parameters = info->scope()->num_parameters();
212 for (int i = 0; i < num_parameters; i++) {
213 Variable* var = scope()->parameter(i);
214 if (var->IsContextSlot()) {
215 int parameter_offset = StandardFrameConstants::kCallerSPOffset +
216 (num_parameters - 1 - i) * kPointerSize;
217 // Load parameter from stack.
218 __ mov(eax, Operand(ebp, parameter_offset));
219 // Store it in the context.
220 int context_offset = Context::SlotOffset(var->index());
221 __ mov(Operand(esi, context_offset), eax);
222 // Update the write barrier. This clobbers eax and ebx.
223 if (need_write_barrier) {
224 __ RecordWriteContextSlot(esi,
229 } else if (FLAG_debug_code) {
231 __ JumpIfInNewSpace(esi, eax, &done, Label::kNear);
232 __ Abort(kExpectedNewSpaceObject);
239 Variable* arguments = scope()->arguments();
240 if (arguments != NULL) {
241 // Function uses arguments object.
242 Comment cmnt(masm_, "[ Allocate arguments object");
243 if (function_in_register) {
246 __ push(Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
248 // Receiver is just before the parameters on the caller's stack.
249 int num_parameters = info->scope()->num_parameters();
250 int offset = num_parameters * kPointerSize;
252 Operand(ebp, StandardFrameConstants::kCallerSPOffset + offset));
254 __ push(Immediate(Smi::FromInt(num_parameters)));
255 // Arguments to ArgumentsAccessStub:
256 // function, receiver address, parameter count.
257 // The stub will rewrite receiver and parameter count if the previous
258 // stack frame was an arguments adapter frame.
259 ArgumentsAccessStub::Type type;
260 if (strict_mode() == STRICT) {
261 type = ArgumentsAccessStub::NEW_STRICT;
262 } else if (function()->has_duplicate_parameters()) {
263 type = ArgumentsAccessStub::NEW_SLOPPY_SLOW;
265 type = ArgumentsAccessStub::NEW_SLOPPY_FAST;
267 ArgumentsAccessStub stub(isolate(), type);
270 SetVar(arguments, eax, ebx, edx);
274 __ CallRuntime(Runtime::kTraceEnter, 0);
277 // Visit the declarations and body unless there is an illegal
279 if (scope()->HasIllegalRedeclaration()) {
280 Comment cmnt(masm_, "[ Declarations");
281 scope()->VisitIllegalRedeclaration(this);
284 PrepareForBailoutForId(BailoutId::FunctionEntry(), NO_REGISTERS);
285 { Comment cmnt(masm_, "[ Declarations");
286 // For named function expressions, declare the function name as a
288 if (scope()->is_function_scope() && scope()->function() != NULL) {
289 VariableDeclaration* function = scope()->function();
290 DCHECK(function->proxy()->var()->mode() == CONST ||
291 function->proxy()->var()->mode() == CONST_LEGACY);
292 DCHECK(function->proxy()->var()->location() != Variable::UNALLOCATED);
293 VisitVariableDeclaration(function);
295 VisitDeclarations(scope()->declarations());
298 { Comment cmnt(masm_, "[ Stack check");
299 PrepareForBailoutForId(BailoutId::Declarations(), NO_REGISTERS);
301 ExternalReference stack_limit
302 = ExternalReference::address_of_stack_limit(isolate());
303 __ cmp(esp, Operand::StaticVariable(stack_limit));
304 __ j(above_equal, &ok, Label::kNear);
305 __ call(isolate()->builtins()->StackCheck(), RelocInfo::CODE_TARGET);
309 { Comment cmnt(masm_, "[ Body");
310 DCHECK(loop_depth() == 0);
311 VisitStatements(function()->body());
312 DCHECK(loop_depth() == 0);
316 // Always emit a 'return undefined' in case control fell off the end of
318 { Comment cmnt(masm_, "[ return <undefined>;");
319 __ mov(eax, isolate()->factory()->undefined_value());
320 EmitReturnSequence();
325 void FullCodeGenerator::ClearAccumulator() {
326 __ Move(eax, Immediate(Smi::FromInt(0)));
330 void FullCodeGenerator::EmitProfilingCounterDecrement(int delta) {
331 __ mov(ebx, Immediate(profiling_counter_));
332 __ sub(FieldOperand(ebx, Cell::kValueOffset),
333 Immediate(Smi::FromInt(delta)));
337 void FullCodeGenerator::EmitProfilingCounterReset() {
338 int reset_value = FLAG_interrupt_budget;
339 __ mov(ebx, Immediate(profiling_counter_));
340 __ mov(FieldOperand(ebx, Cell::kValueOffset),
341 Immediate(Smi::FromInt(reset_value)));
345 void FullCodeGenerator::EmitBackEdgeBookkeeping(IterationStatement* stmt,
346 Label* back_edge_target) {
347 Comment cmnt(masm_, "[ Back edge bookkeeping");
350 DCHECK(back_edge_target->is_bound());
351 int distance = masm_->SizeOfCodeGeneratedSince(back_edge_target);
352 int weight = Min(kMaxBackEdgeWeight,
353 Max(1, distance / kCodeSizeMultiplier));
354 EmitProfilingCounterDecrement(weight);
355 __ j(positive, &ok, Label::kNear);
356 __ call(isolate()->builtins()->InterruptCheck(), RelocInfo::CODE_TARGET);
358 // Record a mapping of this PC offset to the OSR id. This is used to find
359 // the AST id from the unoptimized code in order to use it as a key into
360 // the deoptimization input data found in the optimized code.
361 RecordBackEdge(stmt->OsrEntryId());
363 EmitProfilingCounterReset();
366 PrepareForBailoutForId(stmt->EntryId(), NO_REGISTERS);
367 // Record a mapping of the OSR id to this PC. This is used if the OSR
368 // entry becomes the target of a bailout. We don't expect it to be, but
369 // we want it to work if it is.
370 PrepareForBailoutForId(stmt->OsrEntryId(), NO_REGISTERS);
374 void FullCodeGenerator::EmitReturnSequence() {
375 Comment cmnt(masm_, "[ Return sequence");
376 if (return_label_.is_bound()) {
377 __ jmp(&return_label_);
379 // Common return label
380 __ bind(&return_label_);
383 __ CallRuntime(Runtime::kTraceExit, 1);
385 // Pretend that the exit is a backwards jump to the entry.
387 if (info_->ShouldSelfOptimize()) {
388 weight = FLAG_interrupt_budget / FLAG_self_opt_count;
390 int distance = masm_->pc_offset();
391 weight = Min(kMaxBackEdgeWeight,
392 Max(1, distance / kCodeSizeMultiplier));
394 EmitProfilingCounterDecrement(weight);
396 __ j(positive, &ok, Label::kNear);
398 __ call(isolate()->builtins()->InterruptCheck(),
399 RelocInfo::CODE_TARGET);
401 EmitProfilingCounterReset();
404 // Add a label for checking the size of the code used for returning.
405 Label check_exit_codesize;
406 masm_->bind(&check_exit_codesize);
408 SetSourcePosition(function()->end_position() - 1);
410 // Do not use the leave instruction here because it is too short to
411 // patch with the code required by the debugger.
413 int no_frame_start = masm_->pc_offset();
416 int arguments_bytes = (info_->scope()->num_parameters() + 1) * kPointerSize;
417 __ Ret(arguments_bytes, ecx);
418 // Check that the size of the code used for returning is large enough
419 // for the debugger's requirements.
420 DCHECK(Assembler::kJSReturnSequenceLength <=
421 masm_->SizeOfCodeGeneratedSince(&check_exit_codesize));
422 info_->AddNoFrameRange(no_frame_start, masm_->pc_offset());
427 void FullCodeGenerator::EffectContext::Plug(Variable* var) const {
428 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
432 void FullCodeGenerator::AccumulatorValueContext::Plug(Variable* var) const {
433 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
434 codegen()->GetVar(result_register(), var);
438 void FullCodeGenerator::StackValueContext::Plug(Variable* var) const {
439 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
440 MemOperand operand = codegen()->VarOperand(var, result_register());
441 // Memory operands can be pushed directly.
446 void FullCodeGenerator::TestContext::Plug(Variable* var) const {
447 // For simplicity we always test the accumulator register.
448 codegen()->GetVar(result_register(), var);
449 codegen()->PrepareForBailoutBeforeSplit(condition(), false, NULL, NULL);
450 codegen()->DoTest(this);
454 void FullCodeGenerator::EffectContext::Plug(Heap::RootListIndex index) const {
455 UNREACHABLE(); // Not used on IA32.
459 void FullCodeGenerator::AccumulatorValueContext::Plug(
460 Heap::RootListIndex index) const {
461 UNREACHABLE(); // Not used on IA32.
465 void FullCodeGenerator::StackValueContext::Plug(
466 Heap::RootListIndex index) const {
467 UNREACHABLE(); // Not used on IA32.
471 void FullCodeGenerator::TestContext::Plug(Heap::RootListIndex index) const {
472 UNREACHABLE(); // Not used on IA32.
476 void FullCodeGenerator::EffectContext::Plug(Handle<Object> lit) const {
480 void FullCodeGenerator::AccumulatorValueContext::Plug(
481 Handle<Object> lit) const {
483 __ SafeMove(result_register(), Immediate(lit));
485 __ Move(result_register(), Immediate(lit));
490 void FullCodeGenerator::StackValueContext::Plug(Handle<Object> lit) const {
492 __ SafePush(Immediate(lit));
494 __ push(Immediate(lit));
499 void FullCodeGenerator::TestContext::Plug(Handle<Object> lit) const {
500 codegen()->PrepareForBailoutBeforeSplit(condition(),
504 DCHECK(!lit->IsUndetectableObject()); // There are no undetectable literals.
505 if (lit->IsUndefined() || lit->IsNull() || lit->IsFalse()) {
506 if (false_label_ != fall_through_) __ jmp(false_label_);
507 } else if (lit->IsTrue() || lit->IsJSObject()) {
508 if (true_label_ != fall_through_) __ jmp(true_label_);
509 } else if (lit->IsString()) {
510 if (String::cast(*lit)->length() == 0) {
511 if (false_label_ != fall_through_) __ jmp(false_label_);
513 if (true_label_ != fall_through_) __ jmp(true_label_);
515 } else if (lit->IsSmi()) {
516 if (Smi::cast(*lit)->value() == 0) {
517 if (false_label_ != fall_through_) __ jmp(false_label_);
519 if (true_label_ != fall_through_) __ jmp(true_label_);
522 // For simplicity we always test the accumulator register.
523 __ mov(result_register(), lit);
524 codegen()->DoTest(this);
529 void FullCodeGenerator::EffectContext::DropAndPlug(int count,
530 Register reg) const {
536 void FullCodeGenerator::AccumulatorValueContext::DropAndPlug(
538 Register reg) const {
541 __ Move(result_register(), reg);
545 void FullCodeGenerator::StackValueContext::DropAndPlug(int count,
546 Register reg) const {
548 if (count > 1) __ Drop(count - 1);
549 __ mov(Operand(esp, 0), reg);
553 void FullCodeGenerator::TestContext::DropAndPlug(int count,
554 Register reg) const {
556 // For simplicity we always test the accumulator register.
558 __ Move(result_register(), reg);
559 codegen()->PrepareForBailoutBeforeSplit(condition(), false, NULL, NULL);
560 codegen()->DoTest(this);
564 void FullCodeGenerator::EffectContext::Plug(Label* materialize_true,
565 Label* materialize_false) const {
566 DCHECK(materialize_true == materialize_false);
567 __ bind(materialize_true);
571 void FullCodeGenerator::AccumulatorValueContext::Plug(
572 Label* materialize_true,
573 Label* materialize_false) const {
575 __ bind(materialize_true);
576 __ mov(result_register(), isolate()->factory()->true_value());
577 __ jmp(&done, Label::kNear);
578 __ bind(materialize_false);
579 __ mov(result_register(), isolate()->factory()->false_value());
584 void FullCodeGenerator::StackValueContext::Plug(
585 Label* materialize_true,
586 Label* materialize_false) const {
588 __ bind(materialize_true);
589 __ push(Immediate(isolate()->factory()->true_value()));
590 __ jmp(&done, Label::kNear);
591 __ bind(materialize_false);
592 __ push(Immediate(isolate()->factory()->false_value()));
597 void FullCodeGenerator::TestContext::Plug(Label* materialize_true,
598 Label* materialize_false) const {
599 DCHECK(materialize_true == true_label_);
600 DCHECK(materialize_false == false_label_);
604 void FullCodeGenerator::EffectContext::Plug(bool flag) const {
608 void FullCodeGenerator::AccumulatorValueContext::Plug(bool flag) const {
609 Handle<Object> value = flag
610 ? isolate()->factory()->true_value()
611 : isolate()->factory()->false_value();
612 __ mov(result_register(), value);
616 void FullCodeGenerator::StackValueContext::Plug(bool flag) const {
617 Handle<Object> value = flag
618 ? isolate()->factory()->true_value()
619 : isolate()->factory()->false_value();
620 __ push(Immediate(value));
624 void FullCodeGenerator::TestContext::Plug(bool flag) const {
625 codegen()->PrepareForBailoutBeforeSplit(condition(),
630 if (true_label_ != fall_through_) __ jmp(true_label_);
632 if (false_label_ != fall_through_) __ jmp(false_label_);
637 void FullCodeGenerator::DoTest(Expression* condition,
640 Label* fall_through) {
641 Handle<Code> ic = ToBooleanStub::GetUninitialized(isolate());
642 CallIC(ic, condition->test_id());
643 __ test(result_register(), result_register());
644 // The stub returns nonzero for true.
645 Split(not_zero, if_true, if_false, fall_through);
649 void FullCodeGenerator::Split(Condition cc,
652 Label* fall_through) {
653 if (if_false == fall_through) {
655 } else if (if_true == fall_through) {
656 __ j(NegateCondition(cc), if_false);
664 MemOperand FullCodeGenerator::StackOperand(Variable* var) {
665 DCHECK(var->IsStackAllocated());
666 // Offset is negative because higher indexes are at lower addresses.
667 int offset = -var->index() * kPointerSize;
668 // Adjust by a (parameter or local) base offset.
669 if (var->IsParameter()) {
670 offset += (info_->scope()->num_parameters() + 1) * kPointerSize;
672 offset += JavaScriptFrameConstants::kLocal0Offset;
674 return Operand(ebp, offset);
678 MemOperand FullCodeGenerator::VarOperand(Variable* var, Register scratch) {
679 DCHECK(var->IsContextSlot() || var->IsStackAllocated());
680 if (var->IsContextSlot()) {
681 int context_chain_length = scope()->ContextChainLength(var->scope());
682 __ LoadContext(scratch, context_chain_length);
683 return ContextOperand(scratch, var->index());
685 return StackOperand(var);
690 void FullCodeGenerator::GetVar(Register dest, Variable* var) {
691 DCHECK(var->IsContextSlot() || var->IsStackAllocated());
692 MemOperand location = VarOperand(var, dest);
693 __ mov(dest, location);
697 void FullCodeGenerator::SetVar(Variable* var,
701 DCHECK(var->IsContextSlot() || var->IsStackAllocated());
702 DCHECK(!scratch0.is(src));
703 DCHECK(!scratch0.is(scratch1));
704 DCHECK(!scratch1.is(src));
705 MemOperand location = VarOperand(var, scratch0);
706 __ mov(location, src);
708 // Emit the write barrier code if the location is in the heap.
709 if (var->IsContextSlot()) {
710 int offset = Context::SlotOffset(var->index());
711 DCHECK(!scratch0.is(esi) && !src.is(esi) && !scratch1.is(esi));
712 __ RecordWriteContextSlot(scratch0, offset, src, scratch1, kDontSaveFPRegs);
717 void FullCodeGenerator::PrepareForBailoutBeforeSplit(Expression* expr,
718 bool should_normalize,
721 // Only prepare for bailouts before splits if we're in a test
722 // context. Otherwise, we let the Visit function deal with the
723 // preparation to avoid preparing with the same AST id twice.
724 if (!context()->IsTest() || !info_->IsOptimizable()) return;
727 if (should_normalize) __ jmp(&skip, Label::kNear);
728 PrepareForBailout(expr, TOS_REG);
729 if (should_normalize) {
730 __ cmp(eax, isolate()->factory()->true_value());
731 Split(equal, if_true, if_false, NULL);
737 void FullCodeGenerator::EmitDebugCheckDeclarationContext(Variable* variable) {
738 // The variable in the declaration always resides in the current context.
739 DCHECK_EQ(0, scope()->ContextChainLength(variable->scope()));
740 if (generate_debug_code_) {
741 // Check that we're not inside a with or catch context.
742 __ mov(ebx, FieldOperand(esi, HeapObject::kMapOffset));
743 __ cmp(ebx, isolate()->factory()->with_context_map());
744 __ Check(not_equal, kDeclarationInWithContext);
745 __ cmp(ebx, isolate()->factory()->catch_context_map());
746 __ Check(not_equal, kDeclarationInCatchContext);
751 void FullCodeGenerator::VisitVariableDeclaration(
752 VariableDeclaration* declaration) {
753 // If it was not possible to allocate the variable at compile time, we
754 // need to "declare" it at runtime to make sure it actually exists in the
756 VariableProxy* proxy = declaration->proxy();
757 VariableMode mode = declaration->mode();
758 Variable* variable = proxy->var();
759 bool hole_init = mode == LET || mode == CONST || mode == CONST_LEGACY;
760 switch (variable->location()) {
761 case Variable::UNALLOCATED:
762 globals_->Add(variable->name(), zone());
763 globals_->Add(variable->binding_needs_init()
764 ? isolate()->factory()->the_hole_value()
765 : isolate()->factory()->undefined_value(), zone());
768 case Variable::PARAMETER:
769 case Variable::LOCAL:
771 Comment cmnt(masm_, "[ VariableDeclaration");
772 __ mov(StackOperand(variable),
773 Immediate(isolate()->factory()->the_hole_value()));
777 case Variable::CONTEXT:
779 Comment cmnt(masm_, "[ VariableDeclaration");
780 EmitDebugCheckDeclarationContext(variable);
781 __ mov(ContextOperand(esi, variable->index()),
782 Immediate(isolate()->factory()->the_hole_value()));
783 // No write barrier since the hole value is in old space.
784 PrepareForBailoutForId(proxy->id(), NO_REGISTERS);
788 case Variable::LOOKUP: {
789 Comment cmnt(masm_, "[ VariableDeclaration");
791 __ push(Immediate(variable->name()));
792 // VariableDeclaration nodes are always introduced in one of four modes.
793 DCHECK(IsDeclaredVariableMode(mode));
794 PropertyAttributes attr =
795 IsImmutableVariableMode(mode) ? READ_ONLY : NONE;
796 __ push(Immediate(Smi::FromInt(attr)));
797 // Push initial value, if any.
798 // Note: For variables we must not push an initial value (such as
799 // 'undefined') because we may have a (legal) redeclaration and we
800 // must not destroy the current value.
802 __ push(Immediate(isolate()->factory()->the_hole_value()));
804 __ push(Immediate(Smi::FromInt(0))); // Indicates no initial value.
806 __ CallRuntime(Runtime::kDeclareLookupSlot, 4);
813 void FullCodeGenerator::VisitFunctionDeclaration(
814 FunctionDeclaration* declaration) {
815 VariableProxy* proxy = declaration->proxy();
816 Variable* variable = proxy->var();
817 switch (variable->location()) {
818 case Variable::UNALLOCATED: {
819 globals_->Add(variable->name(), zone());
820 Handle<SharedFunctionInfo> function =
821 Compiler::BuildFunctionInfo(declaration->fun(), script(), info_);
822 // Check for stack-overflow exception.
823 if (function.is_null()) return SetStackOverflow();
824 globals_->Add(function, zone());
828 case Variable::PARAMETER:
829 case Variable::LOCAL: {
830 Comment cmnt(masm_, "[ FunctionDeclaration");
831 VisitForAccumulatorValue(declaration->fun());
832 __ mov(StackOperand(variable), result_register());
836 case Variable::CONTEXT: {
837 Comment cmnt(masm_, "[ FunctionDeclaration");
838 EmitDebugCheckDeclarationContext(variable);
839 VisitForAccumulatorValue(declaration->fun());
840 __ mov(ContextOperand(esi, variable->index()), result_register());
841 // We know that we have written a function, which is not a smi.
842 __ RecordWriteContextSlot(esi,
843 Context::SlotOffset(variable->index()),
849 PrepareForBailoutForId(proxy->id(), NO_REGISTERS);
853 case Variable::LOOKUP: {
854 Comment cmnt(masm_, "[ FunctionDeclaration");
856 __ push(Immediate(variable->name()));
857 __ push(Immediate(Smi::FromInt(NONE)));
858 VisitForStackValue(declaration->fun());
859 __ CallRuntime(Runtime::kDeclareLookupSlot, 4);
866 void FullCodeGenerator::VisitModuleDeclaration(ModuleDeclaration* declaration) {
867 Variable* variable = declaration->proxy()->var();
868 DCHECK(variable->location() == Variable::CONTEXT);
869 DCHECK(variable->interface()->IsFrozen());
871 Comment cmnt(masm_, "[ ModuleDeclaration");
872 EmitDebugCheckDeclarationContext(variable);
874 // Load instance object.
875 __ LoadContext(eax, scope_->ContextChainLength(scope_->GlobalScope()));
876 __ mov(eax, ContextOperand(eax, variable->interface()->Index()));
877 __ mov(eax, ContextOperand(eax, Context::EXTENSION_INDEX));
880 __ mov(ContextOperand(esi, variable->index()), eax);
881 // We know that we have written a module, which is not a smi.
882 __ RecordWriteContextSlot(esi,
883 Context::SlotOffset(variable->index()),
889 PrepareForBailoutForId(declaration->proxy()->id(), NO_REGISTERS);
891 // Traverse into body.
892 Visit(declaration->module());
896 void FullCodeGenerator::VisitImportDeclaration(ImportDeclaration* declaration) {
897 VariableProxy* proxy = declaration->proxy();
898 Variable* variable = proxy->var();
899 switch (variable->location()) {
900 case Variable::UNALLOCATED:
904 case Variable::CONTEXT: {
905 Comment cmnt(masm_, "[ ImportDeclaration");
906 EmitDebugCheckDeclarationContext(variable);
911 case Variable::PARAMETER:
912 case Variable::LOCAL:
913 case Variable::LOOKUP:
919 void FullCodeGenerator::VisitExportDeclaration(ExportDeclaration* declaration) {
924 void FullCodeGenerator::DeclareGlobals(Handle<FixedArray> pairs) {
925 // Call the runtime to declare the globals.
926 __ push(esi); // The context is the first argument.
928 __ Push(Smi::FromInt(DeclareGlobalsFlags()));
929 __ CallRuntime(Runtime::kDeclareGlobals, 3);
930 // Return value is ignored.
934 void FullCodeGenerator::DeclareModules(Handle<FixedArray> descriptions) {
935 // Call the runtime to declare the modules.
936 __ Push(descriptions);
937 __ CallRuntime(Runtime::kDeclareModules, 1);
938 // Return value is ignored.
942 void FullCodeGenerator::VisitSwitchStatement(SwitchStatement* stmt) {
943 Comment cmnt(masm_, "[ SwitchStatement");
944 Breakable nested_statement(this, stmt);
945 SetStatementPosition(stmt);
947 // Keep the switch value on the stack until a case matches.
948 VisitForStackValue(stmt->tag());
949 PrepareForBailoutForId(stmt->EntryId(), NO_REGISTERS);
951 ZoneList<CaseClause*>* clauses = stmt->cases();
952 CaseClause* default_clause = NULL; // Can occur anywhere in the list.
954 Label next_test; // Recycled for each test.
955 // Compile all the tests with branches to their bodies.
956 for (int i = 0; i < clauses->length(); i++) {
957 CaseClause* clause = clauses->at(i);
958 clause->body_target()->Unuse();
960 // The default is not a test, but remember it as final fall through.
961 if (clause->is_default()) {
962 default_clause = clause;
966 Comment cmnt(masm_, "[ Case comparison");
970 // Compile the label expression.
971 VisitForAccumulatorValue(clause->label());
973 // Perform the comparison as if via '==='.
974 __ mov(edx, Operand(esp, 0)); // Switch value.
975 bool inline_smi_code = ShouldInlineSmiCase(Token::EQ_STRICT);
976 JumpPatchSite patch_site(masm_);
977 if (inline_smi_code) {
981 patch_site.EmitJumpIfNotSmi(ecx, &slow_case, Label::kNear);
984 __ j(not_equal, &next_test);
985 __ Drop(1); // Switch value is no longer needed.
986 __ jmp(clause->body_target());
990 // Record position before stub call for type feedback.
991 SetSourcePosition(clause->position());
993 CodeFactory::CompareIC(isolate(), Token::EQ_STRICT).code();
994 CallIC(ic, clause->CompareId());
995 patch_site.EmitPatchInfo();
998 __ jmp(&skip, Label::kNear);
999 PrepareForBailout(clause, TOS_REG);
1000 __ cmp(eax, isolate()->factory()->true_value());
1001 __ j(not_equal, &next_test);
1003 __ jmp(clause->body_target());
1007 __ j(not_equal, &next_test);
1008 __ Drop(1); // Switch value is no longer needed.
1009 __ jmp(clause->body_target());
1012 // Discard the test value and jump to the default if present, otherwise to
1013 // the end of the statement.
1014 __ bind(&next_test);
1015 __ Drop(1); // Switch value is no longer needed.
1016 if (default_clause == NULL) {
1017 __ jmp(nested_statement.break_label());
1019 __ jmp(default_clause->body_target());
1022 // Compile all the case bodies.
1023 for (int i = 0; i < clauses->length(); i++) {
1024 Comment cmnt(masm_, "[ Case body");
1025 CaseClause* clause = clauses->at(i);
1026 __ bind(clause->body_target());
1027 PrepareForBailoutForId(clause->EntryId(), NO_REGISTERS);
1028 VisitStatements(clause->statements());
1031 __ bind(nested_statement.break_label());
1032 PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1036 void FullCodeGenerator::VisitForInStatement(ForInStatement* stmt) {
1037 Comment cmnt(masm_, "[ ForInStatement");
1038 FeedbackVectorSlot slot = stmt->ForInFeedbackSlot();
1040 SetStatementPosition(stmt);
1043 ForIn loop_statement(this, stmt);
1044 increment_loop_depth();
1046 // Get the object to enumerate over. If the object is null or undefined, skip
1047 // over the loop. See ECMA-262 version 5, section 12.6.4.
1048 VisitForAccumulatorValue(stmt->enumerable());
1049 __ cmp(eax, isolate()->factory()->undefined_value());
1051 __ cmp(eax, isolate()->factory()->null_value());
1054 PrepareForBailoutForId(stmt->PrepareId(), TOS_REG);
1056 // Convert the object to a JS object.
1057 Label convert, done_convert;
1058 __ JumpIfSmi(eax, &convert, Label::kNear);
1059 __ CmpObjectType(eax, FIRST_SPEC_OBJECT_TYPE, ecx);
1060 __ j(above_equal, &done_convert, Label::kNear);
1063 __ InvokeBuiltin(Builtins::TO_OBJECT, CALL_FUNCTION);
1064 __ bind(&done_convert);
1065 PrepareForBailoutForId(stmt->ToObjectId(), TOS_REG);
1068 // Check for proxies.
1069 Label call_runtime, use_cache, fixed_array;
1070 STATIC_ASSERT(FIRST_JS_PROXY_TYPE == FIRST_SPEC_OBJECT_TYPE);
1071 __ CmpObjectType(eax, LAST_JS_PROXY_TYPE, ecx);
1072 __ j(below_equal, &call_runtime);
1074 // Check cache validity in generated code. This is a fast case for
1075 // the JSObject::IsSimpleEnum cache validity checks. If we cannot
1076 // guarantee cache validity, call the runtime system to check cache
1077 // validity or get the property names in a fixed array.
1078 __ CheckEnumCache(&call_runtime);
1080 __ mov(eax, FieldOperand(eax, HeapObject::kMapOffset));
1081 __ jmp(&use_cache, Label::kNear);
1083 // Get the set of properties to enumerate.
1084 __ bind(&call_runtime);
1086 __ CallRuntime(Runtime::kGetPropertyNamesFast, 1);
1087 PrepareForBailoutForId(stmt->EnumId(), TOS_REG);
1088 __ cmp(FieldOperand(eax, HeapObject::kMapOffset),
1089 isolate()->factory()->meta_map());
1090 __ j(not_equal, &fixed_array);
1093 // We got a map in register eax. Get the enumeration cache from it.
1094 Label no_descriptors;
1095 __ bind(&use_cache);
1097 __ EnumLength(edx, eax);
1098 __ cmp(edx, Immediate(Smi::FromInt(0)));
1099 __ j(equal, &no_descriptors);
1101 __ LoadInstanceDescriptors(eax, ecx);
1102 __ mov(ecx, FieldOperand(ecx, DescriptorArray::kEnumCacheOffset));
1103 __ mov(ecx, FieldOperand(ecx, DescriptorArray::kEnumCacheBridgeCacheOffset));
1105 // Set up the four remaining stack slots.
1106 __ push(eax); // Map.
1107 __ push(ecx); // Enumeration cache.
1108 __ push(edx); // Number of valid entries for the map in the enum cache.
1109 __ push(Immediate(Smi::FromInt(0))); // Initial index.
1112 __ bind(&no_descriptors);
1113 __ add(esp, Immediate(kPointerSize));
1116 // We got a fixed array in register eax. Iterate through that.
1118 __ bind(&fixed_array);
1120 // No need for a write barrier, we are storing a Smi in the feedback vector.
1121 __ LoadHeapObject(ebx, FeedbackVector());
1122 int vector_index = FeedbackVector()->GetIndex(slot);
1123 __ mov(FieldOperand(ebx, FixedArray::OffsetOfElementAt(vector_index)),
1124 Immediate(TypeFeedbackVector::MegamorphicSentinel(isolate())));
1126 __ mov(ebx, Immediate(Smi::FromInt(1))); // Smi indicates slow check
1127 __ mov(ecx, Operand(esp, 0 * kPointerSize)); // Get enumerated object
1128 STATIC_ASSERT(FIRST_JS_PROXY_TYPE == FIRST_SPEC_OBJECT_TYPE);
1129 __ CmpObjectType(ecx, LAST_JS_PROXY_TYPE, ecx);
1130 __ j(above, &non_proxy);
1131 __ Move(ebx, Immediate(Smi::FromInt(0))); // Zero indicates proxy
1132 __ bind(&non_proxy);
1133 __ push(ebx); // Smi
1134 __ push(eax); // Array
1135 __ mov(eax, FieldOperand(eax, FixedArray::kLengthOffset));
1136 __ push(eax); // Fixed array length (as smi).
1137 __ push(Immediate(Smi::FromInt(0))); // Initial index.
1139 // Generate code for doing the condition check.
1140 PrepareForBailoutForId(stmt->BodyId(), NO_REGISTERS);
1142 __ mov(eax, Operand(esp, 0 * kPointerSize)); // Get the current index.
1143 __ cmp(eax, Operand(esp, 1 * kPointerSize)); // Compare to the array length.
1144 __ j(above_equal, loop_statement.break_label());
1146 // Get the current entry of the array into register ebx.
1147 __ mov(ebx, Operand(esp, 2 * kPointerSize));
1148 __ mov(ebx, FieldOperand(ebx, eax, times_2, FixedArray::kHeaderSize));
1150 // Get the expected map from the stack or a smi in the
1151 // permanent slow case into register edx.
1152 __ mov(edx, Operand(esp, 3 * kPointerSize));
1154 // Check if the expected map still matches that of the enumerable.
1155 // If not, we may have to filter the key.
1157 __ mov(ecx, Operand(esp, 4 * kPointerSize));
1158 __ cmp(edx, FieldOperand(ecx, HeapObject::kMapOffset));
1159 __ j(equal, &update_each, Label::kNear);
1161 // For proxies, no filtering is done.
1162 // TODO(rossberg): What if only a prototype is a proxy? Not specified yet.
1163 DCHECK(Smi::FromInt(0) == 0);
1165 __ j(zero, &update_each);
1167 // Convert the entry to a string or null if it isn't a property
1168 // anymore. If the property has been removed while iterating, we
1170 __ push(ecx); // Enumerable.
1171 __ push(ebx); // Current entry.
1172 __ InvokeBuiltin(Builtins::FILTER_KEY, CALL_FUNCTION);
1174 __ j(equal, loop_statement.continue_label());
1177 // Update the 'each' property or variable from the possibly filtered
1178 // entry in register ebx.
1179 __ bind(&update_each);
1180 __ mov(result_register(), ebx);
1181 // Perform the assignment as if via '='.
1182 { EffectContext context(this);
1183 EmitAssignment(stmt->each());
1186 // Generate code for the body of the loop.
1187 Visit(stmt->body());
1189 // Generate code for going to the next element by incrementing the
1190 // index (smi) stored on top of the stack.
1191 __ bind(loop_statement.continue_label());
1192 __ add(Operand(esp, 0 * kPointerSize), Immediate(Smi::FromInt(1)));
1194 EmitBackEdgeBookkeeping(stmt, &loop);
1197 // Remove the pointers stored on the stack.
1198 __ bind(loop_statement.break_label());
1199 __ add(esp, Immediate(5 * kPointerSize));
1201 // Exit and decrement the loop depth.
1202 PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1204 decrement_loop_depth();
1208 void FullCodeGenerator::VisitForOfStatement(ForOfStatement* stmt) {
1209 Comment cmnt(masm_, "[ ForOfStatement");
1210 SetStatementPosition(stmt);
1212 Iteration loop_statement(this, stmt);
1213 increment_loop_depth();
1215 // var iterator = iterable[Symbol.iterator]();
1216 VisitForEffect(stmt->assign_iterator());
1219 __ bind(loop_statement.continue_label());
1221 // result = iterator.next()
1222 VisitForEffect(stmt->next_result());
1224 // if (result.done) break;
1225 Label result_not_done;
1226 VisitForControl(stmt->result_done(),
1227 loop_statement.break_label(),
1230 __ bind(&result_not_done);
1232 // each = result.value
1233 VisitForEffect(stmt->assign_each());
1235 // Generate code for the body of the loop.
1236 Visit(stmt->body());
1238 // Check stack before looping.
1239 PrepareForBailoutForId(stmt->BackEdgeId(), NO_REGISTERS);
1240 EmitBackEdgeBookkeeping(stmt, loop_statement.continue_label());
1241 __ jmp(loop_statement.continue_label());
1243 // Exit and decrement the loop depth.
1244 PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1245 __ bind(loop_statement.break_label());
1246 decrement_loop_depth();
1250 void FullCodeGenerator::EmitNewClosure(Handle<SharedFunctionInfo> info,
1252 // Use the fast case closure allocation code that allocates in new
1253 // space for nested functions that don't need literals cloning. If
1254 // we're running with the --always-opt or the --prepare-always-opt
1255 // flag, we need to use the runtime function so that the new function
1256 // we are creating here gets a chance to have its code optimized and
1257 // doesn't just get a copy of the existing unoptimized code.
1258 if (!FLAG_always_opt &&
1259 !FLAG_prepare_always_opt &&
1261 scope()->is_function_scope() &&
1262 info->num_literals() == 0) {
1263 FastNewClosureStub stub(isolate(), info->strict_mode(), info->kind());
1264 __ mov(ebx, Immediate(info));
1268 __ push(Immediate(info));
1269 __ push(Immediate(pretenure
1270 ? isolate()->factory()->true_value()
1271 : isolate()->factory()->false_value()));
1272 __ CallRuntime(Runtime::kNewClosure, 3);
1274 context()->Plug(eax);
1278 void FullCodeGenerator::VisitVariableProxy(VariableProxy* expr) {
1279 Comment cmnt(masm_, "[ VariableProxy");
1280 EmitVariableLoad(expr);
1284 void FullCodeGenerator::EmitLoadHomeObject(SuperReference* expr) {
1285 Comment cnmt(masm_, "[ SuperReference ");
1287 __ mov(LoadDescriptor::ReceiverRegister(),
1288 Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
1290 Handle<Symbol> home_object_symbol(isolate()->heap()->home_object_symbol());
1291 __ mov(LoadDescriptor::NameRegister(), home_object_symbol);
1293 if (FLAG_vector_ics) {
1294 __ mov(VectorLoadICDescriptor::SlotRegister(),
1295 Immediate(SmiFromSlot(expr->HomeObjectFeedbackSlot())));
1296 CallLoadIC(NOT_CONTEXTUAL);
1298 CallLoadIC(NOT_CONTEXTUAL, expr->HomeObjectFeedbackId());
1301 __ cmp(eax, isolate()->factory()->undefined_value());
1303 __ j(not_equal, &done);
1304 __ CallRuntime(Runtime::kThrowNonMethodError, 0);
1309 void FullCodeGenerator::EmitLoadGlobalCheckExtensions(VariableProxy* proxy,
1310 TypeofState typeof_state,
1312 Register context = esi;
1313 Register temp = edx;
1317 if (s->num_heap_slots() > 0) {
1318 if (s->calls_sloppy_eval()) {
1319 // Check that extension is NULL.
1320 __ cmp(ContextOperand(context, Context::EXTENSION_INDEX),
1322 __ j(not_equal, slow);
1324 // Load next context in chain.
1325 __ mov(temp, ContextOperand(context, Context::PREVIOUS_INDEX));
1326 // Walk the rest of the chain without clobbering esi.
1329 // If no outer scope calls eval, we do not need to check more
1330 // context extensions. If we have reached an eval scope, we check
1331 // all extensions from this point.
1332 if (!s->outer_scope_calls_sloppy_eval() || s->is_eval_scope()) break;
1333 s = s->outer_scope();
1336 if (s != NULL && s->is_eval_scope()) {
1337 // Loop up the context chain. There is no frame effect so it is
1338 // safe to use raw labels here.
1340 if (!context.is(temp)) {
1341 __ mov(temp, context);
1344 // Terminate at native context.
1345 __ cmp(FieldOperand(temp, HeapObject::kMapOffset),
1346 Immediate(isolate()->factory()->native_context_map()));
1347 __ j(equal, &fast, Label::kNear);
1348 // Check that extension is NULL.
1349 __ cmp(ContextOperand(temp, Context::EXTENSION_INDEX), Immediate(0));
1350 __ j(not_equal, slow);
1351 // Load next context in chain.
1352 __ mov(temp, ContextOperand(temp, Context::PREVIOUS_INDEX));
1357 // All extension objects were empty and it is safe to use a global
1359 __ mov(LoadDescriptor::ReceiverRegister(), GlobalObjectOperand());
1360 __ mov(LoadDescriptor::NameRegister(), proxy->var()->name());
1361 if (FLAG_vector_ics) {
1362 __ mov(VectorLoadICDescriptor::SlotRegister(),
1363 Immediate(SmiFromSlot(proxy->VariableFeedbackSlot())));
1366 ContextualMode mode = (typeof_state == INSIDE_TYPEOF)
1374 MemOperand FullCodeGenerator::ContextSlotOperandCheckExtensions(Variable* var,
1376 DCHECK(var->IsContextSlot());
1377 Register context = esi;
1378 Register temp = ebx;
1380 for (Scope* s = scope(); s != var->scope(); s = s->outer_scope()) {
1381 if (s->num_heap_slots() > 0) {
1382 if (s->calls_sloppy_eval()) {
1383 // Check that extension is NULL.
1384 __ cmp(ContextOperand(context, Context::EXTENSION_INDEX),
1386 __ j(not_equal, slow);
1388 __ mov(temp, ContextOperand(context, Context::PREVIOUS_INDEX));
1389 // Walk the rest of the chain without clobbering esi.
1393 // Check that last extension is NULL.
1394 __ cmp(ContextOperand(context, Context::EXTENSION_INDEX), Immediate(0));
1395 __ j(not_equal, slow);
1397 // This function is used only for loads, not stores, so it's safe to
1398 // return an esi-based operand (the write barrier cannot be allowed to
1399 // destroy the esi register).
1400 return ContextOperand(context, var->index());
1404 void FullCodeGenerator::EmitDynamicLookupFastCase(VariableProxy* proxy,
1405 TypeofState typeof_state,
1408 // Generate fast-case code for variables that might be shadowed by
1409 // eval-introduced variables. Eval is used a lot without
1410 // introducing variables. In those cases, we do not want to
1411 // perform a runtime call for all variables in the scope
1412 // containing the eval.
1413 Variable* var = proxy->var();
1414 if (var->mode() == DYNAMIC_GLOBAL) {
1415 EmitLoadGlobalCheckExtensions(proxy, typeof_state, slow);
1417 } else if (var->mode() == DYNAMIC_LOCAL) {
1418 Variable* local = var->local_if_not_shadowed();
1419 __ mov(eax, ContextSlotOperandCheckExtensions(local, slow));
1420 if (local->mode() == LET || local->mode() == CONST ||
1421 local->mode() == CONST_LEGACY) {
1422 __ cmp(eax, isolate()->factory()->the_hole_value());
1423 __ j(not_equal, done);
1424 if (local->mode() == CONST_LEGACY) {
1425 __ mov(eax, isolate()->factory()->undefined_value());
1426 } else { // LET || CONST
1427 __ push(Immediate(var->name()));
1428 __ CallRuntime(Runtime::kThrowReferenceError, 1);
1436 void FullCodeGenerator::EmitVariableLoad(VariableProxy* proxy) {
1437 // Record position before possible IC call.
1438 SetSourcePosition(proxy->position());
1439 Variable* var = proxy->var();
1441 // Three cases: global variables, lookup variables, and all other types of
1443 switch (var->location()) {
1444 case Variable::UNALLOCATED: {
1445 Comment cmnt(masm_, "[ Global variable");
1446 __ mov(LoadDescriptor::ReceiverRegister(), GlobalObjectOperand());
1447 __ mov(LoadDescriptor::NameRegister(), var->name());
1448 if (FLAG_vector_ics) {
1449 __ mov(VectorLoadICDescriptor::SlotRegister(),
1450 Immediate(SmiFromSlot(proxy->VariableFeedbackSlot())));
1452 CallLoadIC(CONTEXTUAL);
1453 context()->Plug(eax);
1457 case Variable::PARAMETER:
1458 case Variable::LOCAL:
1459 case Variable::CONTEXT: {
1460 Comment cmnt(masm_, var->IsContextSlot() ? "[ Context variable"
1461 : "[ Stack variable");
1462 if (var->binding_needs_init()) {
1463 // var->scope() may be NULL when the proxy is located in eval code and
1464 // refers to a potential outside binding. Currently those bindings are
1465 // always looked up dynamically, i.e. in that case
1466 // var->location() == LOOKUP.
1468 DCHECK(var->scope() != NULL);
1470 // Check if the binding really needs an initialization check. The check
1471 // can be skipped in the following situation: we have a LET or CONST
1472 // binding in harmony mode, both the Variable and the VariableProxy have
1473 // the same declaration scope (i.e. they are both in global code, in the
1474 // same function or in the same eval code) and the VariableProxy is in
1475 // the source physically located after the initializer of the variable.
1477 // We cannot skip any initialization checks for CONST in non-harmony
1478 // mode because const variables may be declared but never initialized:
1479 // if (false) { const x; }; var y = x;
1481 // The condition on the declaration scopes is a conservative check for
1482 // nested functions that access a binding and are called before the
1483 // binding is initialized:
1484 // function() { f(); let x = 1; function f() { x = 2; } }
1486 bool skip_init_check;
1487 if (var->scope()->DeclarationScope() != scope()->DeclarationScope()) {
1488 skip_init_check = false;
1490 // Check that we always have valid source position.
1491 DCHECK(var->initializer_position() != RelocInfo::kNoPosition);
1492 DCHECK(proxy->position() != RelocInfo::kNoPosition);
1493 skip_init_check = var->mode() != CONST_LEGACY &&
1494 var->initializer_position() < proxy->position();
1497 if (!skip_init_check) {
1498 // Let and const need a read barrier.
1501 __ cmp(eax, isolate()->factory()->the_hole_value());
1502 __ j(not_equal, &done, Label::kNear);
1503 if (var->mode() == LET || var->mode() == CONST) {
1504 // Throw a reference error when using an uninitialized let/const
1505 // binding in harmony mode.
1506 __ push(Immediate(var->name()));
1507 __ CallRuntime(Runtime::kThrowReferenceError, 1);
1509 // Uninitalized const bindings outside of harmony mode are unholed.
1510 DCHECK(var->mode() == CONST_LEGACY);
1511 __ mov(eax, isolate()->factory()->undefined_value());
1514 context()->Plug(eax);
1518 context()->Plug(var);
1522 case Variable::LOOKUP: {
1523 Comment cmnt(masm_, "[ Lookup variable");
1525 // Generate code for loading from variables potentially shadowed
1526 // by eval-introduced variables.
1527 EmitDynamicLookupFastCase(proxy, NOT_INSIDE_TYPEOF, &slow, &done);
1529 __ push(esi); // Context.
1530 __ push(Immediate(var->name()));
1531 __ CallRuntime(Runtime::kLoadLookupSlot, 2);
1533 context()->Plug(eax);
1540 void FullCodeGenerator::VisitRegExpLiteral(RegExpLiteral* expr) {
1541 Comment cmnt(masm_, "[ RegExpLiteral");
1543 // Registers will be used as follows:
1544 // edi = JS function.
1545 // ecx = literals array.
1546 // ebx = regexp literal.
1547 // eax = regexp literal clone.
1548 __ mov(edi, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
1549 __ mov(ecx, FieldOperand(edi, JSFunction::kLiteralsOffset));
1550 int literal_offset =
1551 FixedArray::kHeaderSize + expr->literal_index() * kPointerSize;
1552 __ mov(ebx, FieldOperand(ecx, literal_offset));
1553 __ cmp(ebx, isolate()->factory()->undefined_value());
1554 __ j(not_equal, &materialized, Label::kNear);
1556 // Create regexp literal using runtime function
1557 // Result will be in eax.
1559 __ push(Immediate(Smi::FromInt(expr->literal_index())));
1560 __ push(Immediate(expr->pattern()));
1561 __ push(Immediate(expr->flags()));
1562 __ CallRuntime(Runtime::kMaterializeRegExpLiteral, 4);
1565 __ bind(&materialized);
1566 int size = JSRegExp::kSize + JSRegExp::kInObjectFieldCount * kPointerSize;
1567 Label allocated, runtime_allocate;
1568 __ Allocate(size, eax, ecx, edx, &runtime_allocate, TAG_OBJECT);
1571 __ bind(&runtime_allocate);
1573 __ push(Immediate(Smi::FromInt(size)));
1574 __ CallRuntime(Runtime::kAllocateInNewSpace, 1);
1577 __ bind(&allocated);
1578 // Copy the content into the newly allocated memory.
1579 // (Unroll copy loop once for better throughput).
1580 for (int i = 0; i < size - kPointerSize; i += 2 * kPointerSize) {
1581 __ mov(edx, FieldOperand(ebx, i));
1582 __ mov(ecx, FieldOperand(ebx, i + kPointerSize));
1583 __ mov(FieldOperand(eax, i), edx);
1584 __ mov(FieldOperand(eax, i + kPointerSize), ecx);
1586 if ((size % (2 * kPointerSize)) != 0) {
1587 __ mov(edx, FieldOperand(ebx, size - kPointerSize));
1588 __ mov(FieldOperand(eax, size - kPointerSize), edx);
1590 context()->Plug(eax);
1594 void FullCodeGenerator::EmitAccessor(Expression* expression) {
1595 if (expression == NULL) {
1596 __ push(Immediate(isolate()->factory()->null_value()));
1598 VisitForStackValue(expression);
1603 void FullCodeGenerator::VisitObjectLiteral(ObjectLiteral* expr) {
1604 Comment cmnt(masm_, "[ ObjectLiteral");
1606 expr->BuildConstantProperties(isolate());
1607 Handle<FixedArray> constant_properties = expr->constant_properties();
1608 int flags = expr->fast_elements()
1609 ? ObjectLiteral::kFastElements
1610 : ObjectLiteral::kNoFlags;
1611 flags |= expr->has_function()
1612 ? ObjectLiteral::kHasFunction
1613 : ObjectLiteral::kNoFlags;
1614 int properties_count = constant_properties->length() / 2;
1615 if (expr->may_store_doubles() || expr->depth() > 1 ||
1616 masm()->serializer_enabled() ||
1617 flags != ObjectLiteral::kFastElements ||
1618 properties_count > FastCloneShallowObjectStub::kMaximumClonedProperties) {
1619 __ mov(edi, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
1620 __ push(FieldOperand(edi, JSFunction::kLiteralsOffset));
1621 __ push(Immediate(Smi::FromInt(expr->literal_index())));
1622 __ push(Immediate(constant_properties));
1623 __ push(Immediate(Smi::FromInt(flags)));
1624 __ CallRuntime(Runtime::kCreateObjectLiteral, 4);
1626 __ mov(edi, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
1627 __ mov(eax, FieldOperand(edi, JSFunction::kLiteralsOffset));
1628 __ mov(ebx, Immediate(Smi::FromInt(expr->literal_index())));
1629 __ mov(ecx, Immediate(constant_properties));
1630 __ mov(edx, Immediate(Smi::FromInt(flags)));
1631 FastCloneShallowObjectStub stub(isolate(), properties_count);
1634 PrepareForBailoutForId(expr->CreateLiteralId(), TOS_REG);
1636 // If result_saved is true the result is on top of the stack. If
1637 // result_saved is false the result is in eax.
1638 bool result_saved = false;
1640 // Mark all computed expressions that are bound to a key that
1641 // is shadowed by a later occurrence of the same key. For the
1642 // marked expressions, no store code is emitted.
1643 expr->CalculateEmitStore(zone());
1645 AccessorTable accessor_table(zone());
1646 for (int i = 0; i < expr->properties()->length(); i++) {
1647 ObjectLiteral::Property* property = expr->properties()->at(i);
1648 if (property->IsCompileTimeValue()) continue;
1650 Literal* key = property->key();
1651 Expression* value = property->value();
1652 if (!result_saved) {
1653 __ push(eax); // Save result on the stack
1654 result_saved = true;
1656 switch (property->kind()) {
1657 case ObjectLiteral::Property::CONSTANT:
1659 case ObjectLiteral::Property::MATERIALIZED_LITERAL:
1660 DCHECK(!CompileTimeValue::IsCompileTimeValue(value));
1662 case ObjectLiteral::Property::COMPUTED:
1663 // It is safe to use [[Put]] here because the boilerplate already
1664 // contains computed properties with an uninitialized value.
1665 if (key->value()->IsInternalizedString()) {
1666 if (property->emit_store()) {
1667 VisitForAccumulatorValue(value);
1668 DCHECK(StoreDescriptor::ValueRegister().is(eax));
1669 __ mov(StoreDescriptor::NameRegister(), Immediate(key->value()));
1670 __ mov(StoreDescriptor::ReceiverRegister(), Operand(esp, 0));
1671 CallStoreIC(key->LiteralFeedbackId());
1672 PrepareForBailoutForId(key->id(), NO_REGISTERS);
1674 VisitForEffect(value);
1678 __ push(Operand(esp, 0)); // Duplicate receiver.
1679 VisitForStackValue(key);
1680 VisitForStackValue(value);
1681 if (property->emit_store()) {
1682 __ push(Immediate(Smi::FromInt(SLOPPY))); // Strict mode
1683 __ CallRuntime(Runtime::kSetProperty, 4);
1688 case ObjectLiteral::Property::PROTOTYPE:
1689 __ push(Operand(esp, 0)); // Duplicate receiver.
1690 VisitForStackValue(value);
1691 if (property->emit_store()) {
1692 __ CallRuntime(Runtime::kInternalSetPrototype, 2);
1697 case ObjectLiteral::Property::GETTER:
1698 accessor_table.lookup(key)->second->getter = value;
1700 case ObjectLiteral::Property::SETTER:
1701 accessor_table.lookup(key)->second->setter = value;
1706 // Emit code to define accessors, using only a single call to the runtime for
1707 // each pair of corresponding getters and setters.
1708 for (AccessorTable::Iterator it = accessor_table.begin();
1709 it != accessor_table.end();
1711 __ push(Operand(esp, 0)); // Duplicate receiver.
1712 VisitForStackValue(it->first);
1713 EmitAccessor(it->second->getter);
1714 EmitAccessor(it->second->setter);
1715 __ push(Immediate(Smi::FromInt(NONE)));
1716 __ CallRuntime(Runtime::kDefineAccessorPropertyUnchecked, 5);
1719 if (expr->has_function()) {
1720 DCHECK(result_saved);
1721 __ push(Operand(esp, 0));
1722 __ CallRuntime(Runtime::kToFastProperties, 1);
1726 context()->PlugTOS();
1728 context()->Plug(eax);
1733 void FullCodeGenerator::VisitArrayLiteral(ArrayLiteral* expr) {
1734 Comment cmnt(masm_, "[ ArrayLiteral");
1736 expr->BuildConstantElements(isolate());
1737 int flags = expr->depth() == 1
1738 ? ArrayLiteral::kShallowElements
1739 : ArrayLiteral::kNoFlags;
1741 ZoneList<Expression*>* subexprs = expr->values();
1742 int length = subexprs->length();
1743 Handle<FixedArray> constant_elements = expr->constant_elements();
1744 DCHECK_EQ(2, constant_elements->length());
1745 ElementsKind constant_elements_kind =
1746 static_cast<ElementsKind>(Smi::cast(constant_elements->get(0))->value());
1747 bool has_constant_fast_elements =
1748 IsFastObjectElementsKind(constant_elements_kind);
1749 Handle<FixedArrayBase> constant_elements_values(
1750 FixedArrayBase::cast(constant_elements->get(1)));
1752 AllocationSiteMode allocation_site_mode = TRACK_ALLOCATION_SITE;
1753 if (has_constant_fast_elements && !FLAG_allocation_site_pretenuring) {
1754 // If the only customer of allocation sites is transitioning, then
1755 // we can turn it off if we don't have anywhere else to transition to.
1756 allocation_site_mode = DONT_TRACK_ALLOCATION_SITE;
1759 if (expr->depth() > 1 || length > JSObject::kInitialMaxFastElementArray) {
1760 __ mov(ebx, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
1761 __ push(FieldOperand(ebx, JSFunction::kLiteralsOffset));
1762 __ push(Immediate(Smi::FromInt(expr->literal_index())));
1763 __ push(Immediate(constant_elements));
1764 __ push(Immediate(Smi::FromInt(flags)));
1765 __ CallRuntime(Runtime::kCreateArrayLiteral, 4);
1767 __ mov(ebx, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
1768 __ mov(eax, FieldOperand(ebx, JSFunction::kLiteralsOffset));
1769 __ mov(ebx, Immediate(Smi::FromInt(expr->literal_index())));
1770 __ mov(ecx, Immediate(constant_elements));
1771 FastCloneShallowArrayStub stub(isolate(), allocation_site_mode);
1775 bool result_saved = false; // Is the result saved to the stack?
1777 // Emit code to evaluate all the non-constant subexpressions and to store
1778 // them into the newly cloned array.
1779 for (int i = 0; i < length; i++) {
1780 Expression* subexpr = subexprs->at(i);
1781 // If the subexpression is a literal or a simple materialized literal it
1782 // is already set in the cloned array.
1783 if (CompileTimeValue::IsCompileTimeValue(subexpr)) continue;
1785 if (!result_saved) {
1786 __ push(eax); // array literal.
1787 __ push(Immediate(Smi::FromInt(expr->literal_index())));
1788 result_saved = true;
1790 VisitForAccumulatorValue(subexpr);
1792 if (IsFastObjectElementsKind(constant_elements_kind)) {
1793 // Fast-case array literal with ElementsKind of FAST_*_ELEMENTS, they
1794 // cannot transition and don't need to call the runtime stub.
1795 int offset = FixedArray::kHeaderSize + (i * kPointerSize);
1796 __ mov(ebx, Operand(esp, kPointerSize)); // Copy of array literal.
1797 __ mov(ebx, FieldOperand(ebx, JSObject::kElementsOffset));
1798 // Store the subexpression value in the array's elements.
1799 __ mov(FieldOperand(ebx, offset), result_register());
1800 // Update the write barrier for the array store.
1801 __ RecordWriteField(ebx, offset, result_register(), ecx,
1803 EMIT_REMEMBERED_SET,
1806 // Store the subexpression value in the array's elements.
1807 __ mov(ecx, Immediate(Smi::FromInt(i)));
1808 StoreArrayLiteralElementStub stub(isolate());
1812 PrepareForBailoutForId(expr->GetIdForElement(i), NO_REGISTERS);
1816 __ add(esp, Immediate(kPointerSize)); // literal index
1817 context()->PlugTOS();
1819 context()->Plug(eax);
1824 void FullCodeGenerator::VisitAssignment(Assignment* expr) {
1825 DCHECK(expr->target()->IsValidReferenceExpression());
1827 Comment cmnt(masm_, "[ Assignment");
1829 Property* property = expr->target()->AsProperty();
1830 LhsKind assign_type = GetAssignType(property);
1832 // Evaluate LHS expression.
1833 switch (assign_type) {
1835 // Nothing to do here.
1837 case NAMED_SUPER_PROPERTY:
1838 VisitForStackValue(property->obj()->AsSuperReference()->this_var());
1839 EmitLoadHomeObject(property->obj()->AsSuperReference());
1840 __ push(result_register());
1841 if (expr->is_compound()) {
1842 __ push(MemOperand(esp, kPointerSize));
1843 __ push(result_register());
1846 case NAMED_PROPERTY:
1847 if (expr->is_compound()) {
1848 // We need the receiver both on the stack and in the register.
1849 VisitForStackValue(property->obj());
1850 __ mov(LoadDescriptor::ReceiverRegister(), Operand(esp, 0));
1852 VisitForStackValue(property->obj());
1855 case KEYED_SUPER_PROPERTY:
1856 VisitForStackValue(property->obj()->AsSuperReference()->this_var());
1857 EmitLoadHomeObject(property->obj()->AsSuperReference());
1858 __ Push(result_register());
1859 VisitForAccumulatorValue(property->key());
1860 __ Push(result_register());
1861 if (expr->is_compound()) {
1862 __ push(MemOperand(esp, 2 * kPointerSize));
1863 __ push(MemOperand(esp, 2 * kPointerSize));
1864 __ push(result_register());
1867 case KEYED_PROPERTY: {
1868 if (expr->is_compound()) {
1869 VisitForStackValue(property->obj());
1870 VisitForStackValue(property->key());
1871 __ mov(LoadDescriptor::ReceiverRegister(), Operand(esp, kPointerSize));
1872 __ mov(LoadDescriptor::NameRegister(), Operand(esp, 0));
1874 VisitForStackValue(property->obj());
1875 VisitForStackValue(property->key());
1881 // For compound assignments we need another deoptimization point after the
1882 // variable/property load.
1883 if (expr->is_compound()) {
1884 AccumulatorValueContext result_context(this);
1885 { AccumulatorValueContext left_operand_context(this);
1886 switch (assign_type) {
1888 EmitVariableLoad(expr->target()->AsVariableProxy());
1889 PrepareForBailout(expr->target(), TOS_REG);
1891 case NAMED_SUPER_PROPERTY:
1892 EmitNamedSuperPropertyLoad(property);
1893 PrepareForBailoutForId(property->LoadId(), TOS_REG);
1895 case NAMED_PROPERTY:
1896 EmitNamedPropertyLoad(property);
1897 PrepareForBailoutForId(property->LoadId(), TOS_REG);
1899 case KEYED_SUPER_PROPERTY:
1900 EmitKeyedSuperPropertyLoad(property);
1901 PrepareForBailoutForId(property->LoadId(), TOS_REG);
1903 case KEYED_PROPERTY:
1904 EmitKeyedPropertyLoad(property);
1905 PrepareForBailoutForId(property->LoadId(), TOS_REG);
1910 Token::Value op = expr->binary_op();
1911 __ push(eax); // Left operand goes on the stack.
1912 VisitForAccumulatorValue(expr->value());
1914 OverwriteMode mode = expr->value()->ResultOverwriteAllowed()
1917 SetSourcePosition(expr->position() + 1);
1918 if (ShouldInlineSmiCase(op)) {
1919 EmitInlineSmiBinaryOp(expr->binary_operation(),
1925 EmitBinaryOp(expr->binary_operation(), op, mode);
1928 // Deoptimization point in case the binary operation may have side effects.
1929 PrepareForBailout(expr->binary_operation(), TOS_REG);
1931 VisitForAccumulatorValue(expr->value());
1934 // Record source position before possible IC call.
1935 SetSourcePosition(expr->position());
1938 switch (assign_type) {
1940 EmitVariableAssignment(expr->target()->AsVariableProxy()->var(),
1942 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
1943 context()->Plug(eax);
1945 case NAMED_PROPERTY:
1946 EmitNamedPropertyAssignment(expr);
1948 case NAMED_SUPER_PROPERTY:
1949 EmitNamedSuperPropertyStore(property);
1950 context()->Plug(result_register());
1952 case KEYED_SUPER_PROPERTY:
1953 EmitKeyedSuperPropertyStore(property);
1954 context()->Plug(result_register());
1956 case KEYED_PROPERTY:
1957 EmitKeyedPropertyAssignment(expr);
1963 void FullCodeGenerator::VisitYield(Yield* expr) {
1964 Comment cmnt(masm_, "[ Yield");
1965 // Evaluate yielded value first; the initial iterator definition depends on
1966 // this. It stays on the stack while we update the iterator.
1967 VisitForStackValue(expr->expression());
1969 switch (expr->yield_kind()) {
1970 case Yield::kSuspend:
1971 // Pop value from top-of-stack slot; box result into result register.
1972 EmitCreateIteratorResult(false);
1973 __ push(result_register());
1975 case Yield::kInitial: {
1976 Label suspend, continuation, post_runtime, resume;
1980 __ bind(&continuation);
1984 VisitForAccumulatorValue(expr->generator_object());
1985 DCHECK(continuation.pos() > 0 && Smi::IsValid(continuation.pos()));
1986 __ mov(FieldOperand(eax, JSGeneratorObject::kContinuationOffset),
1987 Immediate(Smi::FromInt(continuation.pos())));
1988 __ mov(FieldOperand(eax, JSGeneratorObject::kContextOffset), esi);
1990 __ RecordWriteField(eax, JSGeneratorObject::kContextOffset, ecx, edx,
1992 __ lea(ebx, Operand(ebp, StandardFrameConstants::kExpressionsOffset));
1994 __ j(equal, &post_runtime);
1995 __ push(eax); // generator object
1996 __ CallRuntime(Runtime::kSuspendJSGeneratorObject, 1);
1997 __ mov(context_register(),
1998 Operand(ebp, StandardFrameConstants::kContextOffset));
1999 __ bind(&post_runtime);
2000 __ pop(result_register());
2001 EmitReturnSequence();
2004 context()->Plug(result_register());
2008 case Yield::kFinal: {
2009 VisitForAccumulatorValue(expr->generator_object());
2010 __ mov(FieldOperand(result_register(),
2011 JSGeneratorObject::kContinuationOffset),
2012 Immediate(Smi::FromInt(JSGeneratorObject::kGeneratorClosed)));
2013 // Pop value from top-of-stack slot, box result into result register.
2014 EmitCreateIteratorResult(true);
2015 EmitUnwindBeforeReturn();
2016 EmitReturnSequence();
2020 case Yield::kDelegating: {
2021 VisitForStackValue(expr->generator_object());
2023 // Initial stack layout is as follows:
2024 // [sp + 1 * kPointerSize] iter
2025 // [sp + 0 * kPointerSize] g
2027 Label l_catch, l_try, l_suspend, l_continuation, l_resume;
2028 Label l_next, l_call, l_loop;
2029 Register load_receiver = LoadDescriptor::ReceiverRegister();
2030 Register load_name = LoadDescriptor::NameRegister();
2032 // Initial send value is undefined.
2033 __ mov(eax, isolate()->factory()->undefined_value());
2036 // catch (e) { receiver = iter; f = 'throw'; arg = e; goto l_call; }
2038 handler_table()->set(expr->index(), Smi::FromInt(l_catch.pos()));
2039 __ mov(load_name, isolate()->factory()->throw_string()); // "throw"
2040 __ push(load_name); // "throw"
2041 __ push(Operand(esp, 2 * kPointerSize)); // iter
2042 __ push(eax); // exception
2045 // try { received = %yield result }
2046 // Shuffle the received result above a try handler and yield it without
2049 __ pop(eax); // result
2050 __ PushTryHandler(StackHandler::CATCH, expr->index());
2051 const int handler_size = StackHandlerConstants::kSize;
2052 __ push(eax); // result
2054 __ bind(&l_continuation);
2056 __ bind(&l_suspend);
2057 const int generator_object_depth = kPointerSize + handler_size;
2058 __ mov(eax, Operand(esp, generator_object_depth));
2060 DCHECK(l_continuation.pos() > 0 && Smi::IsValid(l_continuation.pos()));
2061 __ mov(FieldOperand(eax, JSGeneratorObject::kContinuationOffset),
2062 Immediate(Smi::FromInt(l_continuation.pos())));
2063 __ mov(FieldOperand(eax, JSGeneratorObject::kContextOffset), esi);
2065 __ RecordWriteField(eax, JSGeneratorObject::kContextOffset, ecx, edx,
2067 __ CallRuntime(Runtime::kSuspendJSGeneratorObject, 1);
2068 __ mov(context_register(),
2069 Operand(ebp, StandardFrameConstants::kContextOffset));
2070 __ pop(eax); // result
2071 EmitReturnSequence();
2072 __ bind(&l_resume); // received in eax
2075 // receiver = iter; f = iter.next; arg = received;
2078 __ mov(load_name, isolate()->factory()->next_string());
2079 __ push(load_name); // "next"
2080 __ push(Operand(esp, 2 * kPointerSize)); // iter
2081 __ push(eax); // received
2083 // result = receiver[f](arg);
2085 __ mov(load_receiver, Operand(esp, kPointerSize));
2086 if (FLAG_vector_ics) {
2087 __ mov(VectorLoadICDescriptor::SlotRegister(),
2088 Immediate(SmiFromSlot(expr->KeyedLoadFeedbackSlot())));
2090 Handle<Code> ic = CodeFactory::KeyedLoadIC(isolate()).code();
2091 CallIC(ic, TypeFeedbackId::None());
2093 __ mov(Operand(esp, 2 * kPointerSize), edi);
2094 CallFunctionStub stub(isolate(), 1, CALL_AS_METHOD);
2097 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
2098 __ Drop(1); // The function is still on the stack; drop it.
2100 // if (!result.done) goto l_try;
2102 __ push(eax); // save result
2103 __ Move(load_receiver, eax); // result
2105 isolate()->factory()->done_string()); // "done"
2106 if (FLAG_vector_ics) {
2107 __ mov(VectorLoadICDescriptor::SlotRegister(),
2108 Immediate(SmiFromSlot(expr->DoneFeedbackSlot())));
2110 CallLoadIC(NOT_CONTEXTUAL); // result.done in eax
2111 Handle<Code> bool_ic = ToBooleanStub::GetUninitialized(isolate());
2117 __ pop(load_receiver); // result
2119 isolate()->factory()->value_string()); // "value"
2120 if (FLAG_vector_ics) {
2121 __ mov(VectorLoadICDescriptor::SlotRegister(),
2122 Immediate(SmiFromSlot(expr->ValueFeedbackSlot())));
2124 CallLoadIC(NOT_CONTEXTUAL); // result.value in eax
2125 context()->DropAndPlug(2, eax); // drop iter and g
2132 void FullCodeGenerator::EmitGeneratorResume(Expression *generator,
2134 JSGeneratorObject::ResumeMode resume_mode) {
2135 // The value stays in eax, and is ultimately read by the resumed generator, as
2136 // if CallRuntime(Runtime::kSuspendJSGeneratorObject) returned it. Or it
2137 // is read to throw the value when the resumed generator is already closed.
2138 // ebx will hold the generator object until the activation has been resumed.
2139 VisitForStackValue(generator);
2140 VisitForAccumulatorValue(value);
2143 // Check generator state.
2144 Label wrong_state, closed_state, done;
2145 STATIC_ASSERT(JSGeneratorObject::kGeneratorExecuting < 0);
2146 STATIC_ASSERT(JSGeneratorObject::kGeneratorClosed == 0);
2147 __ cmp(FieldOperand(ebx, JSGeneratorObject::kContinuationOffset),
2148 Immediate(Smi::FromInt(0)));
2149 __ j(equal, &closed_state);
2150 __ j(less, &wrong_state);
2152 // Load suspended function and context.
2153 __ mov(esi, FieldOperand(ebx, JSGeneratorObject::kContextOffset));
2154 __ mov(edi, FieldOperand(ebx, JSGeneratorObject::kFunctionOffset));
2157 __ push(FieldOperand(ebx, JSGeneratorObject::kReceiverOffset));
2159 // Push holes for arguments to generator function.
2160 __ mov(edx, FieldOperand(edi, JSFunction::kSharedFunctionInfoOffset));
2162 FieldOperand(edx, SharedFunctionInfo::kFormalParameterCountOffset));
2163 __ mov(ecx, isolate()->factory()->the_hole_value());
2164 Label push_argument_holes, push_frame;
2165 __ bind(&push_argument_holes);
2166 __ sub(edx, Immediate(Smi::FromInt(1)));
2167 __ j(carry, &push_frame);
2169 __ jmp(&push_argument_holes);
2171 // Enter a new JavaScript frame, and initialize its slots as they were when
2172 // the generator was suspended.
2174 __ bind(&push_frame);
2175 __ call(&resume_frame);
2177 __ bind(&resume_frame);
2178 __ push(ebp); // Caller's frame pointer.
2180 __ push(esi); // Callee's context.
2181 __ push(edi); // Callee's JS Function.
2183 // Load the operand stack size.
2184 __ mov(edx, FieldOperand(ebx, JSGeneratorObject::kOperandStackOffset));
2185 __ mov(edx, FieldOperand(edx, FixedArray::kLengthOffset));
2188 // If we are sending a value and there is no operand stack, we can jump back
2190 if (resume_mode == JSGeneratorObject::NEXT) {
2192 __ cmp(edx, Immediate(0));
2193 __ j(not_zero, &slow_resume);
2194 __ mov(edx, FieldOperand(edi, JSFunction::kCodeEntryOffset));
2195 __ mov(ecx, FieldOperand(ebx, JSGeneratorObject::kContinuationOffset));
2198 __ mov(FieldOperand(ebx, JSGeneratorObject::kContinuationOffset),
2199 Immediate(Smi::FromInt(JSGeneratorObject::kGeneratorExecuting)));
2201 __ bind(&slow_resume);
2204 // Otherwise, we push holes for the operand stack and call the runtime to fix
2205 // up the stack and the handlers.
2206 Label push_operand_holes, call_resume;
2207 __ bind(&push_operand_holes);
2208 __ sub(edx, Immediate(1));
2209 __ j(carry, &call_resume);
2211 __ jmp(&push_operand_holes);
2212 __ bind(&call_resume);
2214 __ push(result_register());
2215 __ Push(Smi::FromInt(resume_mode));
2216 __ CallRuntime(Runtime::kResumeJSGeneratorObject, 3);
2217 // Not reached: the runtime call returns elsewhere.
2218 __ Abort(kGeneratorFailedToResume);
2220 // Reach here when generator is closed.
2221 __ bind(&closed_state);
2222 if (resume_mode == JSGeneratorObject::NEXT) {
2223 // Return completed iterator result when generator is closed.
2224 __ push(Immediate(isolate()->factory()->undefined_value()));
2225 // Pop value from top-of-stack slot; box result into result register.
2226 EmitCreateIteratorResult(true);
2228 // Throw the provided value.
2230 __ CallRuntime(Runtime::kThrow, 1);
2234 // Throw error if we attempt to operate on a running generator.
2235 __ bind(&wrong_state);
2237 __ CallRuntime(Runtime::kThrowGeneratorStateError, 1);
2240 context()->Plug(result_register());
2244 void FullCodeGenerator::EmitCreateIteratorResult(bool done) {
2248 const int instance_size = 5 * kPointerSize;
2249 DCHECK_EQ(isolate()->native_context()->iterator_result_map()->instance_size(),
2252 __ Allocate(instance_size, eax, ecx, edx, &gc_required, TAG_OBJECT);
2255 __ bind(&gc_required);
2256 __ Push(Smi::FromInt(instance_size));
2257 __ CallRuntime(Runtime::kAllocateInNewSpace, 1);
2258 __ mov(context_register(),
2259 Operand(ebp, StandardFrameConstants::kContextOffset));
2261 __ bind(&allocated);
2262 __ mov(ebx, Operand(esi, Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX)));
2263 __ mov(ebx, FieldOperand(ebx, GlobalObject::kNativeContextOffset));
2264 __ mov(ebx, ContextOperand(ebx, Context::ITERATOR_RESULT_MAP_INDEX));
2266 __ mov(edx, isolate()->factory()->ToBoolean(done));
2267 __ mov(FieldOperand(eax, HeapObject::kMapOffset), ebx);
2268 __ mov(FieldOperand(eax, JSObject::kPropertiesOffset),
2269 isolate()->factory()->empty_fixed_array());
2270 __ mov(FieldOperand(eax, JSObject::kElementsOffset),
2271 isolate()->factory()->empty_fixed_array());
2272 __ mov(FieldOperand(eax, JSGeneratorObject::kResultValuePropertyOffset), ecx);
2273 __ mov(FieldOperand(eax, JSGeneratorObject::kResultDonePropertyOffset), edx);
2275 // Only the value field needs a write barrier, as the other values are in the
2277 __ RecordWriteField(eax, JSGeneratorObject::kResultValuePropertyOffset,
2278 ecx, edx, kDontSaveFPRegs);
2282 void FullCodeGenerator::EmitNamedPropertyLoad(Property* prop) {
2283 SetSourcePosition(prop->position());
2284 Literal* key = prop->key()->AsLiteral();
2285 DCHECK(!key->value()->IsSmi());
2286 DCHECK(!prop->IsSuperAccess());
2288 __ mov(LoadDescriptor::NameRegister(), Immediate(key->value()));
2289 if (FLAG_vector_ics) {
2290 __ mov(VectorLoadICDescriptor::SlotRegister(),
2291 Immediate(SmiFromSlot(prop->PropertyFeedbackSlot())));
2292 CallLoadIC(NOT_CONTEXTUAL);
2294 CallLoadIC(NOT_CONTEXTUAL, prop->PropertyFeedbackId());
2299 void FullCodeGenerator::EmitNamedSuperPropertyLoad(Property* prop) {
2300 // Stack: receiver, home_object.
2301 SetSourcePosition(prop->position());
2302 Literal* key = prop->key()->AsLiteral();
2303 DCHECK(!key->value()->IsSmi());
2304 DCHECK(prop->IsSuperAccess());
2306 __ push(Immediate(key->value()));
2307 __ CallRuntime(Runtime::kLoadFromSuper, 3);
2311 void FullCodeGenerator::EmitKeyedPropertyLoad(Property* prop) {
2312 SetSourcePosition(prop->position());
2313 Handle<Code> ic = CodeFactory::KeyedLoadIC(isolate()).code();
2314 if (FLAG_vector_ics) {
2315 __ mov(VectorLoadICDescriptor::SlotRegister(),
2316 Immediate(SmiFromSlot(prop->PropertyFeedbackSlot())));
2319 CallIC(ic, prop->PropertyFeedbackId());
2324 void FullCodeGenerator::EmitKeyedSuperPropertyLoad(Property* prop) {
2325 // Stack: receiver, home_object, key.
2326 SetSourcePosition(prop->position());
2328 __ CallRuntime(Runtime::kLoadKeyedFromSuper, 3);
2332 void FullCodeGenerator::EmitInlineSmiBinaryOp(BinaryOperation* expr,
2336 Expression* right) {
2337 // Do combined smi check of the operands. Left operand is on the
2338 // stack. Right operand is in eax.
2339 Label smi_case, done, stub_call;
2343 JumpPatchSite patch_site(masm_);
2344 patch_site.EmitJumpIfSmi(eax, &smi_case, Label::kNear);
2346 __ bind(&stub_call);
2348 Handle<Code> code = CodeFactory::BinaryOpIC(isolate(), op, mode).code();
2349 CallIC(code, expr->BinaryOperationFeedbackId());
2350 patch_site.EmitPatchInfo();
2351 __ jmp(&done, Label::kNear);
2355 __ mov(eax, edx); // Copy left operand in case of a stub call.
2360 __ sar_cl(eax); // No checks of result necessary
2361 __ and_(eax, Immediate(~kSmiTagMask));
2368 // Check that the *signed* result fits in a smi.
2369 __ cmp(eax, 0xc0000000);
2370 __ j(positive, &result_ok);
2373 __ bind(&result_ok);
2382 __ test(eax, Immediate(0xc0000000));
2383 __ j(zero, &result_ok);
2386 __ bind(&result_ok);
2392 __ j(overflow, &stub_call);
2396 __ j(overflow, &stub_call);
2401 __ j(overflow, &stub_call);
2403 __ j(not_zero, &done, Label::kNear);
2406 __ j(negative, &stub_call);
2412 case Token::BIT_AND:
2415 case Token::BIT_XOR:
2423 context()->Plug(eax);
2427 void FullCodeGenerator::EmitClassDefineProperties(ClassLiteral* lit) {
2428 // Constructor is in eax.
2429 DCHECK(lit != NULL);
2432 // No access check is needed here since the constructor is created by the
2434 Register scratch = ebx;
2435 __ mov(scratch, FieldOperand(eax, JSFunction::kPrototypeOrInitialMapOffset));
2438 for (int i = 0; i < lit->properties()->length(); i++) {
2439 ObjectLiteral::Property* property = lit->properties()->at(i);
2440 Literal* key = property->key()->AsLiteral();
2441 Expression* value = property->value();
2442 DCHECK(key != NULL);
2444 if (property->is_static()) {
2445 __ push(Operand(esp, kPointerSize)); // constructor
2447 __ push(Operand(esp, 0)); // prototype
2449 VisitForStackValue(key);
2450 VisitForStackValue(value);
2452 switch (property->kind()) {
2453 case ObjectLiteral::Property::CONSTANT:
2454 case ObjectLiteral::Property::MATERIALIZED_LITERAL:
2455 case ObjectLiteral::Property::COMPUTED:
2456 case ObjectLiteral::Property::PROTOTYPE:
2457 __ CallRuntime(Runtime::kDefineClassMethod, 3);
2460 case ObjectLiteral::Property::GETTER:
2461 __ CallRuntime(Runtime::kDefineClassGetter, 3);
2464 case ObjectLiteral::Property::SETTER:
2465 __ CallRuntime(Runtime::kDefineClassSetter, 3);
2474 __ CallRuntime(Runtime::kToFastProperties, 1);
2477 __ CallRuntime(Runtime::kToFastProperties, 1);
2481 void FullCodeGenerator::EmitBinaryOp(BinaryOperation* expr,
2483 OverwriteMode mode) {
2485 Handle<Code> code = CodeFactory::BinaryOpIC(isolate(), op, mode).code();
2486 JumpPatchSite patch_site(masm_); // unbound, signals no inlined smi code.
2487 CallIC(code, expr->BinaryOperationFeedbackId());
2488 patch_site.EmitPatchInfo();
2489 context()->Plug(eax);
2493 void FullCodeGenerator::EmitAssignment(Expression* expr) {
2494 DCHECK(expr->IsValidReferenceExpression());
2496 Property* prop = expr->AsProperty();
2497 LhsKind assign_type = GetAssignType(prop);
2499 switch (assign_type) {
2501 Variable* var = expr->AsVariableProxy()->var();
2502 EffectContext context(this);
2503 EmitVariableAssignment(var, Token::ASSIGN);
2506 case NAMED_PROPERTY: {
2507 __ push(eax); // Preserve value.
2508 VisitForAccumulatorValue(prop->obj());
2509 __ Move(StoreDescriptor::ReceiverRegister(), eax);
2510 __ pop(StoreDescriptor::ValueRegister()); // Restore value.
2511 __ mov(StoreDescriptor::NameRegister(),
2512 prop->key()->AsLiteral()->value());
2516 case NAMED_SUPER_PROPERTY: {
2518 VisitForStackValue(prop->obj()->AsSuperReference()->this_var());
2519 EmitLoadHomeObject(prop->obj()->AsSuperReference());
2520 // stack: value, this; eax: home_object
2521 Register scratch = ecx;
2522 Register scratch2 = edx;
2523 __ mov(scratch, result_register()); // home_object
2524 __ mov(eax, MemOperand(esp, kPointerSize)); // value
2525 __ mov(scratch2, MemOperand(esp, 0)); // this
2526 __ mov(MemOperand(esp, kPointerSize), scratch2); // this
2527 __ mov(MemOperand(esp, 0), scratch); // home_object
2528 // stack: this, home_object. eax: value
2529 EmitNamedSuperPropertyStore(prop);
2532 case KEYED_SUPER_PROPERTY: {
2534 VisitForStackValue(prop->obj()->AsSuperReference()->this_var());
2535 EmitLoadHomeObject(prop->obj()->AsSuperReference());
2536 __ push(result_register());
2537 VisitForAccumulatorValue(prop->key());
2538 Register scratch = ecx;
2539 Register scratch2 = edx;
2540 __ mov(scratch2, MemOperand(esp, 2 * kPointerSize)); // value
2541 // stack: value, this, home_object; eax: key, edx: value
2542 __ mov(scratch, MemOperand(esp, kPointerSize)); // this
2543 __ mov(MemOperand(esp, 2 * kPointerSize), scratch);
2544 __ mov(scratch, MemOperand(esp, 0)); // home_object
2545 __ mov(MemOperand(esp, kPointerSize), scratch);
2546 __ mov(MemOperand(esp, 0), eax);
2547 __ mov(eax, scratch2);
2548 // stack: this, home_object, key; eax: value.
2549 EmitKeyedSuperPropertyStore(prop);
2552 case KEYED_PROPERTY: {
2553 __ push(eax); // Preserve value.
2554 VisitForStackValue(prop->obj());
2555 VisitForAccumulatorValue(prop->key());
2556 __ Move(StoreDescriptor::NameRegister(), eax);
2557 __ pop(StoreDescriptor::ReceiverRegister()); // Receiver.
2558 __ pop(StoreDescriptor::ValueRegister()); // Restore value.
2560 CodeFactory::KeyedStoreIC(isolate(), strict_mode()).code();
2565 context()->Plug(eax);
2569 void FullCodeGenerator::EmitStoreToStackLocalOrContextSlot(
2570 Variable* var, MemOperand location) {
2571 __ mov(location, eax);
2572 if (var->IsContextSlot()) {
2574 int offset = Context::SlotOffset(var->index());
2575 __ RecordWriteContextSlot(ecx, offset, edx, ebx, kDontSaveFPRegs);
2580 void FullCodeGenerator::EmitVariableAssignment(Variable* var,
2582 if (var->IsUnallocated()) {
2583 // Global var, const, or let.
2584 __ mov(StoreDescriptor::NameRegister(), var->name());
2585 __ mov(StoreDescriptor::ReceiverRegister(), GlobalObjectOperand());
2588 } else if (op == Token::INIT_CONST_LEGACY) {
2589 // Const initializers need a write barrier.
2590 DCHECK(!var->IsParameter()); // No const parameters.
2591 if (var->IsLookupSlot()) {
2594 __ push(Immediate(var->name()));
2595 __ CallRuntime(Runtime::kInitializeLegacyConstLookupSlot, 3);
2597 DCHECK(var->IsStackLocal() || var->IsContextSlot());
2599 MemOperand location = VarOperand(var, ecx);
2600 __ mov(edx, location);
2601 __ cmp(edx, isolate()->factory()->the_hole_value());
2602 __ j(not_equal, &skip, Label::kNear);
2603 EmitStoreToStackLocalOrContextSlot(var, location);
2607 } else if (var->mode() == LET && op != Token::INIT_LET) {
2608 // Non-initializing assignment to let variable needs a write barrier.
2609 DCHECK(!var->IsLookupSlot());
2610 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
2612 MemOperand location = VarOperand(var, ecx);
2613 __ mov(edx, location);
2614 __ cmp(edx, isolate()->factory()->the_hole_value());
2615 __ j(not_equal, &assign, Label::kNear);
2616 __ push(Immediate(var->name()));
2617 __ CallRuntime(Runtime::kThrowReferenceError, 1);
2619 EmitStoreToStackLocalOrContextSlot(var, location);
2621 } else if (!var->is_const_mode() || op == Token::INIT_CONST) {
2622 if (var->IsLookupSlot()) {
2623 // Assignment to var.
2624 __ push(eax); // Value.
2625 __ push(esi); // Context.
2626 __ push(Immediate(var->name()));
2627 __ push(Immediate(Smi::FromInt(strict_mode())));
2628 __ CallRuntime(Runtime::kStoreLookupSlot, 4);
2630 // Assignment to var or initializing assignment to let/const in harmony
2632 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
2633 MemOperand location = VarOperand(var, ecx);
2634 if (generate_debug_code_ && op == Token::INIT_LET) {
2635 // Check for an uninitialized let binding.
2636 __ mov(edx, location);
2637 __ cmp(edx, isolate()->factory()->the_hole_value());
2638 __ Check(equal, kLetBindingReInitialization);
2640 EmitStoreToStackLocalOrContextSlot(var, location);
2643 // Non-initializing assignments to consts are ignored.
2647 void FullCodeGenerator::EmitNamedPropertyAssignment(Assignment* expr) {
2648 // Assignment to a property, using a named store IC.
2650 // esp[0] : receiver
2652 Property* prop = expr->target()->AsProperty();
2653 DCHECK(prop != NULL);
2654 DCHECK(prop->key()->IsLiteral());
2656 // Record source code position before IC call.
2657 SetSourcePosition(expr->position());
2658 __ mov(StoreDescriptor::NameRegister(), prop->key()->AsLiteral()->value());
2659 __ pop(StoreDescriptor::ReceiverRegister());
2660 CallStoreIC(expr->AssignmentFeedbackId());
2661 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
2662 context()->Plug(eax);
2666 void FullCodeGenerator::EmitNamedSuperPropertyStore(Property* prop) {
2667 // Assignment to named property of super.
2669 // stack : receiver ('this'), home_object
2670 DCHECK(prop != NULL);
2671 Literal* key = prop->key()->AsLiteral();
2672 DCHECK(key != NULL);
2674 __ push(Immediate(key->value()));
2676 __ CallRuntime((strict_mode() == STRICT ? Runtime::kStoreToSuper_Strict
2677 : Runtime::kStoreToSuper_Sloppy),
2682 void FullCodeGenerator::EmitKeyedSuperPropertyStore(Property* prop) {
2683 // Assignment to named property of super.
2685 // stack : receiver ('this'), home_object, key
2688 __ CallRuntime((strict_mode() == STRICT ? Runtime::kStoreKeyedToSuper_Strict
2689 : Runtime::kStoreKeyedToSuper_Sloppy),
2694 void FullCodeGenerator::EmitKeyedPropertyAssignment(Assignment* expr) {
2695 // Assignment to a property, using a keyed store IC.
2698 // esp[kPointerSize] : receiver
2700 __ pop(StoreDescriptor::NameRegister()); // Key.
2701 __ pop(StoreDescriptor::ReceiverRegister());
2702 DCHECK(StoreDescriptor::ValueRegister().is(eax));
2703 // Record source code position before IC call.
2704 SetSourcePosition(expr->position());
2705 Handle<Code> ic = CodeFactory::KeyedStoreIC(isolate(), strict_mode()).code();
2706 CallIC(ic, expr->AssignmentFeedbackId());
2708 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
2709 context()->Plug(eax);
2713 void FullCodeGenerator::VisitProperty(Property* expr) {
2714 Comment cmnt(masm_, "[ Property");
2715 Expression* key = expr->key();
2717 if (key->IsPropertyName()) {
2718 if (!expr->IsSuperAccess()) {
2719 VisitForAccumulatorValue(expr->obj());
2720 __ Move(LoadDescriptor::ReceiverRegister(), result_register());
2721 EmitNamedPropertyLoad(expr);
2723 VisitForStackValue(expr->obj()->AsSuperReference()->this_var());
2724 EmitLoadHomeObject(expr->obj()->AsSuperReference());
2725 __ push(result_register());
2726 EmitNamedSuperPropertyLoad(expr);
2728 PrepareForBailoutForId(expr->LoadId(), TOS_REG);
2729 context()->Plug(eax);
2731 if (!expr->IsSuperAccess()) {
2732 VisitForStackValue(expr->obj());
2733 VisitForAccumulatorValue(expr->key());
2734 __ pop(LoadDescriptor::ReceiverRegister()); // Object.
2735 __ Move(LoadDescriptor::NameRegister(), result_register()); // Key.
2736 EmitKeyedPropertyLoad(expr);
2738 VisitForStackValue(expr->obj()->AsSuperReference()->this_var());
2739 EmitLoadHomeObject(expr->obj()->AsSuperReference());
2740 __ push(result_register());
2741 VisitForStackValue(expr->key());
2742 EmitKeyedSuperPropertyLoad(expr);
2744 context()->Plug(eax);
2749 void FullCodeGenerator::CallIC(Handle<Code> code,
2750 TypeFeedbackId ast_id) {
2752 __ call(code, RelocInfo::CODE_TARGET, ast_id);
2756 // Code common for calls using the IC.
2757 void FullCodeGenerator::EmitCallWithLoadIC(Call* expr) {
2758 Expression* callee = expr->expression();
2760 CallICState::CallType call_type =
2761 callee->IsVariableProxy() ? CallICState::FUNCTION : CallICState::METHOD;
2762 // Get the target function.
2763 if (call_type == CallICState::FUNCTION) {
2764 { StackValueContext context(this);
2765 EmitVariableLoad(callee->AsVariableProxy());
2766 PrepareForBailout(callee, NO_REGISTERS);
2768 // Push undefined as receiver. This is patched in the method prologue if it
2769 // is a sloppy mode method.
2770 __ push(Immediate(isolate()->factory()->undefined_value()));
2772 // Load the function from the receiver.
2773 DCHECK(callee->IsProperty());
2774 DCHECK(!callee->AsProperty()->IsSuperAccess());
2775 __ mov(LoadDescriptor::ReceiverRegister(), Operand(esp, 0));
2776 EmitNamedPropertyLoad(callee->AsProperty());
2777 PrepareForBailoutForId(callee->AsProperty()->LoadId(), TOS_REG);
2778 // Push the target function under the receiver.
2779 __ push(Operand(esp, 0));
2780 __ mov(Operand(esp, kPointerSize), eax);
2783 EmitCall(expr, call_type);
2787 void FullCodeGenerator::EmitSuperCallWithLoadIC(Call* expr) {
2788 Expression* callee = expr->expression();
2789 DCHECK(callee->IsProperty());
2790 Property* prop = callee->AsProperty();
2791 DCHECK(prop->IsSuperAccess());
2793 SetSourcePosition(prop->position());
2794 Literal* key = prop->key()->AsLiteral();
2795 DCHECK(!key->value()->IsSmi());
2796 // Load the function from the receiver.
2797 SuperReference* super_ref = callee->AsProperty()->obj()->AsSuperReference();
2798 EmitLoadHomeObject(super_ref);
2800 VisitForAccumulatorValue(super_ref->this_var());
2803 __ push(Operand(esp, kPointerSize * 2));
2804 __ push(Immediate(key->value()));
2807 // - this (receiver)
2808 // - this (receiver) <-- LoadFromSuper will pop here and below.
2811 __ CallRuntime(Runtime::kLoadFromSuper, 3);
2813 // Replace home_object with target function.
2814 __ mov(Operand(esp, kPointerSize), eax);
2817 // - target function
2818 // - this (receiver)
2819 EmitCall(expr, CallICState::METHOD);
2823 // Code common for calls using the IC.
2824 void FullCodeGenerator::EmitKeyedCallWithLoadIC(Call* expr,
2827 VisitForAccumulatorValue(key);
2829 Expression* callee = expr->expression();
2831 // Load the function from the receiver.
2832 DCHECK(callee->IsProperty());
2833 __ mov(LoadDescriptor::ReceiverRegister(), Operand(esp, 0));
2834 __ mov(LoadDescriptor::NameRegister(), eax);
2835 EmitKeyedPropertyLoad(callee->AsProperty());
2836 PrepareForBailoutForId(callee->AsProperty()->LoadId(), TOS_REG);
2838 // Push the target function under the receiver.
2839 __ push(Operand(esp, 0));
2840 __ mov(Operand(esp, kPointerSize), eax);
2842 EmitCall(expr, CallICState::METHOD);
2846 void FullCodeGenerator::EmitKeyedSuperCallWithLoadIC(Call* expr) {
2847 Expression* callee = expr->expression();
2848 DCHECK(callee->IsProperty());
2849 Property* prop = callee->AsProperty();
2850 DCHECK(prop->IsSuperAccess());
2852 SetSourcePosition(prop->position());
2853 // Load the function from the receiver.
2854 SuperReference* super_ref = callee->AsProperty()->obj()->AsSuperReference();
2855 EmitLoadHomeObject(super_ref);
2857 VisitForAccumulatorValue(super_ref->this_var());
2860 __ push(Operand(esp, kPointerSize * 2));
2861 VisitForStackValue(prop->key());
2864 // - this (receiver)
2865 // - this (receiver) <-- LoadKeyedFromSuper will pop here and below.
2868 __ CallRuntime(Runtime::kLoadKeyedFromSuper, 3);
2870 // Replace home_object with target function.
2871 __ mov(Operand(esp, kPointerSize), eax);
2874 // - target function
2875 // - this (receiver)
2876 EmitCall(expr, CallICState::METHOD);
2880 void FullCodeGenerator::EmitCall(Call* expr, CallICState::CallType call_type) {
2881 // Load the arguments.
2882 ZoneList<Expression*>* args = expr->arguments();
2883 int arg_count = args->length();
2884 { PreservePositionScope scope(masm()->positions_recorder());
2885 for (int i = 0; i < arg_count; i++) {
2886 VisitForStackValue(args->at(i));
2890 // Record source position of the IC call.
2891 SetSourcePosition(expr->position());
2892 Handle<Code> ic = CallIC::initialize_stub(
2893 isolate(), arg_count, call_type);
2894 __ Move(edx, Immediate(SmiFromSlot(expr->CallFeedbackSlot())));
2895 __ mov(edi, Operand(esp, (arg_count + 1) * kPointerSize));
2896 // Don't assign a type feedback id to the IC, since type feedback is provided
2897 // by the vector above.
2900 RecordJSReturnSite(expr);
2902 // Restore context register.
2903 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
2905 context()->DropAndPlug(1, eax);
2909 void FullCodeGenerator::EmitResolvePossiblyDirectEval(int arg_count) {
2910 // Push copy of the first argument or undefined if it doesn't exist.
2911 if (arg_count > 0) {
2912 __ push(Operand(esp, arg_count * kPointerSize));
2914 __ push(Immediate(isolate()->factory()->undefined_value()));
2917 // Push the enclosing function.
2918 __ push(Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
2919 // Push the receiver of the enclosing function.
2920 __ push(Operand(ebp, (2 + info_->scope()->num_parameters()) * kPointerSize));
2921 // Push the language mode.
2922 __ push(Immediate(Smi::FromInt(strict_mode())));
2924 // Push the start position of the scope the calls resides in.
2925 __ push(Immediate(Smi::FromInt(scope()->start_position())));
2927 // Do the runtime call.
2928 __ CallRuntime(Runtime::kResolvePossiblyDirectEval, 6);
2932 void FullCodeGenerator::EmitLoadSuperConstructor(SuperReference* super_ref) {
2933 DCHECK(super_ref != NULL);
2934 __ push(Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
2935 __ CallRuntime(Runtime::kGetPrototype, 1);
2939 void FullCodeGenerator::VisitCall(Call* expr) {
2941 // We want to verify that RecordJSReturnSite gets called on all paths
2942 // through this function. Avoid early returns.
2943 expr->return_is_recorded_ = false;
2946 Comment cmnt(masm_, "[ Call");
2947 Expression* callee = expr->expression();
2948 Call::CallType call_type = expr->GetCallType(isolate());
2950 if (call_type == Call::POSSIBLY_EVAL_CALL) {
2951 // In a call to eval, we first call RuntimeHidden_ResolvePossiblyDirectEval
2952 // to resolve the function we need to call and the receiver of the call.
2953 // Then we call the resolved function using the given arguments.
2954 ZoneList<Expression*>* args = expr->arguments();
2955 int arg_count = args->length();
2956 { PreservePositionScope pos_scope(masm()->positions_recorder());
2957 VisitForStackValue(callee);
2958 // Reserved receiver slot.
2959 __ push(Immediate(isolate()->factory()->undefined_value()));
2960 // Push the arguments.
2961 for (int i = 0; i < arg_count; i++) {
2962 VisitForStackValue(args->at(i));
2965 // Push a copy of the function (found below the arguments) and
2967 __ push(Operand(esp, (arg_count + 1) * kPointerSize));
2968 EmitResolvePossiblyDirectEval(arg_count);
2970 // The runtime call returns a pair of values in eax (function) and
2971 // edx (receiver). Touch up the stack with the right values.
2972 __ mov(Operand(esp, (arg_count + 0) * kPointerSize), edx);
2973 __ mov(Operand(esp, (arg_count + 1) * kPointerSize), eax);
2975 PrepareForBailoutForId(expr->EvalOrLookupId(), NO_REGISTERS);
2977 // Record source position for debugger.
2978 SetSourcePosition(expr->position());
2979 CallFunctionStub stub(isolate(), arg_count, NO_CALL_FUNCTION_FLAGS);
2980 __ mov(edi, Operand(esp, (arg_count + 1) * kPointerSize));
2982 RecordJSReturnSite(expr);
2983 // Restore context register.
2984 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
2985 context()->DropAndPlug(1, eax);
2987 } else if (call_type == Call::GLOBAL_CALL) {
2988 EmitCallWithLoadIC(expr);
2990 } else if (call_type == Call::LOOKUP_SLOT_CALL) {
2991 // Call to a lookup slot (dynamically introduced variable).
2992 VariableProxy* proxy = callee->AsVariableProxy();
2994 { PreservePositionScope scope(masm()->positions_recorder());
2995 // Generate code for loading from variables potentially shadowed by
2996 // eval-introduced variables.
2997 EmitDynamicLookupFastCase(proxy, NOT_INSIDE_TYPEOF, &slow, &done);
3000 // Call the runtime to find the function to call (returned in eax) and
3001 // the object holding it (returned in edx).
3002 __ push(context_register());
3003 __ push(Immediate(proxy->name()));
3004 __ CallRuntime(Runtime::kLoadLookupSlot, 2);
3005 __ push(eax); // Function.
3006 __ push(edx); // Receiver.
3007 PrepareForBailoutForId(expr->EvalOrLookupId(), NO_REGISTERS);
3009 // If fast case code has been generated, emit code to push the function
3010 // and receiver and have the slow path jump around this code.
3011 if (done.is_linked()) {
3013 __ jmp(&call, Label::kNear);
3017 // The receiver is implicitly the global receiver. Indicate this by
3018 // passing the hole to the call function stub.
3019 __ push(Immediate(isolate()->factory()->undefined_value()));
3023 // The receiver is either the global receiver or an object found by
3027 } else if (call_type == Call::PROPERTY_CALL) {
3028 Property* property = callee->AsProperty();
3029 bool is_named_call = property->key()->IsPropertyName();
3030 if (property->IsSuperAccess()) {
3031 if (is_named_call) {
3032 EmitSuperCallWithLoadIC(expr);
3034 EmitKeyedSuperCallWithLoadIC(expr);
3038 PreservePositionScope scope(masm()->positions_recorder());
3039 VisitForStackValue(property->obj());
3041 if (is_named_call) {
3042 EmitCallWithLoadIC(expr);
3044 EmitKeyedCallWithLoadIC(expr, property->key());
3047 } else if (call_type == Call::SUPER_CALL) {
3048 SuperReference* super_ref = callee->AsSuperReference();
3049 EmitLoadSuperConstructor(super_ref);
3050 __ push(result_register());
3051 VisitForStackValue(super_ref->this_var());
3052 EmitCall(expr, CallICState::METHOD);
3054 DCHECK(call_type == Call::OTHER_CALL);
3055 // Call to an arbitrary expression not handled specially above.
3056 { PreservePositionScope scope(masm()->positions_recorder());
3057 VisitForStackValue(callee);
3059 __ push(Immediate(isolate()->factory()->undefined_value()));
3060 // Emit function call.
3065 // RecordJSReturnSite should have been called.
3066 DCHECK(expr->return_is_recorded_);
3071 void FullCodeGenerator::VisitCallNew(CallNew* expr) {
3072 Comment cmnt(masm_, "[ CallNew");
3073 // According to ECMA-262, section 11.2.2, page 44, the function
3074 // expression in new calls must be evaluated before the
3077 // Push constructor on the stack. If it's not a function it's used as
3078 // receiver for CALL_NON_FUNCTION, otherwise the value on the stack is
3080 if (expr->expression()->IsSuperReference()) {
3081 EmitLoadSuperConstructor(expr->expression()->AsSuperReference());
3082 __ push(result_register());
3084 VisitForStackValue(expr->expression());
3087 // Push the arguments ("left-to-right") on the stack.
3088 ZoneList<Expression*>* args = expr->arguments();
3089 int arg_count = args->length();
3090 for (int i = 0; i < arg_count; i++) {
3091 VisitForStackValue(args->at(i));
3094 // Call the construct call builtin that handles allocation and
3095 // constructor invocation.
3096 SetSourcePosition(expr->position());
3098 // Load function and argument count into edi and eax.
3099 __ Move(eax, Immediate(arg_count));
3100 __ mov(edi, Operand(esp, arg_count * kPointerSize));
3102 // Record call targets in unoptimized code.
3103 if (FLAG_pretenuring_call_new) {
3104 EnsureSlotContainsAllocationSite(expr->AllocationSiteFeedbackSlot());
3105 DCHECK(expr->AllocationSiteFeedbackSlot().ToInt() ==
3106 expr->CallNewFeedbackSlot().ToInt() + 1);
3109 __ LoadHeapObject(ebx, FeedbackVector());
3110 __ mov(edx, Immediate(SmiFromSlot(expr->CallNewFeedbackSlot())));
3112 CallConstructStub stub(isolate(), RECORD_CONSTRUCTOR_TARGET);
3113 __ call(stub.GetCode(), RelocInfo::CONSTRUCT_CALL);
3114 PrepareForBailoutForId(expr->ReturnId(), TOS_REG);
3115 context()->Plug(eax);
3119 void FullCodeGenerator::EmitIsSmi(CallRuntime* expr) {
3120 ZoneList<Expression*>* args = expr->arguments();
3121 DCHECK(args->length() == 1);
3123 VisitForAccumulatorValue(args->at(0));
3125 Label materialize_true, materialize_false;
3126 Label* if_true = NULL;
3127 Label* if_false = NULL;
3128 Label* fall_through = NULL;
3129 context()->PrepareTest(&materialize_true, &materialize_false,
3130 &if_true, &if_false, &fall_through);
3132 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3133 __ test(eax, Immediate(kSmiTagMask));
3134 Split(zero, if_true, if_false, fall_through);
3136 context()->Plug(if_true, if_false);
3140 void FullCodeGenerator::EmitIsNonNegativeSmi(CallRuntime* expr) {
3141 ZoneList<Expression*>* args = expr->arguments();
3142 DCHECK(args->length() == 1);
3144 VisitForAccumulatorValue(args->at(0));
3146 Label materialize_true, materialize_false;
3147 Label* if_true = NULL;
3148 Label* if_false = NULL;
3149 Label* fall_through = NULL;
3150 context()->PrepareTest(&materialize_true, &materialize_false,
3151 &if_true, &if_false, &fall_through);
3153 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3154 __ test(eax, Immediate(kSmiTagMask | 0x80000000));
3155 Split(zero, if_true, if_false, fall_through);
3157 context()->Plug(if_true, if_false);
3161 void FullCodeGenerator::EmitIsObject(CallRuntime* expr) {
3162 ZoneList<Expression*>* args = expr->arguments();
3163 DCHECK(args->length() == 1);
3165 VisitForAccumulatorValue(args->at(0));
3167 Label materialize_true, materialize_false;
3168 Label* if_true = NULL;
3169 Label* if_false = NULL;
3170 Label* fall_through = NULL;
3171 context()->PrepareTest(&materialize_true, &materialize_false,
3172 &if_true, &if_false, &fall_through);
3174 __ JumpIfSmi(eax, if_false);
3175 __ cmp(eax, isolate()->factory()->null_value());
3176 __ j(equal, if_true);
3177 __ mov(ebx, FieldOperand(eax, HeapObject::kMapOffset));
3178 // Undetectable objects behave like undefined when tested with typeof.
3179 __ movzx_b(ecx, FieldOperand(ebx, Map::kBitFieldOffset));
3180 __ test(ecx, Immediate(1 << Map::kIsUndetectable));
3181 __ j(not_zero, if_false);
3182 __ movzx_b(ecx, FieldOperand(ebx, Map::kInstanceTypeOffset));
3183 __ cmp(ecx, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE);
3184 __ j(below, if_false);
3185 __ cmp(ecx, LAST_NONCALLABLE_SPEC_OBJECT_TYPE);
3186 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3187 Split(below_equal, if_true, if_false, fall_through);
3189 context()->Plug(if_true, if_false);
3193 void FullCodeGenerator::EmitIsSpecObject(CallRuntime* expr) {
3194 ZoneList<Expression*>* args = expr->arguments();
3195 DCHECK(args->length() == 1);
3197 VisitForAccumulatorValue(args->at(0));
3199 Label materialize_true, materialize_false;
3200 Label* if_true = NULL;
3201 Label* if_false = NULL;
3202 Label* fall_through = NULL;
3203 context()->PrepareTest(&materialize_true, &materialize_false,
3204 &if_true, &if_false, &fall_through);
3206 __ JumpIfSmi(eax, if_false);
3207 __ CmpObjectType(eax, FIRST_SPEC_OBJECT_TYPE, ebx);
3208 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3209 Split(above_equal, if_true, if_false, fall_through);
3211 context()->Plug(if_true, if_false);
3215 void FullCodeGenerator::EmitIsUndetectableObject(CallRuntime* expr) {
3216 ZoneList<Expression*>* args = expr->arguments();
3217 DCHECK(args->length() == 1);
3219 VisitForAccumulatorValue(args->at(0));
3221 Label materialize_true, materialize_false;
3222 Label* if_true = NULL;
3223 Label* if_false = NULL;
3224 Label* fall_through = NULL;
3225 context()->PrepareTest(&materialize_true, &materialize_false,
3226 &if_true, &if_false, &fall_through);
3228 __ JumpIfSmi(eax, if_false);
3229 __ mov(ebx, FieldOperand(eax, HeapObject::kMapOffset));
3230 __ movzx_b(ebx, FieldOperand(ebx, Map::kBitFieldOffset));
3231 __ test(ebx, Immediate(1 << Map::kIsUndetectable));
3232 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3233 Split(not_zero, if_true, if_false, fall_through);
3235 context()->Plug(if_true, if_false);
3239 void FullCodeGenerator::EmitIsStringWrapperSafeForDefaultValueOf(
3240 CallRuntime* expr) {
3241 ZoneList<Expression*>* args = expr->arguments();
3242 DCHECK(args->length() == 1);
3244 VisitForAccumulatorValue(args->at(0));
3246 Label materialize_true, materialize_false, skip_lookup;
3247 Label* if_true = NULL;
3248 Label* if_false = NULL;
3249 Label* fall_through = NULL;
3250 context()->PrepareTest(&materialize_true, &materialize_false,
3251 &if_true, &if_false, &fall_through);
3253 __ AssertNotSmi(eax);
3255 // Check whether this map has already been checked to be safe for default
3257 __ mov(ebx, FieldOperand(eax, HeapObject::kMapOffset));
3258 __ test_b(FieldOperand(ebx, Map::kBitField2Offset),
3259 1 << Map::kStringWrapperSafeForDefaultValueOf);
3260 __ j(not_zero, &skip_lookup);
3262 // Check for fast case object. Return false for slow case objects.
3263 __ mov(ecx, FieldOperand(eax, JSObject::kPropertiesOffset));
3264 __ mov(ecx, FieldOperand(ecx, HeapObject::kMapOffset));
3265 __ cmp(ecx, isolate()->factory()->hash_table_map());
3266 __ j(equal, if_false);
3268 // Look for valueOf string in the descriptor array, and indicate false if
3269 // found. Since we omit an enumeration index check, if it is added via a
3270 // transition that shares its descriptor array, this is a false positive.
3271 Label entry, loop, done;
3273 // Skip loop if no descriptors are valid.
3274 __ NumberOfOwnDescriptors(ecx, ebx);
3278 __ LoadInstanceDescriptors(ebx, ebx);
3279 // ebx: descriptor array.
3280 // ecx: valid entries in the descriptor array.
3281 // Calculate the end of the descriptor array.
3282 STATIC_ASSERT(kSmiTag == 0);
3283 STATIC_ASSERT(kSmiTagSize == 1);
3284 STATIC_ASSERT(kPointerSize == 4);
3285 __ imul(ecx, ecx, DescriptorArray::kDescriptorSize);
3286 __ lea(ecx, Operand(ebx, ecx, times_4, DescriptorArray::kFirstOffset));
3287 // Calculate location of the first key name.
3288 __ add(ebx, Immediate(DescriptorArray::kFirstOffset));
3289 // Loop through all the keys in the descriptor array. If one of these is the
3290 // internalized string "valueOf" the result is false.
3293 __ mov(edx, FieldOperand(ebx, 0));
3294 __ cmp(edx, isolate()->factory()->value_of_string());
3295 __ j(equal, if_false);
3296 __ add(ebx, Immediate(DescriptorArray::kDescriptorSize * kPointerSize));
3299 __ j(not_equal, &loop);
3303 // Reload map as register ebx was used as temporary above.
3304 __ mov(ebx, FieldOperand(eax, HeapObject::kMapOffset));
3306 // Set the bit in the map to indicate that there is no local valueOf field.
3307 __ or_(FieldOperand(ebx, Map::kBitField2Offset),
3308 Immediate(1 << Map::kStringWrapperSafeForDefaultValueOf));
3310 __ bind(&skip_lookup);
3312 // If a valueOf property is not found on the object check that its
3313 // prototype is the un-modified String prototype. If not result is false.
3314 __ mov(ecx, FieldOperand(ebx, Map::kPrototypeOffset));
3315 __ JumpIfSmi(ecx, if_false);
3316 __ mov(ecx, FieldOperand(ecx, HeapObject::kMapOffset));
3317 __ mov(edx, Operand(esi, Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX)));
3319 FieldOperand(edx, GlobalObject::kNativeContextOffset));
3322 Context::STRING_FUNCTION_PROTOTYPE_MAP_INDEX));
3323 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3324 Split(equal, if_true, if_false, fall_through);
3326 context()->Plug(if_true, if_false);
3330 void FullCodeGenerator::EmitIsFunction(CallRuntime* expr) {
3331 ZoneList<Expression*>* args = expr->arguments();
3332 DCHECK(args->length() == 1);
3334 VisitForAccumulatorValue(args->at(0));
3336 Label materialize_true, materialize_false;
3337 Label* if_true = NULL;
3338 Label* if_false = NULL;
3339 Label* fall_through = NULL;
3340 context()->PrepareTest(&materialize_true, &materialize_false,
3341 &if_true, &if_false, &fall_through);
3343 __ JumpIfSmi(eax, if_false);
3344 __ CmpObjectType(eax, JS_FUNCTION_TYPE, ebx);
3345 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3346 Split(equal, if_true, if_false, fall_through);
3348 context()->Plug(if_true, if_false);
3352 void FullCodeGenerator::EmitIsMinusZero(CallRuntime* expr) {
3353 ZoneList<Expression*>* args = expr->arguments();
3354 DCHECK(args->length() == 1);
3356 VisitForAccumulatorValue(args->at(0));
3358 Label materialize_true, materialize_false;
3359 Label* if_true = NULL;
3360 Label* if_false = NULL;
3361 Label* fall_through = NULL;
3362 context()->PrepareTest(&materialize_true, &materialize_false,
3363 &if_true, &if_false, &fall_through);
3365 Handle<Map> map = masm()->isolate()->factory()->heap_number_map();
3366 __ CheckMap(eax, map, if_false, DO_SMI_CHECK);
3367 // Check if the exponent half is 0x80000000. Comparing against 1 and
3368 // checking for overflow is the shortest possible encoding.
3369 __ cmp(FieldOperand(eax, HeapNumber::kExponentOffset), Immediate(0x1));
3370 __ j(no_overflow, if_false);
3371 __ cmp(FieldOperand(eax, HeapNumber::kMantissaOffset), Immediate(0x0));
3372 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3373 Split(equal, if_true, if_false, fall_through);
3375 context()->Plug(if_true, if_false);
3380 void FullCodeGenerator::EmitIsArray(CallRuntime* expr) {
3381 ZoneList<Expression*>* args = expr->arguments();
3382 DCHECK(args->length() == 1);
3384 VisitForAccumulatorValue(args->at(0));
3386 Label materialize_true, materialize_false;
3387 Label* if_true = NULL;
3388 Label* if_false = NULL;
3389 Label* fall_through = NULL;
3390 context()->PrepareTest(&materialize_true, &materialize_false,
3391 &if_true, &if_false, &fall_through);
3393 __ JumpIfSmi(eax, if_false);
3394 __ CmpObjectType(eax, JS_ARRAY_TYPE, ebx);
3395 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3396 Split(equal, if_true, if_false, fall_through);
3398 context()->Plug(if_true, if_false);
3402 void FullCodeGenerator::EmitIsRegExp(CallRuntime* expr) {
3403 ZoneList<Expression*>* args = expr->arguments();
3404 DCHECK(args->length() == 1);
3406 VisitForAccumulatorValue(args->at(0));
3408 Label materialize_true, materialize_false;
3409 Label* if_true = NULL;
3410 Label* if_false = NULL;
3411 Label* fall_through = NULL;
3412 context()->PrepareTest(&materialize_true, &materialize_false,
3413 &if_true, &if_false, &fall_through);
3415 __ JumpIfSmi(eax, if_false);
3416 __ CmpObjectType(eax, JS_REGEXP_TYPE, ebx);
3417 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3418 Split(equal, if_true, if_false, fall_through);
3420 context()->Plug(if_true, if_false);
3424 void FullCodeGenerator::EmitIsJSProxy(CallRuntime* expr) {
3425 ZoneList<Expression*>* args = expr->arguments();
3426 DCHECK(args->length() == 1);
3428 VisitForAccumulatorValue(args->at(0));
3430 Label materialize_true, materialize_false;
3431 Label* if_true = NULL;
3432 Label* if_false = NULL;
3433 Label* fall_through = NULL;
3434 context()->PrepareTest(&materialize_true, &materialize_false, &if_true,
3435 &if_false, &fall_through);
3437 __ JumpIfSmi(eax, if_false);
3439 __ mov(map, FieldOperand(eax, HeapObject::kMapOffset));
3440 __ CmpInstanceType(map, FIRST_JS_PROXY_TYPE);
3441 __ j(less, if_false);
3442 __ CmpInstanceType(map, LAST_JS_PROXY_TYPE);
3443 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3444 Split(less_equal, if_true, if_false, fall_through);
3446 context()->Plug(if_true, if_false);
3450 void FullCodeGenerator::EmitIsConstructCall(CallRuntime* expr) {
3451 DCHECK(expr->arguments()->length() == 0);
3453 Label materialize_true, materialize_false;
3454 Label* if_true = NULL;
3455 Label* if_false = NULL;
3456 Label* fall_through = NULL;
3457 context()->PrepareTest(&materialize_true, &materialize_false,
3458 &if_true, &if_false, &fall_through);
3460 // Get the frame pointer for the calling frame.
3461 __ mov(eax, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3463 // Skip the arguments adaptor frame if it exists.
3464 Label check_frame_marker;
3465 __ cmp(Operand(eax, StandardFrameConstants::kContextOffset),
3466 Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
3467 __ j(not_equal, &check_frame_marker);
3468 __ mov(eax, Operand(eax, StandardFrameConstants::kCallerFPOffset));
3470 // Check the marker in the calling frame.
3471 __ bind(&check_frame_marker);
3472 __ cmp(Operand(eax, StandardFrameConstants::kMarkerOffset),
3473 Immediate(Smi::FromInt(StackFrame::CONSTRUCT)));
3474 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3475 Split(equal, if_true, if_false, fall_through);
3477 context()->Plug(if_true, if_false);
3481 void FullCodeGenerator::EmitObjectEquals(CallRuntime* expr) {
3482 ZoneList<Expression*>* args = expr->arguments();
3483 DCHECK(args->length() == 2);
3485 // Load the two objects into registers and perform the comparison.
3486 VisitForStackValue(args->at(0));
3487 VisitForAccumulatorValue(args->at(1));
3489 Label materialize_true, materialize_false;
3490 Label* if_true = NULL;
3491 Label* if_false = NULL;
3492 Label* fall_through = NULL;
3493 context()->PrepareTest(&materialize_true, &materialize_false,
3494 &if_true, &if_false, &fall_through);
3498 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3499 Split(equal, if_true, if_false, fall_through);
3501 context()->Plug(if_true, if_false);
3505 void FullCodeGenerator::EmitArguments(CallRuntime* expr) {
3506 ZoneList<Expression*>* args = expr->arguments();
3507 DCHECK(args->length() == 1);
3509 // ArgumentsAccessStub expects the key in edx and the formal
3510 // parameter count in eax.
3511 VisitForAccumulatorValue(args->at(0));
3513 __ Move(eax, Immediate(Smi::FromInt(info_->scope()->num_parameters())));
3514 ArgumentsAccessStub stub(isolate(), ArgumentsAccessStub::READ_ELEMENT);
3516 context()->Plug(eax);
3520 void FullCodeGenerator::EmitArgumentsLength(CallRuntime* expr) {
3521 DCHECK(expr->arguments()->length() == 0);
3524 // Get the number of formal parameters.
3525 __ Move(eax, Immediate(Smi::FromInt(info_->scope()->num_parameters())));
3527 // Check if the calling frame is an arguments adaptor frame.
3528 __ mov(ebx, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3529 __ cmp(Operand(ebx, StandardFrameConstants::kContextOffset),
3530 Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
3531 __ j(not_equal, &exit);
3533 // Arguments adaptor case: Read the arguments length from the
3535 __ mov(eax, Operand(ebx, ArgumentsAdaptorFrameConstants::kLengthOffset));
3539 context()->Plug(eax);
3543 void FullCodeGenerator::EmitClassOf(CallRuntime* expr) {
3544 ZoneList<Expression*>* args = expr->arguments();
3545 DCHECK(args->length() == 1);
3546 Label done, null, function, non_function_constructor;
3548 VisitForAccumulatorValue(args->at(0));
3550 // If the object is a smi, we return null.
3551 __ JumpIfSmi(eax, &null);
3553 // Check that the object is a JS object but take special care of JS
3554 // functions to make sure they have 'Function' as their class.
3555 // Assume that there are only two callable types, and one of them is at
3556 // either end of the type range for JS object types. Saves extra comparisons.
3557 STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
3558 __ CmpObjectType(eax, FIRST_SPEC_OBJECT_TYPE, eax);
3559 // Map is now in eax.
3561 STATIC_ASSERT(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE ==
3562 FIRST_SPEC_OBJECT_TYPE + 1);
3563 __ j(equal, &function);
3565 __ CmpInstanceType(eax, LAST_SPEC_OBJECT_TYPE);
3566 STATIC_ASSERT(LAST_NONCALLABLE_SPEC_OBJECT_TYPE ==
3567 LAST_SPEC_OBJECT_TYPE - 1);
3568 __ j(equal, &function);
3569 // Assume that there is no larger type.
3570 STATIC_ASSERT(LAST_NONCALLABLE_SPEC_OBJECT_TYPE == LAST_TYPE - 1);
3572 // Check if the constructor in the map is a JS function.
3573 __ mov(eax, FieldOperand(eax, Map::kConstructorOffset));
3574 __ CmpObjectType(eax, JS_FUNCTION_TYPE, ebx);
3575 __ j(not_equal, &non_function_constructor);
3577 // eax now contains the constructor function. Grab the
3578 // instance class name from there.
3579 __ mov(eax, FieldOperand(eax, JSFunction::kSharedFunctionInfoOffset));
3580 __ mov(eax, FieldOperand(eax, SharedFunctionInfo::kInstanceClassNameOffset));
3583 // Functions have class 'Function'.
3585 __ mov(eax, isolate()->factory()->Function_string());
3588 // Objects with a non-function constructor have class 'Object'.
3589 __ bind(&non_function_constructor);
3590 __ mov(eax, isolate()->factory()->Object_string());
3593 // Non-JS objects have class null.
3595 __ mov(eax, isolate()->factory()->null_value());
3600 context()->Plug(eax);
3604 void FullCodeGenerator::EmitSubString(CallRuntime* expr) {
3605 // Load the arguments on the stack and call the stub.
3606 SubStringStub stub(isolate());
3607 ZoneList<Expression*>* args = expr->arguments();
3608 DCHECK(args->length() == 3);
3609 VisitForStackValue(args->at(0));
3610 VisitForStackValue(args->at(1));
3611 VisitForStackValue(args->at(2));
3613 context()->Plug(eax);
3617 void FullCodeGenerator::EmitRegExpExec(CallRuntime* expr) {
3618 // Load the arguments on the stack and call the stub.
3619 RegExpExecStub stub(isolate());
3620 ZoneList<Expression*>* args = expr->arguments();
3621 DCHECK(args->length() == 4);
3622 VisitForStackValue(args->at(0));
3623 VisitForStackValue(args->at(1));
3624 VisitForStackValue(args->at(2));
3625 VisitForStackValue(args->at(3));
3627 context()->Plug(eax);
3631 void FullCodeGenerator::EmitValueOf(CallRuntime* expr) {
3632 ZoneList<Expression*>* args = expr->arguments();
3633 DCHECK(args->length() == 1);
3635 VisitForAccumulatorValue(args->at(0)); // Load the object.
3638 // If the object is a smi return the object.
3639 __ JumpIfSmi(eax, &done, Label::kNear);
3640 // If the object is not a value type, return the object.
3641 __ CmpObjectType(eax, JS_VALUE_TYPE, ebx);
3642 __ j(not_equal, &done, Label::kNear);
3643 __ mov(eax, FieldOperand(eax, JSValue::kValueOffset));
3646 context()->Plug(eax);
3650 void FullCodeGenerator::EmitDateField(CallRuntime* expr) {
3651 ZoneList<Expression*>* args = expr->arguments();
3652 DCHECK(args->length() == 2);
3653 DCHECK_NE(NULL, args->at(1)->AsLiteral());
3654 Smi* index = Smi::cast(*(args->at(1)->AsLiteral()->value()));
3656 VisitForAccumulatorValue(args->at(0)); // Load the object.
3658 Label runtime, done, not_date_object;
3659 Register object = eax;
3660 Register result = eax;
3661 Register scratch = ecx;
3663 __ JumpIfSmi(object, ¬_date_object);
3664 __ CmpObjectType(object, JS_DATE_TYPE, scratch);
3665 __ j(not_equal, ¬_date_object);
3667 if (index->value() == 0) {
3668 __ mov(result, FieldOperand(object, JSDate::kValueOffset));
3671 if (index->value() < JSDate::kFirstUncachedField) {
3672 ExternalReference stamp = ExternalReference::date_cache_stamp(isolate());
3673 __ mov(scratch, Operand::StaticVariable(stamp));
3674 __ cmp(scratch, FieldOperand(object, JSDate::kCacheStampOffset));
3675 __ j(not_equal, &runtime, Label::kNear);
3676 __ mov(result, FieldOperand(object, JSDate::kValueOffset +
3677 kPointerSize * index->value()));
3681 __ PrepareCallCFunction(2, scratch);
3682 __ mov(Operand(esp, 0), object);
3683 __ mov(Operand(esp, 1 * kPointerSize), Immediate(index));
3684 __ CallCFunction(ExternalReference::get_date_field_function(isolate()), 2);
3688 __ bind(¬_date_object);
3689 __ CallRuntime(Runtime::kThrowNotDateError, 0);
3691 context()->Plug(result);
3695 void FullCodeGenerator::EmitOneByteSeqStringSetChar(CallRuntime* expr) {
3696 ZoneList<Expression*>* args = expr->arguments();
3697 DCHECK_EQ(3, args->length());
3699 Register string = eax;
3700 Register index = ebx;
3701 Register value = ecx;
3703 VisitForStackValue(args->at(0)); // index
3704 VisitForStackValue(args->at(1)); // value
3705 VisitForAccumulatorValue(args->at(2)); // string
3710 if (FLAG_debug_code) {
3711 __ test(value, Immediate(kSmiTagMask));
3712 __ Check(zero, kNonSmiValue);
3713 __ test(index, Immediate(kSmiTagMask));
3714 __ Check(zero, kNonSmiValue);
3720 if (FLAG_debug_code) {
3721 static const uint32_t one_byte_seq_type = kSeqStringTag | kOneByteStringTag;
3722 __ EmitSeqStringSetCharCheck(string, index, value, one_byte_seq_type);
3725 __ mov_b(FieldOperand(string, index, times_1, SeqOneByteString::kHeaderSize),
3727 context()->Plug(string);
3731 void FullCodeGenerator::EmitTwoByteSeqStringSetChar(CallRuntime* expr) {
3732 ZoneList<Expression*>* args = expr->arguments();
3733 DCHECK_EQ(3, args->length());
3735 Register string = eax;
3736 Register index = ebx;
3737 Register value = ecx;
3739 VisitForStackValue(args->at(0)); // index
3740 VisitForStackValue(args->at(1)); // value
3741 VisitForAccumulatorValue(args->at(2)); // string
3745 if (FLAG_debug_code) {
3746 __ test(value, Immediate(kSmiTagMask));
3747 __ Check(zero, kNonSmiValue);
3748 __ test(index, Immediate(kSmiTagMask));
3749 __ Check(zero, kNonSmiValue);
3751 static const uint32_t two_byte_seq_type = kSeqStringTag | kTwoByteStringTag;
3752 __ EmitSeqStringSetCharCheck(string, index, value, two_byte_seq_type);
3757 // No need to untag a smi for two-byte addressing.
3758 __ mov_w(FieldOperand(string, index, times_1, SeqTwoByteString::kHeaderSize),
3760 context()->Plug(string);
3764 void FullCodeGenerator::EmitMathPow(CallRuntime* expr) {
3765 // Load the arguments on the stack and call the runtime function.
3766 ZoneList<Expression*>* args = expr->arguments();
3767 DCHECK(args->length() == 2);
3768 VisitForStackValue(args->at(0));
3769 VisitForStackValue(args->at(1));
3771 MathPowStub stub(isolate(), MathPowStub::ON_STACK);
3773 context()->Plug(eax);
3777 void FullCodeGenerator::EmitSetValueOf(CallRuntime* expr) {
3778 ZoneList<Expression*>* args = expr->arguments();
3779 DCHECK(args->length() == 2);
3781 VisitForStackValue(args->at(0)); // Load the object.
3782 VisitForAccumulatorValue(args->at(1)); // Load the value.
3783 __ pop(ebx); // eax = value. ebx = object.
3786 // If the object is a smi, return the value.
3787 __ JumpIfSmi(ebx, &done, Label::kNear);
3789 // If the object is not a value type, return the value.
3790 __ CmpObjectType(ebx, JS_VALUE_TYPE, ecx);
3791 __ j(not_equal, &done, Label::kNear);
3794 __ mov(FieldOperand(ebx, JSValue::kValueOffset), eax);
3796 // Update the write barrier. Save the value as it will be
3797 // overwritten by the write barrier code and is needed afterward.
3799 __ RecordWriteField(ebx, JSValue::kValueOffset, edx, ecx, kDontSaveFPRegs);
3802 context()->Plug(eax);
3806 void FullCodeGenerator::EmitNumberToString(CallRuntime* expr) {
3807 ZoneList<Expression*>* args = expr->arguments();
3808 DCHECK_EQ(args->length(), 1);
3810 // Load the argument into eax and call the stub.
3811 VisitForAccumulatorValue(args->at(0));
3813 NumberToStringStub stub(isolate());
3815 context()->Plug(eax);
3819 void FullCodeGenerator::EmitStringCharFromCode(CallRuntime* expr) {
3820 ZoneList<Expression*>* args = expr->arguments();
3821 DCHECK(args->length() == 1);
3823 VisitForAccumulatorValue(args->at(0));
3826 StringCharFromCodeGenerator generator(eax, ebx);
3827 generator.GenerateFast(masm_);
3830 NopRuntimeCallHelper call_helper;
3831 generator.GenerateSlow(masm_, call_helper);
3834 context()->Plug(ebx);
3838 void FullCodeGenerator::EmitStringCharCodeAt(CallRuntime* expr) {
3839 ZoneList<Expression*>* args = expr->arguments();
3840 DCHECK(args->length() == 2);
3842 VisitForStackValue(args->at(0));
3843 VisitForAccumulatorValue(args->at(1));
3845 Register object = ebx;
3846 Register index = eax;
3847 Register result = edx;
3851 Label need_conversion;
3852 Label index_out_of_range;
3854 StringCharCodeAtGenerator generator(object,
3859 &index_out_of_range,
3860 STRING_INDEX_IS_NUMBER);
3861 generator.GenerateFast(masm_);
3864 __ bind(&index_out_of_range);
3865 // When the index is out of range, the spec requires us to return
3867 __ Move(result, Immediate(isolate()->factory()->nan_value()));
3870 __ bind(&need_conversion);
3871 // Move the undefined value into the result register, which will
3872 // trigger conversion.
3873 __ Move(result, Immediate(isolate()->factory()->undefined_value()));
3876 NopRuntimeCallHelper call_helper;
3877 generator.GenerateSlow(masm_, call_helper);
3880 context()->Plug(result);
3884 void FullCodeGenerator::EmitStringCharAt(CallRuntime* expr) {
3885 ZoneList<Expression*>* args = expr->arguments();
3886 DCHECK(args->length() == 2);
3888 VisitForStackValue(args->at(0));
3889 VisitForAccumulatorValue(args->at(1));
3891 Register object = ebx;
3892 Register index = eax;
3893 Register scratch = edx;
3894 Register result = eax;
3898 Label need_conversion;
3899 Label index_out_of_range;
3901 StringCharAtGenerator generator(object,
3907 &index_out_of_range,
3908 STRING_INDEX_IS_NUMBER);
3909 generator.GenerateFast(masm_);
3912 __ bind(&index_out_of_range);
3913 // When the index is out of range, the spec requires us to return
3914 // the empty string.
3915 __ Move(result, Immediate(isolate()->factory()->empty_string()));
3918 __ bind(&need_conversion);
3919 // Move smi zero into the result register, which will trigger
3921 __ Move(result, Immediate(Smi::FromInt(0)));
3924 NopRuntimeCallHelper call_helper;
3925 generator.GenerateSlow(masm_, call_helper);
3928 context()->Plug(result);
3932 void FullCodeGenerator::EmitStringAdd(CallRuntime* expr) {
3933 ZoneList<Expression*>* args = expr->arguments();
3934 DCHECK_EQ(2, args->length());
3935 VisitForStackValue(args->at(0));
3936 VisitForAccumulatorValue(args->at(1));
3939 StringAddStub stub(isolate(), STRING_ADD_CHECK_BOTH, NOT_TENURED);
3941 context()->Plug(eax);
3945 void FullCodeGenerator::EmitStringCompare(CallRuntime* expr) {
3946 ZoneList<Expression*>* args = expr->arguments();
3947 DCHECK_EQ(2, args->length());
3949 VisitForStackValue(args->at(0));
3950 VisitForStackValue(args->at(1));
3952 StringCompareStub stub(isolate());
3954 context()->Plug(eax);
3958 void FullCodeGenerator::EmitCallFunction(CallRuntime* expr) {
3959 ZoneList<Expression*>* args = expr->arguments();
3960 DCHECK(args->length() >= 2);
3962 int arg_count = args->length() - 2; // 2 ~ receiver and function.
3963 for (int i = 0; i < arg_count + 1; ++i) {
3964 VisitForStackValue(args->at(i));
3966 VisitForAccumulatorValue(args->last()); // Function.
3968 Label runtime, done;
3969 // Check for non-function argument (including proxy).
3970 __ JumpIfSmi(eax, &runtime);
3971 __ CmpObjectType(eax, JS_FUNCTION_TYPE, ebx);
3972 __ j(not_equal, &runtime);
3974 // InvokeFunction requires the function in edi. Move it in there.
3975 __ mov(edi, result_register());
3976 ParameterCount count(arg_count);
3977 __ InvokeFunction(edi, count, CALL_FUNCTION, NullCallWrapper());
3978 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
3983 __ CallRuntime(Runtime::kCall, args->length());
3986 context()->Plug(eax);
3990 void FullCodeGenerator::EmitRegExpConstructResult(CallRuntime* expr) {
3991 // Load the arguments on the stack and call the stub.
3992 RegExpConstructResultStub stub(isolate());
3993 ZoneList<Expression*>* args = expr->arguments();
3994 DCHECK(args->length() == 3);
3995 VisitForStackValue(args->at(0));
3996 VisitForStackValue(args->at(1));
3997 VisitForAccumulatorValue(args->at(2));
4001 context()->Plug(eax);
4005 void FullCodeGenerator::EmitGetFromCache(CallRuntime* expr) {
4006 ZoneList<Expression*>* args = expr->arguments();
4007 DCHECK_EQ(2, args->length());
4009 DCHECK_NE(NULL, args->at(0)->AsLiteral());
4010 int cache_id = Smi::cast(*(args->at(0)->AsLiteral()->value()))->value();
4012 Handle<FixedArray> jsfunction_result_caches(
4013 isolate()->native_context()->jsfunction_result_caches());
4014 if (jsfunction_result_caches->length() <= cache_id) {
4015 __ Abort(kAttemptToUseUndefinedCache);
4016 __ mov(eax, isolate()->factory()->undefined_value());
4017 context()->Plug(eax);
4021 VisitForAccumulatorValue(args->at(1));
4024 Register cache = ebx;
4026 __ mov(cache, ContextOperand(esi, Context::GLOBAL_OBJECT_INDEX));
4028 FieldOperand(cache, GlobalObject::kNativeContextOffset));
4029 __ mov(cache, ContextOperand(cache, Context::JSFUNCTION_RESULT_CACHES_INDEX));
4031 FieldOperand(cache, FixedArray::OffsetOfElementAt(cache_id)));
4033 Label done, not_found;
4034 STATIC_ASSERT(kSmiTag == 0 && kSmiTagSize == 1);
4035 __ mov(tmp, FieldOperand(cache, JSFunctionResultCache::kFingerOffset));
4036 // tmp now holds finger offset as a smi.
4037 __ cmp(key, FixedArrayElementOperand(cache, tmp));
4038 __ j(not_equal, ¬_found);
4040 __ mov(eax, FixedArrayElementOperand(cache, tmp, 1));
4043 __ bind(¬_found);
4044 // Call runtime to perform the lookup.
4047 __ CallRuntime(Runtime::kGetFromCache, 2);
4050 context()->Plug(eax);
4054 void FullCodeGenerator::EmitHasCachedArrayIndex(CallRuntime* expr) {
4055 ZoneList<Expression*>* args = expr->arguments();
4056 DCHECK(args->length() == 1);
4058 VisitForAccumulatorValue(args->at(0));
4060 __ AssertString(eax);
4062 Label materialize_true, materialize_false;
4063 Label* if_true = NULL;
4064 Label* if_false = NULL;
4065 Label* fall_through = NULL;
4066 context()->PrepareTest(&materialize_true, &materialize_false,
4067 &if_true, &if_false, &fall_through);
4069 __ test(FieldOperand(eax, String::kHashFieldOffset),
4070 Immediate(String::kContainsCachedArrayIndexMask));
4071 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
4072 Split(zero, if_true, if_false, fall_through);
4074 context()->Plug(if_true, if_false);
4078 void FullCodeGenerator::EmitGetCachedArrayIndex(CallRuntime* expr) {
4079 ZoneList<Expression*>* args = expr->arguments();
4080 DCHECK(args->length() == 1);
4081 VisitForAccumulatorValue(args->at(0));
4083 __ AssertString(eax);
4085 __ mov(eax, FieldOperand(eax, String::kHashFieldOffset));
4086 __ IndexFromHash(eax, eax);
4088 context()->Plug(eax);
4092 void FullCodeGenerator::EmitFastOneByteArrayJoin(CallRuntime* expr) {
4093 Label bailout, done, one_char_separator, long_separator,
4094 non_trivial_array, not_size_one_array, loop,
4095 loop_1, loop_1_condition, loop_2, loop_2_entry, loop_3, loop_3_entry;
4097 ZoneList<Expression*>* args = expr->arguments();
4098 DCHECK(args->length() == 2);
4099 // We will leave the separator on the stack until the end of the function.
4100 VisitForStackValue(args->at(1));
4101 // Load this to eax (= array)
4102 VisitForAccumulatorValue(args->at(0));
4103 // All aliases of the same register have disjoint lifetimes.
4104 Register array = eax;
4105 Register elements = no_reg; // Will be eax.
4107 Register index = edx;
4109 Register string_length = ecx;
4111 Register string = esi;
4113 Register scratch = ebx;
4115 Register array_length = edi;
4116 Register result_pos = no_reg; // Will be edi.
4118 // Separator operand is already pushed.
4119 Operand separator_operand = Operand(esp, 2 * kPointerSize);
4120 Operand result_operand = Operand(esp, 1 * kPointerSize);
4121 Operand array_length_operand = Operand(esp, 0);
4122 __ sub(esp, Immediate(2 * kPointerSize));
4124 // Check that the array is a JSArray
4125 __ JumpIfSmi(array, &bailout);
4126 __ CmpObjectType(array, JS_ARRAY_TYPE, scratch);
4127 __ j(not_equal, &bailout);
4129 // Check that the array has fast elements.
4130 __ CheckFastElements(scratch, &bailout);
4132 // If the array has length zero, return the empty string.
4133 __ mov(array_length, FieldOperand(array, JSArray::kLengthOffset));
4134 __ SmiUntag(array_length);
4135 __ j(not_zero, &non_trivial_array);
4136 __ mov(result_operand, isolate()->factory()->empty_string());
4139 // Save the array length.
4140 __ bind(&non_trivial_array);
4141 __ mov(array_length_operand, array_length);
4143 // Save the FixedArray containing array's elements.
4144 // End of array's live range.
4146 __ mov(elements, FieldOperand(array, JSArray::kElementsOffset));
4150 // Check that all array elements are sequential one-byte strings, and
4151 // accumulate the sum of their lengths, as a smi-encoded value.
4152 __ Move(index, Immediate(0));
4153 __ Move(string_length, Immediate(0));
4154 // Loop condition: while (index < length).
4155 // Live loop registers: index, array_length, string,
4156 // scratch, string_length, elements.
4157 if (generate_debug_code_) {
4158 __ cmp(index, array_length);
4159 __ Assert(less, kNoEmptyArraysHereInEmitFastOneByteArrayJoin);
4162 __ mov(string, FieldOperand(elements,
4165 FixedArray::kHeaderSize));
4166 __ JumpIfSmi(string, &bailout);
4167 __ mov(scratch, FieldOperand(string, HeapObject::kMapOffset));
4168 __ movzx_b(scratch, FieldOperand(scratch, Map::kInstanceTypeOffset));
4169 __ and_(scratch, Immediate(
4170 kIsNotStringMask | kStringEncodingMask | kStringRepresentationMask));
4171 __ cmp(scratch, kStringTag | kOneByteStringTag | kSeqStringTag);
4172 __ j(not_equal, &bailout);
4173 __ add(string_length,
4174 FieldOperand(string, SeqOneByteString::kLengthOffset));
4175 __ j(overflow, &bailout);
4176 __ add(index, Immediate(1));
4177 __ cmp(index, array_length);
4180 // If array_length is 1, return elements[0], a string.
4181 __ cmp(array_length, 1);
4182 __ j(not_equal, ¬_size_one_array);
4183 __ mov(scratch, FieldOperand(elements, FixedArray::kHeaderSize));
4184 __ mov(result_operand, scratch);
4187 __ bind(¬_size_one_array);
4189 // End of array_length live range.
4190 result_pos = array_length;
4191 array_length = no_reg;
4194 // string_length: Sum of string lengths, as a smi.
4195 // elements: FixedArray of strings.
4197 // Check that the separator is a flat one-byte string.
4198 __ mov(string, separator_operand);
4199 __ JumpIfSmi(string, &bailout);
4200 __ mov(scratch, FieldOperand(string, HeapObject::kMapOffset));
4201 __ movzx_b(scratch, FieldOperand(scratch, Map::kInstanceTypeOffset));
4202 __ and_(scratch, Immediate(
4203 kIsNotStringMask | kStringEncodingMask | kStringRepresentationMask));
4204 __ cmp(scratch, kStringTag | kOneByteStringTag | kSeqStringTag);
4205 __ j(not_equal, &bailout);
4207 // Add (separator length times array_length) - separator length
4208 // to string_length.
4209 __ mov(scratch, separator_operand);
4210 __ mov(scratch, FieldOperand(scratch, SeqOneByteString::kLengthOffset));
4211 __ sub(string_length, scratch); // May be negative, temporarily.
4212 __ imul(scratch, array_length_operand);
4213 __ j(overflow, &bailout);
4214 __ add(string_length, scratch);
4215 __ j(overflow, &bailout);
4217 __ shr(string_length, 1);
4218 // Live registers and stack values:
4221 __ AllocateOneByteString(result_pos, string_length, scratch, index, string,
4223 __ mov(result_operand, result_pos);
4224 __ lea(result_pos, FieldOperand(result_pos, SeqOneByteString::kHeaderSize));
4227 __ mov(string, separator_operand);
4228 __ cmp(FieldOperand(string, SeqOneByteString::kLengthOffset),
4229 Immediate(Smi::FromInt(1)));
4230 __ j(equal, &one_char_separator);
4231 __ j(greater, &long_separator);
4234 // Empty separator case
4235 __ mov(index, Immediate(0));
4236 __ jmp(&loop_1_condition);
4237 // Loop condition: while (index < length).
4239 // Each iteration of the loop concatenates one string to the result.
4240 // Live values in registers:
4241 // index: which element of the elements array we are adding to the result.
4242 // result_pos: the position to which we are currently copying characters.
4243 // elements: the FixedArray of strings we are joining.
4245 // Get string = array[index].
4246 __ mov(string, FieldOperand(elements, index,
4248 FixedArray::kHeaderSize));
4249 __ mov(string_length,
4250 FieldOperand(string, String::kLengthOffset));
4251 __ shr(string_length, 1);
4253 FieldOperand(string, SeqOneByteString::kHeaderSize));
4254 __ CopyBytes(string, result_pos, string_length, scratch);
4255 __ add(index, Immediate(1));
4256 __ bind(&loop_1_condition);
4257 __ cmp(index, array_length_operand);
4258 __ j(less, &loop_1); // End while (index < length).
4263 // One-character separator case
4264 __ bind(&one_char_separator);
4265 // Replace separator with its one-byte character value.
4266 __ mov_b(scratch, FieldOperand(string, SeqOneByteString::kHeaderSize));
4267 __ mov_b(separator_operand, scratch);
4269 __ Move(index, Immediate(0));
4270 // Jump into the loop after the code that copies the separator, so the first
4271 // element is not preceded by a separator
4272 __ jmp(&loop_2_entry);
4273 // Loop condition: while (index < length).
4275 // Each iteration of the loop concatenates one string to the result.
4276 // Live values in registers:
4277 // index: which element of the elements array we are adding to the result.
4278 // result_pos: the position to which we are currently copying characters.
4280 // Copy the separator character to the result.
4281 __ mov_b(scratch, separator_operand);
4282 __ mov_b(Operand(result_pos, 0), scratch);
4285 __ bind(&loop_2_entry);
4286 // Get string = array[index].
4287 __ mov(string, FieldOperand(elements, index,
4289 FixedArray::kHeaderSize));
4290 __ mov(string_length,
4291 FieldOperand(string, String::kLengthOffset));
4292 __ shr(string_length, 1);
4294 FieldOperand(string, SeqOneByteString::kHeaderSize));
4295 __ CopyBytes(string, result_pos, string_length, scratch);
4296 __ add(index, Immediate(1));
4298 __ cmp(index, array_length_operand);
4299 __ j(less, &loop_2); // End while (index < length).
4303 // Long separator case (separator is more than one character).
4304 __ bind(&long_separator);
4306 __ Move(index, Immediate(0));
4307 // Jump into the loop after the code that copies the separator, so the first
4308 // element is not preceded by a separator
4309 __ jmp(&loop_3_entry);
4310 // Loop condition: while (index < length).
4312 // Each iteration of the loop concatenates one string to the result.
4313 // Live values in registers:
4314 // index: which element of the elements array we are adding to the result.
4315 // result_pos: the position to which we are currently copying characters.
4317 // Copy the separator to the result.
4318 __ mov(string, separator_operand);
4319 __ mov(string_length,
4320 FieldOperand(string, String::kLengthOffset));
4321 __ shr(string_length, 1);
4323 FieldOperand(string, SeqOneByteString::kHeaderSize));
4324 __ CopyBytes(string, result_pos, string_length, scratch);
4326 __ bind(&loop_3_entry);
4327 // Get string = array[index].
4328 __ mov(string, FieldOperand(elements, index,
4330 FixedArray::kHeaderSize));
4331 __ mov(string_length,
4332 FieldOperand(string, String::kLengthOffset));
4333 __ shr(string_length, 1);
4335 FieldOperand(string, SeqOneByteString::kHeaderSize));
4336 __ CopyBytes(string, result_pos, string_length, scratch);
4337 __ add(index, Immediate(1));
4339 __ cmp(index, array_length_operand);
4340 __ j(less, &loop_3); // End while (index < length).
4345 __ mov(result_operand, isolate()->factory()->undefined_value());
4347 __ mov(eax, result_operand);
4348 // Drop temp values from the stack, and restore context register.
4349 __ add(esp, Immediate(3 * kPointerSize));
4351 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4352 context()->Plug(eax);
4356 void FullCodeGenerator::EmitDebugIsActive(CallRuntime* expr) {
4357 DCHECK(expr->arguments()->length() == 0);
4358 ExternalReference debug_is_active =
4359 ExternalReference::debug_is_active_address(isolate());
4360 __ movzx_b(eax, Operand::StaticVariable(debug_is_active));
4362 context()->Plug(eax);
4366 void FullCodeGenerator::VisitCallRuntime(CallRuntime* expr) {
4367 if (expr->function() != NULL &&
4368 expr->function()->intrinsic_type == Runtime::INLINE) {
4369 Comment cmnt(masm_, "[ InlineRuntimeCall");
4370 EmitInlineRuntimeCall(expr);
4374 Comment cmnt(masm_, "[ CallRuntime");
4375 ZoneList<Expression*>* args = expr->arguments();
4377 if (expr->is_jsruntime()) {
4378 // Push the builtins object as receiver.
4379 __ mov(eax, GlobalObjectOperand());
4380 __ push(FieldOperand(eax, GlobalObject::kBuiltinsOffset));
4382 // Load the function from the receiver.
4383 __ mov(LoadDescriptor::ReceiverRegister(), Operand(esp, 0));
4384 __ mov(LoadDescriptor::NameRegister(), Immediate(expr->name()));
4385 if (FLAG_vector_ics) {
4386 __ mov(VectorLoadICDescriptor::SlotRegister(),
4387 Immediate(SmiFromSlot(expr->CallRuntimeFeedbackSlot())));
4388 CallLoadIC(NOT_CONTEXTUAL);
4390 CallLoadIC(NOT_CONTEXTUAL, expr->CallRuntimeFeedbackId());
4393 // Push the target function under the receiver.
4394 __ push(Operand(esp, 0));
4395 __ mov(Operand(esp, kPointerSize), eax);
4397 // Code common for calls using the IC.
4398 ZoneList<Expression*>* args = expr->arguments();
4399 int arg_count = args->length();
4400 for (int i = 0; i < arg_count; i++) {
4401 VisitForStackValue(args->at(i));
4404 // Record source position of the IC call.
4405 SetSourcePosition(expr->position());
4406 CallFunctionStub stub(isolate(), arg_count, NO_CALL_FUNCTION_FLAGS);
4407 __ mov(edi, Operand(esp, (arg_count + 1) * kPointerSize));
4409 // Restore context register.
4410 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4411 context()->DropAndPlug(1, eax);
4414 // Push the arguments ("left-to-right").
4415 int arg_count = args->length();
4416 for (int i = 0; i < arg_count; i++) {
4417 VisitForStackValue(args->at(i));
4420 // Call the C runtime function.
4421 __ CallRuntime(expr->function(), arg_count);
4423 context()->Plug(eax);
4428 void FullCodeGenerator::VisitUnaryOperation(UnaryOperation* expr) {
4429 switch (expr->op()) {
4430 case Token::DELETE: {
4431 Comment cmnt(masm_, "[ UnaryOperation (DELETE)");
4432 Property* property = expr->expression()->AsProperty();
4433 VariableProxy* proxy = expr->expression()->AsVariableProxy();
4435 if (property != NULL) {
4436 VisitForStackValue(property->obj());
4437 VisitForStackValue(property->key());
4438 __ push(Immediate(Smi::FromInt(strict_mode())));
4439 __ InvokeBuiltin(Builtins::DELETE, CALL_FUNCTION);
4440 context()->Plug(eax);
4441 } else if (proxy != NULL) {
4442 Variable* var = proxy->var();
4443 // Delete of an unqualified identifier is disallowed in strict mode
4444 // but "delete this" is allowed.
4445 DCHECK(strict_mode() == SLOPPY || var->is_this());
4446 if (var->IsUnallocated()) {
4447 __ push(GlobalObjectOperand());
4448 __ push(Immediate(var->name()));
4449 __ push(Immediate(Smi::FromInt(SLOPPY)));
4450 __ InvokeBuiltin(Builtins::DELETE, CALL_FUNCTION);
4451 context()->Plug(eax);
4452 } else if (var->IsStackAllocated() || var->IsContextSlot()) {
4453 // Result of deleting non-global variables is false. 'this' is
4454 // not really a variable, though we implement it as one. The
4455 // subexpression does not have side effects.
4456 context()->Plug(var->is_this());
4458 // Non-global variable. Call the runtime to try to delete from the
4459 // context where the variable was introduced.
4460 __ push(context_register());
4461 __ push(Immediate(var->name()));
4462 __ CallRuntime(Runtime::kDeleteLookupSlot, 2);
4463 context()->Plug(eax);
4466 // Result of deleting non-property, non-variable reference is true.
4467 // The subexpression may have side effects.
4468 VisitForEffect(expr->expression());
4469 context()->Plug(true);
4475 Comment cmnt(masm_, "[ UnaryOperation (VOID)");
4476 VisitForEffect(expr->expression());
4477 context()->Plug(isolate()->factory()->undefined_value());
4482 Comment cmnt(masm_, "[ UnaryOperation (NOT)");
4483 if (context()->IsEffect()) {
4484 // Unary NOT has no side effects so it's only necessary to visit the
4485 // subexpression. Match the optimizing compiler by not branching.
4486 VisitForEffect(expr->expression());
4487 } else if (context()->IsTest()) {
4488 const TestContext* test = TestContext::cast(context());
4489 // The labels are swapped for the recursive call.
4490 VisitForControl(expr->expression(),
4491 test->false_label(),
4493 test->fall_through());
4494 context()->Plug(test->true_label(), test->false_label());
4496 // We handle value contexts explicitly rather than simply visiting
4497 // for control and plugging the control flow into the context,
4498 // because we need to prepare a pair of extra administrative AST ids
4499 // for the optimizing compiler.
4500 DCHECK(context()->IsAccumulatorValue() || context()->IsStackValue());
4501 Label materialize_true, materialize_false, done;
4502 VisitForControl(expr->expression(),
4506 __ bind(&materialize_true);
4507 PrepareForBailoutForId(expr->MaterializeTrueId(), NO_REGISTERS);
4508 if (context()->IsAccumulatorValue()) {
4509 __ mov(eax, isolate()->factory()->true_value());
4511 __ Push(isolate()->factory()->true_value());
4513 __ jmp(&done, Label::kNear);
4514 __ bind(&materialize_false);
4515 PrepareForBailoutForId(expr->MaterializeFalseId(), NO_REGISTERS);
4516 if (context()->IsAccumulatorValue()) {
4517 __ mov(eax, isolate()->factory()->false_value());
4519 __ Push(isolate()->factory()->false_value());
4526 case Token::TYPEOF: {
4527 Comment cmnt(masm_, "[ UnaryOperation (TYPEOF)");
4528 { StackValueContext context(this);
4529 VisitForTypeofValue(expr->expression());
4531 __ CallRuntime(Runtime::kTypeof, 1);
4532 context()->Plug(eax);
4542 void FullCodeGenerator::VisitCountOperation(CountOperation* expr) {
4543 DCHECK(expr->expression()->IsValidReferenceExpression());
4545 Comment cmnt(masm_, "[ CountOperation");
4546 SetSourcePosition(expr->position());
4548 Property* prop = expr->expression()->AsProperty();
4549 LhsKind assign_type = GetAssignType(prop);
4551 // Evaluate expression and get value.
4552 if (assign_type == VARIABLE) {
4553 DCHECK(expr->expression()->AsVariableProxy()->var() != NULL);
4554 AccumulatorValueContext context(this);
4555 EmitVariableLoad(expr->expression()->AsVariableProxy());
4557 // Reserve space for result of postfix operation.
4558 if (expr->is_postfix() && !context()->IsEffect()) {
4559 __ push(Immediate(Smi::FromInt(0)));
4561 switch (assign_type) {
4562 case NAMED_PROPERTY: {
4563 // Put the object both on the stack and in the register.
4564 VisitForStackValue(prop->obj());
4565 __ mov(LoadDescriptor::ReceiverRegister(), Operand(esp, 0));
4566 EmitNamedPropertyLoad(prop);
4570 case NAMED_SUPER_PROPERTY: {
4571 VisitForStackValue(prop->obj()->AsSuperReference()->this_var());
4572 EmitLoadHomeObject(prop->obj()->AsSuperReference());
4573 __ push(result_register());
4574 __ push(MemOperand(esp, kPointerSize));
4575 __ push(result_register());
4576 EmitNamedSuperPropertyLoad(prop);
4580 case KEYED_SUPER_PROPERTY: {
4581 VisitForStackValue(prop->obj()->AsSuperReference()->this_var());
4582 EmitLoadHomeObject(prop->obj()->AsSuperReference());
4583 __ push(result_register());
4584 VisitForAccumulatorValue(prop->key());
4585 __ push(result_register());
4586 __ push(MemOperand(esp, 2 * kPointerSize));
4587 __ push(MemOperand(esp, 2 * kPointerSize));
4588 __ push(result_register());
4589 EmitKeyedSuperPropertyLoad(prop);
4593 case KEYED_PROPERTY: {
4594 VisitForStackValue(prop->obj());
4595 VisitForStackValue(prop->key());
4596 __ mov(LoadDescriptor::ReceiverRegister(),
4597 Operand(esp, kPointerSize)); // Object.
4598 __ mov(LoadDescriptor::NameRegister(), Operand(esp, 0)); // Key.
4599 EmitKeyedPropertyLoad(prop);
4608 // We need a second deoptimization point after loading the value
4609 // in case evaluating the property load my have a side effect.
4610 if (assign_type == VARIABLE) {
4611 PrepareForBailout(expr->expression(), TOS_REG);
4613 PrepareForBailoutForId(prop->LoadId(), TOS_REG);
4616 // Inline smi case if we are in a loop.
4617 Label done, stub_call;
4618 JumpPatchSite patch_site(masm_);
4619 if (ShouldInlineSmiCase(expr->op())) {
4621 patch_site.EmitJumpIfNotSmi(eax, &slow, Label::kNear);
4623 // Save result for postfix expressions.
4624 if (expr->is_postfix()) {
4625 if (!context()->IsEffect()) {
4626 // Save the result on the stack. If we have a named or keyed property
4627 // we store the result under the receiver that is currently on top
4629 switch (assign_type) {
4633 case NAMED_PROPERTY:
4634 __ mov(Operand(esp, kPointerSize), eax);
4636 case NAMED_SUPER_PROPERTY:
4637 __ mov(Operand(esp, 2 * kPointerSize), eax);
4639 case KEYED_PROPERTY:
4640 __ mov(Operand(esp, 2 * kPointerSize), eax);
4642 case KEYED_SUPER_PROPERTY:
4643 __ mov(Operand(esp, 3 * kPointerSize), eax);
4649 if (expr->op() == Token::INC) {
4650 __ add(eax, Immediate(Smi::FromInt(1)));
4652 __ sub(eax, Immediate(Smi::FromInt(1)));
4654 __ j(no_overflow, &done, Label::kNear);
4655 // Call stub. Undo operation first.
4656 if (expr->op() == Token::INC) {
4657 __ sub(eax, Immediate(Smi::FromInt(1)));
4659 __ add(eax, Immediate(Smi::FromInt(1)));
4661 __ jmp(&stub_call, Label::kNear);
4664 ToNumberStub convert_stub(isolate());
4665 __ CallStub(&convert_stub);
4667 // Save result for postfix expressions.
4668 if (expr->is_postfix()) {
4669 if (!context()->IsEffect()) {
4670 // Save the result on the stack. If we have a named or keyed property
4671 // we store the result under the receiver that is currently on top
4673 switch (assign_type) {
4677 case NAMED_PROPERTY:
4678 __ mov(Operand(esp, kPointerSize), eax);
4680 case NAMED_SUPER_PROPERTY:
4681 __ mov(Operand(esp, 2 * kPointerSize), eax);
4683 case KEYED_PROPERTY:
4684 __ mov(Operand(esp, 2 * kPointerSize), eax);
4686 case KEYED_SUPER_PROPERTY:
4687 __ mov(Operand(esp, 3 * kPointerSize), eax);
4693 // Record position before stub call.
4694 SetSourcePosition(expr->position());
4696 // Call stub for +1/-1.
4697 __ bind(&stub_call);
4699 __ mov(eax, Immediate(Smi::FromInt(1)));
4700 Handle<Code> code = CodeFactory::BinaryOpIC(isolate(), expr->binary_op(),
4701 NO_OVERWRITE).code();
4702 CallIC(code, expr->CountBinOpFeedbackId());
4703 patch_site.EmitPatchInfo();
4706 // Store the value returned in eax.
4707 switch (assign_type) {
4709 if (expr->is_postfix()) {
4710 // Perform the assignment as if via '='.
4711 { EffectContext context(this);
4712 EmitVariableAssignment(expr->expression()->AsVariableProxy()->var(),
4714 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
4717 // For all contexts except EffectContext We have the result on
4718 // top of the stack.
4719 if (!context()->IsEffect()) {
4720 context()->PlugTOS();
4723 // Perform the assignment as if via '='.
4724 EmitVariableAssignment(expr->expression()->AsVariableProxy()->var(),
4726 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
4727 context()->Plug(eax);
4730 case NAMED_PROPERTY: {
4731 __ mov(StoreDescriptor::NameRegister(),
4732 prop->key()->AsLiteral()->value());
4733 __ pop(StoreDescriptor::ReceiverRegister());
4734 CallStoreIC(expr->CountStoreFeedbackId());
4735 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
4736 if (expr->is_postfix()) {
4737 if (!context()->IsEffect()) {
4738 context()->PlugTOS();
4741 context()->Plug(eax);
4745 case NAMED_SUPER_PROPERTY: {
4746 EmitNamedSuperPropertyStore(prop);
4747 if (expr->is_postfix()) {
4748 if (!context()->IsEffect()) {
4749 context()->PlugTOS();
4752 context()->Plug(eax);
4756 case KEYED_SUPER_PROPERTY: {
4757 EmitKeyedSuperPropertyStore(prop);
4758 if (expr->is_postfix()) {
4759 if (!context()->IsEffect()) {
4760 context()->PlugTOS();
4763 context()->Plug(eax);
4767 case KEYED_PROPERTY: {
4768 __ pop(StoreDescriptor::NameRegister());
4769 __ pop(StoreDescriptor::ReceiverRegister());
4771 CodeFactory::KeyedStoreIC(isolate(), strict_mode()).code();
4772 CallIC(ic, expr->CountStoreFeedbackId());
4773 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
4774 if (expr->is_postfix()) {
4775 // Result is on the stack
4776 if (!context()->IsEffect()) {
4777 context()->PlugTOS();
4780 context()->Plug(eax);
4788 void FullCodeGenerator::VisitForTypeofValue(Expression* expr) {
4789 VariableProxy* proxy = expr->AsVariableProxy();
4790 DCHECK(!context()->IsEffect());
4791 DCHECK(!context()->IsTest());
4793 if (proxy != NULL && proxy->var()->IsUnallocated()) {
4794 Comment cmnt(masm_, "[ Global variable");
4795 __ mov(LoadDescriptor::ReceiverRegister(), GlobalObjectOperand());
4796 __ mov(LoadDescriptor::NameRegister(), Immediate(proxy->name()));
4797 if (FLAG_vector_ics) {
4798 __ mov(VectorLoadICDescriptor::SlotRegister(),
4799 Immediate(SmiFromSlot(proxy->VariableFeedbackSlot())));
4801 // Use a regular load, not a contextual load, to avoid a reference
4803 CallLoadIC(NOT_CONTEXTUAL);
4804 PrepareForBailout(expr, TOS_REG);
4805 context()->Plug(eax);
4806 } else if (proxy != NULL && proxy->var()->IsLookupSlot()) {
4807 Comment cmnt(masm_, "[ Lookup slot");
4810 // Generate code for loading from variables potentially shadowed
4811 // by eval-introduced variables.
4812 EmitDynamicLookupFastCase(proxy, INSIDE_TYPEOF, &slow, &done);
4816 __ push(Immediate(proxy->name()));
4817 __ CallRuntime(Runtime::kLoadLookupSlotNoReferenceError, 2);
4818 PrepareForBailout(expr, TOS_REG);
4821 context()->Plug(eax);
4823 // This expression cannot throw a reference error at the top level.
4824 VisitInDuplicateContext(expr);
4829 void FullCodeGenerator::EmitLiteralCompareTypeof(Expression* expr,
4830 Expression* sub_expr,
4831 Handle<String> check) {
4832 Label materialize_true, materialize_false;
4833 Label* if_true = NULL;
4834 Label* if_false = NULL;
4835 Label* fall_through = NULL;
4836 context()->PrepareTest(&materialize_true, &materialize_false,
4837 &if_true, &if_false, &fall_through);
4839 { AccumulatorValueContext context(this);
4840 VisitForTypeofValue(sub_expr);
4842 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
4844 Factory* factory = isolate()->factory();
4845 if (String::Equals(check, factory->number_string())) {
4846 __ JumpIfSmi(eax, if_true);
4847 __ cmp(FieldOperand(eax, HeapObject::kMapOffset),
4848 isolate()->factory()->heap_number_map());
4849 Split(equal, if_true, if_false, fall_through);
4850 } else if (String::Equals(check, factory->string_string())) {
4851 __ JumpIfSmi(eax, if_false);
4852 __ CmpObjectType(eax, FIRST_NONSTRING_TYPE, edx);
4853 __ j(above_equal, if_false);
4854 // Check for undetectable objects => false.
4855 __ test_b(FieldOperand(edx, Map::kBitFieldOffset),
4856 1 << Map::kIsUndetectable);
4857 Split(zero, if_true, if_false, fall_through);
4858 } else if (String::Equals(check, factory->symbol_string())) {
4859 __ JumpIfSmi(eax, if_false);
4860 __ CmpObjectType(eax, SYMBOL_TYPE, edx);
4861 Split(equal, if_true, if_false, fall_through);
4862 } else if (String::Equals(check, factory->boolean_string())) {
4863 __ cmp(eax, isolate()->factory()->true_value());
4864 __ j(equal, if_true);
4865 __ cmp(eax, isolate()->factory()->false_value());
4866 Split(equal, if_true, if_false, fall_through);
4867 } else if (String::Equals(check, factory->undefined_string())) {
4868 __ cmp(eax, isolate()->factory()->undefined_value());
4869 __ j(equal, if_true);
4870 __ JumpIfSmi(eax, if_false);
4871 // Check for undetectable objects => true.
4872 __ mov(edx, FieldOperand(eax, HeapObject::kMapOffset));
4873 __ movzx_b(ecx, FieldOperand(edx, Map::kBitFieldOffset));
4874 __ test(ecx, Immediate(1 << Map::kIsUndetectable));
4875 Split(not_zero, if_true, if_false, fall_through);
4876 } else if (String::Equals(check, factory->function_string())) {
4877 __ JumpIfSmi(eax, if_false);
4878 STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
4879 __ CmpObjectType(eax, JS_FUNCTION_TYPE, edx);
4880 __ j(equal, if_true);
4881 __ CmpInstanceType(edx, JS_FUNCTION_PROXY_TYPE);
4882 Split(equal, if_true, if_false, fall_through);
4883 } else if (String::Equals(check, factory->object_string())) {
4884 __ JumpIfSmi(eax, if_false);
4885 __ cmp(eax, isolate()->factory()->null_value());
4886 __ j(equal, if_true);
4887 __ CmpObjectType(eax, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE, edx);
4888 __ j(below, if_false);
4889 __ CmpInstanceType(edx, LAST_NONCALLABLE_SPEC_OBJECT_TYPE);
4890 __ j(above, if_false);
4891 // Check for undetectable objects => false.
4892 __ test_b(FieldOperand(edx, Map::kBitFieldOffset),
4893 1 << Map::kIsUndetectable);
4894 Split(zero, if_true, if_false, fall_through);
4896 if (if_false != fall_through) __ jmp(if_false);
4898 context()->Plug(if_true, if_false);
4902 void FullCodeGenerator::VisitCompareOperation(CompareOperation* expr) {
4903 Comment cmnt(masm_, "[ CompareOperation");
4904 SetSourcePosition(expr->position());
4906 // First we try a fast inlined version of the compare when one of
4907 // the operands is a literal.
4908 if (TryLiteralCompare(expr)) return;
4910 // Always perform the comparison for its control flow. Pack the result
4911 // into the expression's context after the comparison is performed.
4912 Label materialize_true, materialize_false;
4913 Label* if_true = NULL;
4914 Label* if_false = NULL;
4915 Label* fall_through = NULL;
4916 context()->PrepareTest(&materialize_true, &materialize_false,
4917 &if_true, &if_false, &fall_through);
4919 Token::Value op = expr->op();
4920 VisitForStackValue(expr->left());
4923 VisitForStackValue(expr->right());
4924 __ InvokeBuiltin(Builtins::IN, CALL_FUNCTION);
4925 PrepareForBailoutBeforeSplit(expr, false, NULL, NULL);
4926 __ cmp(eax, isolate()->factory()->true_value());
4927 Split(equal, if_true, if_false, fall_through);
4930 case Token::INSTANCEOF: {
4931 VisitForStackValue(expr->right());
4932 InstanceofStub stub(isolate(), InstanceofStub::kNoFlags);
4934 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
4936 // The stub returns 0 for true.
4937 Split(zero, if_true, if_false, fall_through);
4942 VisitForAccumulatorValue(expr->right());
4943 Condition cc = CompareIC::ComputeCondition(op);
4946 bool inline_smi_code = ShouldInlineSmiCase(op);
4947 JumpPatchSite patch_site(masm_);
4948 if (inline_smi_code) {
4952 patch_site.EmitJumpIfNotSmi(ecx, &slow_case, Label::kNear);
4954 Split(cc, if_true, if_false, NULL);
4955 __ bind(&slow_case);
4958 // Record position and call the compare IC.
4959 SetSourcePosition(expr->position());
4960 Handle<Code> ic = CodeFactory::CompareIC(isolate(), op).code();
4961 CallIC(ic, expr->CompareOperationFeedbackId());
4962 patch_site.EmitPatchInfo();
4964 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
4966 Split(cc, if_true, if_false, fall_through);
4970 // Convert the result of the comparison into one expected for this
4971 // expression's context.
4972 context()->Plug(if_true, if_false);
4976 void FullCodeGenerator::EmitLiteralCompareNil(CompareOperation* expr,
4977 Expression* sub_expr,
4979 Label materialize_true, materialize_false;
4980 Label* if_true = NULL;
4981 Label* if_false = NULL;
4982 Label* fall_through = NULL;
4983 context()->PrepareTest(&materialize_true, &materialize_false,
4984 &if_true, &if_false, &fall_through);
4986 VisitForAccumulatorValue(sub_expr);
4987 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
4989 Handle<Object> nil_value = nil == kNullValue
4990 ? isolate()->factory()->null_value()
4991 : isolate()->factory()->undefined_value();
4992 if (expr->op() == Token::EQ_STRICT) {
4993 __ cmp(eax, nil_value);
4994 Split(equal, if_true, if_false, fall_through);
4996 Handle<Code> ic = CompareNilICStub::GetUninitialized(isolate(), nil);
4997 CallIC(ic, expr->CompareOperationFeedbackId());
4999 Split(not_zero, if_true, if_false, fall_through);
5001 context()->Plug(if_true, if_false);
5005 void FullCodeGenerator::VisitThisFunction(ThisFunction* expr) {
5006 __ mov(eax, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
5007 context()->Plug(eax);
5011 Register FullCodeGenerator::result_register() {
5016 Register FullCodeGenerator::context_register() {
5021 void FullCodeGenerator::StoreToFrameField(int frame_offset, Register value) {
5022 DCHECK_EQ(POINTER_SIZE_ALIGN(frame_offset), frame_offset);
5023 __ mov(Operand(ebp, frame_offset), value);
5027 void FullCodeGenerator::LoadContextField(Register dst, int context_index) {
5028 __ mov(dst, ContextOperand(esi, context_index));
5032 void FullCodeGenerator::PushFunctionArgumentForContextAllocation() {
5033 Scope* declaration_scope = scope()->DeclarationScope();
5034 if (declaration_scope->is_global_scope() ||
5035 declaration_scope->is_module_scope()) {
5036 // Contexts nested in the native context have a canonical empty function
5037 // as their closure, not the anonymous closure containing the global
5038 // code. Pass a smi sentinel and let the runtime look up the empty
5040 __ push(Immediate(Smi::FromInt(0)));
5041 } else if (declaration_scope->is_eval_scope()) {
5042 // Contexts nested inside eval code have the same closure as the context
5043 // calling eval, not the anonymous closure containing the eval code.
5044 // Fetch it from the context.
5045 __ push(ContextOperand(esi, Context::CLOSURE_INDEX));
5047 DCHECK(declaration_scope->is_function_scope());
5048 __ push(Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
5053 // ----------------------------------------------------------------------------
5054 // Non-local control flow support.
5056 void FullCodeGenerator::EnterFinallyBlock() {
5057 // Cook return address on top of stack (smi encoded Code* delta)
5058 DCHECK(!result_register().is(edx));
5060 __ sub(edx, Immediate(masm_->CodeObject()));
5061 STATIC_ASSERT(kSmiTagSize + kSmiShiftSize == 1);
5062 STATIC_ASSERT(kSmiTag == 0);
5066 // Store result register while executing finally block.
5067 __ push(result_register());
5069 // Store pending message while executing finally block.
5070 ExternalReference pending_message_obj =
5071 ExternalReference::address_of_pending_message_obj(isolate());
5072 __ mov(edx, Operand::StaticVariable(pending_message_obj));
5075 ExternalReference has_pending_message =
5076 ExternalReference::address_of_has_pending_message(isolate());
5077 __ mov(edx, Operand::StaticVariable(has_pending_message));
5081 ExternalReference pending_message_script =
5082 ExternalReference::address_of_pending_message_script(isolate());
5083 __ mov(edx, Operand::StaticVariable(pending_message_script));
5088 void FullCodeGenerator::ExitFinallyBlock() {
5089 DCHECK(!result_register().is(edx));
5090 // Restore pending message from stack.
5092 ExternalReference pending_message_script =
5093 ExternalReference::address_of_pending_message_script(isolate());
5094 __ mov(Operand::StaticVariable(pending_message_script), edx);
5098 ExternalReference has_pending_message =
5099 ExternalReference::address_of_has_pending_message(isolate());
5100 __ mov(Operand::StaticVariable(has_pending_message), edx);
5103 ExternalReference pending_message_obj =
5104 ExternalReference::address_of_pending_message_obj(isolate());
5105 __ mov(Operand::StaticVariable(pending_message_obj), edx);
5107 // Restore result register from stack.
5108 __ pop(result_register());
5110 // Uncook return address.
5113 __ add(edx, Immediate(masm_->CodeObject()));
5120 #define __ ACCESS_MASM(masm())
5122 FullCodeGenerator::NestedStatement* FullCodeGenerator::TryFinally::Exit(
5124 int* context_length) {
5125 // The macros used here must preserve the result register.
5127 // Because the handler block contains the context of the finally
5128 // code, we can restore it directly from there for the finally code
5129 // rather than iteratively unwinding contexts via their previous
5131 __ Drop(*stack_depth); // Down to the handler block.
5132 if (*context_length > 0) {
5133 // Restore the context to its dedicated register and the stack.
5134 __ mov(esi, Operand(esp, StackHandlerConstants::kContextOffset));
5135 __ mov(Operand(ebp, StandardFrameConstants::kContextOffset), esi);
5138 __ call(finally_entry_);
5141 *context_length = 0;
5148 static const byte kJnsInstruction = 0x79;
5149 static const byte kJnsOffset = 0x11;
5150 static const byte kNopByteOne = 0x66;
5151 static const byte kNopByteTwo = 0x90;
5153 static const byte kCallInstruction = 0xe8;
5157 void BackEdgeTable::PatchAt(Code* unoptimized_code,
5159 BackEdgeState target_state,
5160 Code* replacement_code) {
5161 Address call_target_address = pc - kIntSize;
5162 Address jns_instr_address = call_target_address - 3;
5163 Address jns_offset_address = call_target_address - 2;
5165 switch (target_state) {
5167 // sub <profiling_counter>, <delta> ;; Not changed
5169 // call <interrupt stub>
5171 *jns_instr_address = kJnsInstruction;
5172 *jns_offset_address = kJnsOffset;
5174 case ON_STACK_REPLACEMENT:
5175 case OSR_AFTER_STACK_CHECK:
5176 // sub <profiling_counter>, <delta> ;; Not changed
5179 // call <on-stack replacment>
5181 *jns_instr_address = kNopByteOne;
5182 *jns_offset_address = kNopByteTwo;
5186 Assembler::set_target_address_at(call_target_address,
5188 replacement_code->entry());
5189 unoptimized_code->GetHeap()->incremental_marking()->RecordCodeTargetPatch(
5190 unoptimized_code, call_target_address, replacement_code);
5194 BackEdgeTable::BackEdgeState BackEdgeTable::GetBackEdgeState(
5196 Code* unoptimized_code,
5198 Address call_target_address = pc - kIntSize;
5199 Address jns_instr_address = call_target_address - 3;
5200 DCHECK_EQ(kCallInstruction, *(call_target_address - 1));
5202 if (*jns_instr_address == kJnsInstruction) {
5203 DCHECK_EQ(kJnsOffset, *(call_target_address - 2));
5204 DCHECK_EQ(isolate->builtins()->InterruptCheck()->entry(),
5205 Assembler::target_address_at(call_target_address,
5210 DCHECK_EQ(kNopByteOne, *jns_instr_address);
5211 DCHECK_EQ(kNopByteTwo, *(call_target_address - 2));
5213 if (Assembler::target_address_at(call_target_address, unoptimized_code) ==
5214 isolate->builtins()->OnStackReplacement()->entry()) {
5215 return ON_STACK_REPLACEMENT;
5218 DCHECK_EQ(isolate->builtins()->OsrAfterStackCheck()->entry(),
5219 Assembler::target_address_at(call_target_address,
5221 return OSR_AFTER_STACK_CHECK;
5225 } } // namespace v8::internal
5227 #endif // V8_TARGET_ARCH_IA32