1 // Copyright 2013 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
7 #include "src/arm64/lithium-codegen-arm64.h"
8 #include "src/arm64/lithium-gap-resolver-arm64.h"
9 #include "src/base/bits.h"
10 #include "src/code-factory.h"
11 #include "src/code-stubs.h"
12 #include "src/cpu-profiler.h"
13 #include "src/hydrogen-osr.h"
14 #include "src/ic/ic.h"
15 #include "src/ic/stub-cache.h"
21 class SafepointGenerator final : public CallWrapper {
23 SafepointGenerator(LCodeGen* codegen,
24 LPointerMap* pointers,
25 Safepoint::DeoptMode mode)
29 virtual ~SafepointGenerator() { }
31 virtual void BeforeCall(int call_size) const { }
33 virtual void AfterCall() const {
34 codegen_->RecordSafepoint(pointers_, deopt_mode_);
39 LPointerMap* pointers_;
40 Safepoint::DeoptMode deopt_mode_;
46 // Emit code to branch if the given condition holds.
47 // The code generated here doesn't modify the flags and they must have
48 // been set by some prior instructions.
50 // The EmitInverted function simply inverts the condition.
51 class BranchOnCondition : public BranchGenerator {
53 BranchOnCondition(LCodeGen* codegen, Condition cond)
54 : BranchGenerator(codegen),
57 virtual void Emit(Label* label) const {
61 virtual void EmitInverted(Label* label) const {
63 __ B(NegateCondition(cond_), label);
72 // Emit code to compare lhs and rhs and branch if the condition holds.
73 // This uses MacroAssembler's CompareAndBranch function so it will handle
74 // converting the comparison to Cbz/Cbnz if the right-hand side is 0.
76 // EmitInverted still compares the two operands but inverts the condition.
77 class CompareAndBranch : public BranchGenerator {
79 CompareAndBranch(LCodeGen* codegen,
83 : BranchGenerator(codegen),
88 virtual void Emit(Label* label) const {
89 __ CompareAndBranch(lhs_, rhs_, cond_, label);
92 virtual void EmitInverted(Label* label) const {
93 __ CompareAndBranch(lhs_, rhs_, NegateCondition(cond_), label);
103 // Test the input with the given mask and branch if the condition holds.
104 // If the condition is 'eq' or 'ne' this will use MacroAssembler's
105 // TestAndBranchIfAllClear and TestAndBranchIfAnySet so it will handle the
106 // conversion to Tbz/Tbnz when possible.
107 class TestAndBranch : public BranchGenerator {
109 TestAndBranch(LCodeGen* codegen,
111 const Register& value,
113 : BranchGenerator(codegen),
118 virtual void Emit(Label* label) const {
121 __ TestAndBranchIfAllClear(value_, mask_, label);
124 __ TestAndBranchIfAnySet(value_, mask_, label);
127 __ Tst(value_, mask_);
132 virtual void EmitInverted(Label* label) const {
133 // The inverse of "all clear" is "any set" and vice versa.
136 __ TestAndBranchIfAnySet(value_, mask_, label);
139 __ TestAndBranchIfAllClear(value_, mask_, label);
142 __ Tst(value_, mask_);
143 __ B(NegateCondition(cond_), label);
149 const Register& value_;
154 // Test the input and branch if it is non-zero and not a NaN.
155 class BranchIfNonZeroNumber : public BranchGenerator {
157 BranchIfNonZeroNumber(LCodeGen* codegen, const FPRegister& value,
158 const FPRegister& scratch)
159 : BranchGenerator(codegen), value_(value), scratch_(scratch) { }
161 virtual void Emit(Label* label) const {
162 __ Fabs(scratch_, value_);
163 // Compare with 0.0. Because scratch_ is positive, the result can be one of
164 // nZCv (equal), nzCv (greater) or nzCV (unordered).
165 __ Fcmp(scratch_, 0.0);
169 virtual void EmitInverted(Label* label) const {
170 __ Fabs(scratch_, value_);
171 __ Fcmp(scratch_, 0.0);
176 const FPRegister& value_;
177 const FPRegister& scratch_;
181 // Test the input and branch if it is a heap number.
182 class BranchIfHeapNumber : public BranchGenerator {
184 BranchIfHeapNumber(LCodeGen* codegen, const Register& value)
185 : BranchGenerator(codegen), value_(value) { }
187 virtual void Emit(Label* label) const {
188 __ JumpIfHeapNumber(value_, label);
191 virtual void EmitInverted(Label* label) const {
192 __ JumpIfNotHeapNumber(value_, label);
196 const Register& value_;
200 // Test the input and branch if it is the specified root value.
201 class BranchIfRoot : public BranchGenerator {
203 BranchIfRoot(LCodeGen* codegen, const Register& value,
204 Heap::RootListIndex index)
205 : BranchGenerator(codegen), value_(value), index_(index) { }
207 virtual void Emit(Label* label) const {
208 __ JumpIfRoot(value_, index_, label);
211 virtual void EmitInverted(Label* label) const {
212 __ JumpIfNotRoot(value_, index_, label);
216 const Register& value_;
217 const Heap::RootListIndex index_;
221 void LCodeGen::WriteTranslation(LEnvironment* environment,
222 Translation* translation) {
223 if (environment == NULL) return;
225 // The translation includes one command per value in the environment.
226 int translation_size = environment->translation_size();
228 WriteTranslation(environment->outer(), translation);
229 WriteTranslationFrame(environment, translation);
231 int object_index = 0;
232 int dematerialized_index = 0;
233 for (int i = 0; i < translation_size; ++i) {
234 LOperand* value = environment->values()->at(i);
236 environment, translation, value, environment->HasTaggedValueAt(i),
237 environment->HasUint32ValueAt(i), &object_index, &dematerialized_index);
242 void LCodeGen::AddToTranslation(LEnvironment* environment,
243 Translation* translation,
247 int* object_index_pointer,
248 int* dematerialized_index_pointer) {
249 if (op == LEnvironment::materialization_marker()) {
250 int object_index = (*object_index_pointer)++;
251 if (environment->ObjectIsDuplicateAt(object_index)) {
252 int dupe_of = environment->ObjectDuplicateOfAt(object_index);
253 translation->DuplicateObject(dupe_of);
256 int object_length = environment->ObjectLengthAt(object_index);
257 if (environment->ObjectIsArgumentsAt(object_index)) {
258 translation->BeginArgumentsObject(object_length);
260 translation->BeginCapturedObject(object_length);
262 int dematerialized_index = *dematerialized_index_pointer;
263 int env_offset = environment->translation_size() + dematerialized_index;
264 *dematerialized_index_pointer += object_length;
265 for (int i = 0; i < object_length; ++i) {
266 LOperand* value = environment->values()->at(env_offset + i);
267 AddToTranslation(environment,
270 environment->HasTaggedValueAt(env_offset + i),
271 environment->HasUint32ValueAt(env_offset + i),
272 object_index_pointer,
273 dematerialized_index_pointer);
278 if (op->IsStackSlot()) {
280 translation->StoreStackSlot(op->index());
281 } else if (is_uint32) {
282 translation->StoreUint32StackSlot(op->index());
284 translation->StoreInt32StackSlot(op->index());
286 } else if (op->IsDoubleStackSlot()) {
287 translation->StoreDoubleStackSlot(op->index());
288 } else if (op->IsRegister()) {
289 Register reg = ToRegister(op);
291 translation->StoreRegister(reg);
292 } else if (is_uint32) {
293 translation->StoreUint32Register(reg);
295 translation->StoreInt32Register(reg);
297 } else if (op->IsDoubleRegister()) {
298 DoubleRegister reg = ToDoubleRegister(op);
299 translation->StoreDoubleRegister(reg);
300 } else if (op->IsConstantOperand()) {
301 HConstant* constant = chunk()->LookupConstant(LConstantOperand::cast(op));
302 int src_index = DefineDeoptimizationLiteral(constant->handle(isolate()));
303 translation->StoreLiteral(src_index);
310 void LCodeGen::RegisterEnvironmentForDeoptimization(LEnvironment* environment,
311 Safepoint::DeoptMode mode) {
312 environment->set_has_been_used();
313 if (!environment->HasBeenRegistered()) {
315 int jsframe_count = 0;
316 for (LEnvironment* e = environment; e != NULL; e = e->outer()) {
318 if (e->frame_type() == JS_FUNCTION) {
322 Translation translation(&translations_, frame_count, jsframe_count, zone());
323 WriteTranslation(environment, &translation);
324 int deoptimization_index = deoptimizations_.length();
325 int pc_offset = masm()->pc_offset();
326 environment->Register(deoptimization_index,
328 (mode == Safepoint::kLazyDeopt) ? pc_offset : -1);
329 deoptimizations_.Add(environment, zone());
334 void LCodeGen::CallCode(Handle<Code> code,
335 RelocInfo::Mode mode,
336 LInstruction* instr) {
337 CallCodeGeneric(code, mode, instr, RECORD_SIMPLE_SAFEPOINT);
341 void LCodeGen::CallCodeGeneric(Handle<Code> code,
342 RelocInfo::Mode mode,
344 SafepointMode safepoint_mode) {
345 DCHECK(instr != NULL);
347 Assembler::BlockPoolsScope scope(masm_);
349 RecordSafepointWithLazyDeopt(instr, safepoint_mode);
351 if ((code->kind() == Code::BINARY_OP_IC) ||
352 (code->kind() == Code::COMPARE_IC)) {
353 // Signal that we don't inline smi code before these stubs in the
354 // optimizing code generator.
355 InlineSmiCheckInfo::EmitNotInlined(masm());
360 void LCodeGen::DoCallFunction(LCallFunction* instr) {
361 DCHECK(ToRegister(instr->context()).is(cp));
362 DCHECK(ToRegister(instr->function()).Is(x1));
363 DCHECK(ToRegister(instr->result()).Is(x0));
365 int arity = instr->arity();
366 CallFunctionFlags flags = instr->hydrogen()->function_flags();
367 if (instr->hydrogen()->HasVectorAndSlot()) {
368 Register slot_register = ToRegister(instr->temp_slot());
369 Register vector_register = ToRegister(instr->temp_vector());
370 DCHECK(slot_register.is(x3));
371 DCHECK(vector_register.is(x2));
373 AllowDeferredHandleDereference vector_structure_check;
374 Handle<TypeFeedbackVector> vector = instr->hydrogen()->feedback_vector();
375 int index = vector->GetIndex(instr->hydrogen()->slot());
377 __ Mov(vector_register, vector);
378 __ Mov(slot_register, Operand(Smi::FromInt(index)));
380 CallICState::CallType call_type =
381 (flags & CALL_AS_METHOD) ? CallICState::METHOD : CallICState::FUNCTION;
384 CodeFactory::CallICInOptimizedCode(isolate(), arity, call_type).code();
385 CallCode(ic, RelocInfo::CODE_TARGET, instr);
387 CallFunctionStub stub(isolate(), arity, flags);
388 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
390 RecordPushedArgumentsDelta(instr->hydrogen()->argument_delta());
394 void LCodeGen::DoCallNew(LCallNew* instr) {
395 DCHECK(ToRegister(instr->context()).is(cp));
396 DCHECK(instr->IsMarkedAsCall());
397 DCHECK(ToRegister(instr->constructor()).is(x1));
399 __ Mov(x0, instr->arity());
400 // No cell in x2 for construct type feedback in optimized code.
401 __ LoadRoot(x2, Heap::kUndefinedValueRootIndex);
403 CallConstructStub stub(isolate(), NO_CALL_CONSTRUCTOR_FLAGS);
404 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
405 RecordPushedArgumentsDelta(instr->hydrogen()->argument_delta());
407 DCHECK(ToRegister(instr->result()).is(x0));
411 void LCodeGen::DoCallNewArray(LCallNewArray* instr) {
412 DCHECK(instr->IsMarkedAsCall());
413 DCHECK(ToRegister(instr->context()).is(cp));
414 DCHECK(ToRegister(instr->constructor()).is(x1));
416 __ Mov(x0, Operand(instr->arity()));
417 if (instr->arity() == 1) {
418 // We only need the allocation site for the case we have a length argument.
419 // The case may bail out to the runtime, which will determine the correct
420 // elements kind with the site.
421 __ Mov(x2, instr->hydrogen()->site());
423 __ LoadRoot(x2, Heap::kUndefinedValueRootIndex);
427 ElementsKind kind = instr->hydrogen()->elements_kind();
428 AllocationSiteOverrideMode override_mode =
429 (AllocationSite::GetMode(kind) == TRACK_ALLOCATION_SITE)
430 ? DISABLE_ALLOCATION_SITES
433 if (instr->arity() == 0) {
434 ArrayNoArgumentConstructorStub stub(isolate(), kind, override_mode);
435 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
436 } else if (instr->arity() == 1) {
438 if (IsFastPackedElementsKind(kind)) {
441 // We might need to create a holey array; look at the first argument.
443 __ Cbz(x10, &packed_case);
445 ElementsKind holey_kind = GetHoleyElementsKind(kind);
446 ArraySingleArgumentConstructorStub stub(isolate(),
449 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
451 __ Bind(&packed_case);
454 ArraySingleArgumentConstructorStub stub(isolate(), kind, override_mode);
455 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
458 ArrayNArgumentsConstructorStub stub(isolate(), kind, override_mode);
459 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
461 RecordPushedArgumentsDelta(instr->hydrogen()->argument_delta());
463 DCHECK(ToRegister(instr->result()).is(x0));
467 void LCodeGen::CallRuntime(const Runtime::Function* function,
470 SaveFPRegsMode save_doubles) {
471 DCHECK(instr != NULL);
473 __ CallRuntime(function, num_arguments, save_doubles);
475 RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
479 void LCodeGen::LoadContextFromDeferred(LOperand* context) {
480 if (context->IsRegister()) {
481 __ Mov(cp, ToRegister(context));
482 } else if (context->IsStackSlot()) {
483 __ Ldr(cp, ToMemOperand(context, kMustUseFramePointer));
484 } else if (context->IsConstantOperand()) {
485 HConstant* constant =
486 chunk_->LookupConstant(LConstantOperand::cast(context));
487 __ LoadHeapObject(cp,
488 Handle<HeapObject>::cast(constant->handle(isolate())));
495 void LCodeGen::CallRuntimeFromDeferred(Runtime::FunctionId id,
499 LoadContextFromDeferred(context);
500 __ CallRuntimeSaveDoubles(id);
501 RecordSafepointWithRegisters(
502 instr->pointer_map(), argc, Safepoint::kNoLazyDeopt);
506 void LCodeGen::RecordAndWritePosition(int position) {
507 if (position == RelocInfo::kNoPosition) return;
508 masm()->positions_recorder()->RecordPosition(position);
509 masm()->positions_recorder()->WriteRecordedPositions();
513 void LCodeGen::RecordSafepointWithLazyDeopt(LInstruction* instr,
514 SafepointMode safepoint_mode) {
515 if (safepoint_mode == RECORD_SIMPLE_SAFEPOINT) {
516 RecordSafepoint(instr->pointer_map(), Safepoint::kLazyDeopt);
518 DCHECK(safepoint_mode == RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
519 RecordSafepointWithRegisters(
520 instr->pointer_map(), 0, Safepoint::kLazyDeopt);
525 void LCodeGen::RecordSafepoint(LPointerMap* pointers,
526 Safepoint::Kind kind,
528 Safepoint::DeoptMode deopt_mode) {
529 DCHECK(expected_safepoint_kind_ == kind);
531 const ZoneList<LOperand*>* operands = pointers->GetNormalizedOperands();
532 Safepoint safepoint = safepoints_.DefineSafepoint(
533 masm(), kind, arguments, deopt_mode);
535 for (int i = 0; i < operands->length(); i++) {
536 LOperand* pointer = operands->at(i);
537 if (pointer->IsStackSlot()) {
538 safepoint.DefinePointerSlot(pointer->index(), zone());
539 } else if (pointer->IsRegister() && (kind & Safepoint::kWithRegisters)) {
540 safepoint.DefinePointerRegister(ToRegister(pointer), zone());
545 void LCodeGen::RecordSafepoint(LPointerMap* pointers,
546 Safepoint::DeoptMode deopt_mode) {
547 RecordSafepoint(pointers, Safepoint::kSimple, 0, deopt_mode);
551 void LCodeGen::RecordSafepoint(Safepoint::DeoptMode deopt_mode) {
552 LPointerMap empty_pointers(zone());
553 RecordSafepoint(&empty_pointers, deopt_mode);
557 void LCodeGen::RecordSafepointWithRegisters(LPointerMap* pointers,
559 Safepoint::DeoptMode deopt_mode) {
560 RecordSafepoint(pointers, Safepoint::kWithRegisters, arguments, deopt_mode);
564 bool LCodeGen::GenerateCode() {
565 LPhase phase("Z_Code generation", chunk());
567 status_ = GENERATING;
569 // Open a frame scope to indicate that there is a frame on the stack. The
570 // NONE indicates that the scope shouldn't actually generate code to set up
571 // the frame (that is done in GeneratePrologue).
572 FrameScope frame_scope(masm_, StackFrame::NONE);
574 return GeneratePrologue() && GenerateBody() && GenerateDeferredCode() &&
575 GenerateJumpTable() && GenerateSafepointTable();
579 void LCodeGen::SaveCallerDoubles() {
580 DCHECK(info()->saves_caller_doubles());
581 DCHECK(NeedsEagerFrame());
582 Comment(";;; Save clobbered callee double registers");
583 BitVector* doubles = chunk()->allocated_double_registers();
584 BitVector::Iterator iterator(doubles);
586 while (!iterator.Done()) {
587 // TODO(all): Is this supposed to save just the callee-saved doubles? It
588 // looks like it's saving all of them.
589 FPRegister value = FPRegister::FromAllocationIndex(iterator.Current());
590 __ Poke(value, count * kDoubleSize);
597 void LCodeGen::RestoreCallerDoubles() {
598 DCHECK(info()->saves_caller_doubles());
599 DCHECK(NeedsEagerFrame());
600 Comment(";;; Restore clobbered callee double registers");
601 BitVector* doubles = chunk()->allocated_double_registers();
602 BitVector::Iterator iterator(doubles);
604 while (!iterator.Done()) {
605 // TODO(all): Is this supposed to restore just the callee-saved doubles? It
606 // looks like it's restoring all of them.
607 FPRegister value = FPRegister::FromAllocationIndex(iterator.Current());
608 __ Peek(value, count * kDoubleSize);
615 bool LCodeGen::GeneratePrologue() {
616 DCHECK(is_generating());
618 if (info()->IsOptimizing()) {
619 ProfileEntryHookStub::MaybeCallEntryHook(masm_);
621 // TODO(all): Add support for stop_t FLAG in DEBUG mode.
623 // Sloppy mode functions and builtins need to replace the receiver with the
624 // global proxy when called as functions (without an explicit receiver
626 if (is_sloppy(info_->language_mode()) && info()->MayUseThis() &&
627 !info()->is_native() && info()->scope()->has_this_declaration()) {
629 int receiver_offset = info_->scope()->num_parameters() * kXRegSize;
630 __ Peek(x10, receiver_offset);
631 __ JumpIfNotRoot(x10, Heap::kUndefinedValueRootIndex, &ok);
633 __ Ldr(x10, GlobalObjectMemOperand());
634 __ Ldr(x10, FieldMemOperand(x10, GlobalObject::kGlobalProxyOffset));
635 __ Poke(x10, receiver_offset);
641 DCHECK(__ StackPointer().Is(jssp));
642 info()->set_prologue_offset(masm_->pc_offset());
643 if (NeedsEagerFrame()) {
644 if (info()->IsStub()) {
647 __ Prologue(info()->IsCodePreAgingActive());
649 frame_is_built_ = true;
650 info_->AddNoFrameRange(0, masm_->pc_offset());
653 // Reserve space for the stack slots needed by the code.
654 int slots = GetStackSlotCount();
656 __ Claim(slots, kPointerSize);
659 if (info()->saves_caller_doubles()) {
663 // Allocate a local context if needed.
664 int heap_slots = info()->num_heap_slots() - Context::MIN_CONTEXT_SLOTS;
665 if (heap_slots > 0) {
666 Comment(";;; Allocate local context");
667 bool need_write_barrier = true;
668 // Argument to NewContext is the function, which is in x1.
669 DCHECK(!info()->scope()->is_script_scope());
670 if (heap_slots <= FastNewContextStub::kMaximumSlots) {
671 FastNewContextStub stub(isolate(), heap_slots);
673 // Result of FastNewContextStub is always in new space.
674 need_write_barrier = false;
677 __ CallRuntime(Runtime::kNewFunctionContext, 1);
679 RecordSafepoint(Safepoint::kNoLazyDeopt);
680 // Context is returned in x0. It replaces the context passed to us. It's
681 // saved in the stack and kept live in cp.
683 __ Str(x0, MemOperand(fp, StandardFrameConstants::kContextOffset));
684 // Copy any necessary parameters into the context.
685 int num_parameters = scope()->num_parameters();
686 int first_parameter = scope()->has_this_declaration() ? -1 : 0;
687 for (int i = first_parameter; i < num_parameters; i++) {
688 Variable* var = (i == -1) ? scope()->receiver() : scope()->parameter(i);
689 if (var->IsContextSlot()) {
691 Register scratch = x3;
693 int parameter_offset = StandardFrameConstants::kCallerSPOffset +
694 (num_parameters - 1 - i) * kPointerSize;
695 // Load parameter from stack.
696 __ Ldr(value, MemOperand(fp, parameter_offset));
697 // Store it in the context.
698 MemOperand target = ContextMemOperand(cp, var->index());
699 __ Str(value, target);
700 // Update the write barrier. This clobbers value and scratch.
701 if (need_write_barrier) {
702 __ RecordWriteContextSlot(cp, static_cast<int>(target.offset()),
703 value, scratch, GetLinkRegisterState(),
705 } else if (FLAG_debug_code) {
707 __ JumpIfInNewSpace(cp, &done);
708 __ Abort(kExpectedNewSpaceObject);
713 Comment(";;; End allocate local context");
717 if (FLAG_trace && info()->IsOptimizing()) {
718 // We have not executed any compiled code yet, so cp still holds the
720 __ CallRuntime(Runtime::kTraceEnter, 0);
723 return !is_aborted();
727 void LCodeGen::GenerateOsrPrologue() {
728 // Generate the OSR entry prologue at the first unknown OSR value, or if there
729 // are none, at the OSR entrypoint instruction.
730 if (osr_pc_offset_ >= 0) return;
732 osr_pc_offset_ = masm()->pc_offset();
734 // Adjust the frame size, subsuming the unoptimized frame into the
736 int slots = GetStackSlotCount() - graph()->osr()->UnoptimizedFrameSlots();
742 void LCodeGen::GenerateBodyInstructionPre(LInstruction* instr) {
743 if (instr->IsCall()) {
744 EnsureSpaceForLazyDeopt(Deoptimizer::patch_size());
746 if (!instr->IsLazyBailout() && !instr->IsGap()) {
747 safepoints_.BumpLastLazySafepointIndex();
752 bool LCodeGen::GenerateDeferredCode() {
753 DCHECK(is_generating());
754 if (deferred_.length() > 0) {
755 for (int i = 0; !is_aborted() && (i < deferred_.length()); i++) {
756 LDeferredCode* code = deferred_[i];
759 instructions_->at(code->instruction_index())->hydrogen_value();
760 RecordAndWritePosition(
761 chunk()->graph()->SourcePositionToScriptPosition(value->position()));
763 Comment(";;; <@%d,#%d> "
764 "-------------------- Deferred %s --------------------",
765 code->instruction_index(),
766 code->instr()->hydrogen_value()->id(),
767 code->instr()->Mnemonic());
769 __ Bind(code->entry());
771 if (NeedsDeferredFrame()) {
772 Comment(";;; Build frame");
773 DCHECK(!frame_is_built_);
774 DCHECK(info()->IsStub());
775 frame_is_built_ = true;
777 __ Mov(fp, Smi::FromInt(StackFrame::STUB));
779 __ Add(fp, __ StackPointer(),
780 StandardFrameConstants::kFixedFrameSizeFromFp);
781 Comment(";;; Deferred code");
786 if (NeedsDeferredFrame()) {
787 Comment(";;; Destroy frame");
788 DCHECK(frame_is_built_);
789 __ Pop(xzr, cp, fp, lr);
790 frame_is_built_ = false;
797 // Force constant pool emission at the end of the deferred code to make
798 // sure that no constant pools are emitted after deferred code because
799 // deferred code generation is the last step which generates code. The two
800 // following steps will only output data used by crakshaft.
801 masm()->CheckConstPool(true, false);
803 return !is_aborted();
807 bool LCodeGen::GenerateJumpTable() {
808 Label needs_frame, call_deopt_entry;
810 if (jump_table_.length() > 0) {
811 Comment(";;; -------------------- Jump table --------------------");
812 Address base = jump_table_[0]->address;
814 UseScratchRegisterScope temps(masm());
815 Register entry_offset = temps.AcquireX();
817 int length = jump_table_.length();
818 for (int i = 0; i < length; i++) {
819 Deoptimizer::JumpTableEntry* table_entry = jump_table_[i];
820 __ Bind(&table_entry->label);
822 Address entry = table_entry->address;
823 DeoptComment(table_entry->deopt_info);
825 // Second-level deopt table entries are contiguous and small, so instead
826 // of loading the full, absolute address of each one, load the base
827 // address and add an immediate offset.
828 __ Mov(entry_offset, entry - base);
830 if (table_entry->needs_frame) {
831 DCHECK(!info()->saves_caller_doubles());
832 Comment(";;; call deopt with frame");
833 // Save lr before Bl, fp will be adjusted in the needs_frame code.
835 // Reuse the existing needs_frame code.
838 // There is nothing special to do, so just continue to the second-level
840 __ Bl(&call_deopt_entry);
842 info()->LogDeoptCallPosition(masm()->pc_offset(),
843 table_entry->deopt_info.inlining_id);
845 masm()->CheckConstPool(false, false);
848 if (needs_frame.is_linked()) {
849 // This variant of deopt can only be used with stubs. Since we don't
850 // have a function pointer to install in the stack frame that we're
851 // building, install a special marker there instead.
852 DCHECK(info()->IsStub());
854 Comment(";;; needs_frame common code");
855 UseScratchRegisterScope temps(masm());
856 Register stub_marker = temps.AcquireX();
857 __ Bind(&needs_frame);
858 __ Mov(stub_marker, Smi::FromInt(StackFrame::STUB));
859 __ Push(cp, stub_marker);
860 __ Add(fp, __ StackPointer(), 2 * kPointerSize);
863 // Generate common code for calling the second-level deopt table.
864 __ Bind(&call_deopt_entry);
866 if (info()->saves_caller_doubles()) {
867 DCHECK(info()->IsStub());
868 RestoreCallerDoubles();
871 Register deopt_entry = temps.AcquireX();
872 __ Mov(deopt_entry, Operand(reinterpret_cast<uint64_t>(base),
873 RelocInfo::RUNTIME_ENTRY));
874 __ Add(deopt_entry, deopt_entry, entry_offset);
878 // Force constant pool emission at the end of the deopt jump table to make
879 // sure that no constant pools are emitted after.
880 masm()->CheckConstPool(true, false);
882 // The deoptimization jump table is the last part of the instruction
883 // sequence. Mark the generated code as done unless we bailed out.
884 if (!is_aborted()) status_ = DONE;
885 return !is_aborted();
889 bool LCodeGen::GenerateSafepointTable() {
891 // We do not know how much data will be emitted for the safepoint table, so
892 // force emission of the veneer pool.
893 masm()->CheckVeneerPool(true, true);
894 safepoints_.Emit(masm(), GetStackSlotCount());
895 return !is_aborted();
899 void LCodeGen::FinishCode(Handle<Code> code) {
901 code->set_stack_slots(GetStackSlotCount());
902 code->set_safepoint_table_offset(safepoints_.GetCodeOffset());
903 PopulateDeoptimizationData(code);
907 void LCodeGen::PopulateDeoptimizationData(Handle<Code> code) {
908 int length = deoptimizations_.length();
909 if (length == 0) return;
911 Handle<DeoptimizationInputData> data =
912 DeoptimizationInputData::New(isolate(), length, TENURED);
914 Handle<ByteArray> translations =
915 translations_.CreateByteArray(isolate()->factory());
916 data->SetTranslationByteArray(*translations);
917 data->SetInlinedFunctionCount(Smi::FromInt(inlined_function_count_));
918 data->SetOptimizationId(Smi::FromInt(info_->optimization_id()));
919 if (info_->IsOptimizing()) {
920 // Reference to shared function info does not change between phases.
921 AllowDeferredHandleDereference allow_handle_dereference;
922 data->SetSharedFunctionInfo(*info_->shared_info());
924 data->SetSharedFunctionInfo(Smi::FromInt(0));
926 data->SetWeakCellCache(Smi::FromInt(0));
928 Handle<FixedArray> literals =
929 factory()->NewFixedArray(deoptimization_literals_.length(), TENURED);
930 { AllowDeferredHandleDereference copy_handles;
931 for (int i = 0; i < deoptimization_literals_.length(); i++) {
932 literals->set(i, *deoptimization_literals_[i]);
934 data->SetLiteralArray(*literals);
937 data->SetOsrAstId(Smi::FromInt(info_->osr_ast_id().ToInt()));
938 data->SetOsrPcOffset(Smi::FromInt(osr_pc_offset_));
940 // Populate the deoptimization entries.
941 for (int i = 0; i < length; i++) {
942 LEnvironment* env = deoptimizations_[i];
943 data->SetAstId(i, env->ast_id());
944 data->SetTranslationIndex(i, Smi::FromInt(env->translation_index()));
945 data->SetArgumentsStackHeight(i,
946 Smi::FromInt(env->arguments_stack_height()));
947 data->SetPc(i, Smi::FromInt(env->pc_offset()));
950 code->set_deoptimization_data(*data);
954 void LCodeGen::PopulateDeoptimizationLiteralsWithInlinedFunctions() {
955 DCHECK_EQ(0, deoptimization_literals_.length());
956 for (auto function : chunk()->inlined_functions()) {
957 DefineDeoptimizationLiteral(function);
959 inlined_function_count_ = deoptimization_literals_.length();
963 void LCodeGen::DeoptimizeBranch(
964 LInstruction* instr, Deoptimizer::DeoptReason deopt_reason,
965 BranchType branch_type, Register reg, int bit,
966 Deoptimizer::BailoutType* override_bailout_type) {
967 LEnvironment* environment = instr->environment();
968 RegisterEnvironmentForDeoptimization(environment, Safepoint::kNoLazyDeopt);
969 Deoptimizer::BailoutType bailout_type =
970 info()->IsStub() ? Deoptimizer::LAZY : Deoptimizer::EAGER;
972 if (override_bailout_type != NULL) {
973 bailout_type = *override_bailout_type;
976 DCHECK(environment->HasBeenRegistered());
977 DCHECK(info()->IsOptimizing() || info()->IsStub());
978 int id = environment->deoptimization_index();
980 Deoptimizer::GetDeoptimizationEntry(isolate(), id, bailout_type);
983 Abort(kBailoutWasNotPrepared);
986 if (FLAG_deopt_every_n_times != 0 && !info()->IsStub()) {
988 ExternalReference count = ExternalReference::stress_deopt_count(isolate());
993 __ Ldr(w1, MemOperand(x0));
996 __ Mov(w1, FLAG_deopt_every_n_times);
997 __ Str(w1, MemOperand(x0));
999 DCHECK(frame_is_built_);
1000 __ Call(entry, RelocInfo::RUNTIME_ENTRY);
1004 __ Str(w1, MemOperand(x0));
1009 if (info()->ShouldTrapOnDeopt()) {
1011 __ B(&dont_trap, InvertBranchType(branch_type), reg, bit);
1012 __ Debug("trap_on_deopt", __LINE__, BREAK);
1013 __ Bind(&dont_trap);
1016 Deoptimizer::DeoptInfo deopt_info = MakeDeoptInfo(instr, deopt_reason);
1018 DCHECK(info()->IsStub() || frame_is_built_);
1019 // Go through jump table if we need to build frame, or restore caller doubles.
1020 if (branch_type == always &&
1021 frame_is_built_ && !info()->saves_caller_doubles()) {
1022 DeoptComment(deopt_info);
1023 __ Call(entry, RelocInfo::RUNTIME_ENTRY);
1024 info()->LogDeoptCallPosition(masm()->pc_offset(), deopt_info.inlining_id);
1026 Deoptimizer::JumpTableEntry* table_entry =
1027 new (zone()) Deoptimizer::JumpTableEntry(
1028 entry, deopt_info, bailout_type, !frame_is_built_);
1029 // We often have several deopts to the same entry, reuse the last
1030 // jump entry if this is the case.
1031 if (FLAG_trace_deopt || isolate()->cpu_profiler()->is_profiling() ||
1032 jump_table_.is_empty() ||
1033 !table_entry->IsEquivalentTo(*jump_table_.last())) {
1034 jump_table_.Add(table_entry, zone());
1036 __ B(&jump_table_.last()->label, branch_type, reg, bit);
1041 void LCodeGen::Deoptimize(LInstruction* instr,
1042 Deoptimizer::DeoptReason deopt_reason,
1043 Deoptimizer::BailoutType* override_bailout_type) {
1044 DeoptimizeBranch(instr, deopt_reason, always, NoReg, -1,
1045 override_bailout_type);
1049 void LCodeGen::DeoptimizeIf(Condition cond, LInstruction* instr,
1050 Deoptimizer::DeoptReason deopt_reason) {
1051 DeoptimizeBranch(instr, deopt_reason, static_cast<BranchType>(cond));
1055 void LCodeGen::DeoptimizeIfZero(Register rt, LInstruction* instr,
1056 Deoptimizer::DeoptReason deopt_reason) {
1057 DeoptimizeBranch(instr, deopt_reason, reg_zero, rt);
1061 void LCodeGen::DeoptimizeIfNotZero(Register rt, LInstruction* instr,
1062 Deoptimizer::DeoptReason deopt_reason) {
1063 DeoptimizeBranch(instr, deopt_reason, reg_not_zero, rt);
1067 void LCodeGen::DeoptimizeIfNegative(Register rt, LInstruction* instr,
1068 Deoptimizer::DeoptReason deopt_reason) {
1069 int sign_bit = rt.Is64Bits() ? kXSignBit : kWSignBit;
1070 DeoptimizeIfBitSet(rt, sign_bit, instr, deopt_reason);
1074 void LCodeGen::DeoptimizeIfSmi(Register rt, LInstruction* instr,
1075 Deoptimizer::DeoptReason deopt_reason) {
1076 DeoptimizeIfBitClear(rt, MaskToBit(kSmiTagMask), instr, deopt_reason);
1080 void LCodeGen::DeoptimizeIfNotSmi(Register rt, LInstruction* instr,
1081 Deoptimizer::DeoptReason deopt_reason) {
1082 DeoptimizeIfBitSet(rt, MaskToBit(kSmiTagMask), instr, deopt_reason);
1086 void LCodeGen::DeoptimizeIfRoot(Register rt, Heap::RootListIndex index,
1087 LInstruction* instr,
1088 Deoptimizer::DeoptReason deopt_reason) {
1089 __ CompareRoot(rt, index);
1090 DeoptimizeIf(eq, instr, deopt_reason);
1094 void LCodeGen::DeoptimizeIfNotRoot(Register rt, Heap::RootListIndex index,
1095 LInstruction* instr,
1096 Deoptimizer::DeoptReason deopt_reason) {
1097 __ CompareRoot(rt, index);
1098 DeoptimizeIf(ne, instr, deopt_reason);
1102 void LCodeGen::DeoptimizeIfMinusZero(DoubleRegister input, LInstruction* instr,
1103 Deoptimizer::DeoptReason deopt_reason) {
1104 __ TestForMinusZero(input);
1105 DeoptimizeIf(vs, instr, deopt_reason);
1109 void LCodeGen::DeoptimizeIfNotHeapNumber(Register object, LInstruction* instr) {
1110 __ CompareObjectMap(object, Heap::kHeapNumberMapRootIndex);
1111 DeoptimizeIf(ne, instr, Deoptimizer::kNotAHeapNumber);
1115 void LCodeGen::DeoptimizeIfBitSet(Register rt, int bit, LInstruction* instr,
1116 Deoptimizer::DeoptReason deopt_reason) {
1117 DeoptimizeBranch(instr, deopt_reason, reg_bit_set, rt, bit);
1121 void LCodeGen::DeoptimizeIfBitClear(Register rt, int bit, LInstruction* instr,
1122 Deoptimizer::DeoptReason deopt_reason) {
1123 DeoptimizeBranch(instr, deopt_reason, reg_bit_clear, rt, bit);
1127 void LCodeGen::EnsureSpaceForLazyDeopt(int space_needed) {
1128 if (!info()->IsStub()) {
1129 // Ensure that we have enough space after the previous lazy-bailout
1130 // instruction for patching the code here.
1131 intptr_t current_pc = masm()->pc_offset();
1133 if (current_pc < (last_lazy_deopt_pc_ + space_needed)) {
1134 ptrdiff_t padding_size = last_lazy_deopt_pc_ + space_needed - current_pc;
1135 DCHECK((padding_size % kInstructionSize) == 0);
1136 InstructionAccurateScope instruction_accurate(
1137 masm(), padding_size / kInstructionSize);
1139 while (padding_size > 0) {
1141 padding_size -= kInstructionSize;
1145 last_lazy_deopt_pc_ = masm()->pc_offset();
1149 Register LCodeGen::ToRegister(LOperand* op) const {
1150 // TODO(all): support zero register results, as ToRegister32.
1151 DCHECK((op != NULL) && op->IsRegister());
1152 return Register::FromAllocationIndex(op->index());
1156 Register LCodeGen::ToRegister32(LOperand* op) const {
1158 if (op->IsConstantOperand()) {
1159 // If this is a constant operand, the result must be the zero register.
1160 DCHECK(ToInteger32(LConstantOperand::cast(op)) == 0);
1163 return ToRegister(op).W();
1168 Smi* LCodeGen::ToSmi(LConstantOperand* op) const {
1169 HConstant* constant = chunk_->LookupConstant(op);
1170 return Smi::FromInt(constant->Integer32Value());
1174 DoubleRegister LCodeGen::ToDoubleRegister(LOperand* op) const {
1175 DCHECK((op != NULL) && op->IsDoubleRegister());
1176 return DoubleRegister::FromAllocationIndex(op->index());
1180 Operand LCodeGen::ToOperand(LOperand* op) {
1182 if (op->IsConstantOperand()) {
1183 LConstantOperand* const_op = LConstantOperand::cast(op);
1184 HConstant* constant = chunk()->LookupConstant(const_op);
1185 Representation r = chunk_->LookupLiteralRepresentation(const_op);
1187 DCHECK(constant->HasSmiValue());
1188 return Operand(Smi::FromInt(constant->Integer32Value()));
1189 } else if (r.IsInteger32()) {
1190 DCHECK(constant->HasInteger32Value());
1191 return Operand(constant->Integer32Value());
1192 } else if (r.IsDouble()) {
1193 Abort(kToOperandUnsupportedDoubleImmediate);
1195 DCHECK(r.IsTagged());
1196 return Operand(constant->handle(isolate()));
1197 } else if (op->IsRegister()) {
1198 return Operand(ToRegister(op));
1199 } else if (op->IsDoubleRegister()) {
1200 Abort(kToOperandIsDoubleRegisterUnimplemented);
1203 // Stack slots not implemented, use ToMemOperand instead.
1209 Operand LCodeGen::ToOperand32(LOperand* op) {
1211 if (op->IsRegister()) {
1212 return Operand(ToRegister32(op));
1213 } else if (op->IsConstantOperand()) {
1214 LConstantOperand* const_op = LConstantOperand::cast(op);
1215 HConstant* constant = chunk()->LookupConstant(const_op);
1216 Representation r = chunk_->LookupLiteralRepresentation(const_op);
1217 if (r.IsInteger32()) {
1218 return Operand(constant->Integer32Value());
1220 // Other constants not implemented.
1221 Abort(kToOperand32UnsupportedImmediate);
1224 // Other cases are not implemented.
1230 static int64_t ArgumentsOffsetWithoutFrame(int index) {
1232 return -(index + 1) * kPointerSize;
1236 MemOperand LCodeGen::ToMemOperand(LOperand* op, StackMode stack_mode) const {
1238 DCHECK(!op->IsRegister());
1239 DCHECK(!op->IsDoubleRegister());
1240 DCHECK(op->IsStackSlot() || op->IsDoubleStackSlot());
1241 if (NeedsEagerFrame()) {
1242 int fp_offset = StackSlotOffset(op->index());
1243 // Loads and stores have a bigger reach in positive offset than negative.
1244 // We try to access using jssp (positive offset) first, then fall back to
1245 // fp (negative offset) if that fails.
1247 // We can reference a stack slot from jssp only if we know how much we've
1248 // put on the stack. We don't know this in the following cases:
1249 // - stack_mode != kCanUseStackPointer: this is the case when deferred
1250 // code has saved the registers.
1251 // - saves_caller_doubles(): some double registers have been pushed, jssp
1252 // references the end of the double registers and not the end of the stack
1254 // In both of the cases above, we _could_ add the tracking information
1255 // required so that we can use jssp here, but in practice it isn't worth it.
1256 if ((stack_mode == kCanUseStackPointer) &&
1257 !info()->saves_caller_doubles()) {
1258 int jssp_offset_to_fp =
1259 StandardFrameConstants::kFixedFrameSizeFromFp +
1260 (pushed_arguments_ + GetStackSlotCount()) * kPointerSize;
1261 int jssp_offset = fp_offset + jssp_offset_to_fp;
1262 if (masm()->IsImmLSScaled(jssp_offset, LSDoubleWord)) {
1263 return MemOperand(masm()->StackPointer(), jssp_offset);
1266 return MemOperand(fp, fp_offset);
1268 // Retrieve parameter without eager stack-frame relative to the
1270 return MemOperand(masm()->StackPointer(),
1271 ArgumentsOffsetWithoutFrame(op->index()));
1276 Handle<Object> LCodeGen::ToHandle(LConstantOperand* op) const {
1277 HConstant* constant = chunk_->LookupConstant(op);
1278 DCHECK(chunk_->LookupLiteralRepresentation(op).IsSmiOrTagged());
1279 return constant->handle(isolate());
1284 Operand LCodeGen::ToShiftedRightOperand32(LOperand* right, LI* shift_info) {
1285 if (shift_info->shift() == NO_SHIFT) {
1286 return ToOperand32(right);
1289 ToRegister32(right),
1290 shift_info->shift(),
1291 JSShiftAmountFromLConstant(shift_info->shift_amount()));
1296 bool LCodeGen::IsSmi(LConstantOperand* op) const {
1297 return chunk_->LookupLiteralRepresentation(op).IsSmi();
1301 bool LCodeGen::IsInteger32Constant(LConstantOperand* op) const {
1302 return chunk_->LookupLiteralRepresentation(op).IsSmiOrInteger32();
1306 int32_t LCodeGen::ToInteger32(LConstantOperand* op) const {
1307 HConstant* constant = chunk_->LookupConstant(op);
1308 return constant->Integer32Value();
1312 double LCodeGen::ToDouble(LConstantOperand* op) const {
1313 HConstant* constant = chunk_->LookupConstant(op);
1314 DCHECK(constant->HasDoubleValue());
1315 return constant->DoubleValue();
1319 Condition LCodeGen::TokenToCondition(Token::Value op, bool is_unsigned) {
1320 Condition cond = nv;
1323 case Token::EQ_STRICT:
1327 case Token::NE_STRICT:
1331 cond = is_unsigned ? lo : lt;
1334 cond = is_unsigned ? hi : gt;
1337 cond = is_unsigned ? ls : le;
1340 cond = is_unsigned ? hs : ge;
1343 case Token::INSTANCEOF:
1351 template<class InstrType>
1352 void LCodeGen::EmitBranchGeneric(InstrType instr,
1353 const BranchGenerator& branch) {
1354 int left_block = instr->TrueDestination(chunk_);
1355 int right_block = instr->FalseDestination(chunk_);
1357 int next_block = GetNextEmittedBlock();
1359 if (right_block == left_block) {
1360 EmitGoto(left_block);
1361 } else if (left_block == next_block) {
1362 branch.EmitInverted(chunk_->GetAssemblyLabel(right_block));
1364 branch.Emit(chunk_->GetAssemblyLabel(left_block));
1365 if (right_block != next_block) {
1366 __ B(chunk_->GetAssemblyLabel(right_block));
1372 template<class InstrType>
1373 void LCodeGen::EmitBranch(InstrType instr, Condition condition) {
1374 DCHECK((condition != al) && (condition != nv));
1375 BranchOnCondition branch(this, condition);
1376 EmitBranchGeneric(instr, branch);
1380 template<class InstrType>
1381 void LCodeGen::EmitCompareAndBranch(InstrType instr,
1382 Condition condition,
1383 const Register& lhs,
1384 const Operand& rhs) {
1385 DCHECK((condition != al) && (condition != nv));
1386 CompareAndBranch branch(this, condition, lhs, rhs);
1387 EmitBranchGeneric(instr, branch);
1391 template<class InstrType>
1392 void LCodeGen::EmitTestAndBranch(InstrType instr,
1393 Condition condition,
1394 const Register& value,
1396 DCHECK((condition != al) && (condition != nv));
1397 TestAndBranch branch(this, condition, value, mask);
1398 EmitBranchGeneric(instr, branch);
1402 template<class InstrType>
1403 void LCodeGen::EmitBranchIfNonZeroNumber(InstrType instr,
1404 const FPRegister& value,
1405 const FPRegister& scratch) {
1406 BranchIfNonZeroNumber branch(this, value, scratch);
1407 EmitBranchGeneric(instr, branch);
1411 template<class InstrType>
1412 void LCodeGen::EmitBranchIfHeapNumber(InstrType instr,
1413 const Register& value) {
1414 BranchIfHeapNumber branch(this, value);
1415 EmitBranchGeneric(instr, branch);
1419 template<class InstrType>
1420 void LCodeGen::EmitBranchIfRoot(InstrType instr,
1421 const Register& value,
1422 Heap::RootListIndex index) {
1423 BranchIfRoot branch(this, value, index);
1424 EmitBranchGeneric(instr, branch);
1428 void LCodeGen::DoGap(LGap* gap) {
1429 for (int i = LGap::FIRST_INNER_POSITION;
1430 i <= LGap::LAST_INNER_POSITION;
1432 LGap::InnerPosition inner_pos = static_cast<LGap::InnerPosition>(i);
1433 LParallelMove* move = gap->GetParallelMove(inner_pos);
1435 resolver_.Resolve(move);
1441 void LCodeGen::DoAccessArgumentsAt(LAccessArgumentsAt* instr) {
1442 Register arguments = ToRegister(instr->arguments());
1443 Register result = ToRegister(instr->result());
1445 // The pointer to the arguments array come from DoArgumentsElements.
1446 // It does not point directly to the arguments and there is an offest of
1447 // two words that we must take into account when accessing an argument.
1448 // Subtracting the index from length accounts for one, so we add one more.
1450 if (instr->length()->IsConstantOperand() &&
1451 instr->index()->IsConstantOperand()) {
1452 int index = ToInteger32(LConstantOperand::cast(instr->index()));
1453 int length = ToInteger32(LConstantOperand::cast(instr->length()));
1454 int offset = ((length - index) + 1) * kPointerSize;
1455 __ Ldr(result, MemOperand(arguments, offset));
1456 } else if (instr->index()->IsConstantOperand()) {
1457 Register length = ToRegister32(instr->length());
1458 int index = ToInteger32(LConstantOperand::cast(instr->index()));
1459 int loc = index - 1;
1461 __ Sub(result.W(), length, loc);
1462 __ Ldr(result, MemOperand(arguments, result, UXTW, kPointerSizeLog2));
1464 __ Ldr(result, MemOperand(arguments, length, UXTW, kPointerSizeLog2));
1467 Register length = ToRegister32(instr->length());
1468 Operand index = ToOperand32(instr->index());
1469 __ Sub(result.W(), length, index);
1470 __ Add(result.W(), result.W(), 1);
1471 __ Ldr(result, MemOperand(arguments, result, UXTW, kPointerSizeLog2));
1476 void LCodeGen::DoAddE(LAddE* instr) {
1477 Register result = ToRegister(instr->result());
1478 Register left = ToRegister(instr->left());
1479 Operand right = Operand(x0); // Dummy initialization.
1480 if (instr->hydrogen()->external_add_type() == AddOfExternalAndTagged) {
1481 right = Operand(ToRegister(instr->right()));
1482 } else if (instr->right()->IsConstantOperand()) {
1483 right = ToInteger32(LConstantOperand::cast(instr->right()));
1485 right = Operand(ToRegister32(instr->right()), SXTW);
1488 DCHECK(!instr->hydrogen()->CheckFlag(HValue::kCanOverflow));
1489 __ Add(result, left, right);
1493 void LCodeGen::DoAddI(LAddI* instr) {
1494 bool can_overflow = instr->hydrogen()->CheckFlag(HValue::kCanOverflow);
1495 Register result = ToRegister32(instr->result());
1496 Register left = ToRegister32(instr->left());
1497 Operand right = ToShiftedRightOperand32(instr->right(), instr);
1500 __ Adds(result, left, right);
1501 DeoptimizeIf(vs, instr, Deoptimizer::kOverflow);
1503 __ Add(result, left, right);
1508 void LCodeGen::DoAddS(LAddS* instr) {
1509 bool can_overflow = instr->hydrogen()->CheckFlag(HValue::kCanOverflow);
1510 Register result = ToRegister(instr->result());
1511 Register left = ToRegister(instr->left());
1512 Operand right = ToOperand(instr->right());
1514 __ Adds(result, left, right);
1515 DeoptimizeIf(vs, instr, Deoptimizer::kOverflow);
1517 __ Add(result, left, right);
1522 void LCodeGen::DoAllocate(LAllocate* instr) {
1523 class DeferredAllocate: public LDeferredCode {
1525 DeferredAllocate(LCodeGen* codegen, LAllocate* instr)
1526 : LDeferredCode(codegen), instr_(instr) { }
1527 virtual void Generate() { codegen()->DoDeferredAllocate(instr_); }
1528 virtual LInstruction* instr() { return instr_; }
1533 DeferredAllocate* deferred = new(zone()) DeferredAllocate(this, instr);
1535 Register result = ToRegister(instr->result());
1536 Register temp1 = ToRegister(instr->temp1());
1537 Register temp2 = ToRegister(instr->temp2());
1539 // Allocate memory for the object.
1540 AllocationFlags flags = TAG_OBJECT;
1541 if (instr->hydrogen()->MustAllocateDoubleAligned()) {
1542 flags = static_cast<AllocationFlags>(flags | DOUBLE_ALIGNMENT);
1545 if (instr->hydrogen()->IsOldSpaceAllocation()) {
1546 DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
1547 flags = static_cast<AllocationFlags>(flags | PRETENURE);
1550 if (instr->size()->IsConstantOperand()) {
1551 int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
1552 if (size <= Page::kMaxRegularHeapObjectSize) {
1553 __ Allocate(size, result, temp1, temp2, deferred->entry(), flags);
1555 __ B(deferred->entry());
1558 Register size = ToRegister32(instr->size());
1559 __ Sxtw(size.X(), size);
1560 __ Allocate(size.X(), result, temp1, temp2, deferred->entry(), flags);
1563 __ Bind(deferred->exit());
1565 if (instr->hydrogen()->MustPrefillWithFiller()) {
1566 Register filler_count = temp1;
1567 Register filler = temp2;
1568 Register untagged_result = ToRegister(instr->temp3());
1570 if (instr->size()->IsConstantOperand()) {
1571 int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
1572 __ Mov(filler_count, size / kPointerSize);
1574 __ Lsr(filler_count.W(), ToRegister32(instr->size()), kPointerSizeLog2);
1577 __ Sub(untagged_result, result, kHeapObjectTag);
1578 __ Mov(filler, Operand(isolate()->factory()->one_pointer_filler_map()));
1579 __ FillFields(untagged_result, filler_count, filler);
1581 DCHECK(instr->temp3() == NULL);
1586 void LCodeGen::DoDeferredAllocate(LAllocate* instr) {
1587 // TODO(3095996): Get rid of this. For now, we need to make the
1588 // result register contain a valid pointer because it is already
1589 // contained in the register pointer map.
1590 __ Mov(ToRegister(instr->result()), Smi::FromInt(0));
1592 PushSafepointRegistersScope scope(this);
1593 // We're in a SafepointRegistersScope so we can use any scratch registers.
1595 if (instr->size()->IsConstantOperand()) {
1596 __ Mov(size, ToSmi(LConstantOperand::cast(instr->size())));
1598 __ SmiTag(size, ToRegister32(instr->size()).X());
1600 int flags = AllocateDoubleAlignFlag::encode(
1601 instr->hydrogen()->MustAllocateDoubleAligned());
1602 if (instr->hydrogen()->IsOldSpaceAllocation()) {
1603 DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
1604 flags = AllocateTargetSpace::update(flags, OLD_SPACE);
1606 flags = AllocateTargetSpace::update(flags, NEW_SPACE);
1608 __ Mov(x10, Smi::FromInt(flags));
1611 CallRuntimeFromDeferred(
1612 Runtime::kAllocateInTargetSpace, 2, instr, instr->context());
1613 __ StoreToSafepointRegisterSlot(x0, ToRegister(instr->result()));
1617 void LCodeGen::DoApplyArguments(LApplyArguments* instr) {
1618 Register receiver = ToRegister(instr->receiver());
1619 Register function = ToRegister(instr->function());
1620 Register length = ToRegister32(instr->length());
1622 Register elements = ToRegister(instr->elements());
1623 Register scratch = x5;
1624 DCHECK(receiver.Is(x0)); // Used for parameter count.
1625 DCHECK(function.Is(x1)); // Required by InvokeFunction.
1626 DCHECK(ToRegister(instr->result()).Is(x0));
1627 DCHECK(instr->IsMarkedAsCall());
1629 // Copy the arguments to this function possibly from the
1630 // adaptor frame below it.
1631 const uint32_t kArgumentsLimit = 1 * KB;
1632 __ Cmp(length, kArgumentsLimit);
1633 DeoptimizeIf(hi, instr, Deoptimizer::kTooManyArguments);
1635 // Push the receiver and use the register to keep the original
1636 // number of arguments.
1638 Register argc = receiver;
1640 __ Sxtw(argc, length);
1641 // The arguments are at a one pointer size offset from elements.
1642 __ Add(elements, elements, 1 * kPointerSize);
1644 // Loop through the arguments pushing them onto the execution
1647 // length is a small non-negative integer, due to the test above.
1648 __ Cbz(length, &invoke);
1650 __ Ldr(scratch, MemOperand(elements, length, SXTW, kPointerSizeLog2));
1652 __ Subs(length, length, 1);
1656 DCHECK(instr->HasPointerMap());
1657 LPointerMap* pointers = instr->pointer_map();
1658 SafepointGenerator safepoint_generator(this, pointers, Safepoint::kLazyDeopt);
1659 // The number of arguments is stored in argc (receiver) which is x0, as
1660 // expected by InvokeFunction.
1661 ParameterCount actual(argc);
1662 __ InvokeFunction(function, actual, CALL_FUNCTION, safepoint_generator);
1666 void LCodeGen::DoArgumentsElements(LArgumentsElements* instr) {
1667 Register result = ToRegister(instr->result());
1669 if (instr->hydrogen()->from_inlined()) {
1670 // When we are inside an inlined function, the arguments are the last things
1671 // that have been pushed on the stack. Therefore the arguments array can be
1672 // accessed directly from jssp.
1673 // However in the normal case, it is accessed via fp but there are two words
1674 // on the stack between fp and the arguments (the saved lr and fp) and the
1675 // LAccessArgumentsAt implementation take that into account.
1676 // In the inlined case we need to subtract the size of 2 words to jssp to
1677 // get a pointer which will work well with LAccessArgumentsAt.
1678 DCHECK(masm()->StackPointer().Is(jssp));
1679 __ Sub(result, jssp, 2 * kPointerSize);
1681 DCHECK(instr->temp() != NULL);
1682 Register previous_fp = ToRegister(instr->temp());
1685 MemOperand(fp, StandardFrameConstants::kCallerFPOffset));
1687 MemOperand(previous_fp, StandardFrameConstants::kContextOffset));
1688 __ Cmp(result, Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR));
1689 __ Csel(result, fp, previous_fp, ne);
1694 void LCodeGen::DoArgumentsLength(LArgumentsLength* instr) {
1695 Register elements = ToRegister(instr->elements());
1696 Register result = ToRegister32(instr->result());
1699 // If no arguments adaptor frame the number of arguments is fixed.
1700 __ Cmp(fp, elements);
1701 __ Mov(result, scope()->num_parameters());
1704 // Arguments adaptor frame present. Get argument length from there.
1705 __ Ldr(result.X(), MemOperand(fp, StandardFrameConstants::kCallerFPOffset));
1707 UntagSmiMemOperand(result.X(),
1708 ArgumentsAdaptorFrameConstants::kLengthOffset));
1710 // Argument length is in result register.
1715 void LCodeGen::DoArithmeticD(LArithmeticD* instr) {
1716 DoubleRegister left = ToDoubleRegister(instr->left());
1717 DoubleRegister right = ToDoubleRegister(instr->right());
1718 DoubleRegister result = ToDoubleRegister(instr->result());
1720 switch (instr->op()) {
1721 case Token::ADD: __ Fadd(result, left, right); break;
1722 case Token::SUB: __ Fsub(result, left, right); break;
1723 case Token::MUL: __ Fmul(result, left, right); break;
1724 case Token::DIV: __ Fdiv(result, left, right); break;
1726 // The ECMA-262 remainder operator is the remainder from a truncating
1727 // (round-towards-zero) division. Note that this differs from IEEE-754.
1729 // TODO(jbramley): See if it's possible to do this inline, rather than by
1730 // calling a helper function. With frintz (to produce the intermediate
1731 // quotient) and fmsub (to calculate the remainder without loss of
1732 // precision), it should be possible. However, we would need support for
1733 // fdiv in round-towards-zero mode, and the ARM64 simulator doesn't
1734 // support that yet.
1735 DCHECK(left.Is(d0));
1736 DCHECK(right.Is(d1));
1738 ExternalReference::mod_two_doubles_operation(isolate()),
1740 DCHECK(result.Is(d0));
1750 void LCodeGen::DoArithmeticT(LArithmeticT* instr) {
1751 DCHECK(ToRegister(instr->context()).is(cp));
1752 DCHECK(ToRegister(instr->left()).is(x1));
1753 DCHECK(ToRegister(instr->right()).is(x0));
1754 DCHECK(ToRegister(instr->result()).is(x0));
1757 CodeFactory::BinaryOpIC(isolate(), instr->op(), instr->strength()).code();
1758 CallCode(code, RelocInfo::CODE_TARGET, instr);
1762 void LCodeGen::DoBitI(LBitI* instr) {
1763 Register result = ToRegister32(instr->result());
1764 Register left = ToRegister32(instr->left());
1765 Operand right = ToShiftedRightOperand32(instr->right(), instr);
1767 switch (instr->op()) {
1768 case Token::BIT_AND: __ And(result, left, right); break;
1769 case Token::BIT_OR: __ Orr(result, left, right); break;
1770 case Token::BIT_XOR: __ Eor(result, left, right); break;
1778 void LCodeGen::DoBitS(LBitS* instr) {
1779 Register result = ToRegister(instr->result());
1780 Register left = ToRegister(instr->left());
1781 Operand right = ToOperand(instr->right());
1783 switch (instr->op()) {
1784 case Token::BIT_AND: __ And(result, left, right); break;
1785 case Token::BIT_OR: __ Orr(result, left, right); break;
1786 case Token::BIT_XOR: __ Eor(result, left, right); break;
1794 void LCodeGen::DoBoundsCheck(LBoundsCheck *instr) {
1795 Condition cond = instr->hydrogen()->allow_equality() ? hi : hs;
1796 DCHECK(instr->hydrogen()->index()->representation().IsInteger32());
1797 DCHECK(instr->hydrogen()->length()->representation().IsInteger32());
1798 if (instr->index()->IsConstantOperand()) {
1799 Operand index = ToOperand32(instr->index());
1800 Register length = ToRegister32(instr->length());
1801 __ Cmp(length, index);
1802 cond = CommuteCondition(cond);
1804 Register index = ToRegister32(instr->index());
1805 Operand length = ToOperand32(instr->length());
1806 __ Cmp(index, length);
1808 if (FLAG_debug_code && instr->hydrogen()->skip_check()) {
1809 __ Assert(NegateCondition(cond), kEliminatedBoundsCheckFailed);
1811 DeoptimizeIf(cond, instr, Deoptimizer::kOutOfBounds);
1816 void LCodeGen::DoBranch(LBranch* instr) {
1817 Representation r = instr->hydrogen()->value()->representation();
1818 Label* true_label = instr->TrueLabel(chunk_);
1819 Label* false_label = instr->FalseLabel(chunk_);
1821 if (r.IsInteger32()) {
1822 DCHECK(!info()->IsStub());
1823 EmitCompareAndBranch(instr, ne, ToRegister32(instr->value()), 0);
1824 } else if (r.IsSmi()) {
1825 DCHECK(!info()->IsStub());
1826 STATIC_ASSERT(kSmiTag == 0);
1827 EmitCompareAndBranch(instr, ne, ToRegister(instr->value()), 0);
1828 } else if (r.IsDouble()) {
1829 DoubleRegister value = ToDoubleRegister(instr->value());
1830 // Test the double value. Zero and NaN are false.
1831 EmitBranchIfNonZeroNumber(instr, value, double_scratch());
1833 DCHECK(r.IsTagged());
1834 Register value = ToRegister(instr->value());
1835 HType type = instr->hydrogen()->value()->type();
1837 if (type.IsBoolean()) {
1838 DCHECK(!info()->IsStub());
1839 __ CompareRoot(value, Heap::kTrueValueRootIndex);
1840 EmitBranch(instr, eq);
1841 } else if (type.IsSmi()) {
1842 DCHECK(!info()->IsStub());
1843 EmitCompareAndBranch(instr, ne, value, Smi::FromInt(0));
1844 } else if (type.IsJSArray()) {
1845 DCHECK(!info()->IsStub());
1846 EmitGoto(instr->TrueDestination(chunk()));
1847 } else if (type.IsHeapNumber()) {
1848 DCHECK(!info()->IsStub());
1849 __ Ldr(double_scratch(), FieldMemOperand(value,
1850 HeapNumber::kValueOffset));
1851 // Test the double value. Zero and NaN are false.
1852 EmitBranchIfNonZeroNumber(instr, double_scratch(), double_scratch());
1853 } else if (type.IsString()) {
1854 DCHECK(!info()->IsStub());
1855 Register temp = ToRegister(instr->temp1());
1856 __ Ldr(temp, FieldMemOperand(value, String::kLengthOffset));
1857 EmitCompareAndBranch(instr, ne, temp, 0);
1859 ToBooleanStub::Types expected = instr->hydrogen()->expected_input_types();
1860 // Avoid deopts in the case where we've never executed this path before.
1861 if (expected.IsEmpty()) expected = ToBooleanStub::Types::Generic();
1863 if (expected.Contains(ToBooleanStub::UNDEFINED)) {
1864 // undefined -> false.
1866 value, Heap::kUndefinedValueRootIndex, false_label);
1869 if (expected.Contains(ToBooleanStub::BOOLEAN)) {
1870 // Boolean -> its value.
1872 value, Heap::kTrueValueRootIndex, true_label);
1874 value, Heap::kFalseValueRootIndex, false_label);
1877 if (expected.Contains(ToBooleanStub::NULL_TYPE)) {
1880 value, Heap::kNullValueRootIndex, false_label);
1883 if (expected.Contains(ToBooleanStub::SMI)) {
1884 // Smis: 0 -> false, all other -> true.
1885 DCHECK(Smi::FromInt(0) == 0);
1886 __ Cbz(value, false_label);
1887 __ JumpIfSmi(value, true_label);
1888 } else if (expected.NeedsMap()) {
1889 // If we need a map later and have a smi, deopt.
1890 DeoptimizeIfSmi(value, instr, Deoptimizer::kSmi);
1893 Register map = NoReg;
1894 Register scratch = NoReg;
1896 if (expected.NeedsMap()) {
1897 DCHECK((instr->temp1() != NULL) && (instr->temp2() != NULL));
1898 map = ToRegister(instr->temp1());
1899 scratch = ToRegister(instr->temp2());
1901 __ Ldr(map, FieldMemOperand(value, HeapObject::kMapOffset));
1903 if (expected.CanBeUndetectable()) {
1904 // Undetectable -> false.
1905 __ Ldrb(scratch, FieldMemOperand(map, Map::kBitFieldOffset));
1906 __ TestAndBranchIfAnySet(
1907 scratch, 1 << Map::kIsUndetectable, false_label);
1911 if (expected.Contains(ToBooleanStub::SPEC_OBJECT)) {
1912 // spec object -> true.
1913 __ CompareInstanceType(map, scratch, FIRST_SPEC_OBJECT_TYPE);
1914 __ B(ge, true_label);
1917 if (expected.Contains(ToBooleanStub::STRING)) {
1918 // String value -> false iff empty.
1920 __ CompareInstanceType(map, scratch, FIRST_NONSTRING_TYPE);
1921 __ B(ge, ¬_string);
1922 __ Ldr(scratch, FieldMemOperand(value, String::kLengthOffset));
1923 __ Cbz(scratch, false_label);
1925 __ Bind(¬_string);
1928 if (expected.Contains(ToBooleanStub::SYMBOL)) {
1929 // Symbol value -> true.
1930 __ CompareInstanceType(map, scratch, SYMBOL_TYPE);
1931 __ B(eq, true_label);
1934 if (expected.Contains(ToBooleanStub::SIMD_VALUE)) {
1935 // SIMD value -> true.
1936 __ CompareInstanceType(map, scratch, FLOAT32X4_TYPE);
1937 __ B(eq, true_label);
1940 if (expected.Contains(ToBooleanStub::HEAP_NUMBER)) {
1941 Label not_heap_number;
1942 __ JumpIfNotRoot(map, Heap::kHeapNumberMapRootIndex, ¬_heap_number);
1944 __ Ldr(double_scratch(),
1945 FieldMemOperand(value, HeapNumber::kValueOffset));
1946 __ Fcmp(double_scratch(), 0.0);
1947 // If we got a NaN (overflow bit is set), jump to the false branch.
1948 __ B(vs, false_label);
1949 __ B(eq, false_label);
1951 __ Bind(¬_heap_number);
1954 if (!expected.IsGeneric()) {
1955 // We've seen something for the first time -> deopt.
1956 // This can only happen if we are not generic already.
1957 Deoptimize(instr, Deoptimizer::kUnexpectedObject);
1964 void LCodeGen::CallKnownFunction(Handle<JSFunction> function,
1965 int formal_parameter_count, int arity,
1966 LInstruction* instr) {
1967 bool dont_adapt_arguments =
1968 formal_parameter_count == SharedFunctionInfo::kDontAdaptArgumentsSentinel;
1969 bool can_invoke_directly =
1970 dont_adapt_arguments || formal_parameter_count == arity;
1972 // The function interface relies on the following register assignments.
1973 Register function_reg = x1;
1974 Register arity_reg = x0;
1976 LPointerMap* pointers = instr->pointer_map();
1978 if (FLAG_debug_code) {
1980 // Try to confirm that function_reg (x1) is a tagged pointer.
1981 __ JumpIfNotSmi(function_reg, &is_not_smi);
1982 __ Abort(kExpectedFunctionObject);
1983 __ Bind(&is_not_smi);
1986 if (can_invoke_directly) {
1988 __ Ldr(cp, FieldMemOperand(function_reg, JSFunction::kContextOffset));
1990 // Set the arguments count if adaption is not needed. Assumes that x0 is
1991 // available to write to at this point.
1992 if (dont_adapt_arguments) {
1993 __ Mov(arity_reg, arity);
1997 __ Ldr(x10, FieldMemOperand(function_reg, JSFunction::kCodeEntryOffset));
2000 // Set up deoptimization.
2001 RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
2003 SafepointGenerator generator(this, pointers, Safepoint::kLazyDeopt);
2004 ParameterCount count(arity);
2005 ParameterCount expected(formal_parameter_count);
2006 __ InvokeFunction(function_reg, expected, count, CALL_FUNCTION, generator);
2011 void LCodeGen::DoCallWithDescriptor(LCallWithDescriptor* instr) {
2012 DCHECK(instr->IsMarkedAsCall());
2013 DCHECK(ToRegister(instr->result()).Is(x0));
2015 if (instr->hydrogen()->IsTailCall()) {
2016 if (NeedsEagerFrame()) __ LeaveFrame(StackFrame::INTERNAL);
2018 if (instr->target()->IsConstantOperand()) {
2019 LConstantOperand* target = LConstantOperand::cast(instr->target());
2020 Handle<Code> code = Handle<Code>::cast(ToHandle(target));
2021 // TODO(all): on ARM we use a call descriptor to specify a storage mode
2022 // but on ARM64 we only have one storage mode so it isn't necessary. Check
2023 // this understanding is correct.
2024 __ Jump(code, RelocInfo::CODE_TARGET);
2026 DCHECK(instr->target()->IsRegister());
2027 Register target = ToRegister(instr->target());
2028 __ Add(target, target, Code::kHeaderSize - kHeapObjectTag);
2032 LPointerMap* pointers = instr->pointer_map();
2033 SafepointGenerator generator(this, pointers, Safepoint::kLazyDeopt);
2035 if (instr->target()->IsConstantOperand()) {
2036 LConstantOperand* target = LConstantOperand::cast(instr->target());
2037 Handle<Code> code = Handle<Code>::cast(ToHandle(target));
2038 generator.BeforeCall(__ CallSize(code, RelocInfo::CODE_TARGET));
2039 // TODO(all): on ARM we use a call descriptor to specify a storage mode
2040 // but on ARM64 we only have one storage mode so it isn't necessary. Check
2041 // this understanding is correct.
2042 __ Call(code, RelocInfo::CODE_TARGET, TypeFeedbackId::None());
2044 DCHECK(instr->target()->IsRegister());
2045 Register target = ToRegister(instr->target());
2046 generator.BeforeCall(__ CallSize(target));
2047 __ Add(target, target, Code::kHeaderSize - kHeapObjectTag);
2050 generator.AfterCall();
2053 RecordPushedArgumentsDelta(instr->hydrogen()->argument_delta());
2057 void LCodeGen::DoCallJSFunction(LCallJSFunction* instr) {
2058 DCHECK(instr->IsMarkedAsCall());
2059 DCHECK(ToRegister(instr->function()).is(x1));
2061 if (instr->hydrogen()->pass_argument_count()) {
2062 __ Mov(x0, Operand(instr->arity()));
2066 __ Ldr(cp, FieldMemOperand(x1, JSFunction::kContextOffset));
2068 // Load the code entry address
2069 __ Ldr(x10, FieldMemOperand(x1, JSFunction::kCodeEntryOffset));
2072 RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
2073 RecordPushedArgumentsDelta(instr->hydrogen()->argument_delta());
2077 void LCodeGen::DoCallRuntime(LCallRuntime* instr) {
2078 CallRuntime(instr->function(), instr->arity(), instr);
2079 RecordPushedArgumentsDelta(instr->hydrogen()->argument_delta());
2083 void LCodeGen::DoCallStub(LCallStub* instr) {
2084 DCHECK(ToRegister(instr->context()).is(cp));
2085 DCHECK(ToRegister(instr->result()).is(x0));
2086 switch (instr->hydrogen()->major_key()) {
2087 case CodeStub::RegExpExec: {
2088 RegExpExecStub stub(isolate());
2089 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
2092 case CodeStub::SubString: {
2093 SubStringStub stub(isolate());
2094 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
2097 case CodeStub::StringCompare: {
2098 StringCompareStub stub(isolate());
2099 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
2105 RecordPushedArgumentsDelta(instr->hydrogen()->argument_delta());
2109 void LCodeGen::DoUnknownOSRValue(LUnknownOSRValue* instr) {
2110 GenerateOsrPrologue();
2114 void LCodeGen::DoDeferredInstanceMigration(LCheckMaps* instr, Register object) {
2115 Register temp = ToRegister(instr->temp());
2117 PushSafepointRegistersScope scope(this);
2120 __ CallRuntimeSaveDoubles(Runtime::kTryMigrateInstance);
2121 RecordSafepointWithRegisters(
2122 instr->pointer_map(), 1, Safepoint::kNoLazyDeopt);
2123 __ StoreToSafepointRegisterSlot(x0, temp);
2125 DeoptimizeIfSmi(temp, instr, Deoptimizer::kInstanceMigrationFailed);
2129 void LCodeGen::DoCheckMaps(LCheckMaps* instr) {
2130 class DeferredCheckMaps: public LDeferredCode {
2132 DeferredCheckMaps(LCodeGen* codegen, LCheckMaps* instr, Register object)
2133 : LDeferredCode(codegen), instr_(instr), object_(object) {
2134 SetExit(check_maps());
2136 virtual void Generate() {
2137 codegen()->DoDeferredInstanceMigration(instr_, object_);
2139 Label* check_maps() { return &check_maps_; }
2140 virtual LInstruction* instr() { return instr_; }
2147 if (instr->hydrogen()->IsStabilityCheck()) {
2148 const UniqueSet<Map>* maps = instr->hydrogen()->maps();
2149 for (int i = 0; i < maps->size(); ++i) {
2150 AddStabilityDependency(maps->at(i).handle());
2155 Register object = ToRegister(instr->value());
2156 Register map_reg = ToRegister(instr->temp());
2158 __ Ldr(map_reg, FieldMemOperand(object, HeapObject::kMapOffset));
2160 DeferredCheckMaps* deferred = NULL;
2161 if (instr->hydrogen()->HasMigrationTarget()) {
2162 deferred = new(zone()) DeferredCheckMaps(this, instr, object);
2163 __ Bind(deferred->check_maps());
2166 const UniqueSet<Map>* maps = instr->hydrogen()->maps();
2168 for (int i = 0; i < maps->size() - 1; i++) {
2169 Handle<Map> map = maps->at(i).handle();
2170 __ CompareMap(map_reg, map);
2173 Handle<Map> map = maps->at(maps->size() - 1).handle();
2174 __ CompareMap(map_reg, map);
2176 // We didn't match a map.
2177 if (instr->hydrogen()->HasMigrationTarget()) {
2178 __ B(ne, deferred->entry());
2180 DeoptimizeIf(ne, instr, Deoptimizer::kWrongMap);
2187 void LCodeGen::DoCheckNonSmi(LCheckNonSmi* instr) {
2188 if (!instr->hydrogen()->value()->type().IsHeapObject()) {
2189 DeoptimizeIfSmi(ToRegister(instr->value()), instr, Deoptimizer::kSmi);
2194 void LCodeGen::DoCheckSmi(LCheckSmi* instr) {
2195 Register value = ToRegister(instr->value());
2196 DCHECK(!instr->result() || ToRegister(instr->result()).Is(value));
2197 DeoptimizeIfNotSmi(value, instr, Deoptimizer::kNotASmi);
2201 void LCodeGen::DoCheckArrayBufferNotNeutered(
2202 LCheckArrayBufferNotNeutered* instr) {
2203 UseScratchRegisterScope temps(masm());
2204 Register view = ToRegister(instr->view());
2205 Register scratch = temps.AcquireX();
2207 __ Ldr(scratch, FieldMemOperand(view, JSArrayBufferView::kBufferOffset));
2208 __ Ldr(scratch, FieldMemOperand(scratch, JSArrayBuffer::kBitFieldOffset));
2209 __ Tst(scratch, Operand(1 << JSArrayBuffer::WasNeutered::kShift));
2210 DeoptimizeIf(ne, instr, Deoptimizer::kOutOfBounds);
2214 void LCodeGen::DoCheckInstanceType(LCheckInstanceType* instr) {
2215 Register input = ToRegister(instr->value());
2216 Register scratch = ToRegister(instr->temp());
2218 __ Ldr(scratch, FieldMemOperand(input, HeapObject::kMapOffset));
2219 __ Ldrb(scratch, FieldMemOperand(scratch, Map::kInstanceTypeOffset));
2221 if (instr->hydrogen()->is_interval_check()) {
2222 InstanceType first, last;
2223 instr->hydrogen()->GetCheckInterval(&first, &last);
2225 __ Cmp(scratch, first);
2226 if (first == last) {
2227 // If there is only one type in the interval check for equality.
2228 DeoptimizeIf(ne, instr, Deoptimizer::kWrongInstanceType);
2229 } else if (last == LAST_TYPE) {
2230 // We don't need to compare with the higher bound of the interval.
2231 DeoptimizeIf(lo, instr, Deoptimizer::kWrongInstanceType);
2233 // If we are below the lower bound, set the C flag and clear the Z flag
2234 // to force a deopt.
2235 __ Ccmp(scratch, last, CFlag, hs);
2236 DeoptimizeIf(hi, instr, Deoptimizer::kWrongInstanceType);
2241 instr->hydrogen()->GetCheckMaskAndTag(&mask, &tag);
2243 if (base::bits::IsPowerOfTwo32(mask)) {
2244 DCHECK((tag == 0) || (tag == mask));
2246 DeoptimizeIfBitSet(scratch, MaskToBit(mask), instr,
2247 Deoptimizer::kWrongInstanceType);
2249 DeoptimizeIfBitClear(scratch, MaskToBit(mask), instr,
2250 Deoptimizer::kWrongInstanceType);
2254 __ Tst(scratch, mask);
2256 __ And(scratch, scratch, mask);
2257 __ Cmp(scratch, tag);
2259 DeoptimizeIf(ne, instr, Deoptimizer::kWrongInstanceType);
2265 void LCodeGen::DoClampDToUint8(LClampDToUint8* instr) {
2266 DoubleRegister input = ToDoubleRegister(instr->unclamped());
2267 Register result = ToRegister32(instr->result());
2268 __ ClampDoubleToUint8(result, input, double_scratch());
2272 void LCodeGen::DoClampIToUint8(LClampIToUint8* instr) {
2273 Register input = ToRegister32(instr->unclamped());
2274 Register result = ToRegister32(instr->result());
2275 __ ClampInt32ToUint8(result, input);
2279 void LCodeGen::DoClampTToUint8(LClampTToUint8* instr) {
2280 Register input = ToRegister(instr->unclamped());
2281 Register result = ToRegister32(instr->result());
2284 // Both smi and heap number cases are handled.
2286 __ JumpIfNotSmi(input, &is_not_smi);
2287 __ SmiUntag(result.X(), input);
2288 __ ClampInt32ToUint8(result);
2291 __ Bind(&is_not_smi);
2293 // Check for heap number.
2294 Label is_heap_number;
2295 __ JumpIfHeapNumber(input, &is_heap_number);
2297 // Check for undefined. Undefined is coverted to zero for clamping conversion.
2298 DeoptimizeIfNotRoot(input, Heap::kUndefinedValueRootIndex, instr,
2299 Deoptimizer::kNotAHeapNumberUndefined);
2303 // Heap number case.
2304 __ Bind(&is_heap_number);
2305 DoubleRegister dbl_scratch = double_scratch();
2306 DoubleRegister dbl_scratch2 = ToDoubleRegister(instr->temp1());
2307 __ Ldr(dbl_scratch, FieldMemOperand(input, HeapNumber::kValueOffset));
2308 __ ClampDoubleToUint8(result, dbl_scratch, dbl_scratch2);
2314 void LCodeGen::DoDoubleBits(LDoubleBits* instr) {
2315 DoubleRegister value_reg = ToDoubleRegister(instr->value());
2316 Register result_reg = ToRegister(instr->result());
2317 if (instr->hydrogen()->bits() == HDoubleBits::HIGH) {
2318 __ Fmov(result_reg, value_reg);
2319 __ Lsr(result_reg, result_reg, 32);
2321 __ Fmov(result_reg.W(), value_reg.S());
2326 void LCodeGen::DoConstructDouble(LConstructDouble* instr) {
2327 Register hi_reg = ToRegister(instr->hi());
2328 Register lo_reg = ToRegister(instr->lo());
2329 DoubleRegister result_reg = ToDoubleRegister(instr->result());
2331 // Insert the least significant 32 bits of hi_reg into the most significant
2332 // 32 bits of lo_reg, and move to a floating point register.
2333 __ Bfi(lo_reg, hi_reg, 32, 32);
2334 __ Fmov(result_reg, lo_reg);
2338 void LCodeGen::DoClassOfTestAndBranch(LClassOfTestAndBranch* instr) {
2339 Handle<String> class_name = instr->hydrogen()->class_name();
2340 Label* true_label = instr->TrueLabel(chunk_);
2341 Label* false_label = instr->FalseLabel(chunk_);
2342 Register input = ToRegister(instr->value());
2343 Register scratch1 = ToRegister(instr->temp1());
2344 Register scratch2 = ToRegister(instr->temp2());
2346 __ JumpIfSmi(input, false_label);
2348 Register map = scratch2;
2349 if (String::Equals(isolate()->factory()->Function_string(), class_name)) {
2350 // Assuming the following assertions, we can use the same compares to test
2351 // for both being a function type and being in the object type range.
2352 STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
2353 STATIC_ASSERT(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE ==
2354 FIRST_SPEC_OBJECT_TYPE + 1);
2355 STATIC_ASSERT(LAST_NONCALLABLE_SPEC_OBJECT_TYPE ==
2356 LAST_SPEC_OBJECT_TYPE - 1);
2357 STATIC_ASSERT(LAST_SPEC_OBJECT_TYPE == LAST_TYPE);
2359 // We expect CompareObjectType to load the object instance type in scratch1.
2360 __ CompareObjectType(input, map, scratch1, FIRST_SPEC_OBJECT_TYPE);
2361 __ B(lt, false_label);
2362 __ B(eq, true_label);
2363 __ Cmp(scratch1, LAST_SPEC_OBJECT_TYPE);
2364 __ B(eq, true_label);
2366 __ IsObjectJSObjectType(input, map, scratch1, false_label);
2369 // Now we are in the FIRST-LAST_NONCALLABLE_SPEC_OBJECT_TYPE range.
2370 // Check if the constructor in the map is a function.
2372 UseScratchRegisterScope temps(masm());
2373 Register instance_type = temps.AcquireX();
2374 __ GetMapConstructor(scratch1, map, scratch2, instance_type);
2375 __ Cmp(instance_type, JS_FUNCTION_TYPE);
2377 // Objects with a non-function constructor have class 'Object'.
2378 if (String::Equals(class_name, isolate()->factory()->Object_string())) {
2379 __ B(ne, true_label);
2381 __ B(ne, false_label);
2384 // The constructor function is in scratch1. Get its instance class name.
2386 FieldMemOperand(scratch1, JSFunction::kSharedFunctionInfoOffset));
2388 FieldMemOperand(scratch1,
2389 SharedFunctionInfo::kInstanceClassNameOffset));
2391 // The class name we are testing against is internalized since it's a literal.
2392 // The name in the constructor is internalized because of the way the context
2393 // is booted. This routine isn't expected to work for random API-created
2394 // classes and it doesn't have to because you can't access it with natives
2395 // syntax. Since both sides are internalized it is sufficient to use an
2396 // identity comparison.
2397 EmitCompareAndBranch(instr, eq, scratch1, Operand(class_name));
2401 void LCodeGen::DoCmpHoleAndBranchD(LCmpHoleAndBranchD* instr) {
2402 DCHECK(instr->hydrogen()->representation().IsDouble());
2403 FPRegister object = ToDoubleRegister(instr->object());
2404 Register temp = ToRegister(instr->temp());
2406 // If we don't have a NaN, we don't have the hole, so branch now to avoid the
2407 // (relatively expensive) hole-NaN check.
2408 __ Fcmp(object, object);
2409 __ B(vc, instr->FalseLabel(chunk_));
2411 // We have a NaN, but is it the hole?
2412 __ Fmov(temp, object);
2413 EmitCompareAndBranch(instr, eq, temp, kHoleNanInt64);
2417 void LCodeGen::DoCmpHoleAndBranchT(LCmpHoleAndBranchT* instr) {
2418 DCHECK(instr->hydrogen()->representation().IsTagged());
2419 Register object = ToRegister(instr->object());
2421 EmitBranchIfRoot(instr, object, Heap::kTheHoleValueRootIndex);
2425 void LCodeGen::DoCmpMapAndBranch(LCmpMapAndBranch* instr) {
2426 Register value = ToRegister(instr->value());
2427 Register map = ToRegister(instr->temp());
2429 __ Ldr(map, FieldMemOperand(value, HeapObject::kMapOffset));
2430 EmitCompareAndBranch(instr, eq, map, Operand(instr->map()));
2434 void LCodeGen::DoCompareMinusZeroAndBranch(LCompareMinusZeroAndBranch* instr) {
2435 Representation rep = instr->hydrogen()->value()->representation();
2436 DCHECK(!rep.IsInteger32());
2437 Register scratch = ToRegister(instr->temp());
2439 if (rep.IsDouble()) {
2440 __ JumpIfMinusZero(ToDoubleRegister(instr->value()),
2441 instr->TrueLabel(chunk()));
2443 Register value = ToRegister(instr->value());
2444 __ JumpIfNotHeapNumber(value, instr->FalseLabel(chunk()), DO_SMI_CHECK);
2445 __ Ldr(scratch, FieldMemOperand(value, HeapNumber::kValueOffset));
2446 __ JumpIfMinusZero(scratch, instr->TrueLabel(chunk()));
2448 EmitGoto(instr->FalseDestination(chunk()));
2452 void LCodeGen::DoCompareNumericAndBranch(LCompareNumericAndBranch* instr) {
2453 LOperand* left = instr->left();
2454 LOperand* right = instr->right();
2456 instr->hydrogen()->left()->CheckFlag(HInstruction::kUint32) ||
2457 instr->hydrogen()->right()->CheckFlag(HInstruction::kUint32);
2458 Condition cond = TokenToCondition(instr->op(), is_unsigned);
2460 if (left->IsConstantOperand() && right->IsConstantOperand()) {
2461 // We can statically evaluate the comparison.
2462 double left_val = ToDouble(LConstantOperand::cast(left));
2463 double right_val = ToDouble(LConstantOperand::cast(right));
2464 int next_block = EvalComparison(instr->op(), left_val, right_val) ?
2465 instr->TrueDestination(chunk_) : instr->FalseDestination(chunk_);
2466 EmitGoto(next_block);
2468 if (instr->is_double()) {
2469 __ Fcmp(ToDoubleRegister(left), ToDoubleRegister(right));
2471 // If a NaN is involved, i.e. the result is unordered (V set),
2472 // jump to false block label.
2473 __ B(vs, instr->FalseLabel(chunk_));
2474 EmitBranch(instr, cond);
2476 if (instr->hydrogen_value()->representation().IsInteger32()) {
2477 if (right->IsConstantOperand()) {
2478 EmitCompareAndBranch(instr, cond, ToRegister32(left),
2479 ToOperand32(right));
2481 // Commute the operands and the condition.
2482 EmitCompareAndBranch(instr, CommuteCondition(cond),
2483 ToRegister32(right), ToOperand32(left));
2486 DCHECK(instr->hydrogen_value()->representation().IsSmi());
2487 if (right->IsConstantOperand()) {
2488 int32_t value = ToInteger32(LConstantOperand::cast(right));
2489 EmitCompareAndBranch(instr,
2492 Operand(Smi::FromInt(value)));
2493 } else if (left->IsConstantOperand()) {
2494 // Commute the operands and the condition.
2495 int32_t value = ToInteger32(LConstantOperand::cast(left));
2496 EmitCompareAndBranch(instr,
2497 CommuteCondition(cond),
2499 Operand(Smi::FromInt(value)));
2501 EmitCompareAndBranch(instr,
2512 void LCodeGen::DoCmpObjectEqAndBranch(LCmpObjectEqAndBranch* instr) {
2513 Register left = ToRegister(instr->left());
2514 Register right = ToRegister(instr->right());
2515 EmitCompareAndBranch(instr, eq, left, right);
2519 void LCodeGen::DoCmpT(LCmpT* instr) {
2520 DCHECK(ToRegister(instr->context()).is(cp));
2521 Token::Value op = instr->op();
2522 Condition cond = TokenToCondition(op, false);
2524 DCHECK(ToRegister(instr->left()).Is(x1));
2525 DCHECK(ToRegister(instr->right()).Is(x0));
2527 CodeFactory::CompareIC(isolate(), op, instr->strength()).code();
2528 CallCode(ic, RelocInfo::CODE_TARGET, instr);
2529 // Signal that we don't inline smi code before this stub.
2530 InlineSmiCheckInfo::EmitNotInlined(masm());
2532 // Return true or false depending on CompareIC result.
2533 // This instruction is marked as call. We can clobber any register.
2534 DCHECK(instr->IsMarkedAsCall());
2535 __ LoadTrueFalseRoots(x1, x2);
2537 __ Csel(ToRegister(instr->result()), x1, x2, cond);
2541 void LCodeGen::DoConstantD(LConstantD* instr) {
2542 DCHECK(instr->result()->IsDoubleRegister());
2543 DoubleRegister result = ToDoubleRegister(instr->result());
2544 if (instr->value() == 0) {
2545 if (copysign(1.0, instr->value()) == 1.0) {
2546 __ Fmov(result, fp_zero);
2548 __ Fneg(result, fp_zero);
2551 __ Fmov(result, instr->value());
2556 void LCodeGen::DoConstantE(LConstantE* instr) {
2557 __ Mov(ToRegister(instr->result()), Operand(instr->value()));
2561 void LCodeGen::DoConstantI(LConstantI* instr) {
2562 DCHECK(is_int32(instr->value()));
2563 // Cast the value here to ensure that the value isn't sign extended by the
2564 // implicit Operand constructor.
2565 __ Mov(ToRegister32(instr->result()), static_cast<uint32_t>(instr->value()));
2569 void LCodeGen::DoConstantS(LConstantS* instr) {
2570 __ Mov(ToRegister(instr->result()), Operand(instr->value()));
2574 void LCodeGen::DoConstantT(LConstantT* instr) {
2575 Handle<Object> object = instr->value(isolate());
2576 AllowDeferredHandleDereference smi_check;
2577 __ LoadObject(ToRegister(instr->result()), object);
2581 void LCodeGen::DoContext(LContext* instr) {
2582 // If there is a non-return use, the context must be moved to a register.
2583 Register result = ToRegister(instr->result());
2584 if (info()->IsOptimizing()) {
2585 __ Ldr(result, MemOperand(fp, StandardFrameConstants::kContextOffset));
2587 // If there is no frame, the context must be in cp.
2588 DCHECK(result.is(cp));
2593 void LCodeGen::DoCheckValue(LCheckValue* instr) {
2594 Register reg = ToRegister(instr->value());
2595 Handle<HeapObject> object = instr->hydrogen()->object().handle();
2596 AllowDeferredHandleDereference smi_check;
2597 if (isolate()->heap()->InNewSpace(*object)) {
2598 UseScratchRegisterScope temps(masm());
2599 Register temp = temps.AcquireX();
2600 Handle<Cell> cell = isolate()->factory()->NewCell(object);
2601 __ Mov(temp, Operand(cell));
2602 __ Ldr(temp, FieldMemOperand(temp, Cell::kValueOffset));
2605 __ Cmp(reg, Operand(object));
2607 DeoptimizeIf(ne, instr, Deoptimizer::kValueMismatch);
2611 void LCodeGen::DoLazyBailout(LLazyBailout* instr) {
2612 last_lazy_deopt_pc_ = masm()->pc_offset();
2613 DCHECK(instr->HasEnvironment());
2614 LEnvironment* env = instr->environment();
2615 RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt);
2616 safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
2620 void LCodeGen::DoDateField(LDateField* instr) {
2621 Register object = ToRegister(instr->date());
2622 Register result = ToRegister(instr->result());
2623 Register temp1 = x10;
2624 Register temp2 = x11;
2625 Smi* index = instr->index();
2627 DCHECK(object.is(result) && object.Is(x0));
2628 DCHECK(instr->IsMarkedAsCall());
2630 if (index->value() == 0) {
2631 __ Ldr(result, FieldMemOperand(object, JSDate::kValueOffset));
2633 Label runtime, done;
2634 if (index->value() < JSDate::kFirstUncachedField) {
2635 ExternalReference stamp = ExternalReference::date_cache_stamp(isolate());
2636 __ Mov(temp1, Operand(stamp));
2637 __ Ldr(temp1, MemOperand(temp1));
2638 __ Ldr(temp2, FieldMemOperand(object, JSDate::kCacheStampOffset));
2639 __ Cmp(temp1, temp2);
2641 __ Ldr(result, FieldMemOperand(object, JSDate::kValueOffset +
2642 kPointerSize * index->value()));
2647 __ Mov(x1, Operand(index));
2648 __ CallCFunction(ExternalReference::get_date_field_function(isolate()), 2);
2654 void LCodeGen::DoDeoptimize(LDeoptimize* instr) {
2655 Deoptimizer::BailoutType type = instr->hydrogen()->type();
2656 // TODO(danno): Stubs expect all deopts to be lazy for historical reasons (the
2657 // needed return address), even though the implementation of LAZY and EAGER is
2658 // now identical. When LAZY is eventually completely folded into EAGER, remove
2659 // the special case below.
2660 if (info()->IsStub() && (type == Deoptimizer::EAGER)) {
2661 type = Deoptimizer::LAZY;
2664 Deoptimize(instr, instr->hydrogen()->reason(), &type);
2668 void LCodeGen::DoDivByPowerOf2I(LDivByPowerOf2I* instr) {
2669 Register dividend = ToRegister32(instr->dividend());
2670 int32_t divisor = instr->divisor();
2671 Register result = ToRegister32(instr->result());
2672 DCHECK(divisor == kMinInt || base::bits::IsPowerOfTwo32(Abs(divisor)));
2673 DCHECK(!result.is(dividend));
2675 // Check for (0 / -x) that will produce negative zero.
2676 HDiv* hdiv = instr->hydrogen();
2677 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
2678 DeoptimizeIfZero(dividend, instr, Deoptimizer::kDivisionByZero);
2680 // Check for (kMinInt / -1).
2681 if (hdiv->CheckFlag(HValue::kCanOverflow) && divisor == -1) {
2682 // Test dividend for kMinInt by subtracting one (cmp) and checking for
2684 __ Cmp(dividend, 1);
2685 DeoptimizeIf(vs, instr, Deoptimizer::kOverflow);
2687 // Deoptimize if remainder will not be 0.
2688 if (!hdiv->CheckFlag(HInstruction::kAllUsesTruncatingToInt32) &&
2689 divisor != 1 && divisor != -1) {
2690 int32_t mask = divisor < 0 ? -(divisor + 1) : (divisor - 1);
2691 __ Tst(dividend, mask);
2692 DeoptimizeIf(ne, instr, Deoptimizer::kLostPrecision);
2695 if (divisor == -1) { // Nice shortcut, not needed for correctness.
2696 __ Neg(result, dividend);
2699 int32_t shift = WhichPowerOf2Abs(divisor);
2701 __ Mov(result, dividend);
2702 } else if (shift == 1) {
2703 __ Add(result, dividend, Operand(dividend, LSR, 31));
2705 __ Mov(result, Operand(dividend, ASR, 31));
2706 __ Add(result, dividend, Operand(result, LSR, 32 - shift));
2708 if (shift > 0) __ Mov(result, Operand(result, ASR, shift));
2709 if (divisor < 0) __ Neg(result, result);
2713 void LCodeGen::DoDivByConstI(LDivByConstI* instr) {
2714 Register dividend = ToRegister32(instr->dividend());
2715 int32_t divisor = instr->divisor();
2716 Register result = ToRegister32(instr->result());
2717 DCHECK(!AreAliased(dividend, result));
2720 Deoptimize(instr, Deoptimizer::kDivisionByZero);
2724 // Check for (0 / -x) that will produce negative zero.
2725 HDiv* hdiv = instr->hydrogen();
2726 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
2727 DeoptimizeIfZero(dividend, instr, Deoptimizer::kMinusZero);
2730 __ TruncatingDiv(result, dividend, Abs(divisor));
2731 if (divisor < 0) __ Neg(result, result);
2733 if (!hdiv->CheckFlag(HInstruction::kAllUsesTruncatingToInt32)) {
2734 Register temp = ToRegister32(instr->temp());
2735 DCHECK(!AreAliased(dividend, result, temp));
2736 __ Sxtw(dividend.X(), dividend);
2737 __ Mov(temp, divisor);
2738 __ Smsubl(temp.X(), result, temp, dividend.X());
2739 DeoptimizeIfNotZero(temp, instr, Deoptimizer::kLostPrecision);
2744 // TODO(svenpanne) Refactor this to avoid code duplication with DoFlooringDivI.
2745 void LCodeGen::DoDivI(LDivI* instr) {
2746 HBinaryOperation* hdiv = instr->hydrogen();
2747 Register dividend = ToRegister32(instr->dividend());
2748 Register divisor = ToRegister32(instr->divisor());
2749 Register result = ToRegister32(instr->result());
2751 // Issue the division first, and then check for any deopt cases whilst the
2752 // result is computed.
2753 __ Sdiv(result, dividend, divisor);
2755 if (hdiv->CheckFlag(HValue::kAllUsesTruncatingToInt32)) {
2756 DCHECK(!instr->temp());
2761 if (hdiv->CheckFlag(HValue::kCanBeDivByZero)) {
2762 DeoptimizeIfZero(divisor, instr, Deoptimizer::kDivisionByZero);
2765 // Check for (0 / -x) as that will produce negative zero.
2766 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero)) {
2769 // If the divisor < 0 (mi), compare the dividend, and deopt if it is
2770 // zero, ie. zero dividend with negative divisor deopts.
2771 // If the divisor >= 0 (pl, the opposite of mi) set the flags to
2772 // condition ne, so we don't deopt, ie. positive divisor doesn't deopt.
2773 __ Ccmp(dividend, 0, NoFlag, mi);
2774 DeoptimizeIf(eq, instr, Deoptimizer::kMinusZero);
2777 // Check for (kMinInt / -1).
2778 if (hdiv->CheckFlag(HValue::kCanOverflow)) {
2779 // Test dividend for kMinInt by subtracting one (cmp) and checking for
2781 __ Cmp(dividend, 1);
2782 // If overflow is set, ie. dividend = kMinInt, compare the divisor with
2783 // -1. If overflow is clear, set the flags for condition ne, as the
2784 // dividend isn't -1, and thus we shouldn't deopt.
2785 __ Ccmp(divisor, -1, NoFlag, vs);
2786 DeoptimizeIf(eq, instr, Deoptimizer::kOverflow);
2789 // Compute remainder and deopt if it's not zero.
2790 Register remainder = ToRegister32(instr->temp());
2791 __ Msub(remainder, result, divisor, dividend);
2792 DeoptimizeIfNotZero(remainder, instr, Deoptimizer::kLostPrecision);
2796 void LCodeGen::DoDoubleToIntOrSmi(LDoubleToIntOrSmi* instr) {
2797 DoubleRegister input = ToDoubleRegister(instr->value());
2798 Register result = ToRegister32(instr->result());
2800 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
2801 DeoptimizeIfMinusZero(input, instr, Deoptimizer::kMinusZero);
2804 __ TryRepresentDoubleAsInt32(result, input, double_scratch());
2805 DeoptimizeIf(ne, instr, Deoptimizer::kLostPrecisionOrNaN);
2807 if (instr->tag_result()) {
2808 __ SmiTag(result.X());
2813 void LCodeGen::DoDrop(LDrop* instr) {
2814 __ Drop(instr->count());
2818 void LCodeGen::DoDummy(LDummy* instr) {
2819 // Nothing to see here, move on!
2823 void LCodeGen::DoDummyUse(LDummyUse* instr) {
2824 // Nothing to see here, move on!
2828 void LCodeGen::DoFunctionLiteral(LFunctionLiteral* instr) {
2829 DCHECK(ToRegister(instr->context()).is(cp));
2830 // FunctionLiteral instruction is marked as call, we can trash any register.
2831 DCHECK(instr->IsMarkedAsCall());
2833 // Use the fast case closure allocation code that allocates in new
2834 // space for nested functions that don't need literals cloning.
2835 bool pretenure = instr->hydrogen()->pretenure();
2836 if (!pretenure && instr->hydrogen()->has_no_literals()) {
2837 FastNewClosureStub stub(isolate(), instr->hydrogen()->language_mode(),
2838 instr->hydrogen()->kind());
2839 __ Mov(x2, Operand(instr->hydrogen()->shared_info()));
2840 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
2842 __ Mov(x2, Operand(instr->hydrogen()->shared_info()));
2843 __ Mov(x1, Operand(pretenure ? factory()->true_value()
2844 : factory()->false_value()));
2845 __ Push(cp, x2, x1);
2846 CallRuntime(Runtime::kNewClosure, 3, instr);
2851 void LCodeGen::DoForInCacheArray(LForInCacheArray* instr) {
2852 Register map = ToRegister(instr->map());
2853 Register result = ToRegister(instr->result());
2854 Label load_cache, done;
2856 __ EnumLengthUntagged(result, map);
2857 __ Cbnz(result, &load_cache);
2859 __ Mov(result, Operand(isolate()->factory()->empty_fixed_array()));
2862 __ Bind(&load_cache);
2863 __ LoadInstanceDescriptors(map, result);
2864 __ Ldr(result, FieldMemOperand(result, DescriptorArray::kEnumCacheOffset));
2865 __ Ldr(result, FieldMemOperand(result, FixedArray::SizeFor(instr->idx())));
2866 DeoptimizeIfZero(result, instr, Deoptimizer::kNoCache);
2872 void LCodeGen::DoForInPrepareMap(LForInPrepareMap* instr) {
2873 Register object = ToRegister(instr->object());
2874 Register null_value = x5;
2876 DCHECK(instr->IsMarkedAsCall());
2877 DCHECK(object.Is(x0));
2879 DeoptimizeIfSmi(object, instr, Deoptimizer::kSmi);
2881 STATIC_ASSERT(FIRST_JS_PROXY_TYPE == FIRST_SPEC_OBJECT_TYPE);
2882 __ CompareObjectType(object, x1, x1, LAST_JS_PROXY_TYPE);
2883 DeoptimizeIf(le, instr, Deoptimizer::kNotAJavaScriptObject);
2885 Label use_cache, call_runtime;
2886 __ LoadRoot(null_value, Heap::kNullValueRootIndex);
2887 __ CheckEnumCache(object, null_value, x1, x2, x3, x4, &call_runtime);
2889 __ Ldr(object, FieldMemOperand(object, HeapObject::kMapOffset));
2892 // Get the set of properties to enumerate.
2893 __ Bind(&call_runtime);
2895 CallRuntime(Runtime::kGetPropertyNamesFast, 1, instr);
2897 __ Ldr(x1, FieldMemOperand(object, HeapObject::kMapOffset));
2898 DeoptimizeIfNotRoot(x1, Heap::kMetaMapRootIndex, instr,
2899 Deoptimizer::kWrongMap);
2901 __ Bind(&use_cache);
2905 void LCodeGen::DoGetCachedArrayIndex(LGetCachedArrayIndex* instr) {
2906 Register input = ToRegister(instr->value());
2907 Register result = ToRegister(instr->result());
2909 __ AssertString(input);
2911 // Assert that we can use a W register load to get the hash.
2912 DCHECK((String::kHashShift + String::kArrayIndexValueBits) < kWRegSizeInBits);
2913 __ Ldr(result.W(), FieldMemOperand(input, String::kHashFieldOffset));
2914 __ IndexFromHash(result, result);
2918 void LCodeGen::EmitGoto(int block) {
2919 // Do not emit jump if we are emitting a goto to the next block.
2920 if (!IsNextEmittedBlock(block)) {
2921 __ B(chunk_->GetAssemblyLabel(LookupDestination(block)));
2926 void LCodeGen::DoGoto(LGoto* instr) {
2927 EmitGoto(instr->block_id());
2931 void LCodeGen::DoHasCachedArrayIndexAndBranch(
2932 LHasCachedArrayIndexAndBranch* instr) {
2933 Register input = ToRegister(instr->value());
2934 Register temp = ToRegister32(instr->temp());
2936 // Assert that the cache status bits fit in a W register.
2937 DCHECK(is_uint32(String::kContainsCachedArrayIndexMask));
2938 __ Ldr(temp, FieldMemOperand(input, String::kHashFieldOffset));
2939 __ Tst(temp, String::kContainsCachedArrayIndexMask);
2940 EmitBranch(instr, eq);
2944 // HHasInstanceTypeAndBranch instruction is built with an interval of type
2945 // to test but is only used in very restricted ways. The only possible kinds
2946 // of intervals are:
2947 // - [ FIRST_TYPE, instr->to() ]
2948 // - [ instr->form(), LAST_TYPE ]
2949 // - instr->from() == instr->to()
2951 // These kinds of intervals can be check with only one compare instruction
2952 // providing the correct value and test condition are used.
2954 // TestType() will return the value to use in the compare instruction and
2955 // BranchCondition() will return the condition to use depending on the kind
2956 // of interval actually specified in the instruction.
2957 static InstanceType TestType(HHasInstanceTypeAndBranch* instr) {
2958 InstanceType from = instr->from();
2959 InstanceType to = instr->to();
2960 if (from == FIRST_TYPE) return to;
2961 DCHECK((from == to) || (to == LAST_TYPE));
2966 // See comment above TestType function for what this function does.
2967 static Condition BranchCondition(HHasInstanceTypeAndBranch* instr) {
2968 InstanceType from = instr->from();
2969 InstanceType to = instr->to();
2970 if (from == to) return eq;
2971 if (to == LAST_TYPE) return hs;
2972 if (from == FIRST_TYPE) return ls;
2978 void LCodeGen::DoHasInstanceTypeAndBranch(LHasInstanceTypeAndBranch* instr) {
2979 Register input = ToRegister(instr->value());
2980 Register scratch = ToRegister(instr->temp());
2982 if (!instr->hydrogen()->value()->type().IsHeapObject()) {
2983 __ JumpIfSmi(input, instr->FalseLabel(chunk_));
2985 __ CompareObjectType(input, scratch, scratch, TestType(instr->hydrogen()));
2986 EmitBranch(instr, BranchCondition(instr->hydrogen()));
2990 void LCodeGen::DoInnerAllocatedObject(LInnerAllocatedObject* instr) {
2991 Register result = ToRegister(instr->result());
2992 Register base = ToRegister(instr->base_object());
2993 if (instr->offset()->IsConstantOperand()) {
2994 __ Add(result, base, ToOperand32(instr->offset()));
2996 __ Add(result, base, Operand(ToRegister32(instr->offset()), SXTW));
3001 void LCodeGen::DoInstanceOf(LInstanceOf* instr) {
3002 DCHECK(ToRegister(instr->context()).is(cp));
3003 // Assert that the arguments are in the registers expected by InstanceofStub.
3004 DCHECK(ToRegister(instr->left()).Is(InstanceofStub::left()));
3005 DCHECK(ToRegister(instr->right()).Is(InstanceofStub::right()));
3007 InstanceofStub stub(isolate(), InstanceofStub::kArgsInRegisters);
3008 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
3010 // InstanceofStub returns a result in x0:
3011 // 0 => not an instance
3012 // smi 1 => instance.
3014 __ LoadTrueFalseRoots(x0, x1);
3015 __ Csel(x0, x0, x1, eq);
3019 void LCodeGen::DoInstanceOfKnownGlobal(LInstanceOfKnownGlobal* instr) {
3020 class DeferredInstanceOfKnownGlobal: public LDeferredCode {
3022 DeferredInstanceOfKnownGlobal(LCodeGen* codegen,
3023 LInstanceOfKnownGlobal* instr)
3024 : LDeferredCode(codegen), instr_(instr) { }
3025 virtual void Generate() {
3026 codegen()->DoDeferredInstanceOfKnownGlobal(instr_);
3028 virtual LInstruction* instr() { return instr_; }
3030 LInstanceOfKnownGlobal* instr_;
3033 DeferredInstanceOfKnownGlobal* deferred =
3034 new(zone()) DeferredInstanceOfKnownGlobal(this, instr);
3036 Label map_check, return_false, cache_miss, done;
3037 Register object = ToRegister(instr->value());
3038 Register result = ToRegister(instr->result());
3039 // x4 is expected in the associated deferred code and stub.
3040 Register map_check_site = x4;
3043 // This instruction is marked as call. We can clobber any register.
3044 DCHECK(instr->IsMarkedAsCall());
3046 // We must take into account that object is in x11.
3047 DCHECK(object.Is(x11));
3048 Register scratch = x10;
3050 // A Smi is not instance of anything.
3051 __ JumpIfSmi(object, &return_false);
3053 // This is the inlined call site instanceof cache. The two occurences of the
3054 // hole value will be patched to the last map/result pair generated by the
3056 __ Ldr(map, FieldMemOperand(object, HeapObject::kMapOffset));
3058 // Below we use Factory::the_hole_value() on purpose instead of loading from
3059 // the root array to force relocation and later be able to patch with a
3061 InstructionAccurateScope scope(masm(), 5);
3062 __ bind(&map_check);
3063 // Will be patched with the cached map.
3064 Handle<Cell> cell = factory()->NewCell(factory()->the_hole_value());
3065 __ ldr(scratch, Immediate(cell));
3066 __ ldr(scratch, FieldMemOperand(scratch, Cell::kValueOffset));
3067 __ cmp(map, scratch);
3068 __ b(&cache_miss, ne);
3069 // The address of this instruction is computed relative to the map check
3070 // above, so check the size of the code generated.
3071 DCHECK(masm()->InstructionsGeneratedSince(&map_check) == 4);
3072 // Will be patched with the cached result.
3073 __ ldr(result, Immediate(factory()->the_hole_value()));
3077 // The inlined call site cache did not match.
3078 // Check null and string before calling the deferred code.
3079 __ Bind(&cache_miss);
3080 // Compute the address of the map check. It must not be clobbered until the
3081 // InstanceOfStub has used it.
3082 __ Adr(map_check_site, &map_check);
3083 // Null is not instance of anything.
3084 __ JumpIfRoot(object, Heap::kNullValueRootIndex, &return_false);
3086 // String values are not instances of anything.
3087 // Return false if the object is a string. Otherwise, jump to the deferred
3089 // Note that we can't jump directly to deferred code from
3090 // IsObjectJSStringType, because it uses tbz for the jump and the deferred
3091 // code can be out of range.
3092 __ IsObjectJSStringType(object, scratch, NULL, &return_false);
3093 __ B(deferred->entry());
3095 __ Bind(&return_false);
3096 __ LoadRoot(result, Heap::kFalseValueRootIndex);
3098 // Here result is either true or false.
3099 __ Bind(deferred->exit());
3104 void LCodeGen::DoDeferredInstanceOfKnownGlobal(LInstanceOfKnownGlobal* instr) {
3105 Register result = ToRegister(instr->result());
3106 DCHECK(result.Is(x0)); // InstanceofStub returns its result in x0.
3107 InstanceofStub::Flags flags = InstanceofStub::kNoFlags;
3108 flags = static_cast<InstanceofStub::Flags>(
3109 flags | InstanceofStub::kArgsInRegisters);
3110 flags = static_cast<InstanceofStub::Flags>(
3111 flags | InstanceofStub::kReturnTrueFalseObject);
3112 flags = static_cast<InstanceofStub::Flags>(
3113 flags | InstanceofStub::kCallSiteInlineCheck);
3115 PushSafepointRegistersScope scope(this);
3116 LoadContextFromDeferred(instr->context());
3118 // Prepare InstanceofStub arguments.
3119 DCHECK(ToRegister(instr->value()).Is(InstanceofStub::left()));
3120 __ LoadObject(InstanceofStub::right(), instr->function());
3122 InstanceofStub stub(isolate(), flags);
3123 CallCodeGeneric(stub.GetCode(),
3124 RelocInfo::CODE_TARGET,
3126 RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
3127 LEnvironment* env = instr->GetDeferredLazyDeoptimizationEnvironment();
3128 safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
3130 // Put the result value into the result register slot.
3131 __ StoreToSafepointRegisterSlot(result, result);
3135 void LCodeGen::DoInstructionGap(LInstructionGap* instr) {
3140 void LCodeGen::DoInteger32ToDouble(LInteger32ToDouble* instr) {
3141 Register value = ToRegister32(instr->value());
3142 DoubleRegister result = ToDoubleRegister(instr->result());
3143 __ Scvtf(result, value);
3147 void LCodeGen::DoInvokeFunction(LInvokeFunction* instr) {
3148 DCHECK(ToRegister(instr->context()).is(cp));
3149 // The function is required to be in x1.
3150 DCHECK(ToRegister(instr->function()).is(x1));
3151 DCHECK(instr->HasPointerMap());
3153 Handle<JSFunction> known_function = instr->hydrogen()->known_function();
3154 if (known_function.is_null()) {
3155 LPointerMap* pointers = instr->pointer_map();
3156 SafepointGenerator generator(this, pointers, Safepoint::kLazyDeopt);
3157 ParameterCount count(instr->arity());
3158 __ InvokeFunction(x1, count, CALL_FUNCTION, generator);
3160 CallKnownFunction(known_function,
3161 instr->hydrogen()->formal_parameter_count(),
3162 instr->arity(), instr);
3164 RecordPushedArgumentsDelta(instr->hydrogen()->argument_delta());
3168 void LCodeGen::DoIsConstructCallAndBranch(LIsConstructCallAndBranch* instr) {
3169 Register temp1 = ToRegister(instr->temp1());
3170 Register temp2 = ToRegister(instr->temp2());
3172 // Get the frame pointer for the calling frame.
3173 __ Ldr(temp1, MemOperand(fp, StandardFrameConstants::kCallerFPOffset));
3175 // Skip the arguments adaptor frame if it exists.
3176 Label check_frame_marker;
3177 __ Ldr(temp2, MemOperand(temp1, StandardFrameConstants::kContextOffset));
3178 __ Cmp(temp2, Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR));
3179 __ B(ne, &check_frame_marker);
3180 __ Ldr(temp1, MemOperand(temp1, StandardFrameConstants::kCallerFPOffset));
3182 // Check the marker in the calling frame.
3183 __ Bind(&check_frame_marker);
3184 __ Ldr(temp1, MemOperand(temp1, StandardFrameConstants::kMarkerOffset));
3186 EmitCompareAndBranch(
3187 instr, eq, temp1, Operand(Smi::FromInt(StackFrame::CONSTRUCT)));
3191 void LCodeGen::DoIsObjectAndBranch(LIsObjectAndBranch* instr) {
3192 Label* is_object = instr->TrueLabel(chunk_);
3193 Label* is_not_object = instr->FalseLabel(chunk_);
3194 Register value = ToRegister(instr->value());
3195 Register map = ToRegister(instr->temp1());
3196 Register scratch = ToRegister(instr->temp2());
3198 __ JumpIfSmi(value, is_not_object);
3199 __ JumpIfRoot(value, Heap::kNullValueRootIndex, is_object);
3201 __ Ldr(map, FieldMemOperand(value, HeapObject::kMapOffset));
3203 // Check for undetectable objects.
3204 __ Ldrb(scratch, FieldMemOperand(map, Map::kBitFieldOffset));
3205 __ TestAndBranchIfAnySet(scratch, 1 << Map::kIsUndetectable, is_not_object);
3207 // Check that instance type is in object type range.
3208 __ IsInstanceJSObjectType(map, scratch, NULL);
3209 // Flags have been updated by IsInstanceJSObjectType. We can now test the
3210 // flags for "le" condition to check if the object's type is a valid
3212 EmitBranch(instr, le);
3216 Condition LCodeGen::EmitIsString(Register input,
3218 Label* is_not_string,
3219 SmiCheck check_needed = INLINE_SMI_CHECK) {
3220 if (check_needed == INLINE_SMI_CHECK) {
3221 __ JumpIfSmi(input, is_not_string);
3223 __ CompareObjectType(input, temp1, temp1, FIRST_NONSTRING_TYPE);
3229 void LCodeGen::DoIsStringAndBranch(LIsStringAndBranch* instr) {
3230 Register val = ToRegister(instr->value());
3231 Register scratch = ToRegister(instr->temp());
3233 SmiCheck check_needed =
3234 instr->hydrogen()->value()->type().IsHeapObject()
3235 ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
3236 Condition true_cond =
3237 EmitIsString(val, scratch, instr->FalseLabel(chunk_), check_needed);
3239 EmitBranch(instr, true_cond);
3243 void LCodeGen::DoIsSmiAndBranch(LIsSmiAndBranch* instr) {
3244 Register value = ToRegister(instr->value());
3245 STATIC_ASSERT(kSmiTag == 0);
3246 EmitTestAndBranch(instr, eq, value, kSmiTagMask);
3250 void LCodeGen::DoIsUndetectableAndBranch(LIsUndetectableAndBranch* instr) {
3251 Register input = ToRegister(instr->value());
3252 Register temp = ToRegister(instr->temp());
3254 if (!instr->hydrogen()->value()->type().IsHeapObject()) {
3255 __ JumpIfSmi(input, instr->FalseLabel(chunk_));
3257 __ Ldr(temp, FieldMemOperand(input, HeapObject::kMapOffset));
3258 __ Ldrb(temp, FieldMemOperand(temp, Map::kBitFieldOffset));
3260 EmitTestAndBranch(instr, ne, temp, 1 << Map::kIsUndetectable);
3264 static const char* LabelType(LLabel* label) {
3265 if (label->is_loop_header()) return " (loop header)";
3266 if (label->is_osr_entry()) return " (OSR entry)";
3271 void LCodeGen::DoLabel(LLabel* label) {
3272 Comment(";;; <@%d,#%d> -------------------- B%d%s --------------------",
3273 current_instruction_,
3274 label->hydrogen_value()->id(),
3278 // Inherit pushed_arguments_ from the predecessor's argument count.
3279 if (label->block()->HasPredecessor()) {
3280 pushed_arguments_ = label->block()->predecessors()->at(0)->argument_count();
3282 for (auto p : *label->block()->predecessors()) {
3283 DCHECK_EQ(p->argument_count(), pushed_arguments_);
3288 __ Bind(label->label());
3289 current_block_ = label->block_id();
3294 void LCodeGen::DoLoadContextSlot(LLoadContextSlot* instr) {
3295 Register context = ToRegister(instr->context());
3296 Register result = ToRegister(instr->result());
3297 __ Ldr(result, ContextMemOperand(context, instr->slot_index()));
3298 if (instr->hydrogen()->RequiresHoleCheck()) {
3299 if (instr->hydrogen()->DeoptimizesOnHole()) {
3300 DeoptimizeIfRoot(result, Heap::kTheHoleValueRootIndex, instr,
3301 Deoptimizer::kHole);
3304 __ JumpIfNotRoot(result, Heap::kTheHoleValueRootIndex, ¬_the_hole);
3305 __ LoadRoot(result, Heap::kUndefinedValueRootIndex);
3306 __ Bind(¬_the_hole);
3312 void LCodeGen::DoLoadFunctionPrototype(LLoadFunctionPrototype* instr) {
3313 Register function = ToRegister(instr->function());
3314 Register result = ToRegister(instr->result());
3315 Register temp = ToRegister(instr->temp());
3317 // Get the prototype or initial map from the function.
3318 __ Ldr(result, FieldMemOperand(function,
3319 JSFunction::kPrototypeOrInitialMapOffset));
3321 // Check that the function has a prototype or an initial map.
3322 DeoptimizeIfRoot(result, Heap::kTheHoleValueRootIndex, instr,
3323 Deoptimizer::kHole);
3325 // If the function does not have an initial map, we're done.
3327 __ CompareObjectType(result, temp, temp, MAP_TYPE);
3330 // Get the prototype from the initial map.
3331 __ Ldr(result, FieldMemOperand(result, Map::kPrototypeOffset));
3339 void LCodeGen::EmitVectorLoadICRegisters(T* instr) {
3340 Register vector_register = ToRegister(instr->temp_vector());
3341 Register slot_register = LoadWithVectorDescriptor::SlotRegister();
3342 DCHECK(vector_register.is(LoadWithVectorDescriptor::VectorRegister()));
3343 DCHECK(slot_register.is(x0));
3345 AllowDeferredHandleDereference vector_structure_check;
3346 Handle<TypeFeedbackVector> vector = instr->hydrogen()->feedback_vector();
3347 __ Mov(vector_register, vector);
3348 // No need to allocate this register.
3349 FeedbackVectorICSlot slot = instr->hydrogen()->slot();
3350 int index = vector->GetIndex(slot);
3351 __ Mov(slot_register, Smi::FromInt(index));
3356 void LCodeGen::EmitVectorStoreICRegisters(T* instr) {
3357 Register vector_register = ToRegister(instr->temp_vector());
3358 Register slot_register = ToRegister(instr->temp_slot());
3360 AllowDeferredHandleDereference vector_structure_check;
3361 Handle<TypeFeedbackVector> vector = instr->hydrogen()->feedback_vector();
3362 __ Mov(vector_register, vector);
3363 FeedbackVectorICSlot slot = instr->hydrogen()->slot();
3364 int index = vector->GetIndex(slot);
3365 __ Mov(slot_register, Smi::FromInt(index));
3369 void LCodeGen::DoLoadGlobalGeneric(LLoadGlobalGeneric* instr) {
3370 DCHECK(ToRegister(instr->context()).is(cp));
3371 DCHECK(ToRegister(instr->global_object())
3372 .is(LoadDescriptor::ReceiverRegister()));
3373 DCHECK(ToRegister(instr->result()).Is(x0));
3374 __ Mov(LoadDescriptor::NameRegister(), Operand(instr->name()));
3375 EmitVectorLoadICRegisters<LLoadGlobalGeneric>(instr);
3377 CodeFactory::LoadICInOptimizedCode(isolate(), instr->typeof_mode(),
3378 SLOPPY, PREMONOMORPHIC).code();
3379 CallCode(ic, RelocInfo::CODE_TARGET, instr);
3383 void LCodeGen::DoLoadGlobalViaContext(LLoadGlobalViaContext* instr) {
3384 DCHECK(ToRegister(instr->context()).is(cp));
3385 DCHECK(ToRegister(instr->result()).is(x0));
3387 int const slot = instr->slot_index();
3388 int const depth = instr->depth();
3389 if (depth <= LoadGlobalViaContextStub::kMaximumDepth) {
3390 __ Mov(LoadGlobalViaContextDescriptor::SlotRegister(), Operand(slot));
3392 CodeFactory::LoadGlobalViaContext(isolate(), depth).code();
3393 CallCode(stub, RelocInfo::CODE_TARGET, instr);
3395 __ Push(Smi::FromInt(slot));
3396 __ CallRuntime(Runtime::kLoadGlobalViaContext, 1);
3401 MemOperand LCodeGen::PrepareKeyedExternalArrayOperand(
3406 bool key_is_constant,
3408 ElementsKind elements_kind,
3410 int element_size_shift = ElementsKindToShiftSize(elements_kind);
3412 if (key_is_constant) {
3413 int key_offset = constant_key << element_size_shift;
3414 return MemOperand(base, key_offset + base_offset);
3418 __ Add(scratch, base, Operand::UntagSmiAndScale(key, element_size_shift));
3419 return MemOperand(scratch, base_offset);
3422 if (base_offset == 0) {
3423 return MemOperand(base, key, SXTW, element_size_shift);
3426 DCHECK(!AreAliased(scratch, key));
3427 __ Add(scratch, base, base_offset);
3428 return MemOperand(scratch, key, SXTW, element_size_shift);
3432 void LCodeGen::DoLoadKeyedExternal(LLoadKeyedExternal* instr) {
3433 Register ext_ptr = ToRegister(instr->elements());
3435 ElementsKind elements_kind = instr->elements_kind();
3437 bool key_is_smi = instr->hydrogen()->key()->representation().IsSmi();
3438 bool key_is_constant = instr->key()->IsConstantOperand();
3439 Register key = no_reg;
3440 int constant_key = 0;
3441 if (key_is_constant) {
3442 DCHECK(instr->temp() == NULL);
3443 constant_key = ToInteger32(LConstantOperand::cast(instr->key()));
3444 if (constant_key & 0xf0000000) {
3445 Abort(kArrayIndexConstantValueTooBig);
3448 scratch = ToRegister(instr->temp());
3449 key = ToRegister(instr->key());
3453 PrepareKeyedExternalArrayOperand(key, ext_ptr, scratch, key_is_smi,
3454 key_is_constant, constant_key,
3456 instr->base_offset());
3458 if ((elements_kind == EXTERNAL_FLOAT32_ELEMENTS) ||
3459 (elements_kind == FLOAT32_ELEMENTS)) {
3460 DoubleRegister result = ToDoubleRegister(instr->result());
3461 __ Ldr(result.S(), mem_op);
3462 __ Fcvt(result, result.S());
3463 } else if ((elements_kind == EXTERNAL_FLOAT64_ELEMENTS) ||
3464 (elements_kind == FLOAT64_ELEMENTS)) {
3465 DoubleRegister result = ToDoubleRegister(instr->result());
3466 __ Ldr(result, mem_op);
3468 Register result = ToRegister(instr->result());
3470 switch (elements_kind) {
3471 case EXTERNAL_INT8_ELEMENTS:
3473 __ Ldrsb(result, mem_op);
3475 case EXTERNAL_UINT8_CLAMPED_ELEMENTS:
3476 case EXTERNAL_UINT8_ELEMENTS:
3477 case UINT8_ELEMENTS:
3478 case UINT8_CLAMPED_ELEMENTS:
3479 __ Ldrb(result, mem_op);
3481 case EXTERNAL_INT16_ELEMENTS:
3482 case INT16_ELEMENTS:
3483 __ Ldrsh(result, mem_op);
3485 case EXTERNAL_UINT16_ELEMENTS:
3486 case UINT16_ELEMENTS:
3487 __ Ldrh(result, mem_op);
3489 case EXTERNAL_INT32_ELEMENTS:
3490 case INT32_ELEMENTS:
3491 __ Ldrsw(result, mem_op);
3493 case EXTERNAL_UINT32_ELEMENTS:
3494 case UINT32_ELEMENTS:
3495 __ Ldr(result.W(), mem_op);
3496 if (!instr->hydrogen()->CheckFlag(HInstruction::kUint32)) {
3497 // Deopt if value > 0x80000000.
3498 __ Tst(result, 0xFFFFFFFF80000000);
3499 DeoptimizeIf(ne, instr, Deoptimizer::kNegativeValue);
3502 case FLOAT32_ELEMENTS:
3503 case FLOAT64_ELEMENTS:
3504 case EXTERNAL_FLOAT32_ELEMENTS:
3505 case EXTERNAL_FLOAT64_ELEMENTS:
3506 case FAST_HOLEY_DOUBLE_ELEMENTS:
3507 case FAST_HOLEY_ELEMENTS:
3508 case FAST_HOLEY_SMI_ELEMENTS:
3509 case FAST_DOUBLE_ELEMENTS:
3511 case FAST_SMI_ELEMENTS:
3512 case DICTIONARY_ELEMENTS:
3513 case FAST_SLOPPY_ARGUMENTS_ELEMENTS:
3514 case SLOW_SLOPPY_ARGUMENTS_ELEMENTS:
3522 MemOperand LCodeGen::PrepareKeyedArrayOperand(Register base,
3526 ElementsKind elements_kind,
3527 Representation representation,
3529 STATIC_ASSERT(static_cast<unsigned>(kSmiValueSize) == kWRegSizeInBits);
3530 STATIC_ASSERT(kSmiTag == 0);
3531 int element_size_shift = ElementsKindToShiftSize(elements_kind);
3533 // Even though the HLoad/StoreKeyed instructions force the input
3534 // representation for the key to be an integer, the input gets replaced during
3535 // bounds check elimination with the index argument to the bounds check, which
3536 // can be tagged, so that case must be handled here, too.
3537 if (key_is_tagged) {
3538 __ Add(base, elements, Operand::UntagSmiAndScale(key, element_size_shift));
3539 if (representation.IsInteger32()) {
3540 DCHECK(elements_kind == FAST_SMI_ELEMENTS);
3541 // Read or write only the smi payload in the case of fast smi arrays.
3542 return UntagSmiMemOperand(base, base_offset);
3544 return MemOperand(base, base_offset);
3547 // Sign extend key because it could be a 32-bit negative value or contain
3548 // garbage in the top 32-bits. The address computation happens in 64-bit.
3549 DCHECK((element_size_shift >= 0) && (element_size_shift <= 4));
3550 if (representation.IsInteger32()) {
3551 DCHECK(elements_kind == FAST_SMI_ELEMENTS);
3552 // Read or write only the smi payload in the case of fast smi arrays.
3553 __ Add(base, elements, Operand(key, SXTW, element_size_shift));
3554 return UntagSmiMemOperand(base, base_offset);
3556 __ Add(base, elements, base_offset);
3557 return MemOperand(base, key, SXTW, element_size_shift);
3563 void LCodeGen::DoLoadKeyedFixedDouble(LLoadKeyedFixedDouble* instr) {
3564 Register elements = ToRegister(instr->elements());
3565 DoubleRegister result = ToDoubleRegister(instr->result());
3568 if (instr->key()->IsConstantOperand()) {
3569 DCHECK(instr->hydrogen()->RequiresHoleCheck() ||
3570 (instr->temp() == NULL));
3572 int constant_key = ToInteger32(LConstantOperand::cast(instr->key()));
3573 if (constant_key & 0xf0000000) {
3574 Abort(kArrayIndexConstantValueTooBig);
3576 int offset = instr->base_offset() + constant_key * kDoubleSize;
3577 mem_op = MemOperand(elements, offset);
3579 Register load_base = ToRegister(instr->temp());
3580 Register key = ToRegister(instr->key());
3581 bool key_is_tagged = instr->hydrogen()->key()->representation().IsSmi();
3582 mem_op = PrepareKeyedArrayOperand(load_base, elements, key, key_is_tagged,
3583 instr->hydrogen()->elements_kind(),
3584 instr->hydrogen()->representation(),
3585 instr->base_offset());
3588 __ Ldr(result, mem_op);
3590 if (instr->hydrogen()->RequiresHoleCheck()) {
3591 Register scratch = ToRegister(instr->temp());
3592 __ Fmov(scratch, result);
3593 __ Eor(scratch, scratch, kHoleNanInt64);
3594 DeoptimizeIfZero(scratch, instr, Deoptimizer::kHole);
3599 void LCodeGen::DoLoadKeyedFixed(LLoadKeyedFixed* instr) {
3600 Register elements = ToRegister(instr->elements());
3601 Register result = ToRegister(instr->result());
3604 Representation representation = instr->hydrogen()->representation();
3605 if (instr->key()->IsConstantOperand()) {
3606 DCHECK(instr->temp() == NULL);
3607 LConstantOperand* const_operand = LConstantOperand::cast(instr->key());
3608 int offset = instr->base_offset() +
3609 ToInteger32(const_operand) * kPointerSize;
3610 if (representation.IsInteger32()) {
3611 DCHECK(instr->hydrogen()->elements_kind() == FAST_SMI_ELEMENTS);
3612 STATIC_ASSERT(static_cast<unsigned>(kSmiValueSize) == kWRegSizeInBits);
3613 STATIC_ASSERT(kSmiTag == 0);
3614 mem_op = UntagSmiMemOperand(elements, offset);
3616 mem_op = MemOperand(elements, offset);
3619 Register load_base = ToRegister(instr->temp());
3620 Register key = ToRegister(instr->key());
3621 bool key_is_tagged = instr->hydrogen()->key()->representation().IsSmi();
3623 mem_op = PrepareKeyedArrayOperand(load_base, elements, key, key_is_tagged,
3624 instr->hydrogen()->elements_kind(),
3625 representation, instr->base_offset());
3628 __ Load(result, mem_op, representation);
3630 if (instr->hydrogen()->RequiresHoleCheck()) {
3631 if (IsFastSmiElementsKind(instr->hydrogen()->elements_kind())) {
3632 DeoptimizeIfNotSmi(result, instr, Deoptimizer::kNotASmi);
3634 DeoptimizeIfRoot(result, Heap::kTheHoleValueRootIndex, instr,
3635 Deoptimizer::kHole);
3637 } else if (instr->hydrogen()->hole_mode() == CONVERT_HOLE_TO_UNDEFINED) {
3638 DCHECK(instr->hydrogen()->elements_kind() == FAST_HOLEY_ELEMENTS);
3640 __ CompareRoot(result, Heap::kTheHoleValueRootIndex);
3642 if (info()->IsStub()) {
3643 // A stub can safely convert the hole to undefined only if the array
3644 // protector cell contains (Smi) Isolate::kArrayProtectorValid. Otherwise
3645 // it needs to bail out.
3646 __ LoadRoot(result, Heap::kArrayProtectorRootIndex);
3647 __ Ldr(result, FieldMemOperand(result, Cell::kValueOffset));
3648 __ Cmp(result, Operand(Smi::FromInt(Isolate::kArrayProtectorValid)));
3649 DeoptimizeIf(ne, instr, Deoptimizer::kHole);
3651 __ LoadRoot(result, Heap::kUndefinedValueRootIndex);
3657 void LCodeGen::DoLoadKeyedGeneric(LLoadKeyedGeneric* instr) {
3658 DCHECK(ToRegister(instr->context()).is(cp));
3659 DCHECK(ToRegister(instr->object()).is(LoadDescriptor::ReceiverRegister()));
3660 DCHECK(ToRegister(instr->key()).is(LoadDescriptor::NameRegister()));
3662 if (instr->hydrogen()->HasVectorAndSlot()) {
3663 EmitVectorLoadICRegisters<LLoadKeyedGeneric>(instr);
3666 Handle<Code> ic = CodeFactory::KeyedLoadICInOptimizedCode(
3667 isolate(), instr->hydrogen()->language_mode(),
3668 instr->hydrogen()->initialization_state()).code();
3669 CallCode(ic, RelocInfo::CODE_TARGET, instr);
3671 DCHECK(ToRegister(instr->result()).Is(x0));
3675 void LCodeGen::DoLoadNamedField(LLoadNamedField* instr) {
3676 HObjectAccess access = instr->hydrogen()->access();
3677 int offset = access.offset();
3678 Register object = ToRegister(instr->object());
3680 if (access.IsExternalMemory()) {
3681 Register result = ToRegister(instr->result());
3682 __ Load(result, MemOperand(object, offset), access.representation());
3686 if (instr->hydrogen()->representation().IsDouble()) {
3687 DCHECK(access.IsInobject());
3688 FPRegister result = ToDoubleRegister(instr->result());
3689 __ Ldr(result, FieldMemOperand(object, offset));
3693 Register result = ToRegister(instr->result());
3695 if (access.IsInobject()) {
3698 // Load the properties array, using result as a scratch register.
3699 __ Ldr(result, FieldMemOperand(object, JSObject::kPropertiesOffset));
3703 if (access.representation().IsSmi() &&
3704 instr->hydrogen()->representation().IsInteger32()) {
3705 // Read int value directly from upper half of the smi.
3706 STATIC_ASSERT(static_cast<unsigned>(kSmiValueSize) == kWRegSizeInBits);
3707 STATIC_ASSERT(kSmiTag == 0);
3708 __ Load(result, UntagSmiFieldMemOperand(source, offset),
3709 Representation::Integer32());
3711 __ Load(result, FieldMemOperand(source, offset), access.representation());
3716 void LCodeGen::DoLoadNamedGeneric(LLoadNamedGeneric* instr) {
3717 DCHECK(ToRegister(instr->context()).is(cp));
3718 // LoadIC expects name and receiver in registers.
3719 DCHECK(ToRegister(instr->object()).is(LoadDescriptor::ReceiverRegister()));
3720 __ Mov(LoadDescriptor::NameRegister(), Operand(instr->name()));
3721 EmitVectorLoadICRegisters<LLoadNamedGeneric>(instr);
3723 CodeFactory::LoadICInOptimizedCode(
3724 isolate(), NOT_INSIDE_TYPEOF, instr->hydrogen()->language_mode(),
3725 instr->hydrogen()->initialization_state()).code();
3726 CallCode(ic, RelocInfo::CODE_TARGET, instr);
3728 DCHECK(ToRegister(instr->result()).is(x0));
3732 void LCodeGen::DoLoadRoot(LLoadRoot* instr) {
3733 Register result = ToRegister(instr->result());
3734 __ LoadRoot(result, instr->index());
3738 void LCodeGen::DoMapEnumLength(LMapEnumLength* instr) {
3739 Register result = ToRegister(instr->result());
3740 Register map = ToRegister(instr->value());
3741 __ EnumLengthSmi(result, map);
3745 void LCodeGen::DoMathAbs(LMathAbs* instr) {
3746 Representation r = instr->hydrogen()->value()->representation();
3748 DoubleRegister input = ToDoubleRegister(instr->value());
3749 DoubleRegister result = ToDoubleRegister(instr->result());
3750 __ Fabs(result, input);
3751 } else if (r.IsSmi() || r.IsInteger32()) {
3752 Register input = r.IsSmi() ? ToRegister(instr->value())
3753 : ToRegister32(instr->value());
3754 Register result = r.IsSmi() ? ToRegister(instr->result())
3755 : ToRegister32(instr->result());
3756 __ Abs(result, input);
3757 DeoptimizeIf(vs, instr, Deoptimizer::kOverflow);
3762 void LCodeGen::DoDeferredMathAbsTagged(LMathAbsTagged* instr,
3764 Label* allocation_entry) {
3765 // Handle the tricky cases of MathAbsTagged:
3766 // - HeapNumber inputs.
3767 // - Negative inputs produce a positive result, so a new HeapNumber is
3768 // allocated to hold it.
3769 // - Positive inputs are returned as-is, since there is no need to allocate
3770 // a new HeapNumber for the result.
3771 // - The (smi) input -0x80000000, produces +0x80000000, which does not fit
3772 // a smi. In this case, the inline code sets the result and jumps directly
3773 // to the allocation_entry label.
3774 DCHECK(instr->context() != NULL);
3775 DCHECK(ToRegister(instr->context()).is(cp));
3776 Register input = ToRegister(instr->value());
3777 Register temp1 = ToRegister(instr->temp1());
3778 Register temp2 = ToRegister(instr->temp2());
3779 Register result_bits = ToRegister(instr->temp3());
3780 Register result = ToRegister(instr->result());
3782 Label runtime_allocation;
3784 // Deoptimize if the input is not a HeapNumber.
3785 DeoptimizeIfNotHeapNumber(input, instr);
3787 // If the argument is positive, we can return it as-is, without any need to
3788 // allocate a new HeapNumber for the result. We have to do this in integer
3789 // registers (rather than with fabs) because we need to be able to distinguish
3791 __ Ldr(result_bits, FieldMemOperand(input, HeapNumber::kValueOffset));
3792 __ Mov(result, input);
3793 __ Tbz(result_bits, kXSignBit, exit);
3795 // Calculate abs(input) by clearing the sign bit.
3796 __ Bic(result_bits, result_bits, kXSignMask);
3798 // Allocate a new HeapNumber to hold the result.
3799 // result_bits The bit representation of the (double) result.
3800 __ Bind(allocation_entry);
3801 __ AllocateHeapNumber(result, &runtime_allocation, temp1, temp2);
3802 // The inline (non-deferred) code will store result_bits into result.
3805 __ Bind(&runtime_allocation);
3806 if (FLAG_debug_code) {
3807 // Because result is in the pointer map, we need to make sure it has a valid
3808 // tagged value before we call the runtime. We speculatively set it to the
3809 // input (for abs(+x)) or to a smi (for abs(-SMI_MIN)), so it should already
3812 Register input = ToRegister(instr->value());
3813 __ JumpIfSmi(result, &result_ok);
3814 __ Cmp(input, result);
3815 __ Assert(eq, kUnexpectedValue);
3816 __ Bind(&result_ok);
3819 { PushSafepointRegistersScope scope(this);
3820 CallRuntimeFromDeferred(Runtime::kAllocateHeapNumber, 0, instr,
3822 __ StoreToSafepointRegisterSlot(x0, result);
3824 // The inline (non-deferred) code will store result_bits into result.
3828 void LCodeGen::DoMathAbsTagged(LMathAbsTagged* instr) {
3829 // Class for deferred case.
3830 class DeferredMathAbsTagged: public LDeferredCode {
3832 DeferredMathAbsTagged(LCodeGen* codegen, LMathAbsTagged* instr)
3833 : LDeferredCode(codegen), instr_(instr) { }
3834 virtual void Generate() {
3835 codegen()->DoDeferredMathAbsTagged(instr_, exit(),
3836 allocation_entry());
3838 virtual LInstruction* instr() { return instr_; }
3839 Label* allocation_entry() { return &allocation; }
3841 LMathAbsTagged* instr_;
3845 // TODO(jbramley): The early-exit mechanism would skip the new frame handling
3846 // in GenerateDeferredCode. Tidy this up.
3847 DCHECK(!NeedsDeferredFrame());
3849 DeferredMathAbsTagged* deferred =
3850 new(zone()) DeferredMathAbsTagged(this, instr);
3852 DCHECK(instr->hydrogen()->value()->representation().IsTagged() ||
3853 instr->hydrogen()->value()->representation().IsSmi());
3854 Register input = ToRegister(instr->value());
3855 Register result_bits = ToRegister(instr->temp3());
3856 Register result = ToRegister(instr->result());
3859 // Handle smis inline.
3860 // We can treat smis as 64-bit integers, since the (low-order) tag bits will
3861 // never get set by the negation. This is therefore the same as the Integer32
3862 // case in DoMathAbs, except that it operates on 64-bit values.
3863 STATIC_ASSERT((kSmiValueSize == 32) && (kSmiShift == 32) && (kSmiTag == 0));
3865 __ JumpIfNotSmi(input, deferred->entry());
3867 __ Abs(result, input, NULL, &done);
3869 // The result is the magnitude (abs) of the smallest value a smi can
3870 // represent, encoded as a double.
3871 __ Mov(result_bits, double_to_rawbits(0x80000000));
3872 __ B(deferred->allocation_entry());
3874 __ Bind(deferred->exit());
3875 __ Str(result_bits, FieldMemOperand(result, HeapNumber::kValueOffset));
3881 void LCodeGen::DoMathExp(LMathExp* instr) {
3882 DoubleRegister input = ToDoubleRegister(instr->value());
3883 DoubleRegister result = ToDoubleRegister(instr->result());
3884 DoubleRegister double_temp1 = ToDoubleRegister(instr->double_temp1());
3885 DoubleRegister double_temp2 = double_scratch();
3886 Register temp1 = ToRegister(instr->temp1());
3887 Register temp2 = ToRegister(instr->temp2());
3888 Register temp3 = ToRegister(instr->temp3());
3890 MathExpGenerator::EmitMathExp(masm(), input, result,
3891 double_temp1, double_temp2,
3892 temp1, temp2, temp3);
3896 void LCodeGen::DoMathFloorD(LMathFloorD* instr) {
3897 DoubleRegister input = ToDoubleRegister(instr->value());
3898 DoubleRegister result = ToDoubleRegister(instr->result());
3900 __ Frintm(result, input);
3904 void LCodeGen::DoMathFloorI(LMathFloorI* instr) {
3905 DoubleRegister input = ToDoubleRegister(instr->value());
3906 Register result = ToRegister(instr->result());
3908 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3909 DeoptimizeIfMinusZero(input, instr, Deoptimizer::kMinusZero);
3912 __ Fcvtms(result, input);
3914 // Check that the result fits into a 32-bit integer.
3915 // - The result did not overflow.
3916 __ Cmp(result, Operand(result, SXTW));
3917 // - The input was not NaN.
3918 __ Fccmp(input, input, NoFlag, eq);
3919 DeoptimizeIf(ne, instr, Deoptimizer::kLostPrecisionOrNaN);
3923 void LCodeGen::DoFlooringDivByPowerOf2I(LFlooringDivByPowerOf2I* instr) {
3924 Register dividend = ToRegister32(instr->dividend());
3925 Register result = ToRegister32(instr->result());
3926 int32_t divisor = instr->divisor();
3928 // If the divisor is 1, return the dividend.
3930 __ Mov(result, dividend, kDiscardForSameWReg);
3934 // If the divisor is positive, things are easy: There can be no deopts and we
3935 // can simply do an arithmetic right shift.
3936 int32_t shift = WhichPowerOf2Abs(divisor);
3938 __ Mov(result, Operand(dividend, ASR, shift));
3942 // If the divisor is negative, we have to negate and handle edge cases.
3943 __ Negs(result, dividend);
3944 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3945 DeoptimizeIf(eq, instr, Deoptimizer::kMinusZero);
3948 // Dividing by -1 is basically negation, unless we overflow.
3949 if (divisor == -1) {
3950 if (instr->hydrogen()->CheckFlag(HValue::kLeftCanBeMinInt)) {
3951 DeoptimizeIf(vs, instr, Deoptimizer::kOverflow);
3956 // If the negation could not overflow, simply shifting is OK.
3957 if (!instr->hydrogen()->CheckFlag(HValue::kLeftCanBeMinInt)) {
3958 __ Mov(result, Operand(dividend, ASR, shift));
3962 __ Asr(result, result, shift);
3963 __ Csel(result, result, kMinInt / divisor, vc);
3967 void LCodeGen::DoFlooringDivByConstI(LFlooringDivByConstI* instr) {
3968 Register dividend = ToRegister32(instr->dividend());
3969 int32_t divisor = instr->divisor();
3970 Register result = ToRegister32(instr->result());
3971 DCHECK(!AreAliased(dividend, result));
3974 Deoptimize(instr, Deoptimizer::kDivisionByZero);
3978 // Check for (0 / -x) that will produce negative zero.
3979 HMathFloorOfDiv* hdiv = instr->hydrogen();
3980 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
3981 DeoptimizeIfZero(dividend, instr, Deoptimizer::kMinusZero);
3984 // Easy case: We need no dynamic check for the dividend and the flooring
3985 // division is the same as the truncating division.
3986 if ((divisor > 0 && !hdiv->CheckFlag(HValue::kLeftCanBeNegative)) ||
3987 (divisor < 0 && !hdiv->CheckFlag(HValue::kLeftCanBePositive))) {
3988 __ TruncatingDiv(result, dividend, Abs(divisor));
3989 if (divisor < 0) __ Neg(result, result);
3993 // In the general case we may need to adjust before and after the truncating
3994 // division to get a flooring division.
3995 Register temp = ToRegister32(instr->temp());
3996 DCHECK(!AreAliased(temp, dividend, result));
3997 Label needs_adjustment, done;
3998 __ Cmp(dividend, 0);
3999 __ B(divisor > 0 ? lt : gt, &needs_adjustment);
4000 __ TruncatingDiv(result, dividend, Abs(divisor));
4001 if (divisor < 0) __ Neg(result, result);
4003 __ Bind(&needs_adjustment);
4004 __ Add(temp, dividend, Operand(divisor > 0 ? 1 : -1));
4005 __ TruncatingDiv(result, temp, Abs(divisor));
4006 if (divisor < 0) __ Neg(result, result);
4007 __ Sub(result, result, Operand(1));
4012 // TODO(svenpanne) Refactor this to avoid code duplication with DoDivI.
4013 void LCodeGen::DoFlooringDivI(LFlooringDivI* instr) {
4014 Register dividend = ToRegister32(instr->dividend());
4015 Register divisor = ToRegister32(instr->divisor());
4016 Register remainder = ToRegister32(instr->temp());
4017 Register result = ToRegister32(instr->result());
4019 // This can't cause an exception on ARM, so we can speculatively
4020 // execute it already now.
4021 __ Sdiv(result, dividend, divisor);
4024 DeoptimizeIfZero(divisor, instr, Deoptimizer::kDivisionByZero);
4026 // Check for (kMinInt / -1).
4027 if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
4028 // The V flag will be set iff dividend == kMinInt.
4029 __ Cmp(dividend, 1);
4030 __ Ccmp(divisor, -1, NoFlag, vs);
4031 DeoptimizeIf(eq, instr, Deoptimizer::kOverflow);
4034 // Check for (0 / -x) that will produce negative zero.
4035 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
4037 __ Ccmp(dividend, 0, ZFlag, mi);
4038 // "divisor" can't be null because the code would have already been
4039 // deoptimized. The Z flag is set only if (divisor < 0) and (dividend == 0).
4040 // In this case we need to deoptimize to produce a -0.
4041 DeoptimizeIf(eq, instr, Deoptimizer::kMinusZero);
4045 // If both operands have the same sign then we are done.
4046 __ Eor(remainder, dividend, divisor);
4047 __ Tbz(remainder, kWSignBit, &done);
4049 // Check if the result needs to be corrected.
4050 __ Msub(remainder, result, divisor, dividend);
4051 __ Cbz(remainder, &done);
4052 __ Sub(result, result, 1);
4058 void LCodeGen::DoMathLog(LMathLog* instr) {
4059 DCHECK(instr->IsMarkedAsCall());
4060 DCHECK(ToDoubleRegister(instr->value()).is(d0));
4061 __ CallCFunction(ExternalReference::math_log_double_function(isolate()),
4063 DCHECK(ToDoubleRegister(instr->result()).Is(d0));
4067 void LCodeGen::DoMathClz32(LMathClz32* instr) {
4068 Register input = ToRegister32(instr->value());
4069 Register result = ToRegister32(instr->result());
4070 __ Clz(result, input);
4074 void LCodeGen::DoMathPowHalf(LMathPowHalf* instr) {
4075 DoubleRegister input = ToDoubleRegister(instr->value());
4076 DoubleRegister result = ToDoubleRegister(instr->result());
4079 // Math.pow(x, 0.5) differs from fsqrt(x) in the following cases:
4080 // Math.pow(-Infinity, 0.5) == +Infinity
4081 // Math.pow(-0.0, 0.5) == +0.0
4083 // Catch -infinity inputs first.
4084 // TODO(jbramley): A constant infinity register would be helpful here.
4085 __ Fmov(double_scratch(), kFP64NegativeInfinity);
4086 __ Fcmp(double_scratch(), input);
4087 __ Fabs(result, input);
4090 // Add +0.0 to convert -0.0 to +0.0.
4091 __ Fadd(double_scratch(), input, fp_zero);
4092 __ Fsqrt(result, double_scratch());
4098 void LCodeGen::DoPower(LPower* instr) {
4099 Representation exponent_type = instr->hydrogen()->right()->representation();
4100 // Having marked this as a call, we can use any registers.
4101 // Just make sure that the input/output registers are the expected ones.
4102 Register tagged_exponent = MathPowTaggedDescriptor::exponent();
4103 Register integer_exponent = MathPowIntegerDescriptor::exponent();
4104 DCHECK(!instr->right()->IsDoubleRegister() ||
4105 ToDoubleRegister(instr->right()).is(d1));
4106 DCHECK(exponent_type.IsInteger32() || !instr->right()->IsRegister() ||
4107 ToRegister(instr->right()).is(tagged_exponent));
4108 DCHECK(!exponent_type.IsInteger32() ||
4109 ToRegister(instr->right()).is(integer_exponent));
4110 DCHECK(ToDoubleRegister(instr->left()).is(d0));
4111 DCHECK(ToDoubleRegister(instr->result()).is(d0));
4113 if (exponent_type.IsSmi()) {
4114 MathPowStub stub(isolate(), MathPowStub::TAGGED);
4116 } else if (exponent_type.IsTagged()) {
4118 __ JumpIfSmi(tagged_exponent, &no_deopt);
4119 DeoptimizeIfNotHeapNumber(tagged_exponent, instr);
4121 MathPowStub stub(isolate(), MathPowStub::TAGGED);
4123 } else if (exponent_type.IsInteger32()) {
4124 // Ensure integer exponent has no garbage in top 32-bits, as MathPowStub
4125 // supports large integer exponents.
4126 __ Sxtw(integer_exponent, integer_exponent);
4127 MathPowStub stub(isolate(), MathPowStub::INTEGER);
4130 DCHECK(exponent_type.IsDouble());
4131 MathPowStub stub(isolate(), MathPowStub::DOUBLE);
4137 void LCodeGen::DoMathRoundD(LMathRoundD* instr) {
4138 DoubleRegister input = ToDoubleRegister(instr->value());
4139 DoubleRegister result = ToDoubleRegister(instr->result());
4140 DoubleRegister scratch_d = double_scratch();
4142 DCHECK(!AreAliased(input, result, scratch_d));
4146 __ Frinta(result, input);
4147 __ Fcmp(input, 0.0);
4148 __ Fccmp(result, input, ZFlag, lt);
4149 // The result is correct if the input was in [-0, +infinity], or was a
4150 // negative integral value.
4153 // Here the input is negative, non integral, with an exponent lower than 52.
4154 // We do not have to worry about the 0.49999999999999994 (0x3fdfffffffffffff)
4155 // case. So we can safely add 0.5.
4156 __ Fmov(scratch_d, 0.5);
4157 __ Fadd(result, input, scratch_d);
4158 __ Frintm(result, result);
4159 // The range [-0.5, -0.0[ yielded +0.0. Force the sign to negative.
4160 __ Fabs(result, result);
4161 __ Fneg(result, result);
4167 void LCodeGen::DoMathRoundI(LMathRoundI* instr) {
4168 DoubleRegister input = ToDoubleRegister(instr->value());
4169 DoubleRegister temp = ToDoubleRegister(instr->temp1());
4170 DoubleRegister dot_five = double_scratch();
4171 Register result = ToRegister(instr->result());
4174 // Math.round() rounds to the nearest integer, with ties going towards
4175 // +infinity. This does not match any IEEE-754 rounding mode.
4176 // - Infinities and NaNs are propagated unchanged, but cause deopts because
4177 // they can't be represented as integers.
4178 // - The sign of the result is the same as the sign of the input. This means
4179 // that -0.0 rounds to itself, and values -0.5 <= input < 0 also produce a
4182 // Add 0.5 and round towards -infinity.
4183 __ Fmov(dot_five, 0.5);
4184 __ Fadd(temp, input, dot_five);
4185 __ Fcvtms(result, temp);
4187 // The result is correct if:
4188 // result is not 0, as the input could be NaN or [-0.5, -0.0].
4189 // result is not 1, as 0.499...94 will wrongly map to 1.
4190 // result fits in 32 bits.
4191 __ Cmp(result, Operand(result.W(), SXTW));
4192 __ Ccmp(result, 1, ZFlag, eq);
4195 // At this point, we have to handle possible inputs of NaN or numbers in the
4196 // range [-0.5, 1.5[, or numbers larger than 32 bits.
4198 // Deoptimize if the result > 1, as it must be larger than 32 bits.
4200 DeoptimizeIf(hi, instr, Deoptimizer::kOverflow);
4202 // Deoptimize for negative inputs, which at this point are only numbers in
4203 // the range [-0.5, -0.0]
4204 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
4205 __ Fmov(result, input);
4206 DeoptimizeIfNegative(result, instr, Deoptimizer::kMinusZero);
4209 // Deoptimize if the input was NaN.
4210 __ Fcmp(input, dot_five);
4211 DeoptimizeIf(vs, instr, Deoptimizer::kNaN);
4213 // Now, the only unhandled inputs are in the range [0.0, 1.5[ (or [-0.5, 1.5[
4214 // if we didn't generate a -0.0 bailout). If input >= 0.5 then return 1,
4215 // else 0; we avoid dealing with 0.499...94 directly.
4216 __ Cset(result, ge);
4221 void LCodeGen::DoMathFround(LMathFround* instr) {
4222 DoubleRegister input = ToDoubleRegister(instr->value());
4223 DoubleRegister result = ToDoubleRegister(instr->result());
4224 __ Fcvt(result.S(), input);
4225 __ Fcvt(result, result.S());
4229 void LCodeGen::DoMathSqrt(LMathSqrt* instr) {
4230 DoubleRegister input = ToDoubleRegister(instr->value());
4231 DoubleRegister result = ToDoubleRegister(instr->result());
4232 __ Fsqrt(result, input);
4236 void LCodeGen::DoMathMinMax(LMathMinMax* instr) {
4237 HMathMinMax::Operation op = instr->hydrogen()->operation();
4238 if (instr->hydrogen()->representation().IsInteger32()) {
4239 Register result = ToRegister32(instr->result());
4240 Register left = ToRegister32(instr->left());
4241 Operand right = ToOperand32(instr->right());
4243 __ Cmp(left, right);
4244 __ Csel(result, left, right, (op == HMathMinMax::kMathMax) ? ge : le);
4245 } else if (instr->hydrogen()->representation().IsSmi()) {
4246 Register result = ToRegister(instr->result());
4247 Register left = ToRegister(instr->left());
4248 Operand right = ToOperand(instr->right());
4250 __ Cmp(left, right);
4251 __ Csel(result, left, right, (op == HMathMinMax::kMathMax) ? ge : le);
4253 DCHECK(instr->hydrogen()->representation().IsDouble());
4254 DoubleRegister result = ToDoubleRegister(instr->result());
4255 DoubleRegister left = ToDoubleRegister(instr->left());
4256 DoubleRegister right = ToDoubleRegister(instr->right());
4258 if (op == HMathMinMax::kMathMax) {
4259 __ Fmax(result, left, right);
4261 DCHECK(op == HMathMinMax::kMathMin);
4262 __ Fmin(result, left, right);
4268 void LCodeGen::DoModByPowerOf2I(LModByPowerOf2I* instr) {
4269 Register dividend = ToRegister32(instr->dividend());
4270 int32_t divisor = instr->divisor();
4271 DCHECK(dividend.is(ToRegister32(instr->result())));
4273 // Theoretically, a variation of the branch-free code for integer division by
4274 // a power of 2 (calculating the remainder via an additional multiplication
4275 // (which gets simplified to an 'and') and subtraction) should be faster, and
4276 // this is exactly what GCC and clang emit. Nevertheless, benchmarks seem to
4277 // indicate that positive dividends are heavily favored, so the branching
4278 // version performs better.
4279 HMod* hmod = instr->hydrogen();
4280 int32_t mask = divisor < 0 ? -(divisor + 1) : (divisor - 1);
4281 Label dividend_is_not_negative, done;
4282 if (hmod->CheckFlag(HValue::kLeftCanBeNegative)) {
4283 __ Tbz(dividend, kWSignBit, ÷nd_is_not_negative);
4284 // Note that this is correct even for kMinInt operands.
4285 __ Neg(dividend, dividend);
4286 __ And(dividend, dividend, mask);
4287 __ Negs(dividend, dividend);
4288 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
4289 DeoptimizeIf(eq, instr, Deoptimizer::kMinusZero);
4294 __ bind(÷nd_is_not_negative);
4295 __ And(dividend, dividend, mask);
4300 void LCodeGen::DoModByConstI(LModByConstI* instr) {
4301 Register dividend = ToRegister32(instr->dividend());
4302 int32_t divisor = instr->divisor();
4303 Register result = ToRegister32(instr->result());
4304 Register temp = ToRegister32(instr->temp());
4305 DCHECK(!AreAliased(dividend, result, temp));
4308 Deoptimize(instr, Deoptimizer::kDivisionByZero);
4312 __ TruncatingDiv(result, dividend, Abs(divisor));
4313 __ Sxtw(dividend.X(), dividend);
4314 __ Mov(temp, Abs(divisor));
4315 __ Smsubl(result.X(), result, temp, dividend.X());
4317 // Check for negative zero.
4318 HMod* hmod = instr->hydrogen();
4319 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
4320 Label remainder_not_zero;
4321 __ Cbnz(result, &remainder_not_zero);
4322 DeoptimizeIfNegative(dividend, instr, Deoptimizer::kMinusZero);
4323 __ bind(&remainder_not_zero);
4328 void LCodeGen::DoModI(LModI* instr) {
4329 Register dividend = ToRegister32(instr->left());
4330 Register divisor = ToRegister32(instr->right());
4331 Register result = ToRegister32(instr->result());
4334 // modulo = dividend - quotient * divisor
4335 __ Sdiv(result, dividend, divisor);
4336 if (instr->hydrogen()->CheckFlag(HValue::kCanBeDivByZero)) {
4337 DeoptimizeIfZero(divisor, instr, Deoptimizer::kDivisionByZero);
4339 __ Msub(result, result, divisor, dividend);
4340 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
4341 __ Cbnz(result, &done);
4342 DeoptimizeIfNegative(dividend, instr, Deoptimizer::kMinusZero);
4348 void LCodeGen::DoMulConstIS(LMulConstIS* instr) {
4349 DCHECK(instr->hydrogen()->representation().IsSmiOrInteger32());
4350 bool is_smi = instr->hydrogen()->representation().IsSmi();
4352 is_smi ? ToRegister(instr->result()) : ToRegister32(instr->result());
4354 is_smi ? ToRegister(instr->left()) : ToRegister32(instr->left()) ;
4355 int32_t right = ToInteger32(instr->right());
4356 DCHECK((right > -kMaxInt) && (right < kMaxInt));
4358 bool can_overflow = instr->hydrogen()->CheckFlag(HValue::kCanOverflow);
4359 bool bailout_on_minus_zero =
4360 instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero);
4362 if (bailout_on_minus_zero) {
4364 // The result is -0 if right is negative and left is zero.
4365 DeoptimizeIfZero(left, instr, Deoptimizer::kMinusZero);
4366 } else if (right == 0) {
4367 // The result is -0 if the right is zero and the left is negative.
4368 DeoptimizeIfNegative(left, instr, Deoptimizer::kMinusZero);
4373 // Cases which can detect overflow.
4376 // Only 0x80000000 can overflow here.
4377 __ Negs(result, left);
4378 DeoptimizeIf(vs, instr, Deoptimizer::kOverflow);
4380 __ Neg(result, left);
4384 // This case can never overflow.
4388 // This case can never overflow.
4389 __ Mov(result, left, kDiscardForSameWReg);
4393 __ Adds(result, left, left);
4394 DeoptimizeIf(vs, instr, Deoptimizer::kOverflow);
4396 __ Add(result, left, left);
4401 // Multiplication by constant powers of two (and some related values)
4402 // can be done efficiently with shifted operands.
4403 int32_t right_abs = Abs(right);
4405 if (base::bits::IsPowerOfTwo32(right_abs)) {
4406 int right_log2 = WhichPowerOf2(right_abs);
4409 Register scratch = result;
4410 DCHECK(!AreAliased(scratch, left));
4411 __ Cls(scratch, left);
4412 __ Cmp(scratch, right_log2);
4413 DeoptimizeIf(lt, instr, Deoptimizer::kOverflow);
4417 // result = left << log2(right)
4418 __ Lsl(result, left, right_log2);
4420 // result = -left << log2(-right)
4422 __ Negs(result, Operand(left, LSL, right_log2));
4423 DeoptimizeIf(vs, instr, Deoptimizer::kOverflow);
4425 __ Neg(result, Operand(left, LSL, right_log2));
4432 // For the following cases, we could perform a conservative overflow check
4433 // with CLS as above. However the few cycles saved are likely not worth
4434 // the risk of deoptimizing more often than required.
4435 DCHECK(!can_overflow);
4438 if (base::bits::IsPowerOfTwo32(right - 1)) {
4439 // result = left + left << log2(right - 1)
4440 __ Add(result, left, Operand(left, LSL, WhichPowerOf2(right - 1)));
4441 } else if (base::bits::IsPowerOfTwo32(right + 1)) {
4442 // result = -left + left << log2(right + 1)
4443 __ Sub(result, left, Operand(left, LSL, WhichPowerOf2(right + 1)));
4444 __ Neg(result, result);
4449 if (base::bits::IsPowerOfTwo32(-right + 1)) {
4450 // result = left - left << log2(-right + 1)
4451 __ Sub(result, left, Operand(left, LSL, WhichPowerOf2(-right + 1)));
4452 } else if (base::bits::IsPowerOfTwo32(-right - 1)) {
4453 // result = -left - left << log2(-right - 1)
4454 __ Add(result, left, Operand(left, LSL, WhichPowerOf2(-right - 1)));
4455 __ Neg(result, result);
4464 void LCodeGen::DoMulI(LMulI* instr) {
4465 Register result = ToRegister32(instr->result());
4466 Register left = ToRegister32(instr->left());
4467 Register right = ToRegister32(instr->right());
4469 bool can_overflow = instr->hydrogen()->CheckFlag(HValue::kCanOverflow);
4470 bool bailout_on_minus_zero =
4471 instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero);
4473 if (bailout_on_minus_zero && !left.Is(right)) {
4474 // If one operand is zero and the other is negative, the result is -0.
4475 // - Set Z (eq) if either left or right, or both, are 0.
4477 __ Ccmp(right, 0, ZFlag, ne);
4478 // - If so (eq), set N (mi) if left + right is negative.
4479 // - Otherwise, clear N.
4480 __ Ccmn(left, right, NoFlag, eq);
4481 DeoptimizeIf(mi, instr, Deoptimizer::kMinusZero);
4485 __ Smull(result.X(), left, right);
4486 __ Cmp(result.X(), Operand(result, SXTW));
4487 DeoptimizeIf(ne, instr, Deoptimizer::kOverflow);
4489 __ Mul(result, left, right);
4494 void LCodeGen::DoMulS(LMulS* instr) {
4495 Register result = ToRegister(instr->result());
4496 Register left = ToRegister(instr->left());
4497 Register right = ToRegister(instr->right());
4499 bool can_overflow = instr->hydrogen()->CheckFlag(HValue::kCanOverflow);
4500 bool bailout_on_minus_zero =
4501 instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero);
4503 if (bailout_on_minus_zero && !left.Is(right)) {
4504 // If one operand is zero and the other is negative, the result is -0.
4505 // - Set Z (eq) if either left or right, or both, are 0.
4507 __ Ccmp(right, 0, ZFlag, ne);
4508 // - If so (eq), set N (mi) if left + right is negative.
4509 // - Otherwise, clear N.
4510 __ Ccmn(left, right, NoFlag, eq);
4511 DeoptimizeIf(mi, instr, Deoptimizer::kMinusZero);
4514 STATIC_ASSERT((kSmiShift == 32) && (kSmiTag == 0));
4516 __ Smulh(result, left, right);
4517 __ Cmp(result, Operand(result.W(), SXTW));
4519 DeoptimizeIf(ne, instr, Deoptimizer::kOverflow);
4521 if (AreAliased(result, left, right)) {
4522 // All three registers are the same: half untag the input and then
4523 // multiply, giving a tagged result.
4524 STATIC_ASSERT((kSmiShift % 2) == 0);
4525 __ Asr(result, left, kSmiShift / 2);
4526 __ Mul(result, result, result);
4527 } else if (result.Is(left) && !left.Is(right)) {
4528 // Registers result and left alias, right is distinct: untag left into
4529 // result, and then multiply by right, giving a tagged result.
4530 __ SmiUntag(result, left);
4531 __ Mul(result, result, right);
4533 DCHECK(!left.Is(result));
4534 // Registers result and right alias, left is distinct, or all registers
4535 // are distinct: untag right into result, and then multiply by left,
4536 // giving a tagged result.
4537 __ SmiUntag(result, right);
4538 __ Mul(result, left, result);
4544 void LCodeGen::DoDeferredNumberTagD(LNumberTagD* instr) {
4545 // TODO(3095996): Get rid of this. For now, we need to make the
4546 // result register contain a valid pointer because it is already
4547 // contained in the register pointer map.
4548 Register result = ToRegister(instr->result());
4551 PushSafepointRegistersScope scope(this);
4552 // NumberTagU and NumberTagD use the context from the frame, rather than
4553 // the environment's HContext or HInlinedContext value.
4554 // They only call Runtime::kAllocateHeapNumber.
4555 // The corresponding HChange instructions are added in a phase that does
4556 // not have easy access to the local context.
4557 __ Ldr(cp, MemOperand(fp, StandardFrameConstants::kContextOffset));
4558 __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
4559 RecordSafepointWithRegisters(
4560 instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
4561 __ StoreToSafepointRegisterSlot(x0, result);
4565 void LCodeGen::DoNumberTagD(LNumberTagD* instr) {
4566 class DeferredNumberTagD: public LDeferredCode {
4568 DeferredNumberTagD(LCodeGen* codegen, LNumberTagD* instr)
4569 : LDeferredCode(codegen), instr_(instr) { }
4570 virtual void Generate() { codegen()->DoDeferredNumberTagD(instr_); }
4571 virtual LInstruction* instr() { return instr_; }
4573 LNumberTagD* instr_;
4576 DoubleRegister input = ToDoubleRegister(instr->value());
4577 Register result = ToRegister(instr->result());
4578 Register temp1 = ToRegister(instr->temp1());
4579 Register temp2 = ToRegister(instr->temp2());
4581 DeferredNumberTagD* deferred = new(zone()) DeferredNumberTagD(this, instr);
4582 if (FLAG_inline_new) {
4583 __ AllocateHeapNumber(result, deferred->entry(), temp1, temp2);
4585 __ B(deferred->entry());
4588 __ Bind(deferred->exit());
4589 __ Str(input, FieldMemOperand(result, HeapNumber::kValueOffset));
4593 void LCodeGen::DoDeferredNumberTagU(LInstruction* instr,
4597 Label slow, convert_and_store;
4598 Register src = ToRegister32(value);
4599 Register dst = ToRegister(instr->result());
4600 Register scratch1 = ToRegister(temp1);
4602 if (FLAG_inline_new) {
4603 Register scratch2 = ToRegister(temp2);
4604 __ AllocateHeapNumber(dst, &slow, scratch1, scratch2);
4605 __ B(&convert_and_store);
4608 // Slow case: call the runtime system to do the number allocation.
4610 // TODO(3095996): Put a valid pointer value in the stack slot where the result
4611 // register is stored, as this register is in the pointer map, but contains an
4615 // Preserve the value of all registers.
4616 PushSafepointRegistersScope scope(this);
4618 // NumberTagU and NumberTagD use the context from the frame, rather than
4619 // the environment's HContext or HInlinedContext value.
4620 // They only call Runtime::kAllocateHeapNumber.
4621 // The corresponding HChange instructions are added in a phase that does
4622 // not have easy access to the local context.
4623 __ Ldr(cp, MemOperand(fp, StandardFrameConstants::kContextOffset));
4624 __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
4625 RecordSafepointWithRegisters(
4626 instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
4627 __ StoreToSafepointRegisterSlot(x0, dst);
4630 // Convert number to floating point and store in the newly allocated heap
4632 __ Bind(&convert_and_store);
4633 DoubleRegister dbl_scratch = double_scratch();
4634 __ Ucvtf(dbl_scratch, src);
4635 __ Str(dbl_scratch, FieldMemOperand(dst, HeapNumber::kValueOffset));
4639 void LCodeGen::DoNumberTagU(LNumberTagU* instr) {
4640 class DeferredNumberTagU: public LDeferredCode {
4642 DeferredNumberTagU(LCodeGen* codegen, LNumberTagU* instr)
4643 : LDeferredCode(codegen), instr_(instr) { }
4644 virtual void Generate() {
4645 codegen()->DoDeferredNumberTagU(instr_,
4650 virtual LInstruction* instr() { return instr_; }
4652 LNumberTagU* instr_;
4655 Register value = ToRegister32(instr->value());
4656 Register result = ToRegister(instr->result());
4658 DeferredNumberTagU* deferred = new(zone()) DeferredNumberTagU(this, instr);
4659 __ Cmp(value, Smi::kMaxValue);
4660 __ B(hi, deferred->entry());
4661 __ SmiTag(result, value.X());
4662 __ Bind(deferred->exit());
4666 void LCodeGen::DoNumberUntagD(LNumberUntagD* instr) {
4667 Register input = ToRegister(instr->value());
4668 Register scratch = ToRegister(instr->temp());
4669 DoubleRegister result = ToDoubleRegister(instr->result());
4670 bool can_convert_undefined_to_nan =
4671 instr->hydrogen()->can_convert_undefined_to_nan();
4673 Label done, load_smi;
4675 // Work out what untag mode we're working with.
4676 HValue* value = instr->hydrogen()->value();
4677 NumberUntagDMode mode = value->representation().IsSmi()
4678 ? NUMBER_CANDIDATE_IS_SMI : NUMBER_CANDIDATE_IS_ANY_TAGGED;
4680 if (mode == NUMBER_CANDIDATE_IS_ANY_TAGGED) {
4681 __ JumpIfSmi(input, &load_smi);
4683 Label convert_undefined;
4685 // Heap number map check.
4686 if (can_convert_undefined_to_nan) {
4687 __ JumpIfNotHeapNumber(input, &convert_undefined);
4689 DeoptimizeIfNotHeapNumber(input, instr);
4692 // Load heap number.
4693 __ Ldr(result, FieldMemOperand(input, HeapNumber::kValueOffset));
4694 if (instr->hydrogen()->deoptimize_on_minus_zero()) {
4695 DeoptimizeIfMinusZero(result, instr, Deoptimizer::kMinusZero);
4699 if (can_convert_undefined_to_nan) {
4700 __ Bind(&convert_undefined);
4701 DeoptimizeIfNotRoot(input, Heap::kUndefinedValueRootIndex, instr,
4702 Deoptimizer::kNotAHeapNumberUndefined);
4704 __ LoadRoot(scratch, Heap::kNanValueRootIndex);
4705 __ Ldr(result, FieldMemOperand(scratch, HeapNumber::kValueOffset));
4710 DCHECK(mode == NUMBER_CANDIDATE_IS_SMI);
4711 // Fall through to load_smi.
4714 // Smi to double register conversion.
4716 __ SmiUntagToDouble(result, input);
4722 void LCodeGen::DoOsrEntry(LOsrEntry* instr) {
4723 // This is a pseudo-instruction that ensures that the environment here is
4724 // properly registered for deoptimization and records the assembler's PC
4726 LEnvironment* environment = instr->environment();
4728 // If the environment were already registered, we would have no way of
4729 // backpatching it with the spill slot operands.
4730 DCHECK(!environment->HasBeenRegistered());
4731 RegisterEnvironmentForDeoptimization(environment, Safepoint::kNoLazyDeopt);
4733 GenerateOsrPrologue();
4737 void LCodeGen::DoParameter(LParameter* instr) {
4742 void LCodeGen::DoPreparePushArguments(LPreparePushArguments* instr) {
4743 __ PushPreamble(instr->argc(), kPointerSize);
4747 void LCodeGen::DoPushArguments(LPushArguments* instr) {
4748 MacroAssembler::PushPopQueue args(masm());
4750 for (int i = 0; i < instr->ArgumentCount(); ++i) {
4751 LOperand* arg = instr->argument(i);
4752 if (arg->IsDoubleRegister() || arg->IsDoubleStackSlot()) {
4753 Abort(kDoPushArgumentNotImplementedForDoubleType);
4756 args.Queue(ToRegister(arg));
4759 // The preamble was done by LPreparePushArguments.
4760 args.PushQueued(MacroAssembler::PushPopQueue::SKIP_PREAMBLE);
4762 RecordPushedArgumentsDelta(instr->ArgumentCount());
4766 void LCodeGen::DoReturn(LReturn* instr) {
4767 if (FLAG_trace && info()->IsOptimizing()) {
4768 // Push the return value on the stack as the parameter.
4769 // Runtime::TraceExit returns its parameter in x0. We're leaving the code
4770 // managed by the register allocator and tearing down the frame, it's
4771 // safe to write to the context register.
4773 __ Ldr(cp, MemOperand(fp, StandardFrameConstants::kContextOffset));
4774 __ CallRuntime(Runtime::kTraceExit, 1);
4777 if (info()->saves_caller_doubles()) {
4778 RestoreCallerDoubles();
4781 int no_frame_start = -1;
4782 if (NeedsEagerFrame()) {
4783 Register stack_pointer = masm()->StackPointer();
4784 __ Mov(stack_pointer, fp);
4785 no_frame_start = masm_->pc_offset();
4789 if (instr->has_constant_parameter_count()) {
4790 int parameter_count = ToInteger32(instr->constant_parameter_count());
4791 __ Drop(parameter_count + 1);
4793 DCHECK(info()->IsStub()); // Functions would need to drop one more value.
4794 Register parameter_count = ToRegister(instr->parameter_count());
4795 __ DropBySMI(parameter_count);
4799 if (no_frame_start != -1) {
4800 info_->AddNoFrameRange(no_frame_start, masm_->pc_offset());
4805 MemOperand LCodeGen::BuildSeqStringOperand(Register string,
4808 String::Encoding encoding) {
4809 if (index->IsConstantOperand()) {
4810 int offset = ToInteger32(LConstantOperand::cast(index));
4811 if (encoding == String::TWO_BYTE_ENCODING) {
4812 offset *= kUC16Size;
4814 STATIC_ASSERT(kCharSize == 1);
4815 return FieldMemOperand(string, SeqString::kHeaderSize + offset);
4818 __ Add(temp, string, SeqString::kHeaderSize - kHeapObjectTag);
4819 if (encoding == String::ONE_BYTE_ENCODING) {
4820 return MemOperand(temp, ToRegister32(index), SXTW);
4822 STATIC_ASSERT(kUC16Size == 2);
4823 return MemOperand(temp, ToRegister32(index), SXTW, 1);
4828 void LCodeGen::DoSeqStringGetChar(LSeqStringGetChar* instr) {
4829 String::Encoding encoding = instr->hydrogen()->encoding();
4830 Register string = ToRegister(instr->string());
4831 Register result = ToRegister(instr->result());
4832 Register temp = ToRegister(instr->temp());
4834 if (FLAG_debug_code) {
4835 // Even though this lithium instruction comes with a temp register, we
4836 // can't use it here because we want to use "AtStart" constraints on the
4837 // inputs and the debug code here needs a scratch register.
4838 UseScratchRegisterScope temps(masm());
4839 Register dbg_temp = temps.AcquireX();
4841 __ Ldr(dbg_temp, FieldMemOperand(string, HeapObject::kMapOffset));
4842 __ Ldrb(dbg_temp, FieldMemOperand(dbg_temp, Map::kInstanceTypeOffset));
4844 __ And(dbg_temp, dbg_temp,
4845 Operand(kStringRepresentationMask | kStringEncodingMask));
4846 static const uint32_t one_byte_seq_type = kSeqStringTag | kOneByteStringTag;
4847 static const uint32_t two_byte_seq_type = kSeqStringTag | kTwoByteStringTag;
4848 __ Cmp(dbg_temp, Operand(encoding == String::ONE_BYTE_ENCODING
4849 ? one_byte_seq_type : two_byte_seq_type));
4850 __ Check(eq, kUnexpectedStringType);
4853 MemOperand operand =
4854 BuildSeqStringOperand(string, temp, instr->index(), encoding);
4855 if (encoding == String::ONE_BYTE_ENCODING) {
4856 __ Ldrb(result, operand);
4858 __ Ldrh(result, operand);
4863 void LCodeGen::DoSeqStringSetChar(LSeqStringSetChar* instr) {
4864 String::Encoding encoding = instr->hydrogen()->encoding();
4865 Register string = ToRegister(instr->string());
4866 Register value = ToRegister(instr->value());
4867 Register temp = ToRegister(instr->temp());
4869 if (FLAG_debug_code) {
4870 DCHECK(ToRegister(instr->context()).is(cp));
4871 Register index = ToRegister(instr->index());
4872 static const uint32_t one_byte_seq_type = kSeqStringTag | kOneByteStringTag;
4873 static const uint32_t two_byte_seq_type = kSeqStringTag | kTwoByteStringTag;
4875 instr->hydrogen()->encoding() == String::ONE_BYTE_ENCODING
4876 ? one_byte_seq_type : two_byte_seq_type;
4877 __ EmitSeqStringSetCharCheck(string, index, kIndexIsInteger32, temp,
4880 MemOperand operand =
4881 BuildSeqStringOperand(string, temp, instr->index(), encoding);
4882 if (encoding == String::ONE_BYTE_ENCODING) {
4883 __ Strb(value, operand);
4885 __ Strh(value, operand);
4890 void LCodeGen::DoSmiTag(LSmiTag* instr) {
4891 HChange* hchange = instr->hydrogen();
4892 Register input = ToRegister(instr->value());
4893 Register output = ToRegister(instr->result());
4894 if (hchange->CheckFlag(HValue::kCanOverflow) &&
4895 hchange->value()->CheckFlag(HValue::kUint32)) {
4896 DeoptimizeIfNegative(input.W(), instr, Deoptimizer::kOverflow);
4898 __ SmiTag(output, input);
4902 void LCodeGen::DoSmiUntag(LSmiUntag* instr) {
4903 Register input = ToRegister(instr->value());
4904 Register result = ToRegister(instr->result());
4907 if (instr->needs_check()) {
4908 DeoptimizeIfNotSmi(input, instr, Deoptimizer::kNotASmi);
4912 __ SmiUntag(result, input);
4917 void LCodeGen::DoShiftI(LShiftI* instr) {
4918 LOperand* right_op = instr->right();
4919 Register left = ToRegister32(instr->left());
4920 Register result = ToRegister32(instr->result());
4922 if (right_op->IsRegister()) {
4923 Register right = ToRegister32(instr->right());
4924 switch (instr->op()) {
4925 case Token::ROR: __ Ror(result, left, right); break;
4926 case Token::SAR: __ Asr(result, left, right); break;
4927 case Token::SHL: __ Lsl(result, left, right); break;
4929 __ Lsr(result, left, right);
4930 if (instr->can_deopt()) {
4931 // If `left >>> right` >= 0x80000000, the result is not representable
4932 // in a signed 32-bit smi.
4933 DeoptimizeIfNegative(result, instr, Deoptimizer::kNegativeValue);
4936 default: UNREACHABLE();
4939 DCHECK(right_op->IsConstantOperand());
4940 int shift_count = JSShiftAmountFromLConstant(right_op);
4941 if (shift_count == 0) {
4942 if ((instr->op() == Token::SHR) && instr->can_deopt()) {
4943 DeoptimizeIfNegative(left, instr, Deoptimizer::kNegativeValue);
4945 __ Mov(result, left, kDiscardForSameWReg);
4947 switch (instr->op()) {
4948 case Token::ROR: __ Ror(result, left, shift_count); break;
4949 case Token::SAR: __ Asr(result, left, shift_count); break;
4950 case Token::SHL: __ Lsl(result, left, shift_count); break;
4951 case Token::SHR: __ Lsr(result, left, shift_count); break;
4952 default: UNREACHABLE();
4959 void LCodeGen::DoShiftS(LShiftS* instr) {
4960 LOperand* right_op = instr->right();
4961 Register left = ToRegister(instr->left());
4962 Register result = ToRegister(instr->result());
4964 if (right_op->IsRegister()) {
4965 Register right = ToRegister(instr->right());
4967 // JavaScript shifts only look at the bottom 5 bits of the 'right' operand.
4968 // Since we're handling smis in X registers, we have to extract these bits
4970 __ Ubfx(result, right, kSmiShift, 5);
4972 switch (instr->op()) {
4974 // This is the only case that needs a scratch register. To keep things
4975 // simple for the other cases, borrow a MacroAssembler scratch register.
4976 UseScratchRegisterScope temps(masm());
4977 Register temp = temps.AcquireW();
4978 __ SmiUntag(temp, left);
4979 __ Ror(result.W(), temp.W(), result.W());
4984 __ Asr(result, left, result);
4985 __ Bic(result, result, kSmiShiftMask);
4988 __ Lsl(result, left, result);
4991 __ Lsr(result, left, result);
4992 __ Bic(result, result, kSmiShiftMask);
4993 if (instr->can_deopt()) {
4994 // If `left >>> right` >= 0x80000000, the result is not representable
4995 // in a signed 32-bit smi.
4996 DeoptimizeIfNegative(result, instr, Deoptimizer::kNegativeValue);
4999 default: UNREACHABLE();
5002 DCHECK(right_op->IsConstantOperand());
5003 int shift_count = JSShiftAmountFromLConstant(right_op);
5004 if (shift_count == 0) {
5005 if ((instr->op() == Token::SHR) && instr->can_deopt()) {
5006 DeoptimizeIfNegative(left, instr, Deoptimizer::kNegativeValue);
5008 __ Mov(result, left);
5010 switch (instr->op()) {
5012 __ SmiUntag(result, left);
5013 __ Ror(result.W(), result.W(), shift_count);
5017 __ Asr(result, left, shift_count);
5018 __ Bic(result, result, kSmiShiftMask);
5021 __ Lsl(result, left, shift_count);
5024 __ Lsr(result, left, shift_count);
5025 __ Bic(result, result, kSmiShiftMask);
5027 default: UNREACHABLE();
5034 void LCodeGen::DoDebugBreak(LDebugBreak* instr) {
5035 __ Debug("LDebugBreak", 0, BREAK);
5039 void LCodeGen::DoDeclareGlobals(LDeclareGlobals* instr) {
5040 DCHECK(ToRegister(instr->context()).is(cp));
5041 Register scratch1 = x5;
5042 Register scratch2 = x6;
5043 DCHECK(instr->IsMarkedAsCall());
5045 // TODO(all): if Mov could handle object in new space then it could be used
5047 __ LoadHeapObject(scratch1, instr->hydrogen()->pairs());
5048 __ Mov(scratch2, Smi::FromInt(instr->hydrogen()->flags()));
5049 __ Push(cp, scratch1, scratch2); // The context is the first argument.
5050 CallRuntime(Runtime::kDeclareGlobals, 3, instr);
5054 void LCodeGen::DoDeferredStackCheck(LStackCheck* instr) {
5055 PushSafepointRegistersScope scope(this);
5056 LoadContextFromDeferred(instr->context());
5057 __ CallRuntimeSaveDoubles(Runtime::kStackGuard);
5058 RecordSafepointWithLazyDeopt(
5059 instr, RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
5060 DCHECK(instr->HasEnvironment());
5061 LEnvironment* env = instr->environment();
5062 safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
5066 void LCodeGen::DoStackCheck(LStackCheck* instr) {
5067 class DeferredStackCheck: public LDeferredCode {
5069 DeferredStackCheck(LCodeGen* codegen, LStackCheck* instr)
5070 : LDeferredCode(codegen), instr_(instr) { }
5071 virtual void Generate() { codegen()->DoDeferredStackCheck(instr_); }
5072 virtual LInstruction* instr() { return instr_; }
5074 LStackCheck* instr_;
5077 DCHECK(instr->HasEnvironment());
5078 LEnvironment* env = instr->environment();
5079 // There is no LLazyBailout instruction for stack-checks. We have to
5080 // prepare for lazy deoptimization explicitly here.
5081 if (instr->hydrogen()->is_function_entry()) {
5082 // Perform stack overflow check.
5084 __ CompareRoot(masm()->StackPointer(), Heap::kStackLimitRootIndex);
5087 PredictableCodeSizeScope predictable(masm_,
5088 Assembler::kCallSizeWithRelocation);
5089 DCHECK(instr->context()->IsRegister());
5090 DCHECK(ToRegister(instr->context()).is(cp));
5091 CallCode(isolate()->builtins()->StackCheck(),
5092 RelocInfo::CODE_TARGET,
5096 DCHECK(instr->hydrogen()->is_backwards_branch());
5097 // Perform stack overflow check if this goto needs it before jumping.
5098 DeferredStackCheck* deferred_stack_check =
5099 new(zone()) DeferredStackCheck(this, instr);
5100 __ CompareRoot(masm()->StackPointer(), Heap::kStackLimitRootIndex);
5101 __ B(lo, deferred_stack_check->entry());
5103 EnsureSpaceForLazyDeopt(Deoptimizer::patch_size());
5104 __ Bind(instr->done_label());
5105 deferred_stack_check->SetExit(instr->done_label());
5106 RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt);
5107 // Don't record a deoptimization index for the safepoint here.
5108 // This will be done explicitly when emitting call and the safepoint in
5109 // the deferred code.
5114 void LCodeGen::DoStoreCodeEntry(LStoreCodeEntry* instr) {
5115 Register function = ToRegister(instr->function());
5116 Register code_object = ToRegister(instr->code_object());
5117 Register temp = ToRegister(instr->temp());
5118 __ Add(temp, code_object, Code::kHeaderSize - kHeapObjectTag);
5119 __ Str(temp, FieldMemOperand(function, JSFunction::kCodeEntryOffset));
5123 void LCodeGen::DoStoreContextSlot(LStoreContextSlot* instr) {
5124 Register context = ToRegister(instr->context());
5125 Register value = ToRegister(instr->value());
5126 Register scratch = ToRegister(instr->temp());
5127 MemOperand target = ContextMemOperand(context, instr->slot_index());
5129 Label skip_assignment;
5131 if (instr->hydrogen()->RequiresHoleCheck()) {
5132 __ Ldr(scratch, target);
5133 if (instr->hydrogen()->DeoptimizesOnHole()) {
5134 DeoptimizeIfRoot(scratch, Heap::kTheHoleValueRootIndex, instr,
5135 Deoptimizer::kHole);
5137 __ JumpIfNotRoot(scratch, Heap::kTheHoleValueRootIndex, &skip_assignment);
5141 __ Str(value, target);
5142 if (instr->hydrogen()->NeedsWriteBarrier()) {
5143 SmiCheck check_needed =
5144 instr->hydrogen()->value()->type().IsHeapObject()
5145 ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
5146 __ RecordWriteContextSlot(context, static_cast<int>(target.offset()), value,
5147 scratch, GetLinkRegisterState(), kSaveFPRegs,
5148 EMIT_REMEMBERED_SET, check_needed);
5150 __ Bind(&skip_assignment);
5154 void LCodeGen::DoStoreKeyedExternal(LStoreKeyedExternal* instr) {
5155 Register ext_ptr = ToRegister(instr->elements());
5156 Register key = no_reg;
5158 ElementsKind elements_kind = instr->elements_kind();
5160 bool key_is_smi = instr->hydrogen()->key()->representation().IsSmi();
5161 bool key_is_constant = instr->key()->IsConstantOperand();
5162 int constant_key = 0;
5163 if (key_is_constant) {
5164 DCHECK(instr->temp() == NULL);
5165 constant_key = ToInteger32(LConstantOperand::cast(instr->key()));
5166 if (constant_key & 0xf0000000) {
5167 Abort(kArrayIndexConstantValueTooBig);
5170 key = ToRegister(instr->key());
5171 scratch = ToRegister(instr->temp());
5175 PrepareKeyedExternalArrayOperand(key, ext_ptr, scratch, key_is_smi,
5176 key_is_constant, constant_key,
5178 instr->base_offset());
5180 if ((elements_kind == EXTERNAL_FLOAT32_ELEMENTS) ||
5181 (elements_kind == FLOAT32_ELEMENTS)) {
5182 DoubleRegister value = ToDoubleRegister(instr->value());
5183 DoubleRegister dbl_scratch = double_scratch();
5184 __ Fcvt(dbl_scratch.S(), value);
5185 __ Str(dbl_scratch.S(), dst);
5186 } else if ((elements_kind == EXTERNAL_FLOAT64_ELEMENTS) ||
5187 (elements_kind == FLOAT64_ELEMENTS)) {
5188 DoubleRegister value = ToDoubleRegister(instr->value());
5191 Register value = ToRegister(instr->value());
5193 switch (elements_kind) {
5194 case EXTERNAL_UINT8_CLAMPED_ELEMENTS:
5195 case EXTERNAL_INT8_ELEMENTS:
5196 case EXTERNAL_UINT8_ELEMENTS:
5197 case UINT8_ELEMENTS:
5198 case UINT8_CLAMPED_ELEMENTS:
5200 __ Strb(value, dst);
5202 case EXTERNAL_INT16_ELEMENTS:
5203 case EXTERNAL_UINT16_ELEMENTS:
5204 case INT16_ELEMENTS:
5205 case UINT16_ELEMENTS:
5206 __ Strh(value, dst);
5208 case EXTERNAL_INT32_ELEMENTS:
5209 case EXTERNAL_UINT32_ELEMENTS:
5210 case INT32_ELEMENTS:
5211 case UINT32_ELEMENTS:
5212 __ Str(value.W(), dst);
5214 case FLOAT32_ELEMENTS:
5215 case FLOAT64_ELEMENTS:
5216 case EXTERNAL_FLOAT32_ELEMENTS:
5217 case EXTERNAL_FLOAT64_ELEMENTS:
5218 case FAST_DOUBLE_ELEMENTS:
5220 case FAST_SMI_ELEMENTS:
5221 case FAST_HOLEY_DOUBLE_ELEMENTS:
5222 case FAST_HOLEY_ELEMENTS:
5223 case FAST_HOLEY_SMI_ELEMENTS:
5224 case DICTIONARY_ELEMENTS:
5225 case FAST_SLOPPY_ARGUMENTS_ELEMENTS:
5226 case SLOW_SLOPPY_ARGUMENTS_ELEMENTS:
5234 void LCodeGen::DoStoreKeyedFixedDouble(LStoreKeyedFixedDouble* instr) {
5235 Register elements = ToRegister(instr->elements());
5236 DoubleRegister value = ToDoubleRegister(instr->value());
5239 if (instr->key()->IsConstantOperand()) {
5240 int constant_key = ToInteger32(LConstantOperand::cast(instr->key()));
5241 if (constant_key & 0xf0000000) {
5242 Abort(kArrayIndexConstantValueTooBig);
5244 int offset = instr->base_offset() + constant_key * kDoubleSize;
5245 mem_op = MemOperand(elements, offset);
5247 Register store_base = ToRegister(instr->temp());
5248 Register key = ToRegister(instr->key());
5249 bool key_is_tagged = instr->hydrogen()->key()->representation().IsSmi();
5250 mem_op = PrepareKeyedArrayOperand(store_base, elements, key, key_is_tagged,
5251 instr->hydrogen()->elements_kind(),
5252 instr->hydrogen()->representation(),
5253 instr->base_offset());
5256 if (instr->NeedsCanonicalization()) {
5257 __ CanonicalizeNaN(double_scratch(), value);
5258 __ Str(double_scratch(), mem_op);
5260 __ Str(value, mem_op);
5265 void LCodeGen::DoStoreKeyedFixed(LStoreKeyedFixed* instr) {
5266 Register value = ToRegister(instr->value());
5267 Register elements = ToRegister(instr->elements());
5268 Register scratch = no_reg;
5269 Register store_base = no_reg;
5270 Register key = no_reg;
5273 if (!instr->key()->IsConstantOperand() ||
5274 instr->hydrogen()->NeedsWriteBarrier()) {
5275 scratch = ToRegister(instr->temp());
5278 Representation representation = instr->hydrogen()->value()->representation();
5279 if (instr->key()->IsConstantOperand()) {
5280 LConstantOperand* const_operand = LConstantOperand::cast(instr->key());
5281 int offset = instr->base_offset() +
5282 ToInteger32(const_operand) * kPointerSize;
5283 store_base = elements;
5284 if (representation.IsInteger32()) {
5285 DCHECK(instr->hydrogen()->store_mode() == STORE_TO_INITIALIZED_ENTRY);
5286 DCHECK(instr->hydrogen()->elements_kind() == FAST_SMI_ELEMENTS);
5287 STATIC_ASSERT(static_cast<unsigned>(kSmiValueSize) == kWRegSizeInBits);
5288 STATIC_ASSERT(kSmiTag == 0);
5289 mem_op = UntagSmiMemOperand(store_base, offset);
5291 mem_op = MemOperand(store_base, offset);
5294 store_base = scratch;
5295 key = ToRegister(instr->key());
5296 bool key_is_tagged = instr->hydrogen()->key()->representation().IsSmi();
5298 mem_op = PrepareKeyedArrayOperand(store_base, elements, key, key_is_tagged,
5299 instr->hydrogen()->elements_kind(),
5300 representation, instr->base_offset());
5303 __ Store(value, mem_op, representation);
5305 if (instr->hydrogen()->NeedsWriteBarrier()) {
5306 DCHECK(representation.IsTagged());
5307 // This assignment may cause element_addr to alias store_base.
5308 Register element_addr = scratch;
5309 SmiCheck check_needed =
5310 instr->hydrogen()->value()->type().IsHeapObject()
5311 ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
5312 // Compute address of modified element and store it into key register.
5313 __ Add(element_addr, mem_op.base(), mem_op.OffsetAsOperand());
5314 __ RecordWrite(elements, element_addr, value, GetLinkRegisterState(),
5315 kSaveFPRegs, EMIT_REMEMBERED_SET, check_needed,
5316 instr->hydrogen()->PointersToHereCheckForValue());
5321 void LCodeGen::DoStoreKeyedGeneric(LStoreKeyedGeneric* instr) {
5322 DCHECK(ToRegister(instr->context()).is(cp));
5323 DCHECK(ToRegister(instr->object()).is(StoreDescriptor::ReceiverRegister()));
5324 DCHECK(ToRegister(instr->key()).is(StoreDescriptor::NameRegister()));
5325 DCHECK(ToRegister(instr->value()).is(StoreDescriptor::ValueRegister()));
5327 if (instr->hydrogen()->HasVectorAndSlot()) {
5328 EmitVectorStoreICRegisters<LStoreKeyedGeneric>(instr);
5331 Handle<Code> ic = CodeFactory::KeyedStoreICInOptimizedCode(
5332 isolate(), instr->language_mode(),
5333 instr->hydrogen()->initialization_state()).code();
5334 CallCode(ic, RelocInfo::CODE_TARGET, instr);
5338 void LCodeGen::DoMaybeGrowElements(LMaybeGrowElements* instr) {
5339 class DeferredMaybeGrowElements final : public LDeferredCode {
5341 DeferredMaybeGrowElements(LCodeGen* codegen, LMaybeGrowElements* instr)
5342 : LDeferredCode(codegen), instr_(instr) {}
5343 void Generate() override { codegen()->DoDeferredMaybeGrowElements(instr_); }
5344 LInstruction* instr() override { return instr_; }
5347 LMaybeGrowElements* instr_;
5350 Register result = x0;
5351 DeferredMaybeGrowElements* deferred =
5352 new (zone()) DeferredMaybeGrowElements(this, instr);
5353 LOperand* key = instr->key();
5354 LOperand* current_capacity = instr->current_capacity();
5356 DCHECK(instr->hydrogen()->key()->representation().IsInteger32());
5357 DCHECK(instr->hydrogen()->current_capacity()->representation().IsInteger32());
5358 DCHECK(key->IsConstantOperand() || key->IsRegister());
5359 DCHECK(current_capacity->IsConstantOperand() ||
5360 current_capacity->IsRegister());
5362 if (key->IsConstantOperand() && current_capacity->IsConstantOperand()) {
5363 int32_t constant_key = ToInteger32(LConstantOperand::cast(key));
5364 int32_t constant_capacity =
5365 ToInteger32(LConstantOperand::cast(current_capacity));
5366 if (constant_key >= constant_capacity) {
5368 __ B(deferred->entry());
5370 } else if (key->IsConstantOperand()) {
5371 int32_t constant_key = ToInteger32(LConstantOperand::cast(key));
5372 __ Cmp(ToRegister(current_capacity), Operand(constant_key));
5373 __ B(le, deferred->entry());
5374 } else if (current_capacity->IsConstantOperand()) {
5375 int32_t constant_capacity =
5376 ToInteger32(LConstantOperand::cast(current_capacity));
5377 __ Cmp(ToRegister(key), Operand(constant_capacity));
5378 __ B(ge, deferred->entry());
5380 __ Cmp(ToRegister(key), ToRegister(current_capacity));
5381 __ B(ge, deferred->entry());
5384 __ Mov(result, ToRegister(instr->elements()));
5386 __ Bind(deferred->exit());
5390 void LCodeGen::DoDeferredMaybeGrowElements(LMaybeGrowElements* instr) {
5391 // TODO(3095996): Get rid of this. For now, we need to make the
5392 // result register contain a valid pointer because it is already
5393 // contained in the register pointer map.
5394 Register result = x0;
5397 // We have to call a stub.
5399 PushSafepointRegistersScope scope(this);
5400 __ Move(result, ToRegister(instr->object()));
5402 LOperand* key = instr->key();
5403 if (key->IsConstantOperand()) {
5404 __ Mov(x3, Operand(ToSmi(LConstantOperand::cast(key))));
5406 __ Mov(x3, ToRegister(key));
5410 GrowArrayElementsStub stub(isolate(), instr->hydrogen()->is_js_array(),
5411 instr->hydrogen()->kind());
5413 RecordSafepointWithLazyDeopt(
5414 instr, RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
5415 __ StoreToSafepointRegisterSlot(result, result);
5418 // Deopt on smi, which means the elements array changed to dictionary mode.
5419 DeoptimizeIfSmi(result, instr, Deoptimizer::kSmi);
5423 void LCodeGen::DoStoreNamedField(LStoreNamedField* instr) {
5424 Representation representation = instr->representation();
5426 Register object = ToRegister(instr->object());
5427 HObjectAccess access = instr->hydrogen()->access();
5428 int offset = access.offset();
5430 if (access.IsExternalMemory()) {
5431 DCHECK(!instr->hydrogen()->has_transition());
5432 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
5433 Register value = ToRegister(instr->value());
5434 __ Store(value, MemOperand(object, offset), representation);
5438 __ AssertNotSmi(object);
5440 if (!FLAG_unbox_double_fields && representation.IsDouble()) {
5441 DCHECK(access.IsInobject());
5442 DCHECK(!instr->hydrogen()->has_transition());
5443 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
5444 FPRegister value = ToDoubleRegister(instr->value());
5445 __ Str(value, FieldMemOperand(object, offset));
5449 DCHECK(!representation.IsSmi() ||
5450 !instr->value()->IsConstantOperand() ||
5451 IsInteger32Constant(LConstantOperand::cast(instr->value())));
5453 if (instr->hydrogen()->has_transition()) {
5454 Handle<Map> transition = instr->hydrogen()->transition_map();
5455 AddDeprecationDependency(transition);
5456 // Store the new map value.
5457 Register new_map_value = ToRegister(instr->temp0());
5458 __ Mov(new_map_value, Operand(transition));
5459 __ Str(new_map_value, FieldMemOperand(object, HeapObject::kMapOffset));
5460 if (instr->hydrogen()->NeedsWriteBarrierForMap()) {
5461 // Update the write barrier for the map field.
5462 __ RecordWriteForMap(object,
5464 ToRegister(instr->temp1()),
5465 GetLinkRegisterState(),
5471 Register destination;
5472 if (access.IsInobject()) {
5473 destination = object;
5475 Register temp0 = ToRegister(instr->temp0());
5476 __ Ldr(temp0, FieldMemOperand(object, JSObject::kPropertiesOffset));
5477 destination = temp0;
5480 if (FLAG_unbox_double_fields && representation.IsDouble()) {
5481 DCHECK(access.IsInobject());
5482 FPRegister value = ToDoubleRegister(instr->value());
5483 __ Str(value, FieldMemOperand(object, offset));
5484 } else if (representation.IsSmi() &&
5485 instr->hydrogen()->value()->representation().IsInteger32()) {
5486 DCHECK(instr->hydrogen()->store_mode() == STORE_TO_INITIALIZED_ENTRY);
5488 Register temp0 = ToRegister(instr->temp0());
5489 __ Ldr(temp0, FieldMemOperand(destination, offset));
5490 __ AssertSmi(temp0);
5491 // If destination aliased temp0, restore it to the address calculated
5493 if (destination.Is(temp0)) {
5494 DCHECK(!access.IsInobject());
5495 __ Ldr(destination, FieldMemOperand(object, JSObject::kPropertiesOffset));
5498 STATIC_ASSERT(static_cast<unsigned>(kSmiValueSize) == kWRegSizeInBits);
5499 STATIC_ASSERT(kSmiTag == 0);
5500 Register value = ToRegister(instr->value());
5501 __ Store(value, UntagSmiFieldMemOperand(destination, offset),
5502 Representation::Integer32());
5504 Register value = ToRegister(instr->value());
5505 __ Store(value, FieldMemOperand(destination, offset), representation);
5507 if (instr->hydrogen()->NeedsWriteBarrier()) {
5508 Register value = ToRegister(instr->value());
5509 __ RecordWriteField(destination,
5511 value, // Clobbered.
5512 ToRegister(instr->temp1()), // Clobbered.
5513 GetLinkRegisterState(),
5515 EMIT_REMEMBERED_SET,
5516 instr->hydrogen()->SmiCheckForWriteBarrier(),
5517 instr->hydrogen()->PointersToHereCheckForValue());
5522 void LCodeGen::DoStoreNamedGeneric(LStoreNamedGeneric* instr) {
5523 DCHECK(ToRegister(instr->context()).is(cp));
5524 DCHECK(ToRegister(instr->object()).is(StoreDescriptor::ReceiverRegister()));
5525 DCHECK(ToRegister(instr->value()).is(StoreDescriptor::ValueRegister()));
5527 if (instr->hydrogen()->HasVectorAndSlot()) {
5528 EmitVectorStoreICRegisters<LStoreNamedGeneric>(instr);
5531 __ Mov(StoreDescriptor::NameRegister(), Operand(instr->name()));
5532 Handle<Code> ic = CodeFactory::StoreICInOptimizedCode(
5533 isolate(), instr->language_mode(),
5534 instr->hydrogen()->initialization_state()).code();
5535 CallCode(ic, RelocInfo::CODE_TARGET, instr);
5539 void LCodeGen::DoStoreGlobalViaContext(LStoreGlobalViaContext* instr) {
5540 DCHECK(ToRegister(instr->context()).is(cp));
5541 DCHECK(ToRegister(instr->value())
5542 .is(StoreGlobalViaContextDescriptor::ValueRegister()));
5544 int const slot = instr->slot_index();
5545 int const depth = instr->depth();
5546 if (depth <= StoreGlobalViaContextStub::kMaximumDepth) {
5547 __ Mov(StoreGlobalViaContextDescriptor::SlotRegister(), Operand(slot));
5548 Handle<Code> stub = CodeFactory::StoreGlobalViaContext(
5549 isolate(), depth, instr->language_mode())
5551 CallCode(stub, RelocInfo::CODE_TARGET, instr);
5553 __ Push(Smi::FromInt(slot));
5554 __ Push(StoreGlobalViaContextDescriptor::ValueRegister());
5555 __ CallRuntime(is_strict(instr->language_mode())
5556 ? Runtime::kStoreGlobalViaContext_Strict
5557 : Runtime::kStoreGlobalViaContext_Sloppy,
5563 void LCodeGen::DoStringAdd(LStringAdd* instr) {
5564 DCHECK(ToRegister(instr->context()).is(cp));
5565 DCHECK(ToRegister(instr->left()).Is(x1));
5566 DCHECK(ToRegister(instr->right()).Is(x0));
5567 StringAddStub stub(isolate(),
5568 instr->hydrogen()->flags(),
5569 instr->hydrogen()->pretenure_flag());
5570 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
5574 void LCodeGen::DoStringCharCodeAt(LStringCharCodeAt* instr) {
5575 class DeferredStringCharCodeAt: public LDeferredCode {
5577 DeferredStringCharCodeAt(LCodeGen* codegen, LStringCharCodeAt* instr)
5578 : LDeferredCode(codegen), instr_(instr) { }
5579 virtual void Generate() { codegen()->DoDeferredStringCharCodeAt(instr_); }
5580 virtual LInstruction* instr() { return instr_; }
5582 LStringCharCodeAt* instr_;
5585 DeferredStringCharCodeAt* deferred =
5586 new(zone()) DeferredStringCharCodeAt(this, instr);
5588 StringCharLoadGenerator::Generate(masm(),
5589 ToRegister(instr->string()),
5590 ToRegister32(instr->index()),
5591 ToRegister(instr->result()),
5593 __ Bind(deferred->exit());
5597 void LCodeGen::DoDeferredStringCharCodeAt(LStringCharCodeAt* instr) {
5598 Register string = ToRegister(instr->string());
5599 Register result = ToRegister(instr->result());
5601 // TODO(3095996): Get rid of this. For now, we need to make the
5602 // result register contain a valid pointer because it is already
5603 // contained in the register pointer map.
5606 PushSafepointRegistersScope scope(this);
5608 // Push the index as a smi. This is safe because of the checks in
5609 // DoStringCharCodeAt above.
5610 Register index = ToRegister(instr->index());
5611 __ SmiTagAndPush(index);
5613 CallRuntimeFromDeferred(Runtime::kStringCharCodeAtRT, 2, instr,
5617 __ StoreToSafepointRegisterSlot(x0, result);
5621 void LCodeGen::DoStringCharFromCode(LStringCharFromCode* instr) {
5622 class DeferredStringCharFromCode: public LDeferredCode {
5624 DeferredStringCharFromCode(LCodeGen* codegen, LStringCharFromCode* instr)
5625 : LDeferredCode(codegen), instr_(instr) { }
5626 virtual void Generate() { codegen()->DoDeferredStringCharFromCode(instr_); }
5627 virtual LInstruction* instr() { return instr_; }
5629 LStringCharFromCode* instr_;
5632 DeferredStringCharFromCode* deferred =
5633 new(zone()) DeferredStringCharFromCode(this, instr);
5635 DCHECK(instr->hydrogen()->value()->representation().IsInteger32());
5636 Register char_code = ToRegister32(instr->char_code());
5637 Register result = ToRegister(instr->result());
5639 __ Cmp(char_code, String::kMaxOneByteCharCode);
5640 __ B(hi, deferred->entry());
5641 __ LoadRoot(result, Heap::kSingleCharacterStringCacheRootIndex);
5642 __ Add(result, result, FixedArray::kHeaderSize - kHeapObjectTag);
5643 __ Ldr(result, MemOperand(result, char_code, SXTW, kPointerSizeLog2));
5644 __ CompareRoot(result, Heap::kUndefinedValueRootIndex);
5645 __ B(eq, deferred->entry());
5646 __ Bind(deferred->exit());
5650 void LCodeGen::DoDeferredStringCharFromCode(LStringCharFromCode* instr) {
5651 Register char_code = ToRegister(instr->char_code());
5652 Register result = ToRegister(instr->result());
5654 // TODO(3095996): Get rid of this. For now, we need to make the
5655 // result register contain a valid pointer because it is already
5656 // contained in the register pointer map.
5659 PushSafepointRegistersScope scope(this);
5660 __ SmiTagAndPush(char_code);
5661 CallRuntimeFromDeferred(Runtime::kCharFromCode, 1, instr, instr->context());
5662 __ StoreToSafepointRegisterSlot(x0, result);
5666 void LCodeGen::DoStringCompareAndBranch(LStringCompareAndBranch* instr) {
5667 DCHECK(ToRegister(instr->context()).is(cp));
5668 Token::Value op = instr->op();
5671 CodeFactory::CompareIC(isolate(), op, Strength::WEAK).code();
5672 CallCode(ic, RelocInfo::CODE_TARGET, instr);
5673 InlineSmiCheckInfo::EmitNotInlined(masm());
5675 Condition condition = TokenToCondition(op, false);
5677 EmitCompareAndBranch(instr, condition, x0, 0);
5681 void LCodeGen::DoSubI(LSubI* instr) {
5682 bool can_overflow = instr->hydrogen()->CheckFlag(HValue::kCanOverflow);
5683 Register result = ToRegister32(instr->result());
5684 Register left = ToRegister32(instr->left());
5685 Operand right = ToShiftedRightOperand32(instr->right(), instr);
5688 __ Subs(result, left, right);
5689 DeoptimizeIf(vs, instr, Deoptimizer::kOverflow);
5691 __ Sub(result, left, right);
5696 void LCodeGen::DoSubS(LSubS* instr) {
5697 bool can_overflow = instr->hydrogen()->CheckFlag(HValue::kCanOverflow);
5698 Register result = ToRegister(instr->result());
5699 Register left = ToRegister(instr->left());
5700 Operand right = ToOperand(instr->right());
5702 __ Subs(result, left, right);
5703 DeoptimizeIf(vs, instr, Deoptimizer::kOverflow);
5705 __ Sub(result, left, right);
5710 void LCodeGen::DoDeferredTaggedToI(LTaggedToI* instr,
5714 Register input = ToRegister(value);
5715 Register scratch1 = ToRegister(temp1);
5716 DoubleRegister dbl_scratch1 = double_scratch();
5720 if (instr->truncating()) {
5721 Register output = ToRegister(instr->result());
5724 // If it's not a heap number, jump to undefined check.
5725 __ JumpIfNotHeapNumber(input, &check_bools);
5727 // A heap number: load value and convert to int32 using truncating function.
5728 __ TruncateHeapNumberToI(output, input);
5731 __ Bind(&check_bools);
5733 Register true_root = output;
5734 Register false_root = scratch1;
5735 __ LoadTrueFalseRoots(true_root, false_root);
5736 __ Cmp(input, true_root);
5737 __ Cset(output, eq);
5738 __ Ccmp(input, false_root, ZFlag, ne);
5741 // Output contains zero, undefined is converted to zero for truncating
5743 DeoptimizeIfNotRoot(input, Heap::kUndefinedValueRootIndex, instr,
5744 Deoptimizer::kNotAHeapNumberUndefinedBoolean);
5746 Register output = ToRegister32(instr->result());
5747 DoubleRegister dbl_scratch2 = ToDoubleRegister(temp2);
5749 DeoptimizeIfNotHeapNumber(input, instr);
5751 // A heap number: load value and convert to int32 using non-truncating
5752 // function. If the result is out of range, branch to deoptimize.
5753 __ Ldr(dbl_scratch1, FieldMemOperand(input, HeapNumber::kValueOffset));
5754 __ TryRepresentDoubleAsInt32(output, dbl_scratch1, dbl_scratch2);
5755 DeoptimizeIf(ne, instr, Deoptimizer::kLostPrecisionOrNaN);
5757 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
5760 __ Fmov(scratch1, dbl_scratch1);
5761 DeoptimizeIfNegative(scratch1, instr, Deoptimizer::kMinusZero);
5768 void LCodeGen::DoTaggedToI(LTaggedToI* instr) {
5769 class DeferredTaggedToI: public LDeferredCode {
5771 DeferredTaggedToI(LCodeGen* codegen, LTaggedToI* instr)
5772 : LDeferredCode(codegen), instr_(instr) { }
5773 virtual void Generate() {
5774 codegen()->DoDeferredTaggedToI(instr_, instr_->value(), instr_->temp1(),
5778 virtual LInstruction* instr() { return instr_; }
5783 Register input = ToRegister(instr->value());
5784 Register output = ToRegister(instr->result());
5786 if (instr->hydrogen()->value()->representation().IsSmi()) {
5787 __ SmiUntag(output, input);
5789 DeferredTaggedToI* deferred = new(zone()) DeferredTaggedToI(this, instr);
5791 __ JumpIfNotSmi(input, deferred->entry());
5792 __ SmiUntag(output, input);
5793 __ Bind(deferred->exit());
5798 void LCodeGen::DoThisFunction(LThisFunction* instr) {
5799 Register result = ToRegister(instr->result());
5800 __ Ldr(result, MemOperand(fp, JavaScriptFrameConstants::kFunctionOffset));
5804 void LCodeGen::DoToFastProperties(LToFastProperties* instr) {
5805 DCHECK(ToRegister(instr->value()).Is(x0));
5806 DCHECK(ToRegister(instr->result()).Is(x0));
5808 CallRuntime(Runtime::kToFastProperties, 1, instr);
5812 void LCodeGen::DoRegExpLiteral(LRegExpLiteral* instr) {
5813 DCHECK(ToRegister(instr->context()).is(cp));
5815 // Registers will be used as follows:
5816 // x7 = literals array.
5817 // x1 = regexp literal.
5818 // x0 = regexp literal clone.
5819 // x10-x12 are used as temporaries.
5820 int literal_offset =
5821 FixedArray::OffsetOfElementAt(instr->hydrogen()->literal_index());
5822 __ LoadObject(x7, instr->hydrogen()->literals());
5823 __ Ldr(x1, FieldMemOperand(x7, literal_offset));
5824 __ JumpIfNotRoot(x1, Heap::kUndefinedValueRootIndex, &materialized);
5826 // Create regexp literal using runtime function
5827 // Result will be in x0.
5828 __ Mov(x12, Operand(Smi::FromInt(instr->hydrogen()->literal_index())));
5829 __ Mov(x11, Operand(instr->hydrogen()->pattern()));
5830 __ Mov(x10, Operand(instr->hydrogen()->flags()));
5831 __ Push(x7, x12, x11, x10);
5832 CallRuntime(Runtime::kMaterializeRegExpLiteral, 4, instr);
5835 __ Bind(&materialized);
5836 int size = JSRegExp::kSize + JSRegExp::kInObjectFieldCount * kPointerSize;
5837 Label allocated, runtime_allocate;
5839 __ Allocate(size, x0, x10, x11, &runtime_allocate, TAG_OBJECT);
5842 __ Bind(&runtime_allocate);
5843 __ Mov(x0, Smi::FromInt(size));
5845 CallRuntime(Runtime::kAllocateInNewSpace, 1, instr);
5848 __ Bind(&allocated);
5849 // Copy the content into the newly allocated memory.
5850 __ CopyFields(x0, x1, CPURegList(x10, x11, x12), size / kPointerSize);
5854 void LCodeGen::DoTransitionElementsKind(LTransitionElementsKind* instr) {
5855 Register object = ToRegister(instr->object());
5857 Handle<Map> from_map = instr->original_map();
5858 Handle<Map> to_map = instr->transitioned_map();
5859 ElementsKind from_kind = instr->from_kind();
5860 ElementsKind to_kind = instr->to_kind();
5862 Label not_applicable;
5864 if (IsSimpleMapChangeTransition(from_kind, to_kind)) {
5865 Register temp1 = ToRegister(instr->temp1());
5866 Register new_map = ToRegister(instr->temp2());
5867 __ CheckMap(object, temp1, from_map, ¬_applicable, DONT_DO_SMI_CHECK);
5868 __ Mov(new_map, Operand(to_map));
5869 __ Str(new_map, FieldMemOperand(object, HeapObject::kMapOffset));
5871 __ RecordWriteForMap(object, new_map, temp1, GetLinkRegisterState(),
5875 UseScratchRegisterScope temps(masm());
5876 // Use the temp register only in a restricted scope - the codegen checks
5877 // that we do not use any register across a call.
5878 __ CheckMap(object, temps.AcquireX(), from_map, ¬_applicable,
5881 DCHECK(object.is(x0));
5882 DCHECK(ToRegister(instr->context()).is(cp));
5883 PushSafepointRegistersScope scope(this);
5884 __ Mov(x1, Operand(to_map));
5885 bool is_js_array = from_map->instance_type() == JS_ARRAY_TYPE;
5886 TransitionElementsKindStub stub(isolate(), from_kind, to_kind, is_js_array);
5888 RecordSafepointWithRegisters(
5889 instr->pointer_map(), 0, Safepoint::kLazyDeopt);
5891 __ Bind(¬_applicable);
5895 void LCodeGen::DoTrapAllocationMemento(LTrapAllocationMemento* instr) {
5896 Register object = ToRegister(instr->object());
5897 Register temp1 = ToRegister(instr->temp1());
5898 Register temp2 = ToRegister(instr->temp2());
5900 Label no_memento_found;
5901 __ TestJSArrayForAllocationMemento(object, temp1, temp2, &no_memento_found);
5902 DeoptimizeIf(eq, instr, Deoptimizer::kMementoFound);
5903 __ Bind(&no_memento_found);
5907 void LCodeGen::DoTruncateDoubleToIntOrSmi(LTruncateDoubleToIntOrSmi* instr) {
5908 DoubleRegister input = ToDoubleRegister(instr->value());
5909 Register result = ToRegister(instr->result());
5910 __ TruncateDoubleToI(result, input);
5911 if (instr->tag_result()) {
5912 __ SmiTag(result, result);
5917 void LCodeGen::DoTypeof(LTypeof* instr) {
5918 DCHECK(ToRegister(instr->value()).is(x3));
5919 DCHECK(ToRegister(instr->result()).is(x0));
5921 Register value_register = ToRegister(instr->value());
5922 __ JumpIfNotSmi(value_register, &do_call);
5923 __ Mov(x0, Immediate(isolate()->factory()->number_string()));
5926 TypeofStub stub(isolate());
5927 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
5932 void LCodeGen::DoTypeofIsAndBranch(LTypeofIsAndBranch* instr) {
5933 Handle<String> type_name = instr->type_literal();
5934 Label* true_label = instr->TrueLabel(chunk_);
5935 Label* false_label = instr->FalseLabel(chunk_);
5936 Register value = ToRegister(instr->value());
5938 Factory* factory = isolate()->factory();
5939 if (String::Equals(type_name, factory->number_string())) {
5940 __ JumpIfSmi(value, true_label);
5942 int true_block = instr->TrueDestination(chunk_);
5943 int false_block = instr->FalseDestination(chunk_);
5944 int next_block = GetNextEmittedBlock();
5946 if (true_block == false_block) {
5947 EmitGoto(true_block);
5948 } else if (true_block == next_block) {
5949 __ JumpIfNotHeapNumber(value, chunk_->GetAssemblyLabel(false_block));
5951 __ JumpIfHeapNumber(value, chunk_->GetAssemblyLabel(true_block));
5952 if (false_block != next_block) {
5953 __ B(chunk_->GetAssemblyLabel(false_block));
5957 } else if (String::Equals(type_name, factory->string_string())) {
5958 DCHECK((instr->temp1() != NULL) && (instr->temp2() != NULL));
5959 Register map = ToRegister(instr->temp1());
5960 Register scratch = ToRegister(instr->temp2());
5962 __ JumpIfSmi(value, false_label);
5963 __ JumpIfObjectType(
5964 value, map, scratch, FIRST_NONSTRING_TYPE, false_label, ge);
5965 __ Ldrb(scratch, FieldMemOperand(map, Map::kBitFieldOffset));
5966 EmitTestAndBranch(instr, eq, scratch, 1 << Map::kIsUndetectable);
5968 } else if (String::Equals(type_name, factory->symbol_string())) {
5969 DCHECK((instr->temp1() != NULL) && (instr->temp2() != NULL));
5970 Register map = ToRegister(instr->temp1());
5971 Register scratch = ToRegister(instr->temp2());
5973 __ JumpIfSmi(value, false_label);
5974 __ CompareObjectType(value, map, scratch, SYMBOL_TYPE);
5975 EmitBranch(instr, eq);
5977 } else if (String::Equals(type_name, factory->boolean_string())) {
5978 __ JumpIfRoot(value, Heap::kTrueValueRootIndex, true_label);
5979 __ CompareRoot(value, Heap::kFalseValueRootIndex);
5980 EmitBranch(instr, eq);
5982 } else if (String::Equals(type_name, factory->undefined_string())) {
5983 DCHECK(instr->temp1() != NULL);
5984 Register scratch = ToRegister(instr->temp1());
5986 __ JumpIfRoot(value, Heap::kUndefinedValueRootIndex, true_label);
5987 __ JumpIfSmi(value, false_label);
5988 // Check for undetectable objects and jump to the true branch in this case.
5989 __ Ldr(scratch, FieldMemOperand(value, HeapObject::kMapOffset));
5990 __ Ldrb(scratch, FieldMemOperand(scratch, Map::kBitFieldOffset));
5991 EmitTestAndBranch(instr, ne, scratch, 1 << Map::kIsUndetectable);
5993 } else if (String::Equals(type_name, factory->function_string())) {
5994 STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
5995 DCHECK(instr->temp1() != NULL);
5996 Register type = ToRegister(instr->temp1());
5998 __ JumpIfSmi(value, false_label);
5999 __ JumpIfObjectType(value, type, type, JS_FUNCTION_TYPE, true_label);
6000 // HeapObject's type has been loaded into type register by JumpIfObjectType.
6001 EmitCompareAndBranch(instr, eq, type, JS_FUNCTION_PROXY_TYPE);
6003 } else if (String::Equals(type_name, factory->object_string())) {
6004 DCHECK((instr->temp1() != NULL) && (instr->temp2() != NULL));
6005 Register map = ToRegister(instr->temp1());
6006 Register scratch = ToRegister(instr->temp2());
6008 __ JumpIfSmi(value, false_label);
6009 __ JumpIfRoot(value, Heap::kNullValueRootIndex, true_label);
6010 __ JumpIfObjectType(value, map, scratch,
6011 FIRST_NONCALLABLE_SPEC_OBJECT_TYPE, false_label, lt);
6012 __ CompareInstanceType(map, scratch, LAST_NONCALLABLE_SPEC_OBJECT_TYPE);
6013 __ B(gt, false_label);
6014 // Check for undetectable objects => false.
6015 __ Ldrb(scratch, FieldMemOperand(map, Map::kBitFieldOffset));
6016 EmitTestAndBranch(instr, eq, scratch, 1 << Map::kIsUndetectable);
6018 } else if (String::Equals(type_name, factory->float32x4_string())) {
6019 DCHECK((instr->temp1() != NULL) && (instr->temp2() != NULL));
6020 Register map = ToRegister(instr->temp1());
6021 Register scratch = ToRegister(instr->temp2());
6023 __ JumpIfSmi(value, false_label);
6024 __ CompareObjectType(value, map, scratch, FLOAT32X4_TYPE);
6025 EmitBranch(instr, eq);
6033 void LCodeGen::DoUint32ToDouble(LUint32ToDouble* instr) {
6034 __ Ucvtf(ToDoubleRegister(instr->result()), ToRegister32(instr->value()));
6038 void LCodeGen::DoCheckMapValue(LCheckMapValue* instr) {
6039 Register object = ToRegister(instr->value());
6040 Register map = ToRegister(instr->map());
6041 Register temp = ToRegister(instr->temp());
6042 __ Ldr(temp, FieldMemOperand(object, HeapObject::kMapOffset));
6044 DeoptimizeIf(ne, instr, Deoptimizer::kWrongMap);
6048 void LCodeGen::DoWrapReceiver(LWrapReceiver* instr) {
6049 Register receiver = ToRegister(instr->receiver());
6050 Register function = ToRegister(instr->function());
6051 Register result = ToRegister(instr->result());
6053 // If the receiver is null or undefined, we have to pass the global object as
6054 // a receiver to normal functions. Values have to be passed unchanged to
6055 // builtins and strict-mode functions.
6056 Label global_object, done, copy_receiver;
6058 if (!instr->hydrogen()->known_function()) {
6059 __ Ldr(result, FieldMemOperand(function,
6060 JSFunction::kSharedFunctionInfoOffset));
6062 // CompilerHints is an int32 field. See objects.h.
6064 FieldMemOperand(result, SharedFunctionInfo::kCompilerHintsOffset));
6066 // Do not transform the receiver to object for strict mode functions.
6067 __ Tbnz(result, SharedFunctionInfo::kStrictModeFunction, ©_receiver);
6069 // Do not transform the receiver to object for builtins.
6070 __ Tbnz(result, SharedFunctionInfo::kNative, ©_receiver);
6073 // Normal function. Replace undefined or null with global receiver.
6074 __ JumpIfRoot(receiver, Heap::kNullValueRootIndex, &global_object);
6075 __ JumpIfRoot(receiver, Heap::kUndefinedValueRootIndex, &global_object);
6077 // Deoptimize if the receiver is not a JS object.
6078 DeoptimizeIfSmi(receiver, instr, Deoptimizer::kSmi);
6079 __ CompareObjectType(receiver, result, result, FIRST_SPEC_OBJECT_TYPE);
6080 __ B(ge, ©_receiver);
6081 Deoptimize(instr, Deoptimizer::kNotAJavaScriptObject);
6083 __ Bind(&global_object);
6084 __ Ldr(result, FieldMemOperand(function, JSFunction::kContextOffset));
6085 __ Ldr(result, ContextMemOperand(result, Context::GLOBAL_OBJECT_INDEX));
6086 __ Ldr(result, FieldMemOperand(result, GlobalObject::kGlobalProxyOffset));
6089 __ Bind(©_receiver);
6090 __ Mov(result, receiver);
6095 void LCodeGen::DoDeferredLoadMutableDouble(LLoadFieldByIndex* instr,
6099 PushSafepointRegistersScope scope(this);
6103 __ CallRuntimeSaveDoubles(Runtime::kLoadMutableDouble);
6104 RecordSafepointWithRegisters(
6105 instr->pointer_map(), 2, Safepoint::kNoLazyDeopt);
6106 __ StoreToSafepointRegisterSlot(x0, result);
6110 void LCodeGen::DoLoadFieldByIndex(LLoadFieldByIndex* instr) {
6111 class DeferredLoadMutableDouble final : public LDeferredCode {
6113 DeferredLoadMutableDouble(LCodeGen* codegen,
6114 LLoadFieldByIndex* instr,
6118 : LDeferredCode(codegen),
6124 void Generate() override {
6125 codegen()->DoDeferredLoadMutableDouble(instr_, result_, object_, index_);
6127 LInstruction* instr() override { return instr_; }
6130 LLoadFieldByIndex* instr_;
6135 Register object = ToRegister(instr->object());
6136 Register index = ToRegister(instr->index());
6137 Register result = ToRegister(instr->result());
6139 __ AssertSmi(index);
6141 DeferredLoadMutableDouble* deferred;
6142 deferred = new(zone()) DeferredLoadMutableDouble(
6143 this, instr, result, object, index);
6145 Label out_of_object, done;
6147 __ TestAndBranchIfAnySet(
6148 index, reinterpret_cast<uint64_t>(Smi::FromInt(1)), deferred->entry());
6149 __ Mov(index, Operand(index, ASR, 1));
6151 __ Cmp(index, Smi::FromInt(0));
6152 __ B(lt, &out_of_object);
6154 STATIC_ASSERT(kPointerSizeLog2 > kSmiTagSize);
6155 __ Add(result, object, Operand::UntagSmiAndScale(index, kPointerSizeLog2));
6156 __ Ldr(result, FieldMemOperand(result, JSObject::kHeaderSize));
6160 __ Bind(&out_of_object);
6161 __ Ldr(result, FieldMemOperand(object, JSObject::kPropertiesOffset));
6162 // Index is equal to negated out of object property index plus 1.
6163 __ Sub(result, result, Operand::UntagSmiAndScale(index, kPointerSizeLog2));
6164 __ Ldr(result, FieldMemOperand(result,
6165 FixedArray::kHeaderSize - kPointerSize));
6166 __ Bind(deferred->exit());
6171 void LCodeGen::DoStoreFrameContext(LStoreFrameContext* instr) {
6172 Register context = ToRegister(instr->context());
6173 __ Str(context, MemOperand(fp, StandardFrameConstants::kContextOffset));
6177 void LCodeGen::DoAllocateBlockContext(LAllocateBlockContext* instr) {
6178 Handle<ScopeInfo> scope_info = instr->scope_info();
6179 __ Push(scope_info);
6180 __ Push(ToRegister(instr->function()));
6181 CallRuntime(Runtime::kPushBlockContext, 2, instr);
6182 RecordSafepoint(Safepoint::kNoLazyDeopt);
6186 } // namespace internal