1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
7 #if V8_TARGET_ARCH_IA32
9 #include "src/base/bits.h"
10 #include "src/code-factory.h"
11 #include "src/code-stubs.h"
12 #include "src/codegen.h"
13 #include "src/cpu-profiler.h"
14 #include "src/deoptimizer.h"
15 #include "src/hydrogen-osr.h"
16 #include "src/ia32/lithium-codegen-ia32.h"
17 #include "src/ic/ic.h"
18 #include "src/ic/stub-cache.h"
23 // When invoking builtins, we need to record the safepoint in the middle of
24 // the invoke instruction sequence generated by the macro assembler.
25 class SafepointGenerator final : public CallWrapper {
27 SafepointGenerator(LCodeGen* codegen,
28 LPointerMap* pointers,
29 Safepoint::DeoptMode mode)
33 virtual ~SafepointGenerator() {}
35 void BeforeCall(int call_size) const override {}
37 void AfterCall() const override {
38 codegen_->RecordSafepoint(pointers_, deopt_mode_);
43 LPointerMap* pointers_;
44 Safepoint::DeoptMode deopt_mode_;
50 bool LCodeGen::GenerateCode() {
51 LPhase phase("Z_Code generation", chunk());
55 // Open a frame scope to indicate that there is a frame on the stack. The
56 // MANUAL indicates that the scope shouldn't actually generate code to set up
57 // the frame (that is done in GeneratePrologue).
58 FrameScope frame_scope(masm_, StackFrame::MANUAL);
60 support_aligned_spilled_doubles_ = info()->IsOptimizing();
62 dynamic_frame_alignment_ = info()->IsOptimizing() &&
63 ((chunk()->num_double_slots() > 2 &&
64 !chunk()->graph()->is_recursive()) ||
65 !info()->osr_ast_id().IsNone());
67 return GeneratePrologue() &&
69 GenerateDeferredCode() &&
70 GenerateJumpTable() &&
71 GenerateSafepointTable();
75 void LCodeGen::FinishCode(Handle<Code> code) {
77 code->set_stack_slots(GetStackSlotCount());
78 code->set_safepoint_table_offset(safepoints_.GetCodeOffset());
79 PopulateDeoptimizationData(code);
80 if (!info()->IsStub()) {
81 Deoptimizer::EnsureRelocSpaceForLazyDeoptimization(code);
87 void LCodeGen::MakeSureStackPagesMapped(int offset) {
88 const int kPageSize = 4 * KB;
89 for (offset -= kPageSize; offset > 0; offset -= kPageSize) {
90 __ mov(Operand(esp, offset), eax);
96 void LCodeGen::SaveCallerDoubles() {
97 DCHECK(info()->saves_caller_doubles());
98 DCHECK(NeedsEagerFrame());
99 Comment(";;; Save clobbered callee double registers");
101 BitVector* doubles = chunk()->allocated_double_registers();
102 BitVector::Iterator save_iterator(doubles);
103 while (!save_iterator.Done()) {
104 __ movsd(MemOperand(esp, count * kDoubleSize),
105 XMMRegister::FromAllocationIndex(save_iterator.Current()));
106 save_iterator.Advance();
112 void LCodeGen::RestoreCallerDoubles() {
113 DCHECK(info()->saves_caller_doubles());
114 DCHECK(NeedsEagerFrame());
115 Comment(";;; Restore clobbered callee double registers");
116 BitVector* doubles = chunk()->allocated_double_registers();
117 BitVector::Iterator save_iterator(doubles);
119 while (!save_iterator.Done()) {
120 __ movsd(XMMRegister::FromAllocationIndex(save_iterator.Current()),
121 MemOperand(esp, count * kDoubleSize));
122 save_iterator.Advance();
128 bool LCodeGen::GeneratePrologue() {
129 DCHECK(is_generating());
131 if (info()->IsOptimizing()) {
132 ProfileEntryHookStub::MaybeCallEntryHook(masm_);
135 if (strlen(FLAG_stop_at) > 0 &&
136 info_->function()->name()->IsUtf8EqualTo(CStrVector(FLAG_stop_at))) {
141 // Sloppy mode functions and builtins need to replace the receiver with the
142 // global proxy when called as functions (without an explicit receiver
144 if (is_sloppy(info()->language_mode()) && info()->MayUseThis() &&
145 !info()->is_native() && info()->scope()->has_this_declaration()) {
147 // +1 for return address.
148 int receiver_offset = (scope()->num_parameters() + 1) * kPointerSize;
149 __ mov(ecx, Operand(esp, receiver_offset));
151 __ cmp(ecx, isolate()->factory()->undefined_value());
152 __ j(not_equal, &ok, Label::kNear);
154 __ mov(ecx, GlobalObjectOperand());
155 __ mov(ecx, FieldOperand(ecx, GlobalObject::kGlobalProxyOffset));
157 __ mov(Operand(esp, receiver_offset), ecx);
162 if (support_aligned_spilled_doubles_ && dynamic_frame_alignment_) {
163 // Move state of dynamic frame alignment into edx.
164 __ Move(edx, Immediate(kNoAlignmentPadding));
166 Label do_not_pad, align_loop;
167 STATIC_ASSERT(kDoubleSize == 2 * kPointerSize);
168 // Align esp + 4 to a multiple of 2 * kPointerSize.
169 __ test(esp, Immediate(kPointerSize));
170 __ j(not_zero, &do_not_pad, Label::kNear);
171 __ push(Immediate(0));
173 __ mov(edx, Immediate(kAlignmentPaddingPushed));
174 // Copy arguments, receiver, and return address.
175 __ mov(ecx, Immediate(scope()->num_parameters() + 2));
177 __ bind(&align_loop);
178 __ mov(eax, Operand(ebx, 1 * kPointerSize));
179 __ mov(Operand(ebx, 0), eax);
180 __ add(Operand(ebx), Immediate(kPointerSize));
182 __ j(not_zero, &align_loop, Label::kNear);
183 __ mov(Operand(ebx, 0), Immediate(kAlignmentZapValue));
184 __ bind(&do_not_pad);
188 info()->set_prologue_offset(masm_->pc_offset());
189 if (NeedsEagerFrame()) {
190 DCHECK(!frame_is_built_);
191 frame_is_built_ = true;
192 if (info()->IsStub()) {
195 __ Prologue(info()->IsCodePreAgingActive());
197 info()->AddNoFrameRange(0, masm_->pc_offset());
200 if (info()->IsOptimizing() &&
201 dynamic_frame_alignment_ &&
203 __ test(esp, Immediate(kPointerSize));
204 __ Assert(zero, kFrameIsExpectedToBeAligned);
207 // Reserve space for the stack slots needed by the code.
208 int slots = GetStackSlotCount();
209 DCHECK(slots != 0 || !info()->IsOptimizing());
212 if (dynamic_frame_alignment_) {
215 __ push(Immediate(kNoAlignmentPadding));
218 if (FLAG_debug_code) {
219 __ sub(Operand(esp), Immediate(slots * kPointerSize));
221 MakeSureStackPagesMapped(slots * kPointerSize);
224 __ mov(Operand(eax), Immediate(slots));
227 __ mov(MemOperand(esp, eax, times_4, 0),
228 Immediate(kSlotsZapValue));
230 __ j(not_zero, &loop);
233 __ sub(Operand(esp), Immediate(slots * kPointerSize));
235 MakeSureStackPagesMapped(slots * kPointerSize);
239 if (support_aligned_spilled_doubles_) {
240 Comment(";;; Store dynamic frame alignment tag for spilled doubles");
241 // Store dynamic frame alignment state in the first local.
242 int offset = JavaScriptFrameConstants::kDynamicAlignmentStateOffset;
243 if (dynamic_frame_alignment_) {
244 __ mov(Operand(ebp, offset), edx);
246 __ mov(Operand(ebp, offset), Immediate(kNoAlignmentPadding));
251 if (info()->saves_caller_doubles()) SaveCallerDoubles();
254 // Possibly allocate a local context.
255 int heap_slots = info_->num_heap_slots() - Context::MIN_CONTEXT_SLOTS;
256 if (heap_slots > 0) {
257 Comment(";;; Allocate local context");
258 bool need_write_barrier = true;
259 // Argument to NewContext is the function, which is still in edi.
260 DCHECK(!info()->scope()->is_script_scope());
261 if (heap_slots <= FastNewContextStub::kMaximumSlots) {
262 FastNewContextStub stub(isolate(), heap_slots);
264 // Result of FastNewContextStub is always in new space.
265 need_write_barrier = false;
268 __ CallRuntime(Runtime::kNewFunctionContext, 1);
270 RecordSafepoint(Safepoint::kNoLazyDeopt);
271 // Context is returned in eax. It replaces the context passed to us.
272 // It's saved in the stack and kept live in esi.
274 __ mov(Operand(ebp, StandardFrameConstants::kContextOffset), eax);
276 // Copy parameters into context if necessary.
277 int num_parameters = scope()->num_parameters();
278 int first_parameter = scope()->has_this_declaration() ? -1 : 0;
279 for (int i = first_parameter; i < num_parameters; i++) {
280 Variable* var = (i == -1) ? scope()->receiver() : scope()->parameter(i);
281 if (var->IsContextSlot()) {
282 int parameter_offset = StandardFrameConstants::kCallerSPOffset +
283 (num_parameters - 1 - i) * kPointerSize;
284 // Load parameter from stack.
285 __ mov(eax, Operand(ebp, parameter_offset));
286 // Store it in the context.
287 int context_offset = Context::SlotOffset(var->index());
288 __ mov(Operand(esi, context_offset), eax);
289 // Update the write barrier. This clobbers eax and ebx.
290 if (need_write_barrier) {
291 __ RecordWriteContextSlot(esi,
296 } else if (FLAG_debug_code) {
298 __ JumpIfInNewSpace(esi, eax, &done, Label::kNear);
299 __ Abort(kExpectedNewSpaceObject);
304 Comment(";;; End allocate local context");
308 if (FLAG_trace && info()->IsOptimizing()) {
309 // We have not executed any compiled code yet, so esi still holds the
311 __ CallRuntime(Runtime::kTraceEnter, 0);
313 return !is_aborted();
317 void LCodeGen::GenerateOsrPrologue() {
318 // Generate the OSR entry prologue at the first unknown OSR value, or if there
319 // are none, at the OSR entrypoint instruction.
320 if (osr_pc_offset_ >= 0) return;
322 osr_pc_offset_ = masm()->pc_offset();
324 // Move state of dynamic frame alignment into edx.
325 __ Move(edx, Immediate(kNoAlignmentPadding));
327 if (support_aligned_spilled_doubles_ && dynamic_frame_alignment_) {
328 Label do_not_pad, align_loop;
329 // Align ebp + 4 to a multiple of 2 * kPointerSize.
330 __ test(ebp, Immediate(kPointerSize));
331 __ j(zero, &do_not_pad, Label::kNear);
332 __ push(Immediate(0));
334 __ mov(edx, Immediate(kAlignmentPaddingPushed));
336 // Move all parts of the frame over one word. The frame consists of:
337 // unoptimized frame slots, alignment state, context, frame pointer, return
338 // address, receiver, and the arguments.
339 __ mov(ecx, Immediate(scope()->num_parameters() +
340 5 + graph()->osr()->UnoptimizedFrameSlots()));
342 __ bind(&align_loop);
343 __ mov(eax, Operand(ebx, 1 * kPointerSize));
344 __ mov(Operand(ebx, 0), eax);
345 __ add(Operand(ebx), Immediate(kPointerSize));
347 __ j(not_zero, &align_loop, Label::kNear);
348 __ mov(Operand(ebx, 0), Immediate(kAlignmentZapValue));
349 __ sub(Operand(ebp), Immediate(kPointerSize));
350 __ bind(&do_not_pad);
353 // Save the first local, which is overwritten by the alignment state.
354 Operand alignment_loc = MemOperand(ebp, -3 * kPointerSize);
355 __ push(alignment_loc);
357 // Set the dynamic frame alignment state.
358 __ mov(alignment_loc, edx);
360 // Adjust the frame size, subsuming the unoptimized frame into the
362 int slots = GetStackSlotCount() - graph()->osr()->UnoptimizedFrameSlots();
364 __ sub(esp, Immediate((slots - 1) * kPointerSize));
368 void LCodeGen::GenerateBodyInstructionPre(LInstruction* instr) {
369 if (instr->IsCall()) {
370 EnsureSpaceForLazyDeopt(Deoptimizer::patch_size());
372 if (!instr->IsLazyBailout() && !instr->IsGap()) {
373 safepoints_.BumpLastLazySafepointIndex();
378 void LCodeGen::GenerateBodyInstructionPost(LInstruction* instr) { }
381 bool LCodeGen::GenerateJumpTable() {
382 if (!jump_table_.length()) return !is_aborted();
385 Comment(";;; -------------------- Jump table --------------------");
387 for (int i = 0; i < jump_table_.length(); i++) {
388 Deoptimizer::JumpTableEntry* table_entry = &jump_table_[i];
389 __ bind(&table_entry->label);
390 Address entry = table_entry->address;
391 DeoptComment(table_entry->deopt_info);
392 if (table_entry->needs_frame) {
393 DCHECK(!info()->saves_caller_doubles());
394 __ push(Immediate(ExternalReference::ForDeoptEntry(entry)));
395 __ call(&needs_frame);
397 if (info()->saves_caller_doubles()) RestoreCallerDoubles();
398 __ call(entry, RelocInfo::RUNTIME_ENTRY);
400 info()->LogDeoptCallPosition(masm()->pc_offset(),
401 table_entry->deopt_info.inlining_id);
403 if (needs_frame.is_linked()) {
404 __ bind(&needs_frame);
407 3: return address <-- esp
412 __ sub(esp, Immediate(kPointerSize)); // Reserve space for stub marker.
413 __ push(MemOperand(esp, kPointerSize)); // Copy return address.
414 __ push(MemOperand(esp, 3 * kPointerSize)); // Copy entry address.
421 0: entry address <-- esp
423 __ mov(MemOperand(esp, 4 * kPointerSize), ebp); // Save ebp.
425 __ mov(ebp, MemOperand(ebp, StandardFrameConstants::kContextOffset));
426 __ mov(MemOperand(esp, 3 * kPointerSize), ebp);
427 // Fill ebp with the right stack frame address.
428 __ lea(ebp, MemOperand(esp, 4 * kPointerSize));
429 // This variant of deopt can only be used with stubs. Since we don't
430 // have a function pointer to install in the stack frame that we're
431 // building, install a special marker there instead.
432 DCHECK(info()->IsStub());
433 __ mov(MemOperand(esp, 2 * kPointerSize),
434 Immediate(Smi::FromInt(StackFrame::STUB)));
441 0: entry address <-- esp
443 __ ret(0); // Call the continuation without clobbering registers.
445 return !is_aborted();
449 bool LCodeGen::GenerateDeferredCode() {
450 DCHECK(is_generating());
451 if (deferred_.length() > 0) {
452 for (int i = 0; !is_aborted() && i < deferred_.length(); i++) {
453 LDeferredCode* code = deferred_[i];
456 instructions_->at(code->instruction_index())->hydrogen_value();
457 RecordAndWritePosition(
458 chunk()->graph()->SourcePositionToScriptPosition(value->position()));
460 Comment(";;; <@%d,#%d> "
461 "-------------------- Deferred %s --------------------",
462 code->instruction_index(),
463 code->instr()->hydrogen_value()->id(),
464 code->instr()->Mnemonic());
465 __ bind(code->entry());
466 if (NeedsDeferredFrame()) {
467 Comment(";;; Build frame");
468 DCHECK(!frame_is_built_);
469 DCHECK(info()->IsStub());
470 frame_is_built_ = true;
471 // Build the frame in such a way that esi isn't trashed.
472 __ push(ebp); // Caller's frame pointer.
473 __ push(Operand(ebp, StandardFrameConstants::kContextOffset));
474 __ push(Immediate(Smi::FromInt(StackFrame::STUB)));
475 __ lea(ebp, Operand(esp, 2 * kPointerSize));
476 Comment(";;; Deferred code");
479 if (NeedsDeferredFrame()) {
480 __ bind(code->done());
481 Comment(";;; Destroy frame");
482 DCHECK(frame_is_built_);
483 frame_is_built_ = false;
487 __ jmp(code->exit());
491 // Deferred code is the last part of the instruction sequence. Mark
492 // the generated code as done unless we bailed out.
493 if (!is_aborted()) status_ = DONE;
494 return !is_aborted();
498 bool LCodeGen::GenerateSafepointTable() {
500 if (!info()->IsStub()) {
501 // For lazy deoptimization we need space to patch a call after every call.
502 // Ensure there is always space for such patching, even if the code ends
504 int target_offset = masm()->pc_offset() + Deoptimizer::patch_size();
505 while (masm()->pc_offset() < target_offset) {
509 safepoints_.Emit(masm(), GetStackSlotCount());
510 return !is_aborted();
514 Register LCodeGen::ToRegister(int index) const {
515 return Register::FromAllocationIndex(index);
519 XMMRegister LCodeGen::ToDoubleRegister(int index) const {
520 return XMMRegister::FromAllocationIndex(index);
524 Register LCodeGen::ToRegister(LOperand* op) const {
525 DCHECK(op->IsRegister());
526 return ToRegister(op->index());
530 XMMRegister LCodeGen::ToDoubleRegister(LOperand* op) const {
531 DCHECK(op->IsDoubleRegister());
532 return ToDoubleRegister(op->index());
536 int32_t LCodeGen::ToInteger32(LConstantOperand* op) const {
537 return ToRepresentation(op, Representation::Integer32());
541 int32_t LCodeGen::ToRepresentation(LConstantOperand* op,
542 const Representation& r) const {
543 HConstant* constant = chunk_->LookupConstant(op);
544 int32_t value = constant->Integer32Value();
545 if (r.IsInteger32()) return value;
546 DCHECK(r.IsSmiOrTagged());
547 return reinterpret_cast<int32_t>(Smi::FromInt(value));
551 Handle<Object> LCodeGen::ToHandle(LConstantOperand* op) const {
552 HConstant* constant = chunk_->LookupConstant(op);
553 DCHECK(chunk_->LookupLiteralRepresentation(op).IsSmiOrTagged());
554 return constant->handle(isolate());
558 double LCodeGen::ToDouble(LConstantOperand* op) const {
559 HConstant* constant = chunk_->LookupConstant(op);
560 DCHECK(constant->HasDoubleValue());
561 return constant->DoubleValue();
565 ExternalReference LCodeGen::ToExternalReference(LConstantOperand* op) const {
566 HConstant* constant = chunk_->LookupConstant(op);
567 DCHECK(constant->HasExternalReferenceValue());
568 return constant->ExternalReferenceValue();
572 bool LCodeGen::IsInteger32(LConstantOperand* op) const {
573 return chunk_->LookupLiteralRepresentation(op).IsSmiOrInteger32();
577 bool LCodeGen::IsSmi(LConstantOperand* op) const {
578 return chunk_->LookupLiteralRepresentation(op).IsSmi();
582 static int ArgumentsOffsetWithoutFrame(int index) {
584 return -(index + 1) * kPointerSize + kPCOnStackSize;
588 Operand LCodeGen::ToOperand(LOperand* op) const {
589 if (op->IsRegister()) return Operand(ToRegister(op));
590 if (op->IsDoubleRegister()) return Operand(ToDoubleRegister(op));
591 DCHECK(op->IsStackSlot() || op->IsDoubleStackSlot());
592 if (NeedsEagerFrame()) {
593 return Operand(ebp, StackSlotOffset(op->index()));
595 // Retrieve parameter without eager stack-frame relative to the
597 return Operand(esp, ArgumentsOffsetWithoutFrame(op->index()));
602 Operand LCodeGen::HighOperand(LOperand* op) {
603 DCHECK(op->IsDoubleStackSlot());
604 if (NeedsEagerFrame()) {
605 return Operand(ebp, StackSlotOffset(op->index()) + kPointerSize);
607 // Retrieve parameter without eager stack-frame relative to the
610 esp, ArgumentsOffsetWithoutFrame(op->index()) + kPointerSize);
615 void LCodeGen::WriteTranslation(LEnvironment* environment,
616 Translation* translation) {
617 if (environment == NULL) return;
619 // The translation includes one command per value in the environment.
620 int translation_size = environment->translation_size();
622 WriteTranslation(environment->outer(), translation);
623 WriteTranslationFrame(environment, translation);
625 int object_index = 0;
626 int dematerialized_index = 0;
627 for (int i = 0; i < translation_size; ++i) {
628 LOperand* value = environment->values()->at(i);
630 environment, translation, value, environment->HasTaggedValueAt(i),
631 environment->HasUint32ValueAt(i), &object_index, &dematerialized_index);
636 void LCodeGen::AddToTranslation(LEnvironment* environment,
637 Translation* translation,
641 int* object_index_pointer,
642 int* dematerialized_index_pointer) {
643 if (op == LEnvironment::materialization_marker()) {
644 int object_index = (*object_index_pointer)++;
645 if (environment->ObjectIsDuplicateAt(object_index)) {
646 int dupe_of = environment->ObjectDuplicateOfAt(object_index);
647 translation->DuplicateObject(dupe_of);
650 int object_length = environment->ObjectLengthAt(object_index);
651 if (environment->ObjectIsArgumentsAt(object_index)) {
652 translation->BeginArgumentsObject(object_length);
654 translation->BeginCapturedObject(object_length);
656 int dematerialized_index = *dematerialized_index_pointer;
657 int env_offset = environment->translation_size() + dematerialized_index;
658 *dematerialized_index_pointer += object_length;
659 for (int i = 0; i < object_length; ++i) {
660 LOperand* value = environment->values()->at(env_offset + i);
661 AddToTranslation(environment,
664 environment->HasTaggedValueAt(env_offset + i),
665 environment->HasUint32ValueAt(env_offset + i),
666 object_index_pointer,
667 dematerialized_index_pointer);
672 if (op->IsStackSlot()) {
674 translation->StoreStackSlot(op->index());
675 } else if (is_uint32) {
676 translation->StoreUint32StackSlot(op->index());
678 translation->StoreInt32StackSlot(op->index());
680 } else if (op->IsDoubleStackSlot()) {
681 translation->StoreDoubleStackSlot(op->index());
682 } else if (op->IsRegister()) {
683 Register reg = ToRegister(op);
685 translation->StoreRegister(reg);
686 } else if (is_uint32) {
687 translation->StoreUint32Register(reg);
689 translation->StoreInt32Register(reg);
691 } else if (op->IsDoubleRegister()) {
692 XMMRegister reg = ToDoubleRegister(op);
693 translation->StoreDoubleRegister(reg);
694 } else if (op->IsConstantOperand()) {
695 HConstant* constant = chunk()->LookupConstant(LConstantOperand::cast(op));
696 int src_index = DefineDeoptimizationLiteral(constant->handle(isolate()));
697 translation->StoreLiteral(src_index);
704 void LCodeGen::CallCodeGeneric(Handle<Code> code,
705 RelocInfo::Mode mode,
707 SafepointMode safepoint_mode) {
708 DCHECK(instr != NULL);
710 RecordSafepointWithLazyDeopt(instr, safepoint_mode);
712 // Signal that we don't inline smi code before these stubs in the
713 // optimizing code generator.
714 if (code->kind() == Code::BINARY_OP_IC ||
715 code->kind() == Code::COMPARE_IC) {
721 void LCodeGen::CallCode(Handle<Code> code,
722 RelocInfo::Mode mode,
723 LInstruction* instr) {
724 CallCodeGeneric(code, mode, instr, RECORD_SIMPLE_SAFEPOINT);
728 void LCodeGen::CallRuntime(const Runtime::Function* fun,
731 SaveFPRegsMode save_doubles) {
732 DCHECK(instr != NULL);
733 DCHECK(instr->HasPointerMap());
735 __ CallRuntime(fun, argc, save_doubles);
737 RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
739 DCHECK(info()->is_calling());
743 void LCodeGen::LoadContextFromDeferred(LOperand* context) {
744 if (context->IsRegister()) {
745 if (!ToRegister(context).is(esi)) {
746 __ mov(esi, ToRegister(context));
748 } else if (context->IsStackSlot()) {
749 __ mov(esi, ToOperand(context));
750 } else if (context->IsConstantOperand()) {
751 HConstant* constant =
752 chunk_->LookupConstant(LConstantOperand::cast(context));
753 __ LoadObject(esi, Handle<Object>::cast(constant->handle(isolate())));
759 void LCodeGen::CallRuntimeFromDeferred(Runtime::FunctionId id,
763 LoadContextFromDeferred(context);
765 __ CallRuntimeSaveDoubles(id);
766 RecordSafepointWithRegisters(
767 instr->pointer_map(), argc, Safepoint::kNoLazyDeopt);
769 DCHECK(info()->is_calling());
773 void LCodeGen::RegisterEnvironmentForDeoptimization(
774 LEnvironment* environment, Safepoint::DeoptMode mode) {
775 environment->set_has_been_used();
776 if (!environment->HasBeenRegistered()) {
777 // Physical stack frame layout:
778 // -x ............. -4 0 ..................................... y
779 // [incoming arguments] [spill slots] [pushed outgoing arguments]
781 // Layout of the environment:
782 // 0 ..................................................... size-1
783 // [parameters] [locals] [expression stack including arguments]
785 // Layout of the translation:
786 // 0 ........................................................ size - 1 + 4
787 // [expression stack including arguments] [locals] [4 words] [parameters]
788 // |>------------ translation_size ------------<|
791 int jsframe_count = 0;
792 for (LEnvironment* e = environment; e != NULL; e = e->outer()) {
794 if (e->frame_type() == JS_FUNCTION) {
798 Translation translation(&translations_, frame_count, jsframe_count, zone());
799 WriteTranslation(environment, &translation);
800 int deoptimization_index = deoptimizations_.length();
801 int pc_offset = masm()->pc_offset();
802 environment->Register(deoptimization_index,
804 (mode == Safepoint::kLazyDeopt) ? pc_offset : -1);
805 deoptimizations_.Add(environment, zone());
810 void LCodeGen::DeoptimizeIf(Condition cc, LInstruction* instr,
811 Deoptimizer::DeoptReason deopt_reason,
812 Deoptimizer::BailoutType bailout_type) {
813 LEnvironment* environment = instr->environment();
814 RegisterEnvironmentForDeoptimization(environment, Safepoint::kNoLazyDeopt);
815 DCHECK(environment->HasBeenRegistered());
816 int id = environment->deoptimization_index();
817 DCHECK(info()->IsOptimizing() || info()->IsStub());
819 Deoptimizer::GetDeoptimizationEntry(isolate(), id, bailout_type);
821 Abort(kBailoutWasNotPrepared);
825 if (DeoptEveryNTimes()) {
826 ExternalReference count = ExternalReference::stress_deopt_count(isolate());
830 __ mov(eax, Operand::StaticVariable(count));
831 __ sub(eax, Immediate(1));
832 __ j(not_zero, &no_deopt, Label::kNear);
833 if (FLAG_trap_on_deopt) __ int3();
834 __ mov(eax, Immediate(FLAG_deopt_every_n_times));
835 __ mov(Operand::StaticVariable(count), eax);
838 DCHECK(frame_is_built_);
839 __ call(entry, RelocInfo::RUNTIME_ENTRY);
841 __ mov(Operand::StaticVariable(count), eax);
846 if (info()->ShouldTrapOnDeopt()) {
848 if (cc != no_condition) __ j(NegateCondition(cc), &done, Label::kNear);
853 Deoptimizer::DeoptInfo deopt_info = MakeDeoptInfo(instr, deopt_reason);
855 DCHECK(info()->IsStub() || frame_is_built_);
856 if (cc == no_condition && frame_is_built_) {
857 DeoptComment(deopt_info);
858 __ call(entry, RelocInfo::RUNTIME_ENTRY);
859 info()->LogDeoptCallPosition(masm()->pc_offset(), deopt_info.inlining_id);
861 Deoptimizer::JumpTableEntry table_entry(entry, deopt_info, bailout_type,
863 // We often have several deopts to the same entry, reuse the last
864 // jump entry if this is the case.
865 if (FLAG_trace_deopt || isolate()->cpu_profiler()->is_profiling() ||
866 jump_table_.is_empty() ||
867 !table_entry.IsEquivalentTo(jump_table_.last())) {
868 jump_table_.Add(table_entry, zone());
870 if (cc == no_condition) {
871 __ jmp(&jump_table_.last().label);
873 __ j(cc, &jump_table_.last().label);
879 void LCodeGen::DeoptimizeIf(Condition cc, LInstruction* instr,
880 Deoptimizer::DeoptReason deopt_reason) {
881 Deoptimizer::BailoutType bailout_type = info()->IsStub()
883 : Deoptimizer::EAGER;
884 DeoptimizeIf(cc, instr, deopt_reason, bailout_type);
888 void LCodeGen::PopulateDeoptimizationData(Handle<Code> code) {
889 int length = deoptimizations_.length();
890 if (length == 0) return;
891 Handle<DeoptimizationInputData> data =
892 DeoptimizationInputData::New(isolate(), length, TENURED);
894 Handle<ByteArray> translations =
895 translations_.CreateByteArray(isolate()->factory());
896 data->SetTranslationByteArray(*translations);
897 data->SetInlinedFunctionCount(Smi::FromInt(inlined_function_count_));
898 data->SetOptimizationId(Smi::FromInt(info_->optimization_id()));
899 if (info_->IsOptimizing()) {
900 // Reference to shared function info does not change between phases.
901 AllowDeferredHandleDereference allow_handle_dereference;
902 data->SetSharedFunctionInfo(*info_->shared_info());
904 data->SetSharedFunctionInfo(Smi::FromInt(0));
906 data->SetWeakCellCache(Smi::FromInt(0));
908 Handle<FixedArray> literals =
909 factory()->NewFixedArray(deoptimization_literals_.length(), TENURED);
910 { AllowDeferredHandleDereference copy_handles;
911 for (int i = 0; i < deoptimization_literals_.length(); i++) {
912 literals->set(i, *deoptimization_literals_[i]);
914 data->SetLiteralArray(*literals);
917 data->SetOsrAstId(Smi::FromInt(info_->osr_ast_id().ToInt()));
918 data->SetOsrPcOffset(Smi::FromInt(osr_pc_offset_));
920 // Populate the deoptimization entries.
921 for (int i = 0; i < length; i++) {
922 LEnvironment* env = deoptimizations_[i];
923 data->SetAstId(i, env->ast_id());
924 data->SetTranslationIndex(i, Smi::FromInt(env->translation_index()));
925 data->SetArgumentsStackHeight(i,
926 Smi::FromInt(env->arguments_stack_height()));
927 data->SetPc(i, Smi::FromInt(env->pc_offset()));
929 code->set_deoptimization_data(*data);
933 void LCodeGen::PopulateDeoptimizationLiteralsWithInlinedFunctions() {
934 DCHECK_EQ(0, deoptimization_literals_.length());
935 for (auto function : chunk()->inlined_functions()) {
936 DefineDeoptimizationLiteral(function);
938 inlined_function_count_ = deoptimization_literals_.length();
942 void LCodeGen::RecordSafepointWithLazyDeopt(
943 LInstruction* instr, SafepointMode safepoint_mode) {
944 if (safepoint_mode == RECORD_SIMPLE_SAFEPOINT) {
945 RecordSafepoint(instr->pointer_map(), Safepoint::kLazyDeopt);
947 DCHECK(safepoint_mode == RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
948 RecordSafepointWithRegisters(
949 instr->pointer_map(), 0, Safepoint::kLazyDeopt);
954 void LCodeGen::RecordSafepoint(
955 LPointerMap* pointers,
956 Safepoint::Kind kind,
958 Safepoint::DeoptMode deopt_mode) {
959 DCHECK(kind == expected_safepoint_kind_);
960 const ZoneList<LOperand*>* operands = pointers->GetNormalizedOperands();
961 Safepoint safepoint =
962 safepoints_.DefineSafepoint(masm(), kind, arguments, deopt_mode);
963 for (int i = 0; i < operands->length(); i++) {
964 LOperand* pointer = operands->at(i);
965 if (pointer->IsStackSlot()) {
966 safepoint.DefinePointerSlot(pointer->index(), zone());
967 } else if (pointer->IsRegister() && (kind & Safepoint::kWithRegisters)) {
968 safepoint.DefinePointerRegister(ToRegister(pointer), zone());
974 void LCodeGen::RecordSafepoint(LPointerMap* pointers,
975 Safepoint::DeoptMode mode) {
976 RecordSafepoint(pointers, Safepoint::kSimple, 0, mode);
980 void LCodeGen::RecordSafepoint(Safepoint::DeoptMode mode) {
981 LPointerMap empty_pointers(zone());
982 RecordSafepoint(&empty_pointers, mode);
986 void LCodeGen::RecordSafepointWithRegisters(LPointerMap* pointers,
988 Safepoint::DeoptMode mode) {
989 RecordSafepoint(pointers, Safepoint::kWithRegisters, arguments, mode);
993 void LCodeGen::RecordAndWritePosition(int position) {
994 if (position == RelocInfo::kNoPosition) return;
995 masm()->positions_recorder()->RecordPosition(position);
996 masm()->positions_recorder()->WriteRecordedPositions();
1000 static const char* LabelType(LLabel* label) {
1001 if (label->is_loop_header()) return " (loop header)";
1002 if (label->is_osr_entry()) return " (OSR entry)";
1007 void LCodeGen::DoLabel(LLabel* label) {
1008 Comment(";;; <@%d,#%d> -------------------- B%d%s --------------------",
1009 current_instruction_,
1010 label->hydrogen_value()->id(),
1013 __ bind(label->label());
1014 current_block_ = label->block_id();
1019 void LCodeGen::DoParallelMove(LParallelMove* move) {
1020 resolver_.Resolve(move);
1024 void LCodeGen::DoGap(LGap* gap) {
1025 for (int i = LGap::FIRST_INNER_POSITION;
1026 i <= LGap::LAST_INNER_POSITION;
1028 LGap::InnerPosition inner_pos = static_cast<LGap::InnerPosition>(i);
1029 LParallelMove* move = gap->GetParallelMove(inner_pos);
1030 if (move != NULL) DoParallelMove(move);
1035 void LCodeGen::DoInstructionGap(LInstructionGap* instr) {
1040 void LCodeGen::DoParameter(LParameter* instr) {
1045 void LCodeGen::DoCallStub(LCallStub* instr) {
1046 DCHECK(ToRegister(instr->context()).is(esi));
1047 DCHECK(ToRegister(instr->result()).is(eax));
1048 switch (instr->hydrogen()->major_key()) {
1049 case CodeStub::RegExpExec: {
1050 RegExpExecStub stub(isolate());
1051 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
1054 case CodeStub::SubString: {
1055 SubStringStub stub(isolate());
1056 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
1059 case CodeStub::StringCompare: {
1060 StringCompareStub stub(isolate());
1061 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
1070 void LCodeGen::DoUnknownOSRValue(LUnknownOSRValue* instr) {
1071 GenerateOsrPrologue();
1075 void LCodeGen::DoModByPowerOf2I(LModByPowerOf2I* instr) {
1076 Register dividend = ToRegister(instr->dividend());
1077 int32_t divisor = instr->divisor();
1078 DCHECK(dividend.is(ToRegister(instr->result())));
1080 // Theoretically, a variation of the branch-free code for integer division by
1081 // a power of 2 (calculating the remainder via an additional multiplication
1082 // (which gets simplified to an 'and') and subtraction) should be faster, and
1083 // this is exactly what GCC and clang emit. Nevertheless, benchmarks seem to
1084 // indicate that positive dividends are heavily favored, so the branching
1085 // version performs better.
1086 HMod* hmod = instr->hydrogen();
1087 int32_t mask = divisor < 0 ? -(divisor + 1) : (divisor - 1);
1088 Label dividend_is_not_negative, done;
1089 if (hmod->CheckFlag(HValue::kLeftCanBeNegative)) {
1090 __ test(dividend, dividend);
1091 __ j(not_sign, ÷nd_is_not_negative, Label::kNear);
1092 // Note that this is correct even for kMinInt operands.
1094 __ and_(dividend, mask);
1096 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1097 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1099 __ jmp(&done, Label::kNear);
1102 __ bind(÷nd_is_not_negative);
1103 __ and_(dividend, mask);
1108 void LCodeGen::DoModByConstI(LModByConstI* instr) {
1109 Register dividend = ToRegister(instr->dividend());
1110 int32_t divisor = instr->divisor();
1111 DCHECK(ToRegister(instr->result()).is(eax));
1114 DeoptimizeIf(no_condition, instr, Deoptimizer::kDivisionByZero);
1118 __ TruncatingDiv(dividend, Abs(divisor));
1119 __ imul(edx, edx, Abs(divisor));
1120 __ mov(eax, dividend);
1123 // Check for negative zero.
1124 HMod* hmod = instr->hydrogen();
1125 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1126 Label remainder_not_zero;
1127 __ j(not_zero, &remainder_not_zero, Label::kNear);
1128 __ cmp(dividend, Immediate(0));
1129 DeoptimizeIf(less, instr, Deoptimizer::kMinusZero);
1130 __ bind(&remainder_not_zero);
1135 void LCodeGen::DoModI(LModI* instr) {
1136 HMod* hmod = instr->hydrogen();
1138 Register left_reg = ToRegister(instr->left());
1139 DCHECK(left_reg.is(eax));
1140 Register right_reg = ToRegister(instr->right());
1141 DCHECK(!right_reg.is(eax));
1142 DCHECK(!right_reg.is(edx));
1143 Register result_reg = ToRegister(instr->result());
1144 DCHECK(result_reg.is(edx));
1147 // Check for x % 0, idiv would signal a divide error. We have to
1148 // deopt in this case because we can't return a NaN.
1149 if (hmod->CheckFlag(HValue::kCanBeDivByZero)) {
1150 __ test(right_reg, Operand(right_reg));
1151 DeoptimizeIf(zero, instr, Deoptimizer::kDivisionByZero);
1154 // Check for kMinInt % -1, idiv would signal a divide error. We
1155 // have to deopt if we care about -0, because we can't return that.
1156 if (hmod->CheckFlag(HValue::kCanOverflow)) {
1157 Label no_overflow_possible;
1158 __ cmp(left_reg, kMinInt);
1159 __ j(not_equal, &no_overflow_possible, Label::kNear);
1160 __ cmp(right_reg, -1);
1161 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1162 DeoptimizeIf(equal, instr, Deoptimizer::kMinusZero);
1164 __ j(not_equal, &no_overflow_possible, Label::kNear);
1165 __ Move(result_reg, Immediate(0));
1166 __ jmp(&done, Label::kNear);
1168 __ bind(&no_overflow_possible);
1171 // Sign extend dividend in eax into edx:eax.
1174 // If we care about -0, test if the dividend is <0 and the result is 0.
1175 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1176 Label positive_left;
1177 __ test(left_reg, Operand(left_reg));
1178 __ j(not_sign, &positive_left, Label::kNear);
1180 __ test(result_reg, Operand(result_reg));
1181 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1182 __ jmp(&done, Label::kNear);
1183 __ bind(&positive_left);
1190 void LCodeGen::DoDivByPowerOf2I(LDivByPowerOf2I* instr) {
1191 Register dividend = ToRegister(instr->dividend());
1192 int32_t divisor = instr->divisor();
1193 Register result = ToRegister(instr->result());
1194 DCHECK(divisor == kMinInt || base::bits::IsPowerOfTwo32(Abs(divisor)));
1195 DCHECK(!result.is(dividend));
1197 // Check for (0 / -x) that will produce negative zero.
1198 HDiv* hdiv = instr->hydrogen();
1199 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
1200 __ test(dividend, dividend);
1201 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1203 // Check for (kMinInt / -1).
1204 if (hdiv->CheckFlag(HValue::kCanOverflow) && divisor == -1) {
1205 __ cmp(dividend, kMinInt);
1206 DeoptimizeIf(zero, instr, Deoptimizer::kOverflow);
1208 // Deoptimize if remainder will not be 0.
1209 if (!hdiv->CheckFlag(HInstruction::kAllUsesTruncatingToInt32) &&
1210 divisor != 1 && divisor != -1) {
1211 int32_t mask = divisor < 0 ? -(divisor + 1) : (divisor - 1);
1212 __ test(dividend, Immediate(mask));
1213 DeoptimizeIf(not_zero, instr, Deoptimizer::kLostPrecision);
1215 __ Move(result, dividend);
1216 int32_t shift = WhichPowerOf2Abs(divisor);
1218 // The arithmetic shift is always OK, the 'if' is an optimization only.
1219 if (shift > 1) __ sar(result, 31);
1220 __ shr(result, 32 - shift);
1221 __ add(result, dividend);
1222 __ sar(result, shift);
1224 if (divisor < 0) __ neg(result);
1228 void LCodeGen::DoDivByConstI(LDivByConstI* instr) {
1229 Register dividend = ToRegister(instr->dividend());
1230 int32_t divisor = instr->divisor();
1231 DCHECK(ToRegister(instr->result()).is(edx));
1234 DeoptimizeIf(no_condition, instr, Deoptimizer::kDivisionByZero);
1238 // Check for (0 / -x) that will produce negative zero.
1239 HDiv* hdiv = instr->hydrogen();
1240 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
1241 __ test(dividend, dividend);
1242 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1245 __ TruncatingDiv(dividend, Abs(divisor));
1246 if (divisor < 0) __ neg(edx);
1248 if (!hdiv->CheckFlag(HInstruction::kAllUsesTruncatingToInt32)) {
1250 __ imul(eax, eax, divisor);
1251 __ sub(eax, dividend);
1252 DeoptimizeIf(not_equal, instr, Deoptimizer::kLostPrecision);
1257 // TODO(svenpanne) Refactor this to avoid code duplication with DoFlooringDivI.
1258 void LCodeGen::DoDivI(LDivI* instr) {
1259 HBinaryOperation* hdiv = instr->hydrogen();
1260 Register dividend = ToRegister(instr->dividend());
1261 Register divisor = ToRegister(instr->divisor());
1262 Register remainder = ToRegister(instr->temp());
1263 DCHECK(dividend.is(eax));
1264 DCHECK(remainder.is(edx));
1265 DCHECK(ToRegister(instr->result()).is(eax));
1266 DCHECK(!divisor.is(eax));
1267 DCHECK(!divisor.is(edx));
1270 if (hdiv->CheckFlag(HValue::kCanBeDivByZero)) {
1271 __ test(divisor, divisor);
1272 DeoptimizeIf(zero, instr, Deoptimizer::kDivisionByZero);
1275 // Check for (0 / -x) that will produce negative zero.
1276 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero)) {
1277 Label dividend_not_zero;
1278 __ test(dividend, dividend);
1279 __ j(not_zero, ÷nd_not_zero, Label::kNear);
1280 __ test(divisor, divisor);
1281 DeoptimizeIf(sign, instr, Deoptimizer::kMinusZero);
1282 __ bind(÷nd_not_zero);
1285 // Check for (kMinInt / -1).
1286 if (hdiv->CheckFlag(HValue::kCanOverflow)) {
1287 Label dividend_not_min_int;
1288 __ cmp(dividend, kMinInt);
1289 __ j(not_zero, ÷nd_not_min_int, Label::kNear);
1290 __ cmp(divisor, -1);
1291 DeoptimizeIf(zero, instr, Deoptimizer::kOverflow);
1292 __ bind(÷nd_not_min_int);
1295 // Sign extend to edx (= remainder).
1299 if (!hdiv->CheckFlag(HValue::kAllUsesTruncatingToInt32)) {
1300 // Deoptimize if remainder is not 0.
1301 __ test(remainder, remainder);
1302 DeoptimizeIf(not_zero, instr, Deoptimizer::kLostPrecision);
1307 void LCodeGen::DoFlooringDivByPowerOf2I(LFlooringDivByPowerOf2I* instr) {
1308 Register dividend = ToRegister(instr->dividend());
1309 int32_t divisor = instr->divisor();
1310 DCHECK(dividend.is(ToRegister(instr->result())));
1312 // If the divisor is positive, things are easy: There can be no deopts and we
1313 // can simply do an arithmetic right shift.
1314 if (divisor == 1) return;
1315 int32_t shift = WhichPowerOf2Abs(divisor);
1317 __ sar(dividend, shift);
1321 // If the divisor is negative, we have to negate and handle edge cases.
1323 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1324 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1327 // Dividing by -1 is basically negation, unless we overflow.
1328 if (divisor == -1) {
1329 if (instr->hydrogen()->CheckFlag(HValue::kLeftCanBeMinInt)) {
1330 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1335 // If the negation could not overflow, simply shifting is OK.
1336 if (!instr->hydrogen()->CheckFlag(HValue::kLeftCanBeMinInt)) {
1337 __ sar(dividend, shift);
1341 Label not_kmin_int, done;
1342 __ j(no_overflow, ¬_kmin_int, Label::kNear);
1343 __ mov(dividend, Immediate(kMinInt / divisor));
1344 __ jmp(&done, Label::kNear);
1345 __ bind(¬_kmin_int);
1346 __ sar(dividend, shift);
1351 void LCodeGen::DoFlooringDivByConstI(LFlooringDivByConstI* instr) {
1352 Register dividend = ToRegister(instr->dividend());
1353 int32_t divisor = instr->divisor();
1354 DCHECK(ToRegister(instr->result()).is(edx));
1357 DeoptimizeIf(no_condition, instr, Deoptimizer::kDivisionByZero);
1361 // Check for (0 / -x) that will produce negative zero.
1362 HMathFloorOfDiv* hdiv = instr->hydrogen();
1363 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
1364 __ test(dividend, dividend);
1365 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1368 // Easy case: We need no dynamic check for the dividend and the flooring
1369 // division is the same as the truncating division.
1370 if ((divisor > 0 && !hdiv->CheckFlag(HValue::kLeftCanBeNegative)) ||
1371 (divisor < 0 && !hdiv->CheckFlag(HValue::kLeftCanBePositive))) {
1372 __ TruncatingDiv(dividend, Abs(divisor));
1373 if (divisor < 0) __ neg(edx);
1377 // In the general case we may need to adjust before and after the truncating
1378 // division to get a flooring division.
1379 Register temp = ToRegister(instr->temp3());
1380 DCHECK(!temp.is(dividend) && !temp.is(eax) && !temp.is(edx));
1381 Label needs_adjustment, done;
1382 __ cmp(dividend, Immediate(0));
1383 __ j(divisor > 0 ? less : greater, &needs_adjustment, Label::kNear);
1384 __ TruncatingDiv(dividend, Abs(divisor));
1385 if (divisor < 0) __ neg(edx);
1386 __ jmp(&done, Label::kNear);
1387 __ bind(&needs_adjustment);
1388 __ lea(temp, Operand(dividend, divisor > 0 ? 1 : -1));
1389 __ TruncatingDiv(temp, Abs(divisor));
1390 if (divisor < 0) __ neg(edx);
1396 // TODO(svenpanne) Refactor this to avoid code duplication with DoDivI.
1397 void LCodeGen::DoFlooringDivI(LFlooringDivI* instr) {
1398 HBinaryOperation* hdiv = instr->hydrogen();
1399 Register dividend = ToRegister(instr->dividend());
1400 Register divisor = ToRegister(instr->divisor());
1401 Register remainder = ToRegister(instr->temp());
1402 Register result = ToRegister(instr->result());
1403 DCHECK(dividend.is(eax));
1404 DCHECK(remainder.is(edx));
1405 DCHECK(result.is(eax));
1406 DCHECK(!divisor.is(eax));
1407 DCHECK(!divisor.is(edx));
1410 if (hdiv->CheckFlag(HValue::kCanBeDivByZero)) {
1411 __ test(divisor, divisor);
1412 DeoptimizeIf(zero, instr, Deoptimizer::kDivisionByZero);
1415 // Check for (0 / -x) that will produce negative zero.
1416 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero)) {
1417 Label dividend_not_zero;
1418 __ test(dividend, dividend);
1419 __ j(not_zero, ÷nd_not_zero, Label::kNear);
1420 __ test(divisor, divisor);
1421 DeoptimizeIf(sign, instr, Deoptimizer::kMinusZero);
1422 __ bind(÷nd_not_zero);
1425 // Check for (kMinInt / -1).
1426 if (hdiv->CheckFlag(HValue::kCanOverflow)) {
1427 Label dividend_not_min_int;
1428 __ cmp(dividend, kMinInt);
1429 __ j(not_zero, ÷nd_not_min_int, Label::kNear);
1430 __ cmp(divisor, -1);
1431 DeoptimizeIf(zero, instr, Deoptimizer::kOverflow);
1432 __ bind(÷nd_not_min_int);
1435 // Sign extend to edx (= remainder).
1440 __ test(remainder, remainder);
1441 __ j(zero, &done, Label::kNear);
1442 __ xor_(remainder, divisor);
1443 __ sar(remainder, 31);
1444 __ add(result, remainder);
1449 void LCodeGen::DoMulI(LMulI* instr) {
1450 Register left = ToRegister(instr->left());
1451 LOperand* right = instr->right();
1453 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1454 __ mov(ToRegister(instr->temp()), left);
1457 if (right->IsConstantOperand()) {
1458 // Try strength reductions on the multiplication.
1459 // All replacement instructions are at most as long as the imul
1460 // and have better latency.
1461 int constant = ToInteger32(LConstantOperand::cast(right));
1462 if (constant == -1) {
1464 } else if (constant == 0) {
1465 __ xor_(left, Operand(left));
1466 } else if (constant == 2) {
1467 __ add(left, Operand(left));
1468 } else if (!instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
1469 // If we know that the multiplication can't overflow, it's safe to
1470 // use instructions that don't set the overflow flag for the
1477 __ lea(left, Operand(left, left, times_2, 0));
1483 __ lea(left, Operand(left, left, times_4, 0));
1489 __ lea(left, Operand(left, left, times_8, 0));
1495 __ imul(left, left, constant);
1499 __ imul(left, left, constant);
1502 if (instr->hydrogen()->representation().IsSmi()) {
1505 __ imul(left, ToOperand(right));
1508 if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
1509 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1512 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1513 // Bail out if the result is supposed to be negative zero.
1515 __ test(left, Operand(left));
1516 __ j(not_zero, &done, Label::kNear);
1517 if (right->IsConstantOperand()) {
1518 if (ToInteger32(LConstantOperand::cast(right)) < 0) {
1519 DeoptimizeIf(no_condition, instr, Deoptimizer::kMinusZero);
1520 } else if (ToInteger32(LConstantOperand::cast(right)) == 0) {
1521 __ cmp(ToRegister(instr->temp()), Immediate(0));
1522 DeoptimizeIf(less, instr, Deoptimizer::kMinusZero);
1525 // Test the non-zero operand for negative sign.
1526 __ or_(ToRegister(instr->temp()), ToOperand(right));
1527 DeoptimizeIf(sign, instr, Deoptimizer::kMinusZero);
1534 void LCodeGen::DoBitI(LBitI* instr) {
1535 LOperand* left = instr->left();
1536 LOperand* right = instr->right();
1537 DCHECK(left->Equals(instr->result()));
1538 DCHECK(left->IsRegister());
1540 if (right->IsConstantOperand()) {
1541 int32_t right_operand =
1542 ToRepresentation(LConstantOperand::cast(right),
1543 instr->hydrogen()->representation());
1544 switch (instr->op()) {
1545 case Token::BIT_AND:
1546 __ and_(ToRegister(left), right_operand);
1549 __ or_(ToRegister(left), right_operand);
1551 case Token::BIT_XOR:
1552 if (right_operand == int32_t(~0)) {
1553 __ not_(ToRegister(left));
1555 __ xor_(ToRegister(left), right_operand);
1563 switch (instr->op()) {
1564 case Token::BIT_AND:
1565 __ and_(ToRegister(left), ToOperand(right));
1568 __ or_(ToRegister(left), ToOperand(right));
1570 case Token::BIT_XOR:
1571 __ xor_(ToRegister(left), ToOperand(right));
1581 void LCodeGen::DoShiftI(LShiftI* instr) {
1582 LOperand* left = instr->left();
1583 LOperand* right = instr->right();
1584 DCHECK(left->Equals(instr->result()));
1585 DCHECK(left->IsRegister());
1586 if (right->IsRegister()) {
1587 DCHECK(ToRegister(right).is(ecx));
1589 switch (instr->op()) {
1591 __ ror_cl(ToRegister(left));
1594 __ sar_cl(ToRegister(left));
1597 __ shr_cl(ToRegister(left));
1598 if (instr->can_deopt()) {
1599 __ test(ToRegister(left), ToRegister(left));
1600 DeoptimizeIf(sign, instr, Deoptimizer::kNegativeValue);
1604 __ shl_cl(ToRegister(left));
1611 int value = ToInteger32(LConstantOperand::cast(right));
1612 uint8_t shift_count = static_cast<uint8_t>(value & 0x1F);
1613 switch (instr->op()) {
1615 if (shift_count == 0 && instr->can_deopt()) {
1616 __ test(ToRegister(left), ToRegister(left));
1617 DeoptimizeIf(sign, instr, Deoptimizer::kNegativeValue);
1619 __ ror(ToRegister(left), shift_count);
1623 if (shift_count != 0) {
1624 __ sar(ToRegister(left), shift_count);
1628 if (shift_count != 0) {
1629 __ shr(ToRegister(left), shift_count);
1630 } else if (instr->can_deopt()) {
1631 __ test(ToRegister(left), ToRegister(left));
1632 DeoptimizeIf(sign, instr, Deoptimizer::kNegativeValue);
1636 if (shift_count != 0) {
1637 if (instr->hydrogen_value()->representation().IsSmi() &&
1638 instr->can_deopt()) {
1639 if (shift_count != 1) {
1640 __ shl(ToRegister(left), shift_count - 1);
1642 __ SmiTag(ToRegister(left));
1643 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1645 __ shl(ToRegister(left), shift_count);
1657 void LCodeGen::DoSubI(LSubI* instr) {
1658 LOperand* left = instr->left();
1659 LOperand* right = instr->right();
1660 DCHECK(left->Equals(instr->result()));
1662 if (right->IsConstantOperand()) {
1663 __ sub(ToOperand(left),
1664 ToImmediate(right, instr->hydrogen()->representation()));
1666 __ sub(ToRegister(left), ToOperand(right));
1668 if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
1669 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1674 void LCodeGen::DoConstantI(LConstantI* instr) {
1675 __ Move(ToRegister(instr->result()), Immediate(instr->value()));
1679 void LCodeGen::DoConstantS(LConstantS* instr) {
1680 __ Move(ToRegister(instr->result()), Immediate(instr->value()));
1684 void LCodeGen::DoConstantD(LConstantD* instr) {
1685 uint64_t const bits = instr->bits();
1686 uint32_t const lower = static_cast<uint32_t>(bits);
1687 uint32_t const upper = static_cast<uint32_t>(bits >> 32);
1688 DCHECK(instr->result()->IsDoubleRegister());
1690 XMMRegister result = ToDoubleRegister(instr->result());
1692 __ xorps(result, result);
1694 Register temp = ToRegister(instr->temp());
1695 if (CpuFeatures::IsSupported(SSE4_1)) {
1696 CpuFeatureScope scope2(masm(), SSE4_1);
1698 __ Move(temp, Immediate(lower));
1699 __ movd(result, Operand(temp));
1700 __ Move(temp, Immediate(upper));
1701 __ pinsrd(result, Operand(temp), 1);
1703 __ xorps(result, result);
1704 __ Move(temp, Immediate(upper));
1705 __ pinsrd(result, Operand(temp), 1);
1708 __ Move(temp, Immediate(upper));
1709 __ movd(result, Operand(temp));
1710 __ psllq(result, 32);
1712 XMMRegister xmm_scratch = double_scratch0();
1713 __ Move(temp, Immediate(lower));
1714 __ movd(xmm_scratch, Operand(temp));
1715 __ orps(result, xmm_scratch);
1722 void LCodeGen::DoConstantE(LConstantE* instr) {
1723 __ lea(ToRegister(instr->result()), Operand::StaticVariable(instr->value()));
1727 void LCodeGen::DoConstantT(LConstantT* instr) {
1728 Register reg = ToRegister(instr->result());
1729 Handle<Object> object = instr->value(isolate());
1730 AllowDeferredHandleDereference smi_check;
1731 __ LoadObject(reg, object);
1735 void LCodeGen::DoMapEnumLength(LMapEnumLength* instr) {
1736 Register result = ToRegister(instr->result());
1737 Register map = ToRegister(instr->value());
1738 __ EnumLength(result, map);
1742 void LCodeGen::DoDateField(LDateField* instr) {
1743 Register object = ToRegister(instr->date());
1744 Register result = ToRegister(instr->result());
1745 Register scratch = ToRegister(instr->temp());
1746 Smi* index = instr->index();
1747 DCHECK(object.is(result));
1748 DCHECK(object.is(eax));
1750 if (index->value() == 0) {
1751 __ mov(result, FieldOperand(object, JSDate::kValueOffset));
1753 Label runtime, done;
1754 if (index->value() < JSDate::kFirstUncachedField) {
1755 ExternalReference stamp = ExternalReference::date_cache_stamp(isolate());
1756 __ mov(scratch, Operand::StaticVariable(stamp));
1757 __ cmp(scratch, FieldOperand(object, JSDate::kCacheStampOffset));
1758 __ j(not_equal, &runtime, Label::kNear);
1759 __ mov(result, FieldOperand(object, JSDate::kValueOffset +
1760 kPointerSize * index->value()));
1761 __ jmp(&done, Label::kNear);
1764 __ PrepareCallCFunction(2, scratch);
1765 __ mov(Operand(esp, 0), object);
1766 __ mov(Operand(esp, 1 * kPointerSize), Immediate(index));
1767 __ CallCFunction(ExternalReference::get_date_field_function(isolate()), 2);
1773 Operand LCodeGen::BuildSeqStringOperand(Register string,
1775 String::Encoding encoding) {
1776 if (index->IsConstantOperand()) {
1777 int offset = ToRepresentation(LConstantOperand::cast(index),
1778 Representation::Integer32());
1779 if (encoding == String::TWO_BYTE_ENCODING) {
1780 offset *= kUC16Size;
1782 STATIC_ASSERT(kCharSize == 1);
1783 return FieldOperand(string, SeqString::kHeaderSize + offset);
1785 return FieldOperand(
1786 string, ToRegister(index),
1787 encoding == String::ONE_BYTE_ENCODING ? times_1 : times_2,
1788 SeqString::kHeaderSize);
1792 void LCodeGen::DoSeqStringGetChar(LSeqStringGetChar* instr) {
1793 String::Encoding encoding = instr->hydrogen()->encoding();
1794 Register result = ToRegister(instr->result());
1795 Register string = ToRegister(instr->string());
1797 if (FLAG_debug_code) {
1799 __ mov(string, FieldOperand(string, HeapObject::kMapOffset));
1800 __ movzx_b(string, FieldOperand(string, Map::kInstanceTypeOffset));
1802 __ and_(string, Immediate(kStringRepresentationMask | kStringEncodingMask));
1803 static const uint32_t one_byte_seq_type = kSeqStringTag | kOneByteStringTag;
1804 static const uint32_t two_byte_seq_type = kSeqStringTag | kTwoByteStringTag;
1805 __ cmp(string, Immediate(encoding == String::ONE_BYTE_ENCODING
1806 ? one_byte_seq_type : two_byte_seq_type));
1807 __ Check(equal, kUnexpectedStringType);
1811 Operand operand = BuildSeqStringOperand(string, instr->index(), encoding);
1812 if (encoding == String::ONE_BYTE_ENCODING) {
1813 __ movzx_b(result, operand);
1815 __ movzx_w(result, operand);
1820 void LCodeGen::DoSeqStringSetChar(LSeqStringSetChar* instr) {
1821 String::Encoding encoding = instr->hydrogen()->encoding();
1822 Register string = ToRegister(instr->string());
1824 if (FLAG_debug_code) {
1825 Register value = ToRegister(instr->value());
1826 Register index = ToRegister(instr->index());
1827 static const uint32_t one_byte_seq_type = kSeqStringTag | kOneByteStringTag;
1828 static const uint32_t two_byte_seq_type = kSeqStringTag | kTwoByteStringTag;
1830 instr->hydrogen()->encoding() == String::ONE_BYTE_ENCODING
1831 ? one_byte_seq_type : two_byte_seq_type;
1832 __ EmitSeqStringSetCharCheck(string, index, value, encoding_mask);
1835 Operand operand = BuildSeqStringOperand(string, instr->index(), encoding);
1836 if (instr->value()->IsConstantOperand()) {
1837 int value = ToRepresentation(LConstantOperand::cast(instr->value()),
1838 Representation::Integer32());
1839 DCHECK_LE(0, value);
1840 if (encoding == String::ONE_BYTE_ENCODING) {
1841 DCHECK_LE(value, String::kMaxOneByteCharCode);
1842 __ mov_b(operand, static_cast<int8_t>(value));
1844 DCHECK_LE(value, String::kMaxUtf16CodeUnit);
1845 __ mov_w(operand, static_cast<int16_t>(value));
1848 Register value = ToRegister(instr->value());
1849 if (encoding == String::ONE_BYTE_ENCODING) {
1850 __ mov_b(operand, value);
1852 __ mov_w(operand, value);
1858 void LCodeGen::DoAddI(LAddI* instr) {
1859 LOperand* left = instr->left();
1860 LOperand* right = instr->right();
1862 if (LAddI::UseLea(instr->hydrogen()) && !left->Equals(instr->result())) {
1863 if (right->IsConstantOperand()) {
1864 int32_t offset = ToRepresentation(LConstantOperand::cast(right),
1865 instr->hydrogen()->representation());
1866 __ lea(ToRegister(instr->result()), MemOperand(ToRegister(left), offset));
1868 Operand address(ToRegister(left), ToRegister(right), times_1, 0);
1869 __ lea(ToRegister(instr->result()), address);
1872 if (right->IsConstantOperand()) {
1873 __ add(ToOperand(left),
1874 ToImmediate(right, instr->hydrogen()->representation()));
1876 __ add(ToRegister(left), ToOperand(right));
1878 if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
1879 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1885 void LCodeGen::DoMathMinMax(LMathMinMax* instr) {
1886 LOperand* left = instr->left();
1887 LOperand* right = instr->right();
1888 DCHECK(left->Equals(instr->result()));
1889 HMathMinMax::Operation operation = instr->hydrogen()->operation();
1890 if (instr->hydrogen()->representation().IsSmiOrInteger32()) {
1892 Condition condition = (operation == HMathMinMax::kMathMin)
1895 if (right->IsConstantOperand()) {
1896 Operand left_op = ToOperand(left);
1897 Immediate immediate = ToImmediate(LConstantOperand::cast(instr->right()),
1898 instr->hydrogen()->representation());
1899 __ cmp(left_op, immediate);
1900 __ j(condition, &return_left, Label::kNear);
1901 __ mov(left_op, immediate);
1903 Register left_reg = ToRegister(left);
1904 Operand right_op = ToOperand(right);
1905 __ cmp(left_reg, right_op);
1906 __ j(condition, &return_left, Label::kNear);
1907 __ mov(left_reg, right_op);
1909 __ bind(&return_left);
1911 DCHECK(instr->hydrogen()->representation().IsDouble());
1912 Label check_nan_left, check_zero, return_left, return_right;
1913 Condition condition = (operation == HMathMinMax::kMathMin) ? below : above;
1914 XMMRegister left_reg = ToDoubleRegister(left);
1915 XMMRegister right_reg = ToDoubleRegister(right);
1916 __ ucomisd(left_reg, right_reg);
1917 __ j(parity_even, &check_nan_left, Label::kNear); // At least one NaN.
1918 __ j(equal, &check_zero, Label::kNear); // left == right.
1919 __ j(condition, &return_left, Label::kNear);
1920 __ jmp(&return_right, Label::kNear);
1922 __ bind(&check_zero);
1923 XMMRegister xmm_scratch = double_scratch0();
1924 __ xorps(xmm_scratch, xmm_scratch);
1925 __ ucomisd(left_reg, xmm_scratch);
1926 __ j(not_equal, &return_left, Label::kNear); // left == right != 0.
1927 // At this point, both left and right are either 0 or -0.
1928 if (operation == HMathMinMax::kMathMin) {
1929 __ orpd(left_reg, right_reg);
1931 // Since we operate on +0 and/or -0, addsd and andsd have the same effect.
1932 __ addsd(left_reg, right_reg);
1934 __ jmp(&return_left, Label::kNear);
1936 __ bind(&check_nan_left);
1937 __ ucomisd(left_reg, left_reg); // NaN check.
1938 __ j(parity_even, &return_left, Label::kNear); // left == NaN.
1939 __ bind(&return_right);
1940 __ movaps(left_reg, right_reg);
1942 __ bind(&return_left);
1947 void LCodeGen::DoArithmeticD(LArithmeticD* instr) {
1948 XMMRegister left = ToDoubleRegister(instr->left());
1949 XMMRegister right = ToDoubleRegister(instr->right());
1950 XMMRegister result = ToDoubleRegister(instr->result());
1951 switch (instr->op()) {
1953 if (CpuFeatures::IsSupported(AVX)) {
1954 CpuFeatureScope scope(masm(), AVX);
1955 __ vaddsd(result, left, right);
1957 DCHECK(result.is(left));
1958 __ addsd(left, right);
1962 if (CpuFeatures::IsSupported(AVX)) {
1963 CpuFeatureScope scope(masm(), AVX);
1964 __ vsubsd(result, left, right);
1966 DCHECK(result.is(left));
1967 __ subsd(left, right);
1971 if (CpuFeatures::IsSupported(AVX)) {
1972 CpuFeatureScope scope(masm(), AVX);
1973 __ vmulsd(result, left, right);
1975 DCHECK(result.is(left));
1976 __ mulsd(left, right);
1980 if (CpuFeatures::IsSupported(AVX)) {
1981 CpuFeatureScope scope(masm(), AVX);
1982 __ vdivsd(result, left, right);
1984 DCHECK(result.is(left));
1985 __ divsd(left, right);
1987 // Don't delete this mov. It may improve performance on some CPUs,
1988 // when there is a (v)mulsd depending on the result
1989 __ movaps(result, result);
1992 // Pass two doubles as arguments on the stack.
1993 __ PrepareCallCFunction(4, eax);
1994 __ movsd(Operand(esp, 0 * kDoubleSize), left);
1995 __ movsd(Operand(esp, 1 * kDoubleSize), right);
1997 ExternalReference::mod_two_doubles_operation(isolate()),
2000 // Return value is in st(0) on ia32.
2001 // Store it into the result register.
2002 __ sub(Operand(esp), Immediate(kDoubleSize));
2003 __ fstp_d(Operand(esp, 0));
2004 __ movsd(result, Operand(esp, 0));
2005 __ add(Operand(esp), Immediate(kDoubleSize));
2015 void LCodeGen::DoArithmeticT(LArithmeticT* instr) {
2016 DCHECK(ToRegister(instr->context()).is(esi));
2017 DCHECK(ToRegister(instr->left()).is(edx));
2018 DCHECK(ToRegister(instr->right()).is(eax));
2019 DCHECK(ToRegister(instr->result()).is(eax));
2022 CodeFactory::BinaryOpIC(isolate(), instr->op(), instr->strength()).code();
2023 CallCode(code, RelocInfo::CODE_TARGET, instr);
2027 template<class InstrType>
2028 void LCodeGen::EmitBranch(InstrType instr, Condition cc) {
2029 int left_block = instr->TrueDestination(chunk_);
2030 int right_block = instr->FalseDestination(chunk_);
2032 int next_block = GetNextEmittedBlock();
2034 if (right_block == left_block || cc == no_condition) {
2035 EmitGoto(left_block);
2036 } else if (left_block == next_block) {
2037 __ j(NegateCondition(cc), chunk_->GetAssemblyLabel(right_block));
2038 } else if (right_block == next_block) {
2039 __ j(cc, chunk_->GetAssemblyLabel(left_block));
2041 __ j(cc, chunk_->GetAssemblyLabel(left_block));
2042 __ jmp(chunk_->GetAssemblyLabel(right_block));
2047 template<class InstrType>
2048 void LCodeGen::EmitFalseBranch(InstrType instr, Condition cc) {
2049 int false_block = instr->FalseDestination(chunk_);
2050 if (cc == no_condition) {
2051 __ jmp(chunk_->GetAssemblyLabel(false_block));
2053 __ j(cc, chunk_->GetAssemblyLabel(false_block));
2058 void LCodeGen::DoBranch(LBranch* instr) {
2059 Representation r = instr->hydrogen()->value()->representation();
2060 if (r.IsSmiOrInteger32()) {
2061 Register reg = ToRegister(instr->value());
2062 __ test(reg, Operand(reg));
2063 EmitBranch(instr, not_zero);
2064 } else if (r.IsDouble()) {
2065 DCHECK(!info()->IsStub());
2066 XMMRegister reg = ToDoubleRegister(instr->value());
2067 XMMRegister xmm_scratch = double_scratch0();
2068 __ xorps(xmm_scratch, xmm_scratch);
2069 __ ucomisd(reg, xmm_scratch);
2070 EmitBranch(instr, not_equal);
2072 DCHECK(r.IsTagged());
2073 Register reg = ToRegister(instr->value());
2074 HType type = instr->hydrogen()->value()->type();
2075 if (type.IsBoolean()) {
2076 DCHECK(!info()->IsStub());
2077 __ cmp(reg, factory()->true_value());
2078 EmitBranch(instr, equal);
2079 } else if (type.IsSmi()) {
2080 DCHECK(!info()->IsStub());
2081 __ test(reg, Operand(reg));
2082 EmitBranch(instr, not_equal);
2083 } else if (type.IsJSArray()) {
2084 DCHECK(!info()->IsStub());
2085 EmitBranch(instr, no_condition);
2086 } else if (type.IsHeapNumber()) {
2087 DCHECK(!info()->IsStub());
2088 XMMRegister xmm_scratch = double_scratch0();
2089 __ xorps(xmm_scratch, xmm_scratch);
2090 __ ucomisd(xmm_scratch, FieldOperand(reg, HeapNumber::kValueOffset));
2091 EmitBranch(instr, not_equal);
2092 } else if (type.IsString()) {
2093 DCHECK(!info()->IsStub());
2094 __ cmp(FieldOperand(reg, String::kLengthOffset), Immediate(0));
2095 EmitBranch(instr, not_equal);
2097 ToBooleanStub::Types expected = instr->hydrogen()->expected_input_types();
2098 if (expected.IsEmpty()) expected = ToBooleanStub::Types::Generic();
2100 if (expected.Contains(ToBooleanStub::UNDEFINED)) {
2101 // undefined -> false.
2102 __ cmp(reg, factory()->undefined_value());
2103 __ j(equal, instr->FalseLabel(chunk_));
2105 if (expected.Contains(ToBooleanStub::BOOLEAN)) {
2107 __ cmp(reg, factory()->true_value());
2108 __ j(equal, instr->TrueLabel(chunk_));
2110 __ cmp(reg, factory()->false_value());
2111 __ j(equal, instr->FalseLabel(chunk_));
2113 if (expected.Contains(ToBooleanStub::NULL_TYPE)) {
2115 __ cmp(reg, factory()->null_value());
2116 __ j(equal, instr->FalseLabel(chunk_));
2119 if (expected.Contains(ToBooleanStub::SMI)) {
2120 // Smis: 0 -> false, all other -> true.
2121 __ test(reg, Operand(reg));
2122 __ j(equal, instr->FalseLabel(chunk_));
2123 __ JumpIfSmi(reg, instr->TrueLabel(chunk_));
2124 } else if (expected.NeedsMap()) {
2125 // If we need a map later and have a Smi -> deopt.
2126 __ test(reg, Immediate(kSmiTagMask));
2127 DeoptimizeIf(zero, instr, Deoptimizer::kSmi);
2130 Register map = no_reg; // Keep the compiler happy.
2131 if (expected.NeedsMap()) {
2132 map = ToRegister(instr->temp());
2133 DCHECK(!map.is(reg));
2134 __ mov(map, FieldOperand(reg, HeapObject::kMapOffset));
2136 if (expected.CanBeUndetectable()) {
2137 // Undetectable -> false.
2138 __ test_b(FieldOperand(map, Map::kBitFieldOffset),
2139 1 << Map::kIsUndetectable);
2140 __ j(not_zero, instr->FalseLabel(chunk_));
2144 if (expected.Contains(ToBooleanStub::SPEC_OBJECT)) {
2145 // spec object -> true.
2146 __ CmpInstanceType(map, FIRST_SPEC_OBJECT_TYPE);
2147 __ j(above_equal, instr->TrueLabel(chunk_));
2150 if (expected.Contains(ToBooleanStub::STRING)) {
2151 // String value -> false iff empty.
2153 __ CmpInstanceType(map, FIRST_NONSTRING_TYPE);
2154 __ j(above_equal, ¬_string, Label::kNear);
2155 __ cmp(FieldOperand(reg, String::kLengthOffset), Immediate(0));
2156 __ j(not_zero, instr->TrueLabel(chunk_));
2157 __ jmp(instr->FalseLabel(chunk_));
2158 __ bind(¬_string);
2161 if (expected.Contains(ToBooleanStub::SYMBOL)) {
2162 // Symbol value -> true.
2163 __ CmpInstanceType(map, SYMBOL_TYPE);
2164 __ j(equal, instr->TrueLabel(chunk_));
2167 if (expected.Contains(ToBooleanStub::SIMD_VALUE)) {
2168 // SIMD value -> true.
2169 __ CmpInstanceType(map, FLOAT32X4_TYPE);
2170 __ j(equal, instr->TrueLabel(chunk_));
2173 if (expected.Contains(ToBooleanStub::HEAP_NUMBER)) {
2174 // heap number -> false iff +0, -0, or NaN.
2175 Label not_heap_number;
2176 __ cmp(FieldOperand(reg, HeapObject::kMapOffset),
2177 factory()->heap_number_map());
2178 __ j(not_equal, ¬_heap_number, Label::kNear);
2179 XMMRegister xmm_scratch = double_scratch0();
2180 __ xorps(xmm_scratch, xmm_scratch);
2181 __ ucomisd(xmm_scratch, FieldOperand(reg, HeapNumber::kValueOffset));
2182 __ j(zero, instr->FalseLabel(chunk_));
2183 __ jmp(instr->TrueLabel(chunk_));
2184 __ bind(¬_heap_number);
2187 if (!expected.IsGeneric()) {
2188 // We've seen something for the first time -> deopt.
2189 // This can only happen if we are not generic already.
2190 DeoptimizeIf(no_condition, instr, Deoptimizer::kUnexpectedObject);
2197 void LCodeGen::EmitGoto(int block) {
2198 if (!IsNextEmittedBlock(block)) {
2199 __ jmp(chunk_->GetAssemblyLabel(LookupDestination(block)));
2204 void LCodeGen::DoGoto(LGoto* instr) {
2205 EmitGoto(instr->block_id());
2209 Condition LCodeGen::TokenToCondition(Token::Value op, bool is_unsigned) {
2210 Condition cond = no_condition;
2213 case Token::EQ_STRICT:
2217 case Token::NE_STRICT:
2221 cond = is_unsigned ? below : less;
2224 cond = is_unsigned ? above : greater;
2227 cond = is_unsigned ? below_equal : less_equal;
2230 cond = is_unsigned ? above_equal : greater_equal;
2233 case Token::INSTANCEOF:
2241 void LCodeGen::DoCompareNumericAndBranch(LCompareNumericAndBranch* instr) {
2242 LOperand* left = instr->left();
2243 LOperand* right = instr->right();
2245 instr->is_double() ||
2246 instr->hydrogen()->left()->CheckFlag(HInstruction::kUint32) ||
2247 instr->hydrogen()->right()->CheckFlag(HInstruction::kUint32);
2248 Condition cc = TokenToCondition(instr->op(), is_unsigned);
2250 if (left->IsConstantOperand() && right->IsConstantOperand()) {
2251 // We can statically evaluate the comparison.
2252 double left_val = ToDouble(LConstantOperand::cast(left));
2253 double right_val = ToDouble(LConstantOperand::cast(right));
2254 int next_block = EvalComparison(instr->op(), left_val, right_val) ?
2255 instr->TrueDestination(chunk_) : instr->FalseDestination(chunk_);
2256 EmitGoto(next_block);
2258 if (instr->is_double()) {
2259 __ ucomisd(ToDoubleRegister(left), ToDoubleRegister(right));
2260 // Don't base result on EFLAGS when a NaN is involved. Instead
2261 // jump to the false block.
2262 __ j(parity_even, instr->FalseLabel(chunk_));
2264 if (right->IsConstantOperand()) {
2265 __ cmp(ToOperand(left),
2266 ToImmediate(right, instr->hydrogen()->representation()));
2267 } else if (left->IsConstantOperand()) {
2268 __ cmp(ToOperand(right),
2269 ToImmediate(left, instr->hydrogen()->representation()));
2270 // We commuted the operands, so commute the condition.
2271 cc = CommuteCondition(cc);
2273 __ cmp(ToRegister(left), ToOperand(right));
2276 EmitBranch(instr, cc);
2281 void LCodeGen::DoCmpObjectEqAndBranch(LCmpObjectEqAndBranch* instr) {
2282 Register left = ToRegister(instr->left());
2284 if (instr->right()->IsConstantOperand()) {
2285 Handle<Object> right = ToHandle(LConstantOperand::cast(instr->right()));
2286 __ CmpObject(left, right);
2288 Operand right = ToOperand(instr->right());
2289 __ cmp(left, right);
2291 EmitBranch(instr, equal);
2295 void LCodeGen::DoCmpHoleAndBranch(LCmpHoleAndBranch* instr) {
2296 if (instr->hydrogen()->representation().IsTagged()) {
2297 Register input_reg = ToRegister(instr->object());
2298 __ cmp(input_reg, factory()->the_hole_value());
2299 EmitBranch(instr, equal);
2303 XMMRegister input_reg = ToDoubleRegister(instr->object());
2304 __ ucomisd(input_reg, input_reg);
2305 EmitFalseBranch(instr, parity_odd);
2307 __ sub(esp, Immediate(kDoubleSize));
2308 __ movsd(MemOperand(esp, 0), input_reg);
2310 __ add(esp, Immediate(kDoubleSize));
2311 int offset = sizeof(kHoleNanUpper32);
2312 __ cmp(MemOperand(esp, -offset), Immediate(kHoleNanUpper32));
2313 EmitBranch(instr, equal);
2317 void LCodeGen::DoCompareMinusZeroAndBranch(LCompareMinusZeroAndBranch* instr) {
2318 Representation rep = instr->hydrogen()->value()->representation();
2319 DCHECK(!rep.IsInteger32());
2320 Register scratch = ToRegister(instr->temp());
2322 if (rep.IsDouble()) {
2323 XMMRegister value = ToDoubleRegister(instr->value());
2324 XMMRegister xmm_scratch = double_scratch0();
2325 __ xorps(xmm_scratch, xmm_scratch);
2326 __ ucomisd(xmm_scratch, value);
2327 EmitFalseBranch(instr, not_equal);
2328 __ movmskpd(scratch, value);
2329 __ test(scratch, Immediate(1));
2330 EmitBranch(instr, not_zero);
2332 Register value = ToRegister(instr->value());
2333 Handle<Map> map = masm()->isolate()->factory()->heap_number_map();
2334 __ CheckMap(value, map, instr->FalseLabel(chunk()), DO_SMI_CHECK);
2335 __ cmp(FieldOperand(value, HeapNumber::kExponentOffset),
2337 EmitFalseBranch(instr, no_overflow);
2338 __ cmp(FieldOperand(value, HeapNumber::kMantissaOffset),
2339 Immediate(0x00000000));
2340 EmitBranch(instr, equal);
2345 Condition LCodeGen::EmitIsObject(Register input,
2347 Label* is_not_object,
2349 __ JumpIfSmi(input, is_not_object);
2351 __ cmp(input, isolate()->factory()->null_value());
2352 __ j(equal, is_object);
2354 __ mov(temp1, FieldOperand(input, HeapObject::kMapOffset));
2355 // Undetectable objects behave like undefined.
2356 __ test_b(FieldOperand(temp1, Map::kBitFieldOffset),
2357 1 << Map::kIsUndetectable);
2358 __ j(not_zero, is_not_object);
2360 __ movzx_b(temp1, FieldOperand(temp1, Map::kInstanceTypeOffset));
2361 __ cmp(temp1, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE);
2362 __ j(below, is_not_object);
2363 __ cmp(temp1, LAST_NONCALLABLE_SPEC_OBJECT_TYPE);
2368 void LCodeGen::DoIsObjectAndBranch(LIsObjectAndBranch* instr) {
2369 Register reg = ToRegister(instr->value());
2370 Register temp = ToRegister(instr->temp());
2372 Condition true_cond = EmitIsObject(
2373 reg, temp, instr->FalseLabel(chunk_), instr->TrueLabel(chunk_));
2375 EmitBranch(instr, true_cond);
2379 Condition LCodeGen::EmitIsString(Register input,
2381 Label* is_not_string,
2382 SmiCheck check_needed = INLINE_SMI_CHECK) {
2383 if (check_needed == INLINE_SMI_CHECK) {
2384 __ JumpIfSmi(input, is_not_string);
2387 Condition cond = masm_->IsObjectStringType(input, temp1, temp1);
2393 void LCodeGen::DoIsStringAndBranch(LIsStringAndBranch* instr) {
2394 Register reg = ToRegister(instr->value());
2395 Register temp = ToRegister(instr->temp());
2397 SmiCheck check_needed =
2398 instr->hydrogen()->value()->type().IsHeapObject()
2399 ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
2401 Condition true_cond = EmitIsString(
2402 reg, temp, instr->FalseLabel(chunk_), check_needed);
2404 EmitBranch(instr, true_cond);
2408 void LCodeGen::DoIsSmiAndBranch(LIsSmiAndBranch* instr) {
2409 Operand input = ToOperand(instr->value());
2411 __ test(input, Immediate(kSmiTagMask));
2412 EmitBranch(instr, zero);
2416 void LCodeGen::DoIsUndetectableAndBranch(LIsUndetectableAndBranch* instr) {
2417 Register input = ToRegister(instr->value());
2418 Register temp = ToRegister(instr->temp());
2420 if (!instr->hydrogen()->value()->type().IsHeapObject()) {
2421 STATIC_ASSERT(kSmiTag == 0);
2422 __ JumpIfSmi(input, instr->FalseLabel(chunk_));
2424 __ mov(temp, FieldOperand(input, HeapObject::kMapOffset));
2425 __ test_b(FieldOperand(temp, Map::kBitFieldOffset),
2426 1 << Map::kIsUndetectable);
2427 EmitBranch(instr, not_zero);
2431 static Condition ComputeCompareCondition(Token::Value op) {
2433 case Token::EQ_STRICT:
2443 return greater_equal;
2446 return no_condition;
2451 void LCodeGen::DoStringCompareAndBranch(LStringCompareAndBranch* instr) {
2452 Token::Value op = instr->op();
2455 CodeFactory::CompareIC(isolate(), op, Strength::WEAK).code();
2456 CallCode(ic, RelocInfo::CODE_TARGET, instr);
2458 Condition condition = ComputeCompareCondition(op);
2459 __ test(eax, Operand(eax));
2461 EmitBranch(instr, condition);
2465 static InstanceType TestType(HHasInstanceTypeAndBranch* instr) {
2466 InstanceType from = instr->from();
2467 InstanceType to = instr->to();
2468 if (from == FIRST_TYPE) return to;
2469 DCHECK(from == to || to == LAST_TYPE);
2474 static Condition BranchCondition(HHasInstanceTypeAndBranch* instr) {
2475 InstanceType from = instr->from();
2476 InstanceType to = instr->to();
2477 if (from == to) return equal;
2478 if (to == LAST_TYPE) return above_equal;
2479 if (from == FIRST_TYPE) return below_equal;
2485 void LCodeGen::DoHasInstanceTypeAndBranch(LHasInstanceTypeAndBranch* instr) {
2486 Register input = ToRegister(instr->value());
2487 Register temp = ToRegister(instr->temp());
2489 if (!instr->hydrogen()->value()->type().IsHeapObject()) {
2490 __ JumpIfSmi(input, instr->FalseLabel(chunk_));
2493 __ CmpObjectType(input, TestType(instr->hydrogen()), temp);
2494 EmitBranch(instr, BranchCondition(instr->hydrogen()));
2498 void LCodeGen::DoGetCachedArrayIndex(LGetCachedArrayIndex* instr) {
2499 Register input = ToRegister(instr->value());
2500 Register result = ToRegister(instr->result());
2502 __ AssertString(input);
2504 __ mov(result, FieldOperand(input, String::kHashFieldOffset));
2505 __ IndexFromHash(result, result);
2509 void LCodeGen::DoHasCachedArrayIndexAndBranch(
2510 LHasCachedArrayIndexAndBranch* instr) {
2511 Register input = ToRegister(instr->value());
2513 __ test(FieldOperand(input, String::kHashFieldOffset),
2514 Immediate(String::kContainsCachedArrayIndexMask));
2515 EmitBranch(instr, equal);
2519 // Branches to a label or falls through with the answer in the z flag. Trashes
2520 // the temp registers, but not the input.
2521 void LCodeGen::EmitClassOfTest(Label* is_true,
2523 Handle<String>class_name,
2527 DCHECK(!input.is(temp));
2528 DCHECK(!input.is(temp2));
2529 DCHECK(!temp.is(temp2));
2530 __ JumpIfSmi(input, is_false);
2532 if (String::Equals(isolate()->factory()->Function_string(), class_name)) {
2533 // Assuming the following assertions, we can use the same compares to test
2534 // for both being a function type and being in the object type range.
2535 STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
2536 STATIC_ASSERT(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE ==
2537 FIRST_SPEC_OBJECT_TYPE + 1);
2538 STATIC_ASSERT(LAST_NONCALLABLE_SPEC_OBJECT_TYPE ==
2539 LAST_SPEC_OBJECT_TYPE - 1);
2540 STATIC_ASSERT(LAST_SPEC_OBJECT_TYPE == LAST_TYPE);
2541 __ CmpObjectType(input, FIRST_SPEC_OBJECT_TYPE, temp);
2542 __ j(below, is_false);
2543 __ j(equal, is_true);
2544 __ CmpInstanceType(temp, LAST_SPEC_OBJECT_TYPE);
2545 __ j(equal, is_true);
2547 // Faster code path to avoid two compares: subtract lower bound from the
2548 // actual type and do a signed compare with the width of the type range.
2549 __ mov(temp, FieldOperand(input, HeapObject::kMapOffset));
2550 __ movzx_b(temp2, FieldOperand(temp, Map::kInstanceTypeOffset));
2551 __ sub(Operand(temp2), Immediate(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE));
2552 __ cmp(Operand(temp2), Immediate(LAST_NONCALLABLE_SPEC_OBJECT_TYPE -
2553 FIRST_NONCALLABLE_SPEC_OBJECT_TYPE));
2554 __ j(above, is_false);
2557 // Now we are in the FIRST-LAST_NONCALLABLE_SPEC_OBJECT_TYPE range.
2558 // Check if the constructor in the map is a function.
2559 __ GetMapConstructor(temp, temp, temp2);
2560 // Objects with a non-function constructor have class 'Object'.
2561 __ CmpInstanceType(temp2, JS_FUNCTION_TYPE);
2562 if (String::Equals(class_name, isolate()->factory()->Object_string())) {
2563 __ j(not_equal, is_true);
2565 __ j(not_equal, is_false);
2568 // temp now contains the constructor function. Grab the
2569 // instance class name from there.
2570 __ mov(temp, FieldOperand(temp, JSFunction::kSharedFunctionInfoOffset));
2571 __ mov(temp, FieldOperand(temp,
2572 SharedFunctionInfo::kInstanceClassNameOffset));
2573 // The class name we are testing against is internalized since it's a literal.
2574 // The name in the constructor is internalized because of the way the context
2575 // is booted. This routine isn't expected to work for random API-created
2576 // classes and it doesn't have to because you can't access it with natives
2577 // syntax. Since both sides are internalized it is sufficient to use an
2578 // identity comparison.
2579 __ cmp(temp, class_name);
2580 // End with the answer in the z flag.
2584 void LCodeGen::DoClassOfTestAndBranch(LClassOfTestAndBranch* instr) {
2585 Register input = ToRegister(instr->value());
2586 Register temp = ToRegister(instr->temp());
2587 Register temp2 = ToRegister(instr->temp2());
2589 Handle<String> class_name = instr->hydrogen()->class_name();
2591 EmitClassOfTest(instr->TrueLabel(chunk_), instr->FalseLabel(chunk_),
2592 class_name, input, temp, temp2);
2594 EmitBranch(instr, equal);
2598 void LCodeGen::DoCmpMapAndBranch(LCmpMapAndBranch* instr) {
2599 Register reg = ToRegister(instr->value());
2600 __ cmp(FieldOperand(reg, HeapObject::kMapOffset), instr->map());
2601 EmitBranch(instr, equal);
2605 void LCodeGen::DoInstanceOf(LInstanceOf* instr) {
2606 // Object and function are in fixed registers defined by the stub.
2607 DCHECK(ToRegister(instr->context()).is(esi));
2608 InstanceofStub stub(isolate(), InstanceofStub::kArgsInRegisters);
2609 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
2611 Label true_value, done;
2612 __ test(eax, Operand(eax));
2613 __ j(zero, &true_value, Label::kNear);
2614 __ mov(ToRegister(instr->result()), factory()->false_value());
2615 __ jmp(&done, Label::kNear);
2616 __ bind(&true_value);
2617 __ mov(ToRegister(instr->result()), factory()->true_value());
2622 void LCodeGen::DoInstanceOfKnownGlobal(LInstanceOfKnownGlobal* instr) {
2623 class DeferredInstanceOfKnownGlobal final : public LDeferredCode {
2625 DeferredInstanceOfKnownGlobal(LCodeGen* codegen,
2626 LInstanceOfKnownGlobal* instr)
2627 : LDeferredCode(codegen), instr_(instr) { }
2628 void Generate() override {
2629 codegen()->DoDeferredInstanceOfKnownGlobal(instr_, &map_check_);
2631 LInstruction* instr() override { return instr_; }
2632 Label* map_check() { return &map_check_; }
2634 LInstanceOfKnownGlobal* instr_;
2638 DeferredInstanceOfKnownGlobal* deferred;
2639 deferred = new(zone()) DeferredInstanceOfKnownGlobal(this, instr);
2641 Label done, false_result;
2642 Register object = ToRegister(instr->value());
2643 Register temp = ToRegister(instr->temp());
2645 // A Smi is not an instance of anything.
2646 __ JumpIfSmi(object, &false_result, Label::kNear);
2648 // This is the inlined call site instanceof cache. The two occurences of the
2649 // hole value will be patched to the last map/result pair generated by the
2652 Register map = ToRegister(instr->temp());
2653 __ mov(map, FieldOperand(object, HeapObject::kMapOffset));
2654 __ bind(deferred->map_check()); // Label for calculating code patching.
2655 Handle<Cell> cache_cell = factory()->NewCell(factory()->the_hole_value());
2656 __ cmp(map, Operand::ForCell(cache_cell)); // Patched to cached map.
2657 __ j(not_equal, &cache_miss, Label::kNear);
2658 __ mov(eax, factory()->the_hole_value()); // Patched to either true or false.
2659 __ jmp(&done, Label::kNear);
2661 // The inlined call site cache did not match. Check for null and string
2662 // before calling the deferred code.
2663 __ bind(&cache_miss);
2664 // Null is not an instance of anything.
2665 __ cmp(object, factory()->null_value());
2666 __ j(equal, &false_result, Label::kNear);
2668 // String values are not instances of anything.
2669 Condition is_string = masm_->IsObjectStringType(object, temp, temp);
2670 __ j(is_string, &false_result, Label::kNear);
2672 // Go to the deferred code.
2673 __ jmp(deferred->entry());
2675 __ bind(&false_result);
2676 __ mov(ToRegister(instr->result()), factory()->false_value());
2678 // Here result has either true or false. Deferred code also produces true or
2680 __ bind(deferred->exit());
2685 void LCodeGen::DoDeferredInstanceOfKnownGlobal(LInstanceOfKnownGlobal* instr,
2687 PushSafepointRegistersScope scope(this);
2689 InstanceofStub::Flags flags = InstanceofStub::kNoFlags;
2690 flags = static_cast<InstanceofStub::Flags>(
2691 flags | InstanceofStub::kArgsInRegisters);
2692 flags = static_cast<InstanceofStub::Flags>(
2693 flags | InstanceofStub::kCallSiteInlineCheck);
2694 flags = static_cast<InstanceofStub::Flags>(
2695 flags | InstanceofStub::kReturnTrueFalseObject);
2696 InstanceofStub stub(isolate(), flags);
2698 // Get the temp register reserved by the instruction. This needs to be a
2699 // register which is pushed last by PushSafepointRegisters as top of the
2700 // stack is used to pass the offset to the location of the map check to
2702 Register temp = ToRegister(instr->temp());
2703 DCHECK(MacroAssembler::SafepointRegisterStackIndex(temp) == 0);
2704 __ LoadHeapObject(InstanceofStub::right(), instr->function());
2705 static const int kAdditionalDelta = 13;
2706 int delta = masm_->SizeOfCodeGeneratedSince(map_check) + kAdditionalDelta;
2707 __ mov(temp, Immediate(delta));
2708 __ StoreToSafepointRegisterSlot(temp, temp);
2709 CallCodeGeneric(stub.GetCode(),
2710 RelocInfo::CODE_TARGET,
2712 RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
2713 // Get the deoptimization index of the LLazyBailout-environment that
2714 // corresponds to this instruction.
2715 LEnvironment* env = instr->GetDeferredLazyDeoptimizationEnvironment();
2716 safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
2718 // Put the result value into the eax slot and restore all registers.
2719 __ StoreToSafepointRegisterSlot(eax, eax);
2723 void LCodeGen::DoCmpT(LCmpT* instr) {
2724 Token::Value op = instr->op();
2727 CodeFactory::CompareIC(isolate(), op, instr->strength()).code();
2728 CallCode(ic, RelocInfo::CODE_TARGET, instr);
2730 Condition condition = ComputeCompareCondition(op);
2731 Label true_value, done;
2732 __ test(eax, Operand(eax));
2733 __ j(condition, &true_value, Label::kNear);
2734 __ mov(ToRegister(instr->result()), factory()->false_value());
2735 __ jmp(&done, Label::kNear);
2736 __ bind(&true_value);
2737 __ mov(ToRegister(instr->result()), factory()->true_value());
2742 void LCodeGen::EmitReturn(LReturn* instr, bool dynamic_frame_alignment) {
2743 int extra_value_count = dynamic_frame_alignment ? 2 : 1;
2745 if (instr->has_constant_parameter_count()) {
2746 int parameter_count = ToInteger32(instr->constant_parameter_count());
2747 if (dynamic_frame_alignment && FLAG_debug_code) {
2749 (parameter_count + extra_value_count) * kPointerSize),
2750 Immediate(kAlignmentZapValue));
2751 __ Assert(equal, kExpectedAlignmentMarker);
2753 __ Ret((parameter_count + extra_value_count) * kPointerSize, ecx);
2755 DCHECK(info()->IsStub()); // Functions would need to drop one more value.
2756 Register reg = ToRegister(instr->parameter_count());
2757 // The argument count parameter is a smi
2759 Register return_addr_reg = reg.is(ecx) ? ebx : ecx;
2760 if (dynamic_frame_alignment && FLAG_debug_code) {
2761 DCHECK(extra_value_count == 2);
2762 __ cmp(Operand(esp, reg, times_pointer_size,
2763 extra_value_count * kPointerSize),
2764 Immediate(kAlignmentZapValue));
2765 __ Assert(equal, kExpectedAlignmentMarker);
2768 // emit code to restore stack based on instr->parameter_count()
2769 __ pop(return_addr_reg); // save return address
2770 if (dynamic_frame_alignment) {
2771 __ inc(reg); // 1 more for alignment
2774 __ shl(reg, kPointerSizeLog2);
2776 __ jmp(return_addr_reg);
2781 void LCodeGen::DoReturn(LReturn* instr) {
2782 if (FLAG_trace && info()->IsOptimizing()) {
2783 // Preserve the return value on the stack and rely on the runtime call
2784 // to return the value in the same register. We're leaving the code
2785 // managed by the register allocator and tearing down the frame, it's
2786 // safe to write to the context register.
2788 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
2789 __ CallRuntime(Runtime::kTraceExit, 1);
2791 if (info()->saves_caller_doubles()) RestoreCallerDoubles();
2792 if (dynamic_frame_alignment_) {
2793 // Fetch the state of the dynamic frame alignment.
2794 __ mov(edx, Operand(ebp,
2795 JavaScriptFrameConstants::kDynamicAlignmentStateOffset));
2797 int no_frame_start = -1;
2798 if (NeedsEagerFrame()) {
2801 no_frame_start = masm_->pc_offset();
2803 if (dynamic_frame_alignment_) {
2805 __ cmp(edx, Immediate(kNoAlignmentPadding));
2806 __ j(equal, &no_padding, Label::kNear);
2808 EmitReturn(instr, true);
2809 __ bind(&no_padding);
2812 EmitReturn(instr, false);
2813 if (no_frame_start != -1) {
2814 info()->AddNoFrameRange(no_frame_start, masm_->pc_offset());
2820 void LCodeGen::EmitVectorLoadICRegisters(T* instr) {
2821 Register vector_register = ToRegister(instr->temp_vector());
2822 Register slot_register = LoadWithVectorDescriptor::SlotRegister();
2823 DCHECK(vector_register.is(LoadWithVectorDescriptor::VectorRegister()));
2824 DCHECK(slot_register.is(eax));
2826 AllowDeferredHandleDereference vector_structure_check;
2827 Handle<TypeFeedbackVector> vector = instr->hydrogen()->feedback_vector();
2828 __ mov(vector_register, vector);
2829 // No need to allocate this register.
2830 FeedbackVectorICSlot slot = instr->hydrogen()->slot();
2831 int index = vector->GetIndex(slot);
2832 __ mov(slot_register, Immediate(Smi::FromInt(index)));
2837 void LCodeGen::EmitVectorStoreICRegisters(T* instr) {
2838 Register vector_register = ToRegister(instr->temp_vector());
2839 Register slot_register = ToRegister(instr->temp_slot());
2841 AllowDeferredHandleDereference vector_structure_check;
2842 Handle<TypeFeedbackVector> vector = instr->hydrogen()->feedback_vector();
2843 __ mov(vector_register, vector);
2844 FeedbackVectorICSlot slot = instr->hydrogen()->slot();
2845 int index = vector->GetIndex(slot);
2846 __ mov(slot_register, Immediate(Smi::FromInt(index)));
2850 void LCodeGen::DoLoadGlobalGeneric(LLoadGlobalGeneric* instr) {
2851 DCHECK(ToRegister(instr->context()).is(esi));
2852 DCHECK(ToRegister(instr->global_object())
2853 .is(LoadDescriptor::ReceiverRegister()));
2854 DCHECK(ToRegister(instr->result()).is(eax));
2856 __ mov(LoadDescriptor::NameRegister(), instr->name());
2857 EmitVectorLoadICRegisters<LLoadGlobalGeneric>(instr);
2859 CodeFactory::LoadICInOptimizedCode(isolate(), instr->typeof_mode(),
2860 SLOPPY, PREMONOMORPHIC).code();
2861 CallCode(ic, RelocInfo::CODE_TARGET, instr);
2865 void LCodeGen::DoLoadContextSlot(LLoadContextSlot* instr) {
2866 Register context = ToRegister(instr->context());
2867 Register result = ToRegister(instr->result());
2868 __ mov(result, ContextOperand(context, instr->slot_index()));
2870 if (instr->hydrogen()->RequiresHoleCheck()) {
2871 __ cmp(result, factory()->the_hole_value());
2872 if (instr->hydrogen()->DeoptimizesOnHole()) {
2873 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
2876 __ j(not_equal, &is_not_hole, Label::kNear);
2877 __ mov(result, factory()->undefined_value());
2878 __ bind(&is_not_hole);
2884 void LCodeGen::DoStoreContextSlot(LStoreContextSlot* instr) {
2885 Register context = ToRegister(instr->context());
2886 Register value = ToRegister(instr->value());
2888 Label skip_assignment;
2890 Operand target = ContextOperand(context, instr->slot_index());
2891 if (instr->hydrogen()->RequiresHoleCheck()) {
2892 __ cmp(target, factory()->the_hole_value());
2893 if (instr->hydrogen()->DeoptimizesOnHole()) {
2894 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
2896 __ j(not_equal, &skip_assignment, Label::kNear);
2900 __ mov(target, value);
2901 if (instr->hydrogen()->NeedsWriteBarrier()) {
2902 SmiCheck check_needed =
2903 instr->hydrogen()->value()->type().IsHeapObject()
2904 ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
2905 Register temp = ToRegister(instr->temp());
2906 int offset = Context::SlotOffset(instr->slot_index());
2907 __ RecordWriteContextSlot(context,
2912 EMIT_REMEMBERED_SET,
2916 __ bind(&skip_assignment);
2920 void LCodeGen::DoLoadNamedField(LLoadNamedField* instr) {
2921 HObjectAccess access = instr->hydrogen()->access();
2922 int offset = access.offset();
2924 if (access.IsExternalMemory()) {
2925 Register result = ToRegister(instr->result());
2926 MemOperand operand = instr->object()->IsConstantOperand()
2927 ? MemOperand::StaticVariable(ToExternalReference(
2928 LConstantOperand::cast(instr->object())))
2929 : MemOperand(ToRegister(instr->object()), offset);
2930 __ Load(result, operand, access.representation());
2934 Register object = ToRegister(instr->object());
2935 if (instr->hydrogen()->representation().IsDouble()) {
2936 XMMRegister result = ToDoubleRegister(instr->result());
2937 __ movsd(result, FieldOperand(object, offset));
2941 Register result = ToRegister(instr->result());
2942 if (!access.IsInobject()) {
2943 __ mov(result, FieldOperand(object, JSObject::kPropertiesOffset));
2946 __ Load(result, FieldOperand(object, offset), access.representation());
2950 void LCodeGen::EmitPushTaggedOperand(LOperand* operand) {
2951 DCHECK(!operand->IsDoubleRegister());
2952 if (operand->IsConstantOperand()) {
2953 Handle<Object> object = ToHandle(LConstantOperand::cast(operand));
2954 AllowDeferredHandleDereference smi_check;
2955 if (object->IsSmi()) {
2956 __ Push(Handle<Smi>::cast(object));
2958 __ PushHeapObject(Handle<HeapObject>::cast(object));
2960 } else if (operand->IsRegister()) {
2961 __ push(ToRegister(operand));
2963 __ push(ToOperand(operand));
2968 void LCodeGen::DoLoadNamedGeneric(LLoadNamedGeneric* instr) {
2969 DCHECK(ToRegister(instr->context()).is(esi));
2970 DCHECK(ToRegister(instr->object()).is(LoadDescriptor::ReceiverRegister()));
2971 DCHECK(ToRegister(instr->result()).is(eax));
2973 __ mov(LoadDescriptor::NameRegister(), instr->name());
2974 EmitVectorLoadICRegisters<LLoadNamedGeneric>(instr);
2976 CodeFactory::LoadICInOptimizedCode(
2977 isolate(), NOT_INSIDE_TYPEOF, instr->hydrogen()->language_mode(),
2978 instr->hydrogen()->initialization_state()).code();
2979 CallCode(ic, RelocInfo::CODE_TARGET, instr);
2983 void LCodeGen::DoLoadFunctionPrototype(LLoadFunctionPrototype* instr) {
2984 Register function = ToRegister(instr->function());
2985 Register temp = ToRegister(instr->temp());
2986 Register result = ToRegister(instr->result());
2988 // Get the prototype or initial map from the function.
2990 FieldOperand(function, JSFunction::kPrototypeOrInitialMapOffset));
2992 // Check that the function has a prototype or an initial map.
2993 __ cmp(Operand(result), Immediate(factory()->the_hole_value()));
2994 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
2996 // If the function does not have an initial map, we're done.
2998 __ CmpObjectType(result, MAP_TYPE, temp);
2999 __ j(not_equal, &done, Label::kNear);
3001 // Get the prototype from the initial map.
3002 __ mov(result, FieldOperand(result, Map::kPrototypeOffset));
3009 void LCodeGen::DoLoadRoot(LLoadRoot* instr) {
3010 Register result = ToRegister(instr->result());
3011 __ LoadRoot(result, instr->index());
3015 void LCodeGen::DoAccessArgumentsAt(LAccessArgumentsAt* instr) {
3016 Register arguments = ToRegister(instr->arguments());
3017 Register result = ToRegister(instr->result());
3018 if (instr->length()->IsConstantOperand() &&
3019 instr->index()->IsConstantOperand()) {
3020 int const_index = ToInteger32(LConstantOperand::cast(instr->index()));
3021 int const_length = ToInteger32(LConstantOperand::cast(instr->length()));
3022 int index = (const_length - const_index) + 1;
3023 __ mov(result, Operand(arguments, index * kPointerSize));
3025 Register length = ToRegister(instr->length());
3026 Operand index = ToOperand(instr->index());
3027 // There are two words between the frame pointer and the last argument.
3028 // Subtracting from length accounts for one of them add one more.
3029 __ sub(length, index);
3030 __ mov(result, Operand(arguments, length, times_4, kPointerSize));
3035 void LCodeGen::DoLoadKeyedExternalArray(LLoadKeyed* instr) {
3036 ElementsKind elements_kind = instr->elements_kind();
3037 LOperand* key = instr->key();
3038 if (!key->IsConstantOperand() &&
3039 ExternalArrayOpRequiresTemp(instr->hydrogen()->key()->representation(),
3041 __ SmiUntag(ToRegister(key));
3043 Operand operand(BuildFastArrayOperand(
3046 instr->hydrogen()->key()->representation(),
3048 instr->base_offset()));
3049 if (elements_kind == EXTERNAL_FLOAT32_ELEMENTS ||
3050 elements_kind == FLOAT32_ELEMENTS) {
3051 XMMRegister result(ToDoubleRegister(instr->result()));
3052 __ movss(result, operand);
3053 __ cvtss2sd(result, result);
3054 } else if (elements_kind == EXTERNAL_FLOAT64_ELEMENTS ||
3055 elements_kind == FLOAT64_ELEMENTS) {
3056 __ movsd(ToDoubleRegister(instr->result()), operand);
3058 Register result(ToRegister(instr->result()));
3059 switch (elements_kind) {
3060 case EXTERNAL_INT8_ELEMENTS:
3062 __ movsx_b(result, operand);
3064 case EXTERNAL_UINT8_CLAMPED_ELEMENTS:
3065 case EXTERNAL_UINT8_ELEMENTS:
3066 case UINT8_ELEMENTS:
3067 case UINT8_CLAMPED_ELEMENTS:
3068 __ movzx_b(result, operand);
3070 case EXTERNAL_INT16_ELEMENTS:
3071 case INT16_ELEMENTS:
3072 __ movsx_w(result, operand);
3074 case EXTERNAL_UINT16_ELEMENTS:
3075 case UINT16_ELEMENTS:
3076 __ movzx_w(result, operand);
3078 case EXTERNAL_INT32_ELEMENTS:
3079 case INT32_ELEMENTS:
3080 __ mov(result, operand);
3082 case EXTERNAL_UINT32_ELEMENTS:
3083 case UINT32_ELEMENTS:
3084 __ mov(result, operand);
3085 if (!instr->hydrogen()->CheckFlag(HInstruction::kUint32)) {
3086 __ test(result, Operand(result));
3087 DeoptimizeIf(negative, instr, Deoptimizer::kNegativeValue);
3090 case EXTERNAL_FLOAT32_ELEMENTS:
3091 case EXTERNAL_FLOAT64_ELEMENTS:
3092 case FLOAT32_ELEMENTS:
3093 case FLOAT64_ELEMENTS:
3094 case FAST_SMI_ELEMENTS:
3096 case FAST_DOUBLE_ELEMENTS:
3097 case FAST_HOLEY_SMI_ELEMENTS:
3098 case FAST_HOLEY_ELEMENTS:
3099 case FAST_HOLEY_DOUBLE_ELEMENTS:
3100 case DICTIONARY_ELEMENTS:
3101 case FAST_SLOPPY_ARGUMENTS_ELEMENTS:
3102 case SLOW_SLOPPY_ARGUMENTS_ELEMENTS:
3110 void LCodeGen::DoLoadKeyedFixedDoubleArray(LLoadKeyed* instr) {
3111 if (instr->hydrogen()->RequiresHoleCheck()) {
3112 Operand hole_check_operand = BuildFastArrayOperand(
3113 instr->elements(), instr->key(),
3114 instr->hydrogen()->key()->representation(),
3115 FAST_DOUBLE_ELEMENTS,
3116 instr->base_offset() + sizeof(kHoleNanLower32));
3117 __ cmp(hole_check_operand, Immediate(kHoleNanUpper32));
3118 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3121 Operand double_load_operand = BuildFastArrayOperand(
3124 instr->hydrogen()->key()->representation(),
3125 FAST_DOUBLE_ELEMENTS,
3126 instr->base_offset());
3127 XMMRegister result = ToDoubleRegister(instr->result());
3128 __ movsd(result, double_load_operand);
3132 void LCodeGen::DoLoadKeyedFixedArray(LLoadKeyed* instr) {
3133 Register result = ToRegister(instr->result());
3137 BuildFastArrayOperand(instr->elements(), instr->key(),
3138 instr->hydrogen()->key()->representation(),
3139 FAST_ELEMENTS, instr->base_offset()));
3141 // Check for the hole value.
3142 if (instr->hydrogen()->RequiresHoleCheck()) {
3143 if (IsFastSmiElementsKind(instr->hydrogen()->elements_kind())) {
3144 __ test(result, Immediate(kSmiTagMask));
3145 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotASmi);
3147 __ cmp(result, factory()->the_hole_value());
3148 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3150 } else if (instr->hydrogen()->hole_mode() == CONVERT_HOLE_TO_UNDEFINED) {
3151 DCHECK(instr->hydrogen()->elements_kind() == FAST_HOLEY_ELEMENTS);
3153 __ cmp(result, factory()->the_hole_value());
3154 __ j(not_equal, &done);
3155 if (info()->IsStub()) {
3156 // A stub can safely convert the hole to undefined only if the array
3157 // protector cell contains (Smi) Isolate::kArrayProtectorValid. Otherwise
3158 // it needs to bail out.
3159 __ mov(result, isolate()->factory()->array_protector());
3160 __ cmp(FieldOperand(result, PropertyCell::kValueOffset),
3161 Immediate(Smi::FromInt(Isolate::kArrayProtectorValid)));
3162 DeoptimizeIf(not_equal, instr, Deoptimizer::kHole);
3164 __ mov(result, isolate()->factory()->undefined_value());
3170 void LCodeGen::DoLoadKeyed(LLoadKeyed* instr) {
3171 if (instr->is_typed_elements()) {
3172 DoLoadKeyedExternalArray(instr);
3173 } else if (instr->hydrogen()->representation().IsDouble()) {
3174 DoLoadKeyedFixedDoubleArray(instr);
3176 DoLoadKeyedFixedArray(instr);
3181 Operand LCodeGen::BuildFastArrayOperand(
3182 LOperand* elements_pointer,
3184 Representation key_representation,
3185 ElementsKind elements_kind,
3186 uint32_t base_offset) {
3187 Register elements_pointer_reg = ToRegister(elements_pointer);
3188 int element_shift_size = ElementsKindToShiftSize(elements_kind);
3189 int shift_size = element_shift_size;
3190 if (key->IsConstantOperand()) {
3191 int constant_value = ToInteger32(LConstantOperand::cast(key));
3192 if (constant_value & 0xF0000000) {
3193 Abort(kArrayIndexConstantValueTooBig);
3195 return Operand(elements_pointer_reg,
3196 ((constant_value) << shift_size)
3199 // Take the tag bit into account while computing the shift size.
3200 if (key_representation.IsSmi() && (shift_size >= 1)) {
3201 shift_size -= kSmiTagSize;
3203 ScaleFactor scale_factor = static_cast<ScaleFactor>(shift_size);
3204 return Operand(elements_pointer_reg,
3212 void LCodeGen::DoLoadKeyedGeneric(LLoadKeyedGeneric* instr) {
3213 DCHECK(ToRegister(instr->context()).is(esi));
3214 DCHECK(ToRegister(instr->object()).is(LoadDescriptor::ReceiverRegister()));
3215 DCHECK(ToRegister(instr->key()).is(LoadDescriptor::NameRegister()));
3217 if (instr->hydrogen()->HasVectorAndSlot()) {
3218 EmitVectorLoadICRegisters<LLoadKeyedGeneric>(instr);
3221 Handle<Code> ic = CodeFactory::KeyedLoadICInOptimizedCode(
3222 isolate(), instr->hydrogen()->language_mode(),
3223 instr->hydrogen()->initialization_state()).code();
3224 CallCode(ic, RelocInfo::CODE_TARGET, instr);
3228 void LCodeGen::DoArgumentsElements(LArgumentsElements* instr) {
3229 Register result = ToRegister(instr->result());
3231 if (instr->hydrogen()->from_inlined()) {
3232 __ lea(result, Operand(esp, -2 * kPointerSize));
3234 // Check for arguments adapter frame.
3235 Label done, adapted;
3236 __ mov(result, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3237 __ mov(result, Operand(result, StandardFrameConstants::kContextOffset));
3238 __ cmp(Operand(result),
3239 Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
3240 __ j(equal, &adapted, Label::kNear);
3242 // No arguments adaptor frame.
3243 __ mov(result, Operand(ebp));
3244 __ jmp(&done, Label::kNear);
3246 // Arguments adaptor frame present.
3248 __ mov(result, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3250 // Result is the frame pointer for the frame if not adapted and for the real
3251 // frame below the adaptor frame if adapted.
3257 void LCodeGen::DoArgumentsLength(LArgumentsLength* instr) {
3258 Operand elem = ToOperand(instr->elements());
3259 Register result = ToRegister(instr->result());
3263 // If no arguments adaptor frame the number of arguments is fixed.
3265 __ mov(result, Immediate(scope()->num_parameters()));
3266 __ j(equal, &done, Label::kNear);
3268 // Arguments adaptor frame present. Get argument length from there.
3269 __ mov(result, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3270 __ mov(result, Operand(result,
3271 ArgumentsAdaptorFrameConstants::kLengthOffset));
3272 __ SmiUntag(result);
3274 // Argument length is in result register.
3279 void LCodeGen::DoWrapReceiver(LWrapReceiver* instr) {
3280 Register receiver = ToRegister(instr->receiver());
3281 Register function = ToRegister(instr->function());
3283 // If the receiver is null or undefined, we have to pass the global
3284 // object as a receiver to normal functions. Values have to be
3285 // passed unchanged to builtins and strict-mode functions.
3286 Label receiver_ok, global_object;
3287 Label::Distance dist = DeoptEveryNTimes() ? Label::kFar : Label::kNear;
3288 Register scratch = ToRegister(instr->temp());
3290 if (!instr->hydrogen()->known_function()) {
3291 // Do not transform the receiver to object for strict mode
3294 FieldOperand(function, JSFunction::kSharedFunctionInfoOffset));
3295 __ test_b(FieldOperand(scratch, SharedFunctionInfo::kStrictModeByteOffset),
3296 1 << SharedFunctionInfo::kStrictModeBitWithinByte);
3297 __ j(not_equal, &receiver_ok, dist);
3299 // Do not transform the receiver to object for builtins.
3300 __ test_b(FieldOperand(scratch, SharedFunctionInfo::kNativeByteOffset),
3301 1 << SharedFunctionInfo::kNativeBitWithinByte);
3302 __ j(not_equal, &receiver_ok, dist);
3305 // Normal function. Replace undefined or null with global receiver.
3306 __ cmp(receiver, factory()->null_value());
3307 __ j(equal, &global_object, Label::kNear);
3308 __ cmp(receiver, factory()->undefined_value());
3309 __ j(equal, &global_object, Label::kNear);
3311 // The receiver should be a JS object.
3312 __ test(receiver, Immediate(kSmiTagMask));
3313 DeoptimizeIf(equal, instr, Deoptimizer::kSmi);
3314 __ CmpObjectType(receiver, FIRST_SPEC_OBJECT_TYPE, scratch);
3315 DeoptimizeIf(below, instr, Deoptimizer::kNotAJavaScriptObject);
3317 __ jmp(&receiver_ok, Label::kNear);
3318 __ bind(&global_object);
3319 __ mov(receiver, FieldOperand(function, JSFunction::kContextOffset));
3320 const int global_offset = Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX);
3321 __ mov(receiver, Operand(receiver, global_offset));
3322 const int proxy_offset = GlobalObject::kGlobalProxyOffset;
3323 __ mov(receiver, FieldOperand(receiver, proxy_offset));
3324 __ bind(&receiver_ok);
3328 void LCodeGen::DoApplyArguments(LApplyArguments* instr) {
3329 Register receiver = ToRegister(instr->receiver());
3330 Register function = ToRegister(instr->function());
3331 Register length = ToRegister(instr->length());
3332 Register elements = ToRegister(instr->elements());
3333 DCHECK(receiver.is(eax)); // Used for parameter count.
3334 DCHECK(function.is(edi)); // Required by InvokeFunction.
3335 DCHECK(ToRegister(instr->result()).is(eax));
3337 // Copy the arguments to this function possibly from the
3338 // adaptor frame below it.
3339 const uint32_t kArgumentsLimit = 1 * KB;
3340 __ cmp(length, kArgumentsLimit);
3341 DeoptimizeIf(above, instr, Deoptimizer::kTooManyArguments);
3344 __ mov(receiver, length);
3346 // Loop through the arguments pushing them onto the execution
3349 // length is a small non-negative integer, due to the test above.
3350 __ test(length, Operand(length));
3351 __ j(zero, &invoke, Label::kNear);
3353 __ push(Operand(elements, length, times_pointer_size, 1 * kPointerSize));
3355 __ j(not_zero, &loop);
3357 // Invoke the function.
3359 DCHECK(instr->HasPointerMap());
3360 LPointerMap* pointers = instr->pointer_map();
3361 SafepointGenerator safepoint_generator(
3362 this, pointers, Safepoint::kLazyDeopt);
3363 ParameterCount actual(eax);
3364 __ InvokeFunction(function, actual, CALL_FUNCTION, safepoint_generator);
3368 void LCodeGen::DoDebugBreak(LDebugBreak* instr) {
3373 void LCodeGen::DoPushArgument(LPushArgument* instr) {
3374 LOperand* argument = instr->value();
3375 EmitPushTaggedOperand(argument);
3379 void LCodeGen::DoDrop(LDrop* instr) {
3380 __ Drop(instr->count());
3384 void LCodeGen::DoThisFunction(LThisFunction* instr) {
3385 Register result = ToRegister(instr->result());
3386 __ mov(result, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
3390 void LCodeGen::DoContext(LContext* instr) {
3391 Register result = ToRegister(instr->result());
3392 if (info()->IsOptimizing()) {
3393 __ mov(result, Operand(ebp, StandardFrameConstants::kContextOffset));
3395 // If there is no frame, the context must be in esi.
3396 DCHECK(result.is(esi));
3401 void LCodeGen::DoDeclareGlobals(LDeclareGlobals* instr) {
3402 DCHECK(ToRegister(instr->context()).is(esi));
3403 __ push(esi); // The context is the first argument.
3404 __ push(Immediate(instr->hydrogen()->pairs()));
3405 __ push(Immediate(Smi::FromInt(instr->hydrogen()->flags())));
3406 CallRuntime(Runtime::kDeclareGlobals, 3, instr);
3410 void LCodeGen::CallKnownFunction(Handle<JSFunction> function,
3411 int formal_parameter_count, int arity,
3412 LInstruction* instr) {
3413 bool dont_adapt_arguments =
3414 formal_parameter_count == SharedFunctionInfo::kDontAdaptArgumentsSentinel;
3415 bool can_invoke_directly =
3416 dont_adapt_arguments || formal_parameter_count == arity;
3418 Register function_reg = edi;
3420 if (can_invoke_directly) {
3422 __ mov(esi, FieldOperand(function_reg, JSFunction::kContextOffset));
3424 // Set eax to arguments count if adaption is not needed. Assumes that eax
3425 // is available to write to at this point.
3426 if (dont_adapt_arguments) {
3430 // Invoke function directly.
3431 if (function.is_identical_to(info()->closure())) {
3434 __ call(FieldOperand(function_reg, JSFunction::kCodeEntryOffset));
3436 RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
3438 // We need to adapt arguments.
3439 LPointerMap* pointers = instr->pointer_map();
3440 SafepointGenerator generator(
3441 this, pointers, Safepoint::kLazyDeopt);
3442 ParameterCount count(arity);
3443 ParameterCount expected(formal_parameter_count);
3444 __ InvokeFunction(function_reg, expected, count, CALL_FUNCTION, generator);
3449 void LCodeGen::DoCallWithDescriptor(LCallWithDescriptor* instr) {
3450 DCHECK(ToRegister(instr->result()).is(eax));
3452 if (instr->hydrogen()->IsTailCall()) {
3453 if (NeedsEagerFrame()) __ leave();
3455 if (instr->target()->IsConstantOperand()) {
3456 LConstantOperand* target = LConstantOperand::cast(instr->target());
3457 Handle<Code> code = Handle<Code>::cast(ToHandle(target));
3458 __ jmp(code, RelocInfo::CODE_TARGET);
3460 DCHECK(instr->target()->IsRegister());
3461 Register target = ToRegister(instr->target());
3462 __ add(target, Immediate(Code::kHeaderSize - kHeapObjectTag));
3466 LPointerMap* pointers = instr->pointer_map();
3467 SafepointGenerator generator(this, pointers, Safepoint::kLazyDeopt);
3469 if (instr->target()->IsConstantOperand()) {
3470 LConstantOperand* target = LConstantOperand::cast(instr->target());
3471 Handle<Code> code = Handle<Code>::cast(ToHandle(target));
3472 generator.BeforeCall(__ CallSize(code, RelocInfo::CODE_TARGET));
3473 __ call(code, RelocInfo::CODE_TARGET);
3475 DCHECK(instr->target()->IsRegister());
3476 Register target = ToRegister(instr->target());
3477 generator.BeforeCall(__ CallSize(Operand(target)));
3478 __ add(target, Immediate(Code::kHeaderSize - kHeapObjectTag));
3481 generator.AfterCall();
3486 void LCodeGen::DoCallJSFunction(LCallJSFunction* instr) {
3487 DCHECK(ToRegister(instr->function()).is(edi));
3488 DCHECK(ToRegister(instr->result()).is(eax));
3490 if (instr->hydrogen()->pass_argument_count()) {
3491 __ mov(eax, instr->arity());
3495 __ mov(esi, FieldOperand(edi, JSFunction::kContextOffset));
3497 bool is_self_call = false;
3498 if (instr->hydrogen()->function()->IsConstant()) {
3499 HConstant* fun_const = HConstant::cast(instr->hydrogen()->function());
3500 Handle<JSFunction> jsfun =
3501 Handle<JSFunction>::cast(fun_const->handle(isolate()));
3502 is_self_call = jsfun.is_identical_to(info()->closure());
3508 __ call(FieldOperand(edi, JSFunction::kCodeEntryOffset));
3511 RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
3515 void LCodeGen::DoDeferredMathAbsTaggedHeapNumber(LMathAbs* instr) {
3516 Register input_reg = ToRegister(instr->value());
3517 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
3518 factory()->heap_number_map());
3519 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
3521 Label slow, allocated, done;
3522 Register tmp = input_reg.is(eax) ? ecx : eax;
3523 Register tmp2 = tmp.is(ecx) ? edx : input_reg.is(ecx) ? edx : ecx;
3525 // Preserve the value of all registers.
3526 PushSafepointRegistersScope scope(this);
3528 __ mov(tmp, FieldOperand(input_reg, HeapNumber::kExponentOffset));
3529 // Check the sign of the argument. If the argument is positive, just
3530 // return it. We do not need to patch the stack since |input| and
3531 // |result| are the same register and |input| will be restored
3532 // unchanged by popping safepoint registers.
3533 __ test(tmp, Immediate(HeapNumber::kSignMask));
3534 __ j(zero, &done, Label::kNear);
3536 __ AllocateHeapNumber(tmp, tmp2, no_reg, &slow);
3537 __ jmp(&allocated, Label::kNear);
3539 // Slow case: Call the runtime system to do the number allocation.
3541 CallRuntimeFromDeferred(Runtime::kAllocateHeapNumber, 0,
3542 instr, instr->context());
3543 // Set the pointer to the new heap number in tmp.
3544 if (!tmp.is(eax)) __ mov(tmp, eax);
3545 // Restore input_reg after call to runtime.
3546 __ LoadFromSafepointRegisterSlot(input_reg, input_reg);
3548 __ bind(&allocated);
3549 __ mov(tmp2, FieldOperand(input_reg, HeapNumber::kExponentOffset));
3550 __ and_(tmp2, ~HeapNumber::kSignMask);
3551 __ mov(FieldOperand(tmp, HeapNumber::kExponentOffset), tmp2);
3552 __ mov(tmp2, FieldOperand(input_reg, HeapNumber::kMantissaOffset));
3553 __ mov(FieldOperand(tmp, HeapNumber::kMantissaOffset), tmp2);
3554 __ StoreToSafepointRegisterSlot(input_reg, tmp);
3560 void LCodeGen::EmitIntegerMathAbs(LMathAbs* instr) {
3561 Register input_reg = ToRegister(instr->value());
3562 __ test(input_reg, Operand(input_reg));
3564 __ j(not_sign, &is_positive, Label::kNear);
3565 __ neg(input_reg); // Sets flags.
3566 DeoptimizeIf(negative, instr, Deoptimizer::kOverflow);
3567 __ bind(&is_positive);
3571 void LCodeGen::DoMathAbs(LMathAbs* instr) {
3572 // Class for deferred case.
3573 class DeferredMathAbsTaggedHeapNumber final : public LDeferredCode {
3575 DeferredMathAbsTaggedHeapNumber(LCodeGen* codegen,
3577 : LDeferredCode(codegen), instr_(instr) { }
3578 void Generate() override {
3579 codegen()->DoDeferredMathAbsTaggedHeapNumber(instr_);
3581 LInstruction* instr() override { return instr_; }
3587 DCHECK(instr->value()->Equals(instr->result()));
3588 Representation r = instr->hydrogen()->value()->representation();
3591 XMMRegister scratch = double_scratch0();
3592 XMMRegister input_reg = ToDoubleRegister(instr->value());
3593 __ xorps(scratch, scratch);
3594 __ subsd(scratch, input_reg);
3595 __ andps(input_reg, scratch);
3596 } else if (r.IsSmiOrInteger32()) {
3597 EmitIntegerMathAbs(instr);
3598 } else { // Tagged case.
3599 DeferredMathAbsTaggedHeapNumber* deferred =
3600 new(zone()) DeferredMathAbsTaggedHeapNumber(this, instr);
3601 Register input_reg = ToRegister(instr->value());
3603 __ JumpIfNotSmi(input_reg, deferred->entry());
3604 EmitIntegerMathAbs(instr);
3605 __ bind(deferred->exit());
3610 void LCodeGen::DoMathFloor(LMathFloor* instr) {
3611 XMMRegister xmm_scratch = double_scratch0();
3612 Register output_reg = ToRegister(instr->result());
3613 XMMRegister input_reg = ToDoubleRegister(instr->value());
3615 if (CpuFeatures::IsSupported(SSE4_1)) {
3616 CpuFeatureScope scope(masm(), SSE4_1);
3617 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3618 // Deoptimize on negative zero.
3620 __ xorps(xmm_scratch, xmm_scratch); // Zero the register.
3621 __ ucomisd(input_reg, xmm_scratch);
3622 __ j(not_equal, &non_zero, Label::kNear);
3623 __ movmskpd(output_reg, input_reg);
3624 __ test(output_reg, Immediate(1));
3625 DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
3628 __ roundsd(xmm_scratch, input_reg, kRoundDown);
3629 __ cvttsd2si(output_reg, Operand(xmm_scratch));
3630 // Overflow is signalled with minint.
3631 __ cmp(output_reg, 0x1);
3632 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
3634 Label negative_sign, done;
3635 // Deoptimize on unordered.
3636 __ xorps(xmm_scratch, xmm_scratch); // Zero the register.
3637 __ ucomisd(input_reg, xmm_scratch);
3638 DeoptimizeIf(parity_even, instr, Deoptimizer::kNaN);
3639 __ j(below, &negative_sign, Label::kNear);
3641 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3642 // Check for negative zero.
3643 Label positive_sign;
3644 __ j(above, &positive_sign, Label::kNear);
3645 __ movmskpd(output_reg, input_reg);
3646 __ test(output_reg, Immediate(1));
3647 DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
3648 __ Move(output_reg, Immediate(0));
3649 __ jmp(&done, Label::kNear);
3650 __ bind(&positive_sign);
3653 // Use truncating instruction (OK because input is positive).
3654 __ cvttsd2si(output_reg, Operand(input_reg));
3655 // Overflow is signalled with minint.
3656 __ cmp(output_reg, 0x1);
3657 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
3658 __ jmp(&done, Label::kNear);
3660 // Non-zero negative reaches here.
3661 __ bind(&negative_sign);
3662 // Truncate, then compare and compensate.
3663 __ cvttsd2si(output_reg, Operand(input_reg));
3664 __ Cvtsi2sd(xmm_scratch, output_reg);
3665 __ ucomisd(input_reg, xmm_scratch);
3666 __ j(equal, &done, Label::kNear);
3667 __ sub(output_reg, Immediate(1));
3668 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
3675 void LCodeGen::DoMathRound(LMathRound* instr) {
3676 Register output_reg = ToRegister(instr->result());
3677 XMMRegister input_reg = ToDoubleRegister(instr->value());
3678 XMMRegister xmm_scratch = double_scratch0();
3679 XMMRegister input_temp = ToDoubleRegister(instr->temp());
3680 ExternalReference one_half = ExternalReference::address_of_one_half();
3681 ExternalReference minus_one_half =
3682 ExternalReference::address_of_minus_one_half();
3684 Label done, round_to_zero, below_one_half, do_not_compensate;
3685 Label::Distance dist = DeoptEveryNTimes() ? Label::kFar : Label::kNear;
3687 __ movsd(xmm_scratch, Operand::StaticVariable(one_half));
3688 __ ucomisd(xmm_scratch, input_reg);
3689 __ j(above, &below_one_half, Label::kNear);
3691 // CVTTSD2SI rounds towards zero, since 0.5 <= x, we use floor(0.5 + x).
3692 __ addsd(xmm_scratch, input_reg);
3693 __ cvttsd2si(output_reg, Operand(xmm_scratch));
3694 // Overflow is signalled with minint.
3695 __ cmp(output_reg, 0x1);
3696 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
3697 __ jmp(&done, dist);
3699 __ bind(&below_one_half);
3700 __ movsd(xmm_scratch, Operand::StaticVariable(minus_one_half));
3701 __ ucomisd(xmm_scratch, input_reg);
3702 __ j(below_equal, &round_to_zero, Label::kNear);
3704 // CVTTSD2SI rounds towards zero, we use ceil(x - (-0.5)) and then
3705 // compare and compensate.
3706 __ movaps(input_temp, input_reg); // Do not alter input_reg.
3707 __ subsd(input_temp, xmm_scratch);
3708 __ cvttsd2si(output_reg, Operand(input_temp));
3709 // Catch minint due to overflow, and to prevent overflow when compensating.
3710 __ cmp(output_reg, 0x1);
3711 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
3713 __ Cvtsi2sd(xmm_scratch, output_reg);
3714 __ ucomisd(xmm_scratch, input_temp);
3715 __ j(equal, &done, dist);
3716 __ sub(output_reg, Immediate(1));
3717 // No overflow because we already ruled out minint.
3718 __ jmp(&done, dist);
3720 __ bind(&round_to_zero);
3721 // We return 0 for the input range [+0, 0.5[, or [-0.5, 0.5[ if
3722 // we can ignore the difference between a result of -0 and +0.
3723 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3724 // If the sign is positive, we return +0.
3725 __ movmskpd(output_reg, input_reg);
3726 __ test(output_reg, Immediate(1));
3727 DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
3729 __ Move(output_reg, Immediate(0));
3734 void LCodeGen::DoMathFround(LMathFround* instr) {
3735 XMMRegister input_reg = ToDoubleRegister(instr->value());
3736 XMMRegister output_reg = ToDoubleRegister(instr->result());
3737 __ cvtsd2ss(output_reg, input_reg);
3738 __ cvtss2sd(output_reg, output_reg);
3742 void LCodeGen::DoMathSqrt(LMathSqrt* instr) {
3743 Operand input = ToOperand(instr->value());
3744 XMMRegister output = ToDoubleRegister(instr->result());
3745 __ sqrtsd(output, input);
3749 void LCodeGen::DoMathPowHalf(LMathPowHalf* instr) {
3750 XMMRegister xmm_scratch = double_scratch0();
3751 XMMRegister input_reg = ToDoubleRegister(instr->value());
3752 Register scratch = ToRegister(instr->temp());
3753 DCHECK(ToDoubleRegister(instr->result()).is(input_reg));
3755 // Note that according to ECMA-262 15.8.2.13:
3756 // Math.pow(-Infinity, 0.5) == Infinity
3757 // Math.sqrt(-Infinity) == NaN
3759 // Check base for -Infinity. According to IEEE-754, single-precision
3760 // -Infinity has the highest 9 bits set and the lowest 23 bits cleared.
3761 __ mov(scratch, 0xFF800000);
3762 __ movd(xmm_scratch, scratch);
3763 __ cvtss2sd(xmm_scratch, xmm_scratch);
3764 __ ucomisd(input_reg, xmm_scratch);
3765 // Comparing -Infinity with NaN results in "unordered", which sets the
3766 // zero flag as if both were equal. However, it also sets the carry flag.
3767 __ j(not_equal, &sqrt, Label::kNear);
3768 __ j(carry, &sqrt, Label::kNear);
3769 // If input is -Infinity, return Infinity.
3770 __ xorps(input_reg, input_reg);
3771 __ subsd(input_reg, xmm_scratch);
3772 __ jmp(&done, Label::kNear);
3776 __ xorps(xmm_scratch, xmm_scratch);
3777 __ addsd(input_reg, xmm_scratch); // Convert -0 to +0.
3778 __ sqrtsd(input_reg, input_reg);
3783 void LCodeGen::DoPower(LPower* instr) {
3784 Representation exponent_type = instr->hydrogen()->right()->representation();
3785 // Having marked this as a call, we can use any registers.
3786 // Just make sure that the input/output registers are the expected ones.
3787 Register tagged_exponent = MathPowTaggedDescriptor::exponent();
3788 DCHECK(!instr->right()->IsDoubleRegister() ||
3789 ToDoubleRegister(instr->right()).is(xmm1));
3790 DCHECK(!instr->right()->IsRegister() ||
3791 ToRegister(instr->right()).is(tagged_exponent));
3792 DCHECK(ToDoubleRegister(instr->left()).is(xmm2));
3793 DCHECK(ToDoubleRegister(instr->result()).is(xmm3));
3795 if (exponent_type.IsSmi()) {
3796 MathPowStub stub(isolate(), MathPowStub::TAGGED);
3798 } else if (exponent_type.IsTagged()) {
3800 __ JumpIfSmi(tagged_exponent, &no_deopt);
3801 DCHECK(!ecx.is(tagged_exponent));
3802 __ CmpObjectType(tagged_exponent, HEAP_NUMBER_TYPE, ecx);
3803 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
3805 MathPowStub stub(isolate(), MathPowStub::TAGGED);
3807 } else if (exponent_type.IsInteger32()) {
3808 MathPowStub stub(isolate(), MathPowStub::INTEGER);
3811 DCHECK(exponent_type.IsDouble());
3812 MathPowStub stub(isolate(), MathPowStub::DOUBLE);
3818 void LCodeGen::DoMathLog(LMathLog* instr) {
3819 DCHECK(instr->value()->Equals(instr->result()));
3820 XMMRegister input_reg = ToDoubleRegister(instr->value());
3821 XMMRegister xmm_scratch = double_scratch0();
3822 Label positive, done, zero;
3823 __ xorps(xmm_scratch, xmm_scratch);
3824 __ ucomisd(input_reg, xmm_scratch);
3825 __ j(above, &positive, Label::kNear);
3826 __ j(not_carry, &zero, Label::kNear);
3827 __ pcmpeqd(input_reg, input_reg);
3828 __ jmp(&done, Label::kNear);
3830 ExternalReference ninf =
3831 ExternalReference::address_of_negative_infinity();
3832 __ movsd(input_reg, Operand::StaticVariable(ninf));
3833 __ jmp(&done, Label::kNear);
3836 __ sub(Operand(esp), Immediate(kDoubleSize));
3837 __ movsd(Operand(esp, 0), input_reg);
3838 __ fld_d(Operand(esp, 0));
3840 __ fstp_d(Operand(esp, 0));
3841 __ movsd(input_reg, Operand(esp, 0));
3842 __ add(Operand(esp), Immediate(kDoubleSize));
3847 void LCodeGen::DoMathClz32(LMathClz32* instr) {
3848 Register input = ToRegister(instr->value());
3849 Register result = ToRegister(instr->result());
3851 __ Lzcnt(result, input);
3855 void LCodeGen::DoMathExp(LMathExp* instr) {
3856 XMMRegister input = ToDoubleRegister(instr->value());
3857 XMMRegister result = ToDoubleRegister(instr->result());
3858 XMMRegister temp0 = double_scratch0();
3859 Register temp1 = ToRegister(instr->temp1());
3860 Register temp2 = ToRegister(instr->temp2());
3862 MathExpGenerator::EmitMathExp(masm(), input, result, temp0, temp1, temp2);
3866 void LCodeGen::DoInvokeFunction(LInvokeFunction* instr) {
3867 DCHECK(ToRegister(instr->context()).is(esi));
3868 DCHECK(ToRegister(instr->function()).is(edi));
3869 DCHECK(instr->HasPointerMap());
3871 Handle<JSFunction> known_function = instr->hydrogen()->known_function();
3872 if (known_function.is_null()) {
3873 LPointerMap* pointers = instr->pointer_map();
3874 SafepointGenerator generator(
3875 this, pointers, Safepoint::kLazyDeopt);
3876 ParameterCount count(instr->arity());
3877 __ InvokeFunction(edi, count, CALL_FUNCTION, generator);
3879 CallKnownFunction(known_function,
3880 instr->hydrogen()->formal_parameter_count(),
3881 instr->arity(), instr);
3886 void LCodeGen::DoCallFunction(LCallFunction* instr) {
3887 DCHECK(ToRegister(instr->context()).is(esi));
3888 DCHECK(ToRegister(instr->function()).is(edi));
3889 DCHECK(ToRegister(instr->result()).is(eax));
3891 int arity = instr->arity();
3892 CallFunctionFlags flags = instr->hydrogen()->function_flags();
3893 if (instr->hydrogen()->HasVectorAndSlot()) {
3894 Register slot_register = ToRegister(instr->temp_slot());
3895 Register vector_register = ToRegister(instr->temp_vector());
3896 DCHECK(slot_register.is(edx));
3897 DCHECK(vector_register.is(ebx));
3899 AllowDeferredHandleDereference vector_structure_check;
3900 Handle<TypeFeedbackVector> vector = instr->hydrogen()->feedback_vector();
3901 int index = vector->GetIndex(instr->hydrogen()->slot());
3903 __ mov(vector_register, vector);
3904 __ mov(slot_register, Immediate(Smi::FromInt(index)));
3906 CallICState::CallType call_type =
3907 (flags & CALL_AS_METHOD) ? CallICState::METHOD : CallICState::FUNCTION;
3910 CodeFactory::CallICInOptimizedCode(isolate(), arity, call_type).code();
3911 CallCode(ic, RelocInfo::CODE_TARGET, instr);
3913 CallFunctionStub stub(isolate(), arity, flags);
3914 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
3919 void LCodeGen::DoCallNew(LCallNew* instr) {
3920 DCHECK(ToRegister(instr->context()).is(esi));
3921 DCHECK(ToRegister(instr->constructor()).is(edi));
3922 DCHECK(ToRegister(instr->result()).is(eax));
3924 // No cell in ebx for construct type feedback in optimized code
3925 __ mov(ebx, isolate()->factory()->undefined_value());
3926 CallConstructStub stub(isolate(), NO_CALL_CONSTRUCTOR_FLAGS);
3927 __ Move(eax, Immediate(instr->arity()));
3928 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
3932 void LCodeGen::DoCallNewArray(LCallNewArray* instr) {
3933 DCHECK(ToRegister(instr->context()).is(esi));
3934 DCHECK(ToRegister(instr->constructor()).is(edi));
3935 DCHECK(ToRegister(instr->result()).is(eax));
3937 __ Move(eax, Immediate(instr->arity()));
3938 if (instr->arity() == 1) {
3939 // We only need the allocation site for the case we have a length argument.
3940 // The case may bail out to the runtime, which will determine the correct
3941 // elements kind with the site.
3942 __ mov(ebx, instr->hydrogen()->site());
3944 __ mov(ebx, isolate()->factory()->undefined_value());
3947 ElementsKind kind = instr->hydrogen()->elements_kind();
3948 AllocationSiteOverrideMode override_mode =
3949 (AllocationSite::GetMode(kind) == TRACK_ALLOCATION_SITE)
3950 ? DISABLE_ALLOCATION_SITES
3953 if (instr->arity() == 0) {
3954 ArrayNoArgumentConstructorStub stub(isolate(), kind, override_mode);
3955 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
3956 } else if (instr->arity() == 1) {
3958 if (IsFastPackedElementsKind(kind)) {
3960 // We might need a change here
3961 // look at the first argument
3962 __ mov(ecx, Operand(esp, 0));
3964 __ j(zero, &packed_case, Label::kNear);
3966 ElementsKind holey_kind = GetHoleyElementsKind(kind);
3967 ArraySingleArgumentConstructorStub stub(isolate(),
3970 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
3971 __ jmp(&done, Label::kNear);
3972 __ bind(&packed_case);
3975 ArraySingleArgumentConstructorStub stub(isolate(), kind, override_mode);
3976 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
3979 ArrayNArgumentsConstructorStub stub(isolate(), kind, override_mode);
3980 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
3985 void LCodeGen::DoCallRuntime(LCallRuntime* instr) {
3986 DCHECK(ToRegister(instr->context()).is(esi));
3987 CallRuntime(instr->function(), instr->arity(), instr, instr->save_doubles());
3991 void LCodeGen::DoStoreCodeEntry(LStoreCodeEntry* instr) {
3992 Register function = ToRegister(instr->function());
3993 Register code_object = ToRegister(instr->code_object());
3994 __ lea(code_object, FieldOperand(code_object, Code::kHeaderSize));
3995 __ mov(FieldOperand(function, JSFunction::kCodeEntryOffset), code_object);
3999 void LCodeGen::DoInnerAllocatedObject(LInnerAllocatedObject* instr) {
4000 Register result = ToRegister(instr->result());
4001 Register base = ToRegister(instr->base_object());
4002 if (instr->offset()->IsConstantOperand()) {
4003 LConstantOperand* offset = LConstantOperand::cast(instr->offset());
4004 __ lea(result, Operand(base, ToInteger32(offset)));
4006 Register offset = ToRegister(instr->offset());
4007 __ lea(result, Operand(base, offset, times_1, 0));
4012 void LCodeGen::DoStoreNamedField(LStoreNamedField* instr) {
4013 Representation representation = instr->hydrogen()->field_representation();
4015 HObjectAccess access = instr->hydrogen()->access();
4016 int offset = access.offset();
4018 if (access.IsExternalMemory()) {
4019 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4020 MemOperand operand = instr->object()->IsConstantOperand()
4021 ? MemOperand::StaticVariable(
4022 ToExternalReference(LConstantOperand::cast(instr->object())))
4023 : MemOperand(ToRegister(instr->object()), offset);
4024 if (instr->value()->IsConstantOperand()) {
4025 LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
4026 __ mov(operand, Immediate(ToInteger32(operand_value)));
4028 Register value = ToRegister(instr->value());
4029 __ Store(value, operand, representation);
4034 Register object = ToRegister(instr->object());
4035 __ AssertNotSmi(object);
4037 DCHECK(!representation.IsSmi() ||
4038 !instr->value()->IsConstantOperand() ||
4039 IsSmi(LConstantOperand::cast(instr->value())));
4040 if (representation.IsDouble()) {
4041 DCHECK(access.IsInobject());
4042 DCHECK(!instr->hydrogen()->has_transition());
4043 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4044 XMMRegister value = ToDoubleRegister(instr->value());
4045 __ movsd(FieldOperand(object, offset), value);
4049 if (instr->hydrogen()->has_transition()) {
4050 Handle<Map> transition = instr->hydrogen()->transition_map();
4051 AddDeprecationDependency(transition);
4052 __ mov(FieldOperand(object, HeapObject::kMapOffset), transition);
4053 if (instr->hydrogen()->NeedsWriteBarrierForMap()) {
4054 Register temp = ToRegister(instr->temp());
4055 Register temp_map = ToRegister(instr->temp_map());
4056 // Update the write barrier for the map field.
4057 __ RecordWriteForMap(object, transition, temp_map, temp, kSaveFPRegs);
4062 Register write_register = object;
4063 if (!access.IsInobject()) {
4064 write_register = ToRegister(instr->temp());
4065 __ mov(write_register, FieldOperand(object, JSObject::kPropertiesOffset));
4068 MemOperand operand = FieldOperand(write_register, offset);
4069 if (instr->value()->IsConstantOperand()) {
4070 LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
4071 if (operand_value->IsRegister()) {
4072 Register value = ToRegister(operand_value);
4073 __ Store(value, operand, representation);
4074 } else if (representation.IsInteger32()) {
4075 Immediate immediate = ToImmediate(operand_value, representation);
4076 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4077 __ mov(operand, immediate);
4079 Handle<Object> handle_value = ToHandle(operand_value);
4080 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4081 __ mov(operand, handle_value);
4084 Register value = ToRegister(instr->value());
4085 __ Store(value, operand, representation);
4088 if (instr->hydrogen()->NeedsWriteBarrier()) {
4089 Register value = ToRegister(instr->value());
4090 Register temp = access.IsInobject() ? ToRegister(instr->temp()) : object;
4091 // Update the write barrier for the object for in-object properties.
4092 __ RecordWriteField(write_register,
4097 EMIT_REMEMBERED_SET,
4098 instr->hydrogen()->SmiCheckForWriteBarrier(),
4099 instr->hydrogen()->PointersToHereCheckForValue());
4104 void LCodeGen::DoStoreNamedGeneric(LStoreNamedGeneric* instr) {
4105 DCHECK(ToRegister(instr->context()).is(esi));
4106 DCHECK(ToRegister(instr->object()).is(StoreDescriptor::ReceiverRegister()));
4107 DCHECK(ToRegister(instr->value()).is(StoreDescriptor::ValueRegister()));
4109 if (instr->hydrogen()->HasVectorAndSlot()) {
4110 EmitVectorStoreICRegisters<LStoreNamedGeneric>(instr);
4113 __ mov(StoreDescriptor::NameRegister(), instr->name());
4114 Handle<Code> ic = CodeFactory::StoreICInOptimizedCode(
4115 isolate(), instr->language_mode(),
4116 instr->hydrogen()->initialization_state()).code();
4117 CallCode(ic, RelocInfo::CODE_TARGET, instr);
4121 void LCodeGen::DoBoundsCheck(LBoundsCheck* instr) {
4122 Condition cc = instr->hydrogen()->allow_equality() ? above : above_equal;
4123 if (instr->index()->IsConstantOperand()) {
4124 __ cmp(ToOperand(instr->length()),
4125 ToImmediate(LConstantOperand::cast(instr->index()),
4126 instr->hydrogen()->length()->representation()));
4127 cc = CommuteCondition(cc);
4128 } else if (instr->length()->IsConstantOperand()) {
4129 __ cmp(ToOperand(instr->index()),
4130 ToImmediate(LConstantOperand::cast(instr->length()),
4131 instr->hydrogen()->index()->representation()));
4133 __ cmp(ToRegister(instr->index()), ToOperand(instr->length()));
4135 if (FLAG_debug_code && instr->hydrogen()->skip_check()) {
4137 __ j(NegateCondition(cc), &done, Label::kNear);
4141 DeoptimizeIf(cc, instr, Deoptimizer::kOutOfBounds);
4146 void LCodeGen::DoStoreKeyedExternalArray(LStoreKeyed* instr) {
4147 ElementsKind elements_kind = instr->elements_kind();
4148 LOperand* key = instr->key();
4149 if (!key->IsConstantOperand() &&
4150 ExternalArrayOpRequiresTemp(instr->hydrogen()->key()->representation(),
4152 __ SmiUntag(ToRegister(key));
4154 Operand operand(BuildFastArrayOperand(
4157 instr->hydrogen()->key()->representation(),
4159 instr->base_offset()));
4160 if (elements_kind == EXTERNAL_FLOAT32_ELEMENTS ||
4161 elements_kind == FLOAT32_ELEMENTS) {
4162 XMMRegister xmm_scratch = double_scratch0();
4163 __ cvtsd2ss(xmm_scratch, ToDoubleRegister(instr->value()));
4164 __ movss(operand, xmm_scratch);
4165 } else if (elements_kind == EXTERNAL_FLOAT64_ELEMENTS ||
4166 elements_kind == FLOAT64_ELEMENTS) {
4167 __ movsd(operand, ToDoubleRegister(instr->value()));
4169 Register value = ToRegister(instr->value());
4170 switch (elements_kind) {
4171 case EXTERNAL_UINT8_CLAMPED_ELEMENTS:
4172 case EXTERNAL_UINT8_ELEMENTS:
4173 case EXTERNAL_INT8_ELEMENTS:
4174 case UINT8_ELEMENTS:
4176 case UINT8_CLAMPED_ELEMENTS:
4177 __ mov_b(operand, value);
4179 case EXTERNAL_INT16_ELEMENTS:
4180 case EXTERNAL_UINT16_ELEMENTS:
4181 case UINT16_ELEMENTS:
4182 case INT16_ELEMENTS:
4183 __ mov_w(operand, value);
4185 case EXTERNAL_INT32_ELEMENTS:
4186 case EXTERNAL_UINT32_ELEMENTS:
4187 case UINT32_ELEMENTS:
4188 case INT32_ELEMENTS:
4189 __ mov(operand, value);
4191 case EXTERNAL_FLOAT32_ELEMENTS:
4192 case EXTERNAL_FLOAT64_ELEMENTS:
4193 case FLOAT32_ELEMENTS:
4194 case FLOAT64_ELEMENTS:
4195 case FAST_SMI_ELEMENTS:
4197 case FAST_DOUBLE_ELEMENTS:
4198 case FAST_HOLEY_SMI_ELEMENTS:
4199 case FAST_HOLEY_ELEMENTS:
4200 case FAST_HOLEY_DOUBLE_ELEMENTS:
4201 case DICTIONARY_ELEMENTS:
4202 case FAST_SLOPPY_ARGUMENTS_ELEMENTS:
4203 case SLOW_SLOPPY_ARGUMENTS_ELEMENTS:
4211 void LCodeGen::DoStoreKeyedFixedDoubleArray(LStoreKeyed* instr) {
4212 Operand double_store_operand = BuildFastArrayOperand(
4215 instr->hydrogen()->key()->representation(),
4216 FAST_DOUBLE_ELEMENTS,
4217 instr->base_offset());
4219 XMMRegister value = ToDoubleRegister(instr->value());
4221 if (instr->NeedsCanonicalization()) {
4222 XMMRegister xmm_scratch = double_scratch0();
4223 // Turn potential sNaN value into qNaN.
4224 __ xorps(xmm_scratch, xmm_scratch);
4225 __ subsd(value, xmm_scratch);
4228 __ movsd(double_store_operand, value);
4232 void LCodeGen::DoStoreKeyedFixedArray(LStoreKeyed* instr) {
4233 Register elements = ToRegister(instr->elements());
4234 Register key = instr->key()->IsRegister() ? ToRegister(instr->key()) : no_reg;
4236 Operand operand = BuildFastArrayOperand(
4239 instr->hydrogen()->key()->representation(),
4241 instr->base_offset());
4242 if (instr->value()->IsRegister()) {
4243 __ mov(operand, ToRegister(instr->value()));
4245 LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
4246 if (IsSmi(operand_value)) {
4247 Immediate immediate = ToImmediate(operand_value, Representation::Smi());
4248 __ mov(operand, immediate);
4250 DCHECK(!IsInteger32(operand_value));
4251 Handle<Object> handle_value = ToHandle(operand_value);
4252 __ mov(operand, handle_value);
4256 if (instr->hydrogen()->NeedsWriteBarrier()) {
4257 DCHECK(instr->value()->IsRegister());
4258 Register value = ToRegister(instr->value());
4259 DCHECK(!instr->key()->IsConstantOperand());
4260 SmiCheck check_needed =
4261 instr->hydrogen()->value()->type().IsHeapObject()
4262 ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
4263 // Compute address of modified element and store it into key register.
4264 __ lea(key, operand);
4265 __ RecordWrite(elements,
4269 EMIT_REMEMBERED_SET,
4271 instr->hydrogen()->PointersToHereCheckForValue());
4276 void LCodeGen::DoStoreKeyed(LStoreKeyed* instr) {
4277 // By cases...external, fast-double, fast
4278 if (instr->is_typed_elements()) {
4279 DoStoreKeyedExternalArray(instr);
4280 } else if (instr->hydrogen()->value()->representation().IsDouble()) {
4281 DoStoreKeyedFixedDoubleArray(instr);
4283 DoStoreKeyedFixedArray(instr);
4288 void LCodeGen::DoStoreKeyedGeneric(LStoreKeyedGeneric* instr) {
4289 DCHECK(ToRegister(instr->context()).is(esi));
4290 DCHECK(ToRegister(instr->object()).is(StoreDescriptor::ReceiverRegister()));
4291 DCHECK(ToRegister(instr->key()).is(StoreDescriptor::NameRegister()));
4292 DCHECK(ToRegister(instr->value()).is(StoreDescriptor::ValueRegister()));
4294 if (instr->hydrogen()->HasVectorAndSlot()) {
4295 EmitVectorStoreICRegisters<LStoreKeyedGeneric>(instr);
4298 Handle<Code> ic = CodeFactory::KeyedStoreICInOptimizedCode(
4299 isolate(), instr->language_mode(),
4300 instr->hydrogen()->initialization_state()).code();
4301 CallCode(ic, RelocInfo::CODE_TARGET, instr);
4305 void LCodeGen::DoTrapAllocationMemento(LTrapAllocationMemento* instr) {
4306 Register object = ToRegister(instr->object());
4307 Register temp = ToRegister(instr->temp());
4308 Label no_memento_found;
4309 __ TestJSArrayForAllocationMemento(object, temp, &no_memento_found);
4310 DeoptimizeIf(equal, instr, Deoptimizer::kMementoFound);
4311 __ bind(&no_memento_found);
4315 void LCodeGen::DoMaybeGrowElements(LMaybeGrowElements* instr) {
4316 class DeferredMaybeGrowElements final : public LDeferredCode {
4318 DeferredMaybeGrowElements(LCodeGen* codegen, LMaybeGrowElements* instr)
4319 : LDeferredCode(codegen), instr_(instr) {}
4320 void Generate() override { codegen()->DoDeferredMaybeGrowElements(instr_); }
4321 LInstruction* instr() override { return instr_; }
4324 LMaybeGrowElements* instr_;
4327 Register result = eax;
4328 DeferredMaybeGrowElements* deferred =
4329 new (zone()) DeferredMaybeGrowElements(this, instr);
4330 LOperand* key = instr->key();
4331 LOperand* current_capacity = instr->current_capacity();
4333 DCHECK(instr->hydrogen()->key()->representation().IsInteger32());
4334 DCHECK(instr->hydrogen()->current_capacity()->representation().IsInteger32());
4335 DCHECK(key->IsConstantOperand() || key->IsRegister());
4336 DCHECK(current_capacity->IsConstantOperand() ||
4337 current_capacity->IsRegister());
4339 if (key->IsConstantOperand() && current_capacity->IsConstantOperand()) {
4340 int32_t constant_key = ToInteger32(LConstantOperand::cast(key));
4341 int32_t constant_capacity =
4342 ToInteger32(LConstantOperand::cast(current_capacity));
4343 if (constant_key >= constant_capacity) {
4345 __ jmp(deferred->entry());
4347 } else if (key->IsConstantOperand()) {
4348 int32_t constant_key = ToInteger32(LConstantOperand::cast(key));
4349 __ cmp(ToOperand(current_capacity), Immediate(constant_key));
4350 __ j(less_equal, deferred->entry());
4351 } else if (current_capacity->IsConstantOperand()) {
4352 int32_t constant_capacity =
4353 ToInteger32(LConstantOperand::cast(current_capacity));
4354 __ cmp(ToRegister(key), Immediate(constant_capacity));
4355 __ j(greater_equal, deferred->entry());
4357 __ cmp(ToRegister(key), ToRegister(current_capacity));
4358 __ j(greater_equal, deferred->entry());
4361 __ mov(result, ToOperand(instr->elements()));
4362 __ bind(deferred->exit());
4366 void LCodeGen::DoDeferredMaybeGrowElements(LMaybeGrowElements* instr) {
4367 // TODO(3095996): Get rid of this. For now, we need to make the
4368 // result register contain a valid pointer because it is already
4369 // contained in the register pointer map.
4370 Register result = eax;
4371 __ Move(result, Immediate(0));
4373 // We have to call a stub.
4375 PushSafepointRegistersScope scope(this);
4376 if (instr->object()->IsRegister()) {
4377 __ Move(result, ToRegister(instr->object()));
4379 __ mov(result, ToOperand(instr->object()));
4382 LOperand* key = instr->key();
4383 if (key->IsConstantOperand()) {
4384 __ mov(ebx, ToImmediate(key, Representation::Smi()));
4386 __ Move(ebx, ToRegister(key));
4390 GrowArrayElementsStub stub(isolate(), instr->hydrogen()->is_js_array(),
4391 instr->hydrogen()->kind());
4393 RecordSafepointWithLazyDeopt(
4394 instr, RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
4395 __ StoreToSafepointRegisterSlot(result, result);
4398 // Deopt on smi, which means the elements array changed to dictionary mode.
4399 __ test(result, Immediate(kSmiTagMask));
4400 DeoptimizeIf(equal, instr, Deoptimizer::kSmi);
4404 void LCodeGen::DoTransitionElementsKind(LTransitionElementsKind* instr) {
4405 Register object_reg = ToRegister(instr->object());
4407 Handle<Map> from_map = instr->original_map();
4408 Handle<Map> to_map = instr->transitioned_map();
4409 ElementsKind from_kind = instr->from_kind();
4410 ElementsKind to_kind = instr->to_kind();
4412 Label not_applicable;
4413 bool is_simple_map_transition =
4414 IsSimpleMapChangeTransition(from_kind, to_kind);
4415 Label::Distance branch_distance =
4416 is_simple_map_transition ? Label::kNear : Label::kFar;
4417 __ cmp(FieldOperand(object_reg, HeapObject::kMapOffset), from_map);
4418 __ j(not_equal, ¬_applicable, branch_distance);
4419 if (is_simple_map_transition) {
4420 Register new_map_reg = ToRegister(instr->new_map_temp());
4421 __ mov(FieldOperand(object_reg, HeapObject::kMapOffset),
4424 DCHECK_NOT_NULL(instr->temp());
4425 __ RecordWriteForMap(object_reg, to_map, new_map_reg,
4426 ToRegister(instr->temp()),
4429 DCHECK(ToRegister(instr->context()).is(esi));
4430 DCHECK(object_reg.is(eax));
4431 PushSafepointRegistersScope scope(this);
4432 __ mov(ebx, to_map);
4433 bool is_js_array = from_map->instance_type() == JS_ARRAY_TYPE;
4434 TransitionElementsKindStub stub(isolate(), from_kind, to_kind, is_js_array);
4436 RecordSafepointWithLazyDeopt(instr,
4437 RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
4439 __ bind(¬_applicable);
4443 void LCodeGen::DoStringCharCodeAt(LStringCharCodeAt* instr) {
4444 class DeferredStringCharCodeAt final : public LDeferredCode {
4446 DeferredStringCharCodeAt(LCodeGen* codegen,
4447 LStringCharCodeAt* instr)
4448 : LDeferredCode(codegen), instr_(instr) { }
4449 void Generate() override { codegen()->DoDeferredStringCharCodeAt(instr_); }
4450 LInstruction* instr() override { return instr_; }
4453 LStringCharCodeAt* instr_;
4456 DeferredStringCharCodeAt* deferred =
4457 new(zone()) DeferredStringCharCodeAt(this, instr);
4459 StringCharLoadGenerator::Generate(masm(),
4461 ToRegister(instr->string()),
4462 ToRegister(instr->index()),
4463 ToRegister(instr->result()),
4465 __ bind(deferred->exit());
4469 void LCodeGen::DoDeferredStringCharCodeAt(LStringCharCodeAt* instr) {
4470 Register string = ToRegister(instr->string());
4471 Register result = ToRegister(instr->result());
4473 // TODO(3095996): Get rid of this. For now, we need to make the
4474 // result register contain a valid pointer because it is already
4475 // contained in the register pointer map.
4476 __ Move(result, Immediate(0));
4478 PushSafepointRegistersScope scope(this);
4480 // Push the index as a smi. This is safe because of the checks in
4481 // DoStringCharCodeAt above.
4482 STATIC_ASSERT(String::kMaxLength <= Smi::kMaxValue);
4483 if (instr->index()->IsConstantOperand()) {
4484 Immediate immediate = ToImmediate(LConstantOperand::cast(instr->index()),
4485 Representation::Smi());
4488 Register index = ToRegister(instr->index());
4492 CallRuntimeFromDeferred(Runtime::kStringCharCodeAtRT, 2,
4493 instr, instr->context());
4496 __ StoreToSafepointRegisterSlot(result, eax);
4500 void LCodeGen::DoStringCharFromCode(LStringCharFromCode* instr) {
4501 class DeferredStringCharFromCode final : public LDeferredCode {
4503 DeferredStringCharFromCode(LCodeGen* codegen,
4504 LStringCharFromCode* instr)
4505 : LDeferredCode(codegen), instr_(instr) { }
4506 void Generate() override {
4507 codegen()->DoDeferredStringCharFromCode(instr_);
4509 LInstruction* instr() override { return instr_; }
4512 LStringCharFromCode* instr_;
4515 DeferredStringCharFromCode* deferred =
4516 new(zone()) DeferredStringCharFromCode(this, instr);
4518 DCHECK(instr->hydrogen()->value()->representation().IsInteger32());
4519 Register char_code = ToRegister(instr->char_code());
4520 Register result = ToRegister(instr->result());
4521 DCHECK(!char_code.is(result));
4523 __ cmp(char_code, String::kMaxOneByteCharCode);
4524 __ j(above, deferred->entry());
4525 __ Move(result, Immediate(factory()->single_character_string_cache()));
4526 __ mov(result, FieldOperand(result,
4527 char_code, times_pointer_size,
4528 FixedArray::kHeaderSize));
4529 __ cmp(result, factory()->undefined_value());
4530 __ j(equal, deferred->entry());
4531 __ bind(deferred->exit());
4535 void LCodeGen::DoDeferredStringCharFromCode(LStringCharFromCode* instr) {
4536 Register char_code = ToRegister(instr->char_code());
4537 Register result = ToRegister(instr->result());
4539 // TODO(3095996): Get rid of this. For now, we need to make the
4540 // result register contain a valid pointer because it is already
4541 // contained in the register pointer map.
4542 __ Move(result, Immediate(0));
4544 PushSafepointRegistersScope scope(this);
4545 __ SmiTag(char_code);
4547 CallRuntimeFromDeferred(Runtime::kCharFromCode, 1, instr, instr->context());
4548 __ StoreToSafepointRegisterSlot(result, eax);
4552 void LCodeGen::DoStringAdd(LStringAdd* instr) {
4553 DCHECK(ToRegister(instr->context()).is(esi));
4554 DCHECK(ToRegister(instr->left()).is(edx));
4555 DCHECK(ToRegister(instr->right()).is(eax));
4556 StringAddStub stub(isolate(),
4557 instr->hydrogen()->flags(),
4558 instr->hydrogen()->pretenure_flag());
4559 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
4563 void LCodeGen::DoInteger32ToDouble(LInteger32ToDouble* instr) {
4564 LOperand* input = instr->value();
4565 LOperand* output = instr->result();
4566 DCHECK(input->IsRegister() || input->IsStackSlot());
4567 DCHECK(output->IsDoubleRegister());
4568 __ Cvtsi2sd(ToDoubleRegister(output), ToOperand(input));
4572 void LCodeGen::DoUint32ToDouble(LUint32ToDouble* instr) {
4573 LOperand* input = instr->value();
4574 LOperand* output = instr->result();
4575 __ LoadUint32(ToDoubleRegister(output), ToRegister(input));
4579 void LCodeGen::DoNumberTagI(LNumberTagI* instr) {
4580 class DeferredNumberTagI final : public LDeferredCode {
4582 DeferredNumberTagI(LCodeGen* codegen,
4584 : LDeferredCode(codegen), instr_(instr) { }
4585 void Generate() override {
4586 codegen()->DoDeferredNumberTagIU(
4587 instr_, instr_->value(), instr_->temp(), SIGNED_INT32);
4589 LInstruction* instr() override { return instr_; }
4592 LNumberTagI* instr_;
4595 LOperand* input = instr->value();
4596 DCHECK(input->IsRegister() && input->Equals(instr->result()));
4597 Register reg = ToRegister(input);
4599 DeferredNumberTagI* deferred =
4600 new(zone()) DeferredNumberTagI(this, instr);
4602 __ j(overflow, deferred->entry());
4603 __ bind(deferred->exit());
4607 void LCodeGen::DoNumberTagU(LNumberTagU* instr) {
4608 class DeferredNumberTagU final : public LDeferredCode {
4610 DeferredNumberTagU(LCodeGen* codegen, LNumberTagU* instr)
4611 : LDeferredCode(codegen), instr_(instr) { }
4612 void Generate() override {
4613 codegen()->DoDeferredNumberTagIU(
4614 instr_, instr_->value(), instr_->temp(), UNSIGNED_INT32);
4616 LInstruction* instr() override { return instr_; }
4619 LNumberTagU* instr_;
4622 LOperand* input = instr->value();
4623 DCHECK(input->IsRegister() && input->Equals(instr->result()));
4624 Register reg = ToRegister(input);
4626 DeferredNumberTagU* deferred =
4627 new(zone()) DeferredNumberTagU(this, instr);
4628 __ cmp(reg, Immediate(Smi::kMaxValue));
4629 __ j(above, deferred->entry());
4631 __ bind(deferred->exit());
4635 void LCodeGen::DoDeferredNumberTagIU(LInstruction* instr,
4638 IntegerSignedness signedness) {
4640 Register reg = ToRegister(value);
4641 Register tmp = ToRegister(temp);
4642 XMMRegister xmm_scratch = double_scratch0();
4644 if (signedness == SIGNED_INT32) {
4645 // There was overflow, so bits 30 and 31 of the original integer
4646 // disagree. Try to allocate a heap number in new space and store
4647 // the value in there. If that fails, call the runtime system.
4649 __ xor_(reg, 0x80000000);
4650 __ Cvtsi2sd(xmm_scratch, Operand(reg));
4652 __ LoadUint32(xmm_scratch, reg);
4655 if (FLAG_inline_new) {
4656 __ AllocateHeapNumber(reg, tmp, no_reg, &slow);
4657 __ jmp(&done, Label::kNear);
4660 // Slow case: Call the runtime system to do the number allocation.
4663 // TODO(3095996): Put a valid pointer value in the stack slot where the
4664 // result register is stored, as this register is in the pointer map, but
4665 // contains an integer value.
4666 __ Move(reg, Immediate(0));
4668 // Preserve the value of all registers.
4669 PushSafepointRegistersScope scope(this);
4671 // NumberTagI and NumberTagD use the context from the frame, rather than
4672 // the environment's HContext or HInlinedContext value.
4673 // They only call Runtime::kAllocateHeapNumber.
4674 // The corresponding HChange instructions are added in a phase that does
4675 // not have easy access to the local context.
4676 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4677 __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
4678 RecordSafepointWithRegisters(
4679 instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
4680 __ StoreToSafepointRegisterSlot(reg, eax);
4683 // Done. Put the value in xmm_scratch into the value of the allocated heap
4686 __ movsd(FieldOperand(reg, HeapNumber::kValueOffset), xmm_scratch);
4690 void LCodeGen::DoNumberTagD(LNumberTagD* instr) {
4691 class DeferredNumberTagD final : public LDeferredCode {
4693 DeferredNumberTagD(LCodeGen* codegen, LNumberTagD* instr)
4694 : LDeferredCode(codegen), instr_(instr) { }
4695 void Generate() override { codegen()->DoDeferredNumberTagD(instr_); }
4696 LInstruction* instr() override { return instr_; }
4699 LNumberTagD* instr_;
4702 Register reg = ToRegister(instr->result());
4704 DeferredNumberTagD* deferred =
4705 new(zone()) DeferredNumberTagD(this, instr);
4706 if (FLAG_inline_new) {
4707 Register tmp = ToRegister(instr->temp());
4708 __ AllocateHeapNumber(reg, tmp, no_reg, deferred->entry());
4710 __ jmp(deferred->entry());
4712 __ bind(deferred->exit());
4713 XMMRegister input_reg = ToDoubleRegister(instr->value());
4714 __ movsd(FieldOperand(reg, HeapNumber::kValueOffset), input_reg);
4718 void LCodeGen::DoDeferredNumberTagD(LNumberTagD* instr) {
4719 // TODO(3095996): Get rid of this. For now, we need to make the
4720 // result register contain a valid pointer because it is already
4721 // contained in the register pointer map.
4722 Register reg = ToRegister(instr->result());
4723 __ Move(reg, Immediate(0));
4725 PushSafepointRegistersScope scope(this);
4726 // NumberTagI and NumberTagD use the context from the frame, rather than
4727 // the environment's HContext or HInlinedContext value.
4728 // They only call Runtime::kAllocateHeapNumber.
4729 // The corresponding HChange instructions are added in a phase that does
4730 // not have easy access to the local context.
4731 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4732 __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
4733 RecordSafepointWithRegisters(
4734 instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
4735 __ StoreToSafepointRegisterSlot(reg, eax);
4739 void LCodeGen::DoSmiTag(LSmiTag* instr) {
4740 HChange* hchange = instr->hydrogen();
4741 Register input = ToRegister(instr->value());
4742 if (hchange->CheckFlag(HValue::kCanOverflow) &&
4743 hchange->value()->CheckFlag(HValue::kUint32)) {
4744 __ test(input, Immediate(0xc0000000));
4745 DeoptimizeIf(not_zero, instr, Deoptimizer::kOverflow);
4748 if (hchange->CheckFlag(HValue::kCanOverflow) &&
4749 !hchange->value()->CheckFlag(HValue::kUint32)) {
4750 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
4755 void LCodeGen::DoSmiUntag(LSmiUntag* instr) {
4756 LOperand* input = instr->value();
4757 Register result = ToRegister(input);
4758 DCHECK(input->IsRegister() && input->Equals(instr->result()));
4759 if (instr->needs_check()) {
4760 __ test(result, Immediate(kSmiTagMask));
4761 DeoptimizeIf(not_zero, instr, Deoptimizer::kNotASmi);
4763 __ AssertSmi(result);
4765 __ SmiUntag(result);
4769 void LCodeGen::EmitNumberUntagD(LNumberUntagD* instr, Register input_reg,
4770 Register temp_reg, XMMRegister result_reg,
4771 NumberUntagDMode mode) {
4772 bool can_convert_undefined_to_nan =
4773 instr->hydrogen()->can_convert_undefined_to_nan();
4774 bool deoptimize_on_minus_zero = instr->hydrogen()->deoptimize_on_minus_zero();
4776 Label convert, load_smi, done;
4778 if (mode == NUMBER_CANDIDATE_IS_ANY_TAGGED) {
4780 __ JumpIfSmi(input_reg, &load_smi, Label::kNear);
4782 // Heap number map check.
4783 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
4784 factory()->heap_number_map());
4785 if (can_convert_undefined_to_nan) {
4786 __ j(not_equal, &convert, Label::kNear);
4788 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
4791 // Heap number to XMM conversion.
4792 __ movsd(result_reg, FieldOperand(input_reg, HeapNumber::kValueOffset));
4794 if (deoptimize_on_minus_zero) {
4795 XMMRegister xmm_scratch = double_scratch0();
4796 __ xorps(xmm_scratch, xmm_scratch);
4797 __ ucomisd(result_reg, xmm_scratch);
4798 __ j(not_zero, &done, Label::kNear);
4799 __ movmskpd(temp_reg, result_reg);
4800 __ test_b(temp_reg, 1);
4801 DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
4803 __ jmp(&done, Label::kNear);
4805 if (can_convert_undefined_to_nan) {
4808 // Convert undefined to NaN.
4809 __ cmp(input_reg, factory()->undefined_value());
4810 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumberUndefined);
4812 __ pcmpeqd(result_reg, result_reg);
4813 __ jmp(&done, Label::kNear);
4816 DCHECK(mode == NUMBER_CANDIDATE_IS_SMI);
4820 // Smi to XMM conversion. Clobbering a temp is faster than re-tagging the
4821 // input register since we avoid dependencies.
4822 __ mov(temp_reg, input_reg);
4823 __ SmiUntag(temp_reg); // Untag smi before converting to float.
4824 __ Cvtsi2sd(result_reg, Operand(temp_reg));
4829 void LCodeGen::DoDeferredTaggedToI(LTaggedToI* instr, Label* done) {
4830 Register input_reg = ToRegister(instr->value());
4832 // The input was optimistically untagged; revert it.
4833 STATIC_ASSERT(kSmiTagSize == 1);
4834 __ lea(input_reg, Operand(input_reg, times_2, kHeapObjectTag));
4836 if (instr->truncating()) {
4837 Label no_heap_number, check_bools, check_false;
4839 // Heap number map check.
4840 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
4841 factory()->heap_number_map());
4842 __ j(not_equal, &no_heap_number, Label::kNear);
4843 __ TruncateHeapNumberToI(input_reg, input_reg);
4846 __ bind(&no_heap_number);
4847 // Check for Oddballs. Undefined/False is converted to zero and True to one
4848 // for truncating conversions.
4849 __ cmp(input_reg, factory()->undefined_value());
4850 __ j(not_equal, &check_bools, Label::kNear);
4851 __ Move(input_reg, Immediate(0));
4854 __ bind(&check_bools);
4855 __ cmp(input_reg, factory()->true_value());
4856 __ j(not_equal, &check_false, Label::kNear);
4857 __ Move(input_reg, Immediate(1));
4860 __ bind(&check_false);
4861 __ cmp(input_reg, factory()->false_value());
4862 DeoptimizeIf(not_equal, instr,
4863 Deoptimizer::kNotAHeapNumberUndefinedBoolean);
4864 __ Move(input_reg, Immediate(0));
4866 XMMRegister scratch = ToDoubleRegister(instr->temp());
4867 DCHECK(!scratch.is(xmm0));
4868 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
4869 isolate()->factory()->heap_number_map());
4870 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
4871 __ movsd(xmm0, FieldOperand(input_reg, HeapNumber::kValueOffset));
4872 __ cvttsd2si(input_reg, Operand(xmm0));
4873 __ Cvtsi2sd(scratch, Operand(input_reg));
4874 __ ucomisd(xmm0, scratch);
4875 DeoptimizeIf(not_equal, instr, Deoptimizer::kLostPrecision);
4876 DeoptimizeIf(parity_even, instr, Deoptimizer::kNaN);
4877 if (instr->hydrogen()->GetMinusZeroMode() == FAIL_ON_MINUS_ZERO) {
4878 __ test(input_reg, Operand(input_reg));
4879 __ j(not_zero, done);
4880 __ movmskpd(input_reg, xmm0);
4881 __ and_(input_reg, 1);
4882 DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
4888 void LCodeGen::DoTaggedToI(LTaggedToI* instr) {
4889 class DeferredTaggedToI final : public LDeferredCode {
4891 DeferredTaggedToI(LCodeGen* codegen, LTaggedToI* instr)
4892 : LDeferredCode(codegen), instr_(instr) { }
4893 void Generate() override { codegen()->DoDeferredTaggedToI(instr_, done()); }
4894 LInstruction* instr() override { return instr_; }
4900 LOperand* input = instr->value();
4901 DCHECK(input->IsRegister());
4902 Register input_reg = ToRegister(input);
4903 DCHECK(input_reg.is(ToRegister(instr->result())));
4905 if (instr->hydrogen()->value()->representation().IsSmi()) {
4906 __ SmiUntag(input_reg);
4908 DeferredTaggedToI* deferred =
4909 new(zone()) DeferredTaggedToI(this, instr);
4910 // Optimistically untag the input.
4911 // If the input is a HeapObject, SmiUntag will set the carry flag.
4912 STATIC_ASSERT(kSmiTagSize == 1 && kSmiTag == 0);
4913 __ SmiUntag(input_reg);
4914 // Branch to deferred code if the input was tagged.
4915 // The deferred code will take care of restoring the tag.
4916 __ j(carry, deferred->entry());
4917 __ bind(deferred->exit());
4922 void LCodeGen::DoNumberUntagD(LNumberUntagD* instr) {
4923 LOperand* input = instr->value();
4924 DCHECK(input->IsRegister());
4925 LOperand* temp = instr->temp();
4926 DCHECK(temp->IsRegister());
4927 LOperand* result = instr->result();
4928 DCHECK(result->IsDoubleRegister());
4930 Register input_reg = ToRegister(input);
4931 Register temp_reg = ToRegister(temp);
4933 HValue* value = instr->hydrogen()->value();
4934 NumberUntagDMode mode = value->representation().IsSmi()
4935 ? NUMBER_CANDIDATE_IS_SMI : NUMBER_CANDIDATE_IS_ANY_TAGGED;
4937 XMMRegister result_reg = ToDoubleRegister(result);
4938 EmitNumberUntagD(instr, input_reg, temp_reg, result_reg, mode);
4942 void LCodeGen::DoDoubleToI(LDoubleToI* instr) {
4943 LOperand* input = instr->value();
4944 DCHECK(input->IsDoubleRegister());
4945 LOperand* result = instr->result();
4946 DCHECK(result->IsRegister());
4947 Register result_reg = ToRegister(result);
4949 if (instr->truncating()) {
4950 XMMRegister input_reg = ToDoubleRegister(input);
4951 __ TruncateDoubleToI(result_reg, input_reg);
4953 Label lost_precision, is_nan, minus_zero, done;
4954 XMMRegister input_reg = ToDoubleRegister(input);
4955 XMMRegister xmm_scratch = double_scratch0();
4956 Label::Distance dist = DeoptEveryNTimes() ? Label::kFar : Label::kNear;
4957 __ DoubleToI(result_reg, input_reg, xmm_scratch,
4958 instr->hydrogen()->GetMinusZeroMode(), &lost_precision,
4959 &is_nan, &minus_zero, dist);
4960 __ jmp(&done, dist);
4961 __ bind(&lost_precision);
4962 DeoptimizeIf(no_condition, instr, Deoptimizer::kLostPrecision);
4964 DeoptimizeIf(no_condition, instr, Deoptimizer::kNaN);
4965 __ bind(&minus_zero);
4966 DeoptimizeIf(no_condition, instr, Deoptimizer::kMinusZero);
4972 void LCodeGen::DoDoubleToSmi(LDoubleToSmi* instr) {
4973 LOperand* input = instr->value();
4974 DCHECK(input->IsDoubleRegister());
4975 LOperand* result = instr->result();
4976 DCHECK(result->IsRegister());
4977 Register result_reg = ToRegister(result);
4979 Label lost_precision, is_nan, minus_zero, done;
4980 XMMRegister input_reg = ToDoubleRegister(input);
4981 XMMRegister xmm_scratch = double_scratch0();
4982 Label::Distance dist = DeoptEveryNTimes() ? Label::kFar : Label::kNear;
4983 __ DoubleToI(result_reg, input_reg, xmm_scratch,
4984 instr->hydrogen()->GetMinusZeroMode(), &lost_precision, &is_nan,
4986 __ jmp(&done, dist);
4987 __ bind(&lost_precision);
4988 DeoptimizeIf(no_condition, instr, Deoptimizer::kLostPrecision);
4990 DeoptimizeIf(no_condition, instr, Deoptimizer::kNaN);
4991 __ bind(&minus_zero);
4992 DeoptimizeIf(no_condition, instr, Deoptimizer::kMinusZero);
4994 __ SmiTag(result_reg);
4995 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
4999 void LCodeGen::DoCheckSmi(LCheckSmi* instr) {
5000 LOperand* input = instr->value();
5001 __ test(ToOperand(input), Immediate(kSmiTagMask));
5002 DeoptimizeIf(not_zero, instr, Deoptimizer::kNotASmi);
5006 void LCodeGen::DoCheckNonSmi(LCheckNonSmi* instr) {
5007 if (!instr->hydrogen()->value()->type().IsHeapObject()) {
5008 LOperand* input = instr->value();
5009 __ test(ToOperand(input), Immediate(kSmiTagMask));
5010 DeoptimizeIf(zero, instr, Deoptimizer::kSmi);
5015 void LCodeGen::DoCheckArrayBufferNotNeutered(
5016 LCheckArrayBufferNotNeutered* instr) {
5017 Register view = ToRegister(instr->view());
5018 Register scratch = ToRegister(instr->scratch());
5020 __ mov(scratch, FieldOperand(view, JSArrayBufferView::kBufferOffset));
5021 __ test_b(FieldOperand(scratch, JSArrayBuffer::kBitFieldOffset),
5022 1 << JSArrayBuffer::WasNeutered::kShift);
5023 DeoptimizeIf(not_zero, instr, Deoptimizer::kOutOfBounds);
5027 void LCodeGen::DoCheckInstanceType(LCheckInstanceType* instr) {
5028 Register input = ToRegister(instr->value());
5029 Register temp = ToRegister(instr->temp());
5031 __ mov(temp, FieldOperand(input, HeapObject::kMapOffset));
5033 if (instr->hydrogen()->is_interval_check()) {
5036 instr->hydrogen()->GetCheckInterval(&first, &last);
5038 __ cmpb(FieldOperand(temp, Map::kInstanceTypeOffset),
5039 static_cast<int8_t>(first));
5041 // If there is only one type in the interval check for equality.
5042 if (first == last) {
5043 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongInstanceType);
5045 DeoptimizeIf(below, instr, Deoptimizer::kWrongInstanceType);
5046 // Omit check for the last type.
5047 if (last != LAST_TYPE) {
5048 __ cmpb(FieldOperand(temp, Map::kInstanceTypeOffset),
5049 static_cast<int8_t>(last));
5050 DeoptimizeIf(above, instr, Deoptimizer::kWrongInstanceType);
5056 instr->hydrogen()->GetCheckMaskAndTag(&mask, &tag);
5058 if (base::bits::IsPowerOfTwo32(mask)) {
5059 DCHECK(tag == 0 || base::bits::IsPowerOfTwo32(tag));
5060 __ test_b(FieldOperand(temp, Map::kInstanceTypeOffset), mask);
5061 DeoptimizeIf(tag == 0 ? not_zero : zero, instr,
5062 Deoptimizer::kWrongInstanceType);
5064 __ movzx_b(temp, FieldOperand(temp, Map::kInstanceTypeOffset));
5065 __ and_(temp, mask);
5067 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongInstanceType);
5073 void LCodeGen::DoCheckValue(LCheckValue* instr) {
5074 Handle<HeapObject> object = instr->hydrogen()->object().handle();
5075 if (instr->hydrogen()->object_in_new_space()) {
5076 Register reg = ToRegister(instr->value());
5077 Handle<Cell> cell = isolate()->factory()->NewCell(object);
5078 __ cmp(reg, Operand::ForCell(cell));
5080 Operand operand = ToOperand(instr->value());
5081 __ cmp(operand, object);
5083 DeoptimizeIf(not_equal, instr, Deoptimizer::kValueMismatch);
5087 void LCodeGen::DoDeferredInstanceMigration(LCheckMaps* instr, Register object) {
5089 PushSafepointRegistersScope scope(this);
5092 __ CallRuntimeSaveDoubles(Runtime::kTryMigrateInstance);
5093 RecordSafepointWithRegisters(
5094 instr->pointer_map(), 1, Safepoint::kNoLazyDeopt);
5096 __ test(eax, Immediate(kSmiTagMask));
5098 DeoptimizeIf(zero, instr, Deoptimizer::kInstanceMigrationFailed);
5102 void LCodeGen::DoCheckMaps(LCheckMaps* instr) {
5103 class DeferredCheckMaps final : public LDeferredCode {
5105 DeferredCheckMaps(LCodeGen* codegen, LCheckMaps* instr, Register object)
5106 : LDeferredCode(codegen), instr_(instr), object_(object) {
5107 SetExit(check_maps());
5109 void Generate() override {
5110 codegen()->DoDeferredInstanceMigration(instr_, object_);
5112 Label* check_maps() { return &check_maps_; }
5113 LInstruction* instr() override { return instr_; }
5121 if (instr->hydrogen()->IsStabilityCheck()) {
5122 const UniqueSet<Map>* maps = instr->hydrogen()->maps();
5123 for (int i = 0; i < maps->size(); ++i) {
5124 AddStabilityDependency(maps->at(i).handle());
5129 LOperand* input = instr->value();
5130 DCHECK(input->IsRegister());
5131 Register reg = ToRegister(input);
5133 DeferredCheckMaps* deferred = NULL;
5134 if (instr->hydrogen()->HasMigrationTarget()) {
5135 deferred = new(zone()) DeferredCheckMaps(this, instr, reg);
5136 __ bind(deferred->check_maps());
5139 const UniqueSet<Map>* maps = instr->hydrogen()->maps();
5141 for (int i = 0; i < maps->size() - 1; i++) {
5142 Handle<Map> map = maps->at(i).handle();
5143 __ CompareMap(reg, map);
5144 __ j(equal, &success, Label::kNear);
5147 Handle<Map> map = maps->at(maps->size() - 1).handle();
5148 __ CompareMap(reg, map);
5149 if (instr->hydrogen()->HasMigrationTarget()) {
5150 __ j(not_equal, deferred->entry());
5152 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongMap);
5159 void LCodeGen::DoClampDToUint8(LClampDToUint8* instr) {
5160 XMMRegister value_reg = ToDoubleRegister(instr->unclamped());
5161 XMMRegister xmm_scratch = double_scratch0();
5162 Register result_reg = ToRegister(instr->result());
5163 __ ClampDoubleToUint8(value_reg, xmm_scratch, result_reg);
5167 void LCodeGen::DoClampIToUint8(LClampIToUint8* instr) {
5168 DCHECK(instr->unclamped()->Equals(instr->result()));
5169 Register value_reg = ToRegister(instr->result());
5170 __ ClampUint8(value_reg);
5174 void LCodeGen::DoClampTToUint8(LClampTToUint8* instr) {
5175 DCHECK(instr->unclamped()->Equals(instr->result()));
5176 Register input_reg = ToRegister(instr->unclamped());
5177 XMMRegister temp_xmm_reg = ToDoubleRegister(instr->temp_xmm());
5178 XMMRegister xmm_scratch = double_scratch0();
5179 Label is_smi, done, heap_number;
5181 __ JumpIfSmi(input_reg, &is_smi);
5183 // Check for heap number
5184 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
5185 factory()->heap_number_map());
5186 __ j(equal, &heap_number, Label::kNear);
5188 // Check for undefined. Undefined is converted to zero for clamping
5190 __ cmp(input_reg, factory()->undefined_value());
5191 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumberUndefined);
5192 __ mov(input_reg, 0);
5193 __ jmp(&done, Label::kNear);
5196 __ bind(&heap_number);
5197 __ movsd(xmm_scratch, FieldOperand(input_reg, HeapNumber::kValueOffset));
5198 __ ClampDoubleToUint8(xmm_scratch, temp_xmm_reg, input_reg);
5199 __ jmp(&done, Label::kNear);
5203 __ SmiUntag(input_reg);
5204 __ ClampUint8(input_reg);
5209 void LCodeGen::DoDoubleBits(LDoubleBits* instr) {
5210 XMMRegister value_reg = ToDoubleRegister(instr->value());
5211 Register result_reg = ToRegister(instr->result());
5212 if (instr->hydrogen()->bits() == HDoubleBits::HIGH) {
5213 if (CpuFeatures::IsSupported(SSE4_1)) {
5214 CpuFeatureScope scope2(masm(), SSE4_1);
5215 __ pextrd(result_reg, value_reg, 1);
5217 XMMRegister xmm_scratch = double_scratch0();
5218 __ pshufd(xmm_scratch, value_reg, 1);
5219 __ movd(result_reg, xmm_scratch);
5222 __ movd(result_reg, value_reg);
5227 void LCodeGen::DoConstructDouble(LConstructDouble* instr) {
5228 Register hi_reg = ToRegister(instr->hi());
5229 Register lo_reg = ToRegister(instr->lo());
5230 XMMRegister result_reg = ToDoubleRegister(instr->result());
5232 if (CpuFeatures::IsSupported(SSE4_1)) {
5233 CpuFeatureScope scope2(masm(), SSE4_1);
5234 __ movd(result_reg, lo_reg);
5235 __ pinsrd(result_reg, hi_reg, 1);
5237 XMMRegister xmm_scratch = double_scratch0();
5238 __ movd(result_reg, hi_reg);
5239 __ psllq(result_reg, 32);
5240 __ movd(xmm_scratch, lo_reg);
5241 __ orps(result_reg, xmm_scratch);
5246 void LCodeGen::DoAllocate(LAllocate* instr) {
5247 class DeferredAllocate final : public LDeferredCode {
5249 DeferredAllocate(LCodeGen* codegen, LAllocate* instr)
5250 : LDeferredCode(codegen), instr_(instr) { }
5251 void Generate() override { codegen()->DoDeferredAllocate(instr_); }
5252 LInstruction* instr() override { return instr_; }
5258 DeferredAllocate* deferred = new(zone()) DeferredAllocate(this, instr);
5260 Register result = ToRegister(instr->result());
5261 Register temp = ToRegister(instr->temp());
5263 // Allocate memory for the object.
5264 AllocationFlags flags = TAG_OBJECT;
5265 if (instr->hydrogen()->MustAllocateDoubleAligned()) {
5266 flags = static_cast<AllocationFlags>(flags | DOUBLE_ALIGNMENT);
5268 if (instr->hydrogen()->IsOldSpaceAllocation()) {
5269 DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
5270 flags = static_cast<AllocationFlags>(flags | PRETENURE);
5273 if (instr->size()->IsConstantOperand()) {
5274 int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
5275 if (size <= Page::kMaxRegularHeapObjectSize) {
5276 __ Allocate(size, result, temp, no_reg, deferred->entry(), flags);
5278 __ jmp(deferred->entry());
5281 Register size = ToRegister(instr->size());
5282 __ Allocate(size, result, temp, no_reg, deferred->entry(), flags);
5285 __ bind(deferred->exit());
5287 if (instr->hydrogen()->MustPrefillWithFiller()) {
5288 if (instr->size()->IsConstantOperand()) {
5289 int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
5290 __ mov(temp, (size / kPointerSize) - 1);
5292 temp = ToRegister(instr->size());
5293 __ shr(temp, kPointerSizeLog2);
5298 __ mov(FieldOperand(result, temp, times_pointer_size, 0),
5299 isolate()->factory()->one_pointer_filler_map());
5301 __ j(not_zero, &loop);
5306 void LCodeGen::DoDeferredAllocate(LAllocate* instr) {
5307 Register result = ToRegister(instr->result());
5309 // TODO(3095996): Get rid of this. For now, we need to make the
5310 // result register contain a valid pointer because it is already
5311 // contained in the register pointer map.
5312 __ Move(result, Immediate(Smi::FromInt(0)));
5314 PushSafepointRegistersScope scope(this);
5315 if (instr->size()->IsRegister()) {
5316 Register size = ToRegister(instr->size());
5317 DCHECK(!size.is(result));
5318 __ SmiTag(ToRegister(instr->size()));
5321 int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
5322 if (size >= 0 && size <= Smi::kMaxValue) {
5323 __ push(Immediate(Smi::FromInt(size)));
5325 // We should never get here at runtime => abort
5331 int flags = AllocateDoubleAlignFlag::encode(
5332 instr->hydrogen()->MustAllocateDoubleAligned());
5333 if (instr->hydrogen()->IsOldSpaceAllocation()) {
5334 DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
5335 flags = AllocateTargetSpace::update(flags, OLD_SPACE);
5337 flags = AllocateTargetSpace::update(flags, NEW_SPACE);
5339 __ push(Immediate(Smi::FromInt(flags)));
5341 CallRuntimeFromDeferred(
5342 Runtime::kAllocateInTargetSpace, 2, instr, instr->context());
5343 __ StoreToSafepointRegisterSlot(result, eax);
5347 void LCodeGen::DoToFastProperties(LToFastProperties* instr) {
5348 DCHECK(ToRegister(instr->value()).is(eax));
5350 CallRuntime(Runtime::kToFastProperties, 1, instr);
5354 void LCodeGen::DoRegExpLiteral(LRegExpLiteral* instr) {
5355 DCHECK(ToRegister(instr->context()).is(esi));
5357 // Registers will be used as follows:
5358 // ecx = literals array.
5359 // ebx = regexp literal.
5360 // eax = regexp literal clone.
5362 int literal_offset =
5363 FixedArray::OffsetOfElementAt(instr->hydrogen()->literal_index());
5364 __ LoadHeapObject(ecx, instr->hydrogen()->literals());
5365 __ mov(ebx, FieldOperand(ecx, literal_offset));
5366 __ cmp(ebx, factory()->undefined_value());
5367 __ j(not_equal, &materialized, Label::kNear);
5369 // Create regexp literal using runtime function
5370 // Result will be in eax.
5372 __ push(Immediate(Smi::FromInt(instr->hydrogen()->literal_index())));
5373 __ push(Immediate(instr->hydrogen()->pattern()));
5374 __ push(Immediate(instr->hydrogen()->flags()));
5375 CallRuntime(Runtime::kMaterializeRegExpLiteral, 4, instr);
5378 __ bind(&materialized);
5379 int size = JSRegExp::kSize + JSRegExp::kInObjectFieldCount * kPointerSize;
5380 Label allocated, runtime_allocate;
5381 __ Allocate(size, eax, ecx, edx, &runtime_allocate, TAG_OBJECT);
5382 __ jmp(&allocated, Label::kNear);
5384 __ bind(&runtime_allocate);
5386 __ push(Immediate(Smi::FromInt(size)));
5387 CallRuntime(Runtime::kAllocateInNewSpace, 1, instr);
5390 __ bind(&allocated);
5391 // Copy the content into the newly allocated memory.
5392 // (Unroll copy loop once for better throughput).
5393 for (int i = 0; i < size - kPointerSize; i += 2 * kPointerSize) {
5394 __ mov(edx, FieldOperand(ebx, i));
5395 __ mov(ecx, FieldOperand(ebx, i + kPointerSize));
5396 __ mov(FieldOperand(eax, i), edx);
5397 __ mov(FieldOperand(eax, i + kPointerSize), ecx);
5399 if ((size % (2 * kPointerSize)) != 0) {
5400 __ mov(edx, FieldOperand(ebx, size - kPointerSize));
5401 __ mov(FieldOperand(eax, size - kPointerSize), edx);
5406 void LCodeGen::DoFunctionLiteral(LFunctionLiteral* instr) {
5407 DCHECK(ToRegister(instr->context()).is(esi));
5408 // Use the fast case closure allocation code that allocates in new
5409 // space for nested functions that don't need literals cloning.
5410 bool pretenure = instr->hydrogen()->pretenure();
5411 if (!pretenure && instr->hydrogen()->has_no_literals()) {
5412 FastNewClosureStub stub(isolate(), instr->hydrogen()->language_mode(),
5413 instr->hydrogen()->kind());
5414 __ mov(ebx, Immediate(instr->hydrogen()->shared_info()));
5415 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
5418 __ push(Immediate(instr->hydrogen()->shared_info()));
5419 __ push(Immediate(pretenure ? factory()->true_value()
5420 : factory()->false_value()));
5421 CallRuntime(Runtime::kNewClosure, 3, instr);
5426 void LCodeGen::DoTypeof(LTypeof* instr) {
5427 DCHECK(ToRegister(instr->context()).is(esi));
5428 DCHECK(ToRegister(instr->value()).is(ebx));
5430 Register value_register = ToRegister(instr->value());
5431 __ JumpIfNotSmi(value_register, &do_call);
5432 __ mov(eax, Immediate(isolate()->factory()->number_string()));
5435 TypeofStub stub(isolate());
5436 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
5441 void LCodeGen::DoTypeofIsAndBranch(LTypeofIsAndBranch* instr) {
5442 Register input = ToRegister(instr->value());
5443 Condition final_branch_condition = EmitTypeofIs(instr, input);
5444 if (final_branch_condition != no_condition) {
5445 EmitBranch(instr, final_branch_condition);
5450 Condition LCodeGen::EmitTypeofIs(LTypeofIsAndBranch* instr, Register input) {
5451 Label* true_label = instr->TrueLabel(chunk_);
5452 Label* false_label = instr->FalseLabel(chunk_);
5453 Handle<String> type_name = instr->type_literal();
5454 int left_block = instr->TrueDestination(chunk_);
5455 int right_block = instr->FalseDestination(chunk_);
5456 int next_block = GetNextEmittedBlock();
5458 Label::Distance true_distance = left_block == next_block ? Label::kNear
5460 Label::Distance false_distance = right_block == next_block ? Label::kNear
5462 Condition final_branch_condition = no_condition;
5463 if (String::Equals(type_name, factory()->number_string())) {
5464 __ JumpIfSmi(input, true_label, true_distance);
5465 __ cmp(FieldOperand(input, HeapObject::kMapOffset),
5466 factory()->heap_number_map());
5467 final_branch_condition = equal;
5469 } else if (String::Equals(type_name, factory()->string_string())) {
5470 __ JumpIfSmi(input, false_label, false_distance);
5471 __ CmpObjectType(input, FIRST_NONSTRING_TYPE, input);
5472 __ j(above_equal, false_label, false_distance);
5473 __ test_b(FieldOperand(input, Map::kBitFieldOffset),
5474 1 << Map::kIsUndetectable);
5475 final_branch_condition = zero;
5477 } else if (String::Equals(type_name, factory()->symbol_string())) {
5478 __ JumpIfSmi(input, false_label, false_distance);
5479 __ CmpObjectType(input, SYMBOL_TYPE, input);
5480 final_branch_condition = equal;
5482 } else if (String::Equals(type_name, factory()->boolean_string())) {
5483 __ cmp(input, factory()->true_value());
5484 __ j(equal, true_label, true_distance);
5485 __ cmp(input, factory()->false_value());
5486 final_branch_condition = equal;
5488 } else if (String::Equals(type_name, factory()->undefined_string())) {
5489 __ cmp(input, factory()->undefined_value());
5490 __ j(equal, true_label, true_distance);
5491 __ JumpIfSmi(input, false_label, false_distance);
5492 // Check for undetectable objects => true.
5493 __ mov(input, FieldOperand(input, HeapObject::kMapOffset));
5494 __ test_b(FieldOperand(input, Map::kBitFieldOffset),
5495 1 << Map::kIsUndetectable);
5496 final_branch_condition = not_zero;
5498 } else if (String::Equals(type_name, factory()->function_string())) {
5499 STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
5500 __ JumpIfSmi(input, false_label, false_distance);
5501 __ CmpObjectType(input, JS_FUNCTION_TYPE, input);
5502 __ j(equal, true_label, true_distance);
5503 __ CmpInstanceType(input, JS_FUNCTION_PROXY_TYPE);
5504 final_branch_condition = equal;
5506 } else if (String::Equals(type_name, factory()->object_string())) {
5507 __ JumpIfSmi(input, false_label, false_distance);
5508 __ cmp(input, factory()->null_value());
5509 __ j(equal, true_label, true_distance);
5510 __ CmpObjectType(input, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE, input);
5511 __ j(below, false_label, false_distance);
5512 __ CmpInstanceType(input, LAST_NONCALLABLE_SPEC_OBJECT_TYPE);
5513 __ j(above, false_label, false_distance);
5514 // Check for undetectable objects => false.
5515 __ test_b(FieldOperand(input, Map::kBitFieldOffset),
5516 1 << Map::kIsUndetectable);
5517 final_branch_condition = zero;
5519 } else if (String::Equals(type_name, factory()->float32x4_string())) {
5520 __ JumpIfSmi(input, false_label, false_distance);
5521 __ CmpObjectType(input, FLOAT32X4_TYPE, input);
5522 final_branch_condition = equal;
5525 __ jmp(false_label, false_distance);
5527 return final_branch_condition;
5531 void LCodeGen::DoIsConstructCallAndBranch(LIsConstructCallAndBranch* instr) {
5532 Register temp = ToRegister(instr->temp());
5534 EmitIsConstructCall(temp);
5535 EmitBranch(instr, equal);
5539 void LCodeGen::EmitIsConstructCall(Register temp) {
5540 // Get the frame pointer for the calling frame.
5541 __ mov(temp, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
5543 // Skip the arguments adaptor frame if it exists.
5544 Label check_frame_marker;
5545 __ cmp(Operand(temp, StandardFrameConstants::kContextOffset),
5546 Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
5547 __ j(not_equal, &check_frame_marker, Label::kNear);
5548 __ mov(temp, Operand(temp, StandardFrameConstants::kCallerFPOffset));
5550 // Check the marker in the calling frame.
5551 __ bind(&check_frame_marker);
5552 __ cmp(Operand(temp, StandardFrameConstants::kMarkerOffset),
5553 Immediate(Smi::FromInt(StackFrame::CONSTRUCT)));
5557 void LCodeGen::EnsureSpaceForLazyDeopt(int space_needed) {
5558 if (!info()->IsStub()) {
5559 // Ensure that we have enough space after the previous lazy-bailout
5560 // instruction for patching the code here.
5561 int current_pc = masm()->pc_offset();
5562 if (current_pc < last_lazy_deopt_pc_ + space_needed) {
5563 int padding_size = last_lazy_deopt_pc_ + space_needed - current_pc;
5564 __ Nop(padding_size);
5567 last_lazy_deopt_pc_ = masm()->pc_offset();
5571 void LCodeGen::DoLazyBailout(LLazyBailout* instr) {
5572 last_lazy_deopt_pc_ = masm()->pc_offset();
5573 DCHECK(instr->HasEnvironment());
5574 LEnvironment* env = instr->environment();
5575 RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt);
5576 safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
5580 void LCodeGen::DoDeoptimize(LDeoptimize* instr) {
5581 Deoptimizer::BailoutType type = instr->hydrogen()->type();
5582 // TODO(danno): Stubs expect all deopts to be lazy for historical reasons (the
5583 // needed return address), even though the implementation of LAZY and EAGER is
5584 // now identical. When LAZY is eventually completely folded into EAGER, remove
5585 // the special case below.
5586 if (info()->IsStub() && type == Deoptimizer::EAGER) {
5587 type = Deoptimizer::LAZY;
5589 DeoptimizeIf(no_condition, instr, instr->hydrogen()->reason(), type);
5593 void LCodeGen::DoDummy(LDummy* instr) {
5594 // Nothing to see here, move on!
5598 void LCodeGen::DoDummyUse(LDummyUse* instr) {
5599 // Nothing to see here, move on!
5603 void LCodeGen::DoDeferredStackCheck(LStackCheck* instr) {
5604 PushSafepointRegistersScope scope(this);
5605 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
5606 __ CallRuntimeSaveDoubles(Runtime::kStackGuard);
5607 RecordSafepointWithLazyDeopt(
5608 instr, RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
5609 DCHECK(instr->HasEnvironment());
5610 LEnvironment* env = instr->environment();
5611 safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
5615 void LCodeGen::DoStackCheck(LStackCheck* instr) {
5616 class DeferredStackCheck final : public LDeferredCode {
5618 DeferredStackCheck(LCodeGen* codegen, LStackCheck* instr)
5619 : LDeferredCode(codegen), instr_(instr) { }
5620 void Generate() override { codegen()->DoDeferredStackCheck(instr_); }
5621 LInstruction* instr() override { return instr_; }
5624 LStackCheck* instr_;
5627 DCHECK(instr->HasEnvironment());
5628 LEnvironment* env = instr->environment();
5629 // There is no LLazyBailout instruction for stack-checks. We have to
5630 // prepare for lazy deoptimization explicitly here.
5631 if (instr->hydrogen()->is_function_entry()) {
5632 // Perform stack overflow check.
5634 ExternalReference stack_limit =
5635 ExternalReference::address_of_stack_limit(isolate());
5636 __ cmp(esp, Operand::StaticVariable(stack_limit));
5637 __ j(above_equal, &done, Label::kNear);
5639 DCHECK(instr->context()->IsRegister());
5640 DCHECK(ToRegister(instr->context()).is(esi));
5641 CallCode(isolate()->builtins()->StackCheck(),
5642 RelocInfo::CODE_TARGET,
5646 DCHECK(instr->hydrogen()->is_backwards_branch());
5647 // Perform stack overflow check if this goto needs it before jumping.
5648 DeferredStackCheck* deferred_stack_check =
5649 new(zone()) DeferredStackCheck(this, instr);
5650 ExternalReference stack_limit =
5651 ExternalReference::address_of_stack_limit(isolate());
5652 __ cmp(esp, Operand::StaticVariable(stack_limit));
5653 __ j(below, deferred_stack_check->entry());
5654 EnsureSpaceForLazyDeopt(Deoptimizer::patch_size());
5655 __ bind(instr->done_label());
5656 deferred_stack_check->SetExit(instr->done_label());
5657 RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt);
5658 // Don't record a deoptimization index for the safepoint here.
5659 // This will be done explicitly when emitting call and the safepoint in
5660 // the deferred code.
5665 void LCodeGen::DoOsrEntry(LOsrEntry* instr) {
5666 // This is a pseudo-instruction that ensures that the environment here is
5667 // properly registered for deoptimization and records the assembler's PC
5669 LEnvironment* environment = instr->environment();
5671 // If the environment were already registered, we would have no way of
5672 // backpatching it with the spill slot operands.
5673 DCHECK(!environment->HasBeenRegistered());
5674 RegisterEnvironmentForDeoptimization(environment, Safepoint::kNoLazyDeopt);
5676 GenerateOsrPrologue();
5680 void LCodeGen::DoForInPrepareMap(LForInPrepareMap* instr) {
5681 DCHECK(ToRegister(instr->context()).is(esi));
5682 __ test(eax, Immediate(kSmiTagMask));
5683 DeoptimizeIf(zero, instr, Deoptimizer::kSmi);
5685 STATIC_ASSERT(FIRST_JS_PROXY_TYPE == FIRST_SPEC_OBJECT_TYPE);
5686 __ CmpObjectType(eax, LAST_JS_PROXY_TYPE, ecx);
5687 DeoptimizeIf(below_equal, instr, Deoptimizer::kWrongInstanceType);
5689 Label use_cache, call_runtime;
5690 __ CheckEnumCache(&call_runtime);
5692 __ mov(eax, FieldOperand(eax, HeapObject::kMapOffset));
5693 __ jmp(&use_cache, Label::kNear);
5695 // Get the set of properties to enumerate.
5696 __ bind(&call_runtime);
5698 CallRuntime(Runtime::kGetPropertyNamesFast, 1, instr);
5700 __ cmp(FieldOperand(eax, HeapObject::kMapOffset),
5701 isolate()->factory()->meta_map());
5702 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongMap);
5703 __ bind(&use_cache);
5707 void LCodeGen::DoForInCacheArray(LForInCacheArray* instr) {
5708 Register map = ToRegister(instr->map());
5709 Register result = ToRegister(instr->result());
5710 Label load_cache, done;
5711 __ EnumLength(result, map);
5712 __ cmp(result, Immediate(Smi::FromInt(0)));
5713 __ j(not_equal, &load_cache, Label::kNear);
5714 __ mov(result, isolate()->factory()->empty_fixed_array());
5715 __ jmp(&done, Label::kNear);
5717 __ bind(&load_cache);
5718 __ LoadInstanceDescriptors(map, result);
5720 FieldOperand(result, DescriptorArray::kEnumCacheOffset));
5722 FieldOperand(result, FixedArray::SizeFor(instr->idx())));
5724 __ test(result, result);
5725 DeoptimizeIf(equal, instr, Deoptimizer::kNoCache);
5729 void LCodeGen::DoCheckMapValue(LCheckMapValue* instr) {
5730 Register object = ToRegister(instr->value());
5731 __ cmp(ToRegister(instr->map()),
5732 FieldOperand(object, HeapObject::kMapOffset));
5733 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongMap);
5737 void LCodeGen::DoDeferredLoadMutableDouble(LLoadFieldByIndex* instr,
5740 PushSafepointRegistersScope scope(this);
5744 __ CallRuntimeSaveDoubles(Runtime::kLoadMutableDouble);
5745 RecordSafepointWithRegisters(
5746 instr->pointer_map(), 2, Safepoint::kNoLazyDeopt);
5747 __ StoreToSafepointRegisterSlot(object, eax);
5751 void LCodeGen::DoLoadFieldByIndex(LLoadFieldByIndex* instr) {
5752 class DeferredLoadMutableDouble final : public LDeferredCode {
5754 DeferredLoadMutableDouble(LCodeGen* codegen,
5755 LLoadFieldByIndex* instr,
5758 : LDeferredCode(codegen),
5763 void Generate() override {
5764 codegen()->DoDeferredLoadMutableDouble(instr_, object_, index_);
5766 LInstruction* instr() override { return instr_; }
5769 LLoadFieldByIndex* instr_;
5774 Register object = ToRegister(instr->object());
5775 Register index = ToRegister(instr->index());
5777 DeferredLoadMutableDouble* deferred;
5778 deferred = new(zone()) DeferredLoadMutableDouble(
5779 this, instr, object, index);
5781 Label out_of_object, done;
5782 __ test(index, Immediate(Smi::FromInt(1)));
5783 __ j(not_zero, deferred->entry());
5787 __ cmp(index, Immediate(0));
5788 __ j(less, &out_of_object, Label::kNear);
5789 __ mov(object, FieldOperand(object,
5791 times_half_pointer_size,
5792 JSObject::kHeaderSize));
5793 __ jmp(&done, Label::kNear);
5795 __ bind(&out_of_object);
5796 __ mov(object, FieldOperand(object, JSObject::kPropertiesOffset));
5798 // Index is now equal to out of object property index plus 1.
5799 __ mov(object, FieldOperand(object,
5801 times_half_pointer_size,
5802 FixedArray::kHeaderSize - kPointerSize));
5803 __ bind(deferred->exit());
5808 void LCodeGen::DoStoreFrameContext(LStoreFrameContext* instr) {
5809 Register context = ToRegister(instr->context());
5810 __ mov(Operand(ebp, StandardFrameConstants::kContextOffset), context);
5814 void LCodeGen::DoAllocateBlockContext(LAllocateBlockContext* instr) {
5815 Handle<ScopeInfo> scope_info = instr->scope_info();
5816 __ Push(scope_info);
5817 __ push(ToRegister(instr->function()));
5818 CallRuntime(Runtime::kPushBlockContext, 2, instr);
5819 RecordSafepoint(Safepoint::kNoLazyDeopt);
5825 } // namespace internal
5828 #endif // V8_TARGET_ARCH_IA32