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