Reland of "Remove ExternalArray, derived types, and element kinds"
[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 == FLOAT32_ELEMENTS) {
3459     DoubleRegister result = ToDoubleRegister(instr->result());
3460     __ Ldr(result.S(), mem_op);
3461     __ Fcvt(result, result.S());
3462   } else if (elements_kind == FLOAT64_ELEMENTS) {
3463     DoubleRegister result = ToDoubleRegister(instr->result());
3464     __ Ldr(result, mem_op);
3465   } else {
3466     Register result = ToRegister(instr->result());
3467
3468     switch (elements_kind) {
3469       case INT8_ELEMENTS:
3470         __ Ldrsb(result, mem_op);
3471         break;
3472       case UINT8_ELEMENTS:
3473       case UINT8_CLAMPED_ELEMENTS:
3474         __ Ldrb(result, mem_op);
3475         break;
3476       case INT16_ELEMENTS:
3477         __ Ldrsh(result, mem_op);
3478         break;
3479       case UINT16_ELEMENTS:
3480         __ Ldrh(result, mem_op);
3481         break;
3482       case INT32_ELEMENTS:
3483         __ Ldrsw(result, mem_op);
3484         break;
3485       case UINT32_ELEMENTS:
3486         __ Ldr(result.W(), mem_op);
3487         if (!instr->hydrogen()->CheckFlag(HInstruction::kUint32)) {
3488           // Deopt if value > 0x80000000.
3489           __ Tst(result, 0xFFFFFFFF80000000);
3490           DeoptimizeIf(ne, instr, Deoptimizer::kNegativeValue);
3491         }
3492         break;
3493       case FLOAT32_ELEMENTS:
3494       case FLOAT64_ELEMENTS:
3495       case FAST_HOLEY_DOUBLE_ELEMENTS:
3496       case FAST_HOLEY_ELEMENTS:
3497       case FAST_HOLEY_SMI_ELEMENTS:
3498       case FAST_DOUBLE_ELEMENTS:
3499       case FAST_ELEMENTS:
3500       case FAST_SMI_ELEMENTS:
3501       case DICTIONARY_ELEMENTS:
3502       case FAST_SLOPPY_ARGUMENTS_ELEMENTS:
3503       case SLOW_SLOPPY_ARGUMENTS_ELEMENTS:
3504         UNREACHABLE();
3505         break;
3506     }
3507   }
3508 }
3509
3510
3511 MemOperand LCodeGen::PrepareKeyedArrayOperand(Register base,
3512                                               Register elements,
3513                                               Register key,
3514                                               bool key_is_tagged,
3515                                               ElementsKind elements_kind,
3516                                               Representation representation,
3517                                               int base_offset) {
3518   STATIC_ASSERT(static_cast<unsigned>(kSmiValueSize) == kWRegSizeInBits);
3519   STATIC_ASSERT(kSmiTag == 0);
3520   int element_size_shift = ElementsKindToShiftSize(elements_kind);
3521
3522   // Even though the HLoad/StoreKeyed instructions force the input
3523   // representation for the key to be an integer, the input gets replaced during
3524   // bounds check elimination with the index argument to the bounds check, which
3525   // can be tagged, so that case must be handled here, too.
3526   if (key_is_tagged) {
3527     __ Add(base, elements, Operand::UntagSmiAndScale(key, element_size_shift));
3528     if (representation.IsInteger32()) {
3529       DCHECK(elements_kind == FAST_SMI_ELEMENTS);
3530       // Read or write only the smi payload in the case of fast smi arrays.
3531       return UntagSmiMemOperand(base, base_offset);
3532     } else {
3533       return MemOperand(base, base_offset);
3534     }
3535   } else {
3536     // Sign extend key because it could be a 32-bit negative value or contain
3537     // garbage in the top 32-bits. The address computation happens in 64-bit.
3538     DCHECK((element_size_shift >= 0) && (element_size_shift <= 4));
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       __ Add(base, elements, Operand(key, SXTW, element_size_shift));
3543       return UntagSmiMemOperand(base, base_offset);
3544     } else {
3545       __ Add(base, elements, base_offset);
3546       return MemOperand(base, key, SXTW, element_size_shift);
3547     }
3548   }
3549 }
3550
3551
3552 void LCodeGen::DoLoadKeyedFixedDouble(LLoadKeyedFixedDouble* instr) {
3553   Register elements = ToRegister(instr->elements());
3554   DoubleRegister result = ToDoubleRegister(instr->result());
3555   MemOperand mem_op;
3556
3557   if (instr->key()->IsConstantOperand()) {
3558     DCHECK(instr->hydrogen()->RequiresHoleCheck() ||
3559            (instr->temp() == NULL));
3560
3561     int constant_key = ToInteger32(LConstantOperand::cast(instr->key()));
3562     if (constant_key & 0xf0000000) {
3563       Abort(kArrayIndexConstantValueTooBig);
3564     }
3565     int offset = instr->base_offset() + constant_key * kDoubleSize;
3566     mem_op = MemOperand(elements, offset);
3567   } else {
3568     Register load_base = ToRegister(instr->temp());
3569     Register key = ToRegister(instr->key());
3570     bool key_is_tagged = instr->hydrogen()->key()->representation().IsSmi();
3571     mem_op = PrepareKeyedArrayOperand(load_base, elements, key, key_is_tagged,
3572                                       instr->hydrogen()->elements_kind(),
3573                                       instr->hydrogen()->representation(),
3574                                       instr->base_offset());
3575   }
3576
3577   __ Ldr(result, mem_op);
3578
3579   if (instr->hydrogen()->RequiresHoleCheck()) {
3580     Register scratch = ToRegister(instr->temp());
3581     __ Fmov(scratch, result);
3582     __ Eor(scratch, scratch, kHoleNanInt64);
3583     DeoptimizeIfZero(scratch, instr, Deoptimizer::kHole);
3584   }
3585 }
3586
3587
3588 void LCodeGen::DoLoadKeyedFixed(LLoadKeyedFixed* instr) {
3589   Register elements = ToRegister(instr->elements());
3590   Register result = ToRegister(instr->result());
3591   MemOperand mem_op;
3592
3593   Representation representation = instr->hydrogen()->representation();
3594   if (instr->key()->IsConstantOperand()) {
3595     DCHECK(instr->temp() == NULL);
3596     LConstantOperand* const_operand = LConstantOperand::cast(instr->key());
3597     int offset = instr->base_offset() +
3598         ToInteger32(const_operand) * kPointerSize;
3599     if (representation.IsInteger32()) {
3600       DCHECK(instr->hydrogen()->elements_kind() == FAST_SMI_ELEMENTS);
3601       STATIC_ASSERT(static_cast<unsigned>(kSmiValueSize) == kWRegSizeInBits);
3602       STATIC_ASSERT(kSmiTag == 0);
3603       mem_op = UntagSmiMemOperand(elements, offset);
3604     } else {
3605       mem_op = MemOperand(elements, offset);
3606     }
3607   } else {
3608     Register load_base = ToRegister(instr->temp());
3609     Register key = ToRegister(instr->key());
3610     bool key_is_tagged = instr->hydrogen()->key()->representation().IsSmi();
3611
3612     mem_op = PrepareKeyedArrayOperand(load_base, elements, key, key_is_tagged,
3613                                       instr->hydrogen()->elements_kind(),
3614                                       representation, instr->base_offset());
3615   }
3616
3617   __ Load(result, mem_op, representation);
3618
3619   if (instr->hydrogen()->RequiresHoleCheck()) {
3620     if (IsFastSmiElementsKind(instr->hydrogen()->elements_kind())) {
3621       DeoptimizeIfNotSmi(result, instr, Deoptimizer::kNotASmi);
3622     } else {
3623       DeoptimizeIfRoot(result, Heap::kTheHoleValueRootIndex, instr,
3624                        Deoptimizer::kHole);
3625     }
3626   } else if (instr->hydrogen()->hole_mode() == CONVERT_HOLE_TO_UNDEFINED) {
3627     DCHECK(instr->hydrogen()->elements_kind() == FAST_HOLEY_ELEMENTS);
3628     Label done;
3629     __ CompareRoot(result, Heap::kTheHoleValueRootIndex);
3630     __ B(ne, &done);
3631     if (info()->IsStub()) {
3632       // A stub can safely convert the hole to undefined only if the array
3633       // protector cell contains (Smi) Isolate::kArrayProtectorValid. Otherwise
3634       // it needs to bail out.
3635       __ LoadRoot(result, Heap::kArrayProtectorRootIndex);
3636       __ Ldr(result, FieldMemOperand(result, Cell::kValueOffset));
3637       __ Cmp(result, Operand(Smi::FromInt(Isolate::kArrayProtectorValid)));
3638       DeoptimizeIf(ne, instr, Deoptimizer::kHole);
3639     }
3640     __ LoadRoot(result, Heap::kUndefinedValueRootIndex);
3641     __ Bind(&done);
3642   }
3643 }
3644
3645
3646 void LCodeGen::DoLoadKeyedGeneric(LLoadKeyedGeneric* instr) {
3647   DCHECK(ToRegister(instr->context()).is(cp));
3648   DCHECK(ToRegister(instr->object()).is(LoadDescriptor::ReceiverRegister()));
3649   DCHECK(ToRegister(instr->key()).is(LoadDescriptor::NameRegister()));
3650
3651   if (instr->hydrogen()->HasVectorAndSlot()) {
3652     EmitVectorLoadICRegisters<LLoadKeyedGeneric>(instr);
3653   }
3654
3655   Handle<Code> ic = CodeFactory::KeyedLoadICInOptimizedCode(
3656                         isolate(), instr->hydrogen()->language_mode(),
3657                         instr->hydrogen()->initialization_state()).code();
3658   CallCode(ic, RelocInfo::CODE_TARGET, instr);
3659
3660   DCHECK(ToRegister(instr->result()).Is(x0));
3661 }
3662
3663
3664 void LCodeGen::DoLoadNamedField(LLoadNamedField* instr) {
3665   HObjectAccess access = instr->hydrogen()->access();
3666   int offset = access.offset();
3667   Register object = ToRegister(instr->object());
3668
3669   if (access.IsExternalMemory()) {
3670     Register result = ToRegister(instr->result());
3671     __ Load(result, MemOperand(object, offset), access.representation());
3672     return;
3673   }
3674
3675   if (instr->hydrogen()->representation().IsDouble()) {
3676     DCHECK(access.IsInobject());
3677     FPRegister result = ToDoubleRegister(instr->result());
3678     __ Ldr(result, FieldMemOperand(object, offset));
3679     return;
3680   }
3681
3682   Register result = ToRegister(instr->result());
3683   Register source;
3684   if (access.IsInobject()) {
3685     source = object;
3686   } else {
3687     // Load the properties array, using result as a scratch register.
3688     __ Ldr(result, FieldMemOperand(object, JSObject::kPropertiesOffset));
3689     source = result;
3690   }
3691
3692   if (access.representation().IsSmi() &&
3693       instr->hydrogen()->representation().IsInteger32()) {
3694     // Read int value directly from upper half of the smi.
3695     STATIC_ASSERT(static_cast<unsigned>(kSmiValueSize) == kWRegSizeInBits);
3696     STATIC_ASSERT(kSmiTag == 0);
3697     __ Load(result, UntagSmiFieldMemOperand(source, offset),
3698             Representation::Integer32());
3699   } else {
3700     __ Load(result, FieldMemOperand(source, offset), access.representation());
3701   }
3702 }
3703
3704
3705 void LCodeGen::DoLoadNamedGeneric(LLoadNamedGeneric* instr) {
3706   DCHECK(ToRegister(instr->context()).is(cp));
3707   // LoadIC expects name and receiver in registers.
3708   DCHECK(ToRegister(instr->object()).is(LoadDescriptor::ReceiverRegister()));
3709   __ Mov(LoadDescriptor::NameRegister(), Operand(instr->name()));
3710   EmitVectorLoadICRegisters<LLoadNamedGeneric>(instr);
3711   Handle<Code> ic =
3712       CodeFactory::LoadICInOptimizedCode(
3713           isolate(), NOT_INSIDE_TYPEOF, instr->hydrogen()->language_mode(),
3714           instr->hydrogen()->initialization_state()).code();
3715   CallCode(ic, RelocInfo::CODE_TARGET, instr);
3716
3717   DCHECK(ToRegister(instr->result()).is(x0));
3718 }
3719
3720
3721 void LCodeGen::DoLoadRoot(LLoadRoot* instr) {
3722   Register result = ToRegister(instr->result());
3723   __ LoadRoot(result, instr->index());
3724 }
3725
3726
3727 void LCodeGen::DoMapEnumLength(LMapEnumLength* instr) {
3728   Register result = ToRegister(instr->result());
3729   Register map = ToRegister(instr->value());
3730   __ EnumLengthSmi(result, map);
3731 }
3732
3733
3734 void LCodeGen::DoMathAbs(LMathAbs* instr) {
3735   Representation r = instr->hydrogen()->value()->representation();
3736   if (r.IsDouble()) {
3737     DoubleRegister input = ToDoubleRegister(instr->value());
3738     DoubleRegister result = ToDoubleRegister(instr->result());
3739     __ Fabs(result, input);
3740   } else if (r.IsSmi() || r.IsInteger32()) {
3741     Register input = r.IsSmi() ? ToRegister(instr->value())
3742                                : ToRegister32(instr->value());
3743     Register result = r.IsSmi() ? ToRegister(instr->result())
3744                                 : ToRegister32(instr->result());
3745     __ Abs(result, input);
3746     DeoptimizeIf(vs, instr, Deoptimizer::kOverflow);
3747   }
3748 }
3749
3750
3751 void LCodeGen::DoDeferredMathAbsTagged(LMathAbsTagged* instr,
3752                                        Label* exit,
3753                                        Label* allocation_entry) {
3754   // Handle the tricky cases of MathAbsTagged:
3755   //  - HeapNumber inputs.
3756   //    - Negative inputs produce a positive result, so a new HeapNumber is
3757   //      allocated to hold it.
3758   //    - Positive inputs are returned as-is, since there is no need to allocate
3759   //      a new HeapNumber for the result.
3760   //  - The (smi) input -0x80000000, produces +0x80000000, which does not fit
3761   //    a smi. In this case, the inline code sets the result and jumps directly
3762   //    to the allocation_entry label.
3763   DCHECK(instr->context() != NULL);
3764   DCHECK(ToRegister(instr->context()).is(cp));
3765   Register input = ToRegister(instr->value());
3766   Register temp1 = ToRegister(instr->temp1());
3767   Register temp2 = ToRegister(instr->temp2());
3768   Register result_bits = ToRegister(instr->temp3());
3769   Register result = ToRegister(instr->result());
3770
3771   Label runtime_allocation;
3772
3773   // Deoptimize if the input is not a HeapNumber.
3774   DeoptimizeIfNotHeapNumber(input, instr);
3775
3776   // If the argument is positive, we can return it as-is, without any need to
3777   // allocate a new HeapNumber for the result. We have to do this in integer
3778   // registers (rather than with fabs) because we need to be able to distinguish
3779   // the two zeroes.
3780   __ Ldr(result_bits, FieldMemOperand(input, HeapNumber::kValueOffset));
3781   __ Mov(result, input);
3782   __ Tbz(result_bits, kXSignBit, exit);
3783
3784   // Calculate abs(input) by clearing the sign bit.
3785   __ Bic(result_bits, result_bits, kXSignMask);
3786
3787   // Allocate a new HeapNumber to hold the result.
3788   //  result_bits   The bit representation of the (double) result.
3789   __ Bind(allocation_entry);
3790   __ AllocateHeapNumber(result, &runtime_allocation, temp1, temp2);
3791   // The inline (non-deferred) code will store result_bits into result.
3792   __ B(exit);
3793
3794   __ Bind(&runtime_allocation);
3795   if (FLAG_debug_code) {
3796     // Because result is in the pointer map, we need to make sure it has a valid
3797     // tagged value before we call the runtime. We speculatively set it to the
3798     // input (for abs(+x)) or to a smi (for abs(-SMI_MIN)), so it should already
3799     // be valid.
3800     Label result_ok;
3801     Register input = ToRegister(instr->value());
3802     __ JumpIfSmi(result, &result_ok);
3803     __ Cmp(input, result);
3804     __ Assert(eq, kUnexpectedValue);
3805     __ Bind(&result_ok);
3806   }
3807
3808   { PushSafepointRegistersScope scope(this);
3809     CallRuntimeFromDeferred(Runtime::kAllocateHeapNumber, 0, instr,
3810                             instr->context());
3811     __ StoreToSafepointRegisterSlot(x0, result);
3812   }
3813   // The inline (non-deferred) code will store result_bits into result.
3814 }
3815
3816
3817 void LCodeGen::DoMathAbsTagged(LMathAbsTagged* instr) {
3818   // Class for deferred case.
3819   class DeferredMathAbsTagged: public LDeferredCode {
3820    public:
3821     DeferredMathAbsTagged(LCodeGen* codegen, LMathAbsTagged* instr)
3822         : LDeferredCode(codegen), instr_(instr) { }
3823     virtual void Generate() {
3824       codegen()->DoDeferredMathAbsTagged(instr_, exit(),
3825                                          allocation_entry());
3826     }
3827     virtual LInstruction* instr() { return instr_; }
3828     Label* allocation_entry() { return &allocation; }
3829    private:
3830     LMathAbsTagged* instr_;
3831     Label allocation;
3832   };
3833
3834   // TODO(jbramley): The early-exit mechanism would skip the new frame handling
3835   // in GenerateDeferredCode. Tidy this up.
3836   DCHECK(!NeedsDeferredFrame());
3837
3838   DeferredMathAbsTagged* deferred =
3839       new(zone()) DeferredMathAbsTagged(this, instr);
3840
3841   DCHECK(instr->hydrogen()->value()->representation().IsTagged() ||
3842          instr->hydrogen()->value()->representation().IsSmi());
3843   Register input = ToRegister(instr->value());
3844   Register result_bits = ToRegister(instr->temp3());
3845   Register result = ToRegister(instr->result());
3846   Label done;
3847
3848   // Handle smis inline.
3849   // We can treat smis as 64-bit integers, since the (low-order) tag bits will
3850   // never get set by the negation. This is therefore the same as the Integer32
3851   // case in DoMathAbs, except that it operates on 64-bit values.
3852   STATIC_ASSERT((kSmiValueSize == 32) && (kSmiShift == 32) && (kSmiTag == 0));
3853
3854   __ JumpIfNotSmi(input, deferred->entry());
3855
3856   __ Abs(result, input, NULL, &done);
3857
3858   // The result is the magnitude (abs) of the smallest value a smi can
3859   // represent, encoded as a double.
3860   __ Mov(result_bits, double_to_rawbits(0x80000000));
3861   __ B(deferred->allocation_entry());
3862
3863   __ Bind(deferred->exit());
3864   __ Str(result_bits, FieldMemOperand(result, HeapNumber::kValueOffset));
3865
3866   __ Bind(&done);
3867 }
3868
3869
3870 void LCodeGen::DoMathExp(LMathExp* instr) {
3871   DoubleRegister input = ToDoubleRegister(instr->value());
3872   DoubleRegister result = ToDoubleRegister(instr->result());
3873   DoubleRegister double_temp1 = ToDoubleRegister(instr->double_temp1());
3874   DoubleRegister double_temp2 = double_scratch();
3875   Register temp1 = ToRegister(instr->temp1());
3876   Register temp2 = ToRegister(instr->temp2());
3877   Register temp3 = ToRegister(instr->temp3());
3878
3879   MathExpGenerator::EmitMathExp(masm(), input, result,
3880                                 double_temp1, double_temp2,
3881                                 temp1, temp2, temp3);
3882 }
3883
3884
3885 void LCodeGen::DoMathFloorD(LMathFloorD* instr) {
3886   DoubleRegister input = ToDoubleRegister(instr->value());
3887   DoubleRegister result = ToDoubleRegister(instr->result());
3888
3889   __ Frintm(result, input);
3890 }
3891
3892
3893 void LCodeGen::DoMathFloorI(LMathFloorI* instr) {
3894   DoubleRegister input = ToDoubleRegister(instr->value());
3895   Register result = ToRegister(instr->result());
3896
3897   if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3898     DeoptimizeIfMinusZero(input, instr, Deoptimizer::kMinusZero);
3899   }
3900
3901   __ Fcvtms(result, input);
3902
3903   // Check that the result fits into a 32-bit integer.
3904   //  - The result did not overflow.
3905   __ Cmp(result, Operand(result, SXTW));
3906   //  - The input was not NaN.
3907   __ Fccmp(input, input, NoFlag, eq);
3908   DeoptimizeIf(ne, instr, Deoptimizer::kLostPrecisionOrNaN);
3909 }
3910
3911
3912 void LCodeGen::DoFlooringDivByPowerOf2I(LFlooringDivByPowerOf2I* instr) {
3913   Register dividend = ToRegister32(instr->dividend());
3914   Register result = ToRegister32(instr->result());
3915   int32_t divisor = instr->divisor();
3916
3917   // If the divisor is 1, return the dividend.
3918   if (divisor == 1) {
3919     __ Mov(result, dividend, kDiscardForSameWReg);
3920     return;
3921   }
3922
3923   // If the divisor is positive, things are easy: There can be no deopts and we
3924   // can simply do an arithmetic right shift.
3925   int32_t shift = WhichPowerOf2Abs(divisor);
3926   if (divisor > 1) {
3927     __ Mov(result, Operand(dividend, ASR, shift));
3928     return;
3929   }
3930
3931   // If the divisor is negative, we have to negate and handle edge cases.
3932   __ Negs(result, dividend);
3933   if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3934     DeoptimizeIf(eq, instr, Deoptimizer::kMinusZero);
3935   }
3936
3937   // Dividing by -1 is basically negation, unless we overflow.
3938   if (divisor == -1) {
3939     if (instr->hydrogen()->CheckFlag(HValue::kLeftCanBeMinInt)) {
3940       DeoptimizeIf(vs, instr, Deoptimizer::kOverflow);
3941     }
3942     return;
3943   }
3944
3945   // If the negation could not overflow, simply shifting is OK.
3946   if (!instr->hydrogen()->CheckFlag(HValue::kLeftCanBeMinInt)) {
3947     __ Mov(result, Operand(dividend, ASR, shift));
3948     return;
3949   }
3950
3951   __ Asr(result, result, shift);
3952   __ Csel(result, result, kMinInt / divisor, vc);
3953 }
3954
3955
3956 void LCodeGen::DoFlooringDivByConstI(LFlooringDivByConstI* instr) {
3957   Register dividend = ToRegister32(instr->dividend());
3958   int32_t divisor = instr->divisor();
3959   Register result = ToRegister32(instr->result());
3960   DCHECK(!AreAliased(dividend, result));
3961
3962   if (divisor == 0) {
3963     Deoptimize(instr, Deoptimizer::kDivisionByZero);
3964     return;
3965   }
3966
3967   // Check for (0 / -x) that will produce negative zero.
3968   HMathFloorOfDiv* hdiv = instr->hydrogen();
3969   if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
3970     DeoptimizeIfZero(dividend, instr, Deoptimizer::kMinusZero);
3971   }
3972
3973   // Easy case: We need no dynamic check for the dividend and the flooring
3974   // division is the same as the truncating division.
3975   if ((divisor > 0 && !hdiv->CheckFlag(HValue::kLeftCanBeNegative)) ||
3976       (divisor < 0 && !hdiv->CheckFlag(HValue::kLeftCanBePositive))) {
3977     __ TruncatingDiv(result, dividend, Abs(divisor));
3978     if (divisor < 0) __ Neg(result, result);
3979     return;
3980   }
3981
3982   // In the general case we may need to adjust before and after the truncating
3983   // division to get a flooring division.
3984   Register temp = ToRegister32(instr->temp());
3985   DCHECK(!AreAliased(temp, dividend, result));
3986   Label needs_adjustment, done;
3987   __ Cmp(dividend, 0);
3988   __ B(divisor > 0 ? lt : gt, &needs_adjustment);
3989   __ TruncatingDiv(result, dividend, Abs(divisor));
3990   if (divisor < 0) __ Neg(result, result);
3991   __ B(&done);
3992   __ Bind(&needs_adjustment);
3993   __ Add(temp, dividend, Operand(divisor > 0 ? 1 : -1));
3994   __ TruncatingDiv(result, temp, Abs(divisor));
3995   if (divisor < 0) __ Neg(result, result);
3996   __ Sub(result, result, Operand(1));
3997   __ Bind(&done);
3998 }
3999
4000
4001 // TODO(svenpanne) Refactor this to avoid code duplication with DoDivI.
4002 void LCodeGen::DoFlooringDivI(LFlooringDivI* instr) {
4003   Register dividend = ToRegister32(instr->dividend());
4004   Register divisor = ToRegister32(instr->divisor());
4005   Register remainder = ToRegister32(instr->temp());
4006   Register result = ToRegister32(instr->result());
4007
4008   // This can't cause an exception on ARM, so we can speculatively
4009   // execute it already now.
4010   __ Sdiv(result, dividend, divisor);
4011
4012   // Check for x / 0.
4013   DeoptimizeIfZero(divisor, instr, Deoptimizer::kDivisionByZero);
4014
4015   // Check for (kMinInt / -1).
4016   if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
4017     // The V flag will be set iff dividend == kMinInt.
4018     __ Cmp(dividend, 1);
4019     __ Ccmp(divisor, -1, NoFlag, vs);
4020     DeoptimizeIf(eq, instr, Deoptimizer::kOverflow);
4021   }
4022
4023   // Check for (0 / -x) that will produce negative zero.
4024   if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
4025     __ Cmp(divisor, 0);
4026     __ Ccmp(dividend, 0, ZFlag, mi);
4027     // "divisor" can't be null because the code would have already been
4028     // deoptimized. The Z flag is set only if (divisor < 0) and (dividend == 0).
4029     // In this case we need to deoptimize to produce a -0.
4030     DeoptimizeIf(eq, instr, Deoptimizer::kMinusZero);
4031   }
4032
4033   Label done;
4034   // If both operands have the same sign then we are done.
4035   __ Eor(remainder, dividend, divisor);
4036   __ Tbz(remainder, kWSignBit, &done);
4037
4038   // Check if the result needs to be corrected.
4039   __ Msub(remainder, result, divisor, dividend);
4040   __ Cbz(remainder, &done);
4041   __ Sub(result, result, 1);
4042
4043   __ Bind(&done);
4044 }
4045
4046
4047 void LCodeGen::DoMathLog(LMathLog* instr) {
4048   DCHECK(instr->IsMarkedAsCall());
4049   DCHECK(ToDoubleRegister(instr->value()).is(d0));
4050   __ CallCFunction(ExternalReference::math_log_double_function(isolate()),
4051                    0, 1);
4052   DCHECK(ToDoubleRegister(instr->result()).Is(d0));
4053 }
4054
4055
4056 void LCodeGen::DoMathClz32(LMathClz32* instr) {
4057   Register input = ToRegister32(instr->value());
4058   Register result = ToRegister32(instr->result());
4059   __ Clz(result, input);
4060 }
4061
4062
4063 void LCodeGen::DoMathPowHalf(LMathPowHalf* instr) {
4064   DoubleRegister input = ToDoubleRegister(instr->value());
4065   DoubleRegister result = ToDoubleRegister(instr->result());
4066   Label done;
4067
4068   // Math.pow(x, 0.5) differs from fsqrt(x) in the following cases:
4069   //  Math.pow(-Infinity, 0.5) == +Infinity
4070   //  Math.pow(-0.0, 0.5) == +0.0
4071
4072   // Catch -infinity inputs first.
4073   // TODO(jbramley): A constant infinity register would be helpful here.
4074   __ Fmov(double_scratch(), kFP64NegativeInfinity);
4075   __ Fcmp(double_scratch(), input);
4076   __ Fabs(result, input);
4077   __ B(&done, eq);
4078
4079   // Add +0.0 to convert -0.0 to +0.0.
4080   __ Fadd(double_scratch(), input, fp_zero);
4081   __ Fsqrt(result, double_scratch());
4082
4083   __ Bind(&done);
4084 }
4085
4086
4087 void LCodeGen::DoPower(LPower* instr) {
4088   Representation exponent_type = instr->hydrogen()->right()->representation();
4089   // Having marked this as a call, we can use any registers.
4090   // Just make sure that the input/output registers are the expected ones.
4091   Register tagged_exponent = MathPowTaggedDescriptor::exponent();
4092   Register integer_exponent = MathPowIntegerDescriptor::exponent();
4093   DCHECK(!instr->right()->IsDoubleRegister() ||
4094          ToDoubleRegister(instr->right()).is(d1));
4095   DCHECK(exponent_type.IsInteger32() || !instr->right()->IsRegister() ||
4096          ToRegister(instr->right()).is(tagged_exponent));
4097   DCHECK(!exponent_type.IsInteger32() ||
4098          ToRegister(instr->right()).is(integer_exponent));
4099   DCHECK(ToDoubleRegister(instr->left()).is(d0));
4100   DCHECK(ToDoubleRegister(instr->result()).is(d0));
4101
4102   if (exponent_type.IsSmi()) {
4103     MathPowStub stub(isolate(), MathPowStub::TAGGED);
4104     __ CallStub(&stub);
4105   } else if (exponent_type.IsTagged()) {
4106     Label no_deopt;
4107     __ JumpIfSmi(tagged_exponent, &no_deopt);
4108     DeoptimizeIfNotHeapNumber(tagged_exponent, instr);
4109     __ Bind(&no_deopt);
4110     MathPowStub stub(isolate(), MathPowStub::TAGGED);
4111     __ CallStub(&stub);
4112   } else if (exponent_type.IsInteger32()) {
4113     // Ensure integer exponent has no garbage in top 32-bits, as MathPowStub
4114     // supports large integer exponents.
4115     __ Sxtw(integer_exponent, integer_exponent);
4116     MathPowStub stub(isolate(), MathPowStub::INTEGER);
4117     __ CallStub(&stub);
4118   } else {
4119     DCHECK(exponent_type.IsDouble());
4120     MathPowStub stub(isolate(), MathPowStub::DOUBLE);
4121     __ CallStub(&stub);
4122   }
4123 }
4124
4125
4126 void LCodeGen::DoMathRoundD(LMathRoundD* instr) {
4127   DoubleRegister input = ToDoubleRegister(instr->value());
4128   DoubleRegister result = ToDoubleRegister(instr->result());
4129   DoubleRegister scratch_d = double_scratch();
4130
4131   DCHECK(!AreAliased(input, result, scratch_d));
4132
4133   Label done;
4134
4135   __ Frinta(result, input);
4136   __ Fcmp(input, 0.0);
4137   __ Fccmp(result, input, ZFlag, lt);
4138   // The result is correct if the input was in [-0, +infinity], or was a
4139   // negative integral value.
4140   __ B(eq, &done);
4141
4142   // Here the input is negative, non integral, with an exponent lower than 52.
4143   // We do not have to worry about the 0.49999999999999994 (0x3fdfffffffffffff)
4144   // case. So we can safely add 0.5.
4145   __ Fmov(scratch_d, 0.5);
4146   __ Fadd(result, input, scratch_d);
4147   __ Frintm(result, result);
4148   // The range [-0.5, -0.0[ yielded +0.0. Force the sign to negative.
4149   __ Fabs(result, result);
4150   __ Fneg(result, result);
4151
4152   __ Bind(&done);
4153 }
4154
4155
4156 void LCodeGen::DoMathRoundI(LMathRoundI* instr) {
4157   DoubleRegister input = ToDoubleRegister(instr->value());
4158   DoubleRegister temp = ToDoubleRegister(instr->temp1());
4159   DoubleRegister dot_five = double_scratch();
4160   Register result = ToRegister(instr->result());
4161   Label done;
4162
4163   // Math.round() rounds to the nearest integer, with ties going towards
4164   // +infinity. This does not match any IEEE-754 rounding mode.
4165   //  - Infinities and NaNs are propagated unchanged, but cause deopts because
4166   //    they can't be represented as integers.
4167   //  - The sign of the result is the same as the sign of the input. This means
4168   //    that -0.0 rounds to itself, and values -0.5 <= input < 0 also produce a
4169   //    result of -0.0.
4170
4171   // Add 0.5 and round towards -infinity.
4172   __ Fmov(dot_five, 0.5);
4173   __ Fadd(temp, input, dot_five);
4174   __ Fcvtms(result, temp);
4175
4176   // The result is correct if:
4177   //  result is not 0, as the input could be NaN or [-0.5, -0.0].
4178   //  result is not 1, as 0.499...94 will wrongly map to 1.
4179   //  result fits in 32 bits.
4180   __ Cmp(result, Operand(result.W(), SXTW));
4181   __ Ccmp(result, 1, ZFlag, eq);
4182   __ B(hi, &done);
4183
4184   // At this point, we have to handle possible inputs of NaN or numbers in the
4185   // range [-0.5, 1.5[, or numbers larger than 32 bits.
4186
4187   // Deoptimize if the result > 1, as it must be larger than 32 bits.
4188   __ Cmp(result, 1);
4189   DeoptimizeIf(hi, instr, Deoptimizer::kOverflow);
4190
4191   // Deoptimize for negative inputs, which at this point are only numbers in
4192   // the range [-0.5, -0.0]
4193   if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
4194     __ Fmov(result, input);
4195     DeoptimizeIfNegative(result, instr, Deoptimizer::kMinusZero);
4196   }
4197
4198   // Deoptimize if the input was NaN.
4199   __ Fcmp(input, dot_five);
4200   DeoptimizeIf(vs, instr, Deoptimizer::kNaN);
4201
4202   // Now, the only unhandled inputs are in the range [0.0, 1.5[ (or [-0.5, 1.5[
4203   // if we didn't generate a -0.0 bailout). If input >= 0.5 then return 1,
4204   // else 0; we avoid dealing with 0.499...94 directly.
4205   __ Cset(result, ge);
4206   __ Bind(&done);
4207 }
4208
4209
4210 void LCodeGen::DoMathFround(LMathFround* instr) {
4211   DoubleRegister input = ToDoubleRegister(instr->value());
4212   DoubleRegister result = ToDoubleRegister(instr->result());
4213   __ Fcvt(result.S(), input);
4214   __ Fcvt(result, result.S());
4215 }
4216
4217
4218 void LCodeGen::DoMathSqrt(LMathSqrt* instr) {
4219   DoubleRegister input = ToDoubleRegister(instr->value());
4220   DoubleRegister result = ToDoubleRegister(instr->result());
4221   __ Fsqrt(result, input);
4222 }
4223
4224
4225 void LCodeGen::DoMathMinMax(LMathMinMax* instr) {
4226   HMathMinMax::Operation op = instr->hydrogen()->operation();
4227   if (instr->hydrogen()->representation().IsInteger32()) {
4228     Register result = ToRegister32(instr->result());
4229     Register left = ToRegister32(instr->left());
4230     Operand right = ToOperand32(instr->right());
4231
4232     __ Cmp(left, right);
4233     __ Csel(result, left, right, (op == HMathMinMax::kMathMax) ? ge : le);
4234   } else if (instr->hydrogen()->representation().IsSmi()) {
4235     Register result = ToRegister(instr->result());
4236     Register left = ToRegister(instr->left());
4237     Operand right = ToOperand(instr->right());
4238
4239     __ Cmp(left, right);
4240     __ Csel(result, left, right, (op == HMathMinMax::kMathMax) ? ge : le);
4241   } else {
4242     DCHECK(instr->hydrogen()->representation().IsDouble());
4243     DoubleRegister result = ToDoubleRegister(instr->result());
4244     DoubleRegister left = ToDoubleRegister(instr->left());
4245     DoubleRegister right = ToDoubleRegister(instr->right());
4246
4247     if (op == HMathMinMax::kMathMax) {
4248       __ Fmax(result, left, right);
4249     } else {
4250       DCHECK(op == HMathMinMax::kMathMin);
4251       __ Fmin(result, left, right);
4252     }
4253   }
4254 }
4255
4256
4257 void LCodeGen::DoModByPowerOf2I(LModByPowerOf2I* instr) {
4258   Register dividend = ToRegister32(instr->dividend());
4259   int32_t divisor = instr->divisor();
4260   DCHECK(dividend.is(ToRegister32(instr->result())));
4261
4262   // Theoretically, a variation of the branch-free code for integer division by
4263   // a power of 2 (calculating the remainder via an additional multiplication
4264   // (which gets simplified to an 'and') and subtraction) should be faster, and
4265   // this is exactly what GCC and clang emit. Nevertheless, benchmarks seem to
4266   // indicate that positive dividends are heavily favored, so the branching
4267   // version performs better.
4268   HMod* hmod = instr->hydrogen();
4269   int32_t mask = divisor < 0 ? -(divisor + 1) : (divisor - 1);
4270   Label dividend_is_not_negative, done;
4271   if (hmod->CheckFlag(HValue::kLeftCanBeNegative)) {
4272     __ Tbz(dividend, kWSignBit, &dividend_is_not_negative);
4273     // Note that this is correct even for kMinInt operands.
4274     __ Neg(dividend, dividend);
4275     __ And(dividend, dividend, mask);
4276     __ Negs(dividend, dividend);
4277     if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
4278       DeoptimizeIf(eq, instr, Deoptimizer::kMinusZero);
4279     }
4280     __ B(&done);
4281   }
4282
4283   __ bind(&dividend_is_not_negative);
4284   __ And(dividend, dividend, mask);
4285   __ bind(&done);
4286 }
4287
4288
4289 void LCodeGen::DoModByConstI(LModByConstI* instr) {
4290   Register dividend = ToRegister32(instr->dividend());
4291   int32_t divisor = instr->divisor();
4292   Register result = ToRegister32(instr->result());
4293   Register temp = ToRegister32(instr->temp());
4294   DCHECK(!AreAliased(dividend, result, temp));
4295
4296   if (divisor == 0) {
4297     Deoptimize(instr, Deoptimizer::kDivisionByZero);
4298     return;
4299   }
4300
4301   __ TruncatingDiv(result, dividend, Abs(divisor));
4302   __ Sxtw(dividend.X(), dividend);
4303   __ Mov(temp, Abs(divisor));
4304   __ Smsubl(result.X(), result, temp, dividend.X());
4305
4306   // Check for negative zero.
4307   HMod* hmod = instr->hydrogen();
4308   if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
4309     Label remainder_not_zero;
4310     __ Cbnz(result, &remainder_not_zero);
4311     DeoptimizeIfNegative(dividend, instr, Deoptimizer::kMinusZero);
4312     __ bind(&remainder_not_zero);
4313   }
4314 }
4315
4316
4317 void LCodeGen::DoModI(LModI* instr) {
4318   Register dividend = ToRegister32(instr->left());
4319   Register divisor = ToRegister32(instr->right());
4320   Register result = ToRegister32(instr->result());
4321
4322   Label done;
4323   // modulo = dividend - quotient * divisor
4324   __ Sdiv(result, dividend, divisor);
4325   if (instr->hydrogen()->CheckFlag(HValue::kCanBeDivByZero)) {
4326     DeoptimizeIfZero(divisor, instr, Deoptimizer::kDivisionByZero);
4327   }
4328   __ Msub(result, result, divisor, dividend);
4329   if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
4330     __ Cbnz(result, &done);
4331     DeoptimizeIfNegative(dividend, instr, Deoptimizer::kMinusZero);
4332   }
4333   __ Bind(&done);
4334 }
4335
4336
4337 void LCodeGen::DoMulConstIS(LMulConstIS* instr) {
4338   DCHECK(instr->hydrogen()->representation().IsSmiOrInteger32());
4339   bool is_smi = instr->hydrogen()->representation().IsSmi();
4340   Register result =
4341       is_smi ? ToRegister(instr->result()) : ToRegister32(instr->result());
4342   Register left =
4343       is_smi ? ToRegister(instr->left()) : ToRegister32(instr->left()) ;
4344   int32_t right = ToInteger32(instr->right());
4345   DCHECK((right > -kMaxInt) && (right < kMaxInt));
4346
4347   bool can_overflow = instr->hydrogen()->CheckFlag(HValue::kCanOverflow);
4348   bool bailout_on_minus_zero =
4349     instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero);
4350
4351   if (bailout_on_minus_zero) {
4352     if (right < 0) {
4353       // The result is -0 if right is negative and left is zero.
4354       DeoptimizeIfZero(left, instr, Deoptimizer::kMinusZero);
4355     } else if (right == 0) {
4356       // The result is -0 if the right is zero and the left is negative.
4357       DeoptimizeIfNegative(left, instr, Deoptimizer::kMinusZero);
4358     }
4359   }
4360
4361   switch (right) {
4362     // Cases which can detect overflow.
4363     case -1:
4364       if (can_overflow) {
4365         // Only 0x80000000 can overflow here.
4366         __ Negs(result, left);
4367         DeoptimizeIf(vs, instr, Deoptimizer::kOverflow);
4368       } else {
4369         __ Neg(result, left);
4370       }
4371       break;
4372     case 0:
4373       // This case can never overflow.
4374       __ Mov(result, 0);
4375       break;
4376     case 1:
4377       // This case can never overflow.
4378       __ Mov(result, left, kDiscardForSameWReg);
4379       break;
4380     case 2:
4381       if (can_overflow) {
4382         __ Adds(result, left, left);
4383         DeoptimizeIf(vs, instr, Deoptimizer::kOverflow);
4384       } else {
4385         __ Add(result, left, left);
4386       }
4387       break;
4388
4389     default:
4390       // Multiplication by constant powers of two (and some related values)
4391       // can be done efficiently with shifted operands.
4392       int32_t right_abs = Abs(right);
4393
4394       if (base::bits::IsPowerOfTwo32(right_abs)) {
4395         int right_log2 = WhichPowerOf2(right_abs);
4396
4397         if (can_overflow) {
4398           Register scratch = result;
4399           DCHECK(!AreAliased(scratch, left));
4400           __ Cls(scratch, left);
4401           __ Cmp(scratch, right_log2);
4402           DeoptimizeIf(lt, instr, Deoptimizer::kOverflow);
4403         }
4404
4405         if (right >= 0) {
4406           // result = left << log2(right)
4407           __ Lsl(result, left, right_log2);
4408         } else {
4409           // result = -left << log2(-right)
4410           if (can_overflow) {
4411             __ Negs(result, Operand(left, LSL, right_log2));
4412             DeoptimizeIf(vs, instr, Deoptimizer::kOverflow);
4413           } else {
4414             __ Neg(result, Operand(left, LSL, right_log2));
4415           }
4416         }
4417         return;
4418       }
4419
4420
4421       // For the following cases, we could perform a conservative overflow check
4422       // with CLS as above. However the few cycles saved are likely not worth
4423       // the risk of deoptimizing more often than required.
4424       DCHECK(!can_overflow);
4425
4426       if (right >= 0) {
4427         if (base::bits::IsPowerOfTwo32(right - 1)) {
4428           // result = left + left << log2(right - 1)
4429           __ Add(result, left, Operand(left, LSL, WhichPowerOf2(right - 1)));
4430         } else if (base::bits::IsPowerOfTwo32(right + 1)) {
4431           // result = -left + left << log2(right + 1)
4432           __ Sub(result, left, Operand(left, LSL, WhichPowerOf2(right + 1)));
4433           __ Neg(result, result);
4434         } else {
4435           UNREACHABLE();
4436         }
4437       } else {
4438         if (base::bits::IsPowerOfTwo32(-right + 1)) {
4439           // result = left - left << log2(-right + 1)
4440           __ Sub(result, left, Operand(left, LSL, WhichPowerOf2(-right + 1)));
4441         } else if (base::bits::IsPowerOfTwo32(-right - 1)) {
4442           // result = -left - left << log2(-right - 1)
4443           __ Add(result, left, Operand(left, LSL, WhichPowerOf2(-right - 1)));
4444           __ Neg(result, result);
4445         } else {
4446           UNREACHABLE();
4447         }
4448       }
4449   }
4450 }
4451
4452
4453 void LCodeGen::DoMulI(LMulI* instr) {
4454   Register result = ToRegister32(instr->result());
4455   Register left = ToRegister32(instr->left());
4456   Register right = ToRegister32(instr->right());
4457
4458   bool can_overflow = instr->hydrogen()->CheckFlag(HValue::kCanOverflow);
4459   bool bailout_on_minus_zero =
4460     instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero);
4461
4462   if (bailout_on_minus_zero && !left.Is(right)) {
4463     // If one operand is zero and the other is negative, the result is -0.
4464     //  - Set Z (eq) if either left or right, or both, are 0.
4465     __ Cmp(left, 0);
4466     __ Ccmp(right, 0, ZFlag, ne);
4467     //  - If so (eq), set N (mi) if left + right is negative.
4468     //  - Otherwise, clear N.
4469     __ Ccmn(left, right, NoFlag, eq);
4470     DeoptimizeIf(mi, instr, Deoptimizer::kMinusZero);
4471   }
4472
4473   if (can_overflow) {
4474     __ Smull(result.X(), left, right);
4475     __ Cmp(result.X(), Operand(result, SXTW));
4476     DeoptimizeIf(ne, instr, Deoptimizer::kOverflow);
4477   } else {
4478     __ Mul(result, left, right);
4479   }
4480 }
4481
4482
4483 void LCodeGen::DoMulS(LMulS* instr) {
4484   Register result = ToRegister(instr->result());
4485   Register left = ToRegister(instr->left());
4486   Register right = ToRegister(instr->right());
4487
4488   bool can_overflow = instr->hydrogen()->CheckFlag(HValue::kCanOverflow);
4489   bool bailout_on_minus_zero =
4490     instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero);
4491
4492   if (bailout_on_minus_zero && !left.Is(right)) {
4493     // If one operand is zero and the other is negative, the result is -0.
4494     //  - Set Z (eq) if either left or right, or both, are 0.
4495     __ Cmp(left, 0);
4496     __ Ccmp(right, 0, ZFlag, ne);
4497     //  - If so (eq), set N (mi) if left + right is negative.
4498     //  - Otherwise, clear N.
4499     __ Ccmn(left, right, NoFlag, eq);
4500     DeoptimizeIf(mi, instr, Deoptimizer::kMinusZero);
4501   }
4502
4503   STATIC_ASSERT((kSmiShift == 32) && (kSmiTag == 0));
4504   if (can_overflow) {
4505     __ Smulh(result, left, right);
4506     __ Cmp(result, Operand(result.W(), SXTW));
4507     __ SmiTag(result);
4508     DeoptimizeIf(ne, instr, Deoptimizer::kOverflow);
4509   } else {
4510     if (AreAliased(result, left, right)) {
4511       // All three registers are the same: half untag the input and then
4512       // multiply, giving a tagged result.
4513       STATIC_ASSERT((kSmiShift % 2) == 0);
4514       __ Asr(result, left, kSmiShift / 2);
4515       __ Mul(result, result, result);
4516     } else if (result.Is(left) && !left.Is(right)) {
4517       // Registers result and left alias, right is distinct: untag left into
4518       // result, and then multiply by right, giving a tagged result.
4519       __ SmiUntag(result, left);
4520       __ Mul(result, result, right);
4521     } else {
4522       DCHECK(!left.Is(result));
4523       // Registers result and right alias, left is distinct, or all registers
4524       // are distinct: untag right into result, and then multiply by left,
4525       // giving a tagged result.
4526       __ SmiUntag(result, right);
4527       __ Mul(result, left, result);
4528     }
4529   }
4530 }
4531
4532
4533 void LCodeGen::DoDeferredNumberTagD(LNumberTagD* instr) {
4534   // TODO(3095996): Get rid of this. For now, we need to make the
4535   // result register contain a valid pointer because it is already
4536   // contained in the register pointer map.
4537   Register result = ToRegister(instr->result());
4538   __ Mov(result, 0);
4539
4540   PushSafepointRegistersScope scope(this);
4541   // NumberTagU and NumberTagD use the context from the frame, rather than
4542   // the environment's HContext or HInlinedContext value.
4543   // They only call Runtime::kAllocateHeapNumber.
4544   // The corresponding HChange instructions are added in a phase that does
4545   // not have easy access to the local context.
4546   __ Ldr(cp, MemOperand(fp, StandardFrameConstants::kContextOffset));
4547   __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
4548   RecordSafepointWithRegisters(
4549       instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
4550   __ StoreToSafepointRegisterSlot(x0, result);
4551 }
4552
4553
4554 void LCodeGen::DoNumberTagD(LNumberTagD* instr) {
4555   class DeferredNumberTagD: public LDeferredCode {
4556    public:
4557     DeferredNumberTagD(LCodeGen* codegen, LNumberTagD* instr)
4558         : LDeferredCode(codegen), instr_(instr) { }
4559     virtual void Generate() { codegen()->DoDeferredNumberTagD(instr_); }
4560     virtual LInstruction* instr() { return instr_; }
4561    private:
4562     LNumberTagD* instr_;
4563   };
4564
4565   DoubleRegister input = ToDoubleRegister(instr->value());
4566   Register result = ToRegister(instr->result());
4567   Register temp1 = ToRegister(instr->temp1());
4568   Register temp2 = ToRegister(instr->temp2());
4569
4570   DeferredNumberTagD* deferred = new(zone()) DeferredNumberTagD(this, instr);
4571   if (FLAG_inline_new) {
4572     __ AllocateHeapNumber(result, deferred->entry(), temp1, temp2);
4573   } else {
4574     __ B(deferred->entry());
4575   }
4576
4577   __ Bind(deferred->exit());
4578   __ Str(input, FieldMemOperand(result, HeapNumber::kValueOffset));
4579 }
4580
4581
4582 void LCodeGen::DoDeferredNumberTagU(LInstruction* instr,
4583                                     LOperand* value,
4584                                     LOperand* temp1,
4585                                     LOperand* temp2) {
4586   Label slow, convert_and_store;
4587   Register src = ToRegister32(value);
4588   Register dst = ToRegister(instr->result());
4589   Register scratch1 = ToRegister(temp1);
4590
4591   if (FLAG_inline_new) {
4592     Register scratch2 = ToRegister(temp2);
4593     __ AllocateHeapNumber(dst, &slow, scratch1, scratch2);
4594     __ B(&convert_and_store);
4595   }
4596
4597   // Slow case: call the runtime system to do the number allocation.
4598   __ Bind(&slow);
4599   // TODO(3095996): Put a valid pointer value in the stack slot where the result
4600   // register is stored, as this register is in the pointer map, but contains an
4601   // integer value.
4602   __ Mov(dst, 0);
4603   {
4604     // Preserve the value of all registers.
4605     PushSafepointRegistersScope scope(this);
4606
4607     // NumberTagU and NumberTagD use the context from the frame, rather than
4608     // the environment's HContext or HInlinedContext value.
4609     // They only call Runtime::kAllocateHeapNumber.
4610     // The corresponding HChange instructions are added in a phase that does
4611     // not have easy access to the local context.
4612     __ Ldr(cp, MemOperand(fp, StandardFrameConstants::kContextOffset));
4613     __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
4614     RecordSafepointWithRegisters(
4615       instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
4616     __ StoreToSafepointRegisterSlot(x0, dst);
4617   }
4618
4619   // Convert number to floating point and store in the newly allocated heap
4620   // number.
4621   __ Bind(&convert_and_store);
4622   DoubleRegister dbl_scratch = double_scratch();
4623   __ Ucvtf(dbl_scratch, src);
4624   __ Str(dbl_scratch, FieldMemOperand(dst, HeapNumber::kValueOffset));
4625 }
4626
4627
4628 void LCodeGen::DoNumberTagU(LNumberTagU* instr) {
4629   class DeferredNumberTagU: public LDeferredCode {
4630    public:
4631     DeferredNumberTagU(LCodeGen* codegen, LNumberTagU* instr)
4632         : LDeferredCode(codegen), instr_(instr) { }
4633     virtual void Generate() {
4634       codegen()->DoDeferredNumberTagU(instr_,
4635                                       instr_->value(),
4636                                       instr_->temp1(),
4637                                       instr_->temp2());
4638     }
4639     virtual LInstruction* instr() { return instr_; }
4640    private:
4641     LNumberTagU* instr_;
4642   };
4643
4644   Register value = ToRegister32(instr->value());
4645   Register result = ToRegister(instr->result());
4646
4647   DeferredNumberTagU* deferred = new(zone()) DeferredNumberTagU(this, instr);
4648   __ Cmp(value, Smi::kMaxValue);
4649   __ B(hi, deferred->entry());
4650   __ SmiTag(result, value.X());
4651   __ Bind(deferred->exit());
4652 }
4653
4654
4655 void LCodeGen::DoNumberUntagD(LNumberUntagD* instr) {
4656   Register input = ToRegister(instr->value());
4657   Register scratch = ToRegister(instr->temp());
4658   DoubleRegister result = ToDoubleRegister(instr->result());
4659   bool can_convert_undefined_to_nan =
4660       instr->hydrogen()->can_convert_undefined_to_nan();
4661
4662   Label done, load_smi;
4663
4664   // Work out what untag mode we're working with.
4665   HValue* value = instr->hydrogen()->value();
4666   NumberUntagDMode mode = value->representation().IsSmi()
4667       ? NUMBER_CANDIDATE_IS_SMI : NUMBER_CANDIDATE_IS_ANY_TAGGED;
4668
4669   if (mode == NUMBER_CANDIDATE_IS_ANY_TAGGED) {
4670     __ JumpIfSmi(input, &load_smi);
4671
4672     Label convert_undefined;
4673
4674     // Heap number map check.
4675     if (can_convert_undefined_to_nan) {
4676       __ JumpIfNotHeapNumber(input, &convert_undefined);
4677     } else {
4678       DeoptimizeIfNotHeapNumber(input, instr);
4679     }
4680
4681     // Load heap number.
4682     __ Ldr(result, FieldMemOperand(input, HeapNumber::kValueOffset));
4683     if (instr->hydrogen()->deoptimize_on_minus_zero()) {
4684       DeoptimizeIfMinusZero(result, instr, Deoptimizer::kMinusZero);
4685     }
4686     __ B(&done);
4687
4688     if (can_convert_undefined_to_nan) {
4689       __ Bind(&convert_undefined);
4690       DeoptimizeIfNotRoot(input, Heap::kUndefinedValueRootIndex, instr,
4691                           Deoptimizer::kNotAHeapNumberUndefined);
4692
4693       __ LoadRoot(scratch, Heap::kNanValueRootIndex);
4694       __ Ldr(result, FieldMemOperand(scratch, HeapNumber::kValueOffset));
4695       __ B(&done);
4696     }
4697
4698   } else {
4699     DCHECK(mode == NUMBER_CANDIDATE_IS_SMI);
4700     // Fall through to load_smi.
4701   }
4702
4703   // Smi to double register conversion.
4704   __ Bind(&load_smi);
4705   __ SmiUntagToDouble(result, input);
4706
4707   __ Bind(&done);
4708 }
4709
4710
4711 void LCodeGen::DoOsrEntry(LOsrEntry* instr) {
4712   // This is a pseudo-instruction that ensures that the environment here is
4713   // properly registered for deoptimization and records the assembler's PC
4714   // offset.
4715   LEnvironment* environment = instr->environment();
4716
4717   // If the environment were already registered, we would have no way of
4718   // backpatching it with the spill slot operands.
4719   DCHECK(!environment->HasBeenRegistered());
4720   RegisterEnvironmentForDeoptimization(environment, Safepoint::kNoLazyDeopt);
4721
4722   GenerateOsrPrologue();
4723 }
4724
4725
4726 void LCodeGen::DoParameter(LParameter* instr) {
4727   // Nothing to do.
4728 }
4729
4730
4731 void LCodeGen::DoPreparePushArguments(LPreparePushArguments* instr) {
4732   __ PushPreamble(instr->argc(), kPointerSize);
4733 }
4734
4735
4736 void LCodeGen::DoPushArguments(LPushArguments* instr) {
4737   MacroAssembler::PushPopQueue args(masm());
4738
4739   for (int i = 0; i < instr->ArgumentCount(); ++i) {
4740     LOperand* arg = instr->argument(i);
4741     if (arg->IsDoubleRegister() || arg->IsDoubleStackSlot()) {
4742       Abort(kDoPushArgumentNotImplementedForDoubleType);
4743       return;
4744     }
4745     args.Queue(ToRegister(arg));
4746   }
4747
4748   // The preamble was done by LPreparePushArguments.
4749   args.PushQueued(MacroAssembler::PushPopQueue::SKIP_PREAMBLE);
4750
4751   RecordPushedArgumentsDelta(instr->ArgumentCount());
4752 }
4753
4754
4755 void LCodeGen::DoReturn(LReturn* instr) {
4756   if (FLAG_trace && info()->IsOptimizing()) {
4757     // Push the return value on the stack as the parameter.
4758     // Runtime::TraceExit returns its parameter in x0.  We're leaving the code
4759     // managed by the register allocator and tearing down the frame, it's
4760     // safe to write to the context register.
4761     __ Push(x0);
4762     __ Ldr(cp, MemOperand(fp, StandardFrameConstants::kContextOffset));
4763     __ CallRuntime(Runtime::kTraceExit, 1);
4764   }
4765
4766   if (info()->saves_caller_doubles()) {
4767     RestoreCallerDoubles();
4768   }
4769
4770   int no_frame_start = -1;
4771   if (NeedsEagerFrame()) {
4772     Register stack_pointer = masm()->StackPointer();
4773     __ Mov(stack_pointer, fp);
4774     no_frame_start = masm_->pc_offset();
4775     __ Pop(fp, lr);
4776   }
4777
4778   if (instr->has_constant_parameter_count()) {
4779     int parameter_count = ToInteger32(instr->constant_parameter_count());
4780     __ Drop(parameter_count + 1);
4781   } else {
4782     DCHECK(info()->IsStub());  // Functions would need to drop one more value.
4783     Register parameter_count = ToRegister(instr->parameter_count());
4784     __ DropBySMI(parameter_count);
4785   }
4786   __ Ret();
4787
4788   if (no_frame_start != -1) {
4789     info_->AddNoFrameRange(no_frame_start, masm_->pc_offset());
4790   }
4791 }
4792
4793
4794 MemOperand LCodeGen::BuildSeqStringOperand(Register string,
4795                                            Register temp,
4796                                            LOperand* index,
4797                                            String::Encoding encoding) {
4798   if (index->IsConstantOperand()) {
4799     int offset = ToInteger32(LConstantOperand::cast(index));
4800     if (encoding == String::TWO_BYTE_ENCODING) {
4801       offset *= kUC16Size;
4802     }
4803     STATIC_ASSERT(kCharSize == 1);
4804     return FieldMemOperand(string, SeqString::kHeaderSize + offset);
4805   }
4806
4807   __ Add(temp, string, SeqString::kHeaderSize - kHeapObjectTag);
4808   if (encoding == String::ONE_BYTE_ENCODING) {
4809     return MemOperand(temp, ToRegister32(index), SXTW);
4810   } else {
4811     STATIC_ASSERT(kUC16Size == 2);
4812     return MemOperand(temp, ToRegister32(index), SXTW, 1);
4813   }
4814 }
4815
4816
4817 void LCodeGen::DoSeqStringGetChar(LSeqStringGetChar* instr) {
4818   String::Encoding encoding = instr->hydrogen()->encoding();
4819   Register string = ToRegister(instr->string());
4820   Register result = ToRegister(instr->result());
4821   Register temp = ToRegister(instr->temp());
4822
4823   if (FLAG_debug_code) {
4824     // Even though this lithium instruction comes with a temp register, we
4825     // can't use it here because we want to use "AtStart" constraints on the
4826     // inputs and the debug code here needs a scratch register.
4827     UseScratchRegisterScope temps(masm());
4828     Register dbg_temp = temps.AcquireX();
4829
4830     __ Ldr(dbg_temp, FieldMemOperand(string, HeapObject::kMapOffset));
4831     __ Ldrb(dbg_temp, FieldMemOperand(dbg_temp, Map::kInstanceTypeOffset));
4832
4833     __ And(dbg_temp, dbg_temp,
4834            Operand(kStringRepresentationMask | kStringEncodingMask));
4835     static const uint32_t one_byte_seq_type = kSeqStringTag | kOneByteStringTag;
4836     static const uint32_t two_byte_seq_type = kSeqStringTag | kTwoByteStringTag;
4837     __ Cmp(dbg_temp, Operand(encoding == String::ONE_BYTE_ENCODING
4838                              ? one_byte_seq_type : two_byte_seq_type));
4839     __ Check(eq, kUnexpectedStringType);
4840   }
4841
4842   MemOperand operand =
4843       BuildSeqStringOperand(string, temp, instr->index(), encoding);
4844   if (encoding == String::ONE_BYTE_ENCODING) {
4845     __ Ldrb(result, operand);
4846   } else {
4847     __ Ldrh(result, operand);
4848   }
4849 }
4850
4851
4852 void LCodeGen::DoSeqStringSetChar(LSeqStringSetChar* instr) {
4853   String::Encoding encoding = instr->hydrogen()->encoding();
4854   Register string = ToRegister(instr->string());
4855   Register value = ToRegister(instr->value());
4856   Register temp = ToRegister(instr->temp());
4857
4858   if (FLAG_debug_code) {
4859     DCHECK(ToRegister(instr->context()).is(cp));
4860     Register index = ToRegister(instr->index());
4861     static const uint32_t one_byte_seq_type = kSeqStringTag | kOneByteStringTag;
4862     static const uint32_t two_byte_seq_type = kSeqStringTag | kTwoByteStringTag;
4863     int encoding_mask =
4864         instr->hydrogen()->encoding() == String::ONE_BYTE_ENCODING
4865         ? one_byte_seq_type : two_byte_seq_type;
4866     __ EmitSeqStringSetCharCheck(string, index, kIndexIsInteger32, temp,
4867                                  encoding_mask);
4868   }
4869   MemOperand operand =
4870       BuildSeqStringOperand(string, temp, instr->index(), encoding);
4871   if (encoding == String::ONE_BYTE_ENCODING) {
4872     __ Strb(value, operand);
4873   } else {
4874     __ Strh(value, operand);
4875   }
4876 }
4877
4878
4879 void LCodeGen::DoSmiTag(LSmiTag* instr) {
4880   HChange* hchange = instr->hydrogen();
4881   Register input = ToRegister(instr->value());
4882   Register output = ToRegister(instr->result());
4883   if (hchange->CheckFlag(HValue::kCanOverflow) &&
4884       hchange->value()->CheckFlag(HValue::kUint32)) {
4885     DeoptimizeIfNegative(input.W(), instr, Deoptimizer::kOverflow);
4886   }
4887   __ SmiTag(output, input);
4888 }
4889
4890
4891 void LCodeGen::DoSmiUntag(LSmiUntag* instr) {
4892   Register input = ToRegister(instr->value());
4893   Register result = ToRegister(instr->result());
4894   Label done, untag;
4895
4896   if (instr->needs_check()) {
4897     DeoptimizeIfNotSmi(input, instr, Deoptimizer::kNotASmi);
4898   }
4899
4900   __ Bind(&untag);
4901   __ SmiUntag(result, input);
4902   __ Bind(&done);
4903 }
4904
4905
4906 void LCodeGen::DoShiftI(LShiftI* instr) {
4907   LOperand* right_op = instr->right();
4908   Register left = ToRegister32(instr->left());
4909   Register result = ToRegister32(instr->result());
4910
4911   if (right_op->IsRegister()) {
4912     Register right = ToRegister32(instr->right());
4913     switch (instr->op()) {
4914       case Token::ROR: __ Ror(result, left, right); break;
4915       case Token::SAR: __ Asr(result, left, right); break;
4916       case Token::SHL: __ Lsl(result, left, right); break;
4917       case Token::SHR:
4918         __ Lsr(result, left, right);
4919         if (instr->can_deopt()) {
4920           // If `left >>> right` >= 0x80000000, the result is not representable
4921           // in a signed 32-bit smi.
4922           DeoptimizeIfNegative(result, instr, Deoptimizer::kNegativeValue);
4923         }
4924         break;
4925       default: UNREACHABLE();
4926     }
4927   } else {
4928     DCHECK(right_op->IsConstantOperand());
4929     int shift_count = JSShiftAmountFromLConstant(right_op);
4930     if (shift_count == 0) {
4931       if ((instr->op() == Token::SHR) && instr->can_deopt()) {
4932         DeoptimizeIfNegative(left, instr, Deoptimizer::kNegativeValue);
4933       }
4934       __ Mov(result, left, kDiscardForSameWReg);
4935     } else {
4936       switch (instr->op()) {
4937         case Token::ROR: __ Ror(result, left, shift_count); break;
4938         case Token::SAR: __ Asr(result, left, shift_count); break;
4939         case Token::SHL: __ Lsl(result, left, shift_count); break;
4940         case Token::SHR: __ Lsr(result, left, shift_count); break;
4941         default: UNREACHABLE();
4942       }
4943     }
4944   }
4945 }
4946
4947
4948 void LCodeGen::DoShiftS(LShiftS* instr) {
4949   LOperand* right_op = instr->right();
4950   Register left = ToRegister(instr->left());
4951   Register result = ToRegister(instr->result());
4952
4953   if (right_op->IsRegister()) {
4954     Register right = ToRegister(instr->right());
4955
4956     // JavaScript shifts only look at the bottom 5 bits of the 'right' operand.
4957     // Since we're handling smis in X registers, we have to extract these bits
4958     // explicitly.
4959     __ Ubfx(result, right, kSmiShift, 5);
4960
4961     switch (instr->op()) {
4962       case Token::ROR: {
4963         // This is the only case that needs a scratch register. To keep things
4964         // simple for the other cases, borrow a MacroAssembler scratch register.
4965         UseScratchRegisterScope temps(masm());
4966         Register temp = temps.AcquireW();
4967         __ SmiUntag(temp, left);
4968         __ Ror(result.W(), temp.W(), result.W());
4969         __ SmiTag(result);
4970         break;
4971       }
4972       case Token::SAR:
4973         __ Asr(result, left, result);
4974         __ Bic(result, result, kSmiShiftMask);
4975         break;
4976       case Token::SHL:
4977         __ Lsl(result, left, result);
4978         break;
4979       case Token::SHR:
4980         __ Lsr(result, left, result);
4981         __ Bic(result, result, kSmiShiftMask);
4982         if (instr->can_deopt()) {
4983           // If `left >>> right` >= 0x80000000, the result is not representable
4984           // in a signed 32-bit smi.
4985           DeoptimizeIfNegative(result, instr, Deoptimizer::kNegativeValue);
4986         }
4987         break;
4988       default: UNREACHABLE();
4989     }
4990   } else {
4991     DCHECK(right_op->IsConstantOperand());
4992     int shift_count = JSShiftAmountFromLConstant(right_op);
4993     if (shift_count == 0) {
4994       if ((instr->op() == Token::SHR) && instr->can_deopt()) {
4995         DeoptimizeIfNegative(left, instr, Deoptimizer::kNegativeValue);
4996       }
4997       __ Mov(result, left);
4998     } else {
4999       switch (instr->op()) {
5000         case Token::ROR:
5001           __ SmiUntag(result, left);
5002           __ Ror(result.W(), result.W(), shift_count);
5003           __ SmiTag(result);
5004           break;
5005         case Token::SAR:
5006           __ Asr(result, left, shift_count);
5007           __ Bic(result, result, kSmiShiftMask);
5008           break;
5009         case Token::SHL:
5010           __ Lsl(result, left, shift_count);
5011           break;
5012         case Token::SHR:
5013           __ Lsr(result, left, shift_count);
5014           __ Bic(result, result, kSmiShiftMask);
5015           break;
5016         default: UNREACHABLE();
5017       }
5018     }
5019   }
5020 }
5021
5022
5023 void LCodeGen::DoDebugBreak(LDebugBreak* instr) {
5024   __ Debug("LDebugBreak", 0, BREAK);
5025 }
5026
5027
5028 void LCodeGen::DoDeclareGlobals(LDeclareGlobals* instr) {
5029   DCHECK(ToRegister(instr->context()).is(cp));
5030   Register scratch1 = x5;
5031   Register scratch2 = x6;
5032   DCHECK(instr->IsMarkedAsCall());
5033
5034   // TODO(all): if Mov could handle object in new space then it could be used
5035   // here.
5036   __ LoadHeapObject(scratch1, instr->hydrogen()->pairs());
5037   __ Mov(scratch2, Smi::FromInt(instr->hydrogen()->flags()));
5038   __ Push(cp, scratch1, scratch2);  // The context is the first argument.
5039   CallRuntime(Runtime::kDeclareGlobals, 3, instr);
5040 }
5041
5042
5043 void LCodeGen::DoDeferredStackCheck(LStackCheck* instr) {
5044   PushSafepointRegistersScope scope(this);
5045   LoadContextFromDeferred(instr->context());
5046   __ CallRuntimeSaveDoubles(Runtime::kStackGuard);
5047   RecordSafepointWithLazyDeopt(
5048       instr, RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
5049   DCHECK(instr->HasEnvironment());
5050   LEnvironment* env = instr->environment();
5051   safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
5052 }
5053
5054
5055 void LCodeGen::DoStackCheck(LStackCheck* instr) {
5056   class DeferredStackCheck: public LDeferredCode {
5057    public:
5058     DeferredStackCheck(LCodeGen* codegen, LStackCheck* instr)
5059         : LDeferredCode(codegen), instr_(instr) { }
5060     virtual void Generate() { codegen()->DoDeferredStackCheck(instr_); }
5061     virtual LInstruction* instr() { return instr_; }
5062    private:
5063     LStackCheck* instr_;
5064   };
5065
5066   DCHECK(instr->HasEnvironment());
5067   LEnvironment* env = instr->environment();
5068   // There is no LLazyBailout instruction for stack-checks. We have to
5069   // prepare for lazy deoptimization explicitly here.
5070   if (instr->hydrogen()->is_function_entry()) {
5071     // Perform stack overflow check.
5072     Label done;
5073     __ CompareRoot(masm()->StackPointer(), Heap::kStackLimitRootIndex);
5074     __ B(hs, &done);
5075
5076     PredictableCodeSizeScope predictable(masm_,
5077                                          Assembler::kCallSizeWithRelocation);
5078     DCHECK(instr->context()->IsRegister());
5079     DCHECK(ToRegister(instr->context()).is(cp));
5080     CallCode(isolate()->builtins()->StackCheck(),
5081              RelocInfo::CODE_TARGET,
5082              instr);
5083     __ Bind(&done);
5084   } else {
5085     DCHECK(instr->hydrogen()->is_backwards_branch());
5086     // Perform stack overflow check if this goto needs it before jumping.
5087     DeferredStackCheck* deferred_stack_check =
5088         new(zone()) DeferredStackCheck(this, instr);
5089     __ CompareRoot(masm()->StackPointer(), Heap::kStackLimitRootIndex);
5090     __ B(lo, deferred_stack_check->entry());
5091
5092     EnsureSpaceForLazyDeopt(Deoptimizer::patch_size());
5093     __ Bind(instr->done_label());
5094     deferred_stack_check->SetExit(instr->done_label());
5095     RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt);
5096     // Don't record a deoptimization index for the safepoint here.
5097     // This will be done explicitly when emitting call and the safepoint in
5098     // the deferred code.
5099   }
5100 }
5101
5102
5103 void LCodeGen::DoStoreCodeEntry(LStoreCodeEntry* instr) {
5104   Register function = ToRegister(instr->function());
5105   Register code_object = ToRegister(instr->code_object());
5106   Register temp = ToRegister(instr->temp());
5107   __ Add(temp, code_object, Code::kHeaderSize - kHeapObjectTag);
5108   __ Str(temp, FieldMemOperand(function, JSFunction::kCodeEntryOffset));
5109 }
5110
5111
5112 void LCodeGen::DoStoreContextSlot(LStoreContextSlot* instr) {
5113   Register context = ToRegister(instr->context());
5114   Register value = ToRegister(instr->value());
5115   Register scratch = ToRegister(instr->temp());
5116   MemOperand target = ContextMemOperand(context, instr->slot_index());
5117
5118   Label skip_assignment;
5119
5120   if (instr->hydrogen()->RequiresHoleCheck()) {
5121     __ Ldr(scratch, target);
5122     if (instr->hydrogen()->DeoptimizesOnHole()) {
5123       DeoptimizeIfRoot(scratch, Heap::kTheHoleValueRootIndex, instr,
5124                        Deoptimizer::kHole);
5125     } else {
5126       __ JumpIfNotRoot(scratch, Heap::kTheHoleValueRootIndex, &skip_assignment);
5127     }
5128   }
5129
5130   __ Str(value, target);
5131   if (instr->hydrogen()->NeedsWriteBarrier()) {
5132     SmiCheck check_needed =
5133         instr->hydrogen()->value()->type().IsHeapObject()
5134             ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
5135     __ RecordWriteContextSlot(context, static_cast<int>(target.offset()), value,
5136                               scratch, GetLinkRegisterState(), kSaveFPRegs,
5137                               EMIT_REMEMBERED_SET, check_needed);
5138   }
5139   __ Bind(&skip_assignment);
5140 }
5141
5142
5143 void LCodeGen::DoStoreKeyedExternal(LStoreKeyedExternal* instr) {
5144   Register ext_ptr = ToRegister(instr->elements());
5145   Register key = no_reg;
5146   Register scratch;
5147   ElementsKind elements_kind = instr->elements_kind();
5148
5149   bool key_is_smi = instr->hydrogen()->key()->representation().IsSmi();
5150   bool key_is_constant = instr->key()->IsConstantOperand();
5151   int constant_key = 0;
5152   if (key_is_constant) {
5153     DCHECK(instr->temp() == NULL);
5154     constant_key = ToInteger32(LConstantOperand::cast(instr->key()));
5155     if (constant_key & 0xf0000000) {
5156       Abort(kArrayIndexConstantValueTooBig);
5157     }
5158   } else {
5159     key = ToRegister(instr->key());
5160     scratch = ToRegister(instr->temp());
5161   }
5162
5163   MemOperand dst =
5164     PrepareKeyedExternalArrayOperand(key, ext_ptr, scratch, key_is_smi,
5165                                      key_is_constant, constant_key,
5166                                      elements_kind,
5167                                      instr->base_offset());
5168
5169   if (elements_kind == FLOAT32_ELEMENTS) {
5170     DoubleRegister value = ToDoubleRegister(instr->value());
5171     DoubleRegister dbl_scratch = double_scratch();
5172     __ Fcvt(dbl_scratch.S(), value);
5173     __ Str(dbl_scratch.S(), dst);
5174   } else if (elements_kind == FLOAT64_ELEMENTS) {
5175     DoubleRegister value = ToDoubleRegister(instr->value());
5176     __ Str(value, dst);
5177   } else {
5178     Register value = ToRegister(instr->value());
5179
5180     switch (elements_kind) {
5181       case UINT8_ELEMENTS:
5182       case UINT8_CLAMPED_ELEMENTS:
5183       case INT8_ELEMENTS:
5184         __ Strb(value, dst);
5185         break;
5186       case INT16_ELEMENTS:
5187       case UINT16_ELEMENTS:
5188         __ Strh(value, dst);
5189         break;
5190       case INT32_ELEMENTS:
5191       case UINT32_ELEMENTS:
5192         __ Str(value.W(), dst);
5193         break;
5194       case FLOAT32_ELEMENTS:
5195       case FLOAT64_ELEMENTS:
5196       case FAST_DOUBLE_ELEMENTS:
5197       case FAST_ELEMENTS:
5198       case FAST_SMI_ELEMENTS:
5199       case FAST_HOLEY_DOUBLE_ELEMENTS:
5200       case FAST_HOLEY_ELEMENTS:
5201       case FAST_HOLEY_SMI_ELEMENTS:
5202       case DICTIONARY_ELEMENTS:
5203       case FAST_SLOPPY_ARGUMENTS_ELEMENTS:
5204       case SLOW_SLOPPY_ARGUMENTS_ELEMENTS:
5205         UNREACHABLE();
5206         break;
5207     }
5208   }
5209 }
5210
5211
5212 void LCodeGen::DoStoreKeyedFixedDouble(LStoreKeyedFixedDouble* instr) {
5213   Register elements = ToRegister(instr->elements());
5214   DoubleRegister value = ToDoubleRegister(instr->value());
5215   MemOperand mem_op;
5216
5217   if (instr->key()->IsConstantOperand()) {
5218     int constant_key = ToInteger32(LConstantOperand::cast(instr->key()));
5219     if (constant_key & 0xf0000000) {
5220       Abort(kArrayIndexConstantValueTooBig);
5221     }
5222     int offset = instr->base_offset() + constant_key * kDoubleSize;
5223     mem_op = MemOperand(elements, offset);
5224   } else {
5225     Register store_base = ToRegister(instr->temp());
5226     Register key = ToRegister(instr->key());
5227     bool key_is_tagged = instr->hydrogen()->key()->representation().IsSmi();
5228     mem_op = PrepareKeyedArrayOperand(store_base, elements, key, key_is_tagged,
5229                                       instr->hydrogen()->elements_kind(),
5230                                       instr->hydrogen()->representation(),
5231                                       instr->base_offset());
5232   }
5233
5234   if (instr->NeedsCanonicalization()) {
5235     __ CanonicalizeNaN(double_scratch(), value);
5236     __ Str(double_scratch(), mem_op);
5237   } else {
5238     __ Str(value, mem_op);
5239   }
5240 }
5241
5242
5243 void LCodeGen::DoStoreKeyedFixed(LStoreKeyedFixed* instr) {
5244   Register value = ToRegister(instr->value());
5245   Register elements = ToRegister(instr->elements());
5246   Register scratch = no_reg;
5247   Register store_base = no_reg;
5248   Register key = no_reg;
5249   MemOperand mem_op;
5250
5251   if (!instr->key()->IsConstantOperand() ||
5252       instr->hydrogen()->NeedsWriteBarrier()) {
5253     scratch = ToRegister(instr->temp());
5254   }
5255
5256   Representation representation = instr->hydrogen()->value()->representation();
5257   if (instr->key()->IsConstantOperand()) {
5258     LConstantOperand* const_operand = LConstantOperand::cast(instr->key());
5259     int offset = instr->base_offset() +
5260         ToInteger32(const_operand) * kPointerSize;
5261     store_base = elements;
5262     if (representation.IsInteger32()) {
5263       DCHECK(instr->hydrogen()->store_mode() == STORE_TO_INITIALIZED_ENTRY);
5264       DCHECK(instr->hydrogen()->elements_kind() == FAST_SMI_ELEMENTS);
5265       STATIC_ASSERT(static_cast<unsigned>(kSmiValueSize) == kWRegSizeInBits);
5266       STATIC_ASSERT(kSmiTag == 0);
5267       mem_op = UntagSmiMemOperand(store_base, offset);
5268     } else {
5269       mem_op = MemOperand(store_base, offset);
5270     }
5271   } else {
5272     store_base = scratch;
5273     key = ToRegister(instr->key());
5274     bool key_is_tagged = instr->hydrogen()->key()->representation().IsSmi();
5275
5276     mem_op = PrepareKeyedArrayOperand(store_base, elements, key, key_is_tagged,
5277                                       instr->hydrogen()->elements_kind(),
5278                                       representation, instr->base_offset());
5279   }
5280
5281   __ Store(value, mem_op, representation);
5282
5283   if (instr->hydrogen()->NeedsWriteBarrier()) {
5284     DCHECK(representation.IsTagged());
5285     // This assignment may cause element_addr to alias store_base.
5286     Register element_addr = scratch;
5287     SmiCheck check_needed =
5288         instr->hydrogen()->value()->type().IsHeapObject()
5289             ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
5290     // Compute address of modified element and store it into key register.
5291     __ Add(element_addr, mem_op.base(), mem_op.OffsetAsOperand());
5292     __ RecordWrite(elements, element_addr, value, GetLinkRegisterState(),
5293                    kSaveFPRegs, EMIT_REMEMBERED_SET, check_needed,
5294                    instr->hydrogen()->PointersToHereCheckForValue());
5295   }
5296 }
5297
5298
5299 void LCodeGen::DoStoreKeyedGeneric(LStoreKeyedGeneric* instr) {
5300   DCHECK(ToRegister(instr->context()).is(cp));
5301   DCHECK(ToRegister(instr->object()).is(StoreDescriptor::ReceiverRegister()));
5302   DCHECK(ToRegister(instr->key()).is(StoreDescriptor::NameRegister()));
5303   DCHECK(ToRegister(instr->value()).is(StoreDescriptor::ValueRegister()));
5304
5305   if (instr->hydrogen()->HasVectorAndSlot()) {
5306     EmitVectorStoreICRegisters<LStoreKeyedGeneric>(instr);
5307   }
5308
5309   Handle<Code> ic = CodeFactory::KeyedStoreICInOptimizedCode(
5310                         isolate(), instr->language_mode(),
5311                         instr->hydrogen()->initialization_state()).code();
5312   CallCode(ic, RelocInfo::CODE_TARGET, instr);
5313 }
5314
5315
5316 void LCodeGen::DoMaybeGrowElements(LMaybeGrowElements* instr) {
5317   class DeferredMaybeGrowElements final : public LDeferredCode {
5318    public:
5319     DeferredMaybeGrowElements(LCodeGen* codegen, LMaybeGrowElements* instr)
5320         : LDeferredCode(codegen), instr_(instr) {}
5321     void Generate() override { codegen()->DoDeferredMaybeGrowElements(instr_); }
5322     LInstruction* instr() override { return instr_; }
5323
5324    private:
5325     LMaybeGrowElements* instr_;
5326   };
5327
5328   Register result = x0;
5329   DeferredMaybeGrowElements* deferred =
5330       new (zone()) DeferredMaybeGrowElements(this, instr);
5331   LOperand* key = instr->key();
5332   LOperand* current_capacity = instr->current_capacity();
5333
5334   DCHECK(instr->hydrogen()->key()->representation().IsInteger32());
5335   DCHECK(instr->hydrogen()->current_capacity()->representation().IsInteger32());
5336   DCHECK(key->IsConstantOperand() || key->IsRegister());
5337   DCHECK(current_capacity->IsConstantOperand() ||
5338          current_capacity->IsRegister());
5339
5340   if (key->IsConstantOperand() && current_capacity->IsConstantOperand()) {
5341     int32_t constant_key = ToInteger32(LConstantOperand::cast(key));
5342     int32_t constant_capacity =
5343         ToInteger32(LConstantOperand::cast(current_capacity));
5344     if (constant_key >= constant_capacity) {
5345       // Deferred case.
5346       __ B(deferred->entry());
5347     }
5348   } else if (key->IsConstantOperand()) {
5349     int32_t constant_key = ToInteger32(LConstantOperand::cast(key));
5350     __ Cmp(ToRegister(current_capacity), Operand(constant_key));
5351     __ B(le, deferred->entry());
5352   } else if (current_capacity->IsConstantOperand()) {
5353     int32_t constant_capacity =
5354         ToInteger32(LConstantOperand::cast(current_capacity));
5355     __ Cmp(ToRegister(key), Operand(constant_capacity));
5356     __ B(ge, deferred->entry());
5357   } else {
5358     __ Cmp(ToRegister(key), ToRegister(current_capacity));
5359     __ B(ge, deferred->entry());
5360   }
5361
5362   __ Mov(result, ToRegister(instr->elements()));
5363
5364   __ Bind(deferred->exit());
5365 }
5366
5367
5368 void LCodeGen::DoDeferredMaybeGrowElements(LMaybeGrowElements* instr) {
5369   // TODO(3095996): Get rid of this. For now, we need to make the
5370   // result register contain a valid pointer because it is already
5371   // contained in the register pointer map.
5372   Register result = x0;
5373   __ Mov(result, 0);
5374
5375   // We have to call a stub.
5376   {
5377     PushSafepointRegistersScope scope(this);
5378     __ Move(result, ToRegister(instr->object()));
5379
5380     LOperand* key = instr->key();
5381     if (key->IsConstantOperand()) {
5382       __ Mov(x3, Operand(ToSmi(LConstantOperand::cast(key))));
5383     } else {
5384       __ Mov(x3, ToRegister(key));
5385       __ SmiTag(x3);
5386     }
5387
5388     GrowArrayElementsStub stub(isolate(), instr->hydrogen()->is_js_array(),
5389                                instr->hydrogen()->kind());
5390     __ CallStub(&stub);
5391     RecordSafepointWithLazyDeopt(
5392         instr, RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
5393     __ StoreToSafepointRegisterSlot(result, result);
5394   }
5395
5396   // Deopt on smi, which means the elements array changed to dictionary mode.
5397   DeoptimizeIfSmi(result, instr, Deoptimizer::kSmi);
5398 }
5399
5400
5401 void LCodeGen::DoStoreNamedField(LStoreNamedField* instr) {
5402   Representation representation = instr->representation();
5403
5404   Register object = ToRegister(instr->object());
5405   HObjectAccess access = instr->hydrogen()->access();
5406   int offset = access.offset();
5407
5408   if (access.IsExternalMemory()) {
5409     DCHECK(!instr->hydrogen()->has_transition());
5410     DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
5411     Register value = ToRegister(instr->value());
5412     __ Store(value, MemOperand(object, offset), representation);
5413     return;
5414   }
5415
5416   __ AssertNotSmi(object);
5417
5418   if (!FLAG_unbox_double_fields && representation.IsDouble()) {
5419     DCHECK(access.IsInobject());
5420     DCHECK(!instr->hydrogen()->has_transition());
5421     DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
5422     FPRegister value = ToDoubleRegister(instr->value());
5423     __ Str(value, FieldMemOperand(object, offset));
5424     return;
5425   }
5426
5427   DCHECK(!representation.IsSmi() ||
5428          !instr->value()->IsConstantOperand() ||
5429          IsInteger32Constant(LConstantOperand::cast(instr->value())));
5430
5431   if (instr->hydrogen()->has_transition()) {
5432     Handle<Map> transition = instr->hydrogen()->transition_map();
5433     AddDeprecationDependency(transition);
5434     // Store the new map value.
5435     Register new_map_value = ToRegister(instr->temp0());
5436     __ Mov(new_map_value, Operand(transition));
5437     __ Str(new_map_value, FieldMemOperand(object, HeapObject::kMapOffset));
5438     if (instr->hydrogen()->NeedsWriteBarrierForMap()) {
5439       // Update the write barrier for the map field.
5440       __ RecordWriteForMap(object,
5441                            new_map_value,
5442                            ToRegister(instr->temp1()),
5443                            GetLinkRegisterState(),
5444                            kSaveFPRegs);
5445     }
5446   }
5447
5448   // Do the store.
5449   Register destination;
5450   if (access.IsInobject()) {
5451     destination = object;
5452   } else {
5453     Register temp0 = ToRegister(instr->temp0());
5454     __ Ldr(temp0, FieldMemOperand(object, JSObject::kPropertiesOffset));
5455     destination = temp0;
5456   }
5457
5458   if (FLAG_unbox_double_fields && representation.IsDouble()) {
5459     DCHECK(access.IsInobject());
5460     FPRegister value = ToDoubleRegister(instr->value());
5461     __ Str(value, FieldMemOperand(object, offset));
5462   } else if (representation.IsSmi() &&
5463              instr->hydrogen()->value()->representation().IsInteger32()) {
5464     DCHECK(instr->hydrogen()->store_mode() == STORE_TO_INITIALIZED_ENTRY);
5465 #ifdef DEBUG
5466     Register temp0 = ToRegister(instr->temp0());
5467     __ Ldr(temp0, FieldMemOperand(destination, offset));
5468     __ AssertSmi(temp0);
5469     // If destination aliased temp0, restore it to the address calculated
5470     // earlier.
5471     if (destination.Is(temp0)) {
5472       DCHECK(!access.IsInobject());
5473       __ Ldr(destination, FieldMemOperand(object, JSObject::kPropertiesOffset));
5474     }
5475 #endif
5476     STATIC_ASSERT(static_cast<unsigned>(kSmiValueSize) == kWRegSizeInBits);
5477     STATIC_ASSERT(kSmiTag == 0);
5478     Register value = ToRegister(instr->value());
5479     __ Store(value, UntagSmiFieldMemOperand(destination, offset),
5480              Representation::Integer32());
5481   } else {
5482     Register value = ToRegister(instr->value());
5483     __ Store(value, FieldMemOperand(destination, offset), representation);
5484   }
5485   if (instr->hydrogen()->NeedsWriteBarrier()) {
5486     Register value = ToRegister(instr->value());
5487     __ RecordWriteField(destination,
5488                         offset,
5489                         value,                        // Clobbered.
5490                         ToRegister(instr->temp1()),   // Clobbered.
5491                         GetLinkRegisterState(),
5492                         kSaveFPRegs,
5493                         EMIT_REMEMBERED_SET,
5494                         instr->hydrogen()->SmiCheckForWriteBarrier(),
5495                         instr->hydrogen()->PointersToHereCheckForValue());
5496   }
5497 }
5498
5499
5500 void LCodeGen::DoStoreNamedGeneric(LStoreNamedGeneric* instr) {
5501   DCHECK(ToRegister(instr->context()).is(cp));
5502   DCHECK(ToRegister(instr->object()).is(StoreDescriptor::ReceiverRegister()));
5503   DCHECK(ToRegister(instr->value()).is(StoreDescriptor::ValueRegister()));
5504
5505   if (instr->hydrogen()->HasVectorAndSlot()) {
5506     EmitVectorStoreICRegisters<LStoreNamedGeneric>(instr);
5507   }
5508
5509   __ Mov(StoreDescriptor::NameRegister(), Operand(instr->name()));
5510   Handle<Code> ic = CodeFactory::StoreICInOptimizedCode(
5511                         isolate(), instr->language_mode(),
5512                         instr->hydrogen()->initialization_state()).code();
5513   CallCode(ic, RelocInfo::CODE_TARGET, instr);
5514 }
5515
5516
5517 void LCodeGen::DoStoreGlobalViaContext(LStoreGlobalViaContext* instr) {
5518   DCHECK(ToRegister(instr->context()).is(cp));
5519   DCHECK(ToRegister(instr->value())
5520              .is(StoreGlobalViaContextDescriptor::ValueRegister()));
5521
5522   int const slot = instr->slot_index();
5523   int const depth = instr->depth();
5524   if (depth <= StoreGlobalViaContextStub::kMaximumDepth) {
5525     __ Mov(StoreGlobalViaContextDescriptor::SlotRegister(), Operand(slot));
5526     Handle<Code> stub = CodeFactory::StoreGlobalViaContext(
5527                             isolate(), depth, instr->language_mode())
5528                             .code();
5529     CallCode(stub, RelocInfo::CODE_TARGET, instr);
5530   } else {
5531     __ Push(Smi::FromInt(slot));
5532     __ Push(StoreGlobalViaContextDescriptor::ValueRegister());
5533     __ CallRuntime(is_strict(instr->language_mode())
5534                        ? Runtime::kStoreGlobalViaContext_Strict
5535                        : Runtime::kStoreGlobalViaContext_Sloppy,
5536                    2);
5537   }
5538 }
5539
5540
5541 void LCodeGen::DoStringAdd(LStringAdd* instr) {
5542   DCHECK(ToRegister(instr->context()).is(cp));
5543   DCHECK(ToRegister(instr->left()).Is(x1));
5544   DCHECK(ToRegister(instr->right()).Is(x0));
5545   StringAddStub stub(isolate(),
5546                      instr->hydrogen()->flags(),
5547                      instr->hydrogen()->pretenure_flag());
5548   CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
5549 }
5550
5551
5552 void LCodeGen::DoStringCharCodeAt(LStringCharCodeAt* instr) {
5553   class DeferredStringCharCodeAt: public LDeferredCode {
5554    public:
5555     DeferredStringCharCodeAt(LCodeGen* codegen, LStringCharCodeAt* instr)
5556         : LDeferredCode(codegen), instr_(instr) { }
5557     virtual void Generate() { codegen()->DoDeferredStringCharCodeAt(instr_); }
5558     virtual LInstruction* instr() { return instr_; }
5559    private:
5560     LStringCharCodeAt* instr_;
5561   };
5562
5563   DeferredStringCharCodeAt* deferred =
5564       new(zone()) DeferredStringCharCodeAt(this, instr);
5565
5566   StringCharLoadGenerator::Generate(masm(),
5567                                     ToRegister(instr->string()),
5568                                     ToRegister32(instr->index()),
5569                                     ToRegister(instr->result()),
5570                                     deferred->entry());
5571   __ Bind(deferred->exit());
5572 }
5573
5574
5575 void LCodeGen::DoDeferredStringCharCodeAt(LStringCharCodeAt* instr) {
5576   Register string = ToRegister(instr->string());
5577   Register result = ToRegister(instr->result());
5578
5579   // TODO(3095996): Get rid of this. For now, we need to make the
5580   // result register contain a valid pointer because it is already
5581   // contained in the register pointer map.
5582   __ Mov(result, 0);
5583
5584   PushSafepointRegistersScope scope(this);
5585   __ Push(string);
5586   // Push the index as a smi. This is safe because of the checks in
5587   // DoStringCharCodeAt above.
5588   Register index = ToRegister(instr->index());
5589   __ SmiTagAndPush(index);
5590
5591   CallRuntimeFromDeferred(Runtime::kStringCharCodeAtRT, 2, instr,
5592                           instr->context());
5593   __ AssertSmi(x0);
5594   __ SmiUntag(x0);
5595   __ StoreToSafepointRegisterSlot(x0, result);
5596 }
5597
5598
5599 void LCodeGen::DoStringCharFromCode(LStringCharFromCode* instr) {
5600   class DeferredStringCharFromCode: public LDeferredCode {
5601    public:
5602     DeferredStringCharFromCode(LCodeGen* codegen, LStringCharFromCode* instr)
5603         : LDeferredCode(codegen), instr_(instr) { }
5604     virtual void Generate() { codegen()->DoDeferredStringCharFromCode(instr_); }
5605     virtual LInstruction* instr() { return instr_; }
5606    private:
5607     LStringCharFromCode* instr_;
5608   };
5609
5610   DeferredStringCharFromCode* deferred =
5611       new(zone()) DeferredStringCharFromCode(this, instr);
5612
5613   DCHECK(instr->hydrogen()->value()->representation().IsInteger32());
5614   Register char_code = ToRegister32(instr->char_code());
5615   Register result = ToRegister(instr->result());
5616
5617   __ Cmp(char_code, String::kMaxOneByteCharCode);
5618   __ B(hi, deferred->entry());
5619   __ LoadRoot(result, Heap::kSingleCharacterStringCacheRootIndex);
5620   __ Add(result, result, FixedArray::kHeaderSize - kHeapObjectTag);
5621   __ Ldr(result, MemOperand(result, char_code, SXTW, kPointerSizeLog2));
5622   __ CompareRoot(result, Heap::kUndefinedValueRootIndex);
5623   __ B(eq, deferred->entry());
5624   __ Bind(deferred->exit());
5625 }
5626
5627
5628 void LCodeGen::DoDeferredStringCharFromCode(LStringCharFromCode* instr) {
5629   Register char_code = ToRegister(instr->char_code());
5630   Register result = ToRegister(instr->result());
5631
5632   // TODO(3095996): Get rid of this. For now, we need to make the
5633   // result register contain a valid pointer because it is already
5634   // contained in the register pointer map.
5635   __ Mov(result, 0);
5636
5637   PushSafepointRegistersScope scope(this);
5638   __ SmiTagAndPush(char_code);
5639   CallRuntimeFromDeferred(Runtime::kCharFromCode, 1, instr, instr->context());
5640   __ StoreToSafepointRegisterSlot(x0, result);
5641 }
5642
5643
5644 void LCodeGen::DoStringCompareAndBranch(LStringCompareAndBranch* instr) {
5645   DCHECK(ToRegister(instr->context()).is(cp));
5646   Token::Value op = instr->op();
5647
5648   Handle<Code> ic =
5649       CodeFactory::CompareIC(isolate(), op, Strength::WEAK).code();
5650   CallCode(ic, RelocInfo::CODE_TARGET, instr);
5651   InlineSmiCheckInfo::EmitNotInlined(masm());
5652
5653   Condition condition = TokenToCondition(op, false);
5654
5655   EmitCompareAndBranch(instr, condition, x0, 0);
5656 }
5657
5658
5659 void LCodeGen::DoSubI(LSubI* instr) {
5660   bool can_overflow = instr->hydrogen()->CheckFlag(HValue::kCanOverflow);
5661   Register result = ToRegister32(instr->result());
5662   Register left = ToRegister32(instr->left());
5663   Operand right = ToShiftedRightOperand32(instr->right(), instr);
5664
5665   if (can_overflow) {
5666     __ Subs(result, left, right);
5667     DeoptimizeIf(vs, instr, Deoptimizer::kOverflow);
5668   } else {
5669     __ Sub(result, left, right);
5670   }
5671 }
5672
5673
5674 void LCodeGen::DoSubS(LSubS* instr) {
5675   bool can_overflow = instr->hydrogen()->CheckFlag(HValue::kCanOverflow);
5676   Register result = ToRegister(instr->result());
5677   Register left = ToRegister(instr->left());
5678   Operand right = ToOperand(instr->right());
5679   if (can_overflow) {
5680     __ Subs(result, left, right);
5681     DeoptimizeIf(vs, instr, Deoptimizer::kOverflow);
5682   } else {
5683     __ Sub(result, left, right);
5684   }
5685 }
5686
5687
5688 void LCodeGen::DoDeferredTaggedToI(LTaggedToI* instr,
5689                                    LOperand* value,
5690                                    LOperand* temp1,
5691                                    LOperand* temp2) {
5692   Register input = ToRegister(value);
5693   Register scratch1 = ToRegister(temp1);
5694   DoubleRegister dbl_scratch1 = double_scratch();
5695
5696   Label done;
5697
5698   if (instr->truncating()) {
5699     Register output = ToRegister(instr->result());
5700     Label check_bools;
5701
5702     // If it's not a heap number, jump to undefined check.
5703     __ JumpIfNotHeapNumber(input, &check_bools);
5704
5705     // A heap number: load value and convert to int32 using truncating function.
5706     __ TruncateHeapNumberToI(output, input);
5707     __ B(&done);
5708
5709     __ Bind(&check_bools);
5710
5711     Register true_root = output;
5712     Register false_root = scratch1;
5713     __ LoadTrueFalseRoots(true_root, false_root);
5714     __ Cmp(input, true_root);
5715     __ Cset(output, eq);
5716     __ Ccmp(input, false_root, ZFlag, ne);
5717     __ B(eq, &done);
5718
5719     // Output contains zero, undefined is converted to zero for truncating
5720     // conversions.
5721     DeoptimizeIfNotRoot(input, Heap::kUndefinedValueRootIndex, instr,
5722                         Deoptimizer::kNotAHeapNumberUndefinedBoolean);
5723   } else {
5724     Register output = ToRegister32(instr->result());
5725     DoubleRegister dbl_scratch2 = ToDoubleRegister(temp2);
5726
5727     DeoptimizeIfNotHeapNumber(input, instr);
5728
5729     // A heap number: load value and convert to int32 using non-truncating
5730     // function. If the result is out of range, branch to deoptimize.
5731     __ Ldr(dbl_scratch1, FieldMemOperand(input, HeapNumber::kValueOffset));
5732     __ TryRepresentDoubleAsInt32(output, dbl_scratch1, dbl_scratch2);
5733     DeoptimizeIf(ne, instr, Deoptimizer::kLostPrecisionOrNaN);
5734
5735     if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
5736       __ Cmp(output, 0);
5737       __ B(ne, &done);
5738       __ Fmov(scratch1, dbl_scratch1);
5739       DeoptimizeIfNegative(scratch1, instr, Deoptimizer::kMinusZero);
5740     }
5741   }
5742   __ Bind(&done);
5743 }
5744
5745
5746 void LCodeGen::DoTaggedToI(LTaggedToI* instr) {
5747   class DeferredTaggedToI: public LDeferredCode {
5748    public:
5749     DeferredTaggedToI(LCodeGen* codegen, LTaggedToI* instr)
5750         : LDeferredCode(codegen), instr_(instr) { }
5751     virtual void Generate() {
5752       codegen()->DoDeferredTaggedToI(instr_, instr_->value(), instr_->temp1(),
5753                                      instr_->temp2());
5754     }
5755
5756     virtual LInstruction* instr() { return instr_; }
5757    private:
5758     LTaggedToI* instr_;
5759   };
5760
5761   Register input = ToRegister(instr->value());
5762   Register output = ToRegister(instr->result());
5763
5764   if (instr->hydrogen()->value()->representation().IsSmi()) {
5765     __ SmiUntag(output, input);
5766   } else {
5767     DeferredTaggedToI* deferred = new(zone()) DeferredTaggedToI(this, instr);
5768
5769     __ JumpIfNotSmi(input, deferred->entry());
5770     __ SmiUntag(output, input);
5771     __ Bind(deferred->exit());
5772   }
5773 }
5774
5775
5776 void LCodeGen::DoThisFunction(LThisFunction* instr) {
5777   Register result = ToRegister(instr->result());
5778   __ Ldr(result, MemOperand(fp, JavaScriptFrameConstants::kFunctionOffset));
5779 }
5780
5781
5782 void LCodeGen::DoToFastProperties(LToFastProperties* instr) {
5783   DCHECK(ToRegister(instr->value()).Is(x0));
5784   DCHECK(ToRegister(instr->result()).Is(x0));
5785   __ Push(x0);
5786   CallRuntime(Runtime::kToFastProperties, 1, instr);
5787 }
5788
5789
5790 void LCodeGen::DoRegExpLiteral(LRegExpLiteral* instr) {
5791   DCHECK(ToRegister(instr->context()).is(cp));
5792   Label materialized;
5793   // Registers will be used as follows:
5794   // x7 = literals array.
5795   // x1 = regexp literal.
5796   // x0 = regexp literal clone.
5797   // x10-x12 are used as temporaries.
5798   int literal_offset =
5799       FixedArray::OffsetOfElementAt(instr->hydrogen()->literal_index());
5800   __ LoadObject(x7, instr->hydrogen()->literals());
5801   __ Ldr(x1, FieldMemOperand(x7, literal_offset));
5802   __ JumpIfNotRoot(x1, Heap::kUndefinedValueRootIndex, &materialized);
5803
5804   // Create regexp literal using runtime function
5805   // Result will be in x0.
5806   __ Mov(x12, Operand(Smi::FromInt(instr->hydrogen()->literal_index())));
5807   __ Mov(x11, Operand(instr->hydrogen()->pattern()));
5808   __ Mov(x10, Operand(instr->hydrogen()->flags()));
5809   __ Push(x7, x12, x11, x10);
5810   CallRuntime(Runtime::kMaterializeRegExpLiteral, 4, instr);
5811   __ Mov(x1, x0);
5812
5813   __ Bind(&materialized);
5814   int size = JSRegExp::kSize + JSRegExp::kInObjectFieldCount * kPointerSize;
5815   Label allocated, runtime_allocate;
5816
5817   __ Allocate(size, x0, x10, x11, &runtime_allocate, TAG_OBJECT);
5818   __ B(&allocated);
5819
5820   __ Bind(&runtime_allocate);
5821   __ Mov(x0, Smi::FromInt(size));
5822   __ Push(x1, x0);
5823   CallRuntime(Runtime::kAllocateInNewSpace, 1, instr);
5824   __ Pop(x1);
5825
5826   __ Bind(&allocated);
5827   // Copy the content into the newly allocated memory.
5828   __ CopyFields(x0, x1, CPURegList(x10, x11, x12), size / kPointerSize);
5829 }
5830
5831
5832 void LCodeGen::DoTransitionElementsKind(LTransitionElementsKind* instr) {
5833   Register object = ToRegister(instr->object());
5834
5835   Handle<Map> from_map = instr->original_map();
5836   Handle<Map> to_map = instr->transitioned_map();
5837   ElementsKind from_kind = instr->from_kind();
5838   ElementsKind to_kind = instr->to_kind();
5839
5840   Label not_applicable;
5841
5842   if (IsSimpleMapChangeTransition(from_kind, to_kind)) {
5843     Register temp1 = ToRegister(instr->temp1());
5844     Register new_map = ToRegister(instr->temp2());
5845     __ CheckMap(object, temp1, from_map, &not_applicable, DONT_DO_SMI_CHECK);
5846     __ Mov(new_map, Operand(to_map));
5847     __ Str(new_map, FieldMemOperand(object, HeapObject::kMapOffset));
5848     // Write barrier.
5849     __ RecordWriteForMap(object, new_map, temp1, GetLinkRegisterState(),
5850                          kDontSaveFPRegs);
5851   } else {
5852     {
5853       UseScratchRegisterScope temps(masm());
5854       // Use the temp register only in a restricted scope - the codegen checks
5855       // that we do not use any register across a call.
5856       __ CheckMap(object, temps.AcquireX(), from_map, &not_applicable,
5857                   DONT_DO_SMI_CHECK);
5858     }
5859     DCHECK(object.is(x0));
5860     DCHECK(ToRegister(instr->context()).is(cp));
5861     PushSafepointRegistersScope scope(this);
5862     __ Mov(x1, Operand(to_map));
5863     bool is_js_array = from_map->instance_type() == JS_ARRAY_TYPE;
5864     TransitionElementsKindStub stub(isolate(), from_kind, to_kind, is_js_array);
5865     __ CallStub(&stub);
5866     RecordSafepointWithRegisters(
5867         instr->pointer_map(), 0, Safepoint::kLazyDeopt);
5868   }
5869   __ Bind(&not_applicable);
5870 }
5871
5872
5873 void LCodeGen::DoTrapAllocationMemento(LTrapAllocationMemento* instr) {
5874   Register object = ToRegister(instr->object());
5875   Register temp1 = ToRegister(instr->temp1());
5876   Register temp2 = ToRegister(instr->temp2());
5877
5878   Label no_memento_found;
5879   __ TestJSArrayForAllocationMemento(object, temp1, temp2, &no_memento_found);
5880   DeoptimizeIf(eq, instr, Deoptimizer::kMementoFound);
5881   __ Bind(&no_memento_found);
5882 }
5883
5884
5885 void LCodeGen::DoTruncateDoubleToIntOrSmi(LTruncateDoubleToIntOrSmi* instr) {
5886   DoubleRegister input = ToDoubleRegister(instr->value());
5887   Register result = ToRegister(instr->result());
5888   __ TruncateDoubleToI(result, input);
5889   if (instr->tag_result()) {
5890     __ SmiTag(result, result);
5891   }
5892 }
5893
5894
5895 void LCodeGen::DoTypeof(LTypeof* instr) {
5896   DCHECK(ToRegister(instr->value()).is(x3));
5897   DCHECK(ToRegister(instr->result()).is(x0));
5898   Label end, do_call;
5899   Register value_register = ToRegister(instr->value());
5900   __ JumpIfNotSmi(value_register, &do_call);
5901   __ Mov(x0, Immediate(isolate()->factory()->number_string()));
5902   __ B(&end);
5903   __ Bind(&do_call);
5904   TypeofStub stub(isolate());
5905   CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
5906   __ Bind(&end);
5907 }
5908
5909
5910 void LCodeGen::DoTypeofIsAndBranch(LTypeofIsAndBranch* instr) {
5911   Handle<String> type_name = instr->type_literal();
5912   Label* true_label = instr->TrueLabel(chunk_);
5913   Label* false_label = instr->FalseLabel(chunk_);
5914   Register value = ToRegister(instr->value());
5915
5916   Factory* factory = isolate()->factory();
5917   if (String::Equals(type_name, factory->number_string())) {
5918     __ JumpIfSmi(value, true_label);
5919
5920     int true_block = instr->TrueDestination(chunk_);
5921     int false_block = instr->FalseDestination(chunk_);
5922     int next_block = GetNextEmittedBlock();
5923
5924     if (true_block == false_block) {
5925       EmitGoto(true_block);
5926     } else if (true_block == next_block) {
5927       __ JumpIfNotHeapNumber(value, chunk_->GetAssemblyLabel(false_block));
5928     } else {
5929       __ JumpIfHeapNumber(value, chunk_->GetAssemblyLabel(true_block));
5930       if (false_block != next_block) {
5931         __ B(chunk_->GetAssemblyLabel(false_block));
5932       }
5933     }
5934
5935   } else if (String::Equals(type_name, factory->string_string())) {
5936     DCHECK((instr->temp1() != NULL) && (instr->temp2() != NULL));
5937     Register map = ToRegister(instr->temp1());
5938     Register scratch = ToRegister(instr->temp2());
5939
5940     __ JumpIfSmi(value, false_label);
5941     __ JumpIfObjectType(
5942         value, map, scratch, FIRST_NONSTRING_TYPE, false_label, ge);
5943     __ Ldrb(scratch, FieldMemOperand(map, Map::kBitFieldOffset));
5944     EmitTestAndBranch(instr, eq, scratch, 1 << Map::kIsUndetectable);
5945
5946   } else if (String::Equals(type_name, factory->symbol_string())) {
5947     DCHECK((instr->temp1() != NULL) && (instr->temp2() != NULL));
5948     Register map = ToRegister(instr->temp1());
5949     Register scratch = ToRegister(instr->temp2());
5950
5951     __ JumpIfSmi(value, false_label);
5952     __ CompareObjectType(value, map, scratch, SYMBOL_TYPE);
5953     EmitBranch(instr, eq);
5954
5955   } else if (String::Equals(type_name, factory->boolean_string())) {
5956     __ JumpIfRoot(value, Heap::kTrueValueRootIndex, true_label);
5957     __ CompareRoot(value, Heap::kFalseValueRootIndex);
5958     EmitBranch(instr, eq);
5959
5960   } else if (String::Equals(type_name, factory->undefined_string())) {
5961     DCHECK(instr->temp1() != NULL);
5962     Register scratch = ToRegister(instr->temp1());
5963
5964     __ JumpIfRoot(value, Heap::kUndefinedValueRootIndex, true_label);
5965     __ JumpIfSmi(value, false_label);
5966     // Check for undetectable objects and jump to the true branch in this case.
5967     __ Ldr(scratch, FieldMemOperand(value, HeapObject::kMapOffset));
5968     __ Ldrb(scratch, FieldMemOperand(scratch, Map::kBitFieldOffset));
5969     EmitTestAndBranch(instr, ne, scratch, 1 << Map::kIsUndetectable);
5970
5971   } else if (String::Equals(type_name, factory->function_string())) {
5972     STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
5973     DCHECK(instr->temp1() != NULL);
5974     Register type = ToRegister(instr->temp1());
5975
5976     __ JumpIfSmi(value, false_label);
5977     __ JumpIfObjectType(value, type, type, JS_FUNCTION_TYPE, true_label);
5978     // HeapObject's type has been loaded into type register by JumpIfObjectType.
5979     EmitCompareAndBranch(instr, eq, type, JS_FUNCTION_PROXY_TYPE);
5980
5981   } else if (String::Equals(type_name, factory->object_string())) {
5982     DCHECK((instr->temp1() != NULL) && (instr->temp2() != NULL));
5983     Register map = ToRegister(instr->temp1());
5984     Register scratch = ToRegister(instr->temp2());
5985
5986     __ JumpIfSmi(value, false_label);
5987     __ JumpIfRoot(value, Heap::kNullValueRootIndex, true_label);
5988     __ JumpIfObjectType(value, map, scratch,
5989                         FIRST_NONCALLABLE_SPEC_OBJECT_TYPE, false_label, lt);
5990     __ CompareInstanceType(map, scratch, LAST_NONCALLABLE_SPEC_OBJECT_TYPE);
5991     __ B(gt, false_label);
5992     // Check for undetectable objects => false.
5993     __ Ldrb(scratch, FieldMemOperand(map, Map::kBitFieldOffset));
5994     EmitTestAndBranch(instr, eq, scratch, 1 << Map::kIsUndetectable);
5995
5996   } else if (String::Equals(type_name, factory->float32x4_string())) {
5997     DCHECK((instr->temp1() != NULL) && (instr->temp2() != NULL));
5998     Register map = ToRegister(instr->temp1());
5999     Register scratch = ToRegister(instr->temp2());
6000
6001     __ JumpIfSmi(value, false_label);
6002     __ CompareObjectType(value, map, scratch, FLOAT32X4_TYPE);
6003     EmitBranch(instr, eq);
6004
6005   } else {
6006     __ B(false_label);
6007   }
6008 }
6009
6010
6011 void LCodeGen::DoUint32ToDouble(LUint32ToDouble* instr) {
6012   __ Ucvtf(ToDoubleRegister(instr->result()), ToRegister32(instr->value()));
6013 }
6014
6015
6016 void LCodeGen::DoCheckMapValue(LCheckMapValue* instr) {
6017   Register object = ToRegister(instr->value());
6018   Register map = ToRegister(instr->map());
6019   Register temp = ToRegister(instr->temp());
6020   __ Ldr(temp, FieldMemOperand(object, HeapObject::kMapOffset));
6021   __ Cmp(map, temp);
6022   DeoptimizeIf(ne, instr, Deoptimizer::kWrongMap);
6023 }
6024
6025
6026 void LCodeGen::DoWrapReceiver(LWrapReceiver* instr) {
6027   Register receiver = ToRegister(instr->receiver());
6028   Register function = ToRegister(instr->function());
6029   Register result = ToRegister(instr->result());
6030
6031   // If the receiver is null or undefined, we have to pass the global object as
6032   // a receiver to normal functions. Values have to be passed unchanged to
6033   // builtins and strict-mode functions.
6034   Label global_object, done, copy_receiver;
6035
6036   if (!instr->hydrogen()->known_function()) {
6037     __ Ldr(result, FieldMemOperand(function,
6038                                    JSFunction::kSharedFunctionInfoOffset));
6039
6040     // CompilerHints is an int32 field. See objects.h.
6041     __ Ldr(result.W(),
6042            FieldMemOperand(result, SharedFunctionInfo::kCompilerHintsOffset));
6043
6044     // Do not transform the receiver to object for strict mode functions.
6045     __ Tbnz(result, SharedFunctionInfo::kStrictModeFunction, &copy_receiver);
6046
6047     // Do not transform the receiver to object for builtins.
6048     __ Tbnz(result, SharedFunctionInfo::kNative, &copy_receiver);
6049   }
6050
6051   // Normal function. Replace undefined or null with global receiver.
6052   __ JumpIfRoot(receiver, Heap::kNullValueRootIndex, &global_object);
6053   __ JumpIfRoot(receiver, Heap::kUndefinedValueRootIndex, &global_object);
6054
6055   // Deoptimize if the receiver is not a JS object.
6056   DeoptimizeIfSmi(receiver, instr, Deoptimizer::kSmi);
6057   __ CompareObjectType(receiver, result, result, FIRST_SPEC_OBJECT_TYPE);
6058   __ B(ge, &copy_receiver);
6059   Deoptimize(instr, Deoptimizer::kNotAJavaScriptObject);
6060
6061   __ Bind(&global_object);
6062   __ Ldr(result, FieldMemOperand(function, JSFunction::kContextOffset));
6063   __ Ldr(result, ContextMemOperand(result, Context::GLOBAL_OBJECT_INDEX));
6064   __ Ldr(result, FieldMemOperand(result, GlobalObject::kGlobalProxyOffset));
6065   __ B(&done);
6066
6067   __ Bind(&copy_receiver);
6068   __ Mov(result, receiver);
6069   __ Bind(&done);
6070 }
6071
6072
6073 void LCodeGen::DoDeferredLoadMutableDouble(LLoadFieldByIndex* instr,
6074                                            Register result,
6075                                            Register object,
6076                                            Register index) {
6077   PushSafepointRegistersScope scope(this);
6078   __ Push(object);
6079   __ Push(index);
6080   __ Mov(cp, 0);
6081   __ CallRuntimeSaveDoubles(Runtime::kLoadMutableDouble);
6082   RecordSafepointWithRegisters(
6083       instr->pointer_map(), 2, Safepoint::kNoLazyDeopt);
6084   __ StoreToSafepointRegisterSlot(x0, result);
6085 }
6086
6087
6088 void LCodeGen::DoLoadFieldByIndex(LLoadFieldByIndex* instr) {
6089   class DeferredLoadMutableDouble final : public LDeferredCode {
6090    public:
6091     DeferredLoadMutableDouble(LCodeGen* codegen,
6092                               LLoadFieldByIndex* instr,
6093                               Register result,
6094                               Register object,
6095                               Register index)
6096         : LDeferredCode(codegen),
6097           instr_(instr),
6098           result_(result),
6099           object_(object),
6100           index_(index) {
6101     }
6102     void Generate() override {
6103       codegen()->DoDeferredLoadMutableDouble(instr_, result_, object_, index_);
6104     }
6105     LInstruction* instr() override { return instr_; }
6106
6107    private:
6108     LLoadFieldByIndex* instr_;
6109     Register result_;
6110     Register object_;
6111     Register index_;
6112   };
6113   Register object = ToRegister(instr->object());
6114   Register index = ToRegister(instr->index());
6115   Register result = ToRegister(instr->result());
6116
6117   __ AssertSmi(index);
6118
6119   DeferredLoadMutableDouble* deferred;
6120   deferred = new(zone()) DeferredLoadMutableDouble(
6121       this, instr, result, object, index);
6122
6123   Label out_of_object, done;
6124
6125   __ TestAndBranchIfAnySet(
6126       index, reinterpret_cast<uint64_t>(Smi::FromInt(1)), deferred->entry());
6127   __ Mov(index, Operand(index, ASR, 1));
6128
6129   __ Cmp(index, Smi::FromInt(0));
6130   __ B(lt, &out_of_object);
6131
6132   STATIC_ASSERT(kPointerSizeLog2 > kSmiTagSize);
6133   __ Add(result, object, Operand::UntagSmiAndScale(index, kPointerSizeLog2));
6134   __ Ldr(result, FieldMemOperand(result, JSObject::kHeaderSize));
6135
6136   __ B(&done);
6137
6138   __ Bind(&out_of_object);
6139   __ Ldr(result, FieldMemOperand(object, JSObject::kPropertiesOffset));
6140   // Index is equal to negated out of object property index plus 1.
6141   __ Sub(result, result, Operand::UntagSmiAndScale(index, kPointerSizeLog2));
6142   __ Ldr(result, FieldMemOperand(result,
6143                                  FixedArray::kHeaderSize - kPointerSize));
6144   __ Bind(deferred->exit());
6145   __ Bind(&done);
6146 }
6147
6148
6149 void LCodeGen::DoStoreFrameContext(LStoreFrameContext* instr) {
6150   Register context = ToRegister(instr->context());
6151   __ Str(context, MemOperand(fp, StandardFrameConstants::kContextOffset));
6152 }
6153
6154
6155 void LCodeGen::DoAllocateBlockContext(LAllocateBlockContext* instr) {
6156   Handle<ScopeInfo> scope_info = instr->scope_info();
6157   __ Push(scope_info);
6158   __ Push(ToRegister(instr->function()));
6159   CallRuntime(Runtime::kPushBlockContext, 2, instr);
6160   RecordSafepoint(Safepoint::kNoLazyDeopt);
6161 }
6162
6163
6164 }  // namespace internal
6165 }  // namespace v8