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