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