Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / v8 / src / ia32 / full-codegen-ia32.cc
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.
4
5 #include "src/v8.h"
6
7 #if V8_TARGET_ARCH_IA32
8
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"
19
20 namespace v8 {
21 namespace internal {
22
23 #define __ ACCESS_MASM(masm_)
24
25
26 class JumpPatchSite BASE_EMBEDDED {
27  public:
28   explicit JumpPatchSite(MacroAssembler* masm) : masm_(masm) {
29 #ifdef DEBUG
30     info_emitted_ = false;
31 #endif
32   }
33
34   ~JumpPatchSite() {
35     DCHECK(patch_site_.is_bound() == info_emitted_);
36   }
37
38   void EmitJumpIfNotSmi(Register reg,
39                         Label* target,
40                         Label::Distance distance = Label::kFar) {
41     __ test(reg, Immediate(kSmiTagMask));
42     EmitJump(not_carry, target, distance);  // Always taken before patched.
43   }
44
45   void EmitJumpIfSmi(Register reg,
46                      Label* target,
47                      Label::Distance distance = Label::kFar) {
48     __ test(reg, Immediate(kSmiTagMask));
49     EmitJump(carry, target, distance);  // Never taken before patched.
50   }
51
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));
57 #ifdef DEBUG
58       info_emitted_ = true;
59 #endif
60     } else {
61       __ nop();  // Signals no inlined code.
62     }
63   }
64
65  private:
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);
72   }
73
74   MacroAssembler* masm_;
75   Label patch_site_;
76 #ifdef DEBUG
77   bool info_emitted_;
78 #endif
79 };
80
81
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.
86 //
87 // The live registers are:
88 //   o edi: the JS function object being called (i.e. ourselves)
89 //   o esi: our context
90 //   o ebp: our caller's frame pointer
91 //   o esp: stack pointer (pointing to return address)
92 //
93 // The function builds a JS frame.  Please see JavaScriptFrameConstants in
94 // frames-ia32.h for its layout.
95 void FullCodeGenerator::Generate() {
96   CompilationInfo* info = info_;
97   handler_table_ =
98       isolate()->factory()->NewFixedArray(function()->handler_count(), TENURED);
99
100   profiling_counter_ = isolate()->factory()->NewCell(
101       Handle<Smi>(Smi::FromInt(FLAG_interrupt_budget), isolate()));
102   SetFunctionPosition(function());
103   Comment cmnt(masm_, "[ function compiled by full code generator");
104
105   ProfileEntryHookStub::MaybeCallEntryHook(masm_);
106
107 #ifdef DEBUG
108   if (strlen(FLAG_stop_at) > 0 &&
109       info->function()->name()->IsUtf8EqualTo(CStrVector(FLAG_stop_at))) {
110     __ int3();
111   }
112 #endif
113
114   // Sloppy mode functions and builtins need to replace the receiver with the
115   // global proxy when called as functions (without an explicit receiver
116   // object).
117   if (info->strict_mode() == SLOPPY && !info->is_native()) {
118     Label ok;
119     // +1 for return address.
120     int receiver_offset = (info->scope()->num_parameters() + 1) * kPointerSize;
121     __ mov(ecx, Operand(esp, receiver_offset));
122
123     __ cmp(ecx, isolate()->factory()->undefined_value());
124     __ j(not_equal, &ok, Label::kNear);
125
126     __ mov(ecx, GlobalObjectOperand());
127     __ mov(ecx, FieldOperand(ecx, GlobalObject::kGlobalProxyOffset));
128
129     __ mov(Operand(esp, receiver_offset), ecx);
130
131     __ bind(&ok);
132   }
133
134   // Open a frame scope to indicate that there is a frame on the stack.  The
135   // MANUAL indicates that the scope shouldn't actually generate code to set up
136   // the frame (that is done below).
137   FrameScope frame_scope(masm_, StackFrame::MANUAL);
138
139   info->set_prologue_offset(masm_->pc_offset());
140   __ Prologue(info->IsCodePreAgingActive());
141   info->AddNoFrameRange(0, masm_->pc_offset());
142
143   { Comment cmnt(masm_, "[ Allocate locals");
144     int locals_count = info->scope()->num_stack_slots();
145     // Generators allocate locals, if any, in context slots.
146     DCHECK(!info->function()->is_generator() || locals_count == 0);
147     if (locals_count == 1) {
148       __ push(Immediate(isolate()->factory()->undefined_value()));
149     } else if (locals_count > 1) {
150       if (locals_count >= 128) {
151         Label ok;
152         __ mov(ecx, esp);
153         __ sub(ecx, Immediate(locals_count * kPointerSize));
154         ExternalReference stack_limit =
155             ExternalReference::address_of_real_stack_limit(isolate());
156         __ cmp(ecx, Operand::StaticVariable(stack_limit));
157         __ j(above_equal, &ok, Label::kNear);
158         __ InvokeBuiltin(Builtins::STACK_OVERFLOW, CALL_FUNCTION);
159         __ bind(&ok);
160       }
161       __ mov(eax, Immediate(isolate()->factory()->undefined_value()));
162       const int kMaxPushes = 32;
163       if (locals_count >= kMaxPushes) {
164         int loop_iterations = locals_count / kMaxPushes;
165         __ mov(ecx, loop_iterations);
166         Label loop_header;
167         __ bind(&loop_header);
168         // Do pushes.
169         for (int i = 0; i < kMaxPushes; i++) {
170           __ push(eax);
171         }
172         __ dec(ecx);
173         __ j(not_zero, &loop_header, Label::kNear);
174       }
175       int remaining = locals_count % kMaxPushes;
176       // Emit the remaining pushes.
177       for (int i  = 0; i < remaining; i++) {
178         __ push(eax);
179       }
180     }
181   }
182
183   bool function_in_register = true;
184
185   // Possibly allocate a local context.
186   int heap_slots = info->scope()->num_heap_slots() - Context::MIN_CONTEXT_SLOTS;
187   if (heap_slots > 0) {
188     Comment cmnt(masm_, "[ Allocate context");
189     bool need_write_barrier = true;
190     // Argument to NewContext is the function, which is still in edi.
191     if (FLAG_harmony_scoping && info->scope()->is_global_scope()) {
192       __ push(edi);
193       __ Push(info->scope()->GetScopeInfo());
194       __ CallRuntime(Runtime::kNewGlobalContext, 2);
195     } else if (heap_slots <= FastNewContextStub::kMaximumSlots) {
196       FastNewContextStub stub(isolate(), heap_slots);
197       __ CallStub(&stub);
198       // Result of FastNewContextStub is always in new space.
199       need_write_barrier = false;
200     } else {
201       __ push(edi);
202       __ CallRuntime(Runtime::kNewFunctionContext, 1);
203     }
204     function_in_register = false;
205     // Context is returned in eax.  It replaces the context passed to us.
206     // It's saved in the stack and kept live in esi.
207     __ mov(esi, eax);
208     __ mov(Operand(ebp, StandardFrameConstants::kContextOffset), eax);
209
210     // Copy parameters into context if necessary.
211     int num_parameters = info->scope()->num_parameters();
212     for (int i = 0; i < num_parameters; i++) {
213       Variable* var = scope()->parameter(i);
214       if (var->IsContextSlot()) {
215         int parameter_offset = StandardFrameConstants::kCallerSPOffset +
216             (num_parameters - 1 - i) * kPointerSize;
217         // Load parameter from stack.
218         __ mov(eax, Operand(ebp, parameter_offset));
219         // Store it in the context.
220         int context_offset = Context::SlotOffset(var->index());
221         __ mov(Operand(esi, context_offset), eax);
222         // Update the write barrier. This clobbers eax and ebx.
223         if (need_write_barrier) {
224           __ RecordWriteContextSlot(esi,
225                                     context_offset,
226                                     eax,
227                                     ebx,
228                                     kDontSaveFPRegs);
229         } else if (FLAG_debug_code) {
230           Label done;
231           __ JumpIfInNewSpace(esi, eax, &done, Label::kNear);
232           __ Abort(kExpectedNewSpaceObject);
233           __ bind(&done);
234         }
235       }
236     }
237   }
238
239   Variable* arguments = scope()->arguments();
240   if (arguments != NULL) {
241     // Function uses arguments object.
242     Comment cmnt(masm_, "[ Allocate arguments object");
243     if (function_in_register) {
244       __ push(edi);
245     } else {
246       __ push(Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
247     }
248     // Receiver is just before the parameters on the caller's stack.
249     int num_parameters = info->scope()->num_parameters();
250     int offset = num_parameters * kPointerSize;
251     __ lea(edx,
252            Operand(ebp, StandardFrameConstants::kCallerSPOffset + offset));
253     __ push(edx);
254     __ push(Immediate(Smi::FromInt(num_parameters)));
255     // Arguments to ArgumentsAccessStub:
256     //   function, receiver address, parameter count.
257     // The stub will rewrite receiver and parameter count if the previous
258     // stack frame was an arguments adapter frame.
259     ArgumentsAccessStub::Type type;
260     if (strict_mode() == STRICT) {
261       type = ArgumentsAccessStub::NEW_STRICT;
262     } else if (function()->has_duplicate_parameters()) {
263       type = ArgumentsAccessStub::NEW_SLOPPY_SLOW;
264     } else {
265       type = ArgumentsAccessStub::NEW_SLOPPY_FAST;
266     }
267     ArgumentsAccessStub stub(isolate(), type);
268     __ CallStub(&stub);
269
270     SetVar(arguments, eax, ebx, edx);
271   }
272
273   if (FLAG_trace) {
274     __ CallRuntime(Runtime::kTraceEnter, 0);
275   }
276
277   // Visit the declarations and body unless there is an illegal
278   // redeclaration.
279   if (scope()->HasIllegalRedeclaration()) {
280     Comment cmnt(masm_, "[ Declarations");
281     scope()->VisitIllegalRedeclaration(this);
282
283   } else {
284     PrepareForBailoutForId(BailoutId::FunctionEntry(), NO_REGISTERS);
285     { Comment cmnt(masm_, "[ Declarations");
286       // For named function expressions, declare the function name as a
287       // constant.
288       if (scope()->is_function_scope() && scope()->function() != NULL) {
289         VariableDeclaration* function = scope()->function();
290         DCHECK(function->proxy()->var()->mode() == CONST ||
291                function->proxy()->var()->mode() == CONST_LEGACY);
292         DCHECK(function->proxy()->var()->location() != Variable::UNALLOCATED);
293         VisitVariableDeclaration(function);
294       }
295       VisitDeclarations(scope()->declarations());
296     }
297
298     { Comment cmnt(masm_, "[ Stack check");
299       PrepareForBailoutForId(BailoutId::Declarations(), NO_REGISTERS);
300       Label ok;
301       ExternalReference stack_limit
302           = ExternalReference::address_of_stack_limit(isolate());
303       __ cmp(esp, Operand::StaticVariable(stack_limit));
304       __ j(above_equal, &ok, Label::kNear);
305       __ call(isolate()->builtins()->StackCheck(), RelocInfo::CODE_TARGET);
306       __ bind(&ok);
307     }
308
309     { Comment cmnt(masm_, "[ Body");
310       DCHECK(loop_depth() == 0);
311       VisitStatements(function()->body());
312       DCHECK(loop_depth() == 0);
313     }
314   }
315
316   // Always emit a 'return undefined' in case control fell off the end of
317   // the body.
318   { Comment cmnt(masm_, "[ return <undefined>;");
319     __ mov(eax, isolate()->factory()->undefined_value());
320     EmitReturnSequence();
321   }
322 }
323
324
325 void FullCodeGenerator::ClearAccumulator() {
326   __ Move(eax, Immediate(Smi::FromInt(0)));
327 }
328
329
330 void FullCodeGenerator::EmitProfilingCounterDecrement(int delta) {
331   __ mov(ebx, Immediate(profiling_counter_));
332   __ sub(FieldOperand(ebx, Cell::kValueOffset),
333          Immediate(Smi::FromInt(delta)));
334 }
335
336
337 void FullCodeGenerator::EmitProfilingCounterReset() {
338   int reset_value = FLAG_interrupt_budget;
339   __ mov(ebx, Immediate(profiling_counter_));
340   __ mov(FieldOperand(ebx, Cell::kValueOffset),
341          Immediate(Smi::FromInt(reset_value)));
342 }
343
344
345 void FullCodeGenerator::EmitBackEdgeBookkeeping(IterationStatement* stmt,
346                                                 Label* back_edge_target) {
347   Comment cmnt(masm_, "[ Back edge bookkeeping");
348   Label ok;
349
350   DCHECK(back_edge_target->is_bound());
351   int distance = masm_->SizeOfCodeGeneratedSince(back_edge_target);
352   int weight = Min(kMaxBackEdgeWeight,
353                    Max(1, distance / kCodeSizeMultiplier));
354   EmitProfilingCounterDecrement(weight);
355   __ j(positive, &ok, Label::kNear);
356   __ call(isolate()->builtins()->InterruptCheck(), RelocInfo::CODE_TARGET);
357
358   // Record a mapping of this PC offset to the OSR id.  This is used to find
359   // the AST id from the unoptimized code in order to use it as a key into
360   // the deoptimization input data found in the optimized code.
361   RecordBackEdge(stmt->OsrEntryId());
362
363   EmitProfilingCounterReset();
364
365   __ bind(&ok);
366   PrepareForBailoutForId(stmt->EntryId(), NO_REGISTERS);
367   // Record a mapping of the OSR id to this PC.  This is used if the OSR
368   // entry becomes the target of a bailout.  We don't expect it to be, but
369   // we want it to work if it is.
370   PrepareForBailoutForId(stmt->OsrEntryId(), NO_REGISTERS);
371 }
372
373
374 void FullCodeGenerator::EmitReturnSequence() {
375   Comment cmnt(masm_, "[ Return sequence");
376   if (return_label_.is_bound()) {
377     __ jmp(&return_label_);
378   } else {
379     // Common return label
380     __ bind(&return_label_);
381     if (FLAG_trace) {
382       __ push(eax);
383       __ CallRuntime(Runtime::kTraceExit, 1);
384     }
385     // Pretend that the exit is a backwards jump to the entry.
386     int weight = 1;
387     if (info_->ShouldSelfOptimize()) {
388       weight = FLAG_interrupt_budget / FLAG_self_opt_count;
389     } else {
390       int distance = masm_->pc_offset();
391       weight = Min(kMaxBackEdgeWeight,
392                    Max(1, distance / kCodeSizeMultiplier));
393     }
394     EmitProfilingCounterDecrement(weight);
395     Label ok;
396     __ j(positive, &ok, Label::kNear);
397     __ push(eax);
398     __ call(isolate()->builtins()->InterruptCheck(),
399             RelocInfo::CODE_TARGET);
400     __ pop(eax);
401     EmitProfilingCounterReset();
402     __ bind(&ok);
403 #ifdef DEBUG
404     // Add a label for checking the size of the code used for returning.
405     Label check_exit_codesize;
406     masm_->bind(&check_exit_codesize);
407 #endif
408     SetSourcePosition(function()->end_position() - 1);
409     __ RecordJSReturn();
410     // Do not use the leave instruction here because it is too short to
411     // patch with the code required by the debugger.
412     __ mov(esp, ebp);
413     int no_frame_start = masm_->pc_offset();
414     __ pop(ebp);
415
416     int arguments_bytes = (info_->scope()->num_parameters() + 1) * kPointerSize;
417     __ Ret(arguments_bytes, ecx);
418     // Check that the size of the code used for returning is large enough
419     // for the debugger's requirements.
420     DCHECK(Assembler::kJSReturnSequenceLength <=
421            masm_->SizeOfCodeGeneratedSince(&check_exit_codesize));
422     info_->AddNoFrameRange(no_frame_start, masm_->pc_offset());
423   }
424 }
425
426
427 void FullCodeGenerator::EffectContext::Plug(Variable* var) const {
428   DCHECK(var->IsStackAllocated() || var->IsContextSlot());
429 }
430
431
432 void FullCodeGenerator::AccumulatorValueContext::Plug(Variable* var) const {
433   DCHECK(var->IsStackAllocated() || var->IsContextSlot());
434   codegen()->GetVar(result_register(), var);
435 }
436
437
438 void FullCodeGenerator::StackValueContext::Plug(Variable* var) const {
439   DCHECK(var->IsStackAllocated() || var->IsContextSlot());
440   MemOperand operand = codegen()->VarOperand(var, result_register());
441   // Memory operands can be pushed directly.
442   __ push(operand);
443 }
444
445
446 void FullCodeGenerator::TestContext::Plug(Variable* var) const {
447   // For simplicity we always test the accumulator register.
448   codegen()->GetVar(result_register(), var);
449   codegen()->PrepareForBailoutBeforeSplit(condition(), false, NULL, NULL);
450   codegen()->DoTest(this);
451 }
452
453
454 void FullCodeGenerator::EffectContext::Plug(Heap::RootListIndex index) const {
455   UNREACHABLE();  // Not used on IA32.
456 }
457
458
459 void FullCodeGenerator::AccumulatorValueContext::Plug(
460     Heap::RootListIndex index) const {
461   UNREACHABLE();  // Not used on IA32.
462 }
463
464
465 void FullCodeGenerator::StackValueContext::Plug(
466     Heap::RootListIndex index) const {
467   UNREACHABLE();  // Not used on IA32.
468 }
469
470
471 void FullCodeGenerator::TestContext::Plug(Heap::RootListIndex index) const {
472   UNREACHABLE();  // Not used on IA32.
473 }
474
475
476 void FullCodeGenerator::EffectContext::Plug(Handle<Object> lit) const {
477 }
478
479
480 void FullCodeGenerator::AccumulatorValueContext::Plug(
481     Handle<Object> lit) const {
482   if (lit->IsSmi()) {
483     __ SafeMove(result_register(), Immediate(lit));
484   } else {
485     __ Move(result_register(), Immediate(lit));
486   }
487 }
488
489
490 void FullCodeGenerator::StackValueContext::Plug(Handle<Object> lit) const {
491   if (lit->IsSmi()) {
492     __ SafePush(Immediate(lit));
493   } else {
494     __ push(Immediate(lit));
495   }
496 }
497
498
499 void FullCodeGenerator::TestContext::Plug(Handle<Object> lit) const {
500   codegen()->PrepareForBailoutBeforeSplit(condition(),
501                                           true,
502                                           true_label_,
503                                           false_label_);
504   DCHECK(!lit->IsUndetectableObject());  // There are no undetectable literals.
505   if (lit->IsUndefined() || lit->IsNull() || lit->IsFalse()) {
506     if (false_label_ != fall_through_) __ jmp(false_label_);
507   } else if (lit->IsTrue() || lit->IsJSObject()) {
508     if (true_label_ != fall_through_) __ jmp(true_label_);
509   } else if (lit->IsString()) {
510     if (String::cast(*lit)->length() == 0) {
511       if (false_label_ != fall_through_) __ jmp(false_label_);
512     } else {
513       if (true_label_ != fall_through_) __ jmp(true_label_);
514     }
515   } else if (lit->IsSmi()) {
516     if (Smi::cast(*lit)->value() == 0) {
517       if (false_label_ != fall_through_) __ jmp(false_label_);
518     } else {
519       if (true_label_ != fall_through_) __ jmp(true_label_);
520     }
521   } else {
522     // For simplicity we always test the accumulator register.
523     __ mov(result_register(), lit);
524     codegen()->DoTest(this);
525   }
526 }
527
528
529 void FullCodeGenerator::EffectContext::DropAndPlug(int count,
530                                                    Register reg) const {
531   DCHECK(count > 0);
532   __ Drop(count);
533 }
534
535
536 void FullCodeGenerator::AccumulatorValueContext::DropAndPlug(
537     int count,
538     Register reg) const {
539   DCHECK(count > 0);
540   __ Drop(count);
541   __ Move(result_register(), reg);
542 }
543
544
545 void FullCodeGenerator::StackValueContext::DropAndPlug(int count,
546                                                        Register reg) const {
547   DCHECK(count > 0);
548   if (count > 1) __ Drop(count - 1);
549   __ mov(Operand(esp, 0), reg);
550 }
551
552
553 void FullCodeGenerator::TestContext::DropAndPlug(int count,
554                                                  Register reg) const {
555   DCHECK(count > 0);
556   // For simplicity we always test the accumulator register.
557   __ Drop(count);
558   __ Move(result_register(), reg);
559   codegen()->PrepareForBailoutBeforeSplit(condition(), false, NULL, NULL);
560   codegen()->DoTest(this);
561 }
562
563
564 void FullCodeGenerator::EffectContext::Plug(Label* materialize_true,
565                                             Label* materialize_false) const {
566   DCHECK(materialize_true == materialize_false);
567   __ bind(materialize_true);
568 }
569
570
571 void FullCodeGenerator::AccumulatorValueContext::Plug(
572     Label* materialize_true,
573     Label* materialize_false) const {
574   Label done;
575   __ bind(materialize_true);
576   __ mov(result_register(), isolate()->factory()->true_value());
577   __ jmp(&done, Label::kNear);
578   __ bind(materialize_false);
579   __ mov(result_register(), isolate()->factory()->false_value());
580   __ bind(&done);
581 }
582
583
584 void FullCodeGenerator::StackValueContext::Plug(
585     Label* materialize_true,
586     Label* materialize_false) const {
587   Label done;
588   __ bind(materialize_true);
589   __ push(Immediate(isolate()->factory()->true_value()));
590   __ jmp(&done, Label::kNear);
591   __ bind(materialize_false);
592   __ push(Immediate(isolate()->factory()->false_value()));
593   __ bind(&done);
594 }
595
596
597 void FullCodeGenerator::TestContext::Plug(Label* materialize_true,
598                                           Label* materialize_false) const {
599   DCHECK(materialize_true == true_label_);
600   DCHECK(materialize_false == false_label_);
601 }
602
603
604 void FullCodeGenerator::EffectContext::Plug(bool flag) const {
605 }
606
607
608 void FullCodeGenerator::AccumulatorValueContext::Plug(bool flag) const {
609   Handle<Object> value = flag
610       ? isolate()->factory()->true_value()
611       : isolate()->factory()->false_value();
612   __ mov(result_register(), value);
613 }
614
615
616 void FullCodeGenerator::StackValueContext::Plug(bool flag) const {
617   Handle<Object> value = flag
618       ? isolate()->factory()->true_value()
619       : isolate()->factory()->false_value();
620   __ push(Immediate(value));
621 }
622
623
624 void FullCodeGenerator::TestContext::Plug(bool flag) const {
625   codegen()->PrepareForBailoutBeforeSplit(condition(),
626                                           true,
627                                           true_label_,
628                                           false_label_);
629   if (flag) {
630     if (true_label_ != fall_through_) __ jmp(true_label_);
631   } else {
632     if (false_label_ != fall_through_) __ jmp(false_label_);
633   }
634 }
635
636
637 void FullCodeGenerator::DoTest(Expression* condition,
638                                Label* if_true,
639                                Label* if_false,
640                                Label* fall_through) {
641   Handle<Code> ic = ToBooleanStub::GetUninitialized(isolate());
642   CallIC(ic, condition->test_id());
643   __ test(result_register(), result_register());
644   // The stub returns nonzero for true.
645   Split(not_zero, if_true, if_false, fall_through);
646 }
647
648
649 void FullCodeGenerator::Split(Condition cc,
650                               Label* if_true,
651                               Label* if_false,
652                               Label* fall_through) {
653   if (if_false == fall_through) {
654     __ j(cc, if_true);
655   } else if (if_true == fall_through) {
656     __ j(NegateCondition(cc), if_false);
657   } else {
658     __ j(cc, if_true);
659     __ jmp(if_false);
660   }
661 }
662
663
664 MemOperand FullCodeGenerator::StackOperand(Variable* var) {
665   DCHECK(var->IsStackAllocated());
666   // Offset is negative because higher indexes are at lower addresses.
667   int offset = -var->index() * kPointerSize;
668   // Adjust by a (parameter or local) base offset.
669   if (var->IsParameter()) {
670     offset += (info_->scope()->num_parameters() + 1) * kPointerSize;
671   } else {
672     offset += JavaScriptFrameConstants::kLocal0Offset;
673   }
674   return Operand(ebp, offset);
675 }
676
677
678 MemOperand FullCodeGenerator::VarOperand(Variable* var, Register scratch) {
679   DCHECK(var->IsContextSlot() || var->IsStackAllocated());
680   if (var->IsContextSlot()) {
681     int context_chain_length = scope()->ContextChainLength(var->scope());
682     __ LoadContext(scratch, context_chain_length);
683     return ContextOperand(scratch, var->index());
684   } else {
685     return StackOperand(var);
686   }
687 }
688
689
690 void FullCodeGenerator::GetVar(Register dest, Variable* var) {
691   DCHECK(var->IsContextSlot() || var->IsStackAllocated());
692   MemOperand location = VarOperand(var, dest);
693   __ mov(dest, location);
694 }
695
696
697 void FullCodeGenerator::SetVar(Variable* var,
698                                Register src,
699                                Register scratch0,
700                                Register scratch1) {
701   DCHECK(var->IsContextSlot() || var->IsStackAllocated());
702   DCHECK(!scratch0.is(src));
703   DCHECK(!scratch0.is(scratch1));
704   DCHECK(!scratch1.is(src));
705   MemOperand location = VarOperand(var, scratch0);
706   __ mov(location, src);
707
708   // Emit the write barrier code if the location is in the heap.
709   if (var->IsContextSlot()) {
710     int offset = Context::SlotOffset(var->index());
711     DCHECK(!scratch0.is(esi) && !src.is(esi) && !scratch1.is(esi));
712     __ RecordWriteContextSlot(scratch0, offset, src, scratch1, kDontSaveFPRegs);
713   }
714 }
715
716
717 void FullCodeGenerator::PrepareForBailoutBeforeSplit(Expression* expr,
718                                                      bool should_normalize,
719                                                      Label* if_true,
720                                                      Label* if_false) {
721   // Only prepare for bailouts before splits if we're in a test
722   // context. Otherwise, we let the Visit function deal with the
723   // preparation to avoid preparing with the same AST id twice.
724   if (!context()->IsTest() || !info_->IsOptimizable()) return;
725
726   Label skip;
727   if (should_normalize) __ jmp(&skip, Label::kNear);
728   PrepareForBailout(expr, TOS_REG);
729   if (should_normalize) {
730     __ cmp(eax, isolate()->factory()->true_value());
731     Split(equal, if_true, if_false, NULL);
732     __ bind(&skip);
733   }
734 }
735
736
737 void FullCodeGenerator::EmitDebugCheckDeclarationContext(Variable* variable) {
738   // The variable in the declaration always resides in the current context.
739   DCHECK_EQ(0, scope()->ContextChainLength(variable->scope()));
740   if (generate_debug_code_) {
741     // Check that we're not inside a with or catch context.
742     __ mov(ebx, FieldOperand(esi, HeapObject::kMapOffset));
743     __ cmp(ebx, isolate()->factory()->with_context_map());
744     __ Check(not_equal, kDeclarationInWithContext);
745     __ cmp(ebx, isolate()->factory()->catch_context_map());
746     __ Check(not_equal, kDeclarationInCatchContext);
747   }
748 }
749
750
751 void FullCodeGenerator::VisitVariableDeclaration(
752     VariableDeclaration* declaration) {
753   // If it was not possible to allocate the variable at compile time, we
754   // need to "declare" it at runtime to make sure it actually exists in the
755   // local context.
756   VariableProxy* proxy = declaration->proxy();
757   VariableMode mode = declaration->mode();
758   Variable* variable = proxy->var();
759   bool hole_init = mode == LET || mode == CONST || mode == CONST_LEGACY;
760   switch (variable->location()) {
761     case Variable::UNALLOCATED:
762       globals_->Add(variable->name(), zone());
763       globals_->Add(variable->binding_needs_init()
764                         ? isolate()->factory()->the_hole_value()
765                         : isolate()->factory()->undefined_value(), zone());
766       break;
767
768     case Variable::PARAMETER:
769     case Variable::LOCAL:
770       if (hole_init) {
771         Comment cmnt(masm_, "[ VariableDeclaration");
772         __ mov(StackOperand(variable),
773                Immediate(isolate()->factory()->the_hole_value()));
774       }
775       break;
776
777     case Variable::CONTEXT:
778       if (hole_init) {
779         Comment cmnt(masm_, "[ VariableDeclaration");
780         EmitDebugCheckDeclarationContext(variable);
781         __ mov(ContextOperand(esi, variable->index()),
782                Immediate(isolate()->factory()->the_hole_value()));
783         // No write barrier since the hole value is in old space.
784         PrepareForBailoutForId(proxy->id(), NO_REGISTERS);
785       }
786       break;
787
788     case Variable::LOOKUP: {
789       Comment cmnt(masm_, "[ VariableDeclaration");
790       __ push(esi);
791       __ push(Immediate(variable->name()));
792       // VariableDeclaration nodes are always introduced in one of four modes.
793       DCHECK(IsDeclaredVariableMode(mode));
794       PropertyAttributes attr =
795           IsImmutableVariableMode(mode) ? READ_ONLY : NONE;
796       __ push(Immediate(Smi::FromInt(attr)));
797       // Push initial value, if any.
798       // Note: For variables we must not push an initial value (such as
799       // 'undefined') because we may have a (legal) redeclaration and we
800       // must not destroy the current value.
801       if (hole_init) {
802         __ push(Immediate(isolate()->factory()->the_hole_value()));
803       } else {
804         __ push(Immediate(Smi::FromInt(0)));  // Indicates no initial value.
805       }
806       __ CallRuntime(Runtime::kDeclareLookupSlot, 4);
807       break;
808     }
809   }
810 }
811
812
813 void FullCodeGenerator::VisitFunctionDeclaration(
814     FunctionDeclaration* declaration) {
815   VariableProxy* proxy = declaration->proxy();
816   Variable* variable = proxy->var();
817   switch (variable->location()) {
818     case Variable::UNALLOCATED: {
819       globals_->Add(variable->name(), zone());
820       Handle<SharedFunctionInfo> function =
821           Compiler::BuildFunctionInfo(declaration->fun(), script(), info_);
822       // Check for stack-overflow exception.
823       if (function.is_null()) return SetStackOverflow();
824       globals_->Add(function, zone());
825       break;
826     }
827
828     case Variable::PARAMETER:
829     case Variable::LOCAL: {
830       Comment cmnt(masm_, "[ FunctionDeclaration");
831       VisitForAccumulatorValue(declaration->fun());
832       __ mov(StackOperand(variable), result_register());
833       break;
834     }
835
836     case Variable::CONTEXT: {
837       Comment cmnt(masm_, "[ FunctionDeclaration");
838       EmitDebugCheckDeclarationContext(variable);
839       VisitForAccumulatorValue(declaration->fun());
840       __ mov(ContextOperand(esi, variable->index()), result_register());
841       // We know that we have written a function, which is not a smi.
842       __ RecordWriteContextSlot(esi,
843                                 Context::SlotOffset(variable->index()),
844                                 result_register(),
845                                 ecx,
846                                 kDontSaveFPRegs,
847                                 EMIT_REMEMBERED_SET,
848                                 OMIT_SMI_CHECK);
849       PrepareForBailoutForId(proxy->id(), NO_REGISTERS);
850       break;
851     }
852
853     case Variable::LOOKUP: {
854       Comment cmnt(masm_, "[ FunctionDeclaration");
855       __ push(esi);
856       __ push(Immediate(variable->name()));
857       __ push(Immediate(Smi::FromInt(NONE)));
858       VisitForStackValue(declaration->fun());
859       __ CallRuntime(Runtime::kDeclareLookupSlot, 4);
860       break;
861     }
862   }
863 }
864
865
866 void FullCodeGenerator::VisitModuleDeclaration(ModuleDeclaration* declaration) {
867   Variable* variable = declaration->proxy()->var();
868   DCHECK(variable->location() == Variable::CONTEXT);
869   DCHECK(variable->interface()->IsFrozen());
870
871   Comment cmnt(masm_, "[ ModuleDeclaration");
872   EmitDebugCheckDeclarationContext(variable);
873
874   // Load instance object.
875   __ LoadContext(eax, scope_->ContextChainLength(scope_->GlobalScope()));
876   __ mov(eax, ContextOperand(eax, variable->interface()->Index()));
877   __ mov(eax, ContextOperand(eax, Context::EXTENSION_INDEX));
878
879   // Assign it.
880   __ mov(ContextOperand(esi, variable->index()), eax);
881   // We know that we have written a module, which is not a smi.
882   __ RecordWriteContextSlot(esi,
883                             Context::SlotOffset(variable->index()),
884                             eax,
885                             ecx,
886                             kDontSaveFPRegs,
887                             EMIT_REMEMBERED_SET,
888                             OMIT_SMI_CHECK);
889   PrepareForBailoutForId(declaration->proxy()->id(), NO_REGISTERS);
890
891   // Traverse into body.
892   Visit(declaration->module());
893 }
894
895
896 void FullCodeGenerator::VisitImportDeclaration(ImportDeclaration* declaration) {
897   VariableProxy* proxy = declaration->proxy();
898   Variable* variable = proxy->var();
899   switch (variable->location()) {
900     case Variable::UNALLOCATED:
901       // TODO(rossberg)
902       break;
903
904     case Variable::CONTEXT: {
905       Comment cmnt(masm_, "[ ImportDeclaration");
906       EmitDebugCheckDeclarationContext(variable);
907       // TODO(rossberg)
908       break;
909     }
910
911     case Variable::PARAMETER:
912     case Variable::LOCAL:
913     case Variable::LOOKUP:
914       UNREACHABLE();
915   }
916 }
917
918
919 void FullCodeGenerator::VisitExportDeclaration(ExportDeclaration* declaration) {
920   // TODO(rossberg)
921 }
922
923
924 void FullCodeGenerator::DeclareGlobals(Handle<FixedArray> pairs) {
925   // Call the runtime to declare the globals.
926   __ push(esi);  // The context is the first argument.
927   __ Push(pairs);
928   __ Push(Smi::FromInt(DeclareGlobalsFlags()));
929   __ CallRuntime(Runtime::kDeclareGlobals, 3);
930   // Return value is ignored.
931 }
932
933
934 void FullCodeGenerator::DeclareModules(Handle<FixedArray> descriptions) {
935   // Call the runtime to declare the modules.
936   __ Push(descriptions);
937   __ CallRuntime(Runtime::kDeclareModules, 1);
938   // Return value is ignored.
939 }
940
941
942 void FullCodeGenerator::VisitSwitchStatement(SwitchStatement* stmt) {
943   Comment cmnt(masm_, "[ SwitchStatement");
944   Breakable nested_statement(this, stmt);
945   SetStatementPosition(stmt);
946
947   // Keep the switch value on the stack until a case matches.
948   VisitForStackValue(stmt->tag());
949   PrepareForBailoutForId(stmt->EntryId(), NO_REGISTERS);
950
951   ZoneList<CaseClause*>* clauses = stmt->cases();
952   CaseClause* default_clause = NULL;  // Can occur anywhere in the list.
953
954   Label next_test;  // Recycled for each test.
955   // Compile all the tests with branches to their bodies.
956   for (int i = 0; i < clauses->length(); i++) {
957     CaseClause* clause = clauses->at(i);
958     clause->body_target()->Unuse();
959
960     // The default is not a test, but remember it as final fall through.
961     if (clause->is_default()) {
962       default_clause = clause;
963       continue;
964     }
965
966     Comment cmnt(masm_, "[ Case comparison");
967     __ bind(&next_test);
968     next_test.Unuse();
969
970     // Compile the label expression.
971     VisitForAccumulatorValue(clause->label());
972
973     // Perform the comparison as if via '==='.
974     __ mov(edx, Operand(esp, 0));  // Switch value.
975     bool inline_smi_code = ShouldInlineSmiCase(Token::EQ_STRICT);
976     JumpPatchSite patch_site(masm_);
977     if (inline_smi_code) {
978       Label slow_case;
979       __ mov(ecx, edx);
980       __ or_(ecx, eax);
981       patch_site.EmitJumpIfNotSmi(ecx, &slow_case, Label::kNear);
982
983       __ cmp(edx, eax);
984       __ j(not_equal, &next_test);
985       __ Drop(1);  // Switch value is no longer needed.
986       __ jmp(clause->body_target());
987       __ bind(&slow_case);
988     }
989
990     // Record position before stub call for type feedback.
991     SetSourcePosition(clause->position());
992     Handle<Code> ic =
993         CodeFactory::CompareIC(isolate(), Token::EQ_STRICT).code();
994     CallIC(ic, clause->CompareId());
995     patch_site.EmitPatchInfo();
996
997     Label skip;
998     __ jmp(&skip, Label::kNear);
999     PrepareForBailout(clause, TOS_REG);
1000     __ cmp(eax, isolate()->factory()->true_value());
1001     __ j(not_equal, &next_test);
1002     __ Drop(1);
1003     __ jmp(clause->body_target());
1004     __ bind(&skip);
1005
1006     __ test(eax, eax);
1007     __ j(not_equal, &next_test);
1008     __ Drop(1);  // Switch value is no longer needed.
1009     __ jmp(clause->body_target());
1010   }
1011
1012   // Discard the test value and jump to the default if present, otherwise to
1013   // the end of the statement.
1014   __ bind(&next_test);
1015   __ Drop(1);  // Switch value is no longer needed.
1016   if (default_clause == NULL) {
1017     __ jmp(nested_statement.break_label());
1018   } else {
1019     __ jmp(default_clause->body_target());
1020   }
1021
1022   // Compile all the case bodies.
1023   for (int i = 0; i < clauses->length(); i++) {
1024     Comment cmnt(masm_, "[ Case body");
1025     CaseClause* clause = clauses->at(i);
1026     __ bind(clause->body_target());
1027     PrepareForBailoutForId(clause->EntryId(), NO_REGISTERS);
1028     VisitStatements(clause->statements());
1029   }
1030
1031   __ bind(nested_statement.break_label());
1032   PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1033 }
1034
1035
1036 void FullCodeGenerator::VisitForInStatement(ForInStatement* stmt) {
1037   Comment cmnt(masm_, "[ ForInStatement");
1038   FeedbackVectorSlot slot = stmt->ForInFeedbackSlot();
1039
1040   SetStatementPosition(stmt);
1041
1042   Label loop, exit;
1043   ForIn loop_statement(this, stmt);
1044   increment_loop_depth();
1045
1046   // Get the object to enumerate over. If the object is null or undefined, skip
1047   // over the loop.  See ECMA-262 version 5, section 12.6.4.
1048   VisitForAccumulatorValue(stmt->enumerable());
1049   __ cmp(eax, isolate()->factory()->undefined_value());
1050   __ j(equal, &exit);
1051   __ cmp(eax, isolate()->factory()->null_value());
1052   __ j(equal, &exit);
1053
1054   PrepareForBailoutForId(stmt->PrepareId(), TOS_REG);
1055
1056   // Convert the object to a JS object.
1057   Label convert, done_convert;
1058   __ JumpIfSmi(eax, &convert, Label::kNear);
1059   __ CmpObjectType(eax, FIRST_SPEC_OBJECT_TYPE, ecx);
1060   __ j(above_equal, &done_convert, Label::kNear);
1061   __ bind(&convert);
1062   __ push(eax);
1063   __ InvokeBuiltin(Builtins::TO_OBJECT, CALL_FUNCTION);
1064   __ bind(&done_convert);
1065   PrepareForBailoutForId(stmt->ToObjectId(), TOS_REG);
1066   __ push(eax);
1067
1068   // Check for proxies.
1069   Label call_runtime, use_cache, fixed_array;
1070   STATIC_ASSERT(FIRST_JS_PROXY_TYPE == FIRST_SPEC_OBJECT_TYPE);
1071   __ CmpObjectType(eax, LAST_JS_PROXY_TYPE, ecx);
1072   __ j(below_equal, &call_runtime);
1073
1074   // Check cache validity in generated code. This is a fast case for
1075   // the JSObject::IsSimpleEnum cache validity checks. If we cannot
1076   // guarantee cache validity, call the runtime system to check cache
1077   // validity or get the property names in a fixed array.
1078   __ CheckEnumCache(&call_runtime);
1079
1080   __ mov(eax, FieldOperand(eax, HeapObject::kMapOffset));
1081   __ jmp(&use_cache, Label::kNear);
1082
1083   // Get the set of properties to enumerate.
1084   __ bind(&call_runtime);
1085   __ push(eax);
1086   __ CallRuntime(Runtime::kGetPropertyNamesFast, 1);
1087   PrepareForBailoutForId(stmt->EnumId(), TOS_REG);
1088   __ cmp(FieldOperand(eax, HeapObject::kMapOffset),
1089          isolate()->factory()->meta_map());
1090   __ j(not_equal, &fixed_array);
1091
1092
1093   // We got a map in register eax. Get the enumeration cache from it.
1094   Label no_descriptors;
1095   __ bind(&use_cache);
1096
1097   __ EnumLength(edx, eax);
1098   __ cmp(edx, Immediate(Smi::FromInt(0)));
1099   __ j(equal, &no_descriptors);
1100
1101   __ LoadInstanceDescriptors(eax, ecx);
1102   __ mov(ecx, FieldOperand(ecx, DescriptorArray::kEnumCacheOffset));
1103   __ mov(ecx, FieldOperand(ecx, DescriptorArray::kEnumCacheBridgeCacheOffset));
1104
1105   // Set up the four remaining stack slots.
1106   __ push(eax);  // Map.
1107   __ push(ecx);  // Enumeration cache.
1108   __ push(edx);  // Number of valid entries for the map in the enum cache.
1109   __ push(Immediate(Smi::FromInt(0)));  // Initial index.
1110   __ jmp(&loop);
1111
1112   __ bind(&no_descriptors);
1113   __ add(esp, Immediate(kPointerSize));
1114   __ jmp(&exit);
1115
1116   // We got a fixed array in register eax. Iterate through that.
1117   Label non_proxy;
1118   __ bind(&fixed_array);
1119
1120   // No need for a write barrier, we are storing a Smi in the feedback vector.
1121   __ LoadHeapObject(ebx, FeedbackVector());
1122   int vector_index = FeedbackVector()->GetIndex(slot);
1123   __ mov(FieldOperand(ebx, FixedArray::OffsetOfElementAt(vector_index)),
1124          Immediate(TypeFeedbackVector::MegamorphicSentinel(isolate())));
1125
1126   __ mov(ebx, Immediate(Smi::FromInt(1)));  // Smi indicates slow check
1127   __ mov(ecx, Operand(esp, 0 * kPointerSize));  // Get enumerated object
1128   STATIC_ASSERT(FIRST_JS_PROXY_TYPE == FIRST_SPEC_OBJECT_TYPE);
1129   __ CmpObjectType(ecx, LAST_JS_PROXY_TYPE, ecx);
1130   __ j(above, &non_proxy);
1131   __ Move(ebx, Immediate(Smi::FromInt(0)));  // Zero indicates proxy
1132   __ bind(&non_proxy);
1133   __ push(ebx);  // Smi
1134   __ push(eax);  // Array
1135   __ mov(eax, FieldOperand(eax, FixedArray::kLengthOffset));
1136   __ push(eax);  // Fixed array length (as smi).
1137   __ push(Immediate(Smi::FromInt(0)));  // Initial index.
1138
1139   // Generate code for doing the condition check.
1140   PrepareForBailoutForId(stmt->BodyId(), NO_REGISTERS);
1141   __ bind(&loop);
1142   __ mov(eax, Operand(esp, 0 * kPointerSize));  // Get the current index.
1143   __ cmp(eax, Operand(esp, 1 * kPointerSize));  // Compare to the array length.
1144   __ j(above_equal, loop_statement.break_label());
1145
1146   // Get the current entry of the array into register ebx.
1147   __ mov(ebx, Operand(esp, 2 * kPointerSize));
1148   __ mov(ebx, FieldOperand(ebx, eax, times_2, FixedArray::kHeaderSize));
1149
1150   // Get the expected map from the stack or a smi in the
1151   // permanent slow case into register edx.
1152   __ mov(edx, Operand(esp, 3 * kPointerSize));
1153
1154   // Check if the expected map still matches that of the enumerable.
1155   // If not, we may have to filter the key.
1156   Label update_each;
1157   __ mov(ecx, Operand(esp, 4 * kPointerSize));
1158   __ cmp(edx, FieldOperand(ecx, HeapObject::kMapOffset));
1159   __ j(equal, &update_each, Label::kNear);
1160
1161   // For proxies, no filtering is done.
1162   // TODO(rossberg): What if only a prototype is a proxy? Not specified yet.
1163   DCHECK(Smi::FromInt(0) == 0);
1164   __ test(edx, edx);
1165   __ j(zero, &update_each);
1166
1167   // Convert the entry to a string or null if it isn't a property
1168   // anymore. If the property has been removed while iterating, we
1169   // just skip it.
1170   __ push(ecx);  // Enumerable.
1171   __ push(ebx);  // Current entry.
1172   __ InvokeBuiltin(Builtins::FILTER_KEY, CALL_FUNCTION);
1173   __ test(eax, eax);
1174   __ j(equal, loop_statement.continue_label());
1175   __ mov(ebx, eax);
1176
1177   // Update the 'each' property or variable from the possibly filtered
1178   // entry in register ebx.
1179   __ bind(&update_each);
1180   __ mov(result_register(), ebx);
1181   // Perform the assignment as if via '='.
1182   { EffectContext context(this);
1183     EmitAssignment(stmt->each());
1184   }
1185
1186   // Generate code for the body of the loop.
1187   Visit(stmt->body());
1188
1189   // Generate code for going to the next element by incrementing the
1190   // index (smi) stored on top of the stack.
1191   __ bind(loop_statement.continue_label());
1192   __ add(Operand(esp, 0 * kPointerSize), Immediate(Smi::FromInt(1)));
1193
1194   EmitBackEdgeBookkeeping(stmt, &loop);
1195   __ jmp(&loop);
1196
1197   // Remove the pointers stored on the stack.
1198   __ bind(loop_statement.break_label());
1199   __ add(esp, Immediate(5 * kPointerSize));
1200
1201   // Exit and decrement the loop depth.
1202   PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1203   __ bind(&exit);
1204   decrement_loop_depth();
1205 }
1206
1207
1208 void FullCodeGenerator::VisitForOfStatement(ForOfStatement* stmt) {
1209   Comment cmnt(masm_, "[ ForOfStatement");
1210   SetStatementPosition(stmt);
1211
1212   Iteration loop_statement(this, stmt);
1213   increment_loop_depth();
1214
1215   // var iterator = iterable[Symbol.iterator]();
1216   VisitForEffect(stmt->assign_iterator());
1217
1218   // Loop entry.
1219   __ bind(loop_statement.continue_label());
1220
1221   // result = iterator.next()
1222   VisitForEffect(stmt->next_result());
1223
1224   // if (result.done) break;
1225   Label result_not_done;
1226   VisitForControl(stmt->result_done(),
1227                   loop_statement.break_label(),
1228                   &result_not_done,
1229                   &result_not_done);
1230   __ bind(&result_not_done);
1231
1232   // each = result.value
1233   VisitForEffect(stmt->assign_each());
1234
1235   // Generate code for the body of the loop.
1236   Visit(stmt->body());
1237
1238   // Check stack before looping.
1239   PrepareForBailoutForId(stmt->BackEdgeId(), NO_REGISTERS);
1240   EmitBackEdgeBookkeeping(stmt, loop_statement.continue_label());
1241   __ jmp(loop_statement.continue_label());
1242
1243   // Exit and decrement the loop depth.
1244   PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1245   __ bind(loop_statement.break_label());
1246   decrement_loop_depth();
1247 }
1248
1249
1250 void FullCodeGenerator::EmitNewClosure(Handle<SharedFunctionInfo> info,
1251                                        bool pretenure) {
1252   // Use the fast case closure allocation code that allocates in new
1253   // space for nested functions that don't need literals cloning. If
1254   // we're running with the --always-opt or the --prepare-always-opt
1255   // flag, we need to use the runtime function so that the new function
1256   // we are creating here gets a chance to have its code optimized and
1257   // doesn't just get a copy of the existing unoptimized code.
1258   if (!FLAG_always_opt &&
1259       !FLAG_prepare_always_opt &&
1260       !pretenure &&
1261       scope()->is_function_scope() &&
1262       info->num_literals() == 0) {
1263     FastNewClosureStub stub(isolate(), info->strict_mode(), info->kind());
1264     __ mov(ebx, Immediate(info));
1265     __ CallStub(&stub);
1266   } else {
1267     __ push(esi);
1268     __ push(Immediate(info));
1269     __ push(Immediate(pretenure
1270                       ? isolate()->factory()->true_value()
1271                       : isolate()->factory()->false_value()));
1272     __ CallRuntime(Runtime::kNewClosure, 3);
1273   }
1274   context()->Plug(eax);
1275 }
1276
1277
1278 void FullCodeGenerator::VisitVariableProxy(VariableProxy* expr) {
1279   Comment cmnt(masm_, "[ VariableProxy");
1280   EmitVariableLoad(expr);
1281 }
1282
1283
1284 void FullCodeGenerator::EmitLoadHomeObject(SuperReference* expr) {
1285   Comment cnmt(masm_, "[ SuperReference ");
1286
1287   __ mov(LoadDescriptor::ReceiverRegister(),
1288          Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
1289
1290   Handle<Symbol> home_object_symbol(isolate()->heap()->home_object_symbol());
1291   __ mov(LoadDescriptor::NameRegister(), home_object_symbol);
1292
1293   if (FLAG_vector_ics) {
1294     __ mov(VectorLoadICDescriptor::SlotRegister(),
1295            Immediate(SmiFromSlot(expr->HomeObjectFeedbackSlot())));
1296     CallLoadIC(NOT_CONTEXTUAL);
1297   } else {
1298     CallLoadIC(NOT_CONTEXTUAL, expr->HomeObjectFeedbackId());
1299   }
1300
1301   __ cmp(eax, isolate()->factory()->undefined_value());
1302   Label done;
1303   __ j(not_equal, &done);
1304   __ CallRuntime(Runtime::kThrowNonMethodError, 0);
1305   __ bind(&done);
1306 }
1307
1308
1309 void FullCodeGenerator::EmitLoadGlobalCheckExtensions(VariableProxy* proxy,
1310                                                       TypeofState typeof_state,
1311                                                       Label* slow) {
1312   Register context = esi;
1313   Register temp = edx;
1314
1315   Scope* s = scope();
1316   while (s != NULL) {
1317     if (s->num_heap_slots() > 0) {
1318       if (s->calls_sloppy_eval()) {
1319         // Check that extension is NULL.
1320         __ cmp(ContextOperand(context, Context::EXTENSION_INDEX),
1321                Immediate(0));
1322         __ j(not_equal, slow);
1323       }
1324       // Load next context in chain.
1325       __ mov(temp, ContextOperand(context, Context::PREVIOUS_INDEX));
1326       // Walk the rest of the chain without clobbering esi.
1327       context = temp;
1328     }
1329     // If no outer scope calls eval, we do not need to check more
1330     // context extensions.  If we have reached an eval scope, we check
1331     // all extensions from this point.
1332     if (!s->outer_scope_calls_sloppy_eval() || s->is_eval_scope()) break;
1333     s = s->outer_scope();
1334   }
1335
1336   if (s != NULL && s->is_eval_scope()) {
1337     // Loop up the context chain.  There is no frame effect so it is
1338     // safe to use raw labels here.
1339     Label next, fast;
1340     if (!context.is(temp)) {
1341       __ mov(temp, context);
1342     }
1343     __ bind(&next);
1344     // Terminate at native context.
1345     __ cmp(FieldOperand(temp, HeapObject::kMapOffset),
1346            Immediate(isolate()->factory()->native_context_map()));
1347     __ j(equal, &fast, Label::kNear);
1348     // Check that extension is NULL.
1349     __ cmp(ContextOperand(temp, Context::EXTENSION_INDEX), Immediate(0));
1350     __ j(not_equal, slow);
1351     // Load next context in chain.
1352     __ mov(temp, ContextOperand(temp, Context::PREVIOUS_INDEX));
1353     __ jmp(&next);
1354     __ bind(&fast);
1355   }
1356
1357   // All extension objects were empty and it is safe to use a global
1358   // load IC call.
1359   __ mov(LoadDescriptor::ReceiverRegister(), GlobalObjectOperand());
1360   __ mov(LoadDescriptor::NameRegister(), proxy->var()->name());
1361   if (FLAG_vector_ics) {
1362     __ mov(VectorLoadICDescriptor::SlotRegister(),
1363            Immediate(SmiFromSlot(proxy->VariableFeedbackSlot())));
1364   }
1365
1366   ContextualMode mode = (typeof_state == INSIDE_TYPEOF)
1367       ? NOT_CONTEXTUAL
1368       : CONTEXTUAL;
1369
1370   CallLoadIC(mode);
1371 }
1372
1373
1374 MemOperand FullCodeGenerator::ContextSlotOperandCheckExtensions(Variable* var,
1375                                                                 Label* slow) {
1376   DCHECK(var->IsContextSlot());
1377   Register context = esi;
1378   Register temp = ebx;
1379
1380   for (Scope* s = scope(); s != var->scope(); s = s->outer_scope()) {
1381     if (s->num_heap_slots() > 0) {
1382       if (s->calls_sloppy_eval()) {
1383         // Check that extension is NULL.
1384         __ cmp(ContextOperand(context, Context::EXTENSION_INDEX),
1385                Immediate(0));
1386         __ j(not_equal, slow);
1387       }
1388       __ mov(temp, ContextOperand(context, Context::PREVIOUS_INDEX));
1389       // Walk the rest of the chain without clobbering esi.
1390       context = temp;
1391     }
1392   }
1393   // Check that last extension is NULL.
1394   __ cmp(ContextOperand(context, Context::EXTENSION_INDEX), Immediate(0));
1395   __ j(not_equal, slow);
1396
1397   // This function is used only for loads, not stores, so it's safe to
1398   // return an esi-based operand (the write barrier cannot be allowed to
1399   // destroy the esi register).
1400   return ContextOperand(context, var->index());
1401 }
1402
1403
1404 void FullCodeGenerator::EmitDynamicLookupFastCase(VariableProxy* proxy,
1405                                                   TypeofState typeof_state,
1406                                                   Label* slow,
1407                                                   Label* done) {
1408   // Generate fast-case code for variables that might be shadowed by
1409   // eval-introduced variables.  Eval is used a lot without
1410   // introducing variables.  In those cases, we do not want to
1411   // perform a runtime call for all variables in the scope
1412   // containing the eval.
1413   Variable* var = proxy->var();
1414   if (var->mode() == DYNAMIC_GLOBAL) {
1415     EmitLoadGlobalCheckExtensions(proxy, typeof_state, slow);
1416     __ jmp(done);
1417   } else if (var->mode() == DYNAMIC_LOCAL) {
1418     Variable* local = var->local_if_not_shadowed();
1419     __ mov(eax, ContextSlotOperandCheckExtensions(local, slow));
1420     if (local->mode() == LET || local->mode() == CONST ||
1421         local->mode() == CONST_LEGACY) {
1422       __ cmp(eax, isolate()->factory()->the_hole_value());
1423       __ j(not_equal, done);
1424       if (local->mode() == CONST_LEGACY) {
1425         __ mov(eax, isolate()->factory()->undefined_value());
1426       } else {  // LET || CONST
1427         __ push(Immediate(var->name()));
1428         __ CallRuntime(Runtime::kThrowReferenceError, 1);
1429       }
1430     }
1431     __ jmp(done);
1432   }
1433 }
1434
1435
1436 void FullCodeGenerator::EmitVariableLoad(VariableProxy* proxy) {
1437   // Record position before possible IC call.
1438   SetSourcePosition(proxy->position());
1439   Variable* var = proxy->var();
1440
1441   // Three cases: global variables, lookup variables, and all other types of
1442   // variables.
1443   switch (var->location()) {
1444     case Variable::UNALLOCATED: {
1445       Comment cmnt(masm_, "[ Global variable");
1446       __ mov(LoadDescriptor::ReceiverRegister(), GlobalObjectOperand());
1447       __ mov(LoadDescriptor::NameRegister(), var->name());
1448       if (FLAG_vector_ics) {
1449         __ mov(VectorLoadICDescriptor::SlotRegister(),
1450                Immediate(SmiFromSlot(proxy->VariableFeedbackSlot())));
1451       }
1452       CallLoadIC(CONTEXTUAL);
1453       context()->Plug(eax);
1454       break;
1455     }
1456
1457     case Variable::PARAMETER:
1458     case Variable::LOCAL:
1459     case Variable::CONTEXT: {
1460       Comment cmnt(masm_, var->IsContextSlot() ? "[ Context variable"
1461                                                : "[ Stack variable");
1462       if (var->binding_needs_init()) {
1463         // var->scope() may be NULL when the proxy is located in eval code and
1464         // refers to a potential outside binding. Currently those bindings are
1465         // always looked up dynamically, i.e. in that case
1466         //     var->location() == LOOKUP.
1467         // always holds.
1468         DCHECK(var->scope() != NULL);
1469
1470         // Check if the binding really needs an initialization check. The check
1471         // can be skipped in the following situation: we have a LET or CONST
1472         // binding in harmony mode, both the Variable and the VariableProxy have
1473         // the same declaration scope (i.e. they are both in global code, in the
1474         // same function or in the same eval code) and the VariableProxy is in
1475         // the source physically located after the initializer of the variable.
1476         //
1477         // We cannot skip any initialization checks for CONST in non-harmony
1478         // mode because const variables may be declared but never initialized:
1479         //   if (false) { const x; }; var y = x;
1480         //
1481         // The condition on the declaration scopes is a conservative check for
1482         // nested functions that access a binding and are called before the
1483         // binding is initialized:
1484         //   function() { f(); let x = 1; function f() { x = 2; } }
1485         //
1486         bool skip_init_check;
1487         if (var->scope()->DeclarationScope() != scope()->DeclarationScope()) {
1488           skip_init_check = false;
1489         } else {
1490           // Check that we always have valid source position.
1491           DCHECK(var->initializer_position() != RelocInfo::kNoPosition);
1492           DCHECK(proxy->position() != RelocInfo::kNoPosition);
1493           skip_init_check = var->mode() != CONST_LEGACY &&
1494               var->initializer_position() < proxy->position();
1495         }
1496
1497         if (!skip_init_check) {
1498           // Let and const need a read barrier.
1499           Label done;
1500           GetVar(eax, var);
1501           __ cmp(eax, isolate()->factory()->the_hole_value());
1502           __ j(not_equal, &done, Label::kNear);
1503           if (var->mode() == LET || var->mode() == CONST) {
1504             // Throw a reference error when using an uninitialized let/const
1505             // binding in harmony mode.
1506             __ push(Immediate(var->name()));
1507             __ CallRuntime(Runtime::kThrowReferenceError, 1);
1508           } else {
1509             // Uninitalized const bindings outside of harmony mode are unholed.
1510             DCHECK(var->mode() == CONST_LEGACY);
1511             __ mov(eax, isolate()->factory()->undefined_value());
1512           }
1513           __ bind(&done);
1514           context()->Plug(eax);
1515           break;
1516         }
1517       }
1518       context()->Plug(var);
1519       break;
1520     }
1521
1522     case Variable::LOOKUP: {
1523       Comment cmnt(masm_, "[ Lookup variable");
1524       Label done, slow;
1525       // Generate code for loading from variables potentially shadowed
1526       // by eval-introduced variables.
1527       EmitDynamicLookupFastCase(proxy, NOT_INSIDE_TYPEOF, &slow, &done);
1528       __ bind(&slow);
1529       __ push(esi);  // Context.
1530       __ push(Immediate(var->name()));
1531       __ CallRuntime(Runtime::kLoadLookupSlot, 2);
1532       __ bind(&done);
1533       context()->Plug(eax);
1534       break;
1535     }
1536   }
1537 }
1538
1539
1540 void FullCodeGenerator::VisitRegExpLiteral(RegExpLiteral* expr) {
1541   Comment cmnt(masm_, "[ RegExpLiteral");
1542   Label materialized;
1543   // Registers will be used as follows:
1544   // edi = JS function.
1545   // ecx = literals array.
1546   // ebx = regexp literal.
1547   // eax = regexp literal clone.
1548   __ mov(edi, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
1549   __ mov(ecx, FieldOperand(edi, JSFunction::kLiteralsOffset));
1550   int literal_offset =
1551       FixedArray::kHeaderSize + expr->literal_index() * kPointerSize;
1552   __ mov(ebx, FieldOperand(ecx, literal_offset));
1553   __ cmp(ebx, isolate()->factory()->undefined_value());
1554   __ j(not_equal, &materialized, Label::kNear);
1555
1556   // Create regexp literal using runtime function
1557   // Result will be in eax.
1558   __ push(ecx);
1559   __ push(Immediate(Smi::FromInt(expr->literal_index())));
1560   __ push(Immediate(expr->pattern()));
1561   __ push(Immediate(expr->flags()));
1562   __ CallRuntime(Runtime::kMaterializeRegExpLiteral, 4);
1563   __ mov(ebx, eax);
1564
1565   __ bind(&materialized);
1566   int size = JSRegExp::kSize + JSRegExp::kInObjectFieldCount * kPointerSize;
1567   Label allocated, runtime_allocate;
1568   __ Allocate(size, eax, ecx, edx, &runtime_allocate, TAG_OBJECT);
1569   __ jmp(&allocated);
1570
1571   __ bind(&runtime_allocate);
1572   __ push(ebx);
1573   __ push(Immediate(Smi::FromInt(size)));
1574   __ CallRuntime(Runtime::kAllocateInNewSpace, 1);
1575   __ pop(ebx);
1576
1577   __ bind(&allocated);
1578   // Copy the content into the newly allocated memory.
1579   // (Unroll copy loop once for better throughput).
1580   for (int i = 0; i < size - kPointerSize; i += 2 * kPointerSize) {
1581     __ mov(edx, FieldOperand(ebx, i));
1582     __ mov(ecx, FieldOperand(ebx, i + kPointerSize));
1583     __ mov(FieldOperand(eax, i), edx);
1584     __ mov(FieldOperand(eax, i + kPointerSize), ecx);
1585   }
1586   if ((size % (2 * kPointerSize)) != 0) {
1587     __ mov(edx, FieldOperand(ebx, size - kPointerSize));
1588     __ mov(FieldOperand(eax, size - kPointerSize), edx);
1589   }
1590   context()->Plug(eax);
1591 }
1592
1593
1594 void FullCodeGenerator::EmitAccessor(Expression* expression) {
1595   if (expression == NULL) {
1596     __ push(Immediate(isolate()->factory()->null_value()));
1597   } else {
1598     VisitForStackValue(expression);
1599   }
1600 }
1601
1602
1603 void FullCodeGenerator::VisitObjectLiteral(ObjectLiteral* expr) {
1604   Comment cmnt(masm_, "[ ObjectLiteral");
1605
1606   expr->BuildConstantProperties(isolate());
1607   Handle<FixedArray> constant_properties = expr->constant_properties();
1608   int flags = expr->fast_elements()
1609       ? ObjectLiteral::kFastElements
1610       : ObjectLiteral::kNoFlags;
1611   flags |= expr->has_function()
1612       ? ObjectLiteral::kHasFunction
1613       : ObjectLiteral::kNoFlags;
1614   int properties_count = constant_properties->length() / 2;
1615   if (expr->may_store_doubles() || expr->depth() > 1 ||
1616       masm()->serializer_enabled() ||
1617       flags != ObjectLiteral::kFastElements ||
1618       properties_count > FastCloneShallowObjectStub::kMaximumClonedProperties) {
1619     __ mov(edi, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
1620     __ push(FieldOperand(edi, JSFunction::kLiteralsOffset));
1621     __ push(Immediate(Smi::FromInt(expr->literal_index())));
1622     __ push(Immediate(constant_properties));
1623     __ push(Immediate(Smi::FromInt(flags)));
1624     __ CallRuntime(Runtime::kCreateObjectLiteral, 4);
1625   } else {
1626     __ mov(edi, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
1627     __ mov(eax, FieldOperand(edi, JSFunction::kLiteralsOffset));
1628     __ mov(ebx, Immediate(Smi::FromInt(expr->literal_index())));
1629     __ mov(ecx, Immediate(constant_properties));
1630     __ mov(edx, Immediate(Smi::FromInt(flags)));
1631     FastCloneShallowObjectStub stub(isolate(), properties_count);
1632     __ CallStub(&stub);
1633   }
1634   PrepareForBailoutForId(expr->CreateLiteralId(), TOS_REG);
1635
1636   // If result_saved is true the result is on top of the stack.  If
1637   // result_saved is false the result is in eax.
1638   bool result_saved = false;
1639
1640   // Mark all computed expressions that are bound to a key that
1641   // is shadowed by a later occurrence of the same key. For the
1642   // marked expressions, no store code is emitted.
1643   expr->CalculateEmitStore(zone());
1644
1645   AccessorTable accessor_table(zone());
1646   for (int i = 0; i < expr->properties()->length(); i++) {
1647     ObjectLiteral::Property* property = expr->properties()->at(i);
1648     if (property->IsCompileTimeValue()) continue;
1649
1650     Literal* key = property->key();
1651     Expression* value = property->value();
1652     if (!result_saved) {
1653       __ push(eax);  // Save result on the stack
1654       result_saved = true;
1655     }
1656     switch (property->kind()) {
1657       case ObjectLiteral::Property::CONSTANT:
1658         UNREACHABLE();
1659       case ObjectLiteral::Property::MATERIALIZED_LITERAL:
1660         DCHECK(!CompileTimeValue::IsCompileTimeValue(value));
1661         // Fall through.
1662       case ObjectLiteral::Property::COMPUTED:
1663         // It is safe to use [[Put]] here because the boilerplate already
1664         // contains computed properties with an uninitialized value.
1665         if (key->value()->IsInternalizedString()) {
1666           if (property->emit_store()) {
1667             VisitForAccumulatorValue(value);
1668             DCHECK(StoreDescriptor::ValueRegister().is(eax));
1669             __ mov(StoreDescriptor::NameRegister(), Immediate(key->value()));
1670             __ mov(StoreDescriptor::ReceiverRegister(), Operand(esp, 0));
1671             CallStoreIC(key->LiteralFeedbackId());
1672             PrepareForBailoutForId(key->id(), NO_REGISTERS);
1673           } else {
1674             VisitForEffect(value);
1675           }
1676           break;
1677         }
1678         __ push(Operand(esp, 0));  // Duplicate receiver.
1679         VisitForStackValue(key);
1680         VisitForStackValue(value);
1681         if (property->emit_store()) {
1682           __ push(Immediate(Smi::FromInt(SLOPPY)));  // Strict mode
1683           __ CallRuntime(Runtime::kSetProperty, 4);
1684         } else {
1685           __ Drop(3);
1686         }
1687         break;
1688       case ObjectLiteral::Property::PROTOTYPE:
1689         __ push(Operand(esp, 0));  // Duplicate receiver.
1690         VisitForStackValue(value);
1691         if (property->emit_store()) {
1692           __ CallRuntime(Runtime::kInternalSetPrototype, 2);
1693         } else {
1694           __ Drop(2);
1695         }
1696         break;
1697       case ObjectLiteral::Property::GETTER:
1698         accessor_table.lookup(key)->second->getter = value;
1699         break;
1700       case ObjectLiteral::Property::SETTER:
1701         accessor_table.lookup(key)->second->setter = value;
1702         break;
1703     }
1704   }
1705
1706   // Emit code to define accessors, using only a single call to the runtime for
1707   // each pair of corresponding getters and setters.
1708   for (AccessorTable::Iterator it = accessor_table.begin();
1709        it != accessor_table.end();
1710        ++it) {
1711     __ push(Operand(esp, 0));  // Duplicate receiver.
1712     VisitForStackValue(it->first);
1713     EmitAccessor(it->second->getter);
1714     EmitAccessor(it->second->setter);
1715     __ push(Immediate(Smi::FromInt(NONE)));
1716     __ CallRuntime(Runtime::kDefineAccessorPropertyUnchecked, 5);
1717   }
1718
1719   if (expr->has_function()) {
1720     DCHECK(result_saved);
1721     __ push(Operand(esp, 0));
1722     __ CallRuntime(Runtime::kToFastProperties, 1);
1723   }
1724
1725   if (result_saved) {
1726     context()->PlugTOS();
1727   } else {
1728     context()->Plug(eax);
1729   }
1730 }
1731
1732
1733 void FullCodeGenerator::VisitArrayLiteral(ArrayLiteral* expr) {
1734   Comment cmnt(masm_, "[ ArrayLiteral");
1735
1736   expr->BuildConstantElements(isolate());
1737   int flags = expr->depth() == 1
1738       ? ArrayLiteral::kShallowElements
1739       : ArrayLiteral::kNoFlags;
1740
1741   ZoneList<Expression*>* subexprs = expr->values();
1742   int length = subexprs->length();
1743   Handle<FixedArray> constant_elements = expr->constant_elements();
1744   DCHECK_EQ(2, constant_elements->length());
1745   ElementsKind constant_elements_kind =
1746       static_cast<ElementsKind>(Smi::cast(constant_elements->get(0))->value());
1747   bool has_constant_fast_elements =
1748       IsFastObjectElementsKind(constant_elements_kind);
1749   Handle<FixedArrayBase> constant_elements_values(
1750       FixedArrayBase::cast(constant_elements->get(1)));
1751
1752   AllocationSiteMode allocation_site_mode = TRACK_ALLOCATION_SITE;
1753   if (has_constant_fast_elements && !FLAG_allocation_site_pretenuring) {
1754     // If the only customer of allocation sites is transitioning, then
1755     // we can turn it off if we don't have anywhere else to transition to.
1756     allocation_site_mode = DONT_TRACK_ALLOCATION_SITE;
1757   }
1758
1759   if (expr->depth() > 1 || length > JSObject::kInitialMaxFastElementArray) {
1760     __ mov(ebx, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
1761     __ push(FieldOperand(ebx, JSFunction::kLiteralsOffset));
1762     __ push(Immediate(Smi::FromInt(expr->literal_index())));
1763     __ push(Immediate(constant_elements));
1764     __ push(Immediate(Smi::FromInt(flags)));
1765     __ CallRuntime(Runtime::kCreateArrayLiteral, 4);
1766   } else {
1767     __ mov(ebx, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
1768     __ mov(eax, FieldOperand(ebx, JSFunction::kLiteralsOffset));
1769     __ mov(ebx, Immediate(Smi::FromInt(expr->literal_index())));
1770     __ mov(ecx, Immediate(constant_elements));
1771     FastCloneShallowArrayStub stub(isolate(), allocation_site_mode);
1772     __ CallStub(&stub);
1773   }
1774
1775   bool result_saved = false;  // Is the result saved to the stack?
1776
1777   // Emit code to evaluate all the non-constant subexpressions and to store
1778   // them into the newly cloned array.
1779   for (int i = 0; i < length; i++) {
1780     Expression* subexpr = subexprs->at(i);
1781     // If the subexpression is a literal or a simple materialized literal it
1782     // is already set in the cloned array.
1783     if (CompileTimeValue::IsCompileTimeValue(subexpr)) continue;
1784
1785     if (!result_saved) {
1786       __ push(eax);  // array literal.
1787       __ push(Immediate(Smi::FromInt(expr->literal_index())));
1788       result_saved = true;
1789     }
1790     VisitForAccumulatorValue(subexpr);
1791
1792     if (IsFastObjectElementsKind(constant_elements_kind)) {
1793       // Fast-case array literal with ElementsKind of FAST_*_ELEMENTS, they
1794       // cannot transition and don't need to call the runtime stub.
1795       int offset = FixedArray::kHeaderSize + (i * kPointerSize);
1796       __ mov(ebx, Operand(esp, kPointerSize));  // Copy of array literal.
1797       __ mov(ebx, FieldOperand(ebx, JSObject::kElementsOffset));
1798       // Store the subexpression value in the array's elements.
1799       __ mov(FieldOperand(ebx, offset), result_register());
1800       // Update the write barrier for the array store.
1801       __ RecordWriteField(ebx, offset, result_register(), ecx,
1802                           kDontSaveFPRegs,
1803                           EMIT_REMEMBERED_SET,
1804                           INLINE_SMI_CHECK);
1805     } else {
1806       // Store the subexpression value in the array's elements.
1807       __ mov(ecx, Immediate(Smi::FromInt(i)));
1808       StoreArrayLiteralElementStub stub(isolate());
1809       __ CallStub(&stub);
1810     }
1811
1812     PrepareForBailoutForId(expr->GetIdForElement(i), NO_REGISTERS);
1813   }
1814
1815   if (result_saved) {
1816     __ add(esp, Immediate(kPointerSize));  // literal index
1817     context()->PlugTOS();
1818   } else {
1819     context()->Plug(eax);
1820   }
1821 }
1822
1823
1824 void FullCodeGenerator::VisitAssignment(Assignment* expr) {
1825   DCHECK(expr->target()->IsValidReferenceExpression());
1826
1827   Comment cmnt(masm_, "[ Assignment");
1828
1829   Property* property = expr->target()->AsProperty();
1830   LhsKind assign_type = GetAssignType(property);
1831
1832   // Evaluate LHS expression.
1833   switch (assign_type) {
1834     case VARIABLE:
1835       // Nothing to do here.
1836       break;
1837     case NAMED_SUPER_PROPERTY:
1838       VisitForStackValue(property->obj()->AsSuperReference()->this_var());
1839       EmitLoadHomeObject(property->obj()->AsSuperReference());
1840       __ push(result_register());
1841       if (expr->is_compound()) {
1842         __ push(MemOperand(esp, kPointerSize));
1843         __ push(result_register());
1844       }
1845       break;
1846     case NAMED_PROPERTY:
1847       if (expr->is_compound()) {
1848         // We need the receiver both on the stack and in the register.
1849         VisitForStackValue(property->obj());
1850         __ mov(LoadDescriptor::ReceiverRegister(), Operand(esp, 0));
1851       } else {
1852         VisitForStackValue(property->obj());
1853       }
1854       break;
1855     case KEYED_SUPER_PROPERTY:
1856       VisitForStackValue(property->obj()->AsSuperReference()->this_var());
1857       EmitLoadHomeObject(property->obj()->AsSuperReference());
1858       __ Push(result_register());
1859       VisitForAccumulatorValue(property->key());
1860       __ Push(result_register());
1861       if (expr->is_compound()) {
1862         __ push(MemOperand(esp, 2 * kPointerSize));
1863         __ push(MemOperand(esp, 2 * kPointerSize));
1864         __ push(result_register());
1865       }
1866       break;
1867     case KEYED_PROPERTY: {
1868       if (expr->is_compound()) {
1869         VisitForStackValue(property->obj());
1870         VisitForStackValue(property->key());
1871         __ mov(LoadDescriptor::ReceiverRegister(), Operand(esp, kPointerSize));
1872         __ mov(LoadDescriptor::NameRegister(), Operand(esp, 0));
1873       } else {
1874         VisitForStackValue(property->obj());
1875         VisitForStackValue(property->key());
1876       }
1877       break;
1878     }
1879   }
1880
1881   // For compound assignments we need another deoptimization point after the
1882   // variable/property load.
1883   if (expr->is_compound()) {
1884     AccumulatorValueContext result_context(this);
1885     { AccumulatorValueContext left_operand_context(this);
1886       switch (assign_type) {
1887         case VARIABLE:
1888           EmitVariableLoad(expr->target()->AsVariableProxy());
1889           PrepareForBailout(expr->target(), TOS_REG);
1890           break;
1891         case NAMED_SUPER_PROPERTY:
1892           EmitNamedSuperPropertyLoad(property);
1893           PrepareForBailoutForId(property->LoadId(), TOS_REG);
1894           break;
1895         case NAMED_PROPERTY:
1896           EmitNamedPropertyLoad(property);
1897           PrepareForBailoutForId(property->LoadId(), TOS_REG);
1898           break;
1899         case KEYED_SUPER_PROPERTY:
1900           EmitKeyedSuperPropertyLoad(property);
1901           PrepareForBailoutForId(property->LoadId(), TOS_REG);
1902           break;
1903         case KEYED_PROPERTY:
1904           EmitKeyedPropertyLoad(property);
1905           PrepareForBailoutForId(property->LoadId(), TOS_REG);
1906           break;
1907       }
1908     }
1909
1910     Token::Value op = expr->binary_op();
1911     __ push(eax);  // Left operand goes on the stack.
1912     VisitForAccumulatorValue(expr->value());
1913
1914     OverwriteMode mode = expr->value()->ResultOverwriteAllowed()
1915         ? OVERWRITE_RIGHT
1916         : NO_OVERWRITE;
1917     SetSourcePosition(expr->position() + 1);
1918     if (ShouldInlineSmiCase(op)) {
1919       EmitInlineSmiBinaryOp(expr->binary_operation(),
1920                             op,
1921                             mode,
1922                             expr->target(),
1923                             expr->value());
1924     } else {
1925       EmitBinaryOp(expr->binary_operation(), op, mode);
1926     }
1927
1928     // Deoptimization point in case the binary operation may have side effects.
1929     PrepareForBailout(expr->binary_operation(), TOS_REG);
1930   } else {
1931     VisitForAccumulatorValue(expr->value());
1932   }
1933
1934   // Record source position before possible IC call.
1935   SetSourcePosition(expr->position());
1936
1937   // Store the value.
1938   switch (assign_type) {
1939     case VARIABLE:
1940       EmitVariableAssignment(expr->target()->AsVariableProxy()->var(),
1941                              expr->op());
1942       PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
1943       context()->Plug(eax);
1944       break;
1945     case NAMED_PROPERTY:
1946       EmitNamedPropertyAssignment(expr);
1947       break;
1948     case NAMED_SUPER_PROPERTY:
1949       EmitNamedSuperPropertyStore(property);
1950       context()->Plug(result_register());
1951       break;
1952     case KEYED_SUPER_PROPERTY:
1953       EmitKeyedSuperPropertyStore(property);
1954       context()->Plug(result_register());
1955       break;
1956     case KEYED_PROPERTY:
1957       EmitKeyedPropertyAssignment(expr);
1958       break;
1959   }
1960 }
1961
1962
1963 void FullCodeGenerator::VisitYield(Yield* expr) {
1964   Comment cmnt(masm_, "[ Yield");
1965   // Evaluate yielded value first; the initial iterator definition depends on
1966   // this.  It stays on the stack while we update the iterator.
1967   VisitForStackValue(expr->expression());
1968
1969   switch (expr->yield_kind()) {
1970     case Yield::kSuspend:
1971       // Pop value from top-of-stack slot; box result into result register.
1972       EmitCreateIteratorResult(false);
1973       __ push(result_register());
1974       // Fall through.
1975     case Yield::kInitial: {
1976       Label suspend, continuation, post_runtime, resume;
1977
1978       __ jmp(&suspend);
1979
1980       __ bind(&continuation);
1981       __ jmp(&resume);
1982
1983       __ bind(&suspend);
1984       VisitForAccumulatorValue(expr->generator_object());
1985       DCHECK(continuation.pos() > 0 && Smi::IsValid(continuation.pos()));
1986       __ mov(FieldOperand(eax, JSGeneratorObject::kContinuationOffset),
1987              Immediate(Smi::FromInt(continuation.pos())));
1988       __ mov(FieldOperand(eax, JSGeneratorObject::kContextOffset), esi);
1989       __ mov(ecx, esi);
1990       __ RecordWriteField(eax, JSGeneratorObject::kContextOffset, ecx, edx,
1991                           kDontSaveFPRegs);
1992       __ lea(ebx, Operand(ebp, StandardFrameConstants::kExpressionsOffset));
1993       __ cmp(esp, ebx);
1994       __ j(equal, &post_runtime);
1995       __ push(eax);  // generator object
1996       __ CallRuntime(Runtime::kSuspendJSGeneratorObject, 1);
1997       __ mov(context_register(),
1998              Operand(ebp, StandardFrameConstants::kContextOffset));
1999       __ bind(&post_runtime);
2000       __ pop(result_register());
2001       EmitReturnSequence();
2002
2003       __ bind(&resume);
2004       context()->Plug(result_register());
2005       break;
2006     }
2007
2008     case Yield::kFinal: {
2009       VisitForAccumulatorValue(expr->generator_object());
2010       __ mov(FieldOperand(result_register(),
2011                           JSGeneratorObject::kContinuationOffset),
2012              Immediate(Smi::FromInt(JSGeneratorObject::kGeneratorClosed)));
2013       // Pop value from top-of-stack slot, box result into result register.
2014       EmitCreateIteratorResult(true);
2015       EmitUnwindBeforeReturn();
2016       EmitReturnSequence();
2017       break;
2018     }
2019
2020     case Yield::kDelegating: {
2021       VisitForStackValue(expr->generator_object());
2022
2023       // Initial stack layout is as follows:
2024       // [sp + 1 * kPointerSize] iter
2025       // [sp + 0 * kPointerSize] g
2026
2027       Label l_catch, l_try, l_suspend, l_continuation, l_resume;
2028       Label l_next, l_call, l_loop;
2029       Register load_receiver = LoadDescriptor::ReceiverRegister();
2030       Register load_name = LoadDescriptor::NameRegister();
2031
2032       // Initial send value is undefined.
2033       __ mov(eax, isolate()->factory()->undefined_value());
2034       __ jmp(&l_next);
2035
2036       // catch (e) { receiver = iter; f = 'throw'; arg = e; goto l_call; }
2037       __ bind(&l_catch);
2038       handler_table()->set(expr->index(), Smi::FromInt(l_catch.pos()));
2039       __ mov(load_name, isolate()->factory()->throw_string());  // "throw"
2040       __ push(load_name);                                       // "throw"
2041       __ push(Operand(esp, 2 * kPointerSize));                  // iter
2042       __ push(eax);                                             // exception
2043       __ jmp(&l_call);
2044
2045       // try { received = %yield result }
2046       // Shuffle the received result above a try handler and yield it without
2047       // re-boxing.
2048       __ bind(&l_try);
2049       __ pop(eax);                                       // result
2050       __ PushTryHandler(StackHandler::CATCH, expr->index());
2051       const int handler_size = StackHandlerConstants::kSize;
2052       __ push(eax);                                      // result
2053       __ jmp(&l_suspend);
2054       __ bind(&l_continuation);
2055       __ jmp(&l_resume);
2056       __ bind(&l_suspend);
2057       const int generator_object_depth = kPointerSize + handler_size;
2058       __ mov(eax, Operand(esp, generator_object_depth));
2059       __ push(eax);                                      // g
2060       DCHECK(l_continuation.pos() > 0 && Smi::IsValid(l_continuation.pos()));
2061       __ mov(FieldOperand(eax, JSGeneratorObject::kContinuationOffset),
2062              Immediate(Smi::FromInt(l_continuation.pos())));
2063       __ mov(FieldOperand(eax, JSGeneratorObject::kContextOffset), esi);
2064       __ mov(ecx, esi);
2065       __ RecordWriteField(eax, JSGeneratorObject::kContextOffset, ecx, edx,
2066                           kDontSaveFPRegs);
2067       __ CallRuntime(Runtime::kSuspendJSGeneratorObject, 1);
2068       __ mov(context_register(),
2069              Operand(ebp, StandardFrameConstants::kContextOffset));
2070       __ pop(eax);                                       // result
2071       EmitReturnSequence();
2072       __ bind(&l_resume);                                // received in eax
2073       __ PopTryHandler();
2074
2075       // receiver = iter; f = iter.next; arg = received;
2076       __ bind(&l_next);
2077
2078       __ mov(load_name, isolate()->factory()->next_string());
2079       __ push(load_name);                           // "next"
2080       __ push(Operand(esp, 2 * kPointerSize));      // iter
2081       __ push(eax);                                 // received
2082
2083       // result = receiver[f](arg);
2084       __ bind(&l_call);
2085       __ mov(load_receiver, Operand(esp, kPointerSize));
2086       if (FLAG_vector_ics) {
2087         __ mov(VectorLoadICDescriptor::SlotRegister(),
2088                Immediate(SmiFromSlot(expr->KeyedLoadFeedbackSlot())));
2089       }
2090       Handle<Code> ic = CodeFactory::KeyedLoadIC(isolate()).code();
2091       CallIC(ic, TypeFeedbackId::None());
2092       __ mov(edi, eax);
2093       __ mov(Operand(esp, 2 * kPointerSize), edi);
2094       CallFunctionStub stub(isolate(), 1, CALL_AS_METHOD);
2095       __ CallStub(&stub);
2096
2097       __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
2098       __ Drop(1);  // The function is still on the stack; drop it.
2099
2100       // if (!result.done) goto l_try;
2101       __ bind(&l_loop);
2102       __ push(eax);                                      // save result
2103       __ Move(load_receiver, eax);                       // result
2104       __ mov(load_name,
2105              isolate()->factory()->done_string());       // "done"
2106       if (FLAG_vector_ics) {
2107         __ mov(VectorLoadICDescriptor::SlotRegister(),
2108                Immediate(SmiFromSlot(expr->DoneFeedbackSlot())));
2109       }
2110       CallLoadIC(NOT_CONTEXTUAL);                        // result.done in eax
2111       Handle<Code> bool_ic = ToBooleanStub::GetUninitialized(isolate());
2112       CallIC(bool_ic);
2113       __ test(eax, eax);
2114       __ j(zero, &l_try);
2115
2116       // result.value
2117       __ pop(load_receiver);                              // result
2118       __ mov(load_name,
2119              isolate()->factory()->value_string());       // "value"
2120       if (FLAG_vector_ics) {
2121         __ mov(VectorLoadICDescriptor::SlotRegister(),
2122                Immediate(SmiFromSlot(expr->ValueFeedbackSlot())));
2123       }
2124       CallLoadIC(NOT_CONTEXTUAL);                         // result.value in eax
2125       context()->DropAndPlug(2, eax);                     // drop iter and g
2126       break;
2127     }
2128   }
2129 }
2130
2131
2132 void FullCodeGenerator::EmitGeneratorResume(Expression *generator,
2133     Expression *value,
2134     JSGeneratorObject::ResumeMode resume_mode) {
2135   // The value stays in eax, and is ultimately read by the resumed generator, as
2136   // if CallRuntime(Runtime::kSuspendJSGeneratorObject) returned it. Or it
2137   // is read to throw the value when the resumed generator is already closed.
2138   // ebx will hold the generator object until the activation has been resumed.
2139   VisitForStackValue(generator);
2140   VisitForAccumulatorValue(value);
2141   __ pop(ebx);
2142
2143   // Check generator state.
2144   Label wrong_state, closed_state, done;
2145   STATIC_ASSERT(JSGeneratorObject::kGeneratorExecuting < 0);
2146   STATIC_ASSERT(JSGeneratorObject::kGeneratorClosed == 0);
2147   __ cmp(FieldOperand(ebx, JSGeneratorObject::kContinuationOffset),
2148          Immediate(Smi::FromInt(0)));
2149   __ j(equal, &closed_state);
2150   __ j(less, &wrong_state);
2151
2152   // Load suspended function and context.
2153   __ mov(esi, FieldOperand(ebx, JSGeneratorObject::kContextOffset));
2154   __ mov(edi, FieldOperand(ebx, JSGeneratorObject::kFunctionOffset));
2155
2156   // Push receiver.
2157   __ push(FieldOperand(ebx, JSGeneratorObject::kReceiverOffset));
2158
2159   // Push holes for arguments to generator function.
2160   __ mov(edx, FieldOperand(edi, JSFunction::kSharedFunctionInfoOffset));
2161   __ mov(edx,
2162          FieldOperand(edx, SharedFunctionInfo::kFormalParameterCountOffset));
2163   __ mov(ecx, isolate()->factory()->the_hole_value());
2164   Label push_argument_holes, push_frame;
2165   __ bind(&push_argument_holes);
2166   __ sub(edx, Immediate(Smi::FromInt(1)));
2167   __ j(carry, &push_frame);
2168   __ push(ecx);
2169   __ jmp(&push_argument_holes);
2170
2171   // Enter a new JavaScript frame, and initialize its slots as they were when
2172   // the generator was suspended.
2173   Label resume_frame;
2174   __ bind(&push_frame);
2175   __ call(&resume_frame);
2176   __ jmp(&done);
2177   __ bind(&resume_frame);
2178   __ push(ebp);  // Caller's frame pointer.
2179   __ mov(ebp, esp);
2180   __ push(esi);  // Callee's context.
2181   __ push(edi);  // Callee's JS Function.
2182
2183   // Load the operand stack size.
2184   __ mov(edx, FieldOperand(ebx, JSGeneratorObject::kOperandStackOffset));
2185   __ mov(edx, FieldOperand(edx, FixedArray::kLengthOffset));
2186   __ SmiUntag(edx);
2187
2188   // If we are sending a value and there is no operand stack, we can jump back
2189   // in directly.
2190   if (resume_mode == JSGeneratorObject::NEXT) {
2191     Label slow_resume;
2192     __ cmp(edx, Immediate(0));
2193     __ j(not_zero, &slow_resume);
2194     __ mov(edx, FieldOperand(edi, JSFunction::kCodeEntryOffset));
2195     __ mov(ecx, FieldOperand(ebx, JSGeneratorObject::kContinuationOffset));
2196     __ SmiUntag(ecx);
2197     __ add(edx, ecx);
2198     __ mov(FieldOperand(ebx, JSGeneratorObject::kContinuationOffset),
2199            Immediate(Smi::FromInt(JSGeneratorObject::kGeneratorExecuting)));
2200     __ jmp(edx);
2201     __ bind(&slow_resume);
2202   }
2203
2204   // Otherwise, we push holes for the operand stack and call the runtime to fix
2205   // up the stack and the handlers.
2206   Label push_operand_holes, call_resume;
2207   __ bind(&push_operand_holes);
2208   __ sub(edx, Immediate(1));
2209   __ j(carry, &call_resume);
2210   __ push(ecx);
2211   __ jmp(&push_operand_holes);
2212   __ bind(&call_resume);
2213   __ push(ebx);
2214   __ push(result_register());
2215   __ Push(Smi::FromInt(resume_mode));
2216   __ CallRuntime(Runtime::kResumeJSGeneratorObject, 3);
2217   // Not reached: the runtime call returns elsewhere.
2218   __ Abort(kGeneratorFailedToResume);
2219
2220   // Reach here when generator is closed.
2221   __ bind(&closed_state);
2222   if (resume_mode == JSGeneratorObject::NEXT) {
2223     // Return completed iterator result when generator is closed.
2224     __ push(Immediate(isolate()->factory()->undefined_value()));
2225     // Pop value from top-of-stack slot; box result into result register.
2226     EmitCreateIteratorResult(true);
2227   } else {
2228     // Throw the provided value.
2229     __ push(eax);
2230     __ CallRuntime(Runtime::kThrow, 1);
2231   }
2232   __ jmp(&done);
2233
2234   // Throw error if we attempt to operate on a running generator.
2235   __ bind(&wrong_state);
2236   __ push(ebx);
2237   __ CallRuntime(Runtime::kThrowGeneratorStateError, 1);
2238
2239   __ bind(&done);
2240   context()->Plug(result_register());
2241 }
2242
2243
2244 void FullCodeGenerator::EmitCreateIteratorResult(bool done) {
2245   Label gc_required;
2246   Label allocated;
2247
2248   const int instance_size = 5 * kPointerSize;
2249   DCHECK_EQ(isolate()->native_context()->iterator_result_map()->instance_size(),
2250             instance_size);
2251
2252   __ Allocate(instance_size, eax, ecx, edx, &gc_required, TAG_OBJECT);
2253   __ jmp(&allocated);
2254
2255   __ bind(&gc_required);
2256   __ Push(Smi::FromInt(instance_size));
2257   __ CallRuntime(Runtime::kAllocateInNewSpace, 1);
2258   __ mov(context_register(),
2259          Operand(ebp, StandardFrameConstants::kContextOffset));
2260
2261   __ bind(&allocated);
2262   __ mov(ebx, Operand(esi, Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX)));
2263   __ mov(ebx, FieldOperand(ebx, GlobalObject::kNativeContextOffset));
2264   __ mov(ebx, ContextOperand(ebx, Context::ITERATOR_RESULT_MAP_INDEX));
2265   __ pop(ecx);
2266   __ mov(edx, isolate()->factory()->ToBoolean(done));
2267   __ mov(FieldOperand(eax, HeapObject::kMapOffset), ebx);
2268   __ mov(FieldOperand(eax, JSObject::kPropertiesOffset),
2269          isolate()->factory()->empty_fixed_array());
2270   __ mov(FieldOperand(eax, JSObject::kElementsOffset),
2271          isolate()->factory()->empty_fixed_array());
2272   __ mov(FieldOperand(eax, JSGeneratorObject::kResultValuePropertyOffset), ecx);
2273   __ mov(FieldOperand(eax, JSGeneratorObject::kResultDonePropertyOffset), edx);
2274
2275   // Only the value field needs a write barrier, as the other values are in the
2276   // root set.
2277   __ RecordWriteField(eax, JSGeneratorObject::kResultValuePropertyOffset,
2278                       ecx, edx, kDontSaveFPRegs);
2279 }
2280
2281
2282 void FullCodeGenerator::EmitNamedPropertyLoad(Property* prop) {
2283   SetSourcePosition(prop->position());
2284   Literal* key = prop->key()->AsLiteral();
2285   DCHECK(!key->value()->IsSmi());
2286   DCHECK(!prop->IsSuperAccess());
2287
2288   __ mov(LoadDescriptor::NameRegister(), Immediate(key->value()));
2289   if (FLAG_vector_ics) {
2290     __ mov(VectorLoadICDescriptor::SlotRegister(),
2291            Immediate(SmiFromSlot(prop->PropertyFeedbackSlot())));
2292     CallLoadIC(NOT_CONTEXTUAL);
2293   } else {
2294     CallLoadIC(NOT_CONTEXTUAL, prop->PropertyFeedbackId());
2295   }
2296 }
2297
2298
2299 void FullCodeGenerator::EmitNamedSuperPropertyLoad(Property* prop) {
2300   // Stack: receiver, home_object.
2301   SetSourcePosition(prop->position());
2302   Literal* key = prop->key()->AsLiteral();
2303   DCHECK(!key->value()->IsSmi());
2304   DCHECK(prop->IsSuperAccess());
2305
2306   __ push(Immediate(key->value()));
2307   __ CallRuntime(Runtime::kLoadFromSuper, 3);
2308 }
2309
2310
2311 void FullCodeGenerator::EmitKeyedPropertyLoad(Property* prop) {
2312   SetSourcePosition(prop->position());
2313   Handle<Code> ic = CodeFactory::KeyedLoadIC(isolate()).code();
2314   if (FLAG_vector_ics) {
2315     __ mov(VectorLoadICDescriptor::SlotRegister(),
2316            Immediate(SmiFromSlot(prop->PropertyFeedbackSlot())));
2317     CallIC(ic);
2318   } else {
2319     CallIC(ic, prop->PropertyFeedbackId());
2320   }
2321 }
2322
2323
2324 void FullCodeGenerator::EmitKeyedSuperPropertyLoad(Property* prop) {
2325   // Stack: receiver, home_object, key.
2326   SetSourcePosition(prop->position());
2327
2328   __ CallRuntime(Runtime::kLoadKeyedFromSuper, 3);
2329 }
2330
2331
2332 void FullCodeGenerator::EmitInlineSmiBinaryOp(BinaryOperation* expr,
2333                                               Token::Value op,
2334                                               OverwriteMode mode,
2335                                               Expression* left,
2336                                               Expression* right) {
2337   // Do combined smi check of the operands. Left operand is on the
2338   // stack. Right operand is in eax.
2339   Label smi_case, done, stub_call;
2340   __ pop(edx);
2341   __ mov(ecx, eax);
2342   __ or_(eax, edx);
2343   JumpPatchSite patch_site(masm_);
2344   patch_site.EmitJumpIfSmi(eax, &smi_case, Label::kNear);
2345
2346   __ bind(&stub_call);
2347   __ mov(eax, ecx);
2348   Handle<Code> code = CodeFactory::BinaryOpIC(isolate(), op, mode).code();
2349   CallIC(code, expr->BinaryOperationFeedbackId());
2350   patch_site.EmitPatchInfo();
2351   __ jmp(&done, Label::kNear);
2352
2353   // Smi case.
2354   __ bind(&smi_case);
2355   __ mov(eax, edx);  // Copy left operand in case of a stub call.
2356
2357   switch (op) {
2358     case Token::SAR:
2359       __ SmiUntag(ecx);
2360       __ sar_cl(eax);  // No checks of result necessary
2361       __ and_(eax, Immediate(~kSmiTagMask));
2362       break;
2363     case Token::SHL: {
2364       Label result_ok;
2365       __ SmiUntag(eax);
2366       __ SmiUntag(ecx);
2367       __ shl_cl(eax);
2368       // Check that the *signed* result fits in a smi.
2369       __ cmp(eax, 0xc0000000);
2370       __ j(positive, &result_ok);
2371       __ SmiTag(ecx);
2372       __ jmp(&stub_call);
2373       __ bind(&result_ok);
2374       __ SmiTag(eax);
2375       break;
2376     }
2377     case Token::SHR: {
2378       Label result_ok;
2379       __ SmiUntag(eax);
2380       __ SmiUntag(ecx);
2381       __ shr_cl(eax);
2382       __ test(eax, Immediate(0xc0000000));
2383       __ j(zero, &result_ok);
2384       __ SmiTag(ecx);
2385       __ jmp(&stub_call);
2386       __ bind(&result_ok);
2387       __ SmiTag(eax);
2388       break;
2389     }
2390     case Token::ADD:
2391       __ add(eax, ecx);
2392       __ j(overflow, &stub_call);
2393       break;
2394     case Token::SUB:
2395       __ sub(eax, ecx);
2396       __ j(overflow, &stub_call);
2397       break;
2398     case Token::MUL: {
2399       __ SmiUntag(eax);
2400       __ imul(eax, ecx);
2401       __ j(overflow, &stub_call);
2402       __ test(eax, eax);
2403       __ j(not_zero, &done, Label::kNear);
2404       __ mov(ebx, edx);
2405       __ or_(ebx, ecx);
2406       __ j(negative, &stub_call);
2407       break;
2408     }
2409     case Token::BIT_OR:
2410       __ or_(eax, ecx);
2411       break;
2412     case Token::BIT_AND:
2413       __ and_(eax, ecx);
2414       break;
2415     case Token::BIT_XOR:
2416       __ xor_(eax, ecx);
2417       break;
2418     default:
2419       UNREACHABLE();
2420   }
2421
2422   __ bind(&done);
2423   context()->Plug(eax);
2424 }
2425
2426
2427 void FullCodeGenerator::EmitClassDefineProperties(ClassLiteral* lit) {
2428   // Constructor is in eax.
2429   DCHECK(lit != NULL);
2430   __ push(eax);
2431
2432   // No access check is needed here since the constructor is created by the
2433   // class literal.
2434   Register scratch = ebx;
2435   __ mov(scratch, FieldOperand(eax, JSFunction::kPrototypeOrInitialMapOffset));
2436   __ Push(scratch);
2437
2438   for (int i = 0; i < lit->properties()->length(); i++) {
2439     ObjectLiteral::Property* property = lit->properties()->at(i);
2440     Literal* key = property->key()->AsLiteral();
2441     Expression* value = property->value();
2442     DCHECK(key != NULL);
2443
2444     if (property->is_static()) {
2445       __ push(Operand(esp, kPointerSize));  // constructor
2446     } else {
2447       __ push(Operand(esp, 0));  // prototype
2448     }
2449     VisitForStackValue(key);
2450     VisitForStackValue(value);
2451
2452     switch (property->kind()) {
2453       case ObjectLiteral::Property::CONSTANT:
2454       case ObjectLiteral::Property::MATERIALIZED_LITERAL:
2455       case ObjectLiteral::Property::COMPUTED:
2456       case ObjectLiteral::Property::PROTOTYPE:
2457         __ CallRuntime(Runtime::kDefineClassMethod, 3);
2458         break;
2459
2460       case ObjectLiteral::Property::GETTER:
2461         __ CallRuntime(Runtime::kDefineClassGetter, 3);
2462         break;
2463
2464       case ObjectLiteral::Property::SETTER:
2465         __ CallRuntime(Runtime::kDefineClassSetter, 3);
2466         break;
2467
2468       default:
2469         UNREACHABLE();
2470     }
2471   }
2472
2473   // prototype
2474   __ CallRuntime(Runtime::kToFastProperties, 1);
2475
2476   // constructor
2477   __ CallRuntime(Runtime::kToFastProperties, 1);
2478 }
2479
2480
2481 void FullCodeGenerator::EmitBinaryOp(BinaryOperation* expr,
2482                                      Token::Value op,
2483                                      OverwriteMode mode) {
2484   __ pop(edx);
2485   Handle<Code> code = CodeFactory::BinaryOpIC(isolate(), op, mode).code();
2486   JumpPatchSite patch_site(masm_);    // unbound, signals no inlined smi code.
2487   CallIC(code, expr->BinaryOperationFeedbackId());
2488   patch_site.EmitPatchInfo();
2489   context()->Plug(eax);
2490 }
2491
2492
2493 void FullCodeGenerator::EmitAssignment(Expression* expr) {
2494   DCHECK(expr->IsValidReferenceExpression());
2495
2496   Property* prop = expr->AsProperty();
2497   LhsKind assign_type = GetAssignType(prop);
2498
2499   switch (assign_type) {
2500     case VARIABLE: {
2501       Variable* var = expr->AsVariableProxy()->var();
2502       EffectContext context(this);
2503       EmitVariableAssignment(var, Token::ASSIGN);
2504       break;
2505     }
2506     case NAMED_PROPERTY: {
2507       __ push(eax);  // Preserve value.
2508       VisitForAccumulatorValue(prop->obj());
2509       __ Move(StoreDescriptor::ReceiverRegister(), eax);
2510       __ pop(StoreDescriptor::ValueRegister());  // Restore value.
2511       __ mov(StoreDescriptor::NameRegister(),
2512              prop->key()->AsLiteral()->value());
2513       CallStoreIC();
2514       break;
2515     }
2516     case NAMED_SUPER_PROPERTY: {
2517       __ push(eax);
2518       VisitForStackValue(prop->obj()->AsSuperReference()->this_var());
2519       EmitLoadHomeObject(prop->obj()->AsSuperReference());
2520       // stack: value, this; eax: home_object
2521       Register scratch = ecx;
2522       Register scratch2 = edx;
2523       __ mov(scratch, result_register());               // home_object
2524       __ mov(eax, MemOperand(esp, kPointerSize));       // value
2525       __ mov(scratch2, MemOperand(esp, 0));             // this
2526       __ mov(MemOperand(esp, kPointerSize), scratch2);  // this
2527       __ mov(MemOperand(esp, 0), scratch);              // home_object
2528       // stack: this, home_object. eax: value
2529       EmitNamedSuperPropertyStore(prop);
2530       break;
2531     }
2532     case KEYED_SUPER_PROPERTY: {
2533       __ push(eax);
2534       VisitForStackValue(prop->obj()->AsSuperReference()->this_var());
2535       EmitLoadHomeObject(prop->obj()->AsSuperReference());
2536       __ push(result_register());
2537       VisitForAccumulatorValue(prop->key());
2538       Register scratch = ecx;
2539       Register scratch2 = edx;
2540       __ mov(scratch2, MemOperand(esp, 2 * kPointerSize));  // value
2541       // stack: value, this, home_object; eax: key, edx: value
2542       __ mov(scratch, MemOperand(esp, kPointerSize));  // this
2543       __ mov(MemOperand(esp, 2 * kPointerSize), scratch);
2544       __ mov(scratch, MemOperand(esp, 0));  // home_object
2545       __ mov(MemOperand(esp, kPointerSize), scratch);
2546       __ mov(MemOperand(esp, 0), eax);
2547       __ mov(eax, scratch2);
2548       // stack: this, home_object, key; eax: value.
2549       EmitKeyedSuperPropertyStore(prop);
2550       break;
2551     }
2552     case KEYED_PROPERTY: {
2553       __ push(eax);  // Preserve value.
2554       VisitForStackValue(prop->obj());
2555       VisitForAccumulatorValue(prop->key());
2556       __ Move(StoreDescriptor::NameRegister(), eax);
2557       __ pop(StoreDescriptor::ReceiverRegister());  // Receiver.
2558       __ pop(StoreDescriptor::ValueRegister());     // Restore value.
2559       Handle<Code> ic =
2560           CodeFactory::KeyedStoreIC(isolate(), strict_mode()).code();
2561       CallIC(ic);
2562       break;
2563     }
2564   }
2565   context()->Plug(eax);
2566 }
2567
2568
2569 void FullCodeGenerator::EmitStoreToStackLocalOrContextSlot(
2570     Variable* var, MemOperand location) {
2571   __ mov(location, eax);
2572   if (var->IsContextSlot()) {
2573     __ mov(edx, eax);
2574     int offset = Context::SlotOffset(var->index());
2575     __ RecordWriteContextSlot(ecx, offset, edx, ebx, kDontSaveFPRegs);
2576   }
2577 }
2578
2579
2580 void FullCodeGenerator::EmitVariableAssignment(Variable* var,
2581                                                Token::Value op) {
2582   if (var->IsUnallocated()) {
2583     // Global var, const, or let.
2584     __ mov(StoreDescriptor::NameRegister(), var->name());
2585     __ mov(StoreDescriptor::ReceiverRegister(), GlobalObjectOperand());
2586     CallStoreIC();
2587
2588   } else if (op == Token::INIT_CONST_LEGACY) {
2589     // Const initializers need a write barrier.
2590     DCHECK(!var->IsParameter());  // No const parameters.
2591     if (var->IsLookupSlot()) {
2592       __ push(eax);
2593       __ push(esi);
2594       __ push(Immediate(var->name()));
2595       __ CallRuntime(Runtime::kInitializeLegacyConstLookupSlot, 3);
2596     } else {
2597       DCHECK(var->IsStackLocal() || var->IsContextSlot());
2598       Label skip;
2599       MemOperand location = VarOperand(var, ecx);
2600       __ mov(edx, location);
2601       __ cmp(edx, isolate()->factory()->the_hole_value());
2602       __ j(not_equal, &skip, Label::kNear);
2603       EmitStoreToStackLocalOrContextSlot(var, location);
2604       __ bind(&skip);
2605     }
2606
2607   } else if (var->mode() == LET && op != Token::INIT_LET) {
2608     // Non-initializing assignment to let variable needs a write barrier.
2609     DCHECK(!var->IsLookupSlot());
2610     DCHECK(var->IsStackAllocated() || var->IsContextSlot());
2611     Label assign;
2612     MemOperand location = VarOperand(var, ecx);
2613     __ mov(edx, location);
2614     __ cmp(edx, isolate()->factory()->the_hole_value());
2615     __ j(not_equal, &assign, Label::kNear);
2616     __ push(Immediate(var->name()));
2617     __ CallRuntime(Runtime::kThrowReferenceError, 1);
2618     __ bind(&assign);
2619     EmitStoreToStackLocalOrContextSlot(var, location);
2620
2621   } else if (!var->is_const_mode() || op == Token::INIT_CONST) {
2622     if (var->IsLookupSlot()) {
2623       // Assignment to var.
2624       __ push(eax);  // Value.
2625       __ push(esi);  // Context.
2626       __ push(Immediate(var->name()));
2627       __ push(Immediate(Smi::FromInt(strict_mode())));
2628       __ CallRuntime(Runtime::kStoreLookupSlot, 4);
2629     } else {
2630       // Assignment to var or initializing assignment to let/const in harmony
2631       // mode.
2632       DCHECK(var->IsStackAllocated() || var->IsContextSlot());
2633       MemOperand location = VarOperand(var, ecx);
2634       if (generate_debug_code_ && op == Token::INIT_LET) {
2635         // Check for an uninitialized let binding.
2636         __ mov(edx, location);
2637         __ cmp(edx, isolate()->factory()->the_hole_value());
2638         __ Check(equal, kLetBindingReInitialization);
2639       }
2640       EmitStoreToStackLocalOrContextSlot(var, location);
2641     }
2642   }
2643   // Non-initializing assignments to consts are ignored.
2644 }
2645
2646
2647 void FullCodeGenerator::EmitNamedPropertyAssignment(Assignment* expr) {
2648   // Assignment to a property, using a named store IC.
2649   // eax    : value
2650   // esp[0] : receiver
2651
2652   Property* prop = expr->target()->AsProperty();
2653   DCHECK(prop != NULL);
2654   DCHECK(prop->key()->IsLiteral());
2655
2656   // Record source code position before IC call.
2657   SetSourcePosition(expr->position());
2658   __ mov(StoreDescriptor::NameRegister(), prop->key()->AsLiteral()->value());
2659   __ pop(StoreDescriptor::ReceiverRegister());
2660   CallStoreIC(expr->AssignmentFeedbackId());
2661   PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
2662   context()->Plug(eax);
2663 }
2664
2665
2666 void FullCodeGenerator::EmitNamedSuperPropertyStore(Property* prop) {
2667   // Assignment to named property of super.
2668   // eax : value
2669   // stack : receiver ('this'), home_object
2670   DCHECK(prop != NULL);
2671   Literal* key = prop->key()->AsLiteral();
2672   DCHECK(key != NULL);
2673
2674   __ push(Immediate(key->value()));
2675   __ push(eax);
2676   __ CallRuntime((strict_mode() == STRICT ? Runtime::kStoreToSuper_Strict
2677                                           : Runtime::kStoreToSuper_Sloppy),
2678                  4);
2679 }
2680
2681
2682 void FullCodeGenerator::EmitKeyedSuperPropertyStore(Property* prop) {
2683   // Assignment to named property of super.
2684   // eax : value
2685   // stack : receiver ('this'), home_object, key
2686
2687   __ push(eax);
2688   __ CallRuntime((strict_mode() == STRICT ? Runtime::kStoreKeyedToSuper_Strict
2689                                           : Runtime::kStoreKeyedToSuper_Sloppy),
2690                  4);
2691 }
2692
2693
2694 void FullCodeGenerator::EmitKeyedPropertyAssignment(Assignment* expr) {
2695   // Assignment to a property, using a keyed store IC.
2696   // eax               : value
2697   // esp[0]            : key
2698   // esp[kPointerSize] : receiver
2699
2700   __ pop(StoreDescriptor::NameRegister());  // Key.
2701   __ pop(StoreDescriptor::ReceiverRegister());
2702   DCHECK(StoreDescriptor::ValueRegister().is(eax));
2703   // Record source code position before IC call.
2704   SetSourcePosition(expr->position());
2705   Handle<Code> ic = CodeFactory::KeyedStoreIC(isolate(), strict_mode()).code();
2706   CallIC(ic, expr->AssignmentFeedbackId());
2707
2708   PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
2709   context()->Plug(eax);
2710 }
2711
2712
2713 void FullCodeGenerator::VisitProperty(Property* expr) {
2714   Comment cmnt(masm_, "[ Property");
2715   Expression* key = expr->key();
2716
2717   if (key->IsPropertyName()) {
2718     if (!expr->IsSuperAccess()) {
2719       VisitForAccumulatorValue(expr->obj());
2720       __ Move(LoadDescriptor::ReceiverRegister(), result_register());
2721       EmitNamedPropertyLoad(expr);
2722     } else {
2723       VisitForStackValue(expr->obj()->AsSuperReference()->this_var());
2724       EmitLoadHomeObject(expr->obj()->AsSuperReference());
2725       __ push(result_register());
2726       EmitNamedSuperPropertyLoad(expr);
2727     }
2728     PrepareForBailoutForId(expr->LoadId(), TOS_REG);
2729     context()->Plug(eax);
2730   } else {
2731     if (!expr->IsSuperAccess()) {
2732       VisitForStackValue(expr->obj());
2733       VisitForAccumulatorValue(expr->key());
2734       __ pop(LoadDescriptor::ReceiverRegister());                  // Object.
2735       __ Move(LoadDescriptor::NameRegister(), result_register());  // Key.
2736       EmitKeyedPropertyLoad(expr);
2737     } else {
2738       VisitForStackValue(expr->obj()->AsSuperReference()->this_var());
2739       EmitLoadHomeObject(expr->obj()->AsSuperReference());
2740       __ push(result_register());
2741       VisitForStackValue(expr->key());
2742       EmitKeyedSuperPropertyLoad(expr);
2743     }
2744     context()->Plug(eax);
2745   }
2746 }
2747
2748
2749 void FullCodeGenerator::CallIC(Handle<Code> code,
2750                                TypeFeedbackId ast_id) {
2751   ic_total_count_++;
2752   __ call(code, RelocInfo::CODE_TARGET, ast_id);
2753 }
2754
2755
2756 // Code common for calls using the IC.
2757 void FullCodeGenerator::EmitCallWithLoadIC(Call* expr) {
2758   Expression* callee = expr->expression();
2759
2760   CallICState::CallType call_type =
2761       callee->IsVariableProxy() ? CallICState::FUNCTION : CallICState::METHOD;
2762   // Get the target function.
2763   if (call_type == CallICState::FUNCTION) {
2764     { StackValueContext context(this);
2765       EmitVariableLoad(callee->AsVariableProxy());
2766       PrepareForBailout(callee, NO_REGISTERS);
2767     }
2768     // Push undefined as receiver. This is patched in the method prologue if it
2769     // is a sloppy mode method.
2770     __ push(Immediate(isolate()->factory()->undefined_value()));
2771   } else {
2772     // Load the function from the receiver.
2773     DCHECK(callee->IsProperty());
2774     DCHECK(!callee->AsProperty()->IsSuperAccess());
2775     __ mov(LoadDescriptor::ReceiverRegister(), Operand(esp, 0));
2776     EmitNamedPropertyLoad(callee->AsProperty());
2777     PrepareForBailoutForId(callee->AsProperty()->LoadId(), TOS_REG);
2778     // Push the target function under the receiver.
2779     __ push(Operand(esp, 0));
2780     __ mov(Operand(esp, kPointerSize), eax);
2781   }
2782
2783   EmitCall(expr, call_type);
2784 }
2785
2786
2787 void FullCodeGenerator::EmitSuperCallWithLoadIC(Call* expr) {
2788   Expression* callee = expr->expression();
2789   DCHECK(callee->IsProperty());
2790   Property* prop = callee->AsProperty();
2791   DCHECK(prop->IsSuperAccess());
2792
2793   SetSourcePosition(prop->position());
2794   Literal* key = prop->key()->AsLiteral();
2795   DCHECK(!key->value()->IsSmi());
2796   // Load the function from the receiver.
2797   SuperReference* super_ref = callee->AsProperty()->obj()->AsSuperReference();
2798   EmitLoadHomeObject(super_ref);
2799   __ push(eax);
2800   VisitForAccumulatorValue(super_ref->this_var());
2801   __ push(eax);
2802   __ push(eax);
2803   __ push(Operand(esp, kPointerSize * 2));
2804   __ push(Immediate(key->value()));
2805   // Stack here:
2806   //  - home_object
2807   //  - this (receiver)
2808   //  - this (receiver) <-- LoadFromSuper will pop here and below.
2809   //  - home_object
2810   //  - key
2811   __ CallRuntime(Runtime::kLoadFromSuper, 3);
2812
2813   // Replace home_object with target function.
2814   __ mov(Operand(esp, kPointerSize), eax);
2815
2816   // Stack here:
2817   // - target function
2818   // - this (receiver)
2819   EmitCall(expr, CallICState::METHOD);
2820 }
2821
2822
2823 // Code common for calls using the IC.
2824 void FullCodeGenerator::EmitKeyedCallWithLoadIC(Call* expr,
2825                                                 Expression* key) {
2826   // Load the key.
2827   VisitForAccumulatorValue(key);
2828
2829   Expression* callee = expr->expression();
2830
2831   // Load the function from the receiver.
2832   DCHECK(callee->IsProperty());
2833   __ mov(LoadDescriptor::ReceiverRegister(), Operand(esp, 0));
2834   __ mov(LoadDescriptor::NameRegister(), eax);
2835   EmitKeyedPropertyLoad(callee->AsProperty());
2836   PrepareForBailoutForId(callee->AsProperty()->LoadId(), TOS_REG);
2837
2838   // Push the target function under the receiver.
2839   __ push(Operand(esp, 0));
2840   __ mov(Operand(esp, kPointerSize), eax);
2841
2842   EmitCall(expr, CallICState::METHOD);
2843 }
2844
2845
2846 void FullCodeGenerator::EmitKeyedSuperCallWithLoadIC(Call* expr) {
2847   Expression* callee = expr->expression();
2848   DCHECK(callee->IsProperty());
2849   Property* prop = callee->AsProperty();
2850   DCHECK(prop->IsSuperAccess());
2851
2852   SetSourcePosition(prop->position());
2853   // Load the function from the receiver.
2854   SuperReference* super_ref = callee->AsProperty()->obj()->AsSuperReference();
2855   EmitLoadHomeObject(super_ref);
2856   __ push(eax);
2857   VisitForAccumulatorValue(super_ref->this_var());
2858   __ push(eax);
2859   __ push(eax);
2860   __ push(Operand(esp, kPointerSize * 2));
2861   VisitForStackValue(prop->key());
2862   // Stack here:
2863   //  - home_object
2864   //  - this (receiver)
2865   //  - this (receiver) <-- LoadKeyedFromSuper will pop here and below.
2866   //  - home_object
2867   //  - key
2868   __ CallRuntime(Runtime::kLoadKeyedFromSuper, 3);
2869
2870   // Replace home_object with target function.
2871   __ mov(Operand(esp, kPointerSize), eax);
2872
2873   // Stack here:
2874   // - target function
2875   // - this (receiver)
2876   EmitCall(expr, CallICState::METHOD);
2877 }
2878
2879
2880 void FullCodeGenerator::EmitCall(Call* expr, CallICState::CallType call_type) {
2881   // Load the arguments.
2882   ZoneList<Expression*>* args = expr->arguments();
2883   int arg_count = args->length();
2884   { PreservePositionScope scope(masm()->positions_recorder());
2885     for (int i = 0; i < arg_count; i++) {
2886       VisitForStackValue(args->at(i));
2887     }
2888   }
2889
2890   // Record source position of the IC call.
2891   SetSourcePosition(expr->position());
2892   Handle<Code> ic = CallIC::initialize_stub(
2893       isolate(), arg_count, call_type);
2894   __ Move(edx, Immediate(SmiFromSlot(expr->CallFeedbackSlot())));
2895   __ mov(edi, Operand(esp, (arg_count + 1) * kPointerSize));
2896   // Don't assign a type feedback id to the IC, since type feedback is provided
2897   // by the vector above.
2898   CallIC(ic);
2899
2900   RecordJSReturnSite(expr);
2901
2902   // Restore context register.
2903   __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
2904
2905   context()->DropAndPlug(1, eax);
2906 }
2907
2908
2909 void FullCodeGenerator::EmitResolvePossiblyDirectEval(int arg_count) {
2910   // Push copy of the first argument or undefined if it doesn't exist.
2911   if (arg_count > 0) {
2912     __ push(Operand(esp, arg_count * kPointerSize));
2913   } else {
2914     __ push(Immediate(isolate()->factory()->undefined_value()));
2915   }
2916
2917   // Push the enclosing function.
2918   __ push(Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
2919   // Push the receiver of the enclosing function.
2920   __ push(Operand(ebp, (2 + info_->scope()->num_parameters()) * kPointerSize));
2921   // Push the language mode.
2922   __ push(Immediate(Smi::FromInt(strict_mode())));
2923
2924   // Push the start position of the scope the calls resides in.
2925   __ push(Immediate(Smi::FromInt(scope()->start_position())));
2926
2927   // Do the runtime call.
2928   __ CallRuntime(Runtime::kResolvePossiblyDirectEval, 6);
2929 }
2930
2931
2932 void FullCodeGenerator::EmitLoadSuperConstructor(SuperReference* super_ref) {
2933   DCHECK(super_ref != NULL);
2934   __ push(Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
2935   __ CallRuntime(Runtime::kGetPrototype, 1);
2936 }
2937
2938
2939 void FullCodeGenerator::VisitCall(Call* expr) {
2940 #ifdef DEBUG
2941   // We want to verify that RecordJSReturnSite gets called on all paths
2942   // through this function.  Avoid early returns.
2943   expr->return_is_recorded_ = false;
2944 #endif
2945
2946   Comment cmnt(masm_, "[ Call");
2947   Expression* callee = expr->expression();
2948   Call::CallType call_type = expr->GetCallType(isolate());
2949
2950   if (call_type == Call::POSSIBLY_EVAL_CALL) {
2951     // In a call to eval, we first call RuntimeHidden_ResolvePossiblyDirectEval
2952     // to resolve the function we need to call and the receiver of the call.
2953     // Then we call the resolved function using the given arguments.
2954     ZoneList<Expression*>* args = expr->arguments();
2955     int arg_count = args->length();
2956     { PreservePositionScope pos_scope(masm()->positions_recorder());
2957       VisitForStackValue(callee);
2958       // Reserved receiver slot.
2959       __ push(Immediate(isolate()->factory()->undefined_value()));
2960       // Push the arguments.
2961       for (int i = 0; i < arg_count; i++) {
2962         VisitForStackValue(args->at(i));
2963       }
2964
2965       // Push a copy of the function (found below the arguments) and
2966       // resolve eval.
2967       __ push(Operand(esp, (arg_count + 1) * kPointerSize));
2968       EmitResolvePossiblyDirectEval(arg_count);
2969
2970       // The runtime call returns a pair of values in eax (function) and
2971       // edx (receiver). Touch up the stack with the right values.
2972       __ mov(Operand(esp, (arg_count + 0) * kPointerSize), edx);
2973       __ mov(Operand(esp, (arg_count + 1) * kPointerSize), eax);
2974
2975       PrepareForBailoutForId(expr->EvalOrLookupId(), NO_REGISTERS);
2976     }
2977     // Record source position for debugger.
2978     SetSourcePosition(expr->position());
2979     CallFunctionStub stub(isolate(), arg_count, NO_CALL_FUNCTION_FLAGS);
2980     __ mov(edi, Operand(esp, (arg_count + 1) * kPointerSize));
2981     __ CallStub(&stub);
2982     RecordJSReturnSite(expr);
2983     // Restore context register.
2984     __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
2985     context()->DropAndPlug(1, eax);
2986
2987   } else if (call_type == Call::GLOBAL_CALL) {
2988     EmitCallWithLoadIC(expr);
2989
2990   } else if (call_type == Call::LOOKUP_SLOT_CALL) {
2991     // Call to a lookup slot (dynamically introduced variable).
2992     VariableProxy* proxy = callee->AsVariableProxy();
2993     Label slow, done;
2994     { PreservePositionScope scope(masm()->positions_recorder());
2995       // Generate code for loading from variables potentially shadowed by
2996       // eval-introduced variables.
2997       EmitDynamicLookupFastCase(proxy, NOT_INSIDE_TYPEOF, &slow, &done);
2998     }
2999     __ bind(&slow);
3000     // Call the runtime to find the function to call (returned in eax) and
3001     // the object holding it (returned in edx).
3002     __ push(context_register());
3003     __ push(Immediate(proxy->name()));
3004     __ CallRuntime(Runtime::kLoadLookupSlot, 2);
3005     __ push(eax);  // Function.
3006     __ push(edx);  // Receiver.
3007     PrepareForBailoutForId(expr->EvalOrLookupId(), NO_REGISTERS);
3008
3009     // If fast case code has been generated, emit code to push the function
3010     // and receiver and have the slow path jump around this code.
3011     if (done.is_linked()) {
3012       Label call;
3013       __ jmp(&call, Label::kNear);
3014       __ bind(&done);
3015       // Push function.
3016       __ push(eax);
3017       // The receiver is implicitly the global receiver. Indicate this by
3018       // passing the hole to the call function stub.
3019       __ push(Immediate(isolate()->factory()->undefined_value()));
3020       __ bind(&call);
3021     }
3022
3023     // The receiver is either the global receiver or an object found by
3024     // LoadContextSlot.
3025     EmitCall(expr);
3026
3027   } else if (call_type == Call::PROPERTY_CALL) {
3028     Property* property = callee->AsProperty();
3029     bool is_named_call = property->key()->IsPropertyName();
3030     if (property->IsSuperAccess()) {
3031       if (is_named_call) {
3032         EmitSuperCallWithLoadIC(expr);
3033       } else {
3034         EmitKeyedSuperCallWithLoadIC(expr);
3035       }
3036     } else {
3037       {
3038         PreservePositionScope scope(masm()->positions_recorder());
3039         VisitForStackValue(property->obj());
3040       }
3041       if (is_named_call) {
3042         EmitCallWithLoadIC(expr);
3043       } else {
3044         EmitKeyedCallWithLoadIC(expr, property->key());
3045       }
3046     }
3047   } else if (call_type == Call::SUPER_CALL) {
3048     SuperReference* super_ref = callee->AsSuperReference();
3049     EmitLoadSuperConstructor(super_ref);
3050     __ push(result_register());
3051     VisitForStackValue(super_ref->this_var());
3052     EmitCall(expr, CallICState::METHOD);
3053   } else {
3054     DCHECK(call_type == Call::OTHER_CALL);
3055     // Call to an arbitrary expression not handled specially above.
3056     { PreservePositionScope scope(masm()->positions_recorder());
3057       VisitForStackValue(callee);
3058     }
3059     __ push(Immediate(isolate()->factory()->undefined_value()));
3060     // Emit function call.
3061     EmitCall(expr);
3062   }
3063
3064 #ifdef DEBUG
3065   // RecordJSReturnSite should have been called.
3066   DCHECK(expr->return_is_recorded_);
3067 #endif
3068 }
3069
3070
3071 void FullCodeGenerator::VisitCallNew(CallNew* expr) {
3072   Comment cmnt(masm_, "[ CallNew");
3073   // According to ECMA-262, section 11.2.2, page 44, the function
3074   // expression in new calls must be evaluated before the
3075   // arguments.
3076
3077   // Push constructor on the stack.  If it's not a function it's used as
3078   // receiver for CALL_NON_FUNCTION, otherwise the value on the stack is
3079   // ignored.
3080   if (expr->expression()->IsSuperReference()) {
3081     EmitLoadSuperConstructor(expr->expression()->AsSuperReference());
3082     __ push(result_register());
3083   } else {
3084     VisitForStackValue(expr->expression());
3085   }
3086
3087   // Push the arguments ("left-to-right") on the stack.
3088   ZoneList<Expression*>* args = expr->arguments();
3089   int arg_count = args->length();
3090   for (int i = 0; i < arg_count; i++) {
3091     VisitForStackValue(args->at(i));
3092   }
3093
3094   // Call the construct call builtin that handles allocation and
3095   // constructor invocation.
3096   SetSourcePosition(expr->position());
3097
3098   // Load function and argument count into edi and eax.
3099   __ Move(eax, Immediate(arg_count));
3100   __ mov(edi, Operand(esp, arg_count * kPointerSize));
3101
3102   // Record call targets in unoptimized code.
3103   if (FLAG_pretenuring_call_new) {
3104     EnsureSlotContainsAllocationSite(expr->AllocationSiteFeedbackSlot());
3105     DCHECK(expr->AllocationSiteFeedbackSlot().ToInt() ==
3106            expr->CallNewFeedbackSlot().ToInt() + 1);
3107   }
3108
3109   __ LoadHeapObject(ebx, FeedbackVector());
3110   __ mov(edx, Immediate(SmiFromSlot(expr->CallNewFeedbackSlot())));
3111
3112   CallConstructStub stub(isolate(), RECORD_CONSTRUCTOR_TARGET);
3113   __ call(stub.GetCode(), RelocInfo::CONSTRUCT_CALL);
3114   PrepareForBailoutForId(expr->ReturnId(), TOS_REG);
3115   context()->Plug(eax);
3116 }
3117
3118
3119 void FullCodeGenerator::EmitIsSmi(CallRuntime* expr) {
3120   ZoneList<Expression*>* args = expr->arguments();
3121   DCHECK(args->length() == 1);
3122
3123   VisitForAccumulatorValue(args->at(0));
3124
3125   Label materialize_true, materialize_false;
3126   Label* if_true = NULL;
3127   Label* if_false = NULL;
3128   Label* fall_through = NULL;
3129   context()->PrepareTest(&materialize_true, &materialize_false,
3130                          &if_true, &if_false, &fall_through);
3131
3132   PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3133   __ test(eax, Immediate(kSmiTagMask));
3134   Split(zero, if_true, if_false, fall_through);
3135
3136   context()->Plug(if_true, if_false);
3137 }
3138
3139
3140 void FullCodeGenerator::EmitIsNonNegativeSmi(CallRuntime* expr) {
3141   ZoneList<Expression*>* args = expr->arguments();
3142   DCHECK(args->length() == 1);
3143
3144   VisitForAccumulatorValue(args->at(0));
3145
3146   Label materialize_true, materialize_false;
3147   Label* if_true = NULL;
3148   Label* if_false = NULL;
3149   Label* fall_through = NULL;
3150   context()->PrepareTest(&materialize_true, &materialize_false,
3151                          &if_true, &if_false, &fall_through);
3152
3153   PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3154   __ test(eax, Immediate(kSmiTagMask | 0x80000000));
3155   Split(zero, if_true, if_false, fall_through);
3156
3157   context()->Plug(if_true, if_false);
3158 }
3159
3160
3161 void FullCodeGenerator::EmitIsObject(CallRuntime* expr) {
3162   ZoneList<Expression*>* args = expr->arguments();
3163   DCHECK(args->length() == 1);
3164
3165   VisitForAccumulatorValue(args->at(0));
3166
3167   Label materialize_true, materialize_false;
3168   Label* if_true = NULL;
3169   Label* if_false = NULL;
3170   Label* fall_through = NULL;
3171   context()->PrepareTest(&materialize_true, &materialize_false,
3172                          &if_true, &if_false, &fall_through);
3173
3174   __ JumpIfSmi(eax, if_false);
3175   __ cmp(eax, isolate()->factory()->null_value());
3176   __ j(equal, if_true);
3177   __ mov(ebx, FieldOperand(eax, HeapObject::kMapOffset));
3178   // Undetectable objects behave like undefined when tested with typeof.
3179   __ movzx_b(ecx, FieldOperand(ebx, Map::kBitFieldOffset));
3180   __ test(ecx, Immediate(1 << Map::kIsUndetectable));
3181   __ j(not_zero, if_false);
3182   __ movzx_b(ecx, FieldOperand(ebx, Map::kInstanceTypeOffset));
3183   __ cmp(ecx, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE);
3184   __ j(below, if_false);
3185   __ cmp(ecx, LAST_NONCALLABLE_SPEC_OBJECT_TYPE);
3186   PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3187   Split(below_equal, if_true, if_false, fall_through);
3188
3189   context()->Plug(if_true, if_false);
3190 }
3191
3192
3193 void FullCodeGenerator::EmitIsSpecObject(CallRuntime* expr) {
3194   ZoneList<Expression*>* args = expr->arguments();
3195   DCHECK(args->length() == 1);
3196
3197   VisitForAccumulatorValue(args->at(0));
3198
3199   Label materialize_true, materialize_false;
3200   Label* if_true = NULL;
3201   Label* if_false = NULL;
3202   Label* fall_through = NULL;
3203   context()->PrepareTest(&materialize_true, &materialize_false,
3204                          &if_true, &if_false, &fall_through);
3205
3206   __ JumpIfSmi(eax, if_false);
3207   __ CmpObjectType(eax, FIRST_SPEC_OBJECT_TYPE, ebx);
3208   PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3209   Split(above_equal, if_true, if_false, fall_through);
3210
3211   context()->Plug(if_true, if_false);
3212 }
3213
3214
3215 void FullCodeGenerator::EmitIsUndetectableObject(CallRuntime* expr) {
3216   ZoneList<Expression*>* args = expr->arguments();
3217   DCHECK(args->length() == 1);
3218
3219   VisitForAccumulatorValue(args->at(0));
3220
3221   Label materialize_true, materialize_false;
3222   Label* if_true = NULL;
3223   Label* if_false = NULL;
3224   Label* fall_through = NULL;
3225   context()->PrepareTest(&materialize_true, &materialize_false,
3226                          &if_true, &if_false, &fall_through);
3227
3228   __ JumpIfSmi(eax, if_false);
3229   __ mov(ebx, FieldOperand(eax, HeapObject::kMapOffset));
3230   __ movzx_b(ebx, FieldOperand(ebx, Map::kBitFieldOffset));
3231   __ test(ebx, Immediate(1 << Map::kIsUndetectable));
3232   PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3233   Split(not_zero, if_true, if_false, fall_through);
3234
3235   context()->Plug(if_true, if_false);
3236 }
3237
3238
3239 void FullCodeGenerator::EmitIsStringWrapperSafeForDefaultValueOf(
3240     CallRuntime* expr) {
3241   ZoneList<Expression*>* args = expr->arguments();
3242   DCHECK(args->length() == 1);
3243
3244   VisitForAccumulatorValue(args->at(0));
3245
3246   Label materialize_true, materialize_false, skip_lookup;
3247   Label* if_true = NULL;
3248   Label* if_false = NULL;
3249   Label* fall_through = NULL;
3250   context()->PrepareTest(&materialize_true, &materialize_false,
3251                          &if_true, &if_false, &fall_through);
3252
3253   __ AssertNotSmi(eax);
3254
3255   // Check whether this map has already been checked to be safe for default
3256   // valueOf.
3257   __ mov(ebx, FieldOperand(eax, HeapObject::kMapOffset));
3258   __ test_b(FieldOperand(ebx, Map::kBitField2Offset),
3259             1 << Map::kStringWrapperSafeForDefaultValueOf);
3260   __ j(not_zero, &skip_lookup);
3261
3262   // Check for fast case object. Return false for slow case objects.
3263   __ mov(ecx, FieldOperand(eax, JSObject::kPropertiesOffset));
3264   __ mov(ecx, FieldOperand(ecx, HeapObject::kMapOffset));
3265   __ cmp(ecx, isolate()->factory()->hash_table_map());
3266   __ j(equal, if_false);
3267
3268   // Look for valueOf string in the descriptor array, and indicate false if
3269   // found. Since we omit an enumeration index check, if it is added via a
3270   // transition that shares its descriptor array, this is a false positive.
3271   Label entry, loop, done;
3272
3273   // Skip loop if no descriptors are valid.
3274   __ NumberOfOwnDescriptors(ecx, ebx);
3275   __ cmp(ecx, 0);
3276   __ j(equal, &done);
3277
3278   __ LoadInstanceDescriptors(ebx, ebx);
3279   // ebx: descriptor array.
3280   // ecx: valid entries in the descriptor array.
3281   // Calculate the end of the descriptor array.
3282   STATIC_ASSERT(kSmiTag == 0);
3283   STATIC_ASSERT(kSmiTagSize == 1);
3284   STATIC_ASSERT(kPointerSize == 4);
3285   __ imul(ecx, ecx, DescriptorArray::kDescriptorSize);
3286   __ lea(ecx, Operand(ebx, ecx, times_4, DescriptorArray::kFirstOffset));
3287   // Calculate location of the first key name.
3288   __ add(ebx, Immediate(DescriptorArray::kFirstOffset));
3289   // Loop through all the keys in the descriptor array. If one of these is the
3290   // internalized string "valueOf" the result is false.
3291   __ jmp(&entry);
3292   __ bind(&loop);
3293   __ mov(edx, FieldOperand(ebx, 0));
3294   __ cmp(edx, isolate()->factory()->value_of_string());
3295   __ j(equal, if_false);
3296   __ add(ebx, Immediate(DescriptorArray::kDescriptorSize * kPointerSize));
3297   __ bind(&entry);
3298   __ cmp(ebx, ecx);
3299   __ j(not_equal, &loop);
3300
3301   __ bind(&done);
3302
3303   // Reload map as register ebx was used as temporary above.
3304   __ mov(ebx, FieldOperand(eax, HeapObject::kMapOffset));
3305
3306   // Set the bit in the map to indicate that there is no local valueOf field.
3307   __ or_(FieldOperand(ebx, Map::kBitField2Offset),
3308          Immediate(1 << Map::kStringWrapperSafeForDefaultValueOf));
3309
3310   __ bind(&skip_lookup);
3311
3312   // If a valueOf property is not found on the object check that its
3313   // prototype is the un-modified String prototype. If not result is false.
3314   __ mov(ecx, FieldOperand(ebx, Map::kPrototypeOffset));
3315   __ JumpIfSmi(ecx, if_false);
3316   __ mov(ecx, FieldOperand(ecx, HeapObject::kMapOffset));
3317   __ mov(edx, Operand(esi, Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX)));
3318   __ mov(edx,
3319          FieldOperand(edx, GlobalObject::kNativeContextOffset));
3320   __ cmp(ecx,
3321          ContextOperand(edx,
3322                         Context::STRING_FUNCTION_PROTOTYPE_MAP_INDEX));
3323   PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3324   Split(equal, if_true, if_false, fall_through);
3325
3326   context()->Plug(if_true, if_false);
3327 }
3328
3329
3330 void FullCodeGenerator::EmitIsFunction(CallRuntime* expr) {
3331   ZoneList<Expression*>* args = expr->arguments();
3332   DCHECK(args->length() == 1);
3333
3334   VisitForAccumulatorValue(args->at(0));
3335
3336   Label materialize_true, materialize_false;
3337   Label* if_true = NULL;
3338   Label* if_false = NULL;
3339   Label* fall_through = NULL;
3340   context()->PrepareTest(&materialize_true, &materialize_false,
3341                          &if_true, &if_false, &fall_through);
3342
3343   __ JumpIfSmi(eax, if_false);
3344   __ CmpObjectType(eax, JS_FUNCTION_TYPE, ebx);
3345   PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3346   Split(equal, if_true, if_false, fall_through);
3347
3348   context()->Plug(if_true, if_false);
3349 }
3350
3351
3352 void FullCodeGenerator::EmitIsMinusZero(CallRuntime* expr) {
3353   ZoneList<Expression*>* args = expr->arguments();
3354   DCHECK(args->length() == 1);
3355
3356   VisitForAccumulatorValue(args->at(0));
3357
3358   Label materialize_true, materialize_false;
3359   Label* if_true = NULL;
3360   Label* if_false = NULL;
3361   Label* fall_through = NULL;
3362   context()->PrepareTest(&materialize_true, &materialize_false,
3363                          &if_true, &if_false, &fall_through);
3364
3365   Handle<Map> map = masm()->isolate()->factory()->heap_number_map();
3366   __ CheckMap(eax, map, if_false, DO_SMI_CHECK);
3367   // Check if the exponent half is 0x80000000. Comparing against 1 and
3368   // checking for overflow is the shortest possible encoding.
3369   __ cmp(FieldOperand(eax, HeapNumber::kExponentOffset), Immediate(0x1));
3370   __ j(no_overflow, if_false);
3371   __ cmp(FieldOperand(eax, HeapNumber::kMantissaOffset), Immediate(0x0));
3372   PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3373   Split(equal, if_true, if_false, fall_through);
3374
3375   context()->Plug(if_true, if_false);
3376 }
3377
3378
3379
3380 void FullCodeGenerator::EmitIsArray(CallRuntime* expr) {
3381   ZoneList<Expression*>* args = expr->arguments();
3382   DCHECK(args->length() == 1);
3383
3384   VisitForAccumulatorValue(args->at(0));
3385
3386   Label materialize_true, materialize_false;
3387   Label* if_true = NULL;
3388   Label* if_false = NULL;
3389   Label* fall_through = NULL;
3390   context()->PrepareTest(&materialize_true, &materialize_false,
3391                          &if_true, &if_false, &fall_through);
3392
3393   __ JumpIfSmi(eax, if_false);
3394   __ CmpObjectType(eax, JS_ARRAY_TYPE, ebx);
3395   PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3396   Split(equal, if_true, if_false, fall_through);
3397
3398   context()->Plug(if_true, if_false);
3399 }
3400
3401
3402 void FullCodeGenerator::EmitIsRegExp(CallRuntime* expr) {
3403   ZoneList<Expression*>* args = expr->arguments();
3404   DCHECK(args->length() == 1);
3405
3406   VisitForAccumulatorValue(args->at(0));
3407
3408   Label materialize_true, materialize_false;
3409   Label* if_true = NULL;
3410   Label* if_false = NULL;
3411   Label* fall_through = NULL;
3412   context()->PrepareTest(&materialize_true, &materialize_false,
3413                          &if_true, &if_false, &fall_through);
3414
3415   __ JumpIfSmi(eax, if_false);
3416   __ CmpObjectType(eax, JS_REGEXP_TYPE, ebx);
3417   PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3418   Split(equal, if_true, if_false, fall_through);
3419
3420   context()->Plug(if_true, if_false);
3421 }
3422
3423
3424 void FullCodeGenerator::EmitIsJSProxy(CallRuntime* expr) {
3425   ZoneList<Expression*>* args = expr->arguments();
3426   DCHECK(args->length() == 1);
3427
3428   VisitForAccumulatorValue(args->at(0));
3429
3430   Label materialize_true, materialize_false;
3431   Label* if_true = NULL;
3432   Label* if_false = NULL;
3433   Label* fall_through = NULL;
3434   context()->PrepareTest(&materialize_true, &materialize_false, &if_true,
3435                          &if_false, &fall_through);
3436
3437   __ JumpIfSmi(eax, if_false);
3438   Register map = ebx;
3439   __ mov(map, FieldOperand(eax, HeapObject::kMapOffset));
3440   __ CmpInstanceType(map, FIRST_JS_PROXY_TYPE);
3441   __ j(less, if_false);
3442   __ CmpInstanceType(map, LAST_JS_PROXY_TYPE);
3443   PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3444   Split(less_equal, if_true, if_false, fall_through);
3445
3446   context()->Plug(if_true, if_false);
3447 }
3448
3449
3450 void FullCodeGenerator::EmitIsConstructCall(CallRuntime* expr) {
3451   DCHECK(expr->arguments()->length() == 0);
3452
3453   Label materialize_true, materialize_false;
3454   Label* if_true = NULL;
3455   Label* if_false = NULL;
3456   Label* fall_through = NULL;
3457   context()->PrepareTest(&materialize_true, &materialize_false,
3458                          &if_true, &if_false, &fall_through);
3459
3460   // Get the frame pointer for the calling frame.
3461   __ mov(eax, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3462
3463   // Skip the arguments adaptor frame if it exists.
3464   Label check_frame_marker;
3465   __ cmp(Operand(eax, StandardFrameConstants::kContextOffset),
3466          Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
3467   __ j(not_equal, &check_frame_marker);
3468   __ mov(eax, Operand(eax, StandardFrameConstants::kCallerFPOffset));
3469
3470   // Check the marker in the calling frame.
3471   __ bind(&check_frame_marker);
3472   __ cmp(Operand(eax, StandardFrameConstants::kMarkerOffset),
3473          Immediate(Smi::FromInt(StackFrame::CONSTRUCT)));
3474   PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3475   Split(equal, if_true, if_false, fall_through);
3476
3477   context()->Plug(if_true, if_false);
3478 }
3479
3480
3481 void FullCodeGenerator::EmitObjectEquals(CallRuntime* expr) {
3482   ZoneList<Expression*>* args = expr->arguments();
3483   DCHECK(args->length() == 2);
3484
3485   // Load the two objects into registers and perform the comparison.
3486   VisitForStackValue(args->at(0));
3487   VisitForAccumulatorValue(args->at(1));
3488
3489   Label materialize_true, materialize_false;
3490   Label* if_true = NULL;
3491   Label* if_false = NULL;
3492   Label* fall_through = NULL;
3493   context()->PrepareTest(&materialize_true, &materialize_false,
3494                          &if_true, &if_false, &fall_through);
3495
3496   __ pop(ebx);
3497   __ cmp(eax, ebx);
3498   PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3499   Split(equal, if_true, if_false, fall_through);
3500
3501   context()->Plug(if_true, if_false);
3502 }
3503
3504
3505 void FullCodeGenerator::EmitArguments(CallRuntime* expr) {
3506   ZoneList<Expression*>* args = expr->arguments();
3507   DCHECK(args->length() == 1);
3508
3509   // ArgumentsAccessStub expects the key in edx and the formal
3510   // parameter count in eax.
3511   VisitForAccumulatorValue(args->at(0));
3512   __ mov(edx, eax);
3513   __ Move(eax, Immediate(Smi::FromInt(info_->scope()->num_parameters())));
3514   ArgumentsAccessStub stub(isolate(), ArgumentsAccessStub::READ_ELEMENT);
3515   __ CallStub(&stub);
3516   context()->Plug(eax);
3517 }
3518
3519
3520 void FullCodeGenerator::EmitArgumentsLength(CallRuntime* expr) {
3521   DCHECK(expr->arguments()->length() == 0);
3522
3523   Label exit;
3524   // Get the number of formal parameters.
3525   __ Move(eax, Immediate(Smi::FromInt(info_->scope()->num_parameters())));
3526
3527   // Check if the calling frame is an arguments adaptor frame.
3528   __ mov(ebx, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3529   __ cmp(Operand(ebx, StandardFrameConstants::kContextOffset),
3530          Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
3531   __ j(not_equal, &exit);
3532
3533   // Arguments adaptor case: Read the arguments length from the
3534   // adaptor frame.
3535   __ mov(eax, Operand(ebx, ArgumentsAdaptorFrameConstants::kLengthOffset));
3536
3537   __ bind(&exit);
3538   __ AssertSmi(eax);
3539   context()->Plug(eax);
3540 }
3541
3542
3543 void FullCodeGenerator::EmitClassOf(CallRuntime* expr) {
3544   ZoneList<Expression*>* args = expr->arguments();
3545   DCHECK(args->length() == 1);
3546   Label done, null, function, non_function_constructor;
3547
3548   VisitForAccumulatorValue(args->at(0));
3549
3550   // If the object is a smi, we return null.
3551   __ JumpIfSmi(eax, &null);
3552
3553   // Check that the object is a JS object but take special care of JS
3554   // functions to make sure they have 'Function' as their class.
3555   // Assume that there are only two callable types, and one of them is at
3556   // either end of the type range for JS object types. Saves extra comparisons.
3557   STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
3558   __ CmpObjectType(eax, FIRST_SPEC_OBJECT_TYPE, eax);
3559   // Map is now in eax.
3560   __ j(below, &null);
3561   STATIC_ASSERT(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE ==
3562                 FIRST_SPEC_OBJECT_TYPE + 1);
3563   __ j(equal, &function);
3564
3565   __ CmpInstanceType(eax, LAST_SPEC_OBJECT_TYPE);
3566   STATIC_ASSERT(LAST_NONCALLABLE_SPEC_OBJECT_TYPE ==
3567                 LAST_SPEC_OBJECT_TYPE - 1);
3568   __ j(equal, &function);
3569   // Assume that there is no larger type.
3570   STATIC_ASSERT(LAST_NONCALLABLE_SPEC_OBJECT_TYPE == LAST_TYPE - 1);
3571
3572   // Check if the constructor in the map is a JS function.
3573   __ mov(eax, FieldOperand(eax, Map::kConstructorOffset));
3574   __ CmpObjectType(eax, JS_FUNCTION_TYPE, ebx);
3575   __ j(not_equal, &non_function_constructor);
3576
3577   // eax now contains the constructor function. Grab the
3578   // instance class name from there.
3579   __ mov(eax, FieldOperand(eax, JSFunction::kSharedFunctionInfoOffset));
3580   __ mov(eax, FieldOperand(eax, SharedFunctionInfo::kInstanceClassNameOffset));
3581   __ jmp(&done);
3582
3583   // Functions have class 'Function'.
3584   __ bind(&function);
3585   __ mov(eax, isolate()->factory()->Function_string());
3586   __ jmp(&done);
3587
3588   // Objects with a non-function constructor have class 'Object'.
3589   __ bind(&non_function_constructor);
3590   __ mov(eax, isolate()->factory()->Object_string());
3591   __ jmp(&done);
3592
3593   // Non-JS objects have class null.
3594   __ bind(&null);
3595   __ mov(eax, isolate()->factory()->null_value());
3596
3597   // All done.
3598   __ bind(&done);
3599
3600   context()->Plug(eax);
3601 }
3602
3603
3604 void FullCodeGenerator::EmitSubString(CallRuntime* expr) {
3605   // Load the arguments on the stack and call the stub.
3606   SubStringStub stub(isolate());
3607   ZoneList<Expression*>* args = expr->arguments();
3608   DCHECK(args->length() == 3);
3609   VisitForStackValue(args->at(0));
3610   VisitForStackValue(args->at(1));
3611   VisitForStackValue(args->at(2));
3612   __ CallStub(&stub);
3613   context()->Plug(eax);
3614 }
3615
3616
3617 void FullCodeGenerator::EmitRegExpExec(CallRuntime* expr) {
3618   // Load the arguments on the stack and call the stub.
3619   RegExpExecStub stub(isolate());
3620   ZoneList<Expression*>* args = expr->arguments();
3621   DCHECK(args->length() == 4);
3622   VisitForStackValue(args->at(0));
3623   VisitForStackValue(args->at(1));
3624   VisitForStackValue(args->at(2));
3625   VisitForStackValue(args->at(3));
3626   __ CallStub(&stub);
3627   context()->Plug(eax);
3628 }
3629
3630
3631 void FullCodeGenerator::EmitValueOf(CallRuntime* expr) {
3632   ZoneList<Expression*>* args = expr->arguments();
3633   DCHECK(args->length() == 1);
3634
3635   VisitForAccumulatorValue(args->at(0));  // Load the object.
3636
3637   Label done;
3638   // If the object is a smi return the object.
3639   __ JumpIfSmi(eax, &done, Label::kNear);
3640   // If the object is not a value type, return the object.
3641   __ CmpObjectType(eax, JS_VALUE_TYPE, ebx);
3642   __ j(not_equal, &done, Label::kNear);
3643   __ mov(eax, FieldOperand(eax, JSValue::kValueOffset));
3644
3645   __ bind(&done);
3646   context()->Plug(eax);
3647 }
3648
3649
3650 void FullCodeGenerator::EmitDateField(CallRuntime* expr) {
3651   ZoneList<Expression*>* args = expr->arguments();
3652   DCHECK(args->length() == 2);
3653   DCHECK_NE(NULL, args->at(1)->AsLiteral());
3654   Smi* index = Smi::cast(*(args->at(1)->AsLiteral()->value()));
3655
3656   VisitForAccumulatorValue(args->at(0));  // Load the object.
3657
3658   Label runtime, done, not_date_object;
3659   Register object = eax;
3660   Register result = eax;
3661   Register scratch = ecx;
3662
3663   __ JumpIfSmi(object, &not_date_object);
3664   __ CmpObjectType(object, JS_DATE_TYPE, scratch);
3665   __ j(not_equal, &not_date_object);
3666
3667   if (index->value() == 0) {
3668     __ mov(result, FieldOperand(object, JSDate::kValueOffset));
3669     __ jmp(&done);
3670   } else {
3671     if (index->value() < JSDate::kFirstUncachedField) {
3672       ExternalReference stamp = ExternalReference::date_cache_stamp(isolate());
3673       __ mov(scratch, Operand::StaticVariable(stamp));
3674       __ cmp(scratch, FieldOperand(object, JSDate::kCacheStampOffset));
3675       __ j(not_equal, &runtime, Label::kNear);
3676       __ mov(result, FieldOperand(object, JSDate::kValueOffset +
3677                                           kPointerSize * index->value()));
3678       __ jmp(&done);
3679     }
3680     __ bind(&runtime);
3681     __ PrepareCallCFunction(2, scratch);
3682     __ mov(Operand(esp, 0), object);
3683     __ mov(Operand(esp, 1 * kPointerSize), Immediate(index));
3684     __ CallCFunction(ExternalReference::get_date_field_function(isolate()), 2);
3685     __ jmp(&done);
3686   }
3687
3688   __ bind(&not_date_object);
3689   __ CallRuntime(Runtime::kThrowNotDateError, 0);
3690   __ bind(&done);
3691   context()->Plug(result);
3692 }
3693
3694
3695 void FullCodeGenerator::EmitOneByteSeqStringSetChar(CallRuntime* expr) {
3696   ZoneList<Expression*>* args = expr->arguments();
3697   DCHECK_EQ(3, args->length());
3698
3699   Register string = eax;
3700   Register index = ebx;
3701   Register value = ecx;
3702
3703   VisitForStackValue(args->at(0));        // index
3704   VisitForStackValue(args->at(1));        // value
3705   VisitForAccumulatorValue(args->at(2));  // string
3706
3707   __ pop(value);
3708   __ pop(index);
3709
3710   if (FLAG_debug_code) {
3711     __ test(value, Immediate(kSmiTagMask));
3712     __ Check(zero, kNonSmiValue);
3713     __ test(index, Immediate(kSmiTagMask));
3714     __ Check(zero, kNonSmiValue);
3715   }
3716
3717   __ SmiUntag(value);
3718   __ SmiUntag(index);
3719
3720   if (FLAG_debug_code) {
3721     static const uint32_t one_byte_seq_type = kSeqStringTag | kOneByteStringTag;
3722     __ EmitSeqStringSetCharCheck(string, index, value, one_byte_seq_type);
3723   }
3724
3725   __ mov_b(FieldOperand(string, index, times_1, SeqOneByteString::kHeaderSize),
3726            value);
3727   context()->Plug(string);
3728 }
3729
3730
3731 void FullCodeGenerator::EmitTwoByteSeqStringSetChar(CallRuntime* expr) {
3732   ZoneList<Expression*>* args = expr->arguments();
3733   DCHECK_EQ(3, args->length());
3734
3735   Register string = eax;
3736   Register index = ebx;
3737   Register value = ecx;
3738
3739   VisitForStackValue(args->at(0));        // index
3740   VisitForStackValue(args->at(1));        // value
3741   VisitForAccumulatorValue(args->at(2));  // string
3742   __ pop(value);
3743   __ pop(index);
3744
3745   if (FLAG_debug_code) {
3746     __ test(value, Immediate(kSmiTagMask));
3747     __ Check(zero, kNonSmiValue);
3748     __ test(index, Immediate(kSmiTagMask));
3749     __ Check(zero, kNonSmiValue);
3750     __ SmiUntag(index);
3751     static const uint32_t two_byte_seq_type = kSeqStringTag | kTwoByteStringTag;
3752     __ EmitSeqStringSetCharCheck(string, index, value, two_byte_seq_type);
3753     __ SmiTag(index);
3754   }
3755
3756   __ SmiUntag(value);
3757   // No need to untag a smi for two-byte addressing.
3758   __ mov_w(FieldOperand(string, index, times_1, SeqTwoByteString::kHeaderSize),
3759            value);
3760   context()->Plug(string);
3761 }
3762
3763
3764 void FullCodeGenerator::EmitMathPow(CallRuntime* expr) {
3765   // Load the arguments on the stack and call the runtime function.
3766   ZoneList<Expression*>* args = expr->arguments();
3767   DCHECK(args->length() == 2);
3768   VisitForStackValue(args->at(0));
3769   VisitForStackValue(args->at(1));
3770
3771   MathPowStub stub(isolate(), MathPowStub::ON_STACK);
3772   __ CallStub(&stub);
3773   context()->Plug(eax);
3774 }
3775
3776
3777 void FullCodeGenerator::EmitSetValueOf(CallRuntime* expr) {
3778   ZoneList<Expression*>* args = expr->arguments();
3779   DCHECK(args->length() == 2);
3780
3781   VisitForStackValue(args->at(0));  // Load the object.
3782   VisitForAccumulatorValue(args->at(1));  // Load the value.
3783   __ pop(ebx);  // eax = value. ebx = object.
3784
3785   Label done;
3786   // If the object is a smi, return the value.
3787   __ JumpIfSmi(ebx, &done, Label::kNear);
3788
3789   // If the object is not a value type, return the value.
3790   __ CmpObjectType(ebx, JS_VALUE_TYPE, ecx);
3791   __ j(not_equal, &done, Label::kNear);
3792
3793   // Store the value.
3794   __ mov(FieldOperand(ebx, JSValue::kValueOffset), eax);
3795
3796   // Update the write barrier.  Save the value as it will be
3797   // overwritten by the write barrier code and is needed afterward.
3798   __ mov(edx, eax);
3799   __ RecordWriteField(ebx, JSValue::kValueOffset, edx, ecx, kDontSaveFPRegs);
3800
3801   __ bind(&done);
3802   context()->Plug(eax);
3803 }
3804
3805
3806 void FullCodeGenerator::EmitNumberToString(CallRuntime* expr) {
3807   ZoneList<Expression*>* args = expr->arguments();
3808   DCHECK_EQ(args->length(), 1);
3809
3810   // Load the argument into eax and call the stub.
3811   VisitForAccumulatorValue(args->at(0));
3812
3813   NumberToStringStub stub(isolate());
3814   __ CallStub(&stub);
3815   context()->Plug(eax);
3816 }
3817
3818
3819 void FullCodeGenerator::EmitStringCharFromCode(CallRuntime* expr) {
3820   ZoneList<Expression*>* args = expr->arguments();
3821   DCHECK(args->length() == 1);
3822
3823   VisitForAccumulatorValue(args->at(0));
3824
3825   Label done;
3826   StringCharFromCodeGenerator generator(eax, ebx);
3827   generator.GenerateFast(masm_);
3828   __ jmp(&done);
3829
3830   NopRuntimeCallHelper call_helper;
3831   generator.GenerateSlow(masm_, call_helper);
3832
3833   __ bind(&done);
3834   context()->Plug(ebx);
3835 }
3836
3837
3838 void FullCodeGenerator::EmitStringCharCodeAt(CallRuntime* expr) {
3839   ZoneList<Expression*>* args = expr->arguments();
3840   DCHECK(args->length() == 2);
3841
3842   VisitForStackValue(args->at(0));
3843   VisitForAccumulatorValue(args->at(1));
3844
3845   Register object = ebx;
3846   Register index = eax;
3847   Register result = edx;
3848
3849   __ pop(object);
3850
3851   Label need_conversion;
3852   Label index_out_of_range;
3853   Label done;
3854   StringCharCodeAtGenerator generator(object,
3855                                       index,
3856                                       result,
3857                                       &need_conversion,
3858                                       &need_conversion,
3859                                       &index_out_of_range,
3860                                       STRING_INDEX_IS_NUMBER);
3861   generator.GenerateFast(masm_);
3862   __ jmp(&done);
3863
3864   __ bind(&index_out_of_range);
3865   // When the index is out of range, the spec requires us to return
3866   // NaN.
3867   __ Move(result, Immediate(isolate()->factory()->nan_value()));
3868   __ jmp(&done);
3869
3870   __ bind(&need_conversion);
3871   // Move the undefined value into the result register, which will
3872   // trigger conversion.
3873   __ Move(result, Immediate(isolate()->factory()->undefined_value()));
3874   __ jmp(&done);
3875
3876   NopRuntimeCallHelper call_helper;
3877   generator.GenerateSlow(masm_, call_helper);
3878
3879   __ bind(&done);
3880   context()->Plug(result);
3881 }
3882
3883
3884 void FullCodeGenerator::EmitStringCharAt(CallRuntime* expr) {
3885   ZoneList<Expression*>* args = expr->arguments();
3886   DCHECK(args->length() == 2);
3887
3888   VisitForStackValue(args->at(0));
3889   VisitForAccumulatorValue(args->at(1));
3890
3891   Register object = ebx;
3892   Register index = eax;
3893   Register scratch = edx;
3894   Register result = eax;
3895
3896   __ pop(object);
3897
3898   Label need_conversion;
3899   Label index_out_of_range;
3900   Label done;
3901   StringCharAtGenerator generator(object,
3902                                   index,
3903                                   scratch,
3904                                   result,
3905                                   &need_conversion,
3906                                   &need_conversion,
3907                                   &index_out_of_range,
3908                                   STRING_INDEX_IS_NUMBER);
3909   generator.GenerateFast(masm_);
3910   __ jmp(&done);
3911
3912   __ bind(&index_out_of_range);
3913   // When the index is out of range, the spec requires us to return
3914   // the empty string.
3915   __ Move(result, Immediate(isolate()->factory()->empty_string()));
3916   __ jmp(&done);
3917
3918   __ bind(&need_conversion);
3919   // Move smi zero into the result register, which will trigger
3920   // conversion.
3921   __ Move(result, Immediate(Smi::FromInt(0)));
3922   __ jmp(&done);
3923
3924   NopRuntimeCallHelper call_helper;
3925   generator.GenerateSlow(masm_, call_helper);
3926
3927   __ bind(&done);
3928   context()->Plug(result);
3929 }
3930
3931
3932 void FullCodeGenerator::EmitStringAdd(CallRuntime* expr) {
3933   ZoneList<Expression*>* args = expr->arguments();
3934   DCHECK_EQ(2, args->length());
3935   VisitForStackValue(args->at(0));
3936   VisitForAccumulatorValue(args->at(1));
3937
3938   __ pop(edx);
3939   StringAddStub stub(isolate(), STRING_ADD_CHECK_BOTH, NOT_TENURED);
3940   __ CallStub(&stub);
3941   context()->Plug(eax);
3942 }
3943
3944
3945 void FullCodeGenerator::EmitStringCompare(CallRuntime* expr) {
3946   ZoneList<Expression*>* args = expr->arguments();
3947   DCHECK_EQ(2, args->length());
3948
3949   VisitForStackValue(args->at(0));
3950   VisitForStackValue(args->at(1));
3951
3952   StringCompareStub stub(isolate());
3953   __ CallStub(&stub);
3954   context()->Plug(eax);
3955 }
3956
3957
3958 void FullCodeGenerator::EmitCallFunction(CallRuntime* expr) {
3959   ZoneList<Expression*>* args = expr->arguments();
3960   DCHECK(args->length() >= 2);
3961
3962   int arg_count = args->length() - 2;  // 2 ~ receiver and function.
3963   for (int i = 0; i < arg_count + 1; ++i) {
3964     VisitForStackValue(args->at(i));
3965   }
3966   VisitForAccumulatorValue(args->last());  // Function.
3967
3968   Label runtime, done;
3969   // Check for non-function argument (including proxy).
3970   __ JumpIfSmi(eax, &runtime);
3971   __ CmpObjectType(eax, JS_FUNCTION_TYPE, ebx);
3972   __ j(not_equal, &runtime);
3973
3974   // InvokeFunction requires the function in edi. Move it in there.
3975   __ mov(edi, result_register());
3976   ParameterCount count(arg_count);
3977   __ InvokeFunction(edi, count, CALL_FUNCTION, NullCallWrapper());
3978   __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
3979   __ jmp(&done);
3980
3981   __ bind(&runtime);
3982   __ push(eax);
3983   __ CallRuntime(Runtime::kCall, args->length());
3984   __ bind(&done);
3985
3986   context()->Plug(eax);
3987 }
3988
3989
3990 void FullCodeGenerator::EmitRegExpConstructResult(CallRuntime* expr) {
3991   // Load the arguments on the stack and call the stub.
3992   RegExpConstructResultStub stub(isolate());
3993   ZoneList<Expression*>* args = expr->arguments();
3994   DCHECK(args->length() == 3);
3995   VisitForStackValue(args->at(0));
3996   VisitForStackValue(args->at(1));
3997   VisitForAccumulatorValue(args->at(2));
3998   __ pop(ebx);
3999   __ pop(ecx);
4000   __ CallStub(&stub);
4001   context()->Plug(eax);
4002 }
4003
4004
4005 void FullCodeGenerator::EmitGetFromCache(CallRuntime* expr) {
4006   ZoneList<Expression*>* args = expr->arguments();
4007   DCHECK_EQ(2, args->length());
4008
4009   DCHECK_NE(NULL, args->at(0)->AsLiteral());
4010   int cache_id = Smi::cast(*(args->at(0)->AsLiteral()->value()))->value();
4011
4012   Handle<FixedArray> jsfunction_result_caches(
4013       isolate()->native_context()->jsfunction_result_caches());
4014   if (jsfunction_result_caches->length() <= cache_id) {
4015     __ Abort(kAttemptToUseUndefinedCache);
4016     __ mov(eax, isolate()->factory()->undefined_value());
4017     context()->Plug(eax);
4018     return;
4019   }
4020
4021   VisitForAccumulatorValue(args->at(1));
4022
4023   Register key = eax;
4024   Register cache = ebx;
4025   Register tmp = ecx;
4026   __ mov(cache, ContextOperand(esi, Context::GLOBAL_OBJECT_INDEX));
4027   __ mov(cache,
4028          FieldOperand(cache, GlobalObject::kNativeContextOffset));
4029   __ mov(cache, ContextOperand(cache, Context::JSFUNCTION_RESULT_CACHES_INDEX));
4030   __ mov(cache,
4031          FieldOperand(cache, FixedArray::OffsetOfElementAt(cache_id)));
4032
4033   Label done, not_found;
4034   STATIC_ASSERT(kSmiTag == 0 && kSmiTagSize == 1);
4035   __ mov(tmp, FieldOperand(cache, JSFunctionResultCache::kFingerOffset));
4036   // tmp now holds finger offset as a smi.
4037   __ cmp(key, FixedArrayElementOperand(cache, tmp));
4038   __ j(not_equal, &not_found);
4039
4040   __ mov(eax, FixedArrayElementOperand(cache, tmp, 1));
4041   __ jmp(&done);
4042
4043   __ bind(&not_found);
4044   // Call runtime to perform the lookup.
4045   __ push(cache);
4046   __ push(key);
4047   __ CallRuntime(Runtime::kGetFromCache, 2);
4048
4049   __ bind(&done);
4050   context()->Plug(eax);
4051 }
4052
4053
4054 void FullCodeGenerator::EmitHasCachedArrayIndex(CallRuntime* expr) {
4055   ZoneList<Expression*>* args = expr->arguments();
4056   DCHECK(args->length() == 1);
4057
4058   VisitForAccumulatorValue(args->at(0));
4059
4060   __ AssertString(eax);
4061
4062   Label materialize_true, materialize_false;
4063   Label* if_true = NULL;
4064   Label* if_false = NULL;
4065   Label* fall_through = NULL;
4066   context()->PrepareTest(&materialize_true, &materialize_false,
4067                          &if_true, &if_false, &fall_through);
4068
4069   __ test(FieldOperand(eax, String::kHashFieldOffset),
4070           Immediate(String::kContainsCachedArrayIndexMask));
4071   PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
4072   Split(zero, if_true, if_false, fall_through);
4073
4074   context()->Plug(if_true, if_false);
4075 }
4076
4077
4078 void FullCodeGenerator::EmitGetCachedArrayIndex(CallRuntime* expr) {
4079   ZoneList<Expression*>* args = expr->arguments();
4080   DCHECK(args->length() == 1);
4081   VisitForAccumulatorValue(args->at(0));
4082
4083   __ AssertString(eax);
4084
4085   __ mov(eax, FieldOperand(eax, String::kHashFieldOffset));
4086   __ IndexFromHash(eax, eax);
4087
4088   context()->Plug(eax);
4089 }
4090
4091
4092 void FullCodeGenerator::EmitFastOneByteArrayJoin(CallRuntime* expr) {
4093   Label bailout, done, one_char_separator, long_separator,
4094       non_trivial_array, not_size_one_array, loop,
4095       loop_1, loop_1_condition, loop_2, loop_2_entry, loop_3, loop_3_entry;
4096
4097   ZoneList<Expression*>* args = expr->arguments();
4098   DCHECK(args->length() == 2);
4099   // We will leave the separator on the stack until the end of the function.
4100   VisitForStackValue(args->at(1));
4101   // Load this to eax (= array)
4102   VisitForAccumulatorValue(args->at(0));
4103   // All aliases of the same register have disjoint lifetimes.
4104   Register array = eax;
4105   Register elements = no_reg;  // Will be eax.
4106
4107   Register index = edx;
4108
4109   Register string_length = ecx;
4110
4111   Register string = esi;
4112
4113   Register scratch = ebx;
4114
4115   Register array_length = edi;
4116   Register result_pos = no_reg;  // Will be edi.
4117
4118   // Separator operand is already pushed.
4119   Operand separator_operand = Operand(esp, 2 * kPointerSize);
4120   Operand result_operand = Operand(esp, 1 * kPointerSize);
4121   Operand array_length_operand = Operand(esp, 0);
4122   __ sub(esp, Immediate(2 * kPointerSize));
4123   __ cld();
4124   // Check that the array is a JSArray
4125   __ JumpIfSmi(array, &bailout);
4126   __ CmpObjectType(array, JS_ARRAY_TYPE, scratch);
4127   __ j(not_equal, &bailout);
4128
4129   // Check that the array has fast elements.
4130   __ CheckFastElements(scratch, &bailout);
4131
4132   // If the array has length zero, return the empty string.
4133   __ mov(array_length, FieldOperand(array, JSArray::kLengthOffset));
4134   __ SmiUntag(array_length);
4135   __ j(not_zero, &non_trivial_array);
4136   __ mov(result_operand, isolate()->factory()->empty_string());
4137   __ jmp(&done);
4138
4139   // Save the array length.
4140   __ bind(&non_trivial_array);
4141   __ mov(array_length_operand, array_length);
4142
4143   // Save the FixedArray containing array's elements.
4144   // End of array's live range.
4145   elements = array;
4146   __ mov(elements, FieldOperand(array, JSArray::kElementsOffset));
4147   array = no_reg;
4148
4149
4150   // Check that all array elements are sequential one-byte strings, and
4151   // accumulate the sum of their lengths, as a smi-encoded value.
4152   __ Move(index, Immediate(0));
4153   __ Move(string_length, Immediate(0));
4154   // Loop condition: while (index < length).
4155   // Live loop registers: index, array_length, string,
4156   //                      scratch, string_length, elements.
4157   if (generate_debug_code_) {
4158     __ cmp(index, array_length);
4159     __ Assert(less, kNoEmptyArraysHereInEmitFastOneByteArrayJoin);
4160   }
4161   __ bind(&loop);
4162   __ mov(string, FieldOperand(elements,
4163                               index,
4164                               times_pointer_size,
4165                               FixedArray::kHeaderSize));
4166   __ JumpIfSmi(string, &bailout);
4167   __ mov(scratch, FieldOperand(string, HeapObject::kMapOffset));
4168   __ movzx_b(scratch, FieldOperand(scratch, Map::kInstanceTypeOffset));
4169   __ and_(scratch, Immediate(
4170       kIsNotStringMask | kStringEncodingMask | kStringRepresentationMask));
4171   __ cmp(scratch, kStringTag | kOneByteStringTag | kSeqStringTag);
4172   __ j(not_equal, &bailout);
4173   __ add(string_length,
4174          FieldOperand(string, SeqOneByteString::kLengthOffset));
4175   __ j(overflow, &bailout);
4176   __ add(index, Immediate(1));
4177   __ cmp(index, array_length);
4178   __ j(less, &loop);
4179
4180   // If array_length is 1, return elements[0], a string.
4181   __ cmp(array_length, 1);
4182   __ j(not_equal, &not_size_one_array);
4183   __ mov(scratch, FieldOperand(elements, FixedArray::kHeaderSize));
4184   __ mov(result_operand, scratch);
4185   __ jmp(&done);
4186
4187   __ bind(&not_size_one_array);
4188
4189   // End of array_length live range.
4190   result_pos = array_length;
4191   array_length = no_reg;
4192
4193   // Live registers:
4194   // string_length: Sum of string lengths, as a smi.
4195   // elements: FixedArray of strings.
4196
4197   // Check that the separator is a flat one-byte string.
4198   __ mov(string, separator_operand);
4199   __ JumpIfSmi(string, &bailout);
4200   __ mov(scratch, FieldOperand(string, HeapObject::kMapOffset));
4201   __ movzx_b(scratch, FieldOperand(scratch, Map::kInstanceTypeOffset));
4202   __ and_(scratch, Immediate(
4203       kIsNotStringMask | kStringEncodingMask | kStringRepresentationMask));
4204   __ cmp(scratch, kStringTag | kOneByteStringTag | kSeqStringTag);
4205   __ j(not_equal, &bailout);
4206
4207   // Add (separator length times array_length) - separator length
4208   // to string_length.
4209   __ mov(scratch, separator_operand);
4210   __ mov(scratch, FieldOperand(scratch, SeqOneByteString::kLengthOffset));
4211   __ sub(string_length, scratch);  // May be negative, temporarily.
4212   __ imul(scratch, array_length_operand);
4213   __ j(overflow, &bailout);
4214   __ add(string_length, scratch);
4215   __ j(overflow, &bailout);
4216
4217   __ shr(string_length, 1);
4218   // Live registers and stack values:
4219   //   string_length
4220   //   elements
4221   __ AllocateOneByteString(result_pos, string_length, scratch, index, string,
4222                            &bailout);
4223   __ mov(result_operand, result_pos);
4224   __ lea(result_pos, FieldOperand(result_pos, SeqOneByteString::kHeaderSize));
4225
4226
4227   __ mov(string, separator_operand);
4228   __ cmp(FieldOperand(string, SeqOneByteString::kLengthOffset),
4229          Immediate(Smi::FromInt(1)));
4230   __ j(equal, &one_char_separator);
4231   __ j(greater, &long_separator);
4232
4233
4234   // Empty separator case
4235   __ mov(index, Immediate(0));
4236   __ jmp(&loop_1_condition);
4237   // Loop condition: while (index < length).
4238   __ bind(&loop_1);
4239   // Each iteration of the loop concatenates one string to the result.
4240   // Live values in registers:
4241   //   index: which element of the elements array we are adding to the result.
4242   //   result_pos: the position to which we are currently copying characters.
4243   //   elements: the FixedArray of strings we are joining.
4244
4245   // Get string = array[index].
4246   __ mov(string, FieldOperand(elements, index,
4247                               times_pointer_size,
4248                               FixedArray::kHeaderSize));
4249   __ mov(string_length,
4250          FieldOperand(string, String::kLengthOffset));
4251   __ shr(string_length, 1);
4252   __ lea(string,
4253          FieldOperand(string, SeqOneByteString::kHeaderSize));
4254   __ CopyBytes(string, result_pos, string_length, scratch);
4255   __ add(index, Immediate(1));
4256   __ bind(&loop_1_condition);
4257   __ cmp(index, array_length_operand);
4258   __ j(less, &loop_1);  // End while (index < length).
4259   __ jmp(&done);
4260
4261
4262
4263   // One-character separator case
4264   __ bind(&one_char_separator);
4265   // Replace separator with its one-byte character value.
4266   __ mov_b(scratch, FieldOperand(string, SeqOneByteString::kHeaderSize));
4267   __ mov_b(separator_operand, scratch);
4268
4269   __ Move(index, Immediate(0));
4270   // Jump into the loop after the code that copies the separator, so the first
4271   // element is not preceded by a separator
4272   __ jmp(&loop_2_entry);
4273   // Loop condition: while (index < length).
4274   __ bind(&loop_2);
4275   // Each iteration of the loop concatenates one string to the result.
4276   // Live values in registers:
4277   //   index: which element of the elements array we are adding to the result.
4278   //   result_pos: the position to which we are currently copying characters.
4279
4280   // Copy the separator character to the result.
4281   __ mov_b(scratch, separator_operand);
4282   __ mov_b(Operand(result_pos, 0), scratch);
4283   __ inc(result_pos);
4284
4285   __ bind(&loop_2_entry);
4286   // Get string = array[index].
4287   __ mov(string, FieldOperand(elements, index,
4288                               times_pointer_size,
4289                               FixedArray::kHeaderSize));
4290   __ mov(string_length,
4291          FieldOperand(string, String::kLengthOffset));
4292   __ shr(string_length, 1);
4293   __ lea(string,
4294          FieldOperand(string, SeqOneByteString::kHeaderSize));
4295   __ CopyBytes(string, result_pos, string_length, scratch);
4296   __ add(index, Immediate(1));
4297
4298   __ cmp(index, array_length_operand);
4299   __ j(less, &loop_2);  // End while (index < length).
4300   __ jmp(&done);
4301
4302
4303   // Long separator case (separator is more than one character).
4304   __ bind(&long_separator);
4305
4306   __ Move(index, Immediate(0));
4307   // Jump into the loop after the code that copies the separator, so the first
4308   // element is not preceded by a separator
4309   __ jmp(&loop_3_entry);
4310   // Loop condition: while (index < length).
4311   __ bind(&loop_3);
4312   // Each iteration of the loop concatenates one string to the result.
4313   // Live values in registers:
4314   //   index: which element of the elements array we are adding to the result.
4315   //   result_pos: the position to which we are currently copying characters.
4316
4317   // Copy the separator to the result.
4318   __ mov(string, separator_operand);
4319   __ mov(string_length,
4320          FieldOperand(string, String::kLengthOffset));
4321   __ shr(string_length, 1);
4322   __ lea(string,
4323          FieldOperand(string, SeqOneByteString::kHeaderSize));
4324   __ CopyBytes(string, result_pos, string_length, scratch);
4325
4326   __ bind(&loop_3_entry);
4327   // Get string = array[index].
4328   __ mov(string, FieldOperand(elements, index,
4329                               times_pointer_size,
4330                               FixedArray::kHeaderSize));
4331   __ mov(string_length,
4332          FieldOperand(string, String::kLengthOffset));
4333   __ shr(string_length, 1);
4334   __ lea(string,
4335          FieldOperand(string, SeqOneByteString::kHeaderSize));
4336   __ CopyBytes(string, result_pos, string_length, scratch);
4337   __ add(index, Immediate(1));
4338
4339   __ cmp(index, array_length_operand);
4340   __ j(less, &loop_3);  // End while (index < length).
4341   __ jmp(&done);
4342
4343
4344   __ bind(&bailout);
4345   __ mov(result_operand, isolate()->factory()->undefined_value());
4346   __ bind(&done);
4347   __ mov(eax, result_operand);
4348   // Drop temp values from the stack, and restore context register.
4349   __ add(esp, Immediate(3 * kPointerSize));
4350
4351   __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4352   context()->Plug(eax);
4353 }
4354
4355
4356 void FullCodeGenerator::EmitDebugIsActive(CallRuntime* expr) {
4357   DCHECK(expr->arguments()->length() == 0);
4358   ExternalReference debug_is_active =
4359       ExternalReference::debug_is_active_address(isolate());
4360   __ movzx_b(eax, Operand::StaticVariable(debug_is_active));
4361   __ SmiTag(eax);
4362   context()->Plug(eax);
4363 }
4364
4365
4366 void FullCodeGenerator::VisitCallRuntime(CallRuntime* expr) {
4367   if (expr->function() != NULL &&
4368       expr->function()->intrinsic_type == Runtime::INLINE) {
4369     Comment cmnt(masm_, "[ InlineRuntimeCall");
4370     EmitInlineRuntimeCall(expr);
4371     return;
4372   }
4373
4374   Comment cmnt(masm_, "[ CallRuntime");
4375   ZoneList<Expression*>* args = expr->arguments();
4376
4377   if (expr->is_jsruntime()) {
4378     // Push the builtins object as receiver.
4379     __ mov(eax, GlobalObjectOperand());
4380     __ push(FieldOperand(eax, GlobalObject::kBuiltinsOffset));
4381
4382     // Load the function from the receiver.
4383     __ mov(LoadDescriptor::ReceiverRegister(), Operand(esp, 0));
4384     __ mov(LoadDescriptor::NameRegister(), Immediate(expr->name()));
4385     if (FLAG_vector_ics) {
4386       __ mov(VectorLoadICDescriptor::SlotRegister(),
4387              Immediate(SmiFromSlot(expr->CallRuntimeFeedbackSlot())));
4388       CallLoadIC(NOT_CONTEXTUAL);
4389     } else {
4390       CallLoadIC(NOT_CONTEXTUAL, expr->CallRuntimeFeedbackId());
4391     }
4392
4393     // Push the target function under the receiver.
4394     __ push(Operand(esp, 0));
4395     __ mov(Operand(esp, kPointerSize), eax);
4396
4397     // Code common for calls using the IC.
4398     ZoneList<Expression*>* args = expr->arguments();
4399     int arg_count = args->length();
4400     for (int i = 0; i < arg_count; i++) {
4401       VisitForStackValue(args->at(i));
4402     }
4403
4404     // Record source position of the IC call.
4405     SetSourcePosition(expr->position());
4406     CallFunctionStub stub(isolate(), arg_count, NO_CALL_FUNCTION_FLAGS);
4407     __ mov(edi, Operand(esp, (arg_count + 1) * kPointerSize));
4408     __ CallStub(&stub);
4409     // Restore context register.
4410     __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4411     context()->DropAndPlug(1, eax);
4412
4413   } else {
4414     // Push the arguments ("left-to-right").
4415     int arg_count = args->length();
4416     for (int i = 0; i < arg_count; i++) {
4417       VisitForStackValue(args->at(i));
4418     }
4419
4420     // Call the C runtime function.
4421     __ CallRuntime(expr->function(), arg_count);
4422
4423     context()->Plug(eax);
4424   }
4425 }
4426
4427
4428 void FullCodeGenerator::VisitUnaryOperation(UnaryOperation* expr) {
4429   switch (expr->op()) {
4430     case Token::DELETE: {
4431       Comment cmnt(masm_, "[ UnaryOperation (DELETE)");
4432       Property* property = expr->expression()->AsProperty();
4433       VariableProxy* proxy = expr->expression()->AsVariableProxy();
4434
4435       if (property != NULL) {
4436         VisitForStackValue(property->obj());
4437         VisitForStackValue(property->key());
4438         __ push(Immediate(Smi::FromInt(strict_mode())));
4439         __ InvokeBuiltin(Builtins::DELETE, CALL_FUNCTION);
4440         context()->Plug(eax);
4441       } else if (proxy != NULL) {
4442         Variable* var = proxy->var();
4443         // Delete of an unqualified identifier is disallowed in strict mode
4444         // but "delete this" is allowed.
4445         DCHECK(strict_mode() == SLOPPY || var->is_this());
4446         if (var->IsUnallocated()) {
4447           __ push(GlobalObjectOperand());
4448           __ push(Immediate(var->name()));
4449           __ push(Immediate(Smi::FromInt(SLOPPY)));
4450           __ InvokeBuiltin(Builtins::DELETE, CALL_FUNCTION);
4451           context()->Plug(eax);
4452         } else if (var->IsStackAllocated() || var->IsContextSlot()) {
4453           // Result of deleting non-global variables is false.  'this' is
4454           // not really a variable, though we implement it as one.  The
4455           // subexpression does not have side effects.
4456           context()->Plug(var->is_this());
4457         } else {
4458           // Non-global variable.  Call the runtime to try to delete from the
4459           // context where the variable was introduced.
4460           __ push(context_register());
4461           __ push(Immediate(var->name()));
4462           __ CallRuntime(Runtime::kDeleteLookupSlot, 2);
4463           context()->Plug(eax);
4464         }
4465       } else {
4466         // Result of deleting non-property, non-variable reference is true.
4467         // The subexpression may have side effects.
4468         VisitForEffect(expr->expression());
4469         context()->Plug(true);
4470       }
4471       break;
4472     }
4473
4474     case Token::VOID: {
4475       Comment cmnt(masm_, "[ UnaryOperation (VOID)");
4476       VisitForEffect(expr->expression());
4477       context()->Plug(isolate()->factory()->undefined_value());
4478       break;
4479     }
4480
4481     case Token::NOT: {
4482       Comment cmnt(masm_, "[ UnaryOperation (NOT)");
4483       if (context()->IsEffect()) {
4484         // Unary NOT has no side effects so it's only necessary to visit the
4485         // subexpression.  Match the optimizing compiler by not branching.
4486         VisitForEffect(expr->expression());
4487       } else if (context()->IsTest()) {
4488         const TestContext* test = TestContext::cast(context());
4489         // The labels are swapped for the recursive call.
4490         VisitForControl(expr->expression(),
4491                         test->false_label(),
4492                         test->true_label(),
4493                         test->fall_through());
4494         context()->Plug(test->true_label(), test->false_label());
4495       } else {
4496         // We handle value contexts explicitly rather than simply visiting
4497         // for control and plugging the control flow into the context,
4498         // because we need to prepare a pair of extra administrative AST ids
4499         // for the optimizing compiler.
4500         DCHECK(context()->IsAccumulatorValue() || context()->IsStackValue());
4501         Label materialize_true, materialize_false, done;
4502         VisitForControl(expr->expression(),
4503                         &materialize_false,
4504                         &materialize_true,
4505                         &materialize_true);
4506         __ bind(&materialize_true);
4507         PrepareForBailoutForId(expr->MaterializeTrueId(), NO_REGISTERS);
4508         if (context()->IsAccumulatorValue()) {
4509           __ mov(eax, isolate()->factory()->true_value());
4510         } else {
4511           __ Push(isolate()->factory()->true_value());
4512         }
4513         __ jmp(&done, Label::kNear);
4514         __ bind(&materialize_false);
4515         PrepareForBailoutForId(expr->MaterializeFalseId(), NO_REGISTERS);
4516         if (context()->IsAccumulatorValue()) {
4517           __ mov(eax, isolate()->factory()->false_value());
4518         } else {
4519           __ Push(isolate()->factory()->false_value());
4520         }
4521         __ bind(&done);
4522       }
4523       break;
4524     }
4525
4526     case Token::TYPEOF: {
4527       Comment cmnt(masm_, "[ UnaryOperation (TYPEOF)");
4528       { StackValueContext context(this);
4529         VisitForTypeofValue(expr->expression());
4530       }
4531       __ CallRuntime(Runtime::kTypeof, 1);
4532       context()->Plug(eax);
4533       break;
4534     }
4535
4536     default:
4537       UNREACHABLE();
4538   }
4539 }
4540
4541
4542 void FullCodeGenerator::VisitCountOperation(CountOperation* expr) {
4543   DCHECK(expr->expression()->IsValidReferenceExpression());
4544
4545   Comment cmnt(masm_, "[ CountOperation");
4546   SetSourcePosition(expr->position());
4547
4548   Property* prop = expr->expression()->AsProperty();
4549   LhsKind assign_type = GetAssignType(prop);
4550
4551   // Evaluate expression and get value.
4552   if (assign_type == VARIABLE) {
4553     DCHECK(expr->expression()->AsVariableProxy()->var() != NULL);
4554     AccumulatorValueContext context(this);
4555     EmitVariableLoad(expr->expression()->AsVariableProxy());
4556   } else {
4557     // Reserve space for result of postfix operation.
4558     if (expr->is_postfix() && !context()->IsEffect()) {
4559       __ push(Immediate(Smi::FromInt(0)));
4560     }
4561     switch (assign_type) {
4562       case NAMED_PROPERTY: {
4563         // Put the object both on the stack and in the register.
4564         VisitForStackValue(prop->obj());
4565         __ mov(LoadDescriptor::ReceiverRegister(), Operand(esp, 0));
4566         EmitNamedPropertyLoad(prop);
4567         break;
4568       }
4569
4570       case NAMED_SUPER_PROPERTY: {
4571         VisitForStackValue(prop->obj()->AsSuperReference()->this_var());
4572         EmitLoadHomeObject(prop->obj()->AsSuperReference());
4573         __ push(result_register());
4574         __ push(MemOperand(esp, kPointerSize));
4575         __ push(result_register());
4576         EmitNamedSuperPropertyLoad(prop);
4577         break;
4578       }
4579
4580       case KEYED_SUPER_PROPERTY: {
4581         VisitForStackValue(prop->obj()->AsSuperReference()->this_var());
4582         EmitLoadHomeObject(prop->obj()->AsSuperReference());
4583         __ push(result_register());
4584         VisitForAccumulatorValue(prop->key());
4585         __ push(result_register());
4586         __ push(MemOperand(esp, 2 * kPointerSize));
4587         __ push(MemOperand(esp, 2 * kPointerSize));
4588         __ push(result_register());
4589         EmitKeyedSuperPropertyLoad(prop);
4590         break;
4591       }
4592
4593       case KEYED_PROPERTY: {
4594         VisitForStackValue(prop->obj());
4595         VisitForStackValue(prop->key());
4596         __ mov(LoadDescriptor::ReceiverRegister(),
4597                Operand(esp, kPointerSize));                       // Object.
4598         __ mov(LoadDescriptor::NameRegister(), Operand(esp, 0));  // Key.
4599         EmitKeyedPropertyLoad(prop);
4600         break;
4601       }
4602
4603       case VARIABLE:
4604         UNREACHABLE();
4605     }
4606   }
4607
4608   // We need a second deoptimization point after loading the value
4609   // in case evaluating the property load my have a side effect.
4610   if (assign_type == VARIABLE) {
4611     PrepareForBailout(expr->expression(), TOS_REG);
4612   } else {
4613     PrepareForBailoutForId(prop->LoadId(), TOS_REG);
4614   }
4615
4616   // Inline smi case if we are in a loop.
4617   Label done, stub_call;
4618   JumpPatchSite patch_site(masm_);
4619   if (ShouldInlineSmiCase(expr->op())) {
4620     Label slow;
4621     patch_site.EmitJumpIfNotSmi(eax, &slow, Label::kNear);
4622
4623     // Save result for postfix expressions.
4624     if (expr->is_postfix()) {
4625       if (!context()->IsEffect()) {
4626         // Save the result on the stack. If we have a named or keyed property
4627         // we store the result under the receiver that is currently on top
4628         // of the stack.
4629         switch (assign_type) {
4630           case VARIABLE:
4631             __ push(eax);
4632             break;
4633           case NAMED_PROPERTY:
4634             __ mov(Operand(esp, kPointerSize), eax);
4635             break;
4636           case NAMED_SUPER_PROPERTY:
4637             __ mov(Operand(esp, 2 * kPointerSize), eax);
4638             break;
4639           case KEYED_PROPERTY:
4640             __ mov(Operand(esp, 2 * kPointerSize), eax);
4641             break;
4642           case KEYED_SUPER_PROPERTY:
4643             __ mov(Operand(esp, 3 * kPointerSize), eax);
4644             break;
4645         }
4646       }
4647     }
4648
4649     if (expr->op() == Token::INC) {
4650       __ add(eax, Immediate(Smi::FromInt(1)));
4651     } else {
4652       __ sub(eax, Immediate(Smi::FromInt(1)));
4653     }
4654     __ j(no_overflow, &done, Label::kNear);
4655     // Call stub. Undo operation first.
4656     if (expr->op() == Token::INC) {
4657       __ sub(eax, Immediate(Smi::FromInt(1)));
4658     } else {
4659       __ add(eax, Immediate(Smi::FromInt(1)));
4660     }
4661     __ jmp(&stub_call, Label::kNear);
4662     __ bind(&slow);
4663   }
4664   ToNumberStub convert_stub(isolate());
4665   __ CallStub(&convert_stub);
4666
4667   // Save result for postfix expressions.
4668   if (expr->is_postfix()) {
4669     if (!context()->IsEffect()) {
4670       // Save the result on the stack. If we have a named or keyed property
4671       // we store the result under the receiver that is currently on top
4672       // of the stack.
4673       switch (assign_type) {
4674         case VARIABLE:
4675           __ push(eax);
4676           break;
4677         case NAMED_PROPERTY:
4678           __ mov(Operand(esp, kPointerSize), eax);
4679           break;
4680         case NAMED_SUPER_PROPERTY:
4681           __ mov(Operand(esp, 2 * kPointerSize), eax);
4682           break;
4683         case KEYED_PROPERTY:
4684           __ mov(Operand(esp, 2 * kPointerSize), eax);
4685           break;
4686         case KEYED_SUPER_PROPERTY:
4687           __ mov(Operand(esp, 3 * kPointerSize), eax);
4688           break;
4689       }
4690     }
4691   }
4692
4693   // Record position before stub call.
4694   SetSourcePosition(expr->position());
4695
4696   // Call stub for +1/-1.
4697   __ bind(&stub_call);
4698   __ mov(edx, eax);
4699   __ mov(eax, Immediate(Smi::FromInt(1)));
4700   Handle<Code> code = CodeFactory::BinaryOpIC(isolate(), expr->binary_op(),
4701                                               NO_OVERWRITE).code();
4702   CallIC(code, expr->CountBinOpFeedbackId());
4703   patch_site.EmitPatchInfo();
4704   __ bind(&done);
4705
4706   // Store the value returned in eax.
4707   switch (assign_type) {
4708     case VARIABLE:
4709       if (expr->is_postfix()) {
4710         // Perform the assignment as if via '='.
4711         { EffectContext context(this);
4712           EmitVariableAssignment(expr->expression()->AsVariableProxy()->var(),
4713                                  Token::ASSIGN);
4714           PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
4715           context.Plug(eax);
4716         }
4717         // For all contexts except EffectContext We have the result on
4718         // top of the stack.
4719         if (!context()->IsEffect()) {
4720           context()->PlugTOS();
4721         }
4722       } else {
4723         // Perform the assignment as if via '='.
4724         EmitVariableAssignment(expr->expression()->AsVariableProxy()->var(),
4725                                Token::ASSIGN);
4726         PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
4727         context()->Plug(eax);
4728       }
4729       break;
4730     case NAMED_PROPERTY: {
4731       __ mov(StoreDescriptor::NameRegister(),
4732              prop->key()->AsLiteral()->value());
4733       __ pop(StoreDescriptor::ReceiverRegister());
4734       CallStoreIC(expr->CountStoreFeedbackId());
4735       PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
4736       if (expr->is_postfix()) {
4737         if (!context()->IsEffect()) {
4738           context()->PlugTOS();
4739         }
4740       } else {
4741         context()->Plug(eax);
4742       }
4743       break;
4744     }
4745     case NAMED_SUPER_PROPERTY: {
4746       EmitNamedSuperPropertyStore(prop);
4747       if (expr->is_postfix()) {
4748         if (!context()->IsEffect()) {
4749           context()->PlugTOS();
4750         }
4751       } else {
4752         context()->Plug(eax);
4753       }
4754       break;
4755     }
4756     case KEYED_SUPER_PROPERTY: {
4757       EmitKeyedSuperPropertyStore(prop);
4758       if (expr->is_postfix()) {
4759         if (!context()->IsEffect()) {
4760           context()->PlugTOS();
4761         }
4762       } else {
4763         context()->Plug(eax);
4764       }
4765       break;
4766     }
4767     case KEYED_PROPERTY: {
4768       __ pop(StoreDescriptor::NameRegister());
4769       __ pop(StoreDescriptor::ReceiverRegister());
4770       Handle<Code> ic =
4771           CodeFactory::KeyedStoreIC(isolate(), strict_mode()).code();
4772       CallIC(ic, expr->CountStoreFeedbackId());
4773       PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
4774       if (expr->is_postfix()) {
4775         // Result is on the stack
4776         if (!context()->IsEffect()) {
4777           context()->PlugTOS();
4778         }
4779       } else {
4780         context()->Plug(eax);
4781       }
4782       break;
4783     }
4784   }
4785 }
4786
4787
4788 void FullCodeGenerator::VisitForTypeofValue(Expression* expr) {
4789   VariableProxy* proxy = expr->AsVariableProxy();
4790   DCHECK(!context()->IsEffect());
4791   DCHECK(!context()->IsTest());
4792
4793   if (proxy != NULL && proxy->var()->IsUnallocated()) {
4794     Comment cmnt(masm_, "[ Global variable");
4795     __ mov(LoadDescriptor::ReceiverRegister(), GlobalObjectOperand());
4796     __ mov(LoadDescriptor::NameRegister(), Immediate(proxy->name()));
4797     if (FLAG_vector_ics) {
4798       __ mov(VectorLoadICDescriptor::SlotRegister(),
4799              Immediate(SmiFromSlot(proxy->VariableFeedbackSlot())));
4800     }
4801     // Use a regular load, not a contextual load, to avoid a reference
4802     // error.
4803     CallLoadIC(NOT_CONTEXTUAL);
4804     PrepareForBailout(expr, TOS_REG);
4805     context()->Plug(eax);
4806   } else if (proxy != NULL && proxy->var()->IsLookupSlot()) {
4807     Comment cmnt(masm_, "[ Lookup slot");
4808     Label done, slow;
4809
4810     // Generate code for loading from variables potentially shadowed
4811     // by eval-introduced variables.
4812     EmitDynamicLookupFastCase(proxy, INSIDE_TYPEOF, &slow, &done);
4813
4814     __ bind(&slow);
4815     __ push(esi);
4816     __ push(Immediate(proxy->name()));
4817     __ CallRuntime(Runtime::kLoadLookupSlotNoReferenceError, 2);
4818     PrepareForBailout(expr, TOS_REG);
4819     __ bind(&done);
4820
4821     context()->Plug(eax);
4822   } else {
4823     // This expression cannot throw a reference error at the top level.
4824     VisitInDuplicateContext(expr);
4825   }
4826 }
4827
4828
4829 void FullCodeGenerator::EmitLiteralCompareTypeof(Expression* expr,
4830                                                  Expression* sub_expr,
4831                                                  Handle<String> check) {
4832   Label materialize_true, materialize_false;
4833   Label* if_true = NULL;
4834   Label* if_false = NULL;
4835   Label* fall_through = NULL;
4836   context()->PrepareTest(&materialize_true, &materialize_false,
4837                          &if_true, &if_false, &fall_through);
4838
4839   { AccumulatorValueContext context(this);
4840     VisitForTypeofValue(sub_expr);
4841   }
4842   PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
4843
4844   Factory* factory = isolate()->factory();
4845   if (String::Equals(check, factory->number_string())) {
4846     __ JumpIfSmi(eax, if_true);
4847     __ cmp(FieldOperand(eax, HeapObject::kMapOffset),
4848            isolate()->factory()->heap_number_map());
4849     Split(equal, if_true, if_false, fall_through);
4850   } else if (String::Equals(check, factory->string_string())) {
4851     __ JumpIfSmi(eax, if_false);
4852     __ CmpObjectType(eax, FIRST_NONSTRING_TYPE, edx);
4853     __ j(above_equal, if_false);
4854     // Check for undetectable objects => false.
4855     __ test_b(FieldOperand(edx, Map::kBitFieldOffset),
4856               1 << Map::kIsUndetectable);
4857     Split(zero, if_true, if_false, fall_through);
4858   } else if (String::Equals(check, factory->symbol_string())) {
4859     __ JumpIfSmi(eax, if_false);
4860     __ CmpObjectType(eax, SYMBOL_TYPE, edx);
4861     Split(equal, if_true, if_false, fall_through);
4862   } else if (String::Equals(check, factory->boolean_string())) {
4863     __ cmp(eax, isolate()->factory()->true_value());
4864     __ j(equal, if_true);
4865     __ cmp(eax, isolate()->factory()->false_value());
4866     Split(equal, if_true, if_false, fall_through);
4867   } else if (String::Equals(check, factory->undefined_string())) {
4868     __ cmp(eax, isolate()->factory()->undefined_value());
4869     __ j(equal, if_true);
4870     __ JumpIfSmi(eax, if_false);
4871     // Check for undetectable objects => true.
4872     __ mov(edx, FieldOperand(eax, HeapObject::kMapOffset));
4873     __ movzx_b(ecx, FieldOperand(edx, Map::kBitFieldOffset));
4874     __ test(ecx, Immediate(1 << Map::kIsUndetectable));
4875     Split(not_zero, if_true, if_false, fall_through);
4876   } else if (String::Equals(check, factory->function_string())) {
4877     __ JumpIfSmi(eax, if_false);
4878     STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
4879     __ CmpObjectType(eax, JS_FUNCTION_TYPE, edx);
4880     __ j(equal, if_true);
4881     __ CmpInstanceType(edx, JS_FUNCTION_PROXY_TYPE);
4882     Split(equal, if_true, if_false, fall_through);
4883   } else if (String::Equals(check, factory->object_string())) {
4884     __ JumpIfSmi(eax, if_false);
4885     __ cmp(eax, isolate()->factory()->null_value());
4886     __ j(equal, if_true);
4887     __ CmpObjectType(eax, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE, edx);
4888     __ j(below, if_false);
4889     __ CmpInstanceType(edx, LAST_NONCALLABLE_SPEC_OBJECT_TYPE);
4890     __ j(above, if_false);
4891     // Check for undetectable objects => false.
4892     __ test_b(FieldOperand(edx, Map::kBitFieldOffset),
4893               1 << Map::kIsUndetectable);
4894     Split(zero, if_true, if_false, fall_through);
4895   } else {
4896     if (if_false != fall_through) __ jmp(if_false);
4897   }
4898   context()->Plug(if_true, if_false);
4899 }
4900
4901
4902 void FullCodeGenerator::VisitCompareOperation(CompareOperation* expr) {
4903   Comment cmnt(masm_, "[ CompareOperation");
4904   SetSourcePosition(expr->position());
4905
4906   // First we try a fast inlined version of the compare when one of
4907   // the operands is a literal.
4908   if (TryLiteralCompare(expr)) return;
4909
4910   // Always perform the comparison for its control flow.  Pack the result
4911   // into the expression's context after the comparison is performed.
4912   Label materialize_true, materialize_false;
4913   Label* if_true = NULL;
4914   Label* if_false = NULL;
4915   Label* fall_through = NULL;
4916   context()->PrepareTest(&materialize_true, &materialize_false,
4917                          &if_true, &if_false, &fall_through);
4918
4919   Token::Value op = expr->op();
4920   VisitForStackValue(expr->left());
4921   switch (op) {
4922     case Token::IN:
4923       VisitForStackValue(expr->right());
4924       __ InvokeBuiltin(Builtins::IN, CALL_FUNCTION);
4925       PrepareForBailoutBeforeSplit(expr, false, NULL, NULL);
4926       __ cmp(eax, isolate()->factory()->true_value());
4927       Split(equal, if_true, if_false, fall_through);
4928       break;
4929
4930     case Token::INSTANCEOF: {
4931       VisitForStackValue(expr->right());
4932       InstanceofStub stub(isolate(), InstanceofStub::kNoFlags);
4933       __ CallStub(&stub);
4934       PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
4935       __ test(eax, eax);
4936       // The stub returns 0 for true.
4937       Split(zero, if_true, if_false, fall_through);
4938       break;
4939     }
4940
4941     default: {
4942       VisitForAccumulatorValue(expr->right());
4943       Condition cc = CompareIC::ComputeCondition(op);
4944       __ pop(edx);
4945
4946       bool inline_smi_code = ShouldInlineSmiCase(op);
4947       JumpPatchSite patch_site(masm_);
4948       if (inline_smi_code) {
4949         Label slow_case;
4950         __ mov(ecx, edx);
4951         __ or_(ecx, eax);
4952         patch_site.EmitJumpIfNotSmi(ecx, &slow_case, Label::kNear);
4953         __ cmp(edx, eax);
4954         Split(cc, if_true, if_false, NULL);
4955         __ bind(&slow_case);
4956       }
4957
4958       // Record position and call the compare IC.
4959       SetSourcePosition(expr->position());
4960       Handle<Code> ic = CodeFactory::CompareIC(isolate(), op).code();
4961       CallIC(ic, expr->CompareOperationFeedbackId());
4962       patch_site.EmitPatchInfo();
4963
4964       PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
4965       __ test(eax, eax);
4966       Split(cc, if_true, if_false, fall_through);
4967     }
4968   }
4969
4970   // Convert the result of the comparison into one expected for this
4971   // expression's context.
4972   context()->Plug(if_true, if_false);
4973 }
4974
4975
4976 void FullCodeGenerator::EmitLiteralCompareNil(CompareOperation* expr,
4977                                               Expression* sub_expr,
4978                                               NilValue nil) {
4979   Label materialize_true, materialize_false;
4980   Label* if_true = NULL;
4981   Label* if_false = NULL;
4982   Label* fall_through = NULL;
4983   context()->PrepareTest(&materialize_true, &materialize_false,
4984                          &if_true, &if_false, &fall_through);
4985
4986   VisitForAccumulatorValue(sub_expr);
4987   PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
4988
4989   Handle<Object> nil_value = nil == kNullValue
4990       ? isolate()->factory()->null_value()
4991       : isolate()->factory()->undefined_value();
4992   if (expr->op() == Token::EQ_STRICT) {
4993     __ cmp(eax, nil_value);
4994     Split(equal, if_true, if_false, fall_through);
4995   } else {
4996     Handle<Code> ic = CompareNilICStub::GetUninitialized(isolate(), nil);
4997     CallIC(ic, expr->CompareOperationFeedbackId());
4998     __ test(eax, eax);
4999     Split(not_zero, if_true, if_false, fall_through);
5000   }
5001   context()->Plug(if_true, if_false);
5002 }
5003
5004
5005 void FullCodeGenerator::VisitThisFunction(ThisFunction* expr) {
5006   __ mov(eax, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
5007   context()->Plug(eax);
5008 }
5009
5010
5011 Register FullCodeGenerator::result_register() {
5012   return eax;
5013 }
5014
5015
5016 Register FullCodeGenerator::context_register() {
5017   return esi;
5018 }
5019
5020
5021 void FullCodeGenerator::StoreToFrameField(int frame_offset, Register value) {
5022   DCHECK_EQ(POINTER_SIZE_ALIGN(frame_offset), frame_offset);
5023   __ mov(Operand(ebp, frame_offset), value);
5024 }
5025
5026
5027 void FullCodeGenerator::LoadContextField(Register dst, int context_index) {
5028   __ mov(dst, ContextOperand(esi, context_index));
5029 }
5030
5031
5032 void FullCodeGenerator::PushFunctionArgumentForContextAllocation() {
5033   Scope* declaration_scope = scope()->DeclarationScope();
5034   if (declaration_scope->is_global_scope() ||
5035       declaration_scope->is_module_scope()) {
5036     // Contexts nested in the native context have a canonical empty function
5037     // as their closure, not the anonymous closure containing the global
5038     // code.  Pass a smi sentinel and let the runtime look up the empty
5039     // function.
5040     __ push(Immediate(Smi::FromInt(0)));
5041   } else if (declaration_scope->is_eval_scope()) {
5042     // Contexts nested inside eval code have the same closure as the context
5043     // calling eval, not the anonymous closure containing the eval code.
5044     // Fetch it from the context.
5045     __ push(ContextOperand(esi, Context::CLOSURE_INDEX));
5046   } else {
5047     DCHECK(declaration_scope->is_function_scope());
5048     __ push(Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
5049   }
5050 }
5051
5052
5053 // ----------------------------------------------------------------------------
5054 // Non-local control flow support.
5055
5056 void FullCodeGenerator::EnterFinallyBlock() {
5057   // Cook return address on top of stack (smi encoded Code* delta)
5058   DCHECK(!result_register().is(edx));
5059   __ pop(edx);
5060   __ sub(edx, Immediate(masm_->CodeObject()));
5061   STATIC_ASSERT(kSmiTagSize + kSmiShiftSize == 1);
5062   STATIC_ASSERT(kSmiTag == 0);
5063   __ SmiTag(edx);
5064   __ push(edx);
5065
5066   // Store result register while executing finally block.
5067   __ push(result_register());
5068
5069   // Store pending message while executing finally block.
5070   ExternalReference pending_message_obj =
5071       ExternalReference::address_of_pending_message_obj(isolate());
5072   __ mov(edx, Operand::StaticVariable(pending_message_obj));
5073   __ push(edx);
5074
5075   ExternalReference has_pending_message =
5076       ExternalReference::address_of_has_pending_message(isolate());
5077   __ mov(edx, Operand::StaticVariable(has_pending_message));
5078   __ SmiTag(edx);
5079   __ push(edx);
5080
5081   ExternalReference pending_message_script =
5082       ExternalReference::address_of_pending_message_script(isolate());
5083   __ mov(edx, Operand::StaticVariable(pending_message_script));
5084   __ push(edx);
5085 }
5086
5087
5088 void FullCodeGenerator::ExitFinallyBlock() {
5089   DCHECK(!result_register().is(edx));
5090   // Restore pending message from stack.
5091   __ pop(edx);
5092   ExternalReference pending_message_script =
5093       ExternalReference::address_of_pending_message_script(isolate());
5094   __ mov(Operand::StaticVariable(pending_message_script), edx);
5095
5096   __ pop(edx);
5097   __ SmiUntag(edx);
5098   ExternalReference has_pending_message =
5099       ExternalReference::address_of_has_pending_message(isolate());
5100   __ mov(Operand::StaticVariable(has_pending_message), edx);
5101
5102   __ pop(edx);
5103   ExternalReference pending_message_obj =
5104       ExternalReference::address_of_pending_message_obj(isolate());
5105   __ mov(Operand::StaticVariable(pending_message_obj), edx);
5106
5107   // Restore result register from stack.
5108   __ pop(result_register());
5109
5110   // Uncook return address.
5111   __ pop(edx);
5112   __ SmiUntag(edx);
5113   __ add(edx, Immediate(masm_->CodeObject()));
5114   __ jmp(edx);
5115 }
5116
5117
5118 #undef __
5119
5120 #define __ ACCESS_MASM(masm())
5121
5122 FullCodeGenerator::NestedStatement* FullCodeGenerator::TryFinally::Exit(
5123     int* stack_depth,
5124     int* context_length) {
5125   // The macros used here must preserve the result register.
5126
5127   // Because the handler block contains the context of the finally
5128   // code, we can restore it directly from there for the finally code
5129   // rather than iteratively unwinding contexts via their previous
5130   // links.
5131   __ Drop(*stack_depth);  // Down to the handler block.
5132   if (*context_length > 0) {
5133     // Restore the context to its dedicated register and the stack.
5134     __ mov(esi, Operand(esp, StackHandlerConstants::kContextOffset));
5135     __ mov(Operand(ebp, StandardFrameConstants::kContextOffset), esi);
5136   }
5137   __ PopTryHandler();
5138   __ call(finally_entry_);
5139
5140   *stack_depth = 0;
5141   *context_length = 0;
5142   return previous_;
5143 }
5144
5145 #undef __
5146
5147
5148 static const byte kJnsInstruction = 0x79;
5149 static const byte kJnsOffset = 0x11;
5150 static const byte kNopByteOne = 0x66;
5151 static const byte kNopByteTwo = 0x90;
5152 #ifdef DEBUG
5153 static const byte kCallInstruction = 0xe8;
5154 #endif
5155
5156
5157 void BackEdgeTable::PatchAt(Code* unoptimized_code,
5158                             Address pc,
5159                             BackEdgeState target_state,
5160                             Code* replacement_code) {
5161   Address call_target_address = pc - kIntSize;
5162   Address jns_instr_address = call_target_address - 3;
5163   Address jns_offset_address = call_target_address - 2;
5164
5165   switch (target_state) {
5166     case INTERRUPT:
5167       //     sub <profiling_counter>, <delta>  ;; Not changed
5168       //     jns ok
5169       //     call <interrupt stub>
5170       //   ok:
5171       *jns_instr_address = kJnsInstruction;
5172       *jns_offset_address = kJnsOffset;
5173       break;
5174     case ON_STACK_REPLACEMENT:
5175     case OSR_AFTER_STACK_CHECK:
5176       //     sub <profiling_counter>, <delta>  ;; Not changed
5177       //     nop
5178       //     nop
5179       //     call <on-stack replacment>
5180       //   ok:
5181       *jns_instr_address = kNopByteOne;
5182       *jns_offset_address = kNopByteTwo;
5183       break;
5184   }
5185
5186   Assembler::set_target_address_at(call_target_address,
5187                                    unoptimized_code,
5188                                    replacement_code->entry());
5189   unoptimized_code->GetHeap()->incremental_marking()->RecordCodeTargetPatch(
5190       unoptimized_code, call_target_address, replacement_code);
5191 }
5192
5193
5194 BackEdgeTable::BackEdgeState BackEdgeTable::GetBackEdgeState(
5195     Isolate* isolate,
5196     Code* unoptimized_code,
5197     Address pc) {
5198   Address call_target_address = pc - kIntSize;
5199   Address jns_instr_address = call_target_address - 3;
5200   DCHECK_EQ(kCallInstruction, *(call_target_address - 1));
5201
5202   if (*jns_instr_address == kJnsInstruction) {
5203     DCHECK_EQ(kJnsOffset, *(call_target_address - 2));
5204     DCHECK_EQ(isolate->builtins()->InterruptCheck()->entry(),
5205               Assembler::target_address_at(call_target_address,
5206                                            unoptimized_code));
5207     return INTERRUPT;
5208   }
5209
5210   DCHECK_EQ(kNopByteOne, *jns_instr_address);
5211   DCHECK_EQ(kNopByteTwo, *(call_target_address - 2));
5212
5213   if (Assembler::target_address_at(call_target_address, unoptimized_code) ==
5214       isolate->builtins()->OnStackReplacement()->entry()) {
5215     return ON_STACK_REPLACEMENT;
5216   }
5217
5218   DCHECK_EQ(isolate->builtins()->OsrAfterStackCheck()->entry(),
5219             Assembler::target_address_at(call_target_address,
5220                                          unoptimized_code));
5221   return OSR_AFTER_STACK_CHECK;
5222 }
5223
5224
5225 } }  // namespace v8::internal
5226
5227 #endif  // V8_TARGET_ARCH_IA32