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