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();
621 // The output frame height does not include the parameters.
622 int height = translation_size - environment->parameter_count();
624 WriteTranslation(environment->outer(), translation);
625 bool has_closure_id = !info()->closure().is_null() &&
626 !info()->closure().is_identical_to(environment->closure());
627 int closure_id = has_closure_id
628 ? DefineDeoptimizationLiteral(environment->closure())
629 : Translation::kSelfLiteralId;
630 switch (environment->frame_type()) {
632 translation->BeginJSFrame(environment->ast_id(), closure_id, height);
635 translation->BeginConstructStubFrame(closure_id, translation_size);
638 DCHECK(translation_size == 1);
640 translation->BeginGetterStubFrame(closure_id);
643 DCHECK(translation_size == 2);
645 translation->BeginSetterStubFrame(closure_id);
647 case ARGUMENTS_ADAPTOR:
648 translation->BeginArgumentsAdaptorFrame(closure_id, translation_size);
651 translation->BeginCompiledStubFrame(translation_size);
657 int object_index = 0;
658 int dematerialized_index = 0;
659 for (int i = 0; i < translation_size; ++i) {
660 LOperand* value = environment->values()->at(i);
661 AddToTranslation(environment,
664 environment->HasTaggedValueAt(i),
665 environment->HasUint32ValueAt(i),
667 &dematerialized_index);
672 void LCodeGen::AddToTranslation(LEnvironment* environment,
673 Translation* translation,
677 int* object_index_pointer,
678 int* dematerialized_index_pointer) {
679 if (op == LEnvironment::materialization_marker()) {
680 int object_index = (*object_index_pointer)++;
681 if (environment->ObjectIsDuplicateAt(object_index)) {
682 int dupe_of = environment->ObjectDuplicateOfAt(object_index);
683 translation->DuplicateObject(dupe_of);
686 int object_length = environment->ObjectLengthAt(object_index);
687 if (environment->ObjectIsArgumentsAt(object_index)) {
688 translation->BeginArgumentsObject(object_length);
690 translation->BeginCapturedObject(object_length);
692 int dematerialized_index = *dematerialized_index_pointer;
693 int env_offset = environment->translation_size() + dematerialized_index;
694 *dematerialized_index_pointer += object_length;
695 for (int i = 0; i < object_length; ++i) {
696 LOperand* value = environment->values()->at(env_offset + i);
697 AddToTranslation(environment,
700 environment->HasTaggedValueAt(env_offset + i),
701 environment->HasUint32ValueAt(env_offset + i),
702 object_index_pointer,
703 dematerialized_index_pointer);
708 if (op->IsStackSlot()) {
710 translation->StoreStackSlot(op->index());
711 } else if (is_uint32) {
712 translation->StoreUint32StackSlot(op->index());
714 translation->StoreInt32StackSlot(op->index());
716 } else if (op->IsDoubleStackSlot()) {
717 translation->StoreDoubleStackSlot(op->index());
718 } else if (op->IsRegister()) {
719 Register reg = ToRegister(op);
721 translation->StoreRegister(reg);
722 } else if (is_uint32) {
723 translation->StoreUint32Register(reg);
725 translation->StoreInt32Register(reg);
727 } else if (op->IsDoubleRegister()) {
728 XMMRegister reg = ToDoubleRegister(op);
729 translation->StoreDoubleRegister(reg);
730 } else if (op->IsConstantOperand()) {
731 HConstant* constant = chunk()->LookupConstant(LConstantOperand::cast(op));
732 int src_index = DefineDeoptimizationLiteral(constant->handle(isolate()));
733 translation->StoreLiteral(src_index);
740 void LCodeGen::CallCodeGeneric(Handle<Code> code,
741 RelocInfo::Mode mode,
743 SafepointMode safepoint_mode) {
744 DCHECK(instr != NULL);
746 RecordSafepointWithLazyDeopt(instr, safepoint_mode);
748 // Signal that we don't inline smi code before these stubs in the
749 // optimizing code generator.
750 if (code->kind() == Code::BINARY_OP_IC ||
751 code->kind() == Code::COMPARE_IC) {
757 void LCodeGen::CallCode(Handle<Code> code,
758 RelocInfo::Mode mode,
759 LInstruction* instr) {
760 CallCodeGeneric(code, mode, instr, RECORD_SIMPLE_SAFEPOINT);
764 void LCodeGen::CallRuntime(const Runtime::Function* fun,
767 SaveFPRegsMode save_doubles) {
768 DCHECK(instr != NULL);
769 DCHECK(instr->HasPointerMap());
771 __ CallRuntime(fun, argc, save_doubles);
773 RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
775 DCHECK(info()->is_calling());
779 void LCodeGen::LoadContextFromDeferred(LOperand* context) {
780 if (context->IsRegister()) {
781 if (!ToRegister(context).is(esi)) {
782 __ mov(esi, ToRegister(context));
784 } else if (context->IsStackSlot()) {
785 __ mov(esi, ToOperand(context));
786 } else if (context->IsConstantOperand()) {
787 HConstant* constant =
788 chunk_->LookupConstant(LConstantOperand::cast(context));
789 __ LoadObject(esi, Handle<Object>::cast(constant->handle(isolate())));
795 void LCodeGen::CallRuntimeFromDeferred(Runtime::FunctionId id,
799 LoadContextFromDeferred(context);
801 __ CallRuntimeSaveDoubles(id);
802 RecordSafepointWithRegisters(
803 instr->pointer_map(), argc, Safepoint::kNoLazyDeopt);
805 DCHECK(info()->is_calling());
809 void LCodeGen::RegisterEnvironmentForDeoptimization(
810 LEnvironment* environment, Safepoint::DeoptMode mode) {
811 environment->set_has_been_used();
812 if (!environment->HasBeenRegistered()) {
813 // Physical stack frame layout:
814 // -x ............. -4 0 ..................................... y
815 // [incoming arguments] [spill slots] [pushed outgoing arguments]
817 // Layout of the environment:
818 // 0 ..................................................... size-1
819 // [parameters] [locals] [expression stack including arguments]
821 // Layout of the translation:
822 // 0 ........................................................ size - 1 + 4
823 // [expression stack including arguments] [locals] [4 words] [parameters]
824 // |>------------ translation_size ------------<|
827 int jsframe_count = 0;
828 for (LEnvironment* e = environment; e != NULL; e = e->outer()) {
830 if (e->frame_type() == JS_FUNCTION) {
834 Translation translation(&translations_, frame_count, jsframe_count, zone());
835 WriteTranslation(environment, &translation);
836 int deoptimization_index = deoptimizations_.length();
837 int pc_offset = masm()->pc_offset();
838 environment->Register(deoptimization_index,
840 (mode == Safepoint::kLazyDeopt) ? pc_offset : -1);
841 deoptimizations_.Add(environment, zone());
846 void LCodeGen::DeoptimizeIf(Condition cc, LInstruction* instr,
847 Deoptimizer::DeoptReason deopt_reason,
848 Deoptimizer::BailoutType bailout_type) {
849 LEnvironment* environment = instr->environment();
850 RegisterEnvironmentForDeoptimization(environment, Safepoint::kNoLazyDeopt);
851 DCHECK(environment->HasBeenRegistered());
852 int id = environment->deoptimization_index();
853 DCHECK(info()->IsOptimizing() || info()->IsStub());
855 Deoptimizer::GetDeoptimizationEntry(isolate(), id, bailout_type);
857 Abort(kBailoutWasNotPrepared);
861 if (DeoptEveryNTimes()) {
862 ExternalReference count = ExternalReference::stress_deopt_count(isolate());
866 __ mov(eax, Operand::StaticVariable(count));
867 __ sub(eax, Immediate(1));
868 __ j(not_zero, &no_deopt, Label::kNear);
869 if (FLAG_trap_on_deopt) __ int3();
870 __ mov(eax, Immediate(FLAG_deopt_every_n_times));
871 __ mov(Operand::StaticVariable(count), eax);
874 DCHECK(frame_is_built_);
875 __ call(entry, RelocInfo::RUNTIME_ENTRY);
877 __ mov(Operand::StaticVariable(count), eax);
882 if (info()->ShouldTrapOnDeopt()) {
884 if (cc != no_condition) __ j(NegateCondition(cc), &done, Label::kNear);
889 Deoptimizer::DeoptInfo deopt_info = MakeDeoptInfo(instr, deopt_reason);
891 DCHECK(info()->IsStub() || frame_is_built_);
892 if (cc == no_condition && frame_is_built_) {
893 DeoptComment(deopt_info);
894 __ call(entry, RelocInfo::RUNTIME_ENTRY);
895 info()->LogDeoptCallPosition(masm()->pc_offset(), deopt_info.inlining_id);
897 Deoptimizer::JumpTableEntry table_entry(entry, deopt_info, bailout_type,
899 // We often have several deopts to the same entry, reuse the last
900 // jump entry if this is the case.
901 if (FLAG_trace_deopt || isolate()->cpu_profiler()->is_profiling() ||
902 jump_table_.is_empty() ||
903 !table_entry.IsEquivalentTo(jump_table_.last())) {
904 jump_table_.Add(table_entry, zone());
906 if (cc == no_condition) {
907 __ jmp(&jump_table_.last().label);
909 __ j(cc, &jump_table_.last().label);
915 void LCodeGen::DeoptimizeIf(Condition cc, LInstruction* instr,
916 Deoptimizer::DeoptReason deopt_reason) {
917 Deoptimizer::BailoutType bailout_type = info()->IsStub()
919 : Deoptimizer::EAGER;
920 DeoptimizeIf(cc, instr, deopt_reason, bailout_type);
924 void LCodeGen::PopulateDeoptimizationData(Handle<Code> code) {
925 int length = deoptimizations_.length();
926 if (length == 0) return;
927 Handle<DeoptimizationInputData> data =
928 DeoptimizationInputData::New(isolate(), length, TENURED);
930 Handle<ByteArray> translations =
931 translations_.CreateByteArray(isolate()->factory());
932 data->SetTranslationByteArray(*translations);
933 data->SetInlinedFunctionCount(Smi::FromInt(inlined_function_count_));
934 data->SetOptimizationId(Smi::FromInt(info_->optimization_id()));
935 if (info_->IsOptimizing()) {
936 // Reference to shared function info does not change between phases.
937 AllowDeferredHandleDereference allow_handle_dereference;
938 data->SetSharedFunctionInfo(*info_->shared_info());
940 data->SetSharedFunctionInfo(Smi::FromInt(0));
942 data->SetWeakCellCache(Smi::FromInt(0));
944 Handle<FixedArray> literals =
945 factory()->NewFixedArray(deoptimization_literals_.length(), TENURED);
946 { AllowDeferredHandleDereference copy_handles;
947 for (int i = 0; i < deoptimization_literals_.length(); i++) {
948 literals->set(i, *deoptimization_literals_[i]);
950 data->SetLiteralArray(*literals);
953 data->SetOsrAstId(Smi::FromInt(info_->osr_ast_id().ToInt()));
954 data->SetOsrPcOffset(Smi::FromInt(osr_pc_offset_));
956 // Populate the deoptimization entries.
957 for (int i = 0; i < length; i++) {
958 LEnvironment* env = deoptimizations_[i];
959 data->SetAstId(i, env->ast_id());
960 data->SetTranslationIndex(i, Smi::FromInt(env->translation_index()));
961 data->SetArgumentsStackHeight(i,
962 Smi::FromInt(env->arguments_stack_height()));
963 data->SetPc(i, Smi::FromInt(env->pc_offset()));
965 code->set_deoptimization_data(*data);
969 int LCodeGen::DefineDeoptimizationLiteral(Handle<Object> literal) {
970 int result = deoptimization_literals_.length();
971 for (int i = 0; i < deoptimization_literals_.length(); ++i) {
972 if (deoptimization_literals_[i].is_identical_to(literal)) return i;
974 deoptimization_literals_.Add(literal, zone());
979 void LCodeGen::PopulateDeoptimizationLiteralsWithInlinedFunctions() {
980 DCHECK_EQ(0, deoptimization_literals_.length());
981 for (auto function : chunk()->inlined_functions()) {
982 DefineDeoptimizationLiteral(function);
984 inlined_function_count_ = deoptimization_literals_.length();
988 void LCodeGen::RecordSafepointWithLazyDeopt(
989 LInstruction* instr, SafepointMode safepoint_mode) {
990 if (safepoint_mode == RECORD_SIMPLE_SAFEPOINT) {
991 RecordSafepoint(instr->pointer_map(), Safepoint::kLazyDeopt);
993 DCHECK(safepoint_mode == RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
994 RecordSafepointWithRegisters(
995 instr->pointer_map(), 0, Safepoint::kLazyDeopt);
1000 void LCodeGen::RecordSafepoint(
1001 LPointerMap* pointers,
1002 Safepoint::Kind kind,
1004 Safepoint::DeoptMode deopt_mode) {
1005 DCHECK(kind == expected_safepoint_kind_);
1006 const ZoneList<LOperand*>* operands = pointers->GetNormalizedOperands();
1007 Safepoint safepoint =
1008 safepoints_.DefineSafepoint(masm(), kind, arguments, deopt_mode);
1009 for (int i = 0; i < operands->length(); i++) {
1010 LOperand* pointer = operands->at(i);
1011 if (pointer->IsStackSlot()) {
1012 safepoint.DefinePointerSlot(pointer->index(), zone());
1013 } else if (pointer->IsRegister() && (kind & Safepoint::kWithRegisters)) {
1014 safepoint.DefinePointerRegister(ToRegister(pointer), zone());
1020 void LCodeGen::RecordSafepoint(LPointerMap* pointers,
1021 Safepoint::DeoptMode mode) {
1022 RecordSafepoint(pointers, Safepoint::kSimple, 0, mode);
1026 void LCodeGen::RecordSafepoint(Safepoint::DeoptMode mode) {
1027 LPointerMap empty_pointers(zone());
1028 RecordSafepoint(&empty_pointers, mode);
1032 void LCodeGen::RecordSafepointWithRegisters(LPointerMap* pointers,
1034 Safepoint::DeoptMode mode) {
1035 RecordSafepoint(pointers, Safepoint::kWithRegisters, arguments, mode);
1039 void LCodeGen::RecordAndWritePosition(int position) {
1040 if (position == RelocInfo::kNoPosition) return;
1041 masm()->positions_recorder()->RecordPosition(position);
1042 masm()->positions_recorder()->WriteRecordedPositions();
1046 static const char* LabelType(LLabel* label) {
1047 if (label->is_loop_header()) return " (loop header)";
1048 if (label->is_osr_entry()) return " (OSR entry)";
1053 void LCodeGen::DoLabel(LLabel* label) {
1054 Comment(";;; <@%d,#%d> -------------------- B%d%s --------------------",
1055 current_instruction_,
1056 label->hydrogen_value()->id(),
1059 __ bind(label->label());
1060 current_block_ = label->block_id();
1065 void LCodeGen::DoParallelMove(LParallelMove* move) {
1066 resolver_.Resolve(move);
1070 void LCodeGen::DoGap(LGap* gap) {
1071 for (int i = LGap::FIRST_INNER_POSITION;
1072 i <= LGap::LAST_INNER_POSITION;
1074 LGap::InnerPosition inner_pos = static_cast<LGap::InnerPosition>(i);
1075 LParallelMove* move = gap->GetParallelMove(inner_pos);
1076 if (move != NULL) DoParallelMove(move);
1081 void LCodeGen::DoInstructionGap(LInstructionGap* instr) {
1086 void LCodeGen::DoParameter(LParameter* instr) {
1091 void LCodeGen::DoCallStub(LCallStub* instr) {
1092 DCHECK(ToRegister(instr->context()).is(esi));
1093 DCHECK(ToRegister(instr->result()).is(eax));
1094 switch (instr->hydrogen()->major_key()) {
1095 case CodeStub::RegExpExec: {
1096 RegExpExecStub stub(isolate());
1097 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
1100 case CodeStub::SubString: {
1101 SubStringStub stub(isolate());
1102 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
1105 case CodeStub::StringCompare: {
1106 StringCompareStub stub(isolate());
1107 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
1116 void LCodeGen::DoUnknownOSRValue(LUnknownOSRValue* instr) {
1117 GenerateOsrPrologue();
1121 void LCodeGen::DoModByPowerOf2I(LModByPowerOf2I* instr) {
1122 Register dividend = ToRegister(instr->dividend());
1123 int32_t divisor = instr->divisor();
1124 DCHECK(dividend.is(ToRegister(instr->result())));
1126 // Theoretically, a variation of the branch-free code for integer division by
1127 // a power of 2 (calculating the remainder via an additional multiplication
1128 // (which gets simplified to an 'and') and subtraction) should be faster, and
1129 // this is exactly what GCC and clang emit. Nevertheless, benchmarks seem to
1130 // indicate that positive dividends are heavily favored, so the branching
1131 // version performs better.
1132 HMod* hmod = instr->hydrogen();
1133 int32_t mask = divisor < 0 ? -(divisor + 1) : (divisor - 1);
1134 Label dividend_is_not_negative, done;
1135 if (hmod->CheckFlag(HValue::kLeftCanBeNegative)) {
1136 __ test(dividend, dividend);
1137 __ j(not_sign, ÷nd_is_not_negative, Label::kNear);
1138 // Note that this is correct even for kMinInt operands.
1140 __ and_(dividend, mask);
1142 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1143 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1145 __ jmp(&done, Label::kNear);
1148 __ bind(÷nd_is_not_negative);
1149 __ and_(dividend, mask);
1154 void LCodeGen::DoModByConstI(LModByConstI* instr) {
1155 Register dividend = ToRegister(instr->dividend());
1156 int32_t divisor = instr->divisor();
1157 DCHECK(ToRegister(instr->result()).is(eax));
1160 DeoptimizeIf(no_condition, instr, Deoptimizer::kDivisionByZero);
1164 __ TruncatingDiv(dividend, Abs(divisor));
1165 __ imul(edx, edx, Abs(divisor));
1166 __ mov(eax, dividend);
1169 // Check for negative zero.
1170 HMod* hmod = instr->hydrogen();
1171 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1172 Label remainder_not_zero;
1173 __ j(not_zero, &remainder_not_zero, Label::kNear);
1174 __ cmp(dividend, Immediate(0));
1175 DeoptimizeIf(less, instr, Deoptimizer::kMinusZero);
1176 __ bind(&remainder_not_zero);
1181 void LCodeGen::DoModI(LModI* instr) {
1182 HMod* hmod = instr->hydrogen();
1184 Register left_reg = ToRegister(instr->left());
1185 DCHECK(left_reg.is(eax));
1186 Register right_reg = ToRegister(instr->right());
1187 DCHECK(!right_reg.is(eax));
1188 DCHECK(!right_reg.is(edx));
1189 Register result_reg = ToRegister(instr->result());
1190 DCHECK(result_reg.is(edx));
1193 // Check for x % 0, idiv would signal a divide error. We have to
1194 // deopt in this case because we can't return a NaN.
1195 if (hmod->CheckFlag(HValue::kCanBeDivByZero)) {
1196 __ test(right_reg, Operand(right_reg));
1197 DeoptimizeIf(zero, instr, Deoptimizer::kDivisionByZero);
1200 // Check for kMinInt % -1, idiv would signal a divide error. We
1201 // have to deopt if we care about -0, because we can't return that.
1202 if (hmod->CheckFlag(HValue::kCanOverflow)) {
1203 Label no_overflow_possible;
1204 __ cmp(left_reg, kMinInt);
1205 __ j(not_equal, &no_overflow_possible, Label::kNear);
1206 __ cmp(right_reg, -1);
1207 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1208 DeoptimizeIf(equal, instr, Deoptimizer::kMinusZero);
1210 __ j(not_equal, &no_overflow_possible, Label::kNear);
1211 __ Move(result_reg, Immediate(0));
1212 __ jmp(&done, Label::kNear);
1214 __ bind(&no_overflow_possible);
1217 // Sign extend dividend in eax into edx:eax.
1220 // If we care about -0, test if the dividend is <0 and the result is 0.
1221 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1222 Label positive_left;
1223 __ test(left_reg, Operand(left_reg));
1224 __ j(not_sign, &positive_left, Label::kNear);
1226 __ test(result_reg, Operand(result_reg));
1227 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1228 __ jmp(&done, Label::kNear);
1229 __ bind(&positive_left);
1236 void LCodeGen::DoDivByPowerOf2I(LDivByPowerOf2I* instr) {
1237 Register dividend = ToRegister(instr->dividend());
1238 int32_t divisor = instr->divisor();
1239 Register result = ToRegister(instr->result());
1240 DCHECK(divisor == kMinInt || base::bits::IsPowerOfTwo32(Abs(divisor)));
1241 DCHECK(!result.is(dividend));
1243 // Check for (0 / -x) that will produce negative zero.
1244 HDiv* hdiv = instr->hydrogen();
1245 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
1246 __ test(dividend, dividend);
1247 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1249 // Check for (kMinInt / -1).
1250 if (hdiv->CheckFlag(HValue::kCanOverflow) && divisor == -1) {
1251 __ cmp(dividend, kMinInt);
1252 DeoptimizeIf(zero, instr, Deoptimizer::kOverflow);
1254 // Deoptimize if remainder will not be 0.
1255 if (!hdiv->CheckFlag(HInstruction::kAllUsesTruncatingToInt32) &&
1256 divisor != 1 && divisor != -1) {
1257 int32_t mask = divisor < 0 ? -(divisor + 1) : (divisor - 1);
1258 __ test(dividend, Immediate(mask));
1259 DeoptimizeIf(not_zero, instr, Deoptimizer::kLostPrecision);
1261 __ Move(result, dividend);
1262 int32_t shift = WhichPowerOf2Abs(divisor);
1264 // The arithmetic shift is always OK, the 'if' is an optimization only.
1265 if (shift > 1) __ sar(result, 31);
1266 __ shr(result, 32 - shift);
1267 __ add(result, dividend);
1268 __ sar(result, shift);
1270 if (divisor < 0) __ neg(result);
1274 void LCodeGen::DoDivByConstI(LDivByConstI* instr) {
1275 Register dividend = ToRegister(instr->dividend());
1276 int32_t divisor = instr->divisor();
1277 DCHECK(ToRegister(instr->result()).is(edx));
1280 DeoptimizeIf(no_condition, instr, Deoptimizer::kDivisionByZero);
1284 // Check for (0 / -x) that will produce negative zero.
1285 HDiv* hdiv = instr->hydrogen();
1286 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
1287 __ test(dividend, dividend);
1288 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1291 __ TruncatingDiv(dividend, Abs(divisor));
1292 if (divisor < 0) __ neg(edx);
1294 if (!hdiv->CheckFlag(HInstruction::kAllUsesTruncatingToInt32)) {
1296 __ imul(eax, eax, divisor);
1297 __ sub(eax, dividend);
1298 DeoptimizeIf(not_equal, instr, Deoptimizer::kLostPrecision);
1303 // TODO(svenpanne) Refactor this to avoid code duplication with DoFlooringDivI.
1304 void LCodeGen::DoDivI(LDivI* instr) {
1305 HBinaryOperation* hdiv = instr->hydrogen();
1306 Register dividend = ToRegister(instr->dividend());
1307 Register divisor = ToRegister(instr->divisor());
1308 Register remainder = ToRegister(instr->temp());
1309 DCHECK(dividend.is(eax));
1310 DCHECK(remainder.is(edx));
1311 DCHECK(ToRegister(instr->result()).is(eax));
1312 DCHECK(!divisor.is(eax));
1313 DCHECK(!divisor.is(edx));
1316 if (hdiv->CheckFlag(HValue::kCanBeDivByZero)) {
1317 __ test(divisor, divisor);
1318 DeoptimizeIf(zero, instr, Deoptimizer::kDivisionByZero);
1321 // Check for (0 / -x) that will produce negative zero.
1322 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero)) {
1323 Label dividend_not_zero;
1324 __ test(dividend, dividend);
1325 __ j(not_zero, ÷nd_not_zero, Label::kNear);
1326 __ test(divisor, divisor);
1327 DeoptimizeIf(sign, instr, Deoptimizer::kMinusZero);
1328 __ bind(÷nd_not_zero);
1331 // Check for (kMinInt / -1).
1332 if (hdiv->CheckFlag(HValue::kCanOverflow)) {
1333 Label dividend_not_min_int;
1334 __ cmp(dividend, kMinInt);
1335 __ j(not_zero, ÷nd_not_min_int, Label::kNear);
1336 __ cmp(divisor, -1);
1337 DeoptimizeIf(zero, instr, Deoptimizer::kOverflow);
1338 __ bind(÷nd_not_min_int);
1341 // Sign extend to edx (= remainder).
1345 if (!hdiv->CheckFlag(HValue::kAllUsesTruncatingToInt32)) {
1346 // Deoptimize if remainder is not 0.
1347 __ test(remainder, remainder);
1348 DeoptimizeIf(not_zero, instr, Deoptimizer::kLostPrecision);
1353 void LCodeGen::DoFlooringDivByPowerOf2I(LFlooringDivByPowerOf2I* instr) {
1354 Register dividend = ToRegister(instr->dividend());
1355 int32_t divisor = instr->divisor();
1356 DCHECK(dividend.is(ToRegister(instr->result())));
1358 // If the divisor is positive, things are easy: There can be no deopts and we
1359 // can simply do an arithmetic right shift.
1360 if (divisor == 1) return;
1361 int32_t shift = WhichPowerOf2Abs(divisor);
1363 __ sar(dividend, shift);
1367 // If the divisor is negative, we have to negate and handle edge cases.
1369 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1370 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1373 // Dividing by -1 is basically negation, unless we overflow.
1374 if (divisor == -1) {
1375 if (instr->hydrogen()->CheckFlag(HValue::kLeftCanBeMinInt)) {
1376 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1381 // If the negation could not overflow, simply shifting is OK.
1382 if (!instr->hydrogen()->CheckFlag(HValue::kLeftCanBeMinInt)) {
1383 __ sar(dividend, shift);
1387 Label not_kmin_int, done;
1388 __ j(no_overflow, ¬_kmin_int, Label::kNear);
1389 __ mov(dividend, Immediate(kMinInt / divisor));
1390 __ jmp(&done, Label::kNear);
1391 __ bind(¬_kmin_int);
1392 __ sar(dividend, shift);
1397 void LCodeGen::DoFlooringDivByConstI(LFlooringDivByConstI* instr) {
1398 Register dividend = ToRegister(instr->dividend());
1399 int32_t divisor = instr->divisor();
1400 DCHECK(ToRegister(instr->result()).is(edx));
1403 DeoptimizeIf(no_condition, instr, Deoptimizer::kDivisionByZero);
1407 // Check for (0 / -x) that will produce negative zero.
1408 HMathFloorOfDiv* hdiv = instr->hydrogen();
1409 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
1410 __ test(dividend, dividend);
1411 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1414 // Easy case: We need no dynamic check for the dividend and the flooring
1415 // division is the same as the truncating division.
1416 if ((divisor > 0 && !hdiv->CheckFlag(HValue::kLeftCanBeNegative)) ||
1417 (divisor < 0 && !hdiv->CheckFlag(HValue::kLeftCanBePositive))) {
1418 __ TruncatingDiv(dividend, Abs(divisor));
1419 if (divisor < 0) __ neg(edx);
1423 // In the general case we may need to adjust before and after the truncating
1424 // division to get a flooring division.
1425 Register temp = ToRegister(instr->temp3());
1426 DCHECK(!temp.is(dividend) && !temp.is(eax) && !temp.is(edx));
1427 Label needs_adjustment, done;
1428 __ cmp(dividend, Immediate(0));
1429 __ j(divisor > 0 ? less : greater, &needs_adjustment, Label::kNear);
1430 __ TruncatingDiv(dividend, Abs(divisor));
1431 if (divisor < 0) __ neg(edx);
1432 __ jmp(&done, Label::kNear);
1433 __ bind(&needs_adjustment);
1434 __ lea(temp, Operand(dividend, divisor > 0 ? 1 : -1));
1435 __ TruncatingDiv(temp, Abs(divisor));
1436 if (divisor < 0) __ neg(edx);
1442 // TODO(svenpanne) Refactor this to avoid code duplication with DoDivI.
1443 void LCodeGen::DoFlooringDivI(LFlooringDivI* instr) {
1444 HBinaryOperation* hdiv = instr->hydrogen();
1445 Register dividend = ToRegister(instr->dividend());
1446 Register divisor = ToRegister(instr->divisor());
1447 Register remainder = ToRegister(instr->temp());
1448 Register result = ToRegister(instr->result());
1449 DCHECK(dividend.is(eax));
1450 DCHECK(remainder.is(edx));
1451 DCHECK(result.is(eax));
1452 DCHECK(!divisor.is(eax));
1453 DCHECK(!divisor.is(edx));
1456 if (hdiv->CheckFlag(HValue::kCanBeDivByZero)) {
1457 __ test(divisor, divisor);
1458 DeoptimizeIf(zero, instr, Deoptimizer::kDivisionByZero);
1461 // Check for (0 / -x) that will produce negative zero.
1462 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero)) {
1463 Label dividend_not_zero;
1464 __ test(dividend, dividend);
1465 __ j(not_zero, ÷nd_not_zero, Label::kNear);
1466 __ test(divisor, divisor);
1467 DeoptimizeIf(sign, instr, Deoptimizer::kMinusZero);
1468 __ bind(÷nd_not_zero);
1471 // Check for (kMinInt / -1).
1472 if (hdiv->CheckFlag(HValue::kCanOverflow)) {
1473 Label dividend_not_min_int;
1474 __ cmp(dividend, kMinInt);
1475 __ j(not_zero, ÷nd_not_min_int, Label::kNear);
1476 __ cmp(divisor, -1);
1477 DeoptimizeIf(zero, instr, Deoptimizer::kOverflow);
1478 __ bind(÷nd_not_min_int);
1481 // Sign extend to edx (= remainder).
1486 __ test(remainder, remainder);
1487 __ j(zero, &done, Label::kNear);
1488 __ xor_(remainder, divisor);
1489 __ sar(remainder, 31);
1490 __ add(result, remainder);
1495 void LCodeGen::DoMulI(LMulI* instr) {
1496 Register left = ToRegister(instr->left());
1497 LOperand* right = instr->right();
1499 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1500 __ mov(ToRegister(instr->temp()), left);
1503 if (right->IsConstantOperand()) {
1504 // Try strength reductions on the multiplication.
1505 // All replacement instructions are at most as long as the imul
1506 // and have better latency.
1507 int constant = ToInteger32(LConstantOperand::cast(right));
1508 if (constant == -1) {
1510 } else if (constant == 0) {
1511 __ xor_(left, Operand(left));
1512 } else if (constant == 2) {
1513 __ add(left, Operand(left));
1514 } else if (!instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
1515 // If we know that the multiplication can't overflow, it's safe to
1516 // use instructions that don't set the overflow flag for the
1523 __ lea(left, Operand(left, left, times_2, 0));
1529 __ lea(left, Operand(left, left, times_4, 0));
1535 __ lea(left, Operand(left, left, times_8, 0));
1541 __ imul(left, left, constant);
1545 __ imul(left, left, constant);
1548 if (instr->hydrogen()->representation().IsSmi()) {
1551 __ imul(left, ToOperand(right));
1554 if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
1555 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1558 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1559 // Bail out if the result is supposed to be negative zero.
1561 __ test(left, Operand(left));
1562 __ j(not_zero, &done, Label::kNear);
1563 if (right->IsConstantOperand()) {
1564 if (ToInteger32(LConstantOperand::cast(right)) < 0) {
1565 DeoptimizeIf(no_condition, instr, Deoptimizer::kMinusZero);
1566 } else if (ToInteger32(LConstantOperand::cast(right)) == 0) {
1567 __ cmp(ToRegister(instr->temp()), Immediate(0));
1568 DeoptimizeIf(less, instr, Deoptimizer::kMinusZero);
1571 // Test the non-zero operand for negative sign.
1572 __ or_(ToRegister(instr->temp()), ToOperand(right));
1573 DeoptimizeIf(sign, instr, Deoptimizer::kMinusZero);
1580 void LCodeGen::DoBitI(LBitI* instr) {
1581 LOperand* left = instr->left();
1582 LOperand* right = instr->right();
1583 DCHECK(left->Equals(instr->result()));
1584 DCHECK(left->IsRegister());
1586 if (right->IsConstantOperand()) {
1587 int32_t right_operand =
1588 ToRepresentation(LConstantOperand::cast(right),
1589 instr->hydrogen()->representation());
1590 switch (instr->op()) {
1591 case Token::BIT_AND:
1592 __ and_(ToRegister(left), right_operand);
1595 __ or_(ToRegister(left), right_operand);
1597 case Token::BIT_XOR:
1598 if (right_operand == int32_t(~0)) {
1599 __ not_(ToRegister(left));
1601 __ xor_(ToRegister(left), right_operand);
1609 switch (instr->op()) {
1610 case Token::BIT_AND:
1611 __ and_(ToRegister(left), ToOperand(right));
1614 __ or_(ToRegister(left), ToOperand(right));
1616 case Token::BIT_XOR:
1617 __ xor_(ToRegister(left), ToOperand(right));
1627 void LCodeGen::DoShiftI(LShiftI* instr) {
1628 LOperand* left = instr->left();
1629 LOperand* right = instr->right();
1630 DCHECK(left->Equals(instr->result()));
1631 DCHECK(left->IsRegister());
1632 if (right->IsRegister()) {
1633 DCHECK(ToRegister(right).is(ecx));
1635 switch (instr->op()) {
1637 __ ror_cl(ToRegister(left));
1640 __ sar_cl(ToRegister(left));
1643 __ shr_cl(ToRegister(left));
1644 if (instr->can_deopt()) {
1645 __ test(ToRegister(left), ToRegister(left));
1646 DeoptimizeIf(sign, instr, Deoptimizer::kNegativeValue);
1650 __ shl_cl(ToRegister(left));
1657 int value = ToInteger32(LConstantOperand::cast(right));
1658 uint8_t shift_count = static_cast<uint8_t>(value & 0x1F);
1659 switch (instr->op()) {
1661 if (shift_count == 0 && instr->can_deopt()) {
1662 __ test(ToRegister(left), ToRegister(left));
1663 DeoptimizeIf(sign, instr, Deoptimizer::kNegativeValue);
1665 __ ror(ToRegister(left), shift_count);
1669 if (shift_count != 0) {
1670 __ sar(ToRegister(left), shift_count);
1674 if (shift_count != 0) {
1675 __ shr(ToRegister(left), shift_count);
1676 } else if (instr->can_deopt()) {
1677 __ test(ToRegister(left), ToRegister(left));
1678 DeoptimizeIf(sign, instr, Deoptimizer::kNegativeValue);
1682 if (shift_count != 0) {
1683 if (instr->hydrogen_value()->representation().IsSmi() &&
1684 instr->can_deopt()) {
1685 if (shift_count != 1) {
1686 __ shl(ToRegister(left), shift_count - 1);
1688 __ SmiTag(ToRegister(left));
1689 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1691 __ shl(ToRegister(left), shift_count);
1703 void LCodeGen::DoSubI(LSubI* instr) {
1704 LOperand* left = instr->left();
1705 LOperand* right = instr->right();
1706 DCHECK(left->Equals(instr->result()));
1708 if (right->IsConstantOperand()) {
1709 __ sub(ToOperand(left),
1710 ToImmediate(right, instr->hydrogen()->representation()));
1712 __ sub(ToRegister(left), ToOperand(right));
1714 if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
1715 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1720 void LCodeGen::DoConstantI(LConstantI* instr) {
1721 __ Move(ToRegister(instr->result()), Immediate(instr->value()));
1725 void LCodeGen::DoConstantS(LConstantS* instr) {
1726 __ Move(ToRegister(instr->result()), Immediate(instr->value()));
1730 void LCodeGen::DoConstantD(LConstantD* instr) {
1731 uint64_t const bits = instr->bits();
1732 uint32_t const lower = static_cast<uint32_t>(bits);
1733 uint32_t const upper = static_cast<uint32_t>(bits >> 32);
1734 DCHECK(instr->result()->IsDoubleRegister());
1736 XMMRegister result = ToDoubleRegister(instr->result());
1738 __ xorps(result, result);
1740 Register temp = ToRegister(instr->temp());
1741 if (CpuFeatures::IsSupported(SSE4_1)) {
1742 CpuFeatureScope scope2(masm(), SSE4_1);
1744 __ Move(temp, Immediate(lower));
1745 __ movd(result, Operand(temp));
1746 __ Move(temp, Immediate(upper));
1747 __ pinsrd(result, Operand(temp), 1);
1749 __ xorps(result, result);
1750 __ Move(temp, Immediate(upper));
1751 __ pinsrd(result, Operand(temp), 1);
1754 __ Move(temp, Immediate(upper));
1755 __ movd(result, Operand(temp));
1756 __ psllq(result, 32);
1758 XMMRegister xmm_scratch = double_scratch0();
1759 __ Move(temp, Immediate(lower));
1760 __ movd(xmm_scratch, Operand(temp));
1761 __ orps(result, xmm_scratch);
1768 void LCodeGen::DoConstantE(LConstantE* instr) {
1769 __ lea(ToRegister(instr->result()), Operand::StaticVariable(instr->value()));
1773 void LCodeGen::DoConstantT(LConstantT* instr) {
1774 Register reg = ToRegister(instr->result());
1775 Handle<Object> object = instr->value(isolate());
1776 AllowDeferredHandleDereference smi_check;
1777 __ LoadObject(reg, object);
1781 void LCodeGen::DoMapEnumLength(LMapEnumLength* instr) {
1782 Register result = ToRegister(instr->result());
1783 Register map = ToRegister(instr->value());
1784 __ EnumLength(result, map);
1788 void LCodeGen::DoDateField(LDateField* instr) {
1789 Register object = ToRegister(instr->date());
1790 Register result = ToRegister(instr->result());
1791 Register scratch = ToRegister(instr->temp());
1792 Smi* index = instr->index();
1793 DCHECK(object.is(result));
1794 DCHECK(object.is(eax));
1796 if (index->value() == 0) {
1797 __ mov(result, FieldOperand(object, JSDate::kValueOffset));
1799 Label runtime, done;
1800 if (index->value() < JSDate::kFirstUncachedField) {
1801 ExternalReference stamp = ExternalReference::date_cache_stamp(isolate());
1802 __ mov(scratch, Operand::StaticVariable(stamp));
1803 __ cmp(scratch, FieldOperand(object, JSDate::kCacheStampOffset));
1804 __ j(not_equal, &runtime, Label::kNear);
1805 __ mov(result, FieldOperand(object, JSDate::kValueOffset +
1806 kPointerSize * index->value()));
1807 __ jmp(&done, Label::kNear);
1810 __ PrepareCallCFunction(2, scratch);
1811 __ mov(Operand(esp, 0), object);
1812 __ mov(Operand(esp, 1 * kPointerSize), Immediate(index));
1813 __ CallCFunction(ExternalReference::get_date_field_function(isolate()), 2);
1819 Operand LCodeGen::BuildSeqStringOperand(Register string,
1821 String::Encoding encoding) {
1822 if (index->IsConstantOperand()) {
1823 int offset = ToRepresentation(LConstantOperand::cast(index),
1824 Representation::Integer32());
1825 if (encoding == String::TWO_BYTE_ENCODING) {
1826 offset *= kUC16Size;
1828 STATIC_ASSERT(kCharSize == 1);
1829 return FieldOperand(string, SeqString::kHeaderSize + offset);
1831 return FieldOperand(
1832 string, ToRegister(index),
1833 encoding == String::ONE_BYTE_ENCODING ? times_1 : times_2,
1834 SeqString::kHeaderSize);
1838 void LCodeGen::DoSeqStringGetChar(LSeqStringGetChar* instr) {
1839 String::Encoding encoding = instr->hydrogen()->encoding();
1840 Register result = ToRegister(instr->result());
1841 Register string = ToRegister(instr->string());
1843 if (FLAG_debug_code) {
1845 __ mov(string, FieldOperand(string, HeapObject::kMapOffset));
1846 __ movzx_b(string, FieldOperand(string, Map::kInstanceTypeOffset));
1848 __ and_(string, Immediate(kStringRepresentationMask | kStringEncodingMask));
1849 static const uint32_t one_byte_seq_type = kSeqStringTag | kOneByteStringTag;
1850 static const uint32_t two_byte_seq_type = kSeqStringTag | kTwoByteStringTag;
1851 __ cmp(string, Immediate(encoding == String::ONE_BYTE_ENCODING
1852 ? one_byte_seq_type : two_byte_seq_type));
1853 __ Check(equal, kUnexpectedStringType);
1857 Operand operand = BuildSeqStringOperand(string, instr->index(), encoding);
1858 if (encoding == String::ONE_BYTE_ENCODING) {
1859 __ movzx_b(result, operand);
1861 __ movzx_w(result, operand);
1866 void LCodeGen::DoSeqStringSetChar(LSeqStringSetChar* instr) {
1867 String::Encoding encoding = instr->hydrogen()->encoding();
1868 Register string = ToRegister(instr->string());
1870 if (FLAG_debug_code) {
1871 Register value = ToRegister(instr->value());
1872 Register index = ToRegister(instr->index());
1873 static const uint32_t one_byte_seq_type = kSeqStringTag | kOneByteStringTag;
1874 static const uint32_t two_byte_seq_type = kSeqStringTag | kTwoByteStringTag;
1876 instr->hydrogen()->encoding() == String::ONE_BYTE_ENCODING
1877 ? one_byte_seq_type : two_byte_seq_type;
1878 __ EmitSeqStringSetCharCheck(string, index, value, encoding_mask);
1881 Operand operand = BuildSeqStringOperand(string, instr->index(), encoding);
1882 if (instr->value()->IsConstantOperand()) {
1883 int value = ToRepresentation(LConstantOperand::cast(instr->value()),
1884 Representation::Integer32());
1885 DCHECK_LE(0, value);
1886 if (encoding == String::ONE_BYTE_ENCODING) {
1887 DCHECK_LE(value, String::kMaxOneByteCharCode);
1888 __ mov_b(operand, static_cast<int8_t>(value));
1890 DCHECK_LE(value, String::kMaxUtf16CodeUnit);
1891 __ mov_w(operand, static_cast<int16_t>(value));
1894 Register value = ToRegister(instr->value());
1895 if (encoding == String::ONE_BYTE_ENCODING) {
1896 __ mov_b(operand, value);
1898 __ mov_w(operand, value);
1904 void LCodeGen::DoAddI(LAddI* instr) {
1905 LOperand* left = instr->left();
1906 LOperand* right = instr->right();
1908 if (LAddI::UseLea(instr->hydrogen()) && !left->Equals(instr->result())) {
1909 if (right->IsConstantOperand()) {
1910 int32_t offset = ToRepresentation(LConstantOperand::cast(right),
1911 instr->hydrogen()->representation());
1912 __ lea(ToRegister(instr->result()), MemOperand(ToRegister(left), offset));
1914 Operand address(ToRegister(left), ToRegister(right), times_1, 0);
1915 __ lea(ToRegister(instr->result()), address);
1918 if (right->IsConstantOperand()) {
1919 __ add(ToOperand(left),
1920 ToImmediate(right, instr->hydrogen()->representation()));
1922 __ add(ToRegister(left), ToOperand(right));
1924 if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
1925 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1931 void LCodeGen::DoMathMinMax(LMathMinMax* instr) {
1932 LOperand* left = instr->left();
1933 LOperand* right = instr->right();
1934 DCHECK(left->Equals(instr->result()));
1935 HMathMinMax::Operation operation = instr->hydrogen()->operation();
1936 if (instr->hydrogen()->representation().IsSmiOrInteger32()) {
1938 Condition condition = (operation == HMathMinMax::kMathMin)
1941 if (right->IsConstantOperand()) {
1942 Operand left_op = ToOperand(left);
1943 Immediate immediate = ToImmediate(LConstantOperand::cast(instr->right()),
1944 instr->hydrogen()->representation());
1945 __ cmp(left_op, immediate);
1946 __ j(condition, &return_left, Label::kNear);
1947 __ mov(left_op, immediate);
1949 Register left_reg = ToRegister(left);
1950 Operand right_op = ToOperand(right);
1951 __ cmp(left_reg, right_op);
1952 __ j(condition, &return_left, Label::kNear);
1953 __ mov(left_reg, right_op);
1955 __ bind(&return_left);
1957 DCHECK(instr->hydrogen()->representation().IsDouble());
1958 Label check_nan_left, check_zero, return_left, return_right;
1959 Condition condition = (operation == HMathMinMax::kMathMin) ? below : above;
1960 XMMRegister left_reg = ToDoubleRegister(left);
1961 XMMRegister right_reg = ToDoubleRegister(right);
1962 __ ucomisd(left_reg, right_reg);
1963 __ j(parity_even, &check_nan_left, Label::kNear); // At least one NaN.
1964 __ j(equal, &check_zero, Label::kNear); // left == right.
1965 __ j(condition, &return_left, Label::kNear);
1966 __ jmp(&return_right, Label::kNear);
1968 __ bind(&check_zero);
1969 XMMRegister xmm_scratch = double_scratch0();
1970 __ xorps(xmm_scratch, xmm_scratch);
1971 __ ucomisd(left_reg, xmm_scratch);
1972 __ j(not_equal, &return_left, Label::kNear); // left == right != 0.
1973 // At this point, both left and right are either 0 or -0.
1974 if (operation == HMathMinMax::kMathMin) {
1975 __ orpd(left_reg, right_reg);
1977 // Since we operate on +0 and/or -0, addsd and andsd have the same effect.
1978 __ addsd(left_reg, right_reg);
1980 __ jmp(&return_left, Label::kNear);
1982 __ bind(&check_nan_left);
1983 __ ucomisd(left_reg, left_reg); // NaN check.
1984 __ j(parity_even, &return_left, Label::kNear); // left == NaN.
1985 __ bind(&return_right);
1986 __ movaps(left_reg, right_reg);
1988 __ bind(&return_left);
1993 void LCodeGen::DoArithmeticD(LArithmeticD* instr) {
1994 XMMRegister left = ToDoubleRegister(instr->left());
1995 XMMRegister right = ToDoubleRegister(instr->right());
1996 XMMRegister result = ToDoubleRegister(instr->result());
1997 switch (instr->op()) {
1999 if (CpuFeatures::IsSupported(AVX)) {
2000 CpuFeatureScope scope(masm(), AVX);
2001 __ vaddsd(result, left, right);
2003 DCHECK(result.is(left));
2004 __ addsd(left, right);
2008 if (CpuFeatures::IsSupported(AVX)) {
2009 CpuFeatureScope scope(masm(), AVX);
2010 __ vsubsd(result, left, right);
2012 DCHECK(result.is(left));
2013 __ subsd(left, right);
2017 if (CpuFeatures::IsSupported(AVX)) {
2018 CpuFeatureScope scope(masm(), AVX);
2019 __ vmulsd(result, left, right);
2021 DCHECK(result.is(left));
2022 __ mulsd(left, right);
2026 if (CpuFeatures::IsSupported(AVX)) {
2027 CpuFeatureScope scope(masm(), AVX);
2028 __ vdivsd(result, left, right);
2030 DCHECK(result.is(left));
2031 __ divsd(left, right);
2033 // Don't delete this mov. It may improve performance on some CPUs,
2034 // when there is a (v)mulsd depending on the result
2035 __ movaps(result, result);
2038 // Pass two doubles as arguments on the stack.
2039 __ PrepareCallCFunction(4, eax);
2040 __ movsd(Operand(esp, 0 * kDoubleSize), left);
2041 __ movsd(Operand(esp, 1 * kDoubleSize), right);
2043 ExternalReference::mod_two_doubles_operation(isolate()),
2046 // Return value is in st(0) on ia32.
2047 // Store it into the result register.
2048 __ sub(Operand(esp), Immediate(kDoubleSize));
2049 __ fstp_d(Operand(esp, 0));
2050 __ movsd(result, Operand(esp, 0));
2051 __ add(Operand(esp), Immediate(kDoubleSize));
2061 void LCodeGen::DoArithmeticT(LArithmeticT* instr) {
2062 DCHECK(ToRegister(instr->context()).is(esi));
2063 DCHECK(ToRegister(instr->left()).is(edx));
2064 DCHECK(ToRegister(instr->right()).is(eax));
2065 DCHECK(ToRegister(instr->result()).is(eax));
2067 Handle<Code> code = CodeFactory::BinaryOpIC(
2068 isolate(), instr->op(), instr->language_mode()).code();
2069 CallCode(code, RelocInfo::CODE_TARGET, instr);
2073 template<class InstrType>
2074 void LCodeGen::EmitBranch(InstrType instr, Condition cc) {
2075 int left_block = instr->TrueDestination(chunk_);
2076 int right_block = instr->FalseDestination(chunk_);
2078 int next_block = GetNextEmittedBlock();
2080 if (right_block == left_block || cc == no_condition) {
2081 EmitGoto(left_block);
2082 } else if (left_block == next_block) {
2083 __ j(NegateCondition(cc), chunk_->GetAssemblyLabel(right_block));
2084 } else if (right_block == next_block) {
2085 __ j(cc, chunk_->GetAssemblyLabel(left_block));
2087 __ j(cc, chunk_->GetAssemblyLabel(left_block));
2088 __ jmp(chunk_->GetAssemblyLabel(right_block));
2093 template<class InstrType>
2094 void LCodeGen::EmitFalseBranch(InstrType instr, Condition cc) {
2095 int false_block = instr->FalseDestination(chunk_);
2096 if (cc == no_condition) {
2097 __ jmp(chunk_->GetAssemblyLabel(false_block));
2099 __ j(cc, chunk_->GetAssemblyLabel(false_block));
2104 void LCodeGen::DoBranch(LBranch* instr) {
2105 Representation r = instr->hydrogen()->value()->representation();
2106 if (r.IsSmiOrInteger32()) {
2107 Register reg = ToRegister(instr->value());
2108 __ test(reg, Operand(reg));
2109 EmitBranch(instr, not_zero);
2110 } else if (r.IsDouble()) {
2111 DCHECK(!info()->IsStub());
2112 XMMRegister reg = ToDoubleRegister(instr->value());
2113 XMMRegister xmm_scratch = double_scratch0();
2114 __ xorps(xmm_scratch, xmm_scratch);
2115 __ ucomisd(reg, xmm_scratch);
2116 EmitBranch(instr, not_equal);
2118 DCHECK(r.IsTagged());
2119 Register reg = ToRegister(instr->value());
2120 HType type = instr->hydrogen()->value()->type();
2121 if (type.IsBoolean()) {
2122 DCHECK(!info()->IsStub());
2123 __ cmp(reg, factory()->true_value());
2124 EmitBranch(instr, equal);
2125 } else if (type.IsSmi()) {
2126 DCHECK(!info()->IsStub());
2127 __ test(reg, Operand(reg));
2128 EmitBranch(instr, not_equal);
2129 } else if (type.IsJSArray()) {
2130 DCHECK(!info()->IsStub());
2131 EmitBranch(instr, no_condition);
2132 } else if (type.IsHeapNumber()) {
2133 DCHECK(!info()->IsStub());
2134 XMMRegister xmm_scratch = double_scratch0();
2135 __ xorps(xmm_scratch, xmm_scratch);
2136 __ ucomisd(xmm_scratch, FieldOperand(reg, HeapNumber::kValueOffset));
2137 EmitBranch(instr, not_equal);
2138 } else if (type.IsString()) {
2139 DCHECK(!info()->IsStub());
2140 __ cmp(FieldOperand(reg, String::kLengthOffset), Immediate(0));
2141 EmitBranch(instr, not_equal);
2143 ToBooleanStub::Types expected = instr->hydrogen()->expected_input_types();
2144 if (expected.IsEmpty()) expected = ToBooleanStub::Types::Generic();
2146 if (expected.Contains(ToBooleanStub::UNDEFINED)) {
2147 // undefined -> false.
2148 __ cmp(reg, factory()->undefined_value());
2149 __ j(equal, instr->FalseLabel(chunk_));
2151 if (expected.Contains(ToBooleanStub::BOOLEAN)) {
2153 __ cmp(reg, factory()->true_value());
2154 __ j(equal, instr->TrueLabel(chunk_));
2156 __ cmp(reg, factory()->false_value());
2157 __ j(equal, instr->FalseLabel(chunk_));
2159 if (expected.Contains(ToBooleanStub::NULL_TYPE)) {
2161 __ cmp(reg, factory()->null_value());
2162 __ j(equal, instr->FalseLabel(chunk_));
2165 if (expected.Contains(ToBooleanStub::SMI)) {
2166 // Smis: 0 -> false, all other -> true.
2167 __ test(reg, Operand(reg));
2168 __ j(equal, instr->FalseLabel(chunk_));
2169 __ JumpIfSmi(reg, instr->TrueLabel(chunk_));
2170 } else if (expected.NeedsMap()) {
2171 // If we need a map later and have a Smi -> deopt.
2172 __ test(reg, Immediate(kSmiTagMask));
2173 DeoptimizeIf(zero, instr, Deoptimizer::kSmi);
2176 Register map = no_reg; // Keep the compiler happy.
2177 if (expected.NeedsMap()) {
2178 map = ToRegister(instr->temp());
2179 DCHECK(!map.is(reg));
2180 __ mov(map, FieldOperand(reg, HeapObject::kMapOffset));
2182 if (expected.CanBeUndetectable()) {
2183 // Undetectable -> false.
2184 __ test_b(FieldOperand(map, Map::kBitFieldOffset),
2185 1 << Map::kIsUndetectable);
2186 __ j(not_zero, instr->FalseLabel(chunk_));
2190 if (expected.Contains(ToBooleanStub::SPEC_OBJECT)) {
2191 // spec object -> true.
2192 __ CmpInstanceType(map, FIRST_SPEC_OBJECT_TYPE);
2193 __ j(above_equal, instr->TrueLabel(chunk_));
2196 if (expected.Contains(ToBooleanStub::STRING)) {
2197 // String value -> false iff empty.
2199 __ CmpInstanceType(map, FIRST_NONSTRING_TYPE);
2200 __ j(above_equal, ¬_string, Label::kNear);
2201 __ cmp(FieldOperand(reg, String::kLengthOffset), Immediate(0));
2202 __ j(not_zero, instr->TrueLabel(chunk_));
2203 __ jmp(instr->FalseLabel(chunk_));
2204 __ bind(¬_string);
2207 if (expected.Contains(ToBooleanStub::SYMBOL)) {
2208 // Symbol value -> true.
2209 __ CmpInstanceType(map, SYMBOL_TYPE);
2210 __ j(equal, instr->TrueLabel(chunk_));
2213 if (expected.Contains(ToBooleanStub::HEAP_NUMBER)) {
2214 // heap number -> false iff +0, -0, or NaN.
2215 Label not_heap_number;
2216 __ cmp(FieldOperand(reg, HeapObject::kMapOffset),
2217 factory()->heap_number_map());
2218 __ j(not_equal, ¬_heap_number, Label::kNear);
2219 XMMRegister xmm_scratch = double_scratch0();
2220 __ xorps(xmm_scratch, xmm_scratch);
2221 __ ucomisd(xmm_scratch, FieldOperand(reg, HeapNumber::kValueOffset));
2222 __ j(zero, instr->FalseLabel(chunk_));
2223 __ jmp(instr->TrueLabel(chunk_));
2224 __ bind(¬_heap_number);
2227 if (!expected.IsGeneric()) {
2228 // We've seen something for the first time -> deopt.
2229 // This can only happen if we are not generic already.
2230 DeoptimizeIf(no_condition, instr, Deoptimizer::kUnexpectedObject);
2237 void LCodeGen::EmitGoto(int block) {
2238 if (!IsNextEmittedBlock(block)) {
2239 __ jmp(chunk_->GetAssemblyLabel(LookupDestination(block)));
2244 void LCodeGen::DoGoto(LGoto* instr) {
2245 EmitGoto(instr->block_id());
2249 Condition LCodeGen::TokenToCondition(Token::Value op, bool is_unsigned) {
2250 Condition cond = no_condition;
2253 case Token::EQ_STRICT:
2257 case Token::NE_STRICT:
2261 cond = is_unsigned ? below : less;
2264 cond = is_unsigned ? above : greater;
2267 cond = is_unsigned ? below_equal : less_equal;
2270 cond = is_unsigned ? above_equal : greater_equal;
2273 case Token::INSTANCEOF:
2281 void LCodeGen::DoCompareNumericAndBranch(LCompareNumericAndBranch* instr) {
2282 LOperand* left = instr->left();
2283 LOperand* right = instr->right();
2285 instr->is_double() ||
2286 instr->hydrogen()->left()->CheckFlag(HInstruction::kUint32) ||
2287 instr->hydrogen()->right()->CheckFlag(HInstruction::kUint32);
2288 Condition cc = TokenToCondition(instr->op(), is_unsigned);
2290 if (left->IsConstantOperand() && right->IsConstantOperand()) {
2291 // We can statically evaluate the comparison.
2292 double left_val = ToDouble(LConstantOperand::cast(left));
2293 double right_val = ToDouble(LConstantOperand::cast(right));
2294 int next_block = EvalComparison(instr->op(), left_val, right_val) ?
2295 instr->TrueDestination(chunk_) : instr->FalseDestination(chunk_);
2296 EmitGoto(next_block);
2298 if (instr->is_double()) {
2299 __ ucomisd(ToDoubleRegister(left), ToDoubleRegister(right));
2300 // Don't base result on EFLAGS when a NaN is involved. Instead
2301 // jump to the false block.
2302 __ j(parity_even, instr->FalseLabel(chunk_));
2304 if (right->IsConstantOperand()) {
2305 __ cmp(ToOperand(left),
2306 ToImmediate(right, instr->hydrogen()->representation()));
2307 } else if (left->IsConstantOperand()) {
2308 __ cmp(ToOperand(right),
2309 ToImmediate(left, instr->hydrogen()->representation()));
2310 // We commuted the operands, so commute the condition.
2311 cc = CommuteCondition(cc);
2313 __ cmp(ToRegister(left), ToOperand(right));
2316 EmitBranch(instr, cc);
2321 void LCodeGen::DoCmpObjectEqAndBranch(LCmpObjectEqAndBranch* instr) {
2322 Register left = ToRegister(instr->left());
2324 if (instr->right()->IsConstantOperand()) {
2325 Handle<Object> right = ToHandle(LConstantOperand::cast(instr->right()));
2326 __ CmpObject(left, right);
2328 Operand right = ToOperand(instr->right());
2329 __ cmp(left, right);
2331 EmitBranch(instr, equal);
2335 void LCodeGen::DoCmpHoleAndBranch(LCmpHoleAndBranch* instr) {
2336 if (instr->hydrogen()->representation().IsTagged()) {
2337 Register input_reg = ToRegister(instr->object());
2338 __ cmp(input_reg, factory()->the_hole_value());
2339 EmitBranch(instr, equal);
2343 XMMRegister input_reg = ToDoubleRegister(instr->object());
2344 __ ucomisd(input_reg, input_reg);
2345 EmitFalseBranch(instr, parity_odd);
2347 __ sub(esp, Immediate(kDoubleSize));
2348 __ movsd(MemOperand(esp, 0), input_reg);
2350 __ add(esp, Immediate(kDoubleSize));
2351 int offset = sizeof(kHoleNanUpper32);
2352 __ cmp(MemOperand(esp, -offset), Immediate(kHoleNanUpper32));
2353 EmitBranch(instr, equal);
2357 void LCodeGen::DoCompareMinusZeroAndBranch(LCompareMinusZeroAndBranch* instr) {
2358 Representation rep = instr->hydrogen()->value()->representation();
2359 DCHECK(!rep.IsInteger32());
2360 Register scratch = ToRegister(instr->temp());
2362 if (rep.IsDouble()) {
2363 XMMRegister value = ToDoubleRegister(instr->value());
2364 XMMRegister xmm_scratch = double_scratch0();
2365 __ xorps(xmm_scratch, xmm_scratch);
2366 __ ucomisd(xmm_scratch, value);
2367 EmitFalseBranch(instr, not_equal);
2368 __ movmskpd(scratch, value);
2369 __ test(scratch, Immediate(1));
2370 EmitBranch(instr, not_zero);
2372 Register value = ToRegister(instr->value());
2373 Handle<Map> map = masm()->isolate()->factory()->heap_number_map();
2374 __ CheckMap(value, map, instr->FalseLabel(chunk()), DO_SMI_CHECK);
2375 __ cmp(FieldOperand(value, HeapNumber::kExponentOffset),
2377 EmitFalseBranch(instr, no_overflow);
2378 __ cmp(FieldOperand(value, HeapNumber::kMantissaOffset),
2379 Immediate(0x00000000));
2380 EmitBranch(instr, equal);
2385 Condition LCodeGen::EmitIsObject(Register input,
2387 Label* is_not_object,
2389 __ JumpIfSmi(input, is_not_object);
2391 __ cmp(input, isolate()->factory()->null_value());
2392 __ j(equal, is_object);
2394 __ mov(temp1, FieldOperand(input, HeapObject::kMapOffset));
2395 // Undetectable objects behave like undefined.
2396 __ test_b(FieldOperand(temp1, Map::kBitFieldOffset),
2397 1 << Map::kIsUndetectable);
2398 __ j(not_zero, is_not_object);
2400 __ movzx_b(temp1, FieldOperand(temp1, Map::kInstanceTypeOffset));
2401 __ cmp(temp1, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE);
2402 __ j(below, is_not_object);
2403 __ cmp(temp1, LAST_NONCALLABLE_SPEC_OBJECT_TYPE);
2408 void LCodeGen::DoIsObjectAndBranch(LIsObjectAndBranch* instr) {
2409 Register reg = ToRegister(instr->value());
2410 Register temp = ToRegister(instr->temp());
2412 Condition true_cond = EmitIsObject(
2413 reg, temp, instr->FalseLabel(chunk_), instr->TrueLabel(chunk_));
2415 EmitBranch(instr, true_cond);
2419 Condition LCodeGen::EmitIsString(Register input,
2421 Label* is_not_string,
2422 SmiCheck check_needed = INLINE_SMI_CHECK) {
2423 if (check_needed == INLINE_SMI_CHECK) {
2424 __ JumpIfSmi(input, is_not_string);
2427 Condition cond = masm_->IsObjectStringType(input, temp1, temp1);
2433 void LCodeGen::DoIsStringAndBranch(LIsStringAndBranch* instr) {
2434 Register reg = ToRegister(instr->value());
2435 Register temp = ToRegister(instr->temp());
2437 SmiCheck check_needed =
2438 instr->hydrogen()->value()->type().IsHeapObject()
2439 ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
2441 Condition true_cond = EmitIsString(
2442 reg, temp, instr->FalseLabel(chunk_), check_needed);
2444 EmitBranch(instr, true_cond);
2448 void LCodeGen::DoIsSmiAndBranch(LIsSmiAndBranch* instr) {
2449 Operand input = ToOperand(instr->value());
2451 __ test(input, Immediate(kSmiTagMask));
2452 EmitBranch(instr, zero);
2456 void LCodeGen::DoIsUndetectableAndBranch(LIsUndetectableAndBranch* instr) {
2457 Register input = ToRegister(instr->value());
2458 Register temp = ToRegister(instr->temp());
2460 if (!instr->hydrogen()->value()->type().IsHeapObject()) {
2461 STATIC_ASSERT(kSmiTag == 0);
2462 __ JumpIfSmi(input, instr->FalseLabel(chunk_));
2464 __ mov(temp, FieldOperand(input, HeapObject::kMapOffset));
2465 __ test_b(FieldOperand(temp, Map::kBitFieldOffset),
2466 1 << Map::kIsUndetectable);
2467 EmitBranch(instr, not_zero);
2471 static Condition ComputeCompareCondition(Token::Value op) {
2473 case Token::EQ_STRICT:
2483 return greater_equal;
2486 return no_condition;
2491 void LCodeGen::DoStringCompareAndBranch(LStringCompareAndBranch* instr) {
2492 Token::Value op = instr->op();
2494 Handle<Code> ic = CodeFactory::CompareIC(isolate(), op, SLOPPY).code();
2495 CallCode(ic, RelocInfo::CODE_TARGET, instr);
2497 Condition condition = ComputeCompareCondition(op);
2498 __ test(eax, Operand(eax));
2500 EmitBranch(instr, condition);
2504 static InstanceType TestType(HHasInstanceTypeAndBranch* instr) {
2505 InstanceType from = instr->from();
2506 InstanceType to = instr->to();
2507 if (from == FIRST_TYPE) return to;
2508 DCHECK(from == to || to == LAST_TYPE);
2513 static Condition BranchCondition(HHasInstanceTypeAndBranch* instr) {
2514 InstanceType from = instr->from();
2515 InstanceType to = instr->to();
2516 if (from == to) return equal;
2517 if (to == LAST_TYPE) return above_equal;
2518 if (from == FIRST_TYPE) return below_equal;
2524 void LCodeGen::DoHasInstanceTypeAndBranch(LHasInstanceTypeAndBranch* instr) {
2525 Register input = ToRegister(instr->value());
2526 Register temp = ToRegister(instr->temp());
2528 if (!instr->hydrogen()->value()->type().IsHeapObject()) {
2529 __ JumpIfSmi(input, instr->FalseLabel(chunk_));
2532 __ CmpObjectType(input, TestType(instr->hydrogen()), temp);
2533 EmitBranch(instr, BranchCondition(instr->hydrogen()));
2537 void LCodeGen::DoGetCachedArrayIndex(LGetCachedArrayIndex* instr) {
2538 Register input = ToRegister(instr->value());
2539 Register result = ToRegister(instr->result());
2541 __ AssertString(input);
2543 __ mov(result, FieldOperand(input, String::kHashFieldOffset));
2544 __ IndexFromHash(result, result);
2548 void LCodeGen::DoHasCachedArrayIndexAndBranch(
2549 LHasCachedArrayIndexAndBranch* instr) {
2550 Register input = ToRegister(instr->value());
2552 __ test(FieldOperand(input, String::kHashFieldOffset),
2553 Immediate(String::kContainsCachedArrayIndexMask));
2554 EmitBranch(instr, equal);
2558 // Branches to a label or falls through with the answer in the z flag. Trashes
2559 // the temp registers, but not the input.
2560 void LCodeGen::EmitClassOfTest(Label* is_true,
2562 Handle<String>class_name,
2566 DCHECK(!input.is(temp));
2567 DCHECK(!input.is(temp2));
2568 DCHECK(!temp.is(temp2));
2569 __ JumpIfSmi(input, is_false);
2571 if (String::Equals(isolate()->factory()->Function_string(), class_name)) {
2572 // Assuming the following assertions, we can use the same compares to test
2573 // for both being a function type and being in the object type range.
2574 STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
2575 STATIC_ASSERT(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE ==
2576 FIRST_SPEC_OBJECT_TYPE + 1);
2577 STATIC_ASSERT(LAST_NONCALLABLE_SPEC_OBJECT_TYPE ==
2578 LAST_SPEC_OBJECT_TYPE - 1);
2579 STATIC_ASSERT(LAST_SPEC_OBJECT_TYPE == LAST_TYPE);
2580 __ CmpObjectType(input, FIRST_SPEC_OBJECT_TYPE, temp);
2581 __ j(below, is_false);
2582 __ j(equal, is_true);
2583 __ CmpInstanceType(temp, LAST_SPEC_OBJECT_TYPE);
2584 __ j(equal, is_true);
2586 // Faster code path to avoid two compares: subtract lower bound from the
2587 // actual type and do a signed compare with the width of the type range.
2588 __ mov(temp, FieldOperand(input, HeapObject::kMapOffset));
2589 __ movzx_b(temp2, FieldOperand(temp, Map::kInstanceTypeOffset));
2590 __ sub(Operand(temp2), Immediate(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE));
2591 __ cmp(Operand(temp2), Immediate(LAST_NONCALLABLE_SPEC_OBJECT_TYPE -
2592 FIRST_NONCALLABLE_SPEC_OBJECT_TYPE));
2593 __ j(above, is_false);
2596 // Now we are in the FIRST-LAST_NONCALLABLE_SPEC_OBJECT_TYPE range.
2597 // Check if the constructor in the map is a function.
2598 __ GetMapConstructor(temp, temp, temp2);
2599 // Objects with a non-function constructor have class 'Object'.
2600 __ CmpInstanceType(temp2, JS_FUNCTION_TYPE);
2601 if (String::Equals(class_name, isolate()->factory()->Object_string())) {
2602 __ j(not_equal, is_true);
2604 __ j(not_equal, is_false);
2607 // temp now contains the constructor function. Grab the
2608 // instance class name from there.
2609 __ mov(temp, FieldOperand(temp, JSFunction::kSharedFunctionInfoOffset));
2610 __ mov(temp, FieldOperand(temp,
2611 SharedFunctionInfo::kInstanceClassNameOffset));
2612 // The class name we are testing against is internalized since it's a literal.
2613 // The name in the constructor is internalized because of the way the context
2614 // is booted. This routine isn't expected to work for random API-created
2615 // classes and it doesn't have to because you can't access it with natives
2616 // syntax. Since both sides are internalized it is sufficient to use an
2617 // identity comparison.
2618 __ cmp(temp, class_name);
2619 // End with the answer in the z flag.
2623 void LCodeGen::DoClassOfTestAndBranch(LClassOfTestAndBranch* instr) {
2624 Register input = ToRegister(instr->value());
2625 Register temp = ToRegister(instr->temp());
2626 Register temp2 = ToRegister(instr->temp2());
2628 Handle<String> class_name = instr->hydrogen()->class_name();
2630 EmitClassOfTest(instr->TrueLabel(chunk_), instr->FalseLabel(chunk_),
2631 class_name, input, temp, temp2);
2633 EmitBranch(instr, equal);
2637 void LCodeGen::DoCmpMapAndBranch(LCmpMapAndBranch* instr) {
2638 Register reg = ToRegister(instr->value());
2639 __ cmp(FieldOperand(reg, HeapObject::kMapOffset), instr->map());
2640 EmitBranch(instr, equal);
2644 void LCodeGen::DoInstanceOf(LInstanceOf* instr) {
2645 // Object and function are in fixed registers defined by the stub.
2646 DCHECK(ToRegister(instr->context()).is(esi));
2647 InstanceofStub stub(isolate(), InstanceofStub::kArgsInRegisters);
2648 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
2650 Label true_value, done;
2651 __ test(eax, Operand(eax));
2652 __ j(zero, &true_value, Label::kNear);
2653 __ mov(ToRegister(instr->result()), factory()->false_value());
2654 __ jmp(&done, Label::kNear);
2655 __ bind(&true_value);
2656 __ mov(ToRegister(instr->result()), factory()->true_value());
2661 void LCodeGen::DoInstanceOfKnownGlobal(LInstanceOfKnownGlobal* instr) {
2662 class DeferredInstanceOfKnownGlobal final : public LDeferredCode {
2664 DeferredInstanceOfKnownGlobal(LCodeGen* codegen,
2665 LInstanceOfKnownGlobal* instr)
2666 : LDeferredCode(codegen), instr_(instr) { }
2667 void Generate() override {
2668 codegen()->DoDeferredInstanceOfKnownGlobal(instr_, &map_check_);
2670 LInstruction* instr() override { return instr_; }
2671 Label* map_check() { return &map_check_; }
2673 LInstanceOfKnownGlobal* instr_;
2677 DeferredInstanceOfKnownGlobal* deferred;
2678 deferred = new(zone()) DeferredInstanceOfKnownGlobal(this, instr);
2680 Label done, false_result;
2681 Register object = ToRegister(instr->value());
2682 Register temp = ToRegister(instr->temp());
2684 // A Smi is not an instance of anything.
2685 __ JumpIfSmi(object, &false_result, Label::kNear);
2687 // This is the inlined call site instanceof cache. The two occurences of the
2688 // hole value will be patched to the last map/result pair generated by the
2691 Register map = ToRegister(instr->temp());
2692 __ mov(map, FieldOperand(object, HeapObject::kMapOffset));
2693 __ bind(deferred->map_check()); // Label for calculating code patching.
2694 Handle<Cell> cache_cell = factory()->NewCell(factory()->the_hole_value());
2695 __ cmp(map, Operand::ForCell(cache_cell)); // Patched to cached map.
2696 __ j(not_equal, &cache_miss, Label::kNear);
2697 __ mov(eax, factory()->the_hole_value()); // Patched to either true or false.
2698 __ jmp(&done, Label::kNear);
2700 // The inlined call site cache did not match. Check for null and string
2701 // before calling the deferred code.
2702 __ bind(&cache_miss);
2703 // Null is not an instance of anything.
2704 __ cmp(object, factory()->null_value());
2705 __ j(equal, &false_result, Label::kNear);
2707 // String values are not instances of anything.
2708 Condition is_string = masm_->IsObjectStringType(object, temp, temp);
2709 __ j(is_string, &false_result, Label::kNear);
2711 // Go to the deferred code.
2712 __ jmp(deferred->entry());
2714 __ bind(&false_result);
2715 __ mov(ToRegister(instr->result()), factory()->false_value());
2717 // Here result has either true or false. Deferred code also produces true or
2719 __ bind(deferred->exit());
2724 void LCodeGen::DoDeferredInstanceOfKnownGlobal(LInstanceOfKnownGlobal* instr,
2726 PushSafepointRegistersScope scope(this);
2728 InstanceofStub::Flags flags = InstanceofStub::kNoFlags;
2729 flags = static_cast<InstanceofStub::Flags>(
2730 flags | InstanceofStub::kArgsInRegisters);
2731 flags = static_cast<InstanceofStub::Flags>(
2732 flags | InstanceofStub::kCallSiteInlineCheck);
2733 flags = static_cast<InstanceofStub::Flags>(
2734 flags | InstanceofStub::kReturnTrueFalseObject);
2735 InstanceofStub stub(isolate(), flags);
2737 // Get the temp register reserved by the instruction. This needs to be a
2738 // register which is pushed last by PushSafepointRegisters as top of the
2739 // stack is used to pass the offset to the location of the map check to
2741 Register temp = ToRegister(instr->temp());
2742 DCHECK(MacroAssembler::SafepointRegisterStackIndex(temp) == 0);
2743 __ LoadHeapObject(InstanceofStub::right(), instr->function());
2744 static const int kAdditionalDelta = 13;
2745 int delta = masm_->SizeOfCodeGeneratedSince(map_check) + kAdditionalDelta;
2746 __ mov(temp, Immediate(delta));
2747 __ StoreToSafepointRegisterSlot(temp, temp);
2748 CallCodeGeneric(stub.GetCode(),
2749 RelocInfo::CODE_TARGET,
2751 RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
2752 // Get the deoptimization index of the LLazyBailout-environment that
2753 // corresponds to this instruction.
2754 LEnvironment* env = instr->GetDeferredLazyDeoptimizationEnvironment();
2755 safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
2757 // Put the result value into the eax slot and restore all registers.
2758 __ StoreToSafepointRegisterSlot(eax, eax);
2762 void LCodeGen::DoCmpT(LCmpT* instr) {
2763 Token::Value op = instr->op();
2766 CodeFactory::CompareIC(isolate(), op, instr->language_mode()).code();
2767 CallCode(ic, RelocInfo::CODE_TARGET, instr);
2769 Condition condition = ComputeCompareCondition(op);
2770 Label true_value, done;
2771 __ test(eax, Operand(eax));
2772 __ j(condition, &true_value, Label::kNear);
2773 __ mov(ToRegister(instr->result()), factory()->false_value());
2774 __ jmp(&done, Label::kNear);
2775 __ bind(&true_value);
2776 __ mov(ToRegister(instr->result()), factory()->true_value());
2781 void LCodeGen::EmitReturn(LReturn* instr, bool dynamic_frame_alignment) {
2782 int extra_value_count = dynamic_frame_alignment ? 2 : 1;
2784 if (instr->has_constant_parameter_count()) {
2785 int parameter_count = ToInteger32(instr->constant_parameter_count());
2786 if (dynamic_frame_alignment && FLAG_debug_code) {
2788 (parameter_count + extra_value_count) * kPointerSize),
2789 Immediate(kAlignmentZapValue));
2790 __ Assert(equal, kExpectedAlignmentMarker);
2792 __ Ret((parameter_count + extra_value_count) * kPointerSize, ecx);
2794 DCHECK(info()->IsStub()); // Functions would need to drop one more value.
2795 Register reg = ToRegister(instr->parameter_count());
2796 // The argument count parameter is a smi
2798 Register return_addr_reg = reg.is(ecx) ? ebx : ecx;
2799 if (dynamic_frame_alignment && FLAG_debug_code) {
2800 DCHECK(extra_value_count == 2);
2801 __ cmp(Operand(esp, reg, times_pointer_size,
2802 extra_value_count * kPointerSize),
2803 Immediate(kAlignmentZapValue));
2804 __ Assert(equal, kExpectedAlignmentMarker);
2807 // emit code to restore stack based on instr->parameter_count()
2808 __ pop(return_addr_reg); // save return address
2809 if (dynamic_frame_alignment) {
2810 __ inc(reg); // 1 more for alignment
2813 __ shl(reg, kPointerSizeLog2);
2815 __ jmp(return_addr_reg);
2820 void LCodeGen::DoReturn(LReturn* instr) {
2821 if (FLAG_trace && info()->IsOptimizing()) {
2822 // Preserve the return value on the stack and rely on the runtime call
2823 // to return the value in the same register. We're leaving the code
2824 // managed by the register allocator and tearing down the frame, it's
2825 // safe to write to the context register.
2827 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
2828 __ CallRuntime(Runtime::kTraceExit, 1);
2830 if (info()->saves_caller_doubles()) RestoreCallerDoubles();
2831 if (dynamic_frame_alignment_) {
2832 // Fetch the state of the dynamic frame alignment.
2833 __ mov(edx, Operand(ebp,
2834 JavaScriptFrameConstants::kDynamicAlignmentStateOffset));
2836 int no_frame_start = -1;
2837 if (NeedsEagerFrame()) {
2840 no_frame_start = masm_->pc_offset();
2842 if (dynamic_frame_alignment_) {
2844 __ cmp(edx, Immediate(kNoAlignmentPadding));
2845 __ j(equal, &no_padding, Label::kNear);
2847 EmitReturn(instr, true);
2848 __ bind(&no_padding);
2851 EmitReturn(instr, false);
2852 if (no_frame_start != -1) {
2853 info()->AddNoFrameRange(no_frame_start, masm_->pc_offset());
2859 void LCodeGen::EmitVectorLoadICRegisters(T* instr) {
2860 Register vector_register = ToRegister(instr->temp_vector());
2861 Register slot_register = LoadWithVectorDescriptor::SlotRegister();
2862 DCHECK(vector_register.is(LoadWithVectorDescriptor::VectorRegister()));
2863 DCHECK(slot_register.is(eax));
2865 AllowDeferredHandleDereference vector_structure_check;
2866 Handle<TypeFeedbackVector> vector = instr->hydrogen()->feedback_vector();
2867 __ mov(vector_register, vector);
2868 // No need to allocate this register.
2869 FeedbackVectorICSlot slot = instr->hydrogen()->slot();
2870 int index = vector->GetIndex(slot);
2871 __ mov(slot_register, Immediate(Smi::FromInt(index)));
2875 void LCodeGen::DoLoadGlobalGeneric(LLoadGlobalGeneric* instr) {
2876 DCHECK(ToRegister(instr->context()).is(esi));
2877 DCHECK(ToRegister(instr->global_object())
2878 .is(LoadDescriptor::ReceiverRegister()));
2879 DCHECK(ToRegister(instr->result()).is(eax));
2881 __ mov(LoadDescriptor::NameRegister(), instr->name());
2882 EmitVectorLoadICRegisters<LLoadGlobalGeneric>(instr);
2883 ContextualMode mode = instr->for_typeof() ? NOT_CONTEXTUAL : CONTEXTUAL;
2884 Handle<Code> ic = CodeFactory::LoadICInOptimizedCode(isolate(), mode,
2885 PREMONOMORPHIC).code();
2886 CallCode(ic, RelocInfo::CODE_TARGET, instr);
2890 void LCodeGen::DoLoadContextSlot(LLoadContextSlot* instr) {
2891 Register context = ToRegister(instr->context());
2892 Register result = ToRegister(instr->result());
2893 __ mov(result, ContextOperand(context, instr->slot_index()));
2895 if (instr->hydrogen()->RequiresHoleCheck()) {
2896 __ cmp(result, factory()->the_hole_value());
2897 if (instr->hydrogen()->DeoptimizesOnHole()) {
2898 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
2901 __ j(not_equal, &is_not_hole, Label::kNear);
2902 __ mov(result, factory()->undefined_value());
2903 __ bind(&is_not_hole);
2909 void LCodeGen::DoStoreContextSlot(LStoreContextSlot* instr) {
2910 Register context = ToRegister(instr->context());
2911 Register value = ToRegister(instr->value());
2913 Label skip_assignment;
2915 Operand target = ContextOperand(context, instr->slot_index());
2916 if (instr->hydrogen()->RequiresHoleCheck()) {
2917 __ cmp(target, factory()->the_hole_value());
2918 if (instr->hydrogen()->DeoptimizesOnHole()) {
2919 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
2921 __ j(not_equal, &skip_assignment, Label::kNear);
2925 __ mov(target, value);
2926 if (instr->hydrogen()->NeedsWriteBarrier()) {
2927 SmiCheck check_needed =
2928 instr->hydrogen()->value()->type().IsHeapObject()
2929 ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
2930 Register temp = ToRegister(instr->temp());
2931 int offset = Context::SlotOffset(instr->slot_index());
2932 __ RecordWriteContextSlot(context,
2937 EMIT_REMEMBERED_SET,
2941 __ bind(&skip_assignment);
2945 void LCodeGen::DoLoadNamedField(LLoadNamedField* instr) {
2946 HObjectAccess access = instr->hydrogen()->access();
2947 int offset = access.offset();
2949 if (access.IsExternalMemory()) {
2950 Register result = ToRegister(instr->result());
2951 MemOperand operand = instr->object()->IsConstantOperand()
2952 ? MemOperand::StaticVariable(ToExternalReference(
2953 LConstantOperand::cast(instr->object())))
2954 : MemOperand(ToRegister(instr->object()), offset);
2955 __ Load(result, operand, access.representation());
2959 Register object = ToRegister(instr->object());
2960 if (instr->hydrogen()->representation().IsDouble()) {
2961 XMMRegister result = ToDoubleRegister(instr->result());
2962 __ movsd(result, FieldOperand(object, offset));
2966 Register result = ToRegister(instr->result());
2967 if (!access.IsInobject()) {
2968 __ mov(result, FieldOperand(object, JSObject::kPropertiesOffset));
2971 __ Load(result, FieldOperand(object, offset), access.representation());
2975 void LCodeGen::EmitPushTaggedOperand(LOperand* operand) {
2976 DCHECK(!operand->IsDoubleRegister());
2977 if (operand->IsConstantOperand()) {
2978 Handle<Object> object = ToHandle(LConstantOperand::cast(operand));
2979 AllowDeferredHandleDereference smi_check;
2980 if (object->IsSmi()) {
2981 __ Push(Handle<Smi>::cast(object));
2983 __ PushHeapObject(Handle<HeapObject>::cast(object));
2985 } else if (operand->IsRegister()) {
2986 __ push(ToRegister(operand));
2988 __ push(ToOperand(operand));
2993 void LCodeGen::DoLoadNamedGeneric(LLoadNamedGeneric* instr) {
2994 DCHECK(ToRegister(instr->context()).is(esi));
2995 DCHECK(ToRegister(instr->object()).is(LoadDescriptor::ReceiverRegister()));
2996 DCHECK(ToRegister(instr->result()).is(eax));
2998 __ mov(LoadDescriptor::NameRegister(), instr->name());
2999 EmitVectorLoadICRegisters<LLoadNamedGeneric>(instr);
3000 Handle<Code> ic = CodeFactory::LoadICInOptimizedCode(
3001 isolate(), NOT_CONTEXTUAL,
3002 instr->hydrogen()->initialization_state()).code();
3003 CallCode(ic, RelocInfo::CODE_TARGET, instr);
3007 void LCodeGen::DoLoadFunctionPrototype(LLoadFunctionPrototype* instr) {
3008 Register function = ToRegister(instr->function());
3009 Register temp = ToRegister(instr->temp());
3010 Register result = ToRegister(instr->result());
3012 // Get the prototype or initial map from the function.
3014 FieldOperand(function, JSFunction::kPrototypeOrInitialMapOffset));
3016 // Check that the function has a prototype or an initial map.
3017 __ cmp(Operand(result), Immediate(factory()->the_hole_value()));
3018 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3020 // If the function does not have an initial map, we're done.
3022 __ CmpObjectType(result, MAP_TYPE, temp);
3023 __ j(not_equal, &done, Label::kNear);
3025 // Get the prototype from the initial map.
3026 __ mov(result, FieldOperand(result, Map::kPrototypeOffset));
3033 void LCodeGen::DoLoadRoot(LLoadRoot* instr) {
3034 Register result = ToRegister(instr->result());
3035 __ LoadRoot(result, instr->index());
3039 void LCodeGen::DoAccessArgumentsAt(LAccessArgumentsAt* instr) {
3040 Register arguments = ToRegister(instr->arguments());
3041 Register result = ToRegister(instr->result());
3042 if (instr->length()->IsConstantOperand() &&
3043 instr->index()->IsConstantOperand()) {
3044 int const_index = ToInteger32(LConstantOperand::cast(instr->index()));
3045 int const_length = ToInteger32(LConstantOperand::cast(instr->length()));
3046 int index = (const_length - const_index) + 1;
3047 __ mov(result, Operand(arguments, index * kPointerSize));
3049 Register length = ToRegister(instr->length());
3050 Operand index = ToOperand(instr->index());
3051 // There are two words between the frame pointer and the last argument.
3052 // Subtracting from length accounts for one of them add one more.
3053 __ sub(length, index);
3054 __ mov(result, Operand(arguments, length, times_4, kPointerSize));
3059 void LCodeGen::DoLoadKeyedExternalArray(LLoadKeyed* instr) {
3060 ElementsKind elements_kind = instr->elements_kind();
3061 LOperand* key = instr->key();
3062 if (!key->IsConstantOperand() &&
3063 ExternalArrayOpRequiresTemp(instr->hydrogen()->key()->representation(),
3065 __ SmiUntag(ToRegister(key));
3067 Operand operand(BuildFastArrayOperand(
3070 instr->hydrogen()->key()->representation(),
3072 instr->base_offset()));
3073 if (elements_kind == EXTERNAL_FLOAT32_ELEMENTS ||
3074 elements_kind == FLOAT32_ELEMENTS) {
3075 XMMRegister result(ToDoubleRegister(instr->result()));
3076 __ movss(result, operand);
3077 __ cvtss2sd(result, result);
3078 } else if (elements_kind == EXTERNAL_FLOAT64_ELEMENTS ||
3079 elements_kind == FLOAT64_ELEMENTS) {
3080 __ movsd(ToDoubleRegister(instr->result()), operand);
3082 Register result(ToRegister(instr->result()));
3083 switch (elements_kind) {
3084 case EXTERNAL_INT8_ELEMENTS:
3086 __ movsx_b(result, operand);
3088 case EXTERNAL_UINT8_CLAMPED_ELEMENTS:
3089 case EXTERNAL_UINT8_ELEMENTS:
3090 case UINT8_ELEMENTS:
3091 case UINT8_CLAMPED_ELEMENTS:
3092 __ movzx_b(result, operand);
3094 case EXTERNAL_INT16_ELEMENTS:
3095 case INT16_ELEMENTS:
3096 __ movsx_w(result, operand);
3098 case EXTERNAL_UINT16_ELEMENTS:
3099 case UINT16_ELEMENTS:
3100 __ movzx_w(result, operand);
3102 case EXTERNAL_INT32_ELEMENTS:
3103 case INT32_ELEMENTS:
3104 __ mov(result, operand);
3106 case EXTERNAL_UINT32_ELEMENTS:
3107 case UINT32_ELEMENTS:
3108 __ mov(result, operand);
3109 if (!instr->hydrogen()->CheckFlag(HInstruction::kUint32)) {
3110 __ test(result, Operand(result));
3111 DeoptimizeIf(negative, instr, Deoptimizer::kNegativeValue);
3114 case EXTERNAL_FLOAT32_ELEMENTS:
3115 case EXTERNAL_FLOAT64_ELEMENTS:
3116 case FLOAT32_ELEMENTS:
3117 case FLOAT64_ELEMENTS:
3118 case FAST_SMI_ELEMENTS:
3120 case FAST_DOUBLE_ELEMENTS:
3121 case FAST_HOLEY_SMI_ELEMENTS:
3122 case FAST_HOLEY_ELEMENTS:
3123 case FAST_HOLEY_DOUBLE_ELEMENTS:
3124 case DICTIONARY_ELEMENTS:
3125 case SLOPPY_ARGUMENTS_ELEMENTS:
3133 void LCodeGen::DoLoadKeyedFixedDoubleArray(LLoadKeyed* instr) {
3134 if (instr->hydrogen()->RequiresHoleCheck()) {
3135 Operand hole_check_operand = BuildFastArrayOperand(
3136 instr->elements(), instr->key(),
3137 instr->hydrogen()->key()->representation(),
3138 FAST_DOUBLE_ELEMENTS,
3139 instr->base_offset() + sizeof(kHoleNanLower32));
3140 __ cmp(hole_check_operand, Immediate(kHoleNanUpper32));
3141 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3144 Operand double_load_operand = BuildFastArrayOperand(
3147 instr->hydrogen()->key()->representation(),
3148 FAST_DOUBLE_ELEMENTS,
3149 instr->base_offset());
3150 XMMRegister result = ToDoubleRegister(instr->result());
3151 __ movsd(result, double_load_operand);
3155 void LCodeGen::DoLoadKeyedFixedArray(LLoadKeyed* instr) {
3156 Register result = ToRegister(instr->result());
3160 BuildFastArrayOperand(instr->elements(), instr->key(),
3161 instr->hydrogen()->key()->representation(),
3162 FAST_ELEMENTS, instr->base_offset()));
3164 // Check for the hole value.
3165 if (instr->hydrogen()->RequiresHoleCheck()) {
3166 if (IsFastSmiElementsKind(instr->hydrogen()->elements_kind())) {
3167 __ test(result, Immediate(kSmiTagMask));
3168 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotASmi);
3170 __ cmp(result, factory()->the_hole_value());
3171 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3173 } else if (instr->hydrogen()->hole_mode() == CONVERT_HOLE_TO_UNDEFINED) {
3174 DCHECK(instr->hydrogen()->elements_kind() == FAST_HOLEY_ELEMENTS);
3176 __ cmp(result, factory()->the_hole_value());
3177 __ j(not_equal, &done);
3178 if (info()->IsStub()) {
3179 // A stub can safely convert the hole to undefined only if the array
3180 // protector cell contains (Smi) Isolate::kArrayProtectorValid. Otherwise
3181 // it needs to bail out.
3182 __ mov(result, isolate()->factory()->array_protector());
3183 __ cmp(FieldOperand(result, PropertyCell::kValueOffset),
3184 Immediate(Smi::FromInt(Isolate::kArrayProtectorValid)));
3185 DeoptimizeIf(not_equal, instr, Deoptimizer::kHole);
3187 __ mov(result, isolate()->factory()->undefined_value());
3193 void LCodeGen::DoLoadKeyed(LLoadKeyed* instr) {
3194 if (instr->is_typed_elements()) {
3195 DoLoadKeyedExternalArray(instr);
3196 } else if (instr->hydrogen()->representation().IsDouble()) {
3197 DoLoadKeyedFixedDoubleArray(instr);
3199 DoLoadKeyedFixedArray(instr);
3204 Operand LCodeGen::BuildFastArrayOperand(
3205 LOperand* elements_pointer,
3207 Representation key_representation,
3208 ElementsKind elements_kind,
3209 uint32_t base_offset) {
3210 Register elements_pointer_reg = ToRegister(elements_pointer);
3211 int element_shift_size = ElementsKindToShiftSize(elements_kind);
3212 int shift_size = element_shift_size;
3213 if (key->IsConstantOperand()) {
3214 int constant_value = ToInteger32(LConstantOperand::cast(key));
3215 if (constant_value & 0xF0000000) {
3216 Abort(kArrayIndexConstantValueTooBig);
3218 return Operand(elements_pointer_reg,
3219 ((constant_value) << shift_size)
3222 // Take the tag bit into account while computing the shift size.
3223 if (key_representation.IsSmi() && (shift_size >= 1)) {
3224 shift_size -= kSmiTagSize;
3226 ScaleFactor scale_factor = static_cast<ScaleFactor>(shift_size);
3227 return Operand(elements_pointer_reg,
3235 void LCodeGen::DoLoadKeyedGeneric(LLoadKeyedGeneric* instr) {
3236 DCHECK(ToRegister(instr->context()).is(esi));
3237 DCHECK(ToRegister(instr->object()).is(LoadDescriptor::ReceiverRegister()));
3238 DCHECK(ToRegister(instr->key()).is(LoadDescriptor::NameRegister()));
3240 if (instr->hydrogen()->HasVectorAndSlot()) {
3241 EmitVectorLoadICRegisters<LLoadKeyedGeneric>(instr);
3245 CodeFactory::KeyedLoadICInOptimizedCode(
3246 isolate(), instr->hydrogen()->initialization_state()).code();
3247 CallCode(ic, RelocInfo::CODE_TARGET, instr);
3251 void LCodeGen::DoArgumentsElements(LArgumentsElements* instr) {
3252 Register result = ToRegister(instr->result());
3254 if (instr->hydrogen()->from_inlined()) {
3255 __ lea(result, Operand(esp, -2 * kPointerSize));
3257 // Check for arguments adapter frame.
3258 Label done, adapted;
3259 __ mov(result, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3260 __ mov(result, Operand(result, StandardFrameConstants::kContextOffset));
3261 __ cmp(Operand(result),
3262 Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
3263 __ j(equal, &adapted, Label::kNear);
3265 // No arguments adaptor frame.
3266 __ mov(result, Operand(ebp));
3267 __ jmp(&done, Label::kNear);
3269 // Arguments adaptor frame present.
3271 __ mov(result, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3273 // Result is the frame pointer for the frame if not adapted and for the real
3274 // frame below the adaptor frame if adapted.
3280 void LCodeGen::DoArgumentsLength(LArgumentsLength* instr) {
3281 Operand elem = ToOperand(instr->elements());
3282 Register result = ToRegister(instr->result());
3286 // If no arguments adaptor frame the number of arguments is fixed.
3288 __ mov(result, Immediate(scope()->num_parameters()));
3289 __ j(equal, &done, Label::kNear);
3291 // Arguments adaptor frame present. Get argument length from there.
3292 __ mov(result, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3293 __ mov(result, Operand(result,
3294 ArgumentsAdaptorFrameConstants::kLengthOffset));
3295 __ SmiUntag(result);
3297 // Argument length is in result register.
3302 void LCodeGen::DoWrapReceiver(LWrapReceiver* instr) {
3303 Register receiver = ToRegister(instr->receiver());
3304 Register function = ToRegister(instr->function());
3306 // If the receiver is null or undefined, we have to pass the global
3307 // object as a receiver to normal functions. Values have to be
3308 // passed unchanged to builtins and strict-mode functions.
3309 Label receiver_ok, global_object;
3310 Label::Distance dist = DeoptEveryNTimes() ? Label::kFar : Label::kNear;
3311 Register scratch = ToRegister(instr->temp());
3313 if (!instr->hydrogen()->known_function()) {
3314 // Do not transform the receiver to object for strict mode
3317 FieldOperand(function, JSFunction::kSharedFunctionInfoOffset));
3318 __ test_b(FieldOperand(scratch, SharedFunctionInfo::kStrictModeByteOffset),
3319 1 << SharedFunctionInfo::kStrictModeBitWithinByte);
3320 __ j(not_equal, &receiver_ok, dist);
3322 // Do not transform the receiver to object for builtins.
3323 __ test_b(FieldOperand(scratch, SharedFunctionInfo::kNativeByteOffset),
3324 1 << SharedFunctionInfo::kNativeBitWithinByte);
3325 __ j(not_equal, &receiver_ok, dist);
3328 // Normal function. Replace undefined or null with global receiver.
3329 __ cmp(receiver, factory()->null_value());
3330 __ j(equal, &global_object, Label::kNear);
3331 __ cmp(receiver, factory()->undefined_value());
3332 __ j(equal, &global_object, Label::kNear);
3334 // The receiver should be a JS object.
3335 __ test(receiver, Immediate(kSmiTagMask));
3336 DeoptimizeIf(equal, instr, Deoptimizer::kSmi);
3337 __ CmpObjectType(receiver, FIRST_SPEC_OBJECT_TYPE, scratch);
3338 DeoptimizeIf(below, instr, Deoptimizer::kNotAJavaScriptObject);
3340 __ jmp(&receiver_ok, Label::kNear);
3341 __ bind(&global_object);
3342 __ mov(receiver, FieldOperand(function, JSFunction::kContextOffset));
3343 const int global_offset = Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX);
3344 __ mov(receiver, Operand(receiver, global_offset));
3345 const int proxy_offset = GlobalObject::kGlobalProxyOffset;
3346 __ mov(receiver, FieldOperand(receiver, proxy_offset));
3347 __ bind(&receiver_ok);
3351 void LCodeGen::DoApplyArguments(LApplyArguments* instr) {
3352 Register receiver = ToRegister(instr->receiver());
3353 Register function = ToRegister(instr->function());
3354 Register length = ToRegister(instr->length());
3355 Register elements = ToRegister(instr->elements());
3356 DCHECK(receiver.is(eax)); // Used for parameter count.
3357 DCHECK(function.is(edi)); // Required by InvokeFunction.
3358 DCHECK(ToRegister(instr->result()).is(eax));
3360 // Copy the arguments to this function possibly from the
3361 // adaptor frame below it.
3362 const uint32_t kArgumentsLimit = 1 * KB;
3363 __ cmp(length, kArgumentsLimit);
3364 DeoptimizeIf(above, instr, Deoptimizer::kTooManyArguments);
3367 __ mov(receiver, length);
3369 // Loop through the arguments pushing them onto the execution
3372 // length is a small non-negative integer, due to the test above.
3373 __ test(length, Operand(length));
3374 __ j(zero, &invoke, Label::kNear);
3376 __ push(Operand(elements, length, times_pointer_size, 1 * kPointerSize));
3378 __ j(not_zero, &loop);
3380 // Invoke the function.
3382 DCHECK(instr->HasPointerMap());
3383 LPointerMap* pointers = instr->pointer_map();
3384 SafepointGenerator safepoint_generator(
3385 this, pointers, Safepoint::kLazyDeopt);
3386 ParameterCount actual(eax);
3387 __ InvokeFunction(function, actual, CALL_FUNCTION, safepoint_generator);
3391 void LCodeGen::DoDebugBreak(LDebugBreak* instr) {
3396 void LCodeGen::DoPushArgument(LPushArgument* instr) {
3397 LOperand* argument = instr->value();
3398 EmitPushTaggedOperand(argument);
3402 void LCodeGen::DoDrop(LDrop* instr) {
3403 __ Drop(instr->count());
3407 void LCodeGen::DoThisFunction(LThisFunction* instr) {
3408 Register result = ToRegister(instr->result());
3409 __ mov(result, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
3413 void LCodeGen::DoContext(LContext* instr) {
3414 Register result = ToRegister(instr->result());
3415 if (info()->IsOptimizing()) {
3416 __ mov(result, Operand(ebp, StandardFrameConstants::kContextOffset));
3418 // If there is no frame, the context must be in esi.
3419 DCHECK(result.is(esi));
3424 void LCodeGen::DoDeclareGlobals(LDeclareGlobals* instr) {
3425 DCHECK(ToRegister(instr->context()).is(esi));
3426 __ push(esi); // The context is the first argument.
3427 __ push(Immediate(instr->hydrogen()->pairs()));
3428 __ push(Immediate(Smi::FromInt(instr->hydrogen()->flags())));
3429 CallRuntime(Runtime::kDeclareGlobals, 3, instr);
3433 void LCodeGen::CallKnownFunction(Handle<JSFunction> function,
3434 int formal_parameter_count, int arity,
3435 LInstruction* instr) {
3436 bool dont_adapt_arguments =
3437 formal_parameter_count == SharedFunctionInfo::kDontAdaptArgumentsSentinel;
3438 bool can_invoke_directly =
3439 dont_adapt_arguments || formal_parameter_count == arity;
3441 Register function_reg = edi;
3443 if (can_invoke_directly) {
3445 __ mov(esi, FieldOperand(function_reg, JSFunction::kContextOffset));
3447 // Set eax to arguments count if adaption is not needed. Assumes that eax
3448 // is available to write to at this point.
3449 if (dont_adapt_arguments) {
3453 // Invoke function directly.
3454 if (function.is_identical_to(info()->closure())) {
3457 __ call(FieldOperand(function_reg, JSFunction::kCodeEntryOffset));
3459 RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
3461 // We need to adapt arguments.
3462 LPointerMap* pointers = instr->pointer_map();
3463 SafepointGenerator generator(
3464 this, pointers, Safepoint::kLazyDeopt);
3465 ParameterCount count(arity);
3466 ParameterCount expected(formal_parameter_count);
3467 __ InvokeFunction(function_reg, expected, count, CALL_FUNCTION, generator);
3472 void LCodeGen::DoCallWithDescriptor(LCallWithDescriptor* instr) {
3473 DCHECK(ToRegister(instr->result()).is(eax));
3475 if (instr->hydrogen()->IsTailCall()) {
3476 if (NeedsEagerFrame()) __ leave();
3478 if (instr->target()->IsConstantOperand()) {
3479 LConstantOperand* target = LConstantOperand::cast(instr->target());
3480 Handle<Code> code = Handle<Code>::cast(ToHandle(target));
3481 __ jmp(code, RelocInfo::CODE_TARGET);
3483 DCHECK(instr->target()->IsRegister());
3484 Register target = ToRegister(instr->target());
3485 __ add(target, Immediate(Code::kHeaderSize - kHeapObjectTag));
3489 LPointerMap* pointers = instr->pointer_map();
3490 SafepointGenerator generator(this, pointers, Safepoint::kLazyDeopt);
3492 if (instr->target()->IsConstantOperand()) {
3493 LConstantOperand* target = LConstantOperand::cast(instr->target());
3494 Handle<Code> code = Handle<Code>::cast(ToHandle(target));
3495 generator.BeforeCall(__ CallSize(code, RelocInfo::CODE_TARGET));
3496 __ call(code, RelocInfo::CODE_TARGET);
3498 DCHECK(instr->target()->IsRegister());
3499 Register target = ToRegister(instr->target());
3500 generator.BeforeCall(__ CallSize(Operand(target)));
3501 __ add(target, Immediate(Code::kHeaderSize - kHeapObjectTag));
3504 generator.AfterCall();
3509 void LCodeGen::DoCallJSFunction(LCallJSFunction* instr) {
3510 DCHECK(ToRegister(instr->function()).is(edi));
3511 DCHECK(ToRegister(instr->result()).is(eax));
3513 if (instr->hydrogen()->pass_argument_count()) {
3514 __ mov(eax, instr->arity());
3518 __ mov(esi, FieldOperand(edi, JSFunction::kContextOffset));
3520 bool is_self_call = false;
3521 if (instr->hydrogen()->function()->IsConstant()) {
3522 HConstant* fun_const = HConstant::cast(instr->hydrogen()->function());
3523 Handle<JSFunction> jsfun =
3524 Handle<JSFunction>::cast(fun_const->handle(isolate()));
3525 is_self_call = jsfun.is_identical_to(info()->closure());
3531 __ call(FieldOperand(edi, JSFunction::kCodeEntryOffset));
3534 RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
3538 void LCodeGen::DoDeferredMathAbsTaggedHeapNumber(LMathAbs* instr) {
3539 Register input_reg = ToRegister(instr->value());
3540 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
3541 factory()->heap_number_map());
3542 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
3544 Label slow, allocated, done;
3545 Register tmp = input_reg.is(eax) ? ecx : eax;
3546 Register tmp2 = tmp.is(ecx) ? edx : input_reg.is(ecx) ? edx : ecx;
3548 // Preserve the value of all registers.
3549 PushSafepointRegistersScope scope(this);
3551 __ mov(tmp, FieldOperand(input_reg, HeapNumber::kExponentOffset));
3552 // Check the sign of the argument. If the argument is positive, just
3553 // return it. We do not need to patch the stack since |input| and
3554 // |result| are the same register and |input| will be restored
3555 // unchanged by popping safepoint registers.
3556 __ test(tmp, Immediate(HeapNumber::kSignMask));
3557 __ j(zero, &done, Label::kNear);
3559 __ AllocateHeapNumber(tmp, tmp2, no_reg, &slow);
3560 __ jmp(&allocated, Label::kNear);
3562 // Slow case: Call the runtime system to do the number allocation.
3564 CallRuntimeFromDeferred(Runtime::kAllocateHeapNumber, 0,
3565 instr, instr->context());
3566 // Set the pointer to the new heap number in tmp.
3567 if (!tmp.is(eax)) __ mov(tmp, eax);
3568 // Restore input_reg after call to runtime.
3569 __ LoadFromSafepointRegisterSlot(input_reg, input_reg);
3571 __ bind(&allocated);
3572 __ mov(tmp2, FieldOperand(input_reg, HeapNumber::kExponentOffset));
3573 __ and_(tmp2, ~HeapNumber::kSignMask);
3574 __ mov(FieldOperand(tmp, HeapNumber::kExponentOffset), tmp2);
3575 __ mov(tmp2, FieldOperand(input_reg, HeapNumber::kMantissaOffset));
3576 __ mov(FieldOperand(tmp, HeapNumber::kMantissaOffset), tmp2);
3577 __ StoreToSafepointRegisterSlot(input_reg, tmp);
3583 void LCodeGen::EmitIntegerMathAbs(LMathAbs* instr) {
3584 Register input_reg = ToRegister(instr->value());
3585 __ test(input_reg, Operand(input_reg));
3587 __ j(not_sign, &is_positive, Label::kNear);
3588 __ neg(input_reg); // Sets flags.
3589 DeoptimizeIf(negative, instr, Deoptimizer::kOverflow);
3590 __ bind(&is_positive);
3594 void LCodeGen::DoMathAbs(LMathAbs* instr) {
3595 // Class for deferred case.
3596 class DeferredMathAbsTaggedHeapNumber final : public LDeferredCode {
3598 DeferredMathAbsTaggedHeapNumber(LCodeGen* codegen,
3600 : LDeferredCode(codegen), instr_(instr) { }
3601 void Generate() override {
3602 codegen()->DoDeferredMathAbsTaggedHeapNumber(instr_);
3604 LInstruction* instr() override { return instr_; }
3610 DCHECK(instr->value()->Equals(instr->result()));
3611 Representation r = instr->hydrogen()->value()->representation();
3614 XMMRegister scratch = double_scratch0();
3615 XMMRegister input_reg = ToDoubleRegister(instr->value());
3616 __ xorps(scratch, scratch);
3617 __ subsd(scratch, input_reg);
3618 __ andps(input_reg, scratch);
3619 } else if (r.IsSmiOrInteger32()) {
3620 EmitIntegerMathAbs(instr);
3621 } else { // Tagged case.
3622 DeferredMathAbsTaggedHeapNumber* deferred =
3623 new(zone()) DeferredMathAbsTaggedHeapNumber(this, instr);
3624 Register input_reg = ToRegister(instr->value());
3626 __ JumpIfNotSmi(input_reg, deferred->entry());
3627 EmitIntegerMathAbs(instr);
3628 __ bind(deferred->exit());
3633 void LCodeGen::DoMathFloor(LMathFloor* instr) {
3634 XMMRegister xmm_scratch = double_scratch0();
3635 Register output_reg = ToRegister(instr->result());
3636 XMMRegister input_reg = ToDoubleRegister(instr->value());
3638 if (CpuFeatures::IsSupported(SSE4_1)) {
3639 CpuFeatureScope scope(masm(), SSE4_1);
3640 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3641 // Deoptimize on negative zero.
3643 __ xorps(xmm_scratch, xmm_scratch); // Zero the register.
3644 __ ucomisd(input_reg, xmm_scratch);
3645 __ j(not_equal, &non_zero, Label::kNear);
3646 __ movmskpd(output_reg, input_reg);
3647 __ test(output_reg, Immediate(1));
3648 DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
3651 __ roundsd(xmm_scratch, input_reg, kRoundDown);
3652 __ cvttsd2si(output_reg, Operand(xmm_scratch));
3653 // Overflow is signalled with minint.
3654 __ cmp(output_reg, 0x1);
3655 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
3657 Label negative_sign, done;
3658 // Deoptimize on unordered.
3659 __ xorps(xmm_scratch, xmm_scratch); // Zero the register.
3660 __ ucomisd(input_reg, xmm_scratch);
3661 DeoptimizeIf(parity_even, instr, Deoptimizer::kNaN);
3662 __ j(below, &negative_sign, Label::kNear);
3664 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3665 // Check for negative zero.
3666 Label positive_sign;
3667 __ j(above, &positive_sign, Label::kNear);
3668 __ movmskpd(output_reg, input_reg);
3669 __ test(output_reg, Immediate(1));
3670 DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
3671 __ Move(output_reg, Immediate(0));
3672 __ jmp(&done, Label::kNear);
3673 __ bind(&positive_sign);
3676 // Use truncating instruction (OK because input is positive).
3677 __ cvttsd2si(output_reg, Operand(input_reg));
3678 // Overflow is signalled with minint.
3679 __ cmp(output_reg, 0x1);
3680 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
3681 __ jmp(&done, Label::kNear);
3683 // Non-zero negative reaches here.
3684 __ bind(&negative_sign);
3685 // Truncate, then compare and compensate.
3686 __ cvttsd2si(output_reg, Operand(input_reg));
3687 __ Cvtsi2sd(xmm_scratch, output_reg);
3688 __ ucomisd(input_reg, xmm_scratch);
3689 __ j(equal, &done, Label::kNear);
3690 __ sub(output_reg, Immediate(1));
3691 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
3698 void LCodeGen::DoMathRound(LMathRound* instr) {
3699 Register output_reg = ToRegister(instr->result());
3700 XMMRegister input_reg = ToDoubleRegister(instr->value());
3701 XMMRegister xmm_scratch = double_scratch0();
3702 XMMRegister input_temp = ToDoubleRegister(instr->temp());
3703 ExternalReference one_half = ExternalReference::address_of_one_half();
3704 ExternalReference minus_one_half =
3705 ExternalReference::address_of_minus_one_half();
3707 Label done, round_to_zero, below_one_half, do_not_compensate;
3708 Label::Distance dist = DeoptEveryNTimes() ? Label::kFar : Label::kNear;
3710 __ movsd(xmm_scratch, Operand::StaticVariable(one_half));
3711 __ ucomisd(xmm_scratch, input_reg);
3712 __ j(above, &below_one_half, Label::kNear);
3714 // CVTTSD2SI rounds towards zero, since 0.5 <= x, we use floor(0.5 + x).
3715 __ addsd(xmm_scratch, input_reg);
3716 __ cvttsd2si(output_reg, Operand(xmm_scratch));
3717 // Overflow is signalled with minint.
3718 __ cmp(output_reg, 0x1);
3719 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
3720 __ jmp(&done, dist);
3722 __ bind(&below_one_half);
3723 __ movsd(xmm_scratch, Operand::StaticVariable(minus_one_half));
3724 __ ucomisd(xmm_scratch, input_reg);
3725 __ j(below_equal, &round_to_zero, Label::kNear);
3727 // CVTTSD2SI rounds towards zero, we use ceil(x - (-0.5)) and then
3728 // compare and compensate.
3729 __ movaps(input_temp, input_reg); // Do not alter input_reg.
3730 __ subsd(input_temp, xmm_scratch);
3731 __ cvttsd2si(output_reg, Operand(input_temp));
3732 // Catch minint due to overflow, and to prevent overflow when compensating.
3733 __ cmp(output_reg, 0x1);
3734 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
3736 __ Cvtsi2sd(xmm_scratch, output_reg);
3737 __ ucomisd(xmm_scratch, input_temp);
3738 __ j(equal, &done, dist);
3739 __ sub(output_reg, Immediate(1));
3740 // No overflow because we already ruled out minint.
3741 __ jmp(&done, dist);
3743 __ bind(&round_to_zero);
3744 // We return 0 for the input range [+0, 0.5[, or [-0.5, 0.5[ if
3745 // we can ignore the difference between a result of -0 and +0.
3746 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3747 // If the sign is positive, we return +0.
3748 __ movmskpd(output_reg, input_reg);
3749 __ test(output_reg, Immediate(1));
3750 DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
3752 __ Move(output_reg, Immediate(0));
3757 void LCodeGen::DoMathFround(LMathFround* instr) {
3758 XMMRegister input_reg = ToDoubleRegister(instr->value());
3759 XMMRegister output_reg = ToDoubleRegister(instr->result());
3760 __ cvtsd2ss(output_reg, input_reg);
3761 __ cvtss2sd(output_reg, output_reg);
3765 void LCodeGen::DoMathSqrt(LMathSqrt* instr) {
3766 Operand input = ToOperand(instr->value());
3767 XMMRegister output = ToDoubleRegister(instr->result());
3768 __ sqrtsd(output, input);
3772 void LCodeGen::DoMathPowHalf(LMathPowHalf* instr) {
3773 XMMRegister xmm_scratch = double_scratch0();
3774 XMMRegister input_reg = ToDoubleRegister(instr->value());
3775 Register scratch = ToRegister(instr->temp());
3776 DCHECK(ToDoubleRegister(instr->result()).is(input_reg));
3778 // Note that according to ECMA-262 15.8.2.13:
3779 // Math.pow(-Infinity, 0.5) == Infinity
3780 // Math.sqrt(-Infinity) == NaN
3782 // Check base for -Infinity. According to IEEE-754, single-precision
3783 // -Infinity has the highest 9 bits set and the lowest 23 bits cleared.
3784 __ mov(scratch, 0xFF800000);
3785 __ movd(xmm_scratch, scratch);
3786 __ cvtss2sd(xmm_scratch, xmm_scratch);
3787 __ ucomisd(input_reg, xmm_scratch);
3788 // Comparing -Infinity with NaN results in "unordered", which sets the
3789 // zero flag as if both were equal. However, it also sets the carry flag.
3790 __ j(not_equal, &sqrt, Label::kNear);
3791 __ j(carry, &sqrt, Label::kNear);
3792 // If input is -Infinity, return Infinity.
3793 __ xorps(input_reg, input_reg);
3794 __ subsd(input_reg, xmm_scratch);
3795 __ jmp(&done, Label::kNear);
3799 __ xorps(xmm_scratch, xmm_scratch);
3800 __ addsd(input_reg, xmm_scratch); // Convert -0 to +0.
3801 __ sqrtsd(input_reg, input_reg);
3806 void LCodeGen::DoPower(LPower* instr) {
3807 Representation exponent_type = instr->hydrogen()->right()->representation();
3808 // Having marked this as a call, we can use any registers.
3809 // Just make sure that the input/output registers are the expected ones.
3810 Register tagged_exponent = MathPowTaggedDescriptor::exponent();
3811 DCHECK(!instr->right()->IsDoubleRegister() ||
3812 ToDoubleRegister(instr->right()).is(xmm1));
3813 DCHECK(!instr->right()->IsRegister() ||
3814 ToRegister(instr->right()).is(tagged_exponent));
3815 DCHECK(ToDoubleRegister(instr->left()).is(xmm2));
3816 DCHECK(ToDoubleRegister(instr->result()).is(xmm3));
3818 if (exponent_type.IsSmi()) {
3819 MathPowStub stub(isolate(), MathPowStub::TAGGED);
3821 } else if (exponent_type.IsTagged()) {
3823 __ JumpIfSmi(tagged_exponent, &no_deopt);
3824 DCHECK(!ecx.is(tagged_exponent));
3825 __ CmpObjectType(tagged_exponent, HEAP_NUMBER_TYPE, ecx);
3826 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
3828 MathPowStub stub(isolate(), MathPowStub::TAGGED);
3830 } else if (exponent_type.IsInteger32()) {
3831 MathPowStub stub(isolate(), MathPowStub::INTEGER);
3834 DCHECK(exponent_type.IsDouble());
3835 MathPowStub stub(isolate(), MathPowStub::DOUBLE);
3841 void LCodeGen::DoMathLog(LMathLog* instr) {
3842 DCHECK(instr->value()->Equals(instr->result()));
3843 XMMRegister input_reg = ToDoubleRegister(instr->value());
3844 XMMRegister xmm_scratch = double_scratch0();
3845 Label positive, done, zero;
3846 __ xorps(xmm_scratch, xmm_scratch);
3847 __ ucomisd(input_reg, xmm_scratch);
3848 __ j(above, &positive, Label::kNear);
3849 __ j(not_carry, &zero, Label::kNear);
3850 __ pcmpeqd(input_reg, input_reg);
3851 __ jmp(&done, Label::kNear);
3853 ExternalReference ninf =
3854 ExternalReference::address_of_negative_infinity();
3855 __ movsd(input_reg, Operand::StaticVariable(ninf));
3856 __ jmp(&done, Label::kNear);
3859 __ sub(Operand(esp), Immediate(kDoubleSize));
3860 __ movsd(Operand(esp, 0), input_reg);
3861 __ fld_d(Operand(esp, 0));
3863 __ fstp_d(Operand(esp, 0));
3864 __ movsd(input_reg, Operand(esp, 0));
3865 __ add(Operand(esp), Immediate(kDoubleSize));
3870 void LCodeGen::DoMathClz32(LMathClz32* instr) {
3871 Register input = ToRegister(instr->value());
3872 Register result = ToRegister(instr->result());
3874 __ Lzcnt(result, input);
3878 void LCodeGen::DoMathExp(LMathExp* instr) {
3879 XMMRegister input = ToDoubleRegister(instr->value());
3880 XMMRegister result = ToDoubleRegister(instr->result());
3881 XMMRegister temp0 = double_scratch0();
3882 Register temp1 = ToRegister(instr->temp1());
3883 Register temp2 = ToRegister(instr->temp2());
3885 MathExpGenerator::EmitMathExp(masm(), input, result, temp0, temp1, temp2);
3889 void LCodeGen::DoInvokeFunction(LInvokeFunction* instr) {
3890 DCHECK(ToRegister(instr->context()).is(esi));
3891 DCHECK(ToRegister(instr->function()).is(edi));
3892 DCHECK(instr->HasPointerMap());
3894 Handle<JSFunction> known_function = instr->hydrogen()->known_function();
3895 if (known_function.is_null()) {
3896 LPointerMap* pointers = instr->pointer_map();
3897 SafepointGenerator generator(
3898 this, pointers, Safepoint::kLazyDeopt);
3899 ParameterCount count(instr->arity());
3900 __ InvokeFunction(edi, count, CALL_FUNCTION, generator);
3902 CallKnownFunction(known_function,
3903 instr->hydrogen()->formal_parameter_count(),
3904 instr->arity(), instr);
3909 void LCodeGen::DoCallFunction(LCallFunction* instr) {
3910 DCHECK(ToRegister(instr->context()).is(esi));
3911 DCHECK(ToRegister(instr->function()).is(edi));
3912 DCHECK(ToRegister(instr->result()).is(eax));
3914 int arity = instr->arity();
3915 CallFunctionFlags flags = instr->hydrogen()->function_flags();
3916 if (instr->hydrogen()->HasVectorAndSlot()) {
3917 Register slot_register = ToRegister(instr->temp_slot());
3918 Register vector_register = ToRegister(instr->temp_vector());
3919 DCHECK(slot_register.is(edx));
3920 DCHECK(vector_register.is(ebx));
3922 AllowDeferredHandleDereference vector_structure_check;
3923 Handle<TypeFeedbackVector> vector = instr->hydrogen()->feedback_vector();
3924 int index = vector->GetIndex(instr->hydrogen()->slot());
3926 __ mov(vector_register, vector);
3927 __ mov(slot_register, Immediate(Smi::FromInt(index)));
3929 CallICState::CallType call_type =
3930 (flags & CALL_AS_METHOD) ? CallICState::METHOD : CallICState::FUNCTION;
3933 CodeFactory::CallICInOptimizedCode(isolate(), arity, call_type).code();
3934 CallCode(ic, RelocInfo::CODE_TARGET, instr);
3936 CallFunctionStub stub(isolate(), arity, flags);
3937 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
3942 void LCodeGen::DoCallNew(LCallNew* instr) {
3943 DCHECK(ToRegister(instr->context()).is(esi));
3944 DCHECK(ToRegister(instr->constructor()).is(edi));
3945 DCHECK(ToRegister(instr->result()).is(eax));
3947 // No cell in ebx for construct type feedback in optimized code
3948 __ mov(ebx, isolate()->factory()->undefined_value());
3949 CallConstructStub stub(isolate(), NO_CALL_CONSTRUCTOR_FLAGS);
3950 __ Move(eax, Immediate(instr->arity()));
3951 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
3955 void LCodeGen::DoCallNewArray(LCallNewArray* instr) {
3956 DCHECK(ToRegister(instr->context()).is(esi));
3957 DCHECK(ToRegister(instr->constructor()).is(edi));
3958 DCHECK(ToRegister(instr->result()).is(eax));
3960 __ Move(eax, Immediate(instr->arity()));
3961 if (instr->arity() == 1) {
3962 // We only need the allocation site for the case we have a length argument.
3963 // The case may bail out to the runtime, which will determine the correct
3964 // elements kind with the site.
3965 __ mov(ebx, instr->hydrogen()->site());
3967 __ mov(ebx, isolate()->factory()->undefined_value());
3970 ElementsKind kind = instr->hydrogen()->elements_kind();
3971 AllocationSiteOverrideMode override_mode =
3972 (AllocationSite::GetMode(kind) == TRACK_ALLOCATION_SITE)
3973 ? DISABLE_ALLOCATION_SITES
3976 if (instr->arity() == 0) {
3977 ArrayNoArgumentConstructorStub stub(isolate(), kind, override_mode);
3978 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
3979 } else if (instr->arity() == 1) {
3981 if (IsFastPackedElementsKind(kind)) {
3983 // We might need a change here
3984 // look at the first argument
3985 __ mov(ecx, Operand(esp, 0));
3987 __ j(zero, &packed_case, Label::kNear);
3989 ElementsKind holey_kind = GetHoleyElementsKind(kind);
3990 ArraySingleArgumentConstructorStub stub(isolate(),
3993 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
3994 __ jmp(&done, Label::kNear);
3995 __ bind(&packed_case);
3998 ArraySingleArgumentConstructorStub stub(isolate(), kind, override_mode);
3999 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
4002 ArrayNArgumentsConstructorStub stub(isolate(), kind, override_mode);
4003 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
4008 void LCodeGen::DoCallRuntime(LCallRuntime* instr) {
4009 DCHECK(ToRegister(instr->context()).is(esi));
4010 CallRuntime(instr->function(), instr->arity(), instr, instr->save_doubles());
4014 void LCodeGen::DoStoreCodeEntry(LStoreCodeEntry* instr) {
4015 Register function = ToRegister(instr->function());
4016 Register code_object = ToRegister(instr->code_object());
4017 __ lea(code_object, FieldOperand(code_object, Code::kHeaderSize));
4018 __ mov(FieldOperand(function, JSFunction::kCodeEntryOffset), code_object);
4022 void LCodeGen::DoInnerAllocatedObject(LInnerAllocatedObject* instr) {
4023 Register result = ToRegister(instr->result());
4024 Register base = ToRegister(instr->base_object());
4025 if (instr->offset()->IsConstantOperand()) {
4026 LConstantOperand* offset = LConstantOperand::cast(instr->offset());
4027 __ lea(result, Operand(base, ToInteger32(offset)));
4029 Register offset = ToRegister(instr->offset());
4030 __ lea(result, Operand(base, offset, times_1, 0));
4035 void LCodeGen::DoStoreNamedField(LStoreNamedField* instr) {
4036 Representation representation = instr->hydrogen()->field_representation();
4038 HObjectAccess access = instr->hydrogen()->access();
4039 int offset = access.offset();
4041 if (access.IsExternalMemory()) {
4042 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4043 MemOperand operand = instr->object()->IsConstantOperand()
4044 ? MemOperand::StaticVariable(
4045 ToExternalReference(LConstantOperand::cast(instr->object())))
4046 : MemOperand(ToRegister(instr->object()), offset);
4047 if (instr->value()->IsConstantOperand()) {
4048 LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
4049 __ mov(operand, Immediate(ToInteger32(operand_value)));
4051 Register value = ToRegister(instr->value());
4052 __ Store(value, operand, representation);
4057 Register object = ToRegister(instr->object());
4058 __ AssertNotSmi(object);
4060 DCHECK(!representation.IsSmi() ||
4061 !instr->value()->IsConstantOperand() ||
4062 IsSmi(LConstantOperand::cast(instr->value())));
4063 if (representation.IsDouble()) {
4064 DCHECK(access.IsInobject());
4065 DCHECK(!instr->hydrogen()->has_transition());
4066 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4067 XMMRegister value = ToDoubleRegister(instr->value());
4068 __ movsd(FieldOperand(object, offset), value);
4072 if (instr->hydrogen()->has_transition()) {
4073 Handle<Map> transition = instr->hydrogen()->transition_map();
4074 AddDeprecationDependency(transition);
4075 __ mov(FieldOperand(object, HeapObject::kMapOffset), transition);
4076 if (instr->hydrogen()->NeedsWriteBarrierForMap()) {
4077 Register temp = ToRegister(instr->temp());
4078 Register temp_map = ToRegister(instr->temp_map());
4079 // Update the write barrier for the map field.
4080 __ RecordWriteForMap(object, transition, temp_map, temp, kSaveFPRegs);
4085 Register write_register = object;
4086 if (!access.IsInobject()) {
4087 write_register = ToRegister(instr->temp());
4088 __ mov(write_register, FieldOperand(object, JSObject::kPropertiesOffset));
4091 MemOperand operand = FieldOperand(write_register, offset);
4092 if (instr->value()->IsConstantOperand()) {
4093 LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
4094 if (operand_value->IsRegister()) {
4095 Register value = ToRegister(operand_value);
4096 __ Store(value, operand, representation);
4097 } else if (representation.IsInteger32()) {
4098 Immediate immediate = ToImmediate(operand_value, representation);
4099 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4100 __ mov(operand, immediate);
4102 Handle<Object> handle_value = ToHandle(operand_value);
4103 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4104 __ mov(operand, handle_value);
4107 Register value = ToRegister(instr->value());
4108 __ Store(value, operand, representation);
4111 if (instr->hydrogen()->NeedsWriteBarrier()) {
4112 Register value = ToRegister(instr->value());
4113 Register temp = access.IsInobject() ? ToRegister(instr->temp()) : object;
4114 // Update the write barrier for the object for in-object properties.
4115 __ RecordWriteField(write_register,
4120 EMIT_REMEMBERED_SET,
4121 instr->hydrogen()->SmiCheckForWriteBarrier(),
4122 instr->hydrogen()->PointersToHereCheckForValue());
4127 void LCodeGen::DoStoreNamedGeneric(LStoreNamedGeneric* instr) {
4128 DCHECK(ToRegister(instr->context()).is(esi));
4129 DCHECK(ToRegister(instr->object()).is(StoreDescriptor::ReceiverRegister()));
4130 DCHECK(ToRegister(instr->value()).is(StoreDescriptor::ValueRegister()));
4132 __ mov(StoreDescriptor::NameRegister(), instr->name());
4134 StoreIC::initialize_stub(isolate(), instr->language_mode(),
4135 instr->hydrogen()->initialization_state());
4136 CallCode(ic, RelocInfo::CODE_TARGET, instr);
4140 void LCodeGen::DoBoundsCheck(LBoundsCheck* instr) {
4141 Condition cc = instr->hydrogen()->allow_equality() ? above : above_equal;
4142 if (instr->index()->IsConstantOperand()) {
4143 __ cmp(ToOperand(instr->length()),
4144 ToImmediate(LConstantOperand::cast(instr->index()),
4145 instr->hydrogen()->length()->representation()));
4146 cc = CommuteCondition(cc);
4147 } else if (instr->length()->IsConstantOperand()) {
4148 __ cmp(ToOperand(instr->index()),
4149 ToImmediate(LConstantOperand::cast(instr->length()),
4150 instr->hydrogen()->index()->representation()));
4152 __ cmp(ToRegister(instr->index()), ToOperand(instr->length()));
4154 if (FLAG_debug_code && instr->hydrogen()->skip_check()) {
4156 __ j(NegateCondition(cc), &done, Label::kNear);
4160 DeoptimizeIf(cc, instr, Deoptimizer::kOutOfBounds);
4165 void LCodeGen::DoStoreKeyedExternalArray(LStoreKeyed* instr) {
4166 ElementsKind elements_kind = instr->elements_kind();
4167 LOperand* key = instr->key();
4168 if (!key->IsConstantOperand() &&
4169 ExternalArrayOpRequiresTemp(instr->hydrogen()->key()->representation(),
4171 __ SmiUntag(ToRegister(key));
4173 Operand operand(BuildFastArrayOperand(
4176 instr->hydrogen()->key()->representation(),
4178 instr->base_offset()));
4179 if (elements_kind == EXTERNAL_FLOAT32_ELEMENTS ||
4180 elements_kind == FLOAT32_ELEMENTS) {
4181 XMMRegister xmm_scratch = double_scratch0();
4182 __ cvtsd2ss(xmm_scratch, ToDoubleRegister(instr->value()));
4183 __ movss(operand, xmm_scratch);
4184 } else if (elements_kind == EXTERNAL_FLOAT64_ELEMENTS ||
4185 elements_kind == FLOAT64_ELEMENTS) {
4186 __ movsd(operand, ToDoubleRegister(instr->value()));
4188 Register value = ToRegister(instr->value());
4189 switch (elements_kind) {
4190 case EXTERNAL_UINT8_CLAMPED_ELEMENTS:
4191 case EXTERNAL_UINT8_ELEMENTS:
4192 case EXTERNAL_INT8_ELEMENTS:
4193 case UINT8_ELEMENTS:
4195 case UINT8_CLAMPED_ELEMENTS:
4196 __ mov_b(operand, value);
4198 case EXTERNAL_INT16_ELEMENTS:
4199 case EXTERNAL_UINT16_ELEMENTS:
4200 case UINT16_ELEMENTS:
4201 case INT16_ELEMENTS:
4202 __ mov_w(operand, value);
4204 case EXTERNAL_INT32_ELEMENTS:
4205 case EXTERNAL_UINT32_ELEMENTS:
4206 case UINT32_ELEMENTS:
4207 case INT32_ELEMENTS:
4208 __ mov(operand, value);
4210 case EXTERNAL_FLOAT32_ELEMENTS:
4211 case EXTERNAL_FLOAT64_ELEMENTS:
4212 case FLOAT32_ELEMENTS:
4213 case FLOAT64_ELEMENTS:
4214 case FAST_SMI_ELEMENTS:
4216 case FAST_DOUBLE_ELEMENTS:
4217 case FAST_HOLEY_SMI_ELEMENTS:
4218 case FAST_HOLEY_ELEMENTS:
4219 case FAST_HOLEY_DOUBLE_ELEMENTS:
4220 case DICTIONARY_ELEMENTS:
4221 case SLOPPY_ARGUMENTS_ELEMENTS:
4229 void LCodeGen::DoStoreKeyedFixedDoubleArray(LStoreKeyed* instr) {
4230 Operand double_store_operand = BuildFastArrayOperand(
4233 instr->hydrogen()->key()->representation(),
4234 FAST_DOUBLE_ELEMENTS,
4235 instr->base_offset());
4237 XMMRegister value = ToDoubleRegister(instr->value());
4239 if (instr->NeedsCanonicalization()) {
4240 XMMRegister xmm_scratch = double_scratch0();
4241 // Turn potential sNaN value into qNaN.
4242 __ xorps(xmm_scratch, xmm_scratch);
4243 __ subsd(value, xmm_scratch);
4246 __ movsd(double_store_operand, value);
4250 void LCodeGen::DoStoreKeyedFixedArray(LStoreKeyed* instr) {
4251 Register elements = ToRegister(instr->elements());
4252 Register key = instr->key()->IsRegister() ? ToRegister(instr->key()) : no_reg;
4254 Operand operand = BuildFastArrayOperand(
4257 instr->hydrogen()->key()->representation(),
4259 instr->base_offset());
4260 if (instr->value()->IsRegister()) {
4261 __ mov(operand, ToRegister(instr->value()));
4263 LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
4264 if (IsSmi(operand_value)) {
4265 Immediate immediate = ToImmediate(operand_value, Representation::Smi());
4266 __ mov(operand, immediate);
4268 DCHECK(!IsInteger32(operand_value));
4269 Handle<Object> handle_value = ToHandle(operand_value);
4270 __ mov(operand, handle_value);
4274 if (instr->hydrogen()->NeedsWriteBarrier()) {
4275 DCHECK(instr->value()->IsRegister());
4276 Register value = ToRegister(instr->value());
4277 DCHECK(!instr->key()->IsConstantOperand());
4278 SmiCheck check_needed =
4279 instr->hydrogen()->value()->type().IsHeapObject()
4280 ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
4281 // Compute address of modified element and store it into key register.
4282 __ lea(key, operand);
4283 __ RecordWrite(elements,
4287 EMIT_REMEMBERED_SET,
4289 instr->hydrogen()->PointersToHereCheckForValue());
4294 void LCodeGen::DoStoreKeyed(LStoreKeyed* instr) {
4295 // By cases...external, fast-double, fast
4296 if (instr->is_typed_elements()) {
4297 DoStoreKeyedExternalArray(instr);
4298 } else if (instr->hydrogen()->value()->representation().IsDouble()) {
4299 DoStoreKeyedFixedDoubleArray(instr);
4301 DoStoreKeyedFixedArray(instr);
4306 void LCodeGen::DoStoreKeyedGeneric(LStoreKeyedGeneric* instr) {
4307 DCHECK(ToRegister(instr->context()).is(esi));
4308 DCHECK(ToRegister(instr->object()).is(StoreDescriptor::ReceiverRegister()));
4309 DCHECK(ToRegister(instr->key()).is(StoreDescriptor::NameRegister()));
4310 DCHECK(ToRegister(instr->value()).is(StoreDescriptor::ValueRegister()));
4312 Handle<Code> ic = CodeFactory::KeyedStoreICInOptimizedCode(
4313 isolate(), instr->language_mode(),
4314 instr->hydrogen()->initialization_state()).code();
4315 CallCode(ic, RelocInfo::CODE_TARGET, instr);
4319 void LCodeGen::DoTrapAllocationMemento(LTrapAllocationMemento* instr) {
4320 Register object = ToRegister(instr->object());
4321 Register temp = ToRegister(instr->temp());
4322 Label no_memento_found;
4323 __ TestJSArrayForAllocationMemento(object, temp, &no_memento_found);
4324 DeoptimizeIf(equal, instr, Deoptimizer::kMementoFound);
4325 __ bind(&no_memento_found);
4329 void LCodeGen::DoMaybeGrowElements(LMaybeGrowElements* instr) {
4330 class DeferredMaybeGrowElements final : public LDeferredCode {
4332 DeferredMaybeGrowElements(LCodeGen* codegen, LMaybeGrowElements* instr)
4333 : LDeferredCode(codegen), instr_(instr) {}
4334 void Generate() override { codegen()->DoDeferredMaybeGrowElements(instr_); }
4335 LInstruction* instr() override { return instr_; }
4338 LMaybeGrowElements* instr_;
4341 Register result = eax;
4342 DeferredMaybeGrowElements* deferred =
4343 new (zone()) DeferredMaybeGrowElements(this, instr);
4344 LOperand* key = instr->key();
4345 LOperand* current_capacity = instr->current_capacity();
4347 DCHECK(instr->hydrogen()->key()->representation().IsInteger32());
4348 DCHECK(instr->hydrogen()->current_capacity()->representation().IsInteger32());
4349 DCHECK(key->IsConstantOperand() || key->IsRegister());
4350 DCHECK(current_capacity->IsConstantOperand() ||
4351 current_capacity->IsRegister());
4353 if (key->IsConstantOperand() && current_capacity->IsConstantOperand()) {
4354 int32_t constant_key = ToInteger32(LConstantOperand::cast(key));
4355 int32_t constant_capacity =
4356 ToInteger32(LConstantOperand::cast(current_capacity));
4357 if (constant_key >= constant_capacity) {
4359 __ jmp(deferred->entry());
4361 } else if (key->IsConstantOperand()) {
4362 int32_t constant_key = ToInteger32(LConstantOperand::cast(key));
4363 __ cmp(ToOperand(current_capacity), Immediate(constant_key));
4364 __ j(less_equal, deferred->entry());
4365 } else if (current_capacity->IsConstantOperand()) {
4366 int32_t constant_capacity =
4367 ToInteger32(LConstantOperand::cast(current_capacity));
4368 __ cmp(ToRegister(key), Immediate(constant_capacity));
4369 __ j(greater_equal, deferred->entry());
4371 __ cmp(ToRegister(key), ToRegister(current_capacity));
4372 __ j(greater_equal, deferred->entry());
4375 __ mov(result, ToOperand(instr->elements()));
4376 __ bind(deferred->exit());
4380 void LCodeGen::DoDeferredMaybeGrowElements(LMaybeGrowElements* instr) {
4381 // TODO(3095996): Get rid of this. For now, we need to make the
4382 // result register contain a valid pointer because it is already
4383 // contained in the register pointer map.
4384 Register result = eax;
4385 __ Move(result, Immediate(0));
4387 // We have to call a stub.
4389 PushSafepointRegistersScope scope(this);
4390 if (instr->object()->IsRegister()) {
4391 __ Move(result, ToRegister(instr->object()));
4393 __ mov(result, ToOperand(instr->object()));
4396 LOperand* key = instr->key();
4397 if (key->IsConstantOperand()) {
4398 __ mov(ebx, ToImmediate(key, Representation::Smi()));
4400 __ Move(ebx, ToRegister(key));
4404 GrowArrayElementsStub stub(isolate(), instr->hydrogen()->is_js_array(),
4405 instr->hydrogen()->kind());
4407 RecordSafepointWithLazyDeopt(
4408 instr, RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
4409 __ StoreToSafepointRegisterSlot(result, result);
4412 // Deopt on smi, which means the elements array changed to dictionary mode.
4413 __ test(result, Immediate(kSmiTagMask));
4414 DeoptimizeIf(equal, instr, Deoptimizer::kSmi);
4418 void LCodeGen::DoTransitionElementsKind(LTransitionElementsKind* instr) {
4419 Register object_reg = ToRegister(instr->object());
4421 Handle<Map> from_map = instr->original_map();
4422 Handle<Map> to_map = instr->transitioned_map();
4423 ElementsKind from_kind = instr->from_kind();
4424 ElementsKind to_kind = instr->to_kind();
4426 Label not_applicable;
4427 bool is_simple_map_transition =
4428 IsSimpleMapChangeTransition(from_kind, to_kind);
4429 Label::Distance branch_distance =
4430 is_simple_map_transition ? Label::kNear : Label::kFar;
4431 __ cmp(FieldOperand(object_reg, HeapObject::kMapOffset), from_map);
4432 __ j(not_equal, ¬_applicable, branch_distance);
4433 if (is_simple_map_transition) {
4434 Register new_map_reg = ToRegister(instr->new_map_temp());
4435 __ mov(FieldOperand(object_reg, HeapObject::kMapOffset),
4438 DCHECK_NOT_NULL(instr->temp());
4439 __ RecordWriteForMap(object_reg, to_map, new_map_reg,
4440 ToRegister(instr->temp()),
4443 DCHECK(ToRegister(instr->context()).is(esi));
4444 DCHECK(object_reg.is(eax));
4445 PushSafepointRegistersScope scope(this);
4446 __ mov(ebx, to_map);
4447 bool is_js_array = from_map->instance_type() == JS_ARRAY_TYPE;
4448 TransitionElementsKindStub stub(isolate(), from_kind, to_kind, is_js_array);
4450 RecordSafepointWithLazyDeopt(instr,
4451 RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
4453 __ bind(¬_applicable);
4457 void LCodeGen::DoStringCharCodeAt(LStringCharCodeAt* instr) {
4458 class DeferredStringCharCodeAt final : public LDeferredCode {
4460 DeferredStringCharCodeAt(LCodeGen* codegen,
4461 LStringCharCodeAt* instr)
4462 : LDeferredCode(codegen), instr_(instr) { }
4463 void Generate() override { codegen()->DoDeferredStringCharCodeAt(instr_); }
4464 LInstruction* instr() override { return instr_; }
4467 LStringCharCodeAt* instr_;
4470 DeferredStringCharCodeAt* deferred =
4471 new(zone()) DeferredStringCharCodeAt(this, instr);
4473 StringCharLoadGenerator::Generate(masm(),
4475 ToRegister(instr->string()),
4476 ToRegister(instr->index()),
4477 ToRegister(instr->result()),
4479 __ bind(deferred->exit());
4483 void LCodeGen::DoDeferredStringCharCodeAt(LStringCharCodeAt* instr) {
4484 Register string = ToRegister(instr->string());
4485 Register result = ToRegister(instr->result());
4487 // TODO(3095996): Get rid of this. For now, we need to make the
4488 // result register contain a valid pointer because it is already
4489 // contained in the register pointer map.
4490 __ Move(result, Immediate(0));
4492 PushSafepointRegistersScope scope(this);
4494 // Push the index as a smi. This is safe because of the checks in
4495 // DoStringCharCodeAt above.
4496 STATIC_ASSERT(String::kMaxLength <= Smi::kMaxValue);
4497 if (instr->index()->IsConstantOperand()) {
4498 Immediate immediate = ToImmediate(LConstantOperand::cast(instr->index()),
4499 Representation::Smi());
4502 Register index = ToRegister(instr->index());
4506 CallRuntimeFromDeferred(Runtime::kStringCharCodeAtRT, 2,
4507 instr, instr->context());
4510 __ StoreToSafepointRegisterSlot(result, eax);
4514 void LCodeGen::DoStringCharFromCode(LStringCharFromCode* instr) {
4515 class DeferredStringCharFromCode final : public LDeferredCode {
4517 DeferredStringCharFromCode(LCodeGen* codegen,
4518 LStringCharFromCode* instr)
4519 : LDeferredCode(codegen), instr_(instr) { }
4520 void Generate() override {
4521 codegen()->DoDeferredStringCharFromCode(instr_);
4523 LInstruction* instr() override { return instr_; }
4526 LStringCharFromCode* instr_;
4529 DeferredStringCharFromCode* deferred =
4530 new(zone()) DeferredStringCharFromCode(this, instr);
4532 DCHECK(instr->hydrogen()->value()->representation().IsInteger32());
4533 Register char_code = ToRegister(instr->char_code());
4534 Register result = ToRegister(instr->result());
4535 DCHECK(!char_code.is(result));
4537 __ cmp(char_code, String::kMaxOneByteCharCode);
4538 __ j(above, deferred->entry());
4539 __ Move(result, Immediate(factory()->single_character_string_cache()));
4540 __ mov(result, FieldOperand(result,
4541 char_code, times_pointer_size,
4542 FixedArray::kHeaderSize));
4543 __ cmp(result, factory()->undefined_value());
4544 __ j(equal, deferred->entry());
4545 __ bind(deferred->exit());
4549 void LCodeGen::DoDeferredStringCharFromCode(LStringCharFromCode* instr) {
4550 Register char_code = ToRegister(instr->char_code());
4551 Register result = ToRegister(instr->result());
4553 // TODO(3095996): Get rid of this. For now, we need to make the
4554 // result register contain a valid pointer because it is already
4555 // contained in the register pointer map.
4556 __ Move(result, Immediate(0));
4558 PushSafepointRegistersScope scope(this);
4559 __ SmiTag(char_code);
4561 CallRuntimeFromDeferred(Runtime::kCharFromCode, 1, instr, instr->context());
4562 __ StoreToSafepointRegisterSlot(result, eax);
4566 void LCodeGen::DoStringAdd(LStringAdd* instr) {
4567 DCHECK(ToRegister(instr->context()).is(esi));
4568 DCHECK(ToRegister(instr->left()).is(edx));
4569 DCHECK(ToRegister(instr->right()).is(eax));
4570 StringAddStub stub(isolate(),
4571 instr->hydrogen()->flags(),
4572 instr->hydrogen()->pretenure_flag());
4573 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
4577 void LCodeGen::DoInteger32ToDouble(LInteger32ToDouble* instr) {
4578 LOperand* input = instr->value();
4579 LOperand* output = instr->result();
4580 DCHECK(input->IsRegister() || input->IsStackSlot());
4581 DCHECK(output->IsDoubleRegister());
4582 __ Cvtsi2sd(ToDoubleRegister(output), ToOperand(input));
4586 void LCodeGen::DoUint32ToDouble(LUint32ToDouble* instr) {
4587 LOperand* input = instr->value();
4588 LOperand* output = instr->result();
4589 __ LoadUint32(ToDoubleRegister(output), ToRegister(input));
4593 void LCodeGen::DoNumberTagI(LNumberTagI* instr) {
4594 class DeferredNumberTagI final : public LDeferredCode {
4596 DeferredNumberTagI(LCodeGen* codegen,
4598 : LDeferredCode(codegen), instr_(instr) { }
4599 void Generate() override {
4600 codegen()->DoDeferredNumberTagIU(
4601 instr_, instr_->value(), instr_->temp(), SIGNED_INT32);
4603 LInstruction* instr() override { return instr_; }
4606 LNumberTagI* instr_;
4609 LOperand* input = instr->value();
4610 DCHECK(input->IsRegister() && input->Equals(instr->result()));
4611 Register reg = ToRegister(input);
4613 DeferredNumberTagI* deferred =
4614 new(zone()) DeferredNumberTagI(this, instr);
4616 __ j(overflow, deferred->entry());
4617 __ bind(deferred->exit());
4621 void LCodeGen::DoNumberTagU(LNumberTagU* instr) {
4622 class DeferredNumberTagU final : public LDeferredCode {
4624 DeferredNumberTagU(LCodeGen* codegen, LNumberTagU* instr)
4625 : LDeferredCode(codegen), instr_(instr) { }
4626 void Generate() override {
4627 codegen()->DoDeferredNumberTagIU(
4628 instr_, instr_->value(), instr_->temp(), UNSIGNED_INT32);
4630 LInstruction* instr() override { return instr_; }
4633 LNumberTagU* instr_;
4636 LOperand* input = instr->value();
4637 DCHECK(input->IsRegister() && input->Equals(instr->result()));
4638 Register reg = ToRegister(input);
4640 DeferredNumberTagU* deferred =
4641 new(zone()) DeferredNumberTagU(this, instr);
4642 __ cmp(reg, Immediate(Smi::kMaxValue));
4643 __ j(above, deferred->entry());
4645 __ bind(deferred->exit());
4649 void LCodeGen::DoDeferredNumberTagIU(LInstruction* instr,
4652 IntegerSignedness signedness) {
4654 Register reg = ToRegister(value);
4655 Register tmp = ToRegister(temp);
4656 XMMRegister xmm_scratch = double_scratch0();
4658 if (signedness == SIGNED_INT32) {
4659 // There was overflow, so bits 30 and 31 of the original integer
4660 // disagree. Try to allocate a heap number in new space and store
4661 // the value in there. If that fails, call the runtime system.
4663 __ xor_(reg, 0x80000000);
4664 __ Cvtsi2sd(xmm_scratch, Operand(reg));
4666 __ LoadUint32(xmm_scratch, reg);
4669 if (FLAG_inline_new) {
4670 __ AllocateHeapNumber(reg, tmp, no_reg, &slow);
4671 __ jmp(&done, Label::kNear);
4674 // Slow case: Call the runtime system to do the number allocation.
4677 // TODO(3095996): Put a valid pointer value in the stack slot where the
4678 // result register is stored, as this register is in the pointer map, but
4679 // contains an integer value.
4680 __ Move(reg, Immediate(0));
4682 // Preserve the value of all registers.
4683 PushSafepointRegistersScope scope(this);
4685 // NumberTagI and NumberTagD use the context from the frame, rather than
4686 // the environment's HContext or HInlinedContext value.
4687 // They only call Runtime::kAllocateHeapNumber.
4688 // The corresponding HChange instructions are added in a phase that does
4689 // not have easy access to the local context.
4690 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4691 __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
4692 RecordSafepointWithRegisters(
4693 instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
4694 __ StoreToSafepointRegisterSlot(reg, eax);
4697 // Done. Put the value in xmm_scratch into the value of the allocated heap
4700 __ movsd(FieldOperand(reg, HeapNumber::kValueOffset), xmm_scratch);
4704 void LCodeGen::DoNumberTagD(LNumberTagD* instr) {
4705 class DeferredNumberTagD final : public LDeferredCode {
4707 DeferredNumberTagD(LCodeGen* codegen, LNumberTagD* instr)
4708 : LDeferredCode(codegen), instr_(instr) { }
4709 void Generate() override { codegen()->DoDeferredNumberTagD(instr_); }
4710 LInstruction* instr() override { return instr_; }
4713 LNumberTagD* instr_;
4716 Register reg = ToRegister(instr->result());
4718 DeferredNumberTagD* deferred =
4719 new(zone()) DeferredNumberTagD(this, instr);
4720 if (FLAG_inline_new) {
4721 Register tmp = ToRegister(instr->temp());
4722 __ AllocateHeapNumber(reg, tmp, no_reg, deferred->entry());
4724 __ jmp(deferred->entry());
4726 __ bind(deferred->exit());
4727 XMMRegister input_reg = ToDoubleRegister(instr->value());
4728 __ movsd(FieldOperand(reg, HeapNumber::kValueOffset), input_reg);
4732 void LCodeGen::DoDeferredNumberTagD(LNumberTagD* instr) {
4733 // TODO(3095996): Get rid of this. For now, we need to make the
4734 // result register contain a valid pointer because it is already
4735 // contained in the register pointer map.
4736 Register reg = ToRegister(instr->result());
4737 __ Move(reg, Immediate(0));
4739 PushSafepointRegistersScope scope(this);
4740 // NumberTagI and NumberTagD use the context from the frame, rather than
4741 // the environment's HContext or HInlinedContext value.
4742 // They only call Runtime::kAllocateHeapNumber.
4743 // The corresponding HChange instructions are added in a phase that does
4744 // not have easy access to the local context.
4745 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4746 __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
4747 RecordSafepointWithRegisters(
4748 instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
4749 __ StoreToSafepointRegisterSlot(reg, eax);
4753 void LCodeGen::DoSmiTag(LSmiTag* instr) {
4754 HChange* hchange = instr->hydrogen();
4755 Register input = ToRegister(instr->value());
4756 if (hchange->CheckFlag(HValue::kCanOverflow) &&
4757 hchange->value()->CheckFlag(HValue::kUint32)) {
4758 __ test(input, Immediate(0xc0000000));
4759 DeoptimizeIf(not_zero, instr, Deoptimizer::kOverflow);
4762 if (hchange->CheckFlag(HValue::kCanOverflow) &&
4763 !hchange->value()->CheckFlag(HValue::kUint32)) {
4764 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
4769 void LCodeGen::DoSmiUntag(LSmiUntag* instr) {
4770 LOperand* input = instr->value();
4771 Register result = ToRegister(input);
4772 DCHECK(input->IsRegister() && input->Equals(instr->result()));
4773 if (instr->needs_check()) {
4774 __ test(result, Immediate(kSmiTagMask));
4775 DeoptimizeIf(not_zero, instr, Deoptimizer::kNotASmi);
4777 __ AssertSmi(result);
4779 __ SmiUntag(result);
4783 void LCodeGen::EmitNumberUntagD(LNumberUntagD* instr, Register input_reg,
4784 Register temp_reg, XMMRegister result_reg,
4785 NumberUntagDMode mode) {
4786 bool can_convert_undefined_to_nan =
4787 instr->hydrogen()->can_convert_undefined_to_nan();
4788 bool deoptimize_on_minus_zero = instr->hydrogen()->deoptimize_on_minus_zero();
4790 Label convert, load_smi, done;
4792 if (mode == NUMBER_CANDIDATE_IS_ANY_TAGGED) {
4794 __ JumpIfSmi(input_reg, &load_smi, Label::kNear);
4796 // Heap number map check.
4797 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
4798 factory()->heap_number_map());
4799 if (can_convert_undefined_to_nan) {
4800 __ j(not_equal, &convert, Label::kNear);
4802 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
4805 // Heap number to XMM conversion.
4806 __ movsd(result_reg, FieldOperand(input_reg, HeapNumber::kValueOffset));
4808 if (deoptimize_on_minus_zero) {
4809 XMMRegister xmm_scratch = double_scratch0();
4810 __ xorps(xmm_scratch, xmm_scratch);
4811 __ ucomisd(result_reg, xmm_scratch);
4812 __ j(not_zero, &done, Label::kNear);
4813 __ movmskpd(temp_reg, result_reg);
4814 __ test_b(temp_reg, 1);
4815 DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
4817 __ jmp(&done, Label::kNear);
4819 if (can_convert_undefined_to_nan) {
4822 // Convert undefined to NaN.
4823 __ cmp(input_reg, factory()->undefined_value());
4824 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumberUndefined);
4826 __ pcmpeqd(result_reg, result_reg);
4827 __ jmp(&done, Label::kNear);
4830 DCHECK(mode == NUMBER_CANDIDATE_IS_SMI);
4834 // Smi to XMM conversion. Clobbering a temp is faster than re-tagging the
4835 // input register since we avoid dependencies.
4836 __ mov(temp_reg, input_reg);
4837 __ SmiUntag(temp_reg); // Untag smi before converting to float.
4838 __ Cvtsi2sd(result_reg, Operand(temp_reg));
4843 void LCodeGen::DoDeferredTaggedToI(LTaggedToI* instr, Label* done) {
4844 Register input_reg = ToRegister(instr->value());
4846 // The input was optimistically untagged; revert it.
4847 STATIC_ASSERT(kSmiTagSize == 1);
4848 __ lea(input_reg, Operand(input_reg, times_2, kHeapObjectTag));
4850 if (instr->truncating()) {
4851 Label no_heap_number, check_bools, check_false;
4853 // Heap number map check.
4854 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
4855 factory()->heap_number_map());
4856 __ j(not_equal, &no_heap_number, Label::kNear);
4857 __ TruncateHeapNumberToI(input_reg, input_reg);
4860 __ bind(&no_heap_number);
4861 // Check for Oddballs. Undefined/False is converted to zero and True to one
4862 // for truncating conversions.
4863 __ cmp(input_reg, factory()->undefined_value());
4864 __ j(not_equal, &check_bools, Label::kNear);
4865 __ Move(input_reg, Immediate(0));
4868 __ bind(&check_bools);
4869 __ cmp(input_reg, factory()->true_value());
4870 __ j(not_equal, &check_false, Label::kNear);
4871 __ Move(input_reg, Immediate(1));
4874 __ bind(&check_false);
4875 __ cmp(input_reg, factory()->false_value());
4876 DeoptimizeIf(not_equal, instr,
4877 Deoptimizer::kNotAHeapNumberUndefinedBoolean);
4878 __ Move(input_reg, Immediate(0));
4880 XMMRegister scratch = ToDoubleRegister(instr->temp());
4881 DCHECK(!scratch.is(xmm0));
4882 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
4883 isolate()->factory()->heap_number_map());
4884 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
4885 __ movsd(xmm0, FieldOperand(input_reg, HeapNumber::kValueOffset));
4886 __ cvttsd2si(input_reg, Operand(xmm0));
4887 __ Cvtsi2sd(scratch, Operand(input_reg));
4888 __ ucomisd(xmm0, scratch);
4889 DeoptimizeIf(not_equal, instr, Deoptimizer::kLostPrecision);
4890 DeoptimizeIf(parity_even, instr, Deoptimizer::kNaN);
4891 if (instr->hydrogen()->GetMinusZeroMode() == FAIL_ON_MINUS_ZERO) {
4892 __ test(input_reg, Operand(input_reg));
4893 __ j(not_zero, done);
4894 __ movmskpd(input_reg, xmm0);
4895 __ and_(input_reg, 1);
4896 DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
4902 void LCodeGen::DoTaggedToI(LTaggedToI* instr) {
4903 class DeferredTaggedToI final : public LDeferredCode {
4905 DeferredTaggedToI(LCodeGen* codegen, LTaggedToI* instr)
4906 : LDeferredCode(codegen), instr_(instr) { }
4907 void Generate() override { codegen()->DoDeferredTaggedToI(instr_, done()); }
4908 LInstruction* instr() override { return instr_; }
4914 LOperand* input = instr->value();
4915 DCHECK(input->IsRegister());
4916 Register input_reg = ToRegister(input);
4917 DCHECK(input_reg.is(ToRegister(instr->result())));
4919 if (instr->hydrogen()->value()->representation().IsSmi()) {
4920 __ SmiUntag(input_reg);
4922 DeferredTaggedToI* deferred =
4923 new(zone()) DeferredTaggedToI(this, instr);
4924 // Optimistically untag the input.
4925 // If the input is a HeapObject, SmiUntag will set the carry flag.
4926 STATIC_ASSERT(kSmiTagSize == 1 && kSmiTag == 0);
4927 __ SmiUntag(input_reg);
4928 // Branch to deferred code if the input was tagged.
4929 // The deferred code will take care of restoring the tag.
4930 __ j(carry, deferred->entry());
4931 __ bind(deferred->exit());
4936 void LCodeGen::DoNumberUntagD(LNumberUntagD* instr) {
4937 LOperand* input = instr->value();
4938 DCHECK(input->IsRegister());
4939 LOperand* temp = instr->temp();
4940 DCHECK(temp->IsRegister());
4941 LOperand* result = instr->result();
4942 DCHECK(result->IsDoubleRegister());
4944 Register input_reg = ToRegister(input);
4945 Register temp_reg = ToRegister(temp);
4947 HValue* value = instr->hydrogen()->value();
4948 NumberUntagDMode mode = value->representation().IsSmi()
4949 ? NUMBER_CANDIDATE_IS_SMI : NUMBER_CANDIDATE_IS_ANY_TAGGED;
4951 XMMRegister result_reg = ToDoubleRegister(result);
4952 EmitNumberUntagD(instr, input_reg, temp_reg, result_reg, mode);
4956 void LCodeGen::DoDoubleToI(LDoubleToI* instr) {
4957 LOperand* input = instr->value();
4958 DCHECK(input->IsDoubleRegister());
4959 LOperand* result = instr->result();
4960 DCHECK(result->IsRegister());
4961 Register result_reg = ToRegister(result);
4963 if (instr->truncating()) {
4964 XMMRegister input_reg = ToDoubleRegister(input);
4965 __ TruncateDoubleToI(result_reg, input_reg);
4967 Label lost_precision, is_nan, minus_zero, done;
4968 XMMRegister input_reg = ToDoubleRegister(input);
4969 XMMRegister xmm_scratch = double_scratch0();
4970 Label::Distance dist = DeoptEveryNTimes() ? Label::kFar : Label::kNear;
4971 __ DoubleToI(result_reg, input_reg, xmm_scratch,
4972 instr->hydrogen()->GetMinusZeroMode(), &lost_precision,
4973 &is_nan, &minus_zero, dist);
4974 __ jmp(&done, dist);
4975 __ bind(&lost_precision);
4976 DeoptimizeIf(no_condition, instr, Deoptimizer::kLostPrecision);
4978 DeoptimizeIf(no_condition, instr, Deoptimizer::kNaN);
4979 __ bind(&minus_zero);
4980 DeoptimizeIf(no_condition, instr, Deoptimizer::kMinusZero);
4986 void LCodeGen::DoDoubleToSmi(LDoubleToSmi* instr) {
4987 LOperand* input = instr->value();
4988 DCHECK(input->IsDoubleRegister());
4989 LOperand* result = instr->result();
4990 DCHECK(result->IsRegister());
4991 Register result_reg = ToRegister(result);
4993 Label lost_precision, is_nan, minus_zero, done;
4994 XMMRegister input_reg = ToDoubleRegister(input);
4995 XMMRegister xmm_scratch = double_scratch0();
4996 Label::Distance dist = DeoptEveryNTimes() ? Label::kFar : Label::kNear;
4997 __ DoubleToI(result_reg, input_reg, xmm_scratch,
4998 instr->hydrogen()->GetMinusZeroMode(), &lost_precision, &is_nan,
5000 __ jmp(&done, dist);
5001 __ bind(&lost_precision);
5002 DeoptimizeIf(no_condition, instr, Deoptimizer::kLostPrecision);
5004 DeoptimizeIf(no_condition, instr, Deoptimizer::kNaN);
5005 __ bind(&minus_zero);
5006 DeoptimizeIf(no_condition, instr, Deoptimizer::kMinusZero);
5008 __ SmiTag(result_reg);
5009 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
5013 void LCodeGen::DoCheckSmi(LCheckSmi* instr) {
5014 LOperand* input = instr->value();
5015 __ test(ToOperand(input), Immediate(kSmiTagMask));
5016 DeoptimizeIf(not_zero, instr, Deoptimizer::kNotASmi);
5020 void LCodeGen::DoCheckNonSmi(LCheckNonSmi* instr) {
5021 if (!instr->hydrogen()->value()->type().IsHeapObject()) {
5022 LOperand* input = instr->value();
5023 __ test(ToOperand(input), Immediate(kSmiTagMask));
5024 DeoptimizeIf(zero, instr, Deoptimizer::kSmi);
5029 void LCodeGen::DoCheckArrayBufferNotNeutered(
5030 LCheckArrayBufferNotNeutered* instr) {
5031 Register view = ToRegister(instr->view());
5032 Register scratch = ToRegister(instr->scratch());
5034 __ mov(scratch, FieldOperand(view, JSArrayBufferView::kBufferOffset));
5035 __ test_b(FieldOperand(scratch, JSArrayBuffer::kBitFieldOffset),
5036 1 << JSArrayBuffer::WasNeutered::kShift);
5037 DeoptimizeIf(not_zero, instr, Deoptimizer::kOutOfBounds);
5041 void LCodeGen::DoCheckInstanceType(LCheckInstanceType* instr) {
5042 Register input = ToRegister(instr->value());
5043 Register temp = ToRegister(instr->temp());
5045 __ mov(temp, FieldOperand(input, HeapObject::kMapOffset));
5047 if (instr->hydrogen()->is_interval_check()) {
5050 instr->hydrogen()->GetCheckInterval(&first, &last);
5052 __ cmpb(FieldOperand(temp, Map::kInstanceTypeOffset),
5053 static_cast<int8_t>(first));
5055 // If there is only one type in the interval check for equality.
5056 if (first == last) {
5057 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongInstanceType);
5059 DeoptimizeIf(below, instr, Deoptimizer::kWrongInstanceType);
5060 // Omit check for the last type.
5061 if (last != LAST_TYPE) {
5062 __ cmpb(FieldOperand(temp, Map::kInstanceTypeOffset),
5063 static_cast<int8_t>(last));
5064 DeoptimizeIf(above, instr, Deoptimizer::kWrongInstanceType);
5070 instr->hydrogen()->GetCheckMaskAndTag(&mask, &tag);
5072 if (base::bits::IsPowerOfTwo32(mask)) {
5073 DCHECK(tag == 0 || base::bits::IsPowerOfTwo32(tag));
5074 __ test_b(FieldOperand(temp, Map::kInstanceTypeOffset), mask);
5075 DeoptimizeIf(tag == 0 ? not_zero : zero, instr,
5076 Deoptimizer::kWrongInstanceType);
5078 __ movzx_b(temp, FieldOperand(temp, Map::kInstanceTypeOffset));
5079 __ and_(temp, mask);
5081 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongInstanceType);
5087 void LCodeGen::DoCheckValue(LCheckValue* instr) {
5088 Handle<HeapObject> object = instr->hydrogen()->object().handle();
5089 if (instr->hydrogen()->object_in_new_space()) {
5090 Register reg = ToRegister(instr->value());
5091 Handle<Cell> cell = isolate()->factory()->NewCell(object);
5092 __ cmp(reg, Operand::ForCell(cell));
5094 Operand operand = ToOperand(instr->value());
5095 __ cmp(operand, object);
5097 DeoptimizeIf(not_equal, instr, Deoptimizer::kValueMismatch);
5101 void LCodeGen::DoDeferredInstanceMigration(LCheckMaps* instr, Register object) {
5103 PushSafepointRegistersScope scope(this);
5106 __ CallRuntimeSaveDoubles(Runtime::kTryMigrateInstance);
5107 RecordSafepointWithRegisters(
5108 instr->pointer_map(), 1, Safepoint::kNoLazyDeopt);
5110 __ test(eax, Immediate(kSmiTagMask));
5112 DeoptimizeIf(zero, instr, Deoptimizer::kInstanceMigrationFailed);
5116 void LCodeGen::DoCheckMaps(LCheckMaps* instr) {
5117 class DeferredCheckMaps final : public LDeferredCode {
5119 DeferredCheckMaps(LCodeGen* codegen, LCheckMaps* instr, Register object)
5120 : LDeferredCode(codegen), instr_(instr), object_(object) {
5121 SetExit(check_maps());
5123 void Generate() override {
5124 codegen()->DoDeferredInstanceMigration(instr_, object_);
5126 Label* check_maps() { return &check_maps_; }
5127 LInstruction* instr() override { return instr_; }
5135 if (instr->hydrogen()->IsStabilityCheck()) {
5136 const UniqueSet<Map>* maps = instr->hydrogen()->maps();
5137 for (int i = 0; i < maps->size(); ++i) {
5138 AddStabilityDependency(maps->at(i).handle());
5143 LOperand* input = instr->value();
5144 DCHECK(input->IsRegister());
5145 Register reg = ToRegister(input);
5147 DeferredCheckMaps* deferred = NULL;
5148 if (instr->hydrogen()->HasMigrationTarget()) {
5149 deferred = new(zone()) DeferredCheckMaps(this, instr, reg);
5150 __ bind(deferred->check_maps());
5153 const UniqueSet<Map>* maps = instr->hydrogen()->maps();
5155 for (int i = 0; i < maps->size() - 1; i++) {
5156 Handle<Map> map = maps->at(i).handle();
5157 __ CompareMap(reg, map);
5158 __ j(equal, &success, Label::kNear);
5161 Handle<Map> map = maps->at(maps->size() - 1).handle();
5162 __ CompareMap(reg, map);
5163 if (instr->hydrogen()->HasMigrationTarget()) {
5164 __ j(not_equal, deferred->entry());
5166 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongMap);
5173 void LCodeGen::DoClampDToUint8(LClampDToUint8* instr) {
5174 XMMRegister value_reg = ToDoubleRegister(instr->unclamped());
5175 XMMRegister xmm_scratch = double_scratch0();
5176 Register result_reg = ToRegister(instr->result());
5177 __ ClampDoubleToUint8(value_reg, xmm_scratch, result_reg);
5181 void LCodeGen::DoClampIToUint8(LClampIToUint8* instr) {
5182 DCHECK(instr->unclamped()->Equals(instr->result()));
5183 Register value_reg = ToRegister(instr->result());
5184 __ ClampUint8(value_reg);
5188 void LCodeGen::DoClampTToUint8(LClampTToUint8* instr) {
5189 DCHECK(instr->unclamped()->Equals(instr->result()));
5190 Register input_reg = ToRegister(instr->unclamped());
5191 XMMRegister temp_xmm_reg = ToDoubleRegister(instr->temp_xmm());
5192 XMMRegister xmm_scratch = double_scratch0();
5193 Label is_smi, done, heap_number;
5195 __ JumpIfSmi(input_reg, &is_smi);
5197 // Check for heap number
5198 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
5199 factory()->heap_number_map());
5200 __ j(equal, &heap_number, Label::kNear);
5202 // Check for undefined. Undefined is converted to zero for clamping
5204 __ cmp(input_reg, factory()->undefined_value());
5205 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumberUndefined);
5206 __ mov(input_reg, 0);
5207 __ jmp(&done, Label::kNear);
5210 __ bind(&heap_number);
5211 __ movsd(xmm_scratch, FieldOperand(input_reg, HeapNumber::kValueOffset));
5212 __ ClampDoubleToUint8(xmm_scratch, temp_xmm_reg, input_reg);
5213 __ jmp(&done, Label::kNear);
5217 __ SmiUntag(input_reg);
5218 __ ClampUint8(input_reg);
5223 void LCodeGen::DoDoubleBits(LDoubleBits* instr) {
5224 XMMRegister value_reg = ToDoubleRegister(instr->value());
5225 Register result_reg = ToRegister(instr->result());
5226 if (instr->hydrogen()->bits() == HDoubleBits::HIGH) {
5227 if (CpuFeatures::IsSupported(SSE4_1)) {
5228 CpuFeatureScope scope2(masm(), SSE4_1);
5229 __ pextrd(result_reg, value_reg, 1);
5231 XMMRegister xmm_scratch = double_scratch0();
5232 __ pshufd(xmm_scratch, value_reg, 1);
5233 __ movd(result_reg, xmm_scratch);
5236 __ movd(result_reg, value_reg);
5241 void LCodeGen::DoConstructDouble(LConstructDouble* instr) {
5242 Register hi_reg = ToRegister(instr->hi());
5243 Register lo_reg = ToRegister(instr->lo());
5244 XMMRegister result_reg = ToDoubleRegister(instr->result());
5246 if (CpuFeatures::IsSupported(SSE4_1)) {
5247 CpuFeatureScope scope2(masm(), SSE4_1);
5248 __ movd(result_reg, lo_reg);
5249 __ pinsrd(result_reg, hi_reg, 1);
5251 XMMRegister xmm_scratch = double_scratch0();
5252 __ movd(result_reg, hi_reg);
5253 __ psllq(result_reg, 32);
5254 __ movd(xmm_scratch, lo_reg);
5255 __ orps(result_reg, xmm_scratch);
5260 void LCodeGen::DoAllocate(LAllocate* instr) {
5261 class DeferredAllocate final : public LDeferredCode {
5263 DeferredAllocate(LCodeGen* codegen, LAllocate* instr)
5264 : LDeferredCode(codegen), instr_(instr) { }
5265 void Generate() override { codegen()->DoDeferredAllocate(instr_); }
5266 LInstruction* instr() override { return instr_; }
5272 DeferredAllocate* deferred = new(zone()) DeferredAllocate(this, instr);
5274 Register result = ToRegister(instr->result());
5275 Register temp = ToRegister(instr->temp());
5277 // Allocate memory for the object.
5278 AllocationFlags flags = TAG_OBJECT;
5279 if (instr->hydrogen()->MustAllocateDoubleAligned()) {
5280 flags = static_cast<AllocationFlags>(flags | DOUBLE_ALIGNMENT);
5282 if (instr->hydrogen()->IsOldSpaceAllocation()) {
5283 DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
5284 flags = static_cast<AllocationFlags>(flags | PRETENURE);
5287 if (instr->size()->IsConstantOperand()) {
5288 int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
5289 if (size <= Page::kMaxRegularHeapObjectSize) {
5290 __ Allocate(size, result, temp, no_reg, deferred->entry(), flags);
5292 __ jmp(deferred->entry());
5295 Register size = ToRegister(instr->size());
5296 __ Allocate(size, result, temp, no_reg, deferred->entry(), flags);
5299 __ bind(deferred->exit());
5301 if (instr->hydrogen()->MustPrefillWithFiller()) {
5302 if (instr->size()->IsConstantOperand()) {
5303 int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
5304 __ mov(temp, (size / kPointerSize) - 1);
5306 temp = ToRegister(instr->size());
5307 __ shr(temp, kPointerSizeLog2);
5312 __ mov(FieldOperand(result, temp, times_pointer_size, 0),
5313 isolate()->factory()->one_pointer_filler_map());
5315 __ j(not_zero, &loop);
5320 void LCodeGen::DoDeferredAllocate(LAllocate* instr) {
5321 Register result = ToRegister(instr->result());
5323 // TODO(3095996): Get rid of this. For now, we need to make the
5324 // result register contain a valid pointer because it is already
5325 // contained in the register pointer map.
5326 __ Move(result, Immediate(Smi::FromInt(0)));
5328 PushSafepointRegistersScope scope(this);
5329 if (instr->size()->IsRegister()) {
5330 Register size = ToRegister(instr->size());
5331 DCHECK(!size.is(result));
5332 __ SmiTag(ToRegister(instr->size()));
5335 int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
5336 if (size >= 0 && size <= Smi::kMaxValue) {
5337 __ push(Immediate(Smi::FromInt(size)));
5339 // We should never get here at runtime => abort
5345 int flags = AllocateDoubleAlignFlag::encode(
5346 instr->hydrogen()->MustAllocateDoubleAligned());
5347 if (instr->hydrogen()->IsOldSpaceAllocation()) {
5348 DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
5349 flags = AllocateTargetSpace::update(flags, OLD_SPACE);
5351 flags = AllocateTargetSpace::update(flags, NEW_SPACE);
5353 __ push(Immediate(Smi::FromInt(flags)));
5355 CallRuntimeFromDeferred(
5356 Runtime::kAllocateInTargetSpace, 2, instr, instr->context());
5357 __ StoreToSafepointRegisterSlot(result, eax);
5361 void LCodeGen::DoToFastProperties(LToFastProperties* instr) {
5362 DCHECK(ToRegister(instr->value()).is(eax));
5364 CallRuntime(Runtime::kToFastProperties, 1, instr);
5368 void LCodeGen::DoRegExpLiteral(LRegExpLiteral* instr) {
5369 DCHECK(ToRegister(instr->context()).is(esi));
5371 // Registers will be used as follows:
5372 // ecx = literals array.
5373 // ebx = regexp literal.
5374 // eax = regexp literal clone.
5376 int literal_offset =
5377 FixedArray::OffsetOfElementAt(instr->hydrogen()->literal_index());
5378 __ LoadHeapObject(ecx, instr->hydrogen()->literals());
5379 __ mov(ebx, FieldOperand(ecx, literal_offset));
5380 __ cmp(ebx, factory()->undefined_value());
5381 __ j(not_equal, &materialized, Label::kNear);
5383 // Create regexp literal using runtime function
5384 // Result will be in eax.
5386 __ push(Immediate(Smi::FromInt(instr->hydrogen()->literal_index())));
5387 __ push(Immediate(instr->hydrogen()->pattern()));
5388 __ push(Immediate(instr->hydrogen()->flags()));
5389 CallRuntime(Runtime::kMaterializeRegExpLiteral, 4, instr);
5392 __ bind(&materialized);
5393 int size = JSRegExp::kSize + JSRegExp::kInObjectFieldCount * kPointerSize;
5394 Label allocated, runtime_allocate;
5395 __ Allocate(size, eax, ecx, edx, &runtime_allocate, TAG_OBJECT);
5396 __ jmp(&allocated, Label::kNear);
5398 __ bind(&runtime_allocate);
5400 __ push(Immediate(Smi::FromInt(size)));
5401 CallRuntime(Runtime::kAllocateInNewSpace, 1, instr);
5404 __ bind(&allocated);
5405 // Copy the content into the newly allocated memory.
5406 // (Unroll copy loop once for better throughput).
5407 for (int i = 0; i < size - kPointerSize; i += 2 * kPointerSize) {
5408 __ mov(edx, FieldOperand(ebx, i));
5409 __ mov(ecx, FieldOperand(ebx, i + kPointerSize));
5410 __ mov(FieldOperand(eax, i), edx);
5411 __ mov(FieldOperand(eax, i + kPointerSize), ecx);
5413 if ((size % (2 * kPointerSize)) != 0) {
5414 __ mov(edx, FieldOperand(ebx, size - kPointerSize));
5415 __ mov(FieldOperand(eax, size - kPointerSize), edx);
5420 void LCodeGen::DoFunctionLiteral(LFunctionLiteral* instr) {
5421 DCHECK(ToRegister(instr->context()).is(esi));
5422 // Use the fast case closure allocation code that allocates in new
5423 // space for nested functions that don't need literals cloning.
5424 bool pretenure = instr->hydrogen()->pretenure();
5425 if (!pretenure && instr->hydrogen()->has_no_literals()) {
5426 FastNewClosureStub stub(isolate(), instr->hydrogen()->language_mode(),
5427 instr->hydrogen()->kind());
5428 __ mov(ebx, Immediate(instr->hydrogen()->shared_info()));
5429 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
5432 __ push(Immediate(instr->hydrogen()->shared_info()));
5433 __ push(Immediate(pretenure ? factory()->true_value()
5434 : factory()->false_value()));
5435 CallRuntime(Runtime::kNewClosure, 3, instr);
5440 void LCodeGen::DoTypeof(LTypeof* instr) {
5441 DCHECK(ToRegister(instr->context()).is(esi));
5442 DCHECK(ToRegister(instr->value()).is(ebx));
5444 Register value_register = ToRegister(instr->value());
5445 __ JumpIfNotSmi(value_register, &do_call);
5446 __ mov(eax, Immediate(isolate()->factory()->number_string()));
5449 TypeofStub stub(isolate());
5450 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
5455 void LCodeGen::DoTypeofIsAndBranch(LTypeofIsAndBranch* instr) {
5456 Register input = ToRegister(instr->value());
5457 Condition final_branch_condition = EmitTypeofIs(instr, input);
5458 if (final_branch_condition != no_condition) {
5459 EmitBranch(instr, final_branch_condition);
5464 Condition LCodeGen::EmitTypeofIs(LTypeofIsAndBranch* instr, Register input) {
5465 Label* true_label = instr->TrueLabel(chunk_);
5466 Label* false_label = instr->FalseLabel(chunk_);
5467 Handle<String> type_name = instr->type_literal();
5468 int left_block = instr->TrueDestination(chunk_);
5469 int right_block = instr->FalseDestination(chunk_);
5470 int next_block = GetNextEmittedBlock();
5472 Label::Distance true_distance = left_block == next_block ? Label::kNear
5474 Label::Distance false_distance = right_block == next_block ? Label::kNear
5476 Condition final_branch_condition = no_condition;
5477 if (String::Equals(type_name, factory()->number_string())) {
5478 __ JumpIfSmi(input, true_label, true_distance);
5479 __ cmp(FieldOperand(input, HeapObject::kMapOffset),
5480 factory()->heap_number_map());
5481 final_branch_condition = equal;
5483 } else if (String::Equals(type_name, factory()->string_string())) {
5484 __ JumpIfSmi(input, false_label, false_distance);
5485 __ CmpObjectType(input, FIRST_NONSTRING_TYPE, input);
5486 __ j(above_equal, false_label, false_distance);
5487 __ test_b(FieldOperand(input, Map::kBitFieldOffset),
5488 1 << Map::kIsUndetectable);
5489 final_branch_condition = zero;
5491 } else if (String::Equals(type_name, factory()->symbol_string())) {
5492 __ JumpIfSmi(input, false_label, false_distance);
5493 __ CmpObjectType(input, SYMBOL_TYPE, input);
5494 final_branch_condition = equal;
5496 } else if (String::Equals(type_name, factory()->boolean_string())) {
5497 __ cmp(input, factory()->true_value());
5498 __ j(equal, true_label, true_distance);
5499 __ cmp(input, factory()->false_value());
5500 final_branch_condition = equal;
5502 } else if (String::Equals(type_name, factory()->undefined_string())) {
5503 __ cmp(input, factory()->undefined_value());
5504 __ j(equal, true_label, true_distance);
5505 __ JumpIfSmi(input, false_label, false_distance);
5506 // Check for undetectable objects => true.
5507 __ mov(input, FieldOperand(input, HeapObject::kMapOffset));
5508 __ test_b(FieldOperand(input, Map::kBitFieldOffset),
5509 1 << Map::kIsUndetectable);
5510 final_branch_condition = not_zero;
5512 } else if (String::Equals(type_name, factory()->function_string())) {
5513 STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
5514 __ JumpIfSmi(input, false_label, false_distance);
5515 __ CmpObjectType(input, JS_FUNCTION_TYPE, input);
5516 __ j(equal, true_label, true_distance);
5517 __ CmpInstanceType(input, JS_FUNCTION_PROXY_TYPE);
5518 final_branch_condition = equal;
5520 } else if (String::Equals(type_name, factory()->object_string())) {
5521 __ JumpIfSmi(input, false_label, false_distance);
5522 __ cmp(input, factory()->null_value());
5523 __ j(equal, true_label, true_distance);
5524 __ CmpObjectType(input, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE, input);
5525 __ j(below, false_label, false_distance);
5526 __ CmpInstanceType(input, LAST_NONCALLABLE_SPEC_OBJECT_TYPE);
5527 __ j(above, false_label, false_distance);
5528 // Check for undetectable objects => false.
5529 __ test_b(FieldOperand(input, Map::kBitFieldOffset),
5530 1 << Map::kIsUndetectable);
5531 final_branch_condition = zero;
5534 __ jmp(false_label, false_distance);
5536 return final_branch_condition;
5540 void LCodeGen::DoIsConstructCallAndBranch(LIsConstructCallAndBranch* instr) {
5541 Register temp = ToRegister(instr->temp());
5543 EmitIsConstructCall(temp);
5544 EmitBranch(instr, equal);
5548 void LCodeGen::EmitIsConstructCall(Register temp) {
5549 // Get the frame pointer for the calling frame.
5550 __ mov(temp, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
5552 // Skip the arguments adaptor frame if it exists.
5553 Label check_frame_marker;
5554 __ cmp(Operand(temp, StandardFrameConstants::kContextOffset),
5555 Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
5556 __ j(not_equal, &check_frame_marker, Label::kNear);
5557 __ mov(temp, Operand(temp, StandardFrameConstants::kCallerFPOffset));
5559 // Check the marker in the calling frame.
5560 __ bind(&check_frame_marker);
5561 __ cmp(Operand(temp, StandardFrameConstants::kMarkerOffset),
5562 Immediate(Smi::FromInt(StackFrame::CONSTRUCT)));
5566 void LCodeGen::EnsureSpaceForLazyDeopt(int space_needed) {
5567 if (!info()->IsStub()) {
5568 // Ensure that we have enough space after the previous lazy-bailout
5569 // instruction for patching the code here.
5570 int current_pc = masm()->pc_offset();
5571 if (current_pc < last_lazy_deopt_pc_ + space_needed) {
5572 int padding_size = last_lazy_deopt_pc_ + space_needed - current_pc;
5573 __ Nop(padding_size);
5576 last_lazy_deopt_pc_ = masm()->pc_offset();
5580 void LCodeGen::DoLazyBailout(LLazyBailout* instr) {
5581 last_lazy_deopt_pc_ = masm()->pc_offset();
5582 DCHECK(instr->HasEnvironment());
5583 LEnvironment* env = instr->environment();
5584 RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt);
5585 safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
5589 void LCodeGen::DoDeoptimize(LDeoptimize* instr) {
5590 Deoptimizer::BailoutType type = instr->hydrogen()->type();
5591 // TODO(danno): Stubs expect all deopts to be lazy for historical reasons (the
5592 // needed return address), even though the implementation of LAZY and EAGER is
5593 // now identical. When LAZY is eventually completely folded into EAGER, remove
5594 // the special case below.
5595 if (info()->IsStub() && type == Deoptimizer::EAGER) {
5596 type = Deoptimizer::LAZY;
5598 DeoptimizeIf(no_condition, instr, instr->hydrogen()->reason(), type);
5602 void LCodeGen::DoDummy(LDummy* instr) {
5603 // Nothing to see here, move on!
5607 void LCodeGen::DoDummyUse(LDummyUse* instr) {
5608 // Nothing to see here, move on!
5612 void LCodeGen::DoDeferredStackCheck(LStackCheck* instr) {
5613 PushSafepointRegistersScope scope(this);
5614 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
5615 __ CallRuntimeSaveDoubles(Runtime::kStackGuard);
5616 RecordSafepointWithLazyDeopt(
5617 instr, RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
5618 DCHECK(instr->HasEnvironment());
5619 LEnvironment* env = instr->environment();
5620 safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
5624 void LCodeGen::DoStackCheck(LStackCheck* instr) {
5625 class DeferredStackCheck final : public LDeferredCode {
5627 DeferredStackCheck(LCodeGen* codegen, LStackCheck* instr)
5628 : LDeferredCode(codegen), instr_(instr) { }
5629 void Generate() override { codegen()->DoDeferredStackCheck(instr_); }
5630 LInstruction* instr() override { return instr_; }
5633 LStackCheck* instr_;
5636 DCHECK(instr->HasEnvironment());
5637 LEnvironment* env = instr->environment();
5638 // There is no LLazyBailout instruction for stack-checks. We have to
5639 // prepare for lazy deoptimization explicitly here.
5640 if (instr->hydrogen()->is_function_entry()) {
5641 // Perform stack overflow check.
5643 ExternalReference stack_limit =
5644 ExternalReference::address_of_stack_limit(isolate());
5645 __ cmp(esp, Operand::StaticVariable(stack_limit));
5646 __ j(above_equal, &done, Label::kNear);
5648 DCHECK(instr->context()->IsRegister());
5649 DCHECK(ToRegister(instr->context()).is(esi));
5650 CallCode(isolate()->builtins()->StackCheck(),
5651 RelocInfo::CODE_TARGET,
5655 DCHECK(instr->hydrogen()->is_backwards_branch());
5656 // Perform stack overflow check if this goto needs it before jumping.
5657 DeferredStackCheck* deferred_stack_check =
5658 new(zone()) DeferredStackCheck(this, instr);
5659 ExternalReference stack_limit =
5660 ExternalReference::address_of_stack_limit(isolate());
5661 __ cmp(esp, Operand::StaticVariable(stack_limit));
5662 __ j(below, deferred_stack_check->entry());
5663 EnsureSpaceForLazyDeopt(Deoptimizer::patch_size());
5664 __ bind(instr->done_label());
5665 deferred_stack_check->SetExit(instr->done_label());
5666 RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt);
5667 // Don't record a deoptimization index for the safepoint here.
5668 // This will be done explicitly when emitting call and the safepoint in
5669 // the deferred code.
5674 void LCodeGen::DoOsrEntry(LOsrEntry* instr) {
5675 // This is a pseudo-instruction that ensures that the environment here is
5676 // properly registered for deoptimization and records the assembler's PC
5678 LEnvironment* environment = instr->environment();
5680 // If the environment were already registered, we would have no way of
5681 // backpatching it with the spill slot operands.
5682 DCHECK(!environment->HasBeenRegistered());
5683 RegisterEnvironmentForDeoptimization(environment, Safepoint::kNoLazyDeopt);
5685 GenerateOsrPrologue();
5689 void LCodeGen::DoForInPrepareMap(LForInPrepareMap* instr) {
5690 DCHECK(ToRegister(instr->context()).is(esi));
5691 __ test(eax, Immediate(kSmiTagMask));
5692 DeoptimizeIf(zero, instr, Deoptimizer::kSmi);
5694 STATIC_ASSERT(FIRST_JS_PROXY_TYPE == FIRST_SPEC_OBJECT_TYPE);
5695 __ CmpObjectType(eax, LAST_JS_PROXY_TYPE, ecx);
5696 DeoptimizeIf(below_equal, instr, Deoptimizer::kWrongInstanceType);
5698 Label use_cache, call_runtime;
5699 __ CheckEnumCache(&call_runtime);
5701 __ mov(eax, FieldOperand(eax, HeapObject::kMapOffset));
5702 __ jmp(&use_cache, Label::kNear);
5704 // Get the set of properties to enumerate.
5705 __ bind(&call_runtime);
5707 CallRuntime(Runtime::kGetPropertyNamesFast, 1, instr);
5709 __ cmp(FieldOperand(eax, HeapObject::kMapOffset),
5710 isolate()->factory()->meta_map());
5711 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongMap);
5712 __ bind(&use_cache);
5716 void LCodeGen::DoForInCacheArray(LForInCacheArray* instr) {
5717 Register map = ToRegister(instr->map());
5718 Register result = ToRegister(instr->result());
5719 Label load_cache, done;
5720 __ EnumLength(result, map);
5721 __ cmp(result, Immediate(Smi::FromInt(0)));
5722 __ j(not_equal, &load_cache, Label::kNear);
5723 __ mov(result, isolate()->factory()->empty_fixed_array());
5724 __ jmp(&done, Label::kNear);
5726 __ bind(&load_cache);
5727 __ LoadInstanceDescriptors(map, result);
5729 FieldOperand(result, DescriptorArray::kEnumCacheOffset));
5731 FieldOperand(result, FixedArray::SizeFor(instr->idx())));
5733 __ test(result, result);
5734 DeoptimizeIf(equal, instr, Deoptimizer::kNoCache);
5738 void LCodeGen::DoCheckMapValue(LCheckMapValue* instr) {
5739 Register object = ToRegister(instr->value());
5740 __ cmp(ToRegister(instr->map()),
5741 FieldOperand(object, HeapObject::kMapOffset));
5742 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongMap);
5746 void LCodeGen::DoDeferredLoadMutableDouble(LLoadFieldByIndex* instr,
5749 PushSafepointRegistersScope scope(this);
5753 __ CallRuntimeSaveDoubles(Runtime::kLoadMutableDouble);
5754 RecordSafepointWithRegisters(
5755 instr->pointer_map(), 2, Safepoint::kNoLazyDeopt);
5756 __ StoreToSafepointRegisterSlot(object, eax);
5760 void LCodeGen::DoLoadFieldByIndex(LLoadFieldByIndex* instr) {
5761 class DeferredLoadMutableDouble final : public LDeferredCode {
5763 DeferredLoadMutableDouble(LCodeGen* codegen,
5764 LLoadFieldByIndex* instr,
5767 : LDeferredCode(codegen),
5772 void Generate() override {
5773 codegen()->DoDeferredLoadMutableDouble(instr_, object_, index_);
5775 LInstruction* instr() override { return instr_; }
5778 LLoadFieldByIndex* instr_;
5783 Register object = ToRegister(instr->object());
5784 Register index = ToRegister(instr->index());
5786 DeferredLoadMutableDouble* deferred;
5787 deferred = new(zone()) DeferredLoadMutableDouble(
5788 this, instr, object, index);
5790 Label out_of_object, done;
5791 __ test(index, Immediate(Smi::FromInt(1)));
5792 __ j(not_zero, deferred->entry());
5796 __ cmp(index, Immediate(0));
5797 __ j(less, &out_of_object, Label::kNear);
5798 __ mov(object, FieldOperand(object,
5800 times_half_pointer_size,
5801 JSObject::kHeaderSize));
5802 __ jmp(&done, Label::kNear);
5804 __ bind(&out_of_object);
5805 __ mov(object, FieldOperand(object, JSObject::kPropertiesOffset));
5807 // Index is now equal to out of object property index plus 1.
5808 __ mov(object, FieldOperand(object,
5810 times_half_pointer_size,
5811 FixedArray::kHeaderSize - kPointerSize));
5812 __ bind(deferred->exit());
5817 void LCodeGen::DoStoreFrameContext(LStoreFrameContext* instr) {
5818 Register context = ToRegister(instr->context());
5819 __ mov(Operand(ebp, StandardFrameConstants::kContextOffset), context);
5823 void LCodeGen::DoAllocateBlockContext(LAllocateBlockContext* instr) {
5824 Handle<ScopeInfo> scope_info = instr->scope_info();
5825 __ Push(scope_info);
5826 __ push(ToRegister(instr->function()));
5827 CallRuntime(Runtime::kPushBlockContext, 2, instr);
5828 RecordSafepoint(Safepoint::kNoLazyDeopt);
5834 } // namespace internal
5837 #endif // V8_TARGET_ARCH_IA32