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