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.
9 #include "src/base/bits.h"
10 #include "src/code-factory.h"
11 #include "src/code-stubs.h"
12 #include "src/codegen.h"
13 #include "src/deoptimizer.h"
14 #include "src/hydrogen-osr.h"
15 #include "src/ic/ic.h"
16 #include "src/ic/stub-cache.h"
17 #include "src/x87/lithium-codegen-x87.h"
23 // When invoking builtins, we need to record the safepoint in the middle of
24 // the invoke instruction sequence generated by the macro assembler.
25 class SafepointGenerator FINAL : public CallWrapper {
27 SafepointGenerator(LCodeGen* codegen,
28 LPointerMap* pointers,
29 Safepoint::DeoptMode mode)
33 virtual ~SafepointGenerator() {}
35 virtual void BeforeCall(int call_size) const OVERRIDE {}
37 virtual void AfterCall() const OVERRIDE {
38 codegen_->RecordSafepoint(pointers_, deopt_mode_);
43 LPointerMap* pointers_;
44 Safepoint::DeoptMode deopt_mode_;
50 bool LCodeGen::GenerateCode() {
51 LPhase phase("Z_Code generation", chunk());
55 // Open a frame scope to indicate that there is a frame on the stack. The
56 // MANUAL indicates that the scope shouldn't actually generate code to set up
57 // the frame (that is done in GeneratePrologue).
58 FrameScope frame_scope(masm_, StackFrame::MANUAL);
60 support_aligned_spilled_doubles_ = info()->IsOptimizing();
62 dynamic_frame_alignment_ = info()->IsOptimizing() &&
63 ((chunk()->num_double_slots() > 2 &&
64 !chunk()->graph()->is_recursive()) ||
65 !info()->osr_ast_id().IsNone());
67 return GeneratePrologue() &&
69 GenerateDeferredCode() &&
70 GenerateJumpTable() &&
71 GenerateSafepointTable();
75 void LCodeGen::FinishCode(Handle<Code> code) {
77 code->set_stack_slots(GetStackSlotCount());
78 code->set_safepoint_table_offset(safepoints_.GetCodeOffset());
79 if (code->is_optimized_code()) RegisterWeakObjectsInOptimizedCode(code);
80 PopulateDeoptimizationData(code);
81 if (!info()->IsStub()) {
82 Deoptimizer::EnsureRelocSpaceForLazyDeoptimization(code);
88 void LCodeGen::MakeSureStackPagesMapped(int offset) {
89 const int kPageSize = 4 * KB;
90 for (offset -= kPageSize; offset > 0; offset -= kPageSize) {
91 __ mov(Operand(esp, offset), eax);
97 bool LCodeGen::GeneratePrologue() {
98 DCHECK(is_generating());
100 if (info()->IsOptimizing()) {
101 ProfileEntryHookStub::MaybeCallEntryHook(masm_);
104 if (strlen(FLAG_stop_at) > 0 &&
105 info_->function()->name()->IsUtf8EqualTo(CStrVector(FLAG_stop_at))) {
110 // Sloppy mode functions and builtins need to replace the receiver with the
111 // global proxy when called as functions (without an explicit receiver
113 if (info_->this_has_uses() &&
114 info_->strict_mode() == SLOPPY &&
115 !info_->is_native()) {
117 // +1 for return address.
118 int receiver_offset = (scope()->num_parameters() + 1) * kPointerSize;
119 __ mov(ecx, Operand(esp, receiver_offset));
121 __ cmp(ecx, isolate()->factory()->undefined_value());
122 __ j(not_equal, &ok, Label::kNear);
124 __ mov(ecx, GlobalObjectOperand());
125 __ mov(ecx, FieldOperand(ecx, GlobalObject::kGlobalProxyOffset));
127 __ mov(Operand(esp, receiver_offset), ecx);
132 if (support_aligned_spilled_doubles_ && dynamic_frame_alignment_) {
133 // Move state of dynamic frame alignment into edx.
134 __ Move(edx, Immediate(kNoAlignmentPadding));
136 Label do_not_pad, align_loop;
137 STATIC_ASSERT(kDoubleSize == 2 * kPointerSize);
138 // Align esp + 4 to a multiple of 2 * kPointerSize.
139 __ test(esp, Immediate(kPointerSize));
140 __ j(not_zero, &do_not_pad, Label::kNear);
141 __ push(Immediate(0));
143 __ mov(edx, Immediate(kAlignmentPaddingPushed));
144 // Copy arguments, receiver, and return address.
145 __ mov(ecx, Immediate(scope()->num_parameters() + 2));
147 __ bind(&align_loop);
148 __ mov(eax, Operand(ebx, 1 * kPointerSize));
149 __ mov(Operand(ebx, 0), eax);
150 __ add(Operand(ebx), Immediate(kPointerSize));
152 __ j(not_zero, &align_loop, Label::kNear);
153 __ mov(Operand(ebx, 0), Immediate(kAlignmentZapValue));
154 __ bind(&do_not_pad);
158 info()->set_prologue_offset(masm_->pc_offset());
159 if (NeedsEagerFrame()) {
160 DCHECK(!frame_is_built_);
161 frame_is_built_ = true;
162 if (info()->IsStub()) {
165 __ Prologue(info()->IsCodePreAgingActive());
167 info()->AddNoFrameRange(0, masm_->pc_offset());
170 if (info()->IsOptimizing() &&
171 dynamic_frame_alignment_ &&
173 __ test(esp, Immediate(kPointerSize));
174 __ Assert(zero, kFrameIsExpectedToBeAligned);
177 // Reserve space for the stack slots needed by the code.
178 int slots = GetStackSlotCount();
179 DCHECK(slots != 0 || !info()->IsOptimizing());
182 if (dynamic_frame_alignment_) {
185 __ push(Immediate(kNoAlignmentPadding));
188 if (FLAG_debug_code) {
189 __ sub(Operand(esp), Immediate(slots * kPointerSize));
191 MakeSureStackPagesMapped(slots * kPointerSize);
194 __ mov(Operand(eax), Immediate(slots));
197 __ mov(MemOperand(esp, eax, times_4, 0),
198 Immediate(kSlotsZapValue));
200 __ j(not_zero, &loop);
203 __ sub(Operand(esp), Immediate(slots * kPointerSize));
205 MakeSureStackPagesMapped(slots * kPointerSize);
209 if (support_aligned_spilled_doubles_) {
210 Comment(";;; Store dynamic frame alignment tag for spilled doubles");
211 // Store dynamic frame alignment state in the first local.
212 int offset = JavaScriptFrameConstants::kDynamicAlignmentStateOffset;
213 if (dynamic_frame_alignment_) {
214 __ mov(Operand(ebp, offset), edx);
216 __ mov(Operand(ebp, offset), Immediate(kNoAlignmentPadding));
222 // Possibly allocate a local context.
223 int heap_slots = info_->num_heap_slots() - Context::MIN_CONTEXT_SLOTS;
224 if (heap_slots > 0) {
225 Comment(";;; Allocate local context");
226 bool need_write_barrier = true;
227 // Argument to NewContext is the function, which is still in edi.
228 if (heap_slots <= FastNewContextStub::kMaximumSlots) {
229 FastNewContextStub stub(isolate(), heap_slots);
231 // Result of FastNewContextStub is always in new space.
232 need_write_barrier = false;
235 __ CallRuntime(Runtime::kNewFunctionContext, 1);
237 RecordSafepoint(Safepoint::kNoLazyDeopt);
238 // Context is returned in eax. It replaces the context passed to us.
239 // It's saved in the stack and kept live in esi.
241 __ mov(Operand(ebp, StandardFrameConstants::kContextOffset), eax);
243 // Copy parameters into context if necessary.
244 int num_parameters = scope()->num_parameters();
245 for (int i = 0; i < num_parameters; i++) {
246 Variable* var = scope()->parameter(i);
247 if (var->IsContextSlot()) {
248 int parameter_offset = StandardFrameConstants::kCallerSPOffset +
249 (num_parameters - 1 - i) * kPointerSize;
250 // Load parameter from stack.
251 __ mov(eax, Operand(ebp, parameter_offset));
252 // Store it in the context.
253 int context_offset = Context::SlotOffset(var->index());
254 __ mov(Operand(esi, context_offset), eax);
255 // Update the write barrier. This clobbers eax and ebx.
256 if (need_write_barrier) {
257 __ RecordWriteContextSlot(esi, context_offset, eax, ebx,
259 } else if (FLAG_debug_code) {
261 __ JumpIfInNewSpace(esi, eax, &done, Label::kNear);
262 __ Abort(kExpectedNewSpaceObject);
267 Comment(";;; End allocate local context");
270 // Initailize FPU state.
273 if (FLAG_trace && info()->IsOptimizing()) {
274 // We have not executed any compiled code yet, so esi still holds the
276 __ CallRuntime(Runtime::kTraceEnter, 0);
278 return !is_aborted();
282 void LCodeGen::GenerateOsrPrologue() {
283 // Generate the OSR entry prologue at the first unknown OSR value, or if there
284 // are none, at the OSR entrypoint instruction.
285 if (osr_pc_offset_ >= 0) return;
287 osr_pc_offset_ = masm()->pc_offset();
289 // Move state of dynamic frame alignment into edx.
290 __ Move(edx, Immediate(kNoAlignmentPadding));
292 if (support_aligned_spilled_doubles_ && dynamic_frame_alignment_) {
293 Label do_not_pad, align_loop;
294 // Align ebp + 4 to a multiple of 2 * kPointerSize.
295 __ test(ebp, Immediate(kPointerSize));
296 __ j(zero, &do_not_pad, Label::kNear);
297 __ push(Immediate(0));
299 __ mov(edx, Immediate(kAlignmentPaddingPushed));
301 // Move all parts of the frame over one word. The frame consists of:
302 // unoptimized frame slots, alignment state, context, frame pointer, return
303 // address, receiver, and the arguments.
304 __ mov(ecx, Immediate(scope()->num_parameters() +
305 5 + graph()->osr()->UnoptimizedFrameSlots()));
307 __ bind(&align_loop);
308 __ mov(eax, Operand(ebx, 1 * kPointerSize));
309 __ mov(Operand(ebx, 0), eax);
310 __ add(Operand(ebx), Immediate(kPointerSize));
312 __ j(not_zero, &align_loop, Label::kNear);
313 __ mov(Operand(ebx, 0), Immediate(kAlignmentZapValue));
314 __ sub(Operand(ebp), Immediate(kPointerSize));
315 __ bind(&do_not_pad);
318 // Save the first local, which is overwritten by the alignment state.
319 Operand alignment_loc = MemOperand(ebp, -3 * kPointerSize);
320 __ push(alignment_loc);
322 // Set the dynamic frame alignment state.
323 __ mov(alignment_loc, edx);
325 // Adjust the frame size, subsuming the unoptimized frame into the
327 int slots = GetStackSlotCount() - graph()->osr()->UnoptimizedFrameSlots();
329 __ sub(esp, Immediate((slots - 1) * kPointerSize));
331 // Initailize FPU state.
336 void LCodeGen::GenerateBodyInstructionPre(LInstruction* instr) {
337 if (instr->IsCall()) {
338 EnsureSpaceForLazyDeopt(Deoptimizer::patch_size());
340 if (!instr->IsLazyBailout() && !instr->IsGap()) {
341 safepoints_.BumpLastLazySafepointIndex();
343 FlushX87StackIfNecessary(instr);
347 void LCodeGen::GenerateBodyInstructionPost(LInstruction* instr) {
348 // When return from function call, FPU should be initialized again.
349 if (instr->IsCall() && instr->ClobbersDoubleRegisters(isolate())) {
350 bool double_result = instr->HasDoubleRegisterResult();
352 __ lea(esp, Operand(esp, -kDoubleSize));
353 __ fstp_d(Operand(esp, 0));
357 __ fld_d(Operand(esp, 0));
358 __ lea(esp, Operand(esp, kDoubleSize));
361 if (instr->IsGoto()) {
362 x87_stack_.LeavingBlock(current_block_, LGoto::cast(instr), this);
363 } else if (FLAG_debug_code && FLAG_enable_slow_asserts &&
364 !instr->IsGap() && !instr->IsReturn()) {
365 if (instr->ClobbersDoubleRegisters(isolate())) {
366 if (instr->HasDoubleRegisterResult()) {
367 DCHECK_EQ(1, x87_stack_.depth());
369 DCHECK_EQ(0, x87_stack_.depth());
372 __ VerifyX87StackDepth(x87_stack_.depth());
377 bool LCodeGen::GenerateJumpTable() {
379 if (jump_table_.length() > 0) {
380 Comment(";;; -------------------- Jump table --------------------");
382 for (int i = 0; i < jump_table_.length(); i++) {
383 Deoptimizer::JumpTableEntry* table_entry = &jump_table_[i];
384 __ bind(&table_entry->label);
385 Address entry = table_entry->address;
386 DeoptComment(table_entry->reason);
387 if (table_entry->needs_frame) {
388 DCHECK(!info()->saves_caller_doubles());
389 __ push(Immediate(ExternalReference::ForDeoptEntry(entry)));
390 if (needs_frame.is_bound()) {
391 __ jmp(&needs_frame);
393 __ bind(&needs_frame);
394 __ push(MemOperand(ebp, StandardFrameConstants::kContextOffset));
395 // This variant of deopt can only be used with stubs. Since we don't
396 // have a function pointer to install in the stack frame that we're
397 // building, install a special marker there instead.
398 DCHECK(info()->IsStub());
399 __ push(Immediate(Smi::FromInt(StackFrame::STUB)));
400 // Push a PC inside the function so that the deopt code can find where
401 // the deopt comes from. It doesn't have to be the precise return
402 // address of a "calling" LAZY deopt, it only has to be somewhere
403 // inside the code body.
404 Label push_approx_pc;
405 __ call(&push_approx_pc);
406 __ bind(&push_approx_pc);
407 // Push the continuation which was stashed were the ebp should
408 // be. Replace it with the saved ebp.
409 __ push(MemOperand(esp, 3 * kPointerSize));
410 __ mov(MemOperand(esp, 4 * kPointerSize), ebp);
411 __ lea(ebp, MemOperand(esp, 4 * kPointerSize));
412 __ ret(0); // Call the continuation without clobbering registers.
415 __ call(entry, RelocInfo::RUNTIME_ENTRY);
418 return !is_aborted();
422 bool LCodeGen::GenerateDeferredCode() {
423 DCHECK(is_generating());
424 if (deferred_.length() > 0) {
425 for (int i = 0; !is_aborted() && i < deferred_.length(); i++) {
426 LDeferredCode* code = deferred_[i];
427 X87Stack copy(code->x87_stack());
431 instructions_->at(code->instruction_index())->hydrogen_value();
432 RecordAndWritePosition(
433 chunk()->graph()->SourcePositionToScriptPosition(value->position()));
435 Comment(";;; <@%d,#%d> "
436 "-------------------- Deferred %s --------------------",
437 code->instruction_index(),
438 code->instr()->hydrogen_value()->id(),
439 code->instr()->Mnemonic());
440 __ bind(code->entry());
441 if (NeedsDeferredFrame()) {
442 Comment(";;; Build frame");
443 DCHECK(!frame_is_built_);
444 DCHECK(info()->IsStub());
445 frame_is_built_ = true;
446 // Build the frame in such a way that esi isn't trashed.
447 __ push(ebp); // Caller's frame pointer.
448 __ push(Operand(ebp, StandardFrameConstants::kContextOffset));
449 __ push(Immediate(Smi::FromInt(StackFrame::STUB)));
450 __ lea(ebp, Operand(esp, 2 * kPointerSize));
451 Comment(";;; Deferred code");
454 if (NeedsDeferredFrame()) {
455 __ bind(code->done());
456 Comment(";;; Destroy frame");
457 DCHECK(frame_is_built_);
458 frame_is_built_ = false;
462 __ jmp(code->exit());
466 // Deferred code is the last part of the instruction sequence. Mark
467 // the generated code as done unless we bailed out.
468 if (!is_aborted()) status_ = DONE;
469 return !is_aborted();
473 bool LCodeGen::GenerateSafepointTable() {
475 if (!info()->IsStub()) {
476 // For lazy deoptimization we need space to patch a call after every call.
477 // Ensure there is always space for such patching, even if the code ends
479 int target_offset = masm()->pc_offset() + Deoptimizer::patch_size();
480 while (masm()->pc_offset() < target_offset) {
484 safepoints_.Emit(masm(), GetStackSlotCount());
485 return !is_aborted();
489 Register LCodeGen::ToRegister(int index) const {
490 return Register::FromAllocationIndex(index);
494 X87Register LCodeGen::ToX87Register(int index) const {
495 return X87Register::FromAllocationIndex(index);
499 void LCodeGen::X87LoadForUsage(X87Register reg) {
500 DCHECK(x87_stack_.Contains(reg));
501 x87_stack_.Fxch(reg);
506 void LCodeGen::X87LoadForUsage(X87Register reg1, X87Register reg2) {
507 DCHECK(x87_stack_.Contains(reg1));
508 DCHECK(x87_stack_.Contains(reg2));
509 if (reg1.is(reg2) && x87_stack_.depth() == 1) {
510 __ fld(x87_stack_.st(reg1));
511 x87_stack_.push(reg1);
515 x87_stack_.Fxch(reg1, 1);
516 x87_stack_.Fxch(reg2);
523 int LCodeGen::X87Stack::GetLayout() {
524 int layout = stack_depth_;
525 for (int i = 0; i < stack_depth_; i++) {
526 layout |= (stack_[stack_depth_ - 1 - i].code() << ((i + 1) * 3));
533 void LCodeGen::X87Stack::Fxch(X87Register reg, int other_slot) {
535 DCHECK(Contains(reg) && stack_depth_ > other_slot);
536 int i = ArrayIndex(reg);
538 if (st != other_slot) {
539 int other_i = st2idx(other_slot);
540 X87Register other = stack_[other_i];
541 stack_[other_i] = reg;
545 } else if (other_slot == 0) {
556 int LCodeGen::X87Stack::st2idx(int pos) {
557 return stack_depth_ - pos - 1;
561 int LCodeGen::X87Stack::ArrayIndex(X87Register reg) {
562 for (int i = 0; i < stack_depth_; i++) {
563 if (stack_[i].is(reg)) return i;
570 bool LCodeGen::X87Stack::Contains(X87Register reg) {
571 for (int i = 0; i < stack_depth_; i++) {
572 if (stack_[i].is(reg)) return true;
578 void LCodeGen::X87Stack::Free(X87Register reg) {
580 DCHECK(Contains(reg));
581 int i = ArrayIndex(reg);
584 // keep track of how fstp(i) changes the order of elements
585 int tos_i = st2idx(0);
586 stack_[i] = stack_[tos_i];
593 void LCodeGen::X87Mov(X87Register dst, Operand src, X87OperandType opts) {
594 if (x87_stack_.Contains(dst)) {
595 x87_stack_.Fxch(dst);
598 x87_stack_.push(dst);
604 void LCodeGen::X87Mov(X87Register dst, X87Register src, X87OperandType opts) {
605 if (x87_stack_.Contains(dst)) {
606 x87_stack_.Fxch(dst);
609 // Push ST(i) onto the FPU register stack
610 __ fld(x87_stack_.st(src));
611 x87_stack_.push(dst);
613 // Push ST(i) onto the FPU register stack
614 __ fld(x87_stack_.st(src));
615 x87_stack_.push(dst);
620 void LCodeGen::X87Fld(Operand src, X87OperandType opts) {
621 DCHECK(!src.is_reg_only());
623 case kX87DoubleOperand:
626 case kX87FloatOperand:
638 void LCodeGen::X87Mov(Operand dst, X87Register src, X87OperandType opts) {
639 DCHECK(!dst.is_reg_only());
640 x87_stack_.Fxch(src);
642 case kX87DoubleOperand:
645 case kX87FloatOperand:
657 void LCodeGen::X87Stack::PrepareToWrite(X87Register reg) {
662 // Mark this register as the next register to write to
663 stack_[stack_depth_] = reg;
667 void LCodeGen::X87Stack::CommitWrite(X87Register reg) {
669 // Assert the reg is prepared to write, but not on the virtual stack yet
670 DCHECK(!Contains(reg) && stack_[stack_depth_].is(reg) &&
671 stack_depth_ < X87Register::kMaxNumAllocatableRegisters);
676 void LCodeGen::X87PrepareBinaryOp(
677 X87Register left, X87Register right, X87Register result) {
678 // You need to use DefineSameAsFirst for x87 instructions
679 DCHECK(result.is(left));
680 x87_stack_.Fxch(right, 1);
681 x87_stack_.Fxch(left);
685 void LCodeGen::X87Stack::FlushIfNecessary(LInstruction* instr, LCodeGen* cgen) {
686 if (stack_depth_ > 0 && instr->ClobbersDoubleRegisters(isolate())) {
687 bool double_inputs = instr->HasDoubleRegisterInput();
689 // Flush stack from tos down, since FreeX87() will mess with tos
690 for (int i = stack_depth_-1; i >= 0; i--) {
691 X87Register reg = stack_[i];
692 // Skip registers which contain the inputs for the next instruction
693 // when flushing the stack
694 if (double_inputs && instr->IsDoubleInput(reg, cgen)) {
698 if (i < stack_depth_-1) i++;
701 if (instr->IsReturn()) {
702 while (stack_depth_ > 0) {
706 if (FLAG_debug_code && FLAG_enable_slow_asserts) __ VerifyX87StackDepth(0);
711 void LCodeGen::X87Stack::LeavingBlock(int current_block_id, LGoto* goto_instr,
713 // For going to a joined block, an explicit LClobberDoubles is inserted before
714 // LGoto. Because all used x87 registers are spilled to stack slots. The
715 // ResolvePhis phase of register allocator could guarantee the two input's x87
716 // stacks have the same layout. So don't check stack_depth_ <= 1 here.
717 int goto_block_id = goto_instr->block_id();
718 if (current_block_id + 1 != goto_block_id) {
719 // If we have a value on the x87 stack on leaving a block, it must be a
720 // phi input. If the next block we compile is not the join block, we have
721 // to discard the stack state.
722 // Before discarding the stack state, we need to save it if the "goto block"
723 // has unreachable last predecessor when FLAG_unreachable_code_elimination.
724 if (FLAG_unreachable_code_elimination) {
725 int length = goto_instr->block()->predecessors()->length();
726 bool has_unreachable_last_predecessor = false;
727 for (int i = 0; i < length; i++) {
728 HBasicBlock* block = goto_instr->block()->predecessors()->at(i);
729 if (block->IsUnreachable() &&
730 (block->block_id() + 1) == goto_block_id) {
731 has_unreachable_last_predecessor = true;
734 if (has_unreachable_last_predecessor) {
735 if (cgen->x87_stack_map_.find(goto_block_id) ==
736 cgen->x87_stack_map_.end()) {
737 X87Stack* stack = new (cgen->zone()) X87Stack(*this);
738 cgen->x87_stack_map_.insert(std::make_pair(goto_block_id, stack));
743 // Discard the stack state.
749 void LCodeGen::EmitFlushX87ForDeopt() {
750 // The deoptimizer does not support X87 Registers. But as long as we
751 // deopt from a stub its not a problem, since we will re-materialize the
752 // original stub inputs, which can't be double registers.
753 // DCHECK(info()->IsStub());
754 if (FLAG_debug_code && FLAG_enable_slow_asserts) {
756 __ VerifyX87StackDepth(x87_stack_.depth());
760 // Flush X87 stack in the deoptimizer entry.
764 Register LCodeGen::ToRegister(LOperand* op) const {
765 DCHECK(op->IsRegister());
766 return ToRegister(op->index());
770 X87Register LCodeGen::ToX87Register(LOperand* op) const {
771 DCHECK(op->IsDoubleRegister());
772 return ToX87Register(op->index());
776 int32_t LCodeGen::ToInteger32(LConstantOperand* op) const {
777 return ToRepresentation(op, Representation::Integer32());
781 int32_t LCodeGen::ToRepresentation(LConstantOperand* op,
782 const Representation& r) const {
783 HConstant* constant = chunk_->LookupConstant(op);
784 int32_t value = constant->Integer32Value();
785 if (r.IsInteger32()) return value;
786 DCHECK(r.IsSmiOrTagged());
787 return reinterpret_cast<int32_t>(Smi::FromInt(value));
791 Handle<Object> LCodeGen::ToHandle(LConstantOperand* op) const {
792 HConstant* constant = chunk_->LookupConstant(op);
793 DCHECK(chunk_->LookupLiteralRepresentation(op).IsSmiOrTagged());
794 return constant->handle(isolate());
798 double LCodeGen::ToDouble(LConstantOperand* op) const {
799 HConstant* constant = chunk_->LookupConstant(op);
800 DCHECK(constant->HasDoubleValue());
801 return constant->DoubleValue();
805 ExternalReference LCodeGen::ToExternalReference(LConstantOperand* op) const {
806 HConstant* constant = chunk_->LookupConstant(op);
807 DCHECK(constant->HasExternalReferenceValue());
808 return constant->ExternalReferenceValue();
812 bool LCodeGen::IsInteger32(LConstantOperand* op) const {
813 return chunk_->LookupLiteralRepresentation(op).IsSmiOrInteger32();
817 bool LCodeGen::IsSmi(LConstantOperand* op) const {
818 return chunk_->LookupLiteralRepresentation(op).IsSmi();
822 static int ArgumentsOffsetWithoutFrame(int index) {
824 return -(index + 1) * kPointerSize + kPCOnStackSize;
828 Operand LCodeGen::ToOperand(LOperand* op) const {
829 if (op->IsRegister()) return Operand(ToRegister(op));
830 DCHECK(!op->IsDoubleRegister());
831 DCHECK(op->IsStackSlot() || op->IsDoubleStackSlot());
832 if (NeedsEagerFrame()) {
833 return Operand(ebp, StackSlotOffset(op->index()));
835 // Retrieve parameter without eager stack-frame relative to the
837 return Operand(esp, ArgumentsOffsetWithoutFrame(op->index()));
842 Operand LCodeGen::HighOperand(LOperand* op) {
843 DCHECK(op->IsDoubleStackSlot());
844 if (NeedsEagerFrame()) {
845 return Operand(ebp, StackSlotOffset(op->index()) + kPointerSize);
847 // Retrieve parameter without eager stack-frame relative to the
850 esp, ArgumentsOffsetWithoutFrame(op->index()) + kPointerSize);
855 void LCodeGen::WriteTranslation(LEnvironment* environment,
856 Translation* translation) {
857 if (environment == NULL) return;
859 // The translation includes one command per value in the environment.
860 int translation_size = environment->translation_size();
861 // The output frame height does not include the parameters.
862 int height = translation_size - environment->parameter_count();
864 WriteTranslation(environment->outer(), translation);
865 bool has_closure_id = !info()->closure().is_null() &&
866 !info()->closure().is_identical_to(environment->closure());
867 int closure_id = has_closure_id
868 ? DefineDeoptimizationLiteral(environment->closure())
869 : Translation::kSelfLiteralId;
870 switch (environment->frame_type()) {
872 translation->BeginJSFrame(environment->ast_id(), closure_id, height);
875 translation->BeginConstructStubFrame(closure_id, translation_size);
878 DCHECK(translation_size == 1);
880 translation->BeginGetterStubFrame(closure_id);
883 DCHECK(translation_size == 2);
885 translation->BeginSetterStubFrame(closure_id);
887 case ARGUMENTS_ADAPTOR:
888 translation->BeginArgumentsAdaptorFrame(closure_id, translation_size);
891 translation->BeginCompiledStubFrame();
897 int object_index = 0;
898 int dematerialized_index = 0;
899 for (int i = 0; i < translation_size; ++i) {
900 LOperand* value = environment->values()->at(i);
901 AddToTranslation(environment,
904 environment->HasTaggedValueAt(i),
905 environment->HasUint32ValueAt(i),
907 &dematerialized_index);
912 void LCodeGen::AddToTranslation(LEnvironment* environment,
913 Translation* translation,
917 int* object_index_pointer,
918 int* dematerialized_index_pointer) {
919 if (op == LEnvironment::materialization_marker()) {
920 int object_index = (*object_index_pointer)++;
921 if (environment->ObjectIsDuplicateAt(object_index)) {
922 int dupe_of = environment->ObjectDuplicateOfAt(object_index);
923 translation->DuplicateObject(dupe_of);
926 int object_length = environment->ObjectLengthAt(object_index);
927 if (environment->ObjectIsArgumentsAt(object_index)) {
928 translation->BeginArgumentsObject(object_length);
930 translation->BeginCapturedObject(object_length);
932 int dematerialized_index = *dematerialized_index_pointer;
933 int env_offset = environment->translation_size() + dematerialized_index;
934 *dematerialized_index_pointer += object_length;
935 for (int i = 0; i < object_length; ++i) {
936 LOperand* value = environment->values()->at(env_offset + i);
937 AddToTranslation(environment,
940 environment->HasTaggedValueAt(env_offset + i),
941 environment->HasUint32ValueAt(env_offset + i),
942 object_index_pointer,
943 dematerialized_index_pointer);
948 if (op->IsStackSlot()) {
950 translation->StoreStackSlot(op->index());
951 } else if (is_uint32) {
952 translation->StoreUint32StackSlot(op->index());
954 translation->StoreInt32StackSlot(op->index());
956 } else if (op->IsDoubleStackSlot()) {
957 translation->StoreDoubleStackSlot(op->index());
958 } else if (op->IsRegister()) {
959 Register reg = ToRegister(op);
961 translation->StoreRegister(reg);
962 } else if (is_uint32) {
963 translation->StoreUint32Register(reg);
965 translation->StoreInt32Register(reg);
967 } else if (op->IsDoubleRegister()) {
968 X87Register reg = ToX87Register(op);
969 translation->StoreDoubleRegister(reg);
970 } else if (op->IsConstantOperand()) {
971 HConstant* constant = chunk()->LookupConstant(LConstantOperand::cast(op));
972 int src_index = DefineDeoptimizationLiteral(constant->handle(isolate()));
973 translation->StoreLiteral(src_index);
980 void LCodeGen::CallCodeGeneric(Handle<Code> code,
981 RelocInfo::Mode mode,
983 SafepointMode safepoint_mode) {
984 DCHECK(instr != NULL);
986 RecordSafepointWithLazyDeopt(instr, safepoint_mode);
988 // Signal that we don't inline smi code before these stubs in the
989 // optimizing code generator.
990 if (code->kind() == Code::BINARY_OP_IC ||
991 code->kind() == Code::COMPARE_IC) {
997 void LCodeGen::CallCode(Handle<Code> code,
998 RelocInfo::Mode mode,
999 LInstruction* instr) {
1000 CallCodeGeneric(code, mode, instr, RECORD_SIMPLE_SAFEPOINT);
1004 void LCodeGen::CallRuntime(const Runtime::Function* fun, int argc,
1005 LInstruction* instr, SaveFPRegsMode save_doubles) {
1006 DCHECK(instr != NULL);
1007 DCHECK(instr->HasPointerMap());
1009 __ CallRuntime(fun, argc, save_doubles);
1011 RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
1013 DCHECK(info()->is_calling());
1017 void LCodeGen::LoadContextFromDeferred(LOperand* context) {
1018 if (context->IsRegister()) {
1019 if (!ToRegister(context).is(esi)) {
1020 __ mov(esi, ToRegister(context));
1022 } else if (context->IsStackSlot()) {
1023 __ mov(esi, ToOperand(context));
1024 } else if (context->IsConstantOperand()) {
1025 HConstant* constant =
1026 chunk_->LookupConstant(LConstantOperand::cast(context));
1027 __ LoadObject(esi, Handle<Object>::cast(constant->handle(isolate())));
1033 void LCodeGen::CallRuntimeFromDeferred(Runtime::FunctionId id,
1035 LInstruction* instr,
1036 LOperand* context) {
1037 LoadContextFromDeferred(context);
1039 __ CallRuntimeSaveDoubles(id);
1040 RecordSafepointWithRegisters(
1041 instr->pointer_map(), argc, Safepoint::kNoLazyDeopt);
1043 DCHECK(info()->is_calling());
1047 void LCodeGen::RegisterEnvironmentForDeoptimization(
1048 LEnvironment* environment, Safepoint::DeoptMode mode) {
1049 environment->set_has_been_used();
1050 if (!environment->HasBeenRegistered()) {
1051 // Physical stack frame layout:
1052 // -x ............. -4 0 ..................................... y
1053 // [incoming arguments] [spill slots] [pushed outgoing arguments]
1055 // Layout of the environment:
1056 // 0 ..................................................... size-1
1057 // [parameters] [locals] [expression stack including arguments]
1059 // Layout of the translation:
1060 // 0 ........................................................ size - 1 + 4
1061 // [expression stack including arguments] [locals] [4 words] [parameters]
1062 // |>------------ translation_size ------------<|
1064 int frame_count = 0;
1065 int jsframe_count = 0;
1066 for (LEnvironment* e = environment; e != NULL; e = e->outer()) {
1068 if (e->frame_type() == JS_FUNCTION) {
1072 Translation translation(&translations_, frame_count, jsframe_count, zone());
1073 WriteTranslation(environment, &translation);
1074 int deoptimization_index = deoptimizations_.length();
1075 int pc_offset = masm()->pc_offset();
1076 environment->Register(deoptimization_index,
1077 translation.index(),
1078 (mode == Safepoint::kLazyDeopt) ? pc_offset : -1);
1079 deoptimizations_.Add(environment, zone());
1084 void LCodeGen::DeoptimizeIf(Condition cc, LInstruction* instr,
1086 Deoptimizer::BailoutType bailout_type) {
1087 LEnvironment* environment = instr->environment();
1088 RegisterEnvironmentForDeoptimization(environment, Safepoint::kNoLazyDeopt);
1089 DCHECK(environment->HasBeenRegistered());
1090 int id = environment->deoptimization_index();
1091 DCHECK(info()->IsOptimizing() || info()->IsStub());
1093 Deoptimizer::GetDeoptimizationEntry(isolate(), id, bailout_type);
1094 if (entry == NULL) {
1095 Abort(kBailoutWasNotPrepared);
1099 if (DeoptEveryNTimes()) {
1100 ExternalReference count = ExternalReference::stress_deopt_count(isolate());
1104 __ mov(eax, Operand::StaticVariable(count));
1105 __ sub(eax, Immediate(1));
1106 __ j(not_zero, &no_deopt, Label::kNear);
1107 if (FLAG_trap_on_deopt) __ int3();
1108 __ mov(eax, Immediate(FLAG_deopt_every_n_times));
1109 __ mov(Operand::StaticVariable(count), eax);
1112 DCHECK(frame_is_built_);
1113 // Put the x87 stack layout in TOS.
1114 if (x87_stack_.depth() > 0) EmitFlushX87ForDeopt();
1115 __ push(Immediate(x87_stack_.GetLayout()));
1116 __ fild_s(MemOperand(esp, 0));
1117 // Don't touch eflags.
1118 __ lea(esp, Operand(esp, kPointerSize));
1119 __ call(entry, RelocInfo::RUNTIME_ENTRY);
1121 __ mov(Operand::StaticVariable(count), eax);
1126 // Put the x87 stack layout in TOS, so that we can save x87 fp registers in
1127 // the correct location.
1130 if (cc != no_condition) __ j(NegateCondition(cc), &done, Label::kNear);
1131 if (x87_stack_.depth() > 0) EmitFlushX87ForDeopt();
1133 int x87_stack_layout = x87_stack_.GetLayout();
1134 __ push(Immediate(x87_stack_layout));
1135 __ fild_s(MemOperand(esp, 0));
1136 // Don't touch eflags.
1137 __ lea(esp, Operand(esp, kPointerSize));
1141 if (info()->ShouldTrapOnDeopt()) {
1143 if (cc != no_condition) __ j(NegateCondition(cc), &done, Label::kNear);
1148 Deoptimizer::Reason reason(instr->hydrogen_value()->position().raw(),
1149 instr->Mnemonic(), detail);
1150 DCHECK(info()->IsStub() || frame_is_built_);
1151 if (cc == no_condition && frame_is_built_) {
1152 DeoptComment(reason);
1153 __ call(entry, RelocInfo::RUNTIME_ENTRY);
1155 Deoptimizer::JumpTableEntry table_entry(entry, reason, bailout_type,
1157 // We often have several deopts to the same entry, reuse the last
1158 // jump entry if this is the case.
1159 if (jump_table_.is_empty() ||
1160 !table_entry.IsEquivalentTo(jump_table_.last())) {
1161 jump_table_.Add(table_entry, zone());
1163 if (cc == no_condition) {
1164 __ jmp(&jump_table_.last().label);
1166 __ j(cc, &jump_table_.last().label);
1172 void LCodeGen::DeoptimizeIf(Condition cc, LInstruction* instr,
1173 const char* detail) {
1174 Deoptimizer::BailoutType bailout_type = info()->IsStub()
1176 : Deoptimizer::EAGER;
1177 DeoptimizeIf(cc, instr, detail, bailout_type);
1181 void LCodeGen::PopulateDeoptimizationData(Handle<Code> code) {
1182 int length = deoptimizations_.length();
1183 if (length == 0) return;
1184 Handle<DeoptimizationInputData> data =
1185 DeoptimizationInputData::New(isolate(), length, TENURED);
1187 Handle<ByteArray> translations =
1188 translations_.CreateByteArray(isolate()->factory());
1189 data->SetTranslationByteArray(*translations);
1190 data->SetInlinedFunctionCount(Smi::FromInt(inlined_function_count_));
1191 data->SetOptimizationId(Smi::FromInt(info_->optimization_id()));
1192 if (info_->IsOptimizing()) {
1193 // Reference to shared function info does not change between phases.
1194 AllowDeferredHandleDereference allow_handle_dereference;
1195 data->SetSharedFunctionInfo(*info_->shared_info());
1197 data->SetSharedFunctionInfo(Smi::FromInt(0));
1200 Handle<FixedArray> literals =
1201 factory()->NewFixedArray(deoptimization_literals_.length(), TENURED);
1202 { AllowDeferredHandleDereference copy_handles;
1203 for (int i = 0; i < deoptimization_literals_.length(); i++) {
1204 literals->set(i, *deoptimization_literals_[i]);
1206 data->SetLiteralArray(*literals);
1209 data->SetOsrAstId(Smi::FromInt(info_->osr_ast_id().ToInt()));
1210 data->SetOsrPcOffset(Smi::FromInt(osr_pc_offset_));
1212 // Populate the deoptimization entries.
1213 for (int i = 0; i < length; i++) {
1214 LEnvironment* env = deoptimizations_[i];
1215 data->SetAstId(i, env->ast_id());
1216 data->SetTranslationIndex(i, Smi::FromInt(env->translation_index()));
1217 data->SetArgumentsStackHeight(i,
1218 Smi::FromInt(env->arguments_stack_height()));
1219 data->SetPc(i, Smi::FromInt(env->pc_offset()));
1221 code->set_deoptimization_data(*data);
1225 int LCodeGen::DefineDeoptimizationLiteral(Handle<Object> literal) {
1226 int result = deoptimization_literals_.length();
1227 for (int i = 0; i < deoptimization_literals_.length(); ++i) {
1228 if (deoptimization_literals_[i].is_identical_to(literal)) return i;
1230 deoptimization_literals_.Add(literal, zone());
1235 void LCodeGen::PopulateDeoptimizationLiteralsWithInlinedFunctions() {
1236 DCHECK(deoptimization_literals_.length() == 0);
1238 const ZoneList<Handle<JSFunction> >* inlined_closures =
1239 chunk()->inlined_closures();
1241 for (int i = 0, length = inlined_closures->length();
1244 DefineDeoptimizationLiteral(inlined_closures->at(i));
1247 inlined_function_count_ = deoptimization_literals_.length();
1251 void LCodeGen::RecordSafepointWithLazyDeopt(
1252 LInstruction* instr, SafepointMode safepoint_mode) {
1253 if (safepoint_mode == RECORD_SIMPLE_SAFEPOINT) {
1254 RecordSafepoint(instr->pointer_map(), Safepoint::kLazyDeopt);
1256 DCHECK(safepoint_mode == RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
1257 RecordSafepointWithRegisters(
1258 instr->pointer_map(), 0, Safepoint::kLazyDeopt);
1263 void LCodeGen::RecordSafepoint(
1264 LPointerMap* pointers,
1265 Safepoint::Kind kind,
1267 Safepoint::DeoptMode deopt_mode) {
1268 DCHECK(kind == expected_safepoint_kind_);
1269 const ZoneList<LOperand*>* operands = pointers->GetNormalizedOperands();
1270 Safepoint safepoint =
1271 safepoints_.DefineSafepoint(masm(), kind, arguments, deopt_mode);
1272 for (int i = 0; i < operands->length(); i++) {
1273 LOperand* pointer = operands->at(i);
1274 if (pointer->IsStackSlot()) {
1275 safepoint.DefinePointerSlot(pointer->index(), zone());
1276 } else if (pointer->IsRegister() && (kind & Safepoint::kWithRegisters)) {
1277 safepoint.DefinePointerRegister(ToRegister(pointer), zone());
1283 void LCodeGen::RecordSafepoint(LPointerMap* pointers,
1284 Safepoint::DeoptMode mode) {
1285 RecordSafepoint(pointers, Safepoint::kSimple, 0, mode);
1289 void LCodeGen::RecordSafepoint(Safepoint::DeoptMode mode) {
1290 LPointerMap empty_pointers(zone());
1291 RecordSafepoint(&empty_pointers, mode);
1295 void LCodeGen::RecordSafepointWithRegisters(LPointerMap* pointers,
1297 Safepoint::DeoptMode mode) {
1298 RecordSafepoint(pointers, Safepoint::kWithRegisters, arguments, mode);
1302 void LCodeGen::RecordAndWritePosition(int position) {
1303 if (position == RelocInfo::kNoPosition) return;
1304 masm()->positions_recorder()->RecordPosition(position);
1305 masm()->positions_recorder()->WriteRecordedPositions();
1309 static const char* LabelType(LLabel* label) {
1310 if (label->is_loop_header()) return " (loop header)";
1311 if (label->is_osr_entry()) return " (OSR entry)";
1316 void LCodeGen::DoLabel(LLabel* label) {
1317 Comment(";;; <@%d,#%d> -------------------- B%d%s --------------------",
1318 current_instruction_,
1319 label->hydrogen_value()->id(),
1322 __ bind(label->label());
1323 current_block_ = label->block_id();
1324 if (label->block()->predecessors()->length() > 1) {
1325 // A join block's x87 stack is that of its last visited predecessor.
1326 // If the last visited predecessor block is unreachable, the stack state
1327 // will be wrong. In such case, use the x87 stack of reachable predecessor.
1328 X87StackMap::const_iterator it = x87_stack_map_.find(current_block_);
1329 // Restore x87 stack.
1330 if (it != x87_stack_map_.end()) {
1331 x87_stack_ = *(it->second);
1338 void LCodeGen::DoParallelMove(LParallelMove* move) {
1339 resolver_.Resolve(move);
1343 void LCodeGen::DoGap(LGap* gap) {
1344 for (int i = LGap::FIRST_INNER_POSITION;
1345 i <= LGap::LAST_INNER_POSITION;
1347 LGap::InnerPosition inner_pos = static_cast<LGap::InnerPosition>(i);
1348 LParallelMove* move = gap->GetParallelMove(inner_pos);
1349 if (move != NULL) DoParallelMove(move);
1354 void LCodeGen::DoInstructionGap(LInstructionGap* instr) {
1359 void LCodeGen::DoParameter(LParameter* instr) {
1364 void LCodeGen::DoCallStub(LCallStub* instr) {
1365 DCHECK(ToRegister(instr->context()).is(esi));
1366 DCHECK(ToRegister(instr->result()).is(eax));
1367 switch (instr->hydrogen()->major_key()) {
1368 case CodeStub::RegExpExec: {
1369 RegExpExecStub stub(isolate());
1370 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
1373 case CodeStub::SubString: {
1374 SubStringStub stub(isolate());
1375 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
1378 case CodeStub::StringCompare: {
1379 StringCompareStub stub(isolate());
1380 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
1389 void LCodeGen::DoUnknownOSRValue(LUnknownOSRValue* instr) {
1390 GenerateOsrPrologue();
1394 void LCodeGen::DoModByPowerOf2I(LModByPowerOf2I* instr) {
1395 Register dividend = ToRegister(instr->dividend());
1396 int32_t divisor = instr->divisor();
1397 DCHECK(dividend.is(ToRegister(instr->result())));
1399 // Theoretically, a variation of the branch-free code for integer division by
1400 // a power of 2 (calculating the remainder via an additional multiplication
1401 // (which gets simplified to an 'and') and subtraction) should be faster, and
1402 // this is exactly what GCC and clang emit. Nevertheless, benchmarks seem to
1403 // indicate that positive dividends are heavily favored, so the branching
1404 // version performs better.
1405 HMod* hmod = instr->hydrogen();
1406 int32_t mask = divisor < 0 ? -(divisor + 1) : (divisor - 1);
1407 Label dividend_is_not_negative, done;
1408 if (hmod->CheckFlag(HValue::kLeftCanBeNegative)) {
1409 __ test(dividend, dividend);
1410 __ j(not_sign, ÷nd_is_not_negative, Label::kNear);
1411 // Note that this is correct even for kMinInt operands.
1413 __ and_(dividend, mask);
1415 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1416 DeoptimizeIf(zero, instr, "minus zero");
1418 __ jmp(&done, Label::kNear);
1421 __ bind(÷nd_is_not_negative);
1422 __ and_(dividend, mask);
1427 void LCodeGen::DoModByConstI(LModByConstI* instr) {
1428 Register dividend = ToRegister(instr->dividend());
1429 int32_t divisor = instr->divisor();
1430 DCHECK(ToRegister(instr->result()).is(eax));
1433 DeoptimizeIf(no_condition, instr, "division by zero");
1437 __ TruncatingDiv(dividend, Abs(divisor));
1438 __ imul(edx, edx, Abs(divisor));
1439 __ mov(eax, dividend);
1442 // Check for negative zero.
1443 HMod* hmod = instr->hydrogen();
1444 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1445 Label remainder_not_zero;
1446 __ j(not_zero, &remainder_not_zero, Label::kNear);
1447 __ cmp(dividend, Immediate(0));
1448 DeoptimizeIf(less, instr, "minus zero");
1449 __ bind(&remainder_not_zero);
1454 void LCodeGen::DoModI(LModI* instr) {
1455 HMod* hmod = instr->hydrogen();
1457 Register left_reg = ToRegister(instr->left());
1458 DCHECK(left_reg.is(eax));
1459 Register right_reg = ToRegister(instr->right());
1460 DCHECK(!right_reg.is(eax));
1461 DCHECK(!right_reg.is(edx));
1462 Register result_reg = ToRegister(instr->result());
1463 DCHECK(result_reg.is(edx));
1466 // Check for x % 0, idiv would signal a divide error. We have to
1467 // deopt in this case because we can't return a NaN.
1468 if (hmod->CheckFlag(HValue::kCanBeDivByZero)) {
1469 __ test(right_reg, Operand(right_reg));
1470 DeoptimizeIf(zero, instr, "division by zero");
1473 // Check for kMinInt % -1, idiv would signal a divide error. We
1474 // have to deopt if we care about -0, because we can't return that.
1475 if (hmod->CheckFlag(HValue::kCanOverflow)) {
1476 Label no_overflow_possible;
1477 __ cmp(left_reg, kMinInt);
1478 __ j(not_equal, &no_overflow_possible, Label::kNear);
1479 __ cmp(right_reg, -1);
1480 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1481 DeoptimizeIf(equal, instr, "minus zero");
1483 __ j(not_equal, &no_overflow_possible, Label::kNear);
1484 __ Move(result_reg, Immediate(0));
1485 __ jmp(&done, Label::kNear);
1487 __ bind(&no_overflow_possible);
1490 // Sign extend dividend in eax into edx:eax.
1493 // If we care about -0, test if the dividend is <0 and the result is 0.
1494 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1495 Label positive_left;
1496 __ test(left_reg, Operand(left_reg));
1497 __ j(not_sign, &positive_left, Label::kNear);
1499 __ test(result_reg, Operand(result_reg));
1500 DeoptimizeIf(zero, instr, "minus zero");
1501 __ jmp(&done, Label::kNear);
1502 __ bind(&positive_left);
1509 void LCodeGen::DoDivByPowerOf2I(LDivByPowerOf2I* instr) {
1510 Register dividend = ToRegister(instr->dividend());
1511 int32_t divisor = instr->divisor();
1512 Register result = ToRegister(instr->result());
1513 DCHECK(divisor == kMinInt || base::bits::IsPowerOfTwo32(Abs(divisor)));
1514 DCHECK(!result.is(dividend));
1516 // Check for (0 / -x) that will produce negative zero.
1517 HDiv* hdiv = instr->hydrogen();
1518 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
1519 __ test(dividend, dividend);
1520 DeoptimizeIf(zero, instr, "minus zero");
1522 // Check for (kMinInt / -1).
1523 if (hdiv->CheckFlag(HValue::kCanOverflow) && divisor == -1) {
1524 __ cmp(dividend, kMinInt);
1525 DeoptimizeIf(zero, instr, "overflow");
1527 // Deoptimize if remainder will not be 0.
1528 if (!hdiv->CheckFlag(HInstruction::kAllUsesTruncatingToInt32) &&
1529 divisor != 1 && divisor != -1) {
1530 int32_t mask = divisor < 0 ? -(divisor + 1) : (divisor - 1);
1531 __ test(dividend, Immediate(mask));
1532 DeoptimizeIf(not_zero, instr, "lost precision");
1534 __ Move(result, dividend);
1535 int32_t shift = WhichPowerOf2Abs(divisor);
1537 // The arithmetic shift is always OK, the 'if' is an optimization only.
1538 if (shift > 1) __ sar(result, 31);
1539 __ shr(result, 32 - shift);
1540 __ add(result, dividend);
1541 __ sar(result, shift);
1543 if (divisor < 0) __ neg(result);
1547 void LCodeGen::DoDivByConstI(LDivByConstI* instr) {
1548 Register dividend = ToRegister(instr->dividend());
1549 int32_t divisor = instr->divisor();
1550 DCHECK(ToRegister(instr->result()).is(edx));
1553 DeoptimizeIf(no_condition, instr, "division by zero");
1557 // Check for (0 / -x) that will produce negative zero.
1558 HDiv* hdiv = instr->hydrogen();
1559 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
1560 __ test(dividend, dividend);
1561 DeoptimizeIf(zero, instr, "minus zero");
1564 __ TruncatingDiv(dividend, Abs(divisor));
1565 if (divisor < 0) __ neg(edx);
1567 if (!hdiv->CheckFlag(HInstruction::kAllUsesTruncatingToInt32)) {
1569 __ imul(eax, eax, divisor);
1570 __ sub(eax, dividend);
1571 DeoptimizeIf(not_equal, instr, "lost precision");
1576 // TODO(svenpanne) Refactor this to avoid code duplication with DoFlooringDivI.
1577 void LCodeGen::DoDivI(LDivI* instr) {
1578 HBinaryOperation* hdiv = instr->hydrogen();
1579 Register dividend = ToRegister(instr->dividend());
1580 Register divisor = ToRegister(instr->divisor());
1581 Register remainder = ToRegister(instr->temp());
1582 DCHECK(dividend.is(eax));
1583 DCHECK(remainder.is(edx));
1584 DCHECK(ToRegister(instr->result()).is(eax));
1585 DCHECK(!divisor.is(eax));
1586 DCHECK(!divisor.is(edx));
1589 if (hdiv->CheckFlag(HValue::kCanBeDivByZero)) {
1590 __ test(divisor, divisor);
1591 DeoptimizeIf(zero, instr, "division by zero");
1594 // Check for (0 / -x) that will produce negative zero.
1595 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero)) {
1596 Label dividend_not_zero;
1597 __ test(dividend, dividend);
1598 __ j(not_zero, ÷nd_not_zero, Label::kNear);
1599 __ test(divisor, divisor);
1600 DeoptimizeIf(sign, instr, "minus zero");
1601 __ bind(÷nd_not_zero);
1604 // Check for (kMinInt / -1).
1605 if (hdiv->CheckFlag(HValue::kCanOverflow)) {
1606 Label dividend_not_min_int;
1607 __ cmp(dividend, kMinInt);
1608 __ j(not_zero, ÷nd_not_min_int, Label::kNear);
1609 __ cmp(divisor, -1);
1610 DeoptimizeIf(zero, instr, "overflow");
1611 __ bind(÷nd_not_min_int);
1614 // Sign extend to edx (= remainder).
1618 if (!hdiv->CheckFlag(HValue::kAllUsesTruncatingToInt32)) {
1619 // Deoptimize if remainder is not 0.
1620 __ test(remainder, remainder);
1621 DeoptimizeIf(not_zero, instr, "lost precision");
1626 void LCodeGen::DoFlooringDivByPowerOf2I(LFlooringDivByPowerOf2I* instr) {
1627 Register dividend = ToRegister(instr->dividend());
1628 int32_t divisor = instr->divisor();
1629 DCHECK(dividend.is(ToRegister(instr->result())));
1631 // If the divisor is positive, things are easy: There can be no deopts and we
1632 // can simply do an arithmetic right shift.
1633 if (divisor == 1) return;
1634 int32_t shift = WhichPowerOf2Abs(divisor);
1636 __ sar(dividend, shift);
1640 // If the divisor is negative, we have to negate and handle edge cases.
1642 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1643 DeoptimizeIf(zero, instr, "minus zero");
1646 // Dividing by -1 is basically negation, unless we overflow.
1647 if (divisor == -1) {
1648 if (instr->hydrogen()->CheckFlag(HValue::kLeftCanBeMinInt)) {
1649 DeoptimizeIf(overflow, instr, "overflow");
1654 // If the negation could not overflow, simply shifting is OK.
1655 if (!instr->hydrogen()->CheckFlag(HValue::kLeftCanBeMinInt)) {
1656 __ sar(dividend, shift);
1660 Label not_kmin_int, done;
1661 __ j(no_overflow, ¬_kmin_int, Label::kNear);
1662 __ mov(dividend, Immediate(kMinInt / divisor));
1663 __ jmp(&done, Label::kNear);
1664 __ bind(¬_kmin_int);
1665 __ sar(dividend, shift);
1670 void LCodeGen::DoFlooringDivByConstI(LFlooringDivByConstI* instr) {
1671 Register dividend = ToRegister(instr->dividend());
1672 int32_t divisor = instr->divisor();
1673 DCHECK(ToRegister(instr->result()).is(edx));
1676 DeoptimizeIf(no_condition, instr, "division by zero");
1680 // Check for (0 / -x) that will produce negative zero.
1681 HMathFloorOfDiv* hdiv = instr->hydrogen();
1682 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
1683 __ test(dividend, dividend);
1684 DeoptimizeIf(zero, instr, "minus zero");
1687 // Easy case: We need no dynamic check for the dividend and the flooring
1688 // division is the same as the truncating division.
1689 if ((divisor > 0 && !hdiv->CheckFlag(HValue::kLeftCanBeNegative)) ||
1690 (divisor < 0 && !hdiv->CheckFlag(HValue::kLeftCanBePositive))) {
1691 __ TruncatingDiv(dividend, Abs(divisor));
1692 if (divisor < 0) __ neg(edx);
1696 // In the general case we may need to adjust before and after the truncating
1697 // division to get a flooring division.
1698 Register temp = ToRegister(instr->temp3());
1699 DCHECK(!temp.is(dividend) && !temp.is(eax) && !temp.is(edx));
1700 Label needs_adjustment, done;
1701 __ cmp(dividend, Immediate(0));
1702 __ j(divisor > 0 ? less : greater, &needs_adjustment, Label::kNear);
1703 __ TruncatingDiv(dividend, Abs(divisor));
1704 if (divisor < 0) __ neg(edx);
1705 __ jmp(&done, Label::kNear);
1706 __ bind(&needs_adjustment);
1707 __ lea(temp, Operand(dividend, divisor > 0 ? 1 : -1));
1708 __ TruncatingDiv(temp, Abs(divisor));
1709 if (divisor < 0) __ neg(edx);
1715 // TODO(svenpanne) Refactor this to avoid code duplication with DoDivI.
1716 void LCodeGen::DoFlooringDivI(LFlooringDivI* instr) {
1717 HBinaryOperation* hdiv = instr->hydrogen();
1718 Register dividend = ToRegister(instr->dividend());
1719 Register divisor = ToRegister(instr->divisor());
1720 Register remainder = ToRegister(instr->temp());
1721 Register result = ToRegister(instr->result());
1722 DCHECK(dividend.is(eax));
1723 DCHECK(remainder.is(edx));
1724 DCHECK(result.is(eax));
1725 DCHECK(!divisor.is(eax));
1726 DCHECK(!divisor.is(edx));
1729 if (hdiv->CheckFlag(HValue::kCanBeDivByZero)) {
1730 __ test(divisor, divisor);
1731 DeoptimizeIf(zero, instr, "division by zero");
1734 // Check for (0 / -x) that will produce negative zero.
1735 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero)) {
1736 Label dividend_not_zero;
1737 __ test(dividend, dividend);
1738 __ j(not_zero, ÷nd_not_zero, Label::kNear);
1739 __ test(divisor, divisor);
1740 DeoptimizeIf(sign, instr, "minus zero");
1741 __ bind(÷nd_not_zero);
1744 // Check for (kMinInt / -1).
1745 if (hdiv->CheckFlag(HValue::kCanOverflow)) {
1746 Label dividend_not_min_int;
1747 __ cmp(dividend, kMinInt);
1748 __ j(not_zero, ÷nd_not_min_int, Label::kNear);
1749 __ cmp(divisor, -1);
1750 DeoptimizeIf(zero, instr, "overflow");
1751 __ bind(÷nd_not_min_int);
1754 // Sign extend to edx (= remainder).
1759 __ test(remainder, remainder);
1760 __ j(zero, &done, Label::kNear);
1761 __ xor_(remainder, divisor);
1762 __ sar(remainder, 31);
1763 __ add(result, remainder);
1768 void LCodeGen::DoMulI(LMulI* instr) {
1769 Register left = ToRegister(instr->left());
1770 LOperand* right = instr->right();
1772 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1773 __ mov(ToRegister(instr->temp()), left);
1776 if (right->IsConstantOperand()) {
1777 // Try strength reductions on the multiplication.
1778 // All replacement instructions are at most as long as the imul
1779 // and have better latency.
1780 int constant = ToInteger32(LConstantOperand::cast(right));
1781 if (constant == -1) {
1783 } else if (constant == 0) {
1784 __ xor_(left, Operand(left));
1785 } else if (constant == 2) {
1786 __ add(left, Operand(left));
1787 } else if (!instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
1788 // If we know that the multiplication can't overflow, it's safe to
1789 // use instructions that don't set the overflow flag for the
1796 __ lea(left, Operand(left, left, times_2, 0));
1802 __ lea(left, Operand(left, left, times_4, 0));
1808 __ lea(left, Operand(left, left, times_8, 0));
1814 __ imul(left, left, constant);
1818 __ imul(left, left, constant);
1821 if (instr->hydrogen()->representation().IsSmi()) {
1824 __ imul(left, ToOperand(right));
1827 if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
1828 DeoptimizeIf(overflow, instr, "overflow");
1831 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1832 // Bail out if the result is supposed to be negative zero.
1834 __ test(left, Operand(left));
1835 __ j(not_zero, &done);
1836 if (right->IsConstantOperand()) {
1837 if (ToInteger32(LConstantOperand::cast(right)) < 0) {
1838 DeoptimizeIf(no_condition, instr, "minus zero");
1839 } else if (ToInteger32(LConstantOperand::cast(right)) == 0) {
1840 __ cmp(ToRegister(instr->temp()), Immediate(0));
1841 DeoptimizeIf(less, instr, "minus zero");
1844 // Test the non-zero operand for negative sign.
1845 __ or_(ToRegister(instr->temp()), ToOperand(right));
1846 DeoptimizeIf(sign, instr, "minus zero");
1853 void LCodeGen::DoBitI(LBitI* instr) {
1854 LOperand* left = instr->left();
1855 LOperand* right = instr->right();
1856 DCHECK(left->Equals(instr->result()));
1857 DCHECK(left->IsRegister());
1859 if (right->IsConstantOperand()) {
1860 int32_t right_operand =
1861 ToRepresentation(LConstantOperand::cast(right),
1862 instr->hydrogen()->representation());
1863 switch (instr->op()) {
1864 case Token::BIT_AND:
1865 __ and_(ToRegister(left), right_operand);
1868 __ or_(ToRegister(left), right_operand);
1870 case Token::BIT_XOR:
1871 if (right_operand == int32_t(~0)) {
1872 __ not_(ToRegister(left));
1874 __ xor_(ToRegister(left), right_operand);
1882 switch (instr->op()) {
1883 case Token::BIT_AND:
1884 __ and_(ToRegister(left), ToOperand(right));
1887 __ or_(ToRegister(left), ToOperand(right));
1889 case Token::BIT_XOR:
1890 __ xor_(ToRegister(left), ToOperand(right));
1900 void LCodeGen::DoShiftI(LShiftI* instr) {
1901 LOperand* left = instr->left();
1902 LOperand* right = instr->right();
1903 DCHECK(left->Equals(instr->result()));
1904 DCHECK(left->IsRegister());
1905 if (right->IsRegister()) {
1906 DCHECK(ToRegister(right).is(ecx));
1908 switch (instr->op()) {
1910 __ ror_cl(ToRegister(left));
1913 __ sar_cl(ToRegister(left));
1916 __ shr_cl(ToRegister(left));
1917 if (instr->can_deopt()) {
1918 __ test(ToRegister(left), ToRegister(left));
1919 DeoptimizeIf(sign, instr, "negative value");
1923 __ shl_cl(ToRegister(left));
1930 int value = ToInteger32(LConstantOperand::cast(right));
1931 uint8_t shift_count = static_cast<uint8_t>(value & 0x1F);
1932 switch (instr->op()) {
1934 if (shift_count == 0 && instr->can_deopt()) {
1935 __ test(ToRegister(left), ToRegister(left));
1936 DeoptimizeIf(sign, instr, "negative value");
1938 __ ror(ToRegister(left), shift_count);
1942 if (shift_count != 0) {
1943 __ sar(ToRegister(left), shift_count);
1947 if (shift_count != 0) {
1948 __ shr(ToRegister(left), shift_count);
1949 } else if (instr->can_deopt()) {
1950 __ test(ToRegister(left), ToRegister(left));
1951 DeoptimizeIf(sign, instr, "negative value");
1955 if (shift_count != 0) {
1956 if (instr->hydrogen_value()->representation().IsSmi() &&
1957 instr->can_deopt()) {
1958 if (shift_count != 1) {
1959 __ shl(ToRegister(left), shift_count - 1);
1961 __ SmiTag(ToRegister(left));
1962 DeoptimizeIf(overflow, instr, "overflow");
1964 __ shl(ToRegister(left), shift_count);
1976 void LCodeGen::DoSubI(LSubI* instr) {
1977 LOperand* left = instr->left();
1978 LOperand* right = instr->right();
1979 DCHECK(left->Equals(instr->result()));
1981 if (right->IsConstantOperand()) {
1982 __ sub(ToOperand(left),
1983 ToImmediate(right, instr->hydrogen()->representation()));
1985 __ sub(ToRegister(left), ToOperand(right));
1987 if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
1988 DeoptimizeIf(overflow, instr, "overflow");
1993 void LCodeGen::DoConstantI(LConstantI* instr) {
1994 __ Move(ToRegister(instr->result()), Immediate(instr->value()));
1998 void LCodeGen::DoConstantS(LConstantS* instr) {
1999 __ Move(ToRegister(instr->result()), Immediate(instr->value()));
2003 void LCodeGen::DoConstantD(LConstantD* instr) {
2004 double v = instr->value();
2005 uint64_t int_val = bit_cast<uint64_t, double>(v);
2006 int32_t lower = static_cast<int32_t>(int_val);
2007 int32_t upper = static_cast<int32_t>(int_val >> (kBitsPerInt));
2008 DCHECK(instr->result()->IsDoubleRegister());
2010 __ push(Immediate(upper));
2011 __ push(Immediate(lower));
2012 X87Register reg = ToX87Register(instr->result());
2013 X87Mov(reg, Operand(esp, 0));
2014 __ add(Operand(esp), Immediate(kDoubleSize));
2018 void LCodeGen::DoConstantE(LConstantE* instr) {
2019 __ lea(ToRegister(instr->result()), Operand::StaticVariable(instr->value()));
2023 void LCodeGen::DoConstantT(LConstantT* instr) {
2024 Register reg = ToRegister(instr->result());
2025 Handle<Object> object = instr->value(isolate());
2026 AllowDeferredHandleDereference smi_check;
2027 __ LoadObject(reg, object);
2031 void LCodeGen::DoMapEnumLength(LMapEnumLength* instr) {
2032 Register result = ToRegister(instr->result());
2033 Register map = ToRegister(instr->value());
2034 __ EnumLength(result, map);
2038 void LCodeGen::DoDateField(LDateField* instr) {
2039 Register object = ToRegister(instr->date());
2040 Register result = ToRegister(instr->result());
2041 Register scratch = ToRegister(instr->temp());
2042 Smi* index = instr->index();
2043 Label runtime, done;
2044 DCHECK(object.is(result));
2045 DCHECK(object.is(eax));
2047 __ test(object, Immediate(kSmiTagMask));
2048 DeoptimizeIf(zero, instr, "Smi");
2049 __ CmpObjectType(object, JS_DATE_TYPE, scratch);
2050 DeoptimizeIf(not_equal, instr, "not a date object");
2052 if (index->value() == 0) {
2053 __ mov(result, FieldOperand(object, JSDate::kValueOffset));
2055 if (index->value() < JSDate::kFirstUncachedField) {
2056 ExternalReference stamp = ExternalReference::date_cache_stamp(isolate());
2057 __ mov(scratch, Operand::StaticVariable(stamp));
2058 __ cmp(scratch, FieldOperand(object, JSDate::kCacheStampOffset));
2059 __ j(not_equal, &runtime, Label::kNear);
2060 __ mov(result, FieldOperand(object, JSDate::kValueOffset +
2061 kPointerSize * index->value()));
2062 __ jmp(&done, Label::kNear);
2065 __ PrepareCallCFunction(2, scratch);
2066 __ mov(Operand(esp, 0), object);
2067 __ mov(Operand(esp, 1 * kPointerSize), Immediate(index));
2068 __ CallCFunction(ExternalReference::get_date_field_function(isolate()), 2);
2074 Operand LCodeGen::BuildSeqStringOperand(Register string,
2076 String::Encoding encoding) {
2077 if (index->IsConstantOperand()) {
2078 int offset = ToRepresentation(LConstantOperand::cast(index),
2079 Representation::Integer32());
2080 if (encoding == String::TWO_BYTE_ENCODING) {
2081 offset *= kUC16Size;
2083 STATIC_ASSERT(kCharSize == 1);
2084 return FieldOperand(string, SeqString::kHeaderSize + offset);
2086 return FieldOperand(
2087 string, ToRegister(index),
2088 encoding == String::ONE_BYTE_ENCODING ? times_1 : times_2,
2089 SeqString::kHeaderSize);
2093 void LCodeGen::DoSeqStringGetChar(LSeqStringGetChar* instr) {
2094 String::Encoding encoding = instr->hydrogen()->encoding();
2095 Register result = ToRegister(instr->result());
2096 Register string = ToRegister(instr->string());
2098 if (FLAG_debug_code) {
2100 __ mov(string, FieldOperand(string, HeapObject::kMapOffset));
2101 __ movzx_b(string, FieldOperand(string, Map::kInstanceTypeOffset));
2103 __ and_(string, Immediate(kStringRepresentationMask | kStringEncodingMask));
2104 static const uint32_t one_byte_seq_type = kSeqStringTag | kOneByteStringTag;
2105 static const uint32_t two_byte_seq_type = kSeqStringTag | kTwoByteStringTag;
2106 __ cmp(string, Immediate(encoding == String::ONE_BYTE_ENCODING
2107 ? one_byte_seq_type : two_byte_seq_type));
2108 __ Check(equal, kUnexpectedStringType);
2112 Operand operand = BuildSeqStringOperand(string, instr->index(), encoding);
2113 if (encoding == String::ONE_BYTE_ENCODING) {
2114 __ movzx_b(result, operand);
2116 __ movzx_w(result, operand);
2121 void LCodeGen::DoSeqStringSetChar(LSeqStringSetChar* instr) {
2122 String::Encoding encoding = instr->hydrogen()->encoding();
2123 Register string = ToRegister(instr->string());
2125 if (FLAG_debug_code) {
2126 Register value = ToRegister(instr->value());
2127 Register index = ToRegister(instr->index());
2128 static const uint32_t one_byte_seq_type = kSeqStringTag | kOneByteStringTag;
2129 static const uint32_t two_byte_seq_type = kSeqStringTag | kTwoByteStringTag;
2131 instr->hydrogen()->encoding() == String::ONE_BYTE_ENCODING
2132 ? one_byte_seq_type : two_byte_seq_type;
2133 __ EmitSeqStringSetCharCheck(string, index, value, encoding_mask);
2136 Operand operand = BuildSeqStringOperand(string, instr->index(), encoding);
2137 if (instr->value()->IsConstantOperand()) {
2138 int value = ToRepresentation(LConstantOperand::cast(instr->value()),
2139 Representation::Integer32());
2140 DCHECK_LE(0, value);
2141 if (encoding == String::ONE_BYTE_ENCODING) {
2142 DCHECK_LE(value, String::kMaxOneByteCharCode);
2143 __ mov_b(operand, static_cast<int8_t>(value));
2145 DCHECK_LE(value, String::kMaxUtf16CodeUnit);
2146 __ mov_w(operand, static_cast<int16_t>(value));
2149 Register value = ToRegister(instr->value());
2150 if (encoding == String::ONE_BYTE_ENCODING) {
2151 __ mov_b(operand, value);
2153 __ mov_w(operand, value);
2159 void LCodeGen::DoAddI(LAddI* instr) {
2160 LOperand* left = instr->left();
2161 LOperand* right = instr->right();
2163 if (LAddI::UseLea(instr->hydrogen()) && !left->Equals(instr->result())) {
2164 if (right->IsConstantOperand()) {
2165 int32_t offset = ToRepresentation(LConstantOperand::cast(right),
2166 instr->hydrogen()->representation());
2167 __ lea(ToRegister(instr->result()), MemOperand(ToRegister(left), offset));
2169 Operand address(ToRegister(left), ToRegister(right), times_1, 0);
2170 __ lea(ToRegister(instr->result()), address);
2173 if (right->IsConstantOperand()) {
2174 __ add(ToOperand(left),
2175 ToImmediate(right, instr->hydrogen()->representation()));
2177 __ add(ToRegister(left), ToOperand(right));
2179 if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
2180 DeoptimizeIf(overflow, instr, "overflow");
2186 void LCodeGen::DoMathMinMax(LMathMinMax* instr) {
2187 LOperand* left = instr->left();
2188 LOperand* right = instr->right();
2189 DCHECK(left->Equals(instr->result()));
2190 HMathMinMax::Operation operation = instr->hydrogen()->operation();
2191 if (instr->hydrogen()->representation().IsSmiOrInteger32()) {
2193 Condition condition = (operation == HMathMinMax::kMathMin)
2196 if (right->IsConstantOperand()) {
2197 Operand left_op = ToOperand(left);
2198 Immediate immediate = ToImmediate(LConstantOperand::cast(instr->right()),
2199 instr->hydrogen()->representation());
2200 __ cmp(left_op, immediate);
2201 __ j(condition, &return_left, Label::kNear);
2202 __ mov(left_op, immediate);
2204 Register left_reg = ToRegister(left);
2205 Operand right_op = ToOperand(right);
2206 __ cmp(left_reg, right_op);
2207 __ j(condition, &return_left, Label::kNear);
2208 __ mov(left_reg, right_op);
2210 __ bind(&return_left);
2212 DCHECK(instr->hydrogen()->representation().IsDouble());
2213 Label check_nan_left, check_zero, return_left, return_right;
2214 Condition condition = (operation == HMathMinMax::kMathMin) ? below : above;
2215 X87Register left_reg = ToX87Register(left);
2216 X87Register right_reg = ToX87Register(right);
2218 X87PrepareBinaryOp(left_reg, right_reg, ToX87Register(instr->result()));
2222 __ j(parity_even, &check_nan_left, Label::kNear); // At least one NaN.
2223 __ j(equal, &check_zero, Label::kNear); // left == right.
2224 __ j(condition, &return_left, Label::kNear);
2225 __ jmp(&return_right, Label::kNear);
2227 __ bind(&check_zero);
2231 __ j(not_equal, &return_left, Label::kNear); // left == right != 0.
2232 // At this point, both left and right are either 0 or -0.
2233 if (operation == HMathMinMax::kMathMin) {
2234 // Push st0 and st1 to stack, then pop them to temp registers and OR them,
2236 Register scratch_reg = ToRegister(instr->temp());
2239 __ sub(esp, Immediate(2 * kPointerSize));
2240 __ fstp_s(MemOperand(esp, 0));
2241 __ fstp_s(MemOperand(esp, kPointerSize));
2242 __ pop(scratch_reg);
2243 __ xor_(MemOperand(esp, 0), scratch_reg);
2244 X87Mov(left_reg, MemOperand(esp, 0), kX87FloatOperand);
2245 __ pop(scratch_reg); // restore esp
2247 // Since we operate on +0 and/or -0, addsd and andsd have the same effect.
2251 __ jmp(&return_left, Label::kNear);
2253 __ bind(&check_nan_left);
2256 __ FCmp(); // NaN check.
2257 __ j(parity_even, &return_left, Label::kNear); // left == NaN.
2259 __ bind(&return_right);
2261 X87Mov(left_reg, right_reg);
2263 __ bind(&return_left);
2268 void LCodeGen::DoArithmeticD(LArithmeticD* instr) {
2269 X87Register left = ToX87Register(instr->left());
2270 X87Register right = ToX87Register(instr->right());
2271 X87Register result = ToX87Register(instr->result());
2272 if (instr->op() != Token::MOD) {
2273 X87PrepareBinaryOp(left, right, result);
2275 switch (instr->op()) {
2289 // Pass two doubles as arguments on the stack.
2290 __ PrepareCallCFunction(4, eax);
2291 X87Mov(Operand(esp, 1 * kDoubleSize), right);
2292 X87Mov(Operand(esp, 0), left);
2294 DCHECK(left.is(result));
2295 X87PrepareToWrite(result);
2297 ExternalReference::mod_two_doubles_operation(isolate()),
2300 // Return value is in st(0) on ia32.
2301 X87CommitWrite(result);
2309 // Only always explicitly storing to memory to force the round-down for double
2311 __ lea(esp, Operand(esp, -kDoubleSize));
2312 __ fstp_d(Operand(esp, 0));
2313 __ fld_d(Operand(esp, 0));
2314 __ lea(esp, Operand(esp, kDoubleSize));
2318 void LCodeGen::DoArithmeticT(LArithmeticT* instr) {
2319 DCHECK(ToRegister(instr->context()).is(esi));
2320 DCHECK(ToRegister(instr->left()).is(edx));
2321 DCHECK(ToRegister(instr->right()).is(eax));
2322 DCHECK(ToRegister(instr->result()).is(eax));
2325 CodeFactory::BinaryOpIC(isolate(), instr->op(), NO_OVERWRITE).code();
2326 CallCode(code, RelocInfo::CODE_TARGET, instr);
2330 template<class InstrType>
2331 void LCodeGen::EmitBranch(InstrType instr, Condition cc) {
2332 int left_block = instr->TrueDestination(chunk_);
2333 int right_block = instr->FalseDestination(chunk_);
2335 int next_block = GetNextEmittedBlock();
2337 if (right_block == left_block || cc == no_condition) {
2338 EmitGoto(left_block);
2339 } else if (left_block == next_block) {
2340 __ j(NegateCondition(cc), chunk_->GetAssemblyLabel(right_block));
2341 } else if (right_block == next_block) {
2342 __ j(cc, chunk_->GetAssemblyLabel(left_block));
2344 __ j(cc, chunk_->GetAssemblyLabel(left_block));
2345 __ jmp(chunk_->GetAssemblyLabel(right_block));
2350 template<class InstrType>
2351 void LCodeGen::EmitFalseBranch(InstrType instr, Condition cc) {
2352 int false_block = instr->FalseDestination(chunk_);
2353 if (cc == no_condition) {
2354 __ jmp(chunk_->GetAssemblyLabel(false_block));
2356 __ j(cc, chunk_->GetAssemblyLabel(false_block));
2361 void LCodeGen::DoBranch(LBranch* instr) {
2362 Representation r = instr->hydrogen()->value()->representation();
2363 if (r.IsSmiOrInteger32()) {
2364 Register reg = ToRegister(instr->value());
2365 __ test(reg, Operand(reg));
2366 EmitBranch(instr, not_zero);
2367 } else if (r.IsDouble()) {
2368 X87Register reg = ToX87Register(instr->value());
2369 X87LoadForUsage(reg);
2372 EmitBranch(instr, not_zero);
2374 DCHECK(r.IsTagged());
2375 Register reg = ToRegister(instr->value());
2376 HType type = instr->hydrogen()->value()->type();
2377 if (type.IsBoolean()) {
2378 DCHECK(!info()->IsStub());
2379 __ cmp(reg, factory()->true_value());
2380 EmitBranch(instr, equal);
2381 } else if (type.IsSmi()) {
2382 DCHECK(!info()->IsStub());
2383 __ test(reg, Operand(reg));
2384 EmitBranch(instr, not_equal);
2385 } else if (type.IsJSArray()) {
2386 DCHECK(!info()->IsStub());
2387 EmitBranch(instr, no_condition);
2388 } else if (type.IsHeapNumber()) {
2390 } else if (type.IsString()) {
2391 DCHECK(!info()->IsStub());
2392 __ cmp(FieldOperand(reg, String::kLengthOffset), Immediate(0));
2393 EmitBranch(instr, not_equal);
2395 ToBooleanStub::Types expected = instr->hydrogen()->expected_input_types();
2396 if (expected.IsEmpty()) expected = ToBooleanStub::Types::Generic();
2398 if (expected.Contains(ToBooleanStub::UNDEFINED)) {
2399 // undefined -> false.
2400 __ cmp(reg, factory()->undefined_value());
2401 __ j(equal, instr->FalseLabel(chunk_));
2403 if (expected.Contains(ToBooleanStub::BOOLEAN)) {
2405 __ cmp(reg, factory()->true_value());
2406 __ j(equal, instr->TrueLabel(chunk_));
2408 __ cmp(reg, factory()->false_value());
2409 __ j(equal, instr->FalseLabel(chunk_));
2411 if (expected.Contains(ToBooleanStub::NULL_TYPE)) {
2413 __ cmp(reg, factory()->null_value());
2414 __ j(equal, instr->FalseLabel(chunk_));
2417 if (expected.Contains(ToBooleanStub::SMI)) {
2418 // Smis: 0 -> false, all other -> true.
2419 __ test(reg, Operand(reg));
2420 __ j(equal, instr->FalseLabel(chunk_));
2421 __ JumpIfSmi(reg, instr->TrueLabel(chunk_));
2422 } else if (expected.NeedsMap()) {
2423 // If we need a map later and have a Smi -> deopt.
2424 __ test(reg, Immediate(kSmiTagMask));
2425 DeoptimizeIf(zero, instr, "Smi");
2428 Register map = no_reg; // Keep the compiler happy.
2429 if (expected.NeedsMap()) {
2430 map = ToRegister(instr->temp());
2431 DCHECK(!map.is(reg));
2432 __ mov(map, FieldOperand(reg, HeapObject::kMapOffset));
2434 if (expected.CanBeUndetectable()) {
2435 // Undetectable -> false.
2436 __ test_b(FieldOperand(map, Map::kBitFieldOffset),
2437 1 << Map::kIsUndetectable);
2438 __ j(not_zero, instr->FalseLabel(chunk_));
2442 if (expected.Contains(ToBooleanStub::SPEC_OBJECT)) {
2443 // spec object -> true.
2444 __ CmpInstanceType(map, FIRST_SPEC_OBJECT_TYPE);
2445 __ j(above_equal, instr->TrueLabel(chunk_));
2448 if (expected.Contains(ToBooleanStub::STRING)) {
2449 // String value -> false iff empty.
2451 __ CmpInstanceType(map, FIRST_NONSTRING_TYPE);
2452 __ j(above_equal, ¬_string, Label::kNear);
2453 __ cmp(FieldOperand(reg, String::kLengthOffset), Immediate(0));
2454 __ j(not_zero, instr->TrueLabel(chunk_));
2455 __ jmp(instr->FalseLabel(chunk_));
2456 __ bind(¬_string);
2459 if (expected.Contains(ToBooleanStub::SYMBOL)) {
2460 // Symbol value -> true.
2461 __ CmpInstanceType(map, SYMBOL_TYPE);
2462 __ j(equal, instr->TrueLabel(chunk_));
2465 if (expected.Contains(ToBooleanStub::HEAP_NUMBER)) {
2466 // heap number -> false iff +0, -0, or NaN.
2467 Label not_heap_number;
2468 __ cmp(FieldOperand(reg, HeapObject::kMapOffset),
2469 factory()->heap_number_map());
2470 __ j(not_equal, ¬_heap_number, Label::kNear);
2472 __ fld_d(FieldOperand(reg, HeapNumber::kValueOffset));
2474 __ j(zero, instr->FalseLabel(chunk_));
2475 __ jmp(instr->TrueLabel(chunk_));
2476 __ bind(¬_heap_number);
2479 if (!expected.IsGeneric()) {
2480 // We've seen something for the first time -> deopt.
2481 // This can only happen if we are not generic already.
2482 DeoptimizeIf(no_condition, instr, "unexpected object");
2489 void LCodeGen::EmitGoto(int block) {
2490 if (!IsNextEmittedBlock(block)) {
2491 __ jmp(chunk_->GetAssemblyLabel(LookupDestination(block)));
2496 void LCodeGen::DoClobberDoubles(LClobberDoubles* instr) {
2500 void LCodeGen::DoGoto(LGoto* instr) {
2501 EmitGoto(instr->block_id());
2505 Condition LCodeGen::TokenToCondition(Token::Value op, bool is_unsigned) {
2506 Condition cond = no_condition;
2509 case Token::EQ_STRICT:
2513 case Token::NE_STRICT:
2517 cond = is_unsigned ? below : less;
2520 cond = is_unsigned ? above : greater;
2523 cond = is_unsigned ? below_equal : less_equal;
2526 cond = is_unsigned ? above_equal : greater_equal;
2529 case Token::INSTANCEOF:
2537 void LCodeGen::DoCompareNumericAndBranch(LCompareNumericAndBranch* instr) {
2538 LOperand* left = instr->left();
2539 LOperand* right = instr->right();
2541 instr->is_double() ||
2542 instr->hydrogen()->left()->CheckFlag(HInstruction::kUint32) ||
2543 instr->hydrogen()->right()->CheckFlag(HInstruction::kUint32);
2544 Condition cc = TokenToCondition(instr->op(), is_unsigned);
2546 if (left->IsConstantOperand() && right->IsConstantOperand()) {
2547 // We can statically evaluate the comparison.
2548 double left_val = ToDouble(LConstantOperand::cast(left));
2549 double right_val = ToDouble(LConstantOperand::cast(right));
2550 int next_block = EvalComparison(instr->op(), left_val, right_val) ?
2551 instr->TrueDestination(chunk_) : instr->FalseDestination(chunk_);
2552 EmitGoto(next_block);
2554 if (instr->is_double()) {
2555 X87LoadForUsage(ToX87Register(right), ToX87Register(left));
2557 // Don't base result on EFLAGS when a NaN is involved. Instead
2558 // jump to the false block.
2559 __ j(parity_even, instr->FalseLabel(chunk_));
2561 if (right->IsConstantOperand()) {
2562 __ cmp(ToOperand(left),
2563 ToImmediate(right, instr->hydrogen()->representation()));
2564 } else if (left->IsConstantOperand()) {
2565 __ cmp(ToOperand(right),
2566 ToImmediate(left, instr->hydrogen()->representation()));
2567 // We commuted the operands, so commute the condition.
2568 cc = CommuteCondition(cc);
2570 __ cmp(ToRegister(left), ToOperand(right));
2573 EmitBranch(instr, cc);
2578 void LCodeGen::DoCmpObjectEqAndBranch(LCmpObjectEqAndBranch* instr) {
2579 Register left = ToRegister(instr->left());
2581 if (instr->right()->IsConstantOperand()) {
2582 Handle<Object> right = ToHandle(LConstantOperand::cast(instr->right()));
2583 __ CmpObject(left, right);
2585 Operand right = ToOperand(instr->right());
2586 __ cmp(left, right);
2588 EmitBranch(instr, equal);
2592 void LCodeGen::DoCmpHoleAndBranch(LCmpHoleAndBranch* instr) {
2593 if (instr->hydrogen()->representation().IsTagged()) {
2594 Register input_reg = ToRegister(instr->object());
2595 __ cmp(input_reg, factory()->the_hole_value());
2596 EmitBranch(instr, equal);
2600 // Put the value to the top of stack
2601 X87Register src = ToX87Register(instr->object());
2602 X87LoadForUsage(src);
2607 __ j(parity_even, &ok, Label::kNear);
2609 EmitFalseBranch(instr, no_condition);
2613 __ sub(esp, Immediate(kDoubleSize));
2614 __ fstp_d(MemOperand(esp, 0));
2616 __ add(esp, Immediate(kDoubleSize));
2617 int offset = sizeof(kHoleNanUpper32);
2618 __ cmp(MemOperand(esp, -offset), Immediate(kHoleNanUpper32));
2619 EmitBranch(instr, equal);
2623 void LCodeGen::DoCompareMinusZeroAndBranch(LCompareMinusZeroAndBranch* instr) {
2624 Representation rep = instr->hydrogen()->value()->representation();
2625 DCHECK(!rep.IsInteger32());
2627 if (rep.IsDouble()) {
2628 X87Register input = ToX87Register(instr->value());
2629 X87LoadForUsage(input);
2631 EmitBranch(instr, equal);
2633 Register value = ToRegister(instr->value());
2634 Handle<Map> map = masm()->isolate()->factory()->heap_number_map();
2635 __ CheckMap(value, map, instr->FalseLabel(chunk()), DO_SMI_CHECK);
2636 __ cmp(FieldOperand(value, HeapNumber::kExponentOffset),
2638 EmitFalseBranch(instr, no_overflow);
2639 __ cmp(FieldOperand(value, HeapNumber::kMantissaOffset),
2640 Immediate(0x00000000));
2641 EmitBranch(instr, equal);
2646 Condition LCodeGen::EmitIsObject(Register input,
2648 Label* is_not_object,
2650 __ JumpIfSmi(input, is_not_object);
2652 __ cmp(input, isolate()->factory()->null_value());
2653 __ j(equal, is_object);
2655 __ mov(temp1, FieldOperand(input, HeapObject::kMapOffset));
2656 // Undetectable objects behave like undefined.
2657 __ test_b(FieldOperand(temp1, Map::kBitFieldOffset),
2658 1 << Map::kIsUndetectable);
2659 __ j(not_zero, is_not_object);
2661 __ movzx_b(temp1, FieldOperand(temp1, Map::kInstanceTypeOffset));
2662 __ cmp(temp1, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE);
2663 __ j(below, is_not_object);
2664 __ cmp(temp1, LAST_NONCALLABLE_SPEC_OBJECT_TYPE);
2669 void LCodeGen::DoIsObjectAndBranch(LIsObjectAndBranch* instr) {
2670 Register reg = ToRegister(instr->value());
2671 Register temp = ToRegister(instr->temp());
2673 Condition true_cond = EmitIsObject(
2674 reg, temp, instr->FalseLabel(chunk_), instr->TrueLabel(chunk_));
2676 EmitBranch(instr, true_cond);
2680 Condition LCodeGen::EmitIsString(Register input,
2682 Label* is_not_string,
2683 SmiCheck check_needed = INLINE_SMI_CHECK) {
2684 if (check_needed == INLINE_SMI_CHECK) {
2685 __ JumpIfSmi(input, is_not_string);
2688 Condition cond = masm_->IsObjectStringType(input, temp1, temp1);
2694 void LCodeGen::DoIsStringAndBranch(LIsStringAndBranch* instr) {
2695 Register reg = ToRegister(instr->value());
2696 Register temp = ToRegister(instr->temp());
2698 SmiCheck check_needed =
2699 instr->hydrogen()->value()->type().IsHeapObject()
2700 ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
2702 Condition true_cond = EmitIsString(
2703 reg, temp, instr->FalseLabel(chunk_), check_needed);
2705 EmitBranch(instr, true_cond);
2709 void LCodeGen::DoIsSmiAndBranch(LIsSmiAndBranch* instr) {
2710 Operand input = ToOperand(instr->value());
2712 __ test(input, Immediate(kSmiTagMask));
2713 EmitBranch(instr, zero);
2717 void LCodeGen::DoIsUndetectableAndBranch(LIsUndetectableAndBranch* instr) {
2718 Register input = ToRegister(instr->value());
2719 Register temp = ToRegister(instr->temp());
2721 if (!instr->hydrogen()->value()->type().IsHeapObject()) {
2722 STATIC_ASSERT(kSmiTag == 0);
2723 __ JumpIfSmi(input, instr->FalseLabel(chunk_));
2725 __ mov(temp, FieldOperand(input, HeapObject::kMapOffset));
2726 __ test_b(FieldOperand(temp, Map::kBitFieldOffset),
2727 1 << Map::kIsUndetectable);
2728 EmitBranch(instr, not_zero);
2732 static Condition ComputeCompareCondition(Token::Value op) {
2734 case Token::EQ_STRICT:
2744 return greater_equal;
2747 return no_condition;
2752 void LCodeGen::DoStringCompareAndBranch(LStringCompareAndBranch* instr) {
2753 Token::Value op = instr->op();
2755 Handle<Code> ic = CodeFactory::CompareIC(isolate(), op).code();
2756 CallCode(ic, RelocInfo::CODE_TARGET, instr);
2758 Condition condition = ComputeCompareCondition(op);
2759 __ test(eax, Operand(eax));
2761 EmitBranch(instr, condition);
2765 static InstanceType TestType(HHasInstanceTypeAndBranch* instr) {
2766 InstanceType from = instr->from();
2767 InstanceType to = instr->to();
2768 if (from == FIRST_TYPE) return to;
2769 DCHECK(from == to || to == LAST_TYPE);
2774 static Condition BranchCondition(HHasInstanceTypeAndBranch* instr) {
2775 InstanceType from = instr->from();
2776 InstanceType to = instr->to();
2777 if (from == to) return equal;
2778 if (to == LAST_TYPE) return above_equal;
2779 if (from == FIRST_TYPE) return below_equal;
2785 void LCodeGen::DoHasInstanceTypeAndBranch(LHasInstanceTypeAndBranch* instr) {
2786 Register input = ToRegister(instr->value());
2787 Register temp = ToRegister(instr->temp());
2789 if (!instr->hydrogen()->value()->type().IsHeapObject()) {
2790 __ JumpIfSmi(input, instr->FalseLabel(chunk_));
2793 __ CmpObjectType(input, TestType(instr->hydrogen()), temp);
2794 EmitBranch(instr, BranchCondition(instr->hydrogen()));
2798 void LCodeGen::DoGetCachedArrayIndex(LGetCachedArrayIndex* instr) {
2799 Register input = ToRegister(instr->value());
2800 Register result = ToRegister(instr->result());
2802 __ AssertString(input);
2804 __ mov(result, FieldOperand(input, String::kHashFieldOffset));
2805 __ IndexFromHash(result, result);
2809 void LCodeGen::DoHasCachedArrayIndexAndBranch(
2810 LHasCachedArrayIndexAndBranch* instr) {
2811 Register input = ToRegister(instr->value());
2813 __ test(FieldOperand(input, String::kHashFieldOffset),
2814 Immediate(String::kContainsCachedArrayIndexMask));
2815 EmitBranch(instr, equal);
2819 // Branches to a label or falls through with the answer in the z flag. Trashes
2820 // the temp registers, but not the input.
2821 void LCodeGen::EmitClassOfTest(Label* is_true,
2823 Handle<String>class_name,
2827 DCHECK(!input.is(temp));
2828 DCHECK(!input.is(temp2));
2829 DCHECK(!temp.is(temp2));
2830 __ JumpIfSmi(input, is_false);
2832 if (String::Equals(isolate()->factory()->Function_string(), class_name)) {
2833 // Assuming the following assertions, we can use the same compares to test
2834 // for both being a function type and being in the object type range.
2835 STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
2836 STATIC_ASSERT(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE ==
2837 FIRST_SPEC_OBJECT_TYPE + 1);
2838 STATIC_ASSERT(LAST_NONCALLABLE_SPEC_OBJECT_TYPE ==
2839 LAST_SPEC_OBJECT_TYPE - 1);
2840 STATIC_ASSERT(LAST_SPEC_OBJECT_TYPE == LAST_TYPE);
2841 __ CmpObjectType(input, FIRST_SPEC_OBJECT_TYPE, temp);
2842 __ j(below, is_false);
2843 __ j(equal, is_true);
2844 __ CmpInstanceType(temp, LAST_SPEC_OBJECT_TYPE);
2845 __ j(equal, is_true);
2847 // Faster code path to avoid two compares: subtract lower bound from the
2848 // actual type and do a signed compare with the width of the type range.
2849 __ mov(temp, FieldOperand(input, HeapObject::kMapOffset));
2850 __ movzx_b(temp2, FieldOperand(temp, Map::kInstanceTypeOffset));
2851 __ sub(Operand(temp2), Immediate(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE));
2852 __ cmp(Operand(temp2), Immediate(LAST_NONCALLABLE_SPEC_OBJECT_TYPE -
2853 FIRST_NONCALLABLE_SPEC_OBJECT_TYPE));
2854 __ j(above, is_false);
2857 // Now we are in the FIRST-LAST_NONCALLABLE_SPEC_OBJECT_TYPE range.
2858 // Check if the constructor in the map is a function.
2859 __ mov(temp, FieldOperand(temp, Map::kConstructorOffset));
2860 // Objects with a non-function constructor have class 'Object'.
2861 __ CmpObjectType(temp, JS_FUNCTION_TYPE, temp2);
2862 if (String::Equals(class_name, isolate()->factory()->Object_string())) {
2863 __ j(not_equal, is_true);
2865 __ j(not_equal, is_false);
2868 // temp now contains the constructor function. Grab the
2869 // instance class name from there.
2870 __ mov(temp, FieldOperand(temp, JSFunction::kSharedFunctionInfoOffset));
2871 __ mov(temp, FieldOperand(temp,
2872 SharedFunctionInfo::kInstanceClassNameOffset));
2873 // The class name we are testing against is internalized since it's a literal.
2874 // The name in the constructor is internalized because of the way the context
2875 // is booted. This routine isn't expected to work for random API-created
2876 // classes and it doesn't have to because you can't access it with natives
2877 // syntax. Since both sides are internalized it is sufficient to use an
2878 // identity comparison.
2879 __ cmp(temp, class_name);
2880 // End with the answer in the z flag.
2884 void LCodeGen::DoClassOfTestAndBranch(LClassOfTestAndBranch* instr) {
2885 Register input = ToRegister(instr->value());
2886 Register temp = ToRegister(instr->temp());
2887 Register temp2 = ToRegister(instr->temp2());
2889 Handle<String> class_name = instr->hydrogen()->class_name();
2891 EmitClassOfTest(instr->TrueLabel(chunk_), instr->FalseLabel(chunk_),
2892 class_name, input, temp, temp2);
2894 EmitBranch(instr, equal);
2898 void LCodeGen::DoCmpMapAndBranch(LCmpMapAndBranch* instr) {
2899 Register reg = ToRegister(instr->value());
2900 __ cmp(FieldOperand(reg, HeapObject::kMapOffset), instr->map());
2901 EmitBranch(instr, equal);
2905 void LCodeGen::DoInstanceOf(LInstanceOf* instr) {
2906 // Object and function are in fixed registers defined by the stub.
2907 DCHECK(ToRegister(instr->context()).is(esi));
2908 InstanceofStub stub(isolate(), InstanceofStub::kArgsInRegisters);
2909 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
2911 Label true_value, done;
2912 __ test(eax, Operand(eax));
2913 __ j(zero, &true_value, Label::kNear);
2914 __ mov(ToRegister(instr->result()), factory()->false_value());
2915 __ jmp(&done, Label::kNear);
2916 __ bind(&true_value);
2917 __ mov(ToRegister(instr->result()), factory()->true_value());
2922 void LCodeGen::DoInstanceOfKnownGlobal(LInstanceOfKnownGlobal* instr) {
2923 class DeferredInstanceOfKnownGlobal FINAL : public LDeferredCode {
2925 DeferredInstanceOfKnownGlobal(LCodeGen* codegen,
2926 LInstanceOfKnownGlobal* instr,
2927 const X87Stack& x87_stack)
2928 : LDeferredCode(codegen, x87_stack), instr_(instr) { }
2929 virtual void Generate() OVERRIDE {
2930 codegen()->DoDeferredInstanceOfKnownGlobal(instr_, &map_check_);
2932 virtual LInstruction* instr() OVERRIDE { return instr_; }
2933 Label* map_check() { return &map_check_; }
2935 LInstanceOfKnownGlobal* instr_;
2939 DeferredInstanceOfKnownGlobal* deferred;
2940 deferred = new(zone()) DeferredInstanceOfKnownGlobal(this, instr, x87_stack_);
2942 Label done, false_result;
2943 Register object = ToRegister(instr->value());
2944 Register temp = ToRegister(instr->temp());
2946 // A Smi is not an instance of anything.
2947 __ JumpIfSmi(object, &false_result, Label::kNear);
2949 // This is the inlined call site instanceof cache. The two occurences of the
2950 // hole value will be patched to the last map/result pair generated by the
2953 Register map = ToRegister(instr->temp());
2954 __ mov(map, FieldOperand(object, HeapObject::kMapOffset));
2955 __ bind(deferred->map_check()); // Label for calculating code patching.
2956 Handle<Cell> cache_cell = factory()->NewCell(factory()->the_hole_value());
2957 __ cmp(map, Operand::ForCell(cache_cell)); // Patched to cached map.
2958 __ j(not_equal, &cache_miss, Label::kNear);
2959 __ mov(eax, factory()->the_hole_value()); // Patched to either true or false.
2960 __ jmp(&done, Label::kNear);
2962 // The inlined call site cache did not match. Check for null and string
2963 // before calling the deferred code.
2964 __ bind(&cache_miss);
2965 // Null is not an instance of anything.
2966 __ cmp(object, factory()->null_value());
2967 __ j(equal, &false_result, Label::kNear);
2969 // String values are not instances of anything.
2970 Condition is_string = masm_->IsObjectStringType(object, temp, temp);
2971 __ j(is_string, &false_result, Label::kNear);
2973 // Go to the deferred code.
2974 __ jmp(deferred->entry());
2976 __ bind(&false_result);
2977 __ mov(ToRegister(instr->result()), factory()->false_value());
2979 // Here result has either true or false. Deferred code also produces true or
2981 __ bind(deferred->exit());
2986 void LCodeGen::DoDeferredInstanceOfKnownGlobal(LInstanceOfKnownGlobal* instr,
2988 PushSafepointRegistersScope scope(this);
2990 InstanceofStub::Flags flags = InstanceofStub::kNoFlags;
2991 flags = static_cast<InstanceofStub::Flags>(
2992 flags | InstanceofStub::kArgsInRegisters);
2993 flags = static_cast<InstanceofStub::Flags>(
2994 flags | InstanceofStub::kCallSiteInlineCheck);
2995 flags = static_cast<InstanceofStub::Flags>(
2996 flags | InstanceofStub::kReturnTrueFalseObject);
2997 InstanceofStub stub(isolate(), flags);
2999 // Get the temp register reserved by the instruction. This needs to be a
3000 // register which is pushed last by PushSafepointRegisters as top of the
3001 // stack is used to pass the offset to the location of the map check to
3003 Register temp = ToRegister(instr->temp());
3004 DCHECK(MacroAssembler::SafepointRegisterStackIndex(temp) == 0);
3005 __ LoadHeapObject(InstanceofStub::right(), instr->function());
3006 static const int kAdditionalDelta = 13;
3007 int delta = masm_->SizeOfCodeGeneratedSince(map_check) + kAdditionalDelta;
3008 __ mov(temp, Immediate(delta));
3009 __ StoreToSafepointRegisterSlot(temp, temp);
3010 CallCodeGeneric(stub.GetCode(),
3011 RelocInfo::CODE_TARGET,
3013 RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
3014 // Get the deoptimization index of the LLazyBailout-environment that
3015 // corresponds to this instruction.
3016 LEnvironment* env = instr->GetDeferredLazyDeoptimizationEnvironment();
3017 safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
3019 // Put the result value into the eax slot and restore all registers.
3020 __ StoreToSafepointRegisterSlot(eax, eax);
3024 void LCodeGen::DoCmpT(LCmpT* instr) {
3025 Token::Value op = instr->op();
3027 Handle<Code> ic = CodeFactory::CompareIC(isolate(), op).code();
3028 CallCode(ic, RelocInfo::CODE_TARGET, instr);
3030 Condition condition = ComputeCompareCondition(op);
3031 Label true_value, done;
3032 __ test(eax, Operand(eax));
3033 __ j(condition, &true_value, Label::kNear);
3034 __ mov(ToRegister(instr->result()), factory()->false_value());
3035 __ jmp(&done, Label::kNear);
3036 __ bind(&true_value);
3037 __ mov(ToRegister(instr->result()), factory()->true_value());
3042 void LCodeGen::EmitReturn(LReturn* instr, bool dynamic_frame_alignment) {
3043 int extra_value_count = dynamic_frame_alignment ? 2 : 1;
3045 if (instr->has_constant_parameter_count()) {
3046 int parameter_count = ToInteger32(instr->constant_parameter_count());
3047 if (dynamic_frame_alignment && FLAG_debug_code) {
3049 (parameter_count + extra_value_count) * kPointerSize),
3050 Immediate(kAlignmentZapValue));
3051 __ Assert(equal, kExpectedAlignmentMarker);
3053 __ Ret((parameter_count + extra_value_count) * kPointerSize, ecx);
3055 Register reg = ToRegister(instr->parameter_count());
3056 // The argument count parameter is a smi
3058 Register return_addr_reg = reg.is(ecx) ? ebx : ecx;
3059 if (dynamic_frame_alignment && FLAG_debug_code) {
3060 DCHECK(extra_value_count == 2);
3061 __ cmp(Operand(esp, reg, times_pointer_size,
3062 extra_value_count * kPointerSize),
3063 Immediate(kAlignmentZapValue));
3064 __ Assert(equal, kExpectedAlignmentMarker);
3067 // emit code to restore stack based on instr->parameter_count()
3068 __ pop(return_addr_reg); // save return address
3069 if (dynamic_frame_alignment) {
3070 __ inc(reg); // 1 more for alignment
3072 __ shl(reg, kPointerSizeLog2);
3074 __ jmp(return_addr_reg);
3079 void LCodeGen::DoReturn(LReturn* instr) {
3080 if (FLAG_trace && info()->IsOptimizing()) {
3081 // Preserve the return value on the stack and rely on the runtime call
3082 // to return the value in the same register. We're leaving the code
3083 // managed by the register allocator and tearing down the frame, it's
3084 // safe to write to the context register.
3086 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
3087 __ CallRuntime(Runtime::kTraceExit, 1);
3089 if (dynamic_frame_alignment_) {
3090 // Fetch the state of the dynamic frame alignment.
3091 __ mov(edx, Operand(ebp,
3092 JavaScriptFrameConstants::kDynamicAlignmentStateOffset));
3094 int no_frame_start = -1;
3095 if (NeedsEagerFrame()) {
3098 no_frame_start = masm_->pc_offset();
3100 if (dynamic_frame_alignment_) {
3102 __ cmp(edx, Immediate(kNoAlignmentPadding));
3103 __ j(equal, &no_padding, Label::kNear);
3105 EmitReturn(instr, true);
3106 __ bind(&no_padding);
3109 EmitReturn(instr, false);
3110 if (no_frame_start != -1) {
3111 info()->AddNoFrameRange(no_frame_start, masm_->pc_offset());
3116 void LCodeGen::DoLoadGlobalCell(LLoadGlobalCell* instr) {
3117 Register result = ToRegister(instr->result());
3118 __ mov(result, Operand::ForCell(instr->hydrogen()->cell().handle()));
3119 if (instr->hydrogen()->RequiresHoleCheck()) {
3120 __ cmp(result, factory()->the_hole_value());
3121 DeoptimizeIf(equal, instr, "hole");
3127 void LCodeGen::EmitVectorLoadICRegisters(T* instr) {
3128 DCHECK(FLAG_vector_ics);
3129 Register vector_register = ToRegister(instr->temp_vector());
3130 DCHECK(vector_register.is(VectorLoadICDescriptor::VectorRegister()));
3131 Handle<TypeFeedbackVector> vector = instr->hydrogen()->feedback_vector();
3132 __ mov(vector_register, vector);
3133 // No need to allocate this register.
3134 DCHECK(VectorLoadICDescriptor::SlotRegister().is(eax));
3135 int index = vector->GetIndex(instr->hydrogen()->slot());
3136 __ mov(VectorLoadICDescriptor::SlotRegister(),
3137 Immediate(Smi::FromInt(index)));
3141 void LCodeGen::DoLoadGlobalGeneric(LLoadGlobalGeneric* instr) {
3142 DCHECK(ToRegister(instr->context()).is(esi));
3143 DCHECK(ToRegister(instr->global_object())
3144 .is(LoadDescriptor::ReceiverRegister()));
3145 DCHECK(ToRegister(instr->result()).is(eax));
3147 __ mov(LoadDescriptor::NameRegister(), instr->name());
3148 if (FLAG_vector_ics) {
3149 EmitVectorLoadICRegisters<LLoadGlobalGeneric>(instr);
3151 ContextualMode mode = instr->for_typeof() ? NOT_CONTEXTUAL : CONTEXTUAL;
3152 Handle<Code> ic = CodeFactory::LoadICInOptimizedCode(isolate(), mode).code();
3153 CallCode(ic, RelocInfo::CODE_TARGET, instr);
3157 void LCodeGen::DoStoreGlobalCell(LStoreGlobalCell* instr) {
3158 Register value = ToRegister(instr->value());
3159 Handle<PropertyCell> cell_handle = instr->hydrogen()->cell().handle();
3161 // If the cell we are storing to contains the hole it could have
3162 // been deleted from the property dictionary. In that case, we need
3163 // to update the property details in the property dictionary to mark
3164 // it as no longer deleted. We deoptimize in that case.
3165 if (instr->hydrogen()->RequiresHoleCheck()) {
3166 __ cmp(Operand::ForCell(cell_handle), factory()->the_hole_value());
3167 DeoptimizeIf(equal, instr, "hole");
3171 __ mov(Operand::ForCell(cell_handle), value);
3172 // Cells are always rescanned, so no write barrier here.
3176 void LCodeGen::DoLoadContextSlot(LLoadContextSlot* instr) {
3177 Register context = ToRegister(instr->context());
3178 Register result = ToRegister(instr->result());
3179 __ mov(result, ContextOperand(context, instr->slot_index()));
3181 if (instr->hydrogen()->RequiresHoleCheck()) {
3182 __ cmp(result, factory()->the_hole_value());
3183 if (instr->hydrogen()->DeoptimizesOnHole()) {
3184 DeoptimizeIf(equal, instr, "hole");
3187 __ j(not_equal, &is_not_hole, Label::kNear);
3188 __ mov(result, factory()->undefined_value());
3189 __ bind(&is_not_hole);
3195 void LCodeGen::DoStoreContextSlot(LStoreContextSlot* instr) {
3196 Register context = ToRegister(instr->context());
3197 Register value = ToRegister(instr->value());
3199 Label skip_assignment;
3201 Operand target = ContextOperand(context, instr->slot_index());
3202 if (instr->hydrogen()->RequiresHoleCheck()) {
3203 __ cmp(target, factory()->the_hole_value());
3204 if (instr->hydrogen()->DeoptimizesOnHole()) {
3205 DeoptimizeIf(equal, instr, "hole");
3207 __ j(not_equal, &skip_assignment, Label::kNear);
3211 __ mov(target, value);
3212 if (instr->hydrogen()->NeedsWriteBarrier()) {
3213 SmiCheck check_needed =
3214 instr->hydrogen()->value()->type().IsHeapObject()
3215 ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
3216 Register temp = ToRegister(instr->temp());
3217 int offset = Context::SlotOffset(instr->slot_index());
3218 __ RecordWriteContextSlot(context, offset, value, temp, kSaveFPRegs,
3219 EMIT_REMEMBERED_SET, check_needed);
3222 __ bind(&skip_assignment);
3226 void LCodeGen::DoLoadNamedField(LLoadNamedField* instr) {
3227 HObjectAccess access = instr->hydrogen()->access();
3228 int offset = access.offset();
3230 if (access.IsExternalMemory()) {
3231 Register result = ToRegister(instr->result());
3232 MemOperand operand = instr->object()->IsConstantOperand()
3233 ? MemOperand::StaticVariable(ToExternalReference(
3234 LConstantOperand::cast(instr->object())))
3235 : MemOperand(ToRegister(instr->object()), offset);
3236 __ Load(result, operand, access.representation());
3240 Register object = ToRegister(instr->object());
3241 if (instr->hydrogen()->representation().IsDouble()) {
3242 X87Mov(ToX87Register(instr->result()), FieldOperand(object, offset));
3246 Register result = ToRegister(instr->result());
3247 if (!access.IsInobject()) {
3248 __ mov(result, FieldOperand(object, JSObject::kPropertiesOffset));
3251 __ Load(result, FieldOperand(object, offset), access.representation());
3255 void LCodeGen::EmitPushTaggedOperand(LOperand* operand) {
3256 DCHECK(!operand->IsDoubleRegister());
3257 if (operand->IsConstantOperand()) {
3258 Handle<Object> object = ToHandle(LConstantOperand::cast(operand));
3259 AllowDeferredHandleDereference smi_check;
3260 if (object->IsSmi()) {
3261 __ Push(Handle<Smi>::cast(object));
3263 __ PushHeapObject(Handle<HeapObject>::cast(object));
3265 } else if (operand->IsRegister()) {
3266 __ push(ToRegister(operand));
3268 __ push(ToOperand(operand));
3273 void LCodeGen::DoLoadNamedGeneric(LLoadNamedGeneric* instr) {
3274 DCHECK(ToRegister(instr->context()).is(esi));
3275 DCHECK(ToRegister(instr->object()).is(LoadDescriptor::ReceiverRegister()));
3276 DCHECK(ToRegister(instr->result()).is(eax));
3278 __ mov(LoadDescriptor::NameRegister(), instr->name());
3279 if (FLAG_vector_ics) {
3280 EmitVectorLoadICRegisters<LLoadNamedGeneric>(instr);
3283 CodeFactory::LoadICInOptimizedCode(isolate(), NOT_CONTEXTUAL).code();
3284 CallCode(ic, RelocInfo::CODE_TARGET, instr);
3288 void LCodeGen::DoLoadFunctionPrototype(LLoadFunctionPrototype* instr) {
3289 Register function = ToRegister(instr->function());
3290 Register temp = ToRegister(instr->temp());
3291 Register result = ToRegister(instr->result());
3293 // Get the prototype or initial map from the function.
3295 FieldOperand(function, JSFunction::kPrototypeOrInitialMapOffset));
3297 // Check that the function has a prototype or an initial map.
3298 __ cmp(Operand(result), Immediate(factory()->the_hole_value()));
3299 DeoptimizeIf(equal, instr, "hole");
3301 // If the function does not have an initial map, we're done.
3303 __ CmpObjectType(result, MAP_TYPE, temp);
3304 __ j(not_equal, &done, Label::kNear);
3306 // Get the prototype from the initial map.
3307 __ mov(result, FieldOperand(result, Map::kPrototypeOffset));
3314 void LCodeGen::DoLoadRoot(LLoadRoot* instr) {
3315 Register result = ToRegister(instr->result());
3316 __ LoadRoot(result, instr->index());
3320 void LCodeGen::DoAccessArgumentsAt(LAccessArgumentsAt* instr) {
3321 Register arguments = ToRegister(instr->arguments());
3322 Register result = ToRegister(instr->result());
3323 if (instr->length()->IsConstantOperand() &&
3324 instr->index()->IsConstantOperand()) {
3325 int const_index = ToInteger32(LConstantOperand::cast(instr->index()));
3326 int const_length = ToInteger32(LConstantOperand::cast(instr->length()));
3327 int index = (const_length - const_index) + 1;
3328 __ mov(result, Operand(arguments, index * kPointerSize));
3330 Register length = ToRegister(instr->length());
3331 Operand index = ToOperand(instr->index());
3332 // There are two words between the frame pointer and the last argument.
3333 // Subtracting from length accounts for one of them add one more.
3334 __ sub(length, index);
3335 __ mov(result, Operand(arguments, length, times_4, kPointerSize));
3340 void LCodeGen::DoLoadKeyedExternalArray(LLoadKeyed* instr) {
3341 ElementsKind elements_kind = instr->elements_kind();
3342 LOperand* key = instr->key();
3343 if (!key->IsConstantOperand() &&
3344 ExternalArrayOpRequiresTemp(instr->hydrogen()->key()->representation(),
3346 __ SmiUntag(ToRegister(key));
3348 Operand operand(BuildFastArrayOperand(
3351 instr->hydrogen()->key()->representation(),
3353 instr->base_offset()));
3354 if (elements_kind == EXTERNAL_FLOAT32_ELEMENTS ||
3355 elements_kind == FLOAT32_ELEMENTS) {
3356 X87Mov(ToX87Register(instr->result()), operand, kX87FloatOperand);
3357 } else if (elements_kind == EXTERNAL_FLOAT64_ELEMENTS ||
3358 elements_kind == FLOAT64_ELEMENTS) {
3359 X87Mov(ToX87Register(instr->result()), operand);
3361 Register result(ToRegister(instr->result()));
3362 switch (elements_kind) {
3363 case EXTERNAL_INT8_ELEMENTS:
3365 __ movsx_b(result, operand);
3367 case EXTERNAL_UINT8_CLAMPED_ELEMENTS:
3368 case EXTERNAL_UINT8_ELEMENTS:
3369 case UINT8_ELEMENTS:
3370 case UINT8_CLAMPED_ELEMENTS:
3371 __ movzx_b(result, operand);
3373 case EXTERNAL_INT16_ELEMENTS:
3374 case INT16_ELEMENTS:
3375 __ movsx_w(result, operand);
3377 case EXTERNAL_UINT16_ELEMENTS:
3378 case UINT16_ELEMENTS:
3379 __ movzx_w(result, operand);
3381 case EXTERNAL_INT32_ELEMENTS:
3382 case INT32_ELEMENTS:
3383 __ mov(result, operand);
3385 case EXTERNAL_UINT32_ELEMENTS:
3386 case UINT32_ELEMENTS:
3387 __ mov(result, operand);
3388 if (!instr->hydrogen()->CheckFlag(HInstruction::kUint32)) {
3389 __ test(result, Operand(result));
3390 DeoptimizeIf(negative, instr, "negative value");
3393 case EXTERNAL_FLOAT32_ELEMENTS:
3394 case EXTERNAL_FLOAT64_ELEMENTS:
3395 case FLOAT32_ELEMENTS:
3396 case FLOAT64_ELEMENTS:
3397 case FAST_SMI_ELEMENTS:
3399 case FAST_DOUBLE_ELEMENTS:
3400 case FAST_HOLEY_SMI_ELEMENTS:
3401 case FAST_HOLEY_ELEMENTS:
3402 case FAST_HOLEY_DOUBLE_ELEMENTS:
3403 case DICTIONARY_ELEMENTS:
3404 case SLOPPY_ARGUMENTS_ELEMENTS:
3412 void LCodeGen::DoLoadKeyedFixedDoubleArray(LLoadKeyed* instr) {
3413 if (instr->hydrogen()->RequiresHoleCheck()) {
3414 Operand hole_check_operand = BuildFastArrayOperand(
3415 instr->elements(), instr->key(),
3416 instr->hydrogen()->key()->representation(),
3417 FAST_DOUBLE_ELEMENTS,
3418 instr->base_offset() + sizeof(kHoleNanLower32));
3419 __ cmp(hole_check_operand, Immediate(kHoleNanUpper32));
3420 DeoptimizeIf(equal, instr, "hole");
3423 Operand double_load_operand = BuildFastArrayOperand(
3426 instr->hydrogen()->key()->representation(),
3427 FAST_DOUBLE_ELEMENTS,
3428 instr->base_offset());
3429 X87Mov(ToX87Register(instr->result()), double_load_operand);
3433 void LCodeGen::DoLoadKeyedFixedArray(LLoadKeyed* instr) {
3434 Register result = ToRegister(instr->result());
3438 BuildFastArrayOperand(instr->elements(), instr->key(),
3439 instr->hydrogen()->key()->representation(),
3440 FAST_ELEMENTS, instr->base_offset()));
3442 // Check for the hole value.
3443 if (instr->hydrogen()->RequiresHoleCheck()) {
3444 if (IsFastSmiElementsKind(instr->hydrogen()->elements_kind())) {
3445 __ test(result, Immediate(kSmiTagMask));
3446 DeoptimizeIf(not_equal, instr, "not a Smi");
3448 __ cmp(result, factory()->the_hole_value());
3449 DeoptimizeIf(equal, instr, "hole");
3455 void LCodeGen::DoLoadKeyed(LLoadKeyed* instr) {
3456 if (instr->is_typed_elements()) {
3457 DoLoadKeyedExternalArray(instr);
3458 } else if (instr->hydrogen()->representation().IsDouble()) {
3459 DoLoadKeyedFixedDoubleArray(instr);
3461 DoLoadKeyedFixedArray(instr);
3466 Operand LCodeGen::BuildFastArrayOperand(
3467 LOperand* elements_pointer,
3469 Representation key_representation,
3470 ElementsKind elements_kind,
3471 uint32_t base_offset) {
3472 Register elements_pointer_reg = ToRegister(elements_pointer);
3473 int element_shift_size = ElementsKindToShiftSize(elements_kind);
3474 int shift_size = element_shift_size;
3475 if (key->IsConstantOperand()) {
3476 int constant_value = ToInteger32(LConstantOperand::cast(key));
3477 if (constant_value & 0xF0000000) {
3478 Abort(kArrayIndexConstantValueTooBig);
3480 return Operand(elements_pointer_reg,
3481 ((constant_value) << shift_size)
3484 // Take the tag bit into account while computing the shift size.
3485 if (key_representation.IsSmi() && (shift_size >= 1)) {
3486 shift_size -= kSmiTagSize;
3488 ScaleFactor scale_factor = static_cast<ScaleFactor>(shift_size);
3489 return Operand(elements_pointer_reg,
3497 void LCodeGen::DoLoadKeyedGeneric(LLoadKeyedGeneric* instr) {
3498 DCHECK(ToRegister(instr->context()).is(esi));
3499 DCHECK(ToRegister(instr->object()).is(LoadDescriptor::ReceiverRegister()));
3500 DCHECK(ToRegister(instr->key()).is(LoadDescriptor::NameRegister()));
3502 if (FLAG_vector_ics) {
3503 EmitVectorLoadICRegisters<LLoadKeyedGeneric>(instr);
3506 Handle<Code> ic = CodeFactory::KeyedLoadICInOptimizedCode(isolate()).code();
3507 CallCode(ic, RelocInfo::CODE_TARGET, instr);
3511 void LCodeGen::DoArgumentsElements(LArgumentsElements* instr) {
3512 Register result = ToRegister(instr->result());
3514 if (instr->hydrogen()->from_inlined()) {
3515 __ lea(result, Operand(esp, -2 * kPointerSize));
3517 // Check for arguments adapter frame.
3518 Label done, adapted;
3519 __ mov(result, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3520 __ mov(result, Operand(result, StandardFrameConstants::kContextOffset));
3521 __ cmp(Operand(result),
3522 Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
3523 __ j(equal, &adapted, Label::kNear);
3525 // No arguments adaptor frame.
3526 __ mov(result, Operand(ebp));
3527 __ jmp(&done, Label::kNear);
3529 // Arguments adaptor frame present.
3531 __ mov(result, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3533 // Result is the frame pointer for the frame if not adapted and for the real
3534 // frame below the adaptor frame if adapted.
3540 void LCodeGen::DoArgumentsLength(LArgumentsLength* instr) {
3541 Operand elem = ToOperand(instr->elements());
3542 Register result = ToRegister(instr->result());
3546 // If no arguments adaptor frame the number of arguments is fixed.
3548 __ mov(result, Immediate(scope()->num_parameters()));
3549 __ j(equal, &done, Label::kNear);
3551 // Arguments adaptor frame present. Get argument length from there.
3552 __ mov(result, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3553 __ mov(result, Operand(result,
3554 ArgumentsAdaptorFrameConstants::kLengthOffset));
3555 __ SmiUntag(result);
3557 // Argument length is in result register.
3562 void LCodeGen::DoWrapReceiver(LWrapReceiver* instr) {
3563 Register receiver = ToRegister(instr->receiver());
3564 Register function = ToRegister(instr->function());
3566 // If the receiver is null or undefined, we have to pass the global
3567 // object as a receiver to normal functions. Values have to be
3568 // passed unchanged to builtins and strict-mode functions.
3569 Label receiver_ok, global_object;
3570 Label::Distance dist = DeoptEveryNTimes() ? Label::kFar : Label::kNear;
3571 Register scratch = ToRegister(instr->temp());
3573 if (!instr->hydrogen()->known_function()) {
3574 // Do not transform the receiver to object for strict mode
3577 FieldOperand(function, JSFunction::kSharedFunctionInfoOffset));
3578 __ test_b(FieldOperand(scratch, SharedFunctionInfo::kStrictModeByteOffset),
3579 1 << SharedFunctionInfo::kStrictModeBitWithinByte);
3580 __ j(not_equal, &receiver_ok, dist);
3582 // Do not transform the receiver to object for builtins.
3583 __ test_b(FieldOperand(scratch, SharedFunctionInfo::kNativeByteOffset),
3584 1 << SharedFunctionInfo::kNativeBitWithinByte);
3585 __ j(not_equal, &receiver_ok, dist);
3588 // Normal function. Replace undefined or null with global receiver.
3589 __ cmp(receiver, factory()->null_value());
3590 __ j(equal, &global_object, Label::kNear);
3591 __ cmp(receiver, factory()->undefined_value());
3592 __ j(equal, &global_object, Label::kNear);
3594 // The receiver should be a JS object.
3595 __ test(receiver, Immediate(kSmiTagMask));
3596 DeoptimizeIf(equal, instr, "Smi");
3597 __ CmpObjectType(receiver, FIRST_SPEC_OBJECT_TYPE, scratch);
3598 DeoptimizeIf(below, instr, "not a JavaScript object");
3600 __ jmp(&receiver_ok, Label::kNear);
3601 __ bind(&global_object);
3602 __ mov(receiver, FieldOperand(function, JSFunction::kContextOffset));
3603 const int global_offset = Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX);
3604 __ mov(receiver, Operand(receiver, global_offset));
3605 const int proxy_offset = GlobalObject::kGlobalProxyOffset;
3606 __ mov(receiver, FieldOperand(receiver, proxy_offset));
3607 __ bind(&receiver_ok);
3611 void LCodeGen::DoApplyArguments(LApplyArguments* instr) {
3612 Register receiver = ToRegister(instr->receiver());
3613 Register function = ToRegister(instr->function());
3614 Register length = ToRegister(instr->length());
3615 Register elements = ToRegister(instr->elements());
3616 DCHECK(receiver.is(eax)); // Used for parameter count.
3617 DCHECK(function.is(edi)); // Required by InvokeFunction.
3618 DCHECK(ToRegister(instr->result()).is(eax));
3620 // Copy the arguments to this function possibly from the
3621 // adaptor frame below it.
3622 const uint32_t kArgumentsLimit = 1 * KB;
3623 __ cmp(length, kArgumentsLimit);
3624 DeoptimizeIf(above, instr, "too many arguments");
3627 __ mov(receiver, length);
3629 // Loop through the arguments pushing them onto the execution
3632 // length is a small non-negative integer, due to the test above.
3633 __ test(length, Operand(length));
3634 __ j(zero, &invoke, Label::kNear);
3636 __ push(Operand(elements, length, times_pointer_size, 1 * kPointerSize));
3638 __ j(not_zero, &loop);
3640 // Invoke the function.
3642 DCHECK(instr->HasPointerMap());
3643 LPointerMap* pointers = instr->pointer_map();
3644 SafepointGenerator safepoint_generator(
3645 this, pointers, Safepoint::kLazyDeopt);
3646 ParameterCount actual(eax);
3647 __ InvokeFunction(function, actual, CALL_FUNCTION, safepoint_generator);
3651 void LCodeGen::DoDebugBreak(LDebugBreak* instr) {
3656 void LCodeGen::DoPushArgument(LPushArgument* instr) {
3657 LOperand* argument = instr->value();
3658 EmitPushTaggedOperand(argument);
3662 void LCodeGen::DoDrop(LDrop* instr) {
3663 __ Drop(instr->count());
3667 void LCodeGen::DoThisFunction(LThisFunction* instr) {
3668 Register result = ToRegister(instr->result());
3669 __ mov(result, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
3673 void LCodeGen::DoContext(LContext* instr) {
3674 Register result = ToRegister(instr->result());
3675 if (info()->IsOptimizing()) {
3676 __ mov(result, Operand(ebp, StandardFrameConstants::kContextOffset));
3678 // If there is no frame, the context must be in esi.
3679 DCHECK(result.is(esi));
3684 void LCodeGen::DoDeclareGlobals(LDeclareGlobals* instr) {
3685 DCHECK(ToRegister(instr->context()).is(esi));
3686 __ push(esi); // The context is the first argument.
3687 __ push(Immediate(instr->hydrogen()->pairs()));
3688 __ push(Immediate(Smi::FromInt(instr->hydrogen()->flags())));
3689 CallRuntime(Runtime::kDeclareGlobals, 3, instr);
3693 void LCodeGen::CallKnownFunction(Handle<JSFunction> function,
3694 int formal_parameter_count,
3696 LInstruction* instr,
3697 EDIState edi_state) {
3698 bool dont_adapt_arguments =
3699 formal_parameter_count == SharedFunctionInfo::kDontAdaptArgumentsSentinel;
3700 bool can_invoke_directly =
3701 dont_adapt_arguments || formal_parameter_count == arity;
3703 if (can_invoke_directly) {
3704 if (edi_state == EDI_UNINITIALIZED) {
3705 __ LoadHeapObject(edi, function);
3709 __ mov(esi, FieldOperand(edi, JSFunction::kContextOffset));
3711 // Set eax to arguments count if adaption is not needed. Assumes that eax
3712 // is available to write to at this point.
3713 if (dont_adapt_arguments) {
3717 // Invoke function directly.
3718 if (function.is_identical_to(info()->closure())) {
3721 __ call(FieldOperand(edi, JSFunction::kCodeEntryOffset));
3723 RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
3725 // We need to adapt arguments.
3726 LPointerMap* pointers = instr->pointer_map();
3727 SafepointGenerator generator(
3728 this, pointers, Safepoint::kLazyDeopt);
3729 ParameterCount count(arity);
3730 ParameterCount expected(formal_parameter_count);
3731 __ InvokeFunction(function, expected, count, CALL_FUNCTION, generator);
3736 void LCodeGen::DoTailCallThroughMegamorphicCache(
3737 LTailCallThroughMegamorphicCache* instr) {
3738 Register receiver = ToRegister(instr->receiver());
3739 Register name = ToRegister(instr->name());
3740 DCHECK(receiver.is(LoadDescriptor::ReceiverRegister()));
3741 DCHECK(name.is(LoadDescriptor::NameRegister()));
3743 Register scratch = ebx;
3744 Register extra = eax;
3745 DCHECK(!scratch.is(receiver) && !scratch.is(name));
3746 DCHECK(!extra.is(receiver) && !extra.is(name));
3748 // Important for the tail-call.
3749 bool must_teardown_frame = NeedsEagerFrame();
3751 // The probe will tail call to a handler if found.
3752 isolate()->stub_cache()->GenerateProbe(masm(), instr->hydrogen()->flags(),
3753 must_teardown_frame, receiver, name,
3756 // Tail call to miss if we ended up here.
3757 if (must_teardown_frame) __ leave();
3758 LoadIC::GenerateMiss(masm());
3762 void LCodeGen::DoCallWithDescriptor(LCallWithDescriptor* instr) {
3763 DCHECK(ToRegister(instr->result()).is(eax));
3765 LPointerMap* pointers = instr->pointer_map();
3766 SafepointGenerator generator(this, pointers, Safepoint::kLazyDeopt);
3768 if (instr->target()->IsConstantOperand()) {
3769 LConstantOperand* target = LConstantOperand::cast(instr->target());
3770 Handle<Code> code = Handle<Code>::cast(ToHandle(target));
3771 generator.BeforeCall(__ CallSize(code, RelocInfo::CODE_TARGET));
3772 __ call(code, RelocInfo::CODE_TARGET);
3774 DCHECK(instr->target()->IsRegister());
3775 Register target = ToRegister(instr->target());
3776 generator.BeforeCall(__ CallSize(Operand(target)));
3777 __ add(target, Immediate(Code::kHeaderSize - kHeapObjectTag));
3780 generator.AfterCall();
3784 void LCodeGen::DoCallJSFunction(LCallJSFunction* instr) {
3785 DCHECK(ToRegister(instr->function()).is(edi));
3786 DCHECK(ToRegister(instr->result()).is(eax));
3788 if (instr->hydrogen()->pass_argument_count()) {
3789 __ mov(eax, instr->arity());
3793 __ mov(esi, FieldOperand(edi, JSFunction::kContextOffset));
3795 bool is_self_call = false;
3796 if (instr->hydrogen()->function()->IsConstant()) {
3797 HConstant* fun_const = HConstant::cast(instr->hydrogen()->function());
3798 Handle<JSFunction> jsfun =
3799 Handle<JSFunction>::cast(fun_const->handle(isolate()));
3800 is_self_call = jsfun.is_identical_to(info()->closure());
3806 __ call(FieldOperand(edi, JSFunction::kCodeEntryOffset));
3809 RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
3813 void LCodeGen::DoDeferredMathAbsTaggedHeapNumber(LMathAbs* instr) {
3814 Register input_reg = ToRegister(instr->value());
3815 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
3816 factory()->heap_number_map());
3817 DeoptimizeIf(not_equal, instr, "not a heap number");
3819 Label slow, allocated, done;
3820 Register tmp = input_reg.is(eax) ? ecx : eax;
3821 Register tmp2 = tmp.is(ecx) ? edx : input_reg.is(ecx) ? edx : ecx;
3823 // Preserve the value of all registers.
3824 PushSafepointRegistersScope scope(this);
3826 __ mov(tmp, FieldOperand(input_reg, HeapNumber::kExponentOffset));
3827 // Check the sign of the argument. If the argument is positive, just
3828 // return it. We do not need to patch the stack since |input| and
3829 // |result| are the same register and |input| will be restored
3830 // unchanged by popping safepoint registers.
3831 __ test(tmp, Immediate(HeapNumber::kSignMask));
3832 __ j(zero, &done, Label::kNear);
3834 __ AllocateHeapNumber(tmp, tmp2, no_reg, &slow);
3835 __ jmp(&allocated, Label::kNear);
3837 // Slow case: Call the runtime system to do the number allocation.
3839 CallRuntimeFromDeferred(Runtime::kAllocateHeapNumber, 0,
3840 instr, instr->context());
3841 // Set the pointer to the new heap number in tmp.
3842 if (!tmp.is(eax)) __ mov(tmp, eax);
3843 // Restore input_reg after call to runtime.
3844 __ LoadFromSafepointRegisterSlot(input_reg, input_reg);
3846 __ bind(&allocated);
3847 __ mov(tmp2, FieldOperand(input_reg, HeapNumber::kExponentOffset));
3848 __ and_(tmp2, ~HeapNumber::kSignMask);
3849 __ mov(FieldOperand(tmp, HeapNumber::kExponentOffset), tmp2);
3850 __ mov(tmp2, FieldOperand(input_reg, HeapNumber::kMantissaOffset));
3851 __ mov(FieldOperand(tmp, HeapNumber::kMantissaOffset), tmp2);
3852 __ StoreToSafepointRegisterSlot(input_reg, tmp);
3858 void LCodeGen::EmitIntegerMathAbs(LMathAbs* instr) {
3859 Register input_reg = ToRegister(instr->value());
3860 __ test(input_reg, Operand(input_reg));
3862 __ j(not_sign, &is_positive, Label::kNear);
3863 __ neg(input_reg); // Sets flags.
3864 DeoptimizeIf(negative, instr, "overflow");
3865 __ bind(&is_positive);
3869 void LCodeGen::DoMathAbs(LMathAbs* instr) {
3870 // Class for deferred case.
3871 class DeferredMathAbsTaggedHeapNumber FINAL : public LDeferredCode {
3873 DeferredMathAbsTaggedHeapNumber(LCodeGen* codegen,
3875 const X87Stack& x87_stack)
3876 : LDeferredCode(codegen, x87_stack), instr_(instr) { }
3877 virtual void Generate() OVERRIDE {
3878 codegen()->DoDeferredMathAbsTaggedHeapNumber(instr_);
3880 virtual LInstruction* instr() OVERRIDE { return instr_; }
3885 DCHECK(instr->value()->Equals(instr->result()));
3886 Representation r = instr->hydrogen()->value()->representation();
3889 X87Register value = ToX87Register(instr->value());
3892 } else if (r.IsSmiOrInteger32()) {
3893 EmitIntegerMathAbs(instr);
3894 } else { // Tagged case.
3895 DeferredMathAbsTaggedHeapNumber* deferred =
3896 new(zone()) DeferredMathAbsTaggedHeapNumber(this, instr, x87_stack_);
3897 Register input_reg = ToRegister(instr->value());
3899 __ JumpIfNotSmi(input_reg, deferred->entry());
3900 EmitIntegerMathAbs(instr);
3901 __ bind(deferred->exit());
3906 void LCodeGen::DoMathFloor(LMathFloor* instr) {
3907 Register output_reg = ToRegister(instr->result());
3908 X87Register input_reg = ToX87Register(instr->value());
3911 Label not_minus_zero, done;
3912 // Deoptimize on unordered.
3916 DeoptimizeIf(parity_even, instr, "NaN");
3917 __ j(below, ¬_minus_zero, Label::kNear);
3919 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3920 // Check for negative zero.
3921 __ j(not_equal, ¬_minus_zero, Label::kNear);
3925 DeoptimizeIf(not_zero, instr, "minus zero");
3926 __ Move(output_reg, Immediate(0));
3927 __ jmp(&done, Label::kFar);
3931 // rc=01B, round down.
3932 __ bind(¬_minus_zero);
3934 __ X87SetRC(0x0400);
3935 __ sub(esp, Immediate(kPointerSize));
3936 __ fist_s(Operand(esp, 0));
3939 DeoptimizeIf(equal, instr, "overflow");
3941 __ X87SetRC(0x0000);
3946 void LCodeGen::DoMathRound(LMathRound* instr) {
3947 X87Register input_reg = ToX87Register(instr->value());
3948 Register result = ToRegister(instr->result());
3950 Label below_one_half, below_minus_one_half, done;
3952 ExternalReference one_half = ExternalReference::address_of_one_half();
3953 ExternalReference minus_one_half =
3954 ExternalReference::address_of_minus_one_half();
3956 __ fld_d(Operand::StaticVariable(one_half));
3959 __ j(carry, &below_one_half);
3961 // Use rounds towards zero, since 0.5 <= x, we use floor(0.5 + x)
3963 __ fadd_d(Operand::StaticVariable(one_half));
3964 // rc=11B, round toward zero.
3965 __ X87SetRC(0x0c00);
3966 __ sub(esp, Immediate(kPointerSize));
3967 // Clear exception bits.
3969 __ fistp_s(MemOperand(esp, 0));
3973 DeoptimizeIf(equal, instr, "conversion overflow");
3975 // Restore round mode.
3976 __ X87SetRC(0x0000);
3979 __ bind(&below_one_half);
3980 __ fld_d(Operand::StaticVariable(minus_one_half));
3983 __ j(carry, &below_minus_one_half);
3984 // We return 0 for the input range [+0, 0.5[, or [-0.5, 0.5[ if
3985 // we can ignore the difference between a result of -0 and +0.
3986 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3987 // If the sign is positive, we return +0.
3990 DeoptimizeIf(not_zero, instr, "minus zero");
3992 __ Move(result, Immediate(0));
3995 __ bind(&below_minus_one_half);
3997 __ fadd_d(Operand::StaticVariable(one_half));
3998 // rc=01B, round down.
3999 __ X87SetRC(0x0400);
4000 __ sub(esp, Immediate(kPointerSize));
4001 // Clear exception bits.
4003 __ fistp_s(MemOperand(esp, 0));
4007 DeoptimizeIf(equal, instr, "conversion overflow");
4009 // Restore round mode.
4010 __ X87SetRC(0x0000);
4016 void LCodeGen::DoMathFround(LMathFround* instr) {
4017 X87Register input_reg = ToX87Register(instr->value());
4019 __ sub(esp, Immediate(kPointerSize));
4020 __ fstp_s(MemOperand(esp, 0));
4021 X87Fld(MemOperand(esp, 0), kX87FloatOperand);
4022 __ add(esp, Immediate(kPointerSize));
4026 void LCodeGen::DoMathSqrt(LMathSqrt* instr) {
4027 X87Register input = ToX87Register(instr->value());
4028 X87Register result_reg = ToX87Register(instr->result());
4029 Register temp_result = ToRegister(instr->temp1());
4030 Register temp = ToRegister(instr->temp2());
4031 Label slow, done, smi, finish;
4032 DCHECK(result_reg.is(input));
4034 // Store input into Heap number and call runtime function kMathExpRT.
4035 if (FLAG_inline_new) {
4036 __ AllocateHeapNumber(temp_result, temp, no_reg, &slow);
4037 __ jmp(&done, Label::kNear);
4040 // Slow case: Call the runtime system to do the number allocation.
4043 // TODO(3095996): Put a valid pointer value in the stack slot where the
4044 // result register is stored, as this register is in the pointer map, but
4045 // contains an integer value.
4046 __ Move(temp_result, Immediate(0));
4048 // Preserve the value of all registers.
4049 PushSafepointRegistersScope scope(this);
4051 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4052 __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
4053 RecordSafepointWithRegisters(
4054 instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
4055 __ StoreToSafepointRegisterSlot(temp_result, eax);
4058 X87LoadForUsage(input);
4059 __ fstp_d(FieldOperand(temp_result, HeapNumber::kValueOffset));
4062 // Preserve the value of all registers.
4063 PushSafepointRegistersScope scope(this);
4065 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4066 __ push(temp_result);
4067 __ CallRuntimeSaveDoubles(Runtime::kMathSqrtRT);
4068 RecordSafepointWithRegisters(instr->pointer_map(), 1,
4069 Safepoint::kNoLazyDeopt);
4070 __ StoreToSafepointRegisterSlot(temp_result, eax);
4072 X87PrepareToWrite(result_reg);
4073 // return value of MathExpRT is Smi or Heap Number.
4074 __ JumpIfSmi(temp_result, &smi);
4075 // Heap number(double)
4076 __ fld_d(FieldOperand(temp_result, HeapNumber::kValueOffset));
4080 __ SmiUntag(temp_result);
4081 __ push(temp_result);
4082 __ fild_s(MemOperand(esp, 0));
4083 __ pop(temp_result);
4085 X87CommitWrite(result_reg);
4089 void LCodeGen::DoMathPowHalf(LMathPowHalf* instr) {
4090 X87Register input_reg = ToX87Register(instr->value());
4091 DCHECK(ToX87Register(instr->result()).is(input_reg));
4093 // Note that according to ECMA-262 15.8.2.13:
4094 // Math.pow(-Infinity, 0.5) == Infinity
4095 // Math.sqrt(-Infinity) == NaN
4097 // Check base for -Infinity. C3 == 0, C2 == 1, C1 == 1 and C0 == 1
4101 __ and_(eax, Immediate(0x4700));
4102 __ cmp(eax, Immediate(0x0700));
4103 __ j(not_equal, &sqrt, Label::kNear);
4104 // If input is -Infinity, return Infinity.
4106 __ jmp(&done, Label::kNear);
4111 __ faddp(); // Convert -0 to +0.
4118 void LCodeGen::DoPower(LPower* instr) {
4119 Representation exponent_type = instr->hydrogen()->right()->representation();
4120 X87Register result = ToX87Register(instr->result());
4121 // Having marked this as a call, we can use any registers.
4122 X87Register base = ToX87Register(instr->left());
4123 ExternalReference one_half = ExternalReference::address_of_one_half();
4125 if (exponent_type.IsSmi()) {
4126 Register exponent = ToRegister(instr->right());
4127 X87LoadForUsage(base);
4128 __ SmiUntag(exponent);
4130 __ fild_s(MemOperand(esp, 0));
4132 } else if (exponent_type.IsTagged()) {
4133 Register exponent = ToRegister(instr->right());
4134 Register temp = exponent.is(ecx) ? eax : ecx;
4135 Label no_deopt, done;
4136 X87LoadForUsage(base);
4137 __ JumpIfSmi(exponent, &no_deopt);
4138 __ CmpObjectType(exponent, HEAP_NUMBER_TYPE, temp);
4139 DeoptimizeIf(not_equal, instr, "not a heap number");
4140 // Heap number(double)
4141 __ fld_d(FieldOperand(exponent, HeapNumber::kValueOffset));
4145 __ SmiUntag(exponent);
4147 __ fild_s(MemOperand(esp, 0));
4150 } else if (exponent_type.IsInteger32()) {
4151 Register exponent = ToRegister(instr->right());
4152 X87LoadForUsage(base);
4154 __ fild_s(MemOperand(esp, 0));
4157 DCHECK(exponent_type.IsDouble());
4158 X87Register exponent_double = ToX87Register(instr->right());
4159 X87LoadForUsage(base, exponent_double);
4162 // FP data stack {base, exponent(TOS)}.
4163 // Handle (exponent==+-0.5 && base == -0).
4167 X87Fld(Operand::StaticVariable(one_half), kX87DoubleOperand);
4169 __ j(parity_even, ¬_plus_0, Label::kNear); // NaN.
4170 __ j(not_equal, ¬_plus_0, Label::kNear);
4172 // FP data stack {base, exponent(TOS), zero}.
4174 __ bind(¬_plus_0);
4177 __ PrepareCallCFunction(4, eax);
4178 __ fstp_d(MemOperand(esp, kDoubleSize)); // Exponent value.
4179 __ fstp_d(MemOperand(esp, 0)); // Base value.
4180 X87PrepareToWrite(result);
4181 __ CallCFunction(ExternalReference::power_double_double_function(isolate()),
4183 // Return value is in st(0) on ia32.
4184 X87CommitWrite(result);
4189 void LCodeGen::DoMathLog(LMathLog* instr) {
4190 DCHECK(instr->value()->Equals(instr->result()));
4191 X87Register input_reg = ToX87Register(instr->value());
4194 Label positive, done, zero, nan_result;
4198 __ j(below, &nan_result, Label::kNear);
4199 __ j(equal, &zero, Label::kNear);
4207 __ jmp(&done, Label::kNear);
4209 __ bind(&nan_result);
4210 ExternalReference nan =
4211 ExternalReference::address_of_canonical_non_hole_nan();
4212 X87PrepareToWrite(input_reg);
4213 __ fld_d(Operand::StaticVariable(nan));
4214 X87CommitWrite(input_reg);
4215 __ jmp(&done, Label::kNear);
4218 ExternalReference ninf = ExternalReference::address_of_negative_infinity();
4219 X87PrepareToWrite(input_reg);
4220 __ fld_d(Operand::StaticVariable(ninf));
4221 X87CommitWrite(input_reg);
4227 void LCodeGen::DoMathClz32(LMathClz32* instr) {
4228 Register input = ToRegister(instr->value());
4229 Register result = ToRegister(instr->result());
4230 Label not_zero_input;
4231 __ bsr(result, input);
4233 __ j(not_zero, ¬_zero_input);
4234 __ Move(result, Immediate(63)); // 63^31 == 32
4236 __ bind(¬_zero_input);
4237 __ xor_(result, Immediate(31)); // for x in [0..31], 31^x == 31-x.
4241 void LCodeGen::DoMathExp(LMathExp* instr) {
4242 X87Register input = ToX87Register(instr->value());
4243 X87Register result_reg = ToX87Register(instr->result());
4244 Register temp_result = ToRegister(instr->temp1());
4245 Register temp = ToRegister(instr->temp2());
4246 Label slow, done, smi, finish;
4247 DCHECK(result_reg.is(input));
4249 // Store input into Heap number and call runtime function kMathExpRT.
4250 if (FLAG_inline_new) {
4251 __ AllocateHeapNumber(temp_result, temp, no_reg, &slow);
4252 __ jmp(&done, Label::kNear);
4255 // Slow case: Call the runtime system to do the number allocation.
4258 // TODO(3095996): Put a valid pointer value in the stack slot where the
4259 // result register is stored, as this register is in the pointer map, but
4260 // contains an integer value.
4261 __ Move(temp_result, Immediate(0));
4263 // Preserve the value of all registers.
4264 PushSafepointRegistersScope scope(this);
4266 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4267 __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
4268 RecordSafepointWithRegisters(instr->pointer_map(), 0,
4269 Safepoint::kNoLazyDeopt);
4270 __ StoreToSafepointRegisterSlot(temp_result, eax);
4273 X87LoadForUsage(input);
4274 __ fstp_d(FieldOperand(temp_result, HeapNumber::kValueOffset));
4277 // Preserve the value of all registers.
4278 PushSafepointRegistersScope scope(this);
4280 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4281 __ push(temp_result);
4282 __ CallRuntimeSaveDoubles(Runtime::kMathExpRT);
4283 RecordSafepointWithRegisters(instr->pointer_map(), 1,
4284 Safepoint::kNoLazyDeopt);
4285 __ StoreToSafepointRegisterSlot(temp_result, eax);
4287 X87PrepareToWrite(result_reg);
4288 // return value of MathExpRT is Smi or Heap Number.
4289 __ JumpIfSmi(temp_result, &smi);
4290 // Heap number(double)
4291 __ fld_d(FieldOperand(temp_result, HeapNumber::kValueOffset));
4295 __ SmiUntag(temp_result);
4296 __ push(temp_result);
4297 __ fild_s(MemOperand(esp, 0));
4298 __ pop(temp_result);
4300 X87CommitWrite(result_reg);
4304 void LCodeGen::DoInvokeFunction(LInvokeFunction* instr) {
4305 DCHECK(ToRegister(instr->context()).is(esi));
4306 DCHECK(ToRegister(instr->function()).is(edi));
4307 DCHECK(instr->HasPointerMap());
4309 Handle<JSFunction> known_function = instr->hydrogen()->known_function();
4310 if (known_function.is_null()) {
4311 LPointerMap* pointers = instr->pointer_map();
4312 SafepointGenerator generator(
4313 this, pointers, Safepoint::kLazyDeopt);
4314 ParameterCount count(instr->arity());
4315 __ InvokeFunction(edi, count, CALL_FUNCTION, generator);
4317 CallKnownFunction(known_function,
4318 instr->hydrogen()->formal_parameter_count(),
4321 EDI_CONTAINS_TARGET);
4326 void LCodeGen::DoCallFunction(LCallFunction* instr) {
4327 DCHECK(ToRegister(instr->context()).is(esi));
4328 DCHECK(ToRegister(instr->function()).is(edi));
4329 DCHECK(ToRegister(instr->result()).is(eax));
4331 int arity = instr->arity();
4332 CallFunctionStub stub(isolate(), arity, instr->hydrogen()->function_flags());
4333 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
4337 void LCodeGen::DoCallNew(LCallNew* instr) {
4338 DCHECK(ToRegister(instr->context()).is(esi));
4339 DCHECK(ToRegister(instr->constructor()).is(edi));
4340 DCHECK(ToRegister(instr->result()).is(eax));
4342 // No cell in ebx for construct type feedback in optimized code
4343 __ mov(ebx, isolate()->factory()->undefined_value());
4344 CallConstructStub stub(isolate(), NO_CALL_CONSTRUCTOR_FLAGS);
4345 __ Move(eax, Immediate(instr->arity()));
4346 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
4350 void LCodeGen::DoCallNewArray(LCallNewArray* instr) {
4351 DCHECK(ToRegister(instr->context()).is(esi));
4352 DCHECK(ToRegister(instr->constructor()).is(edi));
4353 DCHECK(ToRegister(instr->result()).is(eax));
4355 __ Move(eax, Immediate(instr->arity()));
4356 __ mov(ebx, isolate()->factory()->undefined_value());
4357 ElementsKind kind = instr->hydrogen()->elements_kind();
4358 AllocationSiteOverrideMode override_mode =
4359 (AllocationSite::GetMode(kind) == TRACK_ALLOCATION_SITE)
4360 ? DISABLE_ALLOCATION_SITES
4363 if (instr->arity() == 0) {
4364 ArrayNoArgumentConstructorStub stub(isolate(), kind, override_mode);
4365 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
4366 } else if (instr->arity() == 1) {
4368 if (IsFastPackedElementsKind(kind)) {
4370 // We might need a change here
4371 // look at the first argument
4372 __ mov(ecx, Operand(esp, 0));
4374 __ j(zero, &packed_case, Label::kNear);
4376 ElementsKind holey_kind = GetHoleyElementsKind(kind);
4377 ArraySingleArgumentConstructorStub stub(isolate(),
4380 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
4381 __ jmp(&done, Label::kNear);
4382 __ bind(&packed_case);
4385 ArraySingleArgumentConstructorStub stub(isolate(), kind, override_mode);
4386 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
4389 ArrayNArgumentsConstructorStub stub(isolate(), kind, override_mode);
4390 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
4395 void LCodeGen::DoCallRuntime(LCallRuntime* instr) {
4396 DCHECK(ToRegister(instr->context()).is(esi));
4397 CallRuntime(instr->function(), instr->arity(), instr, instr->save_doubles());
4401 void LCodeGen::DoStoreCodeEntry(LStoreCodeEntry* instr) {
4402 Register function = ToRegister(instr->function());
4403 Register code_object = ToRegister(instr->code_object());
4404 __ lea(code_object, FieldOperand(code_object, Code::kHeaderSize));
4405 __ mov(FieldOperand(function, JSFunction::kCodeEntryOffset), code_object);
4409 void LCodeGen::DoInnerAllocatedObject(LInnerAllocatedObject* instr) {
4410 Register result = ToRegister(instr->result());
4411 Register base = ToRegister(instr->base_object());
4412 if (instr->offset()->IsConstantOperand()) {
4413 LConstantOperand* offset = LConstantOperand::cast(instr->offset());
4414 __ lea(result, Operand(base, ToInteger32(offset)));
4416 Register offset = ToRegister(instr->offset());
4417 __ lea(result, Operand(base, offset, times_1, 0));
4422 void LCodeGen::DoStoreNamedField(LStoreNamedField* instr) {
4423 Representation representation = instr->hydrogen()->field_representation();
4425 HObjectAccess access = instr->hydrogen()->access();
4426 int offset = access.offset();
4428 if (access.IsExternalMemory()) {
4429 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4430 MemOperand operand = instr->object()->IsConstantOperand()
4431 ? MemOperand::StaticVariable(
4432 ToExternalReference(LConstantOperand::cast(instr->object())))
4433 : MemOperand(ToRegister(instr->object()), offset);
4434 if (instr->value()->IsConstantOperand()) {
4435 LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
4436 __ mov(operand, Immediate(ToInteger32(operand_value)));
4438 Register value = ToRegister(instr->value());
4439 __ Store(value, operand, representation);
4444 Register object = ToRegister(instr->object());
4445 __ AssertNotSmi(object);
4446 DCHECK(!representation.IsSmi() ||
4447 !instr->value()->IsConstantOperand() ||
4448 IsSmi(LConstantOperand::cast(instr->value())));
4449 if (representation.IsDouble()) {
4450 DCHECK(access.IsInobject());
4451 DCHECK(!instr->hydrogen()->has_transition());
4452 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4453 X87Register value = ToX87Register(instr->value());
4454 X87Mov(FieldOperand(object, offset), value);
4458 if (instr->hydrogen()->has_transition()) {
4459 Handle<Map> transition = instr->hydrogen()->transition_map();
4460 AddDeprecationDependency(transition);
4461 __ mov(FieldOperand(object, HeapObject::kMapOffset), transition);
4462 if (instr->hydrogen()->NeedsWriteBarrierForMap()) {
4463 Register temp = ToRegister(instr->temp());
4464 Register temp_map = ToRegister(instr->temp_map());
4465 __ mov(temp_map, transition);
4466 __ mov(FieldOperand(object, HeapObject::kMapOffset), temp_map);
4467 // Update the write barrier for the map field.
4468 __ RecordWriteForMap(object, transition, temp_map, temp, kSaveFPRegs);
4473 Register write_register = object;
4474 if (!access.IsInobject()) {
4475 write_register = ToRegister(instr->temp());
4476 __ mov(write_register, FieldOperand(object, JSObject::kPropertiesOffset));
4479 MemOperand operand = FieldOperand(write_register, offset);
4480 if (instr->value()->IsConstantOperand()) {
4481 LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
4482 if (operand_value->IsRegister()) {
4483 Register value = ToRegister(operand_value);
4484 __ Store(value, operand, representation);
4485 } else if (representation.IsInteger32()) {
4486 Immediate immediate = ToImmediate(operand_value, representation);
4487 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4488 __ mov(operand, immediate);
4490 Handle<Object> handle_value = ToHandle(operand_value);
4491 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4492 __ mov(operand, handle_value);
4495 Register value = ToRegister(instr->value());
4496 __ Store(value, operand, representation);
4499 if (instr->hydrogen()->NeedsWriteBarrier()) {
4500 Register value = ToRegister(instr->value());
4501 Register temp = access.IsInobject() ? ToRegister(instr->temp()) : object;
4502 // Update the write barrier for the object for in-object properties.
4503 __ RecordWriteField(write_register, offset, value, temp, kSaveFPRegs,
4504 EMIT_REMEMBERED_SET,
4505 instr->hydrogen()->SmiCheckForWriteBarrier(),
4506 instr->hydrogen()->PointersToHereCheckForValue());
4511 void LCodeGen::DoStoreNamedGeneric(LStoreNamedGeneric* instr) {
4512 DCHECK(ToRegister(instr->context()).is(esi));
4513 DCHECK(ToRegister(instr->object()).is(StoreDescriptor::ReceiverRegister()));
4514 DCHECK(ToRegister(instr->value()).is(StoreDescriptor::ValueRegister()));
4516 __ mov(StoreDescriptor::NameRegister(), instr->name());
4517 Handle<Code> ic = StoreIC::initialize_stub(isolate(), instr->strict_mode());
4518 CallCode(ic, RelocInfo::CODE_TARGET, instr);
4522 void LCodeGen::DoBoundsCheck(LBoundsCheck* instr) {
4523 Condition cc = instr->hydrogen()->allow_equality() ? above : above_equal;
4524 if (instr->index()->IsConstantOperand()) {
4525 __ cmp(ToOperand(instr->length()),
4526 ToImmediate(LConstantOperand::cast(instr->index()),
4527 instr->hydrogen()->length()->representation()));
4528 cc = CommuteCondition(cc);
4529 } else if (instr->length()->IsConstantOperand()) {
4530 __ cmp(ToOperand(instr->index()),
4531 ToImmediate(LConstantOperand::cast(instr->length()),
4532 instr->hydrogen()->index()->representation()));
4534 __ cmp(ToRegister(instr->index()), ToOperand(instr->length()));
4536 if (FLAG_debug_code && instr->hydrogen()->skip_check()) {
4538 __ j(NegateCondition(cc), &done, Label::kNear);
4542 DeoptimizeIf(cc, instr, "out of bounds");
4547 void LCodeGen::DoStoreKeyedExternalArray(LStoreKeyed* instr) {
4548 ElementsKind elements_kind = instr->elements_kind();
4549 LOperand* key = instr->key();
4550 if (!key->IsConstantOperand() &&
4551 ExternalArrayOpRequiresTemp(instr->hydrogen()->key()->representation(),
4553 __ SmiUntag(ToRegister(key));
4555 Operand operand(BuildFastArrayOperand(
4558 instr->hydrogen()->key()->representation(),
4560 instr->base_offset()));
4561 if (elements_kind == EXTERNAL_FLOAT32_ELEMENTS ||
4562 elements_kind == FLOAT32_ELEMENTS) {
4563 X87Mov(operand, ToX87Register(instr->value()), kX87FloatOperand);
4564 } else if (elements_kind == EXTERNAL_FLOAT64_ELEMENTS ||
4565 elements_kind == FLOAT64_ELEMENTS) {
4566 X87Mov(operand, ToX87Register(instr->value()));
4568 Register value = ToRegister(instr->value());
4569 switch (elements_kind) {
4570 case EXTERNAL_UINT8_CLAMPED_ELEMENTS:
4571 case EXTERNAL_UINT8_ELEMENTS:
4572 case EXTERNAL_INT8_ELEMENTS:
4573 case UINT8_ELEMENTS:
4575 case UINT8_CLAMPED_ELEMENTS:
4576 __ mov_b(operand, value);
4578 case EXTERNAL_INT16_ELEMENTS:
4579 case EXTERNAL_UINT16_ELEMENTS:
4580 case UINT16_ELEMENTS:
4581 case INT16_ELEMENTS:
4582 __ mov_w(operand, value);
4584 case EXTERNAL_INT32_ELEMENTS:
4585 case EXTERNAL_UINT32_ELEMENTS:
4586 case UINT32_ELEMENTS:
4587 case INT32_ELEMENTS:
4588 __ mov(operand, value);
4590 case EXTERNAL_FLOAT32_ELEMENTS:
4591 case EXTERNAL_FLOAT64_ELEMENTS:
4592 case FLOAT32_ELEMENTS:
4593 case FLOAT64_ELEMENTS:
4594 case FAST_SMI_ELEMENTS:
4596 case FAST_DOUBLE_ELEMENTS:
4597 case FAST_HOLEY_SMI_ELEMENTS:
4598 case FAST_HOLEY_ELEMENTS:
4599 case FAST_HOLEY_DOUBLE_ELEMENTS:
4600 case DICTIONARY_ELEMENTS:
4601 case SLOPPY_ARGUMENTS_ELEMENTS:
4609 void LCodeGen::DoStoreKeyedFixedDoubleArray(LStoreKeyed* instr) {
4610 ExternalReference canonical_nan_reference =
4611 ExternalReference::address_of_canonical_non_hole_nan();
4612 Operand double_store_operand = BuildFastArrayOperand(
4615 instr->hydrogen()->key()->representation(),
4616 FAST_DOUBLE_ELEMENTS,
4617 instr->base_offset());
4619 // Can't use SSE2 in the serializer
4620 if (instr->hydrogen()->IsConstantHoleStore()) {
4621 // This means we should store the (double) hole. No floating point
4622 // registers required.
4623 double nan_double = FixedDoubleArray::hole_nan_as_double();
4624 uint64_t int_val = bit_cast<uint64_t, double>(nan_double);
4625 int32_t lower = static_cast<int32_t>(int_val);
4626 int32_t upper = static_cast<int32_t>(int_val >> (kBitsPerInt));
4628 __ mov(double_store_operand, Immediate(lower));
4629 Operand double_store_operand2 = BuildFastArrayOperand(
4632 instr->hydrogen()->key()->representation(),
4633 FAST_DOUBLE_ELEMENTS,
4634 instr->base_offset() + kPointerSize);
4635 __ mov(double_store_operand2, Immediate(upper));
4637 Label no_special_nan_handling;
4638 X87Register value = ToX87Register(instr->value());
4641 if (instr->NeedsCanonicalization()) {
4646 __ j(parity_odd, &no_special_nan_handling, Label::kNear);
4647 __ sub(esp, Immediate(kDoubleSize));
4648 __ fst_d(MemOperand(esp, 0));
4649 __ cmp(MemOperand(esp, sizeof(kHoleNanLower32)),
4650 Immediate(kHoleNanUpper32));
4651 __ add(esp, Immediate(kDoubleSize));
4653 __ j(not_equal, &canonicalize, Label::kNear);
4654 __ jmp(&no_special_nan_handling, Label::kNear);
4655 __ bind(&canonicalize);
4657 __ fld_d(Operand::StaticVariable(canonical_nan_reference));
4660 __ bind(&no_special_nan_handling);
4661 __ fst_d(double_store_operand);
4666 void LCodeGen::DoStoreKeyedFixedArray(LStoreKeyed* instr) {
4667 Register elements = ToRegister(instr->elements());
4668 Register key = instr->key()->IsRegister() ? ToRegister(instr->key()) : no_reg;
4670 Operand operand = BuildFastArrayOperand(
4673 instr->hydrogen()->key()->representation(),
4675 instr->base_offset());
4676 if (instr->value()->IsRegister()) {
4677 __ mov(operand, ToRegister(instr->value()));
4679 LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
4680 if (IsSmi(operand_value)) {
4681 Immediate immediate = ToImmediate(operand_value, Representation::Smi());
4682 __ mov(operand, immediate);
4684 DCHECK(!IsInteger32(operand_value));
4685 Handle<Object> handle_value = ToHandle(operand_value);
4686 __ mov(operand, handle_value);
4690 if (instr->hydrogen()->NeedsWriteBarrier()) {
4691 DCHECK(instr->value()->IsRegister());
4692 Register value = ToRegister(instr->value());
4693 DCHECK(!instr->key()->IsConstantOperand());
4694 SmiCheck check_needed =
4695 instr->hydrogen()->value()->type().IsHeapObject()
4696 ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
4697 // Compute address of modified element and store it into key register.
4698 __ lea(key, operand);
4699 __ RecordWrite(elements, key, value, kSaveFPRegs, EMIT_REMEMBERED_SET,
4701 instr->hydrogen()->PointersToHereCheckForValue());
4706 void LCodeGen::DoStoreKeyed(LStoreKeyed* instr) {
4707 // By cases...external, fast-double, fast
4708 if (instr->is_typed_elements()) {
4709 DoStoreKeyedExternalArray(instr);
4710 } else if (instr->hydrogen()->value()->representation().IsDouble()) {
4711 DoStoreKeyedFixedDoubleArray(instr);
4713 DoStoreKeyedFixedArray(instr);
4718 void LCodeGen::DoStoreKeyedGeneric(LStoreKeyedGeneric* instr) {
4719 DCHECK(ToRegister(instr->context()).is(esi));
4720 DCHECK(ToRegister(instr->object()).is(StoreDescriptor::ReceiverRegister()));
4721 DCHECK(ToRegister(instr->key()).is(StoreDescriptor::NameRegister()));
4722 DCHECK(ToRegister(instr->value()).is(StoreDescriptor::ValueRegister()));
4725 CodeFactory::KeyedStoreIC(isolate(), instr->strict_mode()).code();
4726 CallCode(ic, RelocInfo::CODE_TARGET, instr);
4730 void LCodeGen::DoTrapAllocationMemento(LTrapAllocationMemento* instr) {
4731 Register object = ToRegister(instr->object());
4732 Register temp = ToRegister(instr->temp());
4733 Label no_memento_found;
4734 __ TestJSArrayForAllocationMemento(object, temp, &no_memento_found);
4735 DeoptimizeIf(equal, instr, "memento found");
4736 __ bind(&no_memento_found);
4740 void LCodeGen::DoTransitionElementsKind(LTransitionElementsKind* instr) {
4741 Register object_reg = ToRegister(instr->object());
4743 Handle<Map> from_map = instr->original_map();
4744 Handle<Map> to_map = instr->transitioned_map();
4745 ElementsKind from_kind = instr->from_kind();
4746 ElementsKind to_kind = instr->to_kind();
4748 Label not_applicable;
4749 bool is_simple_map_transition =
4750 IsSimpleMapChangeTransition(from_kind, to_kind);
4751 Label::Distance branch_distance =
4752 is_simple_map_transition ? Label::kNear : Label::kFar;
4753 __ cmp(FieldOperand(object_reg, HeapObject::kMapOffset), from_map);
4754 __ j(not_equal, ¬_applicable, branch_distance);
4755 if (is_simple_map_transition) {
4756 Register new_map_reg = ToRegister(instr->new_map_temp());
4757 __ mov(FieldOperand(object_reg, HeapObject::kMapOffset),
4760 DCHECK_NE(instr->temp(), NULL);
4761 __ RecordWriteForMap(object_reg, to_map, new_map_reg,
4762 ToRegister(instr->temp()), kDontSaveFPRegs);
4764 DCHECK(ToRegister(instr->context()).is(esi));
4765 DCHECK(object_reg.is(eax));
4766 PushSafepointRegistersScope scope(this);
4767 __ mov(ebx, to_map);
4768 bool is_js_array = from_map->instance_type() == JS_ARRAY_TYPE;
4769 TransitionElementsKindStub stub(isolate(), from_kind, to_kind, is_js_array);
4771 RecordSafepointWithLazyDeopt(instr,
4772 RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
4774 __ bind(¬_applicable);
4778 void LCodeGen::DoStringCharCodeAt(LStringCharCodeAt* instr) {
4779 class DeferredStringCharCodeAt FINAL : public LDeferredCode {
4781 DeferredStringCharCodeAt(LCodeGen* codegen,
4782 LStringCharCodeAt* instr,
4783 const X87Stack& x87_stack)
4784 : LDeferredCode(codegen, x87_stack), instr_(instr) { }
4785 virtual void Generate() OVERRIDE {
4786 codegen()->DoDeferredStringCharCodeAt(instr_);
4788 virtual LInstruction* instr() OVERRIDE { return instr_; }
4790 LStringCharCodeAt* instr_;
4793 DeferredStringCharCodeAt* deferred =
4794 new(zone()) DeferredStringCharCodeAt(this, instr, x87_stack_);
4796 StringCharLoadGenerator::Generate(masm(),
4798 ToRegister(instr->string()),
4799 ToRegister(instr->index()),
4800 ToRegister(instr->result()),
4802 __ bind(deferred->exit());
4806 void LCodeGen::DoDeferredStringCharCodeAt(LStringCharCodeAt* instr) {
4807 Register string = ToRegister(instr->string());
4808 Register result = ToRegister(instr->result());
4810 // TODO(3095996): Get rid of this. For now, we need to make the
4811 // result register contain a valid pointer because it is already
4812 // contained in the register pointer map.
4813 __ Move(result, Immediate(0));
4815 PushSafepointRegistersScope scope(this);
4817 // Push the index as a smi. This is safe because of the checks in
4818 // DoStringCharCodeAt above.
4819 STATIC_ASSERT(String::kMaxLength <= Smi::kMaxValue);
4820 if (instr->index()->IsConstantOperand()) {
4821 Immediate immediate = ToImmediate(LConstantOperand::cast(instr->index()),
4822 Representation::Smi());
4825 Register index = ToRegister(instr->index());
4829 CallRuntimeFromDeferred(Runtime::kStringCharCodeAtRT, 2,
4830 instr, instr->context());
4833 __ StoreToSafepointRegisterSlot(result, eax);
4837 void LCodeGen::DoStringCharFromCode(LStringCharFromCode* instr) {
4838 class DeferredStringCharFromCode FINAL : public LDeferredCode {
4840 DeferredStringCharFromCode(LCodeGen* codegen,
4841 LStringCharFromCode* instr,
4842 const X87Stack& x87_stack)
4843 : LDeferredCode(codegen, x87_stack), instr_(instr) { }
4844 virtual void Generate() OVERRIDE {
4845 codegen()->DoDeferredStringCharFromCode(instr_);
4847 virtual LInstruction* instr() OVERRIDE { return instr_; }
4849 LStringCharFromCode* instr_;
4852 DeferredStringCharFromCode* deferred =
4853 new(zone()) DeferredStringCharFromCode(this, instr, x87_stack_);
4855 DCHECK(instr->hydrogen()->value()->representation().IsInteger32());
4856 Register char_code = ToRegister(instr->char_code());
4857 Register result = ToRegister(instr->result());
4858 DCHECK(!char_code.is(result));
4860 __ cmp(char_code, String::kMaxOneByteCharCode);
4861 __ j(above, deferred->entry());
4862 __ Move(result, Immediate(factory()->single_character_string_cache()));
4863 __ mov(result, FieldOperand(result,
4864 char_code, times_pointer_size,
4865 FixedArray::kHeaderSize));
4866 __ cmp(result, factory()->undefined_value());
4867 __ j(equal, deferred->entry());
4868 __ bind(deferred->exit());
4872 void LCodeGen::DoDeferredStringCharFromCode(LStringCharFromCode* instr) {
4873 Register char_code = ToRegister(instr->char_code());
4874 Register result = ToRegister(instr->result());
4876 // TODO(3095996): Get rid of this. For now, we need to make the
4877 // result register contain a valid pointer because it is already
4878 // contained in the register pointer map.
4879 __ Move(result, Immediate(0));
4881 PushSafepointRegistersScope scope(this);
4882 __ SmiTag(char_code);
4884 CallRuntimeFromDeferred(Runtime::kCharFromCode, 1, instr, instr->context());
4885 __ StoreToSafepointRegisterSlot(result, eax);
4889 void LCodeGen::DoStringAdd(LStringAdd* instr) {
4890 DCHECK(ToRegister(instr->context()).is(esi));
4891 DCHECK(ToRegister(instr->left()).is(edx));
4892 DCHECK(ToRegister(instr->right()).is(eax));
4893 StringAddStub stub(isolate(),
4894 instr->hydrogen()->flags(),
4895 instr->hydrogen()->pretenure_flag());
4896 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
4900 void LCodeGen::DoInteger32ToDouble(LInteger32ToDouble* instr) {
4901 LOperand* input = instr->value();
4902 LOperand* output = instr->result();
4903 DCHECK(input->IsRegister() || input->IsStackSlot());
4904 DCHECK(output->IsDoubleRegister());
4905 if (input->IsRegister()) {
4906 Register input_reg = ToRegister(input);
4908 X87Mov(ToX87Register(output), Operand(esp, 0), kX87IntOperand);
4911 X87Mov(ToX87Register(output), ToOperand(input), kX87IntOperand);
4916 void LCodeGen::DoUint32ToDouble(LUint32ToDouble* instr) {
4917 LOperand* input = instr->value();
4918 LOperand* output = instr->result();
4919 X87Register res = ToX87Register(output);
4920 X87PrepareToWrite(res);
4921 __ LoadUint32NoSSE2(ToRegister(input));
4922 X87CommitWrite(res);
4926 void LCodeGen::DoNumberTagI(LNumberTagI* instr) {
4927 class DeferredNumberTagI FINAL : public LDeferredCode {
4929 DeferredNumberTagI(LCodeGen* codegen,
4931 const X87Stack& x87_stack)
4932 : LDeferredCode(codegen, x87_stack), instr_(instr) { }
4933 virtual void Generate() OVERRIDE {
4934 codegen()->DoDeferredNumberTagIU(instr_, instr_->value(), instr_->temp(),
4937 virtual LInstruction* instr() OVERRIDE { return instr_; }
4939 LNumberTagI* instr_;
4942 LOperand* input = instr->value();
4943 DCHECK(input->IsRegister() && input->Equals(instr->result()));
4944 Register reg = ToRegister(input);
4946 DeferredNumberTagI* deferred =
4947 new(zone()) DeferredNumberTagI(this, instr, x87_stack_);
4949 __ j(overflow, deferred->entry());
4950 __ bind(deferred->exit());
4954 void LCodeGen::DoNumberTagU(LNumberTagU* instr) {
4955 class DeferredNumberTagU FINAL : public LDeferredCode {
4957 DeferredNumberTagU(LCodeGen* codegen,
4959 const X87Stack& x87_stack)
4960 : LDeferredCode(codegen, x87_stack), instr_(instr) { }
4961 virtual void Generate() OVERRIDE {
4962 codegen()->DoDeferredNumberTagIU(instr_, instr_->value(), instr_->temp(),
4965 virtual LInstruction* instr() OVERRIDE { return instr_; }
4967 LNumberTagU* instr_;
4970 LOperand* input = instr->value();
4971 DCHECK(input->IsRegister() && input->Equals(instr->result()));
4972 Register reg = ToRegister(input);
4974 DeferredNumberTagU* deferred =
4975 new(zone()) DeferredNumberTagU(this, instr, x87_stack_);
4976 __ cmp(reg, Immediate(Smi::kMaxValue));
4977 __ j(above, deferred->entry());
4979 __ bind(deferred->exit());
4983 void LCodeGen::DoDeferredNumberTagIU(LInstruction* instr,
4986 IntegerSignedness signedness) {
4988 Register reg = ToRegister(value);
4989 Register tmp = ToRegister(temp);
4991 if (signedness == SIGNED_INT32) {
4992 // There was overflow, so bits 30 and 31 of the original integer
4993 // disagree. Try to allocate a heap number in new space and store
4994 // the value in there. If that fails, call the runtime system.
4996 __ xor_(reg, 0x80000000);
4998 __ fild_s(Operand(esp, 0));
5001 // There's no fild variant for unsigned values, so zero-extend to a 64-bit
5003 __ push(Immediate(0));
5005 __ fild_d(Operand(esp, 0));
5010 if (FLAG_inline_new) {
5011 __ AllocateHeapNumber(reg, tmp, no_reg, &slow);
5012 __ jmp(&done, Label::kNear);
5015 // Slow case: Call the runtime system to do the number allocation.
5018 // TODO(3095996): Put a valid pointer value in the stack slot where the
5019 // result register is stored, as this register is in the pointer map, but
5020 // contains an integer value.
5021 __ Move(reg, Immediate(0));
5023 // Preserve the value of all registers.
5024 PushSafepointRegistersScope scope(this);
5026 // NumberTagI and NumberTagD use the context from the frame, rather than
5027 // the environment's HContext or HInlinedContext value.
5028 // They only call Runtime::kAllocateHeapNumber.
5029 // The corresponding HChange instructions are added in a phase that does
5030 // not have easy access to the local context.
5031 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
5032 __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
5033 RecordSafepointWithRegisters(
5034 instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
5035 __ StoreToSafepointRegisterSlot(reg, eax);
5039 __ fstp_d(FieldOperand(reg, HeapNumber::kValueOffset));
5043 void LCodeGen::DoNumberTagD(LNumberTagD* instr) {
5044 class DeferredNumberTagD FINAL : public LDeferredCode {
5046 DeferredNumberTagD(LCodeGen* codegen,
5048 const X87Stack& x87_stack)
5049 : LDeferredCode(codegen, x87_stack), instr_(instr) { }
5050 virtual void Generate() OVERRIDE {
5051 codegen()->DoDeferredNumberTagD(instr_);
5053 virtual LInstruction* instr() OVERRIDE { return instr_; }
5055 LNumberTagD* instr_;
5058 Register reg = ToRegister(instr->result());
5060 // Put the value to the top of stack
5061 X87Register src = ToX87Register(instr->value());
5062 // Don't use X87LoadForUsage here, which is only used by Instruction which
5063 // clobbers fp registers.
5064 x87_stack_.Fxch(src);
5066 DeferredNumberTagD* deferred =
5067 new(zone()) DeferredNumberTagD(this, instr, x87_stack_);
5068 if (FLAG_inline_new) {
5069 Register tmp = ToRegister(instr->temp());
5070 __ AllocateHeapNumber(reg, tmp, no_reg, deferred->entry());
5072 __ jmp(deferred->entry());
5074 __ bind(deferred->exit());
5075 __ fst_d(FieldOperand(reg, HeapNumber::kValueOffset));
5079 void LCodeGen::DoDeferredNumberTagD(LNumberTagD* instr) {
5080 // TODO(3095996): Get rid of this. For now, we need to make the
5081 // result register contain a valid pointer because it is already
5082 // contained in the register pointer map.
5083 Register reg = ToRegister(instr->result());
5084 __ Move(reg, Immediate(0));
5086 PushSafepointRegistersScope scope(this);
5087 // NumberTagI and NumberTagD use the context from the frame, rather than
5088 // the environment's HContext or HInlinedContext value.
5089 // They only call Runtime::kAllocateHeapNumber.
5090 // The corresponding HChange instructions are added in a phase that does
5091 // not have easy access to the local context.
5092 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
5093 __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
5094 RecordSafepointWithRegisters(
5095 instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
5096 __ StoreToSafepointRegisterSlot(reg, eax);
5100 void LCodeGen::DoSmiTag(LSmiTag* instr) {
5101 HChange* hchange = instr->hydrogen();
5102 Register input = ToRegister(instr->value());
5103 if (hchange->CheckFlag(HValue::kCanOverflow) &&
5104 hchange->value()->CheckFlag(HValue::kUint32)) {
5105 __ test(input, Immediate(0xc0000000));
5106 DeoptimizeIf(not_zero, instr, "overflow");
5109 if (hchange->CheckFlag(HValue::kCanOverflow) &&
5110 !hchange->value()->CheckFlag(HValue::kUint32)) {
5111 DeoptimizeIf(overflow, instr, "overflow");
5116 void LCodeGen::DoSmiUntag(LSmiUntag* instr) {
5117 LOperand* input = instr->value();
5118 Register result = ToRegister(input);
5119 DCHECK(input->IsRegister() && input->Equals(instr->result()));
5120 if (instr->needs_check()) {
5121 __ test(result, Immediate(kSmiTagMask));
5122 DeoptimizeIf(not_zero, instr, "not a Smi");
5124 __ AssertSmi(result);
5126 __ SmiUntag(result);
5130 void LCodeGen::EmitNumberUntagDNoSSE2(LNumberUntagD* instr, Register input_reg,
5131 Register temp_reg, X87Register res_reg,
5132 NumberUntagDMode mode) {
5133 bool can_convert_undefined_to_nan =
5134 instr->hydrogen()->can_convert_undefined_to_nan();
5135 bool deoptimize_on_minus_zero = instr->hydrogen()->deoptimize_on_minus_zero();
5137 Label load_smi, done;
5139 X87PrepareToWrite(res_reg);
5140 if (mode == NUMBER_CANDIDATE_IS_ANY_TAGGED) {
5142 __ JumpIfSmi(input_reg, &load_smi);
5144 // Heap number map check.
5145 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
5146 factory()->heap_number_map());
5147 if (!can_convert_undefined_to_nan) {
5148 DeoptimizeIf(not_equal, instr, "not a heap number");
5150 Label heap_number, convert;
5151 __ j(equal, &heap_number);
5153 // Convert undefined (or hole) to NaN.
5154 __ cmp(input_reg, factory()->undefined_value());
5155 DeoptimizeIf(not_equal, instr, "not a heap number/undefined");
5158 ExternalReference nan =
5159 ExternalReference::address_of_canonical_non_hole_nan();
5160 __ fld_d(Operand::StaticVariable(nan));
5161 __ jmp(&done, Label::kNear);
5163 __ bind(&heap_number);
5165 // Heap number to x87 conversion.
5166 __ fld_d(FieldOperand(input_reg, HeapNumber::kValueOffset));
5167 if (deoptimize_on_minus_zero) {
5170 __ fld_d(FieldOperand(input_reg, HeapNumber::kValueOffset));
5171 __ j(not_zero, &done, Label::kNear);
5173 // Use general purpose registers to check if we have -0.0
5174 __ mov(temp_reg, FieldOperand(input_reg, HeapNumber::kExponentOffset));
5175 __ test(temp_reg, Immediate(HeapNumber::kSignMask));
5176 __ j(zero, &done, Label::kNear);
5178 // Pop FPU stack before deoptimizing.
5180 DeoptimizeIf(not_zero, instr, "minus zero");
5182 __ jmp(&done, Label::kNear);
5184 DCHECK(mode == NUMBER_CANDIDATE_IS_SMI);
5188 // Clobbering a temp is faster than re-tagging the
5189 // input register since we avoid dependencies.
5190 __ mov(temp_reg, input_reg);
5191 __ SmiUntag(temp_reg); // Untag smi before converting to float.
5193 __ fild_s(Operand(esp, 0));
5194 __ add(esp, Immediate(kPointerSize));
5196 X87CommitWrite(res_reg);
5200 void LCodeGen::DoDeferredTaggedToI(LTaggedToI* instr, Label* done) {
5201 Register input_reg = ToRegister(instr->value());
5203 // The input was optimistically untagged; revert it.
5204 STATIC_ASSERT(kSmiTagSize == 1);
5205 __ lea(input_reg, Operand(input_reg, times_2, kHeapObjectTag));
5207 if (instr->truncating()) {
5208 Label no_heap_number, check_bools, check_false;
5210 // Heap number map check.
5211 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
5212 factory()->heap_number_map());
5213 __ j(not_equal, &no_heap_number, Label::kNear);
5214 __ TruncateHeapNumberToI(input_reg, input_reg);
5217 __ bind(&no_heap_number);
5218 // Check for Oddballs. Undefined/False is converted to zero and True to one
5219 // for truncating conversions.
5220 __ cmp(input_reg, factory()->undefined_value());
5221 __ j(not_equal, &check_bools, Label::kNear);
5222 __ Move(input_reg, Immediate(0));
5225 __ bind(&check_bools);
5226 __ cmp(input_reg, factory()->true_value());
5227 __ j(not_equal, &check_false, Label::kNear);
5228 __ Move(input_reg, Immediate(1));
5231 __ bind(&check_false);
5232 __ cmp(input_reg, factory()->false_value());
5233 DeoptimizeIf(not_equal, instr, "not a heap number/undefined/true/false");
5234 __ Move(input_reg, Immediate(0));
5236 // TODO(olivf) Converting a number on the fpu is actually quite slow. We
5237 // should first try a fast conversion and then bailout to this slow case.
5238 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
5239 isolate()->factory()->heap_number_map());
5240 DeoptimizeIf(not_equal, instr, "not a heap number");
5242 __ sub(esp, Immediate(kPointerSize));
5243 __ fld_d(FieldOperand(input_reg, HeapNumber::kValueOffset));
5245 if (instr->hydrogen()->GetMinusZeroMode() == FAIL_ON_MINUS_ZERO) {
5246 Label no_precision_lost, not_nan, zero_check;
5249 __ fist_s(MemOperand(esp, 0));
5250 __ fild_s(MemOperand(esp, 0));
5254 __ j(equal, &no_precision_lost, Label::kNear);
5256 DeoptimizeIf(no_condition, instr, "lost precision");
5257 __ bind(&no_precision_lost);
5259 __ j(parity_odd, ¬_nan);
5261 DeoptimizeIf(no_condition, instr, "NaN");
5264 __ test(input_reg, Operand(input_reg));
5265 __ j(zero, &zero_check, Label::kNear);
5269 __ bind(&zero_check);
5270 // To check for minus zero, we load the value again as float, and check
5271 // if that is still 0.
5272 __ sub(esp, Immediate(kPointerSize));
5273 __ fstp_s(Operand(esp, 0));
5275 __ test(input_reg, Operand(input_reg));
5276 DeoptimizeIf(not_zero, instr, "minus zero");
5278 __ fist_s(MemOperand(esp, 0));
5279 __ fild_s(MemOperand(esp, 0));
5282 DeoptimizeIf(not_equal, instr, "lost precision");
5283 DeoptimizeIf(parity_even, instr, "NaN");
5289 void LCodeGen::DoTaggedToI(LTaggedToI* instr) {
5290 class DeferredTaggedToI FINAL : public LDeferredCode {
5292 DeferredTaggedToI(LCodeGen* codegen,
5294 const X87Stack& x87_stack)
5295 : LDeferredCode(codegen, x87_stack), instr_(instr) { }
5296 virtual void Generate() OVERRIDE {
5297 codegen()->DoDeferredTaggedToI(instr_, done());
5299 virtual LInstruction* instr() OVERRIDE { return instr_; }
5304 LOperand* input = instr->value();
5305 DCHECK(input->IsRegister());
5306 Register input_reg = ToRegister(input);
5307 DCHECK(input_reg.is(ToRegister(instr->result())));
5309 if (instr->hydrogen()->value()->representation().IsSmi()) {
5310 __ SmiUntag(input_reg);
5312 DeferredTaggedToI* deferred =
5313 new(zone()) DeferredTaggedToI(this, instr, x87_stack_);
5314 // Optimistically untag the input.
5315 // If the input is a HeapObject, SmiUntag will set the carry flag.
5316 STATIC_ASSERT(kSmiTagSize == 1 && kSmiTag == 0);
5317 __ SmiUntag(input_reg);
5318 // Branch to deferred code if the input was tagged.
5319 // The deferred code will take care of restoring the tag.
5320 __ j(carry, deferred->entry());
5321 __ bind(deferred->exit());
5326 void LCodeGen::DoNumberUntagD(LNumberUntagD* instr) {
5327 LOperand* input = instr->value();
5328 DCHECK(input->IsRegister());
5329 LOperand* temp = instr->temp();
5330 DCHECK(temp->IsRegister());
5331 LOperand* result = instr->result();
5332 DCHECK(result->IsDoubleRegister());
5334 Register input_reg = ToRegister(input);
5335 Register temp_reg = ToRegister(temp);
5337 HValue* value = instr->hydrogen()->value();
5338 NumberUntagDMode mode = value->representation().IsSmi()
5339 ? NUMBER_CANDIDATE_IS_SMI : NUMBER_CANDIDATE_IS_ANY_TAGGED;
5341 EmitNumberUntagDNoSSE2(instr, input_reg, temp_reg, ToX87Register(result),
5346 void LCodeGen::DoDoubleToI(LDoubleToI* instr) {
5347 LOperand* input = instr->value();
5348 DCHECK(input->IsDoubleRegister());
5349 LOperand* result = instr->result();
5350 DCHECK(result->IsRegister());
5351 Register result_reg = ToRegister(result);
5353 if (instr->truncating()) {
5354 X87Register input_reg = ToX87Register(input);
5356 __ TruncateX87TOSToI(result_reg);
5358 Label lost_precision, is_nan, minus_zero, done;
5359 X87Register input_reg = ToX87Register(input);
5361 Label::Distance dist = DeoptEveryNTimes() ? Label::kFar : Label::kNear;
5362 __ X87TOSToI(result_reg, instr->hydrogen()->GetMinusZeroMode(),
5363 &lost_precision, &is_nan, &minus_zero, dist);
5365 __ bind(&lost_precision);
5366 DeoptimizeIf(no_condition, instr, "lost precision");
5368 DeoptimizeIf(no_condition, instr, "NaN");
5369 __ bind(&minus_zero);
5370 DeoptimizeIf(no_condition, instr, "minus zero");
5376 void LCodeGen::DoDoubleToSmi(LDoubleToSmi* instr) {
5377 LOperand* input = instr->value();
5378 DCHECK(input->IsDoubleRegister());
5379 LOperand* result = instr->result();
5380 DCHECK(result->IsRegister());
5381 Register result_reg = ToRegister(result);
5383 Label lost_precision, is_nan, minus_zero, done;
5384 X87Register input_reg = ToX87Register(input);
5386 Label::Distance dist = DeoptEveryNTimes() ? Label::kFar : Label::kNear;
5387 __ X87TOSToI(result_reg, instr->hydrogen()->GetMinusZeroMode(),
5388 &lost_precision, &is_nan, &minus_zero, dist);
5390 __ bind(&lost_precision);
5391 DeoptimizeIf(no_condition, instr, "lost precision");
5393 DeoptimizeIf(no_condition, instr, "NaN");
5394 __ bind(&minus_zero);
5395 DeoptimizeIf(no_condition, instr, "minus zero");
5397 __ SmiTag(result_reg);
5398 DeoptimizeIf(overflow, instr, "overflow");
5402 void LCodeGen::DoCheckSmi(LCheckSmi* instr) {
5403 LOperand* input = instr->value();
5404 __ test(ToOperand(input), Immediate(kSmiTagMask));
5405 DeoptimizeIf(not_zero, instr, "not a Smi");
5409 void LCodeGen::DoCheckNonSmi(LCheckNonSmi* instr) {
5410 if (!instr->hydrogen()->value()->type().IsHeapObject()) {
5411 LOperand* input = instr->value();
5412 __ test(ToOperand(input), Immediate(kSmiTagMask));
5413 DeoptimizeIf(zero, instr, "Smi");
5418 void LCodeGen::DoCheckInstanceType(LCheckInstanceType* instr) {
5419 Register input = ToRegister(instr->value());
5420 Register temp = ToRegister(instr->temp());
5422 __ mov(temp, FieldOperand(input, HeapObject::kMapOffset));
5424 if (instr->hydrogen()->is_interval_check()) {
5427 instr->hydrogen()->GetCheckInterval(&first, &last);
5429 __ cmpb(FieldOperand(temp, Map::kInstanceTypeOffset),
5430 static_cast<int8_t>(first));
5432 // If there is only one type in the interval check for equality.
5433 if (first == last) {
5434 DeoptimizeIf(not_equal, instr, "wrong instance type");
5436 DeoptimizeIf(below, instr, "wrong instance type");
5437 // Omit check for the last type.
5438 if (last != LAST_TYPE) {
5439 __ cmpb(FieldOperand(temp, Map::kInstanceTypeOffset),
5440 static_cast<int8_t>(last));
5441 DeoptimizeIf(above, instr, "wrong instance type");
5447 instr->hydrogen()->GetCheckMaskAndTag(&mask, &tag);
5449 if (base::bits::IsPowerOfTwo32(mask)) {
5450 DCHECK(tag == 0 || base::bits::IsPowerOfTwo32(tag));
5451 __ test_b(FieldOperand(temp, Map::kInstanceTypeOffset), mask);
5452 DeoptimizeIf(tag == 0 ? not_zero : zero, instr, "wrong instance type");
5454 __ movzx_b(temp, FieldOperand(temp, Map::kInstanceTypeOffset));
5455 __ and_(temp, mask);
5457 DeoptimizeIf(not_equal, instr, "wrong instance type");
5463 void LCodeGen::DoCheckValue(LCheckValue* instr) {
5464 Handle<HeapObject> object = instr->hydrogen()->object().handle();
5465 if (instr->hydrogen()->object_in_new_space()) {
5466 Register reg = ToRegister(instr->value());
5467 Handle<Cell> cell = isolate()->factory()->NewCell(object);
5468 __ cmp(reg, Operand::ForCell(cell));
5470 Operand operand = ToOperand(instr->value());
5471 __ cmp(operand, object);
5473 DeoptimizeIf(not_equal, instr, "value mismatch");
5477 void LCodeGen::DoDeferredInstanceMigration(LCheckMaps* instr, Register object) {
5479 PushSafepointRegistersScope scope(this);
5482 __ CallRuntimeSaveDoubles(Runtime::kTryMigrateInstance);
5483 RecordSafepointWithRegisters(
5484 instr->pointer_map(), 1, Safepoint::kNoLazyDeopt);
5486 __ test(eax, Immediate(kSmiTagMask));
5488 DeoptimizeIf(zero, instr, "instance migration failed");
5492 void LCodeGen::DoCheckMaps(LCheckMaps* instr) {
5493 class DeferredCheckMaps FINAL : public LDeferredCode {
5495 DeferredCheckMaps(LCodeGen* codegen,
5498 const X87Stack& x87_stack)
5499 : LDeferredCode(codegen, x87_stack), instr_(instr), object_(object) {
5500 SetExit(check_maps());
5502 virtual void Generate() OVERRIDE {
5503 codegen()->DoDeferredInstanceMigration(instr_, object_);
5505 Label* check_maps() { return &check_maps_; }
5506 virtual LInstruction* instr() OVERRIDE { return instr_; }
5513 if (instr->hydrogen()->IsStabilityCheck()) {
5514 const UniqueSet<Map>* maps = instr->hydrogen()->maps();
5515 for (int i = 0; i < maps->size(); ++i) {
5516 AddStabilityDependency(maps->at(i).handle());
5521 LOperand* input = instr->value();
5522 DCHECK(input->IsRegister());
5523 Register reg = ToRegister(input);
5525 DeferredCheckMaps* deferred = NULL;
5526 if (instr->hydrogen()->HasMigrationTarget()) {
5527 deferred = new(zone()) DeferredCheckMaps(this, instr, reg, x87_stack_);
5528 __ bind(deferred->check_maps());
5531 const UniqueSet<Map>* maps = instr->hydrogen()->maps();
5533 for (int i = 0; i < maps->size() - 1; i++) {
5534 Handle<Map> map = maps->at(i).handle();
5535 __ CompareMap(reg, map);
5536 __ j(equal, &success, Label::kNear);
5539 Handle<Map> map = maps->at(maps->size() - 1).handle();
5540 __ CompareMap(reg, map);
5541 if (instr->hydrogen()->HasMigrationTarget()) {
5542 __ j(not_equal, deferred->entry());
5544 DeoptimizeIf(not_equal, instr, "wrong map");
5551 void LCodeGen::DoClampDToUint8(LClampDToUint8* instr) {
5552 X87Register value_reg = ToX87Register(instr->unclamped());
5553 Register result_reg = ToRegister(instr->result());
5555 __ ClampTOSToUint8(result_reg);
5559 void LCodeGen::DoClampIToUint8(LClampIToUint8* instr) {
5560 DCHECK(instr->unclamped()->Equals(instr->result()));
5561 Register value_reg = ToRegister(instr->result());
5562 __ ClampUint8(value_reg);
5566 void LCodeGen::DoClampTToUint8NoSSE2(LClampTToUint8NoSSE2* instr) {
5567 Register input_reg = ToRegister(instr->unclamped());
5568 Register result_reg = ToRegister(instr->result());
5569 Register scratch = ToRegister(instr->scratch());
5570 Register scratch2 = ToRegister(instr->scratch2());
5571 Register scratch3 = ToRegister(instr->scratch3());
5572 Label is_smi, done, heap_number, valid_exponent,
5573 largest_value, zero_result, maybe_nan_or_infinity;
5575 __ JumpIfSmi(input_reg, &is_smi);
5577 // Check for heap number
5578 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
5579 factory()->heap_number_map());
5580 __ j(equal, &heap_number, Label::kNear);
5582 // Check for undefined. Undefined is converted to zero for clamping
5584 __ cmp(input_reg, factory()->undefined_value());
5585 DeoptimizeIf(not_equal, instr, "not a heap number/undefined");
5586 __ jmp(&zero_result, Label::kNear);
5589 __ bind(&heap_number);
5591 // Surprisingly, all of the hand-crafted bit-manipulations below are much
5592 // faster than the x86 FPU built-in instruction, especially since "banker's
5593 // rounding" would be additionally very expensive
5595 // Get exponent word.
5596 __ mov(scratch, FieldOperand(input_reg, HeapNumber::kExponentOffset));
5597 __ mov(scratch3, FieldOperand(input_reg, HeapNumber::kMantissaOffset));
5599 // Test for negative values --> clamp to zero
5600 __ test(scratch, scratch);
5601 __ j(negative, &zero_result, Label::kNear);
5603 // Get exponent alone in scratch2.
5604 __ mov(scratch2, scratch);
5605 __ and_(scratch2, HeapNumber::kExponentMask);
5606 __ shr(scratch2, HeapNumber::kExponentShift);
5607 __ j(zero, &zero_result, Label::kNear);
5608 __ sub(scratch2, Immediate(HeapNumber::kExponentBias - 1));
5609 __ j(negative, &zero_result, Label::kNear);
5611 const uint32_t non_int8_exponent = 7;
5612 __ cmp(scratch2, Immediate(non_int8_exponent + 1));
5613 // If the exponent is too big, check for special values.
5614 __ j(greater, &maybe_nan_or_infinity, Label::kNear);
5616 __ bind(&valid_exponent);
5617 // Exponent word in scratch, exponent in scratch2. We know that 0 <= exponent
5618 // < 7. The shift bias is the number of bits to shift the mantissa such that
5619 // with an exponent of 7 such the that top-most one is in bit 30, allowing
5620 // detection the rounding overflow of a 255.5 to 256 (bit 31 goes from 0 to
5622 int shift_bias = (30 - HeapNumber::kExponentShift) - 7 - 1;
5623 __ lea(result_reg, MemOperand(scratch2, shift_bias));
5624 // Here result_reg (ecx) is the shift, scratch is the exponent word. Get the
5625 // top bits of the mantissa.
5626 __ and_(scratch, HeapNumber::kMantissaMask);
5627 // Put back the implicit 1 of the mantissa
5628 __ or_(scratch, 1 << HeapNumber::kExponentShift);
5629 // Shift up to round
5631 // Use "banker's rounding" to spec: If fractional part of number is 0.5, then
5632 // use the bit in the "ones" place and add it to the "halves" place, which has
5633 // the effect of rounding to even.
5634 __ mov(scratch2, scratch);
5635 const uint32_t one_half_bit_shift = 30 - sizeof(uint8_t) * 8;
5636 const uint32_t one_bit_shift = one_half_bit_shift + 1;
5637 __ and_(scratch2, Immediate((1 << one_bit_shift) - 1));
5638 __ cmp(scratch2, Immediate(1 << one_half_bit_shift));
5640 __ j(less, &no_round, Label::kNear);
5642 __ mov(scratch2, Immediate(1 << one_half_bit_shift));
5643 __ j(greater, &round_up, Label::kNear);
5644 __ test(scratch3, scratch3);
5645 __ j(not_zero, &round_up, Label::kNear);
5646 __ mov(scratch2, scratch);
5647 __ and_(scratch2, Immediate(1 << one_bit_shift));
5648 __ shr(scratch2, 1);
5650 __ add(scratch, scratch2);
5651 __ j(overflow, &largest_value, Label::kNear);
5653 __ shr(scratch, 23);
5654 __ mov(result_reg, scratch);
5655 __ jmp(&done, Label::kNear);
5657 __ bind(&maybe_nan_or_infinity);
5658 // Check for NaN/Infinity, all other values map to 255
5659 __ cmp(scratch2, Immediate(HeapNumber::kInfinityOrNanExponent + 1));
5660 __ j(not_equal, &largest_value, Label::kNear);
5662 // Check for NaN, which differs from Infinity in that at least one mantissa
5664 __ and_(scratch, HeapNumber::kMantissaMask);
5665 __ or_(scratch, FieldOperand(input_reg, HeapNumber::kMantissaOffset));
5666 __ j(not_zero, &zero_result, Label::kNear); // M!=0 --> NaN
5667 // Infinity -> Fall through to map to 255.
5669 __ bind(&largest_value);
5670 __ mov(result_reg, Immediate(255));
5671 __ jmp(&done, Label::kNear);
5673 __ bind(&zero_result);
5674 __ xor_(result_reg, result_reg);
5675 __ jmp(&done, Label::kNear);
5679 if (!input_reg.is(result_reg)) {
5680 __ mov(result_reg, input_reg);
5682 __ SmiUntag(result_reg);
5683 __ ClampUint8(result_reg);
5688 void LCodeGen::DoDoubleBits(LDoubleBits* instr) {
5689 X87Register value_reg = ToX87Register(instr->value());
5690 Register result_reg = ToRegister(instr->result());
5692 __ sub(esp, Immediate(kDoubleSize));
5693 __ fst_d(Operand(esp, 0));
5694 if (instr->hydrogen()->bits() == HDoubleBits::HIGH) {
5695 __ mov(result_reg, Operand(esp, kPointerSize));
5697 __ mov(result_reg, Operand(esp, 0));
5699 __ add(esp, Immediate(kDoubleSize));
5703 void LCodeGen::DoConstructDouble(LConstructDouble* instr) {
5704 Register hi_reg = ToRegister(instr->hi());
5705 Register lo_reg = ToRegister(instr->lo());
5706 X87Register result_reg = ToX87Register(instr->result());
5707 // Follow below pattern to write a x87 fp register.
5708 X87PrepareToWrite(result_reg);
5709 __ sub(esp, Immediate(kDoubleSize));
5710 __ mov(Operand(esp, 0), lo_reg);
5711 __ mov(Operand(esp, kPointerSize), hi_reg);
5712 __ fld_d(Operand(esp, 0));
5713 __ add(esp, Immediate(kDoubleSize));
5714 X87CommitWrite(result_reg);
5718 void LCodeGen::DoAllocate(LAllocate* instr) {
5719 class DeferredAllocate FINAL : public LDeferredCode {
5721 DeferredAllocate(LCodeGen* codegen,
5723 const X87Stack& x87_stack)
5724 : LDeferredCode(codegen, x87_stack), instr_(instr) { }
5725 virtual void Generate() OVERRIDE {
5726 codegen()->DoDeferredAllocate(instr_);
5728 virtual LInstruction* instr() OVERRIDE { return instr_; }
5733 DeferredAllocate* deferred =
5734 new(zone()) DeferredAllocate(this, instr, x87_stack_);
5736 Register result = ToRegister(instr->result());
5737 Register temp = ToRegister(instr->temp());
5739 // Allocate memory for the object.
5740 AllocationFlags flags = TAG_OBJECT;
5741 if (instr->hydrogen()->MustAllocateDoubleAligned()) {
5742 flags = static_cast<AllocationFlags>(flags | DOUBLE_ALIGNMENT);
5744 if (instr->hydrogen()->IsOldPointerSpaceAllocation()) {
5745 DCHECK(!instr->hydrogen()->IsOldDataSpaceAllocation());
5746 DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
5747 flags = static_cast<AllocationFlags>(flags | PRETENURE_OLD_POINTER_SPACE);
5748 } else if (instr->hydrogen()->IsOldDataSpaceAllocation()) {
5749 DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
5750 flags = static_cast<AllocationFlags>(flags | PRETENURE_OLD_DATA_SPACE);
5753 if (instr->size()->IsConstantOperand()) {
5754 int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
5755 if (size <= Page::kMaxRegularHeapObjectSize) {
5756 __ Allocate(size, result, temp, no_reg, deferred->entry(), flags);
5758 __ jmp(deferred->entry());
5761 Register size = ToRegister(instr->size());
5762 __ Allocate(size, result, temp, no_reg, deferred->entry(), flags);
5765 __ bind(deferred->exit());
5767 if (instr->hydrogen()->MustPrefillWithFiller()) {
5768 if (instr->size()->IsConstantOperand()) {
5769 int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
5770 __ mov(temp, (size / kPointerSize) - 1);
5772 temp = ToRegister(instr->size());
5773 __ shr(temp, kPointerSizeLog2);
5778 __ mov(FieldOperand(result, temp, times_pointer_size, 0),
5779 isolate()->factory()->one_pointer_filler_map());
5781 __ j(not_zero, &loop);
5786 void LCodeGen::DoDeferredAllocate(LAllocate* instr) {
5787 Register result = ToRegister(instr->result());
5789 // TODO(3095996): Get rid of this. For now, we need to make the
5790 // result register contain a valid pointer because it is already
5791 // contained in the register pointer map.
5792 __ Move(result, Immediate(Smi::FromInt(0)));
5794 PushSafepointRegistersScope scope(this);
5795 if (instr->size()->IsRegister()) {
5796 Register size = ToRegister(instr->size());
5797 DCHECK(!size.is(result));
5798 __ SmiTag(ToRegister(instr->size()));
5801 int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
5802 if (size >= 0 && size <= Smi::kMaxValue) {
5803 __ push(Immediate(Smi::FromInt(size)));
5805 // We should never get here at runtime => abort
5811 int flags = AllocateDoubleAlignFlag::encode(
5812 instr->hydrogen()->MustAllocateDoubleAligned());
5813 if (instr->hydrogen()->IsOldPointerSpaceAllocation()) {
5814 DCHECK(!instr->hydrogen()->IsOldDataSpaceAllocation());
5815 DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
5816 flags = AllocateTargetSpace::update(flags, OLD_POINTER_SPACE);
5817 } else if (instr->hydrogen()->IsOldDataSpaceAllocation()) {
5818 DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
5819 flags = AllocateTargetSpace::update(flags, OLD_DATA_SPACE);
5821 flags = AllocateTargetSpace::update(flags, NEW_SPACE);
5823 __ push(Immediate(Smi::FromInt(flags)));
5825 CallRuntimeFromDeferred(
5826 Runtime::kAllocateInTargetSpace, 2, instr, instr->context());
5827 __ StoreToSafepointRegisterSlot(result, eax);
5831 void LCodeGen::DoToFastProperties(LToFastProperties* instr) {
5832 DCHECK(ToRegister(instr->value()).is(eax));
5834 CallRuntime(Runtime::kToFastProperties, 1, instr);
5838 void LCodeGen::DoRegExpLiteral(LRegExpLiteral* instr) {
5839 DCHECK(ToRegister(instr->context()).is(esi));
5841 // Registers will be used as follows:
5842 // ecx = literals array.
5843 // ebx = regexp literal.
5844 // eax = regexp literal clone.
5846 int literal_offset =
5847 FixedArray::OffsetOfElementAt(instr->hydrogen()->literal_index());
5848 __ LoadHeapObject(ecx, instr->hydrogen()->literals());
5849 __ mov(ebx, FieldOperand(ecx, literal_offset));
5850 __ cmp(ebx, factory()->undefined_value());
5851 __ j(not_equal, &materialized, Label::kNear);
5853 // Create regexp literal using runtime function
5854 // Result will be in eax.
5856 __ push(Immediate(Smi::FromInt(instr->hydrogen()->literal_index())));
5857 __ push(Immediate(instr->hydrogen()->pattern()));
5858 __ push(Immediate(instr->hydrogen()->flags()));
5859 CallRuntime(Runtime::kMaterializeRegExpLiteral, 4, instr);
5862 __ bind(&materialized);
5863 int size = JSRegExp::kSize + JSRegExp::kInObjectFieldCount * kPointerSize;
5864 Label allocated, runtime_allocate;
5865 __ Allocate(size, eax, ecx, edx, &runtime_allocate, TAG_OBJECT);
5866 __ jmp(&allocated, Label::kNear);
5868 __ bind(&runtime_allocate);
5870 __ push(Immediate(Smi::FromInt(size)));
5871 CallRuntime(Runtime::kAllocateInNewSpace, 1, instr);
5874 __ bind(&allocated);
5875 // Copy the content into the newly allocated memory.
5876 // (Unroll copy loop once for better throughput).
5877 for (int i = 0; i < size - kPointerSize; i += 2 * kPointerSize) {
5878 __ mov(edx, FieldOperand(ebx, i));
5879 __ mov(ecx, FieldOperand(ebx, i + kPointerSize));
5880 __ mov(FieldOperand(eax, i), edx);
5881 __ mov(FieldOperand(eax, i + kPointerSize), ecx);
5883 if ((size % (2 * kPointerSize)) != 0) {
5884 __ mov(edx, FieldOperand(ebx, size - kPointerSize));
5885 __ mov(FieldOperand(eax, size - kPointerSize), edx);
5890 void LCodeGen::DoFunctionLiteral(LFunctionLiteral* instr) {
5891 DCHECK(ToRegister(instr->context()).is(esi));
5892 // Use the fast case closure allocation code that allocates in new
5893 // space for nested functions that don't need literals cloning.
5894 bool pretenure = instr->hydrogen()->pretenure();
5895 if (!pretenure && instr->hydrogen()->has_no_literals()) {
5896 FastNewClosureStub stub(isolate(), instr->hydrogen()->strict_mode(),
5897 instr->hydrogen()->kind());
5898 __ mov(ebx, Immediate(instr->hydrogen()->shared_info()));
5899 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
5902 __ push(Immediate(instr->hydrogen()->shared_info()));
5903 __ push(Immediate(pretenure ? factory()->true_value()
5904 : factory()->false_value()));
5905 CallRuntime(Runtime::kNewClosure, 3, instr);
5910 void LCodeGen::DoTypeof(LTypeof* instr) {
5911 DCHECK(ToRegister(instr->context()).is(esi));
5912 LOperand* input = instr->value();
5913 EmitPushTaggedOperand(input);
5914 CallRuntime(Runtime::kTypeof, 1, instr);
5918 void LCodeGen::DoTypeofIsAndBranch(LTypeofIsAndBranch* instr) {
5919 Register input = ToRegister(instr->value());
5920 Condition final_branch_condition = EmitTypeofIs(instr, input);
5921 if (final_branch_condition != no_condition) {
5922 EmitBranch(instr, final_branch_condition);
5927 Condition LCodeGen::EmitTypeofIs(LTypeofIsAndBranch* instr, Register input) {
5928 Label* true_label = instr->TrueLabel(chunk_);
5929 Label* false_label = instr->FalseLabel(chunk_);
5930 Handle<String> type_name = instr->type_literal();
5931 int left_block = instr->TrueDestination(chunk_);
5932 int right_block = instr->FalseDestination(chunk_);
5933 int next_block = GetNextEmittedBlock();
5935 Label::Distance true_distance = left_block == next_block ? Label::kNear
5937 Label::Distance false_distance = right_block == next_block ? Label::kNear
5939 Condition final_branch_condition = no_condition;
5940 if (String::Equals(type_name, factory()->number_string())) {
5941 __ JumpIfSmi(input, true_label, true_distance);
5942 __ cmp(FieldOperand(input, HeapObject::kMapOffset),
5943 factory()->heap_number_map());
5944 final_branch_condition = equal;
5946 } else if (String::Equals(type_name, factory()->string_string())) {
5947 __ JumpIfSmi(input, false_label, false_distance);
5948 __ CmpObjectType(input, FIRST_NONSTRING_TYPE, input);
5949 __ j(above_equal, false_label, false_distance);
5950 __ test_b(FieldOperand(input, Map::kBitFieldOffset),
5951 1 << Map::kIsUndetectable);
5952 final_branch_condition = zero;
5954 } else if (String::Equals(type_name, factory()->symbol_string())) {
5955 __ JumpIfSmi(input, false_label, false_distance);
5956 __ CmpObjectType(input, SYMBOL_TYPE, input);
5957 final_branch_condition = equal;
5959 } else if (String::Equals(type_name, factory()->boolean_string())) {
5960 __ cmp(input, factory()->true_value());
5961 __ j(equal, true_label, true_distance);
5962 __ cmp(input, factory()->false_value());
5963 final_branch_condition = equal;
5965 } else if (String::Equals(type_name, factory()->undefined_string())) {
5966 __ cmp(input, factory()->undefined_value());
5967 __ j(equal, true_label, true_distance);
5968 __ JumpIfSmi(input, false_label, false_distance);
5969 // Check for undetectable objects => true.
5970 __ mov(input, FieldOperand(input, HeapObject::kMapOffset));
5971 __ test_b(FieldOperand(input, Map::kBitFieldOffset),
5972 1 << Map::kIsUndetectable);
5973 final_branch_condition = not_zero;
5975 } else if (String::Equals(type_name, factory()->function_string())) {
5976 STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
5977 __ JumpIfSmi(input, false_label, false_distance);
5978 __ CmpObjectType(input, JS_FUNCTION_TYPE, input);
5979 __ j(equal, true_label, true_distance);
5980 __ CmpInstanceType(input, JS_FUNCTION_PROXY_TYPE);
5981 final_branch_condition = equal;
5983 } else if (String::Equals(type_name, factory()->object_string())) {
5984 __ JumpIfSmi(input, false_label, false_distance);
5985 __ cmp(input, factory()->null_value());
5986 __ j(equal, true_label, true_distance);
5987 __ CmpObjectType(input, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE, input);
5988 __ j(below, false_label, false_distance);
5989 __ CmpInstanceType(input, LAST_NONCALLABLE_SPEC_OBJECT_TYPE);
5990 __ j(above, false_label, false_distance);
5991 // Check for undetectable objects => false.
5992 __ test_b(FieldOperand(input, Map::kBitFieldOffset),
5993 1 << Map::kIsUndetectable);
5994 final_branch_condition = zero;
5997 __ jmp(false_label, false_distance);
5999 return final_branch_condition;
6003 void LCodeGen::DoIsConstructCallAndBranch(LIsConstructCallAndBranch* instr) {
6004 Register temp = ToRegister(instr->temp());
6006 EmitIsConstructCall(temp);
6007 EmitBranch(instr, equal);
6011 void LCodeGen::EmitIsConstructCall(Register temp) {
6012 // Get the frame pointer for the calling frame.
6013 __ mov(temp, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
6015 // Skip the arguments adaptor frame if it exists.
6016 Label check_frame_marker;
6017 __ cmp(Operand(temp, StandardFrameConstants::kContextOffset),
6018 Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
6019 __ j(not_equal, &check_frame_marker, Label::kNear);
6020 __ mov(temp, Operand(temp, StandardFrameConstants::kCallerFPOffset));
6022 // Check the marker in the calling frame.
6023 __ bind(&check_frame_marker);
6024 __ cmp(Operand(temp, StandardFrameConstants::kMarkerOffset),
6025 Immediate(Smi::FromInt(StackFrame::CONSTRUCT)));
6029 void LCodeGen::EnsureSpaceForLazyDeopt(int space_needed) {
6030 if (!info()->IsStub()) {
6031 // Ensure that we have enough space after the previous lazy-bailout
6032 // instruction for patching the code here.
6033 int current_pc = masm()->pc_offset();
6034 if (current_pc < last_lazy_deopt_pc_ + space_needed) {
6035 int padding_size = last_lazy_deopt_pc_ + space_needed - current_pc;
6036 __ Nop(padding_size);
6039 last_lazy_deopt_pc_ = masm()->pc_offset();
6043 void LCodeGen::DoLazyBailout(LLazyBailout* instr) {
6044 last_lazy_deopt_pc_ = masm()->pc_offset();
6045 DCHECK(instr->HasEnvironment());
6046 LEnvironment* env = instr->environment();
6047 RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt);
6048 safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
6052 void LCodeGen::DoDeoptimize(LDeoptimize* instr) {
6053 Deoptimizer::BailoutType type = instr->hydrogen()->type();
6054 // TODO(danno): Stubs expect all deopts to be lazy for historical reasons (the
6055 // needed return address), even though the implementation of LAZY and EAGER is
6056 // now identical. When LAZY is eventually completely folded into EAGER, remove
6057 // the special case below.
6058 if (info()->IsStub() && type == Deoptimizer::EAGER) {
6059 type = Deoptimizer::LAZY;
6061 DeoptimizeIf(no_condition, instr, instr->hydrogen()->reason(), type);
6065 void LCodeGen::DoDummy(LDummy* instr) {
6066 // Nothing to see here, move on!
6070 void LCodeGen::DoDummyUse(LDummyUse* instr) {
6071 // Nothing to see here, move on!
6075 void LCodeGen::DoDeferredStackCheck(LStackCheck* instr) {
6076 PushSafepointRegistersScope scope(this);
6077 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
6078 __ CallRuntimeSaveDoubles(Runtime::kStackGuard);
6079 RecordSafepointWithLazyDeopt(
6080 instr, RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
6081 DCHECK(instr->HasEnvironment());
6082 LEnvironment* env = instr->environment();
6083 safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
6087 void LCodeGen::DoStackCheck(LStackCheck* instr) {
6088 class DeferredStackCheck FINAL : public LDeferredCode {
6090 DeferredStackCheck(LCodeGen* codegen,
6092 const X87Stack& x87_stack)
6093 : LDeferredCode(codegen, x87_stack), instr_(instr) { }
6094 virtual void Generate() OVERRIDE {
6095 codegen()->DoDeferredStackCheck(instr_);
6097 virtual LInstruction* instr() OVERRIDE { return instr_; }
6099 LStackCheck* instr_;
6102 DCHECK(instr->HasEnvironment());
6103 LEnvironment* env = instr->environment();
6104 // There is no LLazyBailout instruction for stack-checks. We have to
6105 // prepare for lazy deoptimization explicitly here.
6106 if (instr->hydrogen()->is_function_entry()) {
6107 // Perform stack overflow check.
6109 ExternalReference stack_limit =
6110 ExternalReference::address_of_stack_limit(isolate());
6111 __ cmp(esp, Operand::StaticVariable(stack_limit));
6112 __ j(above_equal, &done, Label::kNear);
6114 DCHECK(instr->context()->IsRegister());
6115 DCHECK(ToRegister(instr->context()).is(esi));
6116 CallCode(isolate()->builtins()->StackCheck(),
6117 RelocInfo::CODE_TARGET,
6121 DCHECK(instr->hydrogen()->is_backwards_branch());
6122 // Perform stack overflow check if this goto needs it before jumping.
6123 DeferredStackCheck* deferred_stack_check =
6124 new(zone()) DeferredStackCheck(this, instr, x87_stack_);
6125 ExternalReference stack_limit =
6126 ExternalReference::address_of_stack_limit(isolate());
6127 __ cmp(esp, Operand::StaticVariable(stack_limit));
6128 __ j(below, deferred_stack_check->entry());
6129 EnsureSpaceForLazyDeopt(Deoptimizer::patch_size());
6130 __ bind(instr->done_label());
6131 deferred_stack_check->SetExit(instr->done_label());
6132 RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt);
6133 // Don't record a deoptimization index for the safepoint here.
6134 // This will be done explicitly when emitting call and the safepoint in
6135 // the deferred code.
6140 void LCodeGen::DoOsrEntry(LOsrEntry* instr) {
6141 // This is a pseudo-instruction that ensures that the environment here is
6142 // properly registered for deoptimization and records the assembler's PC
6144 LEnvironment* environment = instr->environment();
6146 // If the environment were already registered, we would have no way of
6147 // backpatching it with the spill slot operands.
6148 DCHECK(!environment->HasBeenRegistered());
6149 RegisterEnvironmentForDeoptimization(environment, Safepoint::kNoLazyDeopt);
6151 GenerateOsrPrologue();
6155 void LCodeGen::DoForInPrepareMap(LForInPrepareMap* instr) {
6156 DCHECK(ToRegister(instr->context()).is(esi));
6157 __ cmp(eax, isolate()->factory()->undefined_value());
6158 DeoptimizeIf(equal, instr, "undefined");
6160 __ cmp(eax, isolate()->factory()->null_value());
6161 DeoptimizeIf(equal, instr, "null");
6163 __ test(eax, Immediate(kSmiTagMask));
6164 DeoptimizeIf(zero, instr, "Smi");
6166 STATIC_ASSERT(FIRST_JS_PROXY_TYPE == FIRST_SPEC_OBJECT_TYPE);
6167 __ CmpObjectType(eax, LAST_JS_PROXY_TYPE, ecx);
6168 DeoptimizeIf(below_equal, instr, "wrong instance type");
6170 Label use_cache, call_runtime;
6171 __ CheckEnumCache(&call_runtime);
6173 __ mov(eax, FieldOperand(eax, HeapObject::kMapOffset));
6174 __ jmp(&use_cache, Label::kNear);
6176 // Get the set of properties to enumerate.
6177 __ bind(&call_runtime);
6179 CallRuntime(Runtime::kGetPropertyNamesFast, 1, instr);
6181 __ cmp(FieldOperand(eax, HeapObject::kMapOffset),
6182 isolate()->factory()->meta_map());
6183 DeoptimizeIf(not_equal, instr, "wrong map");
6184 __ bind(&use_cache);
6188 void LCodeGen::DoForInCacheArray(LForInCacheArray* instr) {
6189 Register map = ToRegister(instr->map());
6190 Register result = ToRegister(instr->result());
6191 Label load_cache, done;
6192 __ EnumLength(result, map);
6193 __ cmp(result, Immediate(Smi::FromInt(0)));
6194 __ j(not_equal, &load_cache, Label::kNear);
6195 __ mov(result, isolate()->factory()->empty_fixed_array());
6196 __ jmp(&done, Label::kNear);
6198 __ bind(&load_cache);
6199 __ LoadInstanceDescriptors(map, result);
6201 FieldOperand(result, DescriptorArray::kEnumCacheOffset));
6203 FieldOperand(result, FixedArray::SizeFor(instr->idx())));
6205 __ test(result, result);
6206 DeoptimizeIf(equal, instr, "no cache");
6210 void LCodeGen::DoCheckMapValue(LCheckMapValue* instr) {
6211 Register object = ToRegister(instr->value());
6212 __ cmp(ToRegister(instr->map()),
6213 FieldOperand(object, HeapObject::kMapOffset));
6214 DeoptimizeIf(not_equal, instr, "wrong map");
6218 void LCodeGen::DoDeferredLoadMutableDouble(LLoadFieldByIndex* instr,
6221 PushSafepointRegistersScope scope(this);
6225 __ CallRuntimeSaveDoubles(Runtime::kLoadMutableDouble);
6226 RecordSafepointWithRegisters(
6227 instr->pointer_map(), 2, Safepoint::kNoLazyDeopt);
6228 __ StoreToSafepointRegisterSlot(object, eax);
6232 void LCodeGen::DoLoadFieldByIndex(LLoadFieldByIndex* instr) {
6233 class DeferredLoadMutableDouble FINAL : public LDeferredCode {
6235 DeferredLoadMutableDouble(LCodeGen* codegen,
6236 LLoadFieldByIndex* instr,
6239 const X87Stack& x87_stack)
6240 : LDeferredCode(codegen, x87_stack),
6245 virtual void Generate() OVERRIDE {
6246 codegen()->DoDeferredLoadMutableDouble(instr_, object_, index_);
6248 virtual LInstruction* instr() OVERRIDE { return instr_; }
6250 LLoadFieldByIndex* instr_;
6255 Register object = ToRegister(instr->object());
6256 Register index = ToRegister(instr->index());
6258 DeferredLoadMutableDouble* deferred;
6259 deferred = new(zone()) DeferredLoadMutableDouble(
6260 this, instr, object, index, x87_stack_);
6262 Label out_of_object, done;
6263 __ test(index, Immediate(Smi::FromInt(1)));
6264 __ j(not_zero, deferred->entry());
6268 __ cmp(index, Immediate(0));
6269 __ j(less, &out_of_object, Label::kNear);
6270 __ mov(object, FieldOperand(object,
6272 times_half_pointer_size,
6273 JSObject::kHeaderSize));
6274 __ jmp(&done, Label::kNear);
6276 __ bind(&out_of_object);
6277 __ mov(object, FieldOperand(object, JSObject::kPropertiesOffset));
6279 // Index is now equal to out of object property index plus 1.
6280 __ mov(object, FieldOperand(object,
6282 times_half_pointer_size,
6283 FixedArray::kHeaderSize - kPointerSize));
6284 __ bind(deferred->exit());
6289 void LCodeGen::DoStoreFrameContext(LStoreFrameContext* instr) {
6290 Register context = ToRegister(instr->context());
6291 __ mov(Operand(ebp, StandardFrameConstants::kContextOffset), context);
6295 void LCodeGen::DoAllocateBlockContext(LAllocateBlockContext* instr) {
6296 Handle<ScopeInfo> scope_info = instr->scope_info();
6297 __ Push(scope_info);
6298 __ push(ToRegister(instr->function()));
6299 CallRuntime(Runtime::kPushBlockContext, 2, instr);
6300 RecordSafepoint(Safepoint::kNoLazyDeopt);
6306 } } // namespace v8::internal
6308 #endif // V8_TARGET_ARCH_X87