deps: update v8 to 4.3.61.21
[platform/upstream/nodejs.git] / deps / v8 / src / x87 / lithium-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/base/bits.h"
10 #include "src/code-factory.h"
11 #include "src/code-stubs.h"
12 #include "src/codegen.h"
13 #include "src/cpu-profiler.h"
14 #include "src/deoptimizer.h"
15 #include "src/hydrogen-osr.h"
16 #include "src/ic/ic.h"
17 #include "src/ic/stub-cache.h"
18 #include "src/x87/lithium-codegen-x87.h"
19
20 namespace v8 {
21 namespace internal {
22
23
24 // When invoking builtins, we need to record the safepoint in the middle of
25 // the invoke instruction sequence generated by the macro assembler.
26 class SafepointGenerator FINAL : public CallWrapper {
27  public:
28   SafepointGenerator(LCodeGen* codegen,
29                      LPointerMap* pointers,
30                      Safepoint::DeoptMode mode)
31       : codegen_(codegen),
32         pointers_(pointers),
33         deopt_mode_(mode) {}
34   virtual ~SafepointGenerator() {}
35
36   void BeforeCall(int call_size) const OVERRIDE {}
37
38   void AfterCall() const OVERRIDE {
39     codegen_->RecordSafepoint(pointers_, deopt_mode_);
40   }
41
42  private:
43   LCodeGen* codegen_;
44   LPointerMap* pointers_;
45   Safepoint::DeoptMode deopt_mode_;
46 };
47
48
49 #define __ masm()->
50
51 bool LCodeGen::GenerateCode() {
52   LPhase phase("Z_Code generation", chunk());
53   DCHECK(is_unused());
54   status_ = GENERATING;
55
56   // Open a frame scope to indicate that there is a frame on the stack.  The
57   // MANUAL indicates that the scope shouldn't actually generate code to set up
58   // the frame (that is done in GeneratePrologue).
59   FrameScope frame_scope(masm_, StackFrame::MANUAL);
60
61   support_aligned_spilled_doubles_ = info()->IsOptimizing();
62
63   dynamic_frame_alignment_ = info()->IsOptimizing() &&
64       ((chunk()->num_double_slots() > 2 &&
65         !chunk()->graph()->is_recursive()) ||
66        !info()->osr_ast_id().IsNone());
67
68   return GeneratePrologue() &&
69       GenerateBody() &&
70       GenerateDeferredCode() &&
71       GenerateJumpTable() &&
72       GenerateSafepointTable();
73 }
74
75
76 void LCodeGen::FinishCode(Handle<Code> code) {
77   DCHECK(is_done());
78   code->set_stack_slots(GetStackSlotCount());
79   code->set_safepoint_table_offset(safepoints_.GetCodeOffset());
80   PopulateDeoptimizationData(code);
81   if (!info()->IsStub()) {
82     Deoptimizer::EnsureRelocSpaceForLazyDeoptimization(code);
83   }
84 }
85
86
87 #ifdef _MSC_VER
88 void LCodeGen::MakeSureStackPagesMapped(int offset) {
89   const int kPageSize = 4 * KB;
90   for (offset -= kPageSize; offset > 0; offset -= kPageSize) {
91     __ mov(Operand(esp, offset), eax);
92   }
93 }
94 #endif
95
96
97 bool LCodeGen::GeneratePrologue() {
98   DCHECK(is_generating());
99
100   if (info()->IsOptimizing()) {
101     ProfileEntryHookStub::MaybeCallEntryHook(masm_);
102
103 #ifdef DEBUG
104     if (strlen(FLAG_stop_at) > 0 &&
105         info_->function()->name()->IsUtf8EqualTo(CStrVector(FLAG_stop_at))) {
106       __ int3();
107     }
108 #endif
109
110     // Sloppy mode functions and builtins need to replace the receiver with the
111     // global proxy when called as functions (without an explicit receiver
112     // object).
113     if (graph()->this_has_uses() && is_sloppy(info_->language_mode()) &&
114         !info_->is_native()) {
115       Label ok;
116       // +1 for return address.
117       int receiver_offset = (scope()->num_parameters() + 1) * kPointerSize;
118       __ mov(ecx, Operand(esp, receiver_offset));
119
120       __ cmp(ecx, isolate()->factory()->undefined_value());
121       __ j(not_equal, &ok, Label::kNear);
122
123       __ mov(ecx, GlobalObjectOperand());
124       __ mov(ecx, FieldOperand(ecx, GlobalObject::kGlobalProxyOffset));
125
126       __ mov(Operand(esp, receiver_offset), ecx);
127
128       __ bind(&ok);
129     }
130
131     if (support_aligned_spilled_doubles_ && dynamic_frame_alignment_) {
132       // Move state of dynamic frame alignment into edx.
133       __ Move(edx, Immediate(kNoAlignmentPadding));
134
135       Label do_not_pad, align_loop;
136       STATIC_ASSERT(kDoubleSize == 2 * kPointerSize);
137       // Align esp + 4 to a multiple of 2 * kPointerSize.
138       __ test(esp, Immediate(kPointerSize));
139       __ j(not_zero, &do_not_pad, Label::kNear);
140       __ push(Immediate(0));
141       __ mov(ebx, esp);
142       __ mov(edx, Immediate(kAlignmentPaddingPushed));
143       // Copy arguments, receiver, and return address.
144       __ mov(ecx, Immediate(scope()->num_parameters() + 2));
145
146       __ bind(&align_loop);
147       __ mov(eax, Operand(ebx, 1 * kPointerSize));
148       __ mov(Operand(ebx, 0), eax);
149       __ add(Operand(ebx), Immediate(kPointerSize));
150       __ dec(ecx);
151       __ j(not_zero, &align_loop, Label::kNear);
152       __ mov(Operand(ebx, 0), Immediate(kAlignmentZapValue));
153       __ bind(&do_not_pad);
154     }
155   }
156
157   info()->set_prologue_offset(masm_->pc_offset());
158   if (NeedsEagerFrame()) {
159     DCHECK(!frame_is_built_);
160     frame_is_built_ = true;
161     if (info()->IsStub()) {
162       __ StubPrologue();
163     } else {
164       __ Prologue(info()->IsCodePreAgingActive());
165     }
166     info()->AddNoFrameRange(0, masm_->pc_offset());
167   }
168
169   if (info()->IsOptimizing() &&
170       dynamic_frame_alignment_ &&
171       FLAG_debug_code) {
172     __ test(esp, Immediate(kPointerSize));
173     __ Assert(zero, kFrameIsExpectedToBeAligned);
174   }
175
176   // Reserve space for the stack slots needed by the code.
177   int slots = GetStackSlotCount();
178   DCHECK(slots != 0 || !info()->IsOptimizing());
179   if (slots > 0) {
180     if (slots == 1) {
181       if (dynamic_frame_alignment_) {
182         __ push(edx);
183       } else {
184         __ push(Immediate(kNoAlignmentPadding));
185       }
186     } else {
187       if (FLAG_debug_code) {
188         __ sub(Operand(esp), Immediate(slots * kPointerSize));
189 #ifdef _MSC_VER
190         MakeSureStackPagesMapped(slots * kPointerSize);
191 #endif
192         __ push(eax);
193         __ mov(Operand(eax), Immediate(slots));
194         Label loop;
195         __ bind(&loop);
196         __ mov(MemOperand(esp, eax, times_4, 0),
197                Immediate(kSlotsZapValue));
198         __ dec(eax);
199         __ j(not_zero, &loop);
200         __ pop(eax);
201       } else {
202         __ sub(Operand(esp), Immediate(slots * kPointerSize));
203 #ifdef _MSC_VER
204         MakeSureStackPagesMapped(slots * kPointerSize);
205 #endif
206       }
207
208       if (support_aligned_spilled_doubles_) {
209         Comment(";;; Store dynamic frame alignment tag for spilled doubles");
210         // Store dynamic frame alignment state in the first local.
211         int offset = JavaScriptFrameConstants::kDynamicAlignmentStateOffset;
212         if (dynamic_frame_alignment_) {
213           __ mov(Operand(ebp, offset), edx);
214         } else {
215           __ mov(Operand(ebp, offset), Immediate(kNoAlignmentPadding));
216         }
217       }
218     }
219   }
220
221   // Possibly allocate a local context.
222   int heap_slots = info_->num_heap_slots() - Context::MIN_CONTEXT_SLOTS;
223   if (heap_slots > 0) {
224     Comment(";;; Allocate local context");
225     bool need_write_barrier = true;
226     // Argument to NewContext is the function, which is still in edi.
227     if (heap_slots <= FastNewContextStub::kMaximumSlots) {
228       FastNewContextStub stub(isolate(), heap_slots);
229       __ CallStub(&stub);
230       // Result of FastNewContextStub is always in new space.
231       need_write_barrier = false;
232     } else {
233       __ push(edi);
234       __ CallRuntime(Runtime::kNewFunctionContext, 1);
235     }
236     RecordSafepoint(Safepoint::kNoLazyDeopt);
237     // Context is returned in eax.  It replaces the context passed to us.
238     // It's saved in the stack and kept live in esi.
239     __ mov(esi, eax);
240     __ mov(Operand(ebp, StandardFrameConstants::kContextOffset), eax);
241
242     // Copy parameters into context if necessary.
243     int num_parameters = scope()->num_parameters();
244     for (int i = 0; i < num_parameters; i++) {
245       Variable* var = scope()->parameter(i);
246       if (var->IsContextSlot()) {
247         int parameter_offset = StandardFrameConstants::kCallerSPOffset +
248             (num_parameters - 1 - i) * kPointerSize;
249         // Load parameter from stack.
250         __ mov(eax, Operand(ebp, parameter_offset));
251         // Store it in the context.
252         int context_offset = Context::SlotOffset(var->index());
253         __ mov(Operand(esi, context_offset), eax);
254         // Update the write barrier. This clobbers eax and ebx.
255         if (need_write_barrier) {
256           __ RecordWriteContextSlot(esi, context_offset, eax, ebx,
257                                     kDontSaveFPRegs);
258         } else if (FLAG_debug_code) {
259           Label done;
260           __ JumpIfInNewSpace(esi, eax, &done, Label::kNear);
261           __ Abort(kExpectedNewSpaceObject);
262           __ bind(&done);
263         }
264       }
265     }
266     Comment(";;; End allocate local context");
267   }
268
269   // Initailize FPU state.
270   __ fninit();
271   // Trace the call.
272   if (FLAG_trace && info()->IsOptimizing()) {
273     // We have not executed any compiled code yet, so esi still holds the
274     // incoming context.
275     __ CallRuntime(Runtime::kTraceEnter, 0);
276   }
277   return !is_aborted();
278 }
279
280
281 void LCodeGen::GenerateOsrPrologue() {
282   // Generate the OSR entry prologue at the first unknown OSR value, or if there
283   // are none, at the OSR entrypoint instruction.
284   if (osr_pc_offset_ >= 0) return;
285
286   osr_pc_offset_ = masm()->pc_offset();
287
288     // Move state of dynamic frame alignment into edx.
289   __ Move(edx, Immediate(kNoAlignmentPadding));
290
291   if (support_aligned_spilled_doubles_ && dynamic_frame_alignment_) {
292     Label do_not_pad, align_loop;
293     // Align ebp + 4 to a multiple of 2 * kPointerSize.
294     __ test(ebp, Immediate(kPointerSize));
295     __ j(zero, &do_not_pad, Label::kNear);
296     __ push(Immediate(0));
297     __ mov(ebx, esp);
298     __ mov(edx, Immediate(kAlignmentPaddingPushed));
299
300     // Move all parts of the frame over one word. The frame consists of:
301     // unoptimized frame slots, alignment state, context, frame pointer, return
302     // address, receiver, and the arguments.
303     __ mov(ecx, Immediate(scope()->num_parameters() +
304            5 + graph()->osr()->UnoptimizedFrameSlots()));
305
306     __ bind(&align_loop);
307     __ mov(eax, Operand(ebx, 1 * kPointerSize));
308     __ mov(Operand(ebx, 0), eax);
309     __ add(Operand(ebx), Immediate(kPointerSize));
310     __ dec(ecx);
311     __ j(not_zero, &align_loop, Label::kNear);
312     __ mov(Operand(ebx, 0), Immediate(kAlignmentZapValue));
313     __ sub(Operand(ebp), Immediate(kPointerSize));
314     __ bind(&do_not_pad);
315   }
316
317   // Save the first local, which is overwritten by the alignment state.
318   Operand alignment_loc = MemOperand(ebp, -3 * kPointerSize);
319   __ push(alignment_loc);
320
321   // Set the dynamic frame alignment state.
322   __ mov(alignment_loc, edx);
323
324   // Adjust the frame size, subsuming the unoptimized frame into the
325   // optimized frame.
326   int slots = GetStackSlotCount() - graph()->osr()->UnoptimizedFrameSlots();
327   DCHECK(slots >= 1);
328   __ sub(esp, Immediate((slots - 1) * kPointerSize));
329
330   // Initailize FPU state.
331   __ fninit();
332 }
333
334
335 void LCodeGen::GenerateBodyInstructionPre(LInstruction* instr) {
336   if (instr->IsCall()) {
337     EnsureSpaceForLazyDeopt(Deoptimizer::patch_size());
338   }
339   if (!instr->IsLazyBailout() && !instr->IsGap()) {
340     safepoints_.BumpLastLazySafepointIndex();
341   }
342   FlushX87StackIfNecessary(instr);
343 }
344
345
346 void LCodeGen::GenerateBodyInstructionPost(LInstruction* instr) {
347   // When return from function call, FPU should be initialized again.
348   if (instr->IsCall() && instr->ClobbersDoubleRegisters(isolate())) {
349     bool double_result = instr->HasDoubleRegisterResult();
350     if (double_result) {
351       __ lea(esp, Operand(esp, -kDoubleSize));
352       __ fstp_d(Operand(esp, 0));
353     }
354     __ fninit();
355     if (double_result) {
356       __ fld_d(Operand(esp, 0));
357       __ lea(esp, Operand(esp, kDoubleSize));
358     }
359   }
360   if (instr->IsGoto()) {
361     x87_stack_.LeavingBlock(current_block_, LGoto::cast(instr), this);
362   } else if (FLAG_debug_code && FLAG_enable_slow_asserts &&
363              !instr->IsGap() && !instr->IsReturn()) {
364     if (instr->ClobbersDoubleRegisters(isolate())) {
365       if (instr->HasDoubleRegisterResult()) {
366         DCHECK_EQ(1, x87_stack_.depth());
367       } else {
368         DCHECK_EQ(0, x87_stack_.depth());
369       }
370     }
371     __ VerifyX87StackDepth(x87_stack_.depth());
372   }
373 }
374
375
376 bool LCodeGen::GenerateJumpTable() {
377   if (!jump_table_.length()) return !is_aborted();
378
379   Label needs_frame;
380   Comment(";;; -------------------- Jump table --------------------");
381
382   for (int i = 0; i < jump_table_.length(); i++) {
383     Deoptimizer::JumpTableEntry* table_entry = &jump_table_[i];
384     __ bind(&table_entry->label);
385     Address entry = table_entry->address;
386     DeoptComment(table_entry->deopt_info);
387     if (table_entry->needs_frame) {
388       DCHECK(!info()->saves_caller_doubles());
389       __ push(Immediate(ExternalReference::ForDeoptEntry(entry)));
390       __ call(&needs_frame);
391     } else {
392       __ call(entry, RelocInfo::RUNTIME_ENTRY);
393     }
394     info()->LogDeoptCallPosition(masm()->pc_offset(),
395                                  table_entry->deopt_info.inlining_id);
396   }
397   if (needs_frame.is_linked()) {
398     __ bind(&needs_frame);
399
400     /* stack layout
401        4: entry address
402        3: return address  <-- esp
403        2: garbage
404        1: garbage
405        0: garbage
406     */
407     __ sub(esp, Immediate(kPointerSize));    // Reserve space for stub marker.
408     __ push(MemOperand(esp, kPointerSize));  // Copy return address.
409     __ push(MemOperand(esp, 3 * kPointerSize));  // Copy entry address.
410
411     /* stack layout
412        4: entry address
413        3: return address
414        2: garbage
415        1: return address
416        0: entry address  <-- esp
417     */
418     __ mov(MemOperand(esp, 4 * kPointerSize), ebp);  // Save ebp.
419
420     // Copy context.
421     __ mov(ebp, MemOperand(ebp, StandardFrameConstants::kContextOffset));
422     __ mov(MemOperand(esp, 3 * kPointerSize), ebp);
423     // Fill ebp with the right stack frame address.
424     __ lea(ebp, MemOperand(esp, 4 * kPointerSize));
425
426     // This variant of deopt can only be used with stubs. Since we don't
427     // have a function pointer to install in the stack frame that we're
428     // building, install a special marker there instead.
429     DCHECK(info()->IsStub());
430     __ mov(MemOperand(esp, 2 * kPointerSize),
431            Immediate(Smi::FromInt(StackFrame::STUB)));
432
433     /* stack layout
434        4: old ebp
435        3: context pointer
436        2: stub marker
437        1: return address
438        0: entry address  <-- esp
439     */
440     __ ret(0);  // Call the continuation without clobbering registers.
441   }
442   return !is_aborted();
443 }
444
445
446 bool LCodeGen::GenerateDeferredCode() {
447   DCHECK(is_generating());
448   if (deferred_.length() > 0) {
449     for (int i = 0; !is_aborted() && i < deferred_.length(); i++) {
450       LDeferredCode* code = deferred_[i];
451       X87Stack copy(code->x87_stack());
452       x87_stack_ = copy;
453
454       HValue* value =
455           instructions_->at(code->instruction_index())->hydrogen_value();
456       RecordAndWritePosition(
457           chunk()->graph()->SourcePositionToScriptPosition(value->position()));
458
459       Comment(";;; <@%d,#%d> "
460               "-------------------- Deferred %s --------------------",
461               code->instruction_index(),
462               code->instr()->hydrogen_value()->id(),
463               code->instr()->Mnemonic());
464       __ bind(code->entry());
465       if (NeedsDeferredFrame()) {
466         Comment(";;; Build frame");
467         DCHECK(!frame_is_built_);
468         DCHECK(info()->IsStub());
469         frame_is_built_ = true;
470         // Build the frame in such a way that esi isn't trashed.
471         __ push(ebp);  // Caller's frame pointer.
472         __ push(Operand(ebp, StandardFrameConstants::kContextOffset));
473         __ push(Immediate(Smi::FromInt(StackFrame::STUB)));
474         __ lea(ebp, Operand(esp, 2 * kPointerSize));
475         Comment(";;; Deferred code");
476       }
477       code->Generate();
478       if (NeedsDeferredFrame()) {
479         __ bind(code->done());
480         Comment(";;; Destroy frame");
481         DCHECK(frame_is_built_);
482         frame_is_built_ = false;
483         __ mov(esp, ebp);
484         __ pop(ebp);
485       }
486       __ jmp(code->exit());
487     }
488   }
489
490   // Deferred code is the last part of the instruction sequence. Mark
491   // the generated code as done unless we bailed out.
492   if (!is_aborted()) status_ = DONE;
493   return !is_aborted();
494 }
495
496
497 bool LCodeGen::GenerateSafepointTable() {
498   DCHECK(is_done());
499   if (!info()->IsStub()) {
500     // For lazy deoptimization we need space to patch a call after every call.
501     // Ensure there is always space for such patching, even if the code ends
502     // in a call.
503     int target_offset = masm()->pc_offset() + Deoptimizer::patch_size();
504     while (masm()->pc_offset() < target_offset) {
505       masm()->nop();
506     }
507   }
508   safepoints_.Emit(masm(), GetStackSlotCount());
509   return !is_aborted();
510 }
511
512
513 Register LCodeGen::ToRegister(int index) const {
514   return Register::FromAllocationIndex(index);
515 }
516
517
518 X87Register LCodeGen::ToX87Register(int index) const {
519   return X87Register::FromAllocationIndex(index);
520 }
521
522
523 void LCodeGen::X87LoadForUsage(X87Register reg) {
524   DCHECK(x87_stack_.Contains(reg));
525   x87_stack_.Fxch(reg);
526   x87_stack_.pop();
527 }
528
529
530 void LCodeGen::X87LoadForUsage(X87Register reg1, X87Register reg2) {
531   DCHECK(x87_stack_.Contains(reg1));
532   DCHECK(x87_stack_.Contains(reg2));
533   if (reg1.is(reg2) && x87_stack_.depth() == 1) {
534     __ fld(x87_stack_.st(reg1));
535     x87_stack_.push(reg1);
536     x87_stack_.pop();
537     x87_stack_.pop();
538   } else {
539     x87_stack_.Fxch(reg1, 1);
540     x87_stack_.Fxch(reg2);
541     x87_stack_.pop();
542     x87_stack_.pop();
543   }
544 }
545
546
547 int LCodeGen::X87Stack::GetLayout() {
548   int layout = stack_depth_;
549   for (int i = 0; i < stack_depth_; i++) {
550     layout |= (stack_[stack_depth_ - 1 - i].code() << ((i + 1) * 3));
551   }
552
553   return layout;
554 }
555
556
557 void LCodeGen::X87Stack::Fxch(X87Register reg, int other_slot) {
558   DCHECK(is_mutable_);
559   DCHECK(Contains(reg) && stack_depth_ > other_slot);
560   int i  = ArrayIndex(reg);
561   int st = st2idx(i);
562   if (st != other_slot) {
563     int other_i = st2idx(other_slot);
564     X87Register other = stack_[other_i];
565     stack_[other_i]   = reg;
566     stack_[i]         = other;
567     if (st == 0) {
568       __ fxch(other_slot);
569     } else if (other_slot == 0) {
570       __ fxch(st);
571     } else {
572       __ fxch(st);
573       __ fxch(other_slot);
574       __ fxch(st);
575     }
576   }
577 }
578
579
580 int LCodeGen::X87Stack::st2idx(int pos) {
581   return stack_depth_ - pos - 1;
582 }
583
584
585 int LCodeGen::X87Stack::ArrayIndex(X87Register reg) {
586   for (int i = 0; i < stack_depth_; i++) {
587     if (stack_[i].is(reg)) return i;
588   }
589   UNREACHABLE();
590   return -1;
591 }
592
593
594 bool LCodeGen::X87Stack::Contains(X87Register reg) {
595   for (int i = 0; i < stack_depth_; i++) {
596     if (stack_[i].is(reg)) return true;
597   }
598   return false;
599 }
600
601
602 void LCodeGen::X87Stack::Free(X87Register reg) {
603   DCHECK(is_mutable_);
604   DCHECK(Contains(reg));
605   int i  = ArrayIndex(reg);
606   int st = st2idx(i);
607   if (st > 0) {
608     // keep track of how fstp(i) changes the order of elements
609     int tos_i = st2idx(0);
610     stack_[i] = stack_[tos_i];
611   }
612   pop();
613   __ fstp(st);
614 }
615
616
617 void LCodeGen::X87Mov(X87Register dst, Operand src, X87OperandType opts) {
618   if (x87_stack_.Contains(dst)) {
619     x87_stack_.Fxch(dst);
620     __ fstp(0);
621   } else {
622     x87_stack_.push(dst);
623   }
624   X87Fld(src, opts);
625 }
626
627
628 void LCodeGen::X87Mov(X87Register dst, X87Register src, X87OperandType opts) {
629   if (x87_stack_.Contains(dst)) {
630     x87_stack_.Fxch(dst);
631     __ fstp(0);
632     x87_stack_.pop();
633     // Push ST(i) onto the FPU register stack
634     __ fld(x87_stack_.st(src));
635     x87_stack_.push(dst);
636   } else {
637     // Push ST(i) onto the FPU register stack
638     __ fld(x87_stack_.st(src));
639     x87_stack_.push(dst);
640   }
641 }
642
643
644 void LCodeGen::X87Fld(Operand src, X87OperandType opts) {
645   DCHECK(!src.is_reg_only());
646   switch (opts) {
647     case kX87DoubleOperand:
648       __ fld_d(src);
649       break;
650     case kX87FloatOperand:
651       __ fld_s(src);
652       break;
653     case kX87IntOperand:
654       __ fild_s(src);
655       break;
656     default:
657       UNREACHABLE();
658   }
659 }
660
661
662 void LCodeGen::X87Mov(Operand dst, X87Register src, X87OperandType opts) {
663   DCHECK(!dst.is_reg_only());
664   x87_stack_.Fxch(src);
665   switch (opts) {
666     case kX87DoubleOperand:
667       __ fst_d(dst);
668       break;
669     case kX87FloatOperand:
670       __ fst_s(dst);
671       break;
672     case kX87IntOperand:
673       __ fist_s(dst);
674       break;
675     default:
676       UNREACHABLE();
677   }
678 }
679
680
681 void LCodeGen::X87Stack::PrepareToWrite(X87Register reg) {
682   DCHECK(is_mutable_);
683   if (Contains(reg)) {
684     Free(reg);
685   }
686   // Mark this register as the next register to write to
687   stack_[stack_depth_] = reg;
688 }
689
690
691 void LCodeGen::X87Stack::CommitWrite(X87Register reg) {
692   DCHECK(is_mutable_);
693   // Assert the reg is prepared to write, but not on the virtual stack yet
694   DCHECK(!Contains(reg) && stack_[stack_depth_].is(reg) &&
695       stack_depth_ < X87Register::kMaxNumAllocatableRegisters);
696   stack_depth_++;
697 }
698
699
700 void LCodeGen::X87PrepareBinaryOp(
701     X87Register left, X87Register right, X87Register result) {
702   // You need to use DefineSameAsFirst for x87 instructions
703   DCHECK(result.is(left));
704   x87_stack_.Fxch(right, 1);
705   x87_stack_.Fxch(left);
706 }
707
708
709 void LCodeGen::X87Stack::FlushIfNecessary(LInstruction* instr, LCodeGen* cgen) {
710   if (stack_depth_ > 0 && instr->ClobbersDoubleRegisters(isolate())) {
711     bool double_inputs = instr->HasDoubleRegisterInput();
712
713     // Flush stack from tos down, since FreeX87() will mess with tos
714     for (int i = stack_depth_-1; i >= 0; i--) {
715       X87Register reg = stack_[i];
716       // Skip registers which contain the inputs for the next instruction
717       // when flushing the stack
718       if (double_inputs && instr->IsDoubleInput(reg, cgen)) {
719         continue;
720       }
721       Free(reg);
722       if (i < stack_depth_-1) i++;
723     }
724   }
725   if (instr->IsReturn()) {
726     while (stack_depth_ > 0) {
727       __ fstp(0);
728       stack_depth_--;
729     }
730     if (FLAG_debug_code && FLAG_enable_slow_asserts) __ VerifyX87StackDepth(0);
731   }
732 }
733
734
735 void LCodeGen::X87Stack::LeavingBlock(int current_block_id, LGoto* goto_instr,
736                                       LCodeGen* cgen) {
737   // For going to a joined block, an explicit LClobberDoubles is inserted before
738   // LGoto. Because all used x87 registers are spilled to stack slots. The
739   // ResolvePhis phase of register allocator could guarantee the two input's x87
740   // stacks have the same layout. So don't check stack_depth_ <= 1 here.
741   int goto_block_id = goto_instr->block_id();
742   if (current_block_id + 1 != goto_block_id) {
743     // If we have a value on the x87 stack on leaving a block, it must be a
744     // phi input. If the next block we compile is not the join block, we have
745     // to discard the stack state.
746     // Before discarding the stack state, we need to save it if the "goto block"
747     // has unreachable last predecessor when FLAG_unreachable_code_elimination.
748     if (FLAG_unreachable_code_elimination) {
749       int length = goto_instr->block()->predecessors()->length();
750       bool has_unreachable_last_predecessor = false;
751       for (int i = 0; i < length; i++) {
752         HBasicBlock* block = goto_instr->block()->predecessors()->at(i);
753         if (block->IsUnreachable() &&
754             (block->block_id() + 1) == goto_block_id) {
755           has_unreachable_last_predecessor = true;
756         }
757       }
758       if (has_unreachable_last_predecessor) {
759         if (cgen->x87_stack_map_.find(goto_block_id) ==
760             cgen->x87_stack_map_.end()) {
761           X87Stack* stack = new (cgen->zone()) X87Stack(*this);
762           cgen->x87_stack_map_.insert(std::make_pair(goto_block_id, stack));
763         }
764       }
765     }
766
767     // Discard the stack state.
768     stack_depth_ = 0;
769   }
770 }
771
772
773 void LCodeGen::EmitFlushX87ForDeopt() {
774   // The deoptimizer does not support X87 Registers. But as long as we
775   // deopt from a stub its not a problem, since we will re-materialize the
776   // original stub inputs, which can't be double registers.
777   // DCHECK(info()->IsStub());
778   if (FLAG_debug_code && FLAG_enable_slow_asserts) {
779     __ pushfd();
780     __ VerifyX87StackDepth(x87_stack_.depth());
781     __ popfd();
782   }
783
784   // Flush X87 stack in the deoptimizer entry.
785 }
786
787
788 Register LCodeGen::ToRegister(LOperand* op) const {
789   DCHECK(op->IsRegister());
790   return ToRegister(op->index());
791 }
792
793
794 X87Register LCodeGen::ToX87Register(LOperand* op) const {
795   DCHECK(op->IsDoubleRegister());
796   return ToX87Register(op->index());
797 }
798
799
800 int32_t LCodeGen::ToInteger32(LConstantOperand* op) const {
801   return ToRepresentation(op, Representation::Integer32());
802 }
803
804
805 int32_t LCodeGen::ToRepresentation(LConstantOperand* op,
806                                    const Representation& r) const {
807   HConstant* constant = chunk_->LookupConstant(op);
808   int32_t value = constant->Integer32Value();
809   if (r.IsInteger32()) return value;
810   DCHECK(r.IsSmiOrTagged());
811   return reinterpret_cast<int32_t>(Smi::FromInt(value));
812 }
813
814
815 Handle<Object> LCodeGen::ToHandle(LConstantOperand* op) const {
816   HConstant* constant = chunk_->LookupConstant(op);
817   DCHECK(chunk_->LookupLiteralRepresentation(op).IsSmiOrTagged());
818   return constant->handle(isolate());
819 }
820
821
822 double LCodeGen::ToDouble(LConstantOperand* op) const {
823   HConstant* constant = chunk_->LookupConstant(op);
824   DCHECK(constant->HasDoubleValue());
825   return constant->DoubleValue();
826 }
827
828
829 ExternalReference LCodeGen::ToExternalReference(LConstantOperand* op) const {
830   HConstant* constant = chunk_->LookupConstant(op);
831   DCHECK(constant->HasExternalReferenceValue());
832   return constant->ExternalReferenceValue();
833 }
834
835
836 bool LCodeGen::IsInteger32(LConstantOperand* op) const {
837   return chunk_->LookupLiteralRepresentation(op).IsSmiOrInteger32();
838 }
839
840
841 bool LCodeGen::IsSmi(LConstantOperand* op) const {
842   return chunk_->LookupLiteralRepresentation(op).IsSmi();
843 }
844
845
846 static int ArgumentsOffsetWithoutFrame(int index) {
847   DCHECK(index < 0);
848   return -(index + 1) * kPointerSize + kPCOnStackSize;
849 }
850
851
852 Operand LCodeGen::ToOperand(LOperand* op) const {
853   if (op->IsRegister()) return Operand(ToRegister(op));
854   DCHECK(!op->IsDoubleRegister());
855   DCHECK(op->IsStackSlot() || op->IsDoubleStackSlot());
856   if (NeedsEagerFrame()) {
857     return Operand(ebp, StackSlotOffset(op->index()));
858   } else {
859     // Retrieve parameter without eager stack-frame relative to the
860     // stack-pointer.
861     return Operand(esp, ArgumentsOffsetWithoutFrame(op->index()));
862   }
863 }
864
865
866 Operand LCodeGen::HighOperand(LOperand* op) {
867   DCHECK(op->IsDoubleStackSlot());
868   if (NeedsEagerFrame()) {
869     return Operand(ebp, StackSlotOffset(op->index()) + kPointerSize);
870   } else {
871     // Retrieve parameter without eager stack-frame relative to the
872     // stack-pointer.
873     return Operand(
874         esp, ArgumentsOffsetWithoutFrame(op->index()) + kPointerSize);
875   }
876 }
877
878
879 void LCodeGen::WriteTranslation(LEnvironment* environment,
880                                 Translation* translation) {
881   if (environment == NULL) return;
882
883   // The translation includes one command per value in the environment.
884   int translation_size = environment->translation_size();
885   // The output frame height does not include the parameters.
886   int height = translation_size - environment->parameter_count();
887
888   WriteTranslation(environment->outer(), translation);
889   bool has_closure_id = !info()->closure().is_null() &&
890       !info()->closure().is_identical_to(environment->closure());
891   int closure_id = has_closure_id
892       ? DefineDeoptimizationLiteral(environment->closure())
893       : Translation::kSelfLiteralId;
894   switch (environment->frame_type()) {
895     case JS_FUNCTION:
896       translation->BeginJSFrame(environment->ast_id(), closure_id, height);
897       break;
898     case JS_CONSTRUCT:
899       translation->BeginConstructStubFrame(closure_id, translation_size);
900       break;
901     case JS_GETTER:
902       DCHECK(translation_size == 1);
903       DCHECK(height == 0);
904       translation->BeginGetterStubFrame(closure_id);
905       break;
906     case JS_SETTER:
907       DCHECK(translation_size == 2);
908       DCHECK(height == 0);
909       translation->BeginSetterStubFrame(closure_id);
910       break;
911     case ARGUMENTS_ADAPTOR:
912       translation->BeginArgumentsAdaptorFrame(closure_id, translation_size);
913       break;
914     case STUB:
915       translation->BeginCompiledStubFrame();
916       break;
917     default:
918       UNREACHABLE();
919   }
920
921   int object_index = 0;
922   int dematerialized_index = 0;
923   for (int i = 0; i < translation_size; ++i) {
924     LOperand* value = environment->values()->at(i);
925     AddToTranslation(environment,
926                      translation,
927                      value,
928                      environment->HasTaggedValueAt(i),
929                      environment->HasUint32ValueAt(i),
930                      &object_index,
931                      &dematerialized_index);
932   }
933 }
934
935
936 void LCodeGen::AddToTranslation(LEnvironment* environment,
937                                 Translation* translation,
938                                 LOperand* op,
939                                 bool is_tagged,
940                                 bool is_uint32,
941                                 int* object_index_pointer,
942                                 int* dematerialized_index_pointer) {
943   if (op == LEnvironment::materialization_marker()) {
944     int object_index = (*object_index_pointer)++;
945     if (environment->ObjectIsDuplicateAt(object_index)) {
946       int dupe_of = environment->ObjectDuplicateOfAt(object_index);
947       translation->DuplicateObject(dupe_of);
948       return;
949     }
950     int object_length = environment->ObjectLengthAt(object_index);
951     if (environment->ObjectIsArgumentsAt(object_index)) {
952       translation->BeginArgumentsObject(object_length);
953     } else {
954       translation->BeginCapturedObject(object_length);
955     }
956     int dematerialized_index = *dematerialized_index_pointer;
957     int env_offset = environment->translation_size() + dematerialized_index;
958     *dematerialized_index_pointer += object_length;
959     for (int i = 0; i < object_length; ++i) {
960       LOperand* value = environment->values()->at(env_offset + i);
961       AddToTranslation(environment,
962                        translation,
963                        value,
964                        environment->HasTaggedValueAt(env_offset + i),
965                        environment->HasUint32ValueAt(env_offset + i),
966                        object_index_pointer,
967                        dematerialized_index_pointer);
968     }
969     return;
970   }
971
972   if (op->IsStackSlot()) {
973     if (is_tagged) {
974       translation->StoreStackSlot(op->index());
975     } else if (is_uint32) {
976       translation->StoreUint32StackSlot(op->index());
977     } else {
978       translation->StoreInt32StackSlot(op->index());
979     }
980   } else if (op->IsDoubleStackSlot()) {
981     translation->StoreDoubleStackSlot(op->index());
982   } else if (op->IsRegister()) {
983     Register reg = ToRegister(op);
984     if (is_tagged) {
985       translation->StoreRegister(reg);
986     } else if (is_uint32) {
987       translation->StoreUint32Register(reg);
988     } else {
989       translation->StoreInt32Register(reg);
990     }
991   } else if (op->IsDoubleRegister()) {
992     X87Register reg = ToX87Register(op);
993     translation->StoreDoubleRegister(reg);
994   } else if (op->IsConstantOperand()) {
995     HConstant* constant = chunk()->LookupConstant(LConstantOperand::cast(op));
996     int src_index = DefineDeoptimizationLiteral(constant->handle(isolate()));
997     translation->StoreLiteral(src_index);
998   } else {
999     UNREACHABLE();
1000   }
1001 }
1002
1003
1004 void LCodeGen::CallCodeGeneric(Handle<Code> code,
1005                                RelocInfo::Mode mode,
1006                                LInstruction* instr,
1007                                SafepointMode safepoint_mode) {
1008   DCHECK(instr != NULL);
1009   __ call(code, mode);
1010   RecordSafepointWithLazyDeopt(instr, safepoint_mode);
1011
1012   // Signal that we don't inline smi code before these stubs in the
1013   // optimizing code generator.
1014   if (code->kind() == Code::BINARY_OP_IC ||
1015       code->kind() == Code::COMPARE_IC) {
1016     __ nop();
1017   }
1018 }
1019
1020
1021 void LCodeGen::CallCode(Handle<Code> code,
1022                         RelocInfo::Mode mode,
1023                         LInstruction* instr) {
1024   CallCodeGeneric(code, mode, instr, RECORD_SIMPLE_SAFEPOINT);
1025 }
1026
1027
1028 void LCodeGen::CallRuntime(const Runtime::Function* fun, int argc,
1029                            LInstruction* instr, SaveFPRegsMode save_doubles) {
1030   DCHECK(instr != NULL);
1031   DCHECK(instr->HasPointerMap());
1032
1033   __ CallRuntime(fun, argc, save_doubles);
1034
1035   RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
1036
1037   DCHECK(info()->is_calling());
1038 }
1039
1040
1041 void LCodeGen::LoadContextFromDeferred(LOperand* context) {
1042   if (context->IsRegister()) {
1043     if (!ToRegister(context).is(esi)) {
1044       __ mov(esi, ToRegister(context));
1045     }
1046   } else if (context->IsStackSlot()) {
1047     __ mov(esi, ToOperand(context));
1048   } else if (context->IsConstantOperand()) {
1049     HConstant* constant =
1050         chunk_->LookupConstant(LConstantOperand::cast(context));
1051     __ LoadObject(esi, Handle<Object>::cast(constant->handle(isolate())));
1052   } else {
1053     UNREACHABLE();
1054   }
1055 }
1056
1057 void LCodeGen::CallRuntimeFromDeferred(Runtime::FunctionId id,
1058                                        int argc,
1059                                        LInstruction* instr,
1060                                        LOperand* context) {
1061   LoadContextFromDeferred(context);
1062
1063   __ CallRuntimeSaveDoubles(id);
1064   RecordSafepointWithRegisters(
1065       instr->pointer_map(), argc, Safepoint::kNoLazyDeopt);
1066
1067   DCHECK(info()->is_calling());
1068 }
1069
1070
1071 void LCodeGen::RegisterEnvironmentForDeoptimization(
1072     LEnvironment* environment, Safepoint::DeoptMode mode) {
1073   environment->set_has_been_used();
1074   if (!environment->HasBeenRegistered()) {
1075     // Physical stack frame layout:
1076     // -x ............. -4  0 ..................................... y
1077     // [incoming arguments] [spill slots] [pushed outgoing arguments]
1078
1079     // Layout of the environment:
1080     // 0 ..................................................... size-1
1081     // [parameters] [locals] [expression stack including arguments]
1082
1083     // Layout of the translation:
1084     // 0 ........................................................ size - 1 + 4
1085     // [expression stack including arguments] [locals] [4 words] [parameters]
1086     // |>------------  translation_size ------------<|
1087
1088     int frame_count = 0;
1089     int jsframe_count = 0;
1090     for (LEnvironment* e = environment; e != NULL; e = e->outer()) {
1091       ++frame_count;
1092       if (e->frame_type() == JS_FUNCTION) {
1093         ++jsframe_count;
1094       }
1095     }
1096     Translation translation(&translations_, frame_count, jsframe_count, zone());
1097     WriteTranslation(environment, &translation);
1098     int deoptimization_index = deoptimizations_.length();
1099     int pc_offset = masm()->pc_offset();
1100     environment->Register(deoptimization_index,
1101                           translation.index(),
1102                           (mode == Safepoint::kLazyDeopt) ? pc_offset : -1);
1103     deoptimizations_.Add(environment, zone());
1104   }
1105 }
1106
1107
1108 void LCodeGen::DeoptimizeIf(Condition cc, LInstruction* instr,
1109                             Deoptimizer::DeoptReason deopt_reason,
1110                             Deoptimizer::BailoutType bailout_type) {
1111   LEnvironment* environment = instr->environment();
1112   RegisterEnvironmentForDeoptimization(environment, Safepoint::kNoLazyDeopt);
1113   DCHECK(environment->HasBeenRegistered());
1114   int id = environment->deoptimization_index();
1115   DCHECK(info()->IsOptimizing() || info()->IsStub());
1116   Address entry =
1117       Deoptimizer::GetDeoptimizationEntry(isolate(), id, bailout_type);
1118   if (entry == NULL) {
1119     Abort(kBailoutWasNotPrepared);
1120     return;
1121   }
1122
1123   if (DeoptEveryNTimes()) {
1124     ExternalReference count = ExternalReference::stress_deopt_count(isolate());
1125     Label no_deopt;
1126     __ pushfd();
1127     __ push(eax);
1128     __ mov(eax, Operand::StaticVariable(count));
1129     __ sub(eax, Immediate(1));
1130     __ j(not_zero, &no_deopt, Label::kNear);
1131     if (FLAG_trap_on_deopt) __ int3();
1132     __ mov(eax, Immediate(FLAG_deopt_every_n_times));
1133     __ mov(Operand::StaticVariable(count), eax);
1134     __ pop(eax);
1135     __ popfd();
1136     DCHECK(frame_is_built_);
1137     // Put the x87 stack layout in TOS.
1138     if (x87_stack_.depth() > 0) EmitFlushX87ForDeopt();
1139     __ push(Immediate(x87_stack_.GetLayout()));
1140     __ fild_s(MemOperand(esp, 0));
1141     // Don't touch eflags.
1142     __ lea(esp, Operand(esp, kPointerSize));
1143     __ call(entry, RelocInfo::RUNTIME_ENTRY);
1144     __ bind(&no_deopt);
1145     __ mov(Operand::StaticVariable(count), eax);
1146     __ pop(eax);
1147     __ popfd();
1148   }
1149
1150   // Put the x87 stack layout in TOS, so that we can save x87 fp registers in
1151   // the correct location.
1152   {
1153     Label done;
1154     if (cc != no_condition) __ j(NegateCondition(cc), &done, Label::kNear);
1155     if (x87_stack_.depth() > 0) EmitFlushX87ForDeopt();
1156
1157     int x87_stack_layout = x87_stack_.GetLayout();
1158     __ push(Immediate(x87_stack_layout));
1159     __ fild_s(MemOperand(esp, 0));
1160     // Don't touch eflags.
1161     __ lea(esp, Operand(esp, kPointerSize));
1162     __ bind(&done);
1163   }
1164
1165   if (info()->ShouldTrapOnDeopt()) {
1166     Label done;
1167     if (cc != no_condition) __ j(NegateCondition(cc), &done, Label::kNear);
1168     __ int3();
1169     __ bind(&done);
1170   }
1171
1172   Deoptimizer::DeoptInfo deopt_info = MakeDeoptInfo(instr, deopt_reason);
1173
1174   DCHECK(info()->IsStub() || frame_is_built_);
1175   if (cc == no_condition && frame_is_built_) {
1176     DeoptComment(deopt_info);
1177     __ call(entry, RelocInfo::RUNTIME_ENTRY);
1178     info()->LogDeoptCallPosition(masm()->pc_offset(), deopt_info.inlining_id);
1179   } else {
1180     Deoptimizer::JumpTableEntry table_entry(entry, deopt_info, bailout_type,
1181                                             !frame_is_built_);
1182     // We often have several deopts to the same entry, reuse the last
1183     // jump entry if this is the case.
1184     if (FLAG_trace_deopt || isolate()->cpu_profiler()->is_profiling() ||
1185         jump_table_.is_empty() ||
1186         !table_entry.IsEquivalentTo(jump_table_.last())) {
1187       jump_table_.Add(table_entry, zone());
1188     }
1189     if (cc == no_condition) {
1190       __ jmp(&jump_table_.last().label);
1191     } else {
1192       __ j(cc, &jump_table_.last().label);
1193     }
1194   }
1195 }
1196
1197
1198 void LCodeGen::DeoptimizeIf(Condition cc, LInstruction* instr,
1199                             Deoptimizer::DeoptReason deopt_reason) {
1200   Deoptimizer::BailoutType bailout_type = info()->IsStub()
1201       ? Deoptimizer::LAZY
1202       : Deoptimizer::EAGER;
1203   DeoptimizeIf(cc, instr, deopt_reason, bailout_type);
1204 }
1205
1206
1207 void LCodeGen::PopulateDeoptimizationData(Handle<Code> code) {
1208   int length = deoptimizations_.length();
1209   if (length == 0) return;
1210   Handle<DeoptimizationInputData> data =
1211       DeoptimizationInputData::New(isolate(), length, TENURED);
1212
1213   Handle<ByteArray> translations =
1214       translations_.CreateByteArray(isolate()->factory());
1215   data->SetTranslationByteArray(*translations);
1216   data->SetInlinedFunctionCount(Smi::FromInt(inlined_function_count_));
1217   data->SetOptimizationId(Smi::FromInt(info_->optimization_id()));
1218   if (info_->IsOptimizing()) {
1219     // Reference to shared function info does not change between phases.
1220     AllowDeferredHandleDereference allow_handle_dereference;
1221     data->SetSharedFunctionInfo(*info_->shared_info());
1222   } else {
1223     data->SetSharedFunctionInfo(Smi::FromInt(0));
1224   }
1225   data->SetWeakCellCache(Smi::FromInt(0));
1226
1227   Handle<FixedArray> literals =
1228       factory()->NewFixedArray(deoptimization_literals_.length(), TENURED);
1229   { AllowDeferredHandleDereference copy_handles;
1230     for (int i = 0; i < deoptimization_literals_.length(); i++) {
1231       literals->set(i, *deoptimization_literals_[i]);
1232     }
1233     data->SetLiteralArray(*literals);
1234   }
1235
1236   data->SetOsrAstId(Smi::FromInt(info_->osr_ast_id().ToInt()));
1237   data->SetOsrPcOffset(Smi::FromInt(osr_pc_offset_));
1238
1239   // Populate the deoptimization entries.
1240   for (int i = 0; i < length; i++) {
1241     LEnvironment* env = deoptimizations_[i];
1242     data->SetAstId(i, env->ast_id());
1243     data->SetTranslationIndex(i, Smi::FromInt(env->translation_index()));
1244     data->SetArgumentsStackHeight(i,
1245                                   Smi::FromInt(env->arguments_stack_height()));
1246     data->SetPc(i, Smi::FromInt(env->pc_offset()));
1247   }
1248   code->set_deoptimization_data(*data);
1249 }
1250
1251
1252 int LCodeGen::DefineDeoptimizationLiteral(Handle<Object> literal) {
1253   int result = deoptimization_literals_.length();
1254   for (int i = 0; i < deoptimization_literals_.length(); ++i) {
1255     if (deoptimization_literals_[i].is_identical_to(literal)) return i;
1256   }
1257   deoptimization_literals_.Add(literal, zone());
1258   return result;
1259 }
1260
1261
1262 void LCodeGen::PopulateDeoptimizationLiteralsWithInlinedFunctions() {
1263   DCHECK(deoptimization_literals_.length() == 0);
1264
1265   const ZoneList<Handle<JSFunction> >* inlined_closures =
1266       chunk()->inlined_closures();
1267
1268   for (int i = 0, length = inlined_closures->length();
1269        i < length;
1270        i++) {
1271     DefineDeoptimizationLiteral(inlined_closures->at(i));
1272   }
1273
1274   inlined_function_count_ = deoptimization_literals_.length();
1275 }
1276
1277
1278 void LCodeGen::RecordSafepointWithLazyDeopt(
1279     LInstruction* instr, SafepointMode safepoint_mode) {
1280   if (safepoint_mode == RECORD_SIMPLE_SAFEPOINT) {
1281     RecordSafepoint(instr->pointer_map(), Safepoint::kLazyDeopt);
1282   } else {
1283     DCHECK(safepoint_mode == RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
1284     RecordSafepointWithRegisters(
1285         instr->pointer_map(), 0, Safepoint::kLazyDeopt);
1286   }
1287 }
1288
1289
1290 void LCodeGen::RecordSafepoint(
1291     LPointerMap* pointers,
1292     Safepoint::Kind kind,
1293     int arguments,
1294     Safepoint::DeoptMode deopt_mode) {
1295   DCHECK(kind == expected_safepoint_kind_);
1296   const ZoneList<LOperand*>* operands = pointers->GetNormalizedOperands();
1297   Safepoint safepoint =
1298       safepoints_.DefineSafepoint(masm(), kind, arguments, deopt_mode);
1299   for (int i = 0; i < operands->length(); i++) {
1300     LOperand* pointer = operands->at(i);
1301     if (pointer->IsStackSlot()) {
1302       safepoint.DefinePointerSlot(pointer->index(), zone());
1303     } else if (pointer->IsRegister() && (kind & Safepoint::kWithRegisters)) {
1304       safepoint.DefinePointerRegister(ToRegister(pointer), zone());
1305     }
1306   }
1307 }
1308
1309
1310 void LCodeGen::RecordSafepoint(LPointerMap* pointers,
1311                                Safepoint::DeoptMode mode) {
1312   RecordSafepoint(pointers, Safepoint::kSimple, 0, mode);
1313 }
1314
1315
1316 void LCodeGen::RecordSafepoint(Safepoint::DeoptMode mode) {
1317   LPointerMap empty_pointers(zone());
1318   RecordSafepoint(&empty_pointers, mode);
1319 }
1320
1321
1322 void LCodeGen::RecordSafepointWithRegisters(LPointerMap* pointers,
1323                                             int arguments,
1324                                             Safepoint::DeoptMode mode) {
1325   RecordSafepoint(pointers, Safepoint::kWithRegisters, arguments, mode);
1326 }
1327
1328
1329 void LCodeGen::RecordAndWritePosition(int position) {
1330   if (position == RelocInfo::kNoPosition) return;
1331   masm()->positions_recorder()->RecordPosition(position);
1332   masm()->positions_recorder()->WriteRecordedPositions();
1333 }
1334
1335
1336 static const char* LabelType(LLabel* label) {
1337   if (label->is_loop_header()) return " (loop header)";
1338   if (label->is_osr_entry()) return " (OSR entry)";
1339   return "";
1340 }
1341
1342
1343 void LCodeGen::DoLabel(LLabel* label) {
1344   Comment(";;; <@%d,#%d> -------------------- B%d%s --------------------",
1345           current_instruction_,
1346           label->hydrogen_value()->id(),
1347           label->block_id(),
1348           LabelType(label));
1349   __ bind(label->label());
1350   current_block_ = label->block_id();
1351   if (label->block()->predecessors()->length() > 1) {
1352     // A join block's x87 stack is that of its last visited predecessor.
1353     // If the last visited predecessor block is unreachable, the stack state
1354     // will be wrong. In such case, use the x87 stack of reachable predecessor.
1355     X87StackMap::const_iterator it = x87_stack_map_.find(current_block_);
1356     // Restore x87 stack.
1357     if (it != x87_stack_map_.end()) {
1358       x87_stack_ = *(it->second);
1359     }
1360   }
1361   DoGap(label);
1362 }
1363
1364
1365 void LCodeGen::DoParallelMove(LParallelMove* move) {
1366   resolver_.Resolve(move);
1367 }
1368
1369
1370 void LCodeGen::DoGap(LGap* gap) {
1371   for (int i = LGap::FIRST_INNER_POSITION;
1372        i <= LGap::LAST_INNER_POSITION;
1373        i++) {
1374     LGap::InnerPosition inner_pos = static_cast<LGap::InnerPosition>(i);
1375     LParallelMove* move = gap->GetParallelMove(inner_pos);
1376     if (move != NULL) DoParallelMove(move);
1377   }
1378 }
1379
1380
1381 void LCodeGen::DoInstructionGap(LInstructionGap* instr) {
1382   DoGap(instr);
1383 }
1384
1385
1386 void LCodeGen::DoParameter(LParameter* instr) {
1387   // Nothing to do.
1388 }
1389
1390
1391 void LCodeGen::DoCallStub(LCallStub* instr) {
1392   DCHECK(ToRegister(instr->context()).is(esi));
1393   DCHECK(ToRegister(instr->result()).is(eax));
1394   switch (instr->hydrogen()->major_key()) {
1395     case CodeStub::RegExpExec: {
1396       RegExpExecStub stub(isolate());
1397       CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
1398       break;
1399     }
1400     case CodeStub::SubString: {
1401       SubStringStub stub(isolate());
1402       CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
1403       break;
1404     }
1405     case CodeStub::StringCompare: {
1406       StringCompareStub stub(isolate());
1407       CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
1408       break;
1409     }
1410     default:
1411       UNREACHABLE();
1412   }
1413 }
1414
1415
1416 void LCodeGen::DoUnknownOSRValue(LUnknownOSRValue* instr) {
1417   GenerateOsrPrologue();
1418 }
1419
1420
1421 void LCodeGen::DoModByPowerOf2I(LModByPowerOf2I* instr) {
1422   Register dividend = ToRegister(instr->dividend());
1423   int32_t divisor = instr->divisor();
1424   DCHECK(dividend.is(ToRegister(instr->result())));
1425
1426   // Theoretically, a variation of the branch-free code for integer division by
1427   // a power of 2 (calculating the remainder via an additional multiplication
1428   // (which gets simplified to an 'and') and subtraction) should be faster, and
1429   // this is exactly what GCC and clang emit. Nevertheless, benchmarks seem to
1430   // indicate that positive dividends are heavily favored, so the branching
1431   // version performs better.
1432   HMod* hmod = instr->hydrogen();
1433   int32_t mask = divisor < 0 ? -(divisor + 1) : (divisor - 1);
1434   Label dividend_is_not_negative, done;
1435   if (hmod->CheckFlag(HValue::kLeftCanBeNegative)) {
1436     __ test(dividend, dividend);
1437     __ j(not_sign, &dividend_is_not_negative, Label::kNear);
1438     // Note that this is correct even for kMinInt operands.
1439     __ neg(dividend);
1440     __ and_(dividend, mask);
1441     __ neg(dividend);
1442     if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1443       DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1444     }
1445     __ jmp(&done, Label::kNear);
1446   }
1447
1448   __ bind(&dividend_is_not_negative);
1449   __ and_(dividend, mask);
1450   __ bind(&done);
1451 }
1452
1453
1454 void LCodeGen::DoModByConstI(LModByConstI* instr) {
1455   Register dividend = ToRegister(instr->dividend());
1456   int32_t divisor = instr->divisor();
1457   DCHECK(ToRegister(instr->result()).is(eax));
1458
1459   if (divisor == 0) {
1460     DeoptimizeIf(no_condition, instr, Deoptimizer::kDivisionByZero);
1461     return;
1462   }
1463
1464   __ TruncatingDiv(dividend, Abs(divisor));
1465   __ imul(edx, edx, Abs(divisor));
1466   __ mov(eax, dividend);
1467   __ sub(eax, edx);
1468
1469   // Check for negative zero.
1470   HMod* hmod = instr->hydrogen();
1471   if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1472     Label remainder_not_zero;
1473     __ j(not_zero, &remainder_not_zero, Label::kNear);
1474     __ cmp(dividend, Immediate(0));
1475     DeoptimizeIf(less, instr, Deoptimizer::kMinusZero);
1476     __ bind(&remainder_not_zero);
1477   }
1478 }
1479
1480
1481 void LCodeGen::DoModI(LModI* instr) {
1482   HMod* hmod = instr->hydrogen();
1483
1484   Register left_reg = ToRegister(instr->left());
1485   DCHECK(left_reg.is(eax));
1486   Register right_reg = ToRegister(instr->right());
1487   DCHECK(!right_reg.is(eax));
1488   DCHECK(!right_reg.is(edx));
1489   Register result_reg = ToRegister(instr->result());
1490   DCHECK(result_reg.is(edx));
1491
1492   Label done;
1493   // Check for x % 0, idiv would signal a divide error. We have to
1494   // deopt in this case because we can't return a NaN.
1495   if (hmod->CheckFlag(HValue::kCanBeDivByZero)) {
1496     __ test(right_reg, Operand(right_reg));
1497     DeoptimizeIf(zero, instr, Deoptimizer::kDivisionByZero);
1498   }
1499
1500   // Check for kMinInt % -1, idiv would signal a divide error. We
1501   // have to deopt if we care about -0, because we can't return that.
1502   if (hmod->CheckFlag(HValue::kCanOverflow)) {
1503     Label no_overflow_possible;
1504     __ cmp(left_reg, kMinInt);
1505     __ j(not_equal, &no_overflow_possible, Label::kNear);
1506     __ cmp(right_reg, -1);
1507     if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1508       DeoptimizeIf(equal, instr, Deoptimizer::kMinusZero);
1509     } else {
1510       __ j(not_equal, &no_overflow_possible, Label::kNear);
1511       __ Move(result_reg, Immediate(0));
1512       __ jmp(&done, Label::kNear);
1513     }
1514     __ bind(&no_overflow_possible);
1515   }
1516
1517   // Sign extend dividend in eax into edx:eax.
1518   __ cdq();
1519
1520   // If we care about -0, test if the dividend is <0 and the result is 0.
1521   if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1522     Label positive_left;
1523     __ test(left_reg, Operand(left_reg));
1524     __ j(not_sign, &positive_left, Label::kNear);
1525     __ idiv(right_reg);
1526     __ test(result_reg, Operand(result_reg));
1527     DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1528     __ jmp(&done, Label::kNear);
1529     __ bind(&positive_left);
1530   }
1531   __ idiv(right_reg);
1532   __ bind(&done);
1533 }
1534
1535
1536 void LCodeGen::DoDivByPowerOf2I(LDivByPowerOf2I* instr) {
1537   Register dividend = ToRegister(instr->dividend());
1538   int32_t divisor = instr->divisor();
1539   Register result = ToRegister(instr->result());
1540   DCHECK(divisor == kMinInt || base::bits::IsPowerOfTwo32(Abs(divisor)));
1541   DCHECK(!result.is(dividend));
1542
1543   // Check for (0 / -x) that will produce negative zero.
1544   HDiv* hdiv = instr->hydrogen();
1545   if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
1546     __ test(dividend, dividend);
1547     DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1548   }
1549   // Check for (kMinInt / -1).
1550   if (hdiv->CheckFlag(HValue::kCanOverflow) && divisor == -1) {
1551     __ cmp(dividend, kMinInt);
1552     DeoptimizeIf(zero, instr, Deoptimizer::kOverflow);
1553   }
1554   // Deoptimize if remainder will not be 0.
1555   if (!hdiv->CheckFlag(HInstruction::kAllUsesTruncatingToInt32) &&
1556       divisor != 1 && divisor != -1) {
1557     int32_t mask = divisor < 0 ? -(divisor + 1) : (divisor - 1);
1558     __ test(dividend, Immediate(mask));
1559     DeoptimizeIf(not_zero, instr, Deoptimizer::kLostPrecision);
1560   }
1561   __ Move(result, dividend);
1562   int32_t shift = WhichPowerOf2Abs(divisor);
1563   if (shift > 0) {
1564     // The arithmetic shift is always OK, the 'if' is an optimization only.
1565     if (shift > 1) __ sar(result, 31);
1566     __ shr(result, 32 - shift);
1567     __ add(result, dividend);
1568     __ sar(result, shift);
1569   }
1570   if (divisor < 0) __ neg(result);
1571 }
1572
1573
1574 void LCodeGen::DoDivByConstI(LDivByConstI* instr) {
1575   Register dividend = ToRegister(instr->dividend());
1576   int32_t divisor = instr->divisor();
1577   DCHECK(ToRegister(instr->result()).is(edx));
1578
1579   if (divisor == 0) {
1580     DeoptimizeIf(no_condition, instr, Deoptimizer::kDivisionByZero);
1581     return;
1582   }
1583
1584   // Check for (0 / -x) that will produce negative zero.
1585   HDiv* hdiv = instr->hydrogen();
1586   if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
1587     __ test(dividend, dividend);
1588     DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1589   }
1590
1591   __ TruncatingDiv(dividend, Abs(divisor));
1592   if (divisor < 0) __ neg(edx);
1593
1594   if (!hdiv->CheckFlag(HInstruction::kAllUsesTruncatingToInt32)) {
1595     __ mov(eax, edx);
1596     __ imul(eax, eax, divisor);
1597     __ sub(eax, dividend);
1598     DeoptimizeIf(not_equal, instr, Deoptimizer::kLostPrecision);
1599   }
1600 }
1601
1602
1603 // TODO(svenpanne) Refactor this to avoid code duplication with DoFlooringDivI.
1604 void LCodeGen::DoDivI(LDivI* instr) {
1605   HBinaryOperation* hdiv = instr->hydrogen();
1606   Register dividend = ToRegister(instr->dividend());
1607   Register divisor = ToRegister(instr->divisor());
1608   Register remainder = ToRegister(instr->temp());
1609   DCHECK(dividend.is(eax));
1610   DCHECK(remainder.is(edx));
1611   DCHECK(ToRegister(instr->result()).is(eax));
1612   DCHECK(!divisor.is(eax));
1613   DCHECK(!divisor.is(edx));
1614
1615   // Check for x / 0.
1616   if (hdiv->CheckFlag(HValue::kCanBeDivByZero)) {
1617     __ test(divisor, divisor);
1618     DeoptimizeIf(zero, instr, Deoptimizer::kDivisionByZero);
1619   }
1620
1621   // Check for (0 / -x) that will produce negative zero.
1622   if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero)) {
1623     Label dividend_not_zero;
1624     __ test(dividend, dividend);
1625     __ j(not_zero, &dividend_not_zero, Label::kNear);
1626     __ test(divisor, divisor);
1627     DeoptimizeIf(sign, instr, Deoptimizer::kMinusZero);
1628     __ bind(&dividend_not_zero);
1629   }
1630
1631   // Check for (kMinInt / -1).
1632   if (hdiv->CheckFlag(HValue::kCanOverflow)) {
1633     Label dividend_not_min_int;
1634     __ cmp(dividend, kMinInt);
1635     __ j(not_zero, &dividend_not_min_int, Label::kNear);
1636     __ cmp(divisor, -1);
1637     DeoptimizeIf(zero, instr, Deoptimizer::kOverflow);
1638     __ bind(&dividend_not_min_int);
1639   }
1640
1641   // Sign extend to edx (= remainder).
1642   __ cdq();
1643   __ idiv(divisor);
1644
1645   if (!hdiv->CheckFlag(HValue::kAllUsesTruncatingToInt32)) {
1646     // Deoptimize if remainder is not 0.
1647     __ test(remainder, remainder);
1648     DeoptimizeIf(not_zero, instr, Deoptimizer::kLostPrecision);
1649   }
1650 }
1651
1652
1653 void LCodeGen::DoFlooringDivByPowerOf2I(LFlooringDivByPowerOf2I* instr) {
1654   Register dividend = ToRegister(instr->dividend());
1655   int32_t divisor = instr->divisor();
1656   DCHECK(dividend.is(ToRegister(instr->result())));
1657
1658   // If the divisor is positive, things are easy: There can be no deopts and we
1659   // can simply do an arithmetic right shift.
1660   if (divisor == 1) return;
1661   int32_t shift = WhichPowerOf2Abs(divisor);
1662   if (divisor > 1) {
1663     __ sar(dividend, shift);
1664     return;
1665   }
1666
1667   // If the divisor is negative, we have to negate and handle edge cases.
1668   __ neg(dividend);
1669   if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1670     DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1671   }
1672
1673   // Dividing by -1 is basically negation, unless we overflow.
1674   if (divisor == -1) {
1675     if (instr->hydrogen()->CheckFlag(HValue::kLeftCanBeMinInt)) {
1676       DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1677     }
1678     return;
1679   }
1680
1681   // If the negation could not overflow, simply shifting is OK.
1682   if (!instr->hydrogen()->CheckFlag(HValue::kLeftCanBeMinInt)) {
1683     __ sar(dividend, shift);
1684     return;
1685   }
1686
1687   Label not_kmin_int, done;
1688   __ j(no_overflow, &not_kmin_int, Label::kNear);
1689   __ mov(dividend, Immediate(kMinInt / divisor));
1690   __ jmp(&done, Label::kNear);
1691   __ bind(&not_kmin_int);
1692   __ sar(dividend, shift);
1693   __ bind(&done);
1694 }
1695
1696
1697 void LCodeGen::DoFlooringDivByConstI(LFlooringDivByConstI* instr) {
1698   Register dividend = ToRegister(instr->dividend());
1699   int32_t divisor = instr->divisor();
1700   DCHECK(ToRegister(instr->result()).is(edx));
1701
1702   if (divisor == 0) {
1703     DeoptimizeIf(no_condition, instr, Deoptimizer::kDivisionByZero);
1704     return;
1705   }
1706
1707   // Check for (0 / -x) that will produce negative zero.
1708   HMathFloorOfDiv* hdiv = instr->hydrogen();
1709   if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
1710     __ test(dividend, dividend);
1711     DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1712   }
1713
1714   // Easy case: We need no dynamic check for the dividend and the flooring
1715   // division is the same as the truncating division.
1716   if ((divisor > 0 && !hdiv->CheckFlag(HValue::kLeftCanBeNegative)) ||
1717       (divisor < 0 && !hdiv->CheckFlag(HValue::kLeftCanBePositive))) {
1718     __ TruncatingDiv(dividend, Abs(divisor));
1719     if (divisor < 0) __ neg(edx);
1720     return;
1721   }
1722
1723   // In the general case we may need to adjust before and after the truncating
1724   // division to get a flooring division.
1725   Register temp = ToRegister(instr->temp3());
1726   DCHECK(!temp.is(dividend) && !temp.is(eax) && !temp.is(edx));
1727   Label needs_adjustment, done;
1728   __ cmp(dividend, Immediate(0));
1729   __ j(divisor > 0 ? less : greater, &needs_adjustment, Label::kNear);
1730   __ TruncatingDiv(dividend, Abs(divisor));
1731   if (divisor < 0) __ neg(edx);
1732   __ jmp(&done, Label::kNear);
1733   __ bind(&needs_adjustment);
1734   __ lea(temp, Operand(dividend, divisor > 0 ? 1 : -1));
1735   __ TruncatingDiv(temp, Abs(divisor));
1736   if (divisor < 0) __ neg(edx);
1737   __ dec(edx);
1738   __ bind(&done);
1739 }
1740
1741
1742 // TODO(svenpanne) Refactor this to avoid code duplication with DoDivI.
1743 void LCodeGen::DoFlooringDivI(LFlooringDivI* instr) {
1744   HBinaryOperation* hdiv = instr->hydrogen();
1745   Register dividend = ToRegister(instr->dividend());
1746   Register divisor = ToRegister(instr->divisor());
1747   Register remainder = ToRegister(instr->temp());
1748   Register result = ToRegister(instr->result());
1749   DCHECK(dividend.is(eax));
1750   DCHECK(remainder.is(edx));
1751   DCHECK(result.is(eax));
1752   DCHECK(!divisor.is(eax));
1753   DCHECK(!divisor.is(edx));
1754
1755   // Check for x / 0.
1756   if (hdiv->CheckFlag(HValue::kCanBeDivByZero)) {
1757     __ test(divisor, divisor);
1758     DeoptimizeIf(zero, instr, Deoptimizer::kDivisionByZero);
1759   }
1760
1761   // Check for (0 / -x) that will produce negative zero.
1762   if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero)) {
1763     Label dividend_not_zero;
1764     __ test(dividend, dividend);
1765     __ j(not_zero, &dividend_not_zero, Label::kNear);
1766     __ test(divisor, divisor);
1767     DeoptimizeIf(sign, instr, Deoptimizer::kMinusZero);
1768     __ bind(&dividend_not_zero);
1769   }
1770
1771   // Check for (kMinInt / -1).
1772   if (hdiv->CheckFlag(HValue::kCanOverflow)) {
1773     Label dividend_not_min_int;
1774     __ cmp(dividend, kMinInt);
1775     __ j(not_zero, &dividend_not_min_int, Label::kNear);
1776     __ cmp(divisor, -1);
1777     DeoptimizeIf(zero, instr, Deoptimizer::kOverflow);
1778     __ bind(&dividend_not_min_int);
1779   }
1780
1781   // Sign extend to edx (= remainder).
1782   __ cdq();
1783   __ idiv(divisor);
1784
1785   Label done;
1786   __ test(remainder, remainder);
1787   __ j(zero, &done, Label::kNear);
1788   __ xor_(remainder, divisor);
1789   __ sar(remainder, 31);
1790   __ add(result, remainder);
1791   __ bind(&done);
1792 }
1793
1794
1795 void LCodeGen::DoMulI(LMulI* instr) {
1796   Register left = ToRegister(instr->left());
1797   LOperand* right = instr->right();
1798
1799   if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1800     __ mov(ToRegister(instr->temp()), left);
1801   }
1802
1803   if (right->IsConstantOperand()) {
1804     // Try strength reductions on the multiplication.
1805     // All replacement instructions are at most as long as the imul
1806     // and have better latency.
1807     int constant = ToInteger32(LConstantOperand::cast(right));
1808     if (constant == -1) {
1809       __ neg(left);
1810     } else if (constant == 0) {
1811       __ xor_(left, Operand(left));
1812     } else if (constant == 2) {
1813       __ add(left, Operand(left));
1814     } else if (!instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
1815       // If we know that the multiplication can't overflow, it's safe to
1816       // use instructions that don't set the overflow flag for the
1817       // multiplication.
1818       switch (constant) {
1819         case 1:
1820           // Do nothing.
1821           break;
1822         case 3:
1823           __ lea(left, Operand(left, left, times_2, 0));
1824           break;
1825         case 4:
1826           __ shl(left, 2);
1827           break;
1828         case 5:
1829           __ lea(left, Operand(left, left, times_4, 0));
1830           break;
1831         case 8:
1832           __ shl(left, 3);
1833           break;
1834         case 9:
1835           __ lea(left, Operand(left, left, times_8, 0));
1836           break;
1837         case 16:
1838           __ shl(left, 4);
1839           break;
1840         default:
1841           __ imul(left, left, constant);
1842           break;
1843       }
1844     } else {
1845       __ imul(left, left, constant);
1846     }
1847   } else {
1848     if (instr->hydrogen()->representation().IsSmi()) {
1849       __ SmiUntag(left);
1850     }
1851     __ imul(left, ToOperand(right));
1852   }
1853
1854   if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
1855     DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1856   }
1857
1858   if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1859     // Bail out if the result is supposed to be negative zero.
1860     Label done;
1861     __ test(left, Operand(left));
1862     __ j(not_zero, &done);
1863     if (right->IsConstantOperand()) {
1864       if (ToInteger32(LConstantOperand::cast(right)) < 0) {
1865         DeoptimizeIf(no_condition, instr, Deoptimizer::kMinusZero);
1866       } else if (ToInteger32(LConstantOperand::cast(right)) == 0) {
1867         __ cmp(ToRegister(instr->temp()), Immediate(0));
1868         DeoptimizeIf(less, instr, Deoptimizer::kMinusZero);
1869       }
1870     } else {
1871       // Test the non-zero operand for negative sign.
1872       __ or_(ToRegister(instr->temp()), ToOperand(right));
1873       DeoptimizeIf(sign, instr, Deoptimizer::kMinusZero);
1874     }
1875     __ bind(&done);
1876   }
1877 }
1878
1879
1880 void LCodeGen::DoBitI(LBitI* instr) {
1881   LOperand* left = instr->left();
1882   LOperand* right = instr->right();
1883   DCHECK(left->Equals(instr->result()));
1884   DCHECK(left->IsRegister());
1885
1886   if (right->IsConstantOperand()) {
1887     int32_t right_operand =
1888         ToRepresentation(LConstantOperand::cast(right),
1889                          instr->hydrogen()->representation());
1890     switch (instr->op()) {
1891       case Token::BIT_AND:
1892         __ and_(ToRegister(left), right_operand);
1893         break;
1894       case Token::BIT_OR:
1895         __ or_(ToRegister(left), right_operand);
1896         break;
1897       case Token::BIT_XOR:
1898         if (right_operand == int32_t(~0)) {
1899           __ not_(ToRegister(left));
1900         } else {
1901           __ xor_(ToRegister(left), right_operand);
1902         }
1903         break;
1904       default:
1905         UNREACHABLE();
1906         break;
1907     }
1908   } else {
1909     switch (instr->op()) {
1910       case Token::BIT_AND:
1911         __ and_(ToRegister(left), ToOperand(right));
1912         break;
1913       case Token::BIT_OR:
1914         __ or_(ToRegister(left), ToOperand(right));
1915         break;
1916       case Token::BIT_XOR:
1917         __ xor_(ToRegister(left), ToOperand(right));
1918         break;
1919       default:
1920         UNREACHABLE();
1921         break;
1922     }
1923   }
1924 }
1925
1926
1927 void LCodeGen::DoShiftI(LShiftI* instr) {
1928   LOperand* left = instr->left();
1929   LOperand* right = instr->right();
1930   DCHECK(left->Equals(instr->result()));
1931   DCHECK(left->IsRegister());
1932   if (right->IsRegister()) {
1933     DCHECK(ToRegister(right).is(ecx));
1934
1935     switch (instr->op()) {
1936       case Token::ROR:
1937         __ ror_cl(ToRegister(left));
1938         break;
1939       case Token::SAR:
1940         __ sar_cl(ToRegister(left));
1941         break;
1942       case Token::SHR:
1943         __ shr_cl(ToRegister(left));
1944         if (instr->can_deopt()) {
1945           __ test(ToRegister(left), ToRegister(left));
1946           DeoptimizeIf(sign, instr, Deoptimizer::kNegativeValue);
1947         }
1948         break;
1949       case Token::SHL:
1950         __ shl_cl(ToRegister(left));
1951         break;
1952       default:
1953         UNREACHABLE();
1954         break;
1955     }
1956   } else {
1957     int value = ToInteger32(LConstantOperand::cast(right));
1958     uint8_t shift_count = static_cast<uint8_t>(value & 0x1F);
1959     switch (instr->op()) {
1960       case Token::ROR:
1961         if (shift_count == 0 && instr->can_deopt()) {
1962           __ test(ToRegister(left), ToRegister(left));
1963           DeoptimizeIf(sign, instr, Deoptimizer::kNegativeValue);
1964         } else {
1965           __ ror(ToRegister(left), shift_count);
1966         }
1967         break;
1968       case Token::SAR:
1969         if (shift_count != 0) {
1970           __ sar(ToRegister(left), shift_count);
1971         }
1972         break;
1973       case Token::SHR:
1974         if (shift_count != 0) {
1975           __ shr(ToRegister(left), shift_count);
1976         } else if (instr->can_deopt()) {
1977           __ test(ToRegister(left), ToRegister(left));
1978           DeoptimizeIf(sign, instr, Deoptimizer::kNegativeValue);
1979         }
1980         break;
1981       case Token::SHL:
1982         if (shift_count != 0) {
1983           if (instr->hydrogen_value()->representation().IsSmi() &&
1984               instr->can_deopt()) {
1985             if (shift_count != 1) {
1986               __ shl(ToRegister(left), shift_count - 1);
1987             }
1988             __ SmiTag(ToRegister(left));
1989             DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1990           } else {
1991             __ shl(ToRegister(left), shift_count);
1992           }
1993         }
1994         break;
1995       default:
1996         UNREACHABLE();
1997         break;
1998     }
1999   }
2000 }
2001
2002
2003 void LCodeGen::DoSubI(LSubI* instr) {
2004   LOperand* left = instr->left();
2005   LOperand* right = instr->right();
2006   DCHECK(left->Equals(instr->result()));
2007
2008   if (right->IsConstantOperand()) {
2009     __ sub(ToOperand(left),
2010            ToImmediate(right, instr->hydrogen()->representation()));
2011   } else {
2012     __ sub(ToRegister(left), ToOperand(right));
2013   }
2014   if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
2015     DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
2016   }
2017 }
2018
2019
2020 void LCodeGen::DoConstantI(LConstantI* instr) {
2021   __ Move(ToRegister(instr->result()), Immediate(instr->value()));
2022 }
2023
2024
2025 void LCodeGen::DoConstantS(LConstantS* instr) {
2026   __ Move(ToRegister(instr->result()), Immediate(instr->value()));
2027 }
2028
2029
2030 void LCodeGen::DoConstantD(LConstantD* instr) {
2031   uint64_t const bits = instr->bits();
2032   uint32_t const lower = static_cast<uint32_t>(bits);
2033   uint32_t const upper = static_cast<uint32_t>(bits >> 32);
2034   DCHECK(instr->result()->IsDoubleRegister());
2035
2036   __ push(Immediate(upper));
2037   __ push(Immediate(lower));
2038   X87Register reg = ToX87Register(instr->result());
2039   X87Mov(reg, Operand(esp, 0));
2040   __ add(Operand(esp), Immediate(kDoubleSize));
2041 }
2042
2043
2044 void LCodeGen::DoConstantE(LConstantE* instr) {
2045   __ lea(ToRegister(instr->result()), Operand::StaticVariable(instr->value()));
2046 }
2047
2048
2049 void LCodeGen::DoConstantT(LConstantT* instr) {
2050   Register reg = ToRegister(instr->result());
2051   Handle<Object> object = instr->value(isolate());
2052   AllowDeferredHandleDereference smi_check;
2053   __ LoadObject(reg, object);
2054 }
2055
2056
2057 void LCodeGen::DoMapEnumLength(LMapEnumLength* instr) {
2058   Register result = ToRegister(instr->result());
2059   Register map = ToRegister(instr->value());
2060   __ EnumLength(result, map);
2061 }
2062
2063
2064 void LCodeGen::DoDateField(LDateField* instr) {
2065   Register object = ToRegister(instr->date());
2066   Register result = ToRegister(instr->result());
2067   Register scratch = ToRegister(instr->temp());
2068   Smi* index = instr->index();
2069   Label runtime, done;
2070   DCHECK(object.is(result));
2071   DCHECK(object.is(eax));
2072
2073   __ test(object, Immediate(kSmiTagMask));
2074   DeoptimizeIf(zero, instr, Deoptimizer::kSmi);
2075   __ CmpObjectType(object, JS_DATE_TYPE, scratch);
2076   DeoptimizeIf(not_equal, instr, Deoptimizer::kNotADateObject);
2077
2078   if (index->value() == 0) {
2079     __ mov(result, FieldOperand(object, JSDate::kValueOffset));
2080   } else {
2081     if (index->value() < JSDate::kFirstUncachedField) {
2082       ExternalReference stamp = ExternalReference::date_cache_stamp(isolate());
2083       __ mov(scratch, Operand::StaticVariable(stamp));
2084       __ cmp(scratch, FieldOperand(object, JSDate::kCacheStampOffset));
2085       __ j(not_equal, &runtime, Label::kNear);
2086       __ mov(result, FieldOperand(object, JSDate::kValueOffset +
2087                                           kPointerSize * index->value()));
2088       __ jmp(&done, Label::kNear);
2089     }
2090     __ bind(&runtime);
2091     __ PrepareCallCFunction(2, scratch);
2092     __ mov(Operand(esp, 0), object);
2093     __ mov(Operand(esp, 1 * kPointerSize), Immediate(index));
2094     __ CallCFunction(ExternalReference::get_date_field_function(isolate()), 2);
2095     __ bind(&done);
2096   }
2097 }
2098
2099
2100 Operand LCodeGen::BuildSeqStringOperand(Register string,
2101                                         LOperand* index,
2102                                         String::Encoding encoding) {
2103   if (index->IsConstantOperand()) {
2104     int offset = ToRepresentation(LConstantOperand::cast(index),
2105                                   Representation::Integer32());
2106     if (encoding == String::TWO_BYTE_ENCODING) {
2107       offset *= kUC16Size;
2108     }
2109     STATIC_ASSERT(kCharSize == 1);
2110     return FieldOperand(string, SeqString::kHeaderSize + offset);
2111   }
2112   return FieldOperand(
2113       string, ToRegister(index),
2114       encoding == String::ONE_BYTE_ENCODING ? times_1 : times_2,
2115       SeqString::kHeaderSize);
2116 }
2117
2118
2119 void LCodeGen::DoSeqStringGetChar(LSeqStringGetChar* instr) {
2120   String::Encoding encoding = instr->hydrogen()->encoding();
2121   Register result = ToRegister(instr->result());
2122   Register string = ToRegister(instr->string());
2123
2124   if (FLAG_debug_code) {
2125     __ push(string);
2126     __ mov(string, FieldOperand(string, HeapObject::kMapOffset));
2127     __ movzx_b(string, FieldOperand(string, Map::kInstanceTypeOffset));
2128
2129     __ and_(string, Immediate(kStringRepresentationMask | kStringEncodingMask));
2130     static const uint32_t one_byte_seq_type = kSeqStringTag | kOneByteStringTag;
2131     static const uint32_t two_byte_seq_type = kSeqStringTag | kTwoByteStringTag;
2132     __ cmp(string, Immediate(encoding == String::ONE_BYTE_ENCODING
2133                              ? one_byte_seq_type : two_byte_seq_type));
2134     __ Check(equal, kUnexpectedStringType);
2135     __ pop(string);
2136   }
2137
2138   Operand operand = BuildSeqStringOperand(string, instr->index(), encoding);
2139   if (encoding == String::ONE_BYTE_ENCODING) {
2140     __ movzx_b(result, operand);
2141   } else {
2142     __ movzx_w(result, operand);
2143   }
2144 }
2145
2146
2147 void LCodeGen::DoSeqStringSetChar(LSeqStringSetChar* instr) {
2148   String::Encoding encoding = instr->hydrogen()->encoding();
2149   Register string = ToRegister(instr->string());
2150
2151   if (FLAG_debug_code) {
2152     Register value = ToRegister(instr->value());
2153     Register index = ToRegister(instr->index());
2154     static const uint32_t one_byte_seq_type = kSeqStringTag | kOneByteStringTag;
2155     static const uint32_t two_byte_seq_type = kSeqStringTag | kTwoByteStringTag;
2156     int encoding_mask =
2157         instr->hydrogen()->encoding() == String::ONE_BYTE_ENCODING
2158         ? one_byte_seq_type : two_byte_seq_type;
2159     __ EmitSeqStringSetCharCheck(string, index, value, encoding_mask);
2160   }
2161
2162   Operand operand = BuildSeqStringOperand(string, instr->index(), encoding);
2163   if (instr->value()->IsConstantOperand()) {
2164     int value = ToRepresentation(LConstantOperand::cast(instr->value()),
2165                                  Representation::Integer32());
2166     DCHECK_LE(0, value);
2167     if (encoding == String::ONE_BYTE_ENCODING) {
2168       DCHECK_LE(value, String::kMaxOneByteCharCode);
2169       __ mov_b(operand, static_cast<int8_t>(value));
2170     } else {
2171       DCHECK_LE(value, String::kMaxUtf16CodeUnit);
2172       __ mov_w(operand, static_cast<int16_t>(value));
2173     }
2174   } else {
2175     Register value = ToRegister(instr->value());
2176     if (encoding == String::ONE_BYTE_ENCODING) {
2177       __ mov_b(operand, value);
2178     } else {
2179       __ mov_w(operand, value);
2180     }
2181   }
2182 }
2183
2184
2185 void LCodeGen::DoAddI(LAddI* instr) {
2186   LOperand* left = instr->left();
2187   LOperand* right = instr->right();
2188
2189   if (LAddI::UseLea(instr->hydrogen()) && !left->Equals(instr->result())) {
2190     if (right->IsConstantOperand()) {
2191       int32_t offset = ToRepresentation(LConstantOperand::cast(right),
2192                                         instr->hydrogen()->representation());
2193       __ lea(ToRegister(instr->result()), MemOperand(ToRegister(left), offset));
2194     } else {
2195       Operand address(ToRegister(left), ToRegister(right), times_1, 0);
2196       __ lea(ToRegister(instr->result()), address);
2197     }
2198   } else {
2199     if (right->IsConstantOperand()) {
2200       __ add(ToOperand(left),
2201              ToImmediate(right, instr->hydrogen()->representation()));
2202     } else {
2203       __ add(ToRegister(left), ToOperand(right));
2204     }
2205     if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
2206       DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
2207     }
2208   }
2209 }
2210
2211
2212 void LCodeGen::DoMathMinMax(LMathMinMax* instr) {
2213   LOperand* left = instr->left();
2214   LOperand* right = instr->right();
2215   DCHECK(left->Equals(instr->result()));
2216   HMathMinMax::Operation operation = instr->hydrogen()->operation();
2217   if (instr->hydrogen()->representation().IsSmiOrInteger32()) {
2218     Label return_left;
2219     Condition condition = (operation == HMathMinMax::kMathMin)
2220         ? less_equal
2221         : greater_equal;
2222     if (right->IsConstantOperand()) {
2223       Operand left_op = ToOperand(left);
2224       Immediate immediate = ToImmediate(LConstantOperand::cast(instr->right()),
2225                                         instr->hydrogen()->representation());
2226       __ cmp(left_op, immediate);
2227       __ j(condition, &return_left, Label::kNear);
2228       __ mov(left_op, immediate);
2229     } else {
2230       Register left_reg = ToRegister(left);
2231       Operand right_op = ToOperand(right);
2232       __ cmp(left_reg, right_op);
2233       __ j(condition, &return_left, Label::kNear);
2234       __ mov(left_reg, right_op);
2235     }
2236     __ bind(&return_left);
2237   } else {
2238     DCHECK(instr->hydrogen()->representation().IsDouble());
2239     Label check_nan_left, check_zero, return_left, return_right;
2240     Condition condition = (operation == HMathMinMax::kMathMin) ? below : above;
2241     X87Register left_reg = ToX87Register(left);
2242     X87Register right_reg = ToX87Register(right);
2243
2244     X87PrepareBinaryOp(left_reg, right_reg, ToX87Register(instr->result()));
2245     __ fld(1);
2246     __ fld(1);
2247     __ FCmp();
2248     __ j(parity_even, &check_nan_left, Label::kNear);  // At least one NaN.
2249     __ j(equal, &check_zero, Label::kNear);            // left == right.
2250     __ j(condition, &return_left, Label::kNear);
2251     __ jmp(&return_right, Label::kNear);
2252
2253     __ bind(&check_zero);
2254     __ fld(0);
2255     __ fldz();
2256     __ FCmp();
2257     __ j(not_equal, &return_left, Label::kNear);  // left == right != 0.
2258     // At this point, both left and right are either 0 or -0.
2259     if (operation == HMathMinMax::kMathMin) {
2260       // Push st0 and st1 to stack, then pop them to temp registers and OR them,
2261       // load it to left.
2262       Register scratch_reg = ToRegister(instr->temp());
2263       __ fld(1);
2264       __ fld(1);
2265       __ sub(esp, Immediate(2 * kPointerSize));
2266       __ fstp_s(MemOperand(esp, 0));
2267       __ fstp_s(MemOperand(esp, kPointerSize));
2268       __ pop(scratch_reg);
2269       __ xor_(MemOperand(esp, 0), scratch_reg);
2270       X87Mov(left_reg, MemOperand(esp, 0), kX87FloatOperand);
2271       __ pop(scratch_reg);  // restore esp
2272     } else {
2273       // Since we operate on +0 and/or -0, addsd and andsd have the same effect.
2274       X87Fxch(left_reg);
2275       __ fadd(1);
2276     }
2277     __ jmp(&return_left, Label::kNear);
2278
2279     __ bind(&check_nan_left);
2280     __ fld(0);
2281     __ fld(0);
2282     __ FCmp();                                      // NaN check.
2283     __ j(parity_even, &return_left, Label::kNear);  // left == NaN.
2284
2285     __ bind(&return_right);
2286     X87Fxch(left_reg);
2287     X87Mov(left_reg, right_reg);
2288
2289     __ bind(&return_left);
2290   }
2291 }
2292
2293
2294 void LCodeGen::DoArithmeticD(LArithmeticD* instr) {
2295   X87Register left = ToX87Register(instr->left());
2296   X87Register right = ToX87Register(instr->right());
2297   X87Register result = ToX87Register(instr->result());
2298   if (instr->op() != Token::MOD) {
2299     X87PrepareBinaryOp(left, right, result);
2300   }
2301   // Set the precision control to double-precision.
2302   __ X87SetFPUCW(0x027F);
2303   switch (instr->op()) {
2304     case Token::ADD:
2305       __ fadd_i(1);
2306       break;
2307     case Token::SUB:
2308       __ fsub_i(1);
2309       break;
2310     case Token::MUL:
2311       __ fmul_i(1);
2312       break;
2313     case Token::DIV:
2314       __ fdiv_i(1);
2315       break;
2316     case Token::MOD: {
2317       // Pass two doubles as arguments on the stack.
2318       __ PrepareCallCFunction(4, eax);
2319       X87Mov(Operand(esp, 1 * kDoubleSize), right);
2320       X87Mov(Operand(esp, 0), left);
2321       X87Free(right);
2322       DCHECK(left.is(result));
2323       X87PrepareToWrite(result);
2324       __ CallCFunction(
2325           ExternalReference::mod_two_doubles_operation(isolate()),
2326           4);
2327
2328       // Return value is in st(0) on ia32.
2329       X87CommitWrite(result);
2330       break;
2331     }
2332     default:
2333       UNREACHABLE();
2334       break;
2335   }
2336
2337   // Restore the default value of control word.
2338   __ X87SetFPUCW(0x037F);
2339 }
2340
2341
2342 void LCodeGen::DoArithmeticT(LArithmeticT* instr) {
2343   DCHECK(ToRegister(instr->context()).is(esi));
2344   DCHECK(ToRegister(instr->left()).is(edx));
2345   DCHECK(ToRegister(instr->right()).is(eax));
2346   DCHECK(ToRegister(instr->result()).is(eax));
2347
2348   Handle<Code> code = CodeFactory::BinaryOpIC(isolate(), instr->op()).code();
2349   CallCode(code, RelocInfo::CODE_TARGET, instr);
2350 }
2351
2352
2353 template<class InstrType>
2354 void LCodeGen::EmitBranch(InstrType instr, Condition cc) {
2355   int left_block = instr->TrueDestination(chunk_);
2356   int right_block = instr->FalseDestination(chunk_);
2357
2358   int next_block = GetNextEmittedBlock();
2359
2360   if (right_block == left_block || cc == no_condition) {
2361     EmitGoto(left_block);
2362   } else if (left_block == next_block) {
2363     __ j(NegateCondition(cc), chunk_->GetAssemblyLabel(right_block));
2364   } else if (right_block == next_block) {
2365     __ j(cc, chunk_->GetAssemblyLabel(left_block));
2366   } else {
2367     __ j(cc, chunk_->GetAssemblyLabel(left_block));
2368     __ jmp(chunk_->GetAssemblyLabel(right_block));
2369   }
2370 }
2371
2372
2373 template<class InstrType>
2374 void LCodeGen::EmitFalseBranch(InstrType instr, Condition cc) {
2375   int false_block = instr->FalseDestination(chunk_);
2376   if (cc == no_condition) {
2377     __ jmp(chunk_->GetAssemblyLabel(false_block));
2378   } else {
2379     __ j(cc, chunk_->GetAssemblyLabel(false_block));
2380   }
2381 }
2382
2383
2384 void LCodeGen::DoBranch(LBranch* instr) {
2385   Representation r = instr->hydrogen()->value()->representation();
2386   if (r.IsSmiOrInteger32()) {
2387     Register reg = ToRegister(instr->value());
2388     __ test(reg, Operand(reg));
2389     EmitBranch(instr, not_zero);
2390   } else if (r.IsDouble()) {
2391     X87Register reg = ToX87Register(instr->value());
2392     X87LoadForUsage(reg);
2393     __ fldz();
2394     __ FCmp();
2395     EmitBranch(instr, not_zero);
2396   } else {
2397     DCHECK(r.IsTagged());
2398     Register reg = ToRegister(instr->value());
2399     HType type = instr->hydrogen()->value()->type();
2400     if (type.IsBoolean()) {
2401       DCHECK(!info()->IsStub());
2402       __ cmp(reg, factory()->true_value());
2403       EmitBranch(instr, equal);
2404     } else if (type.IsSmi()) {
2405       DCHECK(!info()->IsStub());
2406       __ test(reg, Operand(reg));
2407       EmitBranch(instr, not_equal);
2408     } else if (type.IsJSArray()) {
2409       DCHECK(!info()->IsStub());
2410       EmitBranch(instr, no_condition);
2411     } else if (type.IsHeapNumber()) {
2412       UNREACHABLE();
2413     } else if (type.IsString()) {
2414       DCHECK(!info()->IsStub());
2415       __ cmp(FieldOperand(reg, String::kLengthOffset), Immediate(0));
2416       EmitBranch(instr, not_equal);
2417     } else {
2418       ToBooleanStub::Types expected = instr->hydrogen()->expected_input_types();
2419       if (expected.IsEmpty()) expected = ToBooleanStub::Types::Generic();
2420
2421       if (expected.Contains(ToBooleanStub::UNDEFINED)) {
2422         // undefined -> false.
2423         __ cmp(reg, factory()->undefined_value());
2424         __ j(equal, instr->FalseLabel(chunk_));
2425       }
2426       if (expected.Contains(ToBooleanStub::BOOLEAN)) {
2427         // true -> true.
2428         __ cmp(reg, factory()->true_value());
2429         __ j(equal, instr->TrueLabel(chunk_));
2430         // false -> false.
2431         __ cmp(reg, factory()->false_value());
2432         __ j(equal, instr->FalseLabel(chunk_));
2433       }
2434       if (expected.Contains(ToBooleanStub::NULL_TYPE)) {
2435         // 'null' -> false.
2436         __ cmp(reg, factory()->null_value());
2437         __ j(equal, instr->FalseLabel(chunk_));
2438       }
2439
2440       if (expected.Contains(ToBooleanStub::SMI)) {
2441         // Smis: 0 -> false, all other -> true.
2442         __ test(reg, Operand(reg));
2443         __ j(equal, instr->FalseLabel(chunk_));
2444         __ JumpIfSmi(reg, instr->TrueLabel(chunk_));
2445       } else if (expected.NeedsMap()) {
2446         // If we need a map later and have a Smi -> deopt.
2447         __ test(reg, Immediate(kSmiTagMask));
2448         DeoptimizeIf(zero, instr, Deoptimizer::kSmi);
2449       }
2450
2451       Register map = no_reg;  // Keep the compiler happy.
2452       if (expected.NeedsMap()) {
2453         map = ToRegister(instr->temp());
2454         DCHECK(!map.is(reg));
2455         __ mov(map, FieldOperand(reg, HeapObject::kMapOffset));
2456
2457         if (expected.CanBeUndetectable()) {
2458           // Undetectable -> false.
2459           __ test_b(FieldOperand(map, Map::kBitFieldOffset),
2460                     1 << Map::kIsUndetectable);
2461           __ j(not_zero, instr->FalseLabel(chunk_));
2462         }
2463       }
2464
2465       if (expected.Contains(ToBooleanStub::SPEC_OBJECT)) {
2466         // spec object -> true.
2467         __ CmpInstanceType(map, FIRST_SPEC_OBJECT_TYPE);
2468         __ j(above_equal, instr->TrueLabel(chunk_));
2469       }
2470
2471       if (expected.Contains(ToBooleanStub::STRING)) {
2472         // String value -> false iff empty.
2473         Label not_string;
2474         __ CmpInstanceType(map, FIRST_NONSTRING_TYPE);
2475         __ j(above_equal, &not_string, Label::kNear);
2476         __ cmp(FieldOperand(reg, String::kLengthOffset), Immediate(0));
2477         __ j(not_zero, instr->TrueLabel(chunk_));
2478         __ jmp(instr->FalseLabel(chunk_));
2479         __ bind(&not_string);
2480       }
2481
2482       if (expected.Contains(ToBooleanStub::SYMBOL)) {
2483         // Symbol value -> true.
2484         __ CmpInstanceType(map, SYMBOL_TYPE);
2485         __ j(equal, instr->TrueLabel(chunk_));
2486       }
2487
2488       if (expected.Contains(ToBooleanStub::HEAP_NUMBER)) {
2489         // heap number -> false iff +0, -0, or NaN.
2490         Label not_heap_number;
2491         __ cmp(FieldOperand(reg, HeapObject::kMapOffset),
2492                factory()->heap_number_map());
2493         __ j(not_equal, &not_heap_number, Label::kNear);
2494         __ fldz();
2495         __ fld_d(FieldOperand(reg, HeapNumber::kValueOffset));
2496         __ FCmp();
2497         __ j(zero, instr->FalseLabel(chunk_));
2498         __ jmp(instr->TrueLabel(chunk_));
2499         __ bind(&not_heap_number);
2500       }
2501
2502       if (!expected.IsGeneric()) {
2503         // We've seen something for the first time -> deopt.
2504         // This can only happen if we are not generic already.
2505         DeoptimizeIf(no_condition, instr, Deoptimizer::kUnexpectedObject);
2506       }
2507     }
2508   }
2509 }
2510
2511
2512 void LCodeGen::EmitGoto(int block) {
2513   if (!IsNextEmittedBlock(block)) {
2514     __ jmp(chunk_->GetAssemblyLabel(LookupDestination(block)));
2515   }
2516 }
2517
2518
2519 void LCodeGen::DoClobberDoubles(LClobberDoubles* instr) {
2520 }
2521
2522
2523 void LCodeGen::DoGoto(LGoto* instr) {
2524   EmitGoto(instr->block_id());
2525 }
2526
2527
2528 Condition LCodeGen::TokenToCondition(Token::Value op, bool is_unsigned) {
2529   Condition cond = no_condition;
2530   switch (op) {
2531     case Token::EQ:
2532     case Token::EQ_STRICT:
2533       cond = equal;
2534       break;
2535     case Token::NE:
2536     case Token::NE_STRICT:
2537       cond = not_equal;
2538       break;
2539     case Token::LT:
2540       cond = is_unsigned ? below : less;
2541       break;
2542     case Token::GT:
2543       cond = is_unsigned ? above : greater;
2544       break;
2545     case Token::LTE:
2546       cond = is_unsigned ? below_equal : less_equal;
2547       break;
2548     case Token::GTE:
2549       cond = is_unsigned ? above_equal : greater_equal;
2550       break;
2551     case Token::IN:
2552     case Token::INSTANCEOF:
2553     default:
2554       UNREACHABLE();
2555   }
2556   return cond;
2557 }
2558
2559
2560 void LCodeGen::DoCompareNumericAndBranch(LCompareNumericAndBranch* instr) {
2561   LOperand* left = instr->left();
2562   LOperand* right = instr->right();
2563   bool is_unsigned =
2564       instr->is_double() ||
2565       instr->hydrogen()->left()->CheckFlag(HInstruction::kUint32) ||
2566       instr->hydrogen()->right()->CheckFlag(HInstruction::kUint32);
2567   Condition cc = TokenToCondition(instr->op(), is_unsigned);
2568
2569   if (left->IsConstantOperand() && right->IsConstantOperand()) {
2570     // We can statically evaluate the comparison.
2571     double left_val = ToDouble(LConstantOperand::cast(left));
2572     double right_val = ToDouble(LConstantOperand::cast(right));
2573     int next_block = EvalComparison(instr->op(), left_val, right_val) ?
2574         instr->TrueDestination(chunk_) : instr->FalseDestination(chunk_);
2575     EmitGoto(next_block);
2576   } else {
2577     if (instr->is_double()) {
2578       X87LoadForUsage(ToX87Register(right), ToX87Register(left));
2579       __ FCmp();
2580       // Don't base result on EFLAGS when a NaN is involved. Instead
2581       // jump to the false block.
2582       __ j(parity_even, instr->FalseLabel(chunk_));
2583     } else {
2584       if (right->IsConstantOperand()) {
2585         __ cmp(ToOperand(left),
2586                ToImmediate(right, instr->hydrogen()->representation()));
2587       } else if (left->IsConstantOperand()) {
2588         __ cmp(ToOperand(right),
2589                ToImmediate(left, instr->hydrogen()->representation()));
2590         // We commuted the operands, so commute the condition.
2591         cc = CommuteCondition(cc);
2592       } else {
2593         __ cmp(ToRegister(left), ToOperand(right));
2594       }
2595     }
2596     EmitBranch(instr, cc);
2597   }
2598 }
2599
2600
2601 void LCodeGen::DoCmpObjectEqAndBranch(LCmpObjectEqAndBranch* instr) {
2602   Register left = ToRegister(instr->left());
2603
2604   if (instr->right()->IsConstantOperand()) {
2605     Handle<Object> right = ToHandle(LConstantOperand::cast(instr->right()));
2606     __ CmpObject(left, right);
2607   } else {
2608     Operand right = ToOperand(instr->right());
2609     __ cmp(left, right);
2610   }
2611   EmitBranch(instr, equal);
2612 }
2613
2614
2615 void LCodeGen::DoCmpHoleAndBranch(LCmpHoleAndBranch* instr) {
2616   if (instr->hydrogen()->representation().IsTagged()) {
2617     Register input_reg = ToRegister(instr->object());
2618     __ cmp(input_reg, factory()->the_hole_value());
2619     EmitBranch(instr, equal);
2620     return;
2621   }
2622
2623   // Put the value to the top of stack
2624   X87Register src = ToX87Register(instr->object());
2625   X87LoadForUsage(src);
2626   __ fld(0);
2627   __ fld(0);
2628   __ FCmp();
2629   Label ok;
2630   __ j(parity_even, &ok, Label::kNear);
2631   __ fstp(0);
2632   EmitFalseBranch(instr, no_condition);
2633   __ bind(&ok);
2634
2635
2636   __ sub(esp, Immediate(kDoubleSize));
2637   __ fstp_d(MemOperand(esp, 0));
2638
2639   __ add(esp, Immediate(kDoubleSize));
2640   int offset = sizeof(kHoleNanUpper32);
2641   // x87 converts sNaN(0xfff7fffffff7ffff) to QNaN(0xfffffffffff7ffff),
2642   // so we check the upper with 0xffffffff for hole as a temporary fix.
2643   __ cmp(MemOperand(esp, -offset), Immediate(0xffffffff));
2644   EmitBranch(instr, equal);
2645 }
2646
2647
2648 void LCodeGen::DoCompareMinusZeroAndBranch(LCompareMinusZeroAndBranch* instr) {
2649   Representation rep = instr->hydrogen()->value()->representation();
2650   DCHECK(!rep.IsInteger32());
2651
2652   if (rep.IsDouble()) {
2653     X87Register input = ToX87Register(instr->value());
2654     X87LoadForUsage(input);
2655     __ FXamMinusZero();
2656     EmitBranch(instr, equal);
2657   } else {
2658     Register value = ToRegister(instr->value());
2659     Handle<Map> map = masm()->isolate()->factory()->heap_number_map();
2660     __ CheckMap(value, map, instr->FalseLabel(chunk()), DO_SMI_CHECK);
2661     __ cmp(FieldOperand(value, HeapNumber::kExponentOffset),
2662            Immediate(0x1));
2663     EmitFalseBranch(instr, no_overflow);
2664     __ cmp(FieldOperand(value, HeapNumber::kMantissaOffset),
2665            Immediate(0x00000000));
2666     EmitBranch(instr, equal);
2667   }
2668 }
2669
2670
2671 Condition LCodeGen::EmitIsObject(Register input,
2672                                  Register temp1,
2673                                  Label* is_not_object,
2674                                  Label* is_object) {
2675   __ JumpIfSmi(input, is_not_object);
2676
2677   __ cmp(input, isolate()->factory()->null_value());
2678   __ j(equal, is_object);
2679
2680   __ mov(temp1, FieldOperand(input, HeapObject::kMapOffset));
2681   // Undetectable objects behave like undefined.
2682   __ test_b(FieldOperand(temp1, Map::kBitFieldOffset),
2683             1 << Map::kIsUndetectable);
2684   __ j(not_zero, is_not_object);
2685
2686   __ movzx_b(temp1, FieldOperand(temp1, Map::kInstanceTypeOffset));
2687   __ cmp(temp1, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE);
2688   __ j(below, is_not_object);
2689   __ cmp(temp1, LAST_NONCALLABLE_SPEC_OBJECT_TYPE);
2690   return below_equal;
2691 }
2692
2693
2694 void LCodeGen::DoIsObjectAndBranch(LIsObjectAndBranch* instr) {
2695   Register reg = ToRegister(instr->value());
2696   Register temp = ToRegister(instr->temp());
2697
2698   Condition true_cond = EmitIsObject(
2699       reg, temp, instr->FalseLabel(chunk_), instr->TrueLabel(chunk_));
2700
2701   EmitBranch(instr, true_cond);
2702 }
2703
2704
2705 Condition LCodeGen::EmitIsString(Register input,
2706                                  Register temp1,
2707                                  Label* is_not_string,
2708                                  SmiCheck check_needed = INLINE_SMI_CHECK) {
2709   if (check_needed == INLINE_SMI_CHECK) {
2710     __ JumpIfSmi(input, is_not_string);
2711   }
2712
2713   Condition cond = masm_->IsObjectStringType(input, temp1, temp1);
2714
2715   return cond;
2716 }
2717
2718
2719 void LCodeGen::DoIsStringAndBranch(LIsStringAndBranch* instr) {
2720   Register reg = ToRegister(instr->value());
2721   Register temp = ToRegister(instr->temp());
2722
2723   SmiCheck check_needed =
2724       instr->hydrogen()->value()->type().IsHeapObject()
2725           ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
2726
2727   Condition true_cond = EmitIsString(
2728       reg, temp, instr->FalseLabel(chunk_), check_needed);
2729
2730   EmitBranch(instr, true_cond);
2731 }
2732
2733
2734 void LCodeGen::DoIsSmiAndBranch(LIsSmiAndBranch* instr) {
2735   Operand input = ToOperand(instr->value());
2736
2737   __ test(input, Immediate(kSmiTagMask));
2738   EmitBranch(instr, zero);
2739 }
2740
2741
2742 void LCodeGen::DoIsUndetectableAndBranch(LIsUndetectableAndBranch* instr) {
2743   Register input = ToRegister(instr->value());
2744   Register temp = ToRegister(instr->temp());
2745
2746   if (!instr->hydrogen()->value()->type().IsHeapObject()) {
2747     STATIC_ASSERT(kSmiTag == 0);
2748     __ JumpIfSmi(input, instr->FalseLabel(chunk_));
2749   }
2750   __ mov(temp, FieldOperand(input, HeapObject::kMapOffset));
2751   __ test_b(FieldOperand(temp, Map::kBitFieldOffset),
2752             1 << Map::kIsUndetectable);
2753   EmitBranch(instr, not_zero);
2754 }
2755
2756
2757 static Condition ComputeCompareCondition(Token::Value op) {
2758   switch (op) {
2759     case Token::EQ_STRICT:
2760     case Token::EQ:
2761       return equal;
2762     case Token::LT:
2763       return less;
2764     case Token::GT:
2765       return greater;
2766     case Token::LTE:
2767       return less_equal;
2768     case Token::GTE:
2769       return greater_equal;
2770     default:
2771       UNREACHABLE();
2772       return no_condition;
2773   }
2774 }
2775
2776
2777 void LCodeGen::DoStringCompareAndBranch(LStringCompareAndBranch* instr) {
2778   Token::Value op = instr->op();
2779
2780   Handle<Code> ic = CodeFactory::CompareIC(isolate(), op).code();
2781   CallCode(ic, RelocInfo::CODE_TARGET, instr);
2782
2783   Condition condition = ComputeCompareCondition(op);
2784   __ test(eax, Operand(eax));
2785
2786   EmitBranch(instr, condition);
2787 }
2788
2789
2790 static InstanceType TestType(HHasInstanceTypeAndBranch* instr) {
2791   InstanceType from = instr->from();
2792   InstanceType to = instr->to();
2793   if (from == FIRST_TYPE) return to;
2794   DCHECK(from == to || to == LAST_TYPE);
2795   return from;
2796 }
2797
2798
2799 static Condition BranchCondition(HHasInstanceTypeAndBranch* instr) {
2800   InstanceType from = instr->from();
2801   InstanceType to = instr->to();
2802   if (from == to) return equal;
2803   if (to == LAST_TYPE) return above_equal;
2804   if (from == FIRST_TYPE) return below_equal;
2805   UNREACHABLE();
2806   return equal;
2807 }
2808
2809
2810 void LCodeGen::DoHasInstanceTypeAndBranch(LHasInstanceTypeAndBranch* instr) {
2811   Register input = ToRegister(instr->value());
2812   Register temp = ToRegister(instr->temp());
2813
2814   if (!instr->hydrogen()->value()->type().IsHeapObject()) {
2815     __ JumpIfSmi(input, instr->FalseLabel(chunk_));
2816   }
2817
2818   __ CmpObjectType(input, TestType(instr->hydrogen()), temp);
2819   EmitBranch(instr, BranchCondition(instr->hydrogen()));
2820 }
2821
2822
2823 void LCodeGen::DoGetCachedArrayIndex(LGetCachedArrayIndex* instr) {
2824   Register input = ToRegister(instr->value());
2825   Register result = ToRegister(instr->result());
2826
2827   __ AssertString(input);
2828
2829   __ mov(result, FieldOperand(input, String::kHashFieldOffset));
2830   __ IndexFromHash(result, result);
2831 }
2832
2833
2834 void LCodeGen::DoHasCachedArrayIndexAndBranch(
2835     LHasCachedArrayIndexAndBranch* instr) {
2836   Register input = ToRegister(instr->value());
2837
2838   __ test(FieldOperand(input, String::kHashFieldOffset),
2839           Immediate(String::kContainsCachedArrayIndexMask));
2840   EmitBranch(instr, equal);
2841 }
2842
2843
2844 // Branches to a label or falls through with the answer in the z flag.  Trashes
2845 // the temp registers, but not the input.
2846 void LCodeGen::EmitClassOfTest(Label* is_true,
2847                                Label* is_false,
2848                                Handle<String>class_name,
2849                                Register input,
2850                                Register temp,
2851                                Register temp2) {
2852   DCHECK(!input.is(temp));
2853   DCHECK(!input.is(temp2));
2854   DCHECK(!temp.is(temp2));
2855   __ JumpIfSmi(input, is_false);
2856
2857   if (String::Equals(isolate()->factory()->Function_string(), class_name)) {
2858     // Assuming the following assertions, we can use the same compares to test
2859     // for both being a function type and being in the object type range.
2860     STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
2861     STATIC_ASSERT(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE ==
2862                   FIRST_SPEC_OBJECT_TYPE + 1);
2863     STATIC_ASSERT(LAST_NONCALLABLE_SPEC_OBJECT_TYPE ==
2864                   LAST_SPEC_OBJECT_TYPE - 1);
2865     STATIC_ASSERT(LAST_SPEC_OBJECT_TYPE == LAST_TYPE);
2866     __ CmpObjectType(input, FIRST_SPEC_OBJECT_TYPE, temp);
2867     __ j(below, is_false);
2868     __ j(equal, is_true);
2869     __ CmpInstanceType(temp, LAST_SPEC_OBJECT_TYPE);
2870     __ j(equal, is_true);
2871   } else {
2872     // Faster code path to avoid two compares: subtract lower bound from the
2873     // actual type and do a signed compare with the width of the type range.
2874     __ mov(temp, FieldOperand(input, HeapObject::kMapOffset));
2875     __ movzx_b(temp2, FieldOperand(temp, Map::kInstanceTypeOffset));
2876     __ sub(Operand(temp2), Immediate(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE));
2877     __ cmp(Operand(temp2), Immediate(LAST_NONCALLABLE_SPEC_OBJECT_TYPE -
2878                                      FIRST_NONCALLABLE_SPEC_OBJECT_TYPE));
2879     __ j(above, is_false);
2880   }
2881
2882   // Now we are in the FIRST-LAST_NONCALLABLE_SPEC_OBJECT_TYPE range.
2883   // Check if the constructor in the map is a function.
2884   __ GetMapConstructor(temp, temp, temp2);
2885   // Objects with a non-function constructor have class 'Object'.
2886   __ CmpInstanceType(temp2, JS_FUNCTION_TYPE);
2887   if (String::Equals(class_name, isolate()->factory()->Object_string())) {
2888     __ j(not_equal, is_true);
2889   } else {
2890     __ j(not_equal, is_false);
2891   }
2892
2893   // temp now contains the constructor function. Grab the
2894   // instance class name from there.
2895   __ mov(temp, FieldOperand(temp, JSFunction::kSharedFunctionInfoOffset));
2896   __ mov(temp, FieldOperand(temp,
2897                             SharedFunctionInfo::kInstanceClassNameOffset));
2898   // The class name we are testing against is internalized since it's a literal.
2899   // The name in the constructor is internalized because of the way the context
2900   // is booted.  This routine isn't expected to work for random API-created
2901   // classes and it doesn't have to because you can't access it with natives
2902   // syntax.  Since both sides are internalized it is sufficient to use an
2903   // identity comparison.
2904   __ cmp(temp, class_name);
2905   // End with the answer in the z flag.
2906 }
2907
2908
2909 void LCodeGen::DoClassOfTestAndBranch(LClassOfTestAndBranch* instr) {
2910   Register input = ToRegister(instr->value());
2911   Register temp = ToRegister(instr->temp());
2912   Register temp2 = ToRegister(instr->temp2());
2913
2914   Handle<String> class_name = instr->hydrogen()->class_name();
2915
2916   EmitClassOfTest(instr->TrueLabel(chunk_), instr->FalseLabel(chunk_),
2917       class_name, input, temp, temp2);
2918
2919   EmitBranch(instr, equal);
2920 }
2921
2922
2923 void LCodeGen::DoCmpMapAndBranch(LCmpMapAndBranch* instr) {
2924   Register reg = ToRegister(instr->value());
2925   __ cmp(FieldOperand(reg, HeapObject::kMapOffset), instr->map());
2926   EmitBranch(instr, equal);
2927 }
2928
2929
2930 void LCodeGen::DoInstanceOf(LInstanceOf* instr) {
2931   // Object and function are in fixed registers defined by the stub.
2932   DCHECK(ToRegister(instr->context()).is(esi));
2933   InstanceofStub stub(isolate(), InstanceofStub::kArgsInRegisters);
2934   CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
2935
2936   Label true_value, done;
2937   __ test(eax, Operand(eax));
2938   __ j(zero, &true_value, Label::kNear);
2939   __ mov(ToRegister(instr->result()), factory()->false_value());
2940   __ jmp(&done, Label::kNear);
2941   __ bind(&true_value);
2942   __ mov(ToRegister(instr->result()), factory()->true_value());
2943   __ bind(&done);
2944 }
2945
2946
2947 void LCodeGen::DoInstanceOfKnownGlobal(LInstanceOfKnownGlobal* instr) {
2948   class DeferredInstanceOfKnownGlobal FINAL : public LDeferredCode {
2949    public:
2950     DeferredInstanceOfKnownGlobal(LCodeGen* codegen,
2951                                   LInstanceOfKnownGlobal* instr,
2952                                   const X87Stack& x87_stack)
2953         : LDeferredCode(codegen, x87_stack), instr_(instr) { }
2954     void Generate() OVERRIDE {
2955       codegen()->DoDeferredInstanceOfKnownGlobal(instr_, &map_check_);
2956     }
2957     LInstruction* instr() OVERRIDE { return instr_; }
2958     Label* map_check() { return &map_check_; }
2959    private:
2960     LInstanceOfKnownGlobal* instr_;
2961     Label map_check_;
2962   };
2963
2964   DeferredInstanceOfKnownGlobal* deferred;
2965   deferred = new(zone()) DeferredInstanceOfKnownGlobal(this, instr, x87_stack_);
2966
2967   Label done, false_result;
2968   Register object = ToRegister(instr->value());
2969   Register temp = ToRegister(instr->temp());
2970
2971   // A Smi is not an instance of anything.
2972   __ JumpIfSmi(object, &false_result, Label::kNear);
2973
2974   // This is the inlined call site instanceof cache. The two occurences of the
2975   // hole value will be patched to the last map/result pair generated by the
2976   // instanceof stub.
2977   Label cache_miss;
2978   Register map = ToRegister(instr->temp());
2979   __ mov(map, FieldOperand(object, HeapObject::kMapOffset));
2980   __ bind(deferred->map_check());  // Label for calculating code patching.
2981   Handle<Cell> cache_cell = factory()->NewCell(factory()->the_hole_value());
2982   __ cmp(map, Operand::ForCell(cache_cell));  // Patched to cached map.
2983   __ j(not_equal, &cache_miss, Label::kNear);
2984   __ mov(eax, factory()->the_hole_value());  // Patched to either true or false.
2985   __ jmp(&done, Label::kNear);
2986
2987   // The inlined call site cache did not match. Check for null and string
2988   // before calling the deferred code.
2989   __ bind(&cache_miss);
2990   // Null is not an instance of anything.
2991   __ cmp(object, factory()->null_value());
2992   __ j(equal, &false_result, Label::kNear);
2993
2994   // String values are not instances of anything.
2995   Condition is_string = masm_->IsObjectStringType(object, temp, temp);
2996   __ j(is_string, &false_result, Label::kNear);
2997
2998   // Go to the deferred code.
2999   __ jmp(deferred->entry());
3000
3001   __ bind(&false_result);
3002   __ mov(ToRegister(instr->result()), factory()->false_value());
3003
3004   // Here result has either true or false. Deferred code also produces true or
3005   // false object.
3006   __ bind(deferred->exit());
3007   __ bind(&done);
3008 }
3009
3010
3011 void LCodeGen::DoDeferredInstanceOfKnownGlobal(LInstanceOfKnownGlobal* instr,
3012                                                Label* map_check) {
3013   PushSafepointRegistersScope scope(this);
3014
3015   InstanceofStub::Flags flags = InstanceofStub::kNoFlags;
3016   flags = static_cast<InstanceofStub::Flags>(
3017       flags | InstanceofStub::kArgsInRegisters);
3018   flags = static_cast<InstanceofStub::Flags>(
3019       flags | InstanceofStub::kCallSiteInlineCheck);
3020   flags = static_cast<InstanceofStub::Flags>(
3021       flags | InstanceofStub::kReturnTrueFalseObject);
3022   InstanceofStub stub(isolate(), flags);
3023
3024   // Get the temp register reserved by the instruction. This needs to be a
3025   // register which is pushed last by PushSafepointRegisters as top of the
3026   // stack is used to pass the offset to the location of the map check to
3027   // the stub.
3028   Register temp = ToRegister(instr->temp());
3029   DCHECK(MacroAssembler::SafepointRegisterStackIndex(temp) == 0);
3030   __ LoadHeapObject(InstanceofStub::right(), instr->function());
3031   static const int kAdditionalDelta = 13;
3032   int delta = masm_->SizeOfCodeGeneratedSince(map_check) + kAdditionalDelta;
3033   __ mov(temp, Immediate(delta));
3034   __ StoreToSafepointRegisterSlot(temp, temp);
3035   CallCodeGeneric(stub.GetCode(),
3036                   RelocInfo::CODE_TARGET,
3037                   instr,
3038                   RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
3039   // Get the deoptimization index of the LLazyBailout-environment that
3040   // corresponds to this instruction.
3041   LEnvironment* env = instr->GetDeferredLazyDeoptimizationEnvironment();
3042   safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
3043
3044   // Put the result value into the eax slot and restore all registers.
3045   __ StoreToSafepointRegisterSlot(eax, eax);
3046 }
3047
3048
3049 void LCodeGen::DoCmpT(LCmpT* instr) {
3050   Token::Value op = instr->op();
3051
3052   Handle<Code> ic = CodeFactory::CompareIC(isolate(), op).code();
3053   CallCode(ic, RelocInfo::CODE_TARGET, instr);
3054
3055   Condition condition = ComputeCompareCondition(op);
3056   Label true_value, done;
3057   __ test(eax, Operand(eax));
3058   __ j(condition, &true_value, Label::kNear);
3059   __ mov(ToRegister(instr->result()), factory()->false_value());
3060   __ jmp(&done, Label::kNear);
3061   __ bind(&true_value);
3062   __ mov(ToRegister(instr->result()), factory()->true_value());
3063   __ bind(&done);
3064 }
3065
3066
3067 void LCodeGen::EmitReturn(LReturn* instr, bool dynamic_frame_alignment) {
3068   int extra_value_count = dynamic_frame_alignment ? 2 : 1;
3069
3070   if (instr->has_constant_parameter_count()) {
3071     int parameter_count = ToInteger32(instr->constant_parameter_count());
3072     if (dynamic_frame_alignment && FLAG_debug_code) {
3073       __ cmp(Operand(esp,
3074                      (parameter_count + extra_value_count) * kPointerSize),
3075              Immediate(kAlignmentZapValue));
3076       __ Assert(equal, kExpectedAlignmentMarker);
3077     }
3078     __ Ret((parameter_count + extra_value_count) * kPointerSize, ecx);
3079   } else {
3080     DCHECK(info()->IsStub());  // Functions would need to drop one more value.
3081     Register reg = ToRegister(instr->parameter_count());
3082     // The argument count parameter is a smi
3083     __ SmiUntag(reg);
3084     Register return_addr_reg = reg.is(ecx) ? ebx : ecx;
3085     if (dynamic_frame_alignment && FLAG_debug_code) {
3086       DCHECK(extra_value_count == 2);
3087       __ cmp(Operand(esp, reg, times_pointer_size,
3088                      extra_value_count * kPointerSize),
3089              Immediate(kAlignmentZapValue));
3090       __ Assert(equal, kExpectedAlignmentMarker);
3091     }
3092
3093     // emit code to restore stack based on instr->parameter_count()
3094     __ pop(return_addr_reg);  // save return address
3095     if (dynamic_frame_alignment) {
3096       __ inc(reg);  // 1 more for alignment
3097     }
3098     __ shl(reg, kPointerSizeLog2);
3099     __ add(esp, reg);
3100     __ jmp(return_addr_reg);
3101   }
3102 }
3103
3104
3105 void LCodeGen::DoReturn(LReturn* instr) {
3106   if (FLAG_trace && info()->IsOptimizing()) {
3107     // Preserve the return value on the stack and rely on the runtime call
3108     // to return the value in the same register.  We're leaving the code
3109     // managed by the register allocator and tearing down the frame, it's
3110     // safe to write to the context register.
3111     __ push(eax);
3112     __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
3113     __ CallRuntime(Runtime::kTraceExit, 1);
3114   }
3115   if (dynamic_frame_alignment_) {
3116     // Fetch the state of the dynamic frame alignment.
3117     __ mov(edx, Operand(ebp,
3118       JavaScriptFrameConstants::kDynamicAlignmentStateOffset));
3119   }
3120   int no_frame_start = -1;
3121   if (NeedsEagerFrame()) {
3122     __ mov(esp, ebp);
3123     __ pop(ebp);
3124     no_frame_start = masm_->pc_offset();
3125   }
3126   if (dynamic_frame_alignment_) {
3127     Label no_padding;
3128     __ cmp(edx, Immediate(kNoAlignmentPadding));
3129     __ j(equal, &no_padding, Label::kNear);
3130
3131     EmitReturn(instr, true);
3132     __ bind(&no_padding);
3133   }
3134
3135   EmitReturn(instr, false);
3136   if (no_frame_start != -1) {
3137     info()->AddNoFrameRange(no_frame_start, masm_->pc_offset());
3138   }
3139 }
3140
3141
3142 template <class T>
3143 void LCodeGen::EmitVectorLoadICRegisters(T* instr) {
3144   DCHECK(FLAG_vector_ics);
3145   Register vector_register = ToRegister(instr->temp_vector());
3146   Register slot_register = VectorLoadICDescriptor::SlotRegister();
3147   DCHECK(vector_register.is(VectorLoadICDescriptor::VectorRegister()));
3148   DCHECK(slot_register.is(eax));
3149
3150   AllowDeferredHandleDereference vector_structure_check;
3151   Handle<TypeFeedbackVector> vector = instr->hydrogen()->feedback_vector();
3152   __ mov(vector_register, vector);
3153   // No need to allocate this register.
3154   FeedbackVectorICSlot slot = instr->hydrogen()->slot();
3155   int index = vector->GetIndex(slot);
3156   __ mov(slot_register, Immediate(Smi::FromInt(index)));
3157 }
3158
3159
3160 void LCodeGen::DoLoadGlobalGeneric(LLoadGlobalGeneric* instr) {
3161   DCHECK(ToRegister(instr->context()).is(esi));
3162   DCHECK(ToRegister(instr->global_object())
3163              .is(LoadDescriptor::ReceiverRegister()));
3164   DCHECK(ToRegister(instr->result()).is(eax));
3165
3166   __ mov(LoadDescriptor::NameRegister(), instr->name());
3167   if (FLAG_vector_ics) {
3168     EmitVectorLoadICRegisters<LLoadGlobalGeneric>(instr);
3169   }
3170   ContextualMode mode = instr->for_typeof() ? NOT_CONTEXTUAL : CONTEXTUAL;
3171   Handle<Code> ic = CodeFactory::LoadICInOptimizedCode(isolate(), mode,
3172                                                        PREMONOMORPHIC).code();
3173   CallCode(ic, RelocInfo::CODE_TARGET, instr);
3174 }
3175
3176
3177 void LCodeGen::DoLoadContextSlot(LLoadContextSlot* instr) {
3178   Register context = ToRegister(instr->context());
3179   Register result = ToRegister(instr->result());
3180   __ mov(result, ContextOperand(context, instr->slot_index()));
3181
3182   if (instr->hydrogen()->RequiresHoleCheck()) {
3183     __ cmp(result, factory()->the_hole_value());
3184     if (instr->hydrogen()->DeoptimizesOnHole()) {
3185       DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3186     } else {
3187       Label is_not_hole;
3188       __ j(not_equal, &is_not_hole, Label::kNear);
3189       __ mov(result, factory()->undefined_value());
3190       __ bind(&is_not_hole);
3191     }
3192   }
3193 }
3194
3195
3196 void LCodeGen::DoStoreContextSlot(LStoreContextSlot* instr) {
3197   Register context = ToRegister(instr->context());
3198   Register value = ToRegister(instr->value());
3199
3200   Label skip_assignment;
3201
3202   Operand target = ContextOperand(context, instr->slot_index());
3203   if (instr->hydrogen()->RequiresHoleCheck()) {
3204     __ cmp(target, factory()->the_hole_value());
3205     if (instr->hydrogen()->DeoptimizesOnHole()) {
3206       DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3207     } else {
3208       __ j(not_equal, &skip_assignment, Label::kNear);
3209     }
3210   }
3211
3212   __ mov(target, value);
3213   if (instr->hydrogen()->NeedsWriteBarrier()) {
3214     SmiCheck check_needed =
3215         instr->hydrogen()->value()->type().IsHeapObject()
3216             ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
3217     Register temp = ToRegister(instr->temp());
3218     int offset = Context::SlotOffset(instr->slot_index());
3219     __ RecordWriteContextSlot(context, offset, value, temp, kSaveFPRegs,
3220                               EMIT_REMEMBERED_SET, check_needed);
3221   }
3222
3223   __ bind(&skip_assignment);
3224 }
3225
3226
3227 void LCodeGen::DoLoadNamedField(LLoadNamedField* instr) {
3228   HObjectAccess access = instr->hydrogen()->access();
3229   int offset = access.offset();
3230
3231   if (access.IsExternalMemory()) {
3232     Register result = ToRegister(instr->result());
3233     MemOperand operand = instr->object()->IsConstantOperand()
3234         ? MemOperand::StaticVariable(ToExternalReference(
3235                 LConstantOperand::cast(instr->object())))
3236         : MemOperand(ToRegister(instr->object()), offset);
3237     __ Load(result, operand, access.representation());
3238     return;
3239   }
3240
3241   Register object = ToRegister(instr->object());
3242   if (instr->hydrogen()->representation().IsDouble()) {
3243     X87Mov(ToX87Register(instr->result()), FieldOperand(object, offset));
3244     return;
3245   }
3246
3247   Register result = ToRegister(instr->result());
3248   if (!access.IsInobject()) {
3249     __ mov(result, FieldOperand(object, JSObject::kPropertiesOffset));
3250     object = result;
3251   }
3252   __ Load(result, FieldOperand(object, offset), access.representation());
3253 }
3254
3255
3256 void LCodeGen::EmitPushTaggedOperand(LOperand* operand) {
3257   DCHECK(!operand->IsDoubleRegister());
3258   if (operand->IsConstantOperand()) {
3259     Handle<Object> object = ToHandle(LConstantOperand::cast(operand));
3260     AllowDeferredHandleDereference smi_check;
3261     if (object->IsSmi()) {
3262       __ Push(Handle<Smi>::cast(object));
3263     } else {
3264       __ PushHeapObject(Handle<HeapObject>::cast(object));
3265     }
3266   } else if (operand->IsRegister()) {
3267     __ push(ToRegister(operand));
3268   } else {
3269     __ push(ToOperand(operand));
3270   }
3271 }
3272
3273
3274 void LCodeGen::DoLoadNamedGeneric(LLoadNamedGeneric* instr) {
3275   DCHECK(ToRegister(instr->context()).is(esi));
3276   DCHECK(ToRegister(instr->object()).is(LoadDescriptor::ReceiverRegister()));
3277   DCHECK(ToRegister(instr->result()).is(eax));
3278
3279   __ mov(LoadDescriptor::NameRegister(), instr->name());
3280   if (FLAG_vector_ics) {
3281     EmitVectorLoadICRegisters<LLoadNamedGeneric>(instr);
3282   }
3283   Handle<Code> ic = CodeFactory::LoadICInOptimizedCode(
3284                         isolate(), NOT_CONTEXTUAL,
3285                         instr->hydrogen()->initialization_state()).code();
3286   CallCode(ic, RelocInfo::CODE_TARGET, instr);
3287 }
3288
3289
3290 void LCodeGen::DoLoadFunctionPrototype(LLoadFunctionPrototype* instr) {
3291   Register function = ToRegister(instr->function());
3292   Register temp = ToRegister(instr->temp());
3293   Register result = ToRegister(instr->result());
3294
3295   // Get the prototype or initial map from the function.
3296   __ mov(result,
3297          FieldOperand(function, JSFunction::kPrototypeOrInitialMapOffset));
3298
3299   // Check that the function has a prototype or an initial map.
3300   __ cmp(Operand(result), Immediate(factory()->the_hole_value()));
3301   DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3302
3303   // If the function does not have an initial map, we're done.
3304   Label done;
3305   __ CmpObjectType(result, MAP_TYPE, temp);
3306   __ j(not_equal, &done, Label::kNear);
3307
3308   // Get the prototype from the initial map.
3309   __ mov(result, FieldOperand(result, Map::kPrototypeOffset));
3310
3311   // All done.
3312   __ bind(&done);
3313 }
3314
3315
3316 void LCodeGen::DoLoadRoot(LLoadRoot* instr) {
3317   Register result = ToRegister(instr->result());
3318   __ LoadRoot(result, instr->index());
3319 }
3320
3321
3322 void LCodeGen::DoAccessArgumentsAt(LAccessArgumentsAt* instr) {
3323   Register arguments = ToRegister(instr->arguments());
3324   Register result = ToRegister(instr->result());
3325   if (instr->length()->IsConstantOperand() &&
3326       instr->index()->IsConstantOperand()) {
3327     int const_index = ToInteger32(LConstantOperand::cast(instr->index()));
3328     int const_length = ToInteger32(LConstantOperand::cast(instr->length()));
3329     int index = (const_length - const_index) + 1;
3330     __ mov(result, Operand(arguments, index * kPointerSize));
3331   } else {
3332     Register length = ToRegister(instr->length());
3333     Operand index = ToOperand(instr->index());
3334     // There are two words between the frame pointer and the last argument.
3335     // Subtracting from length accounts for one of them add one more.
3336     __ sub(length, index);
3337     __ mov(result, Operand(arguments, length, times_4, kPointerSize));
3338   }
3339 }
3340
3341
3342 void LCodeGen::DoLoadKeyedExternalArray(LLoadKeyed* instr) {
3343   ElementsKind elements_kind = instr->elements_kind();
3344   LOperand* key = instr->key();
3345   if (!key->IsConstantOperand() &&
3346       ExternalArrayOpRequiresTemp(instr->hydrogen()->key()->representation(),
3347                                   elements_kind)) {
3348     __ SmiUntag(ToRegister(key));
3349   }
3350   Operand operand(BuildFastArrayOperand(
3351       instr->elements(),
3352       key,
3353       instr->hydrogen()->key()->representation(),
3354       elements_kind,
3355       instr->base_offset()));
3356   if (elements_kind == EXTERNAL_FLOAT32_ELEMENTS ||
3357       elements_kind == FLOAT32_ELEMENTS) {
3358     X87Mov(ToX87Register(instr->result()), operand, kX87FloatOperand);
3359   } else if (elements_kind == EXTERNAL_FLOAT64_ELEMENTS ||
3360              elements_kind == FLOAT64_ELEMENTS) {
3361     X87Mov(ToX87Register(instr->result()), operand);
3362   } else {
3363     Register result(ToRegister(instr->result()));
3364     switch (elements_kind) {
3365       case EXTERNAL_INT8_ELEMENTS:
3366       case INT8_ELEMENTS:
3367         __ movsx_b(result, operand);
3368         break;
3369       case EXTERNAL_UINT8_CLAMPED_ELEMENTS:
3370       case EXTERNAL_UINT8_ELEMENTS:
3371       case UINT8_ELEMENTS:
3372       case UINT8_CLAMPED_ELEMENTS:
3373         __ movzx_b(result, operand);
3374         break;
3375       case EXTERNAL_INT16_ELEMENTS:
3376       case INT16_ELEMENTS:
3377         __ movsx_w(result, operand);
3378         break;
3379       case EXTERNAL_UINT16_ELEMENTS:
3380       case UINT16_ELEMENTS:
3381         __ movzx_w(result, operand);
3382         break;
3383       case EXTERNAL_INT32_ELEMENTS:
3384       case INT32_ELEMENTS:
3385         __ mov(result, operand);
3386         break;
3387       case EXTERNAL_UINT32_ELEMENTS:
3388       case UINT32_ELEMENTS:
3389         __ mov(result, operand);
3390         if (!instr->hydrogen()->CheckFlag(HInstruction::kUint32)) {
3391           __ test(result, Operand(result));
3392           DeoptimizeIf(negative, instr, Deoptimizer::kNegativeValue);
3393         }
3394         break;
3395       case EXTERNAL_FLOAT32_ELEMENTS:
3396       case EXTERNAL_FLOAT64_ELEMENTS:
3397       case FLOAT32_ELEMENTS:
3398       case FLOAT64_ELEMENTS:
3399       case FAST_SMI_ELEMENTS:
3400       case FAST_ELEMENTS:
3401       case FAST_DOUBLE_ELEMENTS:
3402       case FAST_HOLEY_SMI_ELEMENTS:
3403       case FAST_HOLEY_ELEMENTS:
3404       case FAST_HOLEY_DOUBLE_ELEMENTS:
3405       case DICTIONARY_ELEMENTS:
3406       case SLOPPY_ARGUMENTS_ELEMENTS:
3407         UNREACHABLE();
3408         break;
3409     }
3410   }
3411 }
3412
3413
3414 void LCodeGen::DoLoadKeyedFixedDoubleArray(LLoadKeyed* instr) {
3415   if (instr->hydrogen()->RequiresHoleCheck()) {
3416     Operand hole_check_operand = BuildFastArrayOperand(
3417         instr->elements(), instr->key(),
3418         instr->hydrogen()->key()->representation(),
3419         FAST_DOUBLE_ELEMENTS,
3420         instr->base_offset() + sizeof(kHoleNanLower32));
3421     __ cmp(hole_check_operand, Immediate(kHoleNanUpper32));
3422     DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3423   }
3424
3425   Operand double_load_operand = BuildFastArrayOperand(
3426       instr->elements(),
3427       instr->key(),
3428       instr->hydrogen()->key()->representation(),
3429       FAST_DOUBLE_ELEMENTS,
3430       instr->base_offset());
3431   X87Mov(ToX87Register(instr->result()), double_load_operand);
3432 }
3433
3434
3435 void LCodeGen::DoLoadKeyedFixedArray(LLoadKeyed* instr) {
3436   Register result = ToRegister(instr->result());
3437
3438   // Load the result.
3439   __ mov(result,
3440          BuildFastArrayOperand(instr->elements(), instr->key(),
3441                                instr->hydrogen()->key()->representation(),
3442                                FAST_ELEMENTS, instr->base_offset()));
3443
3444   // Check for the hole value.
3445   if (instr->hydrogen()->RequiresHoleCheck()) {
3446     if (IsFastSmiElementsKind(instr->hydrogen()->elements_kind())) {
3447       __ test(result, Immediate(kSmiTagMask));
3448       DeoptimizeIf(not_equal, instr, Deoptimizer::kNotASmi);
3449     } else {
3450       __ cmp(result, factory()->the_hole_value());
3451       DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3452     }
3453   }
3454 }
3455
3456
3457 void LCodeGen::DoLoadKeyed(LLoadKeyed* instr) {
3458   if (instr->is_typed_elements()) {
3459     DoLoadKeyedExternalArray(instr);
3460   } else if (instr->hydrogen()->representation().IsDouble()) {
3461     DoLoadKeyedFixedDoubleArray(instr);
3462   } else {
3463     DoLoadKeyedFixedArray(instr);
3464   }
3465 }
3466
3467
3468 Operand LCodeGen::BuildFastArrayOperand(
3469     LOperand* elements_pointer,
3470     LOperand* key,
3471     Representation key_representation,
3472     ElementsKind elements_kind,
3473     uint32_t base_offset) {
3474   Register elements_pointer_reg = ToRegister(elements_pointer);
3475   int element_shift_size = ElementsKindToShiftSize(elements_kind);
3476   int shift_size = element_shift_size;
3477   if (key->IsConstantOperand()) {
3478     int constant_value = ToInteger32(LConstantOperand::cast(key));
3479     if (constant_value & 0xF0000000) {
3480       Abort(kArrayIndexConstantValueTooBig);
3481     }
3482     return Operand(elements_pointer_reg,
3483                    ((constant_value) << shift_size)
3484                        + base_offset);
3485   } else {
3486     // Take the tag bit into account while computing the shift size.
3487     if (key_representation.IsSmi() && (shift_size >= 1)) {
3488       shift_size -= kSmiTagSize;
3489     }
3490     ScaleFactor scale_factor = static_cast<ScaleFactor>(shift_size);
3491     return Operand(elements_pointer_reg,
3492                    ToRegister(key),
3493                    scale_factor,
3494                    base_offset);
3495   }
3496 }
3497
3498
3499 void LCodeGen::DoLoadKeyedGeneric(LLoadKeyedGeneric* instr) {
3500   DCHECK(ToRegister(instr->context()).is(esi));
3501   DCHECK(ToRegister(instr->object()).is(LoadDescriptor::ReceiverRegister()));
3502   DCHECK(ToRegister(instr->key()).is(LoadDescriptor::NameRegister()));
3503
3504   if (FLAG_vector_ics) {
3505     EmitVectorLoadICRegisters<LLoadKeyedGeneric>(instr);
3506   }
3507
3508   Handle<Code> ic =
3509       CodeFactory::KeyedLoadICInOptimizedCode(
3510           isolate(), instr->hydrogen()->initialization_state()).code();
3511   CallCode(ic, RelocInfo::CODE_TARGET, instr);
3512 }
3513
3514
3515 void LCodeGen::DoArgumentsElements(LArgumentsElements* instr) {
3516   Register result = ToRegister(instr->result());
3517
3518   if (instr->hydrogen()->from_inlined()) {
3519     __ lea(result, Operand(esp, -2 * kPointerSize));
3520   } else {
3521     // Check for arguments adapter frame.
3522     Label done, adapted;
3523     __ mov(result, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3524     __ mov(result, Operand(result, StandardFrameConstants::kContextOffset));
3525     __ cmp(Operand(result),
3526            Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
3527     __ j(equal, &adapted, Label::kNear);
3528
3529     // No arguments adaptor frame.
3530     __ mov(result, Operand(ebp));
3531     __ jmp(&done, Label::kNear);
3532
3533     // Arguments adaptor frame present.
3534     __ bind(&adapted);
3535     __ mov(result, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3536
3537     // Result is the frame pointer for the frame if not adapted and for the real
3538     // frame below the adaptor frame if adapted.
3539     __ bind(&done);
3540   }
3541 }
3542
3543
3544 void LCodeGen::DoArgumentsLength(LArgumentsLength* instr) {
3545   Operand elem = ToOperand(instr->elements());
3546   Register result = ToRegister(instr->result());
3547
3548   Label done;
3549
3550   // If no arguments adaptor frame the number of arguments is fixed.
3551   __ cmp(ebp, elem);
3552   __ mov(result, Immediate(scope()->num_parameters()));
3553   __ j(equal, &done, Label::kNear);
3554
3555   // Arguments adaptor frame present. Get argument length from there.
3556   __ mov(result, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3557   __ mov(result, Operand(result,
3558                          ArgumentsAdaptorFrameConstants::kLengthOffset));
3559   __ SmiUntag(result);
3560
3561   // Argument length is in result register.
3562   __ bind(&done);
3563 }
3564
3565
3566 void LCodeGen::DoWrapReceiver(LWrapReceiver* instr) {
3567   Register receiver = ToRegister(instr->receiver());
3568   Register function = ToRegister(instr->function());
3569
3570   // If the receiver is null or undefined, we have to pass the global
3571   // object as a receiver to normal functions. Values have to be
3572   // passed unchanged to builtins and strict-mode functions.
3573   Label receiver_ok, global_object;
3574   Label::Distance dist = DeoptEveryNTimes() ? Label::kFar : Label::kNear;
3575   Register scratch = ToRegister(instr->temp());
3576
3577   if (!instr->hydrogen()->known_function()) {
3578     // Do not transform the receiver to object for strict mode
3579     // functions.
3580     __ mov(scratch,
3581            FieldOperand(function, JSFunction::kSharedFunctionInfoOffset));
3582     __ test_b(FieldOperand(scratch, SharedFunctionInfo::kStrictModeByteOffset),
3583               1 << SharedFunctionInfo::kStrictModeBitWithinByte);
3584     __ j(not_equal, &receiver_ok, dist);
3585
3586     // Do not transform the receiver to object for builtins.
3587     __ test_b(FieldOperand(scratch, SharedFunctionInfo::kNativeByteOffset),
3588               1 << SharedFunctionInfo::kNativeBitWithinByte);
3589     __ j(not_equal, &receiver_ok, dist);
3590   }
3591
3592   // Normal function. Replace undefined or null with global receiver.
3593   __ cmp(receiver, factory()->null_value());
3594   __ j(equal, &global_object, Label::kNear);
3595   __ cmp(receiver, factory()->undefined_value());
3596   __ j(equal, &global_object, Label::kNear);
3597
3598   // The receiver should be a JS object.
3599   __ test(receiver, Immediate(kSmiTagMask));
3600   DeoptimizeIf(equal, instr, Deoptimizer::kSmi);
3601   __ CmpObjectType(receiver, FIRST_SPEC_OBJECT_TYPE, scratch);
3602   DeoptimizeIf(below, instr, Deoptimizer::kNotAJavaScriptObject);
3603
3604   __ jmp(&receiver_ok, Label::kNear);
3605   __ bind(&global_object);
3606   __ mov(receiver, FieldOperand(function, JSFunction::kContextOffset));
3607   const int global_offset = Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX);
3608   __ mov(receiver, Operand(receiver, global_offset));
3609   const int proxy_offset = GlobalObject::kGlobalProxyOffset;
3610   __ mov(receiver, FieldOperand(receiver, proxy_offset));
3611   __ bind(&receiver_ok);
3612 }
3613
3614
3615 void LCodeGen::DoApplyArguments(LApplyArguments* instr) {
3616   Register receiver = ToRegister(instr->receiver());
3617   Register function = ToRegister(instr->function());
3618   Register length = ToRegister(instr->length());
3619   Register elements = ToRegister(instr->elements());
3620   DCHECK(receiver.is(eax));  // Used for parameter count.
3621   DCHECK(function.is(edi));  // Required by InvokeFunction.
3622   DCHECK(ToRegister(instr->result()).is(eax));
3623
3624   // Copy the arguments to this function possibly from the
3625   // adaptor frame below it.
3626   const uint32_t kArgumentsLimit = 1 * KB;
3627   __ cmp(length, kArgumentsLimit);
3628   DeoptimizeIf(above, instr, Deoptimizer::kTooManyArguments);
3629
3630   __ push(receiver);
3631   __ mov(receiver, length);
3632
3633   // Loop through the arguments pushing them onto the execution
3634   // stack.
3635   Label invoke, loop;
3636   // length is a small non-negative integer, due to the test above.
3637   __ test(length, Operand(length));
3638   __ j(zero, &invoke, Label::kNear);
3639   __ bind(&loop);
3640   __ push(Operand(elements, length, times_pointer_size, 1 * kPointerSize));
3641   __ dec(length);
3642   __ j(not_zero, &loop);
3643
3644   // Invoke the function.
3645   __ bind(&invoke);
3646   DCHECK(instr->HasPointerMap());
3647   LPointerMap* pointers = instr->pointer_map();
3648   SafepointGenerator safepoint_generator(
3649       this, pointers, Safepoint::kLazyDeopt);
3650   ParameterCount actual(eax);
3651   __ InvokeFunction(function, actual, CALL_FUNCTION, safepoint_generator);
3652 }
3653
3654
3655 void LCodeGen::DoDebugBreak(LDebugBreak* instr) {
3656   __ int3();
3657 }
3658
3659
3660 void LCodeGen::DoPushArgument(LPushArgument* instr) {
3661   LOperand* argument = instr->value();
3662   EmitPushTaggedOperand(argument);
3663 }
3664
3665
3666 void LCodeGen::DoDrop(LDrop* instr) {
3667   __ Drop(instr->count());
3668 }
3669
3670
3671 void LCodeGen::DoThisFunction(LThisFunction* instr) {
3672   Register result = ToRegister(instr->result());
3673   __ mov(result, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
3674 }
3675
3676
3677 void LCodeGen::DoContext(LContext* instr) {
3678   Register result = ToRegister(instr->result());
3679   if (info()->IsOptimizing()) {
3680     __ mov(result, Operand(ebp, StandardFrameConstants::kContextOffset));
3681   } else {
3682     // If there is no frame, the context must be in esi.
3683     DCHECK(result.is(esi));
3684   }
3685 }
3686
3687
3688 void LCodeGen::DoDeclareGlobals(LDeclareGlobals* instr) {
3689   DCHECK(ToRegister(instr->context()).is(esi));
3690   __ push(esi);  // The context is the first argument.
3691   __ push(Immediate(instr->hydrogen()->pairs()));
3692   __ push(Immediate(Smi::FromInt(instr->hydrogen()->flags())));
3693   CallRuntime(Runtime::kDeclareGlobals, 3, instr);
3694 }
3695
3696
3697 void LCodeGen::CallKnownFunction(Handle<JSFunction> function,
3698                                  int formal_parameter_count, int arity,
3699                                  LInstruction* instr) {
3700   bool dont_adapt_arguments =
3701       formal_parameter_count == SharedFunctionInfo::kDontAdaptArgumentsSentinel;
3702   bool can_invoke_directly =
3703       dont_adapt_arguments || formal_parameter_count == arity;
3704
3705   Register function_reg = edi;
3706
3707   if (can_invoke_directly) {
3708     // Change context.
3709     __ mov(esi, FieldOperand(function_reg, JSFunction::kContextOffset));
3710
3711     // Set eax to arguments count if adaption is not needed. Assumes that eax
3712     // is available to write to at this point.
3713     if (dont_adapt_arguments) {
3714       __ mov(eax, arity);
3715     }
3716
3717     // Invoke function directly.
3718     if (function.is_identical_to(info()->closure())) {
3719       __ CallSelf();
3720     } else {
3721       __ call(FieldOperand(function_reg, JSFunction::kCodeEntryOffset));
3722     }
3723     RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
3724   } else {
3725     // We need to adapt arguments.
3726     LPointerMap* pointers = instr->pointer_map();
3727     SafepointGenerator generator(
3728         this, pointers, Safepoint::kLazyDeopt);
3729     ParameterCount count(arity);
3730     ParameterCount expected(formal_parameter_count);
3731     __ InvokeFunction(function_reg, expected, count, CALL_FUNCTION, generator);
3732   }
3733 }
3734
3735
3736 void LCodeGen::DoTailCallThroughMegamorphicCache(
3737     LTailCallThroughMegamorphicCache* instr) {
3738   Register receiver = ToRegister(instr->receiver());
3739   Register name = ToRegister(instr->name());
3740   DCHECK(receiver.is(LoadDescriptor::ReceiverRegister()));
3741   DCHECK(name.is(LoadDescriptor::NameRegister()));
3742   Register slot = FLAG_vector_ics ? ToRegister(instr->slot()) : no_reg;
3743   Register vector = FLAG_vector_ics ? ToRegister(instr->vector()) : no_reg;
3744
3745   Register scratch = ebx;
3746   Register extra = edi;
3747   DCHECK(!extra.is(slot) && !extra.is(vector));
3748   DCHECK(!scratch.is(receiver) && !scratch.is(name));
3749   DCHECK(!extra.is(receiver) && !extra.is(name));
3750
3751   // Important for the tail-call.
3752   bool must_teardown_frame = NeedsEagerFrame();
3753
3754   if (!instr->hydrogen()->is_just_miss()) {
3755     if (FLAG_vector_ics) {
3756       __ push(slot);
3757       __ push(vector);
3758     }
3759
3760     // The probe will tail call to a handler if found.
3761     // If --vector-ics is on, then it knows to pop the two args first.
3762     DCHECK(!instr->hydrogen()->is_keyed_load());
3763     isolate()->stub_cache()->GenerateProbe(
3764         masm(), Code::LOAD_IC, instr->hydrogen()->flags(), must_teardown_frame,
3765         receiver, name, scratch, extra);
3766
3767     if (FLAG_vector_ics) {
3768       __ pop(vector);
3769       __ pop(slot);
3770     }
3771   }
3772
3773   // Tail call to miss if we ended up here.
3774   if (must_teardown_frame) __ leave();
3775   if (instr->hydrogen()->is_keyed_load()) {
3776     KeyedLoadIC::GenerateMiss(masm());
3777   } else {
3778     LoadIC::GenerateMiss(masm());
3779   }
3780 }
3781
3782
3783 void LCodeGen::DoCallWithDescriptor(LCallWithDescriptor* instr) {
3784   DCHECK(ToRegister(instr->result()).is(eax));
3785
3786   if (instr->hydrogen()->IsTailCall()) {
3787     if (NeedsEagerFrame()) __ leave();
3788
3789     if (instr->target()->IsConstantOperand()) {
3790       LConstantOperand* target = LConstantOperand::cast(instr->target());
3791       Handle<Code> code = Handle<Code>::cast(ToHandle(target));
3792       __ jmp(code, RelocInfo::CODE_TARGET);
3793     } else {
3794       DCHECK(instr->target()->IsRegister());
3795       Register target = ToRegister(instr->target());
3796       __ add(target, Immediate(Code::kHeaderSize - kHeapObjectTag));
3797       __ jmp(target);
3798     }
3799   } else {
3800     LPointerMap* pointers = instr->pointer_map();
3801     SafepointGenerator generator(this, pointers, Safepoint::kLazyDeopt);
3802
3803     if (instr->target()->IsConstantOperand()) {
3804       LConstantOperand* target = LConstantOperand::cast(instr->target());
3805       Handle<Code> code = Handle<Code>::cast(ToHandle(target));
3806       generator.BeforeCall(__ CallSize(code, RelocInfo::CODE_TARGET));
3807       __ call(code, RelocInfo::CODE_TARGET);
3808     } else {
3809       DCHECK(instr->target()->IsRegister());
3810       Register target = ToRegister(instr->target());
3811       generator.BeforeCall(__ CallSize(Operand(target)));
3812       __ add(target, Immediate(Code::kHeaderSize - kHeapObjectTag));
3813       __ call(target);
3814     }
3815     generator.AfterCall();
3816   }
3817 }
3818
3819
3820 void LCodeGen::DoCallJSFunction(LCallJSFunction* instr) {
3821   DCHECK(ToRegister(instr->function()).is(edi));
3822   DCHECK(ToRegister(instr->result()).is(eax));
3823
3824   if (instr->hydrogen()->pass_argument_count()) {
3825     __ mov(eax, instr->arity());
3826   }
3827
3828   // Change context.
3829   __ mov(esi, FieldOperand(edi, JSFunction::kContextOffset));
3830
3831   bool is_self_call = false;
3832   if (instr->hydrogen()->function()->IsConstant()) {
3833     HConstant* fun_const = HConstant::cast(instr->hydrogen()->function());
3834     Handle<JSFunction> jsfun =
3835       Handle<JSFunction>::cast(fun_const->handle(isolate()));
3836     is_self_call = jsfun.is_identical_to(info()->closure());
3837   }
3838
3839   if (is_self_call) {
3840     __ CallSelf();
3841   } else {
3842     __ call(FieldOperand(edi, JSFunction::kCodeEntryOffset));
3843   }
3844
3845   RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
3846 }
3847
3848
3849 void LCodeGen::DoDeferredMathAbsTaggedHeapNumber(LMathAbs* instr) {
3850   Register input_reg = ToRegister(instr->value());
3851   __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
3852          factory()->heap_number_map());
3853   DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
3854
3855   Label slow, allocated, done;
3856   Register tmp = input_reg.is(eax) ? ecx : eax;
3857   Register tmp2 = tmp.is(ecx) ? edx : input_reg.is(ecx) ? edx : ecx;
3858
3859   // Preserve the value of all registers.
3860   PushSafepointRegistersScope scope(this);
3861
3862   __ mov(tmp, FieldOperand(input_reg, HeapNumber::kExponentOffset));
3863   // Check the sign of the argument. If the argument is positive, just
3864   // return it. We do not need to patch the stack since |input| and
3865   // |result| are the same register and |input| will be restored
3866   // unchanged by popping safepoint registers.
3867   __ test(tmp, Immediate(HeapNumber::kSignMask));
3868   __ j(zero, &done, Label::kNear);
3869
3870   __ AllocateHeapNumber(tmp, tmp2, no_reg, &slow);
3871   __ jmp(&allocated, Label::kNear);
3872
3873   // Slow case: Call the runtime system to do the number allocation.
3874   __ bind(&slow);
3875   CallRuntimeFromDeferred(Runtime::kAllocateHeapNumber, 0,
3876                           instr, instr->context());
3877   // Set the pointer to the new heap number in tmp.
3878   if (!tmp.is(eax)) __ mov(tmp, eax);
3879   // Restore input_reg after call to runtime.
3880   __ LoadFromSafepointRegisterSlot(input_reg, input_reg);
3881
3882   __ bind(&allocated);
3883   __ mov(tmp2, FieldOperand(input_reg, HeapNumber::kExponentOffset));
3884   __ and_(tmp2, ~HeapNumber::kSignMask);
3885   __ mov(FieldOperand(tmp, HeapNumber::kExponentOffset), tmp2);
3886   __ mov(tmp2, FieldOperand(input_reg, HeapNumber::kMantissaOffset));
3887   __ mov(FieldOperand(tmp, HeapNumber::kMantissaOffset), tmp2);
3888   __ StoreToSafepointRegisterSlot(input_reg, tmp);
3889
3890   __ bind(&done);
3891 }
3892
3893
3894 void LCodeGen::EmitIntegerMathAbs(LMathAbs* instr) {
3895   Register input_reg = ToRegister(instr->value());
3896   __ test(input_reg, Operand(input_reg));
3897   Label is_positive;
3898   __ j(not_sign, &is_positive, Label::kNear);
3899   __ neg(input_reg);  // Sets flags.
3900   DeoptimizeIf(negative, instr, Deoptimizer::kOverflow);
3901   __ bind(&is_positive);
3902 }
3903
3904
3905 void LCodeGen::DoMathAbs(LMathAbs* instr) {
3906   // Class for deferred case.
3907   class DeferredMathAbsTaggedHeapNumber FINAL : public LDeferredCode {
3908    public:
3909     DeferredMathAbsTaggedHeapNumber(LCodeGen* codegen,
3910                                     LMathAbs* instr,
3911                                     const X87Stack& x87_stack)
3912         : LDeferredCode(codegen, x87_stack), instr_(instr) { }
3913     void Generate() OVERRIDE {
3914       codegen()->DoDeferredMathAbsTaggedHeapNumber(instr_);
3915     }
3916     LInstruction* instr() OVERRIDE { return instr_; }
3917
3918    private:
3919     LMathAbs* instr_;
3920   };
3921
3922   DCHECK(instr->value()->Equals(instr->result()));
3923   Representation r = instr->hydrogen()->value()->representation();
3924
3925   if (r.IsDouble()) {
3926     X87Register value = ToX87Register(instr->value());
3927     X87Fxch(value);
3928     __ fabs();
3929   } else if (r.IsSmiOrInteger32()) {
3930     EmitIntegerMathAbs(instr);
3931   } else {  // Tagged case.
3932     DeferredMathAbsTaggedHeapNumber* deferred =
3933         new(zone()) DeferredMathAbsTaggedHeapNumber(this, instr, x87_stack_);
3934     Register input_reg = ToRegister(instr->value());
3935     // Smi check.
3936     __ JumpIfNotSmi(input_reg, deferred->entry());
3937     EmitIntegerMathAbs(instr);
3938     __ bind(deferred->exit());
3939   }
3940 }
3941
3942
3943 void LCodeGen::DoMathFloor(LMathFloor* instr) {
3944   Register output_reg = ToRegister(instr->result());
3945   X87Register input_reg = ToX87Register(instr->value());
3946   X87Fxch(input_reg);
3947
3948   Label not_minus_zero, done;
3949   // Deoptimize on unordered.
3950   __ fldz();
3951   __ fld(1);
3952   __ FCmp();
3953   DeoptimizeIf(parity_even, instr, Deoptimizer::kNaN);
3954   __ j(below, &not_minus_zero, Label::kNear);
3955
3956   if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3957     // Check for negative zero.
3958     __ j(not_equal, &not_minus_zero, Label::kNear);
3959     // +- 0.0.
3960     __ fld(0);
3961     __ FXamSign();
3962     DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
3963     __ Move(output_reg, Immediate(0));
3964     __ jmp(&done, Label::kFar);
3965   }
3966
3967   // Positive input.
3968   // rc=01B, round down.
3969   __ bind(&not_minus_zero);
3970   __ fnclex();
3971   __ X87SetRC(0x0400);
3972   __ sub(esp, Immediate(kPointerSize));
3973   __ fist_s(Operand(esp, 0));
3974   __ pop(output_reg);
3975   __ X87CheckIA();
3976   DeoptimizeIf(equal, instr, Deoptimizer::kOverflow);
3977   __ fnclex();
3978   __ X87SetRC(0x0000);
3979   __ bind(&done);
3980 }
3981
3982
3983 void LCodeGen::DoMathRound(LMathRound* instr) {
3984   X87Register input_reg = ToX87Register(instr->value());
3985   Register result = ToRegister(instr->result());
3986   X87Fxch(input_reg);
3987   Label below_one_half, below_minus_one_half, done;
3988
3989   ExternalReference one_half = ExternalReference::address_of_one_half();
3990   ExternalReference minus_one_half =
3991       ExternalReference::address_of_minus_one_half();
3992
3993   __ fld_d(Operand::StaticVariable(one_half));
3994   __ fld(1);
3995   __ FCmp();
3996   __ j(carry, &below_one_half);
3997
3998   // Use rounds towards zero, since 0.5 <= x, we use floor(0.5 + x)
3999   __ fld(0);
4000   __ fadd_d(Operand::StaticVariable(one_half));
4001   // rc=11B, round toward zero.
4002   __ X87SetRC(0x0c00);
4003   __ sub(esp, Immediate(kPointerSize));
4004   // Clear exception bits.
4005   __ fnclex();
4006   __ fistp_s(MemOperand(esp, 0));
4007   // Check overflow.
4008   __ X87CheckIA();
4009   __ pop(result);
4010   DeoptimizeIf(equal, instr, Deoptimizer::kConversionOverflow);
4011   __ fnclex();
4012   // Restore round mode.
4013   __ X87SetRC(0x0000);
4014   __ jmp(&done);
4015
4016   __ bind(&below_one_half);
4017   __ fld_d(Operand::StaticVariable(minus_one_half));
4018   __ fld(1);
4019   __ FCmp();
4020   __ j(carry, &below_minus_one_half);
4021   // We return 0 for the input range [+0, 0.5[, or [-0.5, 0.5[ if
4022   // we can ignore the difference between a result of -0 and +0.
4023   if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
4024     // If the sign is positive, we return +0.
4025     __ fld(0);
4026     __ FXamSign();
4027     DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
4028   }
4029   __ Move(result, Immediate(0));
4030   __ jmp(&done);
4031
4032   __ bind(&below_minus_one_half);
4033   __ fld(0);
4034   __ fadd_d(Operand::StaticVariable(one_half));
4035   // rc=01B, round down.
4036   __ X87SetRC(0x0400);
4037   __ sub(esp, Immediate(kPointerSize));
4038   // Clear exception bits.
4039   __ fnclex();
4040   __ fistp_s(MemOperand(esp, 0));
4041   // Check overflow.
4042   __ X87CheckIA();
4043   __ pop(result);
4044   DeoptimizeIf(equal, instr, Deoptimizer::kConversionOverflow);
4045   __ fnclex();
4046   // Restore round mode.
4047   __ X87SetRC(0x0000);
4048
4049   __ bind(&done);
4050 }
4051
4052
4053 void LCodeGen::DoMathFround(LMathFround* instr) {
4054   X87Register input_reg = ToX87Register(instr->value());
4055   X87Fxch(input_reg);
4056   __ sub(esp, Immediate(kPointerSize));
4057   __ fstp_s(MemOperand(esp, 0));
4058   X87Fld(MemOperand(esp, 0), kX87FloatOperand);
4059   __ add(esp, Immediate(kPointerSize));
4060 }
4061
4062
4063 void LCodeGen::DoMathSqrt(LMathSqrt* instr) {
4064   X87Register input = ToX87Register(instr->value());
4065   X87Register result_reg = ToX87Register(instr->result());
4066   Register temp_result = ToRegister(instr->temp1());
4067   Register temp = ToRegister(instr->temp2());
4068   Label slow, done, smi, finish;
4069   DCHECK(result_reg.is(input));
4070
4071   // Store input into Heap number and call runtime function kMathExpRT.
4072   if (FLAG_inline_new) {
4073     __ AllocateHeapNumber(temp_result, temp, no_reg, &slow);
4074     __ jmp(&done, Label::kNear);
4075   }
4076
4077   // Slow case: Call the runtime system to do the number allocation.
4078   __ bind(&slow);
4079   {
4080     // TODO(3095996): Put a valid pointer value in the stack slot where the
4081     // result register is stored, as this register is in the pointer map, but
4082     // contains an integer value.
4083     __ Move(temp_result, Immediate(0));
4084
4085     // Preserve the value of all registers.
4086     PushSafepointRegistersScope scope(this);
4087
4088     __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4089     __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
4090     RecordSafepointWithRegisters(
4091        instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
4092     __ StoreToSafepointRegisterSlot(temp_result, eax);
4093   }
4094   __ bind(&done);
4095   X87LoadForUsage(input);
4096   __ fstp_d(FieldOperand(temp_result, HeapNumber::kValueOffset));
4097
4098   {
4099     // Preserve the value of all registers.
4100     PushSafepointRegistersScope scope(this);
4101
4102     __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4103     __ push(temp_result);
4104     __ CallRuntimeSaveDoubles(Runtime::kMathSqrt);
4105     RecordSafepointWithRegisters(instr->pointer_map(), 1,
4106                                  Safepoint::kNoLazyDeopt);
4107     __ StoreToSafepointRegisterSlot(temp_result, eax);
4108   }
4109   X87PrepareToWrite(result_reg);
4110   // return value of MathExpRT is Smi or Heap Number.
4111   __ JumpIfSmi(temp_result, &smi);
4112   // Heap number(double)
4113   __ fld_d(FieldOperand(temp_result, HeapNumber::kValueOffset));
4114   __ jmp(&finish);
4115   // SMI
4116   __ bind(&smi);
4117   __ SmiUntag(temp_result);
4118   __ push(temp_result);
4119   __ fild_s(MemOperand(esp, 0));
4120   __ pop(temp_result);
4121   __ bind(&finish);
4122   X87CommitWrite(result_reg);
4123 }
4124
4125
4126 void LCodeGen::DoMathPowHalf(LMathPowHalf* instr) {
4127   X87Register input_reg = ToX87Register(instr->value());
4128   DCHECK(ToX87Register(instr->result()).is(input_reg));
4129   X87Fxch(input_reg);
4130   // Note that according to ECMA-262 15.8.2.13:
4131   // Math.pow(-Infinity, 0.5) == Infinity
4132   // Math.sqrt(-Infinity) == NaN
4133   Label done, sqrt;
4134   // Check base for -Infinity. C3 == 0, C2 == 1, C1 == 1 and C0 == 1
4135   __ fxam();
4136   __ push(eax);
4137   __ fnstsw_ax();
4138   __ and_(eax, Immediate(0x4700));
4139   __ cmp(eax, Immediate(0x0700));
4140   __ j(not_equal, &sqrt, Label::kNear);
4141   // If input is -Infinity, return Infinity.
4142   __ fchs();
4143   __ jmp(&done, Label::kNear);
4144
4145   // Square root.
4146   __ bind(&sqrt);
4147   __ fldz();
4148   __ faddp();  // Convert -0 to +0.
4149   __ fsqrt();
4150   __ bind(&done);
4151   __ pop(eax);
4152 }
4153
4154
4155 void LCodeGen::DoPower(LPower* instr) {
4156   Representation exponent_type = instr->hydrogen()->right()->representation();
4157   X87Register result = ToX87Register(instr->result());
4158   // Having marked this as a call, we can use any registers.
4159   X87Register base = ToX87Register(instr->left());
4160   ExternalReference one_half = ExternalReference::address_of_one_half();
4161
4162   if (exponent_type.IsSmi()) {
4163     Register exponent = ToRegister(instr->right());
4164     X87LoadForUsage(base);
4165     __ SmiUntag(exponent);
4166     __ push(exponent);
4167     __ fild_s(MemOperand(esp, 0));
4168     __ pop(exponent);
4169   } else if (exponent_type.IsTagged()) {
4170     Register exponent = ToRegister(instr->right());
4171     Register temp = exponent.is(ecx) ? eax : ecx;
4172     Label no_deopt, done;
4173     X87LoadForUsage(base);
4174     __ JumpIfSmi(exponent, &no_deopt);
4175     __ CmpObjectType(exponent, HEAP_NUMBER_TYPE, temp);
4176     DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
4177     // Heap number(double)
4178     __ fld_d(FieldOperand(exponent, HeapNumber::kValueOffset));
4179     __ jmp(&done);
4180     // SMI
4181     __ bind(&no_deopt);
4182     __ SmiUntag(exponent);
4183     __ push(exponent);
4184     __ fild_s(MemOperand(esp, 0));
4185     __ pop(exponent);
4186     __ bind(&done);
4187   } else if (exponent_type.IsInteger32()) {
4188     Register exponent = ToRegister(instr->right());
4189     X87LoadForUsage(base);
4190     __ push(exponent);
4191     __ fild_s(MemOperand(esp, 0));
4192     __ pop(exponent);
4193   } else {
4194     DCHECK(exponent_type.IsDouble());
4195     X87Register exponent_double = ToX87Register(instr->right());
4196     X87LoadForUsage(base, exponent_double);
4197   }
4198
4199   // FP data stack {base, exponent(TOS)}.
4200   // Handle (exponent==+-0.5 && base == -0).
4201   Label not_plus_0;
4202   __ fld(0);
4203   __ fabs();
4204   X87Fld(Operand::StaticVariable(one_half), kX87DoubleOperand);
4205   __ FCmp();
4206   __ j(parity_even, &not_plus_0, Label::kNear);  // NaN.
4207   __ j(not_equal, &not_plus_0, Label::kNear);
4208   __ fldz();
4209   // FP data stack {base, exponent(TOS), zero}.
4210   __ faddp(2);
4211   __ bind(&not_plus_0);
4212
4213   {
4214     __ PrepareCallCFunction(4, eax);
4215     __ fstp_d(MemOperand(esp, kDoubleSize));  // Exponent value.
4216     __ fstp_d(MemOperand(esp, 0));            // Base value.
4217     X87PrepareToWrite(result);
4218     __ CallCFunction(ExternalReference::power_double_double_function(isolate()),
4219                      4);
4220     // Return value is in st(0) on ia32.
4221     X87CommitWrite(result);
4222   }
4223 }
4224
4225
4226 void LCodeGen::DoMathLog(LMathLog* instr) {
4227   DCHECK(instr->value()->Equals(instr->result()));
4228   X87Register input_reg = ToX87Register(instr->value());
4229   X87Fxch(input_reg);
4230
4231   Label positive, done, zero, nan_result;
4232   __ fldz();
4233   __ fld(1);
4234   __ FCmp();
4235   __ j(below, &nan_result, Label::kNear);
4236   __ j(equal, &zero, Label::kNear);
4237   // Positive input.
4238   // {input, ln2}.
4239   __ fldln2();
4240   // {ln2, input}.
4241   __ fxch();
4242   // {result}.
4243   __ fyl2x();
4244   __ jmp(&done, Label::kNear);
4245
4246   __ bind(&nan_result);
4247   X87PrepareToWrite(input_reg);
4248   __ push(Immediate(0xffffffff));
4249   __ push(Immediate(0x7fffffff));
4250   __ fld_d(MemOperand(esp, 0));
4251   __ lea(esp, Operand(esp, kDoubleSize));
4252   X87CommitWrite(input_reg);
4253   __ jmp(&done, Label::kNear);
4254
4255   __ bind(&zero);
4256   ExternalReference ninf = ExternalReference::address_of_negative_infinity();
4257   X87PrepareToWrite(input_reg);
4258   __ fld_d(Operand::StaticVariable(ninf));
4259   X87CommitWrite(input_reg);
4260
4261   __ bind(&done);
4262 }
4263
4264
4265 void LCodeGen::DoMathClz32(LMathClz32* instr) {
4266   Register input = ToRegister(instr->value());
4267   Register result = ToRegister(instr->result());
4268
4269   __ Lzcnt(result, input);
4270 }
4271
4272
4273 void LCodeGen::DoMathExp(LMathExp* instr) {
4274   X87Register input = ToX87Register(instr->value());
4275   X87Register result_reg = ToX87Register(instr->result());
4276   Register temp_result = ToRegister(instr->temp1());
4277   Register temp = ToRegister(instr->temp2());
4278   Label slow, done, smi, finish;
4279   DCHECK(result_reg.is(input));
4280
4281   // Store input into Heap number and call runtime function kMathExpRT.
4282   if (FLAG_inline_new) {
4283     __ AllocateHeapNumber(temp_result, temp, no_reg, &slow);
4284     __ jmp(&done, Label::kNear);
4285   }
4286
4287   // Slow case: Call the runtime system to do the number allocation.
4288   __ bind(&slow);
4289   {
4290     // TODO(3095996): Put a valid pointer value in the stack slot where the
4291     // result register is stored, as this register is in the pointer map, but
4292     // contains an integer value.
4293     __ Move(temp_result, Immediate(0));
4294
4295     // Preserve the value of all registers.
4296     PushSafepointRegistersScope scope(this);
4297
4298     __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4299     __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
4300     RecordSafepointWithRegisters(instr->pointer_map(), 0,
4301                                  Safepoint::kNoLazyDeopt);
4302     __ StoreToSafepointRegisterSlot(temp_result, eax);
4303   }
4304   __ bind(&done);
4305   X87LoadForUsage(input);
4306   __ fstp_d(FieldOperand(temp_result, HeapNumber::kValueOffset));
4307
4308   {
4309     // Preserve the value of all registers.
4310     PushSafepointRegistersScope scope(this);
4311
4312     __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4313     __ push(temp_result);
4314     __ CallRuntimeSaveDoubles(Runtime::kMathExpRT);
4315     RecordSafepointWithRegisters(instr->pointer_map(), 1,
4316                                  Safepoint::kNoLazyDeopt);
4317     __ StoreToSafepointRegisterSlot(temp_result, eax);
4318   }
4319   X87PrepareToWrite(result_reg);
4320   // return value of MathExpRT is Smi or Heap Number.
4321   __ JumpIfSmi(temp_result, &smi);
4322   // Heap number(double)
4323   __ fld_d(FieldOperand(temp_result, HeapNumber::kValueOffset));
4324   __ jmp(&finish);
4325   // SMI
4326   __ bind(&smi);
4327   __ SmiUntag(temp_result);
4328   __ push(temp_result);
4329   __ fild_s(MemOperand(esp, 0));
4330   __ pop(temp_result);
4331   __ bind(&finish);
4332   X87CommitWrite(result_reg);
4333 }
4334
4335
4336 void LCodeGen::DoInvokeFunction(LInvokeFunction* instr) {
4337   DCHECK(ToRegister(instr->context()).is(esi));
4338   DCHECK(ToRegister(instr->function()).is(edi));
4339   DCHECK(instr->HasPointerMap());
4340
4341   Handle<JSFunction> known_function = instr->hydrogen()->known_function();
4342   if (known_function.is_null()) {
4343     LPointerMap* pointers = instr->pointer_map();
4344     SafepointGenerator generator(
4345         this, pointers, Safepoint::kLazyDeopt);
4346     ParameterCount count(instr->arity());
4347     __ InvokeFunction(edi, count, CALL_FUNCTION, generator);
4348   } else {
4349     CallKnownFunction(known_function,
4350                       instr->hydrogen()->formal_parameter_count(),
4351                       instr->arity(), instr);
4352   }
4353 }
4354
4355
4356 void LCodeGen::DoCallFunction(LCallFunction* instr) {
4357   DCHECK(ToRegister(instr->context()).is(esi));
4358   DCHECK(ToRegister(instr->function()).is(edi));
4359   DCHECK(ToRegister(instr->result()).is(eax));
4360
4361   int arity = instr->arity();
4362   CallFunctionFlags flags = instr->hydrogen()->function_flags();
4363   if (instr->hydrogen()->HasVectorAndSlot()) {
4364     Register slot_register = ToRegister(instr->temp_slot());
4365     Register vector_register = ToRegister(instr->temp_vector());
4366     DCHECK(slot_register.is(edx));
4367     DCHECK(vector_register.is(ebx));
4368
4369     AllowDeferredHandleDereference vector_structure_check;
4370     Handle<TypeFeedbackVector> vector = instr->hydrogen()->feedback_vector();
4371     int index = vector->GetIndex(instr->hydrogen()->slot());
4372
4373     __ mov(vector_register, vector);
4374     __ mov(slot_register, Immediate(Smi::FromInt(index)));
4375
4376     CallICState::CallType call_type =
4377         (flags & CALL_AS_METHOD) ? CallICState::METHOD : CallICState::FUNCTION;
4378
4379     Handle<Code> ic =
4380         CodeFactory::CallICInOptimizedCode(isolate(), arity, call_type).code();
4381     CallCode(ic, RelocInfo::CODE_TARGET, instr);
4382   } else {
4383     CallFunctionStub stub(isolate(), arity, flags);
4384     CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
4385   }
4386 }
4387
4388
4389 void LCodeGen::DoCallNew(LCallNew* instr) {
4390   DCHECK(ToRegister(instr->context()).is(esi));
4391   DCHECK(ToRegister(instr->constructor()).is(edi));
4392   DCHECK(ToRegister(instr->result()).is(eax));
4393
4394   // No cell in ebx for construct type feedback in optimized code
4395   __ mov(ebx, isolate()->factory()->undefined_value());
4396   CallConstructStub stub(isolate(), NO_CALL_CONSTRUCTOR_FLAGS);
4397   __ Move(eax, Immediate(instr->arity()));
4398   CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
4399 }
4400
4401
4402 void LCodeGen::DoCallNewArray(LCallNewArray* instr) {
4403   DCHECK(ToRegister(instr->context()).is(esi));
4404   DCHECK(ToRegister(instr->constructor()).is(edi));
4405   DCHECK(ToRegister(instr->result()).is(eax));
4406
4407   __ Move(eax, Immediate(instr->arity()));
4408   __ mov(ebx, isolate()->factory()->undefined_value());
4409   ElementsKind kind = instr->hydrogen()->elements_kind();
4410   AllocationSiteOverrideMode override_mode =
4411       (AllocationSite::GetMode(kind) == TRACK_ALLOCATION_SITE)
4412           ? DISABLE_ALLOCATION_SITES
4413           : DONT_OVERRIDE;
4414
4415   if (instr->arity() == 0) {
4416     ArrayNoArgumentConstructorStub stub(isolate(), kind, override_mode);
4417     CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
4418   } else if (instr->arity() == 1) {
4419     Label done;
4420     if (IsFastPackedElementsKind(kind)) {
4421       Label packed_case;
4422       // We might need a change here
4423       // look at the first argument
4424       __ mov(ecx, Operand(esp, 0));
4425       __ test(ecx, ecx);
4426       __ j(zero, &packed_case, Label::kNear);
4427
4428       ElementsKind holey_kind = GetHoleyElementsKind(kind);
4429       ArraySingleArgumentConstructorStub stub(isolate(),
4430                                               holey_kind,
4431                                               override_mode);
4432       CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
4433       __ jmp(&done, Label::kNear);
4434       __ bind(&packed_case);
4435     }
4436
4437     ArraySingleArgumentConstructorStub stub(isolate(), kind, override_mode);
4438     CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
4439     __ bind(&done);
4440   } else {
4441     ArrayNArgumentsConstructorStub stub(isolate(), kind, override_mode);
4442     CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
4443   }
4444 }
4445
4446
4447 void LCodeGen::DoCallRuntime(LCallRuntime* instr) {
4448   DCHECK(ToRegister(instr->context()).is(esi));
4449   CallRuntime(instr->function(), instr->arity(), instr, instr->save_doubles());
4450 }
4451
4452
4453 void LCodeGen::DoStoreCodeEntry(LStoreCodeEntry* instr) {
4454   Register function = ToRegister(instr->function());
4455   Register code_object = ToRegister(instr->code_object());
4456   __ lea(code_object, FieldOperand(code_object, Code::kHeaderSize));
4457   __ mov(FieldOperand(function, JSFunction::kCodeEntryOffset), code_object);
4458 }
4459
4460
4461 void LCodeGen::DoInnerAllocatedObject(LInnerAllocatedObject* instr) {
4462   Register result = ToRegister(instr->result());
4463   Register base = ToRegister(instr->base_object());
4464   if (instr->offset()->IsConstantOperand()) {
4465     LConstantOperand* offset = LConstantOperand::cast(instr->offset());
4466     __ lea(result, Operand(base, ToInteger32(offset)));
4467   } else {
4468     Register offset = ToRegister(instr->offset());
4469     __ lea(result, Operand(base, offset, times_1, 0));
4470   }
4471 }
4472
4473
4474 void LCodeGen::DoStoreNamedField(LStoreNamedField* instr) {
4475   Representation representation = instr->hydrogen()->field_representation();
4476
4477   HObjectAccess access = instr->hydrogen()->access();
4478   int offset = access.offset();
4479
4480   if (access.IsExternalMemory()) {
4481     DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4482     MemOperand operand = instr->object()->IsConstantOperand()
4483         ? MemOperand::StaticVariable(
4484             ToExternalReference(LConstantOperand::cast(instr->object())))
4485         : MemOperand(ToRegister(instr->object()), offset);
4486     if (instr->value()->IsConstantOperand()) {
4487       LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
4488       __ mov(operand, Immediate(ToInteger32(operand_value)));
4489     } else {
4490       Register value = ToRegister(instr->value());
4491       __ Store(value, operand, representation);
4492     }
4493     return;
4494   }
4495
4496   Register object = ToRegister(instr->object());
4497   __ AssertNotSmi(object);
4498   DCHECK(!representation.IsSmi() ||
4499          !instr->value()->IsConstantOperand() ||
4500          IsSmi(LConstantOperand::cast(instr->value())));
4501   if (representation.IsDouble()) {
4502     DCHECK(access.IsInobject());
4503     DCHECK(!instr->hydrogen()->has_transition());
4504     DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4505     X87Register value = ToX87Register(instr->value());
4506     X87Mov(FieldOperand(object, offset), value);
4507     return;
4508   }
4509
4510   if (instr->hydrogen()->has_transition()) {
4511     Handle<Map> transition = instr->hydrogen()->transition_map();
4512     AddDeprecationDependency(transition);
4513     __ mov(FieldOperand(object, HeapObject::kMapOffset), transition);
4514     if (instr->hydrogen()->NeedsWriteBarrierForMap()) {
4515       Register temp = ToRegister(instr->temp());
4516       Register temp_map = ToRegister(instr->temp_map());
4517       __ mov(temp_map, transition);
4518       __ mov(FieldOperand(object, HeapObject::kMapOffset), temp_map);
4519       // Update the write barrier for the map field.
4520       __ RecordWriteForMap(object, transition, temp_map, temp, kSaveFPRegs);
4521     }
4522   }
4523
4524   // Do the store.
4525   Register write_register = object;
4526   if (!access.IsInobject()) {
4527     write_register = ToRegister(instr->temp());
4528     __ mov(write_register, FieldOperand(object, JSObject::kPropertiesOffset));
4529   }
4530
4531   MemOperand operand = FieldOperand(write_register, offset);
4532   if (instr->value()->IsConstantOperand()) {
4533     LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
4534     if (operand_value->IsRegister()) {
4535       Register value = ToRegister(operand_value);
4536       __ Store(value, operand, representation);
4537     } else if (representation.IsInteger32()) {
4538       Immediate immediate = ToImmediate(operand_value, representation);
4539       DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4540       __ mov(operand, immediate);
4541     } else {
4542       Handle<Object> handle_value = ToHandle(operand_value);
4543       DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4544       __ mov(operand, handle_value);
4545     }
4546   } else {
4547     Register value = ToRegister(instr->value());
4548     __ Store(value, operand, representation);
4549   }
4550
4551   if (instr->hydrogen()->NeedsWriteBarrier()) {
4552     Register value = ToRegister(instr->value());
4553     Register temp = access.IsInobject() ? ToRegister(instr->temp()) : object;
4554     // Update the write barrier for the object for in-object properties.
4555     __ RecordWriteField(write_register, offset, value, temp, kSaveFPRegs,
4556                         EMIT_REMEMBERED_SET,
4557                         instr->hydrogen()->SmiCheckForWriteBarrier(),
4558                         instr->hydrogen()->PointersToHereCheckForValue());
4559   }
4560 }
4561
4562
4563 void LCodeGen::DoStoreNamedGeneric(LStoreNamedGeneric* instr) {
4564   DCHECK(ToRegister(instr->context()).is(esi));
4565   DCHECK(ToRegister(instr->object()).is(StoreDescriptor::ReceiverRegister()));
4566   DCHECK(ToRegister(instr->value()).is(StoreDescriptor::ValueRegister()));
4567
4568   __ mov(StoreDescriptor::NameRegister(), instr->name());
4569   Handle<Code> ic =
4570       StoreIC::initialize_stub(isolate(), instr->language_mode(),
4571                                instr->hydrogen()->initialization_state());
4572   CallCode(ic, RelocInfo::CODE_TARGET, instr);
4573 }
4574
4575
4576 void LCodeGen::DoBoundsCheck(LBoundsCheck* instr) {
4577   Condition cc = instr->hydrogen()->allow_equality() ? above : above_equal;
4578   if (instr->index()->IsConstantOperand()) {
4579     __ cmp(ToOperand(instr->length()),
4580            ToImmediate(LConstantOperand::cast(instr->index()),
4581                        instr->hydrogen()->length()->representation()));
4582     cc = CommuteCondition(cc);
4583   } else if (instr->length()->IsConstantOperand()) {
4584     __ cmp(ToOperand(instr->index()),
4585            ToImmediate(LConstantOperand::cast(instr->length()),
4586                        instr->hydrogen()->index()->representation()));
4587   } else {
4588     __ cmp(ToRegister(instr->index()), ToOperand(instr->length()));
4589   }
4590   if (FLAG_debug_code && instr->hydrogen()->skip_check()) {
4591     Label done;
4592     __ j(NegateCondition(cc), &done, Label::kNear);
4593     __ int3();
4594     __ bind(&done);
4595   } else {
4596     DeoptimizeIf(cc, instr, Deoptimizer::kOutOfBounds);
4597   }
4598 }
4599
4600
4601 void LCodeGen::DoStoreKeyedExternalArray(LStoreKeyed* instr) {
4602   ElementsKind elements_kind = instr->elements_kind();
4603   LOperand* key = instr->key();
4604   if (!key->IsConstantOperand() &&
4605       ExternalArrayOpRequiresTemp(instr->hydrogen()->key()->representation(),
4606                                   elements_kind)) {
4607     __ SmiUntag(ToRegister(key));
4608   }
4609   Operand operand(BuildFastArrayOperand(
4610       instr->elements(),
4611       key,
4612       instr->hydrogen()->key()->representation(),
4613       elements_kind,
4614       instr->base_offset()));
4615   if (elements_kind == EXTERNAL_FLOAT32_ELEMENTS ||
4616       elements_kind == FLOAT32_ELEMENTS) {
4617     X87Mov(operand, ToX87Register(instr->value()), kX87FloatOperand);
4618   } else if (elements_kind == EXTERNAL_FLOAT64_ELEMENTS ||
4619              elements_kind == FLOAT64_ELEMENTS) {
4620     uint64_t int_val = kHoleNanInt64;
4621     int32_t lower = static_cast<int32_t>(int_val);
4622     int32_t upper = static_cast<int32_t>(int_val >> (kBitsPerInt));
4623     Operand operand2 = BuildFastArrayOperand(
4624         instr->elements(), instr->key(),
4625         instr->hydrogen()->key()->representation(), elements_kind,
4626         instr->base_offset() + kPointerSize);
4627
4628     Label no_special_nan_handling, done;
4629     X87Register value = ToX87Register(instr->value());
4630     X87Fxch(value);
4631     __ lea(esp, Operand(esp, -kDoubleSize));
4632     __ fst_d(MemOperand(esp, 0));
4633     __ lea(esp, Operand(esp, kDoubleSize));
4634     int offset = sizeof(kHoleNanUpper32);
4635     // x87 converts sNaN(0xfff7fffffff7ffff) to QNaN(0xfffffffffff7ffff),
4636     // so we check the upper with 0xffffffff for hole as a temporary fix.
4637     __ cmp(MemOperand(esp, -offset), Immediate(0xffffffff));
4638     __ j(not_equal, &no_special_nan_handling, Label::kNear);
4639     __ mov(operand, Immediate(lower));
4640     __ mov(operand2, Immediate(upper));
4641     __ jmp(&done, Label::kNear);
4642
4643     __ bind(&no_special_nan_handling);
4644     __ fst_d(operand);
4645     __ bind(&done);
4646   } else {
4647     Register value = ToRegister(instr->value());
4648     switch (elements_kind) {
4649       case EXTERNAL_UINT8_CLAMPED_ELEMENTS:
4650       case EXTERNAL_UINT8_ELEMENTS:
4651       case EXTERNAL_INT8_ELEMENTS:
4652       case UINT8_ELEMENTS:
4653       case INT8_ELEMENTS:
4654       case UINT8_CLAMPED_ELEMENTS:
4655         __ mov_b(operand, value);
4656         break;
4657       case EXTERNAL_INT16_ELEMENTS:
4658       case EXTERNAL_UINT16_ELEMENTS:
4659       case UINT16_ELEMENTS:
4660       case INT16_ELEMENTS:
4661         __ mov_w(operand, value);
4662         break;
4663       case EXTERNAL_INT32_ELEMENTS:
4664       case EXTERNAL_UINT32_ELEMENTS:
4665       case UINT32_ELEMENTS:
4666       case INT32_ELEMENTS:
4667         __ mov(operand, value);
4668         break;
4669       case EXTERNAL_FLOAT32_ELEMENTS:
4670       case EXTERNAL_FLOAT64_ELEMENTS:
4671       case FLOAT32_ELEMENTS:
4672       case FLOAT64_ELEMENTS:
4673       case FAST_SMI_ELEMENTS:
4674       case FAST_ELEMENTS:
4675       case FAST_DOUBLE_ELEMENTS:
4676       case FAST_HOLEY_SMI_ELEMENTS:
4677       case FAST_HOLEY_ELEMENTS:
4678       case FAST_HOLEY_DOUBLE_ELEMENTS:
4679       case DICTIONARY_ELEMENTS:
4680       case SLOPPY_ARGUMENTS_ELEMENTS:
4681         UNREACHABLE();
4682         break;
4683     }
4684   }
4685 }
4686
4687
4688 void LCodeGen::DoStoreKeyedFixedDoubleArray(LStoreKeyed* instr) {
4689   Operand double_store_operand = BuildFastArrayOperand(
4690       instr->elements(),
4691       instr->key(),
4692       instr->hydrogen()->key()->representation(),
4693       FAST_DOUBLE_ELEMENTS,
4694       instr->base_offset());
4695
4696   uint64_t int_val = kHoleNanInt64;
4697   int32_t lower = static_cast<int32_t>(int_val);
4698   int32_t upper = static_cast<int32_t>(int_val >> (kBitsPerInt));
4699   Operand double_store_operand2 = BuildFastArrayOperand(
4700       instr->elements(), instr->key(),
4701       instr->hydrogen()->key()->representation(), FAST_DOUBLE_ELEMENTS,
4702       instr->base_offset() + kPointerSize);
4703
4704   if (instr->hydrogen()->IsConstantHoleStore()) {
4705     // This means we should store the (double) hole. No floating point
4706     // registers required.
4707     __ mov(double_store_operand, Immediate(lower));
4708     __ mov(double_store_operand2, Immediate(upper));
4709   } else {
4710     Label no_special_nan_handling, done;
4711     X87Register value = ToX87Register(instr->value());
4712     X87Fxch(value);
4713
4714     if (instr->NeedsCanonicalization()) {
4715       __ fld(0);
4716       __ fld(0);
4717       __ FCmp();
4718       __ j(parity_odd, &no_special_nan_handling, Label::kNear);
4719       // All NaNs are Canonicalized to 0x7fffffffffffffff
4720       __ mov(double_store_operand, Immediate(0xffffffff));
4721       __ mov(double_store_operand2, Immediate(0x7fffffff));
4722       __ jmp(&done, Label::kNear);
4723     } else {
4724       __ lea(esp, Operand(esp, -kDoubleSize));
4725       __ fst_d(MemOperand(esp, 0));
4726       __ lea(esp, Operand(esp, kDoubleSize));
4727       int offset = sizeof(kHoleNanUpper32);
4728       // x87 converts sNaN(0xfff7fffffff7ffff) to QNaN(0xfffffffffff7ffff),
4729       // so we check the upper with 0xffffffff for hole as a temporary fix.
4730       __ cmp(MemOperand(esp, -offset), Immediate(0xffffffff));
4731       __ j(not_equal, &no_special_nan_handling, Label::kNear);
4732       __ mov(double_store_operand, Immediate(lower));
4733       __ mov(double_store_operand2, Immediate(upper));
4734       __ jmp(&done, Label::kNear);
4735     }
4736     __ bind(&no_special_nan_handling);
4737     __ fst_d(double_store_operand);
4738     __ bind(&done);
4739   }
4740 }
4741
4742
4743 void LCodeGen::DoStoreKeyedFixedArray(LStoreKeyed* instr) {
4744   Register elements = ToRegister(instr->elements());
4745   Register key = instr->key()->IsRegister() ? ToRegister(instr->key()) : no_reg;
4746
4747   Operand operand = BuildFastArrayOperand(
4748       instr->elements(),
4749       instr->key(),
4750       instr->hydrogen()->key()->representation(),
4751       FAST_ELEMENTS,
4752       instr->base_offset());
4753   if (instr->value()->IsRegister()) {
4754     __ mov(operand, ToRegister(instr->value()));
4755   } else {
4756     LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
4757     if (IsSmi(operand_value)) {
4758       Immediate immediate = ToImmediate(operand_value, Representation::Smi());
4759       __ mov(operand, immediate);
4760     } else {
4761       DCHECK(!IsInteger32(operand_value));
4762       Handle<Object> handle_value = ToHandle(operand_value);
4763       __ mov(operand, handle_value);
4764     }
4765   }
4766
4767   if (instr->hydrogen()->NeedsWriteBarrier()) {
4768     DCHECK(instr->value()->IsRegister());
4769     Register value = ToRegister(instr->value());
4770     DCHECK(!instr->key()->IsConstantOperand());
4771     SmiCheck check_needed =
4772         instr->hydrogen()->value()->type().IsHeapObject()
4773           ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
4774     // Compute address of modified element and store it into key register.
4775     __ lea(key, operand);
4776     __ RecordWrite(elements, key, value, kSaveFPRegs, EMIT_REMEMBERED_SET,
4777                    check_needed,
4778                    instr->hydrogen()->PointersToHereCheckForValue());
4779   }
4780 }
4781
4782
4783 void LCodeGen::DoStoreKeyed(LStoreKeyed* instr) {
4784   // By cases...external, fast-double, fast
4785   if (instr->is_typed_elements()) {
4786     DoStoreKeyedExternalArray(instr);
4787   } else if (instr->hydrogen()->value()->representation().IsDouble()) {
4788     DoStoreKeyedFixedDoubleArray(instr);
4789   } else {
4790     DoStoreKeyedFixedArray(instr);
4791   }
4792 }
4793
4794
4795 void LCodeGen::DoStoreKeyedGeneric(LStoreKeyedGeneric* instr) {
4796   DCHECK(ToRegister(instr->context()).is(esi));
4797   DCHECK(ToRegister(instr->object()).is(StoreDescriptor::ReceiverRegister()));
4798   DCHECK(ToRegister(instr->key()).is(StoreDescriptor::NameRegister()));
4799   DCHECK(ToRegister(instr->value()).is(StoreDescriptor::ValueRegister()));
4800
4801   Handle<Code> ic = CodeFactory::KeyedStoreICInOptimizedCode(
4802                         isolate(), instr->language_mode(),
4803                         instr->hydrogen()->initialization_state()).code();
4804   CallCode(ic, RelocInfo::CODE_TARGET, instr);
4805 }
4806
4807
4808 void LCodeGen::DoTrapAllocationMemento(LTrapAllocationMemento* instr) {
4809   Register object = ToRegister(instr->object());
4810   Register temp = ToRegister(instr->temp());
4811   Label no_memento_found;
4812   __ TestJSArrayForAllocationMemento(object, temp, &no_memento_found);
4813   DeoptimizeIf(equal, instr, Deoptimizer::kMementoFound);
4814   __ bind(&no_memento_found);
4815 }
4816
4817
4818 void LCodeGen::DoTransitionElementsKind(LTransitionElementsKind* instr) {
4819   Register object_reg = ToRegister(instr->object());
4820
4821   Handle<Map> from_map = instr->original_map();
4822   Handle<Map> to_map = instr->transitioned_map();
4823   ElementsKind from_kind = instr->from_kind();
4824   ElementsKind to_kind = instr->to_kind();
4825
4826   Label not_applicable;
4827   bool is_simple_map_transition =
4828       IsSimpleMapChangeTransition(from_kind, to_kind);
4829   Label::Distance branch_distance =
4830       is_simple_map_transition ? Label::kNear : Label::kFar;
4831   __ cmp(FieldOperand(object_reg, HeapObject::kMapOffset), from_map);
4832   __ j(not_equal, &not_applicable, branch_distance);
4833   if (is_simple_map_transition) {
4834     Register new_map_reg = ToRegister(instr->new_map_temp());
4835     __ mov(FieldOperand(object_reg, HeapObject::kMapOffset),
4836            Immediate(to_map));
4837     // Write barrier.
4838     DCHECK_NOT_NULL(instr->temp());
4839     __ RecordWriteForMap(object_reg, to_map, new_map_reg,
4840                          ToRegister(instr->temp()), kDontSaveFPRegs);
4841   } else {
4842     DCHECK(ToRegister(instr->context()).is(esi));
4843     DCHECK(object_reg.is(eax));
4844     PushSafepointRegistersScope scope(this);
4845     __ mov(ebx, to_map);
4846     bool is_js_array = from_map->instance_type() == JS_ARRAY_TYPE;
4847     TransitionElementsKindStub stub(isolate(), from_kind, to_kind, is_js_array);
4848     __ CallStub(&stub);
4849     RecordSafepointWithLazyDeopt(instr,
4850         RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
4851   }
4852   __ bind(&not_applicable);
4853 }
4854
4855
4856 void LCodeGen::DoStringCharCodeAt(LStringCharCodeAt* instr) {
4857   class DeferredStringCharCodeAt FINAL : public LDeferredCode {
4858    public:
4859     DeferredStringCharCodeAt(LCodeGen* codegen,
4860                              LStringCharCodeAt* instr,
4861                              const X87Stack& x87_stack)
4862         : LDeferredCode(codegen, x87_stack), instr_(instr) { }
4863     void Generate() OVERRIDE { codegen()->DoDeferredStringCharCodeAt(instr_); }
4864     LInstruction* instr() OVERRIDE { return instr_; }
4865
4866    private:
4867     LStringCharCodeAt* instr_;
4868   };
4869
4870   DeferredStringCharCodeAt* deferred =
4871       new(zone()) DeferredStringCharCodeAt(this, instr, x87_stack_);
4872
4873   StringCharLoadGenerator::Generate(masm(),
4874                                     factory(),
4875                                     ToRegister(instr->string()),
4876                                     ToRegister(instr->index()),
4877                                     ToRegister(instr->result()),
4878                                     deferred->entry());
4879   __ bind(deferred->exit());
4880 }
4881
4882
4883 void LCodeGen::DoDeferredStringCharCodeAt(LStringCharCodeAt* instr) {
4884   Register string = ToRegister(instr->string());
4885   Register result = ToRegister(instr->result());
4886
4887   // TODO(3095996): Get rid of this. For now, we need to make the
4888   // result register contain a valid pointer because it is already
4889   // contained in the register pointer map.
4890   __ Move(result, Immediate(0));
4891
4892   PushSafepointRegistersScope scope(this);
4893   __ push(string);
4894   // Push the index as a smi. This is safe because of the checks in
4895   // DoStringCharCodeAt above.
4896   STATIC_ASSERT(String::kMaxLength <= Smi::kMaxValue);
4897   if (instr->index()->IsConstantOperand()) {
4898     Immediate immediate = ToImmediate(LConstantOperand::cast(instr->index()),
4899                                       Representation::Smi());
4900     __ push(immediate);
4901   } else {
4902     Register index = ToRegister(instr->index());
4903     __ SmiTag(index);
4904     __ push(index);
4905   }
4906   CallRuntimeFromDeferred(Runtime::kStringCharCodeAtRT, 2,
4907                           instr, instr->context());
4908   __ AssertSmi(eax);
4909   __ SmiUntag(eax);
4910   __ StoreToSafepointRegisterSlot(result, eax);
4911 }
4912
4913
4914 void LCodeGen::DoStringCharFromCode(LStringCharFromCode* instr) {
4915   class DeferredStringCharFromCode FINAL : public LDeferredCode {
4916    public:
4917     DeferredStringCharFromCode(LCodeGen* codegen,
4918                                LStringCharFromCode* instr,
4919                                const X87Stack& x87_stack)
4920         : LDeferredCode(codegen, x87_stack), instr_(instr) { }
4921     void Generate() OVERRIDE {
4922       codegen()->DoDeferredStringCharFromCode(instr_);
4923     }
4924     LInstruction* instr() OVERRIDE { return instr_; }
4925
4926    private:
4927     LStringCharFromCode* instr_;
4928   };
4929
4930   DeferredStringCharFromCode* deferred =
4931       new(zone()) DeferredStringCharFromCode(this, instr, x87_stack_);
4932
4933   DCHECK(instr->hydrogen()->value()->representation().IsInteger32());
4934   Register char_code = ToRegister(instr->char_code());
4935   Register result = ToRegister(instr->result());
4936   DCHECK(!char_code.is(result));
4937
4938   __ cmp(char_code, String::kMaxOneByteCharCode);
4939   __ j(above, deferred->entry());
4940   __ Move(result, Immediate(factory()->single_character_string_cache()));
4941   __ mov(result, FieldOperand(result,
4942                               char_code, times_pointer_size,
4943                               FixedArray::kHeaderSize));
4944   __ cmp(result, factory()->undefined_value());
4945   __ j(equal, deferred->entry());
4946   __ bind(deferred->exit());
4947 }
4948
4949
4950 void LCodeGen::DoDeferredStringCharFromCode(LStringCharFromCode* instr) {
4951   Register char_code = ToRegister(instr->char_code());
4952   Register result = ToRegister(instr->result());
4953
4954   // TODO(3095996): Get rid of this. For now, we need to make the
4955   // result register contain a valid pointer because it is already
4956   // contained in the register pointer map.
4957   __ Move(result, Immediate(0));
4958
4959   PushSafepointRegistersScope scope(this);
4960   __ SmiTag(char_code);
4961   __ push(char_code);
4962   CallRuntimeFromDeferred(Runtime::kCharFromCode, 1, instr, instr->context());
4963   __ StoreToSafepointRegisterSlot(result, eax);
4964 }
4965
4966
4967 void LCodeGen::DoStringAdd(LStringAdd* instr) {
4968   DCHECK(ToRegister(instr->context()).is(esi));
4969   DCHECK(ToRegister(instr->left()).is(edx));
4970   DCHECK(ToRegister(instr->right()).is(eax));
4971   StringAddStub stub(isolate(),
4972                      instr->hydrogen()->flags(),
4973                      instr->hydrogen()->pretenure_flag());
4974   CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
4975 }
4976
4977
4978 void LCodeGen::DoInteger32ToDouble(LInteger32ToDouble* instr) {
4979   LOperand* input = instr->value();
4980   LOperand* output = instr->result();
4981   DCHECK(input->IsRegister() || input->IsStackSlot());
4982   DCHECK(output->IsDoubleRegister());
4983   if (input->IsRegister()) {
4984     Register input_reg = ToRegister(input);
4985     __ push(input_reg);
4986     X87Mov(ToX87Register(output), Operand(esp, 0), kX87IntOperand);
4987     __ pop(input_reg);
4988   } else {
4989     X87Mov(ToX87Register(output), ToOperand(input), kX87IntOperand);
4990   }
4991 }
4992
4993
4994 void LCodeGen::DoUint32ToDouble(LUint32ToDouble* instr) {
4995   LOperand* input = instr->value();
4996   LOperand* output = instr->result();
4997   X87Register res = ToX87Register(output);
4998   X87PrepareToWrite(res);
4999   __ LoadUint32NoSSE2(ToRegister(input));
5000   X87CommitWrite(res);
5001 }
5002
5003
5004 void LCodeGen::DoNumberTagI(LNumberTagI* instr) {
5005   class DeferredNumberTagI FINAL : public LDeferredCode {
5006    public:
5007     DeferredNumberTagI(LCodeGen* codegen,
5008                        LNumberTagI* instr,
5009                        const X87Stack& x87_stack)
5010         : LDeferredCode(codegen, x87_stack), instr_(instr) { }
5011     void Generate() OVERRIDE {
5012       codegen()->DoDeferredNumberTagIU(instr_, instr_->value(), instr_->temp(),
5013                                        SIGNED_INT32);
5014     }
5015     LInstruction* instr() OVERRIDE { return instr_; }
5016
5017    private:
5018     LNumberTagI* instr_;
5019   };
5020
5021   LOperand* input = instr->value();
5022   DCHECK(input->IsRegister() && input->Equals(instr->result()));
5023   Register reg = ToRegister(input);
5024
5025   DeferredNumberTagI* deferred =
5026       new(zone()) DeferredNumberTagI(this, instr, x87_stack_);
5027   __ SmiTag(reg);
5028   __ j(overflow, deferred->entry());
5029   __ bind(deferred->exit());
5030 }
5031
5032
5033 void LCodeGen::DoNumberTagU(LNumberTagU* instr) {
5034   class DeferredNumberTagU FINAL : public LDeferredCode {
5035    public:
5036     DeferredNumberTagU(LCodeGen* codegen,
5037                        LNumberTagU* instr,
5038                        const X87Stack& x87_stack)
5039         : LDeferredCode(codegen, x87_stack), instr_(instr) { }
5040     void Generate() OVERRIDE {
5041       codegen()->DoDeferredNumberTagIU(instr_, instr_->value(), instr_->temp(),
5042                                        UNSIGNED_INT32);
5043     }
5044     LInstruction* instr() OVERRIDE { return instr_; }
5045
5046    private:
5047     LNumberTagU* instr_;
5048   };
5049
5050   LOperand* input = instr->value();
5051   DCHECK(input->IsRegister() && input->Equals(instr->result()));
5052   Register reg = ToRegister(input);
5053
5054   DeferredNumberTagU* deferred =
5055       new(zone()) DeferredNumberTagU(this, instr, x87_stack_);
5056   __ cmp(reg, Immediate(Smi::kMaxValue));
5057   __ j(above, deferred->entry());
5058   __ SmiTag(reg);
5059   __ bind(deferred->exit());
5060 }
5061
5062
5063 void LCodeGen::DoDeferredNumberTagIU(LInstruction* instr,
5064                                      LOperand* value,
5065                                      LOperand* temp,
5066                                      IntegerSignedness signedness) {
5067   Label done, slow;
5068   Register reg = ToRegister(value);
5069   Register tmp = ToRegister(temp);
5070
5071   if (signedness == SIGNED_INT32) {
5072     // There was overflow, so bits 30 and 31 of the original integer
5073     // disagree. Try to allocate a heap number in new space and store
5074     // the value in there. If that fails, call the runtime system.
5075     __ SmiUntag(reg);
5076     __ xor_(reg, 0x80000000);
5077     __ push(reg);
5078     __ fild_s(Operand(esp, 0));
5079     __ pop(reg);
5080   } else {
5081     // There's no fild variant for unsigned values, so zero-extend to a 64-bit
5082     // int manually.
5083     __ push(Immediate(0));
5084     __ push(reg);
5085     __ fild_d(Operand(esp, 0));
5086     __ pop(reg);
5087     __ pop(reg);
5088   }
5089
5090   if (FLAG_inline_new) {
5091     __ AllocateHeapNumber(reg, tmp, no_reg, &slow);
5092     __ jmp(&done, Label::kNear);
5093   }
5094
5095   // Slow case: Call the runtime system to do the number allocation.
5096   __ bind(&slow);
5097   {
5098     // TODO(3095996): Put a valid pointer value in the stack slot where the
5099     // result register is stored, as this register is in the pointer map, but
5100     // contains an integer value.
5101     __ Move(reg, Immediate(0));
5102
5103     // Preserve the value of all registers.
5104     PushSafepointRegistersScope scope(this);
5105
5106     // NumberTagI and NumberTagD use the context from the frame, rather than
5107     // the environment's HContext or HInlinedContext value.
5108     // They only call Runtime::kAllocateHeapNumber.
5109     // The corresponding HChange instructions are added in a phase that does
5110     // not have easy access to the local context.
5111     __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
5112     __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
5113     RecordSafepointWithRegisters(
5114         instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
5115     __ StoreToSafepointRegisterSlot(reg, eax);
5116   }
5117
5118   __ bind(&done);
5119   __ fstp_d(FieldOperand(reg, HeapNumber::kValueOffset));
5120 }
5121
5122
5123 void LCodeGen::DoNumberTagD(LNumberTagD* instr) {
5124   class DeferredNumberTagD FINAL : public LDeferredCode {
5125    public:
5126     DeferredNumberTagD(LCodeGen* codegen,
5127                        LNumberTagD* instr,
5128                        const X87Stack& x87_stack)
5129         : LDeferredCode(codegen, x87_stack), instr_(instr) { }
5130     void Generate() OVERRIDE { codegen()->DoDeferredNumberTagD(instr_); }
5131     LInstruction* instr() OVERRIDE { return instr_; }
5132
5133    private:
5134     LNumberTagD* instr_;
5135   };
5136
5137   Register reg = ToRegister(instr->result());
5138
5139   // Put the value to the top of stack
5140   X87Register src = ToX87Register(instr->value());
5141   // Don't use X87LoadForUsage here, which is only used by Instruction which
5142   // clobbers fp registers.
5143   x87_stack_.Fxch(src);
5144
5145   DeferredNumberTagD* deferred =
5146       new(zone()) DeferredNumberTagD(this, instr, x87_stack_);
5147   if (FLAG_inline_new) {
5148     Register tmp = ToRegister(instr->temp());
5149     __ AllocateHeapNumber(reg, tmp, no_reg, deferred->entry());
5150   } else {
5151     __ jmp(deferred->entry());
5152   }
5153   __ bind(deferred->exit());
5154   __ fst_d(FieldOperand(reg, HeapNumber::kValueOffset));
5155 }
5156
5157
5158 void LCodeGen::DoDeferredNumberTagD(LNumberTagD* instr) {
5159   // TODO(3095996): Get rid of this. For now, we need to make the
5160   // result register contain a valid pointer because it is already
5161   // contained in the register pointer map.
5162   Register reg = ToRegister(instr->result());
5163   __ Move(reg, Immediate(0));
5164
5165   PushSafepointRegistersScope scope(this);
5166   // NumberTagI and NumberTagD use the context from the frame, rather than
5167   // the environment's HContext or HInlinedContext value.
5168   // They only call Runtime::kAllocateHeapNumber.
5169   // The corresponding HChange instructions are added in a phase that does
5170   // not have easy access to the local context.
5171   __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
5172   __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
5173   RecordSafepointWithRegisters(
5174       instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
5175   __ StoreToSafepointRegisterSlot(reg, eax);
5176 }
5177
5178
5179 void LCodeGen::DoSmiTag(LSmiTag* instr) {
5180   HChange* hchange = instr->hydrogen();
5181   Register input = ToRegister(instr->value());
5182   if (hchange->CheckFlag(HValue::kCanOverflow) &&
5183       hchange->value()->CheckFlag(HValue::kUint32)) {
5184     __ test(input, Immediate(0xc0000000));
5185     DeoptimizeIf(not_zero, instr, Deoptimizer::kOverflow);
5186   }
5187   __ SmiTag(input);
5188   if (hchange->CheckFlag(HValue::kCanOverflow) &&
5189       !hchange->value()->CheckFlag(HValue::kUint32)) {
5190     DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
5191   }
5192 }
5193
5194
5195 void LCodeGen::DoSmiUntag(LSmiUntag* instr) {
5196   LOperand* input = instr->value();
5197   Register result = ToRegister(input);
5198   DCHECK(input->IsRegister() && input->Equals(instr->result()));
5199   if (instr->needs_check()) {
5200     __ test(result, Immediate(kSmiTagMask));
5201     DeoptimizeIf(not_zero, instr, Deoptimizer::kNotASmi);
5202   } else {
5203     __ AssertSmi(result);
5204   }
5205   __ SmiUntag(result);
5206 }
5207
5208
5209 void LCodeGen::EmitNumberUntagDNoSSE2(LNumberUntagD* instr, Register input_reg,
5210                                       Register temp_reg, X87Register res_reg,
5211                                       NumberUntagDMode mode) {
5212   bool can_convert_undefined_to_nan =
5213       instr->hydrogen()->can_convert_undefined_to_nan();
5214   bool deoptimize_on_minus_zero = instr->hydrogen()->deoptimize_on_minus_zero();
5215
5216   Label load_smi, done;
5217
5218   X87PrepareToWrite(res_reg);
5219   if (mode == NUMBER_CANDIDATE_IS_ANY_TAGGED) {
5220     // Smi check.
5221     __ JumpIfSmi(input_reg, &load_smi);
5222
5223     // Heap number map check.
5224     __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
5225            factory()->heap_number_map());
5226     if (!can_convert_undefined_to_nan) {
5227       DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
5228     } else {
5229       Label heap_number, convert;
5230       __ j(equal, &heap_number);
5231
5232       // Convert undefined (or hole) to NaN.
5233       __ cmp(input_reg, factory()->undefined_value());
5234       DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumberUndefined);
5235
5236       __ bind(&convert);
5237       __ push(Immediate(0xffffffff));
5238       __ push(Immediate(0x7fffffff));
5239       __ fld_d(MemOperand(esp, 0));
5240       __ lea(esp, Operand(esp, kDoubleSize));
5241       __ jmp(&done, Label::kNear);
5242
5243       __ bind(&heap_number);
5244     }
5245     // Heap number to x87 conversion.
5246     __ fld_d(FieldOperand(input_reg, HeapNumber::kValueOffset));
5247     if (deoptimize_on_minus_zero) {
5248       __ fldz();
5249       __ FCmp();
5250       __ fld_d(FieldOperand(input_reg, HeapNumber::kValueOffset));
5251       __ j(not_zero, &done, Label::kNear);
5252
5253       // Use general purpose registers to check if we have -0.0
5254       __ mov(temp_reg, FieldOperand(input_reg, HeapNumber::kExponentOffset));
5255       __ test(temp_reg, Immediate(HeapNumber::kSignMask));
5256       __ j(zero, &done, Label::kNear);
5257
5258       // Pop FPU stack before deoptimizing.
5259       __ fstp(0);
5260       DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
5261     }
5262     __ jmp(&done, Label::kNear);
5263   } else {
5264     DCHECK(mode == NUMBER_CANDIDATE_IS_SMI);
5265   }
5266
5267   __ bind(&load_smi);
5268   // Clobbering a temp is faster than re-tagging the
5269   // input register since we avoid dependencies.
5270   __ mov(temp_reg, input_reg);
5271   __ SmiUntag(temp_reg);  // Untag smi before converting to float.
5272   __ push(temp_reg);
5273   __ fild_s(Operand(esp, 0));
5274   __ add(esp, Immediate(kPointerSize));
5275   __ bind(&done);
5276   X87CommitWrite(res_reg);
5277 }
5278
5279
5280 void LCodeGen::DoDeferredTaggedToI(LTaggedToI* instr, Label* done) {
5281   Register input_reg = ToRegister(instr->value());
5282
5283   // The input was optimistically untagged; revert it.
5284   STATIC_ASSERT(kSmiTagSize == 1);
5285   __ lea(input_reg, Operand(input_reg, times_2, kHeapObjectTag));
5286
5287   if (instr->truncating()) {
5288     Label no_heap_number, check_bools, check_false;
5289
5290     // Heap number map check.
5291     __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
5292            factory()->heap_number_map());
5293     __ j(not_equal, &no_heap_number, Label::kNear);
5294     __ TruncateHeapNumberToI(input_reg, input_reg);
5295     __ jmp(done);
5296
5297     __ bind(&no_heap_number);
5298     // Check for Oddballs. Undefined/False is converted to zero and True to one
5299     // for truncating conversions.
5300     __ cmp(input_reg, factory()->undefined_value());
5301     __ j(not_equal, &check_bools, Label::kNear);
5302     __ Move(input_reg, Immediate(0));
5303     __ jmp(done);
5304
5305     __ bind(&check_bools);
5306     __ cmp(input_reg, factory()->true_value());
5307     __ j(not_equal, &check_false, Label::kNear);
5308     __ Move(input_reg, Immediate(1));
5309     __ jmp(done);
5310
5311     __ bind(&check_false);
5312     __ cmp(input_reg, factory()->false_value());
5313     DeoptimizeIf(not_equal, instr,
5314                  Deoptimizer::kNotAHeapNumberUndefinedBoolean);
5315     __ Move(input_reg, Immediate(0));
5316   } else {
5317     // TODO(olivf) Converting a number on the fpu is actually quite slow. We
5318     // should first try a fast conversion and then bailout to this slow case.
5319     __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
5320            isolate()->factory()->heap_number_map());
5321     DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
5322
5323     __ sub(esp, Immediate(kPointerSize));
5324     __ fld_d(FieldOperand(input_reg, HeapNumber::kValueOffset));
5325
5326     if (instr->hydrogen()->GetMinusZeroMode() == FAIL_ON_MINUS_ZERO) {
5327       Label no_precision_lost, not_nan, zero_check;
5328       __ fld(0);
5329
5330       __ fist_s(MemOperand(esp, 0));
5331       __ fild_s(MemOperand(esp, 0));
5332       __ FCmp();
5333       __ pop(input_reg);
5334
5335       __ j(equal, &no_precision_lost, Label::kNear);
5336       __ fstp(0);
5337       DeoptimizeIf(no_condition, instr, Deoptimizer::kLostPrecision);
5338       __ bind(&no_precision_lost);
5339
5340       __ j(parity_odd, &not_nan);
5341       __ fstp(0);
5342       DeoptimizeIf(no_condition, instr, Deoptimizer::kNaN);
5343       __ bind(&not_nan);
5344
5345       __ test(input_reg, Operand(input_reg));
5346       __ j(zero, &zero_check, Label::kNear);
5347       __ fstp(0);
5348       __ jmp(done);
5349
5350       __ bind(&zero_check);
5351       // To check for minus zero, we load the value again as float, and check
5352       // if that is still 0.
5353       __ sub(esp, Immediate(kPointerSize));
5354       __ fstp_s(Operand(esp, 0));
5355       __ pop(input_reg);
5356       __ test(input_reg, Operand(input_reg));
5357       DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
5358     } else {
5359       __ fist_s(MemOperand(esp, 0));
5360       __ fild_s(MemOperand(esp, 0));
5361       __ FCmp();
5362       __ pop(input_reg);
5363       DeoptimizeIf(not_equal, instr, Deoptimizer::kLostPrecision);
5364       DeoptimizeIf(parity_even, instr, Deoptimizer::kNaN);
5365     }
5366   }
5367 }
5368
5369
5370 void LCodeGen::DoTaggedToI(LTaggedToI* instr) {
5371   class DeferredTaggedToI FINAL : public LDeferredCode {
5372    public:
5373     DeferredTaggedToI(LCodeGen* codegen,
5374                       LTaggedToI* instr,
5375                       const X87Stack& x87_stack)
5376         : LDeferredCode(codegen, x87_stack), instr_(instr) { }
5377     void Generate() OVERRIDE { codegen()->DoDeferredTaggedToI(instr_, done()); }
5378     LInstruction* instr() OVERRIDE { return instr_; }
5379
5380    private:
5381     LTaggedToI* instr_;
5382   };
5383
5384   LOperand* input = instr->value();
5385   DCHECK(input->IsRegister());
5386   Register input_reg = ToRegister(input);
5387   DCHECK(input_reg.is(ToRegister(instr->result())));
5388
5389   if (instr->hydrogen()->value()->representation().IsSmi()) {
5390     __ SmiUntag(input_reg);
5391   } else {
5392     DeferredTaggedToI* deferred =
5393         new(zone()) DeferredTaggedToI(this, instr, x87_stack_);
5394     // Optimistically untag the input.
5395     // If the input is a HeapObject, SmiUntag will set the carry flag.
5396     STATIC_ASSERT(kSmiTagSize == 1 && kSmiTag == 0);
5397     __ SmiUntag(input_reg);
5398     // Branch to deferred code if the input was tagged.
5399     // The deferred code will take care of restoring the tag.
5400     __ j(carry, deferred->entry());
5401     __ bind(deferred->exit());
5402   }
5403 }
5404
5405
5406 void LCodeGen::DoNumberUntagD(LNumberUntagD* instr) {
5407   LOperand* input = instr->value();
5408   DCHECK(input->IsRegister());
5409   LOperand* temp = instr->temp();
5410   DCHECK(temp->IsRegister());
5411   LOperand* result = instr->result();
5412   DCHECK(result->IsDoubleRegister());
5413
5414   Register input_reg = ToRegister(input);
5415   Register temp_reg = ToRegister(temp);
5416
5417   HValue* value = instr->hydrogen()->value();
5418   NumberUntagDMode mode = value->representation().IsSmi()
5419       ? NUMBER_CANDIDATE_IS_SMI : NUMBER_CANDIDATE_IS_ANY_TAGGED;
5420
5421   EmitNumberUntagDNoSSE2(instr, input_reg, temp_reg, ToX87Register(result),
5422                          mode);
5423 }
5424
5425
5426 void LCodeGen::DoDoubleToI(LDoubleToI* instr) {
5427   LOperand* input = instr->value();
5428   DCHECK(input->IsDoubleRegister());
5429   LOperand* result = instr->result();
5430   DCHECK(result->IsRegister());
5431   Register result_reg = ToRegister(result);
5432
5433   if (instr->truncating()) {
5434     X87Register input_reg = ToX87Register(input);
5435     X87Fxch(input_reg);
5436     __ TruncateX87TOSToI(result_reg);
5437   } else {
5438     Label lost_precision, is_nan, minus_zero, done;
5439     X87Register input_reg = ToX87Register(input);
5440     X87Fxch(input_reg);
5441     __ X87TOSToI(result_reg, instr->hydrogen()->GetMinusZeroMode(),
5442                  &lost_precision, &is_nan, &minus_zero);
5443     __ jmp(&done);
5444     __ bind(&lost_precision);
5445     DeoptimizeIf(no_condition, instr, Deoptimizer::kLostPrecision);
5446     __ bind(&is_nan);
5447     DeoptimizeIf(no_condition, instr, Deoptimizer::kNaN);
5448     __ bind(&minus_zero);
5449     DeoptimizeIf(no_condition, instr, Deoptimizer::kMinusZero);
5450     __ bind(&done);
5451   }
5452 }
5453
5454
5455 void LCodeGen::DoDoubleToSmi(LDoubleToSmi* instr) {
5456   LOperand* input = instr->value();
5457   DCHECK(input->IsDoubleRegister());
5458   LOperand* result = instr->result();
5459   DCHECK(result->IsRegister());
5460   Register result_reg = ToRegister(result);
5461
5462   Label lost_precision, is_nan, minus_zero, done;
5463   X87Register input_reg = ToX87Register(input);
5464   X87Fxch(input_reg);
5465   __ X87TOSToI(result_reg, instr->hydrogen()->GetMinusZeroMode(),
5466                &lost_precision, &is_nan, &minus_zero);
5467   __ jmp(&done);
5468   __ bind(&lost_precision);
5469   DeoptimizeIf(no_condition, instr, Deoptimizer::kLostPrecision);
5470   __ bind(&is_nan);
5471   DeoptimizeIf(no_condition, instr, Deoptimizer::kNaN);
5472   __ bind(&minus_zero);
5473   DeoptimizeIf(no_condition, instr, Deoptimizer::kMinusZero);
5474   __ bind(&done);
5475   __ SmiTag(result_reg);
5476   DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
5477 }
5478
5479
5480 void LCodeGen::DoCheckSmi(LCheckSmi* instr) {
5481   LOperand* input = instr->value();
5482   __ test(ToOperand(input), Immediate(kSmiTagMask));
5483   DeoptimizeIf(not_zero, instr, Deoptimizer::kNotASmi);
5484 }
5485
5486
5487 void LCodeGen::DoCheckNonSmi(LCheckNonSmi* instr) {
5488   if (!instr->hydrogen()->value()->type().IsHeapObject()) {
5489     LOperand* input = instr->value();
5490     __ test(ToOperand(input), Immediate(kSmiTagMask));
5491     DeoptimizeIf(zero, instr, Deoptimizer::kSmi);
5492   }
5493 }
5494
5495
5496 void LCodeGen::DoCheckInstanceType(LCheckInstanceType* instr) {
5497   Register input = ToRegister(instr->value());
5498   Register temp = ToRegister(instr->temp());
5499
5500   __ mov(temp, FieldOperand(input, HeapObject::kMapOffset));
5501
5502   if (instr->hydrogen()->is_interval_check()) {
5503     InstanceType first;
5504     InstanceType last;
5505     instr->hydrogen()->GetCheckInterval(&first, &last);
5506
5507     __ cmpb(FieldOperand(temp, Map::kInstanceTypeOffset),
5508             static_cast<int8_t>(first));
5509
5510     // If there is only one type in the interval check for equality.
5511     if (first == last) {
5512       DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongInstanceType);
5513     } else {
5514       DeoptimizeIf(below, instr, Deoptimizer::kWrongInstanceType);
5515       // Omit check for the last type.
5516       if (last != LAST_TYPE) {
5517         __ cmpb(FieldOperand(temp, Map::kInstanceTypeOffset),
5518                 static_cast<int8_t>(last));
5519         DeoptimizeIf(above, instr, Deoptimizer::kWrongInstanceType);
5520       }
5521     }
5522   } else {
5523     uint8_t mask;
5524     uint8_t tag;
5525     instr->hydrogen()->GetCheckMaskAndTag(&mask, &tag);
5526
5527     if (base::bits::IsPowerOfTwo32(mask)) {
5528       DCHECK(tag == 0 || base::bits::IsPowerOfTwo32(tag));
5529       __ test_b(FieldOperand(temp, Map::kInstanceTypeOffset), mask);
5530       DeoptimizeIf(tag == 0 ? not_zero : zero, instr,
5531                    Deoptimizer::kWrongInstanceType);
5532     } else {
5533       __ movzx_b(temp, FieldOperand(temp, Map::kInstanceTypeOffset));
5534       __ and_(temp, mask);
5535       __ cmp(temp, tag);
5536       DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongInstanceType);
5537     }
5538   }
5539 }
5540
5541
5542 void LCodeGen::DoCheckValue(LCheckValue* instr) {
5543   Handle<HeapObject> object = instr->hydrogen()->object().handle();
5544   if (instr->hydrogen()->object_in_new_space()) {
5545     Register reg = ToRegister(instr->value());
5546     Handle<Cell> cell = isolate()->factory()->NewCell(object);
5547     __ cmp(reg, Operand::ForCell(cell));
5548   } else {
5549     Operand operand = ToOperand(instr->value());
5550     __ cmp(operand, object);
5551   }
5552   DeoptimizeIf(not_equal, instr, Deoptimizer::kValueMismatch);
5553 }
5554
5555
5556 void LCodeGen::DoDeferredInstanceMigration(LCheckMaps* instr, Register object) {
5557   {
5558     PushSafepointRegistersScope scope(this);
5559     __ push(object);
5560     __ xor_(esi, esi);
5561     __ CallRuntimeSaveDoubles(Runtime::kTryMigrateInstance);
5562     RecordSafepointWithRegisters(
5563         instr->pointer_map(), 1, Safepoint::kNoLazyDeopt);
5564
5565     __ test(eax, Immediate(kSmiTagMask));
5566   }
5567   DeoptimizeIf(zero, instr, Deoptimizer::kInstanceMigrationFailed);
5568 }
5569
5570
5571 void LCodeGen::DoCheckMaps(LCheckMaps* instr) {
5572   class DeferredCheckMaps FINAL : public LDeferredCode {
5573    public:
5574     DeferredCheckMaps(LCodeGen* codegen,
5575                       LCheckMaps* instr,
5576                       Register object,
5577                       const X87Stack& x87_stack)
5578         : LDeferredCode(codegen, x87_stack), instr_(instr), object_(object) {
5579       SetExit(check_maps());
5580     }
5581     void Generate() OVERRIDE {
5582       codegen()->DoDeferredInstanceMigration(instr_, object_);
5583     }
5584     Label* check_maps() { return &check_maps_; }
5585     LInstruction* instr() OVERRIDE { return instr_; }
5586
5587    private:
5588     LCheckMaps* instr_;
5589     Label check_maps_;
5590     Register object_;
5591   };
5592
5593   if (instr->hydrogen()->IsStabilityCheck()) {
5594     const UniqueSet<Map>* maps = instr->hydrogen()->maps();
5595     for (int i = 0; i < maps->size(); ++i) {
5596       AddStabilityDependency(maps->at(i).handle());
5597     }
5598     return;
5599   }
5600
5601   LOperand* input = instr->value();
5602   DCHECK(input->IsRegister());
5603   Register reg = ToRegister(input);
5604
5605   DeferredCheckMaps* deferred = NULL;
5606   if (instr->hydrogen()->HasMigrationTarget()) {
5607     deferred = new(zone()) DeferredCheckMaps(this, instr, reg, x87_stack_);
5608     __ bind(deferred->check_maps());
5609   }
5610
5611   const UniqueSet<Map>* maps = instr->hydrogen()->maps();
5612   Label success;
5613   for (int i = 0; i < maps->size() - 1; i++) {
5614     Handle<Map> map = maps->at(i).handle();
5615     __ CompareMap(reg, map);
5616     __ j(equal, &success, Label::kNear);
5617   }
5618
5619   Handle<Map> map = maps->at(maps->size() - 1).handle();
5620   __ CompareMap(reg, map);
5621   if (instr->hydrogen()->HasMigrationTarget()) {
5622     __ j(not_equal, deferred->entry());
5623   } else {
5624     DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongMap);
5625   }
5626
5627   __ bind(&success);
5628 }
5629
5630
5631 void LCodeGen::DoClampDToUint8(LClampDToUint8* instr) {
5632   X87Register value_reg = ToX87Register(instr->unclamped());
5633   Register result_reg = ToRegister(instr->result());
5634   X87Fxch(value_reg);
5635   __ ClampTOSToUint8(result_reg);
5636 }
5637
5638
5639 void LCodeGen::DoClampIToUint8(LClampIToUint8* instr) {
5640   DCHECK(instr->unclamped()->Equals(instr->result()));
5641   Register value_reg = ToRegister(instr->result());
5642   __ ClampUint8(value_reg);
5643 }
5644
5645
5646 void LCodeGen::DoClampTToUint8NoSSE2(LClampTToUint8NoSSE2* instr) {
5647   Register input_reg = ToRegister(instr->unclamped());
5648   Register result_reg = ToRegister(instr->result());
5649   Register scratch = ToRegister(instr->scratch());
5650   Register scratch2 = ToRegister(instr->scratch2());
5651   Register scratch3 = ToRegister(instr->scratch3());
5652   Label is_smi, done, heap_number, valid_exponent,
5653       largest_value, zero_result, maybe_nan_or_infinity;
5654
5655   __ JumpIfSmi(input_reg, &is_smi);
5656
5657   // Check for heap number
5658   __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
5659          factory()->heap_number_map());
5660   __ j(equal, &heap_number, Label::kNear);
5661
5662   // Check for undefined. Undefined is converted to zero for clamping
5663   // conversions.
5664   __ cmp(input_reg, factory()->undefined_value());
5665   DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumberUndefined);
5666   __ jmp(&zero_result, Label::kNear);
5667
5668   // Heap number
5669   __ bind(&heap_number);
5670
5671   // Surprisingly, all of the hand-crafted bit-manipulations below are much
5672   // faster than the x86 FPU built-in instruction, especially since "banker's
5673   // rounding" would be additionally very expensive
5674
5675   // Get exponent word.
5676   __ mov(scratch, FieldOperand(input_reg, HeapNumber::kExponentOffset));
5677   __ mov(scratch3, FieldOperand(input_reg, HeapNumber::kMantissaOffset));
5678
5679   // Test for negative values --> clamp to zero
5680   __ test(scratch, scratch);
5681   __ j(negative, &zero_result, Label::kNear);
5682
5683   // Get exponent alone in scratch2.
5684   __ mov(scratch2, scratch);
5685   __ and_(scratch2, HeapNumber::kExponentMask);
5686   __ shr(scratch2, HeapNumber::kExponentShift);
5687   __ j(zero, &zero_result, Label::kNear);
5688   __ sub(scratch2, Immediate(HeapNumber::kExponentBias - 1));
5689   __ j(negative, &zero_result, Label::kNear);
5690
5691   const uint32_t non_int8_exponent = 7;
5692   __ cmp(scratch2, Immediate(non_int8_exponent + 1));
5693   // If the exponent is too big, check for special values.
5694   __ j(greater, &maybe_nan_or_infinity, Label::kNear);
5695
5696   __ bind(&valid_exponent);
5697   // Exponent word in scratch, exponent in scratch2. We know that 0 <= exponent
5698   // < 7. The shift bias is the number of bits to shift the mantissa such that
5699   // with an exponent of 7 such the that top-most one is in bit 30, allowing
5700   // detection the rounding overflow of a 255.5 to 256 (bit 31 goes from 0 to
5701   // 1).
5702   int shift_bias = (30 - HeapNumber::kExponentShift) - 7 - 1;
5703   __ lea(result_reg, MemOperand(scratch2, shift_bias));
5704   // Here result_reg (ecx) is the shift, scratch is the exponent word.  Get the
5705   // top bits of the mantissa.
5706   __ and_(scratch, HeapNumber::kMantissaMask);
5707   // Put back the implicit 1 of the mantissa
5708   __ or_(scratch, 1 << HeapNumber::kExponentShift);
5709   // Shift up to round
5710   __ shl_cl(scratch);
5711   // Use "banker's rounding" to spec: If fractional part of number is 0.5, then
5712   // use the bit in the "ones" place and add it to the "halves" place, which has
5713   // the effect of rounding to even.
5714   __ mov(scratch2, scratch);
5715   const uint32_t one_half_bit_shift = 30 - sizeof(uint8_t) * 8;
5716   const uint32_t one_bit_shift = one_half_bit_shift + 1;
5717   __ and_(scratch2, Immediate((1 << one_bit_shift) - 1));
5718   __ cmp(scratch2, Immediate(1 << one_half_bit_shift));
5719   Label no_round;
5720   __ j(less, &no_round, Label::kNear);
5721   Label round_up;
5722   __ mov(scratch2, Immediate(1 << one_half_bit_shift));
5723   __ j(greater, &round_up, Label::kNear);
5724   __ test(scratch3, scratch3);
5725   __ j(not_zero, &round_up, Label::kNear);
5726   __ mov(scratch2, scratch);
5727   __ and_(scratch2, Immediate(1 << one_bit_shift));
5728   __ shr(scratch2, 1);
5729   __ bind(&round_up);
5730   __ add(scratch, scratch2);
5731   __ j(overflow, &largest_value, Label::kNear);
5732   __ bind(&no_round);
5733   __ shr(scratch, 23);
5734   __ mov(result_reg, scratch);
5735   __ jmp(&done, Label::kNear);
5736
5737   __ bind(&maybe_nan_or_infinity);
5738   // Check for NaN/Infinity, all other values map to 255
5739   __ cmp(scratch2, Immediate(HeapNumber::kInfinityOrNanExponent + 1));
5740   __ j(not_equal, &largest_value, Label::kNear);
5741
5742   // Check for NaN, which differs from Infinity in that at least one mantissa
5743   // bit is set.
5744   __ and_(scratch, HeapNumber::kMantissaMask);
5745   __ or_(scratch, FieldOperand(input_reg, HeapNumber::kMantissaOffset));
5746   __ j(not_zero, &zero_result, Label::kNear);  // M!=0 --> NaN
5747   // Infinity -> Fall through to map to 255.
5748
5749   __ bind(&largest_value);
5750   __ mov(result_reg, Immediate(255));
5751   __ jmp(&done, Label::kNear);
5752
5753   __ bind(&zero_result);
5754   __ xor_(result_reg, result_reg);
5755   __ jmp(&done, Label::kNear);
5756
5757   // smi
5758   __ bind(&is_smi);
5759   if (!input_reg.is(result_reg)) {
5760     __ mov(result_reg, input_reg);
5761   }
5762   __ SmiUntag(result_reg);
5763   __ ClampUint8(result_reg);
5764   __ bind(&done);
5765 }
5766
5767
5768 void LCodeGen::DoDoubleBits(LDoubleBits* instr) {
5769   X87Register value_reg = ToX87Register(instr->value());
5770   Register result_reg = ToRegister(instr->result());
5771   X87Fxch(value_reg);
5772   __ sub(esp, Immediate(kDoubleSize));
5773   __ fst_d(Operand(esp, 0));
5774   if (instr->hydrogen()->bits() == HDoubleBits::HIGH) {
5775     __ mov(result_reg, Operand(esp, kPointerSize));
5776   } else {
5777     __ mov(result_reg, Operand(esp, 0));
5778   }
5779   __ add(esp, Immediate(kDoubleSize));
5780 }
5781
5782
5783 void LCodeGen::DoConstructDouble(LConstructDouble* instr) {
5784   Register hi_reg = ToRegister(instr->hi());
5785   Register lo_reg = ToRegister(instr->lo());
5786   X87Register result_reg = ToX87Register(instr->result());
5787   // Follow below pattern to write a x87 fp register.
5788   X87PrepareToWrite(result_reg);
5789   __ sub(esp, Immediate(kDoubleSize));
5790   __ mov(Operand(esp, 0), lo_reg);
5791   __ mov(Operand(esp, kPointerSize), hi_reg);
5792   __ fld_d(Operand(esp, 0));
5793   __ add(esp, Immediate(kDoubleSize));
5794   X87CommitWrite(result_reg);
5795 }
5796
5797
5798 void LCodeGen::DoAllocate(LAllocate* instr) {
5799   class DeferredAllocate FINAL : public LDeferredCode {
5800    public:
5801     DeferredAllocate(LCodeGen* codegen,
5802                      LAllocate* instr,
5803                      const X87Stack& x87_stack)
5804         : LDeferredCode(codegen, x87_stack), instr_(instr) { }
5805     void Generate() OVERRIDE { codegen()->DoDeferredAllocate(instr_); }
5806     LInstruction* instr() OVERRIDE { return instr_; }
5807
5808    private:
5809     LAllocate* instr_;
5810   };
5811
5812   DeferredAllocate* deferred =
5813       new(zone()) DeferredAllocate(this, instr, x87_stack_);
5814
5815   Register result = ToRegister(instr->result());
5816   Register temp = ToRegister(instr->temp());
5817
5818   // Allocate memory for the object.
5819   AllocationFlags flags = TAG_OBJECT;
5820   if (instr->hydrogen()->MustAllocateDoubleAligned()) {
5821     flags = static_cast<AllocationFlags>(flags | DOUBLE_ALIGNMENT);
5822   }
5823   if (instr->hydrogen()->IsOldPointerSpaceAllocation()) {
5824     DCHECK(!instr->hydrogen()->IsOldDataSpaceAllocation());
5825     DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
5826     flags = static_cast<AllocationFlags>(flags | PRETENURE_OLD_POINTER_SPACE);
5827   } else if (instr->hydrogen()->IsOldDataSpaceAllocation()) {
5828     DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
5829     flags = static_cast<AllocationFlags>(flags | PRETENURE_OLD_DATA_SPACE);
5830   }
5831
5832   if (instr->size()->IsConstantOperand()) {
5833     int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
5834     if (size <= Page::kMaxRegularHeapObjectSize) {
5835       __ Allocate(size, result, temp, no_reg, deferred->entry(), flags);
5836     } else {
5837       __ jmp(deferred->entry());
5838     }
5839   } else {
5840     Register size = ToRegister(instr->size());
5841     __ Allocate(size, result, temp, no_reg, deferred->entry(), flags);
5842   }
5843
5844   __ bind(deferred->exit());
5845
5846   if (instr->hydrogen()->MustPrefillWithFiller()) {
5847     if (instr->size()->IsConstantOperand()) {
5848       int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
5849       __ mov(temp, (size / kPointerSize) - 1);
5850     } else {
5851       temp = ToRegister(instr->size());
5852       __ shr(temp, kPointerSizeLog2);
5853       __ dec(temp);
5854     }
5855     Label loop;
5856     __ bind(&loop);
5857     __ mov(FieldOperand(result, temp, times_pointer_size, 0),
5858         isolate()->factory()->one_pointer_filler_map());
5859     __ dec(temp);
5860     __ j(not_zero, &loop);
5861   }
5862 }
5863
5864
5865 void LCodeGen::DoDeferredAllocate(LAllocate* instr) {
5866   Register result = ToRegister(instr->result());
5867
5868   // TODO(3095996): Get rid of this. For now, we need to make the
5869   // result register contain a valid pointer because it is already
5870   // contained in the register pointer map.
5871   __ Move(result, Immediate(Smi::FromInt(0)));
5872
5873   PushSafepointRegistersScope scope(this);
5874   if (instr->size()->IsRegister()) {
5875     Register size = ToRegister(instr->size());
5876     DCHECK(!size.is(result));
5877     __ SmiTag(ToRegister(instr->size()));
5878     __ push(size);
5879   } else {
5880     int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
5881     if (size >= 0 && size <= Smi::kMaxValue) {
5882       __ push(Immediate(Smi::FromInt(size)));
5883     } else {
5884       // We should never get here at runtime => abort
5885       __ int3();
5886       return;
5887     }
5888   }
5889
5890   int flags = AllocateDoubleAlignFlag::encode(
5891       instr->hydrogen()->MustAllocateDoubleAligned());
5892   if (instr->hydrogen()->IsOldPointerSpaceAllocation()) {
5893     DCHECK(!instr->hydrogen()->IsOldDataSpaceAllocation());
5894     DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
5895     flags = AllocateTargetSpace::update(flags, OLD_POINTER_SPACE);
5896   } else if (instr->hydrogen()->IsOldDataSpaceAllocation()) {
5897     DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
5898     flags = AllocateTargetSpace::update(flags, OLD_DATA_SPACE);
5899   } else {
5900     flags = AllocateTargetSpace::update(flags, NEW_SPACE);
5901   }
5902   __ push(Immediate(Smi::FromInt(flags)));
5903
5904   CallRuntimeFromDeferred(
5905       Runtime::kAllocateInTargetSpace, 2, instr, instr->context());
5906   __ StoreToSafepointRegisterSlot(result, eax);
5907 }
5908
5909
5910 void LCodeGen::DoToFastProperties(LToFastProperties* instr) {
5911   DCHECK(ToRegister(instr->value()).is(eax));
5912   __ push(eax);
5913   CallRuntime(Runtime::kToFastProperties, 1, instr);
5914 }
5915
5916
5917 void LCodeGen::DoRegExpLiteral(LRegExpLiteral* instr) {
5918   DCHECK(ToRegister(instr->context()).is(esi));
5919   Label materialized;
5920   // Registers will be used as follows:
5921   // ecx = literals array.
5922   // ebx = regexp literal.
5923   // eax = regexp literal clone.
5924   // esi = context.
5925   int literal_offset =
5926       FixedArray::OffsetOfElementAt(instr->hydrogen()->literal_index());
5927   __ LoadHeapObject(ecx, instr->hydrogen()->literals());
5928   __ mov(ebx, FieldOperand(ecx, literal_offset));
5929   __ cmp(ebx, factory()->undefined_value());
5930   __ j(not_equal, &materialized, Label::kNear);
5931
5932   // Create regexp literal using runtime function
5933   // Result will be in eax.
5934   __ push(ecx);
5935   __ push(Immediate(Smi::FromInt(instr->hydrogen()->literal_index())));
5936   __ push(Immediate(instr->hydrogen()->pattern()));
5937   __ push(Immediate(instr->hydrogen()->flags()));
5938   CallRuntime(Runtime::kMaterializeRegExpLiteral, 4, instr);
5939   __ mov(ebx, eax);
5940
5941   __ bind(&materialized);
5942   int size = JSRegExp::kSize + JSRegExp::kInObjectFieldCount * kPointerSize;
5943   Label allocated, runtime_allocate;
5944   __ Allocate(size, eax, ecx, edx, &runtime_allocate, TAG_OBJECT);
5945   __ jmp(&allocated, Label::kNear);
5946
5947   __ bind(&runtime_allocate);
5948   __ push(ebx);
5949   __ push(Immediate(Smi::FromInt(size)));
5950   CallRuntime(Runtime::kAllocateInNewSpace, 1, instr);
5951   __ pop(ebx);
5952
5953   __ bind(&allocated);
5954   // Copy the content into the newly allocated memory.
5955   // (Unroll copy loop once for better throughput).
5956   for (int i = 0; i < size - kPointerSize; i += 2 * kPointerSize) {
5957     __ mov(edx, FieldOperand(ebx, i));
5958     __ mov(ecx, FieldOperand(ebx, i + kPointerSize));
5959     __ mov(FieldOperand(eax, i), edx);
5960     __ mov(FieldOperand(eax, i + kPointerSize), ecx);
5961   }
5962   if ((size % (2 * kPointerSize)) != 0) {
5963     __ mov(edx, FieldOperand(ebx, size - kPointerSize));
5964     __ mov(FieldOperand(eax, size - kPointerSize), edx);
5965   }
5966 }
5967
5968
5969 void LCodeGen::DoFunctionLiteral(LFunctionLiteral* instr) {
5970   DCHECK(ToRegister(instr->context()).is(esi));
5971   // Use the fast case closure allocation code that allocates in new
5972   // space for nested functions that don't need literals cloning.
5973   bool pretenure = instr->hydrogen()->pretenure();
5974   if (!pretenure && instr->hydrogen()->has_no_literals()) {
5975     FastNewClosureStub stub(isolate(), instr->hydrogen()->language_mode(),
5976                             instr->hydrogen()->kind());
5977     __ mov(ebx, Immediate(instr->hydrogen()->shared_info()));
5978     CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
5979   } else {
5980     __ push(esi);
5981     __ push(Immediate(instr->hydrogen()->shared_info()));
5982     __ push(Immediate(pretenure ? factory()->true_value()
5983                                 : factory()->false_value()));
5984     CallRuntime(Runtime::kNewClosure, 3, instr);
5985   }
5986 }
5987
5988
5989 void LCodeGen::DoTypeof(LTypeof* instr) {
5990   DCHECK(ToRegister(instr->context()).is(esi));
5991   LOperand* input = instr->value();
5992   EmitPushTaggedOperand(input);
5993   CallRuntime(Runtime::kTypeof, 1, instr);
5994 }
5995
5996
5997 void LCodeGen::DoTypeofIsAndBranch(LTypeofIsAndBranch* instr) {
5998   Register input = ToRegister(instr->value());
5999   Condition final_branch_condition = EmitTypeofIs(instr, input);
6000   if (final_branch_condition != no_condition) {
6001     EmitBranch(instr, final_branch_condition);
6002   }
6003 }
6004
6005
6006 Condition LCodeGen::EmitTypeofIs(LTypeofIsAndBranch* instr, Register input) {
6007   Label* true_label = instr->TrueLabel(chunk_);
6008   Label* false_label = instr->FalseLabel(chunk_);
6009   Handle<String> type_name = instr->type_literal();
6010   int left_block = instr->TrueDestination(chunk_);
6011   int right_block = instr->FalseDestination(chunk_);
6012   int next_block = GetNextEmittedBlock();
6013
6014   Label::Distance true_distance = left_block == next_block ? Label::kNear
6015                                                            : Label::kFar;
6016   Label::Distance false_distance = right_block == next_block ? Label::kNear
6017                                                              : Label::kFar;
6018   Condition final_branch_condition = no_condition;
6019   if (String::Equals(type_name, factory()->number_string())) {
6020     __ JumpIfSmi(input, true_label, true_distance);
6021     __ cmp(FieldOperand(input, HeapObject::kMapOffset),
6022            factory()->heap_number_map());
6023     final_branch_condition = equal;
6024
6025   } else if (String::Equals(type_name, factory()->string_string())) {
6026     __ JumpIfSmi(input, false_label, false_distance);
6027     __ CmpObjectType(input, FIRST_NONSTRING_TYPE, input);
6028     __ j(above_equal, false_label, false_distance);
6029     __ test_b(FieldOperand(input, Map::kBitFieldOffset),
6030               1 << Map::kIsUndetectable);
6031     final_branch_condition = zero;
6032
6033   } else if (String::Equals(type_name, factory()->symbol_string())) {
6034     __ JumpIfSmi(input, false_label, false_distance);
6035     __ CmpObjectType(input, SYMBOL_TYPE, input);
6036     final_branch_condition = equal;
6037
6038   } else if (String::Equals(type_name, factory()->boolean_string())) {
6039     __ cmp(input, factory()->true_value());
6040     __ j(equal, true_label, true_distance);
6041     __ cmp(input, factory()->false_value());
6042     final_branch_condition = equal;
6043
6044   } else if (String::Equals(type_name, factory()->undefined_string())) {
6045     __ cmp(input, factory()->undefined_value());
6046     __ j(equal, true_label, true_distance);
6047     __ JumpIfSmi(input, false_label, false_distance);
6048     // Check for undetectable objects => true.
6049     __ mov(input, FieldOperand(input, HeapObject::kMapOffset));
6050     __ test_b(FieldOperand(input, Map::kBitFieldOffset),
6051               1 << Map::kIsUndetectable);
6052     final_branch_condition = not_zero;
6053
6054   } else if (String::Equals(type_name, factory()->function_string())) {
6055     STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
6056     __ JumpIfSmi(input, false_label, false_distance);
6057     __ CmpObjectType(input, JS_FUNCTION_TYPE, input);
6058     __ j(equal, true_label, true_distance);
6059     __ CmpInstanceType(input, JS_FUNCTION_PROXY_TYPE);
6060     final_branch_condition = equal;
6061
6062   } else if (String::Equals(type_name, factory()->object_string())) {
6063     __ JumpIfSmi(input, false_label, false_distance);
6064     __ cmp(input, factory()->null_value());
6065     __ j(equal, true_label, true_distance);
6066     __ CmpObjectType(input, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE, input);
6067     __ j(below, false_label, false_distance);
6068     __ CmpInstanceType(input, LAST_NONCALLABLE_SPEC_OBJECT_TYPE);
6069     __ j(above, false_label, false_distance);
6070     // Check for undetectable objects => false.
6071     __ test_b(FieldOperand(input, Map::kBitFieldOffset),
6072               1 << Map::kIsUndetectable);
6073     final_branch_condition = zero;
6074
6075   } else {
6076     __ jmp(false_label, false_distance);
6077   }
6078   return final_branch_condition;
6079 }
6080
6081
6082 void LCodeGen::DoIsConstructCallAndBranch(LIsConstructCallAndBranch* instr) {
6083   Register temp = ToRegister(instr->temp());
6084
6085   EmitIsConstructCall(temp);
6086   EmitBranch(instr, equal);
6087 }
6088
6089
6090 void LCodeGen::EmitIsConstructCall(Register temp) {
6091   // Get the frame pointer for the calling frame.
6092   __ mov(temp, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
6093
6094   // Skip the arguments adaptor frame if it exists.
6095   Label check_frame_marker;
6096   __ cmp(Operand(temp, StandardFrameConstants::kContextOffset),
6097          Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
6098   __ j(not_equal, &check_frame_marker, Label::kNear);
6099   __ mov(temp, Operand(temp, StandardFrameConstants::kCallerFPOffset));
6100
6101   // Check the marker in the calling frame.
6102   __ bind(&check_frame_marker);
6103   __ cmp(Operand(temp, StandardFrameConstants::kMarkerOffset),
6104          Immediate(Smi::FromInt(StackFrame::CONSTRUCT)));
6105 }
6106
6107
6108 void LCodeGen::EnsureSpaceForLazyDeopt(int space_needed) {
6109   if (!info()->IsStub()) {
6110     // Ensure that we have enough space after the previous lazy-bailout
6111     // instruction for patching the code here.
6112     int current_pc = masm()->pc_offset();
6113     if (current_pc < last_lazy_deopt_pc_ + space_needed) {
6114       int padding_size = last_lazy_deopt_pc_ + space_needed - current_pc;
6115       __ Nop(padding_size);
6116     }
6117   }
6118   last_lazy_deopt_pc_ = masm()->pc_offset();
6119 }
6120
6121
6122 void LCodeGen::DoLazyBailout(LLazyBailout* instr) {
6123   last_lazy_deopt_pc_ = masm()->pc_offset();
6124   DCHECK(instr->HasEnvironment());
6125   LEnvironment* env = instr->environment();
6126   RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt);
6127   safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
6128 }
6129
6130
6131 void LCodeGen::DoDeoptimize(LDeoptimize* instr) {
6132   Deoptimizer::BailoutType type = instr->hydrogen()->type();
6133   // TODO(danno): Stubs expect all deopts to be lazy for historical reasons (the
6134   // needed return address), even though the implementation of LAZY and EAGER is
6135   // now identical. When LAZY is eventually completely folded into EAGER, remove
6136   // the special case below.
6137   if (info()->IsStub() && type == Deoptimizer::EAGER) {
6138     type = Deoptimizer::LAZY;
6139   }
6140   DeoptimizeIf(no_condition, instr, instr->hydrogen()->reason(), type);
6141 }
6142
6143
6144 void LCodeGen::DoDummy(LDummy* instr) {
6145   // Nothing to see here, move on!
6146 }
6147
6148
6149 void LCodeGen::DoDummyUse(LDummyUse* instr) {
6150   // Nothing to see here, move on!
6151 }
6152
6153
6154 void LCodeGen::DoDeferredStackCheck(LStackCheck* instr) {
6155   PushSafepointRegistersScope scope(this);
6156   __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
6157   __ CallRuntimeSaveDoubles(Runtime::kStackGuard);
6158   RecordSafepointWithLazyDeopt(
6159       instr, RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
6160   DCHECK(instr->HasEnvironment());
6161   LEnvironment* env = instr->environment();
6162   safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
6163 }
6164
6165
6166 void LCodeGen::DoStackCheck(LStackCheck* instr) {
6167   class DeferredStackCheck FINAL : public LDeferredCode {
6168    public:
6169     DeferredStackCheck(LCodeGen* codegen,
6170                        LStackCheck* instr,
6171                        const X87Stack& x87_stack)
6172         : LDeferredCode(codegen, x87_stack), instr_(instr) { }
6173     void Generate() OVERRIDE { codegen()->DoDeferredStackCheck(instr_); }
6174     LInstruction* instr() OVERRIDE { return instr_; }
6175
6176    private:
6177     LStackCheck* instr_;
6178   };
6179
6180   DCHECK(instr->HasEnvironment());
6181   LEnvironment* env = instr->environment();
6182   // There is no LLazyBailout instruction for stack-checks. We have to
6183   // prepare for lazy deoptimization explicitly here.
6184   if (instr->hydrogen()->is_function_entry()) {
6185     // Perform stack overflow check.
6186     Label done;
6187     ExternalReference stack_limit =
6188         ExternalReference::address_of_stack_limit(isolate());
6189     __ cmp(esp, Operand::StaticVariable(stack_limit));
6190     __ j(above_equal, &done, Label::kNear);
6191
6192     DCHECK(instr->context()->IsRegister());
6193     DCHECK(ToRegister(instr->context()).is(esi));
6194     CallCode(isolate()->builtins()->StackCheck(),
6195              RelocInfo::CODE_TARGET,
6196              instr);
6197     __ bind(&done);
6198   } else {
6199     DCHECK(instr->hydrogen()->is_backwards_branch());
6200     // Perform stack overflow check if this goto needs it before jumping.
6201     DeferredStackCheck* deferred_stack_check =
6202         new(zone()) DeferredStackCheck(this, instr, x87_stack_);
6203     ExternalReference stack_limit =
6204         ExternalReference::address_of_stack_limit(isolate());
6205     __ cmp(esp, Operand::StaticVariable(stack_limit));
6206     __ j(below, deferred_stack_check->entry());
6207     EnsureSpaceForLazyDeopt(Deoptimizer::patch_size());
6208     __ bind(instr->done_label());
6209     deferred_stack_check->SetExit(instr->done_label());
6210     RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt);
6211     // Don't record a deoptimization index for the safepoint here.
6212     // This will be done explicitly when emitting call and the safepoint in
6213     // the deferred code.
6214   }
6215 }
6216
6217
6218 void LCodeGen::DoOsrEntry(LOsrEntry* instr) {
6219   // This is a pseudo-instruction that ensures that the environment here is
6220   // properly registered for deoptimization and records the assembler's PC
6221   // offset.
6222   LEnvironment* environment = instr->environment();
6223
6224   // If the environment were already registered, we would have no way of
6225   // backpatching it with the spill slot operands.
6226   DCHECK(!environment->HasBeenRegistered());
6227   RegisterEnvironmentForDeoptimization(environment, Safepoint::kNoLazyDeopt);
6228
6229   GenerateOsrPrologue();
6230 }
6231
6232
6233 void LCodeGen::DoForInPrepareMap(LForInPrepareMap* instr) {
6234   DCHECK(ToRegister(instr->context()).is(esi));
6235   __ cmp(eax, isolate()->factory()->undefined_value());
6236   DeoptimizeIf(equal, instr, Deoptimizer::kUndefined);
6237
6238   __ cmp(eax, isolate()->factory()->null_value());
6239   DeoptimizeIf(equal, instr, Deoptimizer::kNull);
6240
6241   __ test(eax, Immediate(kSmiTagMask));
6242   DeoptimizeIf(zero, instr, Deoptimizer::kSmi);
6243
6244   STATIC_ASSERT(FIRST_JS_PROXY_TYPE == FIRST_SPEC_OBJECT_TYPE);
6245   __ CmpObjectType(eax, LAST_JS_PROXY_TYPE, ecx);
6246   DeoptimizeIf(below_equal, instr, Deoptimizer::kWrongInstanceType);
6247
6248   Label use_cache, call_runtime;
6249   __ CheckEnumCache(&call_runtime);
6250
6251   __ mov(eax, FieldOperand(eax, HeapObject::kMapOffset));
6252   __ jmp(&use_cache, Label::kNear);
6253
6254   // Get the set of properties to enumerate.
6255   __ bind(&call_runtime);
6256   __ push(eax);
6257   CallRuntime(Runtime::kGetPropertyNamesFast, 1, instr);
6258
6259   __ cmp(FieldOperand(eax, HeapObject::kMapOffset),
6260          isolate()->factory()->meta_map());
6261   DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongMap);
6262   __ bind(&use_cache);
6263 }
6264
6265
6266 void LCodeGen::DoForInCacheArray(LForInCacheArray* instr) {
6267   Register map = ToRegister(instr->map());
6268   Register result = ToRegister(instr->result());
6269   Label load_cache, done;
6270   __ EnumLength(result, map);
6271   __ cmp(result, Immediate(Smi::FromInt(0)));
6272   __ j(not_equal, &load_cache, Label::kNear);
6273   __ mov(result, isolate()->factory()->empty_fixed_array());
6274   __ jmp(&done, Label::kNear);
6275
6276   __ bind(&load_cache);
6277   __ LoadInstanceDescriptors(map, result);
6278   __ mov(result,
6279          FieldOperand(result, DescriptorArray::kEnumCacheOffset));
6280   __ mov(result,
6281          FieldOperand(result, FixedArray::SizeFor(instr->idx())));
6282   __ bind(&done);
6283   __ test(result, result);
6284   DeoptimizeIf(equal, instr, Deoptimizer::kNoCache);
6285 }
6286
6287
6288 void LCodeGen::DoCheckMapValue(LCheckMapValue* instr) {
6289   Register object = ToRegister(instr->value());
6290   __ cmp(ToRegister(instr->map()),
6291          FieldOperand(object, HeapObject::kMapOffset));
6292   DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongMap);
6293 }
6294
6295
6296 void LCodeGen::DoDeferredLoadMutableDouble(LLoadFieldByIndex* instr,
6297                                            Register object,
6298                                            Register index) {
6299   PushSafepointRegistersScope scope(this);
6300   __ push(object);
6301   __ push(index);
6302   __ xor_(esi, esi);
6303   __ CallRuntimeSaveDoubles(Runtime::kLoadMutableDouble);
6304   RecordSafepointWithRegisters(
6305       instr->pointer_map(), 2, Safepoint::kNoLazyDeopt);
6306   __ StoreToSafepointRegisterSlot(object, eax);
6307 }
6308
6309
6310 void LCodeGen::DoLoadFieldByIndex(LLoadFieldByIndex* instr) {
6311   class DeferredLoadMutableDouble FINAL : public LDeferredCode {
6312    public:
6313     DeferredLoadMutableDouble(LCodeGen* codegen,
6314                               LLoadFieldByIndex* instr,
6315                               Register object,
6316                               Register index,
6317                               const X87Stack& x87_stack)
6318         : LDeferredCode(codegen, x87_stack),
6319           instr_(instr),
6320           object_(object),
6321           index_(index) {
6322     }
6323     void Generate() OVERRIDE {
6324       codegen()->DoDeferredLoadMutableDouble(instr_, object_, index_);
6325     }
6326     LInstruction* instr() OVERRIDE { return instr_; }
6327
6328    private:
6329     LLoadFieldByIndex* instr_;
6330     Register object_;
6331     Register index_;
6332   };
6333
6334   Register object = ToRegister(instr->object());
6335   Register index = ToRegister(instr->index());
6336
6337   DeferredLoadMutableDouble* deferred;
6338   deferred = new(zone()) DeferredLoadMutableDouble(
6339       this, instr, object, index, x87_stack_);
6340
6341   Label out_of_object, done;
6342   __ test(index, Immediate(Smi::FromInt(1)));
6343   __ j(not_zero, deferred->entry());
6344
6345   __ sar(index, 1);
6346
6347   __ cmp(index, Immediate(0));
6348   __ j(less, &out_of_object, Label::kNear);
6349   __ mov(object, FieldOperand(object,
6350                               index,
6351                               times_half_pointer_size,
6352                               JSObject::kHeaderSize));
6353   __ jmp(&done, Label::kNear);
6354
6355   __ bind(&out_of_object);
6356   __ mov(object, FieldOperand(object, JSObject::kPropertiesOffset));
6357   __ neg(index);
6358   // Index is now equal to out of object property index plus 1.
6359   __ mov(object, FieldOperand(object,
6360                               index,
6361                               times_half_pointer_size,
6362                               FixedArray::kHeaderSize - kPointerSize));
6363   __ bind(deferred->exit());
6364   __ bind(&done);
6365 }
6366
6367
6368 void LCodeGen::DoStoreFrameContext(LStoreFrameContext* instr) {
6369   Register context = ToRegister(instr->context());
6370   __ mov(Operand(ebp, StandardFrameConstants::kContextOffset), context);
6371 }
6372
6373
6374 void LCodeGen::DoAllocateBlockContext(LAllocateBlockContext* instr) {
6375   Handle<ScopeInfo> scope_info = instr->scope_info();
6376   __ Push(scope_info);
6377   __ push(ToRegister(instr->function()));
6378   CallRuntime(Runtime::kPushBlockContext, 2, instr);
6379   RecordSafepoint(Safepoint::kNoLazyDeopt);
6380 }
6381
6382
6383 #undef __
6384
6385 } }  // namespace v8::internal
6386
6387 #endif  // V8_TARGET_ARCH_X87