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