1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
9 #include "src/code-factory.h"
10 #include "src/code-stubs.h"
11 #include "src/codegen.h"
12 #include "src/compiler.h"
13 #include "src/debug.h"
14 #include "src/full-codegen.h"
15 #include "src/ic/ic.h"
16 #include "src/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-x87.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 (is_sloppy(info->language_mode()) && !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(!IsGeneratorFunction(info->function()->kind()) || 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_script_scope()) {
193 __ Push(info->scope()->GetScopeInfo(info->isolate()));
194 __ CallRuntime(Runtime::kNewScriptContext, 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, context_offset, eax, ebx,
226 } else if (FLAG_debug_code) {
228 __ JumpIfInNewSpace(esi, eax, &done, Label::kNear);
229 __ Abort(kExpectedNewSpaceObject);
236 // Possibly allocate RestParameters
238 Variable* rest_param = scope()->rest_parameter(&rest_index);
240 Comment cmnt(masm_, "[ Allocate rest parameter array");
242 int num_parameters = info->scope()->num_parameters();
243 int offset = num_parameters * kPointerSize;
245 Operand(ebp, StandardFrameConstants::kCallerSPOffset + offset));
247 __ push(Immediate(Smi::FromInt(num_parameters)));
248 __ push(Immediate(Smi::FromInt(rest_index)));
250 RestParamAccessStub stub(isolate());
253 SetVar(rest_param, eax, ebx, edx);
256 Variable* arguments = scope()->arguments();
257 if (arguments != NULL) {
258 // Function uses arguments object.
259 Comment cmnt(masm_, "[ Allocate arguments object");
260 if (function_in_register) {
263 __ push(Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
265 // Receiver is just before the parameters on the caller's stack.
266 int num_parameters = info->scope()->num_parameters();
267 int offset = num_parameters * kPointerSize;
269 Operand(ebp, StandardFrameConstants::kCallerSPOffset + offset));
271 __ push(Immediate(Smi::FromInt(num_parameters)));
272 // Arguments to ArgumentsAccessStub:
273 // function, receiver address, parameter count.
274 // The stub will rewrite receiver and parameter count if the previous
275 // stack frame was an arguments adapter frame.
276 ArgumentsAccessStub::Type type;
277 if (is_strict(language_mode()) || !is_simple_parameter_list()) {
278 type = ArgumentsAccessStub::NEW_STRICT;
279 } else if (function()->has_duplicate_parameters()) {
280 type = ArgumentsAccessStub::NEW_SLOPPY_SLOW;
282 type = ArgumentsAccessStub::NEW_SLOPPY_FAST;
284 ArgumentsAccessStub::HasNewTarget has_new_target =
285 IsSubclassConstructor(info->function()->kind())
286 ? ArgumentsAccessStub::HAS_NEW_TARGET
287 : ArgumentsAccessStub::NO_NEW_TARGET;
288 ArgumentsAccessStub stub(isolate(), type, has_new_target);
291 SetVar(arguments, eax, ebx, edx);
295 __ CallRuntime(Runtime::kTraceEnter, 0);
298 // Visit the declarations and body unless there is an illegal
300 if (scope()->HasIllegalRedeclaration()) {
301 Comment cmnt(masm_, "[ Declarations");
302 scope()->VisitIllegalRedeclaration(this);
305 PrepareForBailoutForId(BailoutId::FunctionEntry(), NO_REGISTERS);
306 { Comment cmnt(masm_, "[ Declarations");
307 // For named function expressions, declare the function name as a
309 if (scope()->is_function_scope() && scope()->function() != NULL) {
310 VariableDeclaration* function = scope()->function();
311 DCHECK(function->proxy()->var()->mode() == CONST ||
312 function->proxy()->var()->mode() == CONST_LEGACY);
313 DCHECK(function->proxy()->var()->location() != Variable::UNALLOCATED);
314 VisitVariableDeclaration(function);
316 VisitDeclarations(scope()->declarations());
319 { Comment cmnt(masm_, "[ Stack check");
320 PrepareForBailoutForId(BailoutId::Declarations(), NO_REGISTERS);
322 ExternalReference stack_limit
323 = ExternalReference::address_of_stack_limit(isolate());
324 __ cmp(esp, Operand::StaticVariable(stack_limit));
325 __ j(above_equal, &ok, Label::kNear);
326 __ call(isolate()->builtins()->StackCheck(), RelocInfo::CODE_TARGET);
330 { Comment cmnt(masm_, "[ Body");
331 DCHECK(loop_depth() == 0);
332 VisitStatements(function()->body());
333 DCHECK(loop_depth() == 0);
337 // Always emit a 'return undefined' in case control fell off the end of
339 { Comment cmnt(masm_, "[ return <undefined>;");
340 __ mov(eax, isolate()->factory()->undefined_value());
341 EmitReturnSequence();
346 void FullCodeGenerator::ClearAccumulator() {
347 __ Move(eax, Immediate(Smi::FromInt(0)));
351 void FullCodeGenerator::EmitProfilingCounterDecrement(int delta) {
352 __ mov(ebx, Immediate(profiling_counter_));
353 __ sub(FieldOperand(ebx, Cell::kValueOffset),
354 Immediate(Smi::FromInt(delta)));
358 void FullCodeGenerator::EmitProfilingCounterReset() {
359 int reset_value = FLAG_interrupt_budget;
360 __ mov(ebx, Immediate(profiling_counter_));
361 __ mov(FieldOperand(ebx, Cell::kValueOffset),
362 Immediate(Smi::FromInt(reset_value)));
366 void FullCodeGenerator::EmitBackEdgeBookkeeping(IterationStatement* stmt,
367 Label* back_edge_target) {
368 Comment cmnt(masm_, "[ Back edge bookkeeping");
371 DCHECK(back_edge_target->is_bound());
372 int distance = masm_->SizeOfCodeGeneratedSince(back_edge_target);
373 int weight = Min(kMaxBackEdgeWeight,
374 Max(1, distance / kCodeSizeMultiplier));
375 EmitProfilingCounterDecrement(weight);
376 __ j(positive, &ok, Label::kNear);
377 __ call(isolate()->builtins()->InterruptCheck(), RelocInfo::CODE_TARGET);
379 // Record a mapping of this PC offset to the OSR id. This is used to find
380 // the AST id from the unoptimized code in order to use it as a key into
381 // the deoptimization input data found in the optimized code.
382 RecordBackEdge(stmt->OsrEntryId());
384 EmitProfilingCounterReset();
387 PrepareForBailoutForId(stmt->EntryId(), NO_REGISTERS);
388 // Record a mapping of the OSR id to this PC. This is used if the OSR
389 // entry becomes the target of a bailout. We don't expect it to be, but
390 // we want it to work if it is.
391 PrepareForBailoutForId(stmt->OsrEntryId(), NO_REGISTERS);
395 void FullCodeGenerator::EmitReturnSequence() {
396 Comment cmnt(masm_, "[ Return sequence");
397 if (return_label_.is_bound()) {
398 __ jmp(&return_label_);
400 // Common return label
401 __ bind(&return_label_);
404 __ CallRuntime(Runtime::kTraceExit, 1);
406 // Pretend that the exit is a backwards jump to the entry.
408 if (info_->ShouldSelfOptimize()) {
409 weight = FLAG_interrupt_budget / FLAG_self_opt_count;
411 int distance = masm_->pc_offset();
412 weight = Min(kMaxBackEdgeWeight,
413 Max(1, distance / kCodeSizeMultiplier));
415 EmitProfilingCounterDecrement(weight);
417 __ j(positive, &ok, Label::kNear);
419 __ call(isolate()->builtins()->InterruptCheck(),
420 RelocInfo::CODE_TARGET);
422 EmitProfilingCounterReset();
425 // Add a label for checking the size of the code used for returning.
426 Label check_exit_codesize;
427 masm_->bind(&check_exit_codesize);
429 SetSourcePosition(function()->end_position() - 1);
431 // Do not use the leave instruction here because it is too short to
432 // patch with the code required by the debugger.
434 int no_frame_start = masm_->pc_offset();
437 int arg_count = info_->scope()->num_parameters() + 1;
438 if (IsSubclassConstructor(info_->function()->kind())) {
441 int arguments_bytes = arg_count * kPointerSize;
442 __ Ret(arguments_bytes, ecx);
443 // Check that the size of the code used for returning is large enough
444 // for the debugger's requirements.
445 DCHECK(Assembler::kJSReturnSequenceLength <=
446 masm_->SizeOfCodeGeneratedSince(&check_exit_codesize));
447 info_->AddNoFrameRange(no_frame_start, masm_->pc_offset());
452 void FullCodeGenerator::EffectContext::Plug(Variable* var) const {
453 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
457 void FullCodeGenerator::AccumulatorValueContext::Plug(Variable* var) const {
458 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
459 codegen()->GetVar(result_register(), var);
463 void FullCodeGenerator::StackValueContext::Plug(Variable* var) const {
464 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
465 MemOperand operand = codegen()->VarOperand(var, result_register());
466 // Memory operands can be pushed directly.
471 void FullCodeGenerator::TestContext::Plug(Variable* var) const {
472 // For simplicity we always test the accumulator register.
473 codegen()->GetVar(result_register(), var);
474 codegen()->PrepareForBailoutBeforeSplit(condition(), false, NULL, NULL);
475 codegen()->DoTest(this);
479 void FullCodeGenerator::EffectContext::Plug(Heap::RootListIndex index) const {
480 UNREACHABLE(); // Not used on X87.
484 void FullCodeGenerator::AccumulatorValueContext::Plug(
485 Heap::RootListIndex index) const {
486 UNREACHABLE(); // Not used on X87.
490 void FullCodeGenerator::StackValueContext::Plug(
491 Heap::RootListIndex index) const {
492 UNREACHABLE(); // Not used on X87.
496 void FullCodeGenerator::TestContext::Plug(Heap::RootListIndex index) const {
497 UNREACHABLE(); // Not used on X87.
501 void FullCodeGenerator::EffectContext::Plug(Handle<Object> lit) const {
505 void FullCodeGenerator::AccumulatorValueContext::Plug(
506 Handle<Object> lit) const {
508 __ SafeMove(result_register(), Immediate(lit));
510 __ Move(result_register(), Immediate(lit));
515 void FullCodeGenerator::StackValueContext::Plug(Handle<Object> lit) const {
517 __ SafePush(Immediate(lit));
519 __ push(Immediate(lit));
524 void FullCodeGenerator::TestContext::Plug(Handle<Object> lit) const {
525 codegen()->PrepareForBailoutBeforeSplit(condition(),
529 DCHECK(!lit->IsUndetectableObject()); // There are no undetectable literals.
530 if (lit->IsUndefined() || lit->IsNull() || lit->IsFalse()) {
531 if (false_label_ != fall_through_) __ jmp(false_label_);
532 } else if (lit->IsTrue() || lit->IsJSObject()) {
533 if (true_label_ != fall_through_) __ jmp(true_label_);
534 } else if (lit->IsString()) {
535 if (String::cast(*lit)->length() == 0) {
536 if (false_label_ != fall_through_) __ jmp(false_label_);
538 if (true_label_ != fall_through_) __ jmp(true_label_);
540 } else if (lit->IsSmi()) {
541 if (Smi::cast(*lit)->value() == 0) {
542 if (false_label_ != fall_through_) __ jmp(false_label_);
544 if (true_label_ != fall_through_) __ jmp(true_label_);
547 // For simplicity we always test the accumulator register.
548 __ mov(result_register(), lit);
549 codegen()->DoTest(this);
554 void FullCodeGenerator::EffectContext::DropAndPlug(int count,
555 Register reg) const {
561 void FullCodeGenerator::AccumulatorValueContext::DropAndPlug(
563 Register reg) const {
566 __ Move(result_register(), reg);
570 void FullCodeGenerator::StackValueContext::DropAndPlug(int count,
571 Register reg) const {
573 if (count > 1) __ Drop(count - 1);
574 __ mov(Operand(esp, 0), reg);
578 void FullCodeGenerator::TestContext::DropAndPlug(int count,
579 Register reg) const {
581 // For simplicity we always test the accumulator register.
583 __ Move(result_register(), reg);
584 codegen()->PrepareForBailoutBeforeSplit(condition(), false, NULL, NULL);
585 codegen()->DoTest(this);
589 void FullCodeGenerator::EffectContext::Plug(Label* materialize_true,
590 Label* materialize_false) const {
591 DCHECK(materialize_true == materialize_false);
592 __ bind(materialize_true);
596 void FullCodeGenerator::AccumulatorValueContext::Plug(
597 Label* materialize_true,
598 Label* materialize_false) const {
600 __ bind(materialize_true);
601 __ mov(result_register(), isolate()->factory()->true_value());
602 __ jmp(&done, Label::kNear);
603 __ bind(materialize_false);
604 __ mov(result_register(), isolate()->factory()->false_value());
609 void FullCodeGenerator::StackValueContext::Plug(
610 Label* materialize_true,
611 Label* materialize_false) const {
613 __ bind(materialize_true);
614 __ push(Immediate(isolate()->factory()->true_value()));
615 __ jmp(&done, Label::kNear);
616 __ bind(materialize_false);
617 __ push(Immediate(isolate()->factory()->false_value()));
622 void FullCodeGenerator::TestContext::Plug(Label* materialize_true,
623 Label* materialize_false) const {
624 DCHECK(materialize_true == true_label_);
625 DCHECK(materialize_false == false_label_);
629 void FullCodeGenerator::EffectContext::Plug(bool flag) const {
633 void FullCodeGenerator::AccumulatorValueContext::Plug(bool flag) const {
634 Handle<Object> value = flag
635 ? isolate()->factory()->true_value()
636 : isolate()->factory()->false_value();
637 __ mov(result_register(), value);
641 void FullCodeGenerator::StackValueContext::Plug(bool flag) const {
642 Handle<Object> value = flag
643 ? isolate()->factory()->true_value()
644 : isolate()->factory()->false_value();
645 __ push(Immediate(value));
649 void FullCodeGenerator::TestContext::Plug(bool flag) const {
650 codegen()->PrepareForBailoutBeforeSplit(condition(),
655 if (true_label_ != fall_through_) __ jmp(true_label_);
657 if (false_label_ != fall_through_) __ jmp(false_label_);
662 void FullCodeGenerator::DoTest(Expression* condition,
665 Label* fall_through) {
666 Handle<Code> ic = ToBooleanStub::GetUninitialized(isolate());
667 CallIC(ic, condition->test_id());
668 __ test(result_register(), result_register());
669 // The stub returns nonzero for true.
670 Split(not_zero, if_true, if_false, fall_through);
674 void FullCodeGenerator::Split(Condition cc,
677 Label* fall_through) {
678 if (if_false == fall_through) {
680 } else if (if_true == fall_through) {
681 __ j(NegateCondition(cc), if_false);
689 MemOperand FullCodeGenerator::StackOperand(Variable* var) {
690 DCHECK(var->IsStackAllocated());
691 // Offset is negative because higher indexes are at lower addresses.
692 int offset = -var->index() * kPointerSize;
693 // Adjust by a (parameter or local) base offset.
694 if (var->IsParameter()) {
695 offset += (info_->scope()->num_parameters() + 1) * kPointerSize;
697 offset += JavaScriptFrameConstants::kLocal0Offset;
699 return Operand(ebp, offset);
703 MemOperand FullCodeGenerator::VarOperand(Variable* var, Register scratch) {
704 DCHECK(var->IsContextSlot() || var->IsStackAllocated());
705 if (var->IsContextSlot()) {
706 int context_chain_length = scope()->ContextChainLength(var->scope());
707 __ LoadContext(scratch, context_chain_length);
708 return ContextOperand(scratch, var->index());
710 return StackOperand(var);
715 void FullCodeGenerator::GetVar(Register dest, Variable* var) {
716 DCHECK(var->IsContextSlot() || var->IsStackAllocated());
717 MemOperand location = VarOperand(var, dest);
718 __ mov(dest, location);
722 void FullCodeGenerator::SetVar(Variable* var,
726 DCHECK(var->IsContextSlot() || var->IsStackAllocated());
727 DCHECK(!scratch0.is(src));
728 DCHECK(!scratch0.is(scratch1));
729 DCHECK(!scratch1.is(src));
730 MemOperand location = VarOperand(var, scratch0);
731 __ mov(location, src);
733 // Emit the write barrier code if the location is in the heap.
734 if (var->IsContextSlot()) {
735 int offset = Context::SlotOffset(var->index());
736 DCHECK(!scratch0.is(esi) && !src.is(esi) && !scratch1.is(esi));
737 __ RecordWriteContextSlot(scratch0, offset, src, scratch1, kDontSaveFPRegs);
742 void FullCodeGenerator::PrepareForBailoutBeforeSplit(Expression* expr,
743 bool should_normalize,
746 // Only prepare for bailouts before splits if we're in a test
747 // context. Otherwise, we let the Visit function deal with the
748 // preparation to avoid preparing with the same AST id twice.
749 if (!context()->IsTest() || !info_->IsOptimizable()) return;
752 if (should_normalize) __ jmp(&skip, Label::kNear);
753 PrepareForBailout(expr, TOS_REG);
754 if (should_normalize) {
755 __ cmp(eax, isolate()->factory()->true_value());
756 Split(equal, if_true, if_false, NULL);
762 void FullCodeGenerator::EmitDebugCheckDeclarationContext(Variable* variable) {
763 // The variable in the declaration always resides in the current context.
764 DCHECK_EQ(0, scope()->ContextChainLength(variable->scope()));
765 if (generate_debug_code_) {
766 // Check that we're not inside a with or catch context.
767 __ mov(ebx, FieldOperand(esi, HeapObject::kMapOffset));
768 __ cmp(ebx, isolate()->factory()->with_context_map());
769 __ Check(not_equal, kDeclarationInWithContext);
770 __ cmp(ebx, isolate()->factory()->catch_context_map());
771 __ Check(not_equal, kDeclarationInCatchContext);
776 void FullCodeGenerator::VisitVariableDeclaration(
777 VariableDeclaration* declaration) {
778 // If it was not possible to allocate the variable at compile time, we
779 // need to "declare" it at runtime to make sure it actually exists in the
781 VariableProxy* proxy = declaration->proxy();
782 VariableMode mode = declaration->mode();
783 Variable* variable = proxy->var();
784 bool hole_init = mode == LET || mode == CONST || mode == CONST_LEGACY;
785 switch (variable->location()) {
786 case Variable::UNALLOCATED:
787 globals_->Add(variable->name(), zone());
788 globals_->Add(variable->binding_needs_init()
789 ? isolate()->factory()->the_hole_value()
790 : isolate()->factory()->undefined_value(), zone());
793 case Variable::PARAMETER:
794 case Variable::LOCAL:
796 Comment cmnt(masm_, "[ VariableDeclaration");
797 __ mov(StackOperand(variable),
798 Immediate(isolate()->factory()->the_hole_value()));
802 case Variable::CONTEXT:
804 Comment cmnt(masm_, "[ VariableDeclaration");
805 EmitDebugCheckDeclarationContext(variable);
806 __ mov(ContextOperand(esi, variable->index()),
807 Immediate(isolate()->factory()->the_hole_value()));
808 // No write barrier since the hole value is in old space.
809 PrepareForBailoutForId(proxy->id(), NO_REGISTERS);
813 case Variable::LOOKUP: {
814 Comment cmnt(masm_, "[ VariableDeclaration");
816 __ push(Immediate(variable->name()));
817 // VariableDeclaration nodes are always introduced in one of four modes.
818 DCHECK(IsDeclaredVariableMode(mode));
819 PropertyAttributes attr =
820 IsImmutableVariableMode(mode) ? READ_ONLY : NONE;
821 __ push(Immediate(Smi::FromInt(attr)));
822 // Push initial value, if any.
823 // Note: For variables we must not push an initial value (such as
824 // 'undefined') because we may have a (legal) redeclaration and we
825 // must not destroy the current value.
827 __ push(Immediate(isolate()->factory()->the_hole_value()));
829 __ push(Immediate(Smi::FromInt(0))); // Indicates no initial value.
831 __ CallRuntime(Runtime::kDeclareLookupSlot, 4);
838 void FullCodeGenerator::VisitFunctionDeclaration(
839 FunctionDeclaration* declaration) {
840 VariableProxy* proxy = declaration->proxy();
841 Variable* variable = proxy->var();
842 switch (variable->location()) {
843 case Variable::UNALLOCATED: {
844 globals_->Add(variable->name(), zone());
845 Handle<SharedFunctionInfo> function =
846 Compiler::BuildFunctionInfo(declaration->fun(), script(), info_);
847 // Check for stack-overflow exception.
848 if (function.is_null()) return SetStackOverflow();
849 globals_->Add(function, zone());
853 case Variable::PARAMETER:
854 case Variable::LOCAL: {
855 Comment cmnt(masm_, "[ FunctionDeclaration");
856 VisitForAccumulatorValue(declaration->fun());
857 __ mov(StackOperand(variable), result_register());
861 case Variable::CONTEXT: {
862 Comment cmnt(masm_, "[ FunctionDeclaration");
863 EmitDebugCheckDeclarationContext(variable);
864 VisitForAccumulatorValue(declaration->fun());
865 __ mov(ContextOperand(esi, variable->index()), result_register());
866 // We know that we have written a function, which is not a smi.
867 __ RecordWriteContextSlot(esi, Context::SlotOffset(variable->index()),
868 result_register(), ecx, kDontSaveFPRegs,
869 EMIT_REMEMBERED_SET, OMIT_SMI_CHECK);
870 PrepareForBailoutForId(proxy->id(), NO_REGISTERS);
874 case Variable::LOOKUP: {
875 Comment cmnt(masm_, "[ FunctionDeclaration");
877 __ push(Immediate(variable->name()));
878 __ push(Immediate(Smi::FromInt(NONE)));
879 VisitForStackValue(declaration->fun());
880 __ CallRuntime(Runtime::kDeclareLookupSlot, 4);
887 void FullCodeGenerator::VisitModuleDeclaration(ModuleDeclaration* declaration) {
888 Variable* variable = declaration->proxy()->var();
889 ModuleDescriptor* descriptor = declaration->module()->descriptor();
890 DCHECK(variable->location() == Variable::CONTEXT);
891 DCHECK(descriptor->IsFrozen());
893 Comment cmnt(masm_, "[ ModuleDeclaration");
894 EmitDebugCheckDeclarationContext(variable);
896 // Load instance object.
897 __ LoadContext(eax, scope_->ContextChainLength(scope_->ScriptScope()));
898 __ mov(eax, ContextOperand(eax, descriptor->Index()));
899 __ mov(eax, ContextOperand(eax, Context::EXTENSION_INDEX));
902 __ mov(ContextOperand(esi, variable->index()), eax);
903 // We know that we have written a module, which is not a smi.
904 __ RecordWriteContextSlot(esi, Context::SlotOffset(variable->index()), eax,
905 ecx, kDontSaveFPRegs, EMIT_REMEMBERED_SET,
907 PrepareForBailoutForId(declaration->proxy()->id(), NO_REGISTERS);
909 // Traverse into body.
910 Visit(declaration->module());
914 void FullCodeGenerator::VisitImportDeclaration(ImportDeclaration* declaration) {
915 VariableProxy* proxy = declaration->proxy();
916 Variable* variable = proxy->var();
917 switch (variable->location()) {
918 case Variable::UNALLOCATED:
922 case Variable::CONTEXT: {
923 Comment cmnt(masm_, "[ ImportDeclaration");
924 EmitDebugCheckDeclarationContext(variable);
929 case Variable::PARAMETER:
930 case Variable::LOCAL:
931 case Variable::LOOKUP:
937 void FullCodeGenerator::VisitExportDeclaration(ExportDeclaration* declaration) {
942 void FullCodeGenerator::DeclareGlobals(Handle<FixedArray> pairs) {
943 // Call the runtime to declare the globals.
944 __ push(esi); // The context is the first argument.
946 __ Push(Smi::FromInt(DeclareGlobalsFlags()));
947 __ CallRuntime(Runtime::kDeclareGlobals, 3);
948 // Return value is ignored.
952 void FullCodeGenerator::DeclareModules(Handle<FixedArray> descriptions) {
953 // Call the runtime to declare the modules.
954 __ Push(descriptions);
955 __ CallRuntime(Runtime::kDeclareModules, 1);
956 // Return value is ignored.
960 void FullCodeGenerator::VisitSwitchStatement(SwitchStatement* stmt) {
961 Comment cmnt(masm_, "[ SwitchStatement");
962 Breakable nested_statement(this, stmt);
963 SetStatementPosition(stmt);
965 // Keep the switch value on the stack until a case matches.
966 VisitForStackValue(stmt->tag());
967 PrepareForBailoutForId(stmt->EntryId(), NO_REGISTERS);
969 ZoneList<CaseClause*>* clauses = stmt->cases();
970 CaseClause* default_clause = NULL; // Can occur anywhere in the list.
972 Label next_test; // Recycled for each test.
973 // Compile all the tests with branches to their bodies.
974 for (int i = 0; i < clauses->length(); i++) {
975 CaseClause* clause = clauses->at(i);
976 clause->body_target()->Unuse();
978 // The default is not a test, but remember it as final fall through.
979 if (clause->is_default()) {
980 default_clause = clause;
984 Comment cmnt(masm_, "[ Case comparison");
988 // Compile the label expression.
989 VisitForAccumulatorValue(clause->label());
991 // Perform the comparison as if via '==='.
992 __ mov(edx, Operand(esp, 0)); // Switch value.
993 bool inline_smi_code = ShouldInlineSmiCase(Token::EQ_STRICT);
994 JumpPatchSite patch_site(masm_);
995 if (inline_smi_code) {
999 patch_site.EmitJumpIfNotSmi(ecx, &slow_case, Label::kNear);
1002 __ j(not_equal, &next_test);
1003 __ Drop(1); // Switch value is no longer needed.
1004 __ jmp(clause->body_target());
1005 __ bind(&slow_case);
1008 // Record position before stub call for type feedback.
1009 SetSourcePosition(clause->position());
1011 CodeFactory::CompareIC(isolate(), Token::EQ_STRICT).code();
1012 CallIC(ic, clause->CompareId());
1013 patch_site.EmitPatchInfo();
1016 __ jmp(&skip, Label::kNear);
1017 PrepareForBailout(clause, TOS_REG);
1018 __ cmp(eax, isolate()->factory()->true_value());
1019 __ j(not_equal, &next_test);
1021 __ jmp(clause->body_target());
1025 __ j(not_equal, &next_test);
1026 __ Drop(1); // Switch value is no longer needed.
1027 __ jmp(clause->body_target());
1030 // Discard the test value and jump to the default if present, otherwise to
1031 // the end of the statement.
1032 __ bind(&next_test);
1033 __ Drop(1); // Switch value is no longer needed.
1034 if (default_clause == NULL) {
1035 __ jmp(nested_statement.break_label());
1037 __ jmp(default_clause->body_target());
1040 // Compile all the case bodies.
1041 for (int i = 0; i < clauses->length(); i++) {
1042 Comment cmnt(masm_, "[ Case body");
1043 CaseClause* clause = clauses->at(i);
1044 __ bind(clause->body_target());
1045 PrepareForBailoutForId(clause->EntryId(), NO_REGISTERS);
1046 VisitStatements(clause->statements());
1049 __ bind(nested_statement.break_label());
1050 PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1054 void FullCodeGenerator::VisitForInStatement(ForInStatement* stmt) {
1055 Comment cmnt(masm_, "[ ForInStatement");
1056 FeedbackVectorSlot slot = stmt->ForInFeedbackSlot();
1058 SetStatementPosition(stmt);
1061 ForIn loop_statement(this, stmt);
1062 increment_loop_depth();
1064 // Get the object to enumerate over. If the object is null or undefined, skip
1065 // over the loop. See ECMA-262 version 5, section 12.6.4.
1066 SetExpressionPosition(stmt->enumerable());
1067 VisitForAccumulatorValue(stmt->enumerable());
1068 __ cmp(eax, isolate()->factory()->undefined_value());
1070 __ cmp(eax, isolate()->factory()->null_value());
1073 PrepareForBailoutForId(stmt->PrepareId(), TOS_REG);
1075 // Convert the object to a JS object.
1076 Label convert, done_convert;
1077 __ JumpIfSmi(eax, &convert, Label::kNear);
1078 __ CmpObjectType(eax, FIRST_SPEC_OBJECT_TYPE, ecx);
1079 __ j(above_equal, &done_convert, Label::kNear);
1082 __ InvokeBuiltin(Builtins::TO_OBJECT, CALL_FUNCTION);
1083 __ bind(&done_convert);
1084 PrepareForBailoutForId(stmt->ToObjectId(), TOS_REG);
1087 // Check for proxies.
1088 Label call_runtime, use_cache, fixed_array;
1089 STATIC_ASSERT(FIRST_JS_PROXY_TYPE == FIRST_SPEC_OBJECT_TYPE);
1090 __ CmpObjectType(eax, LAST_JS_PROXY_TYPE, ecx);
1091 __ j(below_equal, &call_runtime);
1093 // Check cache validity in generated code. This is a fast case for
1094 // the JSObject::IsSimpleEnum cache validity checks. If we cannot
1095 // guarantee cache validity, call the runtime system to check cache
1096 // validity or get the property names in a fixed array.
1097 __ CheckEnumCache(&call_runtime);
1099 __ mov(eax, FieldOperand(eax, HeapObject::kMapOffset));
1100 __ jmp(&use_cache, Label::kNear);
1102 // Get the set of properties to enumerate.
1103 __ bind(&call_runtime);
1105 __ CallRuntime(Runtime::kGetPropertyNamesFast, 1);
1106 PrepareForBailoutForId(stmt->EnumId(), TOS_REG);
1107 __ cmp(FieldOperand(eax, HeapObject::kMapOffset),
1108 isolate()->factory()->meta_map());
1109 __ j(not_equal, &fixed_array);
1112 // We got a map in register eax. Get the enumeration cache from it.
1113 Label no_descriptors;
1114 __ bind(&use_cache);
1116 __ EnumLength(edx, eax);
1117 __ cmp(edx, Immediate(Smi::FromInt(0)));
1118 __ j(equal, &no_descriptors);
1120 __ LoadInstanceDescriptors(eax, ecx);
1121 __ mov(ecx, FieldOperand(ecx, DescriptorArray::kEnumCacheOffset));
1122 __ mov(ecx, FieldOperand(ecx, DescriptorArray::kEnumCacheBridgeCacheOffset));
1124 // Set up the four remaining stack slots.
1125 __ push(eax); // Map.
1126 __ push(ecx); // Enumeration cache.
1127 __ push(edx); // Number of valid entries for the map in the enum cache.
1128 __ push(Immediate(Smi::FromInt(0))); // Initial index.
1131 __ bind(&no_descriptors);
1132 __ add(esp, Immediate(kPointerSize));
1135 // We got a fixed array in register eax. Iterate through that.
1137 __ bind(&fixed_array);
1139 // No need for a write barrier, we are storing a Smi in the feedback vector.
1140 __ LoadHeapObject(ebx, FeedbackVector());
1141 int vector_index = FeedbackVector()->GetIndex(slot);
1142 __ mov(FieldOperand(ebx, FixedArray::OffsetOfElementAt(vector_index)),
1143 Immediate(TypeFeedbackVector::MegamorphicSentinel(isolate())));
1145 __ mov(ebx, Immediate(Smi::FromInt(1))); // Smi indicates slow check
1146 __ mov(ecx, Operand(esp, 0 * kPointerSize)); // Get enumerated object
1147 STATIC_ASSERT(FIRST_JS_PROXY_TYPE == FIRST_SPEC_OBJECT_TYPE);
1148 __ CmpObjectType(ecx, LAST_JS_PROXY_TYPE, ecx);
1149 __ j(above, &non_proxy);
1150 __ Move(ebx, Immediate(Smi::FromInt(0))); // Zero indicates proxy
1151 __ bind(&non_proxy);
1152 __ push(ebx); // Smi
1153 __ push(eax); // Array
1154 __ mov(eax, FieldOperand(eax, FixedArray::kLengthOffset));
1155 __ push(eax); // Fixed array length (as smi).
1156 __ push(Immediate(Smi::FromInt(0))); // Initial index.
1158 // Generate code for doing the condition check.
1159 PrepareForBailoutForId(stmt->BodyId(), NO_REGISTERS);
1161 SetExpressionPosition(stmt->each());
1163 __ mov(eax, Operand(esp, 0 * kPointerSize)); // Get the current index.
1164 __ cmp(eax, Operand(esp, 1 * kPointerSize)); // Compare to the array length.
1165 __ j(above_equal, loop_statement.break_label());
1167 // Get the current entry of the array into register ebx.
1168 __ mov(ebx, Operand(esp, 2 * kPointerSize));
1169 __ mov(ebx, FieldOperand(ebx, eax, times_2, FixedArray::kHeaderSize));
1171 // Get the expected map from the stack or a smi in the
1172 // permanent slow case into register edx.
1173 __ mov(edx, Operand(esp, 3 * kPointerSize));
1175 // Check if the expected map still matches that of the enumerable.
1176 // If not, we may have to filter the key.
1178 __ mov(ecx, Operand(esp, 4 * kPointerSize));
1179 __ cmp(edx, FieldOperand(ecx, HeapObject::kMapOffset));
1180 __ j(equal, &update_each, Label::kNear);
1182 // For proxies, no filtering is done.
1183 // TODO(rossberg): What if only a prototype is a proxy? Not specified yet.
1184 DCHECK(Smi::FromInt(0) == 0);
1186 __ j(zero, &update_each);
1188 // Convert the entry to a string or null if it isn't a property
1189 // anymore. If the property has been removed while iterating, we
1191 __ push(ecx); // Enumerable.
1192 __ push(ebx); // Current entry.
1193 __ InvokeBuiltin(Builtins::FILTER_KEY, CALL_FUNCTION);
1195 __ j(equal, loop_statement.continue_label());
1198 // Update the 'each' property or variable from the possibly filtered
1199 // entry in register ebx.
1200 __ bind(&update_each);
1201 __ mov(result_register(), ebx);
1202 // Perform the assignment as if via '='.
1203 { EffectContext context(this);
1204 EmitAssignment(stmt->each());
1205 PrepareForBailoutForId(stmt->AssignmentId(), NO_REGISTERS);
1208 // Generate code for the body of the loop.
1209 Visit(stmt->body());
1211 // Generate code for going to the next element by incrementing the
1212 // index (smi) stored on top of the stack.
1213 __ bind(loop_statement.continue_label());
1214 __ add(Operand(esp, 0 * kPointerSize), Immediate(Smi::FromInt(1)));
1216 EmitBackEdgeBookkeeping(stmt, &loop);
1219 // Remove the pointers stored on the stack.
1220 __ bind(loop_statement.break_label());
1221 __ add(esp, Immediate(5 * kPointerSize));
1223 // Exit and decrement the loop depth.
1224 PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1226 decrement_loop_depth();
1230 void FullCodeGenerator::EmitNewClosure(Handle<SharedFunctionInfo> info,
1232 // Use the fast case closure allocation code that allocates in new
1233 // space for nested functions that don't need literals cloning. If
1234 // we're running with the --always-opt or the --prepare-always-opt
1235 // flag, we need to use the runtime function so that the new function
1236 // we are creating here gets a chance to have its code optimized and
1237 // doesn't just get a copy of the existing unoptimized code.
1238 if (!FLAG_always_opt &&
1239 !FLAG_prepare_always_opt &&
1241 scope()->is_function_scope() &&
1242 info->num_literals() == 0) {
1243 FastNewClosureStub stub(isolate(), info->language_mode(), info->kind());
1244 __ mov(ebx, Immediate(info));
1248 __ push(Immediate(info));
1249 __ push(Immediate(pretenure
1250 ? isolate()->factory()->true_value()
1251 : isolate()->factory()->false_value()));
1252 __ CallRuntime(Runtime::kNewClosure, 3);
1254 context()->Plug(eax);
1258 void FullCodeGenerator::VisitVariableProxy(VariableProxy* expr) {
1259 Comment cmnt(masm_, "[ VariableProxy");
1260 EmitVariableLoad(expr);
1264 void FullCodeGenerator::EmitLoadHomeObject(SuperReference* expr) {
1265 Comment cnmt(masm_, "[ SuperReference ");
1267 __ mov(LoadDescriptor::ReceiverRegister(),
1268 Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
1270 Handle<Symbol> home_object_symbol(isolate()->heap()->home_object_symbol());
1271 __ mov(LoadDescriptor::NameRegister(), home_object_symbol);
1273 if (FLAG_vector_ics) {
1274 __ mov(VectorLoadICDescriptor::SlotRegister(),
1275 Immediate(SmiFromSlot(expr->HomeObjectFeedbackSlot())));
1276 CallLoadIC(NOT_CONTEXTUAL);
1278 CallLoadIC(NOT_CONTEXTUAL, expr->HomeObjectFeedbackId());
1281 __ cmp(eax, isolate()->factory()->undefined_value());
1283 __ j(not_equal, &done);
1284 __ CallRuntime(Runtime::kThrowNonMethodError, 0);
1289 void FullCodeGenerator::EmitSetHomeObjectIfNeeded(Expression* initializer,
1291 if (NeedsHomeObject(initializer)) {
1292 __ mov(StoreDescriptor::ReceiverRegister(), Operand(esp, 0));
1293 __ mov(StoreDescriptor::NameRegister(),
1294 Immediate(isolate()->factory()->home_object_symbol()));
1295 __ mov(StoreDescriptor::ValueRegister(),
1296 Operand(esp, offset * kPointerSize));
1302 void FullCodeGenerator::EmitLoadGlobalCheckExtensions(VariableProxy* proxy,
1303 TypeofState typeof_state,
1305 Register context = esi;
1306 Register temp = edx;
1310 if (s->num_heap_slots() > 0) {
1311 if (s->calls_sloppy_eval()) {
1312 // Check that extension is NULL.
1313 __ cmp(ContextOperand(context, Context::EXTENSION_INDEX),
1315 __ j(not_equal, slow);
1317 // Load next context in chain.
1318 __ mov(temp, ContextOperand(context, Context::PREVIOUS_INDEX));
1319 // Walk the rest of the chain without clobbering esi.
1322 // If no outer scope calls eval, we do not need to check more
1323 // context extensions. If we have reached an eval scope, we check
1324 // all extensions from this point.
1325 if (!s->outer_scope_calls_sloppy_eval() || s->is_eval_scope()) break;
1326 s = s->outer_scope();
1329 if (s != NULL && s->is_eval_scope()) {
1330 // Loop up the context chain. There is no frame effect so it is
1331 // safe to use raw labels here.
1333 if (!context.is(temp)) {
1334 __ mov(temp, context);
1337 // Terminate at native context.
1338 __ cmp(FieldOperand(temp, HeapObject::kMapOffset),
1339 Immediate(isolate()->factory()->native_context_map()));
1340 __ j(equal, &fast, Label::kNear);
1341 // Check that extension is NULL.
1342 __ cmp(ContextOperand(temp, Context::EXTENSION_INDEX), Immediate(0));
1343 __ j(not_equal, slow);
1344 // Load next context in chain.
1345 __ mov(temp, ContextOperand(temp, Context::PREVIOUS_INDEX));
1350 // All extension objects were empty and it is safe to use a global
1352 __ mov(LoadDescriptor::ReceiverRegister(), GlobalObjectOperand());
1353 __ mov(LoadDescriptor::NameRegister(), proxy->var()->name());
1354 if (FLAG_vector_ics) {
1355 __ mov(VectorLoadICDescriptor::SlotRegister(),
1356 Immediate(SmiFromSlot(proxy->VariableFeedbackSlot())));
1359 ContextualMode mode = (typeof_state == INSIDE_TYPEOF)
1367 MemOperand FullCodeGenerator::ContextSlotOperandCheckExtensions(Variable* var,
1369 DCHECK(var->IsContextSlot());
1370 Register context = esi;
1371 Register temp = ebx;
1373 for (Scope* s = scope(); s != var->scope(); s = s->outer_scope()) {
1374 if (s->num_heap_slots() > 0) {
1375 if (s->calls_sloppy_eval()) {
1376 // Check that extension is NULL.
1377 __ cmp(ContextOperand(context, Context::EXTENSION_INDEX),
1379 __ j(not_equal, slow);
1381 __ mov(temp, ContextOperand(context, Context::PREVIOUS_INDEX));
1382 // Walk the rest of the chain without clobbering esi.
1386 // Check that last extension is NULL.
1387 __ cmp(ContextOperand(context, Context::EXTENSION_INDEX), Immediate(0));
1388 __ j(not_equal, slow);
1390 // This function is used only for loads, not stores, so it's safe to
1391 // return an esi-based operand (the write barrier cannot be allowed to
1392 // destroy the esi register).
1393 return ContextOperand(context, var->index());
1397 void FullCodeGenerator::EmitDynamicLookupFastCase(VariableProxy* proxy,
1398 TypeofState typeof_state,
1401 // Generate fast-case code for variables that might be shadowed by
1402 // eval-introduced variables. Eval is used a lot without
1403 // introducing variables. In those cases, we do not want to
1404 // perform a runtime call for all variables in the scope
1405 // containing the eval.
1406 Variable* var = proxy->var();
1407 if (var->mode() == DYNAMIC_GLOBAL) {
1408 EmitLoadGlobalCheckExtensions(proxy, typeof_state, slow);
1410 } else if (var->mode() == DYNAMIC_LOCAL) {
1411 Variable* local = var->local_if_not_shadowed();
1412 __ mov(eax, ContextSlotOperandCheckExtensions(local, slow));
1413 if (local->mode() == LET || local->mode() == CONST ||
1414 local->mode() == CONST_LEGACY) {
1415 __ cmp(eax, isolate()->factory()->the_hole_value());
1416 __ j(not_equal, done);
1417 if (local->mode() == CONST_LEGACY) {
1418 __ mov(eax, isolate()->factory()->undefined_value());
1419 } else { // LET || CONST
1420 __ push(Immediate(var->name()));
1421 __ CallRuntime(Runtime::kThrowReferenceError, 1);
1429 void FullCodeGenerator::EmitVariableLoad(VariableProxy* proxy) {
1430 // Record position before possible IC call.
1431 SetSourcePosition(proxy->position());
1432 Variable* var = proxy->var();
1434 // Three cases: global variables, lookup variables, and all other types of
1436 switch (var->location()) {
1437 case Variable::UNALLOCATED: {
1438 Comment cmnt(masm_, "[ Global variable");
1439 __ mov(LoadDescriptor::ReceiverRegister(), GlobalObjectOperand());
1440 __ mov(LoadDescriptor::NameRegister(), var->name());
1441 if (FLAG_vector_ics) {
1442 __ mov(VectorLoadICDescriptor::SlotRegister(),
1443 Immediate(SmiFromSlot(proxy->VariableFeedbackSlot())));
1445 CallLoadIC(CONTEXTUAL);
1446 context()->Plug(eax);
1450 case Variable::PARAMETER:
1451 case Variable::LOCAL:
1452 case Variable::CONTEXT: {
1453 Comment cmnt(masm_, var->IsContextSlot() ? "[ Context variable"
1454 : "[ Stack variable");
1455 if (var->binding_needs_init()) {
1456 // var->scope() may be NULL when the proxy is located in eval code and
1457 // refers to a potential outside binding. Currently those bindings are
1458 // always looked up dynamically, i.e. in that case
1459 // var->location() == LOOKUP.
1461 DCHECK(var->scope() != NULL);
1463 // Check if the binding really needs an initialization check. The check
1464 // can be skipped in the following situation: we have a LET or CONST
1465 // binding in harmony mode, both the Variable and the VariableProxy have
1466 // the same declaration scope (i.e. they are both in global code, in the
1467 // same function or in the same eval code) and the VariableProxy is in
1468 // the source physically located after the initializer of the variable.
1470 // We cannot skip any initialization checks for CONST in non-harmony
1471 // mode because const variables may be declared but never initialized:
1472 // if (false) { const x; }; var y = x;
1474 // The condition on the declaration scopes is a conservative check for
1475 // nested functions that access a binding and are called before the
1476 // binding is initialized:
1477 // function() { f(); let x = 1; function f() { x = 2; } }
1479 bool skip_init_check;
1480 if (var->scope()->DeclarationScope() != scope()->DeclarationScope()) {
1481 skip_init_check = false;
1482 } else if (var->is_this()) {
1483 CHECK(info_->function() != nullptr &&
1484 (info_->function()->kind() & kSubclassConstructor) != 0);
1485 // TODO(dslomov): implement 'this' hole check elimination.
1486 skip_init_check = false;
1488 // Check that we always have valid source position.
1489 DCHECK(var->initializer_position() != RelocInfo::kNoPosition);
1490 DCHECK(proxy->position() != RelocInfo::kNoPosition);
1491 skip_init_check = var->mode() != CONST_LEGACY &&
1492 var->initializer_position() < proxy->position();
1495 if (!skip_init_check) {
1496 // Let and const need a read barrier.
1499 __ cmp(eax, isolate()->factory()->the_hole_value());
1500 __ j(not_equal, &done, Label::kNear);
1501 if (var->mode() == LET || var->mode() == CONST) {
1502 // Throw a reference error when using an uninitialized let/const
1503 // binding in harmony mode.
1504 __ push(Immediate(var->name()));
1505 __ CallRuntime(Runtime::kThrowReferenceError, 1);
1507 // Uninitalized const bindings outside of harmony mode are unholed.
1508 DCHECK(var->mode() == CONST_LEGACY);
1509 __ mov(eax, isolate()->factory()->undefined_value());
1512 context()->Plug(eax);
1516 context()->Plug(var);
1520 case Variable::LOOKUP: {
1521 Comment cmnt(masm_, "[ Lookup variable");
1523 // Generate code for loading from variables potentially shadowed
1524 // by eval-introduced variables.
1525 EmitDynamicLookupFastCase(proxy, NOT_INSIDE_TYPEOF, &slow, &done);
1527 __ push(esi); // Context.
1528 __ push(Immediate(var->name()));
1529 __ CallRuntime(Runtime::kLoadLookupSlot, 2);
1531 context()->Plug(eax);
1538 void FullCodeGenerator::VisitRegExpLiteral(RegExpLiteral* expr) {
1539 Comment cmnt(masm_, "[ RegExpLiteral");
1541 // Registers will be used as follows:
1542 // edi = JS function.
1543 // ecx = literals array.
1544 // ebx = regexp literal.
1545 // eax = regexp literal clone.
1546 __ mov(edi, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
1547 __ mov(ecx, FieldOperand(edi, JSFunction::kLiteralsOffset));
1548 int literal_offset =
1549 FixedArray::kHeaderSize + expr->literal_index() * kPointerSize;
1550 __ mov(ebx, FieldOperand(ecx, literal_offset));
1551 __ cmp(ebx, isolate()->factory()->undefined_value());
1552 __ j(not_equal, &materialized, Label::kNear);
1554 // Create regexp literal using runtime function
1555 // Result will be in eax.
1557 __ push(Immediate(Smi::FromInt(expr->literal_index())));
1558 __ push(Immediate(expr->pattern()));
1559 __ push(Immediate(expr->flags()));
1560 __ CallRuntime(Runtime::kMaterializeRegExpLiteral, 4);
1563 __ bind(&materialized);
1564 int size = JSRegExp::kSize + JSRegExp::kInObjectFieldCount * kPointerSize;
1565 Label allocated, runtime_allocate;
1566 __ Allocate(size, eax, ecx, edx, &runtime_allocate, TAG_OBJECT);
1569 __ bind(&runtime_allocate);
1571 __ push(Immediate(Smi::FromInt(size)));
1572 __ CallRuntime(Runtime::kAllocateInNewSpace, 1);
1575 __ bind(&allocated);
1576 // Copy the content into the newly allocated memory.
1577 // (Unroll copy loop once for better throughput).
1578 for (int i = 0; i < size - kPointerSize; i += 2 * kPointerSize) {
1579 __ mov(edx, FieldOperand(ebx, i));
1580 __ mov(ecx, FieldOperand(ebx, i + kPointerSize));
1581 __ mov(FieldOperand(eax, i), edx);
1582 __ mov(FieldOperand(eax, i + kPointerSize), ecx);
1584 if ((size % (2 * kPointerSize)) != 0) {
1585 __ mov(edx, FieldOperand(ebx, size - kPointerSize));
1586 __ mov(FieldOperand(eax, size - kPointerSize), edx);
1588 context()->Plug(eax);
1592 void FullCodeGenerator::EmitAccessor(Expression* expression) {
1593 if (expression == NULL) {
1594 __ push(Immediate(isolate()->factory()->null_value()));
1596 VisitForStackValue(expression);
1601 void FullCodeGenerator::VisitObjectLiteral(ObjectLiteral* expr) {
1602 Comment cmnt(masm_, "[ ObjectLiteral");
1604 expr->BuildConstantProperties(isolate());
1605 Handle<FixedArray> constant_properties = expr->constant_properties();
1606 int flags = expr->fast_elements()
1607 ? ObjectLiteral::kFastElements
1608 : ObjectLiteral::kNoFlags;
1609 flags |= expr->has_function()
1610 ? ObjectLiteral::kHasFunction
1611 : ObjectLiteral::kNoFlags;
1612 int properties_count = constant_properties->length() / 2;
1613 if (expr->may_store_doubles() || expr->depth() > 1 ||
1614 masm()->serializer_enabled() ||
1615 flags != ObjectLiteral::kFastElements ||
1616 properties_count > FastCloneShallowObjectStub::kMaximumClonedProperties) {
1617 __ mov(edi, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
1618 __ push(FieldOperand(edi, JSFunction::kLiteralsOffset));
1619 __ push(Immediate(Smi::FromInt(expr->literal_index())));
1620 __ push(Immediate(constant_properties));
1621 __ push(Immediate(Smi::FromInt(flags)));
1622 __ CallRuntime(Runtime::kCreateObjectLiteral, 4);
1624 __ mov(edi, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
1625 __ mov(eax, FieldOperand(edi, JSFunction::kLiteralsOffset));
1626 __ mov(ebx, Immediate(Smi::FromInt(expr->literal_index())));
1627 __ mov(ecx, Immediate(constant_properties));
1628 __ mov(edx, Immediate(Smi::FromInt(flags)));
1629 FastCloneShallowObjectStub stub(isolate(), properties_count);
1632 PrepareForBailoutForId(expr->CreateLiteralId(), TOS_REG);
1634 // If result_saved is true the result is on top of the stack. If
1635 // result_saved is false the result is in eax.
1636 bool result_saved = false;
1638 // Mark all computed expressions that are bound to a key that
1639 // is shadowed by a later occurrence of the same key. For the
1640 // marked expressions, no store code is emitted.
1641 expr->CalculateEmitStore(zone());
1643 AccessorTable accessor_table(zone());
1644 int property_index = 0;
1645 for (; property_index < expr->properties()->length(); property_index++) {
1646 ObjectLiteral::Property* property = expr->properties()->at(property_index);
1647 if (property->is_computed_name()) break;
1648 if (property->IsCompileTimeValue()) continue;
1650 Literal* key = property->key()->AsLiteral();
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 if (NeedsHomeObject(value)) {
1675 __ mov(StoreDescriptor::ReceiverRegister(), eax);
1676 __ mov(StoreDescriptor::NameRegister(),
1677 Immediate(isolate()->factory()->home_object_symbol()));
1678 __ mov(StoreDescriptor::ValueRegister(), Operand(esp, 0));
1682 VisitForEffect(value);
1686 __ push(Operand(esp, 0)); // Duplicate receiver.
1687 VisitForStackValue(key);
1688 VisitForStackValue(value);
1689 if (property->emit_store()) {
1690 EmitSetHomeObjectIfNeeded(value, 2);
1691 __ push(Immediate(Smi::FromInt(SLOPPY))); // Language mode
1692 __ CallRuntime(Runtime::kSetProperty, 4);
1697 case ObjectLiteral::Property::PROTOTYPE:
1698 __ push(Operand(esp, 0)); // Duplicate receiver.
1699 VisitForStackValue(value);
1700 DCHECK(property->emit_store());
1701 __ CallRuntime(Runtime::kInternalSetPrototype, 2);
1703 case ObjectLiteral::Property::GETTER:
1704 if (property->emit_store()) {
1705 accessor_table.lookup(key)->second->getter = value;
1708 case ObjectLiteral::Property::SETTER:
1709 if (property->emit_store()) {
1710 accessor_table.lookup(key)->second->setter = value;
1716 // Emit code to define accessors, using only a single call to the runtime for
1717 // each pair of corresponding getters and setters.
1718 for (AccessorTable::Iterator it = accessor_table.begin();
1719 it != accessor_table.end();
1721 __ push(Operand(esp, 0)); // Duplicate receiver.
1722 VisitForStackValue(it->first);
1723 EmitAccessor(it->second->getter);
1724 EmitSetHomeObjectIfNeeded(it->second->getter, 2);
1725 EmitAccessor(it->second->setter);
1726 EmitSetHomeObjectIfNeeded(it->second->setter, 3);
1727 __ push(Immediate(Smi::FromInt(NONE)));
1728 __ CallRuntime(Runtime::kDefineAccessorPropertyUnchecked, 5);
1731 // Object literals have two parts. The "static" part on the left contains no
1732 // computed property names, and so we can compute its map ahead of time; see
1733 // runtime.cc::CreateObjectLiteralBoilerplate. The second "dynamic" part
1734 // starts with the first computed property name, and continues with all
1735 // properties to its right. All the code from above initializes the static
1736 // component of the object literal, and arranges for the map of the result to
1737 // reflect the static order in which the keys appear. For the dynamic
1738 // properties, we compile them into a series of "SetOwnProperty" runtime
1739 // calls. This will preserve insertion order.
1740 for (; property_index < expr->properties()->length(); property_index++) {
1741 ObjectLiteral::Property* property = expr->properties()->at(property_index);
1743 Expression* value = property->value();
1744 if (!result_saved) {
1745 __ push(eax); // Save result on the stack
1746 result_saved = true;
1749 __ push(Operand(esp, 0)); // Duplicate receiver.
1751 if (property->kind() == ObjectLiteral::Property::PROTOTYPE) {
1752 DCHECK(!property->is_computed_name());
1753 VisitForStackValue(value);
1754 DCHECK(property->emit_store());
1755 __ CallRuntime(Runtime::kInternalSetPrototype, 2);
1757 EmitPropertyKey(property, expr->GetIdForProperty(property_index));
1758 VisitForStackValue(value);
1759 EmitSetHomeObjectIfNeeded(value, 2);
1761 switch (property->kind()) {
1762 case ObjectLiteral::Property::CONSTANT:
1763 case ObjectLiteral::Property::MATERIALIZED_LITERAL:
1764 case ObjectLiteral::Property::COMPUTED:
1765 if (property->emit_store()) {
1766 __ push(Immediate(Smi::FromInt(NONE)));
1767 __ CallRuntime(Runtime::kDefineDataPropertyUnchecked, 4);
1773 case ObjectLiteral::Property::PROTOTYPE:
1777 case ObjectLiteral::Property::GETTER:
1778 __ push(Immediate(Smi::FromInt(NONE)));
1779 __ CallRuntime(Runtime::kDefineGetterPropertyUnchecked, 4);
1782 case ObjectLiteral::Property::SETTER:
1783 __ push(Immediate(Smi::FromInt(NONE)));
1784 __ CallRuntime(Runtime::kDefineSetterPropertyUnchecked, 4);
1790 if (expr->has_function()) {
1791 DCHECK(result_saved);
1792 __ push(Operand(esp, 0));
1793 __ CallRuntime(Runtime::kToFastProperties, 1);
1797 context()->PlugTOS();
1799 context()->Plug(eax);
1804 void FullCodeGenerator::VisitArrayLiteral(ArrayLiteral* expr) {
1805 Comment cmnt(masm_, "[ ArrayLiteral");
1807 expr->BuildConstantElements(isolate());
1808 int flags = expr->depth() == 1
1809 ? ArrayLiteral::kShallowElements
1810 : ArrayLiteral::kNoFlags;
1812 ZoneList<Expression*>* subexprs = expr->values();
1813 int length = subexprs->length();
1814 Handle<FixedArray> constant_elements = expr->constant_elements();
1815 DCHECK_EQ(2, constant_elements->length());
1816 ElementsKind constant_elements_kind =
1817 static_cast<ElementsKind>(Smi::cast(constant_elements->get(0))->value());
1818 bool has_constant_fast_elements =
1819 IsFastObjectElementsKind(constant_elements_kind);
1820 Handle<FixedArrayBase> constant_elements_values(
1821 FixedArrayBase::cast(constant_elements->get(1)));
1823 AllocationSiteMode allocation_site_mode = TRACK_ALLOCATION_SITE;
1824 if (has_constant_fast_elements && !FLAG_allocation_site_pretenuring) {
1825 // If the only customer of allocation sites is transitioning, then
1826 // we can turn it off if we don't have anywhere else to transition to.
1827 allocation_site_mode = DONT_TRACK_ALLOCATION_SITE;
1830 if (expr->depth() > 1 || length > JSObject::kInitialMaxFastElementArray) {
1831 __ mov(ebx, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
1832 __ push(FieldOperand(ebx, JSFunction::kLiteralsOffset));
1833 __ push(Immediate(Smi::FromInt(expr->literal_index())));
1834 __ push(Immediate(constant_elements));
1835 __ push(Immediate(Smi::FromInt(flags)));
1836 __ CallRuntime(Runtime::kCreateArrayLiteral, 4);
1838 __ mov(ebx, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
1839 __ mov(eax, FieldOperand(ebx, JSFunction::kLiteralsOffset));
1840 __ mov(ebx, Immediate(Smi::FromInt(expr->literal_index())));
1841 __ mov(ecx, Immediate(constant_elements));
1842 FastCloneShallowArrayStub stub(isolate(), allocation_site_mode);
1845 PrepareForBailoutForId(expr->CreateLiteralId(), TOS_REG);
1847 bool result_saved = false; // Is the result saved to the stack?
1849 // Emit code to evaluate all the non-constant subexpressions and to store
1850 // them into the newly cloned array.
1851 for (int i = 0; i < length; i++) {
1852 Expression* subexpr = subexprs->at(i);
1853 // If the subexpression is a literal or a simple materialized literal it
1854 // is already set in the cloned array.
1855 if (CompileTimeValue::IsCompileTimeValue(subexpr)) continue;
1857 if (!result_saved) {
1858 __ push(eax); // array literal.
1859 __ push(Immediate(Smi::FromInt(expr->literal_index())));
1860 result_saved = true;
1862 VisitForAccumulatorValue(subexpr);
1864 if (IsFastObjectElementsKind(constant_elements_kind)) {
1865 // Fast-case array literal with ElementsKind of FAST_*_ELEMENTS, they
1866 // cannot transition and don't need to call the runtime stub.
1867 int offset = FixedArray::kHeaderSize + (i * kPointerSize);
1868 __ mov(ebx, Operand(esp, kPointerSize)); // Copy of array literal.
1869 __ mov(ebx, FieldOperand(ebx, JSObject::kElementsOffset));
1870 // Store the subexpression value in the array's elements.
1871 __ mov(FieldOperand(ebx, offset), result_register());
1872 // Update the write barrier for the array store.
1873 __ RecordWriteField(ebx, offset, result_register(), ecx, kDontSaveFPRegs,
1874 EMIT_REMEMBERED_SET, INLINE_SMI_CHECK);
1876 // Store the subexpression value in the array's elements.
1877 __ mov(ecx, Immediate(Smi::FromInt(i)));
1878 StoreArrayLiteralElementStub stub(isolate());
1882 PrepareForBailoutForId(expr->GetIdForElement(i), NO_REGISTERS);
1886 __ add(esp, Immediate(kPointerSize)); // literal index
1887 context()->PlugTOS();
1889 context()->Plug(eax);
1894 void FullCodeGenerator::VisitAssignment(Assignment* expr) {
1895 DCHECK(expr->target()->IsValidReferenceExpression());
1897 Comment cmnt(masm_, "[ Assignment");
1899 Property* property = expr->target()->AsProperty();
1900 LhsKind assign_type = GetAssignType(property);
1902 // Evaluate LHS expression.
1903 switch (assign_type) {
1905 // Nothing to do here.
1907 case NAMED_SUPER_PROPERTY:
1908 VisitForStackValue(property->obj()->AsSuperReference()->this_var());
1909 EmitLoadHomeObject(property->obj()->AsSuperReference());
1910 __ push(result_register());
1911 if (expr->is_compound()) {
1912 __ push(MemOperand(esp, kPointerSize));
1913 __ push(result_register());
1916 case NAMED_PROPERTY:
1917 if (expr->is_compound()) {
1918 // We need the receiver both on the stack and in the register.
1919 VisitForStackValue(property->obj());
1920 __ mov(LoadDescriptor::ReceiverRegister(), Operand(esp, 0));
1922 VisitForStackValue(property->obj());
1925 case KEYED_SUPER_PROPERTY:
1926 VisitForStackValue(property->obj()->AsSuperReference()->this_var());
1927 EmitLoadHomeObject(property->obj()->AsSuperReference());
1928 __ Push(result_register());
1929 VisitForAccumulatorValue(property->key());
1930 __ Push(result_register());
1931 if (expr->is_compound()) {
1932 __ push(MemOperand(esp, 2 * kPointerSize));
1933 __ push(MemOperand(esp, 2 * kPointerSize));
1934 __ push(result_register());
1937 case KEYED_PROPERTY: {
1938 if (expr->is_compound()) {
1939 VisitForStackValue(property->obj());
1940 VisitForStackValue(property->key());
1941 __ mov(LoadDescriptor::ReceiverRegister(), Operand(esp, kPointerSize));
1942 __ mov(LoadDescriptor::NameRegister(), Operand(esp, 0));
1944 VisitForStackValue(property->obj());
1945 VisitForStackValue(property->key());
1951 // For compound assignments we need another deoptimization point after the
1952 // variable/property load.
1953 if (expr->is_compound()) {
1954 AccumulatorValueContext result_context(this);
1955 { AccumulatorValueContext left_operand_context(this);
1956 switch (assign_type) {
1958 EmitVariableLoad(expr->target()->AsVariableProxy());
1959 PrepareForBailout(expr->target(), TOS_REG);
1961 case NAMED_SUPER_PROPERTY:
1962 EmitNamedSuperPropertyLoad(property);
1963 PrepareForBailoutForId(property->LoadId(), TOS_REG);
1965 case NAMED_PROPERTY:
1966 EmitNamedPropertyLoad(property);
1967 PrepareForBailoutForId(property->LoadId(), TOS_REG);
1969 case KEYED_SUPER_PROPERTY:
1970 EmitKeyedSuperPropertyLoad(property);
1971 PrepareForBailoutForId(property->LoadId(), TOS_REG);
1973 case KEYED_PROPERTY:
1974 EmitKeyedPropertyLoad(property);
1975 PrepareForBailoutForId(property->LoadId(), TOS_REG);
1980 Token::Value op = expr->binary_op();
1981 __ push(eax); // Left operand goes on the stack.
1982 VisitForAccumulatorValue(expr->value());
1984 SetSourcePosition(expr->position() + 1);
1985 if (ShouldInlineSmiCase(op)) {
1986 EmitInlineSmiBinaryOp(expr->binary_operation(),
1991 EmitBinaryOp(expr->binary_operation(), op);
1994 // Deoptimization point in case the binary operation may have side effects.
1995 PrepareForBailout(expr->binary_operation(), TOS_REG);
1997 VisitForAccumulatorValue(expr->value());
2000 // Record source position before possible IC call.
2001 SetSourcePosition(expr->position());
2004 switch (assign_type) {
2006 EmitVariableAssignment(expr->target()->AsVariableProxy()->var(),
2008 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
2009 context()->Plug(eax);
2011 case NAMED_PROPERTY:
2012 EmitNamedPropertyAssignment(expr);
2014 case NAMED_SUPER_PROPERTY:
2015 EmitNamedSuperPropertyStore(property);
2016 context()->Plug(result_register());
2018 case KEYED_SUPER_PROPERTY:
2019 EmitKeyedSuperPropertyStore(property);
2020 context()->Plug(result_register());
2022 case KEYED_PROPERTY:
2023 EmitKeyedPropertyAssignment(expr);
2029 void FullCodeGenerator::VisitYield(Yield* expr) {
2030 Comment cmnt(masm_, "[ Yield");
2031 // Evaluate yielded value first; the initial iterator definition depends on
2032 // this. It stays on the stack while we update the iterator.
2033 VisitForStackValue(expr->expression());
2035 switch (expr->yield_kind()) {
2036 case Yield::kSuspend:
2037 // Pop value from top-of-stack slot; box result into result register.
2038 EmitCreateIteratorResult(false);
2039 __ push(result_register());
2041 case Yield::kInitial: {
2042 Label suspend, continuation, post_runtime, resume;
2046 __ bind(&continuation);
2050 VisitForAccumulatorValue(expr->generator_object());
2051 DCHECK(continuation.pos() > 0 && Smi::IsValid(continuation.pos()));
2052 __ mov(FieldOperand(eax, JSGeneratorObject::kContinuationOffset),
2053 Immediate(Smi::FromInt(continuation.pos())));
2054 __ mov(FieldOperand(eax, JSGeneratorObject::kContextOffset), esi);
2056 __ RecordWriteField(eax, JSGeneratorObject::kContextOffset, ecx, edx,
2058 __ lea(ebx, Operand(ebp, StandardFrameConstants::kExpressionsOffset));
2060 __ j(equal, &post_runtime);
2061 __ push(eax); // generator object
2062 __ CallRuntime(Runtime::kSuspendJSGeneratorObject, 1);
2063 __ mov(context_register(),
2064 Operand(ebp, StandardFrameConstants::kContextOffset));
2065 __ bind(&post_runtime);
2066 __ pop(result_register());
2067 EmitReturnSequence();
2070 context()->Plug(result_register());
2074 case Yield::kFinal: {
2075 VisitForAccumulatorValue(expr->generator_object());
2076 __ mov(FieldOperand(result_register(),
2077 JSGeneratorObject::kContinuationOffset),
2078 Immediate(Smi::FromInt(JSGeneratorObject::kGeneratorClosed)));
2079 // Pop value from top-of-stack slot, box result into result register.
2080 EmitCreateIteratorResult(true);
2081 EmitUnwindBeforeReturn();
2082 EmitReturnSequence();
2086 case Yield::kDelegating: {
2087 VisitForStackValue(expr->generator_object());
2089 // Initial stack layout is as follows:
2090 // [sp + 1 * kPointerSize] iter
2091 // [sp + 0 * kPointerSize] g
2093 Label l_catch, l_try, l_suspend, l_continuation, l_resume;
2094 Label l_next, l_call, l_loop;
2095 Register load_receiver = LoadDescriptor::ReceiverRegister();
2096 Register load_name = LoadDescriptor::NameRegister();
2098 // Initial send value is undefined.
2099 __ mov(eax, isolate()->factory()->undefined_value());
2102 // catch (e) { receiver = iter; f = 'throw'; arg = e; goto l_call; }
2104 handler_table()->set(expr->index(), Smi::FromInt(l_catch.pos()));
2105 __ mov(load_name, isolate()->factory()->throw_string()); // "throw"
2106 __ push(load_name); // "throw"
2107 __ push(Operand(esp, 2 * kPointerSize)); // iter
2108 __ push(eax); // exception
2111 // try { received = %yield result }
2112 // Shuffle the received result above a try handler and yield it without
2115 __ pop(eax); // result
2116 __ PushTryHandler(StackHandler::CATCH, expr->index());
2117 const int handler_size = StackHandlerConstants::kSize;
2118 __ push(eax); // result
2120 __ bind(&l_continuation);
2122 __ bind(&l_suspend);
2123 const int generator_object_depth = kPointerSize + handler_size;
2124 __ mov(eax, Operand(esp, generator_object_depth));
2126 DCHECK(l_continuation.pos() > 0 && Smi::IsValid(l_continuation.pos()));
2127 __ mov(FieldOperand(eax, JSGeneratorObject::kContinuationOffset),
2128 Immediate(Smi::FromInt(l_continuation.pos())));
2129 __ mov(FieldOperand(eax, JSGeneratorObject::kContextOffset), esi);
2131 __ RecordWriteField(eax, JSGeneratorObject::kContextOffset, ecx, edx,
2133 __ CallRuntime(Runtime::kSuspendJSGeneratorObject, 1);
2134 __ mov(context_register(),
2135 Operand(ebp, StandardFrameConstants::kContextOffset));
2136 __ pop(eax); // result
2137 EmitReturnSequence();
2138 __ bind(&l_resume); // received in eax
2141 // receiver = iter; f = iter.next; arg = received;
2144 __ mov(load_name, isolate()->factory()->next_string());
2145 __ push(load_name); // "next"
2146 __ push(Operand(esp, 2 * kPointerSize)); // iter
2147 __ push(eax); // received
2149 // result = receiver[f](arg);
2151 __ mov(load_receiver, Operand(esp, kPointerSize));
2152 if (FLAG_vector_ics) {
2153 __ mov(VectorLoadICDescriptor::SlotRegister(),
2154 Immediate(SmiFromSlot(expr->KeyedLoadFeedbackSlot())));
2156 Handle<Code> ic = CodeFactory::KeyedLoadIC(isolate()).code();
2157 CallIC(ic, TypeFeedbackId::None());
2159 __ mov(Operand(esp, 2 * kPointerSize), edi);
2160 CallFunctionStub stub(isolate(), 1, CALL_AS_METHOD);
2163 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
2164 __ Drop(1); // The function is still on the stack; drop it.
2166 // if (!result.done) goto l_try;
2168 __ push(eax); // save result
2169 __ Move(load_receiver, eax); // result
2171 isolate()->factory()->done_string()); // "done"
2172 if (FLAG_vector_ics) {
2173 __ mov(VectorLoadICDescriptor::SlotRegister(),
2174 Immediate(SmiFromSlot(expr->DoneFeedbackSlot())));
2176 CallLoadIC(NOT_CONTEXTUAL); // result.done in eax
2177 Handle<Code> bool_ic = ToBooleanStub::GetUninitialized(isolate());
2183 __ pop(load_receiver); // result
2185 isolate()->factory()->value_string()); // "value"
2186 if (FLAG_vector_ics) {
2187 __ mov(VectorLoadICDescriptor::SlotRegister(),
2188 Immediate(SmiFromSlot(expr->ValueFeedbackSlot())));
2190 CallLoadIC(NOT_CONTEXTUAL); // result.value in eax
2191 context()->DropAndPlug(2, eax); // drop iter and g
2198 void FullCodeGenerator::EmitGeneratorResume(Expression *generator,
2200 JSGeneratorObject::ResumeMode resume_mode) {
2201 // The value stays in eax, and is ultimately read by the resumed generator, as
2202 // if CallRuntime(Runtime::kSuspendJSGeneratorObject) returned it. Or it
2203 // is read to throw the value when the resumed generator is already closed.
2204 // ebx will hold the generator object until the activation has been resumed.
2205 VisitForStackValue(generator);
2206 VisitForAccumulatorValue(value);
2209 // Load suspended function and context.
2210 __ mov(esi, FieldOperand(ebx, JSGeneratorObject::kContextOffset));
2211 __ mov(edi, FieldOperand(ebx, JSGeneratorObject::kFunctionOffset));
2214 __ push(FieldOperand(ebx, JSGeneratorObject::kReceiverOffset));
2216 // Push holes for arguments to generator function.
2217 __ mov(edx, FieldOperand(edi, JSFunction::kSharedFunctionInfoOffset));
2219 FieldOperand(edx, SharedFunctionInfo::kFormalParameterCountOffset));
2220 __ mov(ecx, isolate()->factory()->the_hole_value());
2221 Label push_argument_holes, push_frame;
2222 __ bind(&push_argument_holes);
2223 __ sub(edx, Immediate(Smi::FromInt(1)));
2224 __ j(carry, &push_frame);
2226 __ jmp(&push_argument_holes);
2228 // Enter a new JavaScript frame, and initialize its slots as they were when
2229 // the generator was suspended.
2230 Label resume_frame, done;
2231 __ bind(&push_frame);
2232 __ call(&resume_frame);
2234 __ bind(&resume_frame);
2235 __ push(ebp); // Caller's frame pointer.
2237 __ push(esi); // Callee's context.
2238 __ push(edi); // Callee's JS Function.
2240 // Load the operand stack size.
2241 __ mov(edx, FieldOperand(ebx, JSGeneratorObject::kOperandStackOffset));
2242 __ mov(edx, FieldOperand(edx, FixedArray::kLengthOffset));
2245 // If we are sending a value and there is no operand stack, we can jump back
2247 if (resume_mode == JSGeneratorObject::NEXT) {
2249 __ cmp(edx, Immediate(0));
2250 __ j(not_zero, &slow_resume);
2251 __ mov(edx, FieldOperand(edi, JSFunction::kCodeEntryOffset));
2252 __ mov(ecx, FieldOperand(ebx, JSGeneratorObject::kContinuationOffset));
2255 __ mov(FieldOperand(ebx, JSGeneratorObject::kContinuationOffset),
2256 Immediate(Smi::FromInt(JSGeneratorObject::kGeneratorExecuting)));
2258 __ bind(&slow_resume);
2261 // Otherwise, we push holes for the operand stack and call the runtime to fix
2262 // up the stack and the handlers.
2263 Label push_operand_holes, call_resume;
2264 __ bind(&push_operand_holes);
2265 __ sub(edx, Immediate(1));
2266 __ j(carry, &call_resume);
2268 __ jmp(&push_operand_holes);
2269 __ bind(&call_resume);
2271 __ push(result_register());
2272 __ Push(Smi::FromInt(resume_mode));
2273 __ CallRuntime(Runtime::kResumeJSGeneratorObject, 3);
2274 // Not reached: the runtime call returns elsewhere.
2275 __ Abort(kGeneratorFailedToResume);
2278 context()->Plug(result_register());
2282 void FullCodeGenerator::EmitCreateIteratorResult(bool done) {
2286 const int instance_size = 5 * kPointerSize;
2287 DCHECK_EQ(isolate()->native_context()->iterator_result_map()->instance_size(),
2290 __ Allocate(instance_size, eax, ecx, edx, &gc_required, TAG_OBJECT);
2293 __ bind(&gc_required);
2294 __ Push(Smi::FromInt(instance_size));
2295 __ CallRuntime(Runtime::kAllocateInNewSpace, 1);
2296 __ mov(context_register(),
2297 Operand(ebp, StandardFrameConstants::kContextOffset));
2299 __ bind(&allocated);
2300 __ mov(ebx, Operand(esi, Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX)));
2301 __ mov(ebx, FieldOperand(ebx, GlobalObject::kNativeContextOffset));
2302 __ mov(ebx, ContextOperand(ebx, Context::ITERATOR_RESULT_MAP_INDEX));
2304 __ mov(edx, isolate()->factory()->ToBoolean(done));
2305 __ mov(FieldOperand(eax, HeapObject::kMapOffset), ebx);
2306 __ mov(FieldOperand(eax, JSObject::kPropertiesOffset),
2307 isolate()->factory()->empty_fixed_array());
2308 __ mov(FieldOperand(eax, JSObject::kElementsOffset),
2309 isolate()->factory()->empty_fixed_array());
2310 __ mov(FieldOperand(eax, JSGeneratorObject::kResultValuePropertyOffset), ecx);
2311 __ mov(FieldOperand(eax, JSGeneratorObject::kResultDonePropertyOffset), edx);
2313 // Only the value field needs a write barrier, as the other values are in the
2315 __ RecordWriteField(eax, JSGeneratorObject::kResultValuePropertyOffset, ecx,
2316 edx, kDontSaveFPRegs);
2320 void FullCodeGenerator::EmitNamedPropertyLoad(Property* prop) {
2321 SetSourcePosition(prop->position());
2322 Literal* key = prop->key()->AsLiteral();
2323 DCHECK(!key->value()->IsSmi());
2324 DCHECK(!prop->IsSuperAccess());
2326 __ mov(LoadDescriptor::NameRegister(), Immediate(key->value()));
2327 if (FLAG_vector_ics) {
2328 __ mov(VectorLoadICDescriptor::SlotRegister(),
2329 Immediate(SmiFromSlot(prop->PropertyFeedbackSlot())));
2330 CallLoadIC(NOT_CONTEXTUAL);
2332 CallLoadIC(NOT_CONTEXTUAL, prop->PropertyFeedbackId());
2337 void FullCodeGenerator::EmitNamedSuperPropertyLoad(Property* prop) {
2338 // Stack: receiver, home_object.
2339 SetSourcePosition(prop->position());
2340 Literal* key = prop->key()->AsLiteral();
2341 DCHECK(!key->value()->IsSmi());
2342 DCHECK(prop->IsSuperAccess());
2344 __ push(Immediate(key->value()));
2345 __ CallRuntime(Runtime::kLoadFromSuper, 3);
2349 void FullCodeGenerator::EmitKeyedPropertyLoad(Property* prop) {
2350 SetSourcePosition(prop->position());
2351 Handle<Code> ic = CodeFactory::KeyedLoadIC(isolate()).code();
2352 if (FLAG_vector_ics) {
2353 __ mov(VectorLoadICDescriptor::SlotRegister(),
2354 Immediate(SmiFromSlot(prop->PropertyFeedbackSlot())));
2357 CallIC(ic, prop->PropertyFeedbackId());
2362 void FullCodeGenerator::EmitKeyedSuperPropertyLoad(Property* prop) {
2363 // Stack: receiver, home_object, key.
2364 SetSourcePosition(prop->position());
2366 __ CallRuntime(Runtime::kLoadKeyedFromSuper, 3);
2370 void FullCodeGenerator::EmitInlineSmiBinaryOp(BinaryOperation* expr,
2373 Expression* right) {
2374 // Do combined smi check of the operands. Left operand is on the
2375 // stack. Right operand is in eax.
2376 Label smi_case, done, stub_call;
2380 JumpPatchSite patch_site(masm_);
2381 patch_site.EmitJumpIfSmi(eax, &smi_case, Label::kNear);
2383 __ bind(&stub_call);
2385 Handle<Code> code = CodeFactory::BinaryOpIC(isolate(), op).code();
2386 CallIC(code, expr->BinaryOperationFeedbackId());
2387 patch_site.EmitPatchInfo();
2388 __ jmp(&done, Label::kNear);
2392 __ mov(eax, edx); // Copy left operand in case of a stub call.
2397 __ sar_cl(eax); // No checks of result necessary
2398 __ and_(eax, Immediate(~kSmiTagMask));
2405 // Check that the *signed* result fits in a smi.
2406 __ cmp(eax, 0xc0000000);
2407 __ j(positive, &result_ok);
2410 __ bind(&result_ok);
2419 __ test(eax, Immediate(0xc0000000));
2420 __ j(zero, &result_ok);
2423 __ bind(&result_ok);
2429 __ j(overflow, &stub_call);
2433 __ j(overflow, &stub_call);
2438 __ j(overflow, &stub_call);
2440 __ j(not_zero, &done, Label::kNear);
2443 __ j(negative, &stub_call);
2449 case Token::BIT_AND:
2452 case Token::BIT_XOR:
2460 context()->Plug(eax);
2464 void FullCodeGenerator::EmitClassDefineProperties(ClassLiteral* lit) {
2465 // Constructor is in eax.
2466 DCHECK(lit != NULL);
2469 // No access check is needed here since the constructor is created by the
2471 Register scratch = ebx;
2472 __ mov(scratch, FieldOperand(eax, JSFunction::kPrototypeOrInitialMapOffset));
2475 for (int i = 0; i < lit->properties()->length(); i++) {
2476 ObjectLiteral::Property* property = lit->properties()->at(i);
2477 Expression* value = property->value();
2479 if (property->is_static()) {
2480 __ push(Operand(esp, kPointerSize)); // constructor
2482 __ push(Operand(esp, 0)); // prototype
2484 EmitPropertyKey(property, lit->GetIdForProperty(i));
2485 VisitForStackValue(value);
2486 EmitSetHomeObjectIfNeeded(value, 2);
2488 switch (property->kind()) {
2489 case ObjectLiteral::Property::CONSTANT:
2490 case ObjectLiteral::Property::MATERIALIZED_LITERAL:
2491 case ObjectLiteral::Property::PROTOTYPE:
2493 case ObjectLiteral::Property::COMPUTED:
2494 __ CallRuntime(Runtime::kDefineClassMethod, 3);
2497 case ObjectLiteral::Property::GETTER:
2498 __ push(Immediate(Smi::FromInt(DONT_ENUM)));
2499 __ CallRuntime(Runtime::kDefineGetterPropertyUnchecked, 4);
2502 case ObjectLiteral::Property::SETTER:
2503 __ push(Immediate(Smi::FromInt(DONT_ENUM)));
2504 __ CallRuntime(Runtime::kDefineSetterPropertyUnchecked, 4);
2510 __ CallRuntime(Runtime::kToFastProperties, 1);
2513 __ CallRuntime(Runtime::kToFastProperties, 1);
2517 void FullCodeGenerator::EmitBinaryOp(BinaryOperation* expr, Token::Value op) {
2519 Handle<Code> code = CodeFactory::BinaryOpIC(isolate(), op).code();
2520 JumpPatchSite patch_site(masm_); // unbound, signals no inlined smi code.
2521 CallIC(code, expr->BinaryOperationFeedbackId());
2522 patch_site.EmitPatchInfo();
2523 context()->Plug(eax);
2527 void FullCodeGenerator::EmitAssignment(Expression* expr) {
2528 DCHECK(expr->IsValidReferenceExpression());
2530 Property* prop = expr->AsProperty();
2531 LhsKind assign_type = GetAssignType(prop);
2533 switch (assign_type) {
2535 Variable* var = expr->AsVariableProxy()->var();
2536 EffectContext context(this);
2537 EmitVariableAssignment(var, Token::ASSIGN);
2540 case NAMED_PROPERTY: {
2541 __ push(eax); // Preserve value.
2542 VisitForAccumulatorValue(prop->obj());
2543 __ Move(StoreDescriptor::ReceiverRegister(), eax);
2544 __ pop(StoreDescriptor::ValueRegister()); // Restore value.
2545 __ mov(StoreDescriptor::NameRegister(),
2546 prop->key()->AsLiteral()->value());
2550 case NAMED_SUPER_PROPERTY: {
2552 VisitForStackValue(prop->obj()->AsSuperReference()->this_var());
2553 EmitLoadHomeObject(prop->obj()->AsSuperReference());
2554 // stack: value, this; eax: home_object
2555 Register scratch = ecx;
2556 Register scratch2 = edx;
2557 __ mov(scratch, result_register()); // home_object
2558 __ mov(eax, MemOperand(esp, kPointerSize)); // value
2559 __ mov(scratch2, MemOperand(esp, 0)); // this
2560 __ mov(MemOperand(esp, kPointerSize), scratch2); // this
2561 __ mov(MemOperand(esp, 0), scratch); // home_object
2562 // stack: this, home_object. eax: value
2563 EmitNamedSuperPropertyStore(prop);
2566 case KEYED_SUPER_PROPERTY: {
2568 VisitForStackValue(prop->obj()->AsSuperReference()->this_var());
2569 EmitLoadHomeObject(prop->obj()->AsSuperReference());
2570 __ push(result_register());
2571 VisitForAccumulatorValue(prop->key());
2572 Register scratch = ecx;
2573 Register scratch2 = edx;
2574 __ mov(scratch2, MemOperand(esp, 2 * kPointerSize)); // value
2575 // stack: value, this, home_object; eax: key, edx: value
2576 __ mov(scratch, MemOperand(esp, kPointerSize)); // this
2577 __ mov(MemOperand(esp, 2 * kPointerSize), scratch);
2578 __ mov(scratch, MemOperand(esp, 0)); // home_object
2579 __ mov(MemOperand(esp, kPointerSize), scratch);
2580 __ mov(MemOperand(esp, 0), eax);
2581 __ mov(eax, scratch2);
2582 // stack: this, home_object, key; eax: value.
2583 EmitKeyedSuperPropertyStore(prop);
2586 case KEYED_PROPERTY: {
2587 __ push(eax); // Preserve value.
2588 VisitForStackValue(prop->obj());
2589 VisitForAccumulatorValue(prop->key());
2590 __ Move(StoreDescriptor::NameRegister(), eax);
2591 __ pop(StoreDescriptor::ReceiverRegister()); // Receiver.
2592 __ pop(StoreDescriptor::ValueRegister()); // Restore value.
2594 CodeFactory::KeyedStoreIC(isolate(), language_mode()).code();
2599 context()->Plug(eax);
2603 void FullCodeGenerator::EmitStoreToStackLocalOrContextSlot(
2604 Variable* var, MemOperand location) {
2605 __ mov(location, eax);
2606 if (var->IsContextSlot()) {
2608 int offset = Context::SlotOffset(var->index());
2609 __ RecordWriteContextSlot(ecx, offset, edx, ebx, kDontSaveFPRegs);
2614 void FullCodeGenerator::EmitVariableAssignment(Variable* var,
2616 if (var->IsUnallocated()) {
2617 // Global var, const, or let.
2618 __ mov(StoreDescriptor::NameRegister(), var->name());
2619 __ mov(StoreDescriptor::ReceiverRegister(), GlobalObjectOperand());
2622 } else if (op == Token::INIT_CONST_LEGACY) {
2623 // Const initializers need a write barrier.
2624 DCHECK(!var->IsParameter()); // No const parameters.
2625 if (var->IsLookupSlot()) {
2628 __ push(Immediate(var->name()));
2629 __ CallRuntime(Runtime::kInitializeLegacyConstLookupSlot, 3);
2631 DCHECK(var->IsStackLocal() || var->IsContextSlot());
2633 MemOperand location = VarOperand(var, ecx);
2634 __ mov(edx, location);
2635 __ cmp(edx, isolate()->factory()->the_hole_value());
2636 __ j(not_equal, &skip, Label::kNear);
2637 EmitStoreToStackLocalOrContextSlot(var, location);
2641 } else if (var->mode() == LET && op != Token::INIT_LET) {
2642 // Non-initializing assignment to let variable needs a write barrier.
2643 DCHECK(!var->IsLookupSlot());
2644 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
2646 MemOperand location = VarOperand(var, ecx);
2647 __ mov(edx, location);
2648 __ cmp(edx, isolate()->factory()->the_hole_value());
2649 __ j(not_equal, &assign, Label::kNear);
2650 __ push(Immediate(var->name()));
2651 __ CallRuntime(Runtime::kThrowReferenceError, 1);
2653 EmitStoreToStackLocalOrContextSlot(var, location);
2654 } else if (!var->is_const_mode() || op == Token::INIT_CONST) {
2655 if (var->IsLookupSlot()) {
2656 // Assignment to var.
2657 __ push(eax); // Value.
2658 __ push(esi); // Context.
2659 __ push(Immediate(var->name()));
2660 __ push(Immediate(Smi::FromInt(language_mode())));
2661 __ CallRuntime(Runtime::kStoreLookupSlot, 4);
2663 // Assignment to var or initializing assignment to let/const in harmony
2665 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
2666 MemOperand location = VarOperand(var, ecx);
2667 if (generate_debug_code_ && op == Token::INIT_LET) {
2668 // Check for an uninitialized let binding.
2669 __ mov(edx, location);
2670 __ cmp(edx, isolate()->factory()->the_hole_value());
2671 __ Check(equal, kLetBindingReInitialization);
2673 EmitStoreToStackLocalOrContextSlot(var, location);
2675 } else if (IsSignallingAssignmentToConst(var, op, language_mode())) {
2676 __ CallRuntime(Runtime::kThrowConstAssignError, 0);
2681 void FullCodeGenerator::EmitNamedPropertyAssignment(Assignment* expr) {
2682 // Assignment to a property, using a named store IC.
2684 // esp[0] : receiver
2686 Property* prop = expr->target()->AsProperty();
2687 DCHECK(prop != NULL);
2688 DCHECK(prop->key()->IsLiteral());
2690 // Record source code position before IC call.
2691 SetSourcePosition(expr->position());
2692 __ mov(StoreDescriptor::NameRegister(), prop->key()->AsLiteral()->value());
2693 __ pop(StoreDescriptor::ReceiverRegister());
2694 CallStoreIC(expr->AssignmentFeedbackId());
2695 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
2696 context()->Plug(eax);
2700 void FullCodeGenerator::EmitNamedSuperPropertyStore(Property* prop) {
2701 // Assignment to named property of super.
2703 // stack : receiver ('this'), home_object
2704 DCHECK(prop != NULL);
2705 Literal* key = prop->key()->AsLiteral();
2706 DCHECK(key != NULL);
2708 __ push(Immediate(key->value()));
2710 __ CallRuntime((is_strict(language_mode()) ? Runtime::kStoreToSuper_Strict
2711 : Runtime::kStoreToSuper_Sloppy),
2716 void FullCodeGenerator::EmitKeyedSuperPropertyStore(Property* prop) {
2717 // Assignment to named property of super.
2719 // stack : receiver ('this'), home_object, key
2723 (is_strict(language_mode()) ? Runtime::kStoreKeyedToSuper_Strict
2724 : Runtime::kStoreKeyedToSuper_Sloppy),
2729 void FullCodeGenerator::EmitKeyedPropertyAssignment(Assignment* expr) {
2730 // Assignment to a property, using a keyed store IC.
2733 // esp[kPointerSize] : receiver
2735 __ pop(StoreDescriptor::NameRegister()); // Key.
2736 __ pop(StoreDescriptor::ReceiverRegister());
2737 DCHECK(StoreDescriptor::ValueRegister().is(eax));
2738 // Record source code position before IC call.
2739 SetSourcePosition(expr->position());
2741 CodeFactory::KeyedStoreIC(isolate(), language_mode()).code();
2742 CallIC(ic, expr->AssignmentFeedbackId());
2744 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
2745 context()->Plug(eax);
2749 void FullCodeGenerator::VisitProperty(Property* expr) {
2750 Comment cmnt(masm_, "[ Property");
2751 Expression* key = expr->key();
2753 if (key->IsPropertyName()) {
2754 if (!expr->IsSuperAccess()) {
2755 VisitForAccumulatorValue(expr->obj());
2756 __ Move(LoadDescriptor::ReceiverRegister(), result_register());
2757 EmitNamedPropertyLoad(expr);
2759 VisitForStackValue(expr->obj()->AsSuperReference()->this_var());
2760 EmitLoadHomeObject(expr->obj()->AsSuperReference());
2761 __ push(result_register());
2762 EmitNamedSuperPropertyLoad(expr);
2765 if (!expr->IsSuperAccess()) {
2766 VisitForStackValue(expr->obj());
2767 VisitForAccumulatorValue(expr->key());
2768 __ pop(LoadDescriptor::ReceiverRegister()); // Object.
2769 __ Move(LoadDescriptor::NameRegister(), result_register()); // Key.
2770 EmitKeyedPropertyLoad(expr);
2772 VisitForStackValue(expr->obj()->AsSuperReference()->this_var());
2773 EmitLoadHomeObject(expr->obj()->AsSuperReference());
2774 __ push(result_register());
2775 VisitForStackValue(expr->key());
2776 EmitKeyedSuperPropertyLoad(expr);
2779 PrepareForBailoutForId(expr->LoadId(), TOS_REG);
2780 context()->Plug(eax);
2784 void FullCodeGenerator::CallIC(Handle<Code> code,
2785 TypeFeedbackId ast_id) {
2787 __ call(code, RelocInfo::CODE_TARGET, ast_id);
2791 // Code common for calls using the IC.
2792 void FullCodeGenerator::EmitCallWithLoadIC(Call* expr) {
2793 Expression* callee = expr->expression();
2795 CallICState::CallType call_type =
2796 callee->IsVariableProxy() ? CallICState::FUNCTION : CallICState::METHOD;
2797 // Get the target function.
2798 if (call_type == CallICState::FUNCTION) {
2799 { StackValueContext context(this);
2800 EmitVariableLoad(callee->AsVariableProxy());
2801 PrepareForBailout(callee, NO_REGISTERS);
2803 // Push undefined as receiver. This is patched in the method prologue if it
2804 // is a sloppy mode method.
2805 __ push(Immediate(isolate()->factory()->undefined_value()));
2807 // Load the function from the receiver.
2808 DCHECK(callee->IsProperty());
2809 DCHECK(!callee->AsProperty()->IsSuperAccess());
2810 __ mov(LoadDescriptor::ReceiverRegister(), Operand(esp, 0));
2811 EmitNamedPropertyLoad(callee->AsProperty());
2812 PrepareForBailoutForId(callee->AsProperty()->LoadId(), TOS_REG);
2813 // Push the target function under the receiver.
2814 __ push(Operand(esp, 0));
2815 __ mov(Operand(esp, kPointerSize), eax);
2818 EmitCall(expr, call_type);
2822 void FullCodeGenerator::EmitSuperCallWithLoadIC(Call* expr) {
2823 Expression* callee = expr->expression();
2824 DCHECK(callee->IsProperty());
2825 Property* prop = callee->AsProperty();
2826 DCHECK(prop->IsSuperAccess());
2828 SetSourcePosition(prop->position());
2829 Literal* key = prop->key()->AsLiteral();
2830 DCHECK(!key->value()->IsSmi());
2831 // Load the function from the receiver.
2832 SuperReference* super_ref = callee->AsProperty()->obj()->AsSuperReference();
2833 EmitLoadHomeObject(super_ref);
2835 VisitForAccumulatorValue(super_ref->this_var());
2838 __ push(Operand(esp, kPointerSize * 2));
2839 __ push(Immediate(key->value()));
2842 // - this (receiver)
2843 // - this (receiver) <-- LoadFromSuper will pop here and below.
2846 __ CallRuntime(Runtime::kLoadFromSuper, 3);
2848 // Replace home_object with target function.
2849 __ mov(Operand(esp, kPointerSize), eax);
2852 // - target function
2853 // - this (receiver)
2854 EmitCall(expr, CallICState::METHOD);
2858 // Code common for calls using the IC.
2859 void FullCodeGenerator::EmitKeyedCallWithLoadIC(Call* expr,
2862 VisitForAccumulatorValue(key);
2864 Expression* callee = expr->expression();
2866 // Load the function from the receiver.
2867 DCHECK(callee->IsProperty());
2868 __ mov(LoadDescriptor::ReceiverRegister(), Operand(esp, 0));
2869 __ mov(LoadDescriptor::NameRegister(), eax);
2870 EmitKeyedPropertyLoad(callee->AsProperty());
2871 PrepareForBailoutForId(callee->AsProperty()->LoadId(), TOS_REG);
2873 // Push the target function under the receiver.
2874 __ push(Operand(esp, 0));
2875 __ mov(Operand(esp, kPointerSize), eax);
2877 EmitCall(expr, CallICState::METHOD);
2881 void FullCodeGenerator::EmitKeyedSuperCallWithLoadIC(Call* expr) {
2882 Expression* callee = expr->expression();
2883 DCHECK(callee->IsProperty());
2884 Property* prop = callee->AsProperty();
2885 DCHECK(prop->IsSuperAccess());
2887 SetSourcePosition(prop->position());
2888 // Load the function from the receiver.
2889 SuperReference* super_ref = callee->AsProperty()->obj()->AsSuperReference();
2890 EmitLoadHomeObject(super_ref);
2892 VisitForAccumulatorValue(super_ref->this_var());
2895 __ push(Operand(esp, kPointerSize * 2));
2896 VisitForStackValue(prop->key());
2899 // - this (receiver)
2900 // - this (receiver) <-- LoadKeyedFromSuper will pop here and below.
2903 __ CallRuntime(Runtime::kLoadKeyedFromSuper, 3);
2905 // Replace home_object with target function.
2906 __ mov(Operand(esp, kPointerSize), eax);
2909 // - target function
2910 // - this (receiver)
2911 EmitCall(expr, CallICState::METHOD);
2915 void FullCodeGenerator::EmitCall(Call* expr, CallICState::CallType call_type) {
2916 // Load the arguments.
2917 ZoneList<Expression*>* args = expr->arguments();
2918 int arg_count = args->length();
2919 { PreservePositionScope scope(masm()->positions_recorder());
2920 for (int i = 0; i < arg_count; i++) {
2921 VisitForStackValue(args->at(i));
2925 // Record source position of the IC call.
2926 SetSourcePosition(expr->position());
2927 Handle<Code> ic = CodeFactory::CallIC(isolate(), arg_count, call_type).code();
2928 __ Move(edx, Immediate(SmiFromSlot(expr->CallFeedbackICSlot())));
2929 __ mov(edi, Operand(esp, (arg_count + 1) * kPointerSize));
2930 // Don't assign a type feedback id to the IC, since type feedback is provided
2931 // by the vector above.
2934 RecordJSReturnSite(expr);
2936 // Restore context register.
2937 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
2939 context()->DropAndPlug(1, eax);
2943 void FullCodeGenerator::EmitResolvePossiblyDirectEval(int arg_count) {
2944 // Push copy of the first argument or undefined if it doesn't exist.
2945 if (arg_count > 0) {
2946 __ push(Operand(esp, arg_count * kPointerSize));
2948 __ push(Immediate(isolate()->factory()->undefined_value()));
2951 // Push the enclosing function.
2952 __ push(Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
2953 // Push the receiver of the enclosing function.
2954 __ push(Operand(ebp, (2 + info_->scope()->num_parameters()) * kPointerSize));
2955 // Push the language mode.
2956 __ push(Immediate(Smi::FromInt(language_mode())));
2958 // Push the start position of the scope the calls resides in.
2959 __ push(Immediate(Smi::FromInt(scope()->start_position())));
2961 // Do the runtime call.
2962 __ CallRuntime(Runtime::kResolvePossiblyDirectEval, 6);
2966 void FullCodeGenerator::EmitLoadSuperConstructor() {
2967 __ push(Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
2968 __ CallRuntime(Runtime::kGetPrototype, 1);
2972 void FullCodeGenerator::VisitCall(Call* expr) {
2974 // We want to verify that RecordJSReturnSite gets called on all paths
2975 // through this function. Avoid early returns.
2976 expr->return_is_recorded_ = false;
2979 Comment cmnt(masm_, "[ Call");
2980 Expression* callee = expr->expression();
2981 Call::CallType call_type = expr->GetCallType(isolate());
2983 if (call_type == Call::POSSIBLY_EVAL_CALL) {
2984 // In a call to eval, we first call RuntimeHidden_ResolvePossiblyDirectEval
2985 // to resolve the function we need to call and the receiver of the call.
2986 // Then we call the resolved function using the given arguments.
2987 ZoneList<Expression*>* args = expr->arguments();
2988 int arg_count = args->length();
2989 { PreservePositionScope pos_scope(masm()->positions_recorder());
2990 VisitForStackValue(callee);
2991 // Reserved receiver slot.
2992 __ push(Immediate(isolate()->factory()->undefined_value()));
2993 // Push the arguments.
2994 for (int i = 0; i < arg_count; i++) {
2995 VisitForStackValue(args->at(i));
2998 // Push a copy of the function (found below the arguments) and
3000 __ push(Operand(esp, (arg_count + 1) * kPointerSize));
3001 EmitResolvePossiblyDirectEval(arg_count);
3003 // The runtime call returns a pair of values in eax (function) and
3004 // edx (receiver). Touch up the stack with the right values.
3005 __ mov(Operand(esp, (arg_count + 0) * kPointerSize), edx);
3006 __ mov(Operand(esp, (arg_count + 1) * kPointerSize), eax);
3008 PrepareForBailoutForId(expr->EvalOrLookupId(), NO_REGISTERS);
3010 // Record source position for debugger.
3011 SetSourcePosition(expr->position());
3012 CallFunctionStub stub(isolate(), arg_count, NO_CALL_FUNCTION_FLAGS);
3013 __ mov(edi, Operand(esp, (arg_count + 1) * kPointerSize));
3015 RecordJSReturnSite(expr);
3016 // Restore context register.
3017 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
3018 context()->DropAndPlug(1, eax);
3020 } else if (call_type == Call::GLOBAL_CALL) {
3021 EmitCallWithLoadIC(expr);
3022 } else if (call_type == Call::LOOKUP_SLOT_CALL) {
3023 // Call to a lookup slot (dynamically introduced variable).
3024 VariableProxy* proxy = callee->AsVariableProxy();
3026 { PreservePositionScope scope(masm()->positions_recorder());
3027 // Generate code for loading from variables potentially shadowed by
3028 // eval-introduced variables.
3029 EmitDynamicLookupFastCase(proxy, NOT_INSIDE_TYPEOF, &slow, &done);
3032 // Call the runtime to find the function to call (returned in eax) and
3033 // the object holding it (returned in edx).
3034 __ push(context_register());
3035 __ push(Immediate(proxy->name()));
3036 __ CallRuntime(Runtime::kLoadLookupSlot, 2);
3037 __ push(eax); // Function.
3038 __ push(edx); // Receiver.
3039 PrepareForBailoutForId(expr->EvalOrLookupId(), NO_REGISTERS);
3041 // If fast case code has been generated, emit code to push the function
3042 // and receiver and have the slow path jump around this code.
3043 if (done.is_linked()) {
3045 __ jmp(&call, Label::kNear);
3049 // The receiver is implicitly the global receiver. Indicate this by
3050 // passing the hole to the call function stub.
3051 __ push(Immediate(isolate()->factory()->undefined_value()));
3055 // The receiver is either the global receiver or an object found by
3059 } else if (call_type == Call::PROPERTY_CALL) {
3060 Property* property = callee->AsProperty();
3061 bool is_named_call = property->key()->IsPropertyName();
3062 if (property->IsSuperAccess()) {
3063 if (is_named_call) {
3064 EmitSuperCallWithLoadIC(expr);
3066 EmitKeyedSuperCallWithLoadIC(expr);
3070 PreservePositionScope scope(masm()->positions_recorder());
3071 VisitForStackValue(property->obj());
3073 if (is_named_call) {
3074 EmitCallWithLoadIC(expr);
3076 EmitKeyedCallWithLoadIC(expr, property->key());
3079 } else if (call_type == Call::SUPER_CALL) {
3080 EmitSuperConstructorCall(expr);
3082 DCHECK(call_type == Call::OTHER_CALL);
3083 // Call to an arbitrary expression not handled specially above.
3084 { PreservePositionScope scope(masm()->positions_recorder());
3085 VisitForStackValue(callee);
3087 __ push(Immediate(isolate()->factory()->undefined_value()));
3088 // Emit function call.
3093 // RecordJSReturnSite should have been called.
3094 DCHECK(expr->return_is_recorded_);
3099 void FullCodeGenerator::VisitCallNew(CallNew* expr) {
3100 Comment cmnt(masm_, "[ CallNew");
3101 // According to ECMA-262, section 11.2.2, page 44, the function
3102 // expression in new calls must be evaluated before the
3105 // Push constructor on the stack. If it's not a function it's used as
3106 // receiver for CALL_NON_FUNCTION, otherwise the value on the stack is
3108 DCHECK(!expr->expression()->IsSuperReference());
3109 VisitForStackValue(expr->expression());
3111 // Push the arguments ("left-to-right") on the stack.
3112 ZoneList<Expression*>* args = expr->arguments();
3113 int arg_count = args->length();
3114 for (int i = 0; i < arg_count; i++) {
3115 VisitForStackValue(args->at(i));
3118 // Call the construct call builtin that handles allocation and
3119 // constructor invocation.
3120 SetSourcePosition(expr->position());
3122 // Load function and argument count into edi and eax.
3123 __ Move(eax, Immediate(arg_count));
3124 __ mov(edi, Operand(esp, arg_count * kPointerSize));
3126 // Record call targets in unoptimized code.
3127 if (FLAG_pretenuring_call_new) {
3128 EnsureSlotContainsAllocationSite(expr->AllocationSiteFeedbackSlot());
3129 DCHECK(expr->AllocationSiteFeedbackSlot().ToInt() ==
3130 expr->CallNewFeedbackSlot().ToInt() + 1);
3133 __ LoadHeapObject(ebx, FeedbackVector());
3134 __ mov(edx, Immediate(SmiFromSlot(expr->CallNewFeedbackSlot())));
3136 CallConstructStub stub(isolate(), RECORD_CONSTRUCTOR_TARGET);
3137 __ call(stub.GetCode(), RelocInfo::CONSTRUCT_CALL);
3138 PrepareForBailoutForId(expr->ReturnId(), TOS_REG);
3139 context()->Plug(eax);
3143 void FullCodeGenerator::EmitSuperConstructorCall(Call* expr) {
3144 if (!ValidateSuperCall(expr)) return;
3146 Variable* new_target_var = scope()->DeclarationScope()->new_target_var();
3147 GetVar(eax, new_target_var);
3150 EmitLoadSuperConstructor();
3151 __ push(result_register());
3153 // Push the arguments ("left-to-right") on the stack.
3154 ZoneList<Expression*>* args = expr->arguments();
3155 int arg_count = args->length();
3156 for (int i = 0; i < arg_count; i++) {
3157 VisitForStackValue(args->at(i));
3160 // Call the construct call builtin that handles allocation and
3161 // constructor invocation.
3162 SetSourcePosition(expr->position());
3164 // Load function and argument count into edi and eax.
3165 __ Move(eax, Immediate(arg_count));
3166 __ mov(edi, Operand(esp, arg_count * kPointerSize));
3168 // Record call targets in unoptimized code.
3169 if (FLAG_pretenuring_call_new) {
3171 /* TODO(dslomov): support pretenuring.
3172 EnsureSlotContainsAllocationSite(expr->AllocationSiteFeedbackSlot());
3173 DCHECK(expr->AllocationSiteFeedbackSlot().ToInt() ==
3174 expr->CallNewFeedbackSlot().ToInt() + 1);
3178 __ LoadHeapObject(ebx, FeedbackVector());
3179 __ mov(edx, Immediate(SmiFromSlot(expr->CallFeedbackSlot())));
3181 CallConstructStub stub(isolate(), SUPER_CALL_RECORD_TARGET);
3182 __ call(stub.GetCode(), RelocInfo::CONSTRUCT_CALL);
3186 RecordJSReturnSite(expr);
3188 SuperReference* super_ref = expr->expression()->AsSuperReference();
3189 Variable* this_var = super_ref->this_var()->var();
3190 GetVar(ecx, this_var);
3191 __ cmp(ecx, isolate()->factory()->the_hole_value());
3192 Label uninitialized_this;
3193 __ j(equal, &uninitialized_this);
3194 __ push(Immediate(this_var->name()));
3195 __ CallRuntime(Runtime::kThrowReferenceError, 1);
3196 __ bind(&uninitialized_this);
3198 EmitVariableAssignment(this_var, Token::INIT_CONST);
3199 context()->Plug(eax);
3203 void FullCodeGenerator::EmitIsSmi(CallRuntime* expr) {
3204 ZoneList<Expression*>* args = expr->arguments();
3205 DCHECK(args->length() == 1);
3207 VisitForAccumulatorValue(args->at(0));
3209 Label materialize_true, materialize_false;
3210 Label* if_true = NULL;
3211 Label* if_false = NULL;
3212 Label* fall_through = NULL;
3213 context()->PrepareTest(&materialize_true, &materialize_false,
3214 &if_true, &if_false, &fall_through);
3216 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3217 __ test(eax, Immediate(kSmiTagMask));
3218 Split(zero, if_true, if_false, fall_through);
3220 context()->Plug(if_true, if_false);
3224 void FullCodeGenerator::EmitIsNonNegativeSmi(CallRuntime* expr) {
3225 ZoneList<Expression*>* args = expr->arguments();
3226 DCHECK(args->length() == 1);
3228 VisitForAccumulatorValue(args->at(0));
3230 Label materialize_true, materialize_false;
3231 Label* if_true = NULL;
3232 Label* if_false = NULL;
3233 Label* fall_through = NULL;
3234 context()->PrepareTest(&materialize_true, &materialize_false,
3235 &if_true, &if_false, &fall_through);
3237 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3238 __ test(eax, Immediate(kSmiTagMask | 0x80000000));
3239 Split(zero, if_true, if_false, fall_through);
3241 context()->Plug(if_true, if_false);
3245 void FullCodeGenerator::EmitIsObject(CallRuntime* expr) {
3246 ZoneList<Expression*>* args = expr->arguments();
3247 DCHECK(args->length() == 1);
3249 VisitForAccumulatorValue(args->at(0));
3251 Label materialize_true, materialize_false;
3252 Label* if_true = NULL;
3253 Label* if_false = NULL;
3254 Label* fall_through = NULL;
3255 context()->PrepareTest(&materialize_true, &materialize_false,
3256 &if_true, &if_false, &fall_through);
3258 __ JumpIfSmi(eax, if_false);
3259 __ cmp(eax, isolate()->factory()->null_value());
3260 __ j(equal, if_true);
3261 __ mov(ebx, FieldOperand(eax, HeapObject::kMapOffset));
3262 // Undetectable objects behave like undefined when tested with typeof.
3263 __ movzx_b(ecx, FieldOperand(ebx, Map::kBitFieldOffset));
3264 __ test(ecx, Immediate(1 << Map::kIsUndetectable));
3265 __ j(not_zero, if_false);
3266 __ movzx_b(ecx, FieldOperand(ebx, Map::kInstanceTypeOffset));
3267 __ cmp(ecx, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE);
3268 __ j(below, if_false);
3269 __ cmp(ecx, LAST_NONCALLABLE_SPEC_OBJECT_TYPE);
3270 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3271 Split(below_equal, if_true, if_false, fall_through);
3273 context()->Plug(if_true, if_false);
3277 void FullCodeGenerator::EmitIsSpecObject(CallRuntime* expr) {
3278 ZoneList<Expression*>* args = expr->arguments();
3279 DCHECK(args->length() == 1);
3281 VisitForAccumulatorValue(args->at(0));
3283 Label materialize_true, materialize_false;
3284 Label* if_true = NULL;
3285 Label* if_false = NULL;
3286 Label* fall_through = NULL;
3287 context()->PrepareTest(&materialize_true, &materialize_false,
3288 &if_true, &if_false, &fall_through);
3290 __ JumpIfSmi(eax, if_false);
3291 __ CmpObjectType(eax, FIRST_SPEC_OBJECT_TYPE, ebx);
3292 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3293 Split(above_equal, if_true, if_false, fall_through);
3295 context()->Plug(if_true, if_false);
3299 void FullCodeGenerator::EmitIsUndetectableObject(CallRuntime* expr) {
3300 ZoneList<Expression*>* args = expr->arguments();
3301 DCHECK(args->length() == 1);
3303 VisitForAccumulatorValue(args->at(0));
3305 Label materialize_true, materialize_false;
3306 Label* if_true = NULL;
3307 Label* if_false = NULL;
3308 Label* fall_through = NULL;
3309 context()->PrepareTest(&materialize_true, &materialize_false,
3310 &if_true, &if_false, &fall_through);
3312 __ JumpIfSmi(eax, if_false);
3313 __ mov(ebx, FieldOperand(eax, HeapObject::kMapOffset));
3314 __ movzx_b(ebx, FieldOperand(ebx, Map::kBitFieldOffset));
3315 __ test(ebx, Immediate(1 << Map::kIsUndetectable));
3316 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3317 Split(not_zero, if_true, if_false, fall_through);
3319 context()->Plug(if_true, if_false);
3323 void FullCodeGenerator::EmitIsStringWrapperSafeForDefaultValueOf(
3324 CallRuntime* expr) {
3325 ZoneList<Expression*>* args = expr->arguments();
3326 DCHECK(args->length() == 1);
3328 VisitForAccumulatorValue(args->at(0));
3330 Label materialize_true, materialize_false, skip_lookup;
3331 Label* if_true = NULL;
3332 Label* if_false = NULL;
3333 Label* fall_through = NULL;
3334 context()->PrepareTest(&materialize_true, &materialize_false,
3335 &if_true, &if_false, &fall_through);
3337 __ AssertNotSmi(eax);
3339 // Check whether this map has already been checked to be safe for default
3341 __ mov(ebx, FieldOperand(eax, HeapObject::kMapOffset));
3342 __ test_b(FieldOperand(ebx, Map::kBitField2Offset),
3343 1 << Map::kStringWrapperSafeForDefaultValueOf);
3344 __ j(not_zero, &skip_lookup);
3346 // Check for fast case object. Return false for slow case objects.
3347 __ mov(ecx, FieldOperand(eax, JSObject::kPropertiesOffset));
3348 __ mov(ecx, FieldOperand(ecx, HeapObject::kMapOffset));
3349 __ cmp(ecx, isolate()->factory()->hash_table_map());
3350 __ j(equal, if_false);
3352 // Look for valueOf string in the descriptor array, and indicate false if
3353 // found. Since we omit an enumeration index check, if it is added via a
3354 // transition that shares its descriptor array, this is a false positive.
3355 Label entry, loop, done;
3357 // Skip loop if no descriptors are valid.
3358 __ NumberOfOwnDescriptors(ecx, ebx);
3362 __ LoadInstanceDescriptors(ebx, ebx);
3363 // ebx: descriptor array.
3364 // ecx: valid entries in the descriptor array.
3365 // Calculate the end of the descriptor array.
3366 STATIC_ASSERT(kSmiTag == 0);
3367 STATIC_ASSERT(kSmiTagSize == 1);
3368 STATIC_ASSERT(kPointerSize == 4);
3369 __ imul(ecx, ecx, DescriptorArray::kDescriptorSize);
3370 __ lea(ecx, Operand(ebx, ecx, times_4, DescriptorArray::kFirstOffset));
3371 // Calculate location of the first key name.
3372 __ add(ebx, Immediate(DescriptorArray::kFirstOffset));
3373 // Loop through all the keys in the descriptor array. If one of these is the
3374 // internalized string "valueOf" the result is false.
3377 __ mov(edx, FieldOperand(ebx, 0));
3378 __ cmp(edx, isolate()->factory()->value_of_string());
3379 __ j(equal, if_false);
3380 __ add(ebx, Immediate(DescriptorArray::kDescriptorSize * kPointerSize));
3383 __ j(not_equal, &loop);
3387 // Reload map as register ebx was used as temporary above.
3388 __ mov(ebx, FieldOperand(eax, HeapObject::kMapOffset));
3390 // Set the bit in the map to indicate that there is no local valueOf field.
3391 __ or_(FieldOperand(ebx, Map::kBitField2Offset),
3392 Immediate(1 << Map::kStringWrapperSafeForDefaultValueOf));
3394 __ bind(&skip_lookup);
3396 // If a valueOf property is not found on the object check that its
3397 // prototype is the un-modified String prototype. If not result is false.
3398 __ mov(ecx, FieldOperand(ebx, Map::kPrototypeOffset));
3399 __ JumpIfSmi(ecx, if_false);
3400 __ mov(ecx, FieldOperand(ecx, HeapObject::kMapOffset));
3401 __ mov(edx, Operand(esi, Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX)));
3403 FieldOperand(edx, GlobalObject::kNativeContextOffset));
3406 Context::STRING_FUNCTION_PROTOTYPE_MAP_INDEX));
3407 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3408 Split(equal, if_true, if_false, fall_through);
3410 context()->Plug(if_true, if_false);
3414 void FullCodeGenerator::EmitIsFunction(CallRuntime* expr) {
3415 ZoneList<Expression*>* args = expr->arguments();
3416 DCHECK(args->length() == 1);
3418 VisitForAccumulatorValue(args->at(0));
3420 Label materialize_true, materialize_false;
3421 Label* if_true = NULL;
3422 Label* if_false = NULL;
3423 Label* fall_through = NULL;
3424 context()->PrepareTest(&materialize_true, &materialize_false,
3425 &if_true, &if_false, &fall_through);
3427 __ JumpIfSmi(eax, if_false);
3428 __ CmpObjectType(eax, JS_FUNCTION_TYPE, ebx);
3429 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3430 Split(equal, if_true, if_false, fall_through);
3432 context()->Plug(if_true, if_false);
3436 void FullCodeGenerator::EmitIsMinusZero(CallRuntime* expr) {
3437 ZoneList<Expression*>* args = expr->arguments();
3438 DCHECK(args->length() == 1);
3440 VisitForAccumulatorValue(args->at(0));
3442 Label materialize_true, materialize_false;
3443 Label* if_true = NULL;
3444 Label* if_false = NULL;
3445 Label* fall_through = NULL;
3446 context()->PrepareTest(&materialize_true, &materialize_false,
3447 &if_true, &if_false, &fall_through);
3449 Handle<Map> map = masm()->isolate()->factory()->heap_number_map();
3450 __ CheckMap(eax, map, if_false, DO_SMI_CHECK);
3451 // Check if the exponent half is 0x80000000. Comparing against 1 and
3452 // checking for overflow is the shortest possible encoding.
3453 __ cmp(FieldOperand(eax, HeapNumber::kExponentOffset), Immediate(0x1));
3454 __ j(no_overflow, if_false);
3455 __ cmp(FieldOperand(eax, HeapNumber::kMantissaOffset), Immediate(0x0));
3456 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3457 Split(equal, if_true, if_false, fall_through);
3459 context()->Plug(if_true, if_false);
3464 void FullCodeGenerator::EmitIsArray(CallRuntime* expr) {
3465 ZoneList<Expression*>* args = expr->arguments();
3466 DCHECK(args->length() == 1);
3468 VisitForAccumulatorValue(args->at(0));
3470 Label materialize_true, materialize_false;
3471 Label* if_true = NULL;
3472 Label* if_false = NULL;
3473 Label* fall_through = NULL;
3474 context()->PrepareTest(&materialize_true, &materialize_false,
3475 &if_true, &if_false, &fall_through);
3477 __ JumpIfSmi(eax, if_false);
3478 __ CmpObjectType(eax, JS_ARRAY_TYPE, ebx);
3479 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3480 Split(equal, if_true, if_false, fall_through);
3482 context()->Plug(if_true, if_false);
3486 void FullCodeGenerator::EmitIsRegExp(CallRuntime* expr) {
3487 ZoneList<Expression*>* args = expr->arguments();
3488 DCHECK(args->length() == 1);
3490 VisitForAccumulatorValue(args->at(0));
3492 Label materialize_true, materialize_false;
3493 Label* if_true = NULL;
3494 Label* if_false = NULL;
3495 Label* fall_through = NULL;
3496 context()->PrepareTest(&materialize_true, &materialize_false,
3497 &if_true, &if_false, &fall_through);
3499 __ JumpIfSmi(eax, if_false);
3500 __ CmpObjectType(eax, JS_REGEXP_TYPE, ebx);
3501 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3502 Split(equal, if_true, if_false, fall_through);
3504 context()->Plug(if_true, if_false);
3508 void FullCodeGenerator::EmitIsJSProxy(CallRuntime* expr) {
3509 ZoneList<Expression*>* args = expr->arguments();
3510 DCHECK(args->length() == 1);
3512 VisitForAccumulatorValue(args->at(0));
3514 Label materialize_true, materialize_false;
3515 Label* if_true = NULL;
3516 Label* if_false = NULL;
3517 Label* fall_through = NULL;
3518 context()->PrepareTest(&materialize_true, &materialize_false, &if_true,
3519 &if_false, &fall_through);
3521 __ JumpIfSmi(eax, if_false);
3523 __ mov(map, FieldOperand(eax, HeapObject::kMapOffset));
3524 __ CmpInstanceType(map, FIRST_JS_PROXY_TYPE);
3525 __ j(less, if_false);
3526 __ CmpInstanceType(map, LAST_JS_PROXY_TYPE);
3527 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3528 Split(less_equal, if_true, if_false, fall_through);
3530 context()->Plug(if_true, if_false);
3534 void FullCodeGenerator::EmitIsConstructCall(CallRuntime* expr) {
3535 DCHECK(expr->arguments()->length() == 0);
3537 Label materialize_true, materialize_false;
3538 Label* if_true = NULL;
3539 Label* if_false = NULL;
3540 Label* fall_through = NULL;
3541 context()->PrepareTest(&materialize_true, &materialize_false,
3542 &if_true, &if_false, &fall_through);
3544 // Get the frame pointer for the calling frame.
3545 __ mov(eax, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3547 // Skip the arguments adaptor frame if it exists.
3548 Label check_frame_marker;
3549 __ cmp(Operand(eax, StandardFrameConstants::kContextOffset),
3550 Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
3551 __ j(not_equal, &check_frame_marker);
3552 __ mov(eax, Operand(eax, StandardFrameConstants::kCallerFPOffset));
3554 // Check the marker in the calling frame.
3555 __ bind(&check_frame_marker);
3556 __ cmp(Operand(eax, StandardFrameConstants::kMarkerOffset),
3557 Immediate(Smi::FromInt(StackFrame::CONSTRUCT)));
3558 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3559 Split(equal, if_true, if_false, fall_through);
3561 context()->Plug(if_true, if_false);
3565 void FullCodeGenerator::EmitObjectEquals(CallRuntime* expr) {
3566 ZoneList<Expression*>* args = expr->arguments();
3567 DCHECK(args->length() == 2);
3569 // Load the two objects into registers and perform the comparison.
3570 VisitForStackValue(args->at(0));
3571 VisitForAccumulatorValue(args->at(1));
3573 Label materialize_true, materialize_false;
3574 Label* if_true = NULL;
3575 Label* if_false = NULL;
3576 Label* fall_through = NULL;
3577 context()->PrepareTest(&materialize_true, &materialize_false,
3578 &if_true, &if_false, &fall_through);
3582 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3583 Split(equal, if_true, if_false, fall_through);
3585 context()->Plug(if_true, if_false);
3589 void FullCodeGenerator::EmitArguments(CallRuntime* expr) {
3590 ZoneList<Expression*>* args = expr->arguments();
3591 DCHECK(args->length() == 1);
3593 // ArgumentsAccessStub expects the key in edx and the formal
3594 // parameter count in eax.
3595 VisitForAccumulatorValue(args->at(0));
3597 __ Move(eax, Immediate(Smi::FromInt(info_->scope()->num_parameters())));
3598 ArgumentsAccessStub stub(isolate(), ArgumentsAccessStub::READ_ELEMENT);
3600 context()->Plug(eax);
3604 void FullCodeGenerator::EmitArgumentsLength(CallRuntime* expr) {
3605 DCHECK(expr->arguments()->length() == 0);
3608 // Get the number of formal parameters.
3609 __ Move(eax, Immediate(Smi::FromInt(info_->scope()->num_parameters())));
3611 // Check if the calling frame is an arguments adaptor frame.
3612 __ mov(ebx, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3613 __ cmp(Operand(ebx, StandardFrameConstants::kContextOffset),
3614 Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
3615 __ j(not_equal, &exit);
3617 // Arguments adaptor case: Read the arguments length from the
3619 __ mov(eax, Operand(ebx, ArgumentsAdaptorFrameConstants::kLengthOffset));
3623 context()->Plug(eax);
3627 void FullCodeGenerator::EmitClassOf(CallRuntime* expr) {
3628 ZoneList<Expression*>* args = expr->arguments();
3629 DCHECK(args->length() == 1);
3630 Label done, null, function, non_function_constructor;
3632 VisitForAccumulatorValue(args->at(0));
3634 // If the object is a smi, we return null.
3635 __ JumpIfSmi(eax, &null);
3637 // Check that the object is a JS object but take special care of JS
3638 // functions to make sure they have 'Function' as their class.
3639 // Assume that there are only two callable types, and one of them is at
3640 // either end of the type range for JS object types. Saves extra comparisons.
3641 STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
3642 __ CmpObjectType(eax, FIRST_SPEC_OBJECT_TYPE, eax);
3643 // Map is now in eax.
3645 STATIC_ASSERT(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE ==
3646 FIRST_SPEC_OBJECT_TYPE + 1);
3647 __ j(equal, &function);
3649 __ CmpInstanceType(eax, LAST_SPEC_OBJECT_TYPE);
3650 STATIC_ASSERT(LAST_NONCALLABLE_SPEC_OBJECT_TYPE ==
3651 LAST_SPEC_OBJECT_TYPE - 1);
3652 __ j(equal, &function);
3653 // Assume that there is no larger type.
3654 STATIC_ASSERT(LAST_NONCALLABLE_SPEC_OBJECT_TYPE == LAST_TYPE - 1);
3656 // Check if the constructor in the map is a JS function.
3657 __ mov(eax, FieldOperand(eax, Map::kConstructorOffset));
3658 __ CmpObjectType(eax, JS_FUNCTION_TYPE, ebx);
3659 __ j(not_equal, &non_function_constructor);
3661 // eax now contains the constructor function. Grab the
3662 // instance class name from there.
3663 __ mov(eax, FieldOperand(eax, JSFunction::kSharedFunctionInfoOffset));
3664 __ mov(eax, FieldOperand(eax, SharedFunctionInfo::kInstanceClassNameOffset));
3667 // Functions have class 'Function'.
3669 __ mov(eax, isolate()->factory()->Function_string());
3672 // Objects with a non-function constructor have class 'Object'.
3673 __ bind(&non_function_constructor);
3674 __ mov(eax, isolate()->factory()->Object_string());
3677 // Non-JS objects have class null.
3679 __ mov(eax, isolate()->factory()->null_value());
3684 context()->Plug(eax);
3688 void FullCodeGenerator::EmitSubString(CallRuntime* expr) {
3689 // Load the arguments on the stack and call the stub.
3690 SubStringStub stub(isolate());
3691 ZoneList<Expression*>* args = expr->arguments();
3692 DCHECK(args->length() == 3);
3693 VisitForStackValue(args->at(0));
3694 VisitForStackValue(args->at(1));
3695 VisitForStackValue(args->at(2));
3697 context()->Plug(eax);
3701 void FullCodeGenerator::EmitRegExpExec(CallRuntime* expr) {
3702 // Load the arguments on the stack and call the stub.
3703 RegExpExecStub stub(isolate());
3704 ZoneList<Expression*>* args = expr->arguments();
3705 DCHECK(args->length() == 4);
3706 VisitForStackValue(args->at(0));
3707 VisitForStackValue(args->at(1));
3708 VisitForStackValue(args->at(2));
3709 VisitForStackValue(args->at(3));
3711 context()->Plug(eax);
3715 void FullCodeGenerator::EmitValueOf(CallRuntime* expr) {
3716 ZoneList<Expression*>* args = expr->arguments();
3717 DCHECK(args->length() == 1);
3719 VisitForAccumulatorValue(args->at(0)); // Load the object.
3722 // If the object is a smi return the object.
3723 __ JumpIfSmi(eax, &done, Label::kNear);
3724 // If the object is not a value type, return the object.
3725 __ CmpObjectType(eax, JS_VALUE_TYPE, ebx);
3726 __ j(not_equal, &done, Label::kNear);
3727 __ mov(eax, FieldOperand(eax, JSValue::kValueOffset));
3730 context()->Plug(eax);
3734 void FullCodeGenerator::EmitDateField(CallRuntime* expr) {
3735 ZoneList<Expression*>* args = expr->arguments();
3736 DCHECK(args->length() == 2);
3737 DCHECK_NOT_NULL(args->at(1)->AsLiteral());
3738 Smi* index = Smi::cast(*(args->at(1)->AsLiteral()->value()));
3740 VisitForAccumulatorValue(args->at(0)); // Load the object.
3742 Label runtime, done, not_date_object;
3743 Register object = eax;
3744 Register result = eax;
3745 Register scratch = ecx;
3747 __ JumpIfSmi(object, ¬_date_object);
3748 __ CmpObjectType(object, JS_DATE_TYPE, scratch);
3749 __ j(not_equal, ¬_date_object);
3751 if (index->value() == 0) {
3752 __ mov(result, FieldOperand(object, JSDate::kValueOffset));
3755 if (index->value() < JSDate::kFirstUncachedField) {
3756 ExternalReference stamp = ExternalReference::date_cache_stamp(isolate());
3757 __ mov(scratch, Operand::StaticVariable(stamp));
3758 __ cmp(scratch, FieldOperand(object, JSDate::kCacheStampOffset));
3759 __ j(not_equal, &runtime, Label::kNear);
3760 __ mov(result, FieldOperand(object, JSDate::kValueOffset +
3761 kPointerSize * index->value()));
3765 __ PrepareCallCFunction(2, scratch);
3766 __ mov(Operand(esp, 0), object);
3767 __ mov(Operand(esp, 1 * kPointerSize), Immediate(index));
3768 __ CallCFunction(ExternalReference::get_date_field_function(isolate()), 2);
3772 __ bind(¬_date_object);
3773 __ CallRuntime(Runtime::kThrowNotDateError, 0);
3775 context()->Plug(result);
3779 void FullCodeGenerator::EmitOneByteSeqStringSetChar(CallRuntime* expr) {
3780 ZoneList<Expression*>* args = expr->arguments();
3781 DCHECK_EQ(3, args->length());
3783 Register string = eax;
3784 Register index = ebx;
3785 Register value = ecx;
3787 VisitForStackValue(args->at(0)); // index
3788 VisitForStackValue(args->at(1)); // value
3789 VisitForAccumulatorValue(args->at(2)); // string
3794 if (FLAG_debug_code) {
3795 __ test(value, Immediate(kSmiTagMask));
3796 __ Check(zero, kNonSmiValue);
3797 __ test(index, Immediate(kSmiTagMask));
3798 __ Check(zero, kNonSmiValue);
3804 if (FLAG_debug_code) {
3805 static const uint32_t one_byte_seq_type = kSeqStringTag | kOneByteStringTag;
3806 __ EmitSeqStringSetCharCheck(string, index, value, one_byte_seq_type);
3809 __ mov_b(FieldOperand(string, index, times_1, SeqOneByteString::kHeaderSize),
3811 context()->Plug(string);
3815 void FullCodeGenerator::EmitTwoByteSeqStringSetChar(CallRuntime* expr) {
3816 ZoneList<Expression*>* args = expr->arguments();
3817 DCHECK_EQ(3, args->length());
3819 Register string = eax;
3820 Register index = ebx;
3821 Register value = ecx;
3823 VisitForStackValue(args->at(0)); // index
3824 VisitForStackValue(args->at(1)); // value
3825 VisitForAccumulatorValue(args->at(2)); // string
3829 if (FLAG_debug_code) {
3830 __ test(value, Immediate(kSmiTagMask));
3831 __ Check(zero, kNonSmiValue);
3832 __ test(index, Immediate(kSmiTagMask));
3833 __ Check(zero, kNonSmiValue);
3835 static const uint32_t two_byte_seq_type = kSeqStringTag | kTwoByteStringTag;
3836 __ EmitSeqStringSetCharCheck(string, index, value, two_byte_seq_type);
3841 // No need to untag a smi for two-byte addressing.
3842 __ mov_w(FieldOperand(string, index, times_1, SeqTwoByteString::kHeaderSize),
3844 context()->Plug(string);
3848 void FullCodeGenerator::EmitMathPow(CallRuntime* expr) {
3849 // Load the arguments on the stack and call the runtime function.
3850 ZoneList<Expression*>* args = expr->arguments();
3851 DCHECK(args->length() == 2);
3852 VisitForStackValue(args->at(0));
3853 VisitForStackValue(args->at(1));
3855 __ CallRuntime(Runtime::kMathPowSlow, 2);
3856 context()->Plug(eax);
3860 void FullCodeGenerator::EmitSetValueOf(CallRuntime* expr) {
3861 ZoneList<Expression*>* args = expr->arguments();
3862 DCHECK(args->length() == 2);
3864 VisitForStackValue(args->at(0)); // Load the object.
3865 VisitForAccumulatorValue(args->at(1)); // Load the value.
3866 __ pop(ebx); // eax = value. ebx = object.
3869 // If the object is a smi, return the value.
3870 __ JumpIfSmi(ebx, &done, Label::kNear);
3872 // If the object is not a value type, return the value.
3873 __ CmpObjectType(ebx, JS_VALUE_TYPE, ecx);
3874 __ j(not_equal, &done, Label::kNear);
3877 __ mov(FieldOperand(ebx, JSValue::kValueOffset), eax);
3879 // Update the write barrier. Save the value as it will be
3880 // overwritten by the write barrier code and is needed afterward.
3882 __ RecordWriteField(ebx, JSValue::kValueOffset, edx, ecx, kDontSaveFPRegs);
3885 context()->Plug(eax);
3889 void FullCodeGenerator::EmitNumberToString(CallRuntime* expr) {
3890 ZoneList<Expression*>* args = expr->arguments();
3891 DCHECK_EQ(args->length(), 1);
3893 // Load the argument into eax and call the stub.
3894 VisitForAccumulatorValue(args->at(0));
3896 NumberToStringStub stub(isolate());
3898 context()->Plug(eax);
3902 void FullCodeGenerator::EmitStringCharFromCode(CallRuntime* expr) {
3903 ZoneList<Expression*>* args = expr->arguments();
3904 DCHECK(args->length() == 1);
3906 VisitForAccumulatorValue(args->at(0));
3909 StringCharFromCodeGenerator generator(eax, ebx);
3910 generator.GenerateFast(masm_);
3913 NopRuntimeCallHelper call_helper;
3914 generator.GenerateSlow(masm_, call_helper);
3917 context()->Plug(ebx);
3921 void FullCodeGenerator::EmitStringCharCodeAt(CallRuntime* expr) {
3922 ZoneList<Expression*>* args = expr->arguments();
3923 DCHECK(args->length() == 2);
3925 VisitForStackValue(args->at(0));
3926 VisitForAccumulatorValue(args->at(1));
3928 Register object = ebx;
3929 Register index = eax;
3930 Register result = edx;
3934 Label need_conversion;
3935 Label index_out_of_range;
3937 StringCharCodeAtGenerator generator(object,
3942 &index_out_of_range,
3943 STRING_INDEX_IS_NUMBER);
3944 generator.GenerateFast(masm_);
3947 __ bind(&index_out_of_range);
3948 // When the index is out of range, the spec requires us to return
3950 __ Move(result, Immediate(isolate()->factory()->nan_value()));
3953 __ bind(&need_conversion);
3954 // Move the undefined value into the result register, which will
3955 // trigger conversion.
3956 __ Move(result, Immediate(isolate()->factory()->undefined_value()));
3959 NopRuntimeCallHelper call_helper;
3960 generator.GenerateSlow(masm_, call_helper);
3963 context()->Plug(result);
3967 void FullCodeGenerator::EmitStringCharAt(CallRuntime* expr) {
3968 ZoneList<Expression*>* args = expr->arguments();
3969 DCHECK(args->length() == 2);
3971 VisitForStackValue(args->at(0));
3972 VisitForAccumulatorValue(args->at(1));
3974 Register object = ebx;
3975 Register index = eax;
3976 Register scratch = edx;
3977 Register result = eax;
3981 Label need_conversion;
3982 Label index_out_of_range;
3984 StringCharAtGenerator generator(object,
3990 &index_out_of_range,
3991 STRING_INDEX_IS_NUMBER);
3992 generator.GenerateFast(masm_);
3995 __ bind(&index_out_of_range);
3996 // When the index is out of range, the spec requires us to return
3997 // the empty string.
3998 __ Move(result, Immediate(isolate()->factory()->empty_string()));
4001 __ bind(&need_conversion);
4002 // Move smi zero into the result register, which will trigger
4004 __ Move(result, Immediate(Smi::FromInt(0)));
4007 NopRuntimeCallHelper call_helper;
4008 generator.GenerateSlow(masm_, call_helper);
4011 context()->Plug(result);
4015 void FullCodeGenerator::EmitStringAdd(CallRuntime* expr) {
4016 ZoneList<Expression*>* args = expr->arguments();
4017 DCHECK_EQ(2, args->length());
4018 VisitForStackValue(args->at(0));
4019 VisitForAccumulatorValue(args->at(1));
4022 StringAddStub stub(isolate(), STRING_ADD_CHECK_BOTH, NOT_TENURED);
4024 context()->Plug(eax);
4028 void FullCodeGenerator::EmitStringCompare(CallRuntime* expr) {
4029 ZoneList<Expression*>* args = expr->arguments();
4030 DCHECK_EQ(2, args->length());
4032 VisitForStackValue(args->at(0));
4033 VisitForStackValue(args->at(1));
4035 StringCompareStub stub(isolate());
4037 context()->Plug(eax);
4041 void FullCodeGenerator::EmitCallFunction(CallRuntime* expr) {
4042 ZoneList<Expression*>* args = expr->arguments();
4043 DCHECK(args->length() >= 2);
4045 int arg_count = args->length() - 2; // 2 ~ receiver and function.
4046 for (int i = 0; i < arg_count + 1; ++i) {
4047 VisitForStackValue(args->at(i));
4049 VisitForAccumulatorValue(args->last()); // Function.
4051 Label runtime, done;
4052 // Check for non-function argument (including proxy).
4053 __ JumpIfSmi(eax, &runtime);
4054 __ CmpObjectType(eax, JS_FUNCTION_TYPE, ebx);
4055 __ j(not_equal, &runtime);
4057 // InvokeFunction requires the function in edi. Move it in there.
4058 __ mov(edi, result_register());
4059 ParameterCount count(arg_count);
4060 __ InvokeFunction(edi, count, CALL_FUNCTION, NullCallWrapper());
4061 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4066 __ CallRuntime(Runtime::kCall, args->length());
4069 context()->Plug(eax);
4073 void FullCodeGenerator::EmitDefaultConstructorCallSuper(CallRuntime* expr) {
4074 Variable* new_target_var = scope()->DeclarationScope()->new_target_var();
4075 GetVar(eax, new_target_var);
4078 EmitLoadSuperConstructor();
4079 __ push(result_register());
4081 // Check if the calling frame is an arguments adaptor frame.
4082 Label adaptor_frame, args_set_up, runtime;
4083 __ mov(edx, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
4084 __ mov(ecx, Operand(edx, StandardFrameConstants::kContextOffset));
4085 __ cmp(ecx, Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
4086 __ j(equal, &adaptor_frame);
4087 // default constructor has no arguments, so no adaptor frame means no args.
4088 __ mov(eax, Immediate(0));
4089 __ jmp(&args_set_up);
4091 // Copy arguments from adaptor frame.
4093 __ bind(&adaptor_frame);
4094 __ mov(ecx, Operand(edx, ArgumentsAdaptorFrameConstants::kLengthOffset));
4097 // Subtract 1 from arguments count, for new.target.
4098 __ sub(ecx, Immediate(1));
4100 __ lea(edx, Operand(edx, ecx, times_pointer_size,
4101 StandardFrameConstants::kCallerSPOffset));
4104 __ push(Operand(edx, -1 * kPointerSize));
4105 __ sub(edx, Immediate(kPointerSize));
4107 __ j(not_zero, &loop);
4110 __ bind(&args_set_up);
4112 __ mov(edi, Operand(esp, eax, times_pointer_size, 0));
4113 __ mov(ebx, Immediate(isolate()->factory()->undefined_value()));
4114 CallConstructStub stub(isolate(), SUPER_CONSTRUCTOR_CALL);
4115 __ call(stub.GetCode(), RelocInfo::CONSTRUCT_CALL);
4119 context()->Plug(eax);
4123 void FullCodeGenerator::EmitRegExpConstructResult(CallRuntime* expr) {
4124 // Load the arguments on the stack and call the stub.
4125 RegExpConstructResultStub stub(isolate());
4126 ZoneList<Expression*>* args = expr->arguments();
4127 DCHECK(args->length() == 3);
4128 VisitForStackValue(args->at(0));
4129 VisitForStackValue(args->at(1));
4130 VisitForAccumulatorValue(args->at(2));
4134 context()->Plug(eax);
4138 void FullCodeGenerator::EmitGetFromCache(CallRuntime* expr) {
4139 ZoneList<Expression*>* args = expr->arguments();
4140 DCHECK_EQ(2, args->length());
4142 DCHECK_NOT_NULL(args->at(0)->AsLiteral());
4143 int cache_id = Smi::cast(*(args->at(0)->AsLiteral()->value()))->value();
4145 Handle<FixedArray> jsfunction_result_caches(
4146 isolate()->native_context()->jsfunction_result_caches());
4147 if (jsfunction_result_caches->length() <= cache_id) {
4148 __ Abort(kAttemptToUseUndefinedCache);
4149 __ mov(eax, isolate()->factory()->undefined_value());
4150 context()->Plug(eax);
4154 VisitForAccumulatorValue(args->at(1));
4157 Register cache = ebx;
4159 __ mov(cache, ContextOperand(esi, Context::GLOBAL_OBJECT_INDEX));
4161 FieldOperand(cache, GlobalObject::kNativeContextOffset));
4162 __ mov(cache, ContextOperand(cache, Context::JSFUNCTION_RESULT_CACHES_INDEX));
4164 FieldOperand(cache, FixedArray::OffsetOfElementAt(cache_id)));
4166 Label done, not_found;
4167 STATIC_ASSERT(kSmiTag == 0 && kSmiTagSize == 1);
4168 __ mov(tmp, FieldOperand(cache, JSFunctionResultCache::kFingerOffset));
4169 // tmp now holds finger offset as a smi.
4170 __ cmp(key, FixedArrayElementOperand(cache, tmp));
4171 __ j(not_equal, ¬_found);
4173 __ mov(eax, FixedArrayElementOperand(cache, tmp, 1));
4176 __ bind(¬_found);
4177 // Call runtime to perform the lookup.
4180 __ CallRuntime(Runtime::kGetFromCache, 2);
4183 context()->Plug(eax);
4187 void FullCodeGenerator::EmitHasCachedArrayIndex(CallRuntime* expr) {
4188 ZoneList<Expression*>* args = expr->arguments();
4189 DCHECK(args->length() == 1);
4191 VisitForAccumulatorValue(args->at(0));
4193 __ AssertString(eax);
4195 Label materialize_true, materialize_false;
4196 Label* if_true = NULL;
4197 Label* if_false = NULL;
4198 Label* fall_through = NULL;
4199 context()->PrepareTest(&materialize_true, &materialize_false,
4200 &if_true, &if_false, &fall_through);
4202 __ test(FieldOperand(eax, String::kHashFieldOffset),
4203 Immediate(String::kContainsCachedArrayIndexMask));
4204 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
4205 Split(zero, if_true, if_false, fall_through);
4207 context()->Plug(if_true, if_false);
4211 void FullCodeGenerator::EmitGetCachedArrayIndex(CallRuntime* expr) {
4212 ZoneList<Expression*>* args = expr->arguments();
4213 DCHECK(args->length() == 1);
4214 VisitForAccumulatorValue(args->at(0));
4216 __ AssertString(eax);
4218 __ mov(eax, FieldOperand(eax, String::kHashFieldOffset));
4219 __ IndexFromHash(eax, eax);
4221 context()->Plug(eax);
4225 void FullCodeGenerator::EmitFastOneByteArrayJoin(CallRuntime* expr) {
4226 Label bailout, done, one_char_separator, long_separator,
4227 non_trivial_array, not_size_one_array, loop,
4228 loop_1, loop_1_condition, loop_2, loop_2_entry, loop_3, loop_3_entry;
4230 ZoneList<Expression*>* args = expr->arguments();
4231 DCHECK(args->length() == 2);
4232 // We will leave the separator on the stack until the end of the function.
4233 VisitForStackValue(args->at(1));
4234 // Load this to eax (= array)
4235 VisitForAccumulatorValue(args->at(0));
4236 // All aliases of the same register have disjoint lifetimes.
4237 Register array = eax;
4238 Register elements = no_reg; // Will be eax.
4240 Register index = edx;
4242 Register string_length = ecx;
4244 Register string = esi;
4246 Register scratch = ebx;
4248 Register array_length = edi;
4249 Register result_pos = no_reg; // Will be edi.
4251 // Separator operand is already pushed.
4252 Operand separator_operand = Operand(esp, 2 * kPointerSize);
4253 Operand result_operand = Operand(esp, 1 * kPointerSize);
4254 Operand array_length_operand = Operand(esp, 0);
4255 __ sub(esp, Immediate(2 * kPointerSize));
4257 // Check that the array is a JSArray
4258 __ JumpIfSmi(array, &bailout);
4259 __ CmpObjectType(array, JS_ARRAY_TYPE, scratch);
4260 __ j(not_equal, &bailout);
4262 // Check that the array has fast elements.
4263 __ CheckFastElements(scratch, &bailout);
4265 // If the array has length zero, return the empty string.
4266 __ mov(array_length, FieldOperand(array, JSArray::kLengthOffset));
4267 __ SmiUntag(array_length);
4268 __ j(not_zero, &non_trivial_array);
4269 __ mov(result_operand, isolate()->factory()->empty_string());
4272 // Save the array length.
4273 __ bind(&non_trivial_array);
4274 __ mov(array_length_operand, array_length);
4276 // Save the FixedArray containing array's elements.
4277 // End of array's live range.
4279 __ mov(elements, FieldOperand(array, JSArray::kElementsOffset));
4283 // Check that all array elements are sequential one-byte strings, and
4284 // accumulate the sum of their lengths, as a smi-encoded value.
4285 __ Move(index, Immediate(0));
4286 __ Move(string_length, Immediate(0));
4287 // Loop condition: while (index < length).
4288 // Live loop registers: index, array_length, string,
4289 // scratch, string_length, elements.
4290 if (generate_debug_code_) {
4291 __ cmp(index, array_length);
4292 __ Assert(less, kNoEmptyArraysHereInEmitFastOneByteArrayJoin);
4295 __ mov(string, FieldOperand(elements,
4298 FixedArray::kHeaderSize));
4299 __ JumpIfSmi(string, &bailout);
4300 __ mov(scratch, FieldOperand(string, HeapObject::kMapOffset));
4301 __ movzx_b(scratch, FieldOperand(scratch, Map::kInstanceTypeOffset));
4302 __ and_(scratch, Immediate(
4303 kIsNotStringMask | kStringEncodingMask | kStringRepresentationMask));
4304 __ cmp(scratch, kStringTag | kOneByteStringTag | kSeqStringTag);
4305 __ j(not_equal, &bailout);
4306 __ add(string_length,
4307 FieldOperand(string, SeqOneByteString::kLengthOffset));
4308 __ j(overflow, &bailout);
4309 __ add(index, Immediate(1));
4310 __ cmp(index, array_length);
4313 // If array_length is 1, return elements[0], a string.
4314 __ cmp(array_length, 1);
4315 __ j(not_equal, ¬_size_one_array);
4316 __ mov(scratch, FieldOperand(elements, FixedArray::kHeaderSize));
4317 __ mov(result_operand, scratch);
4320 __ bind(¬_size_one_array);
4322 // End of array_length live range.
4323 result_pos = array_length;
4324 array_length = no_reg;
4327 // string_length: Sum of string lengths, as a smi.
4328 // elements: FixedArray of strings.
4330 // Check that the separator is a flat one-byte string.
4331 __ mov(string, separator_operand);
4332 __ JumpIfSmi(string, &bailout);
4333 __ mov(scratch, FieldOperand(string, HeapObject::kMapOffset));
4334 __ movzx_b(scratch, FieldOperand(scratch, Map::kInstanceTypeOffset));
4335 __ and_(scratch, Immediate(
4336 kIsNotStringMask | kStringEncodingMask | kStringRepresentationMask));
4337 __ cmp(scratch, kStringTag | kOneByteStringTag | kSeqStringTag);
4338 __ j(not_equal, &bailout);
4340 // Add (separator length times array_length) - separator length
4341 // to string_length.
4342 __ mov(scratch, separator_operand);
4343 __ mov(scratch, FieldOperand(scratch, SeqOneByteString::kLengthOffset));
4344 __ sub(string_length, scratch); // May be negative, temporarily.
4345 __ imul(scratch, array_length_operand);
4346 __ j(overflow, &bailout);
4347 __ add(string_length, scratch);
4348 __ j(overflow, &bailout);
4350 __ shr(string_length, 1);
4351 // Live registers and stack values:
4354 __ AllocateOneByteString(result_pos, string_length, scratch, index, string,
4356 __ mov(result_operand, result_pos);
4357 __ lea(result_pos, FieldOperand(result_pos, SeqOneByteString::kHeaderSize));
4360 __ mov(string, separator_operand);
4361 __ cmp(FieldOperand(string, SeqOneByteString::kLengthOffset),
4362 Immediate(Smi::FromInt(1)));
4363 __ j(equal, &one_char_separator);
4364 __ j(greater, &long_separator);
4367 // Empty separator case
4368 __ mov(index, Immediate(0));
4369 __ jmp(&loop_1_condition);
4370 // Loop condition: while (index < length).
4372 // Each iteration of the loop concatenates one string to the result.
4373 // Live values in registers:
4374 // index: which element of the elements array we are adding to the result.
4375 // result_pos: the position to which we are currently copying characters.
4376 // elements: the FixedArray of strings we are joining.
4378 // Get string = array[index].
4379 __ mov(string, FieldOperand(elements, index,
4381 FixedArray::kHeaderSize));
4382 __ mov(string_length,
4383 FieldOperand(string, String::kLengthOffset));
4384 __ shr(string_length, 1);
4386 FieldOperand(string, SeqOneByteString::kHeaderSize));
4387 __ CopyBytes(string, result_pos, string_length, scratch);
4388 __ add(index, Immediate(1));
4389 __ bind(&loop_1_condition);
4390 __ cmp(index, array_length_operand);
4391 __ j(less, &loop_1); // End while (index < length).
4396 // One-character separator case
4397 __ bind(&one_char_separator);
4398 // Replace separator with its one-byte character value.
4399 __ mov_b(scratch, FieldOperand(string, SeqOneByteString::kHeaderSize));
4400 __ mov_b(separator_operand, scratch);
4402 __ Move(index, Immediate(0));
4403 // Jump into the loop after the code that copies the separator, so the first
4404 // element is not preceded by a separator
4405 __ jmp(&loop_2_entry);
4406 // Loop condition: while (index < length).
4408 // Each iteration of the loop concatenates one string to the result.
4409 // Live values in registers:
4410 // index: which element of the elements array we are adding to the result.
4411 // result_pos: the position to which we are currently copying characters.
4413 // Copy the separator character to the result.
4414 __ mov_b(scratch, separator_operand);
4415 __ mov_b(Operand(result_pos, 0), scratch);
4418 __ bind(&loop_2_entry);
4419 // Get string = array[index].
4420 __ mov(string, FieldOperand(elements, index,
4422 FixedArray::kHeaderSize));
4423 __ mov(string_length,
4424 FieldOperand(string, String::kLengthOffset));
4425 __ shr(string_length, 1);
4427 FieldOperand(string, SeqOneByteString::kHeaderSize));
4428 __ CopyBytes(string, result_pos, string_length, scratch);
4429 __ add(index, Immediate(1));
4431 __ cmp(index, array_length_operand);
4432 __ j(less, &loop_2); // End while (index < length).
4436 // Long separator case (separator is more than one character).
4437 __ bind(&long_separator);
4439 __ Move(index, Immediate(0));
4440 // Jump into the loop after the code that copies the separator, so the first
4441 // element is not preceded by a separator
4442 __ jmp(&loop_3_entry);
4443 // Loop condition: while (index < length).
4445 // Each iteration of the loop concatenates one string to the result.
4446 // Live values in registers:
4447 // index: which element of the elements array we are adding to the result.
4448 // result_pos: the position to which we are currently copying characters.
4450 // Copy the separator to the result.
4451 __ mov(string, separator_operand);
4452 __ mov(string_length,
4453 FieldOperand(string, String::kLengthOffset));
4454 __ shr(string_length, 1);
4456 FieldOperand(string, SeqOneByteString::kHeaderSize));
4457 __ CopyBytes(string, result_pos, string_length, scratch);
4459 __ bind(&loop_3_entry);
4460 // Get string = array[index].
4461 __ mov(string, FieldOperand(elements, index,
4463 FixedArray::kHeaderSize));
4464 __ mov(string_length,
4465 FieldOperand(string, String::kLengthOffset));
4466 __ shr(string_length, 1);
4468 FieldOperand(string, SeqOneByteString::kHeaderSize));
4469 __ CopyBytes(string, result_pos, string_length, scratch);
4470 __ add(index, Immediate(1));
4472 __ cmp(index, array_length_operand);
4473 __ j(less, &loop_3); // End while (index < length).
4478 __ mov(result_operand, isolate()->factory()->undefined_value());
4480 __ mov(eax, result_operand);
4481 // Drop temp values from the stack, and restore context register.
4482 __ add(esp, Immediate(3 * kPointerSize));
4484 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4485 context()->Plug(eax);
4489 void FullCodeGenerator::EmitDebugIsActive(CallRuntime* expr) {
4490 DCHECK(expr->arguments()->length() == 0);
4491 ExternalReference debug_is_active =
4492 ExternalReference::debug_is_active_address(isolate());
4493 __ movzx_b(eax, Operand::StaticVariable(debug_is_active));
4495 context()->Plug(eax);
4499 void FullCodeGenerator::VisitCallRuntime(CallRuntime* expr) {
4500 if (expr->function() != NULL &&
4501 expr->function()->intrinsic_type == Runtime::INLINE) {
4502 Comment cmnt(masm_, "[ InlineRuntimeCall");
4503 EmitInlineRuntimeCall(expr);
4507 Comment cmnt(masm_, "[ CallRuntime");
4508 ZoneList<Expression*>* args = expr->arguments();
4510 if (expr->is_jsruntime()) {
4511 // Push the builtins object as receiver.
4512 __ mov(eax, GlobalObjectOperand());
4513 __ push(FieldOperand(eax, GlobalObject::kBuiltinsOffset));
4515 // Load the function from the receiver.
4516 __ mov(LoadDescriptor::ReceiverRegister(), Operand(esp, 0));
4517 __ mov(LoadDescriptor::NameRegister(), Immediate(expr->name()));
4518 if (FLAG_vector_ics) {
4519 __ mov(VectorLoadICDescriptor::SlotRegister(),
4520 Immediate(SmiFromSlot(expr->CallRuntimeFeedbackSlot())));
4521 CallLoadIC(NOT_CONTEXTUAL);
4523 CallLoadIC(NOT_CONTEXTUAL, expr->CallRuntimeFeedbackId());
4526 // Push the target function under the receiver.
4527 __ push(Operand(esp, 0));
4528 __ mov(Operand(esp, kPointerSize), eax);
4530 // Code common for calls using the IC.
4531 ZoneList<Expression*>* args = expr->arguments();
4532 int arg_count = args->length();
4533 for (int i = 0; i < arg_count; i++) {
4534 VisitForStackValue(args->at(i));
4537 // Record source position of the IC call.
4538 SetSourcePosition(expr->position());
4539 CallFunctionStub stub(isolate(), arg_count, NO_CALL_FUNCTION_FLAGS);
4540 __ mov(edi, Operand(esp, (arg_count + 1) * kPointerSize));
4542 // Restore context register.
4543 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4544 context()->DropAndPlug(1, eax);
4547 // Push the arguments ("left-to-right").
4548 int arg_count = args->length();
4549 for (int i = 0; i < arg_count; i++) {
4550 VisitForStackValue(args->at(i));
4553 // Call the C runtime function.
4554 __ CallRuntime(expr->function(), arg_count);
4556 context()->Plug(eax);
4561 void FullCodeGenerator::VisitUnaryOperation(UnaryOperation* expr) {
4562 switch (expr->op()) {
4563 case Token::DELETE: {
4564 Comment cmnt(masm_, "[ UnaryOperation (DELETE)");
4565 Property* property = expr->expression()->AsProperty();
4566 VariableProxy* proxy = expr->expression()->AsVariableProxy();
4568 if (property != NULL) {
4569 VisitForStackValue(property->obj());
4570 VisitForStackValue(property->key());
4571 __ push(Immediate(Smi::FromInt(language_mode())));
4572 __ InvokeBuiltin(Builtins::DELETE, CALL_FUNCTION);
4573 context()->Plug(eax);
4574 } else if (proxy != NULL) {
4575 Variable* var = proxy->var();
4576 // Delete of an unqualified identifier is disallowed in strict mode
4577 // but "delete this" is allowed.
4578 DCHECK(is_sloppy(language_mode()) || var->is_this());
4579 if (var->IsUnallocated()) {
4580 __ push(GlobalObjectOperand());
4581 __ push(Immediate(var->name()));
4582 __ push(Immediate(Smi::FromInt(SLOPPY)));
4583 __ InvokeBuiltin(Builtins::DELETE, CALL_FUNCTION);
4584 context()->Plug(eax);
4585 } else if (var->IsStackAllocated() || var->IsContextSlot()) {
4586 // Result of deleting non-global variables is false. 'this' is
4587 // not really a variable, though we implement it as one. The
4588 // subexpression does not have side effects.
4589 context()->Plug(var->is_this());
4591 // Non-global variable. Call the runtime to try to delete from the
4592 // context where the variable was introduced.
4593 __ push(context_register());
4594 __ push(Immediate(var->name()));
4595 __ CallRuntime(Runtime::kDeleteLookupSlot, 2);
4596 context()->Plug(eax);
4599 // Result of deleting non-property, non-variable reference is true.
4600 // The subexpression may have side effects.
4601 VisitForEffect(expr->expression());
4602 context()->Plug(true);
4608 Comment cmnt(masm_, "[ UnaryOperation (VOID)");
4609 VisitForEffect(expr->expression());
4610 context()->Plug(isolate()->factory()->undefined_value());
4615 Comment cmnt(masm_, "[ UnaryOperation (NOT)");
4616 if (context()->IsEffect()) {
4617 // Unary NOT has no side effects so it's only necessary to visit the
4618 // subexpression. Match the optimizing compiler by not branching.
4619 VisitForEffect(expr->expression());
4620 } else if (context()->IsTest()) {
4621 const TestContext* test = TestContext::cast(context());
4622 // The labels are swapped for the recursive call.
4623 VisitForControl(expr->expression(),
4624 test->false_label(),
4626 test->fall_through());
4627 context()->Plug(test->true_label(), test->false_label());
4629 // We handle value contexts explicitly rather than simply visiting
4630 // for control and plugging the control flow into the context,
4631 // because we need to prepare a pair of extra administrative AST ids
4632 // for the optimizing compiler.
4633 DCHECK(context()->IsAccumulatorValue() || context()->IsStackValue());
4634 Label materialize_true, materialize_false, done;
4635 VisitForControl(expr->expression(),
4639 __ bind(&materialize_true);
4640 PrepareForBailoutForId(expr->MaterializeTrueId(), NO_REGISTERS);
4641 if (context()->IsAccumulatorValue()) {
4642 __ mov(eax, isolate()->factory()->true_value());
4644 __ Push(isolate()->factory()->true_value());
4646 __ jmp(&done, Label::kNear);
4647 __ bind(&materialize_false);
4648 PrepareForBailoutForId(expr->MaterializeFalseId(), NO_REGISTERS);
4649 if (context()->IsAccumulatorValue()) {
4650 __ mov(eax, isolate()->factory()->false_value());
4652 __ Push(isolate()->factory()->false_value());
4659 case Token::TYPEOF: {
4660 Comment cmnt(masm_, "[ UnaryOperation (TYPEOF)");
4661 { StackValueContext context(this);
4662 VisitForTypeofValue(expr->expression());
4664 __ CallRuntime(Runtime::kTypeof, 1);
4665 context()->Plug(eax);
4675 void FullCodeGenerator::VisitCountOperation(CountOperation* expr) {
4676 DCHECK(expr->expression()->IsValidReferenceExpression());
4678 Comment cmnt(masm_, "[ CountOperation");
4679 SetSourcePosition(expr->position());
4681 Property* prop = expr->expression()->AsProperty();
4682 LhsKind assign_type = GetAssignType(prop);
4684 // Evaluate expression and get value.
4685 if (assign_type == VARIABLE) {
4686 DCHECK(expr->expression()->AsVariableProxy()->var() != NULL);
4687 AccumulatorValueContext context(this);
4688 EmitVariableLoad(expr->expression()->AsVariableProxy());
4690 // Reserve space for result of postfix operation.
4691 if (expr->is_postfix() && !context()->IsEffect()) {
4692 __ push(Immediate(Smi::FromInt(0)));
4694 switch (assign_type) {
4695 case NAMED_PROPERTY: {
4696 // Put the object both on the stack and in the register.
4697 VisitForStackValue(prop->obj());
4698 __ mov(LoadDescriptor::ReceiverRegister(), Operand(esp, 0));
4699 EmitNamedPropertyLoad(prop);
4703 case NAMED_SUPER_PROPERTY: {
4704 VisitForStackValue(prop->obj()->AsSuperReference()->this_var());
4705 EmitLoadHomeObject(prop->obj()->AsSuperReference());
4706 __ push(result_register());
4707 __ push(MemOperand(esp, kPointerSize));
4708 __ push(result_register());
4709 EmitNamedSuperPropertyLoad(prop);
4713 case KEYED_SUPER_PROPERTY: {
4714 VisitForStackValue(prop->obj()->AsSuperReference()->this_var());
4715 EmitLoadHomeObject(prop->obj()->AsSuperReference());
4716 __ push(result_register());
4717 VisitForAccumulatorValue(prop->key());
4718 __ push(result_register());
4719 __ push(MemOperand(esp, 2 * kPointerSize));
4720 __ push(MemOperand(esp, 2 * kPointerSize));
4721 __ push(result_register());
4722 EmitKeyedSuperPropertyLoad(prop);
4726 case KEYED_PROPERTY: {
4727 VisitForStackValue(prop->obj());
4728 VisitForStackValue(prop->key());
4729 __ mov(LoadDescriptor::ReceiverRegister(),
4730 Operand(esp, kPointerSize)); // Object.
4731 __ mov(LoadDescriptor::NameRegister(), Operand(esp, 0)); // Key.
4732 EmitKeyedPropertyLoad(prop);
4741 // We need a second deoptimization point after loading the value
4742 // in case evaluating the property load my have a side effect.
4743 if (assign_type == VARIABLE) {
4744 PrepareForBailout(expr->expression(), TOS_REG);
4746 PrepareForBailoutForId(prop->LoadId(), TOS_REG);
4749 // Inline smi case if we are in a loop.
4750 Label done, stub_call;
4751 JumpPatchSite patch_site(masm_);
4752 if (ShouldInlineSmiCase(expr->op())) {
4754 patch_site.EmitJumpIfNotSmi(eax, &slow, Label::kNear);
4756 // Save result for postfix expressions.
4757 if (expr->is_postfix()) {
4758 if (!context()->IsEffect()) {
4759 // Save the result on the stack. If we have a named or keyed property
4760 // we store the result under the receiver that is currently on top
4762 switch (assign_type) {
4766 case NAMED_PROPERTY:
4767 __ mov(Operand(esp, kPointerSize), eax);
4769 case NAMED_SUPER_PROPERTY:
4770 __ mov(Operand(esp, 2 * kPointerSize), eax);
4772 case KEYED_PROPERTY:
4773 __ mov(Operand(esp, 2 * kPointerSize), eax);
4775 case KEYED_SUPER_PROPERTY:
4776 __ mov(Operand(esp, 3 * kPointerSize), eax);
4782 if (expr->op() == Token::INC) {
4783 __ add(eax, Immediate(Smi::FromInt(1)));
4785 __ sub(eax, Immediate(Smi::FromInt(1)));
4787 __ j(no_overflow, &done, Label::kNear);
4788 // Call stub. Undo operation first.
4789 if (expr->op() == Token::INC) {
4790 __ sub(eax, Immediate(Smi::FromInt(1)));
4792 __ add(eax, Immediate(Smi::FromInt(1)));
4794 __ jmp(&stub_call, Label::kNear);
4797 ToNumberStub convert_stub(isolate());
4798 __ CallStub(&convert_stub);
4799 PrepareForBailoutForId(expr->ToNumberId(), TOS_REG);
4801 // Save result for postfix expressions.
4802 if (expr->is_postfix()) {
4803 if (!context()->IsEffect()) {
4804 // Save the result on the stack. If we have a named or keyed property
4805 // we store the result under the receiver that is currently on top
4807 switch (assign_type) {
4811 case NAMED_PROPERTY:
4812 __ mov(Operand(esp, kPointerSize), eax);
4814 case NAMED_SUPER_PROPERTY:
4815 __ mov(Operand(esp, 2 * kPointerSize), eax);
4817 case KEYED_PROPERTY:
4818 __ mov(Operand(esp, 2 * kPointerSize), eax);
4820 case KEYED_SUPER_PROPERTY:
4821 __ mov(Operand(esp, 3 * kPointerSize), eax);
4827 // Record position before stub call.
4828 SetSourcePosition(expr->position());
4830 // Call stub for +1/-1.
4831 __ bind(&stub_call);
4833 __ mov(eax, Immediate(Smi::FromInt(1)));
4835 CodeFactory::BinaryOpIC(isolate(), expr->binary_op()).code();
4836 CallIC(code, expr->CountBinOpFeedbackId());
4837 patch_site.EmitPatchInfo();
4840 // Store the value returned in eax.
4841 switch (assign_type) {
4843 if (expr->is_postfix()) {
4844 // Perform the assignment as if via '='.
4845 { EffectContext context(this);
4846 EmitVariableAssignment(expr->expression()->AsVariableProxy()->var(),
4848 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
4851 // For all contexts except EffectContext We have the result on
4852 // top of the stack.
4853 if (!context()->IsEffect()) {
4854 context()->PlugTOS();
4857 // Perform the assignment as if via '='.
4858 EmitVariableAssignment(expr->expression()->AsVariableProxy()->var(),
4860 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
4861 context()->Plug(eax);
4864 case NAMED_PROPERTY: {
4865 __ mov(StoreDescriptor::NameRegister(),
4866 prop->key()->AsLiteral()->value());
4867 __ pop(StoreDescriptor::ReceiverRegister());
4868 CallStoreIC(expr->CountStoreFeedbackId());
4869 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
4870 if (expr->is_postfix()) {
4871 if (!context()->IsEffect()) {
4872 context()->PlugTOS();
4875 context()->Plug(eax);
4879 case NAMED_SUPER_PROPERTY: {
4880 EmitNamedSuperPropertyStore(prop);
4881 if (expr->is_postfix()) {
4882 if (!context()->IsEffect()) {
4883 context()->PlugTOS();
4886 context()->Plug(eax);
4890 case KEYED_SUPER_PROPERTY: {
4891 EmitKeyedSuperPropertyStore(prop);
4892 if (expr->is_postfix()) {
4893 if (!context()->IsEffect()) {
4894 context()->PlugTOS();
4897 context()->Plug(eax);
4901 case KEYED_PROPERTY: {
4902 __ pop(StoreDescriptor::NameRegister());
4903 __ pop(StoreDescriptor::ReceiverRegister());
4905 CodeFactory::KeyedStoreIC(isolate(), language_mode()).code();
4906 CallIC(ic, expr->CountStoreFeedbackId());
4907 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
4908 if (expr->is_postfix()) {
4909 // Result is on the stack
4910 if (!context()->IsEffect()) {
4911 context()->PlugTOS();
4914 context()->Plug(eax);
4922 void FullCodeGenerator::VisitForTypeofValue(Expression* expr) {
4923 VariableProxy* proxy = expr->AsVariableProxy();
4924 DCHECK(!context()->IsEffect());
4925 DCHECK(!context()->IsTest());
4927 if (proxy != NULL && proxy->var()->IsUnallocated()) {
4928 Comment cmnt(masm_, "[ Global variable");
4929 __ mov(LoadDescriptor::ReceiverRegister(), GlobalObjectOperand());
4930 __ mov(LoadDescriptor::NameRegister(), Immediate(proxy->name()));
4931 if (FLAG_vector_ics) {
4932 __ mov(VectorLoadICDescriptor::SlotRegister(),
4933 Immediate(SmiFromSlot(proxy->VariableFeedbackSlot())));
4935 // Use a regular load, not a contextual load, to avoid a reference
4937 CallLoadIC(NOT_CONTEXTUAL);
4938 PrepareForBailout(expr, TOS_REG);
4939 context()->Plug(eax);
4940 } else if (proxy != NULL && proxy->var()->IsLookupSlot()) {
4941 Comment cmnt(masm_, "[ Lookup slot");
4944 // Generate code for loading from variables potentially shadowed
4945 // by eval-introduced variables.
4946 EmitDynamicLookupFastCase(proxy, INSIDE_TYPEOF, &slow, &done);
4950 __ push(Immediate(proxy->name()));
4951 __ CallRuntime(Runtime::kLoadLookupSlotNoReferenceError, 2);
4952 PrepareForBailout(expr, TOS_REG);
4955 context()->Plug(eax);
4957 // This expression cannot throw a reference error at the top level.
4958 VisitInDuplicateContext(expr);
4963 void FullCodeGenerator::EmitLiteralCompareTypeof(Expression* expr,
4964 Expression* sub_expr,
4965 Handle<String> check) {
4966 Label materialize_true, materialize_false;
4967 Label* if_true = NULL;
4968 Label* if_false = NULL;
4969 Label* fall_through = NULL;
4970 context()->PrepareTest(&materialize_true, &materialize_false,
4971 &if_true, &if_false, &fall_through);
4973 { AccumulatorValueContext context(this);
4974 VisitForTypeofValue(sub_expr);
4976 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
4978 Factory* factory = isolate()->factory();
4979 if (String::Equals(check, factory->number_string())) {
4980 __ JumpIfSmi(eax, if_true);
4981 __ cmp(FieldOperand(eax, HeapObject::kMapOffset),
4982 isolate()->factory()->heap_number_map());
4983 Split(equal, if_true, if_false, fall_through);
4984 } else if (String::Equals(check, factory->string_string())) {
4985 __ JumpIfSmi(eax, if_false);
4986 __ CmpObjectType(eax, FIRST_NONSTRING_TYPE, edx);
4987 __ j(above_equal, if_false);
4988 // Check for undetectable objects => false.
4989 __ test_b(FieldOperand(edx, Map::kBitFieldOffset),
4990 1 << Map::kIsUndetectable);
4991 Split(zero, if_true, if_false, fall_through);
4992 } else if (String::Equals(check, factory->symbol_string())) {
4993 __ JumpIfSmi(eax, if_false);
4994 __ CmpObjectType(eax, SYMBOL_TYPE, edx);
4995 Split(equal, if_true, if_false, fall_through);
4996 } else if (String::Equals(check, factory->boolean_string())) {
4997 __ cmp(eax, isolate()->factory()->true_value());
4998 __ j(equal, if_true);
4999 __ cmp(eax, isolate()->factory()->false_value());
5000 Split(equal, if_true, if_false, fall_through);
5001 } else if (String::Equals(check, factory->undefined_string())) {
5002 __ cmp(eax, isolate()->factory()->undefined_value());
5003 __ j(equal, if_true);
5004 __ JumpIfSmi(eax, if_false);
5005 // Check for undetectable objects => true.
5006 __ mov(edx, FieldOperand(eax, HeapObject::kMapOffset));
5007 __ movzx_b(ecx, FieldOperand(edx, Map::kBitFieldOffset));
5008 __ test(ecx, Immediate(1 << Map::kIsUndetectable));
5009 Split(not_zero, if_true, if_false, fall_through);
5010 } else if (String::Equals(check, factory->function_string())) {
5011 __ JumpIfSmi(eax, if_false);
5012 STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
5013 __ CmpObjectType(eax, JS_FUNCTION_TYPE, edx);
5014 __ j(equal, if_true);
5015 __ CmpInstanceType(edx, JS_FUNCTION_PROXY_TYPE);
5016 Split(equal, if_true, if_false, fall_through);
5017 } else if (String::Equals(check, factory->object_string())) {
5018 __ JumpIfSmi(eax, if_false);
5019 __ cmp(eax, isolate()->factory()->null_value());
5020 __ j(equal, if_true);
5021 __ CmpObjectType(eax, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE, edx);
5022 __ j(below, if_false);
5023 __ CmpInstanceType(edx, LAST_NONCALLABLE_SPEC_OBJECT_TYPE);
5024 __ j(above, if_false);
5025 // Check for undetectable objects => false.
5026 __ test_b(FieldOperand(edx, Map::kBitFieldOffset),
5027 1 << Map::kIsUndetectable);
5028 Split(zero, if_true, if_false, fall_through);
5030 if (if_false != fall_through) __ jmp(if_false);
5032 context()->Plug(if_true, if_false);
5036 void FullCodeGenerator::VisitCompareOperation(CompareOperation* expr) {
5037 Comment cmnt(masm_, "[ CompareOperation");
5038 SetSourcePosition(expr->position());
5040 // First we try a fast inlined version of the compare when one of
5041 // the operands is a literal.
5042 if (TryLiteralCompare(expr)) return;
5044 // Always perform the comparison for its control flow. Pack the result
5045 // into the expression's context after the comparison is performed.
5046 Label materialize_true, materialize_false;
5047 Label* if_true = NULL;
5048 Label* if_false = NULL;
5049 Label* fall_through = NULL;
5050 context()->PrepareTest(&materialize_true, &materialize_false,
5051 &if_true, &if_false, &fall_through);
5053 Token::Value op = expr->op();
5054 VisitForStackValue(expr->left());
5057 VisitForStackValue(expr->right());
5058 __ InvokeBuiltin(Builtins::IN, CALL_FUNCTION);
5059 PrepareForBailoutBeforeSplit(expr, false, NULL, NULL);
5060 __ cmp(eax, isolate()->factory()->true_value());
5061 Split(equal, if_true, if_false, fall_through);
5064 case Token::INSTANCEOF: {
5065 VisitForStackValue(expr->right());
5066 InstanceofStub stub(isolate(), InstanceofStub::kNoFlags);
5068 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
5070 // The stub returns 0 for true.
5071 Split(zero, if_true, if_false, fall_through);
5076 VisitForAccumulatorValue(expr->right());
5077 Condition cc = CompareIC::ComputeCondition(op);
5080 bool inline_smi_code = ShouldInlineSmiCase(op);
5081 JumpPatchSite patch_site(masm_);
5082 if (inline_smi_code) {
5086 patch_site.EmitJumpIfNotSmi(ecx, &slow_case, Label::kNear);
5088 Split(cc, if_true, if_false, NULL);
5089 __ bind(&slow_case);
5092 // Record position and call the compare IC.
5093 SetSourcePosition(expr->position());
5094 Handle<Code> ic = CodeFactory::CompareIC(isolate(), op).code();
5095 CallIC(ic, expr->CompareOperationFeedbackId());
5096 patch_site.EmitPatchInfo();
5098 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
5100 Split(cc, if_true, if_false, fall_through);
5104 // Convert the result of the comparison into one expected for this
5105 // expression's context.
5106 context()->Plug(if_true, if_false);
5110 void FullCodeGenerator::EmitLiteralCompareNil(CompareOperation* expr,
5111 Expression* sub_expr,
5113 Label materialize_true, materialize_false;
5114 Label* if_true = NULL;
5115 Label* if_false = NULL;
5116 Label* fall_through = NULL;
5117 context()->PrepareTest(&materialize_true, &materialize_false,
5118 &if_true, &if_false, &fall_through);
5120 VisitForAccumulatorValue(sub_expr);
5121 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
5123 Handle<Object> nil_value = nil == kNullValue
5124 ? isolate()->factory()->null_value()
5125 : isolate()->factory()->undefined_value();
5126 if (expr->op() == Token::EQ_STRICT) {
5127 __ cmp(eax, nil_value);
5128 Split(equal, if_true, if_false, fall_through);
5130 Handle<Code> ic = CompareNilICStub::GetUninitialized(isolate(), nil);
5131 CallIC(ic, expr->CompareOperationFeedbackId());
5133 Split(not_zero, if_true, if_false, fall_through);
5135 context()->Plug(if_true, if_false);
5139 void FullCodeGenerator::VisitThisFunction(ThisFunction* expr) {
5140 __ mov(eax, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
5141 context()->Plug(eax);
5145 Register FullCodeGenerator::result_register() {
5150 Register FullCodeGenerator::context_register() {
5155 void FullCodeGenerator::StoreToFrameField(int frame_offset, Register value) {
5156 DCHECK_EQ(POINTER_SIZE_ALIGN(frame_offset), frame_offset);
5157 __ mov(Operand(ebp, frame_offset), value);
5161 void FullCodeGenerator::LoadContextField(Register dst, int context_index) {
5162 __ mov(dst, ContextOperand(esi, context_index));
5166 void FullCodeGenerator::PushFunctionArgumentForContextAllocation() {
5167 Scope* declaration_scope = scope()->DeclarationScope();
5168 if (declaration_scope->is_script_scope() ||
5169 declaration_scope->is_module_scope()) {
5170 // Contexts nested in the native context have a canonical empty function
5171 // as their closure, not the anonymous closure containing the global
5172 // code. Pass a smi sentinel and let the runtime look up the empty
5174 __ push(Immediate(Smi::FromInt(0)));
5175 } else if (declaration_scope->is_eval_scope()) {
5176 // Contexts nested inside eval code have the same closure as the context
5177 // calling eval, not the anonymous closure containing the eval code.
5178 // Fetch it from the context.
5179 __ push(ContextOperand(esi, Context::CLOSURE_INDEX));
5181 DCHECK(declaration_scope->is_function_scope());
5182 __ push(Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
5187 // ----------------------------------------------------------------------------
5188 // Non-local control flow support.
5190 void FullCodeGenerator::EnterFinallyBlock() {
5191 // Cook return address on top of stack (smi encoded Code* delta)
5192 DCHECK(!result_register().is(edx));
5194 __ sub(edx, Immediate(masm_->CodeObject()));
5195 STATIC_ASSERT(kSmiTagSize + kSmiShiftSize == 1);
5196 STATIC_ASSERT(kSmiTag == 0);
5200 // Store result register while executing finally block.
5201 __ push(result_register());
5203 // Store pending message while executing finally block.
5204 ExternalReference pending_message_obj =
5205 ExternalReference::address_of_pending_message_obj(isolate());
5206 __ mov(edx, Operand::StaticVariable(pending_message_obj));
5209 ExternalReference has_pending_message =
5210 ExternalReference::address_of_has_pending_message(isolate());
5211 __ mov(edx, Operand::StaticVariable(has_pending_message));
5215 ExternalReference pending_message_script =
5216 ExternalReference::address_of_pending_message_script(isolate());
5217 __ mov(edx, Operand::StaticVariable(pending_message_script));
5222 void FullCodeGenerator::ExitFinallyBlock() {
5223 DCHECK(!result_register().is(edx));
5224 // Restore pending message from stack.
5226 ExternalReference pending_message_script =
5227 ExternalReference::address_of_pending_message_script(isolate());
5228 __ mov(Operand::StaticVariable(pending_message_script), edx);
5232 ExternalReference has_pending_message =
5233 ExternalReference::address_of_has_pending_message(isolate());
5234 __ mov(Operand::StaticVariable(has_pending_message), edx);
5237 ExternalReference pending_message_obj =
5238 ExternalReference::address_of_pending_message_obj(isolate());
5239 __ mov(Operand::StaticVariable(pending_message_obj), edx);
5241 // Restore result register from stack.
5242 __ pop(result_register());
5244 // Uncook return address.
5247 __ add(edx, Immediate(masm_->CodeObject()));
5254 #define __ ACCESS_MASM(masm())
5256 FullCodeGenerator::NestedStatement* FullCodeGenerator::TryFinally::Exit(
5258 int* context_length) {
5259 // The macros used here must preserve the result register.
5261 // Because the handler block contains the context of the finally
5262 // code, we can restore it directly from there for the finally code
5263 // rather than iteratively unwinding contexts via their previous
5265 __ Drop(*stack_depth); // Down to the handler block.
5266 if (*context_length > 0) {
5267 // Restore the context to its dedicated register and the stack.
5268 __ mov(esi, Operand(esp, StackHandlerConstants::kContextOffset));
5269 __ mov(Operand(ebp, StandardFrameConstants::kContextOffset), esi);
5272 __ call(finally_entry_);
5275 *context_length = 0;
5282 static const byte kJnsInstruction = 0x79;
5283 static const byte kJnsOffset = 0x11;
5284 static const byte kNopByteOne = 0x66;
5285 static const byte kNopByteTwo = 0x90;
5287 static const byte kCallInstruction = 0xe8;
5291 void BackEdgeTable::PatchAt(Code* unoptimized_code,
5293 BackEdgeState target_state,
5294 Code* replacement_code) {
5295 Address call_target_address = pc - kIntSize;
5296 Address jns_instr_address = call_target_address - 3;
5297 Address jns_offset_address = call_target_address - 2;
5299 switch (target_state) {
5301 // sub <profiling_counter>, <delta> ;; Not changed
5303 // call <interrupt stub>
5305 *jns_instr_address = kJnsInstruction;
5306 *jns_offset_address = kJnsOffset;
5308 case ON_STACK_REPLACEMENT:
5309 case OSR_AFTER_STACK_CHECK:
5310 // sub <profiling_counter>, <delta> ;; Not changed
5313 // call <on-stack replacment>
5315 *jns_instr_address = kNopByteOne;
5316 *jns_offset_address = kNopByteTwo;
5320 Assembler::set_target_address_at(call_target_address,
5322 replacement_code->entry());
5323 unoptimized_code->GetHeap()->incremental_marking()->RecordCodeTargetPatch(
5324 unoptimized_code, call_target_address, replacement_code);
5328 BackEdgeTable::BackEdgeState BackEdgeTable::GetBackEdgeState(
5330 Code* unoptimized_code,
5332 Address call_target_address = pc - kIntSize;
5333 Address jns_instr_address = call_target_address - 3;
5334 DCHECK_EQ(kCallInstruction, *(call_target_address - 1));
5336 if (*jns_instr_address == kJnsInstruction) {
5337 DCHECK_EQ(kJnsOffset, *(call_target_address - 2));
5338 DCHECK_EQ(isolate->builtins()->InterruptCheck()->entry(),
5339 Assembler::target_address_at(call_target_address,
5344 DCHECK_EQ(kNopByteOne, *jns_instr_address);
5345 DCHECK_EQ(kNopByteTwo, *(call_target_address - 2));
5347 if (Assembler::target_address_at(call_target_address, unoptimized_code) ==
5348 isolate->builtins()->OnStackReplacement()->entry()) {
5349 return ON_STACK_REPLACEMENT;
5352 DCHECK_EQ(isolate->builtins()->OsrAfterStackCheck()->entry(),
5353 Assembler::target_address_at(call_target_address,
5355 return OSR_AFTER_STACK_CHECK;
5359 } } // namespace v8::internal
5361 #endif // V8_TARGET_ARCH_X87