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