[strong] Refactor ObjectStrength into a replacement for strong boolean args
[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 =
2068       CodeFactory::BinaryOpIC(isolate(), instr->op(), instr->strength()).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 =
2495       CodeFactory::CompareIC(isolate(), op, Strength::WEAK).code();
2496   CallCode(ic, RelocInfo::CODE_TARGET, instr);
2497
2498   Condition condition = ComputeCompareCondition(op);
2499   __ test(eax, Operand(eax));
2500
2501   EmitBranch(instr, condition);
2502 }
2503
2504
2505 static InstanceType TestType(HHasInstanceTypeAndBranch* instr) {
2506   InstanceType from = instr->from();
2507   InstanceType to = instr->to();
2508   if (from == FIRST_TYPE) return to;
2509   DCHECK(from == to || to == LAST_TYPE);
2510   return from;
2511 }
2512
2513
2514 static Condition BranchCondition(HHasInstanceTypeAndBranch* instr) {
2515   InstanceType from = instr->from();
2516   InstanceType to = instr->to();
2517   if (from == to) return equal;
2518   if (to == LAST_TYPE) return above_equal;
2519   if (from == FIRST_TYPE) return below_equal;
2520   UNREACHABLE();
2521   return equal;
2522 }
2523
2524
2525 void LCodeGen::DoHasInstanceTypeAndBranch(LHasInstanceTypeAndBranch* instr) {
2526   Register input = ToRegister(instr->value());
2527   Register temp = ToRegister(instr->temp());
2528
2529   if (!instr->hydrogen()->value()->type().IsHeapObject()) {
2530     __ JumpIfSmi(input, instr->FalseLabel(chunk_));
2531   }
2532
2533   __ CmpObjectType(input, TestType(instr->hydrogen()), temp);
2534   EmitBranch(instr, BranchCondition(instr->hydrogen()));
2535 }
2536
2537
2538 void LCodeGen::DoGetCachedArrayIndex(LGetCachedArrayIndex* instr) {
2539   Register input = ToRegister(instr->value());
2540   Register result = ToRegister(instr->result());
2541
2542   __ AssertString(input);
2543
2544   __ mov(result, FieldOperand(input, String::kHashFieldOffset));
2545   __ IndexFromHash(result, result);
2546 }
2547
2548
2549 void LCodeGen::DoHasCachedArrayIndexAndBranch(
2550     LHasCachedArrayIndexAndBranch* instr) {
2551   Register input = ToRegister(instr->value());
2552
2553   __ test(FieldOperand(input, String::kHashFieldOffset),
2554           Immediate(String::kContainsCachedArrayIndexMask));
2555   EmitBranch(instr, equal);
2556 }
2557
2558
2559 // Branches to a label or falls through with the answer in the z flag.  Trashes
2560 // the temp registers, but not the input.
2561 void LCodeGen::EmitClassOfTest(Label* is_true,
2562                                Label* is_false,
2563                                Handle<String>class_name,
2564                                Register input,
2565                                Register temp,
2566                                Register temp2) {
2567   DCHECK(!input.is(temp));
2568   DCHECK(!input.is(temp2));
2569   DCHECK(!temp.is(temp2));
2570   __ JumpIfSmi(input, is_false);
2571
2572   if (String::Equals(isolate()->factory()->Function_string(), class_name)) {
2573     // Assuming the following assertions, we can use the same compares to test
2574     // for both being a function type and being in the object type range.
2575     STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
2576     STATIC_ASSERT(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE ==
2577                   FIRST_SPEC_OBJECT_TYPE + 1);
2578     STATIC_ASSERT(LAST_NONCALLABLE_SPEC_OBJECT_TYPE ==
2579                   LAST_SPEC_OBJECT_TYPE - 1);
2580     STATIC_ASSERT(LAST_SPEC_OBJECT_TYPE == LAST_TYPE);
2581     __ CmpObjectType(input, FIRST_SPEC_OBJECT_TYPE, temp);
2582     __ j(below, is_false);
2583     __ j(equal, is_true);
2584     __ CmpInstanceType(temp, LAST_SPEC_OBJECT_TYPE);
2585     __ j(equal, is_true);
2586   } else {
2587     // Faster code path to avoid two compares: subtract lower bound from the
2588     // actual type and do a signed compare with the width of the type range.
2589     __ mov(temp, FieldOperand(input, HeapObject::kMapOffset));
2590     __ movzx_b(temp2, FieldOperand(temp, Map::kInstanceTypeOffset));
2591     __ sub(Operand(temp2), Immediate(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE));
2592     __ cmp(Operand(temp2), Immediate(LAST_NONCALLABLE_SPEC_OBJECT_TYPE -
2593                                      FIRST_NONCALLABLE_SPEC_OBJECT_TYPE));
2594     __ j(above, is_false);
2595   }
2596
2597   // Now we are in the FIRST-LAST_NONCALLABLE_SPEC_OBJECT_TYPE range.
2598   // Check if the constructor in the map is a function.
2599   __ GetMapConstructor(temp, temp, temp2);
2600   // Objects with a non-function constructor have class 'Object'.
2601   __ CmpInstanceType(temp2, JS_FUNCTION_TYPE);
2602   if (String::Equals(class_name, isolate()->factory()->Object_string())) {
2603     __ j(not_equal, is_true);
2604   } else {
2605     __ j(not_equal, is_false);
2606   }
2607
2608   // temp now contains the constructor function. Grab the
2609   // instance class name from there.
2610   __ mov(temp, FieldOperand(temp, JSFunction::kSharedFunctionInfoOffset));
2611   __ mov(temp, FieldOperand(temp,
2612                             SharedFunctionInfo::kInstanceClassNameOffset));
2613   // The class name we are testing against is internalized since it's a literal.
2614   // The name in the constructor is internalized because of the way the context
2615   // is booted.  This routine isn't expected to work for random API-created
2616   // classes and it doesn't have to because you can't access it with natives
2617   // syntax.  Since both sides are internalized it is sufficient to use an
2618   // identity comparison.
2619   __ cmp(temp, class_name);
2620   // End with the answer in the z flag.
2621 }
2622
2623
2624 void LCodeGen::DoClassOfTestAndBranch(LClassOfTestAndBranch* instr) {
2625   Register input = ToRegister(instr->value());
2626   Register temp = ToRegister(instr->temp());
2627   Register temp2 = ToRegister(instr->temp2());
2628
2629   Handle<String> class_name = instr->hydrogen()->class_name();
2630
2631   EmitClassOfTest(instr->TrueLabel(chunk_), instr->FalseLabel(chunk_),
2632       class_name, input, temp, temp2);
2633
2634   EmitBranch(instr, equal);
2635 }
2636
2637
2638 void LCodeGen::DoCmpMapAndBranch(LCmpMapAndBranch* instr) {
2639   Register reg = ToRegister(instr->value());
2640   __ cmp(FieldOperand(reg, HeapObject::kMapOffset), instr->map());
2641   EmitBranch(instr, equal);
2642 }
2643
2644
2645 void LCodeGen::DoInstanceOf(LInstanceOf* instr) {
2646   // Object and function are in fixed registers defined by the stub.
2647   DCHECK(ToRegister(instr->context()).is(esi));
2648   InstanceofStub stub(isolate(), InstanceofStub::kArgsInRegisters);
2649   CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
2650
2651   Label true_value, done;
2652   __ test(eax, Operand(eax));
2653   __ j(zero, &true_value, Label::kNear);
2654   __ mov(ToRegister(instr->result()), factory()->false_value());
2655   __ jmp(&done, Label::kNear);
2656   __ bind(&true_value);
2657   __ mov(ToRegister(instr->result()), factory()->true_value());
2658   __ bind(&done);
2659 }
2660
2661
2662 void LCodeGen::DoInstanceOfKnownGlobal(LInstanceOfKnownGlobal* instr) {
2663   class DeferredInstanceOfKnownGlobal final : public LDeferredCode {
2664    public:
2665     DeferredInstanceOfKnownGlobal(LCodeGen* codegen,
2666                                   LInstanceOfKnownGlobal* instr)
2667         : LDeferredCode(codegen), instr_(instr) { }
2668     void Generate() override {
2669       codegen()->DoDeferredInstanceOfKnownGlobal(instr_, &map_check_);
2670     }
2671     LInstruction* instr() override { return instr_; }
2672     Label* map_check() { return &map_check_; }
2673    private:
2674     LInstanceOfKnownGlobal* instr_;
2675     Label map_check_;
2676   };
2677
2678   DeferredInstanceOfKnownGlobal* deferred;
2679   deferred = new(zone()) DeferredInstanceOfKnownGlobal(this, instr);
2680
2681   Label done, false_result;
2682   Register object = ToRegister(instr->value());
2683   Register temp = ToRegister(instr->temp());
2684
2685   // A Smi is not an instance of anything.
2686   __ JumpIfSmi(object, &false_result, Label::kNear);
2687
2688   // This is the inlined call site instanceof cache. The two occurences of the
2689   // hole value will be patched to the last map/result pair generated by the
2690   // instanceof stub.
2691   Label cache_miss;
2692   Register map = ToRegister(instr->temp());
2693   __ mov(map, FieldOperand(object, HeapObject::kMapOffset));
2694   __ bind(deferred->map_check());  // Label for calculating code patching.
2695   Handle<Cell> cache_cell = factory()->NewCell(factory()->the_hole_value());
2696   __ cmp(map, Operand::ForCell(cache_cell));  // Patched to cached map.
2697   __ j(not_equal, &cache_miss, Label::kNear);
2698   __ mov(eax, factory()->the_hole_value());  // Patched to either true or false.
2699   __ jmp(&done, Label::kNear);
2700
2701   // The inlined call site cache did not match. Check for null and string
2702   // before calling the deferred code.
2703   __ bind(&cache_miss);
2704   // Null is not an instance of anything.
2705   __ cmp(object, factory()->null_value());
2706   __ j(equal, &false_result, Label::kNear);
2707
2708   // String values are not instances of anything.
2709   Condition is_string = masm_->IsObjectStringType(object, temp, temp);
2710   __ j(is_string, &false_result, Label::kNear);
2711
2712   // Go to the deferred code.
2713   __ jmp(deferred->entry());
2714
2715   __ bind(&false_result);
2716   __ mov(ToRegister(instr->result()), factory()->false_value());
2717
2718   // Here result has either true or false. Deferred code also produces true or
2719   // false object.
2720   __ bind(deferred->exit());
2721   __ bind(&done);
2722 }
2723
2724
2725 void LCodeGen::DoDeferredInstanceOfKnownGlobal(LInstanceOfKnownGlobal* instr,
2726                                                Label* map_check) {
2727   PushSafepointRegistersScope scope(this);
2728
2729   InstanceofStub::Flags flags = InstanceofStub::kNoFlags;
2730   flags = static_cast<InstanceofStub::Flags>(
2731       flags | InstanceofStub::kArgsInRegisters);
2732   flags = static_cast<InstanceofStub::Flags>(
2733       flags | InstanceofStub::kCallSiteInlineCheck);
2734   flags = static_cast<InstanceofStub::Flags>(
2735       flags | InstanceofStub::kReturnTrueFalseObject);
2736   InstanceofStub stub(isolate(), flags);
2737
2738   // Get the temp register reserved by the instruction. This needs to be a
2739   // register which is pushed last by PushSafepointRegisters as top of the
2740   // stack is used to pass the offset to the location of the map check to
2741   // the stub.
2742   Register temp = ToRegister(instr->temp());
2743   DCHECK(MacroAssembler::SafepointRegisterStackIndex(temp) == 0);
2744   __ LoadHeapObject(InstanceofStub::right(), instr->function());
2745   static const int kAdditionalDelta = 13;
2746   int delta = masm_->SizeOfCodeGeneratedSince(map_check) + kAdditionalDelta;
2747   __ mov(temp, Immediate(delta));
2748   __ StoreToSafepointRegisterSlot(temp, temp);
2749   CallCodeGeneric(stub.GetCode(),
2750                   RelocInfo::CODE_TARGET,
2751                   instr,
2752                   RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
2753   // Get the deoptimization index of the LLazyBailout-environment that
2754   // corresponds to this instruction.
2755   LEnvironment* env = instr->GetDeferredLazyDeoptimizationEnvironment();
2756   safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
2757
2758   // Put the result value into the eax slot and restore all registers.
2759   __ StoreToSafepointRegisterSlot(eax, eax);
2760 }
2761
2762
2763 void LCodeGen::DoCmpT(LCmpT* instr) {
2764   Token::Value op = instr->op();
2765
2766   Handle<Code> ic =
2767       CodeFactory::CompareIC(isolate(), op, instr->strength()).code();
2768   CallCode(ic, RelocInfo::CODE_TARGET, instr);
2769
2770   Condition condition = ComputeCompareCondition(op);
2771   Label true_value, done;
2772   __ test(eax, Operand(eax));
2773   __ j(condition, &true_value, Label::kNear);
2774   __ mov(ToRegister(instr->result()), factory()->false_value());
2775   __ jmp(&done, Label::kNear);
2776   __ bind(&true_value);
2777   __ mov(ToRegister(instr->result()), factory()->true_value());
2778   __ bind(&done);
2779 }
2780
2781
2782 void LCodeGen::EmitReturn(LReturn* instr, bool dynamic_frame_alignment) {
2783   int extra_value_count = dynamic_frame_alignment ? 2 : 1;
2784
2785   if (instr->has_constant_parameter_count()) {
2786     int parameter_count = ToInteger32(instr->constant_parameter_count());
2787     if (dynamic_frame_alignment && FLAG_debug_code) {
2788       __ cmp(Operand(esp,
2789                      (parameter_count + extra_value_count) * kPointerSize),
2790              Immediate(kAlignmentZapValue));
2791       __ Assert(equal, kExpectedAlignmentMarker);
2792     }
2793     __ Ret((parameter_count + extra_value_count) * kPointerSize, ecx);
2794   } else {
2795     DCHECK(info()->IsStub());  // Functions would need to drop one more value.
2796     Register reg = ToRegister(instr->parameter_count());
2797     // The argument count parameter is a smi
2798     __ SmiUntag(reg);
2799     Register return_addr_reg = reg.is(ecx) ? ebx : ecx;
2800     if (dynamic_frame_alignment && FLAG_debug_code) {
2801       DCHECK(extra_value_count == 2);
2802       __ cmp(Operand(esp, reg, times_pointer_size,
2803                      extra_value_count * kPointerSize),
2804              Immediate(kAlignmentZapValue));
2805       __ Assert(equal, kExpectedAlignmentMarker);
2806     }
2807
2808     // emit code to restore stack based on instr->parameter_count()
2809     __ pop(return_addr_reg);  // save return address
2810     if (dynamic_frame_alignment) {
2811       __ inc(reg);  // 1 more for alignment
2812     }
2813
2814     __ shl(reg, kPointerSizeLog2);
2815     __ add(esp, reg);
2816     __ jmp(return_addr_reg);
2817   }
2818 }
2819
2820
2821 void LCodeGen::DoReturn(LReturn* instr) {
2822   if (FLAG_trace && info()->IsOptimizing()) {
2823     // Preserve the return value on the stack and rely on the runtime call
2824     // to return the value in the same register.  We're leaving the code
2825     // managed by the register allocator and tearing down the frame, it's
2826     // safe to write to the context register.
2827     __ push(eax);
2828     __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
2829     __ CallRuntime(Runtime::kTraceExit, 1);
2830   }
2831   if (info()->saves_caller_doubles()) RestoreCallerDoubles();
2832   if (dynamic_frame_alignment_) {
2833     // Fetch the state of the dynamic frame alignment.
2834     __ mov(edx, Operand(ebp,
2835       JavaScriptFrameConstants::kDynamicAlignmentStateOffset));
2836   }
2837   int no_frame_start = -1;
2838   if (NeedsEagerFrame()) {
2839     __ mov(esp, ebp);
2840     __ pop(ebp);
2841     no_frame_start = masm_->pc_offset();
2842   }
2843   if (dynamic_frame_alignment_) {
2844     Label no_padding;
2845     __ cmp(edx, Immediate(kNoAlignmentPadding));
2846     __ j(equal, &no_padding, Label::kNear);
2847
2848     EmitReturn(instr, true);
2849     __ bind(&no_padding);
2850   }
2851
2852   EmitReturn(instr, false);
2853   if (no_frame_start != -1) {
2854     info()->AddNoFrameRange(no_frame_start, masm_->pc_offset());
2855   }
2856 }
2857
2858
2859 template <class T>
2860 void LCodeGen::EmitVectorLoadICRegisters(T* instr) {
2861   Register vector_register = ToRegister(instr->temp_vector());
2862   Register slot_register = LoadWithVectorDescriptor::SlotRegister();
2863   DCHECK(vector_register.is(LoadWithVectorDescriptor::VectorRegister()));
2864   DCHECK(slot_register.is(eax));
2865
2866   AllowDeferredHandleDereference vector_structure_check;
2867   Handle<TypeFeedbackVector> vector = instr->hydrogen()->feedback_vector();
2868   __ mov(vector_register, vector);
2869   // No need to allocate this register.
2870   FeedbackVectorICSlot slot = instr->hydrogen()->slot();
2871   int index = vector->GetIndex(slot);
2872   __ mov(slot_register, Immediate(Smi::FromInt(index)));
2873 }
2874
2875
2876 void LCodeGen::DoLoadGlobalGeneric(LLoadGlobalGeneric* instr) {
2877   DCHECK(ToRegister(instr->context()).is(esi));
2878   DCHECK(ToRegister(instr->global_object())
2879              .is(LoadDescriptor::ReceiverRegister()));
2880   DCHECK(ToRegister(instr->result()).is(eax));
2881
2882   __ mov(LoadDescriptor::NameRegister(), instr->name());
2883   EmitVectorLoadICRegisters<LLoadGlobalGeneric>(instr);
2884   ContextualMode mode = instr->for_typeof() ? NOT_CONTEXTUAL : CONTEXTUAL;
2885   Handle<Code> ic = CodeFactory::LoadICInOptimizedCode(isolate(), mode,
2886                                                        PREMONOMORPHIC).code();
2887   CallCode(ic, RelocInfo::CODE_TARGET, instr);
2888 }
2889
2890
2891 void LCodeGen::DoLoadContextSlot(LLoadContextSlot* instr) {
2892   Register context = ToRegister(instr->context());
2893   Register result = ToRegister(instr->result());
2894   __ mov(result, ContextOperand(context, instr->slot_index()));
2895
2896   if (instr->hydrogen()->RequiresHoleCheck()) {
2897     __ cmp(result, factory()->the_hole_value());
2898     if (instr->hydrogen()->DeoptimizesOnHole()) {
2899       DeoptimizeIf(equal, instr, Deoptimizer::kHole);
2900     } else {
2901       Label is_not_hole;
2902       __ j(not_equal, &is_not_hole, Label::kNear);
2903       __ mov(result, factory()->undefined_value());
2904       __ bind(&is_not_hole);
2905     }
2906   }
2907 }
2908
2909
2910 void LCodeGen::DoStoreContextSlot(LStoreContextSlot* instr) {
2911   Register context = ToRegister(instr->context());
2912   Register value = ToRegister(instr->value());
2913
2914   Label skip_assignment;
2915
2916   Operand target = ContextOperand(context, instr->slot_index());
2917   if (instr->hydrogen()->RequiresHoleCheck()) {
2918     __ cmp(target, factory()->the_hole_value());
2919     if (instr->hydrogen()->DeoptimizesOnHole()) {
2920       DeoptimizeIf(equal, instr, Deoptimizer::kHole);
2921     } else {
2922       __ j(not_equal, &skip_assignment, Label::kNear);
2923     }
2924   }
2925
2926   __ mov(target, value);
2927   if (instr->hydrogen()->NeedsWriteBarrier()) {
2928     SmiCheck check_needed =
2929         instr->hydrogen()->value()->type().IsHeapObject()
2930             ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
2931     Register temp = ToRegister(instr->temp());
2932     int offset = Context::SlotOffset(instr->slot_index());
2933     __ RecordWriteContextSlot(context,
2934                               offset,
2935                               value,
2936                               temp,
2937                               kSaveFPRegs,
2938                               EMIT_REMEMBERED_SET,
2939                               check_needed);
2940   }
2941
2942   __ bind(&skip_assignment);
2943 }
2944
2945
2946 void LCodeGen::DoLoadNamedField(LLoadNamedField* instr) {
2947   HObjectAccess access = instr->hydrogen()->access();
2948   int offset = access.offset();
2949
2950   if (access.IsExternalMemory()) {
2951     Register result = ToRegister(instr->result());
2952     MemOperand operand = instr->object()->IsConstantOperand()
2953         ? MemOperand::StaticVariable(ToExternalReference(
2954                 LConstantOperand::cast(instr->object())))
2955         : MemOperand(ToRegister(instr->object()), offset);
2956     __ Load(result, operand, access.representation());
2957     return;
2958   }
2959
2960   Register object = ToRegister(instr->object());
2961   if (instr->hydrogen()->representation().IsDouble()) {
2962     XMMRegister result = ToDoubleRegister(instr->result());
2963     __ movsd(result, FieldOperand(object, offset));
2964     return;
2965   }
2966
2967   Register result = ToRegister(instr->result());
2968   if (!access.IsInobject()) {
2969     __ mov(result, FieldOperand(object, JSObject::kPropertiesOffset));
2970     object = result;
2971   }
2972   __ Load(result, FieldOperand(object, offset), access.representation());
2973 }
2974
2975
2976 void LCodeGen::EmitPushTaggedOperand(LOperand* operand) {
2977   DCHECK(!operand->IsDoubleRegister());
2978   if (operand->IsConstantOperand()) {
2979     Handle<Object> object = ToHandle(LConstantOperand::cast(operand));
2980     AllowDeferredHandleDereference smi_check;
2981     if (object->IsSmi()) {
2982       __ Push(Handle<Smi>::cast(object));
2983     } else {
2984       __ PushHeapObject(Handle<HeapObject>::cast(object));
2985     }
2986   } else if (operand->IsRegister()) {
2987     __ push(ToRegister(operand));
2988   } else {
2989     __ push(ToOperand(operand));
2990   }
2991 }
2992
2993
2994 void LCodeGen::DoLoadNamedGeneric(LLoadNamedGeneric* instr) {
2995   DCHECK(ToRegister(instr->context()).is(esi));
2996   DCHECK(ToRegister(instr->object()).is(LoadDescriptor::ReceiverRegister()));
2997   DCHECK(ToRegister(instr->result()).is(eax));
2998
2999   __ mov(LoadDescriptor::NameRegister(), instr->name());
3000   EmitVectorLoadICRegisters<LLoadNamedGeneric>(instr);
3001   Handle<Code> ic = CodeFactory::LoadICInOptimizedCode(
3002                         isolate(), NOT_CONTEXTUAL,
3003                         instr->hydrogen()->initialization_state()).code();
3004   CallCode(ic, RelocInfo::CODE_TARGET, instr);
3005 }
3006
3007
3008 void LCodeGen::DoLoadFunctionPrototype(LLoadFunctionPrototype* instr) {
3009   Register function = ToRegister(instr->function());
3010   Register temp = ToRegister(instr->temp());
3011   Register result = ToRegister(instr->result());
3012
3013   // Get the prototype or initial map from the function.
3014   __ mov(result,
3015          FieldOperand(function, JSFunction::kPrototypeOrInitialMapOffset));
3016
3017   // Check that the function has a prototype or an initial map.
3018   __ cmp(Operand(result), Immediate(factory()->the_hole_value()));
3019   DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3020
3021   // If the function does not have an initial map, we're done.
3022   Label done;
3023   __ CmpObjectType(result, MAP_TYPE, temp);
3024   __ j(not_equal, &done, Label::kNear);
3025
3026   // Get the prototype from the initial map.
3027   __ mov(result, FieldOperand(result, Map::kPrototypeOffset));
3028
3029   // All done.
3030   __ bind(&done);
3031 }
3032
3033
3034 void LCodeGen::DoLoadRoot(LLoadRoot* instr) {
3035   Register result = ToRegister(instr->result());
3036   __ LoadRoot(result, instr->index());
3037 }
3038
3039
3040 void LCodeGen::DoAccessArgumentsAt(LAccessArgumentsAt* instr) {
3041   Register arguments = ToRegister(instr->arguments());
3042   Register result = ToRegister(instr->result());
3043   if (instr->length()->IsConstantOperand() &&
3044       instr->index()->IsConstantOperand()) {
3045     int const_index = ToInteger32(LConstantOperand::cast(instr->index()));
3046     int const_length = ToInteger32(LConstantOperand::cast(instr->length()));
3047     int index = (const_length - const_index) + 1;
3048     __ mov(result, Operand(arguments, index * kPointerSize));
3049   } else {
3050     Register length = ToRegister(instr->length());
3051     Operand index = ToOperand(instr->index());
3052     // There are two words between the frame pointer and the last argument.
3053     // Subtracting from length accounts for one of them add one more.
3054     __ sub(length, index);
3055     __ mov(result, Operand(arguments, length, times_4, kPointerSize));
3056   }
3057 }
3058
3059
3060 void LCodeGen::DoLoadKeyedExternalArray(LLoadKeyed* instr) {
3061   ElementsKind elements_kind = instr->elements_kind();
3062   LOperand* key = instr->key();
3063   if (!key->IsConstantOperand() &&
3064       ExternalArrayOpRequiresTemp(instr->hydrogen()->key()->representation(),
3065                                   elements_kind)) {
3066     __ SmiUntag(ToRegister(key));
3067   }
3068   Operand operand(BuildFastArrayOperand(
3069       instr->elements(),
3070       key,
3071       instr->hydrogen()->key()->representation(),
3072       elements_kind,
3073       instr->base_offset()));
3074   if (elements_kind == EXTERNAL_FLOAT32_ELEMENTS ||
3075       elements_kind == FLOAT32_ELEMENTS) {
3076     XMMRegister result(ToDoubleRegister(instr->result()));
3077     __ movss(result, operand);
3078     __ cvtss2sd(result, result);
3079   } else if (elements_kind == EXTERNAL_FLOAT64_ELEMENTS ||
3080              elements_kind == FLOAT64_ELEMENTS) {
3081     __ movsd(ToDoubleRegister(instr->result()), operand);
3082   } else {
3083     Register result(ToRegister(instr->result()));
3084     switch (elements_kind) {
3085       case EXTERNAL_INT8_ELEMENTS:
3086       case INT8_ELEMENTS:
3087         __ movsx_b(result, operand);
3088         break;
3089       case EXTERNAL_UINT8_CLAMPED_ELEMENTS:
3090       case EXTERNAL_UINT8_ELEMENTS:
3091       case UINT8_ELEMENTS:
3092       case UINT8_CLAMPED_ELEMENTS:
3093         __ movzx_b(result, operand);
3094         break;
3095       case EXTERNAL_INT16_ELEMENTS:
3096       case INT16_ELEMENTS:
3097         __ movsx_w(result, operand);
3098         break;
3099       case EXTERNAL_UINT16_ELEMENTS:
3100       case UINT16_ELEMENTS:
3101         __ movzx_w(result, operand);
3102         break;
3103       case EXTERNAL_INT32_ELEMENTS:
3104       case INT32_ELEMENTS:
3105         __ mov(result, operand);
3106         break;
3107       case EXTERNAL_UINT32_ELEMENTS:
3108       case UINT32_ELEMENTS:
3109         __ mov(result, operand);
3110         if (!instr->hydrogen()->CheckFlag(HInstruction::kUint32)) {
3111           __ test(result, Operand(result));
3112           DeoptimizeIf(negative, instr, Deoptimizer::kNegativeValue);
3113         }
3114         break;
3115       case EXTERNAL_FLOAT32_ELEMENTS:
3116       case EXTERNAL_FLOAT64_ELEMENTS:
3117       case FLOAT32_ELEMENTS:
3118       case FLOAT64_ELEMENTS:
3119       case FAST_SMI_ELEMENTS:
3120       case FAST_ELEMENTS:
3121       case FAST_DOUBLE_ELEMENTS:
3122       case FAST_HOLEY_SMI_ELEMENTS:
3123       case FAST_HOLEY_ELEMENTS:
3124       case FAST_HOLEY_DOUBLE_ELEMENTS:
3125       case DICTIONARY_ELEMENTS:
3126       case SLOPPY_ARGUMENTS_ELEMENTS:
3127         UNREACHABLE();
3128         break;
3129     }
3130   }
3131 }
3132
3133
3134 void LCodeGen::DoLoadKeyedFixedDoubleArray(LLoadKeyed* instr) {
3135   if (instr->hydrogen()->RequiresHoleCheck()) {
3136     Operand hole_check_operand = BuildFastArrayOperand(
3137         instr->elements(), instr->key(),
3138         instr->hydrogen()->key()->representation(),
3139         FAST_DOUBLE_ELEMENTS,
3140         instr->base_offset() + sizeof(kHoleNanLower32));
3141     __ cmp(hole_check_operand, Immediate(kHoleNanUpper32));
3142     DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3143   }
3144
3145   Operand double_load_operand = BuildFastArrayOperand(
3146       instr->elements(),
3147       instr->key(),
3148       instr->hydrogen()->key()->representation(),
3149       FAST_DOUBLE_ELEMENTS,
3150       instr->base_offset());
3151   XMMRegister result = ToDoubleRegister(instr->result());
3152   __ movsd(result, double_load_operand);
3153 }
3154
3155
3156 void LCodeGen::DoLoadKeyedFixedArray(LLoadKeyed* instr) {
3157   Register result = ToRegister(instr->result());
3158
3159   // Load the result.
3160   __ mov(result,
3161          BuildFastArrayOperand(instr->elements(), instr->key(),
3162                                instr->hydrogen()->key()->representation(),
3163                                FAST_ELEMENTS, instr->base_offset()));
3164
3165   // Check for the hole value.
3166   if (instr->hydrogen()->RequiresHoleCheck()) {
3167     if (IsFastSmiElementsKind(instr->hydrogen()->elements_kind())) {
3168       __ test(result, Immediate(kSmiTagMask));
3169       DeoptimizeIf(not_equal, instr, Deoptimizer::kNotASmi);
3170     } else {
3171       __ cmp(result, factory()->the_hole_value());
3172       DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3173     }
3174   } else if (instr->hydrogen()->hole_mode() == CONVERT_HOLE_TO_UNDEFINED) {
3175     DCHECK(instr->hydrogen()->elements_kind() == FAST_HOLEY_ELEMENTS);
3176     Label done;
3177     __ cmp(result, factory()->the_hole_value());
3178     __ j(not_equal, &done);
3179     if (info()->IsStub()) {
3180       // A stub can safely convert the hole to undefined only if the array
3181       // protector cell contains (Smi) Isolate::kArrayProtectorValid. Otherwise
3182       // it needs to bail out.
3183       __ mov(result, isolate()->factory()->array_protector());
3184       __ cmp(FieldOperand(result, PropertyCell::kValueOffset),
3185              Immediate(Smi::FromInt(Isolate::kArrayProtectorValid)));
3186       DeoptimizeIf(not_equal, instr, Deoptimizer::kHole);
3187     }
3188     __ mov(result, isolate()->factory()->undefined_value());
3189     __ bind(&done);
3190   }
3191 }
3192
3193
3194 void LCodeGen::DoLoadKeyed(LLoadKeyed* instr) {
3195   if (instr->is_typed_elements()) {
3196     DoLoadKeyedExternalArray(instr);
3197   } else if (instr->hydrogen()->representation().IsDouble()) {
3198     DoLoadKeyedFixedDoubleArray(instr);
3199   } else {
3200     DoLoadKeyedFixedArray(instr);
3201   }
3202 }
3203
3204
3205 Operand LCodeGen::BuildFastArrayOperand(
3206     LOperand* elements_pointer,
3207     LOperand* key,
3208     Representation key_representation,
3209     ElementsKind elements_kind,
3210     uint32_t base_offset) {
3211   Register elements_pointer_reg = ToRegister(elements_pointer);
3212   int element_shift_size = ElementsKindToShiftSize(elements_kind);
3213   int shift_size = element_shift_size;
3214   if (key->IsConstantOperand()) {
3215     int constant_value = ToInteger32(LConstantOperand::cast(key));
3216     if (constant_value & 0xF0000000) {
3217       Abort(kArrayIndexConstantValueTooBig);
3218     }
3219     return Operand(elements_pointer_reg,
3220                    ((constant_value) << shift_size)
3221                        + base_offset);
3222   } else {
3223     // Take the tag bit into account while computing the shift size.
3224     if (key_representation.IsSmi() && (shift_size >= 1)) {
3225       shift_size -= kSmiTagSize;
3226     }
3227     ScaleFactor scale_factor = static_cast<ScaleFactor>(shift_size);
3228     return Operand(elements_pointer_reg,
3229                    ToRegister(key),
3230                    scale_factor,
3231                    base_offset);
3232   }
3233 }
3234
3235
3236 void LCodeGen::DoLoadKeyedGeneric(LLoadKeyedGeneric* instr) {
3237   DCHECK(ToRegister(instr->context()).is(esi));
3238   DCHECK(ToRegister(instr->object()).is(LoadDescriptor::ReceiverRegister()));
3239   DCHECK(ToRegister(instr->key()).is(LoadDescriptor::NameRegister()));
3240
3241   if (instr->hydrogen()->HasVectorAndSlot()) {
3242     EmitVectorLoadICRegisters<LLoadKeyedGeneric>(instr);
3243   }
3244
3245   Handle<Code> ic =
3246       CodeFactory::KeyedLoadICInOptimizedCode(
3247           isolate(), instr->hydrogen()->initialization_state()).code();
3248   CallCode(ic, RelocInfo::CODE_TARGET, instr);
3249 }
3250
3251
3252 void LCodeGen::DoArgumentsElements(LArgumentsElements* instr) {
3253   Register result = ToRegister(instr->result());
3254
3255   if (instr->hydrogen()->from_inlined()) {
3256     __ lea(result, Operand(esp, -2 * kPointerSize));
3257   } else {
3258     // Check for arguments adapter frame.
3259     Label done, adapted;
3260     __ mov(result, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3261     __ mov(result, Operand(result, StandardFrameConstants::kContextOffset));
3262     __ cmp(Operand(result),
3263            Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
3264     __ j(equal, &adapted, Label::kNear);
3265
3266     // No arguments adaptor frame.
3267     __ mov(result, Operand(ebp));
3268     __ jmp(&done, Label::kNear);
3269
3270     // Arguments adaptor frame present.
3271     __ bind(&adapted);
3272     __ mov(result, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3273
3274     // Result is the frame pointer for the frame if not adapted and for the real
3275     // frame below the adaptor frame if adapted.
3276     __ bind(&done);
3277   }
3278 }
3279
3280
3281 void LCodeGen::DoArgumentsLength(LArgumentsLength* instr) {
3282   Operand elem = ToOperand(instr->elements());
3283   Register result = ToRegister(instr->result());
3284
3285   Label done;
3286
3287   // If no arguments adaptor frame the number of arguments is fixed.
3288   __ cmp(ebp, elem);
3289   __ mov(result, Immediate(scope()->num_parameters()));
3290   __ j(equal, &done, Label::kNear);
3291
3292   // Arguments adaptor frame present. Get argument length from there.
3293   __ mov(result, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3294   __ mov(result, Operand(result,
3295                          ArgumentsAdaptorFrameConstants::kLengthOffset));
3296   __ SmiUntag(result);
3297
3298   // Argument length is in result register.
3299   __ bind(&done);
3300 }
3301
3302
3303 void LCodeGen::DoWrapReceiver(LWrapReceiver* instr) {
3304   Register receiver = ToRegister(instr->receiver());
3305   Register function = ToRegister(instr->function());
3306
3307   // If the receiver is null or undefined, we have to pass the global
3308   // object as a receiver to normal functions. Values have to be
3309   // passed unchanged to builtins and strict-mode functions.
3310   Label receiver_ok, global_object;
3311   Label::Distance dist = DeoptEveryNTimes() ? Label::kFar : Label::kNear;
3312   Register scratch = ToRegister(instr->temp());
3313
3314   if (!instr->hydrogen()->known_function()) {
3315     // Do not transform the receiver to object for strict mode
3316     // functions.
3317     __ mov(scratch,
3318            FieldOperand(function, JSFunction::kSharedFunctionInfoOffset));
3319     __ test_b(FieldOperand(scratch, SharedFunctionInfo::kStrictModeByteOffset),
3320               1 << SharedFunctionInfo::kStrictModeBitWithinByte);
3321     __ j(not_equal, &receiver_ok, dist);
3322
3323     // Do not transform the receiver to object for builtins.
3324     __ test_b(FieldOperand(scratch, SharedFunctionInfo::kNativeByteOffset),
3325               1 << SharedFunctionInfo::kNativeBitWithinByte);
3326     __ j(not_equal, &receiver_ok, dist);
3327   }
3328
3329   // Normal function. Replace undefined or null with global receiver.
3330   __ cmp(receiver, factory()->null_value());
3331   __ j(equal, &global_object, Label::kNear);
3332   __ cmp(receiver, factory()->undefined_value());
3333   __ j(equal, &global_object, Label::kNear);
3334
3335   // The receiver should be a JS object.
3336   __ test(receiver, Immediate(kSmiTagMask));
3337   DeoptimizeIf(equal, instr, Deoptimizer::kSmi);
3338   __ CmpObjectType(receiver, FIRST_SPEC_OBJECT_TYPE, scratch);
3339   DeoptimizeIf(below, instr, Deoptimizer::kNotAJavaScriptObject);
3340
3341   __ jmp(&receiver_ok, Label::kNear);
3342   __ bind(&global_object);
3343   __ mov(receiver, FieldOperand(function, JSFunction::kContextOffset));
3344   const int global_offset = Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX);
3345   __ mov(receiver, Operand(receiver, global_offset));
3346   const int proxy_offset = GlobalObject::kGlobalProxyOffset;
3347   __ mov(receiver, FieldOperand(receiver, proxy_offset));
3348   __ bind(&receiver_ok);
3349 }
3350
3351
3352 void LCodeGen::DoApplyArguments(LApplyArguments* instr) {
3353   Register receiver = ToRegister(instr->receiver());
3354   Register function = ToRegister(instr->function());
3355   Register length = ToRegister(instr->length());
3356   Register elements = ToRegister(instr->elements());
3357   DCHECK(receiver.is(eax));  // Used for parameter count.
3358   DCHECK(function.is(edi));  // Required by InvokeFunction.
3359   DCHECK(ToRegister(instr->result()).is(eax));
3360
3361   // Copy the arguments to this function possibly from the
3362   // adaptor frame below it.
3363   const uint32_t kArgumentsLimit = 1 * KB;
3364   __ cmp(length, kArgumentsLimit);
3365   DeoptimizeIf(above, instr, Deoptimizer::kTooManyArguments);
3366
3367   __ push(receiver);
3368   __ mov(receiver, length);
3369
3370   // Loop through the arguments pushing them onto the execution
3371   // stack.
3372   Label invoke, loop;
3373   // length is a small non-negative integer, due to the test above.
3374   __ test(length, Operand(length));
3375   __ j(zero, &invoke, Label::kNear);
3376   __ bind(&loop);
3377   __ push(Operand(elements, length, times_pointer_size, 1 * kPointerSize));
3378   __ dec(length);
3379   __ j(not_zero, &loop);
3380
3381   // Invoke the function.
3382   __ bind(&invoke);
3383   DCHECK(instr->HasPointerMap());
3384   LPointerMap* pointers = instr->pointer_map();
3385   SafepointGenerator safepoint_generator(
3386       this, pointers, Safepoint::kLazyDeopt);
3387   ParameterCount actual(eax);
3388   __ InvokeFunction(function, actual, CALL_FUNCTION, safepoint_generator);
3389 }
3390
3391
3392 void LCodeGen::DoDebugBreak(LDebugBreak* instr) {
3393   __ int3();
3394 }
3395
3396
3397 void LCodeGen::DoPushArgument(LPushArgument* instr) {
3398   LOperand* argument = instr->value();
3399   EmitPushTaggedOperand(argument);
3400 }
3401
3402
3403 void LCodeGen::DoDrop(LDrop* instr) {
3404   __ Drop(instr->count());
3405 }
3406
3407
3408 void LCodeGen::DoThisFunction(LThisFunction* instr) {
3409   Register result = ToRegister(instr->result());
3410   __ mov(result, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
3411 }
3412
3413
3414 void LCodeGen::DoContext(LContext* instr) {
3415   Register result = ToRegister(instr->result());
3416   if (info()->IsOptimizing()) {
3417     __ mov(result, Operand(ebp, StandardFrameConstants::kContextOffset));
3418   } else {
3419     // If there is no frame, the context must be in esi.
3420     DCHECK(result.is(esi));
3421   }
3422 }
3423
3424
3425 void LCodeGen::DoDeclareGlobals(LDeclareGlobals* instr) {
3426   DCHECK(ToRegister(instr->context()).is(esi));
3427   __ push(esi);  // The context is the first argument.
3428   __ push(Immediate(instr->hydrogen()->pairs()));
3429   __ push(Immediate(Smi::FromInt(instr->hydrogen()->flags())));
3430   CallRuntime(Runtime::kDeclareGlobals, 3, instr);
3431 }
3432
3433
3434 void LCodeGen::CallKnownFunction(Handle<JSFunction> function,
3435                                  int formal_parameter_count, int arity,
3436                                  LInstruction* instr) {
3437   bool dont_adapt_arguments =
3438       formal_parameter_count == SharedFunctionInfo::kDontAdaptArgumentsSentinel;
3439   bool can_invoke_directly =
3440       dont_adapt_arguments || formal_parameter_count == arity;
3441
3442   Register function_reg = edi;
3443
3444   if (can_invoke_directly) {
3445     // Change context.
3446     __ mov(esi, FieldOperand(function_reg, JSFunction::kContextOffset));
3447
3448     // Set eax to arguments count if adaption is not needed. Assumes that eax
3449     // is available to write to at this point.
3450     if (dont_adapt_arguments) {
3451       __ mov(eax, arity);
3452     }
3453
3454     // Invoke function directly.
3455     if (function.is_identical_to(info()->closure())) {
3456       __ CallSelf();
3457     } else {
3458       __ call(FieldOperand(function_reg, JSFunction::kCodeEntryOffset));
3459     }
3460     RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
3461   } else {
3462     // We need to adapt arguments.
3463     LPointerMap* pointers = instr->pointer_map();
3464     SafepointGenerator generator(
3465         this, pointers, Safepoint::kLazyDeopt);
3466     ParameterCount count(arity);
3467     ParameterCount expected(formal_parameter_count);
3468     __ InvokeFunction(function_reg, expected, count, CALL_FUNCTION, generator);
3469   }
3470 }
3471
3472
3473 void LCodeGen::DoCallWithDescriptor(LCallWithDescriptor* instr) {
3474   DCHECK(ToRegister(instr->result()).is(eax));
3475
3476   if (instr->hydrogen()->IsTailCall()) {
3477     if (NeedsEagerFrame()) __ leave();
3478
3479     if (instr->target()->IsConstantOperand()) {
3480       LConstantOperand* target = LConstantOperand::cast(instr->target());
3481       Handle<Code> code = Handle<Code>::cast(ToHandle(target));
3482       __ jmp(code, RelocInfo::CODE_TARGET);
3483     } else {
3484       DCHECK(instr->target()->IsRegister());
3485       Register target = ToRegister(instr->target());
3486       __ add(target, Immediate(Code::kHeaderSize - kHeapObjectTag));
3487       __ jmp(target);
3488     }
3489   } else {
3490     LPointerMap* pointers = instr->pointer_map();
3491     SafepointGenerator generator(this, pointers, Safepoint::kLazyDeopt);
3492
3493     if (instr->target()->IsConstantOperand()) {
3494       LConstantOperand* target = LConstantOperand::cast(instr->target());
3495       Handle<Code> code = Handle<Code>::cast(ToHandle(target));
3496       generator.BeforeCall(__ CallSize(code, RelocInfo::CODE_TARGET));
3497       __ call(code, RelocInfo::CODE_TARGET);
3498     } else {
3499       DCHECK(instr->target()->IsRegister());
3500       Register target = ToRegister(instr->target());
3501       generator.BeforeCall(__ CallSize(Operand(target)));
3502       __ add(target, Immediate(Code::kHeaderSize - kHeapObjectTag));
3503       __ call(target);
3504     }
3505     generator.AfterCall();
3506   }
3507 }
3508
3509
3510 void LCodeGen::DoCallJSFunction(LCallJSFunction* instr) {
3511   DCHECK(ToRegister(instr->function()).is(edi));
3512   DCHECK(ToRegister(instr->result()).is(eax));
3513
3514   if (instr->hydrogen()->pass_argument_count()) {
3515     __ mov(eax, instr->arity());
3516   }
3517
3518   // Change context.
3519   __ mov(esi, FieldOperand(edi, JSFunction::kContextOffset));
3520
3521   bool is_self_call = false;
3522   if (instr->hydrogen()->function()->IsConstant()) {
3523     HConstant* fun_const = HConstant::cast(instr->hydrogen()->function());
3524     Handle<JSFunction> jsfun =
3525       Handle<JSFunction>::cast(fun_const->handle(isolate()));
3526     is_self_call = jsfun.is_identical_to(info()->closure());
3527   }
3528
3529   if (is_self_call) {
3530     __ CallSelf();
3531   } else {
3532     __ call(FieldOperand(edi, JSFunction::kCodeEntryOffset));
3533   }
3534
3535   RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
3536 }
3537
3538
3539 void LCodeGen::DoDeferredMathAbsTaggedHeapNumber(LMathAbs* instr) {
3540   Register input_reg = ToRegister(instr->value());
3541   __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
3542          factory()->heap_number_map());
3543   DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
3544
3545   Label slow, allocated, done;
3546   Register tmp = input_reg.is(eax) ? ecx : eax;
3547   Register tmp2 = tmp.is(ecx) ? edx : input_reg.is(ecx) ? edx : ecx;
3548
3549   // Preserve the value of all registers.
3550   PushSafepointRegistersScope scope(this);
3551
3552   __ mov(tmp, FieldOperand(input_reg, HeapNumber::kExponentOffset));
3553   // Check the sign of the argument. If the argument is positive, just
3554   // return it. We do not need to patch the stack since |input| and
3555   // |result| are the same register and |input| will be restored
3556   // unchanged by popping safepoint registers.
3557   __ test(tmp, Immediate(HeapNumber::kSignMask));
3558   __ j(zero, &done, Label::kNear);
3559
3560   __ AllocateHeapNumber(tmp, tmp2, no_reg, &slow);
3561   __ jmp(&allocated, Label::kNear);
3562
3563   // Slow case: Call the runtime system to do the number allocation.
3564   __ bind(&slow);
3565   CallRuntimeFromDeferred(Runtime::kAllocateHeapNumber, 0,
3566                           instr, instr->context());
3567   // Set the pointer to the new heap number in tmp.
3568   if (!tmp.is(eax)) __ mov(tmp, eax);
3569   // Restore input_reg after call to runtime.
3570   __ LoadFromSafepointRegisterSlot(input_reg, input_reg);
3571
3572   __ bind(&allocated);
3573   __ mov(tmp2, FieldOperand(input_reg, HeapNumber::kExponentOffset));
3574   __ and_(tmp2, ~HeapNumber::kSignMask);
3575   __ mov(FieldOperand(tmp, HeapNumber::kExponentOffset), tmp2);
3576   __ mov(tmp2, FieldOperand(input_reg, HeapNumber::kMantissaOffset));
3577   __ mov(FieldOperand(tmp, HeapNumber::kMantissaOffset), tmp2);
3578   __ StoreToSafepointRegisterSlot(input_reg, tmp);
3579
3580   __ bind(&done);
3581 }
3582
3583
3584 void LCodeGen::EmitIntegerMathAbs(LMathAbs* instr) {
3585   Register input_reg = ToRegister(instr->value());
3586   __ test(input_reg, Operand(input_reg));
3587   Label is_positive;
3588   __ j(not_sign, &is_positive, Label::kNear);
3589   __ neg(input_reg);  // Sets flags.
3590   DeoptimizeIf(negative, instr, Deoptimizer::kOverflow);
3591   __ bind(&is_positive);
3592 }
3593
3594
3595 void LCodeGen::DoMathAbs(LMathAbs* instr) {
3596   // Class for deferred case.
3597   class DeferredMathAbsTaggedHeapNumber final : public LDeferredCode {
3598    public:
3599     DeferredMathAbsTaggedHeapNumber(LCodeGen* codegen,
3600                                     LMathAbs* instr)
3601         : LDeferredCode(codegen), instr_(instr) { }
3602     void Generate() override {
3603       codegen()->DoDeferredMathAbsTaggedHeapNumber(instr_);
3604     }
3605     LInstruction* instr() override { return instr_; }
3606
3607    private:
3608     LMathAbs* instr_;
3609   };
3610
3611   DCHECK(instr->value()->Equals(instr->result()));
3612   Representation r = instr->hydrogen()->value()->representation();
3613
3614   if (r.IsDouble()) {
3615     XMMRegister scratch = double_scratch0();
3616     XMMRegister input_reg = ToDoubleRegister(instr->value());
3617     __ xorps(scratch, scratch);
3618     __ subsd(scratch, input_reg);
3619     __ andps(input_reg, scratch);
3620   } else if (r.IsSmiOrInteger32()) {
3621     EmitIntegerMathAbs(instr);
3622   } else {  // Tagged case.
3623     DeferredMathAbsTaggedHeapNumber* deferred =
3624         new(zone()) DeferredMathAbsTaggedHeapNumber(this, instr);
3625     Register input_reg = ToRegister(instr->value());
3626     // Smi check.
3627     __ JumpIfNotSmi(input_reg, deferred->entry());
3628     EmitIntegerMathAbs(instr);
3629     __ bind(deferred->exit());
3630   }
3631 }
3632
3633
3634 void LCodeGen::DoMathFloor(LMathFloor* instr) {
3635   XMMRegister xmm_scratch = double_scratch0();
3636   Register output_reg = ToRegister(instr->result());
3637   XMMRegister input_reg = ToDoubleRegister(instr->value());
3638
3639   if (CpuFeatures::IsSupported(SSE4_1)) {
3640     CpuFeatureScope scope(masm(), SSE4_1);
3641     if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3642       // Deoptimize on negative zero.
3643       Label non_zero;
3644       __ xorps(xmm_scratch, xmm_scratch);  // Zero the register.
3645       __ ucomisd(input_reg, xmm_scratch);
3646       __ j(not_equal, &non_zero, Label::kNear);
3647       __ movmskpd(output_reg, input_reg);
3648       __ test(output_reg, Immediate(1));
3649       DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
3650       __ bind(&non_zero);
3651     }
3652     __ roundsd(xmm_scratch, input_reg, kRoundDown);
3653     __ cvttsd2si(output_reg, Operand(xmm_scratch));
3654     // Overflow is signalled with minint.
3655     __ cmp(output_reg, 0x1);
3656     DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
3657   } else {
3658     Label negative_sign, done;
3659     // Deoptimize on unordered.
3660     __ xorps(xmm_scratch, xmm_scratch);  // Zero the register.
3661     __ ucomisd(input_reg, xmm_scratch);
3662     DeoptimizeIf(parity_even, instr, Deoptimizer::kNaN);
3663     __ j(below, &negative_sign, Label::kNear);
3664
3665     if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3666       // Check for negative zero.
3667       Label positive_sign;
3668       __ j(above, &positive_sign, Label::kNear);
3669       __ movmskpd(output_reg, input_reg);
3670       __ test(output_reg, Immediate(1));
3671       DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
3672       __ Move(output_reg, Immediate(0));
3673       __ jmp(&done, Label::kNear);
3674       __ bind(&positive_sign);
3675     }
3676
3677     // Use truncating instruction (OK because input is positive).
3678     __ cvttsd2si(output_reg, Operand(input_reg));
3679     // Overflow is signalled with minint.
3680     __ cmp(output_reg, 0x1);
3681     DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
3682     __ jmp(&done, Label::kNear);
3683
3684     // Non-zero negative reaches here.
3685     __ bind(&negative_sign);
3686     // Truncate, then compare and compensate.
3687     __ cvttsd2si(output_reg, Operand(input_reg));
3688     __ Cvtsi2sd(xmm_scratch, output_reg);
3689     __ ucomisd(input_reg, xmm_scratch);
3690     __ j(equal, &done, Label::kNear);
3691     __ sub(output_reg, Immediate(1));
3692     DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
3693
3694     __ bind(&done);
3695   }
3696 }
3697
3698
3699 void LCodeGen::DoMathRound(LMathRound* instr) {
3700   Register output_reg = ToRegister(instr->result());
3701   XMMRegister input_reg = ToDoubleRegister(instr->value());
3702   XMMRegister xmm_scratch = double_scratch0();
3703   XMMRegister input_temp = ToDoubleRegister(instr->temp());
3704   ExternalReference one_half = ExternalReference::address_of_one_half();
3705   ExternalReference minus_one_half =
3706       ExternalReference::address_of_minus_one_half();
3707
3708   Label done, round_to_zero, below_one_half, do_not_compensate;
3709   Label::Distance dist = DeoptEveryNTimes() ? Label::kFar : Label::kNear;
3710
3711   __ movsd(xmm_scratch, Operand::StaticVariable(one_half));
3712   __ ucomisd(xmm_scratch, input_reg);
3713   __ j(above, &below_one_half, Label::kNear);
3714
3715   // CVTTSD2SI rounds towards zero, since 0.5 <= x, we use floor(0.5 + x).
3716   __ addsd(xmm_scratch, input_reg);
3717   __ cvttsd2si(output_reg, Operand(xmm_scratch));
3718   // Overflow is signalled with minint.
3719   __ cmp(output_reg, 0x1);
3720   DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
3721   __ jmp(&done, dist);
3722
3723   __ bind(&below_one_half);
3724   __ movsd(xmm_scratch, Operand::StaticVariable(minus_one_half));
3725   __ ucomisd(xmm_scratch, input_reg);
3726   __ j(below_equal, &round_to_zero, Label::kNear);
3727
3728   // CVTTSD2SI rounds towards zero, we use ceil(x - (-0.5)) and then
3729   // compare and compensate.
3730   __ movaps(input_temp, input_reg);  // Do not alter input_reg.
3731   __ subsd(input_temp, xmm_scratch);
3732   __ cvttsd2si(output_reg, Operand(input_temp));
3733   // Catch minint due to overflow, and to prevent overflow when compensating.
3734   __ cmp(output_reg, 0x1);
3735   DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
3736
3737   __ Cvtsi2sd(xmm_scratch, output_reg);
3738   __ ucomisd(xmm_scratch, input_temp);
3739   __ j(equal, &done, dist);
3740   __ sub(output_reg, Immediate(1));
3741   // No overflow because we already ruled out minint.
3742   __ jmp(&done, dist);
3743
3744   __ bind(&round_to_zero);
3745   // We return 0 for the input range [+0, 0.5[, or [-0.5, 0.5[ if
3746   // we can ignore the difference between a result of -0 and +0.
3747   if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3748     // If the sign is positive, we return +0.
3749     __ movmskpd(output_reg, input_reg);
3750     __ test(output_reg, Immediate(1));
3751     DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
3752   }
3753   __ Move(output_reg, Immediate(0));
3754   __ bind(&done);
3755 }
3756
3757
3758 void LCodeGen::DoMathFround(LMathFround* instr) {
3759   XMMRegister input_reg = ToDoubleRegister(instr->value());
3760   XMMRegister output_reg = ToDoubleRegister(instr->result());
3761   __ cvtsd2ss(output_reg, input_reg);
3762   __ cvtss2sd(output_reg, output_reg);
3763 }
3764
3765
3766 void LCodeGen::DoMathSqrt(LMathSqrt* instr) {
3767   Operand input = ToOperand(instr->value());
3768   XMMRegister output = ToDoubleRegister(instr->result());
3769   __ sqrtsd(output, input);
3770 }
3771
3772
3773 void LCodeGen::DoMathPowHalf(LMathPowHalf* instr) {
3774   XMMRegister xmm_scratch = double_scratch0();
3775   XMMRegister input_reg = ToDoubleRegister(instr->value());
3776   Register scratch = ToRegister(instr->temp());
3777   DCHECK(ToDoubleRegister(instr->result()).is(input_reg));
3778
3779   // Note that according to ECMA-262 15.8.2.13:
3780   // Math.pow(-Infinity, 0.5) == Infinity
3781   // Math.sqrt(-Infinity) == NaN
3782   Label done, sqrt;
3783   // Check base for -Infinity.  According to IEEE-754, single-precision
3784   // -Infinity has the highest 9 bits set and the lowest 23 bits cleared.
3785   __ mov(scratch, 0xFF800000);
3786   __ movd(xmm_scratch, scratch);
3787   __ cvtss2sd(xmm_scratch, xmm_scratch);
3788   __ ucomisd(input_reg, xmm_scratch);
3789   // Comparing -Infinity with NaN results in "unordered", which sets the
3790   // zero flag as if both were equal.  However, it also sets the carry flag.
3791   __ j(not_equal, &sqrt, Label::kNear);
3792   __ j(carry, &sqrt, Label::kNear);
3793   // If input is -Infinity, return Infinity.
3794   __ xorps(input_reg, input_reg);
3795   __ subsd(input_reg, xmm_scratch);
3796   __ jmp(&done, Label::kNear);
3797
3798   // Square root.
3799   __ bind(&sqrt);
3800   __ xorps(xmm_scratch, xmm_scratch);
3801   __ addsd(input_reg, xmm_scratch);  // Convert -0 to +0.
3802   __ sqrtsd(input_reg, input_reg);
3803   __ bind(&done);
3804 }
3805
3806
3807 void LCodeGen::DoPower(LPower* instr) {
3808   Representation exponent_type = instr->hydrogen()->right()->representation();
3809   // Having marked this as a call, we can use any registers.
3810   // Just make sure that the input/output registers are the expected ones.
3811   Register tagged_exponent = MathPowTaggedDescriptor::exponent();
3812   DCHECK(!instr->right()->IsDoubleRegister() ||
3813          ToDoubleRegister(instr->right()).is(xmm1));
3814   DCHECK(!instr->right()->IsRegister() ||
3815          ToRegister(instr->right()).is(tagged_exponent));
3816   DCHECK(ToDoubleRegister(instr->left()).is(xmm2));
3817   DCHECK(ToDoubleRegister(instr->result()).is(xmm3));
3818
3819   if (exponent_type.IsSmi()) {
3820     MathPowStub stub(isolate(), MathPowStub::TAGGED);
3821     __ CallStub(&stub);
3822   } else if (exponent_type.IsTagged()) {
3823     Label no_deopt;
3824     __ JumpIfSmi(tagged_exponent, &no_deopt);
3825     DCHECK(!ecx.is(tagged_exponent));
3826     __ CmpObjectType(tagged_exponent, HEAP_NUMBER_TYPE, ecx);
3827     DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
3828     __ bind(&no_deopt);
3829     MathPowStub stub(isolate(), MathPowStub::TAGGED);
3830     __ CallStub(&stub);
3831   } else if (exponent_type.IsInteger32()) {
3832     MathPowStub stub(isolate(), MathPowStub::INTEGER);
3833     __ CallStub(&stub);
3834   } else {
3835     DCHECK(exponent_type.IsDouble());
3836     MathPowStub stub(isolate(), MathPowStub::DOUBLE);
3837     __ CallStub(&stub);
3838   }
3839 }
3840
3841
3842 void LCodeGen::DoMathLog(LMathLog* instr) {
3843   DCHECK(instr->value()->Equals(instr->result()));
3844   XMMRegister input_reg = ToDoubleRegister(instr->value());
3845   XMMRegister xmm_scratch = double_scratch0();
3846   Label positive, done, zero;
3847   __ xorps(xmm_scratch, xmm_scratch);
3848   __ ucomisd(input_reg, xmm_scratch);
3849   __ j(above, &positive, Label::kNear);
3850   __ j(not_carry, &zero, Label::kNear);
3851   __ pcmpeqd(input_reg, input_reg);
3852   __ jmp(&done, Label::kNear);
3853   __ bind(&zero);
3854   ExternalReference ninf =
3855       ExternalReference::address_of_negative_infinity();
3856   __ movsd(input_reg, Operand::StaticVariable(ninf));
3857   __ jmp(&done, Label::kNear);
3858   __ bind(&positive);
3859   __ fldln2();
3860   __ sub(Operand(esp), Immediate(kDoubleSize));
3861   __ movsd(Operand(esp, 0), input_reg);
3862   __ fld_d(Operand(esp, 0));
3863   __ fyl2x();
3864   __ fstp_d(Operand(esp, 0));
3865   __ movsd(input_reg, Operand(esp, 0));
3866   __ add(Operand(esp), Immediate(kDoubleSize));
3867   __ bind(&done);
3868 }
3869
3870
3871 void LCodeGen::DoMathClz32(LMathClz32* instr) {
3872   Register input = ToRegister(instr->value());
3873   Register result = ToRegister(instr->result());
3874
3875   __ Lzcnt(result, input);
3876 }
3877
3878
3879 void LCodeGen::DoMathExp(LMathExp* instr) {
3880   XMMRegister input = ToDoubleRegister(instr->value());
3881   XMMRegister result = ToDoubleRegister(instr->result());
3882   XMMRegister temp0 = double_scratch0();
3883   Register temp1 = ToRegister(instr->temp1());
3884   Register temp2 = ToRegister(instr->temp2());
3885
3886   MathExpGenerator::EmitMathExp(masm(), input, result, temp0, temp1, temp2);
3887 }
3888
3889
3890 void LCodeGen::DoInvokeFunction(LInvokeFunction* instr) {
3891   DCHECK(ToRegister(instr->context()).is(esi));
3892   DCHECK(ToRegister(instr->function()).is(edi));
3893   DCHECK(instr->HasPointerMap());
3894
3895   Handle<JSFunction> known_function = instr->hydrogen()->known_function();
3896   if (known_function.is_null()) {
3897     LPointerMap* pointers = instr->pointer_map();
3898     SafepointGenerator generator(
3899         this, pointers, Safepoint::kLazyDeopt);
3900     ParameterCount count(instr->arity());
3901     __ InvokeFunction(edi, count, CALL_FUNCTION, generator);
3902   } else {
3903     CallKnownFunction(known_function,
3904                       instr->hydrogen()->formal_parameter_count(),
3905                       instr->arity(), instr);
3906   }
3907 }
3908
3909
3910 void LCodeGen::DoCallFunction(LCallFunction* instr) {
3911   DCHECK(ToRegister(instr->context()).is(esi));
3912   DCHECK(ToRegister(instr->function()).is(edi));
3913   DCHECK(ToRegister(instr->result()).is(eax));
3914
3915   int arity = instr->arity();
3916   CallFunctionFlags flags = instr->hydrogen()->function_flags();
3917   if (instr->hydrogen()->HasVectorAndSlot()) {
3918     Register slot_register = ToRegister(instr->temp_slot());
3919     Register vector_register = ToRegister(instr->temp_vector());
3920     DCHECK(slot_register.is(edx));
3921     DCHECK(vector_register.is(ebx));
3922
3923     AllowDeferredHandleDereference vector_structure_check;
3924     Handle<TypeFeedbackVector> vector = instr->hydrogen()->feedback_vector();
3925     int index = vector->GetIndex(instr->hydrogen()->slot());
3926
3927     __ mov(vector_register, vector);
3928     __ mov(slot_register, Immediate(Smi::FromInt(index)));
3929
3930     CallICState::CallType call_type =
3931         (flags & CALL_AS_METHOD) ? CallICState::METHOD : CallICState::FUNCTION;
3932
3933     Handle<Code> ic =
3934         CodeFactory::CallICInOptimizedCode(isolate(), arity, call_type).code();
3935     CallCode(ic, RelocInfo::CODE_TARGET, instr);
3936   } else {
3937     CallFunctionStub stub(isolate(), arity, flags);
3938     CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
3939   }
3940 }
3941
3942
3943 void LCodeGen::DoCallNew(LCallNew* instr) {
3944   DCHECK(ToRegister(instr->context()).is(esi));
3945   DCHECK(ToRegister(instr->constructor()).is(edi));
3946   DCHECK(ToRegister(instr->result()).is(eax));
3947
3948   // No cell in ebx for construct type feedback in optimized code
3949   __ mov(ebx, isolate()->factory()->undefined_value());
3950   CallConstructStub stub(isolate(), NO_CALL_CONSTRUCTOR_FLAGS);
3951   __ Move(eax, Immediate(instr->arity()));
3952   CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
3953 }
3954
3955
3956 void LCodeGen::DoCallNewArray(LCallNewArray* instr) {
3957   DCHECK(ToRegister(instr->context()).is(esi));
3958   DCHECK(ToRegister(instr->constructor()).is(edi));
3959   DCHECK(ToRegister(instr->result()).is(eax));
3960
3961   __ Move(eax, Immediate(instr->arity()));
3962   if (instr->arity() == 1) {
3963     // We only need the allocation site for the case we have a length argument.
3964     // The case may bail out to the runtime, which will determine the correct
3965     // elements kind with the site.
3966     __ mov(ebx, instr->hydrogen()->site());
3967   } else {
3968     __ mov(ebx, isolate()->factory()->undefined_value());
3969   }
3970
3971   ElementsKind kind = instr->hydrogen()->elements_kind();
3972   AllocationSiteOverrideMode override_mode =
3973       (AllocationSite::GetMode(kind) == TRACK_ALLOCATION_SITE)
3974           ? DISABLE_ALLOCATION_SITES
3975           : DONT_OVERRIDE;
3976
3977   if (instr->arity() == 0) {
3978     ArrayNoArgumentConstructorStub stub(isolate(), kind, override_mode);
3979     CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
3980   } else if (instr->arity() == 1) {
3981     Label done;
3982     if (IsFastPackedElementsKind(kind)) {
3983       Label packed_case;
3984       // We might need a change here
3985       // look at the first argument
3986       __ mov(ecx, Operand(esp, 0));
3987       __ test(ecx, ecx);
3988       __ j(zero, &packed_case, Label::kNear);
3989
3990       ElementsKind holey_kind = GetHoleyElementsKind(kind);
3991       ArraySingleArgumentConstructorStub stub(isolate(),
3992                                               holey_kind,
3993                                               override_mode);
3994       CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
3995       __ jmp(&done, Label::kNear);
3996       __ bind(&packed_case);
3997     }
3998
3999     ArraySingleArgumentConstructorStub stub(isolate(), kind, override_mode);
4000     CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
4001     __ bind(&done);
4002   } else {
4003     ArrayNArgumentsConstructorStub stub(isolate(), kind, override_mode);
4004     CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
4005   }
4006 }
4007
4008
4009 void LCodeGen::DoCallRuntime(LCallRuntime* instr) {
4010   DCHECK(ToRegister(instr->context()).is(esi));
4011   CallRuntime(instr->function(), instr->arity(), instr, instr->save_doubles());
4012 }
4013
4014
4015 void LCodeGen::DoStoreCodeEntry(LStoreCodeEntry* instr) {
4016   Register function = ToRegister(instr->function());
4017   Register code_object = ToRegister(instr->code_object());
4018   __ lea(code_object, FieldOperand(code_object, Code::kHeaderSize));
4019   __ mov(FieldOperand(function, JSFunction::kCodeEntryOffset), code_object);
4020 }
4021
4022
4023 void LCodeGen::DoInnerAllocatedObject(LInnerAllocatedObject* instr) {
4024   Register result = ToRegister(instr->result());
4025   Register base = ToRegister(instr->base_object());
4026   if (instr->offset()->IsConstantOperand()) {
4027     LConstantOperand* offset = LConstantOperand::cast(instr->offset());
4028     __ lea(result, Operand(base, ToInteger32(offset)));
4029   } else {
4030     Register offset = ToRegister(instr->offset());
4031     __ lea(result, Operand(base, offset, times_1, 0));
4032   }
4033 }
4034
4035
4036 void LCodeGen::DoStoreNamedField(LStoreNamedField* instr) {
4037   Representation representation = instr->hydrogen()->field_representation();
4038
4039   HObjectAccess access = instr->hydrogen()->access();
4040   int offset = access.offset();
4041
4042   if (access.IsExternalMemory()) {
4043     DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4044     MemOperand operand = instr->object()->IsConstantOperand()
4045         ? MemOperand::StaticVariable(
4046             ToExternalReference(LConstantOperand::cast(instr->object())))
4047         : MemOperand(ToRegister(instr->object()), offset);
4048     if (instr->value()->IsConstantOperand()) {
4049       LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
4050       __ mov(operand, Immediate(ToInteger32(operand_value)));
4051     } else {
4052       Register value = ToRegister(instr->value());
4053       __ Store(value, operand, representation);
4054     }
4055     return;
4056   }
4057
4058   Register object = ToRegister(instr->object());
4059   __ AssertNotSmi(object);
4060
4061   DCHECK(!representation.IsSmi() ||
4062          !instr->value()->IsConstantOperand() ||
4063          IsSmi(LConstantOperand::cast(instr->value())));
4064   if (representation.IsDouble()) {
4065     DCHECK(access.IsInobject());
4066     DCHECK(!instr->hydrogen()->has_transition());
4067     DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4068     XMMRegister value = ToDoubleRegister(instr->value());
4069     __ movsd(FieldOperand(object, offset), value);
4070     return;
4071   }
4072
4073   if (instr->hydrogen()->has_transition()) {
4074     Handle<Map> transition = instr->hydrogen()->transition_map();
4075     AddDeprecationDependency(transition);
4076     __ mov(FieldOperand(object, HeapObject::kMapOffset), transition);
4077     if (instr->hydrogen()->NeedsWriteBarrierForMap()) {
4078       Register temp = ToRegister(instr->temp());
4079       Register temp_map = ToRegister(instr->temp_map());
4080       // Update the write barrier for the map field.
4081       __ RecordWriteForMap(object, transition, temp_map, temp, kSaveFPRegs);
4082     }
4083   }
4084
4085   // Do the store.
4086   Register write_register = object;
4087   if (!access.IsInobject()) {
4088     write_register = ToRegister(instr->temp());
4089     __ mov(write_register, FieldOperand(object, JSObject::kPropertiesOffset));
4090   }
4091
4092   MemOperand operand = FieldOperand(write_register, offset);
4093   if (instr->value()->IsConstantOperand()) {
4094     LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
4095     if (operand_value->IsRegister()) {
4096       Register value = ToRegister(operand_value);
4097       __ Store(value, operand, representation);
4098     } else if (representation.IsInteger32()) {
4099       Immediate immediate = ToImmediate(operand_value, representation);
4100       DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4101       __ mov(operand, immediate);
4102     } else {
4103       Handle<Object> handle_value = ToHandle(operand_value);
4104       DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4105       __ mov(operand, handle_value);
4106     }
4107   } else {
4108     Register value = ToRegister(instr->value());
4109     __ Store(value, operand, representation);
4110   }
4111
4112   if (instr->hydrogen()->NeedsWriteBarrier()) {
4113     Register value = ToRegister(instr->value());
4114     Register temp = access.IsInobject() ? ToRegister(instr->temp()) : object;
4115     // Update the write barrier for the object for in-object properties.
4116     __ RecordWriteField(write_register,
4117                         offset,
4118                         value,
4119                         temp,
4120                         kSaveFPRegs,
4121                         EMIT_REMEMBERED_SET,
4122                         instr->hydrogen()->SmiCheckForWriteBarrier(),
4123                         instr->hydrogen()->PointersToHereCheckForValue());
4124   }
4125 }
4126
4127
4128 void LCodeGen::DoStoreNamedGeneric(LStoreNamedGeneric* instr) {
4129   DCHECK(ToRegister(instr->context()).is(esi));
4130   DCHECK(ToRegister(instr->object()).is(StoreDescriptor::ReceiverRegister()));
4131   DCHECK(ToRegister(instr->value()).is(StoreDescriptor::ValueRegister()));
4132
4133   __ mov(StoreDescriptor::NameRegister(), instr->name());
4134   Handle<Code> ic =
4135       StoreIC::initialize_stub(isolate(), instr->language_mode(),
4136                                instr->hydrogen()->initialization_state());
4137   CallCode(ic, RelocInfo::CODE_TARGET, instr);
4138 }
4139
4140
4141 void LCodeGen::DoBoundsCheck(LBoundsCheck* instr) {
4142   Condition cc = instr->hydrogen()->allow_equality() ? above : above_equal;
4143   if (instr->index()->IsConstantOperand()) {
4144     __ cmp(ToOperand(instr->length()),
4145            ToImmediate(LConstantOperand::cast(instr->index()),
4146                        instr->hydrogen()->length()->representation()));
4147     cc = CommuteCondition(cc);
4148   } else if (instr->length()->IsConstantOperand()) {
4149     __ cmp(ToOperand(instr->index()),
4150            ToImmediate(LConstantOperand::cast(instr->length()),
4151                        instr->hydrogen()->index()->representation()));
4152   } else {
4153     __ cmp(ToRegister(instr->index()), ToOperand(instr->length()));
4154   }
4155   if (FLAG_debug_code && instr->hydrogen()->skip_check()) {
4156     Label done;
4157     __ j(NegateCondition(cc), &done, Label::kNear);
4158     __ int3();
4159     __ bind(&done);
4160   } else {
4161     DeoptimizeIf(cc, instr, Deoptimizer::kOutOfBounds);
4162   }
4163 }
4164
4165
4166 void LCodeGen::DoStoreKeyedExternalArray(LStoreKeyed* instr) {
4167   ElementsKind elements_kind = instr->elements_kind();
4168   LOperand* key = instr->key();
4169   if (!key->IsConstantOperand() &&
4170       ExternalArrayOpRequiresTemp(instr->hydrogen()->key()->representation(),
4171                                   elements_kind)) {
4172     __ SmiUntag(ToRegister(key));
4173   }
4174   Operand operand(BuildFastArrayOperand(
4175       instr->elements(),
4176       key,
4177       instr->hydrogen()->key()->representation(),
4178       elements_kind,
4179       instr->base_offset()));
4180   if (elements_kind == EXTERNAL_FLOAT32_ELEMENTS ||
4181       elements_kind == FLOAT32_ELEMENTS) {
4182     XMMRegister xmm_scratch = double_scratch0();
4183     __ cvtsd2ss(xmm_scratch, ToDoubleRegister(instr->value()));
4184     __ movss(operand, xmm_scratch);
4185   } else if (elements_kind == EXTERNAL_FLOAT64_ELEMENTS ||
4186              elements_kind == FLOAT64_ELEMENTS) {
4187     __ movsd(operand, ToDoubleRegister(instr->value()));
4188   } else {
4189     Register value = ToRegister(instr->value());
4190     switch (elements_kind) {
4191       case EXTERNAL_UINT8_CLAMPED_ELEMENTS:
4192       case EXTERNAL_UINT8_ELEMENTS:
4193       case EXTERNAL_INT8_ELEMENTS:
4194       case UINT8_ELEMENTS:
4195       case INT8_ELEMENTS:
4196       case UINT8_CLAMPED_ELEMENTS:
4197         __ mov_b(operand, value);
4198         break;
4199       case EXTERNAL_INT16_ELEMENTS:
4200       case EXTERNAL_UINT16_ELEMENTS:
4201       case UINT16_ELEMENTS:
4202       case INT16_ELEMENTS:
4203         __ mov_w(operand, value);
4204         break;
4205       case EXTERNAL_INT32_ELEMENTS:
4206       case EXTERNAL_UINT32_ELEMENTS:
4207       case UINT32_ELEMENTS:
4208       case INT32_ELEMENTS:
4209         __ mov(operand, value);
4210         break;
4211       case EXTERNAL_FLOAT32_ELEMENTS:
4212       case EXTERNAL_FLOAT64_ELEMENTS:
4213       case FLOAT32_ELEMENTS:
4214       case FLOAT64_ELEMENTS:
4215       case FAST_SMI_ELEMENTS:
4216       case FAST_ELEMENTS:
4217       case FAST_DOUBLE_ELEMENTS:
4218       case FAST_HOLEY_SMI_ELEMENTS:
4219       case FAST_HOLEY_ELEMENTS:
4220       case FAST_HOLEY_DOUBLE_ELEMENTS:
4221       case DICTIONARY_ELEMENTS:
4222       case SLOPPY_ARGUMENTS_ELEMENTS:
4223         UNREACHABLE();
4224         break;
4225     }
4226   }
4227 }
4228
4229
4230 void LCodeGen::DoStoreKeyedFixedDoubleArray(LStoreKeyed* instr) {
4231   Operand double_store_operand = BuildFastArrayOperand(
4232       instr->elements(),
4233       instr->key(),
4234       instr->hydrogen()->key()->representation(),
4235       FAST_DOUBLE_ELEMENTS,
4236       instr->base_offset());
4237
4238   XMMRegister value = ToDoubleRegister(instr->value());
4239
4240   if (instr->NeedsCanonicalization()) {
4241     XMMRegister xmm_scratch = double_scratch0();
4242     // Turn potential sNaN value into qNaN.
4243     __ xorps(xmm_scratch, xmm_scratch);
4244     __ subsd(value, xmm_scratch);
4245   }
4246
4247   __ movsd(double_store_operand, value);
4248 }
4249
4250
4251 void LCodeGen::DoStoreKeyedFixedArray(LStoreKeyed* instr) {
4252   Register elements = ToRegister(instr->elements());
4253   Register key = instr->key()->IsRegister() ? ToRegister(instr->key()) : no_reg;
4254
4255   Operand operand = BuildFastArrayOperand(
4256       instr->elements(),
4257       instr->key(),
4258       instr->hydrogen()->key()->representation(),
4259       FAST_ELEMENTS,
4260       instr->base_offset());
4261   if (instr->value()->IsRegister()) {
4262     __ mov(operand, ToRegister(instr->value()));
4263   } else {
4264     LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
4265     if (IsSmi(operand_value)) {
4266       Immediate immediate = ToImmediate(operand_value, Representation::Smi());
4267       __ mov(operand, immediate);
4268     } else {
4269       DCHECK(!IsInteger32(operand_value));
4270       Handle<Object> handle_value = ToHandle(operand_value);
4271       __ mov(operand, handle_value);
4272     }
4273   }
4274
4275   if (instr->hydrogen()->NeedsWriteBarrier()) {
4276     DCHECK(instr->value()->IsRegister());
4277     Register value = ToRegister(instr->value());
4278     DCHECK(!instr->key()->IsConstantOperand());
4279     SmiCheck check_needed =
4280         instr->hydrogen()->value()->type().IsHeapObject()
4281           ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
4282     // Compute address of modified element and store it into key register.
4283     __ lea(key, operand);
4284     __ RecordWrite(elements,
4285                    key,
4286                    value,
4287                    kSaveFPRegs,
4288                    EMIT_REMEMBERED_SET,
4289                    check_needed,
4290                    instr->hydrogen()->PointersToHereCheckForValue());
4291   }
4292 }
4293
4294
4295 void LCodeGen::DoStoreKeyed(LStoreKeyed* instr) {
4296   // By cases...external, fast-double, fast
4297   if (instr->is_typed_elements()) {
4298     DoStoreKeyedExternalArray(instr);
4299   } else if (instr->hydrogen()->value()->representation().IsDouble()) {
4300     DoStoreKeyedFixedDoubleArray(instr);
4301   } else {
4302     DoStoreKeyedFixedArray(instr);
4303   }
4304 }
4305
4306
4307 void LCodeGen::DoStoreKeyedGeneric(LStoreKeyedGeneric* instr) {
4308   DCHECK(ToRegister(instr->context()).is(esi));
4309   DCHECK(ToRegister(instr->object()).is(StoreDescriptor::ReceiverRegister()));
4310   DCHECK(ToRegister(instr->key()).is(StoreDescriptor::NameRegister()));
4311   DCHECK(ToRegister(instr->value()).is(StoreDescriptor::ValueRegister()));
4312
4313   Handle<Code> ic = CodeFactory::KeyedStoreICInOptimizedCode(
4314                         isolate(), instr->language_mode(),
4315                         instr->hydrogen()->initialization_state()).code();
4316   CallCode(ic, RelocInfo::CODE_TARGET, instr);
4317 }
4318
4319
4320 void LCodeGen::DoTrapAllocationMemento(LTrapAllocationMemento* instr) {
4321   Register object = ToRegister(instr->object());
4322   Register temp = ToRegister(instr->temp());
4323   Label no_memento_found;
4324   __ TestJSArrayForAllocationMemento(object, temp, &no_memento_found);
4325   DeoptimizeIf(equal, instr, Deoptimizer::kMementoFound);
4326   __ bind(&no_memento_found);
4327 }
4328
4329
4330 void LCodeGen::DoMaybeGrowElements(LMaybeGrowElements* instr) {
4331   class DeferredMaybeGrowElements final : public LDeferredCode {
4332    public:
4333     DeferredMaybeGrowElements(LCodeGen* codegen, LMaybeGrowElements* instr)
4334         : LDeferredCode(codegen), instr_(instr) {}
4335     void Generate() override { codegen()->DoDeferredMaybeGrowElements(instr_); }
4336     LInstruction* instr() override { return instr_; }
4337
4338    private:
4339     LMaybeGrowElements* instr_;
4340   };
4341
4342   Register result = eax;
4343   DeferredMaybeGrowElements* deferred =
4344       new (zone()) DeferredMaybeGrowElements(this, instr);
4345   LOperand* key = instr->key();
4346   LOperand* current_capacity = instr->current_capacity();
4347
4348   DCHECK(instr->hydrogen()->key()->representation().IsInteger32());
4349   DCHECK(instr->hydrogen()->current_capacity()->representation().IsInteger32());
4350   DCHECK(key->IsConstantOperand() || key->IsRegister());
4351   DCHECK(current_capacity->IsConstantOperand() ||
4352          current_capacity->IsRegister());
4353
4354   if (key->IsConstantOperand() && current_capacity->IsConstantOperand()) {
4355     int32_t constant_key = ToInteger32(LConstantOperand::cast(key));
4356     int32_t constant_capacity =
4357         ToInteger32(LConstantOperand::cast(current_capacity));
4358     if (constant_key >= constant_capacity) {
4359       // Deferred case.
4360       __ jmp(deferred->entry());
4361     }
4362   } else if (key->IsConstantOperand()) {
4363     int32_t constant_key = ToInteger32(LConstantOperand::cast(key));
4364     __ cmp(ToOperand(current_capacity), Immediate(constant_key));
4365     __ j(less_equal, deferred->entry());
4366   } else if (current_capacity->IsConstantOperand()) {
4367     int32_t constant_capacity =
4368         ToInteger32(LConstantOperand::cast(current_capacity));
4369     __ cmp(ToRegister(key), Immediate(constant_capacity));
4370     __ j(greater_equal, deferred->entry());
4371   } else {
4372     __ cmp(ToRegister(key), ToRegister(current_capacity));
4373     __ j(greater_equal, deferred->entry());
4374   }
4375
4376   __ mov(result, ToOperand(instr->elements()));
4377   __ bind(deferred->exit());
4378 }
4379
4380
4381 void LCodeGen::DoDeferredMaybeGrowElements(LMaybeGrowElements* instr) {
4382   // TODO(3095996): Get rid of this. For now, we need to make the
4383   // result register contain a valid pointer because it is already
4384   // contained in the register pointer map.
4385   Register result = eax;
4386   __ Move(result, Immediate(0));
4387
4388   // We have to call a stub.
4389   {
4390     PushSafepointRegistersScope scope(this);
4391     if (instr->object()->IsRegister()) {
4392       __ Move(result, ToRegister(instr->object()));
4393     } else {
4394       __ mov(result, ToOperand(instr->object()));
4395     }
4396
4397     LOperand* key = instr->key();
4398     if (key->IsConstantOperand()) {
4399       __ mov(ebx, ToImmediate(key, Representation::Smi()));
4400     } else {
4401       __ Move(ebx, ToRegister(key));
4402       __ SmiTag(ebx);
4403     }
4404
4405     GrowArrayElementsStub stub(isolate(), instr->hydrogen()->is_js_array(),
4406                                instr->hydrogen()->kind());
4407     __ CallStub(&stub);
4408     RecordSafepointWithLazyDeopt(
4409         instr, RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
4410     __ StoreToSafepointRegisterSlot(result, result);
4411   }
4412
4413   // Deopt on smi, which means the elements array changed to dictionary mode.
4414   __ test(result, Immediate(kSmiTagMask));
4415   DeoptimizeIf(equal, instr, Deoptimizer::kSmi);
4416 }
4417
4418
4419 void LCodeGen::DoTransitionElementsKind(LTransitionElementsKind* instr) {
4420   Register object_reg = ToRegister(instr->object());
4421
4422   Handle<Map> from_map = instr->original_map();
4423   Handle<Map> to_map = instr->transitioned_map();
4424   ElementsKind from_kind = instr->from_kind();
4425   ElementsKind to_kind = instr->to_kind();
4426
4427   Label not_applicable;
4428   bool is_simple_map_transition =
4429       IsSimpleMapChangeTransition(from_kind, to_kind);
4430   Label::Distance branch_distance =
4431       is_simple_map_transition ? Label::kNear : Label::kFar;
4432   __ cmp(FieldOperand(object_reg, HeapObject::kMapOffset), from_map);
4433   __ j(not_equal, &not_applicable, branch_distance);
4434   if (is_simple_map_transition) {
4435     Register new_map_reg = ToRegister(instr->new_map_temp());
4436     __ mov(FieldOperand(object_reg, HeapObject::kMapOffset),
4437            Immediate(to_map));
4438     // Write barrier.
4439     DCHECK_NOT_NULL(instr->temp());
4440     __ RecordWriteForMap(object_reg, to_map, new_map_reg,
4441                          ToRegister(instr->temp()),
4442                          kDontSaveFPRegs);
4443   } else {
4444     DCHECK(ToRegister(instr->context()).is(esi));
4445     DCHECK(object_reg.is(eax));
4446     PushSafepointRegistersScope scope(this);
4447     __ mov(ebx, to_map);
4448     bool is_js_array = from_map->instance_type() == JS_ARRAY_TYPE;
4449     TransitionElementsKindStub stub(isolate(), from_kind, to_kind, is_js_array);
4450     __ CallStub(&stub);
4451     RecordSafepointWithLazyDeopt(instr,
4452         RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
4453   }
4454   __ bind(&not_applicable);
4455 }
4456
4457
4458 void LCodeGen::DoStringCharCodeAt(LStringCharCodeAt* instr) {
4459   class DeferredStringCharCodeAt final : public LDeferredCode {
4460    public:
4461     DeferredStringCharCodeAt(LCodeGen* codegen,
4462                              LStringCharCodeAt* instr)
4463         : LDeferredCode(codegen), instr_(instr) { }
4464     void Generate() override { codegen()->DoDeferredStringCharCodeAt(instr_); }
4465     LInstruction* instr() override { return instr_; }
4466
4467    private:
4468     LStringCharCodeAt* instr_;
4469   };
4470
4471   DeferredStringCharCodeAt* deferred =
4472       new(zone()) DeferredStringCharCodeAt(this, instr);
4473
4474   StringCharLoadGenerator::Generate(masm(),
4475                                     factory(),
4476                                     ToRegister(instr->string()),
4477                                     ToRegister(instr->index()),
4478                                     ToRegister(instr->result()),
4479                                     deferred->entry());
4480   __ bind(deferred->exit());
4481 }
4482
4483
4484 void LCodeGen::DoDeferredStringCharCodeAt(LStringCharCodeAt* instr) {
4485   Register string = ToRegister(instr->string());
4486   Register result = ToRegister(instr->result());
4487
4488   // TODO(3095996): Get rid of this. For now, we need to make the
4489   // result register contain a valid pointer because it is already
4490   // contained in the register pointer map.
4491   __ Move(result, Immediate(0));
4492
4493   PushSafepointRegistersScope scope(this);
4494   __ push(string);
4495   // Push the index as a smi. This is safe because of the checks in
4496   // DoStringCharCodeAt above.
4497   STATIC_ASSERT(String::kMaxLength <= Smi::kMaxValue);
4498   if (instr->index()->IsConstantOperand()) {
4499     Immediate immediate = ToImmediate(LConstantOperand::cast(instr->index()),
4500                                       Representation::Smi());
4501     __ push(immediate);
4502   } else {
4503     Register index = ToRegister(instr->index());
4504     __ SmiTag(index);
4505     __ push(index);
4506   }
4507   CallRuntimeFromDeferred(Runtime::kStringCharCodeAtRT, 2,
4508                           instr, instr->context());
4509   __ AssertSmi(eax);
4510   __ SmiUntag(eax);
4511   __ StoreToSafepointRegisterSlot(result, eax);
4512 }
4513
4514
4515 void LCodeGen::DoStringCharFromCode(LStringCharFromCode* instr) {
4516   class DeferredStringCharFromCode final : public LDeferredCode {
4517    public:
4518     DeferredStringCharFromCode(LCodeGen* codegen,
4519                                LStringCharFromCode* instr)
4520         : LDeferredCode(codegen), instr_(instr) { }
4521     void Generate() override {
4522       codegen()->DoDeferredStringCharFromCode(instr_);
4523     }
4524     LInstruction* instr() override { return instr_; }
4525
4526    private:
4527     LStringCharFromCode* instr_;
4528   };
4529
4530   DeferredStringCharFromCode* deferred =
4531       new(zone()) DeferredStringCharFromCode(this, instr);
4532
4533   DCHECK(instr->hydrogen()->value()->representation().IsInteger32());
4534   Register char_code = ToRegister(instr->char_code());
4535   Register result = ToRegister(instr->result());
4536   DCHECK(!char_code.is(result));
4537
4538   __ cmp(char_code, String::kMaxOneByteCharCode);
4539   __ j(above, deferred->entry());
4540   __ Move(result, Immediate(factory()->single_character_string_cache()));
4541   __ mov(result, FieldOperand(result,
4542                               char_code, times_pointer_size,
4543                               FixedArray::kHeaderSize));
4544   __ cmp(result, factory()->undefined_value());
4545   __ j(equal, deferred->entry());
4546   __ bind(deferred->exit());
4547 }
4548
4549
4550 void LCodeGen::DoDeferredStringCharFromCode(LStringCharFromCode* instr) {
4551   Register char_code = ToRegister(instr->char_code());
4552   Register result = ToRegister(instr->result());
4553
4554   // TODO(3095996): Get rid of this. For now, we need to make the
4555   // result register contain a valid pointer because it is already
4556   // contained in the register pointer map.
4557   __ Move(result, Immediate(0));
4558
4559   PushSafepointRegistersScope scope(this);
4560   __ SmiTag(char_code);
4561   __ push(char_code);
4562   CallRuntimeFromDeferred(Runtime::kCharFromCode, 1, instr, instr->context());
4563   __ StoreToSafepointRegisterSlot(result, eax);
4564 }
4565
4566
4567 void LCodeGen::DoStringAdd(LStringAdd* instr) {
4568   DCHECK(ToRegister(instr->context()).is(esi));
4569   DCHECK(ToRegister(instr->left()).is(edx));
4570   DCHECK(ToRegister(instr->right()).is(eax));
4571   StringAddStub stub(isolate(),
4572                      instr->hydrogen()->flags(),
4573                      instr->hydrogen()->pretenure_flag());
4574   CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
4575 }
4576
4577
4578 void LCodeGen::DoInteger32ToDouble(LInteger32ToDouble* instr) {
4579   LOperand* input = instr->value();
4580   LOperand* output = instr->result();
4581   DCHECK(input->IsRegister() || input->IsStackSlot());
4582   DCHECK(output->IsDoubleRegister());
4583   __ Cvtsi2sd(ToDoubleRegister(output), ToOperand(input));
4584 }
4585
4586
4587 void LCodeGen::DoUint32ToDouble(LUint32ToDouble* instr) {
4588   LOperand* input = instr->value();
4589   LOperand* output = instr->result();
4590   __ LoadUint32(ToDoubleRegister(output), ToRegister(input));
4591 }
4592
4593
4594 void LCodeGen::DoNumberTagI(LNumberTagI* instr) {
4595   class DeferredNumberTagI final : public LDeferredCode {
4596    public:
4597     DeferredNumberTagI(LCodeGen* codegen,
4598                        LNumberTagI* instr)
4599         : LDeferredCode(codegen), instr_(instr) { }
4600     void Generate() override {
4601       codegen()->DoDeferredNumberTagIU(
4602           instr_, instr_->value(), instr_->temp(), SIGNED_INT32);
4603     }
4604     LInstruction* instr() override { return instr_; }
4605
4606    private:
4607     LNumberTagI* instr_;
4608   };
4609
4610   LOperand* input = instr->value();
4611   DCHECK(input->IsRegister() && input->Equals(instr->result()));
4612   Register reg = ToRegister(input);
4613
4614   DeferredNumberTagI* deferred =
4615       new(zone()) DeferredNumberTagI(this, instr);
4616   __ SmiTag(reg);
4617   __ j(overflow, deferred->entry());
4618   __ bind(deferred->exit());
4619 }
4620
4621
4622 void LCodeGen::DoNumberTagU(LNumberTagU* instr) {
4623   class DeferredNumberTagU final : public LDeferredCode {
4624    public:
4625     DeferredNumberTagU(LCodeGen* codegen, LNumberTagU* instr)
4626         : LDeferredCode(codegen), instr_(instr) { }
4627     void Generate() override {
4628       codegen()->DoDeferredNumberTagIU(
4629           instr_, instr_->value(), instr_->temp(), UNSIGNED_INT32);
4630     }
4631     LInstruction* instr() override { return instr_; }
4632
4633    private:
4634     LNumberTagU* instr_;
4635   };
4636
4637   LOperand* input = instr->value();
4638   DCHECK(input->IsRegister() && input->Equals(instr->result()));
4639   Register reg = ToRegister(input);
4640
4641   DeferredNumberTagU* deferred =
4642       new(zone()) DeferredNumberTagU(this, instr);
4643   __ cmp(reg, Immediate(Smi::kMaxValue));
4644   __ j(above, deferred->entry());
4645   __ SmiTag(reg);
4646   __ bind(deferred->exit());
4647 }
4648
4649
4650 void LCodeGen::DoDeferredNumberTagIU(LInstruction* instr,
4651                                      LOperand* value,
4652                                      LOperand* temp,
4653                                      IntegerSignedness signedness) {
4654   Label done, slow;
4655   Register reg = ToRegister(value);
4656   Register tmp = ToRegister(temp);
4657   XMMRegister xmm_scratch = double_scratch0();
4658
4659   if (signedness == SIGNED_INT32) {
4660     // There was overflow, so bits 30 and 31 of the original integer
4661     // disagree. Try to allocate a heap number in new space and store
4662     // the value in there. If that fails, call the runtime system.
4663     __ SmiUntag(reg);
4664     __ xor_(reg, 0x80000000);
4665     __ Cvtsi2sd(xmm_scratch, Operand(reg));
4666   } else {
4667     __ LoadUint32(xmm_scratch, reg);
4668   }
4669
4670   if (FLAG_inline_new) {
4671     __ AllocateHeapNumber(reg, tmp, no_reg, &slow);
4672     __ jmp(&done, Label::kNear);
4673   }
4674
4675   // Slow case: Call the runtime system to do the number allocation.
4676   __ bind(&slow);
4677   {
4678     // TODO(3095996): Put a valid pointer value in the stack slot where the
4679     // result register is stored, as this register is in the pointer map, but
4680     // contains an integer value.
4681     __ Move(reg, Immediate(0));
4682
4683     // Preserve the value of all registers.
4684     PushSafepointRegistersScope scope(this);
4685
4686     // NumberTagI and NumberTagD use the context from the frame, rather than
4687     // the environment's HContext or HInlinedContext value.
4688     // They only call Runtime::kAllocateHeapNumber.
4689     // The corresponding HChange instructions are added in a phase that does
4690     // not have easy access to the local context.
4691     __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4692     __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
4693     RecordSafepointWithRegisters(
4694         instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
4695     __ StoreToSafepointRegisterSlot(reg, eax);
4696   }
4697
4698   // Done. Put the value in xmm_scratch into the value of the allocated heap
4699   // number.
4700   __ bind(&done);
4701   __ movsd(FieldOperand(reg, HeapNumber::kValueOffset), xmm_scratch);
4702 }
4703
4704
4705 void LCodeGen::DoNumberTagD(LNumberTagD* instr) {
4706   class DeferredNumberTagD final : public LDeferredCode {
4707    public:
4708     DeferredNumberTagD(LCodeGen* codegen, LNumberTagD* instr)
4709         : LDeferredCode(codegen), instr_(instr) { }
4710     void Generate() override { codegen()->DoDeferredNumberTagD(instr_); }
4711     LInstruction* instr() override { return instr_; }
4712
4713    private:
4714     LNumberTagD* instr_;
4715   };
4716
4717   Register reg = ToRegister(instr->result());
4718
4719   DeferredNumberTagD* deferred =
4720       new(zone()) DeferredNumberTagD(this, instr);
4721   if (FLAG_inline_new) {
4722     Register tmp = ToRegister(instr->temp());
4723     __ AllocateHeapNumber(reg, tmp, no_reg, deferred->entry());
4724   } else {
4725     __ jmp(deferred->entry());
4726   }
4727   __ bind(deferred->exit());
4728   XMMRegister input_reg = ToDoubleRegister(instr->value());
4729   __ movsd(FieldOperand(reg, HeapNumber::kValueOffset), input_reg);
4730 }
4731
4732
4733 void LCodeGen::DoDeferredNumberTagD(LNumberTagD* instr) {
4734   // TODO(3095996): Get rid of this. For now, we need to make the
4735   // result register contain a valid pointer because it is already
4736   // contained in the register pointer map.
4737   Register reg = ToRegister(instr->result());
4738   __ Move(reg, Immediate(0));
4739
4740   PushSafepointRegistersScope scope(this);
4741   // NumberTagI and NumberTagD use the context from the frame, rather than
4742   // the environment's HContext or HInlinedContext value.
4743   // They only call Runtime::kAllocateHeapNumber.
4744   // The corresponding HChange instructions are added in a phase that does
4745   // not have easy access to the local context.
4746   __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4747   __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
4748   RecordSafepointWithRegisters(
4749       instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
4750   __ StoreToSafepointRegisterSlot(reg, eax);
4751 }
4752
4753
4754 void LCodeGen::DoSmiTag(LSmiTag* instr) {
4755   HChange* hchange = instr->hydrogen();
4756   Register input = ToRegister(instr->value());
4757   if (hchange->CheckFlag(HValue::kCanOverflow) &&
4758       hchange->value()->CheckFlag(HValue::kUint32)) {
4759     __ test(input, Immediate(0xc0000000));
4760     DeoptimizeIf(not_zero, instr, Deoptimizer::kOverflow);
4761   }
4762   __ SmiTag(input);
4763   if (hchange->CheckFlag(HValue::kCanOverflow) &&
4764       !hchange->value()->CheckFlag(HValue::kUint32)) {
4765     DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
4766   }
4767 }
4768
4769
4770 void LCodeGen::DoSmiUntag(LSmiUntag* instr) {
4771   LOperand* input = instr->value();
4772   Register result = ToRegister(input);
4773   DCHECK(input->IsRegister() && input->Equals(instr->result()));
4774   if (instr->needs_check()) {
4775     __ test(result, Immediate(kSmiTagMask));
4776     DeoptimizeIf(not_zero, instr, Deoptimizer::kNotASmi);
4777   } else {
4778     __ AssertSmi(result);
4779   }
4780   __ SmiUntag(result);
4781 }
4782
4783
4784 void LCodeGen::EmitNumberUntagD(LNumberUntagD* instr, Register input_reg,
4785                                 Register temp_reg, XMMRegister result_reg,
4786                                 NumberUntagDMode mode) {
4787   bool can_convert_undefined_to_nan =
4788       instr->hydrogen()->can_convert_undefined_to_nan();
4789   bool deoptimize_on_minus_zero = instr->hydrogen()->deoptimize_on_minus_zero();
4790
4791   Label convert, load_smi, done;
4792
4793   if (mode == NUMBER_CANDIDATE_IS_ANY_TAGGED) {
4794     // Smi check.
4795     __ JumpIfSmi(input_reg, &load_smi, Label::kNear);
4796
4797     // Heap number map check.
4798     __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
4799            factory()->heap_number_map());
4800     if (can_convert_undefined_to_nan) {
4801       __ j(not_equal, &convert, Label::kNear);
4802     } else {
4803       DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
4804     }
4805
4806     // Heap number to XMM conversion.
4807     __ movsd(result_reg, FieldOperand(input_reg, HeapNumber::kValueOffset));
4808
4809     if (deoptimize_on_minus_zero) {
4810       XMMRegister xmm_scratch = double_scratch0();
4811       __ xorps(xmm_scratch, xmm_scratch);
4812       __ ucomisd(result_reg, xmm_scratch);
4813       __ j(not_zero, &done, Label::kNear);
4814       __ movmskpd(temp_reg, result_reg);
4815       __ test_b(temp_reg, 1);
4816       DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
4817     }
4818     __ jmp(&done, Label::kNear);
4819
4820     if (can_convert_undefined_to_nan) {
4821       __ bind(&convert);
4822
4823       // Convert undefined to NaN.
4824       __ cmp(input_reg, factory()->undefined_value());
4825       DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumberUndefined);
4826
4827       __ pcmpeqd(result_reg, result_reg);
4828       __ jmp(&done, Label::kNear);
4829     }
4830   } else {
4831     DCHECK(mode == NUMBER_CANDIDATE_IS_SMI);
4832   }
4833
4834   __ bind(&load_smi);
4835   // Smi to XMM conversion. Clobbering a temp is faster than re-tagging the
4836   // input register since we avoid dependencies.
4837   __ mov(temp_reg, input_reg);
4838   __ SmiUntag(temp_reg);  // Untag smi before converting to float.
4839   __ Cvtsi2sd(result_reg, Operand(temp_reg));
4840   __ bind(&done);
4841 }
4842
4843
4844 void LCodeGen::DoDeferredTaggedToI(LTaggedToI* instr, Label* done) {
4845   Register input_reg = ToRegister(instr->value());
4846
4847   // The input was optimistically untagged; revert it.
4848   STATIC_ASSERT(kSmiTagSize == 1);
4849   __ lea(input_reg, Operand(input_reg, times_2, kHeapObjectTag));
4850
4851   if (instr->truncating()) {
4852     Label no_heap_number, check_bools, check_false;
4853
4854     // Heap number map check.
4855     __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
4856            factory()->heap_number_map());
4857     __ j(not_equal, &no_heap_number, Label::kNear);
4858     __ TruncateHeapNumberToI(input_reg, input_reg);
4859     __ jmp(done);
4860
4861     __ bind(&no_heap_number);
4862     // Check for Oddballs. Undefined/False is converted to zero and True to one
4863     // for truncating conversions.
4864     __ cmp(input_reg, factory()->undefined_value());
4865     __ j(not_equal, &check_bools, Label::kNear);
4866     __ Move(input_reg, Immediate(0));
4867     __ jmp(done);
4868
4869     __ bind(&check_bools);
4870     __ cmp(input_reg, factory()->true_value());
4871     __ j(not_equal, &check_false, Label::kNear);
4872     __ Move(input_reg, Immediate(1));
4873     __ jmp(done);
4874
4875     __ bind(&check_false);
4876     __ cmp(input_reg, factory()->false_value());
4877     DeoptimizeIf(not_equal, instr,
4878                  Deoptimizer::kNotAHeapNumberUndefinedBoolean);
4879     __ Move(input_reg, Immediate(0));
4880   } else {
4881     XMMRegister scratch = ToDoubleRegister(instr->temp());
4882     DCHECK(!scratch.is(xmm0));
4883     __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
4884            isolate()->factory()->heap_number_map());
4885     DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
4886     __ movsd(xmm0, FieldOperand(input_reg, HeapNumber::kValueOffset));
4887     __ cvttsd2si(input_reg, Operand(xmm0));
4888     __ Cvtsi2sd(scratch, Operand(input_reg));
4889     __ ucomisd(xmm0, scratch);
4890     DeoptimizeIf(not_equal, instr, Deoptimizer::kLostPrecision);
4891     DeoptimizeIf(parity_even, instr, Deoptimizer::kNaN);
4892     if (instr->hydrogen()->GetMinusZeroMode() == FAIL_ON_MINUS_ZERO) {
4893       __ test(input_reg, Operand(input_reg));
4894       __ j(not_zero, done);
4895       __ movmskpd(input_reg, xmm0);
4896       __ and_(input_reg, 1);
4897       DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
4898     }
4899   }
4900 }
4901
4902
4903 void LCodeGen::DoTaggedToI(LTaggedToI* instr) {
4904   class DeferredTaggedToI final : public LDeferredCode {
4905    public:
4906     DeferredTaggedToI(LCodeGen* codegen, LTaggedToI* instr)
4907         : LDeferredCode(codegen), instr_(instr) { }
4908     void Generate() override { codegen()->DoDeferredTaggedToI(instr_, done()); }
4909     LInstruction* instr() override { return instr_; }
4910
4911    private:
4912     LTaggedToI* instr_;
4913   };
4914
4915   LOperand* input = instr->value();
4916   DCHECK(input->IsRegister());
4917   Register input_reg = ToRegister(input);
4918   DCHECK(input_reg.is(ToRegister(instr->result())));
4919
4920   if (instr->hydrogen()->value()->representation().IsSmi()) {
4921     __ SmiUntag(input_reg);
4922   } else {
4923     DeferredTaggedToI* deferred =
4924         new(zone()) DeferredTaggedToI(this, instr);
4925     // Optimistically untag the input.
4926     // If the input is a HeapObject, SmiUntag will set the carry flag.
4927     STATIC_ASSERT(kSmiTagSize == 1 && kSmiTag == 0);
4928     __ SmiUntag(input_reg);
4929     // Branch to deferred code if the input was tagged.
4930     // The deferred code will take care of restoring the tag.
4931     __ j(carry, deferred->entry());
4932     __ bind(deferred->exit());
4933   }
4934 }
4935
4936
4937 void LCodeGen::DoNumberUntagD(LNumberUntagD* instr) {
4938   LOperand* input = instr->value();
4939   DCHECK(input->IsRegister());
4940   LOperand* temp = instr->temp();
4941   DCHECK(temp->IsRegister());
4942   LOperand* result = instr->result();
4943   DCHECK(result->IsDoubleRegister());
4944
4945   Register input_reg = ToRegister(input);
4946   Register temp_reg = ToRegister(temp);
4947
4948   HValue* value = instr->hydrogen()->value();
4949   NumberUntagDMode mode = value->representation().IsSmi()
4950       ? NUMBER_CANDIDATE_IS_SMI : NUMBER_CANDIDATE_IS_ANY_TAGGED;
4951
4952   XMMRegister result_reg = ToDoubleRegister(result);
4953   EmitNumberUntagD(instr, input_reg, temp_reg, result_reg, mode);
4954 }
4955
4956
4957 void LCodeGen::DoDoubleToI(LDoubleToI* instr) {
4958   LOperand* input = instr->value();
4959   DCHECK(input->IsDoubleRegister());
4960   LOperand* result = instr->result();
4961   DCHECK(result->IsRegister());
4962   Register result_reg = ToRegister(result);
4963
4964   if (instr->truncating()) {
4965     XMMRegister input_reg = ToDoubleRegister(input);
4966     __ TruncateDoubleToI(result_reg, input_reg);
4967   } else {
4968     Label lost_precision, is_nan, minus_zero, done;
4969     XMMRegister input_reg = ToDoubleRegister(input);
4970     XMMRegister xmm_scratch = double_scratch0();
4971     Label::Distance dist = DeoptEveryNTimes() ? Label::kFar : Label::kNear;
4972     __ DoubleToI(result_reg, input_reg, xmm_scratch,
4973                  instr->hydrogen()->GetMinusZeroMode(), &lost_precision,
4974                  &is_nan, &minus_zero, dist);
4975     __ jmp(&done, dist);
4976     __ bind(&lost_precision);
4977     DeoptimizeIf(no_condition, instr, Deoptimizer::kLostPrecision);
4978     __ bind(&is_nan);
4979     DeoptimizeIf(no_condition, instr, Deoptimizer::kNaN);
4980     __ bind(&minus_zero);
4981     DeoptimizeIf(no_condition, instr, Deoptimizer::kMinusZero);
4982     __ bind(&done);
4983   }
4984 }
4985
4986
4987 void LCodeGen::DoDoubleToSmi(LDoubleToSmi* instr) {
4988   LOperand* input = instr->value();
4989   DCHECK(input->IsDoubleRegister());
4990   LOperand* result = instr->result();
4991   DCHECK(result->IsRegister());
4992   Register result_reg = ToRegister(result);
4993
4994   Label lost_precision, is_nan, minus_zero, done;
4995   XMMRegister input_reg = ToDoubleRegister(input);
4996   XMMRegister xmm_scratch = double_scratch0();
4997   Label::Distance dist = DeoptEveryNTimes() ? Label::kFar : Label::kNear;
4998   __ DoubleToI(result_reg, input_reg, xmm_scratch,
4999                instr->hydrogen()->GetMinusZeroMode(), &lost_precision, &is_nan,
5000                &minus_zero, dist);
5001   __ jmp(&done, dist);
5002   __ bind(&lost_precision);
5003   DeoptimizeIf(no_condition, instr, Deoptimizer::kLostPrecision);
5004   __ bind(&is_nan);
5005   DeoptimizeIf(no_condition, instr, Deoptimizer::kNaN);
5006   __ bind(&minus_zero);
5007   DeoptimizeIf(no_condition, instr, Deoptimizer::kMinusZero);
5008   __ bind(&done);
5009   __ SmiTag(result_reg);
5010   DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
5011 }
5012
5013
5014 void LCodeGen::DoCheckSmi(LCheckSmi* instr) {
5015   LOperand* input = instr->value();
5016   __ test(ToOperand(input), Immediate(kSmiTagMask));
5017   DeoptimizeIf(not_zero, instr, Deoptimizer::kNotASmi);
5018 }
5019
5020
5021 void LCodeGen::DoCheckNonSmi(LCheckNonSmi* instr) {
5022   if (!instr->hydrogen()->value()->type().IsHeapObject()) {
5023     LOperand* input = instr->value();
5024     __ test(ToOperand(input), Immediate(kSmiTagMask));
5025     DeoptimizeIf(zero, instr, Deoptimizer::kSmi);
5026   }
5027 }
5028
5029
5030 void LCodeGen::DoCheckArrayBufferNotNeutered(
5031     LCheckArrayBufferNotNeutered* instr) {
5032   Register view = ToRegister(instr->view());
5033   Register scratch = ToRegister(instr->scratch());
5034
5035   __ mov(scratch, FieldOperand(view, JSArrayBufferView::kBufferOffset));
5036   __ test_b(FieldOperand(scratch, JSArrayBuffer::kBitFieldOffset),
5037             1 << JSArrayBuffer::WasNeutered::kShift);
5038   DeoptimizeIf(not_zero, instr, Deoptimizer::kOutOfBounds);
5039 }
5040
5041
5042 void LCodeGen::DoCheckInstanceType(LCheckInstanceType* instr) {
5043   Register input = ToRegister(instr->value());
5044   Register temp = ToRegister(instr->temp());
5045
5046   __ mov(temp, FieldOperand(input, HeapObject::kMapOffset));
5047
5048   if (instr->hydrogen()->is_interval_check()) {
5049     InstanceType first;
5050     InstanceType last;
5051     instr->hydrogen()->GetCheckInterval(&first, &last);
5052
5053     __ cmpb(FieldOperand(temp, Map::kInstanceTypeOffset),
5054             static_cast<int8_t>(first));
5055
5056     // If there is only one type in the interval check for equality.
5057     if (first == last) {
5058       DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongInstanceType);
5059     } else {
5060       DeoptimizeIf(below, instr, Deoptimizer::kWrongInstanceType);
5061       // Omit check for the last type.
5062       if (last != LAST_TYPE) {
5063         __ cmpb(FieldOperand(temp, Map::kInstanceTypeOffset),
5064                 static_cast<int8_t>(last));
5065         DeoptimizeIf(above, instr, Deoptimizer::kWrongInstanceType);
5066       }
5067     }
5068   } else {
5069     uint8_t mask;
5070     uint8_t tag;
5071     instr->hydrogen()->GetCheckMaskAndTag(&mask, &tag);
5072
5073     if (base::bits::IsPowerOfTwo32(mask)) {
5074       DCHECK(tag == 0 || base::bits::IsPowerOfTwo32(tag));
5075       __ test_b(FieldOperand(temp, Map::kInstanceTypeOffset), mask);
5076       DeoptimizeIf(tag == 0 ? not_zero : zero, instr,
5077                    Deoptimizer::kWrongInstanceType);
5078     } else {
5079       __ movzx_b(temp, FieldOperand(temp, Map::kInstanceTypeOffset));
5080       __ and_(temp, mask);
5081       __ cmp(temp, tag);
5082       DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongInstanceType);
5083     }
5084   }
5085 }
5086
5087
5088 void LCodeGen::DoCheckValue(LCheckValue* instr) {
5089   Handle<HeapObject> object = instr->hydrogen()->object().handle();
5090   if (instr->hydrogen()->object_in_new_space()) {
5091     Register reg = ToRegister(instr->value());
5092     Handle<Cell> cell = isolate()->factory()->NewCell(object);
5093     __ cmp(reg, Operand::ForCell(cell));
5094   } else {
5095     Operand operand = ToOperand(instr->value());
5096     __ cmp(operand, object);
5097   }
5098   DeoptimizeIf(not_equal, instr, Deoptimizer::kValueMismatch);
5099 }
5100
5101
5102 void LCodeGen::DoDeferredInstanceMigration(LCheckMaps* instr, Register object) {
5103   {
5104     PushSafepointRegistersScope scope(this);
5105     __ push(object);
5106     __ xor_(esi, esi);
5107     __ CallRuntimeSaveDoubles(Runtime::kTryMigrateInstance);
5108     RecordSafepointWithRegisters(
5109         instr->pointer_map(), 1, Safepoint::kNoLazyDeopt);
5110
5111     __ test(eax, Immediate(kSmiTagMask));
5112   }
5113   DeoptimizeIf(zero, instr, Deoptimizer::kInstanceMigrationFailed);
5114 }
5115
5116
5117 void LCodeGen::DoCheckMaps(LCheckMaps* instr) {
5118   class DeferredCheckMaps final : public LDeferredCode {
5119    public:
5120     DeferredCheckMaps(LCodeGen* codegen, LCheckMaps* instr,  Register object)
5121         : LDeferredCode(codegen), instr_(instr), object_(object) {
5122       SetExit(check_maps());
5123     }
5124     void Generate() override {
5125       codegen()->DoDeferredInstanceMigration(instr_, object_);
5126     }
5127     Label* check_maps() { return &check_maps_; }
5128     LInstruction* instr() override { return instr_; }
5129
5130    private:
5131     LCheckMaps* instr_;
5132     Label check_maps_;
5133     Register object_;
5134   };
5135
5136   if (instr->hydrogen()->IsStabilityCheck()) {
5137     const UniqueSet<Map>* maps = instr->hydrogen()->maps();
5138     for (int i = 0; i < maps->size(); ++i) {
5139       AddStabilityDependency(maps->at(i).handle());
5140     }
5141     return;
5142   }
5143
5144   LOperand* input = instr->value();
5145   DCHECK(input->IsRegister());
5146   Register reg = ToRegister(input);
5147
5148   DeferredCheckMaps* deferred = NULL;
5149   if (instr->hydrogen()->HasMigrationTarget()) {
5150     deferred = new(zone()) DeferredCheckMaps(this, instr, reg);
5151     __ bind(deferred->check_maps());
5152   }
5153
5154   const UniqueSet<Map>* maps = instr->hydrogen()->maps();
5155   Label success;
5156   for (int i = 0; i < maps->size() - 1; i++) {
5157     Handle<Map> map = maps->at(i).handle();
5158     __ CompareMap(reg, map);
5159     __ j(equal, &success, Label::kNear);
5160   }
5161
5162   Handle<Map> map = maps->at(maps->size() - 1).handle();
5163   __ CompareMap(reg, map);
5164   if (instr->hydrogen()->HasMigrationTarget()) {
5165     __ j(not_equal, deferred->entry());
5166   } else {
5167     DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongMap);
5168   }
5169
5170   __ bind(&success);
5171 }
5172
5173
5174 void LCodeGen::DoClampDToUint8(LClampDToUint8* instr) {
5175   XMMRegister value_reg = ToDoubleRegister(instr->unclamped());
5176   XMMRegister xmm_scratch = double_scratch0();
5177   Register result_reg = ToRegister(instr->result());
5178   __ ClampDoubleToUint8(value_reg, xmm_scratch, result_reg);
5179 }
5180
5181
5182 void LCodeGen::DoClampIToUint8(LClampIToUint8* instr) {
5183   DCHECK(instr->unclamped()->Equals(instr->result()));
5184   Register value_reg = ToRegister(instr->result());
5185   __ ClampUint8(value_reg);
5186 }
5187
5188
5189 void LCodeGen::DoClampTToUint8(LClampTToUint8* instr) {
5190   DCHECK(instr->unclamped()->Equals(instr->result()));
5191   Register input_reg = ToRegister(instr->unclamped());
5192   XMMRegister temp_xmm_reg = ToDoubleRegister(instr->temp_xmm());
5193   XMMRegister xmm_scratch = double_scratch0();
5194   Label is_smi, done, heap_number;
5195
5196   __ JumpIfSmi(input_reg, &is_smi);
5197
5198   // Check for heap number
5199   __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
5200          factory()->heap_number_map());
5201   __ j(equal, &heap_number, Label::kNear);
5202
5203   // Check for undefined. Undefined is converted to zero for clamping
5204   // conversions.
5205   __ cmp(input_reg, factory()->undefined_value());
5206   DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumberUndefined);
5207   __ mov(input_reg, 0);
5208   __ jmp(&done, Label::kNear);
5209
5210   // Heap number
5211   __ bind(&heap_number);
5212   __ movsd(xmm_scratch, FieldOperand(input_reg, HeapNumber::kValueOffset));
5213   __ ClampDoubleToUint8(xmm_scratch, temp_xmm_reg, input_reg);
5214   __ jmp(&done, Label::kNear);
5215
5216   // smi
5217   __ bind(&is_smi);
5218   __ SmiUntag(input_reg);
5219   __ ClampUint8(input_reg);
5220   __ bind(&done);
5221 }
5222
5223
5224 void LCodeGen::DoDoubleBits(LDoubleBits* instr) {
5225   XMMRegister value_reg = ToDoubleRegister(instr->value());
5226   Register result_reg = ToRegister(instr->result());
5227   if (instr->hydrogen()->bits() == HDoubleBits::HIGH) {
5228     if (CpuFeatures::IsSupported(SSE4_1)) {
5229       CpuFeatureScope scope2(masm(), SSE4_1);
5230       __ pextrd(result_reg, value_reg, 1);
5231     } else {
5232       XMMRegister xmm_scratch = double_scratch0();
5233       __ pshufd(xmm_scratch, value_reg, 1);
5234       __ movd(result_reg, xmm_scratch);
5235     }
5236   } else {
5237     __ movd(result_reg, value_reg);
5238   }
5239 }
5240
5241
5242 void LCodeGen::DoConstructDouble(LConstructDouble* instr) {
5243   Register hi_reg = ToRegister(instr->hi());
5244   Register lo_reg = ToRegister(instr->lo());
5245   XMMRegister result_reg = ToDoubleRegister(instr->result());
5246
5247   if (CpuFeatures::IsSupported(SSE4_1)) {
5248     CpuFeatureScope scope2(masm(), SSE4_1);
5249     __ movd(result_reg, lo_reg);
5250     __ pinsrd(result_reg, hi_reg, 1);
5251   } else {
5252     XMMRegister xmm_scratch = double_scratch0();
5253     __ movd(result_reg, hi_reg);
5254     __ psllq(result_reg, 32);
5255     __ movd(xmm_scratch, lo_reg);
5256     __ orps(result_reg, xmm_scratch);
5257   }
5258 }
5259
5260
5261 void LCodeGen::DoAllocate(LAllocate* instr) {
5262   class DeferredAllocate final : public LDeferredCode {
5263    public:
5264     DeferredAllocate(LCodeGen* codegen,  LAllocate* instr)
5265         : LDeferredCode(codegen), instr_(instr) { }
5266     void Generate() override { codegen()->DoDeferredAllocate(instr_); }
5267     LInstruction* instr() override { return instr_; }
5268
5269    private:
5270     LAllocate* instr_;
5271   };
5272
5273   DeferredAllocate* deferred = new(zone()) DeferredAllocate(this, instr);
5274
5275   Register result = ToRegister(instr->result());
5276   Register temp = ToRegister(instr->temp());
5277
5278   // Allocate memory for the object.
5279   AllocationFlags flags = TAG_OBJECT;
5280   if (instr->hydrogen()->MustAllocateDoubleAligned()) {
5281     flags = static_cast<AllocationFlags>(flags | DOUBLE_ALIGNMENT);
5282   }
5283   if (instr->hydrogen()->IsOldSpaceAllocation()) {
5284     DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
5285     flags = static_cast<AllocationFlags>(flags | PRETENURE);
5286   }
5287
5288   if (instr->size()->IsConstantOperand()) {
5289     int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
5290     if (size <= Page::kMaxRegularHeapObjectSize) {
5291       __ Allocate(size, result, temp, no_reg, deferred->entry(), flags);
5292     } else {
5293       __ jmp(deferred->entry());
5294     }
5295   } else {
5296     Register size = ToRegister(instr->size());
5297     __ Allocate(size, result, temp, no_reg, deferred->entry(), flags);
5298   }
5299
5300   __ bind(deferred->exit());
5301
5302   if (instr->hydrogen()->MustPrefillWithFiller()) {
5303     if (instr->size()->IsConstantOperand()) {
5304       int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
5305       __ mov(temp, (size / kPointerSize) - 1);
5306     } else {
5307       temp = ToRegister(instr->size());
5308       __ shr(temp, kPointerSizeLog2);
5309       __ dec(temp);
5310     }
5311     Label loop;
5312     __ bind(&loop);
5313     __ mov(FieldOperand(result, temp, times_pointer_size, 0),
5314         isolate()->factory()->one_pointer_filler_map());
5315     __ dec(temp);
5316     __ j(not_zero, &loop);
5317   }
5318 }
5319
5320
5321 void LCodeGen::DoDeferredAllocate(LAllocate* instr) {
5322   Register result = ToRegister(instr->result());
5323
5324   // TODO(3095996): Get rid of this. For now, we need to make the
5325   // result register contain a valid pointer because it is already
5326   // contained in the register pointer map.
5327   __ Move(result, Immediate(Smi::FromInt(0)));
5328
5329   PushSafepointRegistersScope scope(this);
5330   if (instr->size()->IsRegister()) {
5331     Register size = ToRegister(instr->size());
5332     DCHECK(!size.is(result));
5333     __ SmiTag(ToRegister(instr->size()));
5334     __ push(size);
5335   } else {
5336     int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
5337     if (size >= 0 && size <= Smi::kMaxValue) {
5338       __ push(Immediate(Smi::FromInt(size)));
5339     } else {
5340       // We should never get here at runtime => abort
5341       __ int3();
5342       return;
5343     }
5344   }
5345
5346   int flags = AllocateDoubleAlignFlag::encode(
5347       instr->hydrogen()->MustAllocateDoubleAligned());
5348   if (instr->hydrogen()->IsOldSpaceAllocation()) {
5349     DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
5350     flags = AllocateTargetSpace::update(flags, OLD_SPACE);
5351   } else {
5352     flags = AllocateTargetSpace::update(flags, NEW_SPACE);
5353   }
5354   __ push(Immediate(Smi::FromInt(flags)));
5355
5356   CallRuntimeFromDeferred(
5357       Runtime::kAllocateInTargetSpace, 2, instr, instr->context());
5358   __ StoreToSafepointRegisterSlot(result, eax);
5359 }
5360
5361
5362 void LCodeGen::DoToFastProperties(LToFastProperties* instr) {
5363   DCHECK(ToRegister(instr->value()).is(eax));
5364   __ push(eax);
5365   CallRuntime(Runtime::kToFastProperties, 1, instr);
5366 }
5367
5368
5369 void LCodeGen::DoRegExpLiteral(LRegExpLiteral* instr) {
5370   DCHECK(ToRegister(instr->context()).is(esi));
5371   Label materialized;
5372   // Registers will be used as follows:
5373   // ecx = literals array.
5374   // ebx = regexp literal.
5375   // eax = regexp literal clone.
5376   // esi = context.
5377   int literal_offset =
5378       FixedArray::OffsetOfElementAt(instr->hydrogen()->literal_index());
5379   __ LoadHeapObject(ecx, instr->hydrogen()->literals());
5380   __ mov(ebx, FieldOperand(ecx, literal_offset));
5381   __ cmp(ebx, factory()->undefined_value());
5382   __ j(not_equal, &materialized, Label::kNear);
5383
5384   // Create regexp literal using runtime function
5385   // Result will be in eax.
5386   __ push(ecx);
5387   __ push(Immediate(Smi::FromInt(instr->hydrogen()->literal_index())));
5388   __ push(Immediate(instr->hydrogen()->pattern()));
5389   __ push(Immediate(instr->hydrogen()->flags()));
5390   CallRuntime(Runtime::kMaterializeRegExpLiteral, 4, instr);
5391   __ mov(ebx, eax);
5392
5393   __ bind(&materialized);
5394   int size = JSRegExp::kSize + JSRegExp::kInObjectFieldCount * kPointerSize;
5395   Label allocated, runtime_allocate;
5396   __ Allocate(size, eax, ecx, edx, &runtime_allocate, TAG_OBJECT);
5397   __ jmp(&allocated, Label::kNear);
5398
5399   __ bind(&runtime_allocate);
5400   __ push(ebx);
5401   __ push(Immediate(Smi::FromInt(size)));
5402   CallRuntime(Runtime::kAllocateInNewSpace, 1, instr);
5403   __ pop(ebx);
5404
5405   __ bind(&allocated);
5406   // Copy the content into the newly allocated memory.
5407   // (Unroll copy loop once for better throughput).
5408   for (int i = 0; i < size - kPointerSize; i += 2 * kPointerSize) {
5409     __ mov(edx, FieldOperand(ebx, i));
5410     __ mov(ecx, FieldOperand(ebx, i + kPointerSize));
5411     __ mov(FieldOperand(eax, i), edx);
5412     __ mov(FieldOperand(eax, i + kPointerSize), ecx);
5413   }
5414   if ((size % (2 * kPointerSize)) != 0) {
5415     __ mov(edx, FieldOperand(ebx, size - kPointerSize));
5416     __ mov(FieldOperand(eax, size - kPointerSize), edx);
5417   }
5418 }
5419
5420
5421 void LCodeGen::DoFunctionLiteral(LFunctionLiteral* instr) {
5422   DCHECK(ToRegister(instr->context()).is(esi));
5423   // Use the fast case closure allocation code that allocates in new
5424   // space for nested functions that don't need literals cloning.
5425   bool pretenure = instr->hydrogen()->pretenure();
5426   if (!pretenure && instr->hydrogen()->has_no_literals()) {
5427     FastNewClosureStub stub(isolate(), instr->hydrogen()->language_mode(),
5428                             instr->hydrogen()->kind());
5429     __ mov(ebx, Immediate(instr->hydrogen()->shared_info()));
5430     CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
5431   } else {
5432     __ push(esi);
5433     __ push(Immediate(instr->hydrogen()->shared_info()));
5434     __ push(Immediate(pretenure ? factory()->true_value()
5435                                 : factory()->false_value()));
5436     CallRuntime(Runtime::kNewClosure, 3, instr);
5437   }
5438 }
5439
5440
5441 void LCodeGen::DoTypeof(LTypeof* instr) {
5442   DCHECK(ToRegister(instr->context()).is(esi));
5443   DCHECK(ToRegister(instr->value()).is(ebx));
5444   Label end, do_call;
5445   Register value_register = ToRegister(instr->value());
5446   __ JumpIfNotSmi(value_register, &do_call);
5447   __ mov(eax, Immediate(isolate()->factory()->number_string()));
5448   __ jmp(&end);
5449   __ bind(&do_call);
5450   TypeofStub stub(isolate());
5451   CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
5452   __ bind(&end);
5453 }
5454
5455
5456 void LCodeGen::DoTypeofIsAndBranch(LTypeofIsAndBranch* instr) {
5457   Register input = ToRegister(instr->value());
5458   Condition final_branch_condition = EmitTypeofIs(instr, input);
5459   if (final_branch_condition != no_condition) {
5460     EmitBranch(instr, final_branch_condition);
5461   }
5462 }
5463
5464
5465 Condition LCodeGen::EmitTypeofIs(LTypeofIsAndBranch* instr, Register input) {
5466   Label* true_label = instr->TrueLabel(chunk_);
5467   Label* false_label = instr->FalseLabel(chunk_);
5468   Handle<String> type_name = instr->type_literal();
5469   int left_block = instr->TrueDestination(chunk_);
5470   int right_block = instr->FalseDestination(chunk_);
5471   int next_block = GetNextEmittedBlock();
5472
5473   Label::Distance true_distance = left_block == next_block ? Label::kNear
5474                                                            : Label::kFar;
5475   Label::Distance false_distance = right_block == next_block ? Label::kNear
5476                                                              : Label::kFar;
5477   Condition final_branch_condition = no_condition;
5478   if (String::Equals(type_name, factory()->number_string())) {
5479     __ JumpIfSmi(input, true_label, true_distance);
5480     __ cmp(FieldOperand(input, HeapObject::kMapOffset),
5481            factory()->heap_number_map());
5482     final_branch_condition = equal;
5483
5484   } else if (String::Equals(type_name, factory()->string_string())) {
5485     __ JumpIfSmi(input, false_label, false_distance);
5486     __ CmpObjectType(input, FIRST_NONSTRING_TYPE, input);
5487     __ j(above_equal, false_label, false_distance);
5488     __ test_b(FieldOperand(input, Map::kBitFieldOffset),
5489               1 << Map::kIsUndetectable);
5490     final_branch_condition = zero;
5491
5492   } else if (String::Equals(type_name, factory()->symbol_string())) {
5493     __ JumpIfSmi(input, false_label, false_distance);
5494     __ CmpObjectType(input, SYMBOL_TYPE, input);
5495     final_branch_condition = equal;
5496
5497   } else if (String::Equals(type_name, factory()->boolean_string())) {
5498     __ cmp(input, factory()->true_value());
5499     __ j(equal, true_label, true_distance);
5500     __ cmp(input, factory()->false_value());
5501     final_branch_condition = equal;
5502
5503   } else if (String::Equals(type_name, factory()->undefined_string())) {
5504     __ cmp(input, factory()->undefined_value());
5505     __ j(equal, true_label, true_distance);
5506     __ JumpIfSmi(input, false_label, false_distance);
5507     // Check for undetectable objects => true.
5508     __ mov(input, FieldOperand(input, HeapObject::kMapOffset));
5509     __ test_b(FieldOperand(input, Map::kBitFieldOffset),
5510               1 << Map::kIsUndetectable);
5511     final_branch_condition = not_zero;
5512
5513   } else if (String::Equals(type_name, factory()->function_string())) {
5514     STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
5515     __ JumpIfSmi(input, false_label, false_distance);
5516     __ CmpObjectType(input, JS_FUNCTION_TYPE, input);
5517     __ j(equal, true_label, true_distance);
5518     __ CmpInstanceType(input, JS_FUNCTION_PROXY_TYPE);
5519     final_branch_condition = equal;
5520
5521   } else if (String::Equals(type_name, factory()->object_string())) {
5522     __ JumpIfSmi(input, false_label, false_distance);
5523     __ cmp(input, factory()->null_value());
5524     __ j(equal, true_label, true_distance);
5525     __ CmpObjectType(input, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE, input);
5526     __ j(below, false_label, false_distance);
5527     __ CmpInstanceType(input, LAST_NONCALLABLE_SPEC_OBJECT_TYPE);
5528     __ j(above, false_label, false_distance);
5529     // Check for undetectable objects => false.
5530     __ test_b(FieldOperand(input, Map::kBitFieldOffset),
5531               1 << Map::kIsUndetectable);
5532     final_branch_condition = zero;
5533
5534   } else {
5535     __ jmp(false_label, false_distance);
5536   }
5537   return final_branch_condition;
5538 }
5539
5540
5541 void LCodeGen::DoIsConstructCallAndBranch(LIsConstructCallAndBranch* instr) {
5542   Register temp = ToRegister(instr->temp());
5543
5544   EmitIsConstructCall(temp);
5545   EmitBranch(instr, equal);
5546 }
5547
5548
5549 void LCodeGen::EmitIsConstructCall(Register temp) {
5550   // Get the frame pointer for the calling frame.
5551   __ mov(temp, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
5552
5553   // Skip the arguments adaptor frame if it exists.
5554   Label check_frame_marker;
5555   __ cmp(Operand(temp, StandardFrameConstants::kContextOffset),
5556          Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
5557   __ j(not_equal, &check_frame_marker, Label::kNear);
5558   __ mov(temp, Operand(temp, StandardFrameConstants::kCallerFPOffset));
5559
5560   // Check the marker in the calling frame.
5561   __ bind(&check_frame_marker);
5562   __ cmp(Operand(temp, StandardFrameConstants::kMarkerOffset),
5563          Immediate(Smi::FromInt(StackFrame::CONSTRUCT)));
5564 }
5565
5566
5567 void LCodeGen::EnsureSpaceForLazyDeopt(int space_needed) {
5568   if (!info()->IsStub()) {
5569     // Ensure that we have enough space after the previous lazy-bailout
5570     // instruction for patching the code here.
5571     int current_pc = masm()->pc_offset();
5572     if (current_pc < last_lazy_deopt_pc_ + space_needed) {
5573       int padding_size = last_lazy_deopt_pc_ + space_needed - current_pc;
5574       __ Nop(padding_size);
5575     }
5576   }
5577   last_lazy_deopt_pc_ = masm()->pc_offset();
5578 }
5579
5580
5581 void LCodeGen::DoLazyBailout(LLazyBailout* instr) {
5582   last_lazy_deopt_pc_ = masm()->pc_offset();
5583   DCHECK(instr->HasEnvironment());
5584   LEnvironment* env = instr->environment();
5585   RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt);
5586   safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
5587 }
5588
5589
5590 void LCodeGen::DoDeoptimize(LDeoptimize* instr) {
5591   Deoptimizer::BailoutType type = instr->hydrogen()->type();
5592   // TODO(danno): Stubs expect all deopts to be lazy for historical reasons (the
5593   // needed return address), even though the implementation of LAZY and EAGER is
5594   // now identical. When LAZY is eventually completely folded into EAGER, remove
5595   // the special case below.
5596   if (info()->IsStub() && type == Deoptimizer::EAGER) {
5597     type = Deoptimizer::LAZY;
5598   }
5599   DeoptimizeIf(no_condition, instr, instr->hydrogen()->reason(), type);
5600 }
5601
5602
5603 void LCodeGen::DoDummy(LDummy* instr) {
5604   // Nothing to see here, move on!
5605 }
5606
5607
5608 void LCodeGen::DoDummyUse(LDummyUse* instr) {
5609   // Nothing to see here, move on!
5610 }
5611
5612
5613 void LCodeGen::DoDeferredStackCheck(LStackCheck* instr) {
5614   PushSafepointRegistersScope scope(this);
5615   __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
5616   __ CallRuntimeSaveDoubles(Runtime::kStackGuard);
5617   RecordSafepointWithLazyDeopt(
5618       instr, RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
5619   DCHECK(instr->HasEnvironment());
5620   LEnvironment* env = instr->environment();
5621   safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
5622 }
5623
5624
5625 void LCodeGen::DoStackCheck(LStackCheck* instr) {
5626   class DeferredStackCheck final : public LDeferredCode {
5627    public:
5628     DeferredStackCheck(LCodeGen* codegen, LStackCheck* instr)
5629         : LDeferredCode(codegen), instr_(instr) { }
5630     void Generate() override { codegen()->DoDeferredStackCheck(instr_); }
5631     LInstruction* instr() override { return instr_; }
5632
5633    private:
5634     LStackCheck* instr_;
5635   };
5636
5637   DCHECK(instr->HasEnvironment());
5638   LEnvironment* env = instr->environment();
5639   // There is no LLazyBailout instruction for stack-checks. We have to
5640   // prepare for lazy deoptimization explicitly here.
5641   if (instr->hydrogen()->is_function_entry()) {
5642     // Perform stack overflow check.
5643     Label done;
5644     ExternalReference stack_limit =
5645         ExternalReference::address_of_stack_limit(isolate());
5646     __ cmp(esp, Operand::StaticVariable(stack_limit));
5647     __ j(above_equal, &done, Label::kNear);
5648
5649     DCHECK(instr->context()->IsRegister());
5650     DCHECK(ToRegister(instr->context()).is(esi));
5651     CallCode(isolate()->builtins()->StackCheck(),
5652              RelocInfo::CODE_TARGET,
5653              instr);
5654     __ bind(&done);
5655   } else {
5656     DCHECK(instr->hydrogen()->is_backwards_branch());
5657     // Perform stack overflow check if this goto needs it before jumping.
5658     DeferredStackCheck* deferred_stack_check =
5659         new(zone()) DeferredStackCheck(this, instr);
5660     ExternalReference stack_limit =
5661         ExternalReference::address_of_stack_limit(isolate());
5662     __ cmp(esp, Operand::StaticVariable(stack_limit));
5663     __ j(below, deferred_stack_check->entry());
5664     EnsureSpaceForLazyDeopt(Deoptimizer::patch_size());
5665     __ bind(instr->done_label());
5666     deferred_stack_check->SetExit(instr->done_label());
5667     RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt);
5668     // Don't record a deoptimization index for the safepoint here.
5669     // This will be done explicitly when emitting call and the safepoint in
5670     // the deferred code.
5671   }
5672 }
5673
5674
5675 void LCodeGen::DoOsrEntry(LOsrEntry* instr) {
5676   // This is a pseudo-instruction that ensures that the environment here is
5677   // properly registered for deoptimization and records the assembler's PC
5678   // offset.
5679   LEnvironment* environment = instr->environment();
5680
5681   // If the environment were already registered, we would have no way of
5682   // backpatching it with the spill slot operands.
5683   DCHECK(!environment->HasBeenRegistered());
5684   RegisterEnvironmentForDeoptimization(environment, Safepoint::kNoLazyDeopt);
5685
5686   GenerateOsrPrologue();
5687 }
5688
5689
5690 void LCodeGen::DoForInPrepareMap(LForInPrepareMap* instr) {
5691   DCHECK(ToRegister(instr->context()).is(esi));
5692   __ test(eax, Immediate(kSmiTagMask));
5693   DeoptimizeIf(zero, instr, Deoptimizer::kSmi);
5694
5695   STATIC_ASSERT(FIRST_JS_PROXY_TYPE == FIRST_SPEC_OBJECT_TYPE);
5696   __ CmpObjectType(eax, LAST_JS_PROXY_TYPE, ecx);
5697   DeoptimizeIf(below_equal, instr, Deoptimizer::kWrongInstanceType);
5698
5699   Label use_cache, call_runtime;
5700   __ CheckEnumCache(&call_runtime);
5701
5702   __ mov(eax, FieldOperand(eax, HeapObject::kMapOffset));
5703   __ jmp(&use_cache, Label::kNear);
5704
5705   // Get the set of properties to enumerate.
5706   __ bind(&call_runtime);
5707   __ push(eax);
5708   CallRuntime(Runtime::kGetPropertyNamesFast, 1, instr);
5709
5710   __ cmp(FieldOperand(eax, HeapObject::kMapOffset),
5711          isolate()->factory()->meta_map());
5712   DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongMap);
5713   __ bind(&use_cache);
5714 }
5715
5716
5717 void LCodeGen::DoForInCacheArray(LForInCacheArray* instr) {
5718   Register map = ToRegister(instr->map());
5719   Register result = ToRegister(instr->result());
5720   Label load_cache, done;
5721   __ EnumLength(result, map);
5722   __ cmp(result, Immediate(Smi::FromInt(0)));
5723   __ j(not_equal, &load_cache, Label::kNear);
5724   __ mov(result, isolate()->factory()->empty_fixed_array());
5725   __ jmp(&done, Label::kNear);
5726
5727   __ bind(&load_cache);
5728   __ LoadInstanceDescriptors(map, result);
5729   __ mov(result,
5730          FieldOperand(result, DescriptorArray::kEnumCacheOffset));
5731   __ mov(result,
5732          FieldOperand(result, FixedArray::SizeFor(instr->idx())));
5733   __ bind(&done);
5734   __ test(result, result);
5735   DeoptimizeIf(equal, instr, Deoptimizer::kNoCache);
5736 }
5737
5738
5739 void LCodeGen::DoCheckMapValue(LCheckMapValue* instr) {
5740   Register object = ToRegister(instr->value());
5741   __ cmp(ToRegister(instr->map()),
5742          FieldOperand(object, HeapObject::kMapOffset));
5743   DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongMap);
5744 }
5745
5746
5747 void LCodeGen::DoDeferredLoadMutableDouble(LLoadFieldByIndex* instr,
5748                                            Register object,
5749                                            Register index) {
5750   PushSafepointRegistersScope scope(this);
5751   __ push(object);
5752   __ push(index);
5753   __ xor_(esi, esi);
5754   __ CallRuntimeSaveDoubles(Runtime::kLoadMutableDouble);
5755   RecordSafepointWithRegisters(
5756       instr->pointer_map(), 2, Safepoint::kNoLazyDeopt);
5757   __ StoreToSafepointRegisterSlot(object, eax);
5758 }
5759
5760
5761 void LCodeGen::DoLoadFieldByIndex(LLoadFieldByIndex* instr) {
5762   class DeferredLoadMutableDouble final : public LDeferredCode {
5763    public:
5764     DeferredLoadMutableDouble(LCodeGen* codegen,
5765                               LLoadFieldByIndex* instr,
5766                               Register object,
5767                               Register index)
5768         : LDeferredCode(codegen),
5769           instr_(instr),
5770           object_(object),
5771           index_(index) {
5772     }
5773     void Generate() override {
5774       codegen()->DoDeferredLoadMutableDouble(instr_, object_, index_);
5775     }
5776     LInstruction* instr() override { return instr_; }
5777
5778    private:
5779     LLoadFieldByIndex* instr_;
5780     Register object_;
5781     Register index_;
5782   };
5783
5784   Register object = ToRegister(instr->object());
5785   Register index = ToRegister(instr->index());
5786
5787   DeferredLoadMutableDouble* deferred;
5788   deferred = new(zone()) DeferredLoadMutableDouble(
5789       this, instr, object, index);
5790
5791   Label out_of_object, done;
5792   __ test(index, Immediate(Smi::FromInt(1)));
5793   __ j(not_zero, deferred->entry());
5794
5795   __ sar(index, 1);
5796
5797   __ cmp(index, Immediate(0));
5798   __ j(less, &out_of_object, Label::kNear);
5799   __ mov(object, FieldOperand(object,
5800                               index,
5801                               times_half_pointer_size,
5802                               JSObject::kHeaderSize));
5803   __ jmp(&done, Label::kNear);
5804
5805   __ bind(&out_of_object);
5806   __ mov(object, FieldOperand(object, JSObject::kPropertiesOffset));
5807   __ neg(index);
5808   // Index is now equal to out of object property index plus 1.
5809   __ mov(object, FieldOperand(object,
5810                               index,
5811                               times_half_pointer_size,
5812                               FixedArray::kHeaderSize - kPointerSize));
5813   __ bind(deferred->exit());
5814   __ bind(&done);
5815 }
5816
5817
5818 void LCodeGen::DoStoreFrameContext(LStoreFrameContext* instr) {
5819   Register context = ToRegister(instr->context());
5820   __ mov(Operand(ebp, StandardFrameConstants::kContextOffset), context);
5821 }
5822
5823
5824 void LCodeGen::DoAllocateBlockContext(LAllocateBlockContext* instr) {
5825   Handle<ScopeInfo> scope_info = instr->scope_info();
5826   __ Push(scope_info);
5827   __ push(ToRegister(instr->function()));
5828   CallRuntime(Runtime::kPushBlockContext, 2, instr);
5829   RecordSafepoint(Safepoint::kNoLazyDeopt);
5830 }
5831
5832
5833 #undef __
5834
5835 }  // namespace internal
5836 }  // namespace v8
5837
5838 #endif  // V8_TARGET_ARCH_IA32