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 Handle<HandlerTable>::cast(isolate()->factory()->NewFixedArray(
99 HandlerTable::LengthForRange(function()->handler_count()), TENURED));
101 profiling_counter_ = isolate()->factory()->NewCell(
102 Handle<Smi>(Smi::FromInt(FLAG_interrupt_budget), isolate()));
103 SetFunctionPosition(function());
104 Comment cmnt(masm_, "[ function compiled by full code generator");
106 ProfileEntryHookStub::MaybeCallEntryHook(masm_);
109 if (strlen(FLAG_stop_at) > 0 &&
110 info->function()->name()->IsUtf8EqualTo(CStrVector(FLAG_stop_at))) {
115 // Sloppy mode functions and builtins need to replace the receiver with the
116 // global proxy when called as functions (without an explicit receiver
118 if (is_sloppy(info->language_mode()) && !info->is_native()) {
120 // +1 for return address.
121 int receiver_offset = (info->scope()->num_parameters() + 1) * kPointerSize;
122 __ mov(ecx, Operand(esp, receiver_offset));
124 __ cmp(ecx, isolate()->factory()->undefined_value());
125 __ j(not_equal, &ok, Label::kNear);
127 __ mov(ecx, GlobalObjectOperand());
128 __ mov(ecx, FieldOperand(ecx, GlobalObject::kGlobalProxyOffset));
130 __ mov(Operand(esp, receiver_offset), ecx);
135 // Open a frame scope to indicate that there is a frame on the stack. The
136 // MANUAL indicates that the scope shouldn't actually generate code to set up
137 // the frame (that is done below).
138 FrameScope frame_scope(masm_, StackFrame::MANUAL);
140 info->set_prologue_offset(masm_->pc_offset());
141 __ Prologue(info->IsCodePreAgingActive());
142 info->AddNoFrameRange(0, masm_->pc_offset());
144 { Comment cmnt(masm_, "[ Allocate locals");
145 int locals_count = info->scope()->num_stack_slots();
146 // Generators allocate locals, if any, in context slots.
147 DCHECK(!IsGeneratorFunction(info->function()->kind()) || locals_count == 0);
148 if (locals_count == 1) {
149 __ push(Immediate(isolate()->factory()->undefined_value()));
150 } else if (locals_count > 1) {
151 if (locals_count >= 128) {
154 __ sub(ecx, Immediate(locals_count * kPointerSize));
155 ExternalReference stack_limit =
156 ExternalReference::address_of_real_stack_limit(isolate());
157 __ cmp(ecx, Operand::StaticVariable(stack_limit));
158 __ j(above_equal, &ok, Label::kNear);
159 __ InvokeBuiltin(Builtins::STACK_OVERFLOW, CALL_FUNCTION);
162 __ mov(eax, Immediate(isolate()->factory()->undefined_value()));
163 const int kMaxPushes = 32;
164 if (locals_count >= kMaxPushes) {
165 int loop_iterations = locals_count / kMaxPushes;
166 __ mov(ecx, loop_iterations);
168 __ bind(&loop_header);
170 for (int i = 0; i < kMaxPushes; i++) {
174 __ j(not_zero, &loop_header, Label::kNear);
176 int remaining = locals_count % kMaxPushes;
177 // Emit the remaining pushes.
178 for (int i = 0; i < remaining; i++) {
184 bool function_in_register = true;
186 // Possibly allocate a local context.
187 int heap_slots = info->scope()->num_heap_slots() - Context::MIN_CONTEXT_SLOTS;
188 if (heap_slots > 0) {
189 Comment cmnt(masm_, "[ Allocate context");
190 bool need_write_barrier = true;
191 // Argument to NewContext is the function, which is still in edi.
192 if (info->scope()->is_script_scope()) {
194 __ Push(info->scope()->GetScopeInfo(info->isolate()));
195 __ CallRuntime(Runtime::kNewScriptContext, 2);
196 } else if (heap_slots <= FastNewContextStub::kMaximumSlots) {
197 FastNewContextStub stub(isolate(), heap_slots);
199 // Result of FastNewContextStub is always in new space.
200 need_write_barrier = false;
203 __ CallRuntime(Runtime::kNewFunctionContext, 1);
205 function_in_register = false;
206 // Context is returned in eax. It replaces the context passed to us.
207 // It's saved in the stack and kept live in esi.
209 __ mov(Operand(ebp, StandardFrameConstants::kContextOffset), eax);
211 // Copy parameters into context if necessary.
212 int num_parameters = info->scope()->num_parameters();
213 for (int i = 0; i < num_parameters; i++) {
214 Variable* var = scope()->parameter(i);
215 if (var->IsContextSlot()) {
216 int parameter_offset = StandardFrameConstants::kCallerSPOffset +
217 (num_parameters - 1 - i) * kPointerSize;
218 // Load parameter from stack.
219 __ mov(eax, Operand(ebp, parameter_offset));
220 // Store it in the context.
221 int context_offset = Context::SlotOffset(var->index());
222 __ mov(Operand(esi, context_offset), eax);
223 // Update the write barrier. This clobbers eax and ebx.
224 if (need_write_barrier) {
225 __ RecordWriteContextSlot(esi, context_offset, eax, ebx,
227 } else if (FLAG_debug_code) {
229 __ JumpIfInNewSpace(esi, eax, &done, Label::kNear);
230 __ Abort(kExpectedNewSpaceObject);
237 ArgumentsAccessStub::HasNewTarget has_new_target =
238 IsSubclassConstructor(info->function()->kind())
239 ? ArgumentsAccessStub::HAS_NEW_TARGET
240 : ArgumentsAccessStub::NO_NEW_TARGET;
242 // Possibly allocate RestParameters
244 Variable* rest_param = scope()->rest_parameter(&rest_index);
246 Comment cmnt(masm_, "[ Allocate rest parameter array");
248 int num_parameters = info->scope()->num_parameters();
249 int offset = num_parameters * kPointerSize;
250 if (has_new_target == ArgumentsAccessStub::HAS_NEW_TARGET) {
256 Operand(ebp, StandardFrameConstants::kCallerSPOffset + offset));
258 __ push(Immediate(Smi::FromInt(num_parameters)));
259 __ push(Immediate(Smi::FromInt(rest_index)));
261 RestParamAccessStub stub(isolate());
264 SetVar(rest_param, eax, ebx, edx);
267 Variable* arguments = scope()->arguments();
268 if (arguments != NULL) {
269 // Function uses arguments object.
270 Comment cmnt(masm_, "[ Allocate arguments object");
271 if (function_in_register) {
274 __ push(Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
276 // Receiver is just before the parameters on the caller's stack.
277 int num_parameters = info->scope()->num_parameters();
278 int offset = num_parameters * kPointerSize;
280 Operand(ebp, StandardFrameConstants::kCallerSPOffset + offset));
282 __ push(Immediate(Smi::FromInt(num_parameters)));
283 // Arguments to ArgumentsAccessStub:
284 // function, receiver address, parameter count.
285 // The stub will rewrite receiver and parameter count if the previous
286 // stack frame was an arguments adapter frame.
287 ArgumentsAccessStub::Type type;
288 if (is_strict(language_mode()) || !is_simple_parameter_list()) {
289 type = ArgumentsAccessStub::NEW_STRICT;
290 } else if (function()->has_duplicate_parameters()) {
291 type = ArgumentsAccessStub::NEW_SLOPPY_SLOW;
293 type = ArgumentsAccessStub::NEW_SLOPPY_FAST;
296 ArgumentsAccessStub stub(isolate(), type, has_new_target);
299 SetVar(arguments, eax, ebx, edx);
303 __ CallRuntime(Runtime::kTraceEnter, 0);
306 // Visit the declarations and body unless there is an illegal
308 if (scope()->HasIllegalRedeclaration()) {
309 Comment cmnt(masm_, "[ Declarations");
310 scope()->VisitIllegalRedeclaration(this);
313 PrepareForBailoutForId(BailoutId::FunctionEntry(), NO_REGISTERS);
314 { Comment cmnt(masm_, "[ Declarations");
315 // For named function expressions, declare the function name as a
317 if (scope()->is_function_scope() && scope()->function() != NULL) {
318 VariableDeclaration* function = scope()->function();
319 DCHECK(function->proxy()->var()->mode() == CONST ||
320 function->proxy()->var()->mode() == CONST_LEGACY);
321 DCHECK(function->proxy()->var()->location() != Variable::UNALLOCATED);
322 VisitVariableDeclaration(function);
324 VisitDeclarations(scope()->declarations());
327 { Comment cmnt(masm_, "[ Stack check");
328 PrepareForBailoutForId(BailoutId::Declarations(), NO_REGISTERS);
330 ExternalReference stack_limit
331 = ExternalReference::address_of_stack_limit(isolate());
332 __ cmp(esp, Operand::StaticVariable(stack_limit));
333 __ j(above_equal, &ok, Label::kNear);
334 __ call(isolate()->builtins()->StackCheck(), RelocInfo::CODE_TARGET);
338 { Comment cmnt(masm_, "[ Body");
339 DCHECK(loop_depth() == 0);
340 VisitStatements(function()->body());
341 DCHECK(loop_depth() == 0);
345 // Always emit a 'return undefined' in case control fell off the end of
347 { Comment cmnt(masm_, "[ return <undefined>;");
348 __ mov(eax, isolate()->factory()->undefined_value());
349 EmitReturnSequence();
354 void FullCodeGenerator::ClearAccumulator() {
355 __ Move(eax, Immediate(Smi::FromInt(0)));
359 void FullCodeGenerator::EmitProfilingCounterDecrement(int delta) {
360 __ mov(ebx, Immediate(profiling_counter_));
361 __ sub(FieldOperand(ebx, Cell::kValueOffset),
362 Immediate(Smi::FromInt(delta)));
366 void FullCodeGenerator::EmitProfilingCounterReset() {
367 int reset_value = FLAG_interrupt_budget;
368 __ mov(ebx, Immediate(profiling_counter_));
369 __ mov(FieldOperand(ebx, Cell::kValueOffset),
370 Immediate(Smi::FromInt(reset_value)));
374 void FullCodeGenerator::EmitBackEdgeBookkeeping(IterationStatement* stmt,
375 Label* back_edge_target) {
376 Comment cmnt(masm_, "[ Back edge bookkeeping");
379 DCHECK(back_edge_target->is_bound());
380 int distance = masm_->SizeOfCodeGeneratedSince(back_edge_target);
381 int weight = Min(kMaxBackEdgeWeight,
382 Max(1, distance / kCodeSizeMultiplier));
383 EmitProfilingCounterDecrement(weight);
384 __ j(positive, &ok, Label::kNear);
385 __ call(isolate()->builtins()->InterruptCheck(), RelocInfo::CODE_TARGET);
387 // Record a mapping of this PC offset to the OSR id. This is used to find
388 // the AST id from the unoptimized code in order to use it as a key into
389 // the deoptimization input data found in the optimized code.
390 RecordBackEdge(stmt->OsrEntryId());
392 EmitProfilingCounterReset();
395 PrepareForBailoutForId(stmt->EntryId(), NO_REGISTERS);
396 // Record a mapping of the OSR id to this PC. This is used if the OSR
397 // entry becomes the target of a bailout. We don't expect it to be, but
398 // we want it to work if it is.
399 PrepareForBailoutForId(stmt->OsrEntryId(), NO_REGISTERS);
403 void FullCodeGenerator::EmitReturnSequence() {
404 Comment cmnt(masm_, "[ Return sequence");
405 if (return_label_.is_bound()) {
406 __ jmp(&return_label_);
408 // Common return label
409 __ bind(&return_label_);
412 __ CallRuntime(Runtime::kTraceExit, 1);
414 // Pretend that the exit is a backwards jump to the entry.
416 if (info_->ShouldSelfOptimize()) {
417 weight = FLAG_interrupt_budget / FLAG_self_opt_count;
419 int distance = masm_->pc_offset();
420 weight = Min(kMaxBackEdgeWeight,
421 Max(1, distance / kCodeSizeMultiplier));
423 EmitProfilingCounterDecrement(weight);
425 __ j(positive, &ok, Label::kNear);
427 __ call(isolate()->builtins()->InterruptCheck(),
428 RelocInfo::CODE_TARGET);
430 EmitProfilingCounterReset();
433 // Add a label for checking the size of the code used for returning.
434 Label check_exit_codesize;
435 masm_->bind(&check_exit_codesize);
437 SetSourcePosition(function()->end_position() - 1);
439 // Do not use the leave instruction here because it is too short to
440 // patch with the code required by the debugger.
442 int no_frame_start = masm_->pc_offset();
445 int arg_count = info_->scope()->num_parameters() + 1;
446 if (IsSubclassConstructor(info_->function()->kind())) {
449 int arguments_bytes = arg_count * kPointerSize;
450 __ Ret(arguments_bytes, ecx);
451 // Check that the size of the code used for returning is large enough
452 // for the debugger's requirements.
453 DCHECK(Assembler::kJSReturnSequenceLength <=
454 masm_->SizeOfCodeGeneratedSince(&check_exit_codesize));
455 info_->AddNoFrameRange(no_frame_start, masm_->pc_offset());
460 void FullCodeGenerator::EffectContext::Plug(Variable* var) const {
461 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
465 void FullCodeGenerator::AccumulatorValueContext::Plug(Variable* var) const {
466 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
467 codegen()->GetVar(result_register(), var);
471 void FullCodeGenerator::StackValueContext::Plug(Variable* var) const {
472 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
473 MemOperand operand = codegen()->VarOperand(var, result_register());
474 // Memory operands can be pushed directly.
479 void FullCodeGenerator::TestContext::Plug(Variable* var) const {
480 // For simplicity we always test the accumulator register.
481 codegen()->GetVar(result_register(), var);
482 codegen()->PrepareForBailoutBeforeSplit(condition(), false, NULL, NULL);
483 codegen()->DoTest(this);
487 void FullCodeGenerator::EffectContext::Plug(Heap::RootListIndex index) const {
488 UNREACHABLE(); // Not used on X87.
492 void FullCodeGenerator::AccumulatorValueContext::Plug(
493 Heap::RootListIndex index) const {
494 UNREACHABLE(); // Not used on X87.
498 void FullCodeGenerator::StackValueContext::Plug(
499 Heap::RootListIndex index) const {
500 UNREACHABLE(); // Not used on X87.
504 void FullCodeGenerator::TestContext::Plug(Heap::RootListIndex index) const {
505 UNREACHABLE(); // Not used on X87.
509 void FullCodeGenerator::EffectContext::Plug(Handle<Object> lit) const {
513 void FullCodeGenerator::AccumulatorValueContext::Plug(
514 Handle<Object> lit) const {
516 __ SafeMove(result_register(), Immediate(lit));
518 __ Move(result_register(), Immediate(lit));
523 void FullCodeGenerator::StackValueContext::Plug(Handle<Object> lit) const {
525 __ SafePush(Immediate(lit));
527 __ push(Immediate(lit));
532 void FullCodeGenerator::TestContext::Plug(Handle<Object> lit) const {
533 codegen()->PrepareForBailoutBeforeSplit(condition(),
537 DCHECK(!lit->IsUndetectableObject()); // There are no undetectable literals.
538 if (lit->IsUndefined() || lit->IsNull() || lit->IsFalse()) {
539 if (false_label_ != fall_through_) __ jmp(false_label_);
540 } else if (lit->IsTrue() || lit->IsJSObject()) {
541 if (true_label_ != fall_through_) __ jmp(true_label_);
542 } else if (lit->IsString()) {
543 if (String::cast(*lit)->length() == 0) {
544 if (false_label_ != fall_through_) __ jmp(false_label_);
546 if (true_label_ != fall_through_) __ jmp(true_label_);
548 } else if (lit->IsSmi()) {
549 if (Smi::cast(*lit)->value() == 0) {
550 if (false_label_ != fall_through_) __ jmp(false_label_);
552 if (true_label_ != fall_through_) __ jmp(true_label_);
555 // For simplicity we always test the accumulator register.
556 __ mov(result_register(), lit);
557 codegen()->DoTest(this);
562 void FullCodeGenerator::EffectContext::DropAndPlug(int count,
563 Register reg) const {
569 void FullCodeGenerator::AccumulatorValueContext::DropAndPlug(
571 Register reg) const {
574 __ Move(result_register(), reg);
578 void FullCodeGenerator::StackValueContext::DropAndPlug(int count,
579 Register reg) const {
581 if (count > 1) __ Drop(count - 1);
582 __ mov(Operand(esp, 0), reg);
586 void FullCodeGenerator::TestContext::DropAndPlug(int count,
587 Register reg) const {
589 // For simplicity we always test the accumulator register.
591 __ Move(result_register(), reg);
592 codegen()->PrepareForBailoutBeforeSplit(condition(), false, NULL, NULL);
593 codegen()->DoTest(this);
597 void FullCodeGenerator::EffectContext::Plug(Label* materialize_true,
598 Label* materialize_false) const {
599 DCHECK(materialize_true == materialize_false);
600 __ bind(materialize_true);
604 void FullCodeGenerator::AccumulatorValueContext::Plug(
605 Label* materialize_true,
606 Label* materialize_false) const {
608 __ bind(materialize_true);
609 __ mov(result_register(), isolate()->factory()->true_value());
610 __ jmp(&done, Label::kNear);
611 __ bind(materialize_false);
612 __ mov(result_register(), isolate()->factory()->false_value());
617 void FullCodeGenerator::StackValueContext::Plug(
618 Label* materialize_true,
619 Label* materialize_false) const {
621 __ bind(materialize_true);
622 __ push(Immediate(isolate()->factory()->true_value()));
623 __ jmp(&done, Label::kNear);
624 __ bind(materialize_false);
625 __ push(Immediate(isolate()->factory()->false_value()));
630 void FullCodeGenerator::TestContext::Plug(Label* materialize_true,
631 Label* materialize_false) const {
632 DCHECK(materialize_true == true_label_);
633 DCHECK(materialize_false == false_label_);
637 void FullCodeGenerator::EffectContext::Plug(bool flag) const {
641 void FullCodeGenerator::AccumulatorValueContext::Plug(bool flag) const {
642 Handle<Object> value = flag
643 ? isolate()->factory()->true_value()
644 : isolate()->factory()->false_value();
645 __ mov(result_register(), value);
649 void FullCodeGenerator::StackValueContext::Plug(bool flag) const {
650 Handle<Object> value = flag
651 ? isolate()->factory()->true_value()
652 : isolate()->factory()->false_value();
653 __ push(Immediate(value));
657 void FullCodeGenerator::TestContext::Plug(bool flag) const {
658 codegen()->PrepareForBailoutBeforeSplit(condition(),
663 if (true_label_ != fall_through_) __ jmp(true_label_);
665 if (false_label_ != fall_through_) __ jmp(false_label_);
670 void FullCodeGenerator::DoTest(Expression* condition,
673 Label* fall_through) {
674 Handle<Code> ic = ToBooleanStub::GetUninitialized(isolate());
675 CallIC(ic, condition->test_id());
676 __ test(result_register(), result_register());
677 // The stub returns nonzero for true.
678 Split(not_zero, if_true, if_false, fall_through);
682 void FullCodeGenerator::Split(Condition cc,
685 Label* fall_through) {
686 if (if_false == fall_through) {
688 } else if (if_true == fall_through) {
689 __ j(NegateCondition(cc), if_false);
697 MemOperand FullCodeGenerator::StackOperand(Variable* var) {
698 DCHECK(var->IsStackAllocated());
699 // Offset is negative because higher indexes are at lower addresses.
700 int offset = -var->index() * kPointerSize;
701 // Adjust by a (parameter or local) base offset.
702 if (var->IsParameter()) {
703 offset += (info_->scope()->num_parameters() + 1) * kPointerSize;
705 offset += JavaScriptFrameConstants::kLocal0Offset;
707 return Operand(ebp, offset);
711 MemOperand FullCodeGenerator::VarOperand(Variable* var, Register scratch) {
712 DCHECK(var->IsContextSlot() || var->IsStackAllocated());
713 if (var->IsContextSlot()) {
714 int context_chain_length = scope()->ContextChainLength(var->scope());
715 __ LoadContext(scratch, context_chain_length);
716 return ContextOperand(scratch, var->index());
718 return StackOperand(var);
723 void FullCodeGenerator::GetVar(Register dest, Variable* var) {
724 DCHECK(var->IsContextSlot() || var->IsStackAllocated());
725 MemOperand location = VarOperand(var, dest);
726 __ mov(dest, location);
730 void FullCodeGenerator::SetVar(Variable* var,
734 DCHECK(var->IsContextSlot() || var->IsStackAllocated());
735 DCHECK(!scratch0.is(src));
736 DCHECK(!scratch0.is(scratch1));
737 DCHECK(!scratch1.is(src));
738 MemOperand location = VarOperand(var, scratch0);
739 __ mov(location, src);
741 // Emit the write barrier code if the location is in the heap.
742 if (var->IsContextSlot()) {
743 int offset = Context::SlotOffset(var->index());
744 DCHECK(!scratch0.is(esi) && !src.is(esi) && !scratch1.is(esi));
745 __ RecordWriteContextSlot(scratch0, offset, src, scratch1, kDontSaveFPRegs);
750 void FullCodeGenerator::PrepareForBailoutBeforeSplit(Expression* expr,
751 bool should_normalize,
754 // Only prepare for bailouts before splits if we're in a test
755 // context. Otherwise, we let the Visit function deal with the
756 // preparation to avoid preparing with the same AST id twice.
757 if (!context()->IsTest() || !info_->IsOptimizable()) return;
760 if (should_normalize) __ jmp(&skip, Label::kNear);
761 PrepareForBailout(expr, TOS_REG);
762 if (should_normalize) {
763 __ cmp(eax, isolate()->factory()->true_value());
764 Split(equal, if_true, if_false, NULL);
770 void FullCodeGenerator::EmitDebugCheckDeclarationContext(Variable* variable) {
771 // The variable in the declaration always resides in the current context.
772 DCHECK_EQ(0, scope()->ContextChainLength(variable->scope()));
773 if (generate_debug_code_) {
774 // Check that we're not inside a with or catch context.
775 __ mov(ebx, FieldOperand(esi, HeapObject::kMapOffset));
776 __ cmp(ebx, isolate()->factory()->with_context_map());
777 __ Check(not_equal, kDeclarationInWithContext);
778 __ cmp(ebx, isolate()->factory()->catch_context_map());
779 __ Check(not_equal, kDeclarationInCatchContext);
784 void FullCodeGenerator::VisitVariableDeclaration(
785 VariableDeclaration* declaration) {
786 // If it was not possible to allocate the variable at compile time, we
787 // need to "declare" it at runtime to make sure it actually exists in the
789 VariableProxy* proxy = declaration->proxy();
790 VariableMode mode = declaration->mode();
791 Variable* variable = proxy->var();
792 bool hole_init = mode == LET || mode == CONST || mode == CONST_LEGACY;
793 switch (variable->location()) {
794 case Variable::UNALLOCATED:
795 globals_->Add(variable->name(), zone());
796 globals_->Add(variable->binding_needs_init()
797 ? isolate()->factory()->the_hole_value()
798 : isolate()->factory()->undefined_value(), zone());
801 case Variable::PARAMETER:
802 case Variable::LOCAL:
804 Comment cmnt(masm_, "[ VariableDeclaration");
805 __ mov(StackOperand(variable),
806 Immediate(isolate()->factory()->the_hole_value()));
810 case Variable::CONTEXT:
812 Comment cmnt(masm_, "[ VariableDeclaration");
813 EmitDebugCheckDeclarationContext(variable);
814 __ mov(ContextOperand(esi, variable->index()),
815 Immediate(isolate()->factory()->the_hole_value()));
816 // No write barrier since the hole value is in old space.
817 PrepareForBailoutForId(proxy->id(), NO_REGISTERS);
821 case Variable::LOOKUP: {
822 Comment cmnt(masm_, "[ VariableDeclaration");
824 __ push(Immediate(variable->name()));
825 // VariableDeclaration nodes are always introduced in one of four modes.
826 DCHECK(IsDeclaredVariableMode(mode));
827 PropertyAttributes attr =
828 IsImmutableVariableMode(mode) ? READ_ONLY : NONE;
829 __ push(Immediate(Smi::FromInt(attr)));
830 // Push initial value, if any.
831 // Note: For variables we must not push an initial value (such as
832 // 'undefined') because we may have a (legal) redeclaration and we
833 // must not destroy the current value.
835 __ push(Immediate(isolate()->factory()->the_hole_value()));
837 __ push(Immediate(Smi::FromInt(0))); // Indicates no initial value.
839 __ CallRuntime(Runtime::kDeclareLookupSlot, 4);
846 void FullCodeGenerator::VisitFunctionDeclaration(
847 FunctionDeclaration* declaration) {
848 VariableProxy* proxy = declaration->proxy();
849 Variable* variable = proxy->var();
850 switch (variable->location()) {
851 case Variable::UNALLOCATED: {
852 globals_->Add(variable->name(), zone());
853 Handle<SharedFunctionInfo> function =
854 Compiler::BuildFunctionInfo(declaration->fun(), script(), info_);
855 // Check for stack-overflow exception.
856 if (function.is_null()) return SetStackOverflow();
857 globals_->Add(function, zone());
861 case Variable::PARAMETER:
862 case Variable::LOCAL: {
863 Comment cmnt(masm_, "[ FunctionDeclaration");
864 VisitForAccumulatorValue(declaration->fun());
865 __ mov(StackOperand(variable), result_register());
869 case Variable::CONTEXT: {
870 Comment cmnt(masm_, "[ FunctionDeclaration");
871 EmitDebugCheckDeclarationContext(variable);
872 VisitForAccumulatorValue(declaration->fun());
873 __ mov(ContextOperand(esi, variable->index()), result_register());
874 // We know that we have written a function, which is not a smi.
875 __ RecordWriteContextSlot(esi, Context::SlotOffset(variable->index()),
876 result_register(), ecx, kDontSaveFPRegs,
877 EMIT_REMEMBERED_SET, OMIT_SMI_CHECK);
878 PrepareForBailoutForId(proxy->id(), NO_REGISTERS);
882 case Variable::LOOKUP: {
883 Comment cmnt(masm_, "[ FunctionDeclaration");
885 __ push(Immediate(variable->name()));
886 __ push(Immediate(Smi::FromInt(NONE)));
887 VisitForStackValue(declaration->fun());
888 __ CallRuntime(Runtime::kDeclareLookupSlot, 4);
895 void FullCodeGenerator::VisitModuleDeclaration(ModuleDeclaration* declaration) {
896 Variable* variable = declaration->proxy()->var();
897 ModuleDescriptor* descriptor = declaration->module()->descriptor();
898 DCHECK(variable->location() == Variable::CONTEXT);
899 DCHECK(descriptor->IsFrozen());
901 Comment cmnt(masm_, "[ ModuleDeclaration");
902 EmitDebugCheckDeclarationContext(variable);
904 // Load instance object.
905 __ LoadContext(eax, scope_->ContextChainLength(scope_->ScriptScope()));
906 __ mov(eax, ContextOperand(eax, descriptor->Index()));
907 __ mov(eax, ContextOperand(eax, Context::EXTENSION_INDEX));
910 __ mov(ContextOperand(esi, variable->index()), eax);
911 // We know that we have written a module, which is not a smi.
912 __ RecordWriteContextSlot(esi, Context::SlotOffset(variable->index()), eax,
913 ecx, kDontSaveFPRegs, EMIT_REMEMBERED_SET,
915 PrepareForBailoutForId(declaration->proxy()->id(), NO_REGISTERS);
917 // Traverse into body.
918 Visit(declaration->module());
922 void FullCodeGenerator::VisitImportDeclaration(ImportDeclaration* declaration) {
923 VariableProxy* proxy = declaration->proxy();
924 Variable* variable = proxy->var();
925 switch (variable->location()) {
926 case Variable::UNALLOCATED:
930 case Variable::CONTEXT: {
931 Comment cmnt(masm_, "[ ImportDeclaration");
932 EmitDebugCheckDeclarationContext(variable);
937 case Variable::PARAMETER:
938 case Variable::LOCAL:
939 case Variable::LOOKUP:
945 void FullCodeGenerator::VisitExportDeclaration(ExportDeclaration* declaration) {
950 void FullCodeGenerator::DeclareGlobals(Handle<FixedArray> pairs) {
951 // Call the runtime to declare the globals.
952 __ push(esi); // The context is the first argument.
954 __ Push(Smi::FromInt(DeclareGlobalsFlags()));
955 __ CallRuntime(Runtime::kDeclareGlobals, 3);
956 // Return value is ignored.
960 void FullCodeGenerator::DeclareModules(Handle<FixedArray> descriptions) {
961 // Call the runtime to declare the modules.
962 __ Push(descriptions);
963 __ CallRuntime(Runtime::kDeclareModules, 1);
964 // Return value is ignored.
968 void FullCodeGenerator::VisitSwitchStatement(SwitchStatement* stmt) {
969 Comment cmnt(masm_, "[ SwitchStatement");
970 Breakable nested_statement(this, stmt);
971 SetStatementPosition(stmt);
973 // Keep the switch value on the stack until a case matches.
974 VisitForStackValue(stmt->tag());
975 PrepareForBailoutForId(stmt->EntryId(), NO_REGISTERS);
977 ZoneList<CaseClause*>* clauses = stmt->cases();
978 CaseClause* default_clause = NULL; // Can occur anywhere in the list.
980 Label next_test; // Recycled for each test.
981 // Compile all the tests with branches to their bodies.
982 for (int i = 0; i < clauses->length(); i++) {
983 CaseClause* clause = clauses->at(i);
984 clause->body_target()->Unuse();
986 // The default is not a test, but remember it as final fall through.
987 if (clause->is_default()) {
988 default_clause = clause;
992 Comment cmnt(masm_, "[ Case comparison");
996 // Compile the label expression.
997 VisitForAccumulatorValue(clause->label());
999 // Perform the comparison as if via '==='.
1000 __ mov(edx, Operand(esp, 0)); // Switch value.
1001 bool inline_smi_code = ShouldInlineSmiCase(Token::EQ_STRICT);
1002 JumpPatchSite patch_site(masm_);
1003 if (inline_smi_code) {
1007 patch_site.EmitJumpIfNotSmi(ecx, &slow_case, Label::kNear);
1010 __ j(not_equal, &next_test);
1011 __ Drop(1); // Switch value is no longer needed.
1012 __ jmp(clause->body_target());
1013 __ bind(&slow_case);
1016 // Record position before stub call for type feedback.
1017 SetSourcePosition(clause->position());
1019 CodeFactory::CompareIC(isolate(), Token::EQ_STRICT).code();
1020 CallIC(ic, clause->CompareId());
1021 patch_site.EmitPatchInfo();
1024 __ jmp(&skip, Label::kNear);
1025 PrepareForBailout(clause, TOS_REG);
1026 __ cmp(eax, isolate()->factory()->true_value());
1027 __ j(not_equal, &next_test);
1029 __ jmp(clause->body_target());
1033 __ j(not_equal, &next_test);
1034 __ Drop(1); // Switch value is no longer needed.
1035 __ jmp(clause->body_target());
1038 // Discard the test value and jump to the default if present, otherwise to
1039 // the end of the statement.
1040 __ bind(&next_test);
1041 __ Drop(1); // Switch value is no longer needed.
1042 if (default_clause == NULL) {
1043 __ jmp(nested_statement.break_label());
1045 __ jmp(default_clause->body_target());
1048 // Compile all the case bodies.
1049 for (int i = 0; i < clauses->length(); i++) {
1050 Comment cmnt(masm_, "[ Case body");
1051 CaseClause* clause = clauses->at(i);
1052 __ bind(clause->body_target());
1053 PrepareForBailoutForId(clause->EntryId(), NO_REGISTERS);
1054 VisitStatements(clause->statements());
1057 __ bind(nested_statement.break_label());
1058 PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1062 void FullCodeGenerator::VisitForInStatement(ForInStatement* stmt) {
1063 Comment cmnt(masm_, "[ ForInStatement");
1064 FeedbackVectorSlot slot = stmt->ForInFeedbackSlot();
1066 SetStatementPosition(stmt);
1069 ForIn loop_statement(this, stmt);
1070 increment_loop_depth();
1072 // Get the object to enumerate over. If the object is null or undefined, skip
1073 // over the loop. See ECMA-262 version 5, section 12.6.4.
1074 SetExpressionPosition(stmt->enumerable());
1075 VisitForAccumulatorValue(stmt->enumerable());
1076 __ cmp(eax, isolate()->factory()->undefined_value());
1078 __ cmp(eax, isolate()->factory()->null_value());
1081 PrepareForBailoutForId(stmt->PrepareId(), TOS_REG);
1083 // Convert the object to a JS object.
1084 Label convert, done_convert;
1085 __ JumpIfSmi(eax, &convert, Label::kNear);
1086 __ CmpObjectType(eax, FIRST_SPEC_OBJECT_TYPE, ecx);
1087 __ j(above_equal, &done_convert, Label::kNear);
1090 __ InvokeBuiltin(Builtins::TO_OBJECT, CALL_FUNCTION);
1091 __ bind(&done_convert);
1092 PrepareForBailoutForId(stmt->ToObjectId(), TOS_REG);
1095 // Check for proxies.
1096 Label call_runtime, use_cache, fixed_array;
1097 STATIC_ASSERT(FIRST_JS_PROXY_TYPE == FIRST_SPEC_OBJECT_TYPE);
1098 __ CmpObjectType(eax, LAST_JS_PROXY_TYPE, ecx);
1099 __ j(below_equal, &call_runtime);
1101 // Check cache validity in generated code. This is a fast case for
1102 // the JSObject::IsSimpleEnum cache validity checks. If we cannot
1103 // guarantee cache validity, call the runtime system to check cache
1104 // validity or get the property names in a fixed array.
1105 __ CheckEnumCache(&call_runtime);
1107 __ mov(eax, FieldOperand(eax, HeapObject::kMapOffset));
1108 __ jmp(&use_cache, Label::kNear);
1110 // Get the set of properties to enumerate.
1111 __ bind(&call_runtime);
1113 __ CallRuntime(Runtime::kGetPropertyNamesFast, 1);
1114 PrepareForBailoutForId(stmt->EnumId(), TOS_REG);
1115 __ cmp(FieldOperand(eax, HeapObject::kMapOffset),
1116 isolate()->factory()->meta_map());
1117 __ j(not_equal, &fixed_array);
1120 // We got a map in register eax. Get the enumeration cache from it.
1121 Label no_descriptors;
1122 __ bind(&use_cache);
1124 __ EnumLength(edx, eax);
1125 __ cmp(edx, Immediate(Smi::FromInt(0)));
1126 __ j(equal, &no_descriptors);
1128 __ LoadInstanceDescriptors(eax, ecx);
1129 __ mov(ecx, FieldOperand(ecx, DescriptorArray::kEnumCacheOffset));
1130 __ mov(ecx, FieldOperand(ecx, DescriptorArray::kEnumCacheBridgeCacheOffset));
1132 // Set up the four remaining stack slots.
1133 __ push(eax); // Map.
1134 __ push(ecx); // Enumeration cache.
1135 __ push(edx); // Number of valid entries for the map in the enum cache.
1136 __ push(Immediate(Smi::FromInt(0))); // Initial index.
1139 __ bind(&no_descriptors);
1140 __ add(esp, Immediate(kPointerSize));
1143 // We got a fixed array in register eax. Iterate through that.
1145 __ bind(&fixed_array);
1147 // No need for a write barrier, we are storing a Smi in the feedback vector.
1148 __ LoadHeapObject(ebx, FeedbackVector());
1149 int vector_index = FeedbackVector()->GetIndex(slot);
1150 __ mov(FieldOperand(ebx, FixedArray::OffsetOfElementAt(vector_index)),
1151 Immediate(TypeFeedbackVector::MegamorphicSentinel(isolate())));
1153 __ mov(ebx, Immediate(Smi::FromInt(1))); // Smi indicates slow check
1154 __ mov(ecx, Operand(esp, 0 * kPointerSize)); // Get enumerated object
1155 STATIC_ASSERT(FIRST_JS_PROXY_TYPE == FIRST_SPEC_OBJECT_TYPE);
1156 __ CmpObjectType(ecx, LAST_JS_PROXY_TYPE, ecx);
1157 __ j(above, &non_proxy);
1158 __ Move(ebx, Immediate(Smi::FromInt(0))); // Zero indicates proxy
1159 __ bind(&non_proxy);
1160 __ push(ebx); // Smi
1161 __ push(eax); // Array
1162 __ mov(eax, FieldOperand(eax, FixedArray::kLengthOffset));
1163 __ push(eax); // Fixed array length (as smi).
1164 __ push(Immediate(Smi::FromInt(0))); // Initial index.
1166 // Generate code for doing the condition check.
1167 PrepareForBailoutForId(stmt->BodyId(), NO_REGISTERS);
1169 SetExpressionPosition(stmt->each());
1171 __ mov(eax, Operand(esp, 0 * kPointerSize)); // Get the current index.
1172 __ cmp(eax, Operand(esp, 1 * kPointerSize)); // Compare to the array length.
1173 __ j(above_equal, loop_statement.break_label());
1175 // Get the current entry of the array into register ebx.
1176 __ mov(ebx, Operand(esp, 2 * kPointerSize));
1177 __ mov(ebx, FieldOperand(ebx, eax, times_2, FixedArray::kHeaderSize));
1179 // Get the expected map from the stack or a smi in the
1180 // permanent slow case into register edx.
1181 __ mov(edx, Operand(esp, 3 * kPointerSize));
1183 // Check if the expected map still matches that of the enumerable.
1184 // If not, we may have to filter the key.
1186 __ mov(ecx, Operand(esp, 4 * kPointerSize));
1187 __ cmp(edx, FieldOperand(ecx, HeapObject::kMapOffset));
1188 __ j(equal, &update_each, Label::kNear);
1190 // For proxies, no filtering is done.
1191 // TODO(rossberg): What if only a prototype is a proxy? Not specified yet.
1192 DCHECK(Smi::FromInt(0) == 0);
1194 __ j(zero, &update_each);
1196 // Convert the entry to a string or null if it isn't a property
1197 // anymore. If the property has been removed while iterating, we
1199 __ push(ecx); // Enumerable.
1200 __ push(ebx); // Current entry.
1201 __ InvokeBuiltin(Builtins::FILTER_KEY, CALL_FUNCTION);
1203 __ j(equal, loop_statement.continue_label());
1206 // Update the 'each' property or variable from the possibly filtered
1207 // entry in register ebx.
1208 __ bind(&update_each);
1209 __ mov(result_register(), ebx);
1210 // Perform the assignment as if via '='.
1211 { EffectContext context(this);
1212 EmitAssignment(stmt->each());
1213 PrepareForBailoutForId(stmt->AssignmentId(), NO_REGISTERS);
1216 // Generate code for the body of the loop.
1217 Visit(stmt->body());
1219 // Generate code for going to the next element by incrementing the
1220 // index (smi) stored on top of the stack.
1221 __ bind(loop_statement.continue_label());
1222 __ add(Operand(esp, 0 * kPointerSize), Immediate(Smi::FromInt(1)));
1224 EmitBackEdgeBookkeeping(stmt, &loop);
1227 // Remove the pointers stored on the stack.
1228 __ bind(loop_statement.break_label());
1229 __ add(esp, Immediate(5 * kPointerSize));
1231 // Exit and decrement the loop depth.
1232 PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1234 decrement_loop_depth();
1238 void FullCodeGenerator::EmitNewClosure(Handle<SharedFunctionInfo> info,
1240 // Use the fast case closure allocation code that allocates in new
1241 // space for nested functions that don't need literals cloning. If
1242 // we're running with the --always-opt or the --prepare-always-opt
1243 // flag, we need to use the runtime function so that the new function
1244 // we are creating here gets a chance to have its code optimized and
1245 // doesn't just get a copy of the existing unoptimized code.
1246 if (!FLAG_always_opt &&
1247 !FLAG_prepare_always_opt &&
1249 scope()->is_function_scope() &&
1250 info->num_literals() == 0) {
1251 FastNewClosureStub stub(isolate(), info->language_mode(), info->kind());
1252 __ mov(ebx, Immediate(info));
1256 __ push(Immediate(info));
1257 __ push(Immediate(pretenure
1258 ? isolate()->factory()->true_value()
1259 : isolate()->factory()->false_value()));
1260 __ CallRuntime(Runtime::kNewClosure, 3);
1262 context()->Plug(eax);
1266 void FullCodeGenerator::VisitVariableProxy(VariableProxy* expr) {
1267 Comment cmnt(masm_, "[ VariableProxy");
1268 EmitVariableLoad(expr);
1272 void FullCodeGenerator::EmitLoadHomeObject(SuperReference* expr) {
1273 Comment cnmt(masm_, "[ SuperReference ");
1275 __ mov(LoadDescriptor::ReceiverRegister(),
1276 Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
1278 Handle<Symbol> home_object_symbol(isolate()->heap()->home_object_symbol());
1279 __ mov(LoadDescriptor::NameRegister(), home_object_symbol);
1281 if (FLAG_vector_ics) {
1282 __ mov(VectorLoadICDescriptor::SlotRegister(),
1283 Immediate(SmiFromSlot(expr->HomeObjectFeedbackSlot())));
1284 CallLoadIC(NOT_CONTEXTUAL);
1286 CallLoadIC(NOT_CONTEXTUAL, expr->HomeObjectFeedbackId());
1289 __ cmp(eax, isolate()->factory()->undefined_value());
1291 __ j(not_equal, &done);
1292 __ CallRuntime(Runtime::kThrowNonMethodError, 0);
1297 void FullCodeGenerator::EmitSetHomeObjectIfNeeded(Expression* initializer,
1299 if (NeedsHomeObject(initializer)) {
1300 __ mov(StoreDescriptor::ReceiverRegister(), Operand(esp, 0));
1301 __ mov(StoreDescriptor::NameRegister(),
1302 Immediate(isolate()->factory()->home_object_symbol()));
1303 __ mov(StoreDescriptor::ValueRegister(),
1304 Operand(esp, offset * kPointerSize));
1310 void FullCodeGenerator::EmitLoadGlobalCheckExtensions(VariableProxy* proxy,
1311 TypeofState typeof_state,
1313 Register context = esi;
1314 Register temp = edx;
1318 if (s->num_heap_slots() > 0) {
1319 if (s->calls_sloppy_eval()) {
1320 // Check that extension is NULL.
1321 __ cmp(ContextOperand(context, Context::EXTENSION_INDEX),
1323 __ j(not_equal, slow);
1325 // Load next context in chain.
1326 __ mov(temp, ContextOperand(context, Context::PREVIOUS_INDEX));
1327 // Walk the rest of the chain without clobbering esi.
1330 // If no outer scope calls eval, we do not need to check more
1331 // context extensions. If we have reached an eval scope, we check
1332 // all extensions from this point.
1333 if (!s->outer_scope_calls_sloppy_eval() || s->is_eval_scope()) break;
1334 s = s->outer_scope();
1337 if (s != NULL && s->is_eval_scope()) {
1338 // Loop up the context chain. There is no frame effect so it is
1339 // safe to use raw labels here.
1341 if (!context.is(temp)) {
1342 __ mov(temp, context);
1345 // Terminate at native context.
1346 __ cmp(FieldOperand(temp, HeapObject::kMapOffset),
1347 Immediate(isolate()->factory()->native_context_map()));
1348 __ j(equal, &fast, Label::kNear);
1349 // Check that extension is NULL.
1350 __ cmp(ContextOperand(temp, Context::EXTENSION_INDEX), Immediate(0));
1351 __ j(not_equal, slow);
1352 // Load next context in chain.
1353 __ mov(temp, ContextOperand(temp, Context::PREVIOUS_INDEX));
1358 // All extension objects were empty and it is safe to use a global
1360 __ mov(LoadDescriptor::ReceiverRegister(), GlobalObjectOperand());
1361 __ mov(LoadDescriptor::NameRegister(), proxy->var()->name());
1362 if (FLAG_vector_ics) {
1363 __ mov(VectorLoadICDescriptor::SlotRegister(),
1364 Immediate(SmiFromSlot(proxy->VariableFeedbackSlot())));
1367 ContextualMode mode = (typeof_state == INSIDE_TYPEOF)
1375 MemOperand FullCodeGenerator::ContextSlotOperandCheckExtensions(Variable* var,
1377 DCHECK(var->IsContextSlot());
1378 Register context = esi;
1379 Register temp = ebx;
1381 for (Scope* s = scope(); s != var->scope(); s = s->outer_scope()) {
1382 if (s->num_heap_slots() > 0) {
1383 if (s->calls_sloppy_eval()) {
1384 // Check that extension is NULL.
1385 __ cmp(ContextOperand(context, Context::EXTENSION_INDEX),
1387 __ j(not_equal, slow);
1389 __ mov(temp, ContextOperand(context, Context::PREVIOUS_INDEX));
1390 // Walk the rest of the chain without clobbering esi.
1394 // Check that last extension is NULL.
1395 __ cmp(ContextOperand(context, Context::EXTENSION_INDEX), Immediate(0));
1396 __ j(not_equal, slow);
1398 // This function is used only for loads, not stores, so it's safe to
1399 // return an esi-based operand (the write barrier cannot be allowed to
1400 // destroy the esi register).
1401 return ContextOperand(context, var->index());
1405 void FullCodeGenerator::EmitDynamicLookupFastCase(VariableProxy* proxy,
1406 TypeofState typeof_state,
1409 // Generate fast-case code for variables that might be shadowed by
1410 // eval-introduced variables. Eval is used a lot without
1411 // introducing variables. In those cases, we do not want to
1412 // perform a runtime call for all variables in the scope
1413 // containing the eval.
1414 Variable* var = proxy->var();
1415 if (var->mode() == DYNAMIC_GLOBAL) {
1416 EmitLoadGlobalCheckExtensions(proxy, typeof_state, slow);
1418 } else if (var->mode() == DYNAMIC_LOCAL) {
1419 Variable* local = var->local_if_not_shadowed();
1420 __ mov(eax, ContextSlotOperandCheckExtensions(local, slow));
1421 if (local->mode() == LET || local->mode() == CONST ||
1422 local->mode() == CONST_LEGACY) {
1423 __ cmp(eax, isolate()->factory()->the_hole_value());
1424 __ j(not_equal, done);
1425 if (local->mode() == CONST_LEGACY) {
1426 __ mov(eax, isolate()->factory()->undefined_value());
1427 } else { // LET || CONST
1428 __ push(Immediate(var->name()));
1429 __ CallRuntime(Runtime::kThrowReferenceError, 1);
1437 void FullCodeGenerator::EmitVariableLoad(VariableProxy* proxy) {
1438 // Record position before possible IC call.
1439 SetSourcePosition(proxy->position());
1440 Variable* var = proxy->var();
1442 // Three cases: global variables, lookup variables, and all other types of
1444 switch (var->location()) {
1445 case Variable::UNALLOCATED: {
1446 Comment cmnt(masm_, "[ Global variable");
1447 __ mov(LoadDescriptor::ReceiverRegister(), GlobalObjectOperand());
1448 __ mov(LoadDescriptor::NameRegister(), var->name());
1449 if (FLAG_vector_ics) {
1450 __ mov(VectorLoadICDescriptor::SlotRegister(),
1451 Immediate(SmiFromSlot(proxy->VariableFeedbackSlot())));
1453 CallGlobalLoadIC(var->name());
1454 context()->Plug(eax);
1458 case Variable::PARAMETER:
1459 case Variable::LOCAL:
1460 case Variable::CONTEXT: {
1461 Comment cmnt(masm_, var->IsContextSlot() ? "[ Context variable"
1462 : "[ Stack variable");
1463 if (var->binding_needs_init()) {
1464 // var->scope() may be NULL when the proxy is located in eval code and
1465 // refers to a potential outside binding. Currently those bindings are
1466 // always looked up dynamically, i.e. in that case
1467 // var->location() == LOOKUP.
1469 DCHECK(var->scope() != NULL);
1471 // Check if the binding really needs an initialization check. The check
1472 // can be skipped in the following situation: we have a LET or CONST
1473 // binding in harmony mode, both the Variable and the VariableProxy have
1474 // the same declaration scope (i.e. they are both in global code, in the
1475 // same function or in the same eval code) and the VariableProxy is in
1476 // the source physically located after the initializer of the variable.
1478 // We cannot skip any initialization checks for CONST in non-harmony
1479 // mode because const variables may be declared but never initialized:
1480 // if (false) { const x; }; var y = x;
1482 // The condition on the declaration scopes is a conservative check for
1483 // nested functions that access a binding and are called before the
1484 // binding is initialized:
1485 // function() { f(); let x = 1; function f() { x = 2; } }
1487 bool skip_init_check;
1488 if (var->scope()->DeclarationScope() != scope()->DeclarationScope()) {
1489 skip_init_check = false;
1490 } else if (var->is_this()) {
1491 CHECK(info_->function() != nullptr &&
1492 (info_->function()->kind() & kSubclassConstructor) != 0);
1493 // TODO(dslomov): implement 'this' hole check elimination.
1494 skip_init_check = false;
1496 // Check that we always have valid source position.
1497 DCHECK(var->initializer_position() != RelocInfo::kNoPosition);
1498 DCHECK(proxy->position() != RelocInfo::kNoPosition);
1499 skip_init_check = var->mode() != CONST_LEGACY &&
1500 var->initializer_position() < proxy->position();
1503 if (!skip_init_check) {
1504 // Let and const need a read barrier.
1507 __ cmp(eax, isolate()->factory()->the_hole_value());
1508 __ j(not_equal, &done, Label::kNear);
1509 if (var->mode() == LET || var->mode() == CONST) {
1510 // Throw a reference error when using an uninitialized let/const
1511 // binding in harmony mode.
1512 __ push(Immediate(var->name()));
1513 __ CallRuntime(Runtime::kThrowReferenceError, 1);
1515 // Uninitalized const bindings outside of harmony mode are unholed.
1516 DCHECK(var->mode() == CONST_LEGACY);
1517 __ mov(eax, isolate()->factory()->undefined_value());
1520 context()->Plug(eax);
1524 context()->Plug(var);
1528 case Variable::LOOKUP: {
1529 Comment cmnt(masm_, "[ Lookup variable");
1531 // Generate code for loading from variables potentially shadowed
1532 // by eval-introduced variables.
1533 EmitDynamicLookupFastCase(proxy, NOT_INSIDE_TYPEOF, &slow, &done);
1535 __ push(esi); // Context.
1536 __ push(Immediate(var->name()));
1537 __ CallRuntime(Runtime::kLoadLookupSlot, 2);
1539 context()->Plug(eax);
1546 void FullCodeGenerator::VisitRegExpLiteral(RegExpLiteral* expr) {
1547 Comment cmnt(masm_, "[ RegExpLiteral");
1549 // Registers will be used as follows:
1550 // edi = JS function.
1551 // ecx = literals array.
1552 // ebx = regexp literal.
1553 // eax = regexp literal clone.
1554 __ mov(edi, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
1555 __ mov(ecx, FieldOperand(edi, JSFunction::kLiteralsOffset));
1556 int literal_offset =
1557 FixedArray::kHeaderSize + expr->literal_index() * kPointerSize;
1558 __ mov(ebx, FieldOperand(ecx, literal_offset));
1559 __ cmp(ebx, isolate()->factory()->undefined_value());
1560 __ j(not_equal, &materialized, Label::kNear);
1562 // Create regexp literal using runtime function
1563 // Result will be in eax.
1565 __ push(Immediate(Smi::FromInt(expr->literal_index())));
1566 __ push(Immediate(expr->pattern()));
1567 __ push(Immediate(expr->flags()));
1568 __ CallRuntime(Runtime::kMaterializeRegExpLiteral, 4);
1571 __ bind(&materialized);
1572 int size = JSRegExp::kSize + JSRegExp::kInObjectFieldCount * kPointerSize;
1573 Label allocated, runtime_allocate;
1574 __ Allocate(size, eax, ecx, edx, &runtime_allocate, TAG_OBJECT);
1577 __ bind(&runtime_allocate);
1579 __ push(Immediate(Smi::FromInt(size)));
1580 __ CallRuntime(Runtime::kAllocateInNewSpace, 1);
1583 __ bind(&allocated);
1584 // Copy the content into the newly allocated memory.
1585 // (Unroll copy loop once for better throughput).
1586 for (int i = 0; i < size - kPointerSize; i += 2 * kPointerSize) {
1587 __ mov(edx, FieldOperand(ebx, i));
1588 __ mov(ecx, FieldOperand(ebx, i + kPointerSize));
1589 __ mov(FieldOperand(eax, i), edx);
1590 __ mov(FieldOperand(eax, i + kPointerSize), ecx);
1592 if ((size % (2 * kPointerSize)) != 0) {
1593 __ mov(edx, FieldOperand(ebx, size - kPointerSize));
1594 __ mov(FieldOperand(eax, size - kPointerSize), edx);
1596 context()->Plug(eax);
1600 void FullCodeGenerator::EmitAccessor(Expression* expression) {
1601 if (expression == NULL) {
1602 __ push(Immediate(isolate()->factory()->null_value()));
1604 VisitForStackValue(expression);
1609 void FullCodeGenerator::VisitObjectLiteral(ObjectLiteral* expr) {
1610 Comment cmnt(masm_, "[ ObjectLiteral");
1612 expr->BuildConstantProperties(isolate());
1613 Handle<FixedArray> constant_properties = expr->constant_properties();
1614 int flags = expr->fast_elements()
1615 ? ObjectLiteral::kFastElements
1616 : ObjectLiteral::kNoFlags;
1617 flags |= expr->has_function()
1618 ? ObjectLiteral::kHasFunction
1619 : ObjectLiteral::kNoFlags;
1620 int properties_count = constant_properties->length() / 2;
1621 if (expr->may_store_doubles() || expr->depth() > 1 ||
1622 masm()->serializer_enabled() ||
1623 flags != ObjectLiteral::kFastElements ||
1624 properties_count > FastCloneShallowObjectStub::kMaximumClonedProperties) {
1625 __ mov(edi, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
1626 __ push(FieldOperand(edi, JSFunction::kLiteralsOffset));
1627 __ push(Immediate(Smi::FromInt(expr->literal_index())));
1628 __ push(Immediate(constant_properties));
1629 __ push(Immediate(Smi::FromInt(flags)));
1630 __ CallRuntime(Runtime::kCreateObjectLiteral, 4);
1632 __ mov(edi, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
1633 __ mov(eax, FieldOperand(edi, JSFunction::kLiteralsOffset));
1634 __ mov(ebx, Immediate(Smi::FromInt(expr->literal_index())));
1635 __ mov(ecx, Immediate(constant_properties));
1636 __ mov(edx, Immediate(Smi::FromInt(flags)));
1637 FastCloneShallowObjectStub stub(isolate(), properties_count);
1640 PrepareForBailoutForId(expr->CreateLiteralId(), TOS_REG);
1642 // If result_saved is true the result is on top of the stack. If
1643 // result_saved is false the result is in eax.
1644 bool result_saved = false;
1646 // Mark all computed expressions that are bound to a key that
1647 // is shadowed by a later occurrence of the same key. For the
1648 // marked expressions, no store code is emitted.
1649 expr->CalculateEmitStore(zone());
1651 AccessorTable accessor_table(zone());
1652 int property_index = 0;
1653 for (; property_index < expr->properties()->length(); property_index++) {
1654 ObjectLiteral::Property* property = expr->properties()->at(property_index);
1655 if (property->is_computed_name()) break;
1656 if (property->IsCompileTimeValue()) continue;
1658 Literal* key = property->key()->AsLiteral();
1659 Expression* value = property->value();
1660 if (!result_saved) {
1661 __ push(eax); // Save result on the stack
1662 result_saved = true;
1664 switch (property->kind()) {
1665 case ObjectLiteral::Property::CONSTANT:
1667 case ObjectLiteral::Property::MATERIALIZED_LITERAL:
1668 DCHECK(!CompileTimeValue::IsCompileTimeValue(value));
1670 case ObjectLiteral::Property::COMPUTED:
1671 // It is safe to use [[Put]] here because the boilerplate already
1672 // contains computed properties with an uninitialized value.
1673 if (key->value()->IsInternalizedString()) {
1674 if (property->emit_store()) {
1675 VisitForAccumulatorValue(value);
1676 DCHECK(StoreDescriptor::ValueRegister().is(eax));
1677 __ mov(StoreDescriptor::NameRegister(), Immediate(key->value()));
1678 __ mov(StoreDescriptor::ReceiverRegister(), Operand(esp, 0));
1679 CallStoreIC(key->LiteralFeedbackId());
1680 PrepareForBailoutForId(key->id(), NO_REGISTERS);
1682 if (NeedsHomeObject(value)) {
1683 __ mov(StoreDescriptor::ReceiverRegister(), eax);
1684 __ mov(StoreDescriptor::NameRegister(),
1685 Immediate(isolate()->factory()->home_object_symbol()));
1686 __ mov(StoreDescriptor::ValueRegister(), Operand(esp, 0));
1690 VisitForEffect(value);
1694 __ push(Operand(esp, 0)); // Duplicate receiver.
1695 VisitForStackValue(key);
1696 VisitForStackValue(value);
1697 if (property->emit_store()) {
1698 EmitSetHomeObjectIfNeeded(value, 2);
1699 __ push(Immediate(Smi::FromInt(SLOPPY))); // Language mode
1700 __ CallRuntime(Runtime::kSetProperty, 4);
1705 case ObjectLiteral::Property::PROTOTYPE:
1706 __ push(Operand(esp, 0)); // Duplicate receiver.
1707 VisitForStackValue(value);
1708 DCHECK(property->emit_store());
1709 __ CallRuntime(Runtime::kInternalSetPrototype, 2);
1711 case ObjectLiteral::Property::GETTER:
1712 if (property->emit_store()) {
1713 accessor_table.lookup(key)->second->getter = value;
1716 case ObjectLiteral::Property::SETTER:
1717 if (property->emit_store()) {
1718 accessor_table.lookup(key)->second->setter = value;
1724 // Emit code to define accessors, using only a single call to the runtime for
1725 // each pair of corresponding getters and setters.
1726 for (AccessorTable::Iterator it = accessor_table.begin();
1727 it != accessor_table.end();
1729 __ push(Operand(esp, 0)); // Duplicate receiver.
1730 VisitForStackValue(it->first);
1731 EmitAccessor(it->second->getter);
1732 EmitSetHomeObjectIfNeeded(it->second->getter, 2);
1733 EmitAccessor(it->second->setter);
1734 EmitSetHomeObjectIfNeeded(it->second->setter, 3);
1735 __ push(Immediate(Smi::FromInt(NONE)));
1736 __ CallRuntime(Runtime::kDefineAccessorPropertyUnchecked, 5);
1739 // Object literals have two parts. The "static" part on the left contains no
1740 // computed property names, and so we can compute its map ahead of time; see
1741 // runtime.cc::CreateObjectLiteralBoilerplate. The second "dynamic" part
1742 // starts with the first computed property name, and continues with all
1743 // properties to its right. All the code from above initializes the static
1744 // component of the object literal, and arranges for the map of the result to
1745 // reflect the static order in which the keys appear. For the dynamic
1746 // properties, we compile them into a series of "SetOwnProperty" runtime
1747 // calls. This will preserve insertion order.
1748 for (; property_index < expr->properties()->length(); property_index++) {
1749 ObjectLiteral::Property* property = expr->properties()->at(property_index);
1751 Expression* value = property->value();
1752 if (!result_saved) {
1753 __ push(eax); // Save result on the stack
1754 result_saved = true;
1757 __ push(Operand(esp, 0)); // Duplicate receiver.
1759 if (property->kind() == ObjectLiteral::Property::PROTOTYPE) {
1760 DCHECK(!property->is_computed_name());
1761 VisitForStackValue(value);
1762 DCHECK(property->emit_store());
1763 __ CallRuntime(Runtime::kInternalSetPrototype, 2);
1765 EmitPropertyKey(property, expr->GetIdForProperty(property_index));
1766 VisitForStackValue(value);
1767 EmitSetHomeObjectIfNeeded(value, 2);
1769 switch (property->kind()) {
1770 case ObjectLiteral::Property::CONSTANT:
1771 case ObjectLiteral::Property::MATERIALIZED_LITERAL:
1772 case ObjectLiteral::Property::COMPUTED:
1773 if (property->emit_store()) {
1774 __ push(Immediate(Smi::FromInt(NONE)));
1775 __ CallRuntime(Runtime::kDefineDataPropertyUnchecked, 4);
1781 case ObjectLiteral::Property::PROTOTYPE:
1785 case ObjectLiteral::Property::GETTER:
1786 __ push(Immediate(Smi::FromInt(NONE)));
1787 __ CallRuntime(Runtime::kDefineGetterPropertyUnchecked, 4);
1790 case ObjectLiteral::Property::SETTER:
1791 __ push(Immediate(Smi::FromInt(NONE)));
1792 __ CallRuntime(Runtime::kDefineSetterPropertyUnchecked, 4);
1798 if (expr->has_function()) {
1799 DCHECK(result_saved);
1800 __ push(Operand(esp, 0));
1801 __ CallRuntime(Runtime::kToFastProperties, 1);
1805 context()->PlugTOS();
1807 context()->Plug(eax);
1812 void FullCodeGenerator::VisitArrayLiteral(ArrayLiteral* expr) {
1813 Comment cmnt(masm_, "[ ArrayLiteral");
1815 expr->BuildConstantElements(isolate());
1816 int flags = expr->depth() == 1
1817 ? ArrayLiteral::kShallowElements
1818 : ArrayLiteral::kNoFlags;
1820 ZoneList<Expression*>* subexprs = expr->values();
1821 int length = subexprs->length();
1822 Handle<FixedArray> constant_elements = expr->constant_elements();
1823 DCHECK_EQ(2, constant_elements->length());
1824 ElementsKind constant_elements_kind =
1825 static_cast<ElementsKind>(Smi::cast(constant_elements->get(0))->value());
1826 bool has_constant_fast_elements =
1827 IsFastObjectElementsKind(constant_elements_kind);
1828 Handle<FixedArrayBase> constant_elements_values(
1829 FixedArrayBase::cast(constant_elements->get(1)));
1831 AllocationSiteMode allocation_site_mode = TRACK_ALLOCATION_SITE;
1832 if (has_constant_fast_elements && !FLAG_allocation_site_pretenuring) {
1833 // If the only customer of allocation sites is transitioning, then
1834 // we can turn it off if we don't have anywhere else to transition to.
1835 allocation_site_mode = DONT_TRACK_ALLOCATION_SITE;
1838 if (expr->depth() > 1 || length > JSObject::kInitialMaxFastElementArray) {
1839 __ mov(ebx, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
1840 __ push(FieldOperand(ebx, JSFunction::kLiteralsOffset));
1841 __ push(Immediate(Smi::FromInt(expr->literal_index())));
1842 __ push(Immediate(constant_elements));
1843 __ push(Immediate(Smi::FromInt(flags)));
1844 __ CallRuntime(Runtime::kCreateArrayLiteral, 4);
1846 __ mov(ebx, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
1847 __ mov(eax, FieldOperand(ebx, JSFunction::kLiteralsOffset));
1848 __ mov(ebx, Immediate(Smi::FromInt(expr->literal_index())));
1849 __ mov(ecx, Immediate(constant_elements));
1850 FastCloneShallowArrayStub stub(isolate(), allocation_site_mode);
1853 PrepareForBailoutForId(expr->CreateLiteralId(), TOS_REG);
1855 bool result_saved = false; // Is the result saved to the stack?
1857 // Emit code to evaluate all the non-constant subexpressions and to store
1858 // them into the newly cloned array.
1859 for (int i = 0; i < length; i++) {
1860 Expression* subexpr = subexprs->at(i);
1861 // If the subexpression is a literal or a simple materialized literal it
1862 // is already set in the cloned array.
1863 if (CompileTimeValue::IsCompileTimeValue(subexpr)) continue;
1865 if (!result_saved) {
1866 __ push(eax); // array literal.
1867 __ push(Immediate(Smi::FromInt(expr->literal_index())));
1868 result_saved = true;
1870 VisitForAccumulatorValue(subexpr);
1872 if (IsFastObjectElementsKind(constant_elements_kind)) {
1873 // Fast-case array literal with ElementsKind of FAST_*_ELEMENTS, they
1874 // cannot transition and don't need to call the runtime stub.
1875 int offset = FixedArray::kHeaderSize + (i * kPointerSize);
1876 __ mov(ebx, Operand(esp, kPointerSize)); // Copy of array literal.
1877 __ mov(ebx, FieldOperand(ebx, JSObject::kElementsOffset));
1878 // Store the subexpression value in the array's elements.
1879 __ mov(FieldOperand(ebx, offset), result_register());
1880 // Update the write barrier for the array store.
1881 __ RecordWriteField(ebx, offset, result_register(), ecx, kDontSaveFPRegs,
1882 EMIT_REMEMBERED_SET, INLINE_SMI_CHECK);
1884 // Store the subexpression value in the array's elements.
1885 __ mov(ecx, Immediate(Smi::FromInt(i)));
1886 StoreArrayLiteralElementStub stub(isolate());
1890 PrepareForBailoutForId(expr->GetIdForElement(i), NO_REGISTERS);
1894 __ add(esp, Immediate(kPointerSize)); // literal index
1895 context()->PlugTOS();
1897 context()->Plug(eax);
1902 void FullCodeGenerator::VisitAssignment(Assignment* expr) {
1903 DCHECK(expr->target()->IsValidReferenceExpression());
1905 Comment cmnt(masm_, "[ Assignment");
1907 Property* property = expr->target()->AsProperty();
1908 LhsKind assign_type = GetAssignType(property);
1910 // Evaluate LHS expression.
1911 switch (assign_type) {
1913 // Nothing to do here.
1915 case NAMED_SUPER_PROPERTY:
1916 VisitForStackValue(property->obj()->AsSuperReference()->this_var());
1917 EmitLoadHomeObject(property->obj()->AsSuperReference());
1918 __ push(result_register());
1919 if (expr->is_compound()) {
1920 __ push(MemOperand(esp, kPointerSize));
1921 __ push(result_register());
1924 case NAMED_PROPERTY:
1925 if (expr->is_compound()) {
1926 // We need the receiver both on the stack and in the register.
1927 VisitForStackValue(property->obj());
1928 __ mov(LoadDescriptor::ReceiverRegister(), Operand(esp, 0));
1930 VisitForStackValue(property->obj());
1933 case KEYED_SUPER_PROPERTY:
1934 VisitForStackValue(property->obj()->AsSuperReference()->this_var());
1935 EmitLoadHomeObject(property->obj()->AsSuperReference());
1936 __ Push(result_register());
1937 VisitForAccumulatorValue(property->key());
1938 __ Push(result_register());
1939 if (expr->is_compound()) {
1940 __ push(MemOperand(esp, 2 * kPointerSize));
1941 __ push(MemOperand(esp, 2 * kPointerSize));
1942 __ push(result_register());
1945 case KEYED_PROPERTY: {
1946 if (expr->is_compound()) {
1947 VisitForStackValue(property->obj());
1948 VisitForStackValue(property->key());
1949 __ mov(LoadDescriptor::ReceiverRegister(), Operand(esp, kPointerSize));
1950 __ mov(LoadDescriptor::NameRegister(), Operand(esp, 0));
1952 VisitForStackValue(property->obj());
1953 VisitForStackValue(property->key());
1959 // For compound assignments we need another deoptimization point after the
1960 // variable/property load.
1961 if (expr->is_compound()) {
1962 AccumulatorValueContext result_context(this);
1963 { AccumulatorValueContext left_operand_context(this);
1964 switch (assign_type) {
1966 EmitVariableLoad(expr->target()->AsVariableProxy());
1967 PrepareForBailout(expr->target(), TOS_REG);
1969 case NAMED_SUPER_PROPERTY:
1970 EmitNamedSuperPropertyLoad(property);
1971 PrepareForBailoutForId(property->LoadId(), TOS_REG);
1973 case NAMED_PROPERTY:
1974 EmitNamedPropertyLoad(property);
1975 PrepareForBailoutForId(property->LoadId(), TOS_REG);
1977 case KEYED_SUPER_PROPERTY:
1978 EmitKeyedSuperPropertyLoad(property);
1979 PrepareForBailoutForId(property->LoadId(), TOS_REG);
1981 case KEYED_PROPERTY:
1982 EmitKeyedPropertyLoad(property);
1983 PrepareForBailoutForId(property->LoadId(), TOS_REG);
1988 Token::Value op = expr->binary_op();
1989 __ push(eax); // Left operand goes on the stack.
1990 VisitForAccumulatorValue(expr->value());
1992 SetSourcePosition(expr->position() + 1);
1993 if (ShouldInlineSmiCase(op)) {
1994 EmitInlineSmiBinaryOp(expr->binary_operation(),
1999 EmitBinaryOp(expr->binary_operation(), op);
2002 // Deoptimization point in case the binary operation may have side effects.
2003 PrepareForBailout(expr->binary_operation(), TOS_REG);
2005 VisitForAccumulatorValue(expr->value());
2008 // Record source position before possible IC call.
2009 SetSourcePosition(expr->position());
2012 switch (assign_type) {
2014 EmitVariableAssignment(expr->target()->AsVariableProxy()->var(),
2016 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
2017 context()->Plug(eax);
2019 case NAMED_PROPERTY:
2020 EmitNamedPropertyAssignment(expr);
2022 case NAMED_SUPER_PROPERTY:
2023 EmitNamedSuperPropertyStore(property);
2024 context()->Plug(result_register());
2026 case KEYED_SUPER_PROPERTY:
2027 EmitKeyedSuperPropertyStore(property);
2028 context()->Plug(result_register());
2030 case KEYED_PROPERTY:
2031 EmitKeyedPropertyAssignment(expr);
2037 void FullCodeGenerator::VisitYield(Yield* expr) {
2038 Comment cmnt(masm_, "[ Yield");
2039 // Evaluate yielded value first; the initial iterator definition depends on
2040 // this. It stays on the stack while we update the iterator.
2041 VisitForStackValue(expr->expression());
2043 switch (expr->yield_kind()) {
2044 case Yield::kSuspend:
2045 // Pop value from top-of-stack slot; box result into result register.
2046 EmitCreateIteratorResult(false);
2047 __ push(result_register());
2049 case Yield::kInitial: {
2050 Label suspend, continuation, post_runtime, resume;
2054 __ bind(&continuation);
2058 VisitForAccumulatorValue(expr->generator_object());
2059 DCHECK(continuation.pos() > 0 && Smi::IsValid(continuation.pos()));
2060 __ mov(FieldOperand(eax, JSGeneratorObject::kContinuationOffset),
2061 Immediate(Smi::FromInt(continuation.pos())));
2062 __ mov(FieldOperand(eax, JSGeneratorObject::kContextOffset), esi);
2064 __ RecordWriteField(eax, JSGeneratorObject::kContextOffset, ecx, edx,
2066 __ lea(ebx, Operand(ebp, StandardFrameConstants::kExpressionsOffset));
2068 __ j(equal, &post_runtime);
2069 __ push(eax); // generator object
2070 __ CallRuntime(Runtime::kSuspendJSGeneratorObject, 1);
2071 __ mov(context_register(),
2072 Operand(ebp, StandardFrameConstants::kContextOffset));
2073 __ bind(&post_runtime);
2074 __ pop(result_register());
2075 EmitReturnSequence();
2078 context()->Plug(result_register());
2082 case Yield::kFinal: {
2083 VisitForAccumulatorValue(expr->generator_object());
2084 __ mov(FieldOperand(result_register(),
2085 JSGeneratorObject::kContinuationOffset),
2086 Immediate(Smi::FromInt(JSGeneratorObject::kGeneratorClosed)));
2087 // Pop value from top-of-stack slot, box result into result register.
2088 EmitCreateIteratorResult(true);
2089 EmitUnwindBeforeReturn();
2090 EmitReturnSequence();
2094 case Yield::kDelegating: {
2095 VisitForStackValue(expr->generator_object());
2097 // Initial stack layout is as follows:
2098 // [sp + 1 * kPointerSize] iter
2099 // [sp + 0 * kPointerSize] g
2101 Label l_catch, l_try, l_suspend, l_continuation, l_resume;
2102 Label l_next, l_call, l_loop;
2103 Register load_receiver = LoadDescriptor::ReceiverRegister();
2104 Register load_name = LoadDescriptor::NameRegister();
2106 // Initial send value is undefined.
2107 __ mov(eax, isolate()->factory()->undefined_value());
2110 // catch (e) { receiver = iter; f = 'throw'; arg = e; goto l_call; }
2112 __ mov(load_name, isolate()->factory()->throw_string()); // "throw"
2113 __ push(load_name); // "throw"
2114 __ push(Operand(esp, 2 * kPointerSize)); // iter
2115 __ push(eax); // exception
2118 // try { received = %yield result }
2119 // Shuffle the received result above a try handler and yield it without
2122 __ pop(eax); // result
2123 EnterTryBlock(expr->index(), &l_catch);
2124 const int try_block_size = TryCatch::kElementCount * kPointerSize;
2125 __ push(eax); // result
2127 __ bind(&l_continuation);
2129 __ bind(&l_suspend);
2130 const int generator_object_depth = kPointerSize + try_block_size;
2131 __ mov(eax, Operand(esp, generator_object_depth));
2133 __ push(Immediate(Smi::FromInt(expr->index()))); // handler-index
2134 DCHECK(l_continuation.pos() > 0 && Smi::IsValid(l_continuation.pos()));
2135 __ mov(FieldOperand(eax, JSGeneratorObject::kContinuationOffset),
2136 Immediate(Smi::FromInt(l_continuation.pos())));
2137 __ mov(FieldOperand(eax, JSGeneratorObject::kContextOffset), esi);
2139 __ RecordWriteField(eax, JSGeneratorObject::kContextOffset, ecx, edx,
2141 __ CallRuntime(Runtime::kSuspendJSGeneratorObject, 2);
2142 __ mov(context_register(),
2143 Operand(ebp, StandardFrameConstants::kContextOffset));
2144 __ pop(eax); // result
2145 EmitReturnSequence();
2146 __ bind(&l_resume); // received in eax
2147 ExitTryBlock(expr->index());
2149 // receiver = iter; f = iter.next; arg = received;
2152 __ mov(load_name, isolate()->factory()->next_string());
2153 __ push(load_name); // "next"
2154 __ push(Operand(esp, 2 * kPointerSize)); // iter
2155 __ push(eax); // received
2157 // result = receiver[f](arg);
2159 __ mov(load_receiver, Operand(esp, kPointerSize));
2160 if (FLAG_vector_ics) {
2161 __ mov(VectorLoadICDescriptor::SlotRegister(),
2162 Immediate(SmiFromSlot(expr->KeyedLoadFeedbackSlot())));
2164 Handle<Code> ic = CodeFactory::KeyedLoadIC(isolate()).code();
2165 CallIC(ic, TypeFeedbackId::None());
2167 __ mov(Operand(esp, 2 * kPointerSize), edi);
2168 CallFunctionStub stub(isolate(), 1, CALL_AS_METHOD);
2171 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
2172 __ Drop(1); // The function is still on the stack; drop it.
2174 // if (!result.done) goto l_try;
2176 __ push(eax); // save result
2177 __ Move(load_receiver, eax); // result
2179 isolate()->factory()->done_string()); // "done"
2180 if (FLAG_vector_ics) {
2181 __ mov(VectorLoadICDescriptor::SlotRegister(),
2182 Immediate(SmiFromSlot(expr->DoneFeedbackSlot())));
2184 CallLoadIC(NOT_CONTEXTUAL); // result.done in eax
2185 Handle<Code> bool_ic = ToBooleanStub::GetUninitialized(isolate());
2191 __ pop(load_receiver); // result
2193 isolate()->factory()->value_string()); // "value"
2194 if (FLAG_vector_ics) {
2195 __ mov(VectorLoadICDescriptor::SlotRegister(),
2196 Immediate(SmiFromSlot(expr->ValueFeedbackSlot())));
2198 CallLoadIC(NOT_CONTEXTUAL); // result.value in eax
2199 context()->DropAndPlug(2, eax); // drop iter and g
2206 void FullCodeGenerator::EmitGeneratorResume(Expression *generator,
2208 JSGeneratorObject::ResumeMode resume_mode) {
2209 // The value stays in eax, and is ultimately read by the resumed generator, as
2210 // if CallRuntime(Runtime::kSuspendJSGeneratorObject) returned it. Or it
2211 // is read to throw the value when the resumed generator is already closed.
2212 // ebx will hold the generator object until the activation has been resumed.
2213 VisitForStackValue(generator);
2214 VisitForAccumulatorValue(value);
2217 // Load suspended function and context.
2218 __ mov(esi, FieldOperand(ebx, JSGeneratorObject::kContextOffset));
2219 __ mov(edi, FieldOperand(ebx, JSGeneratorObject::kFunctionOffset));
2222 __ push(FieldOperand(ebx, JSGeneratorObject::kReceiverOffset));
2224 // Push holes for arguments to generator function.
2225 __ mov(edx, FieldOperand(edi, JSFunction::kSharedFunctionInfoOffset));
2227 FieldOperand(edx, SharedFunctionInfo::kFormalParameterCountOffset));
2228 __ mov(ecx, isolate()->factory()->the_hole_value());
2229 Label push_argument_holes, push_frame;
2230 __ bind(&push_argument_holes);
2231 __ sub(edx, Immediate(Smi::FromInt(1)));
2232 __ j(carry, &push_frame);
2234 __ jmp(&push_argument_holes);
2236 // Enter a new JavaScript frame, and initialize its slots as they were when
2237 // the generator was suspended.
2238 Label resume_frame, done;
2239 __ bind(&push_frame);
2240 __ call(&resume_frame);
2242 __ bind(&resume_frame);
2243 __ push(ebp); // Caller's frame pointer.
2245 __ push(esi); // Callee's context.
2246 __ push(edi); // Callee's JS Function.
2248 // Load the operand stack size.
2249 __ mov(edx, FieldOperand(ebx, JSGeneratorObject::kOperandStackOffset));
2250 __ mov(edx, FieldOperand(edx, FixedArray::kLengthOffset));
2253 // If we are sending a value and there is no operand stack, we can jump back
2255 if (resume_mode == JSGeneratorObject::NEXT) {
2257 __ cmp(edx, Immediate(0));
2258 __ j(not_zero, &slow_resume);
2259 __ mov(edx, FieldOperand(edi, JSFunction::kCodeEntryOffset));
2260 __ mov(ecx, FieldOperand(ebx, JSGeneratorObject::kContinuationOffset));
2263 __ mov(FieldOperand(ebx, JSGeneratorObject::kContinuationOffset),
2264 Immediate(Smi::FromInt(JSGeneratorObject::kGeneratorExecuting)));
2266 __ bind(&slow_resume);
2269 // Otherwise, we push holes for the operand stack and call the runtime to fix
2270 // up the stack and the handlers.
2271 Label push_operand_holes, call_resume;
2272 __ bind(&push_operand_holes);
2273 __ sub(edx, Immediate(1));
2274 __ j(carry, &call_resume);
2276 __ jmp(&push_operand_holes);
2277 __ bind(&call_resume);
2279 __ push(result_register());
2280 __ Push(Smi::FromInt(resume_mode));
2281 __ CallRuntime(Runtime::kResumeJSGeneratorObject, 3);
2282 // Not reached: the runtime call returns elsewhere.
2283 __ Abort(kGeneratorFailedToResume);
2286 context()->Plug(result_register());
2290 void FullCodeGenerator::EmitCreateIteratorResult(bool done) {
2294 const int instance_size = 5 * kPointerSize;
2295 DCHECK_EQ(isolate()->native_context()->iterator_result_map()->instance_size(),
2298 __ Allocate(instance_size, eax, ecx, edx, &gc_required, TAG_OBJECT);
2301 __ bind(&gc_required);
2302 __ Push(Smi::FromInt(instance_size));
2303 __ CallRuntime(Runtime::kAllocateInNewSpace, 1);
2304 __ mov(context_register(),
2305 Operand(ebp, StandardFrameConstants::kContextOffset));
2307 __ bind(&allocated);
2308 __ mov(ebx, Operand(esi, Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX)));
2309 __ mov(ebx, FieldOperand(ebx, GlobalObject::kNativeContextOffset));
2310 __ mov(ebx, ContextOperand(ebx, Context::ITERATOR_RESULT_MAP_INDEX));
2312 __ mov(edx, isolate()->factory()->ToBoolean(done));
2313 __ mov(FieldOperand(eax, HeapObject::kMapOffset), ebx);
2314 __ mov(FieldOperand(eax, JSObject::kPropertiesOffset),
2315 isolate()->factory()->empty_fixed_array());
2316 __ mov(FieldOperand(eax, JSObject::kElementsOffset),
2317 isolate()->factory()->empty_fixed_array());
2318 __ mov(FieldOperand(eax, JSGeneratorObject::kResultValuePropertyOffset), ecx);
2319 __ mov(FieldOperand(eax, JSGeneratorObject::kResultDonePropertyOffset), edx);
2321 // Only the value field needs a write barrier, as the other values are in the
2323 __ RecordWriteField(eax, JSGeneratorObject::kResultValuePropertyOffset, ecx,
2324 edx, kDontSaveFPRegs);
2328 void FullCodeGenerator::EmitNamedPropertyLoad(Property* prop) {
2329 SetSourcePosition(prop->position());
2330 Literal* key = prop->key()->AsLiteral();
2331 DCHECK(!key->value()->IsSmi());
2332 DCHECK(!prop->IsSuperAccess());
2334 __ mov(LoadDescriptor::NameRegister(), Immediate(key->value()));
2335 if (FLAG_vector_ics) {
2336 __ mov(VectorLoadICDescriptor::SlotRegister(),
2337 Immediate(SmiFromSlot(prop->PropertyFeedbackSlot())));
2338 CallLoadIC(NOT_CONTEXTUAL);
2340 CallLoadIC(NOT_CONTEXTUAL, prop->PropertyFeedbackId());
2345 void FullCodeGenerator::EmitNamedSuperPropertyLoad(Property* prop) {
2346 // Stack: receiver, home_object.
2347 SetSourcePosition(prop->position());
2348 Literal* key = prop->key()->AsLiteral();
2349 DCHECK(!key->value()->IsSmi());
2350 DCHECK(prop->IsSuperAccess());
2352 __ push(Immediate(key->value()));
2353 __ CallRuntime(Runtime::kLoadFromSuper, 3);
2357 void FullCodeGenerator::EmitKeyedPropertyLoad(Property* prop) {
2358 SetSourcePosition(prop->position());
2359 Handle<Code> ic = CodeFactory::KeyedLoadIC(isolate()).code();
2360 if (FLAG_vector_ics) {
2361 __ mov(VectorLoadICDescriptor::SlotRegister(),
2362 Immediate(SmiFromSlot(prop->PropertyFeedbackSlot())));
2365 CallIC(ic, prop->PropertyFeedbackId());
2370 void FullCodeGenerator::EmitKeyedSuperPropertyLoad(Property* prop) {
2371 // Stack: receiver, home_object, key.
2372 SetSourcePosition(prop->position());
2374 __ CallRuntime(Runtime::kLoadKeyedFromSuper, 3);
2378 void FullCodeGenerator::EmitInlineSmiBinaryOp(BinaryOperation* expr,
2381 Expression* right) {
2382 // Do combined smi check of the operands. Left operand is on the
2383 // stack. Right operand is in eax.
2384 Label smi_case, done, stub_call;
2388 JumpPatchSite patch_site(masm_);
2389 patch_site.EmitJumpIfSmi(eax, &smi_case, Label::kNear);
2391 __ bind(&stub_call);
2393 Handle<Code> code = CodeFactory::BinaryOpIC(isolate(), op).code();
2394 CallIC(code, expr->BinaryOperationFeedbackId());
2395 patch_site.EmitPatchInfo();
2396 __ jmp(&done, Label::kNear);
2400 __ mov(eax, edx); // Copy left operand in case of a stub call.
2405 __ sar_cl(eax); // No checks of result necessary
2406 __ and_(eax, Immediate(~kSmiTagMask));
2413 // Check that the *signed* result fits in a smi.
2414 __ cmp(eax, 0xc0000000);
2415 __ j(positive, &result_ok);
2418 __ bind(&result_ok);
2427 __ test(eax, Immediate(0xc0000000));
2428 __ j(zero, &result_ok);
2431 __ bind(&result_ok);
2437 __ j(overflow, &stub_call);
2441 __ j(overflow, &stub_call);
2446 __ j(overflow, &stub_call);
2448 __ j(not_zero, &done, Label::kNear);
2451 __ j(negative, &stub_call);
2457 case Token::BIT_AND:
2460 case Token::BIT_XOR:
2468 context()->Plug(eax);
2472 void FullCodeGenerator::EmitClassDefineProperties(ClassLiteral* lit) {
2473 // Constructor is in eax.
2474 DCHECK(lit != NULL);
2477 // No access check is needed here since the constructor is created by the
2479 Register scratch = ebx;
2480 __ mov(scratch, FieldOperand(eax, JSFunction::kPrototypeOrInitialMapOffset));
2483 for (int i = 0; i < lit->properties()->length(); i++) {
2484 ObjectLiteral::Property* property = lit->properties()->at(i);
2485 Expression* value = property->value();
2487 if (property->is_static()) {
2488 __ push(Operand(esp, kPointerSize)); // constructor
2490 __ push(Operand(esp, 0)); // prototype
2492 EmitPropertyKey(property, lit->GetIdForProperty(i));
2494 // The static prototype property is read only. We handle the non computed
2495 // property name case in the parser. Since this is the only case where we
2496 // need to check for an own read only property we special case this so we do
2497 // not need to do this for every property.
2498 if (property->is_static() && property->is_computed_name()) {
2499 __ CallRuntime(Runtime::kThrowIfStaticPrototype, 1);
2503 VisitForStackValue(value);
2504 EmitSetHomeObjectIfNeeded(value, 2);
2506 switch (property->kind()) {
2507 case ObjectLiteral::Property::CONSTANT:
2508 case ObjectLiteral::Property::MATERIALIZED_LITERAL:
2509 case ObjectLiteral::Property::PROTOTYPE:
2511 case ObjectLiteral::Property::COMPUTED:
2512 __ CallRuntime(Runtime::kDefineClassMethod, 3);
2515 case ObjectLiteral::Property::GETTER:
2516 __ push(Immediate(Smi::FromInt(DONT_ENUM)));
2517 __ CallRuntime(Runtime::kDefineGetterPropertyUnchecked, 4);
2520 case ObjectLiteral::Property::SETTER:
2521 __ push(Immediate(Smi::FromInt(DONT_ENUM)));
2522 __ CallRuntime(Runtime::kDefineSetterPropertyUnchecked, 4);
2528 __ CallRuntime(Runtime::kToFastProperties, 1);
2531 __ CallRuntime(Runtime::kToFastProperties, 1);
2535 void FullCodeGenerator::EmitBinaryOp(BinaryOperation* expr, Token::Value op) {
2537 Handle<Code> code = CodeFactory::BinaryOpIC(isolate(), op).code();
2538 JumpPatchSite patch_site(masm_); // unbound, signals no inlined smi code.
2539 CallIC(code, expr->BinaryOperationFeedbackId());
2540 patch_site.EmitPatchInfo();
2541 context()->Plug(eax);
2545 void FullCodeGenerator::EmitAssignment(Expression* expr) {
2546 DCHECK(expr->IsValidReferenceExpression());
2548 Property* prop = expr->AsProperty();
2549 LhsKind assign_type = GetAssignType(prop);
2551 switch (assign_type) {
2553 Variable* var = expr->AsVariableProxy()->var();
2554 EffectContext context(this);
2555 EmitVariableAssignment(var, Token::ASSIGN);
2558 case NAMED_PROPERTY: {
2559 __ push(eax); // Preserve value.
2560 VisitForAccumulatorValue(prop->obj());
2561 __ Move(StoreDescriptor::ReceiverRegister(), eax);
2562 __ pop(StoreDescriptor::ValueRegister()); // Restore value.
2563 __ mov(StoreDescriptor::NameRegister(),
2564 prop->key()->AsLiteral()->value());
2568 case NAMED_SUPER_PROPERTY: {
2570 VisitForStackValue(prop->obj()->AsSuperReference()->this_var());
2571 EmitLoadHomeObject(prop->obj()->AsSuperReference());
2572 // stack: value, this; eax: home_object
2573 Register scratch = ecx;
2574 Register scratch2 = edx;
2575 __ mov(scratch, result_register()); // home_object
2576 __ mov(eax, MemOperand(esp, kPointerSize)); // value
2577 __ mov(scratch2, MemOperand(esp, 0)); // this
2578 __ mov(MemOperand(esp, kPointerSize), scratch2); // this
2579 __ mov(MemOperand(esp, 0), scratch); // home_object
2580 // stack: this, home_object. eax: value
2581 EmitNamedSuperPropertyStore(prop);
2584 case KEYED_SUPER_PROPERTY: {
2586 VisitForStackValue(prop->obj()->AsSuperReference()->this_var());
2587 EmitLoadHomeObject(prop->obj()->AsSuperReference());
2588 __ push(result_register());
2589 VisitForAccumulatorValue(prop->key());
2590 Register scratch = ecx;
2591 Register scratch2 = edx;
2592 __ mov(scratch2, MemOperand(esp, 2 * kPointerSize)); // value
2593 // stack: value, this, home_object; eax: key, edx: value
2594 __ mov(scratch, MemOperand(esp, kPointerSize)); // this
2595 __ mov(MemOperand(esp, 2 * kPointerSize), scratch);
2596 __ mov(scratch, MemOperand(esp, 0)); // home_object
2597 __ mov(MemOperand(esp, kPointerSize), scratch);
2598 __ mov(MemOperand(esp, 0), eax);
2599 __ mov(eax, scratch2);
2600 // stack: this, home_object, key; eax: value.
2601 EmitKeyedSuperPropertyStore(prop);
2604 case KEYED_PROPERTY: {
2605 __ push(eax); // Preserve value.
2606 VisitForStackValue(prop->obj());
2607 VisitForAccumulatorValue(prop->key());
2608 __ Move(StoreDescriptor::NameRegister(), eax);
2609 __ pop(StoreDescriptor::ReceiverRegister()); // Receiver.
2610 __ pop(StoreDescriptor::ValueRegister()); // Restore value.
2612 CodeFactory::KeyedStoreIC(isolate(), language_mode()).code();
2617 context()->Plug(eax);
2621 void FullCodeGenerator::EmitStoreToStackLocalOrContextSlot(
2622 Variable* var, MemOperand location) {
2623 __ mov(location, eax);
2624 if (var->IsContextSlot()) {
2626 int offset = Context::SlotOffset(var->index());
2627 __ RecordWriteContextSlot(ecx, offset, edx, ebx, kDontSaveFPRegs);
2632 void FullCodeGenerator::EmitVariableAssignment(Variable* var,
2634 if (var->IsUnallocated()) {
2635 // Global var, const, or let.
2636 __ mov(StoreDescriptor::NameRegister(), var->name());
2637 __ mov(StoreDescriptor::ReceiverRegister(), GlobalObjectOperand());
2640 } else if (var->mode() == LET && op != Token::INIT_LET) {
2641 // Non-initializing assignment to let variable needs a write barrier.
2642 DCHECK(!var->IsLookupSlot());
2643 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
2645 MemOperand location = VarOperand(var, ecx);
2646 __ mov(edx, location);
2647 __ cmp(edx, isolate()->factory()->the_hole_value());
2648 __ j(not_equal, &assign, Label::kNear);
2649 __ push(Immediate(var->name()));
2650 __ CallRuntime(Runtime::kThrowReferenceError, 1);
2652 EmitStoreToStackLocalOrContextSlot(var, location);
2654 } else if (var->mode() == CONST && op != Token::INIT_CONST) {
2655 // Assignment to const variable needs a write barrier.
2656 DCHECK(!var->IsLookupSlot());
2657 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
2659 MemOperand location = VarOperand(var, ecx);
2660 __ mov(edx, location);
2661 __ cmp(edx, isolate()->factory()->the_hole_value());
2662 __ j(not_equal, &const_error, Label::kNear);
2663 __ push(Immediate(var->name()));
2664 __ CallRuntime(Runtime::kThrowReferenceError, 1);
2665 __ bind(&const_error);
2666 __ CallRuntime(Runtime::kThrowConstAssignError, 0);
2668 } else if (!var->is_const_mode() || op == Token::INIT_CONST) {
2669 if (var->IsLookupSlot()) {
2670 // Assignment to var.
2671 __ push(eax); // Value.
2672 __ push(esi); // Context.
2673 __ push(Immediate(var->name()));
2674 __ push(Immediate(Smi::FromInt(language_mode())));
2675 __ CallRuntime(Runtime::kStoreLookupSlot, 4);
2677 // Assignment to var or initializing assignment to let/const in harmony
2679 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
2680 MemOperand location = VarOperand(var, ecx);
2681 if (generate_debug_code_ && op == Token::INIT_LET) {
2682 // Check for an uninitialized let binding.
2683 __ mov(edx, location);
2684 __ cmp(edx, isolate()->factory()->the_hole_value());
2685 __ Check(equal, kLetBindingReInitialization);
2687 EmitStoreToStackLocalOrContextSlot(var, location);
2690 } else if (op == Token::INIT_CONST_LEGACY) {
2691 // Const initializers need a write barrier.
2692 DCHECK(var->mode() == CONST_LEGACY);
2693 DCHECK(!var->IsParameter()); // No const parameters.
2694 if (var->IsLookupSlot()) {
2697 __ push(Immediate(var->name()));
2698 __ CallRuntime(Runtime::kInitializeLegacyConstLookupSlot, 3);
2700 DCHECK(var->IsStackLocal() || var->IsContextSlot());
2702 MemOperand location = VarOperand(var, ecx);
2703 __ mov(edx, location);
2704 __ cmp(edx, isolate()->factory()->the_hole_value());
2705 __ j(not_equal, &skip, Label::kNear);
2706 EmitStoreToStackLocalOrContextSlot(var, location);
2711 DCHECK(var->mode() == CONST_LEGACY && op != Token::INIT_CONST_LEGACY);
2712 if (is_strict(language_mode())) {
2713 __ CallRuntime(Runtime::kThrowConstAssignError, 0);
2715 // Silently ignore store in sloppy mode.
2720 void FullCodeGenerator::EmitNamedPropertyAssignment(Assignment* expr) {
2721 // Assignment to a property, using a named store IC.
2723 // esp[0] : receiver
2725 Property* prop = expr->target()->AsProperty();
2726 DCHECK(prop != NULL);
2727 DCHECK(prop->key()->IsLiteral());
2729 // Record source code position before IC call.
2730 SetSourcePosition(expr->position());
2731 __ mov(StoreDescriptor::NameRegister(), prop->key()->AsLiteral()->value());
2732 __ pop(StoreDescriptor::ReceiverRegister());
2733 CallStoreIC(expr->AssignmentFeedbackId());
2734 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
2735 context()->Plug(eax);
2739 void FullCodeGenerator::EmitNamedSuperPropertyStore(Property* prop) {
2740 // Assignment to named property of super.
2742 // stack : receiver ('this'), home_object
2743 DCHECK(prop != NULL);
2744 Literal* key = prop->key()->AsLiteral();
2745 DCHECK(key != NULL);
2747 __ push(Immediate(key->value()));
2749 __ CallRuntime((is_strict(language_mode()) ? Runtime::kStoreToSuper_Strict
2750 : Runtime::kStoreToSuper_Sloppy),
2755 void FullCodeGenerator::EmitKeyedSuperPropertyStore(Property* prop) {
2756 // Assignment to named property of super.
2758 // stack : receiver ('this'), home_object, key
2762 (is_strict(language_mode()) ? Runtime::kStoreKeyedToSuper_Strict
2763 : Runtime::kStoreKeyedToSuper_Sloppy),
2768 void FullCodeGenerator::EmitKeyedPropertyAssignment(Assignment* expr) {
2769 // Assignment to a property, using a keyed store IC.
2772 // esp[kPointerSize] : receiver
2774 __ pop(StoreDescriptor::NameRegister()); // Key.
2775 __ pop(StoreDescriptor::ReceiverRegister());
2776 DCHECK(StoreDescriptor::ValueRegister().is(eax));
2777 // Record source code position before IC call.
2778 SetSourcePosition(expr->position());
2780 CodeFactory::KeyedStoreIC(isolate(), language_mode()).code();
2781 CallIC(ic, expr->AssignmentFeedbackId());
2783 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
2784 context()->Plug(eax);
2788 void FullCodeGenerator::VisitProperty(Property* expr) {
2789 Comment cmnt(masm_, "[ Property");
2790 Expression* key = expr->key();
2792 if (key->IsPropertyName()) {
2793 if (!expr->IsSuperAccess()) {
2794 VisitForAccumulatorValue(expr->obj());
2795 __ Move(LoadDescriptor::ReceiverRegister(), result_register());
2796 EmitNamedPropertyLoad(expr);
2798 VisitForStackValue(expr->obj()->AsSuperReference()->this_var());
2799 EmitLoadHomeObject(expr->obj()->AsSuperReference());
2800 __ push(result_register());
2801 EmitNamedSuperPropertyLoad(expr);
2804 if (!expr->IsSuperAccess()) {
2805 VisitForStackValue(expr->obj());
2806 VisitForAccumulatorValue(expr->key());
2807 __ pop(LoadDescriptor::ReceiverRegister()); // Object.
2808 __ Move(LoadDescriptor::NameRegister(), result_register()); // Key.
2809 EmitKeyedPropertyLoad(expr);
2811 VisitForStackValue(expr->obj()->AsSuperReference()->this_var());
2812 EmitLoadHomeObject(expr->obj()->AsSuperReference());
2813 __ push(result_register());
2814 VisitForStackValue(expr->key());
2815 EmitKeyedSuperPropertyLoad(expr);
2818 PrepareForBailoutForId(expr->LoadId(), TOS_REG);
2819 context()->Plug(eax);
2823 void FullCodeGenerator::CallIC(Handle<Code> code,
2824 TypeFeedbackId ast_id) {
2826 __ call(code, RelocInfo::CODE_TARGET, ast_id);
2830 // Code common for calls using the IC.
2831 void FullCodeGenerator::EmitCallWithLoadIC(Call* expr) {
2832 Expression* callee = expr->expression();
2834 CallICState::CallType call_type =
2835 callee->IsVariableProxy() ? CallICState::FUNCTION : CallICState::METHOD;
2836 // Get the target function.
2837 if (call_type == CallICState::FUNCTION) {
2838 { StackValueContext context(this);
2839 EmitVariableLoad(callee->AsVariableProxy());
2840 PrepareForBailout(callee, NO_REGISTERS);
2842 // Push undefined as receiver. This is patched in the method prologue if it
2843 // is a sloppy mode method.
2844 __ push(Immediate(isolate()->factory()->undefined_value()));
2846 // Load the function from the receiver.
2847 DCHECK(callee->IsProperty());
2848 DCHECK(!callee->AsProperty()->IsSuperAccess());
2849 __ mov(LoadDescriptor::ReceiverRegister(), Operand(esp, 0));
2850 EmitNamedPropertyLoad(callee->AsProperty());
2851 PrepareForBailoutForId(callee->AsProperty()->LoadId(), TOS_REG);
2852 // Push the target function under the receiver.
2853 __ push(Operand(esp, 0));
2854 __ mov(Operand(esp, kPointerSize), eax);
2857 EmitCall(expr, call_type);
2861 void FullCodeGenerator::EmitSuperCallWithLoadIC(Call* expr) {
2862 Expression* callee = expr->expression();
2863 DCHECK(callee->IsProperty());
2864 Property* prop = callee->AsProperty();
2865 DCHECK(prop->IsSuperAccess());
2867 SetSourcePosition(prop->position());
2868 Literal* key = prop->key()->AsLiteral();
2869 DCHECK(!key->value()->IsSmi());
2870 // Load the function from the receiver.
2871 SuperReference* super_ref = callee->AsProperty()->obj()->AsSuperReference();
2872 EmitLoadHomeObject(super_ref);
2874 VisitForAccumulatorValue(super_ref->this_var());
2877 __ push(Operand(esp, kPointerSize * 2));
2878 __ push(Immediate(key->value()));
2881 // - this (receiver)
2882 // - this (receiver) <-- LoadFromSuper will pop here and below.
2885 __ CallRuntime(Runtime::kLoadFromSuper, 3);
2887 // Replace home_object with target function.
2888 __ mov(Operand(esp, kPointerSize), eax);
2891 // - target function
2892 // - this (receiver)
2893 EmitCall(expr, CallICState::METHOD);
2897 // Code common for calls using the IC.
2898 void FullCodeGenerator::EmitKeyedCallWithLoadIC(Call* expr,
2901 VisitForAccumulatorValue(key);
2903 Expression* callee = expr->expression();
2905 // Load the function from the receiver.
2906 DCHECK(callee->IsProperty());
2907 __ mov(LoadDescriptor::ReceiverRegister(), Operand(esp, 0));
2908 __ mov(LoadDescriptor::NameRegister(), eax);
2909 EmitKeyedPropertyLoad(callee->AsProperty());
2910 PrepareForBailoutForId(callee->AsProperty()->LoadId(), TOS_REG);
2912 // Push the target function under the receiver.
2913 __ push(Operand(esp, 0));
2914 __ mov(Operand(esp, kPointerSize), eax);
2916 EmitCall(expr, CallICState::METHOD);
2920 void FullCodeGenerator::EmitKeyedSuperCallWithLoadIC(Call* expr) {
2921 Expression* callee = expr->expression();
2922 DCHECK(callee->IsProperty());
2923 Property* prop = callee->AsProperty();
2924 DCHECK(prop->IsSuperAccess());
2926 SetSourcePosition(prop->position());
2927 // Load the function from the receiver.
2928 SuperReference* super_ref = callee->AsProperty()->obj()->AsSuperReference();
2929 EmitLoadHomeObject(super_ref);
2931 VisitForAccumulatorValue(super_ref->this_var());
2934 __ push(Operand(esp, kPointerSize * 2));
2935 VisitForStackValue(prop->key());
2938 // - this (receiver)
2939 // - this (receiver) <-- LoadKeyedFromSuper will pop here and below.
2942 __ CallRuntime(Runtime::kLoadKeyedFromSuper, 3);
2944 // Replace home_object with target function.
2945 __ mov(Operand(esp, kPointerSize), eax);
2948 // - target function
2949 // - this (receiver)
2950 EmitCall(expr, CallICState::METHOD);
2954 void FullCodeGenerator::EmitCall(Call* expr, CallICState::CallType call_type) {
2955 // Load the arguments.
2956 ZoneList<Expression*>* args = expr->arguments();
2957 int arg_count = args->length();
2958 { PreservePositionScope scope(masm()->positions_recorder());
2959 for (int i = 0; i < arg_count; i++) {
2960 VisitForStackValue(args->at(i));
2964 // Record source position of the IC call.
2965 SetSourcePosition(expr->position());
2966 Handle<Code> ic = CodeFactory::CallIC(isolate(), arg_count, call_type).code();
2967 __ Move(edx, Immediate(SmiFromSlot(expr->CallFeedbackICSlot())));
2968 __ mov(edi, Operand(esp, (arg_count + 1) * kPointerSize));
2969 // Don't assign a type feedback id to the IC, since type feedback is provided
2970 // by the vector above.
2973 RecordJSReturnSite(expr);
2975 // Restore context register.
2976 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
2978 context()->DropAndPlug(1, eax);
2982 void FullCodeGenerator::EmitResolvePossiblyDirectEval(int arg_count) {
2983 // Push copy of the first argument or undefined if it doesn't exist.
2984 if (arg_count > 0) {
2985 __ push(Operand(esp, arg_count * kPointerSize));
2987 __ push(Immediate(isolate()->factory()->undefined_value()));
2990 // Push the enclosing function.
2991 __ push(Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
2992 // Push the receiver of the enclosing function.
2993 __ push(Operand(ebp, (2 + info_->scope()->num_parameters()) * kPointerSize));
2994 // Push the language mode.
2995 __ push(Immediate(Smi::FromInt(language_mode())));
2997 // Push the start position of the scope the calls resides in.
2998 __ push(Immediate(Smi::FromInt(scope()->start_position())));
3000 // Do the runtime call.
3001 __ CallRuntime(Runtime::kResolvePossiblyDirectEval, 6);
3005 void FullCodeGenerator::EmitLoadSuperConstructor() {
3006 __ push(Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
3007 __ CallRuntime(Runtime::kGetPrototype, 1);
3011 void FullCodeGenerator::VisitCall(Call* expr) {
3013 // We want to verify that RecordJSReturnSite gets called on all paths
3014 // through this function. Avoid early returns.
3015 expr->return_is_recorded_ = false;
3018 Comment cmnt(masm_, "[ Call");
3019 Expression* callee = expr->expression();
3020 Call::CallType call_type = expr->GetCallType(isolate());
3022 if (call_type == Call::POSSIBLY_EVAL_CALL) {
3023 // In a call to eval, we first call RuntimeHidden_ResolvePossiblyDirectEval
3024 // to resolve the function we need to call and the receiver of the call.
3025 // Then we call the resolved function using the given arguments.
3026 ZoneList<Expression*>* args = expr->arguments();
3027 int arg_count = args->length();
3028 { PreservePositionScope pos_scope(masm()->positions_recorder());
3029 VisitForStackValue(callee);
3030 // Reserved receiver slot.
3031 __ push(Immediate(isolate()->factory()->undefined_value()));
3032 // Push the arguments.
3033 for (int i = 0; i < arg_count; i++) {
3034 VisitForStackValue(args->at(i));
3037 // Push a copy of the function (found below the arguments) and
3039 __ push(Operand(esp, (arg_count + 1) * kPointerSize));
3040 EmitResolvePossiblyDirectEval(arg_count);
3042 // The runtime call returns a pair of values in eax (function) and
3043 // edx (receiver). Touch up the stack with the right values.
3044 __ mov(Operand(esp, (arg_count + 0) * kPointerSize), edx);
3045 __ mov(Operand(esp, (arg_count + 1) * kPointerSize), eax);
3047 PrepareForBailoutForId(expr->EvalOrLookupId(), NO_REGISTERS);
3049 // Record source position for debugger.
3050 SetSourcePosition(expr->position());
3051 CallFunctionStub stub(isolate(), arg_count, NO_CALL_FUNCTION_FLAGS);
3052 __ mov(edi, Operand(esp, (arg_count + 1) * kPointerSize));
3054 RecordJSReturnSite(expr);
3055 // Restore context register.
3056 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
3057 context()->DropAndPlug(1, eax);
3059 } else if (call_type == Call::GLOBAL_CALL) {
3060 EmitCallWithLoadIC(expr);
3061 } else if (call_type == Call::LOOKUP_SLOT_CALL) {
3062 // Call to a lookup slot (dynamically introduced variable).
3063 VariableProxy* proxy = callee->AsVariableProxy();
3065 { PreservePositionScope scope(masm()->positions_recorder());
3066 // Generate code for loading from variables potentially shadowed by
3067 // eval-introduced variables.
3068 EmitDynamicLookupFastCase(proxy, NOT_INSIDE_TYPEOF, &slow, &done);
3071 // Call the runtime to find the function to call (returned in eax) and
3072 // the object holding it (returned in edx).
3073 __ push(context_register());
3074 __ push(Immediate(proxy->name()));
3075 __ CallRuntime(Runtime::kLoadLookupSlot, 2);
3076 __ push(eax); // Function.
3077 __ push(edx); // Receiver.
3078 PrepareForBailoutForId(expr->EvalOrLookupId(), NO_REGISTERS);
3080 // If fast case code has been generated, emit code to push the function
3081 // and receiver and have the slow path jump around this code.
3082 if (done.is_linked()) {
3084 __ jmp(&call, Label::kNear);
3088 // The receiver is implicitly the global receiver. Indicate this by
3089 // passing the hole to the call function stub.
3090 __ push(Immediate(isolate()->factory()->undefined_value()));
3094 // The receiver is either the global receiver or an object found by
3098 } else if (call_type == Call::PROPERTY_CALL) {
3099 Property* property = callee->AsProperty();
3100 bool is_named_call = property->key()->IsPropertyName();
3101 if (property->IsSuperAccess()) {
3102 if (is_named_call) {
3103 EmitSuperCallWithLoadIC(expr);
3105 EmitKeyedSuperCallWithLoadIC(expr);
3109 PreservePositionScope scope(masm()->positions_recorder());
3110 VisitForStackValue(property->obj());
3112 if (is_named_call) {
3113 EmitCallWithLoadIC(expr);
3115 EmitKeyedCallWithLoadIC(expr, property->key());
3118 } else if (call_type == Call::SUPER_CALL) {
3119 EmitSuperConstructorCall(expr);
3121 DCHECK(call_type == Call::OTHER_CALL);
3122 // Call to an arbitrary expression not handled specially above.
3123 { PreservePositionScope scope(masm()->positions_recorder());
3124 VisitForStackValue(callee);
3126 __ push(Immediate(isolate()->factory()->undefined_value()));
3127 // Emit function call.
3132 // RecordJSReturnSite should have been called.
3133 DCHECK(expr->return_is_recorded_);
3138 void FullCodeGenerator::VisitCallNew(CallNew* expr) {
3139 Comment cmnt(masm_, "[ CallNew");
3140 // According to ECMA-262, section 11.2.2, page 44, the function
3141 // expression in new calls must be evaluated before the
3144 // Push constructor on the stack. If it's not a function it's used as
3145 // receiver for CALL_NON_FUNCTION, otherwise the value on the stack is
3147 DCHECK(!expr->expression()->IsSuperReference());
3148 VisitForStackValue(expr->expression());
3150 // Push the arguments ("left-to-right") on the stack.
3151 ZoneList<Expression*>* args = expr->arguments();
3152 int arg_count = args->length();
3153 for (int i = 0; i < arg_count; i++) {
3154 VisitForStackValue(args->at(i));
3157 // Call the construct call builtin that handles allocation and
3158 // constructor invocation.
3159 SetSourcePosition(expr->position());
3161 // Load function and argument count into edi and eax.
3162 __ Move(eax, Immediate(arg_count));
3163 __ mov(edi, Operand(esp, arg_count * kPointerSize));
3165 // Record call targets in unoptimized code.
3166 if (FLAG_pretenuring_call_new) {
3167 EnsureSlotContainsAllocationSite(expr->AllocationSiteFeedbackSlot());
3168 DCHECK(expr->AllocationSiteFeedbackSlot().ToInt() ==
3169 expr->CallNewFeedbackSlot().ToInt() + 1);
3172 __ LoadHeapObject(ebx, FeedbackVector());
3173 __ mov(edx, Immediate(SmiFromSlot(expr->CallNewFeedbackSlot())));
3175 CallConstructStub stub(isolate(), RECORD_CONSTRUCTOR_TARGET);
3176 __ call(stub.GetCode(), RelocInfo::CONSTRUCT_CALL);
3177 PrepareForBailoutForId(expr->ReturnId(), TOS_REG);
3178 context()->Plug(eax);
3182 void FullCodeGenerator::EmitSuperConstructorCall(Call* expr) {
3183 Variable* new_target_var = scope()->DeclarationScope()->new_target_var();
3184 GetVar(eax, new_target_var);
3187 EmitLoadSuperConstructor();
3188 __ push(result_register());
3190 // Push the arguments ("left-to-right") on the stack.
3191 ZoneList<Expression*>* args = expr->arguments();
3192 int arg_count = args->length();
3193 for (int i = 0; i < arg_count; i++) {
3194 VisitForStackValue(args->at(i));
3197 // Call the construct call builtin that handles allocation and
3198 // constructor invocation.
3199 SetSourcePosition(expr->position());
3201 // Load function and argument count into edi and eax.
3202 __ Move(eax, Immediate(arg_count));
3203 __ mov(edi, Operand(esp, arg_count * kPointerSize));
3205 // Record call targets in unoptimized code.
3206 if (FLAG_pretenuring_call_new) {
3208 /* TODO(dslomov): support pretenuring.
3209 EnsureSlotContainsAllocationSite(expr->AllocationSiteFeedbackSlot());
3210 DCHECK(expr->AllocationSiteFeedbackSlot().ToInt() ==
3211 expr->CallNewFeedbackSlot().ToInt() + 1);
3215 __ LoadHeapObject(ebx, FeedbackVector());
3216 __ mov(edx, Immediate(SmiFromSlot(expr->CallFeedbackSlot())));
3218 CallConstructStub stub(isolate(), SUPER_CALL_RECORD_TARGET);
3219 __ call(stub.GetCode(), RelocInfo::CONSTRUCT_CALL);
3223 RecordJSReturnSite(expr);
3225 SuperReference* super_ref = expr->expression()->AsSuperReference();
3226 Variable* this_var = super_ref->this_var()->var();
3227 GetVar(ecx, this_var);
3228 __ cmp(ecx, isolate()->factory()->the_hole_value());
3229 Label uninitialized_this;
3230 __ j(equal, &uninitialized_this);
3231 __ push(Immediate(this_var->name()));
3232 __ CallRuntime(Runtime::kThrowReferenceError, 1);
3233 __ bind(&uninitialized_this);
3235 EmitVariableAssignment(this_var, Token::INIT_CONST);
3236 context()->Plug(eax);
3240 void FullCodeGenerator::EmitIsSmi(CallRuntime* expr) {
3241 ZoneList<Expression*>* args = expr->arguments();
3242 DCHECK(args->length() == 1);
3244 VisitForAccumulatorValue(args->at(0));
3246 Label materialize_true, materialize_false;
3247 Label* if_true = NULL;
3248 Label* if_false = NULL;
3249 Label* fall_through = NULL;
3250 context()->PrepareTest(&materialize_true, &materialize_false,
3251 &if_true, &if_false, &fall_through);
3253 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3254 __ test(eax, Immediate(kSmiTagMask));
3255 Split(zero, if_true, if_false, fall_through);
3257 context()->Plug(if_true, if_false);
3261 void FullCodeGenerator::EmitIsNonNegativeSmi(CallRuntime* expr) {
3262 ZoneList<Expression*>* args = expr->arguments();
3263 DCHECK(args->length() == 1);
3265 VisitForAccumulatorValue(args->at(0));
3267 Label materialize_true, materialize_false;
3268 Label* if_true = NULL;
3269 Label* if_false = NULL;
3270 Label* fall_through = NULL;
3271 context()->PrepareTest(&materialize_true, &materialize_false,
3272 &if_true, &if_false, &fall_through);
3274 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3275 __ test(eax, Immediate(kSmiTagMask | 0x80000000));
3276 Split(zero, if_true, if_false, fall_through);
3278 context()->Plug(if_true, if_false);
3282 void FullCodeGenerator::EmitIsObject(CallRuntime* expr) {
3283 ZoneList<Expression*>* args = expr->arguments();
3284 DCHECK(args->length() == 1);
3286 VisitForAccumulatorValue(args->at(0));
3288 Label materialize_true, materialize_false;
3289 Label* if_true = NULL;
3290 Label* if_false = NULL;
3291 Label* fall_through = NULL;
3292 context()->PrepareTest(&materialize_true, &materialize_false,
3293 &if_true, &if_false, &fall_through);
3295 __ JumpIfSmi(eax, if_false);
3296 __ cmp(eax, isolate()->factory()->null_value());
3297 __ j(equal, if_true);
3298 __ mov(ebx, FieldOperand(eax, HeapObject::kMapOffset));
3299 // Undetectable objects behave like undefined when tested with typeof.
3300 __ movzx_b(ecx, FieldOperand(ebx, Map::kBitFieldOffset));
3301 __ test(ecx, Immediate(1 << Map::kIsUndetectable));
3302 __ j(not_zero, if_false);
3303 __ movzx_b(ecx, FieldOperand(ebx, Map::kInstanceTypeOffset));
3304 __ cmp(ecx, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE);
3305 __ j(below, if_false);
3306 __ cmp(ecx, LAST_NONCALLABLE_SPEC_OBJECT_TYPE);
3307 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3308 Split(below_equal, if_true, if_false, fall_through);
3310 context()->Plug(if_true, if_false);
3314 void FullCodeGenerator::EmitIsSpecObject(CallRuntime* expr) {
3315 ZoneList<Expression*>* args = expr->arguments();
3316 DCHECK(args->length() == 1);
3318 VisitForAccumulatorValue(args->at(0));
3320 Label materialize_true, materialize_false;
3321 Label* if_true = NULL;
3322 Label* if_false = NULL;
3323 Label* fall_through = NULL;
3324 context()->PrepareTest(&materialize_true, &materialize_false,
3325 &if_true, &if_false, &fall_through);
3327 __ JumpIfSmi(eax, if_false);
3328 __ CmpObjectType(eax, FIRST_SPEC_OBJECT_TYPE, ebx);
3329 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3330 Split(above_equal, if_true, if_false, fall_through);
3332 context()->Plug(if_true, if_false);
3336 void FullCodeGenerator::EmitIsUndetectableObject(CallRuntime* expr) {
3337 ZoneList<Expression*>* args = expr->arguments();
3338 DCHECK(args->length() == 1);
3340 VisitForAccumulatorValue(args->at(0));
3342 Label materialize_true, materialize_false;
3343 Label* if_true = NULL;
3344 Label* if_false = NULL;
3345 Label* fall_through = NULL;
3346 context()->PrepareTest(&materialize_true, &materialize_false,
3347 &if_true, &if_false, &fall_through);
3349 __ JumpIfSmi(eax, if_false);
3350 __ mov(ebx, FieldOperand(eax, HeapObject::kMapOffset));
3351 __ movzx_b(ebx, FieldOperand(ebx, Map::kBitFieldOffset));
3352 __ test(ebx, Immediate(1 << Map::kIsUndetectable));
3353 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3354 Split(not_zero, if_true, if_false, fall_through);
3356 context()->Plug(if_true, if_false);
3360 void FullCodeGenerator::EmitIsStringWrapperSafeForDefaultValueOf(
3361 CallRuntime* expr) {
3362 ZoneList<Expression*>* args = expr->arguments();
3363 DCHECK(args->length() == 1);
3365 VisitForAccumulatorValue(args->at(0));
3367 Label materialize_true, materialize_false, skip_lookup;
3368 Label* if_true = NULL;
3369 Label* if_false = NULL;
3370 Label* fall_through = NULL;
3371 context()->PrepareTest(&materialize_true, &materialize_false,
3372 &if_true, &if_false, &fall_through);
3374 __ AssertNotSmi(eax);
3376 // Check whether this map has already been checked to be safe for default
3378 __ mov(ebx, FieldOperand(eax, HeapObject::kMapOffset));
3379 __ test_b(FieldOperand(ebx, Map::kBitField2Offset),
3380 1 << Map::kStringWrapperSafeForDefaultValueOf);
3381 __ j(not_zero, &skip_lookup);
3383 // Check for fast case object. Return false for slow case objects.
3384 __ mov(ecx, FieldOperand(eax, JSObject::kPropertiesOffset));
3385 __ mov(ecx, FieldOperand(ecx, HeapObject::kMapOffset));
3386 __ cmp(ecx, isolate()->factory()->hash_table_map());
3387 __ j(equal, if_false);
3389 // Look for valueOf string in the descriptor array, and indicate false if
3390 // found. Since we omit an enumeration index check, if it is added via a
3391 // transition that shares its descriptor array, this is a false positive.
3392 Label entry, loop, done;
3394 // Skip loop if no descriptors are valid.
3395 __ NumberOfOwnDescriptors(ecx, ebx);
3399 __ LoadInstanceDescriptors(ebx, ebx);
3400 // ebx: descriptor array.
3401 // ecx: valid entries in the descriptor array.
3402 // Calculate the end of the descriptor array.
3403 STATIC_ASSERT(kSmiTag == 0);
3404 STATIC_ASSERT(kSmiTagSize == 1);
3405 STATIC_ASSERT(kPointerSize == 4);
3406 __ imul(ecx, ecx, DescriptorArray::kDescriptorSize);
3407 __ lea(ecx, Operand(ebx, ecx, times_4, DescriptorArray::kFirstOffset));
3408 // Calculate location of the first key name.
3409 __ add(ebx, Immediate(DescriptorArray::kFirstOffset));
3410 // Loop through all the keys in the descriptor array. If one of these is the
3411 // internalized string "valueOf" the result is false.
3414 __ mov(edx, FieldOperand(ebx, 0));
3415 __ cmp(edx, isolate()->factory()->value_of_string());
3416 __ j(equal, if_false);
3417 __ add(ebx, Immediate(DescriptorArray::kDescriptorSize * kPointerSize));
3420 __ j(not_equal, &loop);
3424 // Reload map as register ebx was used as temporary above.
3425 __ mov(ebx, FieldOperand(eax, HeapObject::kMapOffset));
3427 // Set the bit in the map to indicate that there is no local valueOf field.
3428 __ or_(FieldOperand(ebx, Map::kBitField2Offset),
3429 Immediate(1 << Map::kStringWrapperSafeForDefaultValueOf));
3431 __ bind(&skip_lookup);
3433 // If a valueOf property is not found on the object check that its
3434 // prototype is the un-modified String prototype. If not result is false.
3435 __ mov(ecx, FieldOperand(ebx, Map::kPrototypeOffset));
3436 __ JumpIfSmi(ecx, if_false);
3437 __ mov(ecx, FieldOperand(ecx, HeapObject::kMapOffset));
3438 __ mov(edx, Operand(esi, Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX)));
3440 FieldOperand(edx, GlobalObject::kNativeContextOffset));
3443 Context::STRING_FUNCTION_PROTOTYPE_MAP_INDEX));
3444 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3445 Split(equal, if_true, if_false, fall_through);
3447 context()->Plug(if_true, if_false);
3451 void FullCodeGenerator::EmitIsFunction(CallRuntime* expr) {
3452 ZoneList<Expression*>* args = expr->arguments();
3453 DCHECK(args->length() == 1);
3455 VisitForAccumulatorValue(args->at(0));
3457 Label materialize_true, materialize_false;
3458 Label* if_true = NULL;
3459 Label* if_false = NULL;
3460 Label* fall_through = NULL;
3461 context()->PrepareTest(&materialize_true, &materialize_false,
3462 &if_true, &if_false, &fall_through);
3464 __ JumpIfSmi(eax, if_false);
3465 __ CmpObjectType(eax, JS_FUNCTION_TYPE, ebx);
3466 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3467 Split(equal, if_true, if_false, fall_through);
3469 context()->Plug(if_true, if_false);
3473 void FullCodeGenerator::EmitIsMinusZero(CallRuntime* expr) {
3474 ZoneList<Expression*>* args = expr->arguments();
3475 DCHECK(args->length() == 1);
3477 VisitForAccumulatorValue(args->at(0));
3479 Label materialize_true, materialize_false;
3480 Label* if_true = NULL;
3481 Label* if_false = NULL;
3482 Label* fall_through = NULL;
3483 context()->PrepareTest(&materialize_true, &materialize_false,
3484 &if_true, &if_false, &fall_through);
3486 Handle<Map> map = masm()->isolate()->factory()->heap_number_map();
3487 __ CheckMap(eax, map, if_false, DO_SMI_CHECK);
3488 // Check if the exponent half is 0x80000000. Comparing against 1 and
3489 // checking for overflow is the shortest possible encoding.
3490 __ cmp(FieldOperand(eax, HeapNumber::kExponentOffset), Immediate(0x1));
3491 __ j(no_overflow, if_false);
3492 __ cmp(FieldOperand(eax, HeapNumber::kMantissaOffset), Immediate(0x0));
3493 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3494 Split(equal, if_true, if_false, fall_through);
3496 context()->Plug(if_true, if_false);
3501 void FullCodeGenerator::EmitIsArray(CallRuntime* expr) {
3502 ZoneList<Expression*>* args = expr->arguments();
3503 DCHECK(args->length() == 1);
3505 VisitForAccumulatorValue(args->at(0));
3507 Label materialize_true, materialize_false;
3508 Label* if_true = NULL;
3509 Label* if_false = NULL;
3510 Label* fall_through = NULL;
3511 context()->PrepareTest(&materialize_true, &materialize_false,
3512 &if_true, &if_false, &fall_through);
3514 __ JumpIfSmi(eax, if_false);
3515 __ CmpObjectType(eax, JS_ARRAY_TYPE, ebx);
3516 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3517 Split(equal, if_true, if_false, fall_through);
3519 context()->Plug(if_true, if_false);
3523 void FullCodeGenerator::EmitIsRegExp(CallRuntime* expr) {
3524 ZoneList<Expression*>* args = expr->arguments();
3525 DCHECK(args->length() == 1);
3527 VisitForAccumulatorValue(args->at(0));
3529 Label materialize_true, materialize_false;
3530 Label* if_true = NULL;
3531 Label* if_false = NULL;
3532 Label* fall_through = NULL;
3533 context()->PrepareTest(&materialize_true, &materialize_false,
3534 &if_true, &if_false, &fall_through);
3536 __ JumpIfSmi(eax, if_false);
3537 __ CmpObjectType(eax, JS_REGEXP_TYPE, ebx);
3538 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3539 Split(equal, if_true, if_false, fall_through);
3541 context()->Plug(if_true, if_false);
3545 void FullCodeGenerator::EmitIsJSProxy(CallRuntime* expr) {
3546 ZoneList<Expression*>* args = expr->arguments();
3547 DCHECK(args->length() == 1);
3549 VisitForAccumulatorValue(args->at(0));
3551 Label materialize_true, materialize_false;
3552 Label* if_true = NULL;
3553 Label* if_false = NULL;
3554 Label* fall_through = NULL;
3555 context()->PrepareTest(&materialize_true, &materialize_false, &if_true,
3556 &if_false, &fall_through);
3558 __ JumpIfSmi(eax, if_false);
3560 __ mov(map, FieldOperand(eax, HeapObject::kMapOffset));
3561 __ CmpInstanceType(map, FIRST_JS_PROXY_TYPE);
3562 __ j(less, if_false);
3563 __ CmpInstanceType(map, LAST_JS_PROXY_TYPE);
3564 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3565 Split(less_equal, if_true, if_false, fall_through);
3567 context()->Plug(if_true, if_false);
3571 void FullCodeGenerator::EmitIsConstructCall(CallRuntime* expr) {
3572 DCHECK(expr->arguments()->length() == 0);
3574 Label materialize_true, materialize_false;
3575 Label* if_true = NULL;
3576 Label* if_false = NULL;
3577 Label* fall_through = NULL;
3578 context()->PrepareTest(&materialize_true, &materialize_false,
3579 &if_true, &if_false, &fall_through);
3581 // Get the frame pointer for the calling frame.
3582 __ mov(eax, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3584 // Skip the arguments adaptor frame if it exists.
3585 Label check_frame_marker;
3586 __ cmp(Operand(eax, StandardFrameConstants::kContextOffset),
3587 Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
3588 __ j(not_equal, &check_frame_marker);
3589 __ mov(eax, Operand(eax, StandardFrameConstants::kCallerFPOffset));
3591 // Check the marker in the calling frame.
3592 __ bind(&check_frame_marker);
3593 __ cmp(Operand(eax, StandardFrameConstants::kMarkerOffset),
3594 Immediate(Smi::FromInt(StackFrame::CONSTRUCT)));
3595 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3596 Split(equal, if_true, if_false, fall_through);
3598 context()->Plug(if_true, if_false);
3602 void FullCodeGenerator::EmitObjectEquals(CallRuntime* expr) {
3603 ZoneList<Expression*>* args = expr->arguments();
3604 DCHECK(args->length() == 2);
3606 // Load the two objects into registers and perform the comparison.
3607 VisitForStackValue(args->at(0));
3608 VisitForAccumulatorValue(args->at(1));
3610 Label materialize_true, materialize_false;
3611 Label* if_true = NULL;
3612 Label* if_false = NULL;
3613 Label* fall_through = NULL;
3614 context()->PrepareTest(&materialize_true, &materialize_false,
3615 &if_true, &if_false, &fall_through);
3619 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3620 Split(equal, if_true, if_false, fall_through);
3622 context()->Plug(if_true, if_false);
3626 void FullCodeGenerator::EmitArguments(CallRuntime* expr) {
3627 ZoneList<Expression*>* args = expr->arguments();
3628 DCHECK(args->length() == 1);
3630 // ArgumentsAccessStub expects the key in edx and the formal
3631 // parameter count in eax.
3632 VisitForAccumulatorValue(args->at(0));
3634 __ Move(eax, Immediate(Smi::FromInt(info_->scope()->num_parameters())));
3635 ArgumentsAccessStub stub(isolate(), ArgumentsAccessStub::READ_ELEMENT);
3637 context()->Plug(eax);
3641 void FullCodeGenerator::EmitArgumentsLength(CallRuntime* expr) {
3642 DCHECK(expr->arguments()->length() == 0);
3645 // Get the number of formal parameters.
3646 __ Move(eax, Immediate(Smi::FromInt(info_->scope()->num_parameters())));
3648 // Check if the calling frame is an arguments adaptor frame.
3649 __ mov(ebx, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3650 __ cmp(Operand(ebx, StandardFrameConstants::kContextOffset),
3651 Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
3652 __ j(not_equal, &exit);
3654 // Arguments adaptor case: Read the arguments length from the
3656 __ mov(eax, Operand(ebx, ArgumentsAdaptorFrameConstants::kLengthOffset));
3660 context()->Plug(eax);
3664 void FullCodeGenerator::EmitClassOf(CallRuntime* expr) {
3665 ZoneList<Expression*>* args = expr->arguments();
3666 DCHECK(args->length() == 1);
3667 Label done, null, function, non_function_constructor;
3669 VisitForAccumulatorValue(args->at(0));
3671 // If the object is a smi, we return null.
3672 __ JumpIfSmi(eax, &null);
3674 // Check that the object is a JS object but take special care of JS
3675 // functions to make sure they have 'Function' as their class.
3676 // Assume that there are only two callable types, and one of them is at
3677 // either end of the type range for JS object types. Saves extra comparisons.
3678 STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
3679 __ CmpObjectType(eax, FIRST_SPEC_OBJECT_TYPE, eax);
3680 // Map is now in eax.
3682 STATIC_ASSERT(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE ==
3683 FIRST_SPEC_OBJECT_TYPE + 1);
3684 __ j(equal, &function);
3686 __ CmpInstanceType(eax, LAST_SPEC_OBJECT_TYPE);
3687 STATIC_ASSERT(LAST_NONCALLABLE_SPEC_OBJECT_TYPE ==
3688 LAST_SPEC_OBJECT_TYPE - 1);
3689 __ j(equal, &function);
3690 // Assume that there is no larger type.
3691 STATIC_ASSERT(LAST_NONCALLABLE_SPEC_OBJECT_TYPE == LAST_TYPE - 1);
3693 // Check if the constructor in the map is a JS function.
3694 __ GetMapConstructor(eax, eax, ebx);
3695 __ CmpInstanceType(ebx, JS_FUNCTION_TYPE);
3696 __ j(not_equal, &non_function_constructor);
3698 // eax now contains the constructor function. Grab the
3699 // instance class name from there.
3700 __ mov(eax, FieldOperand(eax, JSFunction::kSharedFunctionInfoOffset));
3701 __ mov(eax, FieldOperand(eax, SharedFunctionInfo::kInstanceClassNameOffset));
3704 // Functions have class 'Function'.
3706 __ mov(eax, isolate()->factory()->Function_string());
3709 // Objects with a non-function constructor have class 'Object'.
3710 __ bind(&non_function_constructor);
3711 __ mov(eax, isolate()->factory()->Object_string());
3714 // Non-JS objects have class null.
3716 __ mov(eax, isolate()->factory()->null_value());
3721 context()->Plug(eax);
3725 void FullCodeGenerator::EmitSubString(CallRuntime* expr) {
3726 // Load the arguments on the stack and call the stub.
3727 SubStringStub stub(isolate());
3728 ZoneList<Expression*>* args = expr->arguments();
3729 DCHECK(args->length() == 3);
3730 VisitForStackValue(args->at(0));
3731 VisitForStackValue(args->at(1));
3732 VisitForStackValue(args->at(2));
3734 context()->Plug(eax);
3738 void FullCodeGenerator::EmitRegExpExec(CallRuntime* expr) {
3739 // Load the arguments on the stack and call the stub.
3740 RegExpExecStub stub(isolate());
3741 ZoneList<Expression*>* args = expr->arguments();
3742 DCHECK(args->length() == 4);
3743 VisitForStackValue(args->at(0));
3744 VisitForStackValue(args->at(1));
3745 VisitForStackValue(args->at(2));
3746 VisitForStackValue(args->at(3));
3748 context()->Plug(eax);
3752 void FullCodeGenerator::EmitValueOf(CallRuntime* expr) {
3753 ZoneList<Expression*>* args = expr->arguments();
3754 DCHECK(args->length() == 1);
3756 VisitForAccumulatorValue(args->at(0)); // Load the object.
3759 // If the object is a smi return the object.
3760 __ JumpIfSmi(eax, &done, Label::kNear);
3761 // If the object is not a value type, return the object.
3762 __ CmpObjectType(eax, JS_VALUE_TYPE, ebx);
3763 __ j(not_equal, &done, Label::kNear);
3764 __ mov(eax, FieldOperand(eax, JSValue::kValueOffset));
3767 context()->Plug(eax);
3771 void FullCodeGenerator::EmitDateField(CallRuntime* expr) {
3772 ZoneList<Expression*>* args = expr->arguments();
3773 DCHECK(args->length() == 2);
3774 DCHECK_NOT_NULL(args->at(1)->AsLiteral());
3775 Smi* index = Smi::cast(*(args->at(1)->AsLiteral()->value()));
3777 VisitForAccumulatorValue(args->at(0)); // Load the object.
3779 Label runtime, done, not_date_object;
3780 Register object = eax;
3781 Register result = eax;
3782 Register scratch = ecx;
3784 __ JumpIfSmi(object, ¬_date_object);
3785 __ CmpObjectType(object, JS_DATE_TYPE, scratch);
3786 __ j(not_equal, ¬_date_object);
3788 if (index->value() == 0) {
3789 __ mov(result, FieldOperand(object, JSDate::kValueOffset));
3792 if (index->value() < JSDate::kFirstUncachedField) {
3793 ExternalReference stamp = ExternalReference::date_cache_stamp(isolate());
3794 __ mov(scratch, Operand::StaticVariable(stamp));
3795 __ cmp(scratch, FieldOperand(object, JSDate::kCacheStampOffset));
3796 __ j(not_equal, &runtime, Label::kNear);
3797 __ mov(result, FieldOperand(object, JSDate::kValueOffset +
3798 kPointerSize * index->value()));
3802 __ PrepareCallCFunction(2, scratch);
3803 __ mov(Operand(esp, 0), object);
3804 __ mov(Operand(esp, 1 * kPointerSize), Immediate(index));
3805 __ CallCFunction(ExternalReference::get_date_field_function(isolate()), 2);
3809 __ bind(¬_date_object);
3810 __ CallRuntime(Runtime::kThrowNotDateError, 0);
3812 context()->Plug(result);
3816 void FullCodeGenerator::EmitOneByteSeqStringSetChar(CallRuntime* expr) {
3817 ZoneList<Expression*>* args = expr->arguments();
3818 DCHECK_EQ(3, args->length());
3820 Register string = eax;
3821 Register index = ebx;
3822 Register value = ecx;
3824 VisitForStackValue(args->at(0)); // index
3825 VisitForStackValue(args->at(1)); // value
3826 VisitForAccumulatorValue(args->at(2)); // string
3831 if (FLAG_debug_code) {
3832 __ test(value, Immediate(kSmiTagMask));
3833 __ Check(zero, kNonSmiValue);
3834 __ test(index, Immediate(kSmiTagMask));
3835 __ Check(zero, kNonSmiValue);
3841 if (FLAG_debug_code) {
3842 static const uint32_t one_byte_seq_type = kSeqStringTag | kOneByteStringTag;
3843 __ EmitSeqStringSetCharCheck(string, index, value, one_byte_seq_type);
3846 __ mov_b(FieldOperand(string, index, times_1, SeqOneByteString::kHeaderSize),
3848 context()->Plug(string);
3852 void FullCodeGenerator::EmitTwoByteSeqStringSetChar(CallRuntime* expr) {
3853 ZoneList<Expression*>* args = expr->arguments();
3854 DCHECK_EQ(3, args->length());
3856 Register string = eax;
3857 Register index = ebx;
3858 Register value = ecx;
3860 VisitForStackValue(args->at(0)); // index
3861 VisitForStackValue(args->at(1)); // value
3862 VisitForAccumulatorValue(args->at(2)); // string
3866 if (FLAG_debug_code) {
3867 __ test(value, Immediate(kSmiTagMask));
3868 __ Check(zero, kNonSmiValue);
3869 __ test(index, Immediate(kSmiTagMask));
3870 __ Check(zero, kNonSmiValue);
3872 static const uint32_t two_byte_seq_type = kSeqStringTag | kTwoByteStringTag;
3873 __ EmitSeqStringSetCharCheck(string, index, value, two_byte_seq_type);
3878 // No need to untag a smi for two-byte addressing.
3879 __ mov_w(FieldOperand(string, index, times_1, SeqTwoByteString::kHeaderSize),
3881 context()->Plug(string);
3885 void FullCodeGenerator::EmitMathPow(CallRuntime* expr) {
3886 // Load the arguments on the stack and call the runtime function.
3887 ZoneList<Expression*>* args = expr->arguments();
3888 DCHECK(args->length() == 2);
3889 VisitForStackValue(args->at(0));
3890 VisitForStackValue(args->at(1));
3892 __ CallRuntime(Runtime::kMathPowSlow, 2);
3893 context()->Plug(eax);
3897 void FullCodeGenerator::EmitSetValueOf(CallRuntime* expr) {
3898 ZoneList<Expression*>* args = expr->arguments();
3899 DCHECK(args->length() == 2);
3901 VisitForStackValue(args->at(0)); // Load the object.
3902 VisitForAccumulatorValue(args->at(1)); // Load the value.
3903 __ pop(ebx); // eax = value. ebx = object.
3906 // If the object is a smi, return the value.
3907 __ JumpIfSmi(ebx, &done, Label::kNear);
3909 // If the object is not a value type, return the value.
3910 __ CmpObjectType(ebx, JS_VALUE_TYPE, ecx);
3911 __ j(not_equal, &done, Label::kNear);
3914 __ mov(FieldOperand(ebx, JSValue::kValueOffset), eax);
3916 // Update the write barrier. Save the value as it will be
3917 // overwritten by the write barrier code and is needed afterward.
3919 __ RecordWriteField(ebx, JSValue::kValueOffset, edx, ecx, kDontSaveFPRegs);
3922 context()->Plug(eax);
3926 void FullCodeGenerator::EmitNumberToString(CallRuntime* expr) {
3927 ZoneList<Expression*>* args = expr->arguments();
3928 DCHECK_EQ(args->length(), 1);
3930 // Load the argument into eax and call the stub.
3931 VisitForAccumulatorValue(args->at(0));
3933 NumberToStringStub stub(isolate());
3935 context()->Plug(eax);
3939 void FullCodeGenerator::EmitStringCharFromCode(CallRuntime* expr) {
3940 ZoneList<Expression*>* args = expr->arguments();
3941 DCHECK(args->length() == 1);
3943 VisitForAccumulatorValue(args->at(0));
3946 StringCharFromCodeGenerator generator(eax, ebx);
3947 generator.GenerateFast(masm_);
3950 NopRuntimeCallHelper call_helper;
3951 generator.GenerateSlow(masm_, call_helper);
3954 context()->Plug(ebx);
3958 void FullCodeGenerator::EmitStringCharCodeAt(CallRuntime* expr) {
3959 ZoneList<Expression*>* args = expr->arguments();
3960 DCHECK(args->length() == 2);
3962 VisitForStackValue(args->at(0));
3963 VisitForAccumulatorValue(args->at(1));
3965 Register object = ebx;
3966 Register index = eax;
3967 Register result = edx;
3971 Label need_conversion;
3972 Label index_out_of_range;
3974 StringCharCodeAtGenerator generator(object,
3979 &index_out_of_range,
3980 STRING_INDEX_IS_NUMBER);
3981 generator.GenerateFast(masm_);
3984 __ bind(&index_out_of_range);
3985 // When the index is out of range, the spec requires us to return
3987 __ Move(result, Immediate(isolate()->factory()->nan_value()));
3990 __ bind(&need_conversion);
3991 // Move the undefined value into the result register, which will
3992 // trigger conversion.
3993 __ Move(result, Immediate(isolate()->factory()->undefined_value()));
3996 NopRuntimeCallHelper call_helper;
3997 generator.GenerateSlow(masm_, NOT_PART_OF_IC_HANDLER, call_helper);
4000 context()->Plug(result);
4004 void FullCodeGenerator::EmitStringCharAt(CallRuntime* expr) {
4005 ZoneList<Expression*>* args = expr->arguments();
4006 DCHECK(args->length() == 2);
4008 VisitForStackValue(args->at(0));
4009 VisitForAccumulatorValue(args->at(1));
4011 Register object = ebx;
4012 Register index = eax;
4013 Register scratch = edx;
4014 Register result = eax;
4018 Label need_conversion;
4019 Label index_out_of_range;
4021 StringCharAtGenerator generator(object,
4027 &index_out_of_range,
4028 STRING_INDEX_IS_NUMBER);
4029 generator.GenerateFast(masm_);
4032 __ bind(&index_out_of_range);
4033 // When the index is out of range, the spec requires us to return
4034 // the empty string.
4035 __ Move(result, Immediate(isolate()->factory()->empty_string()));
4038 __ bind(&need_conversion);
4039 // Move smi zero into the result register, which will trigger
4041 __ Move(result, Immediate(Smi::FromInt(0)));
4044 NopRuntimeCallHelper call_helper;
4045 generator.GenerateSlow(masm_, NOT_PART_OF_IC_HANDLER, call_helper);
4048 context()->Plug(result);
4052 void FullCodeGenerator::EmitStringAdd(CallRuntime* expr) {
4053 ZoneList<Expression*>* args = expr->arguments();
4054 DCHECK_EQ(2, args->length());
4055 VisitForStackValue(args->at(0));
4056 VisitForAccumulatorValue(args->at(1));
4059 StringAddStub stub(isolate(), STRING_ADD_CHECK_BOTH, NOT_TENURED);
4061 context()->Plug(eax);
4065 void FullCodeGenerator::EmitStringCompare(CallRuntime* expr) {
4066 ZoneList<Expression*>* args = expr->arguments();
4067 DCHECK_EQ(2, args->length());
4069 VisitForStackValue(args->at(0));
4070 VisitForStackValue(args->at(1));
4072 StringCompareStub stub(isolate());
4074 context()->Plug(eax);
4078 void FullCodeGenerator::EmitCallFunction(CallRuntime* expr) {
4079 ZoneList<Expression*>* args = expr->arguments();
4080 DCHECK(args->length() >= 2);
4082 int arg_count = args->length() - 2; // 2 ~ receiver and function.
4083 for (int i = 0; i < arg_count + 1; ++i) {
4084 VisitForStackValue(args->at(i));
4086 VisitForAccumulatorValue(args->last()); // Function.
4088 Label runtime, done;
4089 // Check for non-function argument (including proxy).
4090 __ JumpIfSmi(eax, &runtime);
4091 __ CmpObjectType(eax, JS_FUNCTION_TYPE, ebx);
4092 __ j(not_equal, &runtime);
4094 // InvokeFunction requires the function in edi. Move it in there.
4095 __ mov(edi, result_register());
4096 ParameterCount count(arg_count);
4097 __ InvokeFunction(edi, count, CALL_FUNCTION, NullCallWrapper());
4098 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4103 __ CallRuntime(Runtime::kCall, args->length());
4106 context()->Plug(eax);
4110 void FullCodeGenerator::EmitDefaultConstructorCallSuper(CallRuntime* expr) {
4111 Variable* new_target_var = scope()->DeclarationScope()->new_target_var();
4112 GetVar(eax, new_target_var);
4115 EmitLoadSuperConstructor();
4116 __ push(result_register());
4118 // Check if the calling frame is an arguments adaptor frame.
4119 Label adaptor_frame, args_set_up, runtime;
4120 __ mov(edx, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
4121 __ mov(ecx, Operand(edx, StandardFrameConstants::kContextOffset));
4122 __ cmp(ecx, Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
4123 __ j(equal, &adaptor_frame);
4124 // default constructor has no arguments, so no adaptor frame means no args.
4125 __ mov(eax, Immediate(0));
4126 __ jmp(&args_set_up);
4128 // Copy arguments from adaptor frame.
4130 __ bind(&adaptor_frame);
4131 __ mov(ecx, Operand(edx, ArgumentsAdaptorFrameConstants::kLengthOffset));
4134 // Subtract 1 from arguments count, for new.target.
4135 __ sub(ecx, Immediate(1));
4137 __ lea(edx, Operand(edx, ecx, times_pointer_size,
4138 StandardFrameConstants::kCallerSPOffset));
4141 __ push(Operand(edx, -1 * kPointerSize));
4142 __ sub(edx, Immediate(kPointerSize));
4144 __ j(not_zero, &loop);
4147 __ bind(&args_set_up);
4149 __ mov(edi, Operand(esp, eax, times_pointer_size, 0));
4150 __ mov(ebx, Immediate(isolate()->factory()->undefined_value()));
4151 CallConstructStub stub(isolate(), SUPER_CONSTRUCTOR_CALL);
4152 __ call(stub.GetCode(), RelocInfo::CONSTRUCT_CALL);
4156 context()->Plug(eax);
4160 void FullCodeGenerator::EmitRegExpConstructResult(CallRuntime* expr) {
4161 // Load the arguments on the stack and call the stub.
4162 RegExpConstructResultStub stub(isolate());
4163 ZoneList<Expression*>* args = expr->arguments();
4164 DCHECK(args->length() == 3);
4165 VisitForStackValue(args->at(0));
4166 VisitForStackValue(args->at(1));
4167 VisitForAccumulatorValue(args->at(2));
4171 context()->Plug(eax);
4175 void FullCodeGenerator::EmitGetFromCache(CallRuntime* expr) {
4176 ZoneList<Expression*>* args = expr->arguments();
4177 DCHECK_EQ(2, args->length());
4179 DCHECK_NOT_NULL(args->at(0)->AsLiteral());
4180 int cache_id = Smi::cast(*(args->at(0)->AsLiteral()->value()))->value();
4182 Handle<FixedArray> jsfunction_result_caches(
4183 isolate()->native_context()->jsfunction_result_caches());
4184 if (jsfunction_result_caches->length() <= cache_id) {
4185 __ Abort(kAttemptToUseUndefinedCache);
4186 __ mov(eax, isolate()->factory()->undefined_value());
4187 context()->Plug(eax);
4191 VisitForAccumulatorValue(args->at(1));
4194 Register cache = ebx;
4196 __ mov(cache, ContextOperand(esi, Context::GLOBAL_OBJECT_INDEX));
4198 FieldOperand(cache, GlobalObject::kNativeContextOffset));
4199 __ mov(cache, ContextOperand(cache, Context::JSFUNCTION_RESULT_CACHES_INDEX));
4201 FieldOperand(cache, FixedArray::OffsetOfElementAt(cache_id)));
4203 Label done, not_found;
4204 STATIC_ASSERT(kSmiTag == 0 && kSmiTagSize == 1);
4205 __ mov(tmp, FieldOperand(cache, JSFunctionResultCache::kFingerOffset));
4206 // tmp now holds finger offset as a smi.
4207 __ cmp(key, FixedArrayElementOperand(cache, tmp));
4208 __ j(not_equal, ¬_found);
4210 __ mov(eax, FixedArrayElementOperand(cache, tmp, 1));
4213 __ bind(¬_found);
4214 // Call runtime to perform the lookup.
4217 __ CallRuntime(Runtime::kGetFromCacheRT, 2);
4220 context()->Plug(eax);
4224 void FullCodeGenerator::EmitHasCachedArrayIndex(CallRuntime* expr) {
4225 ZoneList<Expression*>* args = expr->arguments();
4226 DCHECK(args->length() == 1);
4228 VisitForAccumulatorValue(args->at(0));
4230 __ AssertString(eax);
4232 Label materialize_true, materialize_false;
4233 Label* if_true = NULL;
4234 Label* if_false = NULL;
4235 Label* fall_through = NULL;
4236 context()->PrepareTest(&materialize_true, &materialize_false,
4237 &if_true, &if_false, &fall_through);
4239 __ test(FieldOperand(eax, String::kHashFieldOffset),
4240 Immediate(String::kContainsCachedArrayIndexMask));
4241 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
4242 Split(zero, if_true, if_false, fall_through);
4244 context()->Plug(if_true, if_false);
4248 void FullCodeGenerator::EmitGetCachedArrayIndex(CallRuntime* expr) {
4249 ZoneList<Expression*>* args = expr->arguments();
4250 DCHECK(args->length() == 1);
4251 VisitForAccumulatorValue(args->at(0));
4253 __ AssertString(eax);
4255 __ mov(eax, FieldOperand(eax, String::kHashFieldOffset));
4256 __ IndexFromHash(eax, eax);
4258 context()->Plug(eax);
4262 void FullCodeGenerator::EmitFastOneByteArrayJoin(CallRuntime* expr) {
4263 Label bailout, done, one_char_separator, long_separator,
4264 non_trivial_array, not_size_one_array, loop,
4265 loop_1, loop_1_condition, loop_2, loop_2_entry, loop_3, loop_3_entry;
4267 ZoneList<Expression*>* args = expr->arguments();
4268 DCHECK(args->length() == 2);
4269 // We will leave the separator on the stack until the end of the function.
4270 VisitForStackValue(args->at(1));
4271 // Load this to eax (= array)
4272 VisitForAccumulatorValue(args->at(0));
4273 // All aliases of the same register have disjoint lifetimes.
4274 Register array = eax;
4275 Register elements = no_reg; // Will be eax.
4277 Register index = edx;
4279 Register string_length = ecx;
4281 Register string = esi;
4283 Register scratch = ebx;
4285 Register array_length = edi;
4286 Register result_pos = no_reg; // Will be edi.
4288 // Separator operand is already pushed.
4289 Operand separator_operand = Operand(esp, 2 * kPointerSize);
4290 Operand result_operand = Operand(esp, 1 * kPointerSize);
4291 Operand array_length_operand = Operand(esp, 0);
4292 __ sub(esp, Immediate(2 * kPointerSize));
4294 // Check that the array is a JSArray
4295 __ JumpIfSmi(array, &bailout);
4296 __ CmpObjectType(array, JS_ARRAY_TYPE, scratch);
4297 __ j(not_equal, &bailout);
4299 // Check that the array has fast elements.
4300 __ CheckFastElements(scratch, &bailout);
4302 // If the array has length zero, return the empty string.
4303 __ mov(array_length, FieldOperand(array, JSArray::kLengthOffset));
4304 __ SmiUntag(array_length);
4305 __ j(not_zero, &non_trivial_array);
4306 __ mov(result_operand, isolate()->factory()->empty_string());
4309 // Save the array length.
4310 __ bind(&non_trivial_array);
4311 __ mov(array_length_operand, array_length);
4313 // Save the FixedArray containing array's elements.
4314 // End of array's live range.
4316 __ mov(elements, FieldOperand(array, JSArray::kElementsOffset));
4320 // Check that all array elements are sequential one-byte strings, and
4321 // accumulate the sum of their lengths, as a smi-encoded value.
4322 __ Move(index, Immediate(0));
4323 __ Move(string_length, Immediate(0));
4324 // Loop condition: while (index < length).
4325 // Live loop registers: index, array_length, string,
4326 // scratch, string_length, elements.
4327 if (generate_debug_code_) {
4328 __ cmp(index, array_length);
4329 __ Assert(less, kNoEmptyArraysHereInEmitFastOneByteArrayJoin);
4332 __ mov(string, FieldOperand(elements,
4335 FixedArray::kHeaderSize));
4336 __ JumpIfSmi(string, &bailout);
4337 __ mov(scratch, FieldOperand(string, HeapObject::kMapOffset));
4338 __ movzx_b(scratch, FieldOperand(scratch, Map::kInstanceTypeOffset));
4339 __ and_(scratch, Immediate(
4340 kIsNotStringMask | kStringEncodingMask | kStringRepresentationMask));
4341 __ cmp(scratch, kStringTag | kOneByteStringTag | kSeqStringTag);
4342 __ j(not_equal, &bailout);
4343 __ add(string_length,
4344 FieldOperand(string, SeqOneByteString::kLengthOffset));
4345 __ j(overflow, &bailout);
4346 __ add(index, Immediate(1));
4347 __ cmp(index, array_length);
4350 // If array_length is 1, return elements[0], a string.
4351 __ cmp(array_length, 1);
4352 __ j(not_equal, ¬_size_one_array);
4353 __ mov(scratch, FieldOperand(elements, FixedArray::kHeaderSize));
4354 __ mov(result_operand, scratch);
4357 __ bind(¬_size_one_array);
4359 // End of array_length live range.
4360 result_pos = array_length;
4361 array_length = no_reg;
4364 // string_length: Sum of string lengths, as a smi.
4365 // elements: FixedArray of strings.
4367 // Check that the separator is a flat one-byte string.
4368 __ mov(string, separator_operand);
4369 __ JumpIfSmi(string, &bailout);
4370 __ mov(scratch, FieldOperand(string, HeapObject::kMapOffset));
4371 __ movzx_b(scratch, FieldOperand(scratch, Map::kInstanceTypeOffset));
4372 __ and_(scratch, Immediate(
4373 kIsNotStringMask | kStringEncodingMask | kStringRepresentationMask));
4374 __ cmp(scratch, kStringTag | kOneByteStringTag | kSeqStringTag);
4375 __ j(not_equal, &bailout);
4377 // Add (separator length times array_length) - separator length
4378 // to string_length.
4379 __ mov(scratch, separator_operand);
4380 __ mov(scratch, FieldOperand(scratch, SeqOneByteString::kLengthOffset));
4381 __ sub(string_length, scratch); // May be negative, temporarily.
4382 __ imul(scratch, array_length_operand);
4383 __ j(overflow, &bailout);
4384 __ add(string_length, scratch);
4385 __ j(overflow, &bailout);
4387 __ shr(string_length, 1);
4388 // Live registers and stack values:
4391 __ AllocateOneByteString(result_pos, string_length, scratch, index, string,
4393 __ mov(result_operand, result_pos);
4394 __ lea(result_pos, FieldOperand(result_pos, SeqOneByteString::kHeaderSize));
4397 __ mov(string, separator_operand);
4398 __ cmp(FieldOperand(string, SeqOneByteString::kLengthOffset),
4399 Immediate(Smi::FromInt(1)));
4400 __ j(equal, &one_char_separator);
4401 __ j(greater, &long_separator);
4404 // Empty separator case
4405 __ mov(index, Immediate(0));
4406 __ jmp(&loop_1_condition);
4407 // Loop condition: while (index < length).
4409 // Each iteration of the loop concatenates one string to the result.
4410 // Live values in registers:
4411 // index: which element of the elements array we are adding to the result.
4412 // result_pos: the position to which we are currently copying characters.
4413 // elements: the FixedArray of strings we are joining.
4415 // Get string = array[index].
4416 __ mov(string, FieldOperand(elements, index,
4418 FixedArray::kHeaderSize));
4419 __ mov(string_length,
4420 FieldOperand(string, String::kLengthOffset));
4421 __ shr(string_length, 1);
4423 FieldOperand(string, SeqOneByteString::kHeaderSize));
4424 __ CopyBytes(string, result_pos, string_length, scratch);
4425 __ add(index, Immediate(1));
4426 __ bind(&loop_1_condition);
4427 __ cmp(index, array_length_operand);
4428 __ j(less, &loop_1); // End while (index < length).
4433 // One-character separator case
4434 __ bind(&one_char_separator);
4435 // Replace separator with its one-byte character value.
4436 __ mov_b(scratch, FieldOperand(string, SeqOneByteString::kHeaderSize));
4437 __ mov_b(separator_operand, scratch);
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_2_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 character to the result.
4451 __ mov_b(scratch, separator_operand);
4452 __ mov_b(Operand(result_pos, 0), scratch);
4455 __ bind(&loop_2_entry);
4456 // Get string = array[index].
4457 __ mov(string, FieldOperand(elements, index,
4459 FixedArray::kHeaderSize));
4460 __ mov(string_length,
4461 FieldOperand(string, String::kLengthOffset));
4462 __ shr(string_length, 1);
4464 FieldOperand(string, SeqOneByteString::kHeaderSize));
4465 __ CopyBytes(string, result_pos, string_length, scratch);
4466 __ add(index, Immediate(1));
4468 __ cmp(index, array_length_operand);
4469 __ j(less, &loop_2); // End while (index < length).
4473 // Long separator case (separator is more than one character).
4474 __ bind(&long_separator);
4476 __ Move(index, Immediate(0));
4477 // Jump into the loop after the code that copies the separator, so the first
4478 // element is not preceded by a separator
4479 __ jmp(&loop_3_entry);
4480 // Loop condition: while (index < length).
4482 // Each iteration of the loop concatenates one string to the result.
4483 // Live values in registers:
4484 // index: which element of the elements array we are adding to the result.
4485 // result_pos: the position to which we are currently copying characters.
4487 // Copy the separator to the result.
4488 __ mov(string, separator_operand);
4489 __ mov(string_length,
4490 FieldOperand(string, String::kLengthOffset));
4491 __ shr(string_length, 1);
4493 FieldOperand(string, SeqOneByteString::kHeaderSize));
4494 __ CopyBytes(string, result_pos, string_length, scratch);
4496 __ bind(&loop_3_entry);
4497 // Get string = array[index].
4498 __ mov(string, FieldOperand(elements, index,
4500 FixedArray::kHeaderSize));
4501 __ mov(string_length,
4502 FieldOperand(string, String::kLengthOffset));
4503 __ shr(string_length, 1);
4505 FieldOperand(string, SeqOneByteString::kHeaderSize));
4506 __ CopyBytes(string, result_pos, string_length, scratch);
4507 __ add(index, Immediate(1));
4509 __ cmp(index, array_length_operand);
4510 __ j(less, &loop_3); // End while (index < length).
4515 __ mov(result_operand, isolate()->factory()->undefined_value());
4517 __ mov(eax, result_operand);
4518 // Drop temp values from the stack, and restore context register.
4519 __ add(esp, Immediate(3 * kPointerSize));
4521 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4522 context()->Plug(eax);
4526 void FullCodeGenerator::EmitDebugIsActive(CallRuntime* expr) {
4527 DCHECK(expr->arguments()->length() == 0);
4528 ExternalReference debug_is_active =
4529 ExternalReference::debug_is_active_address(isolate());
4530 __ movzx_b(eax, Operand::StaticVariable(debug_is_active));
4532 context()->Plug(eax);
4536 void FullCodeGenerator::VisitCallRuntime(CallRuntime* expr) {
4537 ZoneList<Expression*>* args = expr->arguments();
4538 int arg_count = args->length();
4540 if (expr->is_jsruntime()) {
4541 Comment cmnt(masm_, "[ CallRuntime");
4542 // Push the builtins object as receiver.
4543 __ mov(eax, GlobalObjectOperand());
4544 __ push(FieldOperand(eax, GlobalObject::kBuiltinsOffset));
4546 // Load the function from the receiver.
4547 __ mov(LoadDescriptor::ReceiverRegister(), Operand(esp, 0));
4548 __ mov(LoadDescriptor::NameRegister(), Immediate(expr->name()));
4549 if (FLAG_vector_ics) {
4550 __ mov(VectorLoadICDescriptor::SlotRegister(),
4551 Immediate(SmiFromSlot(expr->CallRuntimeFeedbackSlot())));
4552 CallLoadIC(NOT_CONTEXTUAL);
4554 CallLoadIC(NOT_CONTEXTUAL, expr->CallRuntimeFeedbackId());
4557 // Push the target function under the receiver.
4558 __ push(Operand(esp, 0));
4559 __ mov(Operand(esp, kPointerSize), eax);
4561 // Push the arguments ("left-to-right").
4562 for (int i = 0; i < arg_count; i++) {
4563 VisitForStackValue(args->at(i));
4566 // Record source position of the IC call.
4567 SetSourcePosition(expr->position());
4568 CallFunctionStub stub(isolate(), arg_count, NO_CALL_FUNCTION_FLAGS);
4569 __ mov(edi, Operand(esp, (arg_count + 1) * kPointerSize));
4571 // Restore context register.
4572 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4573 context()->DropAndPlug(1, eax);
4576 const Runtime::Function* function = expr->function();
4577 switch (function->function_id) {
4578 #define CALL_INTRINSIC_GENERATOR(Name) \
4579 case Runtime::kInline##Name: { \
4580 Comment cmnt(masm_, "[ Inline" #Name); \
4581 return Emit##Name(expr); \
4583 FOR_EACH_FULL_CODE_INTRINSIC(CALL_INTRINSIC_GENERATOR)
4584 #undef CALL_INTRINSIC_GENERATOR
4586 Comment cmnt(masm_, "[ CallRuntime for unhandled intrinsic");
4587 // Push the arguments ("left-to-right").
4588 for (int i = 0; i < arg_count; i++) {
4589 VisitForStackValue(args->at(i));
4592 // Call the C runtime function.
4593 __ CallRuntime(expr->function(), arg_count);
4594 context()->Plug(eax);
4601 void FullCodeGenerator::VisitUnaryOperation(UnaryOperation* expr) {
4602 switch (expr->op()) {
4603 case Token::DELETE: {
4604 Comment cmnt(masm_, "[ UnaryOperation (DELETE)");
4605 Property* property = expr->expression()->AsProperty();
4606 VariableProxy* proxy = expr->expression()->AsVariableProxy();
4608 if (property != NULL) {
4609 VisitForStackValue(property->obj());
4610 VisitForStackValue(property->key());
4611 __ push(Immediate(Smi::FromInt(language_mode())));
4612 __ InvokeBuiltin(Builtins::DELETE, CALL_FUNCTION);
4613 context()->Plug(eax);
4614 } else if (proxy != NULL) {
4615 Variable* var = proxy->var();
4616 // Delete of an unqualified identifier is disallowed in strict mode
4617 // but "delete this" is allowed.
4618 DCHECK(is_sloppy(language_mode()) || var->is_this());
4619 if (var->IsUnallocated()) {
4620 __ push(GlobalObjectOperand());
4621 __ push(Immediate(var->name()));
4622 __ push(Immediate(Smi::FromInt(SLOPPY)));
4623 __ InvokeBuiltin(Builtins::DELETE, CALL_FUNCTION);
4624 context()->Plug(eax);
4625 } else if (var->IsStackAllocated() || var->IsContextSlot()) {
4626 // Result of deleting non-global variables is false. 'this' is
4627 // not really a variable, though we implement it as one. The
4628 // subexpression does not have side effects.
4629 context()->Plug(var->is_this());
4631 // Non-global variable. Call the runtime to try to delete from the
4632 // context where the variable was introduced.
4633 __ push(context_register());
4634 __ push(Immediate(var->name()));
4635 __ CallRuntime(Runtime::kDeleteLookupSlot, 2);
4636 context()->Plug(eax);
4639 // Result of deleting non-property, non-variable reference is true.
4640 // The subexpression may have side effects.
4641 VisitForEffect(expr->expression());
4642 context()->Plug(true);
4648 Comment cmnt(masm_, "[ UnaryOperation (VOID)");
4649 VisitForEffect(expr->expression());
4650 context()->Plug(isolate()->factory()->undefined_value());
4655 Comment cmnt(masm_, "[ UnaryOperation (NOT)");
4656 if (context()->IsEffect()) {
4657 // Unary NOT has no side effects so it's only necessary to visit the
4658 // subexpression. Match the optimizing compiler by not branching.
4659 VisitForEffect(expr->expression());
4660 } else if (context()->IsTest()) {
4661 const TestContext* test = TestContext::cast(context());
4662 // The labels are swapped for the recursive call.
4663 VisitForControl(expr->expression(),
4664 test->false_label(),
4666 test->fall_through());
4667 context()->Plug(test->true_label(), test->false_label());
4669 // We handle value contexts explicitly rather than simply visiting
4670 // for control and plugging the control flow into the context,
4671 // because we need to prepare a pair of extra administrative AST ids
4672 // for the optimizing compiler.
4673 DCHECK(context()->IsAccumulatorValue() || context()->IsStackValue());
4674 Label materialize_true, materialize_false, done;
4675 VisitForControl(expr->expression(),
4679 __ bind(&materialize_true);
4680 PrepareForBailoutForId(expr->MaterializeTrueId(), NO_REGISTERS);
4681 if (context()->IsAccumulatorValue()) {
4682 __ mov(eax, isolate()->factory()->true_value());
4684 __ Push(isolate()->factory()->true_value());
4686 __ jmp(&done, Label::kNear);
4687 __ bind(&materialize_false);
4688 PrepareForBailoutForId(expr->MaterializeFalseId(), NO_REGISTERS);
4689 if (context()->IsAccumulatorValue()) {
4690 __ mov(eax, isolate()->factory()->false_value());
4692 __ Push(isolate()->factory()->false_value());
4699 case Token::TYPEOF: {
4700 Comment cmnt(masm_, "[ UnaryOperation (TYPEOF)");
4701 { StackValueContext context(this);
4702 VisitForTypeofValue(expr->expression());
4704 __ CallRuntime(Runtime::kTypeof, 1);
4705 context()->Plug(eax);
4715 void FullCodeGenerator::VisitCountOperation(CountOperation* expr) {
4716 DCHECK(expr->expression()->IsValidReferenceExpression());
4718 Comment cmnt(masm_, "[ CountOperation");
4719 SetSourcePosition(expr->position());
4721 Property* prop = expr->expression()->AsProperty();
4722 LhsKind assign_type = GetAssignType(prop);
4724 // Evaluate expression and get value.
4725 if (assign_type == VARIABLE) {
4726 DCHECK(expr->expression()->AsVariableProxy()->var() != NULL);
4727 AccumulatorValueContext context(this);
4728 EmitVariableLoad(expr->expression()->AsVariableProxy());
4730 // Reserve space for result of postfix operation.
4731 if (expr->is_postfix() && !context()->IsEffect()) {
4732 __ push(Immediate(Smi::FromInt(0)));
4734 switch (assign_type) {
4735 case NAMED_PROPERTY: {
4736 // Put the object both on the stack and in the register.
4737 VisitForStackValue(prop->obj());
4738 __ mov(LoadDescriptor::ReceiverRegister(), Operand(esp, 0));
4739 EmitNamedPropertyLoad(prop);
4743 case NAMED_SUPER_PROPERTY: {
4744 VisitForStackValue(prop->obj()->AsSuperReference()->this_var());
4745 EmitLoadHomeObject(prop->obj()->AsSuperReference());
4746 __ push(result_register());
4747 __ push(MemOperand(esp, kPointerSize));
4748 __ push(result_register());
4749 EmitNamedSuperPropertyLoad(prop);
4753 case KEYED_SUPER_PROPERTY: {
4754 VisitForStackValue(prop->obj()->AsSuperReference()->this_var());
4755 EmitLoadHomeObject(prop->obj()->AsSuperReference());
4756 __ push(result_register());
4757 VisitForAccumulatorValue(prop->key());
4758 __ push(result_register());
4759 __ push(MemOperand(esp, 2 * kPointerSize));
4760 __ push(MemOperand(esp, 2 * kPointerSize));
4761 __ push(result_register());
4762 EmitKeyedSuperPropertyLoad(prop);
4766 case KEYED_PROPERTY: {
4767 VisitForStackValue(prop->obj());
4768 VisitForStackValue(prop->key());
4769 __ mov(LoadDescriptor::ReceiverRegister(),
4770 Operand(esp, kPointerSize)); // Object.
4771 __ mov(LoadDescriptor::NameRegister(), Operand(esp, 0)); // Key.
4772 EmitKeyedPropertyLoad(prop);
4781 // We need a second deoptimization point after loading the value
4782 // in case evaluating the property load my have a side effect.
4783 if (assign_type == VARIABLE) {
4784 PrepareForBailout(expr->expression(), TOS_REG);
4786 PrepareForBailoutForId(prop->LoadId(), TOS_REG);
4789 // Inline smi case if we are in a loop.
4790 Label done, stub_call;
4791 JumpPatchSite patch_site(masm_);
4792 if (ShouldInlineSmiCase(expr->op())) {
4794 patch_site.EmitJumpIfNotSmi(eax, &slow, Label::kNear);
4796 // Save result for postfix expressions.
4797 if (expr->is_postfix()) {
4798 if (!context()->IsEffect()) {
4799 // Save the result on the stack. If we have a named or keyed property
4800 // we store the result under the receiver that is currently on top
4802 switch (assign_type) {
4806 case NAMED_PROPERTY:
4807 __ mov(Operand(esp, kPointerSize), eax);
4809 case NAMED_SUPER_PROPERTY:
4810 __ mov(Operand(esp, 2 * kPointerSize), eax);
4812 case KEYED_PROPERTY:
4813 __ mov(Operand(esp, 2 * kPointerSize), eax);
4815 case KEYED_SUPER_PROPERTY:
4816 __ mov(Operand(esp, 3 * kPointerSize), eax);
4822 if (expr->op() == Token::INC) {
4823 __ add(eax, Immediate(Smi::FromInt(1)));
4825 __ sub(eax, Immediate(Smi::FromInt(1)));
4827 __ j(no_overflow, &done, Label::kNear);
4828 // Call stub. Undo operation first.
4829 if (expr->op() == Token::INC) {
4830 __ sub(eax, Immediate(Smi::FromInt(1)));
4832 __ add(eax, Immediate(Smi::FromInt(1)));
4834 __ jmp(&stub_call, Label::kNear);
4837 ToNumberStub convert_stub(isolate());
4838 __ CallStub(&convert_stub);
4839 PrepareForBailoutForId(expr->ToNumberId(), TOS_REG);
4841 // Save result for postfix expressions.
4842 if (expr->is_postfix()) {
4843 if (!context()->IsEffect()) {
4844 // Save the result on the stack. If we have a named or keyed property
4845 // we store the result under the receiver that is currently on top
4847 switch (assign_type) {
4851 case NAMED_PROPERTY:
4852 __ mov(Operand(esp, kPointerSize), eax);
4854 case NAMED_SUPER_PROPERTY:
4855 __ mov(Operand(esp, 2 * kPointerSize), eax);
4857 case KEYED_PROPERTY:
4858 __ mov(Operand(esp, 2 * kPointerSize), eax);
4860 case KEYED_SUPER_PROPERTY:
4861 __ mov(Operand(esp, 3 * kPointerSize), eax);
4867 // Record position before stub call.
4868 SetSourcePosition(expr->position());
4870 // Call stub for +1/-1.
4871 __ bind(&stub_call);
4873 __ mov(eax, Immediate(Smi::FromInt(1)));
4875 CodeFactory::BinaryOpIC(isolate(), expr->binary_op()).code();
4876 CallIC(code, expr->CountBinOpFeedbackId());
4877 patch_site.EmitPatchInfo();
4880 // Store the value returned in eax.
4881 switch (assign_type) {
4883 if (expr->is_postfix()) {
4884 // Perform the assignment as if via '='.
4885 { EffectContext context(this);
4886 EmitVariableAssignment(expr->expression()->AsVariableProxy()->var(),
4888 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
4891 // For all contexts except EffectContext We have the result on
4892 // top of the stack.
4893 if (!context()->IsEffect()) {
4894 context()->PlugTOS();
4897 // Perform the assignment as if via '='.
4898 EmitVariableAssignment(expr->expression()->AsVariableProxy()->var(),
4900 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
4901 context()->Plug(eax);
4904 case NAMED_PROPERTY: {
4905 __ mov(StoreDescriptor::NameRegister(),
4906 prop->key()->AsLiteral()->value());
4907 __ pop(StoreDescriptor::ReceiverRegister());
4908 CallStoreIC(expr->CountStoreFeedbackId());
4909 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
4910 if (expr->is_postfix()) {
4911 if (!context()->IsEffect()) {
4912 context()->PlugTOS();
4915 context()->Plug(eax);
4919 case NAMED_SUPER_PROPERTY: {
4920 EmitNamedSuperPropertyStore(prop);
4921 if (expr->is_postfix()) {
4922 if (!context()->IsEffect()) {
4923 context()->PlugTOS();
4926 context()->Plug(eax);
4930 case KEYED_SUPER_PROPERTY: {
4931 EmitKeyedSuperPropertyStore(prop);
4932 if (expr->is_postfix()) {
4933 if (!context()->IsEffect()) {
4934 context()->PlugTOS();
4937 context()->Plug(eax);
4941 case KEYED_PROPERTY: {
4942 __ pop(StoreDescriptor::NameRegister());
4943 __ pop(StoreDescriptor::ReceiverRegister());
4945 CodeFactory::KeyedStoreIC(isolate(), language_mode()).code();
4946 CallIC(ic, expr->CountStoreFeedbackId());
4947 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
4948 if (expr->is_postfix()) {
4949 // Result is on the stack
4950 if (!context()->IsEffect()) {
4951 context()->PlugTOS();
4954 context()->Plug(eax);
4962 void FullCodeGenerator::VisitForTypeofValue(Expression* expr) {
4963 VariableProxy* proxy = expr->AsVariableProxy();
4964 DCHECK(!context()->IsEffect());
4965 DCHECK(!context()->IsTest());
4967 if (proxy != NULL && proxy->var()->IsUnallocated()) {
4968 Comment cmnt(masm_, "[ Global variable");
4969 __ mov(LoadDescriptor::ReceiverRegister(), GlobalObjectOperand());
4970 __ mov(LoadDescriptor::NameRegister(), Immediate(proxy->name()));
4971 if (FLAG_vector_ics) {
4972 __ mov(VectorLoadICDescriptor::SlotRegister(),
4973 Immediate(SmiFromSlot(proxy->VariableFeedbackSlot())));
4975 // Use a regular load, not a contextual load, to avoid a reference
4977 CallLoadIC(NOT_CONTEXTUAL);
4978 PrepareForBailout(expr, TOS_REG);
4979 context()->Plug(eax);
4980 } else if (proxy != NULL && proxy->var()->IsLookupSlot()) {
4981 Comment cmnt(masm_, "[ Lookup slot");
4984 // Generate code for loading from variables potentially shadowed
4985 // by eval-introduced variables.
4986 EmitDynamicLookupFastCase(proxy, INSIDE_TYPEOF, &slow, &done);
4990 __ push(Immediate(proxy->name()));
4991 __ CallRuntime(Runtime::kLoadLookupSlotNoReferenceError, 2);
4992 PrepareForBailout(expr, TOS_REG);
4995 context()->Plug(eax);
4997 // This expression cannot throw a reference error at the top level.
4998 VisitInDuplicateContext(expr);
5003 void FullCodeGenerator::EmitLiteralCompareTypeof(Expression* expr,
5004 Expression* sub_expr,
5005 Handle<String> check) {
5006 Label materialize_true, materialize_false;
5007 Label* if_true = NULL;
5008 Label* if_false = NULL;
5009 Label* fall_through = NULL;
5010 context()->PrepareTest(&materialize_true, &materialize_false,
5011 &if_true, &if_false, &fall_through);
5013 { AccumulatorValueContext context(this);
5014 VisitForTypeofValue(sub_expr);
5016 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
5018 Factory* factory = isolate()->factory();
5019 if (String::Equals(check, factory->number_string())) {
5020 __ JumpIfSmi(eax, if_true);
5021 __ cmp(FieldOperand(eax, HeapObject::kMapOffset),
5022 isolate()->factory()->heap_number_map());
5023 Split(equal, if_true, if_false, fall_through);
5024 } else if (String::Equals(check, factory->string_string())) {
5025 __ JumpIfSmi(eax, if_false);
5026 __ CmpObjectType(eax, FIRST_NONSTRING_TYPE, edx);
5027 __ j(above_equal, if_false);
5028 // Check for undetectable objects => false.
5029 __ test_b(FieldOperand(edx, Map::kBitFieldOffset),
5030 1 << Map::kIsUndetectable);
5031 Split(zero, if_true, if_false, fall_through);
5032 } else if (String::Equals(check, factory->symbol_string())) {
5033 __ JumpIfSmi(eax, if_false);
5034 __ CmpObjectType(eax, SYMBOL_TYPE, edx);
5035 Split(equal, if_true, if_false, fall_through);
5036 } else if (String::Equals(check, factory->boolean_string())) {
5037 __ cmp(eax, isolate()->factory()->true_value());
5038 __ j(equal, if_true);
5039 __ cmp(eax, isolate()->factory()->false_value());
5040 Split(equal, if_true, if_false, fall_through);
5041 } else if (String::Equals(check, factory->undefined_string())) {
5042 __ cmp(eax, isolate()->factory()->undefined_value());
5043 __ j(equal, if_true);
5044 __ JumpIfSmi(eax, if_false);
5045 // Check for undetectable objects => true.
5046 __ mov(edx, FieldOperand(eax, HeapObject::kMapOffset));
5047 __ movzx_b(ecx, FieldOperand(edx, Map::kBitFieldOffset));
5048 __ test(ecx, Immediate(1 << Map::kIsUndetectable));
5049 Split(not_zero, if_true, if_false, fall_through);
5050 } else if (String::Equals(check, factory->function_string())) {
5051 __ JumpIfSmi(eax, if_false);
5052 STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
5053 __ CmpObjectType(eax, JS_FUNCTION_TYPE, edx);
5054 __ j(equal, if_true);
5055 __ CmpInstanceType(edx, JS_FUNCTION_PROXY_TYPE);
5056 Split(equal, if_true, if_false, fall_through);
5057 } else if (String::Equals(check, factory->object_string())) {
5058 __ JumpIfSmi(eax, if_false);
5059 __ cmp(eax, isolate()->factory()->null_value());
5060 __ j(equal, if_true);
5061 __ CmpObjectType(eax, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE, edx);
5062 __ j(below, if_false);
5063 __ CmpInstanceType(edx, LAST_NONCALLABLE_SPEC_OBJECT_TYPE);
5064 __ j(above, if_false);
5065 // Check for undetectable objects => false.
5066 __ test_b(FieldOperand(edx, Map::kBitFieldOffset),
5067 1 << Map::kIsUndetectable);
5068 Split(zero, if_true, if_false, fall_through);
5070 if (if_false != fall_through) __ jmp(if_false);
5072 context()->Plug(if_true, if_false);
5076 void FullCodeGenerator::VisitCompareOperation(CompareOperation* expr) {
5077 Comment cmnt(masm_, "[ CompareOperation");
5078 SetSourcePosition(expr->position());
5080 // First we try a fast inlined version of the compare when one of
5081 // the operands is a literal.
5082 if (TryLiteralCompare(expr)) return;
5084 // Always perform the comparison for its control flow. Pack the result
5085 // into the expression's context after the comparison is performed.
5086 Label materialize_true, materialize_false;
5087 Label* if_true = NULL;
5088 Label* if_false = NULL;
5089 Label* fall_through = NULL;
5090 context()->PrepareTest(&materialize_true, &materialize_false,
5091 &if_true, &if_false, &fall_through);
5093 Token::Value op = expr->op();
5094 VisitForStackValue(expr->left());
5097 VisitForStackValue(expr->right());
5098 __ InvokeBuiltin(Builtins::IN, CALL_FUNCTION);
5099 PrepareForBailoutBeforeSplit(expr, false, NULL, NULL);
5100 __ cmp(eax, isolate()->factory()->true_value());
5101 Split(equal, if_true, if_false, fall_through);
5104 case Token::INSTANCEOF: {
5105 VisitForStackValue(expr->right());
5106 InstanceofStub stub(isolate(), InstanceofStub::kNoFlags);
5108 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
5110 // The stub returns 0 for true.
5111 Split(zero, if_true, if_false, fall_through);
5116 VisitForAccumulatorValue(expr->right());
5117 Condition cc = CompareIC::ComputeCondition(op);
5120 bool inline_smi_code = ShouldInlineSmiCase(op);
5121 JumpPatchSite patch_site(masm_);
5122 if (inline_smi_code) {
5126 patch_site.EmitJumpIfNotSmi(ecx, &slow_case, Label::kNear);
5128 Split(cc, if_true, if_false, NULL);
5129 __ bind(&slow_case);
5132 // Record position and call the compare IC.
5133 SetSourcePosition(expr->position());
5134 Handle<Code> ic = CodeFactory::CompareIC(isolate(), op).code();
5135 CallIC(ic, expr->CompareOperationFeedbackId());
5136 patch_site.EmitPatchInfo();
5138 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
5140 Split(cc, if_true, if_false, fall_through);
5144 // Convert the result of the comparison into one expected for this
5145 // expression's context.
5146 context()->Plug(if_true, if_false);
5150 void FullCodeGenerator::EmitLiteralCompareNil(CompareOperation* expr,
5151 Expression* sub_expr,
5153 Label materialize_true, materialize_false;
5154 Label* if_true = NULL;
5155 Label* if_false = NULL;
5156 Label* fall_through = NULL;
5157 context()->PrepareTest(&materialize_true, &materialize_false,
5158 &if_true, &if_false, &fall_through);
5160 VisitForAccumulatorValue(sub_expr);
5161 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
5163 Handle<Object> nil_value = nil == kNullValue
5164 ? isolate()->factory()->null_value()
5165 : isolate()->factory()->undefined_value();
5166 if (expr->op() == Token::EQ_STRICT) {
5167 __ cmp(eax, nil_value);
5168 Split(equal, if_true, if_false, fall_through);
5170 Handle<Code> ic = CompareNilICStub::GetUninitialized(isolate(), nil);
5171 CallIC(ic, expr->CompareOperationFeedbackId());
5173 Split(not_zero, if_true, if_false, fall_through);
5175 context()->Plug(if_true, if_false);
5179 void FullCodeGenerator::VisitThisFunction(ThisFunction* expr) {
5180 __ mov(eax, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
5181 context()->Plug(eax);
5185 Register FullCodeGenerator::result_register() {
5190 Register FullCodeGenerator::context_register() {
5195 void FullCodeGenerator::StoreToFrameField(int frame_offset, Register value) {
5196 DCHECK_EQ(POINTER_SIZE_ALIGN(frame_offset), frame_offset);
5197 __ mov(Operand(ebp, frame_offset), value);
5201 void FullCodeGenerator::LoadContextField(Register dst, int context_index) {
5202 __ mov(dst, ContextOperand(esi, context_index));
5206 void FullCodeGenerator::PushFunctionArgumentForContextAllocation() {
5207 Scope* declaration_scope = scope()->DeclarationScope();
5208 if (declaration_scope->is_script_scope() ||
5209 declaration_scope->is_module_scope()) {
5210 // Contexts nested in the native context have a canonical empty function
5211 // as their closure, not the anonymous closure containing the global
5212 // code. Pass a smi sentinel and let the runtime look up the empty
5214 __ push(Immediate(Smi::FromInt(0)));
5215 } else if (declaration_scope->is_eval_scope()) {
5216 // Contexts nested inside eval code have the same closure as the context
5217 // calling eval, not the anonymous closure containing the eval code.
5218 // Fetch it from the context.
5219 __ push(ContextOperand(esi, Context::CLOSURE_INDEX));
5221 DCHECK(declaration_scope->is_function_scope());
5222 __ push(Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
5227 // ----------------------------------------------------------------------------
5228 // Non-local control flow support.
5230 void FullCodeGenerator::EnterFinallyBlock() {
5231 // Cook return address on top of stack (smi encoded Code* delta)
5232 DCHECK(!result_register().is(edx));
5234 __ sub(edx, Immediate(masm_->CodeObject()));
5235 STATIC_ASSERT(kSmiTagSize + kSmiShiftSize == 1);
5236 STATIC_ASSERT(kSmiTag == 0);
5240 // Store result register while executing finally block.
5241 __ push(result_register());
5243 // Store pending message while executing finally block.
5244 ExternalReference pending_message_obj =
5245 ExternalReference::address_of_pending_message_obj(isolate());
5246 __ mov(edx, Operand::StaticVariable(pending_message_obj));
5251 void FullCodeGenerator::ExitFinallyBlock() {
5252 DCHECK(!result_register().is(edx));
5253 // Restore pending message from stack.
5255 ExternalReference pending_message_obj =
5256 ExternalReference::address_of_pending_message_obj(isolate());
5257 __ mov(Operand::StaticVariable(pending_message_obj), edx);
5259 // Restore result register from stack.
5260 __ pop(result_register());
5262 // Uncook return address.
5265 __ add(edx, Immediate(masm_->CodeObject()));
5273 static const byte kJnsInstruction = 0x79;
5274 static const byte kJnsOffset = 0x11;
5275 static const byte kNopByteOne = 0x66;
5276 static const byte kNopByteTwo = 0x90;
5278 static const byte kCallInstruction = 0xe8;
5282 void BackEdgeTable::PatchAt(Code* unoptimized_code,
5284 BackEdgeState target_state,
5285 Code* replacement_code) {
5286 Address call_target_address = pc - kIntSize;
5287 Address jns_instr_address = call_target_address - 3;
5288 Address jns_offset_address = call_target_address - 2;
5290 switch (target_state) {
5292 // sub <profiling_counter>, <delta> ;; Not changed
5294 // call <interrupt stub>
5296 *jns_instr_address = kJnsInstruction;
5297 *jns_offset_address = kJnsOffset;
5299 case ON_STACK_REPLACEMENT:
5300 case OSR_AFTER_STACK_CHECK:
5301 // sub <profiling_counter>, <delta> ;; Not changed
5304 // call <on-stack replacment>
5306 *jns_instr_address = kNopByteOne;
5307 *jns_offset_address = kNopByteTwo;
5311 Assembler::set_target_address_at(call_target_address,
5313 replacement_code->entry());
5314 unoptimized_code->GetHeap()->incremental_marking()->RecordCodeTargetPatch(
5315 unoptimized_code, call_target_address, replacement_code);
5319 BackEdgeTable::BackEdgeState BackEdgeTable::GetBackEdgeState(
5321 Code* unoptimized_code,
5323 Address call_target_address = pc - kIntSize;
5324 Address jns_instr_address = call_target_address - 3;
5325 DCHECK_EQ(kCallInstruction, *(call_target_address - 1));
5327 if (*jns_instr_address == kJnsInstruction) {
5328 DCHECK_EQ(kJnsOffset, *(call_target_address - 2));
5329 DCHECK_EQ(isolate->builtins()->InterruptCheck()->entry(),
5330 Assembler::target_address_at(call_target_address,
5335 DCHECK_EQ(kNopByteOne, *jns_instr_address);
5336 DCHECK_EQ(kNopByteTwo, *(call_target_address - 2));
5338 if (Assembler::target_address_at(call_target_address, unoptimized_code) ==
5339 isolate->builtins()->OnStackReplacement()->entry()) {
5340 return ON_STACK_REPLACEMENT;
5343 DCHECK_EQ(isolate->builtins()->OsrAfterStackCheck()->entry(),
5344 Assembler::target_address_at(call_target_address,
5346 return OSR_AFTER_STACK_CHECK;
5350 } } // namespace v8::internal
5352 #endif // V8_TARGET_ARCH_X87