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