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.
5 #if V8_TARGET_ARCH_IA32
7 #include "src/base/bits.h"
8 #include "src/code-factory.h"
9 #include "src/code-stubs.h"
10 #include "src/codegen.h"
11 #include "src/cpu-profiler.h"
12 #include "src/deoptimizer.h"
13 #include "src/hydrogen-osr.h"
14 #include "src/ia32/frames-ia32.h"
15 #include "src/ia32/lithium-codegen-ia32.h"
16 #include "src/ic/ic.h"
17 #include "src/ic/stub-cache.h"
22 // When invoking builtins, we need to record the safepoint in the middle of
23 // the invoke instruction sequence generated by the macro assembler.
24 class SafepointGenerator final : public CallWrapper {
26 SafepointGenerator(LCodeGen* codegen,
27 LPointerMap* pointers,
28 Safepoint::DeoptMode mode)
32 virtual ~SafepointGenerator() {}
34 void BeforeCall(int call_size) const override {}
36 void AfterCall() const override {
37 codegen_->RecordSafepoint(pointers_, deopt_mode_);
42 LPointerMap* pointers_;
43 Safepoint::DeoptMode deopt_mode_;
49 bool LCodeGen::GenerateCode() {
50 LPhase phase("Z_Code generation", chunk());
54 // Open a frame scope to indicate that there is a frame on the stack. The
55 // MANUAL indicates that the scope shouldn't actually generate code to set up
56 // the frame (that is done in GeneratePrologue).
57 FrameScope frame_scope(masm_, StackFrame::MANUAL);
59 support_aligned_spilled_doubles_ = info()->IsOptimizing();
61 dynamic_frame_alignment_ = info()->IsOptimizing() &&
62 ((chunk()->num_double_slots() > 2 &&
63 !chunk()->graph()->is_recursive()) ||
64 !info()->osr_ast_id().IsNone());
66 return GeneratePrologue() &&
68 GenerateDeferredCode() &&
69 GenerateJumpTable() &&
70 GenerateSafepointTable();
74 void LCodeGen::FinishCode(Handle<Code> code) {
76 code->set_stack_slots(GetStackSlotCount());
77 code->set_safepoint_table_offset(safepoints_.GetCodeOffset());
78 PopulateDeoptimizationData(code);
79 if (info()->ShouldEnsureSpaceForLazyDeopt()) {
80 Deoptimizer::EnsureRelocSpaceForLazyDeoptimization(code);
86 void LCodeGen::MakeSureStackPagesMapped(int offset) {
87 const int kPageSize = 4 * KB;
88 for (offset -= kPageSize; offset > 0; offset -= kPageSize) {
89 __ mov(Operand(esp, offset), eax);
95 void LCodeGen::SaveCallerDoubles() {
96 DCHECK(info()->saves_caller_doubles());
97 DCHECK(NeedsEagerFrame());
98 Comment(";;; Save clobbered callee double registers");
100 BitVector* doubles = chunk()->allocated_double_registers();
101 BitVector::Iterator save_iterator(doubles);
102 while (!save_iterator.Done()) {
103 __ movsd(MemOperand(esp, count * kDoubleSize),
104 XMMRegister::FromAllocationIndex(save_iterator.Current()));
105 save_iterator.Advance();
111 void LCodeGen::RestoreCallerDoubles() {
112 DCHECK(info()->saves_caller_doubles());
113 DCHECK(NeedsEagerFrame());
114 Comment(";;; Restore clobbered callee double registers");
115 BitVector* doubles = chunk()->allocated_double_registers();
116 BitVector::Iterator save_iterator(doubles);
118 while (!save_iterator.Done()) {
119 __ movsd(XMMRegister::FromAllocationIndex(save_iterator.Current()),
120 MemOperand(esp, count * kDoubleSize));
121 save_iterator.Advance();
127 bool LCodeGen::GeneratePrologue() {
128 DCHECK(is_generating());
130 if (info()->IsOptimizing()) {
131 ProfileEntryHookStub::MaybeCallEntryHook(masm_);
134 if (strlen(FLAG_stop_at) > 0 &&
135 info_->literal()->name()->IsUtf8EqualTo(CStrVector(FLAG_stop_at))) {
140 // Sloppy mode functions and builtins need to replace the receiver with the
141 // global proxy when called as functions (without an explicit receiver
143 if (info()->MustReplaceUndefinedReceiverWithGlobalProxy()) {
145 // +1 for return address.
146 int receiver_offset = (scope()->num_parameters() + 1) * kPointerSize;
147 __ mov(ecx, Operand(esp, receiver_offset));
149 __ cmp(ecx, isolate()->factory()->undefined_value());
150 __ j(not_equal, &ok, Label::kNear);
152 __ mov(ecx, GlobalObjectOperand());
153 __ mov(ecx, FieldOperand(ecx, GlobalObject::kGlobalProxyOffset));
155 __ mov(Operand(esp, receiver_offset), ecx);
160 if (support_aligned_spilled_doubles_ && dynamic_frame_alignment_) {
161 // Move state of dynamic frame alignment into edx.
162 __ Move(edx, Immediate(kNoAlignmentPadding));
164 Label do_not_pad, align_loop;
165 STATIC_ASSERT(kDoubleSize == 2 * kPointerSize);
166 // Align esp + 4 to a multiple of 2 * kPointerSize.
167 __ test(esp, Immediate(kPointerSize));
168 __ j(not_zero, &do_not_pad, Label::kNear);
169 __ push(Immediate(0));
171 __ mov(edx, Immediate(kAlignmentPaddingPushed));
172 // Copy arguments, receiver, and return address.
173 __ mov(ecx, Immediate(scope()->num_parameters() + 2));
175 __ bind(&align_loop);
176 __ mov(eax, Operand(ebx, 1 * kPointerSize));
177 __ mov(Operand(ebx, 0), eax);
178 __ add(Operand(ebx), Immediate(kPointerSize));
180 __ j(not_zero, &align_loop, Label::kNear);
181 __ mov(Operand(ebx, 0), Immediate(kAlignmentZapValue));
182 __ bind(&do_not_pad);
186 info()->set_prologue_offset(masm_->pc_offset());
187 if (NeedsEagerFrame()) {
188 DCHECK(!frame_is_built_);
189 frame_is_built_ = true;
190 if (info()->IsStub()) {
193 __ Prologue(info()->IsCodePreAgingActive());
195 info()->AddNoFrameRange(0, masm_->pc_offset());
198 if (info()->IsOptimizing() &&
199 dynamic_frame_alignment_ &&
201 __ test(esp, Immediate(kPointerSize));
202 __ Assert(zero, kFrameIsExpectedToBeAligned);
205 // Reserve space for the stack slots needed by the code.
206 int slots = GetStackSlotCount();
207 DCHECK(slots != 0 || !info()->IsOptimizing());
210 if (dynamic_frame_alignment_) {
213 __ push(Immediate(kNoAlignmentPadding));
216 if (FLAG_debug_code) {
217 __ sub(Operand(esp), Immediate(slots * kPointerSize));
219 MakeSureStackPagesMapped(slots * kPointerSize);
222 __ mov(Operand(eax), Immediate(slots));
225 __ mov(MemOperand(esp, eax, times_4, 0),
226 Immediate(kSlotsZapValue));
228 __ j(not_zero, &loop);
231 __ sub(Operand(esp), Immediate(slots * kPointerSize));
233 MakeSureStackPagesMapped(slots * kPointerSize);
237 if (support_aligned_spilled_doubles_) {
238 Comment(";;; Store dynamic frame alignment tag for spilled doubles");
239 // Store dynamic frame alignment state in the first local.
240 int offset = JavaScriptFrameConstants::kDynamicAlignmentStateOffset;
241 if (dynamic_frame_alignment_) {
242 __ mov(Operand(ebp, offset), edx);
244 __ mov(Operand(ebp, offset), Immediate(kNoAlignmentPadding));
249 if (info()->saves_caller_doubles()) SaveCallerDoubles();
251 return !is_aborted();
255 void LCodeGen::DoPrologue(LPrologue* instr) {
256 Comment(";;; Prologue begin");
258 // Possibly allocate a local context.
259 if (info_->num_heap_slots() > 0) {
260 Comment(";;; Allocate local context");
261 bool need_write_barrier = true;
262 // Argument to NewContext is the function, which is still in edi.
263 int slots = info_->num_heap_slots() - Context::MIN_CONTEXT_SLOTS;
264 Safepoint::DeoptMode deopt_mode = Safepoint::kNoLazyDeopt;
265 if (info()->scope()->is_script_scope()) {
267 __ Push(info()->scope()->GetScopeInfo(info()->isolate()));
268 __ CallRuntime(Runtime::kNewScriptContext, 2);
269 deopt_mode = Safepoint::kLazyDeopt;
270 } else if (slots <= FastNewContextStub::kMaximumSlots) {
271 FastNewContextStub stub(isolate(), slots);
273 // Result of FastNewContextStub is always in new space.
274 need_write_barrier = false;
277 __ CallRuntime(Runtime::kNewFunctionContext, 1);
279 RecordSafepoint(deopt_mode);
281 // Context is returned in eax. It replaces the context passed to us.
282 // It's saved in the stack and kept live in esi.
284 __ mov(Operand(ebp, StandardFrameConstants::kContextOffset), eax);
286 // Copy parameters into context if necessary.
287 int num_parameters = scope()->num_parameters();
288 int first_parameter = scope()->has_this_declaration() ? -1 : 0;
289 for (int i = first_parameter; i < num_parameters; i++) {
290 Variable* var = (i == -1) ? scope()->receiver() : scope()->parameter(i);
291 if (var->IsContextSlot()) {
292 int parameter_offset = StandardFrameConstants::kCallerSPOffset +
293 (num_parameters - 1 - i) * kPointerSize;
294 // Load parameter from stack.
295 __ mov(eax, Operand(ebp, parameter_offset));
296 // Store it in the context.
297 int context_offset = Context::SlotOffset(var->index());
298 __ mov(Operand(esi, context_offset), eax);
299 // Update the write barrier. This clobbers eax and ebx.
300 if (need_write_barrier) {
301 __ RecordWriteContextSlot(esi,
306 } else if (FLAG_debug_code) {
308 __ JumpIfInNewSpace(esi, eax, &done, Label::kNear);
309 __ Abort(kExpectedNewSpaceObject);
314 Comment(";;; End allocate local context");
317 Comment(";;; Prologue end");
321 void LCodeGen::GenerateOsrPrologue() {
322 // Generate the OSR entry prologue at the first unknown OSR value, or if there
323 // are none, at the OSR entrypoint instruction.
324 if (osr_pc_offset_ >= 0) return;
326 osr_pc_offset_ = masm()->pc_offset();
328 // Move state of dynamic frame alignment into edx.
329 __ Move(edx, Immediate(kNoAlignmentPadding));
331 if (support_aligned_spilled_doubles_ && dynamic_frame_alignment_) {
332 Label do_not_pad, align_loop;
333 // Align ebp + 4 to a multiple of 2 * kPointerSize.
334 __ test(ebp, Immediate(kPointerSize));
335 __ j(zero, &do_not_pad, Label::kNear);
336 __ push(Immediate(0));
338 __ mov(edx, Immediate(kAlignmentPaddingPushed));
340 // Move all parts of the frame over one word. The frame consists of:
341 // unoptimized frame slots, alignment state, context, frame pointer, return
342 // address, receiver, and the arguments.
343 __ mov(ecx, Immediate(scope()->num_parameters() +
344 5 + graph()->osr()->UnoptimizedFrameSlots()));
346 __ bind(&align_loop);
347 __ mov(eax, Operand(ebx, 1 * kPointerSize));
348 __ mov(Operand(ebx, 0), eax);
349 __ add(Operand(ebx), Immediate(kPointerSize));
351 __ j(not_zero, &align_loop, Label::kNear);
352 __ mov(Operand(ebx, 0), Immediate(kAlignmentZapValue));
353 __ sub(Operand(ebp), Immediate(kPointerSize));
354 __ bind(&do_not_pad);
357 // Save the first local, which is overwritten by the alignment state.
358 Operand alignment_loc = MemOperand(ebp, -3 * kPointerSize);
359 __ push(alignment_loc);
361 // Set the dynamic frame alignment state.
362 __ mov(alignment_loc, edx);
364 // Adjust the frame size, subsuming the unoptimized frame into the
366 int slots = GetStackSlotCount() - graph()->osr()->UnoptimizedFrameSlots();
368 __ sub(esp, Immediate((slots - 1) * kPointerSize));
372 void LCodeGen::GenerateBodyInstructionPre(LInstruction* instr) {
373 if (instr->IsCall()) {
374 EnsureSpaceForLazyDeopt(Deoptimizer::patch_size());
376 if (!instr->IsLazyBailout() && !instr->IsGap()) {
377 safepoints_.BumpLastLazySafepointIndex();
382 void LCodeGen::GenerateBodyInstructionPost(LInstruction* instr) { }
385 bool LCodeGen::GenerateJumpTable() {
386 if (!jump_table_.length()) return !is_aborted();
389 Comment(";;; -------------------- Jump table --------------------");
391 for (int i = 0; i < jump_table_.length(); i++) {
392 Deoptimizer::JumpTableEntry* table_entry = &jump_table_[i];
393 __ bind(&table_entry->label);
394 Address entry = table_entry->address;
395 DeoptComment(table_entry->deopt_info);
396 if (table_entry->needs_frame) {
397 DCHECK(!info()->saves_caller_doubles());
398 __ push(Immediate(ExternalReference::ForDeoptEntry(entry)));
399 __ call(&needs_frame);
401 if (info()->saves_caller_doubles()) RestoreCallerDoubles();
402 __ call(entry, RelocInfo::RUNTIME_ENTRY);
404 info()->LogDeoptCallPosition(masm()->pc_offset(),
405 table_entry->deopt_info.inlining_id);
407 if (needs_frame.is_linked()) {
408 __ bind(&needs_frame);
411 3: return address <-- esp
416 __ sub(esp, Immediate(kPointerSize)); // Reserve space for stub marker.
417 __ push(MemOperand(esp, kPointerSize)); // Copy return address.
418 __ push(MemOperand(esp, 3 * kPointerSize)); // Copy entry address.
425 0: entry address <-- esp
427 __ mov(MemOperand(esp, 4 * kPointerSize), ebp); // Save ebp.
429 __ mov(ebp, MemOperand(ebp, StandardFrameConstants::kContextOffset));
430 __ mov(MemOperand(esp, 3 * kPointerSize), ebp);
431 // Fill ebp with the right stack frame address.
432 __ lea(ebp, MemOperand(esp, 4 * kPointerSize));
433 // This variant of deopt can only be used with stubs. Since we don't
434 // have a function pointer to install in the stack frame that we're
435 // building, install a special marker there instead.
436 DCHECK(info()->IsStub());
437 __ mov(MemOperand(esp, 2 * kPointerSize),
438 Immediate(Smi::FromInt(StackFrame::STUB)));
445 0: entry address <-- esp
447 __ ret(0); // Call the continuation without clobbering registers.
449 return !is_aborted();
453 bool LCodeGen::GenerateDeferredCode() {
454 DCHECK(is_generating());
455 if (deferred_.length() > 0) {
456 for (int i = 0; !is_aborted() && i < deferred_.length(); i++) {
457 LDeferredCode* code = deferred_[i];
460 instructions_->at(code->instruction_index())->hydrogen_value();
461 RecordAndWritePosition(
462 chunk()->graph()->SourcePositionToScriptPosition(value->position()));
464 Comment(";;; <@%d,#%d> "
465 "-------------------- Deferred %s --------------------",
466 code->instruction_index(),
467 code->instr()->hydrogen_value()->id(),
468 code->instr()->Mnemonic());
469 __ bind(code->entry());
470 if (NeedsDeferredFrame()) {
471 Comment(";;; Build frame");
472 DCHECK(!frame_is_built_);
473 DCHECK(info()->IsStub());
474 frame_is_built_ = true;
475 // Build the frame in such a way that esi isn't trashed.
476 __ push(ebp); // Caller's frame pointer.
477 __ push(Operand(ebp, StandardFrameConstants::kContextOffset));
478 __ push(Immediate(Smi::FromInt(StackFrame::STUB)));
479 __ lea(ebp, Operand(esp, 2 * kPointerSize));
480 Comment(";;; Deferred code");
483 if (NeedsDeferredFrame()) {
484 __ bind(code->done());
485 Comment(";;; Destroy frame");
486 DCHECK(frame_is_built_);
487 frame_is_built_ = false;
491 __ jmp(code->exit());
495 // Deferred code is the last part of the instruction sequence. Mark
496 // the generated code as done unless we bailed out.
497 if (!is_aborted()) status_ = DONE;
498 return !is_aborted();
502 bool LCodeGen::GenerateSafepointTable() {
504 if (info()->ShouldEnsureSpaceForLazyDeopt()) {
505 // For lazy deoptimization we need space to patch a call after every call.
506 // Ensure there is always space for such patching, even if the code ends
508 int target_offset = masm()->pc_offset() + Deoptimizer::patch_size();
509 while (masm()->pc_offset() < target_offset) {
513 safepoints_.Emit(masm(), GetStackSlotCount());
514 return !is_aborted();
518 Register LCodeGen::ToRegister(int index) const {
519 return Register::FromAllocationIndex(index);
523 XMMRegister LCodeGen::ToDoubleRegister(int index) const {
524 return XMMRegister::FromAllocationIndex(index);
528 Register LCodeGen::ToRegister(LOperand* op) const {
529 DCHECK(op->IsRegister());
530 return ToRegister(op->index());
534 XMMRegister LCodeGen::ToDoubleRegister(LOperand* op) const {
535 DCHECK(op->IsDoubleRegister());
536 return ToDoubleRegister(op->index());
540 int32_t LCodeGen::ToInteger32(LConstantOperand* op) const {
541 return ToRepresentation(op, Representation::Integer32());
545 int32_t LCodeGen::ToRepresentation(LConstantOperand* op,
546 const Representation& r) const {
547 HConstant* constant = chunk_->LookupConstant(op);
548 if (r.IsExternal()) {
549 return reinterpret_cast<int32_t>(
550 constant->ExternalReferenceValue().address());
552 int32_t value = constant->Integer32Value();
553 if (r.IsInteger32()) return value;
554 DCHECK(r.IsSmiOrTagged());
555 return reinterpret_cast<int32_t>(Smi::FromInt(value));
559 Handle<Object> LCodeGen::ToHandle(LConstantOperand* op) const {
560 HConstant* constant = chunk_->LookupConstant(op);
561 DCHECK(chunk_->LookupLiteralRepresentation(op).IsSmiOrTagged());
562 return constant->handle(isolate());
566 double LCodeGen::ToDouble(LConstantOperand* op) const {
567 HConstant* constant = chunk_->LookupConstant(op);
568 DCHECK(constant->HasDoubleValue());
569 return constant->DoubleValue();
573 ExternalReference LCodeGen::ToExternalReference(LConstantOperand* op) const {
574 HConstant* constant = chunk_->LookupConstant(op);
575 DCHECK(constant->HasExternalReferenceValue());
576 return constant->ExternalReferenceValue();
580 bool LCodeGen::IsInteger32(LConstantOperand* op) const {
581 return chunk_->LookupLiteralRepresentation(op).IsSmiOrInteger32();
585 bool LCodeGen::IsSmi(LConstantOperand* op) const {
586 return chunk_->LookupLiteralRepresentation(op).IsSmi();
590 static int ArgumentsOffsetWithoutFrame(int index) {
592 return -(index + 1) * kPointerSize + kPCOnStackSize;
596 Operand LCodeGen::ToOperand(LOperand* op) const {
597 if (op->IsRegister()) return Operand(ToRegister(op));
598 if (op->IsDoubleRegister()) return Operand(ToDoubleRegister(op));
599 DCHECK(op->IsStackSlot() || op->IsDoubleStackSlot());
600 if (NeedsEagerFrame()) {
601 return Operand(ebp, StackSlotOffset(op->index()));
603 // Retrieve parameter without eager stack-frame relative to the
605 return Operand(esp, ArgumentsOffsetWithoutFrame(op->index()));
610 Operand LCodeGen::HighOperand(LOperand* op) {
611 DCHECK(op->IsDoubleStackSlot());
612 if (NeedsEagerFrame()) {
613 return Operand(ebp, StackSlotOffset(op->index()) + kPointerSize);
615 // Retrieve parameter without eager stack-frame relative to the
618 esp, ArgumentsOffsetWithoutFrame(op->index()) + kPointerSize);
623 void LCodeGen::WriteTranslation(LEnvironment* environment,
624 Translation* translation) {
625 if (environment == NULL) return;
627 // The translation includes one command per value in the environment.
628 int translation_size = environment->translation_size();
630 WriteTranslation(environment->outer(), translation);
631 WriteTranslationFrame(environment, translation);
633 int object_index = 0;
634 int dematerialized_index = 0;
635 for (int i = 0; i < translation_size; ++i) {
636 LOperand* value = environment->values()->at(i);
638 environment, translation, value, environment->HasTaggedValueAt(i),
639 environment->HasUint32ValueAt(i), &object_index, &dematerialized_index);
644 void LCodeGen::AddToTranslation(LEnvironment* environment,
645 Translation* translation,
649 int* object_index_pointer,
650 int* dematerialized_index_pointer) {
651 if (op == LEnvironment::materialization_marker()) {
652 int object_index = (*object_index_pointer)++;
653 if (environment->ObjectIsDuplicateAt(object_index)) {
654 int dupe_of = environment->ObjectDuplicateOfAt(object_index);
655 translation->DuplicateObject(dupe_of);
658 int object_length = environment->ObjectLengthAt(object_index);
659 if (environment->ObjectIsArgumentsAt(object_index)) {
660 translation->BeginArgumentsObject(object_length);
662 translation->BeginCapturedObject(object_length);
664 int dematerialized_index = *dematerialized_index_pointer;
665 int env_offset = environment->translation_size() + dematerialized_index;
666 *dematerialized_index_pointer += object_length;
667 for (int i = 0; i < object_length; ++i) {
668 LOperand* value = environment->values()->at(env_offset + i);
669 AddToTranslation(environment,
672 environment->HasTaggedValueAt(env_offset + i),
673 environment->HasUint32ValueAt(env_offset + i),
674 object_index_pointer,
675 dematerialized_index_pointer);
680 if (op->IsStackSlot()) {
681 int index = op->index();
683 index += StandardFrameConstants::kFixedFrameSize / kPointerSize;
686 translation->StoreStackSlot(index);
687 } else if (is_uint32) {
688 translation->StoreUint32StackSlot(index);
690 translation->StoreInt32StackSlot(index);
692 } else if (op->IsDoubleStackSlot()) {
693 int index = op->index();
695 index += StandardFrameConstants::kFixedFrameSize / kPointerSize;
697 translation->StoreDoubleStackSlot(index);
698 } else if (op->IsRegister()) {
699 Register reg = ToRegister(op);
701 translation->StoreRegister(reg);
702 } else if (is_uint32) {
703 translation->StoreUint32Register(reg);
705 translation->StoreInt32Register(reg);
707 } else if (op->IsDoubleRegister()) {
708 XMMRegister reg = ToDoubleRegister(op);
709 translation->StoreDoubleRegister(reg);
710 } else if (op->IsConstantOperand()) {
711 HConstant* constant = chunk()->LookupConstant(LConstantOperand::cast(op));
712 int src_index = DefineDeoptimizationLiteral(constant->handle(isolate()));
713 translation->StoreLiteral(src_index);
720 void LCodeGen::CallCodeGeneric(Handle<Code> code,
721 RelocInfo::Mode mode,
723 SafepointMode safepoint_mode) {
724 DCHECK(instr != NULL);
726 RecordSafepointWithLazyDeopt(instr, safepoint_mode);
728 // Signal that we don't inline smi code before these stubs in the
729 // optimizing code generator.
730 if (code->kind() == Code::BINARY_OP_IC ||
731 code->kind() == Code::COMPARE_IC) {
737 void LCodeGen::CallCode(Handle<Code> code,
738 RelocInfo::Mode mode,
739 LInstruction* instr) {
740 CallCodeGeneric(code, mode, instr, RECORD_SIMPLE_SAFEPOINT);
744 void LCodeGen::CallRuntime(const Runtime::Function* fun,
747 SaveFPRegsMode save_doubles) {
748 DCHECK(instr != NULL);
749 DCHECK(instr->HasPointerMap());
751 __ CallRuntime(fun, argc, save_doubles);
753 RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
755 DCHECK(info()->is_calling());
759 void LCodeGen::LoadContextFromDeferred(LOperand* context) {
760 if (context->IsRegister()) {
761 if (!ToRegister(context).is(esi)) {
762 __ mov(esi, ToRegister(context));
764 } else if (context->IsStackSlot()) {
765 __ mov(esi, ToOperand(context));
766 } else if (context->IsConstantOperand()) {
767 HConstant* constant =
768 chunk_->LookupConstant(LConstantOperand::cast(context));
769 __ LoadObject(esi, Handle<Object>::cast(constant->handle(isolate())));
775 void LCodeGen::CallRuntimeFromDeferred(Runtime::FunctionId id,
779 LoadContextFromDeferred(context);
781 __ CallRuntimeSaveDoubles(id);
782 RecordSafepointWithRegisters(
783 instr->pointer_map(), argc, Safepoint::kNoLazyDeopt);
785 DCHECK(info()->is_calling());
789 void LCodeGen::RegisterEnvironmentForDeoptimization(
790 LEnvironment* environment, Safepoint::DeoptMode mode) {
791 environment->set_has_been_used();
792 if (!environment->HasBeenRegistered()) {
793 // Physical stack frame layout:
794 // -x ............. -4 0 ..................................... y
795 // [incoming arguments] [spill slots] [pushed outgoing arguments]
797 // Layout of the environment:
798 // 0 ..................................................... size-1
799 // [parameters] [locals] [expression stack including arguments]
801 // Layout of the translation:
802 // 0 ........................................................ size - 1 + 4
803 // [expression stack including arguments] [locals] [4 words] [parameters]
804 // |>------------ translation_size ------------<|
807 int jsframe_count = 0;
808 for (LEnvironment* e = environment; e != NULL; e = e->outer()) {
810 if (e->frame_type() == JS_FUNCTION) {
814 Translation translation(&translations_, frame_count, jsframe_count, zone());
815 WriteTranslation(environment, &translation);
816 int deoptimization_index = deoptimizations_.length();
817 int pc_offset = masm()->pc_offset();
818 environment->Register(deoptimization_index,
820 (mode == Safepoint::kLazyDeopt) ? pc_offset : -1);
821 deoptimizations_.Add(environment, zone());
826 void LCodeGen::DeoptimizeIf(Condition cc, LInstruction* instr,
827 Deoptimizer::DeoptReason deopt_reason,
828 Deoptimizer::BailoutType bailout_type) {
829 LEnvironment* environment = instr->environment();
830 RegisterEnvironmentForDeoptimization(environment, Safepoint::kNoLazyDeopt);
831 DCHECK(environment->HasBeenRegistered());
832 int id = environment->deoptimization_index();
834 Deoptimizer::GetDeoptimizationEntry(isolate(), id, bailout_type);
836 Abort(kBailoutWasNotPrepared);
840 if (DeoptEveryNTimes()) {
841 ExternalReference count = ExternalReference::stress_deopt_count(isolate());
845 __ mov(eax, Operand::StaticVariable(count));
846 __ sub(eax, Immediate(1));
847 __ j(not_zero, &no_deopt, Label::kNear);
848 if (FLAG_trap_on_deopt) __ int3();
849 __ mov(eax, Immediate(FLAG_deopt_every_n_times));
850 __ mov(Operand::StaticVariable(count), eax);
853 DCHECK(frame_is_built_);
854 __ call(entry, RelocInfo::RUNTIME_ENTRY);
856 __ mov(Operand::StaticVariable(count), eax);
861 if (info()->ShouldTrapOnDeopt()) {
863 if (cc != no_condition) __ j(NegateCondition(cc), &done, Label::kNear);
868 Deoptimizer::DeoptInfo deopt_info = MakeDeoptInfo(instr, deopt_reason);
870 DCHECK(info()->IsStub() || frame_is_built_);
871 if (cc == no_condition && frame_is_built_) {
872 DeoptComment(deopt_info);
873 __ call(entry, RelocInfo::RUNTIME_ENTRY);
874 info()->LogDeoptCallPosition(masm()->pc_offset(), deopt_info.inlining_id);
876 Deoptimizer::JumpTableEntry table_entry(entry, deopt_info, bailout_type,
878 // We often have several deopts to the same entry, reuse the last
879 // jump entry if this is the case.
880 if (FLAG_trace_deopt || isolate()->cpu_profiler()->is_profiling() ||
881 jump_table_.is_empty() ||
882 !table_entry.IsEquivalentTo(jump_table_.last())) {
883 jump_table_.Add(table_entry, zone());
885 if (cc == no_condition) {
886 __ jmp(&jump_table_.last().label);
888 __ j(cc, &jump_table_.last().label);
894 void LCodeGen::DeoptimizeIf(Condition cc, LInstruction* instr,
895 Deoptimizer::DeoptReason deopt_reason) {
896 Deoptimizer::BailoutType bailout_type = info()->IsStub()
898 : Deoptimizer::EAGER;
899 DeoptimizeIf(cc, instr, deopt_reason, bailout_type);
903 void LCodeGen::PopulateDeoptimizationData(Handle<Code> code) {
904 int length = deoptimizations_.length();
905 if (length == 0) return;
906 Handle<DeoptimizationInputData> data =
907 DeoptimizationInputData::New(isolate(), length, TENURED);
909 Handle<ByteArray> translations =
910 translations_.CreateByteArray(isolate()->factory());
911 data->SetTranslationByteArray(*translations);
912 data->SetInlinedFunctionCount(Smi::FromInt(inlined_function_count_));
913 data->SetOptimizationId(Smi::FromInt(info_->optimization_id()));
914 if (info_->IsOptimizing()) {
915 // Reference to shared function info does not change between phases.
916 AllowDeferredHandleDereference allow_handle_dereference;
917 data->SetSharedFunctionInfo(*info_->shared_info());
919 data->SetSharedFunctionInfo(Smi::FromInt(0));
921 data->SetWeakCellCache(Smi::FromInt(0));
923 Handle<FixedArray> literals =
924 factory()->NewFixedArray(deoptimization_literals_.length(), TENURED);
925 { AllowDeferredHandleDereference copy_handles;
926 for (int i = 0; i < deoptimization_literals_.length(); i++) {
927 literals->set(i, *deoptimization_literals_[i]);
929 data->SetLiteralArray(*literals);
932 data->SetOsrAstId(Smi::FromInt(info_->osr_ast_id().ToInt()));
933 data->SetOsrPcOffset(Smi::FromInt(osr_pc_offset_));
935 // Populate the deoptimization entries.
936 for (int i = 0; i < length; i++) {
937 LEnvironment* env = deoptimizations_[i];
938 data->SetAstId(i, env->ast_id());
939 data->SetTranslationIndex(i, Smi::FromInt(env->translation_index()));
940 data->SetArgumentsStackHeight(i,
941 Smi::FromInt(env->arguments_stack_height()));
942 data->SetPc(i, Smi::FromInt(env->pc_offset()));
944 code->set_deoptimization_data(*data);
948 void LCodeGen::PopulateDeoptimizationLiteralsWithInlinedFunctions() {
949 DCHECK_EQ(0, deoptimization_literals_.length());
950 for (auto function : chunk()->inlined_functions()) {
951 DefineDeoptimizationLiteral(function);
953 inlined_function_count_ = deoptimization_literals_.length();
957 void LCodeGen::RecordSafepointWithLazyDeopt(
958 LInstruction* instr, SafepointMode safepoint_mode) {
959 if (safepoint_mode == RECORD_SIMPLE_SAFEPOINT) {
960 RecordSafepoint(instr->pointer_map(), Safepoint::kLazyDeopt);
962 DCHECK(safepoint_mode == RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
963 RecordSafepointWithRegisters(
964 instr->pointer_map(), 0, Safepoint::kLazyDeopt);
969 void LCodeGen::RecordSafepoint(
970 LPointerMap* pointers,
971 Safepoint::Kind kind,
973 Safepoint::DeoptMode deopt_mode) {
974 DCHECK(kind == expected_safepoint_kind_);
975 const ZoneList<LOperand*>* operands = pointers->GetNormalizedOperands();
976 Safepoint safepoint =
977 safepoints_.DefineSafepoint(masm(), kind, arguments, deopt_mode);
978 for (int i = 0; i < operands->length(); i++) {
979 LOperand* pointer = operands->at(i);
980 if (pointer->IsStackSlot()) {
981 safepoint.DefinePointerSlot(pointer->index(), zone());
982 } else if (pointer->IsRegister() && (kind & Safepoint::kWithRegisters)) {
983 safepoint.DefinePointerRegister(ToRegister(pointer), zone());
989 void LCodeGen::RecordSafepoint(LPointerMap* pointers,
990 Safepoint::DeoptMode mode) {
991 RecordSafepoint(pointers, Safepoint::kSimple, 0, mode);
995 void LCodeGen::RecordSafepoint(Safepoint::DeoptMode mode) {
996 LPointerMap empty_pointers(zone());
997 RecordSafepoint(&empty_pointers, mode);
1001 void LCodeGen::RecordSafepointWithRegisters(LPointerMap* pointers,
1003 Safepoint::DeoptMode mode) {
1004 RecordSafepoint(pointers, Safepoint::kWithRegisters, arguments, mode);
1008 void LCodeGen::RecordAndWritePosition(int position) {
1009 if (position == RelocInfo::kNoPosition) return;
1010 masm()->positions_recorder()->RecordPosition(position);
1011 masm()->positions_recorder()->WriteRecordedPositions();
1015 static const char* LabelType(LLabel* label) {
1016 if (label->is_loop_header()) return " (loop header)";
1017 if (label->is_osr_entry()) return " (OSR entry)";
1022 void LCodeGen::DoLabel(LLabel* label) {
1023 Comment(";;; <@%d,#%d> -------------------- B%d%s --------------------",
1024 current_instruction_,
1025 label->hydrogen_value()->id(),
1028 __ bind(label->label());
1029 current_block_ = label->block_id();
1034 void LCodeGen::DoParallelMove(LParallelMove* move) {
1035 resolver_.Resolve(move);
1039 void LCodeGen::DoGap(LGap* gap) {
1040 for (int i = LGap::FIRST_INNER_POSITION;
1041 i <= LGap::LAST_INNER_POSITION;
1043 LGap::InnerPosition inner_pos = static_cast<LGap::InnerPosition>(i);
1044 LParallelMove* move = gap->GetParallelMove(inner_pos);
1045 if (move != NULL) DoParallelMove(move);
1050 void LCodeGen::DoInstructionGap(LInstructionGap* instr) {
1055 void LCodeGen::DoParameter(LParameter* instr) {
1060 void LCodeGen::DoCallStub(LCallStub* instr) {
1061 DCHECK(ToRegister(instr->context()).is(esi));
1062 DCHECK(ToRegister(instr->result()).is(eax));
1063 switch (instr->hydrogen()->major_key()) {
1064 case CodeStub::RegExpExec: {
1065 RegExpExecStub stub(isolate());
1066 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
1069 case CodeStub::SubString: {
1070 SubStringStub stub(isolate());
1071 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
1074 case CodeStub::StringCompare: {
1075 StringCompareStub stub(isolate());
1076 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
1085 void LCodeGen::DoUnknownOSRValue(LUnknownOSRValue* instr) {
1086 GenerateOsrPrologue();
1090 void LCodeGen::DoModByPowerOf2I(LModByPowerOf2I* instr) {
1091 Register dividend = ToRegister(instr->dividend());
1092 int32_t divisor = instr->divisor();
1093 DCHECK(dividend.is(ToRegister(instr->result())));
1095 // Theoretically, a variation of the branch-free code for integer division by
1096 // a power of 2 (calculating the remainder via an additional multiplication
1097 // (which gets simplified to an 'and') and subtraction) should be faster, and
1098 // this is exactly what GCC and clang emit. Nevertheless, benchmarks seem to
1099 // indicate that positive dividends are heavily favored, so the branching
1100 // version performs better.
1101 HMod* hmod = instr->hydrogen();
1102 int32_t mask = divisor < 0 ? -(divisor + 1) : (divisor - 1);
1103 Label dividend_is_not_negative, done;
1104 if (hmod->CheckFlag(HValue::kLeftCanBeNegative)) {
1105 __ test(dividend, dividend);
1106 __ j(not_sign, ÷nd_is_not_negative, Label::kNear);
1107 // Note that this is correct even for kMinInt operands.
1109 __ and_(dividend, mask);
1111 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1112 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1114 __ jmp(&done, Label::kNear);
1117 __ bind(÷nd_is_not_negative);
1118 __ and_(dividend, mask);
1123 void LCodeGen::DoModByConstI(LModByConstI* instr) {
1124 Register dividend = ToRegister(instr->dividend());
1125 int32_t divisor = instr->divisor();
1126 DCHECK(ToRegister(instr->result()).is(eax));
1129 DeoptimizeIf(no_condition, instr, Deoptimizer::kDivisionByZero);
1133 __ TruncatingDiv(dividend, Abs(divisor));
1134 __ imul(edx, edx, Abs(divisor));
1135 __ mov(eax, dividend);
1138 // Check for negative zero.
1139 HMod* hmod = instr->hydrogen();
1140 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1141 Label remainder_not_zero;
1142 __ j(not_zero, &remainder_not_zero, Label::kNear);
1143 __ cmp(dividend, Immediate(0));
1144 DeoptimizeIf(less, instr, Deoptimizer::kMinusZero);
1145 __ bind(&remainder_not_zero);
1150 void LCodeGen::DoModI(LModI* instr) {
1151 HMod* hmod = instr->hydrogen();
1153 Register left_reg = ToRegister(instr->left());
1154 DCHECK(left_reg.is(eax));
1155 Register right_reg = ToRegister(instr->right());
1156 DCHECK(!right_reg.is(eax));
1157 DCHECK(!right_reg.is(edx));
1158 Register result_reg = ToRegister(instr->result());
1159 DCHECK(result_reg.is(edx));
1162 // Check for x % 0, idiv would signal a divide error. We have to
1163 // deopt in this case because we can't return a NaN.
1164 if (hmod->CheckFlag(HValue::kCanBeDivByZero)) {
1165 __ test(right_reg, Operand(right_reg));
1166 DeoptimizeIf(zero, instr, Deoptimizer::kDivisionByZero);
1169 // Check for kMinInt % -1, idiv would signal a divide error. We
1170 // have to deopt if we care about -0, because we can't return that.
1171 if (hmod->CheckFlag(HValue::kCanOverflow)) {
1172 Label no_overflow_possible;
1173 __ cmp(left_reg, kMinInt);
1174 __ j(not_equal, &no_overflow_possible, Label::kNear);
1175 __ cmp(right_reg, -1);
1176 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1177 DeoptimizeIf(equal, instr, Deoptimizer::kMinusZero);
1179 __ j(not_equal, &no_overflow_possible, Label::kNear);
1180 __ Move(result_reg, Immediate(0));
1181 __ jmp(&done, Label::kNear);
1183 __ bind(&no_overflow_possible);
1186 // Sign extend dividend in eax into edx:eax.
1189 // If we care about -0, test if the dividend is <0 and the result is 0.
1190 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1191 Label positive_left;
1192 __ test(left_reg, Operand(left_reg));
1193 __ j(not_sign, &positive_left, Label::kNear);
1195 __ test(result_reg, Operand(result_reg));
1196 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1197 __ jmp(&done, Label::kNear);
1198 __ bind(&positive_left);
1205 void LCodeGen::DoDivByPowerOf2I(LDivByPowerOf2I* instr) {
1206 Register dividend = ToRegister(instr->dividend());
1207 int32_t divisor = instr->divisor();
1208 Register result = ToRegister(instr->result());
1209 DCHECK(divisor == kMinInt || base::bits::IsPowerOfTwo32(Abs(divisor)));
1210 DCHECK(!result.is(dividend));
1212 // Check for (0 / -x) that will produce negative zero.
1213 HDiv* hdiv = instr->hydrogen();
1214 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
1215 __ test(dividend, dividend);
1216 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1218 // Check for (kMinInt / -1).
1219 if (hdiv->CheckFlag(HValue::kCanOverflow) && divisor == -1) {
1220 __ cmp(dividend, kMinInt);
1221 DeoptimizeIf(zero, instr, Deoptimizer::kOverflow);
1223 // Deoptimize if remainder will not be 0.
1224 if (!hdiv->CheckFlag(HInstruction::kAllUsesTruncatingToInt32) &&
1225 divisor != 1 && divisor != -1) {
1226 int32_t mask = divisor < 0 ? -(divisor + 1) : (divisor - 1);
1227 __ test(dividend, Immediate(mask));
1228 DeoptimizeIf(not_zero, instr, Deoptimizer::kLostPrecision);
1230 __ Move(result, dividend);
1231 int32_t shift = WhichPowerOf2Abs(divisor);
1233 // The arithmetic shift is always OK, the 'if' is an optimization only.
1234 if (shift > 1) __ sar(result, 31);
1235 __ shr(result, 32 - shift);
1236 __ add(result, dividend);
1237 __ sar(result, shift);
1239 if (divisor < 0) __ neg(result);
1243 void LCodeGen::DoDivByConstI(LDivByConstI* instr) {
1244 Register dividend = ToRegister(instr->dividend());
1245 int32_t divisor = instr->divisor();
1246 DCHECK(ToRegister(instr->result()).is(edx));
1249 DeoptimizeIf(no_condition, instr, Deoptimizer::kDivisionByZero);
1253 // Check for (0 / -x) that will produce negative zero.
1254 HDiv* hdiv = instr->hydrogen();
1255 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
1256 __ test(dividend, dividend);
1257 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1260 __ TruncatingDiv(dividend, Abs(divisor));
1261 if (divisor < 0) __ neg(edx);
1263 if (!hdiv->CheckFlag(HInstruction::kAllUsesTruncatingToInt32)) {
1265 __ imul(eax, eax, divisor);
1266 __ sub(eax, dividend);
1267 DeoptimizeIf(not_equal, instr, Deoptimizer::kLostPrecision);
1272 // TODO(svenpanne) Refactor this to avoid code duplication with DoFlooringDivI.
1273 void LCodeGen::DoDivI(LDivI* instr) {
1274 HBinaryOperation* hdiv = instr->hydrogen();
1275 Register dividend = ToRegister(instr->dividend());
1276 Register divisor = ToRegister(instr->divisor());
1277 Register remainder = ToRegister(instr->temp());
1278 DCHECK(dividend.is(eax));
1279 DCHECK(remainder.is(edx));
1280 DCHECK(ToRegister(instr->result()).is(eax));
1281 DCHECK(!divisor.is(eax));
1282 DCHECK(!divisor.is(edx));
1285 if (hdiv->CheckFlag(HValue::kCanBeDivByZero)) {
1286 __ test(divisor, divisor);
1287 DeoptimizeIf(zero, instr, Deoptimizer::kDivisionByZero);
1290 // Check for (0 / -x) that will produce negative zero.
1291 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero)) {
1292 Label dividend_not_zero;
1293 __ test(dividend, dividend);
1294 __ j(not_zero, ÷nd_not_zero, Label::kNear);
1295 __ test(divisor, divisor);
1296 DeoptimizeIf(sign, instr, Deoptimizer::kMinusZero);
1297 __ bind(÷nd_not_zero);
1300 // Check for (kMinInt / -1).
1301 if (hdiv->CheckFlag(HValue::kCanOverflow)) {
1302 Label dividend_not_min_int;
1303 __ cmp(dividend, kMinInt);
1304 __ j(not_zero, ÷nd_not_min_int, Label::kNear);
1305 __ cmp(divisor, -1);
1306 DeoptimizeIf(zero, instr, Deoptimizer::kOverflow);
1307 __ bind(÷nd_not_min_int);
1310 // Sign extend to edx (= remainder).
1314 if (!hdiv->CheckFlag(HValue::kAllUsesTruncatingToInt32)) {
1315 // Deoptimize if remainder is not 0.
1316 __ test(remainder, remainder);
1317 DeoptimizeIf(not_zero, instr, Deoptimizer::kLostPrecision);
1322 void LCodeGen::DoFlooringDivByPowerOf2I(LFlooringDivByPowerOf2I* instr) {
1323 Register dividend = ToRegister(instr->dividend());
1324 int32_t divisor = instr->divisor();
1325 DCHECK(dividend.is(ToRegister(instr->result())));
1327 // If the divisor is positive, things are easy: There can be no deopts and we
1328 // can simply do an arithmetic right shift.
1329 if (divisor == 1) return;
1330 int32_t shift = WhichPowerOf2Abs(divisor);
1332 __ sar(dividend, shift);
1336 // If the divisor is negative, we have to negate and handle edge cases.
1338 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1339 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1342 // Dividing by -1 is basically negation, unless we overflow.
1343 if (divisor == -1) {
1344 if (instr->hydrogen()->CheckFlag(HValue::kLeftCanBeMinInt)) {
1345 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1350 // If the negation could not overflow, simply shifting is OK.
1351 if (!instr->hydrogen()->CheckFlag(HValue::kLeftCanBeMinInt)) {
1352 __ sar(dividend, shift);
1356 Label not_kmin_int, done;
1357 __ j(no_overflow, ¬_kmin_int, Label::kNear);
1358 __ mov(dividend, Immediate(kMinInt / divisor));
1359 __ jmp(&done, Label::kNear);
1360 __ bind(¬_kmin_int);
1361 __ sar(dividend, shift);
1366 void LCodeGen::DoFlooringDivByConstI(LFlooringDivByConstI* instr) {
1367 Register dividend = ToRegister(instr->dividend());
1368 int32_t divisor = instr->divisor();
1369 DCHECK(ToRegister(instr->result()).is(edx));
1372 DeoptimizeIf(no_condition, instr, Deoptimizer::kDivisionByZero);
1376 // Check for (0 / -x) that will produce negative zero.
1377 HMathFloorOfDiv* hdiv = instr->hydrogen();
1378 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
1379 __ test(dividend, dividend);
1380 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1383 // Easy case: We need no dynamic check for the dividend and the flooring
1384 // division is the same as the truncating division.
1385 if ((divisor > 0 && !hdiv->CheckFlag(HValue::kLeftCanBeNegative)) ||
1386 (divisor < 0 && !hdiv->CheckFlag(HValue::kLeftCanBePositive))) {
1387 __ TruncatingDiv(dividend, Abs(divisor));
1388 if (divisor < 0) __ neg(edx);
1392 // In the general case we may need to adjust before and after the truncating
1393 // division to get a flooring division.
1394 Register temp = ToRegister(instr->temp3());
1395 DCHECK(!temp.is(dividend) && !temp.is(eax) && !temp.is(edx));
1396 Label needs_adjustment, done;
1397 __ cmp(dividend, Immediate(0));
1398 __ j(divisor > 0 ? less : greater, &needs_adjustment, Label::kNear);
1399 __ TruncatingDiv(dividend, Abs(divisor));
1400 if (divisor < 0) __ neg(edx);
1401 __ jmp(&done, Label::kNear);
1402 __ bind(&needs_adjustment);
1403 __ lea(temp, Operand(dividend, divisor > 0 ? 1 : -1));
1404 __ TruncatingDiv(temp, Abs(divisor));
1405 if (divisor < 0) __ neg(edx);
1411 // TODO(svenpanne) Refactor this to avoid code duplication with DoDivI.
1412 void LCodeGen::DoFlooringDivI(LFlooringDivI* instr) {
1413 HBinaryOperation* hdiv = instr->hydrogen();
1414 Register dividend = ToRegister(instr->dividend());
1415 Register divisor = ToRegister(instr->divisor());
1416 Register remainder = ToRegister(instr->temp());
1417 Register result = ToRegister(instr->result());
1418 DCHECK(dividend.is(eax));
1419 DCHECK(remainder.is(edx));
1420 DCHECK(result.is(eax));
1421 DCHECK(!divisor.is(eax));
1422 DCHECK(!divisor.is(edx));
1425 if (hdiv->CheckFlag(HValue::kCanBeDivByZero)) {
1426 __ test(divisor, divisor);
1427 DeoptimizeIf(zero, instr, Deoptimizer::kDivisionByZero);
1430 // Check for (0 / -x) that will produce negative zero.
1431 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero)) {
1432 Label dividend_not_zero;
1433 __ test(dividend, dividend);
1434 __ j(not_zero, ÷nd_not_zero, Label::kNear);
1435 __ test(divisor, divisor);
1436 DeoptimizeIf(sign, instr, Deoptimizer::kMinusZero);
1437 __ bind(÷nd_not_zero);
1440 // Check for (kMinInt / -1).
1441 if (hdiv->CheckFlag(HValue::kCanOverflow)) {
1442 Label dividend_not_min_int;
1443 __ cmp(dividend, kMinInt);
1444 __ j(not_zero, ÷nd_not_min_int, Label::kNear);
1445 __ cmp(divisor, -1);
1446 DeoptimizeIf(zero, instr, Deoptimizer::kOverflow);
1447 __ bind(÷nd_not_min_int);
1450 // Sign extend to edx (= remainder).
1455 __ test(remainder, remainder);
1456 __ j(zero, &done, Label::kNear);
1457 __ xor_(remainder, divisor);
1458 __ sar(remainder, 31);
1459 __ add(result, remainder);
1464 void LCodeGen::DoMulI(LMulI* instr) {
1465 Register left = ToRegister(instr->left());
1466 LOperand* right = instr->right();
1468 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1469 __ mov(ToRegister(instr->temp()), left);
1472 if (right->IsConstantOperand()) {
1473 // Try strength reductions on the multiplication.
1474 // All replacement instructions are at most as long as the imul
1475 // and have better latency.
1476 int constant = ToInteger32(LConstantOperand::cast(right));
1477 if (constant == -1) {
1479 } else if (constant == 0) {
1480 __ xor_(left, Operand(left));
1481 } else if (constant == 2) {
1482 __ add(left, Operand(left));
1483 } else if (!instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
1484 // If we know that the multiplication can't overflow, it's safe to
1485 // use instructions that don't set the overflow flag for the
1492 __ lea(left, Operand(left, left, times_2, 0));
1498 __ lea(left, Operand(left, left, times_4, 0));
1504 __ lea(left, Operand(left, left, times_8, 0));
1510 __ imul(left, left, constant);
1514 __ imul(left, left, constant);
1517 if (instr->hydrogen()->representation().IsSmi()) {
1520 __ imul(left, ToOperand(right));
1523 if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
1524 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1527 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1528 // Bail out if the result is supposed to be negative zero.
1530 __ test(left, Operand(left));
1531 __ j(not_zero, &done, Label::kNear);
1532 if (right->IsConstantOperand()) {
1533 if (ToInteger32(LConstantOperand::cast(right)) < 0) {
1534 DeoptimizeIf(no_condition, instr, Deoptimizer::kMinusZero);
1535 } else if (ToInteger32(LConstantOperand::cast(right)) == 0) {
1536 __ cmp(ToRegister(instr->temp()), Immediate(0));
1537 DeoptimizeIf(less, instr, Deoptimizer::kMinusZero);
1540 // Test the non-zero operand for negative sign.
1541 __ or_(ToRegister(instr->temp()), ToOperand(right));
1542 DeoptimizeIf(sign, instr, Deoptimizer::kMinusZero);
1549 void LCodeGen::DoBitI(LBitI* instr) {
1550 LOperand* left = instr->left();
1551 LOperand* right = instr->right();
1552 DCHECK(left->Equals(instr->result()));
1553 DCHECK(left->IsRegister());
1555 if (right->IsConstantOperand()) {
1556 int32_t right_operand =
1557 ToRepresentation(LConstantOperand::cast(right),
1558 instr->hydrogen()->representation());
1559 switch (instr->op()) {
1560 case Token::BIT_AND:
1561 __ and_(ToRegister(left), right_operand);
1564 __ or_(ToRegister(left), right_operand);
1566 case Token::BIT_XOR:
1567 if (right_operand == int32_t(~0)) {
1568 __ not_(ToRegister(left));
1570 __ xor_(ToRegister(left), right_operand);
1578 switch (instr->op()) {
1579 case Token::BIT_AND:
1580 __ and_(ToRegister(left), ToOperand(right));
1583 __ or_(ToRegister(left), ToOperand(right));
1585 case Token::BIT_XOR:
1586 __ xor_(ToRegister(left), ToOperand(right));
1596 void LCodeGen::DoShiftI(LShiftI* instr) {
1597 LOperand* left = instr->left();
1598 LOperand* right = instr->right();
1599 DCHECK(left->Equals(instr->result()));
1600 DCHECK(left->IsRegister());
1601 if (right->IsRegister()) {
1602 DCHECK(ToRegister(right).is(ecx));
1604 switch (instr->op()) {
1606 __ ror_cl(ToRegister(left));
1609 __ sar_cl(ToRegister(left));
1612 __ shr_cl(ToRegister(left));
1613 if (instr->can_deopt()) {
1614 __ test(ToRegister(left), ToRegister(left));
1615 DeoptimizeIf(sign, instr, Deoptimizer::kNegativeValue);
1619 __ shl_cl(ToRegister(left));
1626 int value = ToInteger32(LConstantOperand::cast(right));
1627 uint8_t shift_count = static_cast<uint8_t>(value & 0x1F);
1628 switch (instr->op()) {
1630 if (shift_count == 0 && instr->can_deopt()) {
1631 __ test(ToRegister(left), ToRegister(left));
1632 DeoptimizeIf(sign, instr, Deoptimizer::kNegativeValue);
1634 __ ror(ToRegister(left), shift_count);
1638 if (shift_count != 0) {
1639 __ sar(ToRegister(left), shift_count);
1643 if (shift_count != 0) {
1644 __ shr(ToRegister(left), shift_count);
1645 } else if (instr->can_deopt()) {
1646 __ test(ToRegister(left), ToRegister(left));
1647 DeoptimizeIf(sign, instr, Deoptimizer::kNegativeValue);
1651 if (shift_count != 0) {
1652 if (instr->hydrogen_value()->representation().IsSmi() &&
1653 instr->can_deopt()) {
1654 if (shift_count != 1) {
1655 __ shl(ToRegister(left), shift_count - 1);
1657 __ SmiTag(ToRegister(left));
1658 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1660 __ shl(ToRegister(left), shift_count);
1672 void LCodeGen::DoSubI(LSubI* instr) {
1673 LOperand* left = instr->left();
1674 LOperand* right = instr->right();
1675 DCHECK(left->Equals(instr->result()));
1677 if (right->IsConstantOperand()) {
1678 __ sub(ToOperand(left),
1679 ToImmediate(right, instr->hydrogen()->representation()));
1681 __ sub(ToRegister(left), ToOperand(right));
1683 if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
1684 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1689 void LCodeGen::DoConstantI(LConstantI* instr) {
1690 __ Move(ToRegister(instr->result()), Immediate(instr->value()));
1694 void LCodeGen::DoConstantS(LConstantS* instr) {
1695 __ Move(ToRegister(instr->result()), Immediate(instr->value()));
1699 void LCodeGen::DoConstantD(LConstantD* instr) {
1700 uint64_t const bits = instr->bits();
1701 uint32_t const lower = static_cast<uint32_t>(bits);
1702 uint32_t const upper = static_cast<uint32_t>(bits >> 32);
1703 DCHECK(instr->result()->IsDoubleRegister());
1705 XMMRegister result = ToDoubleRegister(instr->result());
1707 __ xorps(result, result);
1709 Register temp = ToRegister(instr->temp());
1710 if (CpuFeatures::IsSupported(SSE4_1)) {
1711 CpuFeatureScope scope2(masm(), SSE4_1);
1713 __ Move(temp, Immediate(lower));
1714 __ movd(result, Operand(temp));
1715 __ Move(temp, Immediate(upper));
1716 __ pinsrd(result, Operand(temp), 1);
1718 __ xorps(result, result);
1719 __ Move(temp, Immediate(upper));
1720 __ pinsrd(result, Operand(temp), 1);
1723 __ Move(temp, Immediate(upper));
1724 __ movd(result, Operand(temp));
1725 __ psllq(result, 32);
1727 XMMRegister xmm_scratch = double_scratch0();
1728 __ Move(temp, Immediate(lower));
1729 __ movd(xmm_scratch, Operand(temp));
1730 __ orps(result, xmm_scratch);
1737 void LCodeGen::DoConstantE(LConstantE* instr) {
1738 __ lea(ToRegister(instr->result()), Operand::StaticVariable(instr->value()));
1742 void LCodeGen::DoConstantT(LConstantT* instr) {
1743 Register reg = ToRegister(instr->result());
1744 Handle<Object> object = instr->value(isolate());
1745 AllowDeferredHandleDereference smi_check;
1746 __ LoadObject(reg, object);
1750 void LCodeGen::DoMapEnumLength(LMapEnumLength* instr) {
1751 Register result = ToRegister(instr->result());
1752 Register map = ToRegister(instr->value());
1753 __ EnumLength(result, map);
1757 void LCodeGen::DoDateField(LDateField* instr) {
1758 Register object = ToRegister(instr->date());
1759 Register result = ToRegister(instr->result());
1760 Register scratch = ToRegister(instr->temp());
1761 Smi* index = instr->index();
1762 DCHECK(object.is(result));
1763 DCHECK(object.is(eax));
1765 if (index->value() == 0) {
1766 __ mov(result, FieldOperand(object, JSDate::kValueOffset));
1768 Label runtime, done;
1769 if (index->value() < JSDate::kFirstUncachedField) {
1770 ExternalReference stamp = ExternalReference::date_cache_stamp(isolate());
1771 __ mov(scratch, Operand::StaticVariable(stamp));
1772 __ cmp(scratch, FieldOperand(object, JSDate::kCacheStampOffset));
1773 __ j(not_equal, &runtime, Label::kNear);
1774 __ mov(result, FieldOperand(object, JSDate::kValueOffset +
1775 kPointerSize * index->value()));
1776 __ jmp(&done, Label::kNear);
1779 __ PrepareCallCFunction(2, scratch);
1780 __ mov(Operand(esp, 0), object);
1781 __ mov(Operand(esp, 1 * kPointerSize), Immediate(index));
1782 __ CallCFunction(ExternalReference::get_date_field_function(isolate()), 2);
1788 Operand LCodeGen::BuildSeqStringOperand(Register string,
1790 String::Encoding encoding) {
1791 if (index->IsConstantOperand()) {
1792 int offset = ToRepresentation(LConstantOperand::cast(index),
1793 Representation::Integer32());
1794 if (encoding == String::TWO_BYTE_ENCODING) {
1795 offset *= kUC16Size;
1797 STATIC_ASSERT(kCharSize == 1);
1798 return FieldOperand(string, SeqString::kHeaderSize + offset);
1800 return FieldOperand(
1801 string, ToRegister(index),
1802 encoding == String::ONE_BYTE_ENCODING ? times_1 : times_2,
1803 SeqString::kHeaderSize);
1807 void LCodeGen::DoSeqStringGetChar(LSeqStringGetChar* instr) {
1808 String::Encoding encoding = instr->hydrogen()->encoding();
1809 Register result = ToRegister(instr->result());
1810 Register string = ToRegister(instr->string());
1812 if (FLAG_debug_code) {
1814 __ mov(string, FieldOperand(string, HeapObject::kMapOffset));
1815 __ movzx_b(string, FieldOperand(string, Map::kInstanceTypeOffset));
1817 __ and_(string, Immediate(kStringRepresentationMask | kStringEncodingMask));
1818 static const uint32_t one_byte_seq_type = kSeqStringTag | kOneByteStringTag;
1819 static const uint32_t two_byte_seq_type = kSeqStringTag | kTwoByteStringTag;
1820 __ cmp(string, Immediate(encoding == String::ONE_BYTE_ENCODING
1821 ? one_byte_seq_type : two_byte_seq_type));
1822 __ Check(equal, kUnexpectedStringType);
1826 Operand operand = BuildSeqStringOperand(string, instr->index(), encoding);
1827 if (encoding == String::ONE_BYTE_ENCODING) {
1828 __ movzx_b(result, operand);
1830 __ movzx_w(result, operand);
1835 void LCodeGen::DoSeqStringSetChar(LSeqStringSetChar* instr) {
1836 String::Encoding encoding = instr->hydrogen()->encoding();
1837 Register string = ToRegister(instr->string());
1839 if (FLAG_debug_code) {
1840 Register value = ToRegister(instr->value());
1841 Register index = ToRegister(instr->index());
1842 static const uint32_t one_byte_seq_type = kSeqStringTag | kOneByteStringTag;
1843 static const uint32_t two_byte_seq_type = kSeqStringTag | kTwoByteStringTag;
1845 instr->hydrogen()->encoding() == String::ONE_BYTE_ENCODING
1846 ? one_byte_seq_type : two_byte_seq_type;
1847 __ EmitSeqStringSetCharCheck(string, index, value, encoding_mask);
1850 Operand operand = BuildSeqStringOperand(string, instr->index(), encoding);
1851 if (instr->value()->IsConstantOperand()) {
1852 int value = ToRepresentation(LConstantOperand::cast(instr->value()),
1853 Representation::Integer32());
1854 DCHECK_LE(0, value);
1855 if (encoding == String::ONE_BYTE_ENCODING) {
1856 DCHECK_LE(value, String::kMaxOneByteCharCode);
1857 __ mov_b(operand, static_cast<int8_t>(value));
1859 DCHECK_LE(value, String::kMaxUtf16CodeUnit);
1860 __ mov_w(operand, static_cast<int16_t>(value));
1863 Register value = ToRegister(instr->value());
1864 if (encoding == String::ONE_BYTE_ENCODING) {
1865 __ mov_b(operand, value);
1867 __ mov_w(operand, value);
1873 void LCodeGen::DoAddI(LAddI* instr) {
1874 LOperand* left = instr->left();
1875 LOperand* right = instr->right();
1877 if (LAddI::UseLea(instr->hydrogen()) && !left->Equals(instr->result())) {
1878 if (right->IsConstantOperand()) {
1879 int32_t offset = ToRepresentation(LConstantOperand::cast(right),
1880 instr->hydrogen()->representation());
1881 __ lea(ToRegister(instr->result()), MemOperand(ToRegister(left), offset));
1883 Operand address(ToRegister(left), ToRegister(right), times_1, 0);
1884 __ lea(ToRegister(instr->result()), address);
1887 if (right->IsConstantOperand()) {
1888 __ add(ToOperand(left),
1889 ToImmediate(right, instr->hydrogen()->representation()));
1891 __ add(ToRegister(left), ToOperand(right));
1893 if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
1894 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1900 void LCodeGen::DoMathMinMax(LMathMinMax* instr) {
1901 LOperand* left = instr->left();
1902 LOperand* right = instr->right();
1903 DCHECK(left->Equals(instr->result()));
1904 HMathMinMax::Operation operation = instr->hydrogen()->operation();
1905 if (instr->hydrogen()->representation().IsSmiOrInteger32()) {
1907 Condition condition = (operation == HMathMinMax::kMathMin)
1910 if (right->IsConstantOperand()) {
1911 Operand left_op = ToOperand(left);
1912 Immediate immediate = ToImmediate(LConstantOperand::cast(instr->right()),
1913 instr->hydrogen()->representation());
1914 __ cmp(left_op, immediate);
1915 __ j(condition, &return_left, Label::kNear);
1916 __ mov(left_op, immediate);
1918 Register left_reg = ToRegister(left);
1919 Operand right_op = ToOperand(right);
1920 __ cmp(left_reg, right_op);
1921 __ j(condition, &return_left, Label::kNear);
1922 __ mov(left_reg, right_op);
1924 __ bind(&return_left);
1926 DCHECK(instr->hydrogen()->representation().IsDouble());
1927 Label check_nan_left, check_zero, return_left, return_right;
1928 Condition condition = (operation == HMathMinMax::kMathMin) ? below : above;
1929 XMMRegister left_reg = ToDoubleRegister(left);
1930 XMMRegister right_reg = ToDoubleRegister(right);
1931 __ ucomisd(left_reg, right_reg);
1932 __ j(parity_even, &check_nan_left, Label::kNear); // At least one NaN.
1933 __ j(equal, &check_zero, Label::kNear); // left == right.
1934 __ j(condition, &return_left, Label::kNear);
1935 __ jmp(&return_right, Label::kNear);
1937 __ bind(&check_zero);
1938 XMMRegister xmm_scratch = double_scratch0();
1939 __ xorps(xmm_scratch, xmm_scratch);
1940 __ ucomisd(left_reg, xmm_scratch);
1941 __ j(not_equal, &return_left, Label::kNear); // left == right != 0.
1942 // At this point, both left and right are either 0 or -0.
1943 if (operation == HMathMinMax::kMathMin) {
1944 __ orpd(left_reg, right_reg);
1946 // Since we operate on +0 and/or -0, addsd and andsd have the same effect.
1947 __ addsd(left_reg, right_reg);
1949 __ jmp(&return_left, Label::kNear);
1951 __ bind(&check_nan_left);
1952 __ ucomisd(left_reg, left_reg); // NaN check.
1953 __ j(parity_even, &return_left, Label::kNear); // left == NaN.
1954 __ bind(&return_right);
1955 __ movaps(left_reg, right_reg);
1957 __ bind(&return_left);
1962 void LCodeGen::DoArithmeticD(LArithmeticD* instr) {
1963 XMMRegister left = ToDoubleRegister(instr->left());
1964 XMMRegister right = ToDoubleRegister(instr->right());
1965 XMMRegister result = ToDoubleRegister(instr->result());
1966 switch (instr->op()) {
1968 if (CpuFeatures::IsSupported(AVX)) {
1969 CpuFeatureScope scope(masm(), AVX);
1970 __ vaddsd(result, left, right);
1972 DCHECK(result.is(left));
1973 __ addsd(left, right);
1977 if (CpuFeatures::IsSupported(AVX)) {
1978 CpuFeatureScope scope(masm(), AVX);
1979 __ vsubsd(result, left, right);
1981 DCHECK(result.is(left));
1982 __ subsd(left, right);
1986 if (CpuFeatures::IsSupported(AVX)) {
1987 CpuFeatureScope scope(masm(), AVX);
1988 __ vmulsd(result, left, right);
1990 DCHECK(result.is(left));
1991 __ mulsd(left, right);
1995 if (CpuFeatures::IsSupported(AVX)) {
1996 CpuFeatureScope scope(masm(), AVX);
1997 __ vdivsd(result, left, right);
1999 DCHECK(result.is(left));
2000 __ divsd(left, right);
2002 // Don't delete this mov. It may improve performance on some CPUs,
2003 // when there is a (v)mulsd depending on the result
2004 __ movaps(result, result);
2007 // Pass two doubles as arguments on the stack.
2008 __ PrepareCallCFunction(4, eax);
2009 __ movsd(Operand(esp, 0 * kDoubleSize), left);
2010 __ movsd(Operand(esp, 1 * kDoubleSize), right);
2012 ExternalReference::mod_two_doubles_operation(isolate()),
2015 // Return value is in st(0) on ia32.
2016 // Store it into the result register.
2017 __ sub(Operand(esp), Immediate(kDoubleSize));
2018 __ fstp_d(Operand(esp, 0));
2019 __ movsd(result, Operand(esp, 0));
2020 __ add(Operand(esp), Immediate(kDoubleSize));
2030 void LCodeGen::DoArithmeticT(LArithmeticT* instr) {
2031 DCHECK(ToRegister(instr->context()).is(esi));
2032 DCHECK(ToRegister(instr->left()).is(edx));
2033 DCHECK(ToRegister(instr->right()).is(eax));
2034 DCHECK(ToRegister(instr->result()).is(eax));
2037 CodeFactory::BinaryOpIC(isolate(), instr->op(), instr->strength()).code();
2038 CallCode(code, RelocInfo::CODE_TARGET, instr);
2042 template<class InstrType>
2043 void LCodeGen::EmitBranch(InstrType instr, Condition cc) {
2044 int left_block = instr->TrueDestination(chunk_);
2045 int right_block = instr->FalseDestination(chunk_);
2047 int next_block = GetNextEmittedBlock();
2049 if (right_block == left_block || cc == no_condition) {
2050 EmitGoto(left_block);
2051 } else if (left_block == next_block) {
2052 __ j(NegateCondition(cc), chunk_->GetAssemblyLabel(right_block));
2053 } else if (right_block == next_block) {
2054 __ j(cc, chunk_->GetAssemblyLabel(left_block));
2056 __ j(cc, chunk_->GetAssemblyLabel(left_block));
2057 __ jmp(chunk_->GetAssemblyLabel(right_block));
2062 template <class InstrType>
2063 void LCodeGen::EmitTrueBranch(InstrType instr, Condition cc) {
2064 int true_block = instr->TrueDestination(chunk_);
2065 if (cc == no_condition) {
2066 __ jmp(chunk_->GetAssemblyLabel(true_block));
2068 __ j(cc, chunk_->GetAssemblyLabel(true_block));
2073 template<class InstrType>
2074 void LCodeGen::EmitFalseBranch(InstrType instr, Condition cc) {
2075 int false_block = instr->FalseDestination(chunk_);
2076 if (cc == no_condition) {
2077 __ jmp(chunk_->GetAssemblyLabel(false_block));
2079 __ j(cc, chunk_->GetAssemblyLabel(false_block));
2084 void LCodeGen::DoBranch(LBranch* instr) {
2085 Representation r = instr->hydrogen()->value()->representation();
2086 if (r.IsSmiOrInteger32()) {
2087 Register reg = ToRegister(instr->value());
2088 __ test(reg, Operand(reg));
2089 EmitBranch(instr, not_zero);
2090 } else if (r.IsDouble()) {
2091 DCHECK(!info()->IsStub());
2092 XMMRegister reg = ToDoubleRegister(instr->value());
2093 XMMRegister xmm_scratch = double_scratch0();
2094 __ xorps(xmm_scratch, xmm_scratch);
2095 __ ucomisd(reg, xmm_scratch);
2096 EmitBranch(instr, not_equal);
2098 DCHECK(r.IsTagged());
2099 Register reg = ToRegister(instr->value());
2100 HType type = instr->hydrogen()->value()->type();
2101 if (type.IsBoolean()) {
2102 DCHECK(!info()->IsStub());
2103 __ cmp(reg, factory()->true_value());
2104 EmitBranch(instr, equal);
2105 } else if (type.IsSmi()) {
2106 DCHECK(!info()->IsStub());
2107 __ test(reg, Operand(reg));
2108 EmitBranch(instr, not_equal);
2109 } else if (type.IsJSArray()) {
2110 DCHECK(!info()->IsStub());
2111 EmitBranch(instr, no_condition);
2112 } else if (type.IsHeapNumber()) {
2113 DCHECK(!info()->IsStub());
2114 XMMRegister xmm_scratch = double_scratch0();
2115 __ xorps(xmm_scratch, xmm_scratch);
2116 __ ucomisd(xmm_scratch, FieldOperand(reg, HeapNumber::kValueOffset));
2117 EmitBranch(instr, not_equal);
2118 } else if (type.IsString()) {
2119 DCHECK(!info()->IsStub());
2120 __ cmp(FieldOperand(reg, String::kLengthOffset), Immediate(0));
2121 EmitBranch(instr, not_equal);
2123 ToBooleanStub::Types expected = instr->hydrogen()->expected_input_types();
2124 if (expected.IsEmpty()) expected = ToBooleanStub::Types::Generic();
2126 if (expected.Contains(ToBooleanStub::UNDEFINED)) {
2127 // undefined -> false.
2128 __ cmp(reg, factory()->undefined_value());
2129 __ j(equal, instr->FalseLabel(chunk_));
2131 if (expected.Contains(ToBooleanStub::BOOLEAN)) {
2133 __ cmp(reg, factory()->true_value());
2134 __ j(equal, instr->TrueLabel(chunk_));
2136 __ cmp(reg, factory()->false_value());
2137 __ j(equal, instr->FalseLabel(chunk_));
2139 if (expected.Contains(ToBooleanStub::NULL_TYPE)) {
2141 __ cmp(reg, factory()->null_value());
2142 __ j(equal, instr->FalseLabel(chunk_));
2145 if (expected.Contains(ToBooleanStub::SMI)) {
2146 // Smis: 0 -> false, all other -> true.
2147 __ test(reg, Operand(reg));
2148 __ j(equal, instr->FalseLabel(chunk_));
2149 __ JumpIfSmi(reg, instr->TrueLabel(chunk_));
2150 } else if (expected.NeedsMap()) {
2151 // If we need a map later and have a Smi -> deopt.
2152 __ test(reg, Immediate(kSmiTagMask));
2153 DeoptimizeIf(zero, instr, Deoptimizer::kSmi);
2156 Register map = no_reg; // Keep the compiler happy.
2157 if (expected.NeedsMap()) {
2158 map = ToRegister(instr->temp());
2159 DCHECK(!map.is(reg));
2160 __ mov(map, FieldOperand(reg, HeapObject::kMapOffset));
2162 if (expected.CanBeUndetectable()) {
2163 // Undetectable -> false.
2164 __ test_b(FieldOperand(map, Map::kBitFieldOffset),
2165 1 << Map::kIsUndetectable);
2166 __ j(not_zero, instr->FalseLabel(chunk_));
2170 if (expected.Contains(ToBooleanStub::SPEC_OBJECT)) {
2171 // spec object -> true.
2172 __ CmpInstanceType(map, FIRST_SPEC_OBJECT_TYPE);
2173 __ j(above_equal, instr->TrueLabel(chunk_));
2176 if (expected.Contains(ToBooleanStub::STRING)) {
2177 // String value -> false iff empty.
2179 __ CmpInstanceType(map, FIRST_NONSTRING_TYPE);
2180 __ j(above_equal, ¬_string, Label::kNear);
2181 __ cmp(FieldOperand(reg, String::kLengthOffset), Immediate(0));
2182 __ j(not_zero, instr->TrueLabel(chunk_));
2183 __ jmp(instr->FalseLabel(chunk_));
2184 __ bind(¬_string);
2187 if (expected.Contains(ToBooleanStub::SYMBOL)) {
2188 // Symbol value -> true.
2189 __ CmpInstanceType(map, SYMBOL_TYPE);
2190 __ j(equal, instr->TrueLabel(chunk_));
2193 if (expected.Contains(ToBooleanStub::SIMD_VALUE)) {
2194 // SIMD value -> true.
2195 __ CmpInstanceType(map, SIMD128_VALUE_TYPE);
2196 __ j(equal, instr->TrueLabel(chunk_));
2199 if (expected.Contains(ToBooleanStub::HEAP_NUMBER)) {
2200 // heap number -> false iff +0, -0, or NaN.
2201 Label not_heap_number;
2202 __ cmp(FieldOperand(reg, HeapObject::kMapOffset),
2203 factory()->heap_number_map());
2204 __ j(not_equal, ¬_heap_number, Label::kNear);
2205 XMMRegister xmm_scratch = double_scratch0();
2206 __ xorps(xmm_scratch, xmm_scratch);
2207 __ ucomisd(xmm_scratch, FieldOperand(reg, HeapNumber::kValueOffset));
2208 __ j(zero, instr->FalseLabel(chunk_));
2209 __ jmp(instr->TrueLabel(chunk_));
2210 __ bind(¬_heap_number);
2213 if (!expected.IsGeneric()) {
2214 // We've seen something for the first time -> deopt.
2215 // This can only happen if we are not generic already.
2216 DeoptimizeIf(no_condition, instr, Deoptimizer::kUnexpectedObject);
2223 void LCodeGen::EmitGoto(int block) {
2224 if (!IsNextEmittedBlock(block)) {
2225 __ jmp(chunk_->GetAssemblyLabel(LookupDestination(block)));
2230 void LCodeGen::DoGoto(LGoto* instr) {
2231 EmitGoto(instr->block_id());
2235 Condition LCodeGen::TokenToCondition(Token::Value op, bool is_unsigned) {
2236 Condition cond = no_condition;
2239 case Token::EQ_STRICT:
2243 case Token::NE_STRICT:
2247 cond = is_unsigned ? below : less;
2250 cond = is_unsigned ? above : greater;
2253 cond = is_unsigned ? below_equal : less_equal;
2256 cond = is_unsigned ? above_equal : greater_equal;
2259 case Token::INSTANCEOF:
2267 void LCodeGen::DoCompareNumericAndBranch(LCompareNumericAndBranch* instr) {
2268 LOperand* left = instr->left();
2269 LOperand* right = instr->right();
2271 instr->is_double() ||
2272 instr->hydrogen()->left()->CheckFlag(HInstruction::kUint32) ||
2273 instr->hydrogen()->right()->CheckFlag(HInstruction::kUint32);
2274 Condition cc = TokenToCondition(instr->op(), is_unsigned);
2276 if (left->IsConstantOperand() && right->IsConstantOperand()) {
2277 // We can statically evaluate the comparison.
2278 double left_val = ToDouble(LConstantOperand::cast(left));
2279 double right_val = ToDouble(LConstantOperand::cast(right));
2280 int next_block = EvalComparison(instr->op(), left_val, right_val) ?
2281 instr->TrueDestination(chunk_) : instr->FalseDestination(chunk_);
2282 EmitGoto(next_block);
2284 if (instr->is_double()) {
2285 __ ucomisd(ToDoubleRegister(left), ToDoubleRegister(right));
2286 // Don't base result on EFLAGS when a NaN is involved. Instead
2287 // jump to the false block.
2288 __ j(parity_even, instr->FalseLabel(chunk_));
2290 if (right->IsConstantOperand()) {
2291 __ cmp(ToOperand(left),
2292 ToImmediate(right, instr->hydrogen()->representation()));
2293 } else if (left->IsConstantOperand()) {
2294 __ cmp(ToOperand(right),
2295 ToImmediate(left, instr->hydrogen()->representation()));
2296 // We commuted the operands, so commute the condition.
2297 cc = CommuteCondition(cc);
2299 __ cmp(ToRegister(left), ToOperand(right));
2302 EmitBranch(instr, cc);
2307 void LCodeGen::DoCmpObjectEqAndBranch(LCmpObjectEqAndBranch* instr) {
2308 Register left = ToRegister(instr->left());
2310 if (instr->right()->IsConstantOperand()) {
2311 Handle<Object> right = ToHandle(LConstantOperand::cast(instr->right()));
2312 __ CmpObject(left, right);
2314 Operand right = ToOperand(instr->right());
2315 __ cmp(left, right);
2317 EmitBranch(instr, equal);
2321 void LCodeGen::DoCmpHoleAndBranch(LCmpHoleAndBranch* instr) {
2322 if (instr->hydrogen()->representation().IsTagged()) {
2323 Register input_reg = ToRegister(instr->object());
2324 __ cmp(input_reg, factory()->the_hole_value());
2325 EmitBranch(instr, equal);
2329 XMMRegister input_reg = ToDoubleRegister(instr->object());
2330 __ ucomisd(input_reg, input_reg);
2331 EmitFalseBranch(instr, parity_odd);
2333 __ sub(esp, Immediate(kDoubleSize));
2334 __ movsd(MemOperand(esp, 0), input_reg);
2336 __ add(esp, Immediate(kDoubleSize));
2337 int offset = sizeof(kHoleNanUpper32);
2338 __ cmp(MemOperand(esp, -offset), Immediate(kHoleNanUpper32));
2339 EmitBranch(instr, equal);
2343 void LCodeGen::DoCompareMinusZeroAndBranch(LCompareMinusZeroAndBranch* instr) {
2344 Representation rep = instr->hydrogen()->value()->representation();
2345 DCHECK(!rep.IsInteger32());
2346 Register scratch = ToRegister(instr->temp());
2348 if (rep.IsDouble()) {
2349 XMMRegister value = ToDoubleRegister(instr->value());
2350 XMMRegister xmm_scratch = double_scratch0();
2351 __ xorps(xmm_scratch, xmm_scratch);
2352 __ ucomisd(xmm_scratch, value);
2353 EmitFalseBranch(instr, not_equal);
2354 __ movmskpd(scratch, value);
2355 __ test(scratch, Immediate(1));
2356 EmitBranch(instr, not_zero);
2358 Register value = ToRegister(instr->value());
2359 Handle<Map> map = masm()->isolate()->factory()->heap_number_map();
2360 __ CheckMap(value, map, instr->FalseLabel(chunk()), DO_SMI_CHECK);
2361 __ cmp(FieldOperand(value, HeapNumber::kExponentOffset),
2363 EmitFalseBranch(instr, no_overflow);
2364 __ cmp(FieldOperand(value, HeapNumber::kMantissaOffset),
2365 Immediate(0x00000000));
2366 EmitBranch(instr, equal);
2371 Condition LCodeGen::EmitIsString(Register input,
2373 Label* is_not_string,
2374 SmiCheck check_needed = INLINE_SMI_CHECK) {
2375 if (check_needed == INLINE_SMI_CHECK) {
2376 __ JumpIfSmi(input, is_not_string);
2379 Condition cond = masm_->IsObjectStringType(input, temp1, temp1);
2385 void LCodeGen::DoIsStringAndBranch(LIsStringAndBranch* instr) {
2386 Register reg = ToRegister(instr->value());
2387 Register temp = ToRegister(instr->temp());
2389 SmiCheck check_needed =
2390 instr->hydrogen()->value()->type().IsHeapObject()
2391 ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
2393 Condition true_cond = EmitIsString(
2394 reg, temp, instr->FalseLabel(chunk_), check_needed);
2396 EmitBranch(instr, true_cond);
2400 void LCodeGen::DoIsSmiAndBranch(LIsSmiAndBranch* instr) {
2401 Operand input = ToOperand(instr->value());
2403 __ test(input, Immediate(kSmiTagMask));
2404 EmitBranch(instr, zero);
2408 void LCodeGen::DoIsUndetectableAndBranch(LIsUndetectableAndBranch* instr) {
2409 Register input = ToRegister(instr->value());
2410 Register temp = ToRegister(instr->temp());
2412 if (!instr->hydrogen()->value()->type().IsHeapObject()) {
2413 STATIC_ASSERT(kSmiTag == 0);
2414 __ JumpIfSmi(input, instr->FalseLabel(chunk_));
2416 __ mov(temp, FieldOperand(input, HeapObject::kMapOffset));
2417 __ test_b(FieldOperand(temp, Map::kBitFieldOffset),
2418 1 << Map::kIsUndetectable);
2419 EmitBranch(instr, not_zero);
2423 static Condition ComputeCompareCondition(Token::Value op) {
2425 case Token::EQ_STRICT:
2435 return greater_equal;
2438 return no_condition;
2443 void LCodeGen::DoStringCompareAndBranch(LStringCompareAndBranch* instr) {
2444 Token::Value op = instr->op();
2447 CodeFactory::CompareIC(isolate(), op, Strength::WEAK).code();
2448 CallCode(ic, RelocInfo::CODE_TARGET, instr);
2450 Condition condition = ComputeCompareCondition(op);
2451 __ test(eax, Operand(eax));
2453 EmitBranch(instr, condition);
2457 static InstanceType TestType(HHasInstanceTypeAndBranch* instr) {
2458 InstanceType from = instr->from();
2459 InstanceType to = instr->to();
2460 if (from == FIRST_TYPE) return to;
2461 DCHECK(from == to || to == LAST_TYPE);
2466 static Condition BranchCondition(HHasInstanceTypeAndBranch* instr) {
2467 InstanceType from = instr->from();
2468 InstanceType to = instr->to();
2469 if (from == to) return equal;
2470 if (to == LAST_TYPE) return above_equal;
2471 if (from == FIRST_TYPE) return below_equal;
2477 void LCodeGen::DoHasInstanceTypeAndBranch(LHasInstanceTypeAndBranch* instr) {
2478 Register input = ToRegister(instr->value());
2479 Register temp = ToRegister(instr->temp());
2481 if (!instr->hydrogen()->value()->type().IsHeapObject()) {
2482 __ JumpIfSmi(input, instr->FalseLabel(chunk_));
2485 __ CmpObjectType(input, TestType(instr->hydrogen()), temp);
2486 EmitBranch(instr, BranchCondition(instr->hydrogen()));
2490 void LCodeGen::DoGetCachedArrayIndex(LGetCachedArrayIndex* instr) {
2491 Register input = ToRegister(instr->value());
2492 Register result = ToRegister(instr->result());
2494 __ AssertString(input);
2496 __ mov(result, FieldOperand(input, String::kHashFieldOffset));
2497 __ IndexFromHash(result, result);
2501 void LCodeGen::DoHasCachedArrayIndexAndBranch(
2502 LHasCachedArrayIndexAndBranch* instr) {
2503 Register input = ToRegister(instr->value());
2505 __ test(FieldOperand(input, String::kHashFieldOffset),
2506 Immediate(String::kContainsCachedArrayIndexMask));
2507 EmitBranch(instr, equal);
2511 // Branches to a label or falls through with the answer in the z flag. Trashes
2512 // the temp registers, but not the input.
2513 void LCodeGen::EmitClassOfTest(Label* is_true,
2515 Handle<String>class_name,
2519 DCHECK(!input.is(temp));
2520 DCHECK(!input.is(temp2));
2521 DCHECK(!temp.is(temp2));
2522 __ JumpIfSmi(input, is_false);
2524 if (String::Equals(isolate()->factory()->Function_string(), class_name)) {
2525 // Assuming the following assertions, we can use the same compares to test
2526 // for both being a function type and being in the object type range.
2527 STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
2528 STATIC_ASSERT(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE ==
2529 FIRST_SPEC_OBJECT_TYPE + 1);
2530 STATIC_ASSERT(LAST_NONCALLABLE_SPEC_OBJECT_TYPE ==
2531 LAST_SPEC_OBJECT_TYPE - 1);
2532 STATIC_ASSERT(LAST_SPEC_OBJECT_TYPE == LAST_TYPE);
2533 __ CmpObjectType(input, FIRST_SPEC_OBJECT_TYPE, temp);
2534 __ j(below, is_false);
2535 __ j(equal, is_true);
2536 __ CmpInstanceType(temp, LAST_SPEC_OBJECT_TYPE);
2537 __ j(equal, is_true);
2539 // Faster code path to avoid two compares: subtract lower bound from the
2540 // actual type and do a signed compare with the width of the type range.
2541 __ mov(temp, FieldOperand(input, HeapObject::kMapOffset));
2542 __ movzx_b(temp2, FieldOperand(temp, Map::kInstanceTypeOffset));
2543 __ sub(Operand(temp2), Immediate(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE));
2544 __ cmp(Operand(temp2), Immediate(LAST_NONCALLABLE_SPEC_OBJECT_TYPE -
2545 FIRST_NONCALLABLE_SPEC_OBJECT_TYPE));
2546 __ j(above, is_false);
2549 // Now we are in the FIRST-LAST_NONCALLABLE_SPEC_OBJECT_TYPE range.
2550 // Check if the constructor in the map is a function.
2551 __ GetMapConstructor(temp, temp, temp2);
2552 // Objects with a non-function constructor have class 'Object'.
2553 __ CmpInstanceType(temp2, JS_FUNCTION_TYPE);
2554 if (String::Equals(class_name, isolate()->factory()->Object_string())) {
2555 __ j(not_equal, is_true);
2557 __ j(not_equal, is_false);
2560 // temp now contains the constructor function. Grab the
2561 // instance class name from there.
2562 __ mov(temp, FieldOperand(temp, JSFunction::kSharedFunctionInfoOffset));
2563 __ mov(temp, FieldOperand(temp,
2564 SharedFunctionInfo::kInstanceClassNameOffset));
2565 // The class name we are testing against is internalized since it's a literal.
2566 // The name in the constructor is internalized because of the way the context
2567 // is booted. This routine isn't expected to work for random API-created
2568 // classes and it doesn't have to because you can't access it with natives
2569 // syntax. Since both sides are internalized it is sufficient to use an
2570 // identity comparison.
2571 __ cmp(temp, class_name);
2572 // End with the answer in the z flag.
2576 void LCodeGen::DoClassOfTestAndBranch(LClassOfTestAndBranch* instr) {
2577 Register input = ToRegister(instr->value());
2578 Register temp = ToRegister(instr->temp());
2579 Register temp2 = ToRegister(instr->temp2());
2581 Handle<String> class_name = instr->hydrogen()->class_name();
2583 EmitClassOfTest(instr->TrueLabel(chunk_), instr->FalseLabel(chunk_),
2584 class_name, input, temp, temp2);
2586 EmitBranch(instr, equal);
2590 void LCodeGen::DoCmpMapAndBranch(LCmpMapAndBranch* instr) {
2591 Register reg = ToRegister(instr->value());
2592 __ cmp(FieldOperand(reg, HeapObject::kMapOffset), instr->map());
2593 EmitBranch(instr, equal);
2597 void LCodeGen::DoInstanceOf(LInstanceOf* instr) {
2598 DCHECK(ToRegister(instr->context()).is(esi));
2599 DCHECK(ToRegister(instr->left()).is(InstanceOfDescriptor::LeftRegister()));
2600 DCHECK(ToRegister(instr->right()).is(InstanceOfDescriptor::RightRegister()));
2601 DCHECK(ToRegister(instr->result()).is(eax));
2602 InstanceOfStub stub(isolate());
2603 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
2607 void LCodeGen::DoHasInPrototypeChainAndBranch(
2608 LHasInPrototypeChainAndBranch* instr) {
2609 Register const object = ToRegister(instr->object());
2610 Register const object_map = ToRegister(instr->scratch());
2611 Register const object_prototype = object_map;
2612 Register const prototype = ToRegister(instr->prototype());
2614 // The {object} must be a spec object. It's sufficient to know that {object}
2615 // is not a smi, since all other non-spec objects have {null} prototypes and
2616 // will be ruled out below.
2617 if (instr->hydrogen()->ObjectNeedsSmiCheck()) {
2618 __ test(object, Immediate(kSmiTagMask));
2619 EmitFalseBranch(instr, zero);
2622 // Loop through the {object}s prototype chain looking for the {prototype}.
2623 __ mov(object_map, FieldOperand(object, HeapObject::kMapOffset));
2626 __ mov(object_prototype, FieldOperand(object_map, Map::kPrototypeOffset));
2627 __ cmp(object_prototype, prototype);
2628 EmitTrueBranch(instr, equal);
2629 __ cmp(object_prototype, factory()->null_value());
2630 EmitFalseBranch(instr, equal);
2631 __ mov(object_map, FieldOperand(object_prototype, HeapObject::kMapOffset));
2636 void LCodeGen::DoCmpT(LCmpT* instr) {
2637 Token::Value op = instr->op();
2640 CodeFactory::CompareIC(isolate(), op, instr->strength()).code();
2641 CallCode(ic, RelocInfo::CODE_TARGET, instr);
2643 Condition condition = ComputeCompareCondition(op);
2644 Label true_value, done;
2645 __ test(eax, Operand(eax));
2646 __ j(condition, &true_value, Label::kNear);
2647 __ mov(ToRegister(instr->result()), factory()->false_value());
2648 __ jmp(&done, Label::kNear);
2649 __ bind(&true_value);
2650 __ mov(ToRegister(instr->result()), factory()->true_value());
2655 void LCodeGen::EmitReturn(LReturn* instr, bool dynamic_frame_alignment) {
2656 int extra_value_count = dynamic_frame_alignment ? 2 : 1;
2658 if (instr->has_constant_parameter_count()) {
2659 int parameter_count = ToInteger32(instr->constant_parameter_count());
2660 if (dynamic_frame_alignment && FLAG_debug_code) {
2662 (parameter_count + extra_value_count) * kPointerSize),
2663 Immediate(kAlignmentZapValue));
2664 __ Assert(equal, kExpectedAlignmentMarker);
2666 __ Ret((parameter_count + extra_value_count) * kPointerSize, ecx);
2668 DCHECK(info()->IsStub()); // Functions would need to drop one more value.
2669 Register reg = ToRegister(instr->parameter_count());
2670 // The argument count parameter is a smi
2672 Register return_addr_reg = reg.is(ecx) ? ebx : ecx;
2673 if (dynamic_frame_alignment && FLAG_debug_code) {
2674 DCHECK(extra_value_count == 2);
2675 __ cmp(Operand(esp, reg, times_pointer_size,
2676 extra_value_count * kPointerSize),
2677 Immediate(kAlignmentZapValue));
2678 __ Assert(equal, kExpectedAlignmentMarker);
2681 // emit code to restore stack based on instr->parameter_count()
2682 __ pop(return_addr_reg); // save return address
2683 if (dynamic_frame_alignment) {
2684 __ inc(reg); // 1 more for alignment
2687 __ shl(reg, kPointerSizeLog2);
2689 __ jmp(return_addr_reg);
2694 void LCodeGen::DoReturn(LReturn* instr) {
2695 if (FLAG_trace && info()->IsOptimizing()) {
2696 // Preserve the return value on the stack and rely on the runtime call
2697 // to return the value in the same register. We're leaving the code
2698 // managed by the register allocator and tearing down the frame, it's
2699 // safe to write to the context register.
2701 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
2702 __ CallRuntime(Runtime::kTraceExit, 1);
2704 if (info()->saves_caller_doubles()) RestoreCallerDoubles();
2705 if (dynamic_frame_alignment_) {
2706 // Fetch the state of the dynamic frame alignment.
2707 __ mov(edx, Operand(ebp,
2708 JavaScriptFrameConstants::kDynamicAlignmentStateOffset));
2710 int no_frame_start = -1;
2711 if (NeedsEagerFrame()) {
2714 no_frame_start = masm_->pc_offset();
2716 if (dynamic_frame_alignment_) {
2718 __ cmp(edx, Immediate(kNoAlignmentPadding));
2719 __ j(equal, &no_padding, Label::kNear);
2721 EmitReturn(instr, true);
2722 __ bind(&no_padding);
2725 EmitReturn(instr, false);
2726 if (no_frame_start != -1) {
2727 info()->AddNoFrameRange(no_frame_start, masm_->pc_offset());
2733 void LCodeGen::EmitVectorLoadICRegisters(T* instr) {
2734 Register vector_register = ToRegister(instr->temp_vector());
2735 Register slot_register = LoadWithVectorDescriptor::SlotRegister();
2736 DCHECK(vector_register.is(LoadWithVectorDescriptor::VectorRegister()));
2737 DCHECK(slot_register.is(eax));
2739 AllowDeferredHandleDereference vector_structure_check;
2740 Handle<TypeFeedbackVector> vector = instr->hydrogen()->feedback_vector();
2741 __ mov(vector_register, vector);
2742 // No need to allocate this register.
2743 FeedbackVectorICSlot slot = instr->hydrogen()->slot();
2744 int index = vector->GetIndex(slot);
2745 __ mov(slot_register, Immediate(Smi::FromInt(index)));
2750 void LCodeGen::EmitVectorStoreICRegisters(T* instr) {
2751 Register vector_register = ToRegister(instr->temp_vector());
2752 Register slot_register = ToRegister(instr->temp_slot());
2754 AllowDeferredHandleDereference vector_structure_check;
2755 Handle<TypeFeedbackVector> vector = instr->hydrogen()->feedback_vector();
2756 __ mov(vector_register, vector);
2757 FeedbackVectorICSlot slot = instr->hydrogen()->slot();
2758 int index = vector->GetIndex(slot);
2759 __ mov(slot_register, Immediate(Smi::FromInt(index)));
2763 void LCodeGen::DoLoadGlobalGeneric(LLoadGlobalGeneric* instr) {
2764 DCHECK(ToRegister(instr->context()).is(esi));
2765 DCHECK(ToRegister(instr->global_object())
2766 .is(LoadDescriptor::ReceiverRegister()));
2767 DCHECK(ToRegister(instr->result()).is(eax));
2769 __ mov(LoadDescriptor::NameRegister(), instr->name());
2770 EmitVectorLoadICRegisters<LLoadGlobalGeneric>(instr);
2772 CodeFactory::LoadICInOptimizedCode(isolate(), instr->typeof_mode(),
2773 SLOPPY, PREMONOMORPHIC).code();
2774 CallCode(ic, RelocInfo::CODE_TARGET, instr);
2778 void LCodeGen::DoLoadGlobalViaContext(LLoadGlobalViaContext* instr) {
2779 DCHECK(ToRegister(instr->context()).is(esi));
2780 DCHECK(ToRegister(instr->result()).is(eax));
2782 int const slot = instr->slot_index();
2783 int const depth = instr->depth();
2784 if (depth <= LoadGlobalViaContextStub::kMaximumDepth) {
2785 __ mov(LoadGlobalViaContextDescriptor::SlotRegister(), Immediate(slot));
2787 CodeFactory::LoadGlobalViaContext(isolate(), depth).code();
2788 CallCode(stub, RelocInfo::CODE_TARGET, instr);
2790 __ Push(Smi::FromInt(slot));
2791 __ CallRuntime(Runtime::kLoadGlobalViaContext, 1);
2796 void LCodeGen::DoLoadContextSlot(LLoadContextSlot* instr) {
2797 Register context = ToRegister(instr->context());
2798 Register result = ToRegister(instr->result());
2799 __ mov(result, ContextOperand(context, instr->slot_index()));
2801 if (instr->hydrogen()->RequiresHoleCheck()) {
2802 __ cmp(result, factory()->the_hole_value());
2803 if (instr->hydrogen()->DeoptimizesOnHole()) {
2804 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
2807 __ j(not_equal, &is_not_hole, Label::kNear);
2808 __ mov(result, factory()->undefined_value());
2809 __ bind(&is_not_hole);
2815 void LCodeGen::DoStoreContextSlot(LStoreContextSlot* instr) {
2816 Register context = ToRegister(instr->context());
2817 Register value = ToRegister(instr->value());
2819 Label skip_assignment;
2821 Operand target = ContextOperand(context, instr->slot_index());
2822 if (instr->hydrogen()->RequiresHoleCheck()) {
2823 __ cmp(target, factory()->the_hole_value());
2824 if (instr->hydrogen()->DeoptimizesOnHole()) {
2825 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
2827 __ j(not_equal, &skip_assignment, Label::kNear);
2831 __ mov(target, value);
2832 if (instr->hydrogen()->NeedsWriteBarrier()) {
2833 SmiCheck check_needed =
2834 instr->hydrogen()->value()->type().IsHeapObject()
2835 ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
2836 Register temp = ToRegister(instr->temp());
2837 int offset = Context::SlotOffset(instr->slot_index());
2838 __ RecordWriteContextSlot(context,
2843 EMIT_REMEMBERED_SET,
2847 __ bind(&skip_assignment);
2851 void LCodeGen::DoLoadNamedField(LLoadNamedField* instr) {
2852 HObjectAccess access = instr->hydrogen()->access();
2853 int offset = access.offset();
2855 if (access.IsExternalMemory()) {
2856 Register result = ToRegister(instr->result());
2857 MemOperand operand = instr->object()->IsConstantOperand()
2858 ? MemOperand::StaticVariable(ToExternalReference(
2859 LConstantOperand::cast(instr->object())))
2860 : MemOperand(ToRegister(instr->object()), offset);
2861 __ Load(result, operand, access.representation());
2865 Register object = ToRegister(instr->object());
2866 if (instr->hydrogen()->representation().IsDouble()) {
2867 XMMRegister result = ToDoubleRegister(instr->result());
2868 __ movsd(result, FieldOperand(object, offset));
2872 Register result = ToRegister(instr->result());
2873 if (!access.IsInobject()) {
2874 __ mov(result, FieldOperand(object, JSObject::kPropertiesOffset));
2877 __ Load(result, FieldOperand(object, offset), access.representation());
2881 void LCodeGen::EmitPushTaggedOperand(LOperand* operand) {
2882 DCHECK(!operand->IsDoubleRegister());
2883 if (operand->IsConstantOperand()) {
2884 Handle<Object> object = ToHandle(LConstantOperand::cast(operand));
2885 AllowDeferredHandleDereference smi_check;
2886 if (object->IsSmi()) {
2887 __ Push(Handle<Smi>::cast(object));
2889 __ PushHeapObject(Handle<HeapObject>::cast(object));
2891 } else if (operand->IsRegister()) {
2892 __ push(ToRegister(operand));
2894 __ push(ToOperand(operand));
2899 void LCodeGen::DoLoadNamedGeneric(LLoadNamedGeneric* instr) {
2900 DCHECK(ToRegister(instr->context()).is(esi));
2901 DCHECK(ToRegister(instr->object()).is(LoadDescriptor::ReceiverRegister()));
2902 DCHECK(ToRegister(instr->result()).is(eax));
2904 __ mov(LoadDescriptor::NameRegister(), instr->name());
2905 EmitVectorLoadICRegisters<LLoadNamedGeneric>(instr);
2907 CodeFactory::LoadICInOptimizedCode(
2908 isolate(), NOT_INSIDE_TYPEOF, instr->hydrogen()->language_mode(),
2909 instr->hydrogen()->initialization_state()).code();
2910 CallCode(ic, RelocInfo::CODE_TARGET, instr);
2914 void LCodeGen::DoLoadFunctionPrototype(LLoadFunctionPrototype* instr) {
2915 Register function = ToRegister(instr->function());
2916 Register temp = ToRegister(instr->temp());
2917 Register result = ToRegister(instr->result());
2919 // Get the prototype or initial map from the function.
2921 FieldOperand(function, JSFunction::kPrototypeOrInitialMapOffset));
2923 // Check that the function has a prototype or an initial map.
2924 __ cmp(Operand(result), Immediate(factory()->the_hole_value()));
2925 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
2927 // If the function does not have an initial map, we're done.
2929 __ CmpObjectType(result, MAP_TYPE, temp);
2930 __ j(not_equal, &done, Label::kNear);
2932 // Get the prototype from the initial map.
2933 __ mov(result, FieldOperand(result, Map::kPrototypeOffset));
2940 void LCodeGen::DoLoadRoot(LLoadRoot* instr) {
2941 Register result = ToRegister(instr->result());
2942 __ LoadRoot(result, instr->index());
2946 void LCodeGen::DoAccessArgumentsAt(LAccessArgumentsAt* instr) {
2947 Register arguments = ToRegister(instr->arguments());
2948 Register result = ToRegister(instr->result());
2949 if (instr->length()->IsConstantOperand() &&
2950 instr->index()->IsConstantOperand()) {
2951 int const_index = ToInteger32(LConstantOperand::cast(instr->index()));
2952 int const_length = ToInteger32(LConstantOperand::cast(instr->length()));
2953 int index = (const_length - const_index) + 1;
2954 __ mov(result, Operand(arguments, index * kPointerSize));
2956 Register length = ToRegister(instr->length());
2957 Operand index = ToOperand(instr->index());
2958 // There are two words between the frame pointer and the last argument.
2959 // Subtracting from length accounts for one of them add one more.
2960 __ sub(length, index);
2961 __ mov(result, Operand(arguments, length, times_4, kPointerSize));
2966 void LCodeGen::DoLoadKeyedExternalArray(LLoadKeyed* instr) {
2967 ElementsKind elements_kind = instr->elements_kind();
2968 LOperand* key = instr->key();
2969 if (!key->IsConstantOperand() &&
2970 ExternalArrayOpRequiresTemp(instr->hydrogen()->key()->representation(),
2972 __ SmiUntag(ToRegister(key));
2974 Operand operand(BuildFastArrayOperand(
2977 instr->hydrogen()->key()->representation(),
2979 instr->base_offset()));
2980 if (elements_kind == FLOAT32_ELEMENTS) {
2981 XMMRegister result(ToDoubleRegister(instr->result()));
2982 __ movss(result, operand);
2983 __ cvtss2sd(result, result);
2984 } else if (elements_kind == FLOAT64_ELEMENTS) {
2985 __ movsd(ToDoubleRegister(instr->result()), operand);
2987 Register result(ToRegister(instr->result()));
2988 switch (elements_kind) {
2990 __ movsx_b(result, operand);
2992 case UINT8_ELEMENTS:
2993 case UINT8_CLAMPED_ELEMENTS:
2994 __ movzx_b(result, operand);
2996 case INT16_ELEMENTS:
2997 __ movsx_w(result, operand);
2999 case UINT16_ELEMENTS:
3000 __ movzx_w(result, operand);
3002 case INT32_ELEMENTS:
3003 __ mov(result, operand);
3005 case UINT32_ELEMENTS:
3006 __ mov(result, operand);
3007 if (!instr->hydrogen()->CheckFlag(HInstruction::kUint32)) {
3008 __ test(result, Operand(result));
3009 DeoptimizeIf(negative, instr, Deoptimizer::kNegativeValue);
3012 case FLOAT32_ELEMENTS:
3013 case FLOAT64_ELEMENTS:
3014 case FAST_SMI_ELEMENTS:
3016 case FAST_DOUBLE_ELEMENTS:
3017 case FAST_HOLEY_SMI_ELEMENTS:
3018 case FAST_HOLEY_ELEMENTS:
3019 case FAST_HOLEY_DOUBLE_ELEMENTS:
3020 case DICTIONARY_ELEMENTS:
3021 case FAST_SLOPPY_ARGUMENTS_ELEMENTS:
3022 case SLOW_SLOPPY_ARGUMENTS_ELEMENTS:
3030 void LCodeGen::DoLoadKeyedFixedDoubleArray(LLoadKeyed* instr) {
3031 if (instr->hydrogen()->RequiresHoleCheck()) {
3032 Operand hole_check_operand = BuildFastArrayOperand(
3033 instr->elements(), instr->key(),
3034 instr->hydrogen()->key()->representation(),
3035 FAST_DOUBLE_ELEMENTS,
3036 instr->base_offset() + sizeof(kHoleNanLower32));
3037 __ cmp(hole_check_operand, Immediate(kHoleNanUpper32));
3038 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3041 Operand double_load_operand = BuildFastArrayOperand(
3044 instr->hydrogen()->key()->representation(),
3045 FAST_DOUBLE_ELEMENTS,
3046 instr->base_offset());
3047 XMMRegister result = ToDoubleRegister(instr->result());
3048 __ movsd(result, double_load_operand);
3052 void LCodeGen::DoLoadKeyedFixedArray(LLoadKeyed* instr) {
3053 Register result = ToRegister(instr->result());
3057 BuildFastArrayOperand(instr->elements(), instr->key(),
3058 instr->hydrogen()->key()->representation(),
3059 FAST_ELEMENTS, instr->base_offset()));
3061 // Check for the hole value.
3062 if (instr->hydrogen()->RequiresHoleCheck()) {
3063 if (IsFastSmiElementsKind(instr->hydrogen()->elements_kind())) {
3064 __ test(result, Immediate(kSmiTagMask));
3065 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotASmi);
3067 __ cmp(result, factory()->the_hole_value());
3068 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3070 } else if (instr->hydrogen()->hole_mode() == CONVERT_HOLE_TO_UNDEFINED) {
3071 DCHECK(instr->hydrogen()->elements_kind() == FAST_HOLEY_ELEMENTS);
3073 __ cmp(result, factory()->the_hole_value());
3074 __ j(not_equal, &done);
3075 if (info()->IsStub()) {
3076 // A stub can safely convert the hole to undefined only if the array
3077 // protector cell contains (Smi) Isolate::kArrayProtectorValid. Otherwise
3078 // it needs to bail out.
3079 __ mov(result, isolate()->factory()->array_protector());
3080 __ cmp(FieldOperand(result, PropertyCell::kValueOffset),
3081 Immediate(Smi::FromInt(Isolate::kArrayProtectorValid)));
3082 DeoptimizeIf(not_equal, instr, Deoptimizer::kHole);
3084 __ mov(result, isolate()->factory()->undefined_value());
3090 void LCodeGen::DoLoadKeyed(LLoadKeyed* instr) {
3091 if (instr->is_fixed_typed_array()) {
3092 DoLoadKeyedExternalArray(instr);
3093 } else if (instr->hydrogen()->representation().IsDouble()) {
3094 DoLoadKeyedFixedDoubleArray(instr);
3096 DoLoadKeyedFixedArray(instr);
3101 Operand LCodeGen::BuildFastArrayOperand(
3102 LOperand* elements_pointer,
3104 Representation key_representation,
3105 ElementsKind elements_kind,
3106 uint32_t base_offset) {
3107 Register elements_pointer_reg = ToRegister(elements_pointer);
3108 int element_shift_size = ElementsKindToShiftSize(elements_kind);
3109 int shift_size = element_shift_size;
3110 if (key->IsConstantOperand()) {
3111 int constant_value = ToInteger32(LConstantOperand::cast(key));
3112 if (constant_value & 0xF0000000) {
3113 Abort(kArrayIndexConstantValueTooBig);
3115 return Operand(elements_pointer_reg,
3116 ((constant_value) << shift_size)
3119 // Take the tag bit into account while computing the shift size.
3120 if (key_representation.IsSmi() && (shift_size >= 1)) {
3121 shift_size -= kSmiTagSize;
3123 ScaleFactor scale_factor = static_cast<ScaleFactor>(shift_size);
3124 return Operand(elements_pointer_reg,
3132 void LCodeGen::DoLoadKeyedGeneric(LLoadKeyedGeneric* instr) {
3133 DCHECK(ToRegister(instr->context()).is(esi));
3134 DCHECK(ToRegister(instr->object()).is(LoadDescriptor::ReceiverRegister()));
3135 DCHECK(ToRegister(instr->key()).is(LoadDescriptor::NameRegister()));
3137 if (instr->hydrogen()->HasVectorAndSlot()) {
3138 EmitVectorLoadICRegisters<LLoadKeyedGeneric>(instr);
3141 Handle<Code> ic = CodeFactory::KeyedLoadICInOptimizedCode(
3142 isolate(), instr->hydrogen()->language_mode(),
3143 instr->hydrogen()->initialization_state()).code();
3144 CallCode(ic, RelocInfo::CODE_TARGET, instr);
3148 void LCodeGen::DoArgumentsElements(LArgumentsElements* instr) {
3149 Register result = ToRegister(instr->result());
3151 if (instr->hydrogen()->from_inlined()) {
3152 __ lea(result, Operand(esp, -2 * kPointerSize));
3154 // Check for arguments adapter frame.
3155 Label done, adapted;
3156 __ mov(result, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3157 __ mov(result, Operand(result, StandardFrameConstants::kContextOffset));
3158 __ cmp(Operand(result),
3159 Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
3160 __ j(equal, &adapted, Label::kNear);
3162 // No arguments adaptor frame.
3163 __ mov(result, Operand(ebp));
3164 __ jmp(&done, Label::kNear);
3166 // Arguments adaptor frame present.
3168 __ mov(result, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3170 // Result is the frame pointer for the frame if not adapted and for the real
3171 // frame below the adaptor frame if adapted.
3177 void LCodeGen::DoArgumentsLength(LArgumentsLength* instr) {
3178 Operand elem = ToOperand(instr->elements());
3179 Register result = ToRegister(instr->result());
3183 // If no arguments adaptor frame the number of arguments is fixed.
3185 __ mov(result, Immediate(scope()->num_parameters()));
3186 __ j(equal, &done, Label::kNear);
3188 // Arguments adaptor frame present. Get argument length from there.
3189 __ mov(result, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3190 __ mov(result, Operand(result,
3191 ArgumentsAdaptorFrameConstants::kLengthOffset));
3192 __ SmiUntag(result);
3194 // Argument length is in result register.
3199 void LCodeGen::DoWrapReceiver(LWrapReceiver* instr) {
3200 Register receiver = ToRegister(instr->receiver());
3201 Register function = ToRegister(instr->function());
3203 // If the receiver is null or undefined, we have to pass the global
3204 // object as a receiver to normal functions. Values have to be
3205 // passed unchanged to builtins and strict-mode functions.
3206 Label receiver_ok, global_object;
3207 Label::Distance dist = DeoptEveryNTimes() ? Label::kFar : Label::kNear;
3208 Register scratch = ToRegister(instr->temp());
3210 if (!instr->hydrogen()->known_function()) {
3211 // Do not transform the receiver to object for strict mode
3214 FieldOperand(function, JSFunction::kSharedFunctionInfoOffset));
3215 __ test_b(FieldOperand(scratch, SharedFunctionInfo::kStrictModeByteOffset),
3216 1 << SharedFunctionInfo::kStrictModeBitWithinByte);
3217 __ j(not_equal, &receiver_ok, dist);
3219 // Do not transform the receiver to object for builtins.
3220 __ test_b(FieldOperand(scratch, SharedFunctionInfo::kNativeByteOffset),
3221 1 << SharedFunctionInfo::kNativeBitWithinByte);
3222 __ j(not_equal, &receiver_ok, dist);
3225 // Normal function. Replace undefined or null with global receiver.
3226 __ cmp(receiver, factory()->null_value());
3227 __ j(equal, &global_object, Label::kNear);
3228 __ cmp(receiver, factory()->undefined_value());
3229 __ j(equal, &global_object, Label::kNear);
3231 // The receiver should be a JS object.
3232 __ test(receiver, Immediate(kSmiTagMask));
3233 DeoptimizeIf(equal, instr, Deoptimizer::kSmi);
3234 __ CmpObjectType(receiver, FIRST_SPEC_OBJECT_TYPE, scratch);
3235 DeoptimizeIf(below, instr, Deoptimizer::kNotAJavaScriptObject);
3237 __ jmp(&receiver_ok, Label::kNear);
3238 __ bind(&global_object);
3239 __ mov(receiver, FieldOperand(function, JSFunction::kContextOffset));
3240 const int global_offset = Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX);
3241 __ mov(receiver, Operand(receiver, global_offset));
3242 const int proxy_offset = GlobalObject::kGlobalProxyOffset;
3243 __ mov(receiver, FieldOperand(receiver, proxy_offset));
3244 __ bind(&receiver_ok);
3248 void LCodeGen::DoApplyArguments(LApplyArguments* instr) {
3249 Register receiver = ToRegister(instr->receiver());
3250 Register function = ToRegister(instr->function());
3251 Register length = ToRegister(instr->length());
3252 Register elements = ToRegister(instr->elements());
3253 DCHECK(receiver.is(eax)); // Used for parameter count.
3254 DCHECK(function.is(edi)); // Required by InvokeFunction.
3255 DCHECK(ToRegister(instr->result()).is(eax));
3257 // Copy the arguments to this function possibly from the
3258 // adaptor frame below it.
3259 const uint32_t kArgumentsLimit = 1 * KB;
3260 __ cmp(length, kArgumentsLimit);
3261 DeoptimizeIf(above, instr, Deoptimizer::kTooManyArguments);
3264 __ mov(receiver, length);
3266 // Loop through the arguments pushing them onto the execution
3269 // length is a small non-negative integer, due to the test above.
3270 __ test(length, Operand(length));
3271 __ j(zero, &invoke, Label::kNear);
3273 __ push(Operand(elements, length, times_pointer_size, 1 * kPointerSize));
3275 __ j(not_zero, &loop);
3277 // Invoke the function.
3279 DCHECK(instr->HasPointerMap());
3280 LPointerMap* pointers = instr->pointer_map();
3281 SafepointGenerator safepoint_generator(
3282 this, pointers, Safepoint::kLazyDeopt);
3283 ParameterCount actual(eax);
3284 __ InvokeFunction(function, actual, CALL_FUNCTION, safepoint_generator);
3288 void LCodeGen::DoDebugBreak(LDebugBreak* instr) {
3293 void LCodeGen::DoPushArgument(LPushArgument* instr) {
3294 LOperand* argument = instr->value();
3295 EmitPushTaggedOperand(argument);
3299 void LCodeGen::DoDrop(LDrop* instr) {
3300 __ Drop(instr->count());
3304 void LCodeGen::DoThisFunction(LThisFunction* instr) {
3305 Register result = ToRegister(instr->result());
3306 __ mov(result, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
3310 void LCodeGen::DoContext(LContext* instr) {
3311 Register result = ToRegister(instr->result());
3312 if (info()->IsOptimizing()) {
3313 __ mov(result, Operand(ebp, StandardFrameConstants::kContextOffset));
3315 // If there is no frame, the context must be in esi.
3316 DCHECK(result.is(esi));
3321 void LCodeGen::DoDeclareGlobals(LDeclareGlobals* instr) {
3322 DCHECK(ToRegister(instr->context()).is(esi));
3323 __ push(Immediate(instr->hydrogen()->pairs()));
3324 __ push(Immediate(Smi::FromInt(instr->hydrogen()->flags())));
3325 CallRuntime(Runtime::kDeclareGlobals, 2, instr);
3329 void LCodeGen::CallKnownFunction(Handle<JSFunction> function,
3330 int formal_parameter_count, int arity,
3331 LInstruction* instr) {
3332 bool dont_adapt_arguments =
3333 formal_parameter_count == SharedFunctionInfo::kDontAdaptArgumentsSentinel;
3334 bool can_invoke_directly =
3335 dont_adapt_arguments || formal_parameter_count == arity;
3337 Register function_reg = edi;
3339 if (can_invoke_directly) {
3341 __ mov(esi, FieldOperand(function_reg, JSFunction::kContextOffset));
3343 // Always initialize eax to the number of actual arguments.
3346 // Invoke function directly.
3347 if (function.is_identical_to(info()->closure())) {
3350 __ call(FieldOperand(function_reg, JSFunction::kCodeEntryOffset));
3352 RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
3354 // We need to adapt arguments.
3355 LPointerMap* pointers = instr->pointer_map();
3356 SafepointGenerator generator(
3357 this, pointers, Safepoint::kLazyDeopt);
3358 ParameterCount count(arity);
3359 ParameterCount expected(formal_parameter_count);
3360 __ InvokeFunction(function_reg, expected, count, CALL_FUNCTION, generator);
3365 void LCodeGen::DoCallWithDescriptor(LCallWithDescriptor* instr) {
3366 DCHECK(ToRegister(instr->result()).is(eax));
3368 if (instr->hydrogen()->IsTailCall()) {
3369 if (NeedsEagerFrame()) __ leave();
3371 if (instr->target()->IsConstantOperand()) {
3372 LConstantOperand* target = LConstantOperand::cast(instr->target());
3373 Handle<Code> code = Handle<Code>::cast(ToHandle(target));
3374 __ jmp(code, RelocInfo::CODE_TARGET);
3376 DCHECK(instr->target()->IsRegister());
3377 Register target = ToRegister(instr->target());
3378 __ add(target, Immediate(Code::kHeaderSize - kHeapObjectTag));
3382 LPointerMap* pointers = instr->pointer_map();
3383 SafepointGenerator generator(this, pointers, Safepoint::kLazyDeopt);
3385 if (instr->target()->IsConstantOperand()) {
3386 LConstantOperand* target = LConstantOperand::cast(instr->target());
3387 Handle<Code> code = Handle<Code>::cast(ToHandle(target));
3388 generator.BeforeCall(__ CallSize(code, RelocInfo::CODE_TARGET));
3389 __ call(code, RelocInfo::CODE_TARGET);
3391 DCHECK(instr->target()->IsRegister());
3392 Register target = ToRegister(instr->target());
3393 generator.BeforeCall(__ CallSize(Operand(target)));
3394 __ add(target, Immediate(Code::kHeaderSize - kHeapObjectTag));
3397 generator.AfterCall();
3402 void LCodeGen::DoCallJSFunction(LCallJSFunction* instr) {
3403 DCHECK(ToRegister(instr->function()).is(edi));
3404 DCHECK(ToRegister(instr->result()).is(eax));
3406 __ mov(eax, instr->arity());
3409 __ mov(esi, FieldOperand(edi, JSFunction::kContextOffset));
3411 bool is_self_call = false;
3412 if (instr->hydrogen()->function()->IsConstant()) {
3413 HConstant* fun_const = HConstant::cast(instr->hydrogen()->function());
3414 Handle<JSFunction> jsfun =
3415 Handle<JSFunction>::cast(fun_const->handle(isolate()));
3416 is_self_call = jsfun.is_identical_to(info()->closure());
3422 __ call(FieldOperand(edi, JSFunction::kCodeEntryOffset));
3425 RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
3429 void LCodeGen::DoDeferredMathAbsTaggedHeapNumber(LMathAbs* instr) {
3430 Register input_reg = ToRegister(instr->value());
3431 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
3432 factory()->heap_number_map());
3433 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
3435 Label slow, allocated, done;
3436 Register tmp = input_reg.is(eax) ? ecx : eax;
3437 Register tmp2 = tmp.is(ecx) ? edx : input_reg.is(ecx) ? edx : ecx;
3439 // Preserve the value of all registers.
3440 PushSafepointRegistersScope scope(this);
3442 __ mov(tmp, FieldOperand(input_reg, HeapNumber::kExponentOffset));
3443 // Check the sign of the argument. If the argument is positive, just
3444 // return it. We do not need to patch the stack since |input| and
3445 // |result| are the same register and |input| will be restored
3446 // unchanged by popping safepoint registers.
3447 __ test(tmp, Immediate(HeapNumber::kSignMask));
3448 __ j(zero, &done, Label::kNear);
3450 __ AllocateHeapNumber(tmp, tmp2, no_reg, &slow);
3451 __ jmp(&allocated, Label::kNear);
3453 // Slow case: Call the runtime system to do the number allocation.
3455 CallRuntimeFromDeferred(Runtime::kAllocateHeapNumber, 0,
3456 instr, instr->context());
3457 // Set the pointer to the new heap number in tmp.
3458 if (!tmp.is(eax)) __ mov(tmp, eax);
3459 // Restore input_reg after call to runtime.
3460 __ LoadFromSafepointRegisterSlot(input_reg, input_reg);
3462 __ bind(&allocated);
3463 __ mov(tmp2, FieldOperand(input_reg, HeapNumber::kExponentOffset));
3464 __ and_(tmp2, ~HeapNumber::kSignMask);
3465 __ mov(FieldOperand(tmp, HeapNumber::kExponentOffset), tmp2);
3466 __ mov(tmp2, FieldOperand(input_reg, HeapNumber::kMantissaOffset));
3467 __ mov(FieldOperand(tmp, HeapNumber::kMantissaOffset), tmp2);
3468 __ StoreToSafepointRegisterSlot(input_reg, tmp);
3474 void LCodeGen::EmitIntegerMathAbs(LMathAbs* instr) {
3475 Register input_reg = ToRegister(instr->value());
3476 __ test(input_reg, Operand(input_reg));
3478 __ j(not_sign, &is_positive, Label::kNear);
3479 __ neg(input_reg); // Sets flags.
3480 DeoptimizeIf(negative, instr, Deoptimizer::kOverflow);
3481 __ bind(&is_positive);
3485 void LCodeGen::DoMathAbs(LMathAbs* instr) {
3486 // Class for deferred case.
3487 class DeferredMathAbsTaggedHeapNumber final : public LDeferredCode {
3489 DeferredMathAbsTaggedHeapNumber(LCodeGen* codegen,
3491 : LDeferredCode(codegen), instr_(instr) { }
3492 void Generate() override {
3493 codegen()->DoDeferredMathAbsTaggedHeapNumber(instr_);
3495 LInstruction* instr() override { return instr_; }
3501 DCHECK(instr->value()->Equals(instr->result()));
3502 Representation r = instr->hydrogen()->value()->representation();
3505 XMMRegister scratch = double_scratch0();
3506 XMMRegister input_reg = ToDoubleRegister(instr->value());
3507 __ xorps(scratch, scratch);
3508 __ subsd(scratch, input_reg);
3509 __ andps(input_reg, scratch);
3510 } else if (r.IsSmiOrInteger32()) {
3511 EmitIntegerMathAbs(instr);
3512 } else { // Tagged case.
3513 DeferredMathAbsTaggedHeapNumber* deferred =
3514 new(zone()) DeferredMathAbsTaggedHeapNumber(this, instr);
3515 Register input_reg = ToRegister(instr->value());
3517 __ JumpIfNotSmi(input_reg, deferred->entry());
3518 EmitIntegerMathAbs(instr);
3519 __ bind(deferred->exit());
3524 void LCodeGen::DoMathFloor(LMathFloor* instr) {
3525 XMMRegister xmm_scratch = double_scratch0();
3526 Register output_reg = ToRegister(instr->result());
3527 XMMRegister input_reg = ToDoubleRegister(instr->value());
3529 if (CpuFeatures::IsSupported(SSE4_1)) {
3530 CpuFeatureScope scope(masm(), SSE4_1);
3531 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3532 // Deoptimize on negative zero.
3534 __ xorps(xmm_scratch, xmm_scratch); // Zero the register.
3535 __ ucomisd(input_reg, xmm_scratch);
3536 __ j(not_equal, &non_zero, Label::kNear);
3537 __ movmskpd(output_reg, input_reg);
3538 __ test(output_reg, Immediate(1));
3539 DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
3542 __ roundsd(xmm_scratch, input_reg, kRoundDown);
3543 __ cvttsd2si(output_reg, Operand(xmm_scratch));
3544 // Overflow is signalled with minint.
3545 __ cmp(output_reg, 0x1);
3546 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
3548 Label negative_sign, done;
3549 // Deoptimize on unordered.
3550 __ xorps(xmm_scratch, xmm_scratch); // Zero the register.
3551 __ ucomisd(input_reg, xmm_scratch);
3552 DeoptimizeIf(parity_even, instr, Deoptimizer::kNaN);
3553 __ j(below, &negative_sign, Label::kNear);
3555 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3556 // Check for negative zero.
3557 Label positive_sign;
3558 __ j(above, &positive_sign, Label::kNear);
3559 __ movmskpd(output_reg, input_reg);
3560 __ test(output_reg, Immediate(1));
3561 DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
3562 __ Move(output_reg, Immediate(0));
3563 __ jmp(&done, Label::kNear);
3564 __ bind(&positive_sign);
3567 // Use truncating instruction (OK because input is positive).
3568 __ cvttsd2si(output_reg, Operand(input_reg));
3569 // Overflow is signalled with minint.
3570 __ cmp(output_reg, 0x1);
3571 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
3572 __ jmp(&done, Label::kNear);
3574 // Non-zero negative reaches here.
3575 __ bind(&negative_sign);
3576 // Truncate, then compare and compensate.
3577 __ cvttsd2si(output_reg, Operand(input_reg));
3578 __ Cvtsi2sd(xmm_scratch, output_reg);
3579 __ ucomisd(input_reg, xmm_scratch);
3580 __ j(equal, &done, Label::kNear);
3581 __ sub(output_reg, Immediate(1));
3582 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
3589 void LCodeGen::DoMathRound(LMathRound* instr) {
3590 Register output_reg = ToRegister(instr->result());
3591 XMMRegister input_reg = ToDoubleRegister(instr->value());
3592 XMMRegister xmm_scratch = double_scratch0();
3593 XMMRegister input_temp = ToDoubleRegister(instr->temp());
3594 ExternalReference one_half = ExternalReference::address_of_one_half();
3595 ExternalReference minus_one_half =
3596 ExternalReference::address_of_minus_one_half();
3598 Label done, round_to_zero, below_one_half, do_not_compensate;
3599 Label::Distance dist = DeoptEveryNTimes() ? Label::kFar : Label::kNear;
3601 __ movsd(xmm_scratch, Operand::StaticVariable(one_half));
3602 __ ucomisd(xmm_scratch, input_reg);
3603 __ j(above, &below_one_half, Label::kNear);
3605 // CVTTSD2SI rounds towards zero, since 0.5 <= x, we use floor(0.5 + x).
3606 __ addsd(xmm_scratch, input_reg);
3607 __ cvttsd2si(output_reg, Operand(xmm_scratch));
3608 // Overflow is signalled with minint.
3609 __ cmp(output_reg, 0x1);
3610 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
3611 __ jmp(&done, dist);
3613 __ bind(&below_one_half);
3614 __ movsd(xmm_scratch, Operand::StaticVariable(minus_one_half));
3615 __ ucomisd(xmm_scratch, input_reg);
3616 __ j(below_equal, &round_to_zero, Label::kNear);
3618 // CVTTSD2SI rounds towards zero, we use ceil(x - (-0.5)) and then
3619 // compare and compensate.
3620 __ movaps(input_temp, input_reg); // Do not alter input_reg.
3621 __ subsd(input_temp, xmm_scratch);
3622 __ cvttsd2si(output_reg, Operand(input_temp));
3623 // Catch minint due to overflow, and to prevent overflow when compensating.
3624 __ cmp(output_reg, 0x1);
3625 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
3627 __ Cvtsi2sd(xmm_scratch, output_reg);
3628 __ ucomisd(xmm_scratch, input_temp);
3629 __ j(equal, &done, dist);
3630 __ sub(output_reg, Immediate(1));
3631 // No overflow because we already ruled out minint.
3632 __ jmp(&done, dist);
3634 __ bind(&round_to_zero);
3635 // We return 0 for the input range [+0, 0.5[, or [-0.5, 0.5[ if
3636 // we can ignore the difference between a result of -0 and +0.
3637 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3638 // If the sign is positive, we return +0.
3639 __ movmskpd(output_reg, input_reg);
3640 __ test(output_reg, Immediate(1));
3641 DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
3643 __ Move(output_reg, Immediate(0));
3648 void LCodeGen::DoMathFround(LMathFround* instr) {
3649 XMMRegister input_reg = ToDoubleRegister(instr->value());
3650 XMMRegister output_reg = ToDoubleRegister(instr->result());
3651 __ cvtsd2ss(output_reg, input_reg);
3652 __ cvtss2sd(output_reg, output_reg);
3656 void LCodeGen::DoMathSqrt(LMathSqrt* instr) {
3657 Operand input = ToOperand(instr->value());
3658 XMMRegister output = ToDoubleRegister(instr->result());
3659 __ sqrtsd(output, input);
3663 void LCodeGen::DoMathPowHalf(LMathPowHalf* instr) {
3664 XMMRegister xmm_scratch = double_scratch0();
3665 XMMRegister input_reg = ToDoubleRegister(instr->value());
3666 Register scratch = ToRegister(instr->temp());
3667 DCHECK(ToDoubleRegister(instr->result()).is(input_reg));
3669 // Note that according to ECMA-262 15.8.2.13:
3670 // Math.pow(-Infinity, 0.5) == Infinity
3671 // Math.sqrt(-Infinity) == NaN
3673 // Check base for -Infinity. According to IEEE-754, single-precision
3674 // -Infinity has the highest 9 bits set and the lowest 23 bits cleared.
3675 __ mov(scratch, 0xFF800000);
3676 __ movd(xmm_scratch, scratch);
3677 __ cvtss2sd(xmm_scratch, xmm_scratch);
3678 __ ucomisd(input_reg, xmm_scratch);
3679 // Comparing -Infinity with NaN results in "unordered", which sets the
3680 // zero flag as if both were equal. However, it also sets the carry flag.
3681 __ j(not_equal, &sqrt, Label::kNear);
3682 __ j(carry, &sqrt, Label::kNear);
3683 // If input is -Infinity, return Infinity.
3684 __ xorps(input_reg, input_reg);
3685 __ subsd(input_reg, xmm_scratch);
3686 __ jmp(&done, Label::kNear);
3690 __ xorps(xmm_scratch, xmm_scratch);
3691 __ addsd(input_reg, xmm_scratch); // Convert -0 to +0.
3692 __ sqrtsd(input_reg, input_reg);
3697 void LCodeGen::DoPower(LPower* instr) {
3698 Representation exponent_type = instr->hydrogen()->right()->representation();
3699 // Having marked this as a call, we can use any registers.
3700 // Just make sure that the input/output registers are the expected ones.
3701 Register tagged_exponent = MathPowTaggedDescriptor::exponent();
3702 DCHECK(!instr->right()->IsDoubleRegister() ||
3703 ToDoubleRegister(instr->right()).is(xmm1));
3704 DCHECK(!instr->right()->IsRegister() ||
3705 ToRegister(instr->right()).is(tagged_exponent));
3706 DCHECK(ToDoubleRegister(instr->left()).is(xmm2));
3707 DCHECK(ToDoubleRegister(instr->result()).is(xmm3));
3709 if (exponent_type.IsSmi()) {
3710 MathPowStub stub(isolate(), MathPowStub::TAGGED);
3712 } else if (exponent_type.IsTagged()) {
3714 __ JumpIfSmi(tagged_exponent, &no_deopt);
3715 DCHECK(!ecx.is(tagged_exponent));
3716 __ CmpObjectType(tagged_exponent, HEAP_NUMBER_TYPE, ecx);
3717 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
3719 MathPowStub stub(isolate(), MathPowStub::TAGGED);
3721 } else if (exponent_type.IsInteger32()) {
3722 MathPowStub stub(isolate(), MathPowStub::INTEGER);
3725 DCHECK(exponent_type.IsDouble());
3726 MathPowStub stub(isolate(), MathPowStub::DOUBLE);
3732 void LCodeGen::DoMathLog(LMathLog* instr) {
3733 DCHECK(instr->value()->Equals(instr->result()));
3734 XMMRegister input_reg = ToDoubleRegister(instr->value());
3735 XMMRegister xmm_scratch = double_scratch0();
3736 Label positive, done, zero;
3737 __ xorps(xmm_scratch, xmm_scratch);
3738 __ ucomisd(input_reg, xmm_scratch);
3739 __ j(above, &positive, Label::kNear);
3740 __ j(not_carry, &zero, Label::kNear);
3741 __ pcmpeqd(input_reg, input_reg);
3742 __ jmp(&done, Label::kNear);
3744 ExternalReference ninf =
3745 ExternalReference::address_of_negative_infinity();
3746 __ movsd(input_reg, Operand::StaticVariable(ninf));
3747 __ jmp(&done, Label::kNear);
3750 __ sub(Operand(esp), Immediate(kDoubleSize));
3751 __ movsd(Operand(esp, 0), input_reg);
3752 __ fld_d(Operand(esp, 0));
3754 __ fstp_d(Operand(esp, 0));
3755 __ movsd(input_reg, Operand(esp, 0));
3756 __ add(Operand(esp), Immediate(kDoubleSize));
3761 void LCodeGen::DoMathClz32(LMathClz32* instr) {
3762 Register input = ToRegister(instr->value());
3763 Register result = ToRegister(instr->result());
3765 __ Lzcnt(result, input);
3769 void LCodeGen::DoMathExp(LMathExp* instr) {
3770 XMMRegister input = ToDoubleRegister(instr->value());
3771 XMMRegister result = ToDoubleRegister(instr->result());
3772 XMMRegister temp0 = double_scratch0();
3773 Register temp1 = ToRegister(instr->temp1());
3774 Register temp2 = ToRegister(instr->temp2());
3776 MathExpGenerator::EmitMathExp(masm(), input, result, temp0, temp1, temp2);
3780 void LCodeGen::DoInvokeFunction(LInvokeFunction* instr) {
3781 DCHECK(ToRegister(instr->context()).is(esi));
3782 DCHECK(ToRegister(instr->function()).is(edi));
3783 DCHECK(instr->HasPointerMap());
3785 Handle<JSFunction> known_function = instr->hydrogen()->known_function();
3786 if (known_function.is_null()) {
3787 LPointerMap* pointers = instr->pointer_map();
3788 SafepointGenerator generator(
3789 this, pointers, Safepoint::kLazyDeopt);
3790 ParameterCount count(instr->arity());
3791 __ InvokeFunction(edi, count, CALL_FUNCTION, generator);
3793 CallKnownFunction(known_function,
3794 instr->hydrogen()->formal_parameter_count(),
3795 instr->arity(), instr);
3800 void LCodeGen::DoCallFunction(LCallFunction* instr) {
3801 DCHECK(ToRegister(instr->context()).is(esi));
3802 DCHECK(ToRegister(instr->function()).is(edi));
3803 DCHECK(ToRegister(instr->result()).is(eax));
3805 int arity = instr->arity();
3806 CallFunctionFlags flags = instr->hydrogen()->function_flags();
3807 if (instr->hydrogen()->HasVectorAndSlot()) {
3808 Register slot_register = ToRegister(instr->temp_slot());
3809 Register vector_register = ToRegister(instr->temp_vector());
3810 DCHECK(slot_register.is(edx));
3811 DCHECK(vector_register.is(ebx));
3813 AllowDeferredHandleDereference vector_structure_check;
3814 Handle<TypeFeedbackVector> vector = instr->hydrogen()->feedback_vector();
3815 int index = vector->GetIndex(instr->hydrogen()->slot());
3817 __ mov(vector_register, vector);
3818 __ mov(slot_register, Immediate(Smi::FromInt(index)));
3820 CallICState::CallType call_type =
3821 (flags & CALL_AS_METHOD) ? CallICState::METHOD : CallICState::FUNCTION;
3824 CodeFactory::CallICInOptimizedCode(isolate(), arity, call_type).code();
3825 CallCode(ic, RelocInfo::CODE_TARGET, instr);
3827 CallFunctionStub stub(isolate(), arity, flags);
3828 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
3833 void LCodeGen::DoCallNew(LCallNew* instr) {
3834 DCHECK(ToRegister(instr->context()).is(esi));
3835 DCHECK(ToRegister(instr->constructor()).is(edi));
3836 DCHECK(ToRegister(instr->result()).is(eax));
3838 // No cell in ebx for construct type feedback in optimized code
3839 __ mov(ebx, isolate()->factory()->undefined_value());
3840 CallConstructStub stub(isolate(), NO_CALL_CONSTRUCTOR_FLAGS);
3841 __ Move(eax, Immediate(instr->arity()));
3842 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
3846 void LCodeGen::DoCallNewArray(LCallNewArray* instr) {
3847 DCHECK(ToRegister(instr->context()).is(esi));
3848 DCHECK(ToRegister(instr->constructor()).is(edi));
3849 DCHECK(ToRegister(instr->result()).is(eax));
3851 __ Move(eax, Immediate(instr->arity()));
3852 if (instr->arity() == 1) {
3853 // We only need the allocation site for the case we have a length argument.
3854 // The case may bail out to the runtime, which will determine the correct
3855 // elements kind with the site.
3856 __ mov(ebx, instr->hydrogen()->site());
3858 __ mov(ebx, isolate()->factory()->undefined_value());
3861 ElementsKind kind = instr->hydrogen()->elements_kind();
3862 AllocationSiteOverrideMode override_mode =
3863 (AllocationSite::GetMode(kind) == TRACK_ALLOCATION_SITE)
3864 ? DISABLE_ALLOCATION_SITES
3867 if (instr->arity() == 0) {
3868 ArrayNoArgumentConstructorStub stub(isolate(), kind, override_mode);
3869 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
3870 } else if (instr->arity() == 1) {
3872 if (IsFastPackedElementsKind(kind)) {
3874 // We might need a change here
3875 // look at the first argument
3876 __ mov(ecx, Operand(esp, 0));
3878 __ j(zero, &packed_case, Label::kNear);
3880 ElementsKind holey_kind = GetHoleyElementsKind(kind);
3881 ArraySingleArgumentConstructorStub stub(isolate(),
3884 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
3885 __ jmp(&done, Label::kNear);
3886 __ bind(&packed_case);
3889 ArraySingleArgumentConstructorStub stub(isolate(), kind, override_mode);
3890 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
3893 ArrayNArgumentsConstructorStub stub(isolate(), kind, override_mode);
3894 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
3899 void LCodeGen::DoCallRuntime(LCallRuntime* instr) {
3900 DCHECK(ToRegister(instr->context()).is(esi));
3901 CallRuntime(instr->function(), instr->arity(), instr, instr->save_doubles());
3905 void LCodeGen::DoStoreCodeEntry(LStoreCodeEntry* instr) {
3906 Register function = ToRegister(instr->function());
3907 Register code_object = ToRegister(instr->code_object());
3908 __ lea(code_object, FieldOperand(code_object, Code::kHeaderSize));
3909 __ mov(FieldOperand(function, JSFunction::kCodeEntryOffset), code_object);
3913 void LCodeGen::DoInnerAllocatedObject(LInnerAllocatedObject* instr) {
3914 Register result = ToRegister(instr->result());
3915 Register base = ToRegister(instr->base_object());
3916 if (instr->offset()->IsConstantOperand()) {
3917 LConstantOperand* offset = LConstantOperand::cast(instr->offset());
3918 __ lea(result, Operand(base, ToInteger32(offset)));
3920 Register offset = ToRegister(instr->offset());
3921 __ lea(result, Operand(base, offset, times_1, 0));
3926 void LCodeGen::DoStoreNamedField(LStoreNamedField* instr) {
3927 Representation representation = instr->hydrogen()->field_representation();
3929 HObjectAccess access = instr->hydrogen()->access();
3930 int offset = access.offset();
3932 if (access.IsExternalMemory()) {
3933 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
3934 MemOperand operand = instr->object()->IsConstantOperand()
3935 ? MemOperand::StaticVariable(
3936 ToExternalReference(LConstantOperand::cast(instr->object())))
3937 : MemOperand(ToRegister(instr->object()), offset);
3938 if (instr->value()->IsConstantOperand()) {
3939 LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
3940 __ mov(operand, Immediate(ToInteger32(operand_value)));
3942 Register value = ToRegister(instr->value());
3943 __ Store(value, operand, representation);
3948 Register object = ToRegister(instr->object());
3949 __ AssertNotSmi(object);
3951 DCHECK(!representation.IsSmi() ||
3952 !instr->value()->IsConstantOperand() ||
3953 IsSmi(LConstantOperand::cast(instr->value())));
3954 if (representation.IsDouble()) {
3955 DCHECK(access.IsInobject());
3956 DCHECK(!instr->hydrogen()->has_transition());
3957 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
3958 XMMRegister value = ToDoubleRegister(instr->value());
3959 __ movsd(FieldOperand(object, offset), value);
3963 if (instr->hydrogen()->has_transition()) {
3964 Handle<Map> transition = instr->hydrogen()->transition_map();
3965 AddDeprecationDependency(transition);
3966 __ mov(FieldOperand(object, HeapObject::kMapOffset), transition);
3967 if (instr->hydrogen()->NeedsWriteBarrierForMap()) {
3968 Register temp = ToRegister(instr->temp());
3969 Register temp_map = ToRegister(instr->temp_map());
3970 // Update the write barrier for the map field.
3971 __ RecordWriteForMap(object, transition, temp_map, temp, kSaveFPRegs);
3976 Register write_register = object;
3977 if (!access.IsInobject()) {
3978 write_register = ToRegister(instr->temp());
3979 __ mov(write_register, FieldOperand(object, JSObject::kPropertiesOffset));
3982 MemOperand operand = FieldOperand(write_register, offset);
3983 if (instr->value()->IsConstantOperand()) {
3984 LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
3985 if (operand_value->IsRegister()) {
3986 Register value = ToRegister(operand_value);
3987 __ Store(value, operand, representation);
3988 } else if (representation.IsInteger32() || representation.IsExternal()) {
3989 Immediate immediate = ToImmediate(operand_value, representation);
3990 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
3991 __ mov(operand, immediate);
3993 Handle<Object> handle_value = ToHandle(operand_value);
3994 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
3995 __ mov(operand, handle_value);
3998 Register value = ToRegister(instr->value());
3999 __ Store(value, operand, representation);
4002 if (instr->hydrogen()->NeedsWriteBarrier()) {
4003 Register value = ToRegister(instr->value());
4004 Register temp = access.IsInobject() ? ToRegister(instr->temp()) : object;
4005 // Update the write barrier for the object for in-object properties.
4006 __ RecordWriteField(write_register,
4011 EMIT_REMEMBERED_SET,
4012 instr->hydrogen()->SmiCheckForWriteBarrier(),
4013 instr->hydrogen()->PointersToHereCheckForValue());
4018 void LCodeGen::DoStoreNamedGeneric(LStoreNamedGeneric* instr) {
4019 DCHECK(ToRegister(instr->context()).is(esi));
4020 DCHECK(ToRegister(instr->object()).is(StoreDescriptor::ReceiverRegister()));
4021 DCHECK(ToRegister(instr->value()).is(StoreDescriptor::ValueRegister()));
4023 if (instr->hydrogen()->HasVectorAndSlot()) {
4024 EmitVectorStoreICRegisters<LStoreNamedGeneric>(instr);
4027 __ mov(StoreDescriptor::NameRegister(), instr->name());
4028 Handle<Code> ic = CodeFactory::StoreICInOptimizedCode(
4029 isolate(), instr->language_mode(),
4030 instr->hydrogen()->initialization_state()).code();
4031 CallCode(ic, RelocInfo::CODE_TARGET, instr);
4035 void LCodeGen::DoStoreGlobalViaContext(LStoreGlobalViaContext* instr) {
4036 DCHECK(ToRegister(instr->context()).is(esi));
4037 DCHECK(ToRegister(instr->value())
4038 .is(StoreGlobalViaContextDescriptor::ValueRegister()));
4040 int const slot = instr->slot_index();
4041 int const depth = instr->depth();
4042 if (depth <= StoreGlobalViaContextStub::kMaximumDepth) {
4043 __ mov(StoreGlobalViaContextDescriptor::SlotRegister(), Immediate(slot));
4044 Handle<Code> stub = CodeFactory::StoreGlobalViaContext(
4045 isolate(), depth, instr->language_mode())
4047 CallCode(stub, RelocInfo::CODE_TARGET, instr);
4049 __ Push(Smi::FromInt(slot));
4050 __ Push(StoreGlobalViaContextDescriptor::ValueRegister());
4051 __ CallRuntime(is_strict(instr->language_mode())
4052 ? Runtime::kStoreGlobalViaContext_Strict
4053 : Runtime::kStoreGlobalViaContext_Sloppy,
4059 void LCodeGen::DoBoundsCheck(LBoundsCheck* instr) {
4060 Condition cc = instr->hydrogen()->allow_equality() ? above : above_equal;
4061 if (instr->index()->IsConstantOperand()) {
4062 __ cmp(ToOperand(instr->length()),
4063 ToImmediate(LConstantOperand::cast(instr->index()),
4064 instr->hydrogen()->length()->representation()));
4065 cc = CommuteCondition(cc);
4066 } else if (instr->length()->IsConstantOperand()) {
4067 __ cmp(ToOperand(instr->index()),
4068 ToImmediate(LConstantOperand::cast(instr->length()),
4069 instr->hydrogen()->index()->representation()));
4071 __ cmp(ToRegister(instr->index()), ToOperand(instr->length()));
4073 if (FLAG_debug_code && instr->hydrogen()->skip_check()) {
4075 __ j(NegateCondition(cc), &done, Label::kNear);
4079 DeoptimizeIf(cc, instr, Deoptimizer::kOutOfBounds);
4084 void LCodeGen::DoStoreKeyedExternalArray(LStoreKeyed* instr) {
4085 ElementsKind elements_kind = instr->elements_kind();
4086 LOperand* key = instr->key();
4087 if (!key->IsConstantOperand() &&
4088 ExternalArrayOpRequiresTemp(instr->hydrogen()->key()->representation(),
4090 __ SmiUntag(ToRegister(key));
4092 Operand operand(BuildFastArrayOperand(
4095 instr->hydrogen()->key()->representation(),
4097 instr->base_offset()));
4098 if (elements_kind == FLOAT32_ELEMENTS) {
4099 XMMRegister xmm_scratch = double_scratch0();
4100 __ cvtsd2ss(xmm_scratch, ToDoubleRegister(instr->value()));
4101 __ movss(operand, xmm_scratch);
4102 } else if (elements_kind == FLOAT64_ELEMENTS) {
4103 __ movsd(operand, ToDoubleRegister(instr->value()));
4105 Register value = ToRegister(instr->value());
4106 switch (elements_kind) {
4107 case UINT8_ELEMENTS:
4109 case UINT8_CLAMPED_ELEMENTS:
4110 __ mov_b(operand, value);
4112 case UINT16_ELEMENTS:
4113 case INT16_ELEMENTS:
4114 __ mov_w(operand, value);
4116 case UINT32_ELEMENTS:
4117 case INT32_ELEMENTS:
4118 __ mov(operand, value);
4120 case FLOAT32_ELEMENTS:
4121 case FLOAT64_ELEMENTS:
4122 case FAST_SMI_ELEMENTS:
4124 case FAST_DOUBLE_ELEMENTS:
4125 case FAST_HOLEY_SMI_ELEMENTS:
4126 case FAST_HOLEY_ELEMENTS:
4127 case FAST_HOLEY_DOUBLE_ELEMENTS:
4128 case DICTIONARY_ELEMENTS:
4129 case FAST_SLOPPY_ARGUMENTS_ELEMENTS:
4130 case SLOW_SLOPPY_ARGUMENTS_ELEMENTS:
4138 void LCodeGen::DoStoreKeyedFixedDoubleArray(LStoreKeyed* instr) {
4139 Operand double_store_operand = BuildFastArrayOperand(
4142 instr->hydrogen()->key()->representation(),
4143 FAST_DOUBLE_ELEMENTS,
4144 instr->base_offset());
4146 XMMRegister value = ToDoubleRegister(instr->value());
4148 if (instr->NeedsCanonicalization()) {
4149 XMMRegister xmm_scratch = double_scratch0();
4150 // Turn potential sNaN value into qNaN.
4151 __ xorps(xmm_scratch, xmm_scratch);
4152 __ subsd(value, xmm_scratch);
4155 __ movsd(double_store_operand, value);
4159 void LCodeGen::DoStoreKeyedFixedArray(LStoreKeyed* instr) {
4160 Register elements = ToRegister(instr->elements());
4161 Register key = instr->key()->IsRegister() ? ToRegister(instr->key()) : no_reg;
4163 Operand operand = BuildFastArrayOperand(
4166 instr->hydrogen()->key()->representation(),
4168 instr->base_offset());
4169 if (instr->value()->IsRegister()) {
4170 __ mov(operand, ToRegister(instr->value()));
4172 LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
4173 if (IsSmi(operand_value)) {
4174 Immediate immediate = ToImmediate(operand_value, Representation::Smi());
4175 __ mov(operand, immediate);
4177 DCHECK(!IsInteger32(operand_value));
4178 Handle<Object> handle_value = ToHandle(operand_value);
4179 __ mov(operand, handle_value);
4183 if (instr->hydrogen()->NeedsWriteBarrier()) {
4184 DCHECK(instr->value()->IsRegister());
4185 Register value = ToRegister(instr->value());
4186 DCHECK(!instr->key()->IsConstantOperand());
4187 SmiCheck check_needed =
4188 instr->hydrogen()->value()->type().IsHeapObject()
4189 ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
4190 // Compute address of modified element and store it into key register.
4191 __ lea(key, operand);
4192 __ RecordWrite(elements,
4196 EMIT_REMEMBERED_SET,
4198 instr->hydrogen()->PointersToHereCheckForValue());
4203 void LCodeGen::DoStoreKeyed(LStoreKeyed* instr) {
4204 // By cases...external, fast-double, fast
4205 if (instr->is_fixed_typed_array()) {
4206 DoStoreKeyedExternalArray(instr);
4207 } else if (instr->hydrogen()->value()->representation().IsDouble()) {
4208 DoStoreKeyedFixedDoubleArray(instr);
4210 DoStoreKeyedFixedArray(instr);
4215 void LCodeGen::DoStoreKeyedGeneric(LStoreKeyedGeneric* instr) {
4216 DCHECK(ToRegister(instr->context()).is(esi));
4217 DCHECK(ToRegister(instr->object()).is(StoreDescriptor::ReceiverRegister()));
4218 DCHECK(ToRegister(instr->key()).is(StoreDescriptor::NameRegister()));
4219 DCHECK(ToRegister(instr->value()).is(StoreDescriptor::ValueRegister()));
4221 if (instr->hydrogen()->HasVectorAndSlot()) {
4222 EmitVectorStoreICRegisters<LStoreKeyedGeneric>(instr);
4225 Handle<Code> ic = CodeFactory::KeyedStoreICInOptimizedCode(
4226 isolate(), instr->language_mode(),
4227 instr->hydrogen()->initialization_state()).code();
4228 CallCode(ic, RelocInfo::CODE_TARGET, instr);
4232 void LCodeGen::DoTrapAllocationMemento(LTrapAllocationMemento* instr) {
4233 Register object = ToRegister(instr->object());
4234 Register temp = ToRegister(instr->temp());
4235 Label no_memento_found;
4236 __ TestJSArrayForAllocationMemento(object, temp, &no_memento_found);
4237 DeoptimizeIf(equal, instr, Deoptimizer::kMementoFound);
4238 __ bind(&no_memento_found);
4242 void LCodeGen::DoMaybeGrowElements(LMaybeGrowElements* instr) {
4243 class DeferredMaybeGrowElements final : public LDeferredCode {
4245 DeferredMaybeGrowElements(LCodeGen* codegen, LMaybeGrowElements* instr)
4246 : LDeferredCode(codegen), instr_(instr) {}
4247 void Generate() override { codegen()->DoDeferredMaybeGrowElements(instr_); }
4248 LInstruction* instr() override { return instr_; }
4251 LMaybeGrowElements* instr_;
4254 Register result = eax;
4255 DeferredMaybeGrowElements* deferred =
4256 new (zone()) DeferredMaybeGrowElements(this, instr);
4257 LOperand* key = instr->key();
4258 LOperand* current_capacity = instr->current_capacity();
4260 DCHECK(instr->hydrogen()->key()->representation().IsInteger32());
4261 DCHECK(instr->hydrogen()->current_capacity()->representation().IsInteger32());
4262 DCHECK(key->IsConstantOperand() || key->IsRegister());
4263 DCHECK(current_capacity->IsConstantOperand() ||
4264 current_capacity->IsRegister());
4266 if (key->IsConstantOperand() && current_capacity->IsConstantOperand()) {
4267 int32_t constant_key = ToInteger32(LConstantOperand::cast(key));
4268 int32_t constant_capacity =
4269 ToInteger32(LConstantOperand::cast(current_capacity));
4270 if (constant_key >= constant_capacity) {
4272 __ jmp(deferred->entry());
4274 } else if (key->IsConstantOperand()) {
4275 int32_t constant_key = ToInteger32(LConstantOperand::cast(key));
4276 __ cmp(ToOperand(current_capacity), Immediate(constant_key));
4277 __ j(less_equal, deferred->entry());
4278 } else if (current_capacity->IsConstantOperand()) {
4279 int32_t constant_capacity =
4280 ToInteger32(LConstantOperand::cast(current_capacity));
4281 __ cmp(ToRegister(key), Immediate(constant_capacity));
4282 __ j(greater_equal, deferred->entry());
4284 __ cmp(ToRegister(key), ToRegister(current_capacity));
4285 __ j(greater_equal, deferred->entry());
4288 __ mov(result, ToOperand(instr->elements()));
4289 __ bind(deferred->exit());
4293 void LCodeGen::DoDeferredMaybeGrowElements(LMaybeGrowElements* instr) {
4294 // TODO(3095996): Get rid of this. For now, we need to make the
4295 // result register contain a valid pointer because it is already
4296 // contained in the register pointer map.
4297 Register result = eax;
4298 __ Move(result, Immediate(0));
4300 // We have to call a stub.
4302 PushSafepointRegistersScope scope(this);
4303 if (instr->object()->IsRegister()) {
4304 __ Move(result, ToRegister(instr->object()));
4306 __ mov(result, ToOperand(instr->object()));
4309 LOperand* key = instr->key();
4310 if (key->IsConstantOperand()) {
4311 __ mov(ebx, ToImmediate(key, Representation::Smi()));
4313 __ Move(ebx, ToRegister(key));
4317 GrowArrayElementsStub stub(isolate(), instr->hydrogen()->is_js_array(),
4318 instr->hydrogen()->kind());
4320 RecordSafepointWithLazyDeopt(
4321 instr, RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
4322 __ StoreToSafepointRegisterSlot(result, result);
4325 // Deopt on smi, which means the elements array changed to dictionary mode.
4326 __ test(result, Immediate(kSmiTagMask));
4327 DeoptimizeIf(equal, instr, Deoptimizer::kSmi);
4331 void LCodeGen::DoTransitionElementsKind(LTransitionElementsKind* instr) {
4332 Register object_reg = ToRegister(instr->object());
4334 Handle<Map> from_map = instr->original_map();
4335 Handle<Map> to_map = instr->transitioned_map();
4336 ElementsKind from_kind = instr->from_kind();
4337 ElementsKind to_kind = instr->to_kind();
4339 Label not_applicable;
4340 bool is_simple_map_transition =
4341 IsSimpleMapChangeTransition(from_kind, to_kind);
4342 Label::Distance branch_distance =
4343 is_simple_map_transition ? Label::kNear : Label::kFar;
4344 __ cmp(FieldOperand(object_reg, HeapObject::kMapOffset), from_map);
4345 __ j(not_equal, ¬_applicable, branch_distance);
4346 if (is_simple_map_transition) {
4347 Register new_map_reg = ToRegister(instr->new_map_temp());
4348 __ mov(FieldOperand(object_reg, HeapObject::kMapOffset),
4351 DCHECK_NOT_NULL(instr->temp());
4352 __ RecordWriteForMap(object_reg, to_map, new_map_reg,
4353 ToRegister(instr->temp()),
4356 DCHECK(ToRegister(instr->context()).is(esi));
4357 DCHECK(object_reg.is(eax));
4358 PushSafepointRegistersScope scope(this);
4359 __ mov(ebx, to_map);
4360 bool is_js_array = from_map->instance_type() == JS_ARRAY_TYPE;
4361 TransitionElementsKindStub stub(isolate(), from_kind, to_kind, is_js_array);
4363 RecordSafepointWithLazyDeopt(instr,
4364 RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
4366 __ bind(¬_applicable);
4370 void LCodeGen::DoStringCharCodeAt(LStringCharCodeAt* instr) {
4371 class DeferredStringCharCodeAt final : public LDeferredCode {
4373 DeferredStringCharCodeAt(LCodeGen* codegen,
4374 LStringCharCodeAt* instr)
4375 : LDeferredCode(codegen), instr_(instr) { }
4376 void Generate() override { codegen()->DoDeferredStringCharCodeAt(instr_); }
4377 LInstruction* instr() override { return instr_; }
4380 LStringCharCodeAt* instr_;
4383 DeferredStringCharCodeAt* deferred =
4384 new(zone()) DeferredStringCharCodeAt(this, instr);
4386 StringCharLoadGenerator::Generate(masm(),
4388 ToRegister(instr->string()),
4389 ToRegister(instr->index()),
4390 ToRegister(instr->result()),
4392 __ bind(deferred->exit());
4396 void LCodeGen::DoDeferredStringCharCodeAt(LStringCharCodeAt* instr) {
4397 Register string = ToRegister(instr->string());
4398 Register result = ToRegister(instr->result());
4400 // TODO(3095996): Get rid of this. For now, we need to make the
4401 // result register contain a valid pointer because it is already
4402 // contained in the register pointer map.
4403 __ Move(result, Immediate(0));
4405 PushSafepointRegistersScope scope(this);
4407 // Push the index as a smi. This is safe because of the checks in
4408 // DoStringCharCodeAt above.
4409 STATIC_ASSERT(String::kMaxLength <= Smi::kMaxValue);
4410 if (instr->index()->IsConstantOperand()) {
4411 Immediate immediate = ToImmediate(LConstantOperand::cast(instr->index()),
4412 Representation::Smi());
4415 Register index = ToRegister(instr->index());
4419 CallRuntimeFromDeferred(Runtime::kStringCharCodeAtRT, 2,
4420 instr, instr->context());
4423 __ StoreToSafepointRegisterSlot(result, eax);
4427 void LCodeGen::DoStringCharFromCode(LStringCharFromCode* instr) {
4428 class DeferredStringCharFromCode final : public LDeferredCode {
4430 DeferredStringCharFromCode(LCodeGen* codegen,
4431 LStringCharFromCode* instr)
4432 : LDeferredCode(codegen), instr_(instr) { }
4433 void Generate() override {
4434 codegen()->DoDeferredStringCharFromCode(instr_);
4436 LInstruction* instr() override { return instr_; }
4439 LStringCharFromCode* instr_;
4442 DeferredStringCharFromCode* deferred =
4443 new(zone()) DeferredStringCharFromCode(this, instr);
4445 DCHECK(instr->hydrogen()->value()->representation().IsInteger32());
4446 Register char_code = ToRegister(instr->char_code());
4447 Register result = ToRegister(instr->result());
4448 DCHECK(!char_code.is(result));
4450 __ cmp(char_code, String::kMaxOneByteCharCode);
4451 __ j(above, deferred->entry());
4452 __ Move(result, Immediate(factory()->single_character_string_cache()));
4453 __ mov(result, FieldOperand(result,
4454 char_code, times_pointer_size,
4455 FixedArray::kHeaderSize));
4456 __ cmp(result, factory()->undefined_value());
4457 __ j(equal, deferred->entry());
4458 __ bind(deferred->exit());
4462 void LCodeGen::DoDeferredStringCharFromCode(LStringCharFromCode* instr) {
4463 Register char_code = ToRegister(instr->char_code());
4464 Register result = ToRegister(instr->result());
4466 // TODO(3095996): Get rid of this. For now, we need to make the
4467 // result register contain a valid pointer because it is already
4468 // contained in the register pointer map.
4469 __ Move(result, Immediate(0));
4471 PushSafepointRegistersScope scope(this);
4472 __ SmiTag(char_code);
4474 CallRuntimeFromDeferred(Runtime::kCharFromCode, 1, instr, instr->context());
4475 __ StoreToSafepointRegisterSlot(result, eax);
4479 void LCodeGen::DoStringAdd(LStringAdd* instr) {
4480 DCHECK(ToRegister(instr->context()).is(esi));
4481 DCHECK(ToRegister(instr->left()).is(edx));
4482 DCHECK(ToRegister(instr->right()).is(eax));
4483 StringAddStub stub(isolate(),
4484 instr->hydrogen()->flags(),
4485 instr->hydrogen()->pretenure_flag());
4486 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
4490 void LCodeGen::DoInteger32ToDouble(LInteger32ToDouble* instr) {
4491 LOperand* input = instr->value();
4492 LOperand* output = instr->result();
4493 DCHECK(input->IsRegister() || input->IsStackSlot());
4494 DCHECK(output->IsDoubleRegister());
4495 __ Cvtsi2sd(ToDoubleRegister(output), ToOperand(input));
4499 void LCodeGen::DoUint32ToDouble(LUint32ToDouble* instr) {
4500 LOperand* input = instr->value();
4501 LOperand* output = instr->result();
4502 __ LoadUint32(ToDoubleRegister(output), ToRegister(input));
4506 void LCodeGen::DoNumberTagI(LNumberTagI* instr) {
4507 class DeferredNumberTagI final : public LDeferredCode {
4509 DeferredNumberTagI(LCodeGen* codegen,
4511 : LDeferredCode(codegen), instr_(instr) { }
4512 void Generate() override {
4513 codegen()->DoDeferredNumberTagIU(
4514 instr_, instr_->value(), instr_->temp(), SIGNED_INT32);
4516 LInstruction* instr() override { return instr_; }
4519 LNumberTagI* instr_;
4522 LOperand* input = instr->value();
4523 DCHECK(input->IsRegister() && input->Equals(instr->result()));
4524 Register reg = ToRegister(input);
4526 DeferredNumberTagI* deferred =
4527 new(zone()) DeferredNumberTagI(this, instr);
4529 __ j(overflow, deferred->entry());
4530 __ bind(deferred->exit());
4534 void LCodeGen::DoNumberTagU(LNumberTagU* instr) {
4535 class DeferredNumberTagU final : public LDeferredCode {
4537 DeferredNumberTagU(LCodeGen* codegen, LNumberTagU* instr)
4538 : LDeferredCode(codegen), instr_(instr) { }
4539 void Generate() override {
4540 codegen()->DoDeferredNumberTagIU(
4541 instr_, instr_->value(), instr_->temp(), UNSIGNED_INT32);
4543 LInstruction* instr() override { return instr_; }
4546 LNumberTagU* instr_;
4549 LOperand* input = instr->value();
4550 DCHECK(input->IsRegister() && input->Equals(instr->result()));
4551 Register reg = ToRegister(input);
4553 DeferredNumberTagU* deferred =
4554 new(zone()) DeferredNumberTagU(this, instr);
4555 __ cmp(reg, Immediate(Smi::kMaxValue));
4556 __ j(above, deferred->entry());
4558 __ bind(deferred->exit());
4562 void LCodeGen::DoDeferredNumberTagIU(LInstruction* instr,
4565 IntegerSignedness signedness) {
4567 Register reg = ToRegister(value);
4568 Register tmp = ToRegister(temp);
4569 XMMRegister xmm_scratch = double_scratch0();
4571 if (signedness == SIGNED_INT32) {
4572 // There was overflow, so bits 30 and 31 of the original integer
4573 // disagree. Try to allocate a heap number in new space and store
4574 // the value in there. If that fails, call the runtime system.
4576 __ xor_(reg, 0x80000000);
4577 __ Cvtsi2sd(xmm_scratch, Operand(reg));
4579 __ LoadUint32(xmm_scratch, reg);
4582 if (FLAG_inline_new) {
4583 __ AllocateHeapNumber(reg, tmp, no_reg, &slow);
4584 __ jmp(&done, Label::kNear);
4587 // Slow case: Call the runtime system to do the number allocation.
4590 // TODO(3095996): Put a valid pointer value in the stack slot where the
4591 // result register is stored, as this register is in the pointer map, but
4592 // contains an integer value.
4593 __ Move(reg, Immediate(0));
4595 // Preserve the value of all registers.
4596 PushSafepointRegistersScope scope(this);
4598 // NumberTagI and NumberTagD use the context from the frame, rather than
4599 // the environment's HContext or HInlinedContext value.
4600 // They only call Runtime::kAllocateHeapNumber.
4601 // The corresponding HChange instructions are added in a phase that does
4602 // not have easy access to the local context.
4603 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4604 __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
4605 RecordSafepointWithRegisters(
4606 instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
4607 __ StoreToSafepointRegisterSlot(reg, eax);
4610 // Done. Put the value in xmm_scratch into the value of the allocated heap
4613 __ movsd(FieldOperand(reg, HeapNumber::kValueOffset), xmm_scratch);
4617 void LCodeGen::DoNumberTagD(LNumberTagD* instr) {
4618 class DeferredNumberTagD final : public LDeferredCode {
4620 DeferredNumberTagD(LCodeGen* codegen, LNumberTagD* instr)
4621 : LDeferredCode(codegen), instr_(instr) { }
4622 void Generate() override { codegen()->DoDeferredNumberTagD(instr_); }
4623 LInstruction* instr() override { return instr_; }
4626 LNumberTagD* instr_;
4629 Register reg = ToRegister(instr->result());
4631 DeferredNumberTagD* deferred =
4632 new(zone()) DeferredNumberTagD(this, instr);
4633 if (FLAG_inline_new) {
4634 Register tmp = ToRegister(instr->temp());
4635 __ AllocateHeapNumber(reg, tmp, no_reg, deferred->entry());
4637 __ jmp(deferred->entry());
4639 __ bind(deferred->exit());
4640 XMMRegister input_reg = ToDoubleRegister(instr->value());
4641 __ movsd(FieldOperand(reg, HeapNumber::kValueOffset), input_reg);
4645 void LCodeGen::DoDeferredNumberTagD(LNumberTagD* instr) {
4646 // TODO(3095996): Get rid of this. For now, we need to make the
4647 // result register contain a valid pointer because it is already
4648 // contained in the register pointer map.
4649 Register reg = ToRegister(instr->result());
4650 __ Move(reg, Immediate(0));
4652 PushSafepointRegistersScope scope(this);
4653 // NumberTagI and NumberTagD use the context from the frame, rather than
4654 // the environment's HContext or HInlinedContext value.
4655 // They only call Runtime::kAllocateHeapNumber.
4656 // The corresponding HChange instructions are added in a phase that does
4657 // not have easy access to the local context.
4658 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4659 __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
4660 RecordSafepointWithRegisters(
4661 instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
4662 __ StoreToSafepointRegisterSlot(reg, eax);
4666 void LCodeGen::DoSmiTag(LSmiTag* instr) {
4667 HChange* hchange = instr->hydrogen();
4668 Register input = ToRegister(instr->value());
4669 if (hchange->CheckFlag(HValue::kCanOverflow) &&
4670 hchange->value()->CheckFlag(HValue::kUint32)) {
4671 __ test(input, Immediate(0xc0000000));
4672 DeoptimizeIf(not_zero, instr, Deoptimizer::kOverflow);
4675 if (hchange->CheckFlag(HValue::kCanOverflow) &&
4676 !hchange->value()->CheckFlag(HValue::kUint32)) {
4677 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
4682 void LCodeGen::DoSmiUntag(LSmiUntag* instr) {
4683 LOperand* input = instr->value();
4684 Register result = ToRegister(input);
4685 DCHECK(input->IsRegister() && input->Equals(instr->result()));
4686 if (instr->needs_check()) {
4687 __ test(result, Immediate(kSmiTagMask));
4688 DeoptimizeIf(not_zero, instr, Deoptimizer::kNotASmi);
4690 __ AssertSmi(result);
4692 __ SmiUntag(result);
4696 void LCodeGen::EmitNumberUntagD(LNumberUntagD* instr, Register input_reg,
4697 Register temp_reg, XMMRegister result_reg,
4698 NumberUntagDMode mode) {
4699 bool can_convert_undefined_to_nan =
4700 instr->hydrogen()->can_convert_undefined_to_nan();
4701 bool deoptimize_on_minus_zero = instr->hydrogen()->deoptimize_on_minus_zero();
4703 Label convert, load_smi, done;
4705 if (mode == NUMBER_CANDIDATE_IS_ANY_TAGGED) {
4707 __ JumpIfSmi(input_reg, &load_smi, Label::kNear);
4709 // Heap number map check.
4710 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
4711 factory()->heap_number_map());
4712 if (can_convert_undefined_to_nan) {
4713 __ j(not_equal, &convert, Label::kNear);
4715 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
4718 // Heap number to XMM conversion.
4719 __ movsd(result_reg, FieldOperand(input_reg, HeapNumber::kValueOffset));
4721 if (deoptimize_on_minus_zero) {
4722 XMMRegister xmm_scratch = double_scratch0();
4723 __ xorps(xmm_scratch, xmm_scratch);
4724 __ ucomisd(result_reg, xmm_scratch);
4725 __ j(not_zero, &done, Label::kNear);
4726 __ movmskpd(temp_reg, result_reg);
4727 __ test_b(temp_reg, 1);
4728 DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
4730 __ jmp(&done, Label::kNear);
4732 if (can_convert_undefined_to_nan) {
4735 // Convert undefined to NaN.
4736 __ cmp(input_reg, factory()->undefined_value());
4737 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumberUndefined);
4739 __ pcmpeqd(result_reg, result_reg);
4740 __ jmp(&done, Label::kNear);
4743 DCHECK(mode == NUMBER_CANDIDATE_IS_SMI);
4747 // Smi to XMM conversion. Clobbering a temp is faster than re-tagging the
4748 // input register since we avoid dependencies.
4749 __ mov(temp_reg, input_reg);
4750 __ SmiUntag(temp_reg); // Untag smi before converting to float.
4751 __ Cvtsi2sd(result_reg, Operand(temp_reg));
4756 void LCodeGen::DoDeferredTaggedToI(LTaggedToI* instr, Label* done) {
4757 Register input_reg = ToRegister(instr->value());
4759 // The input was optimistically untagged; revert it.
4760 STATIC_ASSERT(kSmiTagSize == 1);
4761 __ lea(input_reg, Operand(input_reg, times_2, kHeapObjectTag));
4763 if (instr->truncating()) {
4764 Label no_heap_number, check_bools, check_false;
4766 // Heap number map check.
4767 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
4768 factory()->heap_number_map());
4769 __ j(not_equal, &no_heap_number, Label::kNear);
4770 __ TruncateHeapNumberToI(input_reg, input_reg);
4773 __ bind(&no_heap_number);
4774 // Check for Oddballs. Undefined/False is converted to zero and True to one
4775 // for truncating conversions.
4776 __ cmp(input_reg, factory()->undefined_value());
4777 __ j(not_equal, &check_bools, Label::kNear);
4778 __ Move(input_reg, Immediate(0));
4781 __ bind(&check_bools);
4782 __ cmp(input_reg, factory()->true_value());
4783 __ j(not_equal, &check_false, Label::kNear);
4784 __ Move(input_reg, Immediate(1));
4787 __ bind(&check_false);
4788 __ cmp(input_reg, factory()->false_value());
4789 DeoptimizeIf(not_equal, instr,
4790 Deoptimizer::kNotAHeapNumberUndefinedBoolean);
4791 __ Move(input_reg, Immediate(0));
4793 XMMRegister scratch = ToDoubleRegister(instr->temp());
4794 DCHECK(!scratch.is(xmm0));
4795 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
4796 isolate()->factory()->heap_number_map());
4797 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
4798 __ movsd(xmm0, FieldOperand(input_reg, HeapNumber::kValueOffset));
4799 __ cvttsd2si(input_reg, Operand(xmm0));
4800 __ Cvtsi2sd(scratch, Operand(input_reg));
4801 __ ucomisd(xmm0, scratch);
4802 DeoptimizeIf(not_equal, instr, Deoptimizer::kLostPrecision);
4803 DeoptimizeIf(parity_even, instr, Deoptimizer::kNaN);
4804 if (instr->hydrogen()->GetMinusZeroMode() == FAIL_ON_MINUS_ZERO) {
4805 __ test(input_reg, Operand(input_reg));
4806 __ j(not_zero, done);
4807 __ movmskpd(input_reg, xmm0);
4808 __ and_(input_reg, 1);
4809 DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
4815 void LCodeGen::DoTaggedToI(LTaggedToI* instr) {
4816 class DeferredTaggedToI final : public LDeferredCode {
4818 DeferredTaggedToI(LCodeGen* codegen, LTaggedToI* instr)
4819 : LDeferredCode(codegen), instr_(instr) { }
4820 void Generate() override { codegen()->DoDeferredTaggedToI(instr_, done()); }
4821 LInstruction* instr() override { return instr_; }
4827 LOperand* input = instr->value();
4828 DCHECK(input->IsRegister());
4829 Register input_reg = ToRegister(input);
4830 DCHECK(input_reg.is(ToRegister(instr->result())));
4832 if (instr->hydrogen()->value()->representation().IsSmi()) {
4833 __ SmiUntag(input_reg);
4835 DeferredTaggedToI* deferred =
4836 new(zone()) DeferredTaggedToI(this, instr);
4837 // Optimistically untag the input.
4838 // If the input is a HeapObject, SmiUntag will set the carry flag.
4839 STATIC_ASSERT(kSmiTagSize == 1 && kSmiTag == 0);
4840 __ SmiUntag(input_reg);
4841 // Branch to deferred code if the input was tagged.
4842 // The deferred code will take care of restoring the tag.
4843 __ j(carry, deferred->entry());
4844 __ bind(deferred->exit());
4849 void LCodeGen::DoNumberUntagD(LNumberUntagD* instr) {
4850 LOperand* input = instr->value();
4851 DCHECK(input->IsRegister());
4852 LOperand* temp = instr->temp();
4853 DCHECK(temp->IsRegister());
4854 LOperand* result = instr->result();
4855 DCHECK(result->IsDoubleRegister());
4857 Register input_reg = ToRegister(input);
4858 Register temp_reg = ToRegister(temp);
4860 HValue* value = instr->hydrogen()->value();
4861 NumberUntagDMode mode = value->representation().IsSmi()
4862 ? NUMBER_CANDIDATE_IS_SMI : NUMBER_CANDIDATE_IS_ANY_TAGGED;
4864 XMMRegister result_reg = ToDoubleRegister(result);
4865 EmitNumberUntagD(instr, input_reg, temp_reg, result_reg, mode);
4869 void LCodeGen::DoDoubleToI(LDoubleToI* instr) {
4870 LOperand* input = instr->value();
4871 DCHECK(input->IsDoubleRegister());
4872 LOperand* result = instr->result();
4873 DCHECK(result->IsRegister());
4874 Register result_reg = ToRegister(result);
4876 if (instr->truncating()) {
4877 XMMRegister input_reg = ToDoubleRegister(input);
4878 __ TruncateDoubleToI(result_reg, input_reg);
4880 Label lost_precision, is_nan, minus_zero, done;
4881 XMMRegister input_reg = ToDoubleRegister(input);
4882 XMMRegister xmm_scratch = double_scratch0();
4883 Label::Distance dist = DeoptEveryNTimes() ? Label::kFar : Label::kNear;
4884 __ DoubleToI(result_reg, input_reg, xmm_scratch,
4885 instr->hydrogen()->GetMinusZeroMode(), &lost_precision,
4886 &is_nan, &minus_zero, dist);
4887 __ jmp(&done, dist);
4888 __ bind(&lost_precision);
4889 DeoptimizeIf(no_condition, instr, Deoptimizer::kLostPrecision);
4891 DeoptimizeIf(no_condition, instr, Deoptimizer::kNaN);
4892 __ bind(&minus_zero);
4893 DeoptimizeIf(no_condition, instr, Deoptimizer::kMinusZero);
4899 void LCodeGen::DoDoubleToSmi(LDoubleToSmi* instr) {
4900 LOperand* input = instr->value();
4901 DCHECK(input->IsDoubleRegister());
4902 LOperand* result = instr->result();
4903 DCHECK(result->IsRegister());
4904 Register result_reg = ToRegister(result);
4906 Label lost_precision, is_nan, minus_zero, done;
4907 XMMRegister input_reg = ToDoubleRegister(input);
4908 XMMRegister xmm_scratch = double_scratch0();
4909 Label::Distance dist = DeoptEveryNTimes() ? Label::kFar : Label::kNear;
4910 __ DoubleToI(result_reg, input_reg, xmm_scratch,
4911 instr->hydrogen()->GetMinusZeroMode(), &lost_precision, &is_nan,
4913 __ jmp(&done, dist);
4914 __ bind(&lost_precision);
4915 DeoptimizeIf(no_condition, instr, Deoptimizer::kLostPrecision);
4917 DeoptimizeIf(no_condition, instr, Deoptimizer::kNaN);
4918 __ bind(&minus_zero);
4919 DeoptimizeIf(no_condition, instr, Deoptimizer::kMinusZero);
4921 __ SmiTag(result_reg);
4922 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
4926 void LCodeGen::DoCheckSmi(LCheckSmi* instr) {
4927 LOperand* input = instr->value();
4928 __ test(ToOperand(input), Immediate(kSmiTagMask));
4929 DeoptimizeIf(not_zero, instr, Deoptimizer::kNotASmi);
4933 void LCodeGen::DoCheckNonSmi(LCheckNonSmi* instr) {
4934 if (!instr->hydrogen()->value()->type().IsHeapObject()) {
4935 LOperand* input = instr->value();
4936 __ test(ToOperand(input), Immediate(kSmiTagMask));
4937 DeoptimizeIf(zero, instr, Deoptimizer::kSmi);
4942 void LCodeGen::DoCheckArrayBufferNotNeutered(
4943 LCheckArrayBufferNotNeutered* instr) {
4944 Register view = ToRegister(instr->view());
4945 Register scratch = ToRegister(instr->scratch());
4947 __ mov(scratch, FieldOperand(view, JSArrayBufferView::kBufferOffset));
4948 __ test_b(FieldOperand(scratch, JSArrayBuffer::kBitFieldOffset),
4949 1 << JSArrayBuffer::WasNeutered::kShift);
4950 DeoptimizeIf(not_zero, instr, Deoptimizer::kOutOfBounds);
4954 void LCodeGen::DoCheckInstanceType(LCheckInstanceType* instr) {
4955 Register input = ToRegister(instr->value());
4956 Register temp = ToRegister(instr->temp());
4958 __ mov(temp, FieldOperand(input, HeapObject::kMapOffset));
4960 if (instr->hydrogen()->is_interval_check()) {
4963 instr->hydrogen()->GetCheckInterval(&first, &last);
4965 __ cmpb(FieldOperand(temp, Map::kInstanceTypeOffset),
4966 static_cast<int8_t>(first));
4968 // If there is only one type in the interval check for equality.
4969 if (first == last) {
4970 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongInstanceType);
4972 DeoptimizeIf(below, instr, Deoptimizer::kWrongInstanceType);
4973 // Omit check for the last type.
4974 if (last != LAST_TYPE) {
4975 __ cmpb(FieldOperand(temp, Map::kInstanceTypeOffset),
4976 static_cast<int8_t>(last));
4977 DeoptimizeIf(above, instr, Deoptimizer::kWrongInstanceType);
4983 instr->hydrogen()->GetCheckMaskAndTag(&mask, &tag);
4985 if (base::bits::IsPowerOfTwo32(mask)) {
4986 DCHECK(tag == 0 || base::bits::IsPowerOfTwo32(tag));
4987 __ test_b(FieldOperand(temp, Map::kInstanceTypeOffset), mask);
4988 DeoptimizeIf(tag == 0 ? not_zero : zero, instr,
4989 Deoptimizer::kWrongInstanceType);
4991 __ movzx_b(temp, FieldOperand(temp, Map::kInstanceTypeOffset));
4992 __ and_(temp, mask);
4994 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongInstanceType);
5000 void LCodeGen::DoCheckValue(LCheckValue* instr) {
5001 Handle<HeapObject> object = instr->hydrogen()->object().handle();
5002 if (instr->hydrogen()->object_in_new_space()) {
5003 Register reg = ToRegister(instr->value());
5004 Handle<Cell> cell = isolate()->factory()->NewCell(object);
5005 __ cmp(reg, Operand::ForCell(cell));
5007 Operand operand = ToOperand(instr->value());
5008 __ cmp(operand, object);
5010 DeoptimizeIf(not_equal, instr, Deoptimizer::kValueMismatch);
5014 void LCodeGen::DoDeferredInstanceMigration(LCheckMaps* instr, Register object) {
5016 PushSafepointRegistersScope scope(this);
5019 __ CallRuntimeSaveDoubles(Runtime::kTryMigrateInstance);
5020 RecordSafepointWithRegisters(
5021 instr->pointer_map(), 1, Safepoint::kNoLazyDeopt);
5023 __ test(eax, Immediate(kSmiTagMask));
5025 DeoptimizeIf(zero, instr, Deoptimizer::kInstanceMigrationFailed);
5029 void LCodeGen::DoCheckMaps(LCheckMaps* instr) {
5030 class DeferredCheckMaps final : public LDeferredCode {
5032 DeferredCheckMaps(LCodeGen* codegen, LCheckMaps* instr, Register object)
5033 : LDeferredCode(codegen), instr_(instr), object_(object) {
5034 SetExit(check_maps());
5036 void Generate() override {
5037 codegen()->DoDeferredInstanceMigration(instr_, object_);
5039 Label* check_maps() { return &check_maps_; }
5040 LInstruction* instr() override { return instr_; }
5048 if (instr->hydrogen()->IsStabilityCheck()) {
5049 const UniqueSet<Map>* maps = instr->hydrogen()->maps();
5050 for (int i = 0; i < maps->size(); ++i) {
5051 AddStabilityDependency(maps->at(i).handle());
5056 LOperand* input = instr->value();
5057 DCHECK(input->IsRegister());
5058 Register reg = ToRegister(input);
5060 DeferredCheckMaps* deferred = NULL;
5061 if (instr->hydrogen()->HasMigrationTarget()) {
5062 deferred = new(zone()) DeferredCheckMaps(this, instr, reg);
5063 __ bind(deferred->check_maps());
5066 const UniqueSet<Map>* maps = instr->hydrogen()->maps();
5068 for (int i = 0; i < maps->size() - 1; i++) {
5069 Handle<Map> map = maps->at(i).handle();
5070 __ CompareMap(reg, map);
5071 __ j(equal, &success, Label::kNear);
5074 Handle<Map> map = maps->at(maps->size() - 1).handle();
5075 __ CompareMap(reg, map);
5076 if (instr->hydrogen()->HasMigrationTarget()) {
5077 __ j(not_equal, deferred->entry());
5079 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongMap);
5086 void LCodeGen::DoClampDToUint8(LClampDToUint8* instr) {
5087 XMMRegister value_reg = ToDoubleRegister(instr->unclamped());
5088 XMMRegister xmm_scratch = double_scratch0();
5089 Register result_reg = ToRegister(instr->result());
5090 __ ClampDoubleToUint8(value_reg, xmm_scratch, result_reg);
5094 void LCodeGen::DoClampIToUint8(LClampIToUint8* instr) {
5095 DCHECK(instr->unclamped()->Equals(instr->result()));
5096 Register value_reg = ToRegister(instr->result());
5097 __ ClampUint8(value_reg);
5101 void LCodeGen::DoClampTToUint8(LClampTToUint8* instr) {
5102 DCHECK(instr->unclamped()->Equals(instr->result()));
5103 Register input_reg = ToRegister(instr->unclamped());
5104 XMMRegister temp_xmm_reg = ToDoubleRegister(instr->temp_xmm());
5105 XMMRegister xmm_scratch = double_scratch0();
5106 Label is_smi, done, heap_number;
5108 __ JumpIfSmi(input_reg, &is_smi);
5110 // Check for heap number
5111 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
5112 factory()->heap_number_map());
5113 __ j(equal, &heap_number, Label::kNear);
5115 // Check for undefined. Undefined is converted to zero for clamping
5117 __ cmp(input_reg, factory()->undefined_value());
5118 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumberUndefined);
5119 __ mov(input_reg, 0);
5120 __ jmp(&done, Label::kNear);
5123 __ bind(&heap_number);
5124 __ movsd(xmm_scratch, FieldOperand(input_reg, HeapNumber::kValueOffset));
5125 __ ClampDoubleToUint8(xmm_scratch, temp_xmm_reg, input_reg);
5126 __ jmp(&done, Label::kNear);
5130 __ SmiUntag(input_reg);
5131 __ ClampUint8(input_reg);
5136 void LCodeGen::DoDoubleBits(LDoubleBits* instr) {
5137 XMMRegister value_reg = ToDoubleRegister(instr->value());
5138 Register result_reg = ToRegister(instr->result());
5139 if (instr->hydrogen()->bits() == HDoubleBits::HIGH) {
5140 if (CpuFeatures::IsSupported(SSE4_1)) {
5141 CpuFeatureScope scope2(masm(), SSE4_1);
5142 __ pextrd(result_reg, value_reg, 1);
5144 XMMRegister xmm_scratch = double_scratch0();
5145 __ pshufd(xmm_scratch, value_reg, 1);
5146 __ movd(result_reg, xmm_scratch);
5149 __ movd(result_reg, value_reg);
5154 void LCodeGen::DoConstructDouble(LConstructDouble* instr) {
5155 Register hi_reg = ToRegister(instr->hi());
5156 Register lo_reg = ToRegister(instr->lo());
5157 XMMRegister result_reg = ToDoubleRegister(instr->result());
5159 if (CpuFeatures::IsSupported(SSE4_1)) {
5160 CpuFeatureScope scope2(masm(), SSE4_1);
5161 __ movd(result_reg, lo_reg);
5162 __ pinsrd(result_reg, hi_reg, 1);
5164 XMMRegister xmm_scratch = double_scratch0();
5165 __ movd(result_reg, hi_reg);
5166 __ psllq(result_reg, 32);
5167 __ movd(xmm_scratch, lo_reg);
5168 __ orps(result_reg, xmm_scratch);
5173 void LCodeGen::DoAllocate(LAllocate* instr) {
5174 class DeferredAllocate final : public LDeferredCode {
5176 DeferredAllocate(LCodeGen* codegen, LAllocate* instr)
5177 : LDeferredCode(codegen), instr_(instr) { }
5178 void Generate() override { codegen()->DoDeferredAllocate(instr_); }
5179 LInstruction* instr() override { return instr_; }
5185 DeferredAllocate* deferred = new(zone()) DeferredAllocate(this, instr);
5187 Register result = ToRegister(instr->result());
5188 Register temp = ToRegister(instr->temp());
5190 // Allocate memory for the object.
5191 AllocationFlags flags = TAG_OBJECT;
5192 if (instr->hydrogen()->MustAllocateDoubleAligned()) {
5193 flags = static_cast<AllocationFlags>(flags | DOUBLE_ALIGNMENT);
5195 if (instr->hydrogen()->IsOldSpaceAllocation()) {
5196 DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
5197 flags = static_cast<AllocationFlags>(flags | PRETENURE);
5200 if (instr->size()->IsConstantOperand()) {
5201 int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
5202 if (size <= Page::kMaxRegularHeapObjectSize) {
5203 __ Allocate(size, result, temp, no_reg, deferred->entry(), flags);
5205 __ jmp(deferred->entry());
5208 Register size = ToRegister(instr->size());
5209 __ Allocate(size, result, temp, no_reg, deferred->entry(), flags);
5212 __ bind(deferred->exit());
5214 if (instr->hydrogen()->MustPrefillWithFiller()) {
5215 if (instr->size()->IsConstantOperand()) {
5216 int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
5217 __ mov(temp, (size / kPointerSize) - 1);
5219 temp = ToRegister(instr->size());
5220 __ shr(temp, kPointerSizeLog2);
5225 __ mov(FieldOperand(result, temp, times_pointer_size, 0),
5226 isolate()->factory()->one_pointer_filler_map());
5228 __ j(not_zero, &loop);
5233 void LCodeGen::DoDeferredAllocate(LAllocate* instr) {
5234 Register result = ToRegister(instr->result());
5236 // TODO(3095996): Get rid of this. For now, we need to make the
5237 // result register contain a valid pointer because it is already
5238 // contained in the register pointer map.
5239 __ Move(result, Immediate(Smi::FromInt(0)));
5241 PushSafepointRegistersScope scope(this);
5242 if (instr->size()->IsRegister()) {
5243 Register size = ToRegister(instr->size());
5244 DCHECK(!size.is(result));
5245 __ SmiTag(ToRegister(instr->size()));
5248 int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
5249 if (size >= 0 && size <= Smi::kMaxValue) {
5250 __ push(Immediate(Smi::FromInt(size)));
5252 // We should never get here at runtime => abort
5258 int flags = AllocateDoubleAlignFlag::encode(
5259 instr->hydrogen()->MustAllocateDoubleAligned());
5260 if (instr->hydrogen()->IsOldSpaceAllocation()) {
5261 DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
5262 flags = AllocateTargetSpace::update(flags, OLD_SPACE);
5264 flags = AllocateTargetSpace::update(flags, NEW_SPACE);
5266 __ push(Immediate(Smi::FromInt(flags)));
5268 CallRuntimeFromDeferred(
5269 Runtime::kAllocateInTargetSpace, 2, instr, instr->context());
5270 __ StoreToSafepointRegisterSlot(result, eax);
5274 void LCodeGen::DoToFastProperties(LToFastProperties* instr) {
5275 DCHECK(ToRegister(instr->value()).is(eax));
5277 CallRuntime(Runtime::kToFastProperties, 1, instr);
5281 void LCodeGen::DoRegExpLiteral(LRegExpLiteral* instr) {
5282 DCHECK(ToRegister(instr->context()).is(esi));
5284 // Registers will be used as follows:
5285 // ecx = literals array.
5286 // ebx = regexp literal.
5287 // eax = regexp literal clone.
5289 int literal_offset =
5290 FixedArray::OffsetOfElementAt(instr->hydrogen()->literal_index());
5291 __ LoadHeapObject(ecx, instr->hydrogen()->literals());
5292 __ mov(ebx, FieldOperand(ecx, literal_offset));
5293 __ cmp(ebx, factory()->undefined_value());
5294 __ j(not_equal, &materialized, Label::kNear);
5296 // Create regexp literal using runtime function
5297 // Result will be in eax.
5299 __ push(Immediate(Smi::FromInt(instr->hydrogen()->literal_index())));
5300 __ push(Immediate(instr->hydrogen()->pattern()));
5301 __ push(Immediate(instr->hydrogen()->flags()));
5302 CallRuntime(Runtime::kMaterializeRegExpLiteral, 4, instr);
5305 __ bind(&materialized);
5306 int size = JSRegExp::kSize + JSRegExp::kInObjectFieldCount * kPointerSize;
5307 Label allocated, runtime_allocate;
5308 __ Allocate(size, eax, ecx, edx, &runtime_allocate, TAG_OBJECT);
5309 __ jmp(&allocated, Label::kNear);
5311 __ bind(&runtime_allocate);
5313 __ push(Immediate(Smi::FromInt(size)));
5314 CallRuntime(Runtime::kAllocateInNewSpace, 1, instr);
5317 __ bind(&allocated);
5318 // Copy the content into the newly allocated memory.
5319 // (Unroll copy loop once for better throughput).
5320 for (int i = 0; i < size - kPointerSize; i += 2 * kPointerSize) {
5321 __ mov(edx, FieldOperand(ebx, i));
5322 __ mov(ecx, FieldOperand(ebx, i + kPointerSize));
5323 __ mov(FieldOperand(eax, i), edx);
5324 __ mov(FieldOperand(eax, i + kPointerSize), ecx);
5326 if ((size % (2 * kPointerSize)) != 0) {
5327 __ mov(edx, FieldOperand(ebx, size - kPointerSize));
5328 __ mov(FieldOperand(eax, size - kPointerSize), edx);
5333 void LCodeGen::DoTypeof(LTypeof* instr) {
5334 DCHECK(ToRegister(instr->context()).is(esi));
5335 DCHECK(ToRegister(instr->value()).is(ebx));
5337 Register value_register = ToRegister(instr->value());
5338 __ JumpIfNotSmi(value_register, &do_call);
5339 __ mov(eax, Immediate(isolate()->factory()->number_string()));
5342 TypeofStub stub(isolate());
5343 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
5348 void LCodeGen::DoTypeofIsAndBranch(LTypeofIsAndBranch* instr) {
5349 Register input = ToRegister(instr->value());
5350 Condition final_branch_condition = EmitTypeofIs(instr, input);
5351 if (final_branch_condition != no_condition) {
5352 EmitBranch(instr, final_branch_condition);
5357 Condition LCodeGen::EmitTypeofIs(LTypeofIsAndBranch* instr, Register input) {
5358 Label* true_label = instr->TrueLabel(chunk_);
5359 Label* false_label = instr->FalseLabel(chunk_);
5360 Handle<String> type_name = instr->type_literal();
5361 int left_block = instr->TrueDestination(chunk_);
5362 int right_block = instr->FalseDestination(chunk_);
5363 int next_block = GetNextEmittedBlock();
5365 Label::Distance true_distance = left_block == next_block ? Label::kNear
5367 Label::Distance false_distance = right_block == next_block ? Label::kNear
5369 Condition final_branch_condition = no_condition;
5370 if (String::Equals(type_name, factory()->number_string())) {
5371 __ JumpIfSmi(input, true_label, true_distance);
5372 __ cmp(FieldOperand(input, HeapObject::kMapOffset),
5373 factory()->heap_number_map());
5374 final_branch_condition = equal;
5376 } else if (String::Equals(type_name, factory()->string_string())) {
5377 __ JumpIfSmi(input, false_label, false_distance);
5378 __ CmpObjectType(input, FIRST_NONSTRING_TYPE, input);
5379 final_branch_condition = below;
5381 } else if (String::Equals(type_name, factory()->symbol_string())) {
5382 __ JumpIfSmi(input, false_label, false_distance);
5383 __ CmpObjectType(input, SYMBOL_TYPE, input);
5384 final_branch_condition = equal;
5386 } else if (String::Equals(type_name, factory()->boolean_string())) {
5387 __ cmp(input, factory()->true_value());
5388 __ j(equal, true_label, true_distance);
5389 __ cmp(input, factory()->false_value());
5390 final_branch_condition = equal;
5392 } else if (String::Equals(type_name, factory()->undefined_string())) {
5393 __ cmp(input, factory()->undefined_value());
5394 __ j(equal, true_label, true_distance);
5395 __ JumpIfSmi(input, false_label, false_distance);
5396 // Check for undetectable objects => true.
5397 __ mov(input, FieldOperand(input, HeapObject::kMapOffset));
5398 __ test_b(FieldOperand(input, Map::kBitFieldOffset),
5399 1 << Map::kIsUndetectable);
5400 final_branch_condition = not_zero;
5402 } else if (String::Equals(type_name, factory()->function_string())) {
5403 __ JumpIfSmi(input, false_label, false_distance);
5404 // Check for callable and not undetectable objects => true.
5405 __ mov(input, FieldOperand(input, HeapObject::kMapOffset));
5406 __ movzx_b(input, FieldOperand(input, Map::kBitFieldOffset));
5407 __ and_(input, (1 << Map::kIsCallable) | (1 << Map::kIsUndetectable));
5408 __ cmp(input, 1 << Map::kIsCallable);
5409 final_branch_condition = equal;
5411 } else if (String::Equals(type_name, factory()->object_string())) {
5412 __ JumpIfSmi(input, false_label, false_distance);
5413 __ cmp(input, factory()->null_value());
5414 __ j(equal, true_label, true_distance);
5415 STATIC_ASSERT(LAST_SPEC_OBJECT_TYPE == LAST_TYPE);
5416 __ CmpObjectType(input, FIRST_SPEC_OBJECT_TYPE, input);
5417 __ j(below, false_label, false_distance);
5418 // Check for callable or undetectable objects => false.
5419 __ test_b(FieldOperand(input, Map::kBitFieldOffset),
5420 (1 << Map::kIsCallable) | (1 << Map::kIsUndetectable));
5421 final_branch_condition = zero;
5424 #define SIMD128_TYPE(TYPE, Type, type, lane_count, lane_type) \
5425 } else if (String::Equals(type_name, factory()->type##_string())) { \
5426 __ JumpIfSmi(input, false_label, false_distance); \
5427 __ cmp(FieldOperand(input, HeapObject::kMapOffset), \
5428 factory()->type##_map()); \
5429 final_branch_condition = equal;
5430 SIMD128_TYPES(SIMD128_TYPE)
5435 __ jmp(false_label, false_distance);
5437 return final_branch_condition;
5441 void LCodeGen::DoIsConstructCallAndBranch(LIsConstructCallAndBranch* instr) {
5442 Register temp = ToRegister(instr->temp());
5444 EmitIsConstructCall(temp);
5445 EmitBranch(instr, equal);
5449 void LCodeGen::EmitIsConstructCall(Register temp) {
5450 // Get the frame pointer for the calling frame.
5451 __ mov(temp, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
5453 // Skip the arguments adaptor frame if it exists.
5454 Label check_frame_marker;
5455 __ cmp(Operand(temp, StandardFrameConstants::kContextOffset),
5456 Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
5457 __ j(not_equal, &check_frame_marker, Label::kNear);
5458 __ mov(temp, Operand(temp, StandardFrameConstants::kCallerFPOffset));
5460 // Check the marker in the calling frame.
5461 __ bind(&check_frame_marker);
5462 __ cmp(Operand(temp, StandardFrameConstants::kMarkerOffset),
5463 Immediate(Smi::FromInt(StackFrame::CONSTRUCT)));
5467 void LCodeGen::EnsureSpaceForLazyDeopt(int space_needed) {
5468 if (info()->ShouldEnsureSpaceForLazyDeopt()) {
5469 // Ensure that we have enough space after the previous lazy-bailout
5470 // instruction for patching the code here.
5471 int current_pc = masm()->pc_offset();
5472 if (current_pc < last_lazy_deopt_pc_ + space_needed) {
5473 int padding_size = last_lazy_deopt_pc_ + space_needed - current_pc;
5474 __ Nop(padding_size);
5477 last_lazy_deopt_pc_ = masm()->pc_offset();
5481 void LCodeGen::DoLazyBailout(LLazyBailout* instr) {
5482 last_lazy_deopt_pc_ = masm()->pc_offset();
5483 DCHECK(instr->HasEnvironment());
5484 LEnvironment* env = instr->environment();
5485 RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt);
5486 safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
5490 void LCodeGen::DoDeoptimize(LDeoptimize* instr) {
5491 Deoptimizer::BailoutType type = instr->hydrogen()->type();
5492 // TODO(danno): Stubs expect all deopts to be lazy for historical reasons (the
5493 // needed return address), even though the implementation of LAZY and EAGER is
5494 // now identical. When LAZY is eventually completely folded into EAGER, remove
5495 // the special case below.
5496 if (info()->IsStub() && type == Deoptimizer::EAGER) {
5497 type = Deoptimizer::LAZY;
5499 DeoptimizeIf(no_condition, instr, instr->hydrogen()->reason(), type);
5503 void LCodeGen::DoDummy(LDummy* instr) {
5504 // Nothing to see here, move on!
5508 void LCodeGen::DoDummyUse(LDummyUse* instr) {
5509 // Nothing to see here, move on!
5513 void LCodeGen::DoDeferredStackCheck(LStackCheck* instr) {
5514 PushSafepointRegistersScope scope(this);
5515 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
5516 __ CallRuntimeSaveDoubles(Runtime::kStackGuard);
5517 RecordSafepointWithLazyDeopt(
5518 instr, RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
5519 DCHECK(instr->HasEnvironment());
5520 LEnvironment* env = instr->environment();
5521 safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
5525 void LCodeGen::DoStackCheck(LStackCheck* instr) {
5526 class DeferredStackCheck final : public LDeferredCode {
5528 DeferredStackCheck(LCodeGen* codegen, LStackCheck* instr)
5529 : LDeferredCode(codegen), instr_(instr) { }
5530 void Generate() override { codegen()->DoDeferredStackCheck(instr_); }
5531 LInstruction* instr() override { return instr_; }
5534 LStackCheck* instr_;
5537 DCHECK(instr->HasEnvironment());
5538 LEnvironment* env = instr->environment();
5539 // There is no LLazyBailout instruction for stack-checks. We have to
5540 // prepare for lazy deoptimization explicitly here.
5541 if (instr->hydrogen()->is_function_entry()) {
5542 // Perform stack overflow check.
5544 ExternalReference stack_limit =
5545 ExternalReference::address_of_stack_limit(isolate());
5546 __ cmp(esp, Operand::StaticVariable(stack_limit));
5547 __ j(above_equal, &done, Label::kNear);
5549 DCHECK(instr->context()->IsRegister());
5550 DCHECK(ToRegister(instr->context()).is(esi));
5551 CallCode(isolate()->builtins()->StackCheck(),
5552 RelocInfo::CODE_TARGET,
5556 DCHECK(instr->hydrogen()->is_backwards_branch());
5557 // Perform stack overflow check if this goto needs it before jumping.
5558 DeferredStackCheck* deferred_stack_check =
5559 new(zone()) DeferredStackCheck(this, instr);
5560 ExternalReference stack_limit =
5561 ExternalReference::address_of_stack_limit(isolate());
5562 __ cmp(esp, Operand::StaticVariable(stack_limit));
5563 __ j(below, deferred_stack_check->entry());
5564 EnsureSpaceForLazyDeopt(Deoptimizer::patch_size());
5565 __ bind(instr->done_label());
5566 deferred_stack_check->SetExit(instr->done_label());
5567 RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt);
5568 // Don't record a deoptimization index for the safepoint here.
5569 // This will be done explicitly when emitting call and the safepoint in
5570 // the deferred code.
5575 void LCodeGen::DoOsrEntry(LOsrEntry* instr) {
5576 // This is a pseudo-instruction that ensures that the environment here is
5577 // properly registered for deoptimization and records the assembler's PC
5579 LEnvironment* environment = instr->environment();
5581 // If the environment were already registered, we would have no way of
5582 // backpatching it with the spill slot operands.
5583 DCHECK(!environment->HasBeenRegistered());
5584 RegisterEnvironmentForDeoptimization(environment, Safepoint::kNoLazyDeopt);
5586 GenerateOsrPrologue();
5590 void LCodeGen::DoForInPrepareMap(LForInPrepareMap* instr) {
5591 DCHECK(ToRegister(instr->context()).is(esi));
5592 __ test(eax, Immediate(kSmiTagMask));
5593 DeoptimizeIf(zero, instr, Deoptimizer::kSmi);
5595 STATIC_ASSERT(FIRST_JS_PROXY_TYPE == FIRST_SPEC_OBJECT_TYPE);
5596 __ CmpObjectType(eax, LAST_JS_PROXY_TYPE, ecx);
5597 DeoptimizeIf(below_equal, instr, Deoptimizer::kWrongInstanceType);
5599 Label use_cache, call_runtime;
5600 __ CheckEnumCache(&call_runtime);
5602 __ mov(eax, FieldOperand(eax, HeapObject::kMapOffset));
5603 __ jmp(&use_cache, Label::kNear);
5605 // Get the set of properties to enumerate.
5606 __ bind(&call_runtime);
5608 CallRuntime(Runtime::kGetPropertyNamesFast, 1, instr);
5610 __ cmp(FieldOperand(eax, HeapObject::kMapOffset),
5611 isolate()->factory()->meta_map());
5612 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongMap);
5613 __ bind(&use_cache);
5617 void LCodeGen::DoForInCacheArray(LForInCacheArray* instr) {
5618 Register map = ToRegister(instr->map());
5619 Register result = ToRegister(instr->result());
5620 Label load_cache, done;
5621 __ EnumLength(result, map);
5622 __ cmp(result, Immediate(Smi::FromInt(0)));
5623 __ j(not_equal, &load_cache, Label::kNear);
5624 __ mov(result, isolate()->factory()->empty_fixed_array());
5625 __ jmp(&done, Label::kNear);
5627 __ bind(&load_cache);
5628 __ LoadInstanceDescriptors(map, result);
5630 FieldOperand(result, DescriptorArray::kEnumCacheOffset));
5632 FieldOperand(result, FixedArray::SizeFor(instr->idx())));
5634 __ test(result, result);
5635 DeoptimizeIf(equal, instr, Deoptimizer::kNoCache);
5639 void LCodeGen::DoCheckMapValue(LCheckMapValue* instr) {
5640 Register object = ToRegister(instr->value());
5641 __ cmp(ToRegister(instr->map()),
5642 FieldOperand(object, HeapObject::kMapOffset));
5643 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongMap);
5647 void LCodeGen::DoDeferredLoadMutableDouble(LLoadFieldByIndex* instr,
5650 PushSafepointRegistersScope scope(this);
5654 __ CallRuntimeSaveDoubles(Runtime::kLoadMutableDouble);
5655 RecordSafepointWithRegisters(
5656 instr->pointer_map(), 2, Safepoint::kNoLazyDeopt);
5657 __ StoreToSafepointRegisterSlot(object, eax);
5661 void LCodeGen::DoLoadFieldByIndex(LLoadFieldByIndex* instr) {
5662 class DeferredLoadMutableDouble final : public LDeferredCode {
5664 DeferredLoadMutableDouble(LCodeGen* codegen,
5665 LLoadFieldByIndex* instr,
5668 : LDeferredCode(codegen),
5673 void Generate() override {
5674 codegen()->DoDeferredLoadMutableDouble(instr_, object_, index_);
5676 LInstruction* instr() override { return instr_; }
5679 LLoadFieldByIndex* instr_;
5684 Register object = ToRegister(instr->object());
5685 Register index = ToRegister(instr->index());
5687 DeferredLoadMutableDouble* deferred;
5688 deferred = new(zone()) DeferredLoadMutableDouble(
5689 this, instr, object, index);
5691 Label out_of_object, done;
5692 __ test(index, Immediate(Smi::FromInt(1)));
5693 __ j(not_zero, deferred->entry());
5697 __ cmp(index, Immediate(0));
5698 __ j(less, &out_of_object, Label::kNear);
5699 __ mov(object, FieldOperand(object,
5701 times_half_pointer_size,
5702 JSObject::kHeaderSize));
5703 __ jmp(&done, Label::kNear);
5705 __ bind(&out_of_object);
5706 __ mov(object, FieldOperand(object, JSObject::kPropertiesOffset));
5708 // Index is now equal to out of object property index plus 1.
5709 __ mov(object, FieldOperand(object,
5711 times_half_pointer_size,
5712 FixedArray::kHeaderSize - kPointerSize));
5713 __ bind(deferred->exit());
5718 void LCodeGen::DoStoreFrameContext(LStoreFrameContext* instr) {
5719 Register context = ToRegister(instr->context());
5720 __ mov(Operand(ebp, StandardFrameConstants::kContextOffset), context);
5724 void LCodeGen::DoAllocateBlockContext(LAllocateBlockContext* instr) {
5725 Handle<ScopeInfo> scope_info = instr->scope_info();
5726 __ Push(scope_info);
5727 __ push(ToRegister(instr->function()));
5728 CallRuntime(Runtime::kPushBlockContext, 2, instr);
5729 RecordSafepoint(Safepoint::kNoLazyDeopt);
5735 } // namespace internal
5738 #endif // V8_TARGET_ARCH_IA32