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