1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #if V8_TARGET_ARCH_IA32
7 #include "src/base/bits.h"
8 #include "src/code-factory.h"
9 #include "src/code-stubs.h"
10 #include "src/codegen.h"
11 #include "src/cpu-profiler.h"
12 #include "src/deoptimizer.h"
13 #include "src/hydrogen-osr.h"
14 #include "src/ia32/frames-ia32.h"
15 #include "src/ia32/lithium-codegen-ia32.h"
16 #include "src/ic/ic.h"
17 #include "src/ic/stub-cache.h"
22 // When invoking builtins, we need to record the safepoint in the middle of
23 // the invoke instruction sequence generated by the macro assembler.
24 class SafepointGenerator final : public CallWrapper {
26 SafepointGenerator(LCodeGen* codegen,
27 LPointerMap* pointers,
28 Safepoint::DeoptMode mode)
32 virtual ~SafepointGenerator() {}
34 void BeforeCall(int call_size) const override {}
36 void AfterCall() const override {
37 codegen_->RecordSafepoint(pointers_, deopt_mode_);
42 LPointerMap* pointers_;
43 Safepoint::DeoptMode deopt_mode_;
49 bool LCodeGen::GenerateCode() {
50 LPhase phase("Z_Code generation", chunk());
54 // Open a frame scope to indicate that there is a frame on the stack. The
55 // MANUAL indicates that the scope shouldn't actually generate code to set up
56 // the frame (that is done in GeneratePrologue).
57 FrameScope frame_scope(masm_, StackFrame::MANUAL);
59 support_aligned_spilled_doubles_ = info()->IsOptimizing();
61 dynamic_frame_alignment_ = info()->IsOptimizing() &&
62 ((chunk()->num_double_slots() > 2 &&
63 !chunk()->graph()->is_recursive()) ||
64 !info()->osr_ast_id().IsNone());
66 return GeneratePrologue() &&
68 GenerateDeferredCode() &&
69 GenerateJumpTable() &&
70 GenerateSafepointTable();
74 void LCodeGen::FinishCode(Handle<Code> code) {
76 code->set_stack_slots(GetStackSlotCount());
77 code->set_safepoint_table_offset(safepoints_.GetCodeOffset());
78 PopulateDeoptimizationData(code);
79 if (!info()->IsStub()) {
80 Deoptimizer::EnsureRelocSpaceForLazyDeoptimization(code);
86 void LCodeGen::MakeSureStackPagesMapped(int offset) {
87 const int kPageSize = 4 * KB;
88 for (offset -= kPageSize; offset > 0; offset -= kPageSize) {
89 __ mov(Operand(esp, offset), eax);
95 void LCodeGen::SaveCallerDoubles() {
96 DCHECK(info()->saves_caller_doubles());
97 DCHECK(NeedsEagerFrame());
98 Comment(";;; Save clobbered callee double registers");
100 BitVector* doubles = chunk()->allocated_double_registers();
101 BitVector::Iterator save_iterator(doubles);
102 while (!save_iterator.Done()) {
103 __ movsd(MemOperand(esp, count * kDoubleSize),
104 XMMRegister::FromAllocationIndex(save_iterator.Current()));
105 save_iterator.Advance();
111 void LCodeGen::RestoreCallerDoubles() {
112 DCHECK(info()->saves_caller_doubles());
113 DCHECK(NeedsEagerFrame());
114 Comment(";;; Restore clobbered callee double registers");
115 BitVector* doubles = chunk()->allocated_double_registers();
116 BitVector::Iterator save_iterator(doubles);
118 while (!save_iterator.Done()) {
119 __ movsd(XMMRegister::FromAllocationIndex(save_iterator.Current()),
120 MemOperand(esp, count * kDoubleSize));
121 save_iterator.Advance();
127 bool LCodeGen::GeneratePrologue() {
128 DCHECK(is_generating());
130 if (info()->IsOptimizing()) {
131 ProfileEntryHookStub::MaybeCallEntryHook(masm_);
134 if (strlen(FLAG_stop_at) > 0 &&
135 info_->literal()->name()->IsUtf8EqualTo(CStrVector(FLAG_stop_at))) {
140 // Sloppy mode functions and builtins need to replace the receiver with the
141 // global proxy when called as functions (without an explicit receiver
143 if (is_sloppy(info()->language_mode()) && info()->MayUseThis() &&
144 !info()->is_native() && info()->scope()->has_this_declaration()) {
146 // +1 for return address.
147 int receiver_offset = (scope()->num_parameters() + 1) * kPointerSize;
148 __ mov(ecx, Operand(esp, receiver_offset));
150 __ cmp(ecx, isolate()->factory()->undefined_value());
151 __ j(not_equal, &ok, Label::kNear);
153 __ mov(ecx, GlobalObjectOperand());
154 __ mov(ecx, FieldOperand(ecx, GlobalObject::kGlobalProxyOffset));
156 __ mov(Operand(esp, receiver_offset), ecx);
161 if (support_aligned_spilled_doubles_ && dynamic_frame_alignment_) {
162 // Move state of dynamic frame alignment into edx.
163 __ Move(edx, Immediate(kNoAlignmentPadding));
165 Label do_not_pad, align_loop;
166 STATIC_ASSERT(kDoubleSize == 2 * kPointerSize);
167 // Align esp + 4 to a multiple of 2 * kPointerSize.
168 __ test(esp, Immediate(kPointerSize));
169 __ j(not_zero, &do_not_pad, Label::kNear);
170 __ push(Immediate(0));
172 __ mov(edx, Immediate(kAlignmentPaddingPushed));
173 // Copy arguments, receiver, and return address.
174 __ mov(ecx, Immediate(scope()->num_parameters() + 2));
176 __ bind(&align_loop);
177 __ mov(eax, Operand(ebx, 1 * kPointerSize));
178 __ mov(Operand(ebx, 0), eax);
179 __ add(Operand(ebx), Immediate(kPointerSize));
181 __ j(not_zero, &align_loop, Label::kNear);
182 __ mov(Operand(ebx, 0), Immediate(kAlignmentZapValue));
183 __ bind(&do_not_pad);
187 info()->set_prologue_offset(masm_->pc_offset());
188 if (NeedsEagerFrame()) {
189 DCHECK(!frame_is_built_);
190 frame_is_built_ = true;
191 if (info()->IsStub()) {
194 __ Prologue(info()->IsCodePreAgingActive());
196 info()->AddNoFrameRange(0, masm_->pc_offset());
199 if (info()->IsOptimizing() &&
200 dynamic_frame_alignment_ &&
202 __ test(esp, Immediate(kPointerSize));
203 __ Assert(zero, kFrameIsExpectedToBeAligned);
206 // Reserve space for the stack slots needed by the code.
207 int slots = GetStackSlotCount();
208 DCHECK(slots != 0 || !info()->IsOptimizing());
211 if (dynamic_frame_alignment_) {
214 __ push(Immediate(kNoAlignmentPadding));
217 if (FLAG_debug_code) {
218 __ sub(Operand(esp), Immediate(slots * kPointerSize));
220 MakeSureStackPagesMapped(slots * kPointerSize);
223 __ mov(Operand(eax), Immediate(slots));
226 __ mov(MemOperand(esp, eax, times_4, 0),
227 Immediate(kSlotsZapValue));
229 __ j(not_zero, &loop);
232 __ sub(Operand(esp), Immediate(slots * kPointerSize));
234 MakeSureStackPagesMapped(slots * kPointerSize);
238 if (support_aligned_spilled_doubles_) {
239 Comment(";;; Store dynamic frame alignment tag for spilled doubles");
240 // Store dynamic frame alignment state in the first local.
241 int offset = JavaScriptFrameConstants::kDynamicAlignmentStateOffset;
242 if (dynamic_frame_alignment_) {
243 __ mov(Operand(ebp, offset), edx);
245 __ mov(Operand(ebp, offset), Immediate(kNoAlignmentPadding));
250 if (info()->saves_caller_doubles()) SaveCallerDoubles();
253 // Possibly allocate a local context.
254 int heap_slots = info_->num_heap_slots() - Context::MIN_CONTEXT_SLOTS;
255 if (heap_slots > 0) {
256 Comment(";;; Allocate local context");
257 bool need_write_barrier = true;
258 // Argument to NewContext is the function, which is still in edi.
259 DCHECK(!info()->scope()->is_script_scope());
260 if (heap_slots <= FastNewContextStub::kMaximumSlots) {
261 FastNewContextStub stub(isolate(), heap_slots);
263 // Result of FastNewContextStub is always in new space.
264 need_write_barrier = false;
267 __ CallRuntime(Runtime::kNewFunctionContext, 1);
269 RecordSafepoint(Safepoint::kNoLazyDeopt);
270 // Context is returned in eax. It replaces the context passed to us.
271 // It's saved in the stack and kept live in esi.
273 __ mov(Operand(ebp, StandardFrameConstants::kContextOffset), eax);
275 // Copy parameters into context if necessary.
276 int num_parameters = scope()->num_parameters();
277 int first_parameter = scope()->has_this_declaration() ? -1 : 0;
278 for (int i = first_parameter; i < num_parameters; i++) {
279 Variable* var = (i == -1) ? scope()->receiver() : scope()->parameter(i);
280 if (var->IsContextSlot()) {
281 int parameter_offset = StandardFrameConstants::kCallerSPOffset +
282 (num_parameters - 1 - i) * kPointerSize;
283 // Load parameter from stack.
284 __ mov(eax, Operand(ebp, parameter_offset));
285 // Store it in the context.
286 int context_offset = Context::SlotOffset(var->index());
287 __ mov(Operand(esi, context_offset), eax);
288 // Update the write barrier. This clobbers eax and ebx.
289 if (need_write_barrier) {
290 __ RecordWriteContextSlot(esi,
295 } else if (FLAG_debug_code) {
297 __ JumpIfInNewSpace(esi, eax, &done, Label::kNear);
298 __ Abort(kExpectedNewSpaceObject);
303 Comment(";;; End allocate local context");
307 if (FLAG_trace && info()->IsOptimizing()) {
308 // We have not executed any compiled code yet, so esi still holds the
310 __ CallRuntime(Runtime::kTraceEnter, 0);
312 return !is_aborted();
316 void LCodeGen::GenerateOsrPrologue() {
317 // Generate the OSR entry prologue at the first unknown OSR value, or if there
318 // are none, at the OSR entrypoint instruction.
319 if (osr_pc_offset_ >= 0) return;
321 osr_pc_offset_ = masm()->pc_offset();
323 // Move state of dynamic frame alignment into edx.
324 __ Move(edx, Immediate(kNoAlignmentPadding));
326 if (support_aligned_spilled_doubles_ && dynamic_frame_alignment_) {
327 Label do_not_pad, align_loop;
328 // Align ebp + 4 to a multiple of 2 * kPointerSize.
329 __ test(ebp, Immediate(kPointerSize));
330 __ j(zero, &do_not_pad, Label::kNear);
331 __ push(Immediate(0));
333 __ mov(edx, Immediate(kAlignmentPaddingPushed));
335 // Move all parts of the frame over one word. The frame consists of:
336 // unoptimized frame slots, alignment state, context, frame pointer, return
337 // address, receiver, and the arguments.
338 __ mov(ecx, Immediate(scope()->num_parameters() +
339 5 + graph()->osr()->UnoptimizedFrameSlots()));
341 __ bind(&align_loop);
342 __ mov(eax, Operand(ebx, 1 * kPointerSize));
343 __ mov(Operand(ebx, 0), eax);
344 __ add(Operand(ebx), Immediate(kPointerSize));
346 __ j(not_zero, &align_loop, Label::kNear);
347 __ mov(Operand(ebx, 0), Immediate(kAlignmentZapValue));
348 __ sub(Operand(ebp), Immediate(kPointerSize));
349 __ bind(&do_not_pad);
352 // Save the first local, which is overwritten by the alignment state.
353 Operand alignment_loc = MemOperand(ebp, -3 * kPointerSize);
354 __ push(alignment_loc);
356 // Set the dynamic frame alignment state.
357 __ mov(alignment_loc, edx);
359 // Adjust the frame size, subsuming the unoptimized frame into the
361 int slots = GetStackSlotCount() - graph()->osr()->UnoptimizedFrameSlots();
363 __ sub(esp, Immediate((slots - 1) * kPointerSize));
367 void LCodeGen::GenerateBodyInstructionPre(LInstruction* instr) {
368 if (instr->IsCall()) {
369 EnsureSpaceForLazyDeopt(Deoptimizer::patch_size());
371 if (!instr->IsLazyBailout() && !instr->IsGap()) {
372 safepoints_.BumpLastLazySafepointIndex();
377 void LCodeGen::GenerateBodyInstructionPost(LInstruction* instr) { }
380 bool LCodeGen::GenerateJumpTable() {
381 if (!jump_table_.length()) return !is_aborted();
384 Comment(";;; -------------------- Jump table --------------------");
386 for (int i = 0; i < jump_table_.length(); i++) {
387 Deoptimizer::JumpTableEntry* table_entry = &jump_table_[i];
388 __ bind(&table_entry->label);
389 Address entry = table_entry->address;
390 DeoptComment(table_entry->deopt_info);
391 if (table_entry->needs_frame) {
392 DCHECK(!info()->saves_caller_doubles());
393 __ push(Immediate(ExternalReference::ForDeoptEntry(entry)));
394 __ call(&needs_frame);
396 if (info()->saves_caller_doubles()) RestoreCallerDoubles();
397 __ call(entry, RelocInfo::RUNTIME_ENTRY);
399 info()->LogDeoptCallPosition(masm()->pc_offset(),
400 table_entry->deopt_info.inlining_id);
402 if (needs_frame.is_linked()) {
403 __ bind(&needs_frame);
406 3: return address <-- esp
411 __ sub(esp, Immediate(kPointerSize)); // Reserve space for stub marker.
412 __ push(MemOperand(esp, kPointerSize)); // Copy return address.
413 __ push(MemOperand(esp, 3 * kPointerSize)); // Copy entry address.
420 0: entry address <-- esp
422 __ mov(MemOperand(esp, 4 * kPointerSize), ebp); // Save ebp.
424 __ mov(ebp, MemOperand(ebp, StandardFrameConstants::kContextOffset));
425 __ mov(MemOperand(esp, 3 * kPointerSize), ebp);
426 // Fill ebp with the right stack frame address.
427 __ lea(ebp, MemOperand(esp, 4 * kPointerSize));
428 // This variant of deopt can only be used with stubs. Since we don't
429 // have a function pointer to install in the stack frame that we're
430 // building, install a special marker there instead.
431 DCHECK(info()->IsStub());
432 __ mov(MemOperand(esp, 2 * kPointerSize),
433 Immediate(Smi::FromInt(StackFrame::STUB)));
440 0: entry address <-- esp
442 __ ret(0); // Call the continuation without clobbering registers.
444 return !is_aborted();
448 bool LCodeGen::GenerateDeferredCode() {
449 DCHECK(is_generating());
450 if (deferred_.length() > 0) {
451 for (int i = 0; !is_aborted() && i < deferred_.length(); i++) {
452 LDeferredCode* code = deferred_[i];
455 instructions_->at(code->instruction_index())->hydrogen_value();
456 RecordAndWritePosition(
457 chunk()->graph()->SourcePositionToScriptPosition(value->position()));
459 Comment(";;; <@%d,#%d> "
460 "-------------------- Deferred %s --------------------",
461 code->instruction_index(),
462 code->instr()->hydrogen_value()->id(),
463 code->instr()->Mnemonic());
464 __ bind(code->entry());
465 if (NeedsDeferredFrame()) {
466 Comment(";;; Build frame");
467 DCHECK(!frame_is_built_);
468 DCHECK(info()->IsStub());
469 frame_is_built_ = true;
470 // Build the frame in such a way that esi isn't trashed.
471 __ push(ebp); // Caller's frame pointer.
472 __ push(Operand(ebp, StandardFrameConstants::kContextOffset));
473 __ push(Immediate(Smi::FromInt(StackFrame::STUB)));
474 __ lea(ebp, Operand(esp, 2 * kPointerSize));
475 Comment(";;; Deferred code");
478 if (NeedsDeferredFrame()) {
479 __ bind(code->done());
480 Comment(";;; Destroy frame");
481 DCHECK(frame_is_built_);
482 frame_is_built_ = false;
486 __ jmp(code->exit());
490 // Deferred code is the last part of the instruction sequence. Mark
491 // the generated code as done unless we bailed out.
492 if (!is_aborted()) status_ = DONE;
493 return !is_aborted();
497 bool LCodeGen::GenerateSafepointTable() {
499 if (!info()->IsStub()) {
500 // For lazy deoptimization we need space to patch a call after every call.
501 // Ensure there is always space for such patching, even if the code ends
503 int target_offset = masm()->pc_offset() + Deoptimizer::patch_size();
504 while (masm()->pc_offset() < target_offset) {
508 safepoints_.Emit(masm(), GetStackSlotCount());
509 return !is_aborted();
513 Register LCodeGen::ToRegister(int index) const {
514 return Register::FromAllocationIndex(index);
518 XMMRegister LCodeGen::ToDoubleRegister(int index) const {
519 return XMMRegister::FromAllocationIndex(index);
523 Register LCodeGen::ToRegister(LOperand* op) const {
524 DCHECK(op->IsRegister());
525 return ToRegister(op->index());
529 XMMRegister LCodeGen::ToDoubleRegister(LOperand* op) const {
530 DCHECK(op->IsDoubleRegister());
531 return ToDoubleRegister(op->index());
535 int32_t LCodeGen::ToInteger32(LConstantOperand* op) const {
536 return ToRepresentation(op, Representation::Integer32());
540 int32_t LCodeGen::ToRepresentation(LConstantOperand* op,
541 const Representation& r) const {
542 HConstant* constant = chunk_->LookupConstant(op);
543 if (r.IsExternal()) {
544 return reinterpret_cast<int32_t>(
545 constant->ExternalReferenceValue().address());
547 int32_t value = constant->Integer32Value();
548 if (r.IsInteger32()) return value;
549 DCHECK(r.IsSmiOrTagged());
550 return reinterpret_cast<int32_t>(Smi::FromInt(value));
554 Handle<Object> LCodeGen::ToHandle(LConstantOperand* op) const {
555 HConstant* constant = chunk_->LookupConstant(op);
556 DCHECK(chunk_->LookupLiteralRepresentation(op).IsSmiOrTagged());
557 return constant->handle(isolate());
561 double LCodeGen::ToDouble(LConstantOperand* op) const {
562 HConstant* constant = chunk_->LookupConstant(op);
563 DCHECK(constant->HasDoubleValue());
564 return constant->DoubleValue();
568 ExternalReference LCodeGen::ToExternalReference(LConstantOperand* op) const {
569 HConstant* constant = chunk_->LookupConstant(op);
570 DCHECK(constant->HasExternalReferenceValue());
571 return constant->ExternalReferenceValue();
575 bool LCodeGen::IsInteger32(LConstantOperand* op) const {
576 return chunk_->LookupLiteralRepresentation(op).IsSmiOrInteger32();
580 bool LCodeGen::IsSmi(LConstantOperand* op) const {
581 return chunk_->LookupLiteralRepresentation(op).IsSmi();
585 static int ArgumentsOffsetWithoutFrame(int index) {
587 return -(index + 1) * kPointerSize + kPCOnStackSize;
591 Operand LCodeGen::ToOperand(LOperand* op) const {
592 if (op->IsRegister()) return Operand(ToRegister(op));
593 if (op->IsDoubleRegister()) return Operand(ToDoubleRegister(op));
594 DCHECK(op->IsStackSlot() || op->IsDoubleStackSlot());
595 if (NeedsEagerFrame()) {
596 return Operand(ebp, StackSlotOffset(op->index()));
598 // Retrieve parameter without eager stack-frame relative to the
600 return Operand(esp, ArgumentsOffsetWithoutFrame(op->index()));
605 Operand LCodeGen::HighOperand(LOperand* op) {
606 DCHECK(op->IsDoubleStackSlot());
607 if (NeedsEagerFrame()) {
608 return Operand(ebp, StackSlotOffset(op->index()) + kPointerSize);
610 // Retrieve parameter without eager stack-frame relative to the
613 esp, ArgumentsOffsetWithoutFrame(op->index()) + kPointerSize);
618 void LCodeGen::WriteTranslation(LEnvironment* environment,
619 Translation* translation) {
620 if (environment == NULL) return;
622 // The translation includes one command per value in the environment.
623 int translation_size = environment->translation_size();
625 WriteTranslation(environment->outer(), translation);
626 WriteTranslationFrame(environment, translation);
628 int object_index = 0;
629 int dematerialized_index = 0;
630 for (int i = 0; i < translation_size; ++i) {
631 LOperand* value = environment->values()->at(i);
633 environment, translation, value, environment->HasTaggedValueAt(i),
634 environment->HasUint32ValueAt(i), &object_index, &dematerialized_index);
639 void LCodeGen::AddToTranslation(LEnvironment* environment,
640 Translation* translation,
644 int* object_index_pointer,
645 int* dematerialized_index_pointer) {
646 if (op == LEnvironment::materialization_marker()) {
647 int object_index = (*object_index_pointer)++;
648 if (environment->ObjectIsDuplicateAt(object_index)) {
649 int dupe_of = environment->ObjectDuplicateOfAt(object_index);
650 translation->DuplicateObject(dupe_of);
653 int object_length = environment->ObjectLengthAt(object_index);
654 if (environment->ObjectIsArgumentsAt(object_index)) {
655 translation->BeginArgumentsObject(object_length);
657 translation->BeginCapturedObject(object_length);
659 int dematerialized_index = *dematerialized_index_pointer;
660 int env_offset = environment->translation_size() + dematerialized_index;
661 *dematerialized_index_pointer += object_length;
662 for (int i = 0; i < object_length; ++i) {
663 LOperand* value = environment->values()->at(env_offset + i);
664 AddToTranslation(environment,
667 environment->HasTaggedValueAt(env_offset + i),
668 environment->HasUint32ValueAt(env_offset + i),
669 object_index_pointer,
670 dematerialized_index_pointer);
675 if (op->IsStackSlot()) {
676 int index = op->index();
678 index += StandardFrameConstants::kFixedFrameSize / kPointerSize;
681 translation->StoreStackSlot(index);
682 } else if (is_uint32) {
683 translation->StoreUint32StackSlot(index);
685 translation->StoreInt32StackSlot(index);
687 } else if (op->IsDoubleStackSlot()) {
688 int index = op->index();
690 index += StandardFrameConstants::kFixedFrameSize / kPointerSize;
692 translation->StoreDoubleStackSlot(index);
693 } else if (op->IsRegister()) {
694 Register reg = ToRegister(op);
696 translation->StoreRegister(reg);
697 } else if (is_uint32) {
698 translation->StoreUint32Register(reg);
700 translation->StoreInt32Register(reg);
702 } else if (op->IsDoubleRegister()) {
703 XMMRegister reg = ToDoubleRegister(op);
704 translation->StoreDoubleRegister(reg);
705 } else if (op->IsConstantOperand()) {
706 HConstant* constant = chunk()->LookupConstant(LConstantOperand::cast(op));
707 int src_index = DefineDeoptimizationLiteral(constant->handle(isolate()));
708 translation->StoreLiteral(src_index);
715 void LCodeGen::CallCodeGeneric(Handle<Code> code,
716 RelocInfo::Mode mode,
718 SafepointMode safepoint_mode) {
719 DCHECK(instr != NULL);
721 RecordSafepointWithLazyDeopt(instr, safepoint_mode);
723 // Signal that we don't inline smi code before these stubs in the
724 // optimizing code generator.
725 if (code->kind() == Code::BINARY_OP_IC ||
726 code->kind() == Code::COMPARE_IC) {
732 void LCodeGen::CallCode(Handle<Code> code,
733 RelocInfo::Mode mode,
734 LInstruction* instr) {
735 CallCodeGeneric(code, mode, instr, RECORD_SIMPLE_SAFEPOINT);
739 void LCodeGen::CallRuntime(const Runtime::Function* fun,
742 SaveFPRegsMode save_doubles) {
743 DCHECK(instr != NULL);
744 DCHECK(instr->HasPointerMap());
746 __ CallRuntime(fun, argc, save_doubles);
748 RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
750 DCHECK(info()->is_calling());
754 void LCodeGen::LoadContextFromDeferred(LOperand* context) {
755 if (context->IsRegister()) {
756 if (!ToRegister(context).is(esi)) {
757 __ mov(esi, ToRegister(context));
759 } else if (context->IsStackSlot()) {
760 __ mov(esi, ToOperand(context));
761 } else if (context->IsConstantOperand()) {
762 HConstant* constant =
763 chunk_->LookupConstant(LConstantOperand::cast(context));
764 __ LoadObject(esi, Handle<Object>::cast(constant->handle(isolate())));
770 void LCodeGen::CallRuntimeFromDeferred(Runtime::FunctionId id,
774 LoadContextFromDeferred(context);
776 __ CallRuntimeSaveDoubles(id);
777 RecordSafepointWithRegisters(
778 instr->pointer_map(), argc, Safepoint::kNoLazyDeopt);
780 DCHECK(info()->is_calling());
784 void LCodeGen::RegisterEnvironmentForDeoptimization(
785 LEnvironment* environment, Safepoint::DeoptMode mode) {
786 environment->set_has_been_used();
787 if (!environment->HasBeenRegistered()) {
788 // Physical stack frame layout:
789 // -x ............. -4 0 ..................................... y
790 // [incoming arguments] [spill slots] [pushed outgoing arguments]
792 // Layout of the environment:
793 // 0 ..................................................... size-1
794 // [parameters] [locals] [expression stack including arguments]
796 // Layout of the translation:
797 // 0 ........................................................ size - 1 + 4
798 // [expression stack including arguments] [locals] [4 words] [parameters]
799 // |>------------ translation_size ------------<|
802 int jsframe_count = 0;
803 for (LEnvironment* e = environment; e != NULL; e = e->outer()) {
805 if (e->frame_type() == JS_FUNCTION) {
809 Translation translation(&translations_, frame_count, jsframe_count, zone());
810 WriteTranslation(environment, &translation);
811 int deoptimization_index = deoptimizations_.length();
812 int pc_offset = masm()->pc_offset();
813 environment->Register(deoptimization_index,
815 (mode == Safepoint::kLazyDeopt) ? pc_offset : -1);
816 deoptimizations_.Add(environment, zone());
821 void LCodeGen::DeoptimizeIf(Condition cc, LInstruction* instr,
822 Deoptimizer::DeoptReason deopt_reason,
823 Deoptimizer::BailoutType bailout_type) {
824 LEnvironment* environment = instr->environment();
825 RegisterEnvironmentForDeoptimization(environment, Safepoint::kNoLazyDeopt);
826 DCHECK(environment->HasBeenRegistered());
827 int id = environment->deoptimization_index();
828 DCHECK(info()->IsOptimizing() || info()->IsStub());
830 Deoptimizer::GetDeoptimizationEntry(isolate(), id, bailout_type);
832 Abort(kBailoutWasNotPrepared);
836 if (DeoptEveryNTimes()) {
837 ExternalReference count = ExternalReference::stress_deopt_count(isolate());
841 __ mov(eax, Operand::StaticVariable(count));
842 __ sub(eax, Immediate(1));
843 __ j(not_zero, &no_deopt, Label::kNear);
844 if (FLAG_trap_on_deopt) __ int3();
845 __ mov(eax, Immediate(FLAG_deopt_every_n_times));
846 __ mov(Operand::StaticVariable(count), eax);
849 DCHECK(frame_is_built_);
850 __ call(entry, RelocInfo::RUNTIME_ENTRY);
852 __ mov(Operand::StaticVariable(count), eax);
857 if (info()->ShouldTrapOnDeopt()) {
859 if (cc != no_condition) __ j(NegateCondition(cc), &done, Label::kNear);
864 Deoptimizer::DeoptInfo deopt_info = MakeDeoptInfo(instr, deopt_reason);
866 DCHECK(info()->IsStub() || frame_is_built_);
867 if (cc == no_condition && frame_is_built_) {
868 DeoptComment(deopt_info);
869 __ call(entry, RelocInfo::RUNTIME_ENTRY);
870 info()->LogDeoptCallPosition(masm()->pc_offset(), deopt_info.inlining_id);
872 Deoptimizer::JumpTableEntry table_entry(entry, deopt_info, bailout_type,
874 // We often have several deopts to the same entry, reuse the last
875 // jump entry if this is the case.
876 if (FLAG_trace_deopt || isolate()->cpu_profiler()->is_profiling() ||
877 jump_table_.is_empty() ||
878 !table_entry.IsEquivalentTo(jump_table_.last())) {
879 jump_table_.Add(table_entry, zone());
881 if (cc == no_condition) {
882 __ jmp(&jump_table_.last().label);
884 __ j(cc, &jump_table_.last().label);
890 void LCodeGen::DeoptimizeIf(Condition cc, LInstruction* instr,
891 Deoptimizer::DeoptReason deopt_reason) {
892 Deoptimizer::BailoutType bailout_type = info()->IsStub()
894 : Deoptimizer::EAGER;
895 DeoptimizeIf(cc, instr, deopt_reason, bailout_type);
899 void LCodeGen::PopulateDeoptimizationData(Handle<Code> code) {
900 int length = deoptimizations_.length();
901 if (length == 0) return;
902 Handle<DeoptimizationInputData> data =
903 DeoptimizationInputData::New(isolate(), length, TENURED);
905 Handle<ByteArray> translations =
906 translations_.CreateByteArray(isolate()->factory());
907 data->SetTranslationByteArray(*translations);
908 data->SetInlinedFunctionCount(Smi::FromInt(inlined_function_count_));
909 data->SetOptimizationId(Smi::FromInt(info_->optimization_id()));
910 if (info_->IsOptimizing()) {
911 // Reference to shared function info does not change between phases.
912 AllowDeferredHandleDereference allow_handle_dereference;
913 data->SetSharedFunctionInfo(*info_->shared_info());
915 data->SetSharedFunctionInfo(Smi::FromInt(0));
917 data->SetWeakCellCache(Smi::FromInt(0));
919 Handle<FixedArray> literals =
920 factory()->NewFixedArray(deoptimization_literals_.length(), TENURED);
921 { AllowDeferredHandleDereference copy_handles;
922 for (int i = 0; i < deoptimization_literals_.length(); i++) {
923 literals->set(i, *deoptimization_literals_[i]);
925 data->SetLiteralArray(*literals);
928 data->SetOsrAstId(Smi::FromInt(info_->osr_ast_id().ToInt()));
929 data->SetOsrPcOffset(Smi::FromInt(osr_pc_offset_));
931 // Populate the deoptimization entries.
932 for (int i = 0; i < length; i++) {
933 LEnvironment* env = deoptimizations_[i];
934 data->SetAstId(i, env->ast_id());
935 data->SetTranslationIndex(i, Smi::FromInt(env->translation_index()));
936 data->SetArgumentsStackHeight(i,
937 Smi::FromInt(env->arguments_stack_height()));
938 data->SetPc(i, Smi::FromInt(env->pc_offset()));
940 code->set_deoptimization_data(*data);
944 void LCodeGen::PopulateDeoptimizationLiteralsWithInlinedFunctions() {
945 DCHECK_EQ(0, deoptimization_literals_.length());
946 for (auto function : chunk()->inlined_functions()) {
947 DefineDeoptimizationLiteral(function);
949 inlined_function_count_ = deoptimization_literals_.length();
953 void LCodeGen::RecordSafepointWithLazyDeopt(
954 LInstruction* instr, SafepointMode safepoint_mode) {
955 if (safepoint_mode == RECORD_SIMPLE_SAFEPOINT) {
956 RecordSafepoint(instr->pointer_map(), Safepoint::kLazyDeopt);
958 DCHECK(safepoint_mode == RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
959 RecordSafepointWithRegisters(
960 instr->pointer_map(), 0, Safepoint::kLazyDeopt);
965 void LCodeGen::RecordSafepoint(
966 LPointerMap* pointers,
967 Safepoint::Kind kind,
969 Safepoint::DeoptMode deopt_mode) {
970 DCHECK(kind == expected_safepoint_kind_);
971 const ZoneList<LOperand*>* operands = pointers->GetNormalizedOperands();
972 Safepoint safepoint =
973 safepoints_.DefineSafepoint(masm(), kind, arguments, deopt_mode);
974 for (int i = 0; i < operands->length(); i++) {
975 LOperand* pointer = operands->at(i);
976 if (pointer->IsStackSlot()) {
977 safepoint.DefinePointerSlot(pointer->index(), zone());
978 } else if (pointer->IsRegister() && (kind & Safepoint::kWithRegisters)) {
979 safepoint.DefinePointerRegister(ToRegister(pointer), zone());
985 void LCodeGen::RecordSafepoint(LPointerMap* pointers,
986 Safepoint::DeoptMode mode) {
987 RecordSafepoint(pointers, Safepoint::kSimple, 0, mode);
991 void LCodeGen::RecordSafepoint(Safepoint::DeoptMode mode) {
992 LPointerMap empty_pointers(zone());
993 RecordSafepoint(&empty_pointers, mode);
997 void LCodeGen::RecordSafepointWithRegisters(LPointerMap* pointers,
999 Safepoint::DeoptMode mode) {
1000 RecordSafepoint(pointers, Safepoint::kWithRegisters, arguments, mode);
1004 void LCodeGen::RecordAndWritePosition(int position) {
1005 if (position == RelocInfo::kNoPosition) return;
1006 masm()->positions_recorder()->RecordPosition(position);
1007 masm()->positions_recorder()->WriteRecordedPositions();
1011 static const char* LabelType(LLabel* label) {
1012 if (label->is_loop_header()) return " (loop header)";
1013 if (label->is_osr_entry()) return " (OSR entry)";
1018 void LCodeGen::DoLabel(LLabel* label) {
1019 Comment(";;; <@%d,#%d> -------------------- B%d%s --------------------",
1020 current_instruction_,
1021 label->hydrogen_value()->id(),
1024 __ bind(label->label());
1025 current_block_ = label->block_id();
1030 void LCodeGen::DoParallelMove(LParallelMove* move) {
1031 resolver_.Resolve(move);
1035 void LCodeGen::DoGap(LGap* gap) {
1036 for (int i = LGap::FIRST_INNER_POSITION;
1037 i <= LGap::LAST_INNER_POSITION;
1039 LGap::InnerPosition inner_pos = static_cast<LGap::InnerPosition>(i);
1040 LParallelMove* move = gap->GetParallelMove(inner_pos);
1041 if (move != NULL) DoParallelMove(move);
1046 void LCodeGen::DoInstructionGap(LInstructionGap* instr) {
1051 void LCodeGen::DoParameter(LParameter* instr) {
1056 void LCodeGen::DoCallStub(LCallStub* instr) {
1057 DCHECK(ToRegister(instr->context()).is(esi));
1058 DCHECK(ToRegister(instr->result()).is(eax));
1059 switch (instr->hydrogen()->major_key()) {
1060 case CodeStub::RegExpExec: {
1061 RegExpExecStub stub(isolate());
1062 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
1065 case CodeStub::SubString: {
1066 SubStringStub stub(isolate());
1067 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
1070 case CodeStub::StringCompare: {
1071 StringCompareStub stub(isolate());
1072 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
1081 void LCodeGen::DoUnknownOSRValue(LUnknownOSRValue* instr) {
1082 GenerateOsrPrologue();
1086 void LCodeGen::DoModByPowerOf2I(LModByPowerOf2I* instr) {
1087 Register dividend = ToRegister(instr->dividend());
1088 int32_t divisor = instr->divisor();
1089 DCHECK(dividend.is(ToRegister(instr->result())));
1091 // Theoretically, a variation of the branch-free code for integer division by
1092 // a power of 2 (calculating the remainder via an additional multiplication
1093 // (which gets simplified to an 'and') and subtraction) should be faster, and
1094 // this is exactly what GCC and clang emit. Nevertheless, benchmarks seem to
1095 // indicate that positive dividends are heavily favored, so the branching
1096 // version performs better.
1097 HMod* hmod = instr->hydrogen();
1098 int32_t mask = divisor < 0 ? -(divisor + 1) : (divisor - 1);
1099 Label dividend_is_not_negative, done;
1100 if (hmod->CheckFlag(HValue::kLeftCanBeNegative)) {
1101 __ test(dividend, dividend);
1102 __ j(not_sign, ÷nd_is_not_negative, Label::kNear);
1103 // Note that this is correct even for kMinInt operands.
1105 __ and_(dividend, mask);
1107 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1108 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1110 __ jmp(&done, Label::kNear);
1113 __ bind(÷nd_is_not_negative);
1114 __ and_(dividend, mask);
1119 void LCodeGen::DoModByConstI(LModByConstI* instr) {
1120 Register dividend = ToRegister(instr->dividend());
1121 int32_t divisor = instr->divisor();
1122 DCHECK(ToRegister(instr->result()).is(eax));
1125 DeoptimizeIf(no_condition, instr, Deoptimizer::kDivisionByZero);
1129 __ TruncatingDiv(dividend, Abs(divisor));
1130 __ imul(edx, edx, Abs(divisor));
1131 __ mov(eax, dividend);
1134 // Check for negative zero.
1135 HMod* hmod = instr->hydrogen();
1136 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1137 Label remainder_not_zero;
1138 __ j(not_zero, &remainder_not_zero, Label::kNear);
1139 __ cmp(dividend, Immediate(0));
1140 DeoptimizeIf(less, instr, Deoptimizer::kMinusZero);
1141 __ bind(&remainder_not_zero);
1146 void LCodeGen::DoModI(LModI* instr) {
1147 HMod* hmod = instr->hydrogen();
1149 Register left_reg = ToRegister(instr->left());
1150 DCHECK(left_reg.is(eax));
1151 Register right_reg = ToRegister(instr->right());
1152 DCHECK(!right_reg.is(eax));
1153 DCHECK(!right_reg.is(edx));
1154 Register result_reg = ToRegister(instr->result());
1155 DCHECK(result_reg.is(edx));
1158 // Check for x % 0, idiv would signal a divide error. We have to
1159 // deopt in this case because we can't return a NaN.
1160 if (hmod->CheckFlag(HValue::kCanBeDivByZero)) {
1161 __ test(right_reg, Operand(right_reg));
1162 DeoptimizeIf(zero, instr, Deoptimizer::kDivisionByZero);
1165 // Check for kMinInt % -1, idiv would signal a divide error. We
1166 // have to deopt if we care about -0, because we can't return that.
1167 if (hmod->CheckFlag(HValue::kCanOverflow)) {
1168 Label no_overflow_possible;
1169 __ cmp(left_reg, kMinInt);
1170 __ j(not_equal, &no_overflow_possible, Label::kNear);
1171 __ cmp(right_reg, -1);
1172 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1173 DeoptimizeIf(equal, instr, Deoptimizer::kMinusZero);
1175 __ j(not_equal, &no_overflow_possible, Label::kNear);
1176 __ Move(result_reg, Immediate(0));
1177 __ jmp(&done, Label::kNear);
1179 __ bind(&no_overflow_possible);
1182 // Sign extend dividend in eax into edx:eax.
1185 // If we care about -0, test if the dividend is <0 and the result is 0.
1186 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1187 Label positive_left;
1188 __ test(left_reg, Operand(left_reg));
1189 __ j(not_sign, &positive_left, Label::kNear);
1191 __ test(result_reg, Operand(result_reg));
1192 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1193 __ jmp(&done, Label::kNear);
1194 __ bind(&positive_left);
1201 void LCodeGen::DoDivByPowerOf2I(LDivByPowerOf2I* instr) {
1202 Register dividend = ToRegister(instr->dividend());
1203 int32_t divisor = instr->divisor();
1204 Register result = ToRegister(instr->result());
1205 DCHECK(divisor == kMinInt || base::bits::IsPowerOfTwo32(Abs(divisor)));
1206 DCHECK(!result.is(dividend));
1208 // Check for (0 / -x) that will produce negative zero.
1209 HDiv* hdiv = instr->hydrogen();
1210 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
1211 __ test(dividend, dividend);
1212 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1214 // Check for (kMinInt / -1).
1215 if (hdiv->CheckFlag(HValue::kCanOverflow) && divisor == -1) {
1216 __ cmp(dividend, kMinInt);
1217 DeoptimizeIf(zero, instr, Deoptimizer::kOverflow);
1219 // Deoptimize if remainder will not be 0.
1220 if (!hdiv->CheckFlag(HInstruction::kAllUsesTruncatingToInt32) &&
1221 divisor != 1 && divisor != -1) {
1222 int32_t mask = divisor < 0 ? -(divisor + 1) : (divisor - 1);
1223 __ test(dividend, Immediate(mask));
1224 DeoptimizeIf(not_zero, instr, Deoptimizer::kLostPrecision);
1226 __ Move(result, dividend);
1227 int32_t shift = WhichPowerOf2Abs(divisor);
1229 // The arithmetic shift is always OK, the 'if' is an optimization only.
1230 if (shift > 1) __ sar(result, 31);
1231 __ shr(result, 32 - shift);
1232 __ add(result, dividend);
1233 __ sar(result, shift);
1235 if (divisor < 0) __ neg(result);
1239 void LCodeGen::DoDivByConstI(LDivByConstI* instr) {
1240 Register dividend = ToRegister(instr->dividend());
1241 int32_t divisor = instr->divisor();
1242 DCHECK(ToRegister(instr->result()).is(edx));
1245 DeoptimizeIf(no_condition, instr, Deoptimizer::kDivisionByZero);
1249 // Check for (0 / -x) that will produce negative zero.
1250 HDiv* hdiv = instr->hydrogen();
1251 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
1252 __ test(dividend, dividend);
1253 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1256 __ TruncatingDiv(dividend, Abs(divisor));
1257 if (divisor < 0) __ neg(edx);
1259 if (!hdiv->CheckFlag(HInstruction::kAllUsesTruncatingToInt32)) {
1261 __ imul(eax, eax, divisor);
1262 __ sub(eax, dividend);
1263 DeoptimizeIf(not_equal, instr, Deoptimizer::kLostPrecision);
1268 // TODO(svenpanne) Refactor this to avoid code duplication with DoFlooringDivI.
1269 void LCodeGen::DoDivI(LDivI* instr) {
1270 HBinaryOperation* hdiv = instr->hydrogen();
1271 Register dividend = ToRegister(instr->dividend());
1272 Register divisor = ToRegister(instr->divisor());
1273 Register remainder = ToRegister(instr->temp());
1274 DCHECK(dividend.is(eax));
1275 DCHECK(remainder.is(edx));
1276 DCHECK(ToRegister(instr->result()).is(eax));
1277 DCHECK(!divisor.is(eax));
1278 DCHECK(!divisor.is(edx));
1281 if (hdiv->CheckFlag(HValue::kCanBeDivByZero)) {
1282 __ test(divisor, divisor);
1283 DeoptimizeIf(zero, instr, Deoptimizer::kDivisionByZero);
1286 // Check for (0 / -x) that will produce negative zero.
1287 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero)) {
1288 Label dividend_not_zero;
1289 __ test(dividend, dividend);
1290 __ j(not_zero, ÷nd_not_zero, Label::kNear);
1291 __ test(divisor, divisor);
1292 DeoptimizeIf(sign, instr, Deoptimizer::kMinusZero);
1293 __ bind(÷nd_not_zero);
1296 // Check for (kMinInt / -1).
1297 if (hdiv->CheckFlag(HValue::kCanOverflow)) {
1298 Label dividend_not_min_int;
1299 __ cmp(dividend, kMinInt);
1300 __ j(not_zero, ÷nd_not_min_int, Label::kNear);
1301 __ cmp(divisor, -1);
1302 DeoptimizeIf(zero, instr, Deoptimizer::kOverflow);
1303 __ bind(÷nd_not_min_int);
1306 // Sign extend to edx (= remainder).
1310 if (!hdiv->CheckFlag(HValue::kAllUsesTruncatingToInt32)) {
1311 // Deoptimize if remainder is not 0.
1312 __ test(remainder, remainder);
1313 DeoptimizeIf(not_zero, instr, Deoptimizer::kLostPrecision);
1318 void LCodeGen::DoFlooringDivByPowerOf2I(LFlooringDivByPowerOf2I* instr) {
1319 Register dividend = ToRegister(instr->dividend());
1320 int32_t divisor = instr->divisor();
1321 DCHECK(dividend.is(ToRegister(instr->result())));
1323 // If the divisor is positive, things are easy: There can be no deopts and we
1324 // can simply do an arithmetic right shift.
1325 if (divisor == 1) return;
1326 int32_t shift = WhichPowerOf2Abs(divisor);
1328 __ sar(dividend, shift);
1332 // If the divisor is negative, we have to negate and handle edge cases.
1334 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1335 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1338 // Dividing by -1 is basically negation, unless we overflow.
1339 if (divisor == -1) {
1340 if (instr->hydrogen()->CheckFlag(HValue::kLeftCanBeMinInt)) {
1341 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1346 // If the negation could not overflow, simply shifting is OK.
1347 if (!instr->hydrogen()->CheckFlag(HValue::kLeftCanBeMinInt)) {
1348 __ sar(dividend, shift);
1352 Label not_kmin_int, done;
1353 __ j(no_overflow, ¬_kmin_int, Label::kNear);
1354 __ mov(dividend, Immediate(kMinInt / divisor));
1355 __ jmp(&done, Label::kNear);
1356 __ bind(¬_kmin_int);
1357 __ sar(dividend, shift);
1362 void LCodeGen::DoFlooringDivByConstI(LFlooringDivByConstI* instr) {
1363 Register dividend = ToRegister(instr->dividend());
1364 int32_t divisor = instr->divisor();
1365 DCHECK(ToRegister(instr->result()).is(edx));
1368 DeoptimizeIf(no_condition, instr, Deoptimizer::kDivisionByZero);
1372 // Check for (0 / -x) that will produce negative zero.
1373 HMathFloorOfDiv* hdiv = instr->hydrogen();
1374 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
1375 __ test(dividend, dividend);
1376 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1379 // Easy case: We need no dynamic check for the dividend and the flooring
1380 // division is the same as the truncating division.
1381 if ((divisor > 0 && !hdiv->CheckFlag(HValue::kLeftCanBeNegative)) ||
1382 (divisor < 0 && !hdiv->CheckFlag(HValue::kLeftCanBePositive))) {
1383 __ TruncatingDiv(dividend, Abs(divisor));
1384 if (divisor < 0) __ neg(edx);
1388 // In the general case we may need to adjust before and after the truncating
1389 // division to get a flooring division.
1390 Register temp = ToRegister(instr->temp3());
1391 DCHECK(!temp.is(dividend) && !temp.is(eax) && !temp.is(edx));
1392 Label needs_adjustment, done;
1393 __ cmp(dividend, Immediate(0));
1394 __ j(divisor > 0 ? less : greater, &needs_adjustment, Label::kNear);
1395 __ TruncatingDiv(dividend, Abs(divisor));
1396 if (divisor < 0) __ neg(edx);
1397 __ jmp(&done, Label::kNear);
1398 __ bind(&needs_adjustment);
1399 __ lea(temp, Operand(dividend, divisor > 0 ? 1 : -1));
1400 __ TruncatingDiv(temp, Abs(divisor));
1401 if (divisor < 0) __ neg(edx);
1407 // TODO(svenpanne) Refactor this to avoid code duplication with DoDivI.
1408 void LCodeGen::DoFlooringDivI(LFlooringDivI* instr) {
1409 HBinaryOperation* hdiv = instr->hydrogen();
1410 Register dividend = ToRegister(instr->dividend());
1411 Register divisor = ToRegister(instr->divisor());
1412 Register remainder = ToRegister(instr->temp());
1413 Register result = ToRegister(instr->result());
1414 DCHECK(dividend.is(eax));
1415 DCHECK(remainder.is(edx));
1416 DCHECK(result.is(eax));
1417 DCHECK(!divisor.is(eax));
1418 DCHECK(!divisor.is(edx));
1421 if (hdiv->CheckFlag(HValue::kCanBeDivByZero)) {
1422 __ test(divisor, divisor);
1423 DeoptimizeIf(zero, instr, Deoptimizer::kDivisionByZero);
1426 // Check for (0 / -x) that will produce negative zero.
1427 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero)) {
1428 Label dividend_not_zero;
1429 __ test(dividend, dividend);
1430 __ j(not_zero, ÷nd_not_zero, Label::kNear);
1431 __ test(divisor, divisor);
1432 DeoptimizeIf(sign, instr, Deoptimizer::kMinusZero);
1433 __ bind(÷nd_not_zero);
1436 // Check for (kMinInt / -1).
1437 if (hdiv->CheckFlag(HValue::kCanOverflow)) {
1438 Label dividend_not_min_int;
1439 __ cmp(dividend, kMinInt);
1440 __ j(not_zero, ÷nd_not_min_int, Label::kNear);
1441 __ cmp(divisor, -1);
1442 DeoptimizeIf(zero, instr, Deoptimizer::kOverflow);
1443 __ bind(÷nd_not_min_int);
1446 // Sign extend to edx (= remainder).
1451 __ test(remainder, remainder);
1452 __ j(zero, &done, Label::kNear);
1453 __ xor_(remainder, divisor);
1454 __ sar(remainder, 31);
1455 __ add(result, remainder);
1460 void LCodeGen::DoMulI(LMulI* instr) {
1461 Register left = ToRegister(instr->left());
1462 LOperand* right = instr->right();
1464 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1465 __ mov(ToRegister(instr->temp()), left);
1468 if (right->IsConstantOperand()) {
1469 // Try strength reductions on the multiplication.
1470 // All replacement instructions are at most as long as the imul
1471 // and have better latency.
1472 int constant = ToInteger32(LConstantOperand::cast(right));
1473 if (constant == -1) {
1475 } else if (constant == 0) {
1476 __ xor_(left, Operand(left));
1477 } else if (constant == 2) {
1478 __ add(left, Operand(left));
1479 } else if (!instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
1480 // If we know that the multiplication can't overflow, it's safe to
1481 // use instructions that don't set the overflow flag for the
1488 __ lea(left, Operand(left, left, times_2, 0));
1494 __ lea(left, Operand(left, left, times_4, 0));
1500 __ lea(left, Operand(left, left, times_8, 0));
1506 __ imul(left, left, constant);
1510 __ imul(left, left, constant);
1513 if (instr->hydrogen()->representation().IsSmi()) {
1516 __ imul(left, ToOperand(right));
1519 if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
1520 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1523 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1524 // Bail out if the result is supposed to be negative zero.
1526 __ test(left, Operand(left));
1527 __ j(not_zero, &done, Label::kNear);
1528 if (right->IsConstantOperand()) {
1529 if (ToInteger32(LConstantOperand::cast(right)) < 0) {
1530 DeoptimizeIf(no_condition, instr, Deoptimizer::kMinusZero);
1531 } else if (ToInteger32(LConstantOperand::cast(right)) == 0) {
1532 __ cmp(ToRegister(instr->temp()), Immediate(0));
1533 DeoptimizeIf(less, instr, Deoptimizer::kMinusZero);
1536 // Test the non-zero operand for negative sign.
1537 __ or_(ToRegister(instr->temp()), ToOperand(right));
1538 DeoptimizeIf(sign, instr, Deoptimizer::kMinusZero);
1545 void LCodeGen::DoBitI(LBitI* instr) {
1546 LOperand* left = instr->left();
1547 LOperand* right = instr->right();
1548 DCHECK(left->Equals(instr->result()));
1549 DCHECK(left->IsRegister());
1551 if (right->IsConstantOperand()) {
1552 int32_t right_operand =
1553 ToRepresentation(LConstantOperand::cast(right),
1554 instr->hydrogen()->representation());
1555 switch (instr->op()) {
1556 case Token::BIT_AND:
1557 __ and_(ToRegister(left), right_operand);
1560 __ or_(ToRegister(left), right_operand);
1562 case Token::BIT_XOR:
1563 if (right_operand == int32_t(~0)) {
1564 __ not_(ToRegister(left));
1566 __ xor_(ToRegister(left), right_operand);
1574 switch (instr->op()) {
1575 case Token::BIT_AND:
1576 __ and_(ToRegister(left), ToOperand(right));
1579 __ or_(ToRegister(left), ToOperand(right));
1581 case Token::BIT_XOR:
1582 __ xor_(ToRegister(left), ToOperand(right));
1592 void LCodeGen::DoShiftI(LShiftI* instr) {
1593 LOperand* left = instr->left();
1594 LOperand* right = instr->right();
1595 DCHECK(left->Equals(instr->result()));
1596 DCHECK(left->IsRegister());
1597 if (right->IsRegister()) {
1598 DCHECK(ToRegister(right).is(ecx));
1600 switch (instr->op()) {
1602 __ ror_cl(ToRegister(left));
1605 __ sar_cl(ToRegister(left));
1608 __ shr_cl(ToRegister(left));
1609 if (instr->can_deopt()) {
1610 __ test(ToRegister(left), ToRegister(left));
1611 DeoptimizeIf(sign, instr, Deoptimizer::kNegativeValue);
1615 __ shl_cl(ToRegister(left));
1622 int value = ToInteger32(LConstantOperand::cast(right));
1623 uint8_t shift_count = static_cast<uint8_t>(value & 0x1F);
1624 switch (instr->op()) {
1626 if (shift_count == 0 && instr->can_deopt()) {
1627 __ test(ToRegister(left), ToRegister(left));
1628 DeoptimizeIf(sign, instr, Deoptimizer::kNegativeValue);
1630 __ ror(ToRegister(left), shift_count);
1634 if (shift_count != 0) {
1635 __ sar(ToRegister(left), shift_count);
1639 if (shift_count != 0) {
1640 __ shr(ToRegister(left), shift_count);
1641 } else if (instr->can_deopt()) {
1642 __ test(ToRegister(left), ToRegister(left));
1643 DeoptimizeIf(sign, instr, Deoptimizer::kNegativeValue);
1647 if (shift_count != 0) {
1648 if (instr->hydrogen_value()->representation().IsSmi() &&
1649 instr->can_deopt()) {
1650 if (shift_count != 1) {
1651 __ shl(ToRegister(left), shift_count - 1);
1653 __ SmiTag(ToRegister(left));
1654 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1656 __ shl(ToRegister(left), shift_count);
1668 void LCodeGen::DoSubI(LSubI* instr) {
1669 LOperand* left = instr->left();
1670 LOperand* right = instr->right();
1671 DCHECK(left->Equals(instr->result()));
1673 if (right->IsConstantOperand()) {
1674 __ sub(ToOperand(left),
1675 ToImmediate(right, instr->hydrogen()->representation()));
1677 __ sub(ToRegister(left), ToOperand(right));
1679 if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
1680 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1685 void LCodeGen::DoConstantI(LConstantI* instr) {
1686 __ Move(ToRegister(instr->result()), Immediate(instr->value()));
1690 void LCodeGen::DoConstantS(LConstantS* instr) {
1691 __ Move(ToRegister(instr->result()), Immediate(instr->value()));
1695 void LCodeGen::DoConstantD(LConstantD* instr) {
1696 uint64_t const bits = instr->bits();
1697 uint32_t const lower = static_cast<uint32_t>(bits);
1698 uint32_t const upper = static_cast<uint32_t>(bits >> 32);
1699 DCHECK(instr->result()->IsDoubleRegister());
1701 XMMRegister result = ToDoubleRegister(instr->result());
1703 __ xorps(result, result);
1705 Register temp = ToRegister(instr->temp());
1706 if (CpuFeatures::IsSupported(SSE4_1)) {
1707 CpuFeatureScope scope2(masm(), SSE4_1);
1709 __ Move(temp, Immediate(lower));
1710 __ movd(result, Operand(temp));
1711 __ Move(temp, Immediate(upper));
1712 __ pinsrd(result, Operand(temp), 1);
1714 __ xorps(result, result);
1715 __ Move(temp, Immediate(upper));
1716 __ pinsrd(result, Operand(temp), 1);
1719 __ Move(temp, Immediate(upper));
1720 __ movd(result, Operand(temp));
1721 __ psllq(result, 32);
1723 XMMRegister xmm_scratch = double_scratch0();
1724 __ Move(temp, Immediate(lower));
1725 __ movd(xmm_scratch, Operand(temp));
1726 __ orps(result, xmm_scratch);
1733 void LCodeGen::DoConstantE(LConstantE* instr) {
1734 __ lea(ToRegister(instr->result()), Operand::StaticVariable(instr->value()));
1738 void LCodeGen::DoConstantT(LConstantT* instr) {
1739 Register reg = ToRegister(instr->result());
1740 Handle<Object> object = instr->value(isolate());
1741 AllowDeferredHandleDereference smi_check;
1742 __ LoadObject(reg, object);
1746 void LCodeGen::DoMapEnumLength(LMapEnumLength* instr) {
1747 Register result = ToRegister(instr->result());
1748 Register map = ToRegister(instr->value());
1749 __ EnumLength(result, map);
1753 void LCodeGen::DoDateField(LDateField* instr) {
1754 Register object = ToRegister(instr->date());
1755 Register result = ToRegister(instr->result());
1756 Register scratch = ToRegister(instr->temp());
1757 Smi* index = instr->index();
1758 DCHECK(object.is(result));
1759 DCHECK(object.is(eax));
1761 if (index->value() == 0) {
1762 __ mov(result, FieldOperand(object, JSDate::kValueOffset));
1764 Label runtime, done;
1765 if (index->value() < JSDate::kFirstUncachedField) {
1766 ExternalReference stamp = ExternalReference::date_cache_stamp(isolate());
1767 __ mov(scratch, Operand::StaticVariable(stamp));
1768 __ cmp(scratch, FieldOperand(object, JSDate::kCacheStampOffset));
1769 __ j(not_equal, &runtime, Label::kNear);
1770 __ mov(result, FieldOperand(object, JSDate::kValueOffset +
1771 kPointerSize * index->value()));
1772 __ jmp(&done, Label::kNear);
1775 __ PrepareCallCFunction(2, scratch);
1776 __ mov(Operand(esp, 0), object);
1777 __ mov(Operand(esp, 1 * kPointerSize), Immediate(index));
1778 __ CallCFunction(ExternalReference::get_date_field_function(isolate()), 2);
1784 Operand LCodeGen::BuildSeqStringOperand(Register string,
1786 String::Encoding encoding) {
1787 if (index->IsConstantOperand()) {
1788 int offset = ToRepresentation(LConstantOperand::cast(index),
1789 Representation::Integer32());
1790 if (encoding == String::TWO_BYTE_ENCODING) {
1791 offset *= kUC16Size;
1793 STATIC_ASSERT(kCharSize == 1);
1794 return FieldOperand(string, SeqString::kHeaderSize + offset);
1796 return FieldOperand(
1797 string, ToRegister(index),
1798 encoding == String::ONE_BYTE_ENCODING ? times_1 : times_2,
1799 SeqString::kHeaderSize);
1803 void LCodeGen::DoSeqStringGetChar(LSeqStringGetChar* instr) {
1804 String::Encoding encoding = instr->hydrogen()->encoding();
1805 Register result = ToRegister(instr->result());
1806 Register string = ToRegister(instr->string());
1808 if (FLAG_debug_code) {
1810 __ mov(string, FieldOperand(string, HeapObject::kMapOffset));
1811 __ movzx_b(string, FieldOperand(string, Map::kInstanceTypeOffset));
1813 __ and_(string, Immediate(kStringRepresentationMask | kStringEncodingMask));
1814 static const uint32_t one_byte_seq_type = kSeqStringTag | kOneByteStringTag;
1815 static const uint32_t two_byte_seq_type = kSeqStringTag | kTwoByteStringTag;
1816 __ cmp(string, Immediate(encoding == String::ONE_BYTE_ENCODING
1817 ? one_byte_seq_type : two_byte_seq_type));
1818 __ Check(equal, kUnexpectedStringType);
1822 Operand operand = BuildSeqStringOperand(string, instr->index(), encoding);
1823 if (encoding == String::ONE_BYTE_ENCODING) {
1824 __ movzx_b(result, operand);
1826 __ movzx_w(result, operand);
1831 void LCodeGen::DoSeqStringSetChar(LSeqStringSetChar* instr) {
1832 String::Encoding encoding = instr->hydrogen()->encoding();
1833 Register string = ToRegister(instr->string());
1835 if (FLAG_debug_code) {
1836 Register value = ToRegister(instr->value());
1837 Register index = ToRegister(instr->index());
1838 static const uint32_t one_byte_seq_type = kSeqStringTag | kOneByteStringTag;
1839 static const uint32_t two_byte_seq_type = kSeqStringTag | kTwoByteStringTag;
1841 instr->hydrogen()->encoding() == String::ONE_BYTE_ENCODING
1842 ? one_byte_seq_type : two_byte_seq_type;
1843 __ EmitSeqStringSetCharCheck(string, index, value, encoding_mask);
1846 Operand operand = BuildSeqStringOperand(string, instr->index(), encoding);
1847 if (instr->value()->IsConstantOperand()) {
1848 int value = ToRepresentation(LConstantOperand::cast(instr->value()),
1849 Representation::Integer32());
1850 DCHECK_LE(0, value);
1851 if (encoding == String::ONE_BYTE_ENCODING) {
1852 DCHECK_LE(value, String::kMaxOneByteCharCode);
1853 __ mov_b(operand, static_cast<int8_t>(value));
1855 DCHECK_LE(value, String::kMaxUtf16CodeUnit);
1856 __ mov_w(operand, static_cast<int16_t>(value));
1859 Register value = ToRegister(instr->value());
1860 if (encoding == String::ONE_BYTE_ENCODING) {
1861 __ mov_b(operand, value);
1863 __ mov_w(operand, value);
1869 void LCodeGen::DoAddI(LAddI* instr) {
1870 LOperand* left = instr->left();
1871 LOperand* right = instr->right();
1873 if (LAddI::UseLea(instr->hydrogen()) && !left->Equals(instr->result())) {
1874 if (right->IsConstantOperand()) {
1875 int32_t offset = ToRepresentation(LConstantOperand::cast(right),
1876 instr->hydrogen()->representation());
1877 __ lea(ToRegister(instr->result()), MemOperand(ToRegister(left), offset));
1879 Operand address(ToRegister(left), ToRegister(right), times_1, 0);
1880 __ lea(ToRegister(instr->result()), address);
1883 if (right->IsConstantOperand()) {
1884 __ add(ToOperand(left),
1885 ToImmediate(right, instr->hydrogen()->representation()));
1887 __ add(ToRegister(left), ToOperand(right));
1889 if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
1890 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1896 void LCodeGen::DoMathMinMax(LMathMinMax* instr) {
1897 LOperand* left = instr->left();
1898 LOperand* right = instr->right();
1899 DCHECK(left->Equals(instr->result()));
1900 HMathMinMax::Operation operation = instr->hydrogen()->operation();
1901 if (instr->hydrogen()->representation().IsSmiOrInteger32()) {
1903 Condition condition = (operation == HMathMinMax::kMathMin)
1906 if (right->IsConstantOperand()) {
1907 Operand left_op = ToOperand(left);
1908 Immediate immediate = ToImmediate(LConstantOperand::cast(instr->right()),
1909 instr->hydrogen()->representation());
1910 __ cmp(left_op, immediate);
1911 __ j(condition, &return_left, Label::kNear);
1912 __ mov(left_op, immediate);
1914 Register left_reg = ToRegister(left);
1915 Operand right_op = ToOperand(right);
1916 __ cmp(left_reg, right_op);
1917 __ j(condition, &return_left, Label::kNear);
1918 __ mov(left_reg, right_op);
1920 __ bind(&return_left);
1922 DCHECK(instr->hydrogen()->representation().IsDouble());
1923 Label check_nan_left, check_zero, return_left, return_right;
1924 Condition condition = (operation == HMathMinMax::kMathMin) ? below : above;
1925 XMMRegister left_reg = ToDoubleRegister(left);
1926 XMMRegister right_reg = ToDoubleRegister(right);
1927 __ ucomisd(left_reg, right_reg);
1928 __ j(parity_even, &check_nan_left, Label::kNear); // At least one NaN.
1929 __ j(equal, &check_zero, Label::kNear); // left == right.
1930 __ j(condition, &return_left, Label::kNear);
1931 __ jmp(&return_right, Label::kNear);
1933 __ bind(&check_zero);
1934 XMMRegister xmm_scratch = double_scratch0();
1935 __ xorps(xmm_scratch, xmm_scratch);
1936 __ ucomisd(left_reg, xmm_scratch);
1937 __ j(not_equal, &return_left, Label::kNear); // left == right != 0.
1938 // At this point, both left and right are either 0 or -0.
1939 if (operation == HMathMinMax::kMathMin) {
1940 __ orpd(left_reg, right_reg);
1942 // Since we operate on +0 and/or -0, addsd and andsd have the same effect.
1943 __ addsd(left_reg, right_reg);
1945 __ jmp(&return_left, Label::kNear);
1947 __ bind(&check_nan_left);
1948 __ ucomisd(left_reg, left_reg); // NaN check.
1949 __ j(parity_even, &return_left, Label::kNear); // left == NaN.
1950 __ bind(&return_right);
1951 __ movaps(left_reg, right_reg);
1953 __ bind(&return_left);
1958 void LCodeGen::DoArithmeticD(LArithmeticD* instr) {
1959 XMMRegister left = ToDoubleRegister(instr->left());
1960 XMMRegister right = ToDoubleRegister(instr->right());
1961 XMMRegister result = ToDoubleRegister(instr->result());
1962 switch (instr->op()) {
1964 if (CpuFeatures::IsSupported(AVX)) {
1965 CpuFeatureScope scope(masm(), AVX);
1966 __ vaddsd(result, left, right);
1968 DCHECK(result.is(left));
1969 __ addsd(left, right);
1973 if (CpuFeatures::IsSupported(AVX)) {
1974 CpuFeatureScope scope(masm(), AVX);
1975 __ vsubsd(result, left, right);
1977 DCHECK(result.is(left));
1978 __ subsd(left, right);
1982 if (CpuFeatures::IsSupported(AVX)) {
1983 CpuFeatureScope scope(masm(), AVX);
1984 __ vmulsd(result, left, right);
1986 DCHECK(result.is(left));
1987 __ mulsd(left, right);
1991 if (CpuFeatures::IsSupported(AVX)) {
1992 CpuFeatureScope scope(masm(), AVX);
1993 __ vdivsd(result, left, right);
1995 DCHECK(result.is(left));
1996 __ divsd(left, right);
1998 // Don't delete this mov. It may improve performance on some CPUs,
1999 // when there is a (v)mulsd depending on the result
2000 __ movaps(result, result);
2003 // Pass two doubles as arguments on the stack.
2004 __ PrepareCallCFunction(4, eax);
2005 __ movsd(Operand(esp, 0 * kDoubleSize), left);
2006 __ movsd(Operand(esp, 1 * kDoubleSize), right);
2008 ExternalReference::mod_two_doubles_operation(isolate()),
2011 // Return value is in st(0) on ia32.
2012 // Store it into the result register.
2013 __ sub(Operand(esp), Immediate(kDoubleSize));
2014 __ fstp_d(Operand(esp, 0));
2015 __ movsd(result, Operand(esp, 0));
2016 __ add(Operand(esp), Immediate(kDoubleSize));
2026 void LCodeGen::DoArithmeticT(LArithmeticT* instr) {
2027 DCHECK(ToRegister(instr->context()).is(esi));
2028 DCHECK(ToRegister(instr->left()).is(edx));
2029 DCHECK(ToRegister(instr->right()).is(eax));
2030 DCHECK(ToRegister(instr->result()).is(eax));
2033 CodeFactory::BinaryOpIC(isolate(), instr->op(), instr->strength()).code();
2034 CallCode(code, RelocInfo::CODE_TARGET, instr);
2038 template<class InstrType>
2039 void LCodeGen::EmitBranch(InstrType instr, Condition cc) {
2040 int left_block = instr->TrueDestination(chunk_);
2041 int right_block = instr->FalseDestination(chunk_);
2043 int next_block = GetNextEmittedBlock();
2045 if (right_block == left_block || cc == no_condition) {
2046 EmitGoto(left_block);
2047 } else if (left_block == next_block) {
2048 __ j(NegateCondition(cc), chunk_->GetAssemblyLabel(right_block));
2049 } else if (right_block == next_block) {
2050 __ j(cc, chunk_->GetAssemblyLabel(left_block));
2052 __ j(cc, chunk_->GetAssemblyLabel(left_block));
2053 __ jmp(chunk_->GetAssemblyLabel(right_block));
2058 template <class InstrType>
2059 void LCodeGen::EmitTrueBranch(InstrType instr, Condition cc) {
2060 int true_block = instr->TrueDestination(chunk_);
2061 if (cc == no_condition) {
2062 __ jmp(chunk_->GetAssemblyLabel(true_block));
2064 __ j(cc, chunk_->GetAssemblyLabel(true_block));
2069 template<class InstrType>
2070 void LCodeGen::EmitFalseBranch(InstrType instr, Condition cc) {
2071 int false_block = instr->FalseDestination(chunk_);
2072 if (cc == no_condition) {
2073 __ jmp(chunk_->GetAssemblyLabel(false_block));
2075 __ j(cc, chunk_->GetAssemblyLabel(false_block));
2080 void LCodeGen::DoBranch(LBranch* instr) {
2081 Representation r = instr->hydrogen()->value()->representation();
2082 if (r.IsSmiOrInteger32()) {
2083 Register reg = ToRegister(instr->value());
2084 __ test(reg, Operand(reg));
2085 EmitBranch(instr, not_zero);
2086 } else if (r.IsDouble()) {
2087 DCHECK(!info()->IsStub());
2088 XMMRegister reg = ToDoubleRegister(instr->value());
2089 XMMRegister xmm_scratch = double_scratch0();
2090 __ xorps(xmm_scratch, xmm_scratch);
2091 __ ucomisd(reg, xmm_scratch);
2092 EmitBranch(instr, not_equal);
2094 DCHECK(r.IsTagged());
2095 Register reg = ToRegister(instr->value());
2096 HType type = instr->hydrogen()->value()->type();
2097 if (type.IsBoolean()) {
2098 DCHECK(!info()->IsStub());
2099 __ cmp(reg, factory()->true_value());
2100 EmitBranch(instr, equal);
2101 } else if (type.IsSmi()) {
2102 DCHECK(!info()->IsStub());
2103 __ test(reg, Operand(reg));
2104 EmitBranch(instr, not_equal);
2105 } else if (type.IsJSArray()) {
2106 DCHECK(!info()->IsStub());
2107 EmitBranch(instr, no_condition);
2108 } else if (type.IsHeapNumber()) {
2109 DCHECK(!info()->IsStub());
2110 XMMRegister xmm_scratch = double_scratch0();
2111 __ xorps(xmm_scratch, xmm_scratch);
2112 __ ucomisd(xmm_scratch, FieldOperand(reg, HeapNumber::kValueOffset));
2113 EmitBranch(instr, not_equal);
2114 } else if (type.IsString()) {
2115 DCHECK(!info()->IsStub());
2116 __ cmp(FieldOperand(reg, String::kLengthOffset), Immediate(0));
2117 EmitBranch(instr, not_equal);
2119 ToBooleanStub::Types expected = instr->hydrogen()->expected_input_types();
2120 if (expected.IsEmpty()) expected = ToBooleanStub::Types::Generic();
2122 if (expected.Contains(ToBooleanStub::UNDEFINED)) {
2123 // undefined -> false.
2124 __ cmp(reg, factory()->undefined_value());
2125 __ j(equal, instr->FalseLabel(chunk_));
2127 if (expected.Contains(ToBooleanStub::BOOLEAN)) {
2129 __ cmp(reg, factory()->true_value());
2130 __ j(equal, instr->TrueLabel(chunk_));
2132 __ cmp(reg, factory()->false_value());
2133 __ j(equal, instr->FalseLabel(chunk_));
2135 if (expected.Contains(ToBooleanStub::NULL_TYPE)) {
2137 __ cmp(reg, factory()->null_value());
2138 __ j(equal, instr->FalseLabel(chunk_));
2141 if (expected.Contains(ToBooleanStub::SMI)) {
2142 // Smis: 0 -> false, all other -> true.
2143 __ test(reg, Operand(reg));
2144 __ j(equal, instr->FalseLabel(chunk_));
2145 __ JumpIfSmi(reg, instr->TrueLabel(chunk_));
2146 } else if (expected.NeedsMap()) {
2147 // If we need a map later and have a Smi -> deopt.
2148 __ test(reg, Immediate(kSmiTagMask));
2149 DeoptimizeIf(zero, instr, Deoptimizer::kSmi);
2152 Register map = no_reg; // Keep the compiler happy.
2153 if (expected.NeedsMap()) {
2154 map = ToRegister(instr->temp());
2155 DCHECK(!map.is(reg));
2156 __ mov(map, FieldOperand(reg, HeapObject::kMapOffset));
2158 if (expected.CanBeUndetectable()) {
2159 // Undetectable -> false.
2160 __ test_b(FieldOperand(map, Map::kBitFieldOffset),
2161 1 << Map::kIsUndetectable);
2162 __ j(not_zero, instr->FalseLabel(chunk_));
2166 if (expected.Contains(ToBooleanStub::SPEC_OBJECT)) {
2167 // spec object -> true.
2168 __ CmpInstanceType(map, FIRST_SPEC_OBJECT_TYPE);
2169 __ j(above_equal, instr->TrueLabel(chunk_));
2172 if (expected.Contains(ToBooleanStub::STRING)) {
2173 // String value -> false iff empty.
2175 __ CmpInstanceType(map, FIRST_NONSTRING_TYPE);
2176 __ j(above_equal, ¬_string, Label::kNear);
2177 __ cmp(FieldOperand(reg, String::kLengthOffset), Immediate(0));
2178 __ j(not_zero, instr->TrueLabel(chunk_));
2179 __ jmp(instr->FalseLabel(chunk_));
2180 __ bind(¬_string);
2183 if (expected.Contains(ToBooleanStub::SYMBOL)) {
2184 // Symbol value -> true.
2185 __ CmpInstanceType(map, SYMBOL_TYPE);
2186 __ j(equal, instr->TrueLabel(chunk_));
2189 if (expected.Contains(ToBooleanStub::SIMD_VALUE)) {
2190 // SIMD value -> true.
2191 __ CmpInstanceType(map, SIMD128_VALUE_TYPE);
2192 __ j(equal, instr->TrueLabel(chunk_));
2195 if (expected.Contains(ToBooleanStub::HEAP_NUMBER)) {
2196 // heap number -> false iff +0, -0, or NaN.
2197 Label not_heap_number;
2198 __ cmp(FieldOperand(reg, HeapObject::kMapOffset),
2199 factory()->heap_number_map());
2200 __ j(not_equal, ¬_heap_number, Label::kNear);
2201 XMMRegister xmm_scratch = double_scratch0();
2202 __ xorps(xmm_scratch, xmm_scratch);
2203 __ ucomisd(xmm_scratch, FieldOperand(reg, HeapNumber::kValueOffset));
2204 __ j(zero, instr->FalseLabel(chunk_));
2205 __ jmp(instr->TrueLabel(chunk_));
2206 __ bind(¬_heap_number);
2209 if (!expected.IsGeneric()) {
2210 // We've seen something for the first time -> deopt.
2211 // This can only happen if we are not generic already.
2212 DeoptimizeIf(no_condition, instr, Deoptimizer::kUnexpectedObject);
2219 void LCodeGen::EmitGoto(int block) {
2220 if (!IsNextEmittedBlock(block)) {
2221 __ jmp(chunk_->GetAssemblyLabel(LookupDestination(block)));
2226 void LCodeGen::DoGoto(LGoto* instr) {
2227 EmitGoto(instr->block_id());
2231 Condition LCodeGen::TokenToCondition(Token::Value op, bool is_unsigned) {
2232 Condition cond = no_condition;
2235 case Token::EQ_STRICT:
2239 case Token::NE_STRICT:
2243 cond = is_unsigned ? below : less;
2246 cond = is_unsigned ? above : greater;
2249 cond = is_unsigned ? below_equal : less_equal;
2252 cond = is_unsigned ? above_equal : greater_equal;
2255 case Token::INSTANCEOF:
2263 void LCodeGen::DoCompareNumericAndBranch(LCompareNumericAndBranch* instr) {
2264 LOperand* left = instr->left();
2265 LOperand* right = instr->right();
2267 instr->is_double() ||
2268 instr->hydrogen()->left()->CheckFlag(HInstruction::kUint32) ||
2269 instr->hydrogen()->right()->CheckFlag(HInstruction::kUint32);
2270 Condition cc = TokenToCondition(instr->op(), is_unsigned);
2272 if (left->IsConstantOperand() && right->IsConstantOperand()) {
2273 // We can statically evaluate the comparison.
2274 double left_val = ToDouble(LConstantOperand::cast(left));
2275 double right_val = ToDouble(LConstantOperand::cast(right));
2276 int next_block = EvalComparison(instr->op(), left_val, right_val) ?
2277 instr->TrueDestination(chunk_) : instr->FalseDestination(chunk_);
2278 EmitGoto(next_block);
2280 if (instr->is_double()) {
2281 __ ucomisd(ToDoubleRegister(left), ToDoubleRegister(right));
2282 // Don't base result on EFLAGS when a NaN is involved. Instead
2283 // jump to the false block.
2284 __ j(parity_even, instr->FalseLabel(chunk_));
2286 if (right->IsConstantOperand()) {
2287 __ cmp(ToOperand(left),
2288 ToImmediate(right, instr->hydrogen()->representation()));
2289 } else if (left->IsConstantOperand()) {
2290 __ cmp(ToOperand(right),
2291 ToImmediate(left, instr->hydrogen()->representation()));
2292 // We commuted the operands, so commute the condition.
2293 cc = CommuteCondition(cc);
2295 __ cmp(ToRegister(left), ToOperand(right));
2298 EmitBranch(instr, cc);
2303 void LCodeGen::DoCmpObjectEqAndBranch(LCmpObjectEqAndBranch* instr) {
2304 Register left = ToRegister(instr->left());
2306 if (instr->right()->IsConstantOperand()) {
2307 Handle<Object> right = ToHandle(LConstantOperand::cast(instr->right()));
2308 __ CmpObject(left, right);
2310 Operand right = ToOperand(instr->right());
2311 __ cmp(left, right);
2313 EmitBranch(instr, equal);
2317 void LCodeGen::DoCmpHoleAndBranch(LCmpHoleAndBranch* instr) {
2318 if (instr->hydrogen()->representation().IsTagged()) {
2319 Register input_reg = ToRegister(instr->object());
2320 __ cmp(input_reg, factory()->the_hole_value());
2321 EmitBranch(instr, equal);
2325 XMMRegister input_reg = ToDoubleRegister(instr->object());
2326 __ ucomisd(input_reg, input_reg);
2327 EmitFalseBranch(instr, parity_odd);
2329 __ sub(esp, Immediate(kDoubleSize));
2330 __ movsd(MemOperand(esp, 0), input_reg);
2332 __ add(esp, Immediate(kDoubleSize));
2333 int offset = sizeof(kHoleNanUpper32);
2334 __ cmp(MemOperand(esp, -offset), Immediate(kHoleNanUpper32));
2335 EmitBranch(instr, equal);
2339 void LCodeGen::DoCompareMinusZeroAndBranch(LCompareMinusZeroAndBranch* instr) {
2340 Representation rep = instr->hydrogen()->value()->representation();
2341 DCHECK(!rep.IsInteger32());
2342 Register scratch = ToRegister(instr->temp());
2344 if (rep.IsDouble()) {
2345 XMMRegister value = ToDoubleRegister(instr->value());
2346 XMMRegister xmm_scratch = double_scratch0();
2347 __ xorps(xmm_scratch, xmm_scratch);
2348 __ ucomisd(xmm_scratch, value);
2349 EmitFalseBranch(instr, not_equal);
2350 __ movmskpd(scratch, value);
2351 __ test(scratch, Immediate(1));
2352 EmitBranch(instr, not_zero);
2354 Register value = ToRegister(instr->value());
2355 Handle<Map> map = masm()->isolate()->factory()->heap_number_map();
2356 __ CheckMap(value, map, instr->FalseLabel(chunk()), DO_SMI_CHECK);
2357 __ cmp(FieldOperand(value, HeapNumber::kExponentOffset),
2359 EmitFalseBranch(instr, no_overflow);
2360 __ cmp(FieldOperand(value, HeapNumber::kMantissaOffset),
2361 Immediate(0x00000000));
2362 EmitBranch(instr, equal);
2367 Condition LCodeGen::EmitIsString(Register input,
2369 Label* is_not_string,
2370 SmiCheck check_needed = INLINE_SMI_CHECK) {
2371 if (check_needed == INLINE_SMI_CHECK) {
2372 __ JumpIfSmi(input, is_not_string);
2375 Condition cond = masm_->IsObjectStringType(input, temp1, temp1);
2381 void LCodeGen::DoIsStringAndBranch(LIsStringAndBranch* instr) {
2382 Register reg = ToRegister(instr->value());
2383 Register temp = ToRegister(instr->temp());
2385 SmiCheck check_needed =
2386 instr->hydrogen()->value()->type().IsHeapObject()
2387 ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
2389 Condition true_cond = EmitIsString(
2390 reg, temp, instr->FalseLabel(chunk_), check_needed);
2392 EmitBranch(instr, true_cond);
2396 void LCodeGen::DoIsSmiAndBranch(LIsSmiAndBranch* instr) {
2397 Operand input = ToOperand(instr->value());
2399 __ test(input, Immediate(kSmiTagMask));
2400 EmitBranch(instr, zero);
2404 void LCodeGen::DoIsUndetectableAndBranch(LIsUndetectableAndBranch* instr) {
2405 Register input = ToRegister(instr->value());
2406 Register temp = ToRegister(instr->temp());
2408 if (!instr->hydrogen()->value()->type().IsHeapObject()) {
2409 STATIC_ASSERT(kSmiTag == 0);
2410 __ JumpIfSmi(input, instr->FalseLabel(chunk_));
2412 __ mov(temp, FieldOperand(input, HeapObject::kMapOffset));
2413 __ test_b(FieldOperand(temp, Map::kBitFieldOffset),
2414 1 << Map::kIsUndetectable);
2415 EmitBranch(instr, not_zero);
2419 static Condition ComputeCompareCondition(Token::Value op) {
2421 case Token::EQ_STRICT:
2431 return greater_equal;
2434 return no_condition;
2439 void LCodeGen::DoStringCompareAndBranch(LStringCompareAndBranch* instr) {
2440 Token::Value op = instr->op();
2443 CodeFactory::CompareIC(isolate(), op, Strength::WEAK).code();
2444 CallCode(ic, RelocInfo::CODE_TARGET, instr);
2446 Condition condition = ComputeCompareCondition(op);
2447 __ test(eax, Operand(eax));
2449 EmitBranch(instr, condition);
2453 static InstanceType TestType(HHasInstanceTypeAndBranch* instr) {
2454 InstanceType from = instr->from();
2455 InstanceType to = instr->to();
2456 if (from == FIRST_TYPE) return to;
2457 DCHECK(from == to || to == LAST_TYPE);
2462 static Condition BranchCondition(HHasInstanceTypeAndBranch* instr) {
2463 InstanceType from = instr->from();
2464 InstanceType to = instr->to();
2465 if (from == to) return equal;
2466 if (to == LAST_TYPE) return above_equal;
2467 if (from == FIRST_TYPE) return below_equal;
2473 void LCodeGen::DoHasInstanceTypeAndBranch(LHasInstanceTypeAndBranch* instr) {
2474 Register input = ToRegister(instr->value());
2475 Register temp = ToRegister(instr->temp());
2477 if (!instr->hydrogen()->value()->type().IsHeapObject()) {
2478 __ JumpIfSmi(input, instr->FalseLabel(chunk_));
2481 __ CmpObjectType(input, TestType(instr->hydrogen()), temp);
2482 EmitBranch(instr, BranchCondition(instr->hydrogen()));
2486 void LCodeGen::DoGetCachedArrayIndex(LGetCachedArrayIndex* instr) {
2487 Register input = ToRegister(instr->value());
2488 Register result = ToRegister(instr->result());
2490 __ AssertString(input);
2492 __ mov(result, FieldOperand(input, String::kHashFieldOffset));
2493 __ IndexFromHash(result, result);
2497 void LCodeGen::DoHasCachedArrayIndexAndBranch(
2498 LHasCachedArrayIndexAndBranch* instr) {
2499 Register input = ToRegister(instr->value());
2501 __ test(FieldOperand(input, String::kHashFieldOffset),
2502 Immediate(String::kContainsCachedArrayIndexMask));
2503 EmitBranch(instr, equal);
2507 // Branches to a label or falls through with the answer in the z flag. Trashes
2508 // the temp registers, but not the input.
2509 void LCodeGen::EmitClassOfTest(Label* is_true,
2511 Handle<String>class_name,
2515 DCHECK(!input.is(temp));
2516 DCHECK(!input.is(temp2));
2517 DCHECK(!temp.is(temp2));
2518 __ JumpIfSmi(input, is_false);
2520 if (String::Equals(isolate()->factory()->Function_string(), class_name)) {
2521 // Assuming the following assertions, we can use the same compares to test
2522 // for both being a function type and being in the object type range.
2523 STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
2524 STATIC_ASSERT(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE ==
2525 FIRST_SPEC_OBJECT_TYPE + 1);
2526 STATIC_ASSERT(LAST_NONCALLABLE_SPEC_OBJECT_TYPE ==
2527 LAST_SPEC_OBJECT_TYPE - 1);
2528 STATIC_ASSERT(LAST_SPEC_OBJECT_TYPE == LAST_TYPE);
2529 __ CmpObjectType(input, FIRST_SPEC_OBJECT_TYPE, temp);
2530 __ j(below, is_false);
2531 __ j(equal, is_true);
2532 __ CmpInstanceType(temp, LAST_SPEC_OBJECT_TYPE);
2533 __ j(equal, is_true);
2535 // Faster code path to avoid two compares: subtract lower bound from the
2536 // actual type and do a signed compare with the width of the type range.
2537 __ mov(temp, FieldOperand(input, HeapObject::kMapOffset));
2538 __ movzx_b(temp2, FieldOperand(temp, Map::kInstanceTypeOffset));
2539 __ sub(Operand(temp2), Immediate(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE));
2540 __ cmp(Operand(temp2), Immediate(LAST_NONCALLABLE_SPEC_OBJECT_TYPE -
2541 FIRST_NONCALLABLE_SPEC_OBJECT_TYPE));
2542 __ j(above, is_false);
2545 // Now we are in the FIRST-LAST_NONCALLABLE_SPEC_OBJECT_TYPE range.
2546 // Check if the constructor in the map is a function.
2547 __ GetMapConstructor(temp, temp, temp2);
2548 // Objects with a non-function constructor have class 'Object'.
2549 __ CmpInstanceType(temp2, JS_FUNCTION_TYPE);
2550 if (String::Equals(class_name, isolate()->factory()->Object_string())) {
2551 __ j(not_equal, is_true);
2553 __ j(not_equal, is_false);
2556 // temp now contains the constructor function. Grab the
2557 // instance class name from there.
2558 __ mov(temp, FieldOperand(temp, JSFunction::kSharedFunctionInfoOffset));
2559 __ mov(temp, FieldOperand(temp,
2560 SharedFunctionInfo::kInstanceClassNameOffset));
2561 // The class name we are testing against is internalized since it's a literal.
2562 // The name in the constructor is internalized because of the way the context
2563 // is booted. This routine isn't expected to work for random API-created
2564 // classes and it doesn't have to because you can't access it with natives
2565 // syntax. Since both sides are internalized it is sufficient to use an
2566 // identity comparison.
2567 __ cmp(temp, class_name);
2568 // End with the answer in the z flag.
2572 void LCodeGen::DoClassOfTestAndBranch(LClassOfTestAndBranch* instr) {
2573 Register input = ToRegister(instr->value());
2574 Register temp = ToRegister(instr->temp());
2575 Register temp2 = ToRegister(instr->temp2());
2577 Handle<String> class_name = instr->hydrogen()->class_name();
2579 EmitClassOfTest(instr->TrueLabel(chunk_), instr->FalseLabel(chunk_),
2580 class_name, input, temp, temp2);
2582 EmitBranch(instr, equal);
2586 void LCodeGen::DoCmpMapAndBranch(LCmpMapAndBranch* instr) {
2587 Register reg = ToRegister(instr->value());
2588 __ cmp(FieldOperand(reg, HeapObject::kMapOffset), instr->map());
2589 EmitBranch(instr, equal);
2593 void LCodeGen::DoInstanceOf(LInstanceOf* instr) {
2594 DCHECK(ToRegister(instr->context()).is(esi));
2595 DCHECK(ToRegister(instr->left()).is(InstanceOfDescriptor::LeftRegister()));
2596 DCHECK(ToRegister(instr->right()).is(InstanceOfDescriptor::RightRegister()));
2597 DCHECK(ToRegister(instr->result()).is(eax));
2598 InstanceOfStub stub(isolate());
2599 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
2603 void LCodeGen::DoHasInPrototypeChainAndBranch(
2604 LHasInPrototypeChainAndBranch* instr) {
2605 Register const object = ToRegister(instr->object());
2606 Register const object_map = ToRegister(instr->scratch());
2607 Register const object_prototype = object_map;
2608 Register const prototype = ToRegister(instr->prototype());
2610 // The {object} must be a spec object. It's sufficient to know that {object}
2611 // is not a smi, since all other non-spec objects have {null} prototypes and
2612 // will be ruled out below.
2613 if (instr->hydrogen()->ObjectNeedsSmiCheck()) {
2614 __ test(object, Immediate(kSmiTagMask));
2615 EmitFalseBranch(instr, zero);
2618 // Loop through the {object}s prototype chain looking for the {prototype}.
2619 __ mov(object_map, FieldOperand(object, HeapObject::kMapOffset));
2622 __ mov(object_prototype, FieldOperand(object_map, Map::kPrototypeOffset));
2623 __ cmp(object_prototype, prototype);
2624 EmitTrueBranch(instr, equal);
2625 __ cmp(object_prototype, factory()->null_value());
2626 EmitFalseBranch(instr, equal);
2627 __ mov(object_map, FieldOperand(object_prototype, HeapObject::kMapOffset));
2632 void LCodeGen::DoCmpT(LCmpT* instr) {
2633 Token::Value op = instr->op();
2636 CodeFactory::CompareIC(isolate(), op, instr->strength()).code();
2637 CallCode(ic, RelocInfo::CODE_TARGET, instr);
2639 Condition condition = ComputeCompareCondition(op);
2640 Label true_value, done;
2641 __ test(eax, Operand(eax));
2642 __ j(condition, &true_value, Label::kNear);
2643 __ mov(ToRegister(instr->result()), factory()->false_value());
2644 __ jmp(&done, Label::kNear);
2645 __ bind(&true_value);
2646 __ mov(ToRegister(instr->result()), factory()->true_value());
2651 void LCodeGen::EmitReturn(LReturn* instr, bool dynamic_frame_alignment) {
2652 int extra_value_count = dynamic_frame_alignment ? 2 : 1;
2654 if (instr->has_constant_parameter_count()) {
2655 int parameter_count = ToInteger32(instr->constant_parameter_count());
2656 if (dynamic_frame_alignment && FLAG_debug_code) {
2658 (parameter_count + extra_value_count) * kPointerSize),
2659 Immediate(kAlignmentZapValue));
2660 __ Assert(equal, kExpectedAlignmentMarker);
2662 __ Ret((parameter_count + extra_value_count) * kPointerSize, ecx);
2664 DCHECK(info()->IsStub()); // Functions would need to drop one more value.
2665 Register reg = ToRegister(instr->parameter_count());
2666 // The argument count parameter is a smi
2668 Register return_addr_reg = reg.is(ecx) ? ebx : ecx;
2669 if (dynamic_frame_alignment && FLAG_debug_code) {
2670 DCHECK(extra_value_count == 2);
2671 __ cmp(Operand(esp, reg, times_pointer_size,
2672 extra_value_count * kPointerSize),
2673 Immediate(kAlignmentZapValue));
2674 __ Assert(equal, kExpectedAlignmentMarker);
2677 // emit code to restore stack based on instr->parameter_count()
2678 __ pop(return_addr_reg); // save return address
2679 if (dynamic_frame_alignment) {
2680 __ inc(reg); // 1 more for alignment
2683 __ shl(reg, kPointerSizeLog2);
2685 __ jmp(return_addr_reg);
2690 void LCodeGen::DoReturn(LReturn* instr) {
2691 if (FLAG_trace && info()->IsOptimizing()) {
2692 // Preserve the return value on the stack and rely on the runtime call
2693 // to return the value in the same register. We're leaving the code
2694 // managed by the register allocator and tearing down the frame, it's
2695 // safe to write to the context register.
2697 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
2698 __ CallRuntime(Runtime::kTraceExit, 1);
2700 if (info()->saves_caller_doubles()) RestoreCallerDoubles();
2701 if (dynamic_frame_alignment_) {
2702 // Fetch the state of the dynamic frame alignment.
2703 __ mov(edx, Operand(ebp,
2704 JavaScriptFrameConstants::kDynamicAlignmentStateOffset));
2706 int no_frame_start = -1;
2707 if (NeedsEagerFrame()) {
2710 no_frame_start = masm_->pc_offset();
2712 if (dynamic_frame_alignment_) {
2714 __ cmp(edx, Immediate(kNoAlignmentPadding));
2715 __ j(equal, &no_padding, Label::kNear);
2717 EmitReturn(instr, true);
2718 __ bind(&no_padding);
2721 EmitReturn(instr, false);
2722 if (no_frame_start != -1) {
2723 info()->AddNoFrameRange(no_frame_start, masm_->pc_offset());
2729 void LCodeGen::EmitVectorLoadICRegisters(T* instr) {
2730 Register vector_register = ToRegister(instr->temp_vector());
2731 Register slot_register = LoadWithVectorDescriptor::SlotRegister();
2732 DCHECK(vector_register.is(LoadWithVectorDescriptor::VectorRegister()));
2733 DCHECK(slot_register.is(eax));
2735 AllowDeferredHandleDereference vector_structure_check;
2736 Handle<TypeFeedbackVector> vector = instr->hydrogen()->feedback_vector();
2737 __ mov(vector_register, vector);
2738 // No need to allocate this register.
2739 FeedbackVectorICSlot slot = instr->hydrogen()->slot();
2740 int index = vector->GetIndex(slot);
2741 __ mov(slot_register, Immediate(Smi::FromInt(index)));
2746 void LCodeGen::EmitVectorStoreICRegisters(T* instr) {
2747 Register vector_register = ToRegister(instr->temp_vector());
2748 Register slot_register = ToRegister(instr->temp_slot());
2750 AllowDeferredHandleDereference vector_structure_check;
2751 Handle<TypeFeedbackVector> vector = instr->hydrogen()->feedback_vector();
2752 __ mov(vector_register, vector);
2753 FeedbackVectorICSlot slot = instr->hydrogen()->slot();
2754 int index = vector->GetIndex(slot);
2755 __ mov(slot_register, Immediate(Smi::FromInt(index)));
2759 void LCodeGen::DoLoadGlobalGeneric(LLoadGlobalGeneric* instr) {
2760 DCHECK(ToRegister(instr->context()).is(esi));
2761 DCHECK(ToRegister(instr->global_object())
2762 .is(LoadDescriptor::ReceiverRegister()));
2763 DCHECK(ToRegister(instr->result()).is(eax));
2765 __ mov(LoadDescriptor::NameRegister(), instr->name());
2766 EmitVectorLoadICRegisters<LLoadGlobalGeneric>(instr);
2768 CodeFactory::LoadICInOptimizedCode(isolate(), instr->typeof_mode(),
2769 SLOPPY, PREMONOMORPHIC).code();
2770 CallCode(ic, RelocInfo::CODE_TARGET, instr);
2774 void LCodeGen::DoLoadGlobalViaContext(LLoadGlobalViaContext* instr) {
2775 DCHECK(ToRegister(instr->context()).is(esi));
2776 DCHECK(ToRegister(instr->result()).is(eax));
2778 int const slot = instr->slot_index();
2779 int const depth = instr->depth();
2780 if (depth <= LoadGlobalViaContextStub::kMaximumDepth) {
2781 __ mov(LoadGlobalViaContextDescriptor::SlotRegister(), Immediate(slot));
2783 CodeFactory::LoadGlobalViaContext(isolate(), depth).code();
2784 CallCode(stub, RelocInfo::CODE_TARGET, instr);
2786 __ Push(Smi::FromInt(slot));
2787 __ CallRuntime(Runtime::kLoadGlobalViaContext, 1);
2792 void LCodeGen::DoLoadContextSlot(LLoadContextSlot* instr) {
2793 Register context = ToRegister(instr->context());
2794 Register result = ToRegister(instr->result());
2795 __ mov(result, ContextOperand(context, instr->slot_index()));
2797 if (instr->hydrogen()->RequiresHoleCheck()) {
2798 __ cmp(result, factory()->the_hole_value());
2799 if (instr->hydrogen()->DeoptimizesOnHole()) {
2800 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
2803 __ j(not_equal, &is_not_hole, Label::kNear);
2804 __ mov(result, factory()->undefined_value());
2805 __ bind(&is_not_hole);
2811 void LCodeGen::DoStoreContextSlot(LStoreContextSlot* instr) {
2812 Register context = ToRegister(instr->context());
2813 Register value = ToRegister(instr->value());
2815 Label skip_assignment;
2817 Operand target = ContextOperand(context, instr->slot_index());
2818 if (instr->hydrogen()->RequiresHoleCheck()) {
2819 __ cmp(target, factory()->the_hole_value());
2820 if (instr->hydrogen()->DeoptimizesOnHole()) {
2821 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
2823 __ j(not_equal, &skip_assignment, Label::kNear);
2827 __ mov(target, value);
2828 if (instr->hydrogen()->NeedsWriteBarrier()) {
2829 SmiCheck check_needed =
2830 instr->hydrogen()->value()->type().IsHeapObject()
2831 ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
2832 Register temp = ToRegister(instr->temp());
2833 int offset = Context::SlotOffset(instr->slot_index());
2834 __ RecordWriteContextSlot(context,
2839 EMIT_REMEMBERED_SET,
2843 __ bind(&skip_assignment);
2847 void LCodeGen::DoLoadNamedField(LLoadNamedField* instr) {
2848 HObjectAccess access = instr->hydrogen()->access();
2849 int offset = access.offset();
2851 if (access.IsExternalMemory()) {
2852 Register result = ToRegister(instr->result());
2853 MemOperand operand = instr->object()->IsConstantOperand()
2854 ? MemOperand::StaticVariable(ToExternalReference(
2855 LConstantOperand::cast(instr->object())))
2856 : MemOperand(ToRegister(instr->object()), offset);
2857 __ Load(result, operand, access.representation());
2861 Register object = ToRegister(instr->object());
2862 if (instr->hydrogen()->representation().IsDouble()) {
2863 XMMRegister result = ToDoubleRegister(instr->result());
2864 __ movsd(result, FieldOperand(object, offset));
2868 Register result = ToRegister(instr->result());
2869 if (!access.IsInobject()) {
2870 __ mov(result, FieldOperand(object, JSObject::kPropertiesOffset));
2873 __ Load(result, FieldOperand(object, offset), access.representation());
2877 void LCodeGen::EmitPushTaggedOperand(LOperand* operand) {
2878 DCHECK(!operand->IsDoubleRegister());
2879 if (operand->IsConstantOperand()) {
2880 Handle<Object> object = ToHandle(LConstantOperand::cast(operand));
2881 AllowDeferredHandleDereference smi_check;
2882 if (object->IsSmi()) {
2883 __ Push(Handle<Smi>::cast(object));
2885 __ PushHeapObject(Handle<HeapObject>::cast(object));
2887 } else if (operand->IsRegister()) {
2888 __ push(ToRegister(operand));
2890 __ push(ToOperand(operand));
2895 void LCodeGen::DoLoadNamedGeneric(LLoadNamedGeneric* instr) {
2896 DCHECK(ToRegister(instr->context()).is(esi));
2897 DCHECK(ToRegister(instr->object()).is(LoadDescriptor::ReceiverRegister()));
2898 DCHECK(ToRegister(instr->result()).is(eax));
2900 __ mov(LoadDescriptor::NameRegister(), instr->name());
2901 EmitVectorLoadICRegisters<LLoadNamedGeneric>(instr);
2903 CodeFactory::LoadICInOptimizedCode(
2904 isolate(), NOT_INSIDE_TYPEOF, instr->hydrogen()->language_mode(),
2905 instr->hydrogen()->initialization_state()).code();
2906 CallCode(ic, RelocInfo::CODE_TARGET, instr);
2910 void LCodeGen::DoLoadFunctionPrototype(LLoadFunctionPrototype* instr) {
2911 Register function = ToRegister(instr->function());
2912 Register temp = ToRegister(instr->temp());
2913 Register result = ToRegister(instr->result());
2915 // Get the prototype or initial map from the function.
2917 FieldOperand(function, JSFunction::kPrototypeOrInitialMapOffset));
2919 // Check that the function has a prototype or an initial map.
2920 __ cmp(Operand(result), Immediate(factory()->the_hole_value()));
2921 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
2923 // If the function does not have an initial map, we're done.
2925 __ CmpObjectType(result, MAP_TYPE, temp);
2926 __ j(not_equal, &done, Label::kNear);
2928 // Get the prototype from the initial map.
2929 __ mov(result, FieldOperand(result, Map::kPrototypeOffset));
2936 void LCodeGen::DoLoadRoot(LLoadRoot* instr) {
2937 Register result = ToRegister(instr->result());
2938 __ LoadRoot(result, instr->index());
2942 void LCodeGen::DoAccessArgumentsAt(LAccessArgumentsAt* instr) {
2943 Register arguments = ToRegister(instr->arguments());
2944 Register result = ToRegister(instr->result());
2945 if (instr->length()->IsConstantOperand() &&
2946 instr->index()->IsConstantOperand()) {
2947 int const_index = ToInteger32(LConstantOperand::cast(instr->index()));
2948 int const_length = ToInteger32(LConstantOperand::cast(instr->length()));
2949 int index = (const_length - const_index) + 1;
2950 __ mov(result, Operand(arguments, index * kPointerSize));
2952 Register length = ToRegister(instr->length());
2953 Operand index = ToOperand(instr->index());
2954 // There are two words between the frame pointer and the last argument.
2955 // Subtracting from length accounts for one of them add one more.
2956 __ sub(length, index);
2957 __ mov(result, Operand(arguments, length, times_4, kPointerSize));
2962 void LCodeGen::DoLoadKeyedExternalArray(LLoadKeyed* instr) {
2963 ElementsKind elements_kind = instr->elements_kind();
2964 LOperand* key = instr->key();
2965 if (!key->IsConstantOperand() &&
2966 ExternalArrayOpRequiresTemp(instr->hydrogen()->key()->representation(),
2968 __ SmiUntag(ToRegister(key));
2970 Operand operand(BuildFastArrayOperand(
2973 instr->hydrogen()->key()->representation(),
2975 instr->base_offset()));
2976 if (elements_kind == FLOAT32_ELEMENTS) {
2977 XMMRegister result(ToDoubleRegister(instr->result()));
2978 __ movss(result, operand);
2979 __ cvtss2sd(result, result);
2980 } else if (elements_kind == FLOAT64_ELEMENTS) {
2981 __ movsd(ToDoubleRegister(instr->result()), operand);
2983 Register result(ToRegister(instr->result()));
2984 switch (elements_kind) {
2986 __ movsx_b(result, operand);
2988 case UINT8_ELEMENTS:
2989 case UINT8_CLAMPED_ELEMENTS:
2990 __ movzx_b(result, operand);
2992 case INT16_ELEMENTS:
2993 __ movsx_w(result, operand);
2995 case UINT16_ELEMENTS:
2996 __ movzx_w(result, operand);
2998 case INT32_ELEMENTS:
2999 __ mov(result, operand);
3001 case UINT32_ELEMENTS:
3002 __ mov(result, operand);
3003 if (!instr->hydrogen()->CheckFlag(HInstruction::kUint32)) {
3004 __ test(result, Operand(result));
3005 DeoptimizeIf(negative, instr, Deoptimizer::kNegativeValue);
3008 case FLOAT32_ELEMENTS:
3009 case FLOAT64_ELEMENTS:
3010 case FAST_SMI_ELEMENTS:
3012 case FAST_DOUBLE_ELEMENTS:
3013 case FAST_HOLEY_SMI_ELEMENTS:
3014 case FAST_HOLEY_ELEMENTS:
3015 case FAST_HOLEY_DOUBLE_ELEMENTS:
3016 case DICTIONARY_ELEMENTS:
3017 case FAST_SLOPPY_ARGUMENTS_ELEMENTS:
3018 case SLOW_SLOPPY_ARGUMENTS_ELEMENTS:
3026 void LCodeGen::DoLoadKeyedFixedDoubleArray(LLoadKeyed* instr) {
3027 if (instr->hydrogen()->RequiresHoleCheck()) {
3028 Operand hole_check_operand = BuildFastArrayOperand(
3029 instr->elements(), instr->key(),
3030 instr->hydrogen()->key()->representation(),
3031 FAST_DOUBLE_ELEMENTS,
3032 instr->base_offset() + sizeof(kHoleNanLower32));
3033 __ cmp(hole_check_operand, Immediate(kHoleNanUpper32));
3034 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3037 Operand double_load_operand = BuildFastArrayOperand(
3040 instr->hydrogen()->key()->representation(),
3041 FAST_DOUBLE_ELEMENTS,
3042 instr->base_offset());
3043 XMMRegister result = ToDoubleRegister(instr->result());
3044 __ movsd(result, double_load_operand);
3048 void LCodeGen::DoLoadKeyedFixedArray(LLoadKeyed* instr) {
3049 Register result = ToRegister(instr->result());
3053 BuildFastArrayOperand(instr->elements(), instr->key(),
3054 instr->hydrogen()->key()->representation(),
3055 FAST_ELEMENTS, instr->base_offset()));
3057 // Check for the hole value.
3058 if (instr->hydrogen()->RequiresHoleCheck()) {
3059 if (IsFastSmiElementsKind(instr->hydrogen()->elements_kind())) {
3060 __ test(result, Immediate(kSmiTagMask));
3061 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotASmi);
3063 __ cmp(result, factory()->the_hole_value());
3064 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3066 } else if (instr->hydrogen()->hole_mode() == CONVERT_HOLE_TO_UNDEFINED) {
3067 DCHECK(instr->hydrogen()->elements_kind() == FAST_HOLEY_ELEMENTS);
3069 __ cmp(result, factory()->the_hole_value());
3070 __ j(not_equal, &done);
3071 if (info()->IsStub()) {
3072 // A stub can safely convert the hole to undefined only if the array
3073 // protector cell contains (Smi) Isolate::kArrayProtectorValid. Otherwise
3074 // it needs to bail out.
3075 __ mov(result, isolate()->factory()->array_protector());
3076 __ cmp(FieldOperand(result, PropertyCell::kValueOffset),
3077 Immediate(Smi::FromInt(Isolate::kArrayProtectorValid)));
3078 DeoptimizeIf(not_equal, instr, Deoptimizer::kHole);
3080 __ mov(result, isolate()->factory()->undefined_value());
3086 void LCodeGen::DoLoadKeyed(LLoadKeyed* instr) {
3087 if (instr->is_fixed_typed_array()) {
3088 DoLoadKeyedExternalArray(instr);
3089 } else if (instr->hydrogen()->representation().IsDouble()) {
3090 DoLoadKeyedFixedDoubleArray(instr);
3092 DoLoadKeyedFixedArray(instr);
3097 Operand LCodeGen::BuildFastArrayOperand(
3098 LOperand* elements_pointer,
3100 Representation key_representation,
3101 ElementsKind elements_kind,
3102 uint32_t base_offset) {
3103 Register elements_pointer_reg = ToRegister(elements_pointer);
3104 int element_shift_size = ElementsKindToShiftSize(elements_kind);
3105 int shift_size = element_shift_size;
3106 if (key->IsConstantOperand()) {
3107 int constant_value = ToInteger32(LConstantOperand::cast(key));
3108 if (constant_value & 0xF0000000) {
3109 Abort(kArrayIndexConstantValueTooBig);
3111 return Operand(elements_pointer_reg,
3112 ((constant_value) << shift_size)
3115 // Take the tag bit into account while computing the shift size.
3116 if (key_representation.IsSmi() && (shift_size >= 1)) {
3117 shift_size -= kSmiTagSize;
3119 ScaleFactor scale_factor = static_cast<ScaleFactor>(shift_size);
3120 return Operand(elements_pointer_reg,
3128 void LCodeGen::DoLoadKeyedGeneric(LLoadKeyedGeneric* instr) {
3129 DCHECK(ToRegister(instr->context()).is(esi));
3130 DCHECK(ToRegister(instr->object()).is(LoadDescriptor::ReceiverRegister()));
3131 DCHECK(ToRegister(instr->key()).is(LoadDescriptor::NameRegister()));
3133 if (instr->hydrogen()->HasVectorAndSlot()) {
3134 EmitVectorLoadICRegisters<LLoadKeyedGeneric>(instr);
3137 Handle<Code> ic = CodeFactory::KeyedLoadICInOptimizedCode(
3138 isolate(), instr->hydrogen()->language_mode(),
3139 instr->hydrogen()->initialization_state()).code();
3140 CallCode(ic, RelocInfo::CODE_TARGET, instr);
3144 void LCodeGen::DoArgumentsElements(LArgumentsElements* instr) {
3145 Register result = ToRegister(instr->result());
3147 if (instr->hydrogen()->from_inlined()) {
3148 __ lea(result, Operand(esp, -2 * kPointerSize));
3150 // Check for arguments adapter frame.
3151 Label done, adapted;
3152 __ mov(result, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3153 __ mov(result, Operand(result, StandardFrameConstants::kContextOffset));
3154 __ cmp(Operand(result),
3155 Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
3156 __ j(equal, &adapted, Label::kNear);
3158 // No arguments adaptor frame.
3159 __ mov(result, Operand(ebp));
3160 __ jmp(&done, Label::kNear);
3162 // Arguments adaptor frame present.
3164 __ mov(result, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3166 // Result is the frame pointer for the frame if not adapted and for the real
3167 // frame below the adaptor frame if adapted.
3173 void LCodeGen::DoArgumentsLength(LArgumentsLength* instr) {
3174 Operand elem = ToOperand(instr->elements());
3175 Register result = ToRegister(instr->result());
3179 // If no arguments adaptor frame the number of arguments is fixed.
3181 __ mov(result, Immediate(scope()->num_parameters()));
3182 __ j(equal, &done, Label::kNear);
3184 // Arguments adaptor frame present. Get argument length from there.
3185 __ mov(result, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3186 __ mov(result, Operand(result,
3187 ArgumentsAdaptorFrameConstants::kLengthOffset));
3188 __ SmiUntag(result);
3190 // Argument length is in result register.
3195 void LCodeGen::DoWrapReceiver(LWrapReceiver* instr) {
3196 Register receiver = ToRegister(instr->receiver());
3197 Register function = ToRegister(instr->function());
3199 // If the receiver is null or undefined, we have to pass the global
3200 // object as a receiver to normal functions. Values have to be
3201 // passed unchanged to builtins and strict-mode functions.
3202 Label receiver_ok, global_object;
3203 Label::Distance dist = DeoptEveryNTimes() ? Label::kFar : Label::kNear;
3204 Register scratch = ToRegister(instr->temp());
3206 if (!instr->hydrogen()->known_function()) {
3207 // Do not transform the receiver to object for strict mode
3210 FieldOperand(function, JSFunction::kSharedFunctionInfoOffset));
3211 __ test_b(FieldOperand(scratch, SharedFunctionInfo::kStrictModeByteOffset),
3212 1 << SharedFunctionInfo::kStrictModeBitWithinByte);
3213 __ j(not_equal, &receiver_ok, dist);
3215 // Do not transform the receiver to object for builtins.
3216 __ test_b(FieldOperand(scratch, SharedFunctionInfo::kNativeByteOffset),
3217 1 << SharedFunctionInfo::kNativeBitWithinByte);
3218 __ j(not_equal, &receiver_ok, dist);
3221 // Normal function. Replace undefined or null with global receiver.
3222 __ cmp(receiver, factory()->null_value());
3223 __ j(equal, &global_object, Label::kNear);
3224 __ cmp(receiver, factory()->undefined_value());
3225 __ j(equal, &global_object, Label::kNear);
3227 // The receiver should be a JS object.
3228 __ test(receiver, Immediate(kSmiTagMask));
3229 DeoptimizeIf(equal, instr, Deoptimizer::kSmi);
3230 __ CmpObjectType(receiver, FIRST_SPEC_OBJECT_TYPE, scratch);
3231 DeoptimizeIf(below, instr, Deoptimizer::kNotAJavaScriptObject);
3233 __ jmp(&receiver_ok, Label::kNear);
3234 __ bind(&global_object);
3235 __ mov(receiver, FieldOperand(function, JSFunction::kContextOffset));
3236 const int global_offset = Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX);
3237 __ mov(receiver, Operand(receiver, global_offset));
3238 const int proxy_offset = GlobalObject::kGlobalProxyOffset;
3239 __ mov(receiver, FieldOperand(receiver, proxy_offset));
3240 __ bind(&receiver_ok);
3244 void LCodeGen::DoApplyArguments(LApplyArguments* instr) {
3245 Register receiver = ToRegister(instr->receiver());
3246 Register function = ToRegister(instr->function());
3247 Register length = ToRegister(instr->length());
3248 Register elements = ToRegister(instr->elements());
3249 DCHECK(receiver.is(eax)); // Used for parameter count.
3250 DCHECK(function.is(edi)); // Required by InvokeFunction.
3251 DCHECK(ToRegister(instr->result()).is(eax));
3253 // Copy the arguments to this function possibly from the
3254 // adaptor frame below it.
3255 const uint32_t kArgumentsLimit = 1 * KB;
3256 __ cmp(length, kArgumentsLimit);
3257 DeoptimizeIf(above, instr, Deoptimizer::kTooManyArguments);
3260 __ mov(receiver, length);
3262 // Loop through the arguments pushing them onto the execution
3265 // length is a small non-negative integer, due to the test above.
3266 __ test(length, Operand(length));
3267 __ j(zero, &invoke, Label::kNear);
3269 __ push(Operand(elements, length, times_pointer_size, 1 * kPointerSize));
3271 __ j(not_zero, &loop);
3273 // Invoke the function.
3275 DCHECK(instr->HasPointerMap());
3276 LPointerMap* pointers = instr->pointer_map();
3277 SafepointGenerator safepoint_generator(
3278 this, pointers, Safepoint::kLazyDeopt);
3279 ParameterCount actual(eax);
3280 __ InvokeFunction(function, actual, CALL_FUNCTION, safepoint_generator);
3284 void LCodeGen::DoDebugBreak(LDebugBreak* instr) {
3289 void LCodeGen::DoPushArgument(LPushArgument* instr) {
3290 LOperand* argument = instr->value();
3291 EmitPushTaggedOperand(argument);
3295 void LCodeGen::DoDrop(LDrop* instr) {
3296 __ Drop(instr->count());
3300 void LCodeGen::DoThisFunction(LThisFunction* instr) {
3301 Register result = ToRegister(instr->result());
3302 __ mov(result, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
3306 void LCodeGen::DoContext(LContext* instr) {
3307 Register result = ToRegister(instr->result());
3308 if (info()->IsOptimizing()) {
3309 __ mov(result, Operand(ebp, StandardFrameConstants::kContextOffset));
3311 // If there is no frame, the context must be in esi.
3312 DCHECK(result.is(esi));
3317 void LCodeGen::DoDeclareGlobals(LDeclareGlobals* instr) {
3318 DCHECK(ToRegister(instr->context()).is(esi));
3319 __ push(Immediate(instr->hydrogen()->pairs()));
3320 __ push(Immediate(Smi::FromInt(instr->hydrogen()->flags())));
3321 CallRuntime(Runtime::kDeclareGlobals, 2, instr);
3325 void LCodeGen::CallKnownFunction(Handle<JSFunction> function,
3326 int formal_parameter_count, int arity,
3327 LInstruction* instr) {
3328 bool dont_adapt_arguments =
3329 formal_parameter_count == SharedFunctionInfo::kDontAdaptArgumentsSentinel;
3330 bool can_invoke_directly =
3331 dont_adapt_arguments || formal_parameter_count == arity;
3333 Register function_reg = edi;
3335 if (can_invoke_directly) {
3337 __ mov(esi, FieldOperand(function_reg, JSFunction::kContextOffset));
3339 // Set eax to arguments count if adaption is not needed. Assumes that eax
3340 // is available to write to at this point.
3341 if (dont_adapt_arguments) {
3345 // Invoke function directly.
3346 if (function.is_identical_to(info()->closure())) {
3349 __ call(FieldOperand(function_reg, JSFunction::kCodeEntryOffset));
3351 RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
3353 // We need to adapt arguments.
3354 LPointerMap* pointers = instr->pointer_map();
3355 SafepointGenerator generator(
3356 this, pointers, Safepoint::kLazyDeopt);
3357 ParameterCount count(arity);
3358 ParameterCount expected(formal_parameter_count);
3359 __ InvokeFunction(function_reg, expected, count, CALL_FUNCTION, generator);
3364 void LCodeGen::DoCallWithDescriptor(LCallWithDescriptor* instr) {
3365 DCHECK(ToRegister(instr->result()).is(eax));
3367 if (instr->hydrogen()->IsTailCall()) {
3368 if (NeedsEagerFrame()) __ leave();
3370 if (instr->target()->IsConstantOperand()) {
3371 LConstantOperand* target = LConstantOperand::cast(instr->target());
3372 Handle<Code> code = Handle<Code>::cast(ToHandle(target));
3373 __ jmp(code, RelocInfo::CODE_TARGET);
3375 DCHECK(instr->target()->IsRegister());
3376 Register target = ToRegister(instr->target());
3377 __ add(target, Immediate(Code::kHeaderSize - kHeapObjectTag));
3381 LPointerMap* pointers = instr->pointer_map();
3382 SafepointGenerator generator(this, pointers, Safepoint::kLazyDeopt);
3384 if (instr->target()->IsConstantOperand()) {
3385 LConstantOperand* target = LConstantOperand::cast(instr->target());
3386 Handle<Code> code = Handle<Code>::cast(ToHandle(target));
3387 generator.BeforeCall(__ CallSize(code, RelocInfo::CODE_TARGET));
3388 __ call(code, RelocInfo::CODE_TARGET);
3390 DCHECK(instr->target()->IsRegister());
3391 Register target = ToRegister(instr->target());
3392 generator.BeforeCall(__ CallSize(Operand(target)));
3393 __ add(target, Immediate(Code::kHeaderSize - kHeapObjectTag));
3396 generator.AfterCall();
3401 void LCodeGen::DoCallJSFunction(LCallJSFunction* instr) {
3402 DCHECK(ToRegister(instr->function()).is(edi));
3403 DCHECK(ToRegister(instr->result()).is(eax));
3405 if (instr->hydrogen()->pass_argument_count()) {
3406 __ mov(eax, instr->arity());
3410 __ mov(esi, FieldOperand(edi, JSFunction::kContextOffset));
3412 bool is_self_call = false;
3413 if (instr->hydrogen()->function()->IsConstant()) {
3414 HConstant* fun_const = HConstant::cast(instr->hydrogen()->function());
3415 Handle<JSFunction> jsfun =
3416 Handle<JSFunction>::cast(fun_const->handle(isolate()));
3417 is_self_call = jsfun.is_identical_to(info()->closure());
3423 __ call(FieldOperand(edi, JSFunction::kCodeEntryOffset));
3426 RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
3430 void LCodeGen::DoDeferredMathAbsTaggedHeapNumber(LMathAbs* instr) {
3431 Register input_reg = ToRegister(instr->value());
3432 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
3433 factory()->heap_number_map());
3434 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
3436 Label slow, allocated, done;
3437 Register tmp = input_reg.is(eax) ? ecx : eax;
3438 Register tmp2 = tmp.is(ecx) ? edx : input_reg.is(ecx) ? edx : ecx;
3440 // Preserve the value of all registers.
3441 PushSafepointRegistersScope scope(this);
3443 __ mov(tmp, FieldOperand(input_reg, HeapNumber::kExponentOffset));
3444 // Check the sign of the argument. If the argument is positive, just
3445 // return it. We do not need to patch the stack since |input| and
3446 // |result| are the same register and |input| will be restored
3447 // unchanged by popping safepoint registers.
3448 __ test(tmp, Immediate(HeapNumber::kSignMask));
3449 __ j(zero, &done, Label::kNear);
3451 __ AllocateHeapNumber(tmp, tmp2, no_reg, &slow);
3452 __ jmp(&allocated, Label::kNear);
3454 // Slow case: Call the runtime system to do the number allocation.
3456 CallRuntimeFromDeferred(Runtime::kAllocateHeapNumber, 0,
3457 instr, instr->context());
3458 // Set the pointer to the new heap number in tmp.
3459 if (!tmp.is(eax)) __ mov(tmp, eax);
3460 // Restore input_reg after call to runtime.
3461 __ LoadFromSafepointRegisterSlot(input_reg, input_reg);
3463 __ bind(&allocated);
3464 __ mov(tmp2, FieldOperand(input_reg, HeapNumber::kExponentOffset));
3465 __ and_(tmp2, ~HeapNumber::kSignMask);
3466 __ mov(FieldOperand(tmp, HeapNumber::kExponentOffset), tmp2);
3467 __ mov(tmp2, FieldOperand(input_reg, HeapNumber::kMantissaOffset));
3468 __ mov(FieldOperand(tmp, HeapNumber::kMantissaOffset), tmp2);
3469 __ StoreToSafepointRegisterSlot(input_reg, tmp);
3475 void LCodeGen::EmitIntegerMathAbs(LMathAbs* instr) {
3476 Register input_reg = ToRegister(instr->value());
3477 __ test(input_reg, Operand(input_reg));
3479 __ j(not_sign, &is_positive, Label::kNear);
3480 __ neg(input_reg); // Sets flags.
3481 DeoptimizeIf(negative, instr, Deoptimizer::kOverflow);
3482 __ bind(&is_positive);
3486 void LCodeGen::DoMathAbs(LMathAbs* instr) {
3487 // Class for deferred case.
3488 class DeferredMathAbsTaggedHeapNumber final : public LDeferredCode {
3490 DeferredMathAbsTaggedHeapNumber(LCodeGen* codegen,
3492 : LDeferredCode(codegen), instr_(instr) { }
3493 void Generate() override {
3494 codegen()->DoDeferredMathAbsTaggedHeapNumber(instr_);
3496 LInstruction* instr() override { return instr_; }
3502 DCHECK(instr->value()->Equals(instr->result()));
3503 Representation r = instr->hydrogen()->value()->representation();
3506 XMMRegister scratch = double_scratch0();
3507 XMMRegister input_reg = ToDoubleRegister(instr->value());
3508 __ xorps(scratch, scratch);
3509 __ subsd(scratch, input_reg);
3510 __ andps(input_reg, scratch);
3511 } else if (r.IsSmiOrInteger32()) {
3512 EmitIntegerMathAbs(instr);
3513 } else { // Tagged case.
3514 DeferredMathAbsTaggedHeapNumber* deferred =
3515 new(zone()) DeferredMathAbsTaggedHeapNumber(this, instr);
3516 Register input_reg = ToRegister(instr->value());
3518 __ JumpIfNotSmi(input_reg, deferred->entry());
3519 EmitIntegerMathAbs(instr);
3520 __ bind(deferred->exit());
3525 void LCodeGen::DoMathFloor(LMathFloor* instr) {
3526 XMMRegister xmm_scratch = double_scratch0();
3527 Register output_reg = ToRegister(instr->result());
3528 XMMRegister input_reg = ToDoubleRegister(instr->value());
3530 if (CpuFeatures::IsSupported(SSE4_1)) {
3531 CpuFeatureScope scope(masm(), SSE4_1);
3532 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3533 // Deoptimize on negative zero.
3535 __ xorps(xmm_scratch, xmm_scratch); // Zero the register.
3536 __ ucomisd(input_reg, xmm_scratch);
3537 __ j(not_equal, &non_zero, Label::kNear);
3538 __ movmskpd(output_reg, input_reg);
3539 __ test(output_reg, Immediate(1));
3540 DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
3543 __ roundsd(xmm_scratch, input_reg, kRoundDown);
3544 __ cvttsd2si(output_reg, Operand(xmm_scratch));
3545 // Overflow is signalled with minint.
3546 __ cmp(output_reg, 0x1);
3547 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
3549 Label negative_sign, done;
3550 // Deoptimize on unordered.
3551 __ xorps(xmm_scratch, xmm_scratch); // Zero the register.
3552 __ ucomisd(input_reg, xmm_scratch);
3553 DeoptimizeIf(parity_even, instr, Deoptimizer::kNaN);
3554 __ j(below, &negative_sign, Label::kNear);
3556 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3557 // Check for negative zero.
3558 Label positive_sign;
3559 __ j(above, &positive_sign, Label::kNear);
3560 __ movmskpd(output_reg, input_reg);
3561 __ test(output_reg, Immediate(1));
3562 DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
3563 __ Move(output_reg, Immediate(0));
3564 __ jmp(&done, Label::kNear);
3565 __ bind(&positive_sign);
3568 // Use truncating instruction (OK because input is positive).
3569 __ cvttsd2si(output_reg, Operand(input_reg));
3570 // Overflow is signalled with minint.
3571 __ cmp(output_reg, 0x1);
3572 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
3573 __ jmp(&done, Label::kNear);
3575 // Non-zero negative reaches here.
3576 __ bind(&negative_sign);
3577 // Truncate, then compare and compensate.
3578 __ cvttsd2si(output_reg, Operand(input_reg));
3579 __ Cvtsi2sd(xmm_scratch, output_reg);
3580 __ ucomisd(input_reg, xmm_scratch);
3581 __ j(equal, &done, Label::kNear);
3582 __ sub(output_reg, Immediate(1));
3583 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
3590 void LCodeGen::DoMathRound(LMathRound* instr) {
3591 Register output_reg = ToRegister(instr->result());
3592 XMMRegister input_reg = ToDoubleRegister(instr->value());
3593 XMMRegister xmm_scratch = double_scratch0();
3594 XMMRegister input_temp = ToDoubleRegister(instr->temp());
3595 ExternalReference one_half = ExternalReference::address_of_one_half();
3596 ExternalReference minus_one_half =
3597 ExternalReference::address_of_minus_one_half();
3599 Label done, round_to_zero, below_one_half, do_not_compensate;
3600 Label::Distance dist = DeoptEveryNTimes() ? Label::kFar : Label::kNear;
3602 __ movsd(xmm_scratch, Operand::StaticVariable(one_half));
3603 __ ucomisd(xmm_scratch, input_reg);
3604 __ j(above, &below_one_half, Label::kNear);
3606 // CVTTSD2SI rounds towards zero, since 0.5 <= x, we use floor(0.5 + x).
3607 __ addsd(xmm_scratch, input_reg);
3608 __ cvttsd2si(output_reg, Operand(xmm_scratch));
3609 // Overflow is signalled with minint.
3610 __ cmp(output_reg, 0x1);
3611 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
3612 __ jmp(&done, dist);
3614 __ bind(&below_one_half);
3615 __ movsd(xmm_scratch, Operand::StaticVariable(minus_one_half));
3616 __ ucomisd(xmm_scratch, input_reg);
3617 __ j(below_equal, &round_to_zero, Label::kNear);
3619 // CVTTSD2SI rounds towards zero, we use ceil(x - (-0.5)) and then
3620 // compare and compensate.
3621 __ movaps(input_temp, input_reg); // Do not alter input_reg.
3622 __ subsd(input_temp, xmm_scratch);
3623 __ cvttsd2si(output_reg, Operand(input_temp));
3624 // Catch minint due to overflow, and to prevent overflow when compensating.
3625 __ cmp(output_reg, 0x1);
3626 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
3628 __ Cvtsi2sd(xmm_scratch, output_reg);
3629 __ ucomisd(xmm_scratch, input_temp);
3630 __ j(equal, &done, dist);
3631 __ sub(output_reg, Immediate(1));
3632 // No overflow because we already ruled out minint.
3633 __ jmp(&done, dist);
3635 __ bind(&round_to_zero);
3636 // We return 0 for the input range [+0, 0.5[, or [-0.5, 0.5[ if
3637 // we can ignore the difference between a result of -0 and +0.
3638 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3639 // If the sign is positive, we return +0.
3640 __ movmskpd(output_reg, input_reg);
3641 __ test(output_reg, Immediate(1));
3642 DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
3644 __ Move(output_reg, Immediate(0));
3649 void LCodeGen::DoMathFround(LMathFround* instr) {
3650 XMMRegister input_reg = ToDoubleRegister(instr->value());
3651 XMMRegister output_reg = ToDoubleRegister(instr->result());
3652 __ cvtsd2ss(output_reg, input_reg);
3653 __ cvtss2sd(output_reg, output_reg);
3657 void LCodeGen::DoMathSqrt(LMathSqrt* instr) {
3658 Operand input = ToOperand(instr->value());
3659 XMMRegister output = ToDoubleRegister(instr->result());
3660 __ sqrtsd(output, input);
3664 void LCodeGen::DoMathPowHalf(LMathPowHalf* instr) {
3665 XMMRegister xmm_scratch = double_scratch0();
3666 XMMRegister input_reg = ToDoubleRegister(instr->value());
3667 Register scratch = ToRegister(instr->temp());
3668 DCHECK(ToDoubleRegister(instr->result()).is(input_reg));
3670 // Note that according to ECMA-262 15.8.2.13:
3671 // Math.pow(-Infinity, 0.5) == Infinity
3672 // Math.sqrt(-Infinity) == NaN
3674 // Check base for -Infinity. According to IEEE-754, single-precision
3675 // -Infinity has the highest 9 bits set and the lowest 23 bits cleared.
3676 __ mov(scratch, 0xFF800000);
3677 __ movd(xmm_scratch, scratch);
3678 __ cvtss2sd(xmm_scratch, xmm_scratch);
3679 __ ucomisd(input_reg, xmm_scratch);
3680 // Comparing -Infinity with NaN results in "unordered", which sets the
3681 // zero flag as if both were equal. However, it also sets the carry flag.
3682 __ j(not_equal, &sqrt, Label::kNear);
3683 __ j(carry, &sqrt, Label::kNear);
3684 // If input is -Infinity, return Infinity.
3685 __ xorps(input_reg, input_reg);
3686 __ subsd(input_reg, xmm_scratch);
3687 __ jmp(&done, Label::kNear);
3691 __ xorps(xmm_scratch, xmm_scratch);
3692 __ addsd(input_reg, xmm_scratch); // Convert -0 to +0.
3693 __ sqrtsd(input_reg, input_reg);
3698 void LCodeGen::DoPower(LPower* instr) {
3699 Representation exponent_type = instr->hydrogen()->right()->representation();
3700 // Having marked this as a call, we can use any registers.
3701 // Just make sure that the input/output registers are the expected ones.
3702 Register tagged_exponent = MathPowTaggedDescriptor::exponent();
3703 DCHECK(!instr->right()->IsDoubleRegister() ||
3704 ToDoubleRegister(instr->right()).is(xmm1));
3705 DCHECK(!instr->right()->IsRegister() ||
3706 ToRegister(instr->right()).is(tagged_exponent));
3707 DCHECK(ToDoubleRegister(instr->left()).is(xmm2));
3708 DCHECK(ToDoubleRegister(instr->result()).is(xmm3));
3710 if (exponent_type.IsSmi()) {
3711 MathPowStub stub(isolate(), MathPowStub::TAGGED);
3713 } else if (exponent_type.IsTagged()) {
3715 __ JumpIfSmi(tagged_exponent, &no_deopt);
3716 DCHECK(!ecx.is(tagged_exponent));
3717 __ CmpObjectType(tagged_exponent, HEAP_NUMBER_TYPE, ecx);
3718 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
3720 MathPowStub stub(isolate(), MathPowStub::TAGGED);
3722 } else if (exponent_type.IsInteger32()) {
3723 MathPowStub stub(isolate(), MathPowStub::INTEGER);
3726 DCHECK(exponent_type.IsDouble());
3727 MathPowStub stub(isolate(), MathPowStub::DOUBLE);
3733 void LCodeGen::DoMathLog(LMathLog* instr) {
3734 DCHECK(instr->value()->Equals(instr->result()));
3735 XMMRegister input_reg = ToDoubleRegister(instr->value());
3736 XMMRegister xmm_scratch = double_scratch0();
3737 Label positive, done, zero;
3738 __ xorps(xmm_scratch, xmm_scratch);
3739 __ ucomisd(input_reg, xmm_scratch);
3740 __ j(above, &positive, Label::kNear);
3741 __ j(not_carry, &zero, Label::kNear);
3742 __ pcmpeqd(input_reg, input_reg);
3743 __ jmp(&done, Label::kNear);
3745 ExternalReference ninf =
3746 ExternalReference::address_of_negative_infinity();
3747 __ movsd(input_reg, Operand::StaticVariable(ninf));
3748 __ jmp(&done, Label::kNear);
3751 __ sub(Operand(esp), Immediate(kDoubleSize));
3752 __ movsd(Operand(esp, 0), input_reg);
3753 __ fld_d(Operand(esp, 0));
3755 __ fstp_d(Operand(esp, 0));
3756 __ movsd(input_reg, Operand(esp, 0));
3757 __ add(Operand(esp), Immediate(kDoubleSize));
3762 void LCodeGen::DoMathClz32(LMathClz32* instr) {
3763 Register input = ToRegister(instr->value());
3764 Register result = ToRegister(instr->result());
3766 __ Lzcnt(result, input);
3770 void LCodeGen::DoMathExp(LMathExp* instr) {
3771 XMMRegister input = ToDoubleRegister(instr->value());
3772 XMMRegister result = ToDoubleRegister(instr->result());
3773 XMMRegister temp0 = double_scratch0();
3774 Register temp1 = ToRegister(instr->temp1());
3775 Register temp2 = ToRegister(instr->temp2());
3777 MathExpGenerator::EmitMathExp(masm(), input, result, temp0, temp1, temp2);
3781 void LCodeGen::DoInvokeFunction(LInvokeFunction* instr) {
3782 DCHECK(ToRegister(instr->context()).is(esi));
3783 DCHECK(ToRegister(instr->function()).is(edi));
3784 DCHECK(instr->HasPointerMap());
3786 Handle<JSFunction> known_function = instr->hydrogen()->known_function();
3787 if (known_function.is_null()) {
3788 LPointerMap* pointers = instr->pointer_map();
3789 SafepointGenerator generator(
3790 this, pointers, Safepoint::kLazyDeopt);
3791 ParameterCount count(instr->arity());
3792 __ InvokeFunction(edi, count, CALL_FUNCTION, generator);
3794 CallKnownFunction(known_function,
3795 instr->hydrogen()->formal_parameter_count(),
3796 instr->arity(), instr);
3801 void LCodeGen::DoCallFunction(LCallFunction* instr) {
3802 DCHECK(ToRegister(instr->context()).is(esi));
3803 DCHECK(ToRegister(instr->function()).is(edi));
3804 DCHECK(ToRegister(instr->result()).is(eax));
3806 int arity = instr->arity();
3807 CallFunctionFlags flags = instr->hydrogen()->function_flags();
3808 if (instr->hydrogen()->HasVectorAndSlot()) {
3809 Register slot_register = ToRegister(instr->temp_slot());
3810 Register vector_register = ToRegister(instr->temp_vector());
3811 DCHECK(slot_register.is(edx));
3812 DCHECK(vector_register.is(ebx));
3814 AllowDeferredHandleDereference vector_structure_check;
3815 Handle<TypeFeedbackVector> vector = instr->hydrogen()->feedback_vector();
3816 int index = vector->GetIndex(instr->hydrogen()->slot());
3818 __ mov(vector_register, vector);
3819 __ mov(slot_register, Immediate(Smi::FromInt(index)));
3821 CallICState::CallType call_type =
3822 (flags & CALL_AS_METHOD) ? CallICState::METHOD : CallICState::FUNCTION;
3825 CodeFactory::CallICInOptimizedCode(isolate(), arity, call_type).code();
3826 CallCode(ic, RelocInfo::CODE_TARGET, instr);
3828 CallFunctionStub stub(isolate(), arity, flags);
3829 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
3834 void LCodeGen::DoCallNew(LCallNew* instr) {
3835 DCHECK(ToRegister(instr->context()).is(esi));
3836 DCHECK(ToRegister(instr->constructor()).is(edi));
3837 DCHECK(ToRegister(instr->result()).is(eax));
3839 // No cell in ebx for construct type feedback in optimized code
3840 __ mov(ebx, isolate()->factory()->undefined_value());
3841 CallConstructStub stub(isolate(), NO_CALL_CONSTRUCTOR_FLAGS);
3842 __ Move(eax, Immediate(instr->arity()));
3843 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
3847 void LCodeGen::DoCallNewArray(LCallNewArray* instr) {
3848 DCHECK(ToRegister(instr->context()).is(esi));
3849 DCHECK(ToRegister(instr->constructor()).is(edi));
3850 DCHECK(ToRegister(instr->result()).is(eax));
3852 __ Move(eax, Immediate(instr->arity()));
3853 if (instr->arity() == 1) {
3854 // We only need the allocation site for the case we have a length argument.
3855 // The case may bail out to the runtime, which will determine the correct
3856 // elements kind with the site.
3857 __ mov(ebx, instr->hydrogen()->site());
3859 __ mov(ebx, isolate()->factory()->undefined_value());
3862 ElementsKind kind = instr->hydrogen()->elements_kind();
3863 AllocationSiteOverrideMode override_mode =
3864 (AllocationSite::GetMode(kind) == TRACK_ALLOCATION_SITE)
3865 ? DISABLE_ALLOCATION_SITES
3868 if (instr->arity() == 0) {
3869 ArrayNoArgumentConstructorStub stub(isolate(), kind, override_mode);
3870 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
3871 } else if (instr->arity() == 1) {
3873 if (IsFastPackedElementsKind(kind)) {
3875 // We might need a change here
3876 // look at the first argument
3877 __ mov(ecx, Operand(esp, 0));
3879 __ j(zero, &packed_case, Label::kNear);
3881 ElementsKind holey_kind = GetHoleyElementsKind(kind);
3882 ArraySingleArgumentConstructorStub stub(isolate(),
3885 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
3886 __ jmp(&done, Label::kNear);
3887 __ bind(&packed_case);
3890 ArraySingleArgumentConstructorStub stub(isolate(), kind, override_mode);
3891 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
3894 ArrayNArgumentsConstructorStub stub(isolate(), kind, override_mode);
3895 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
3900 void LCodeGen::DoCallRuntime(LCallRuntime* instr) {
3901 DCHECK(ToRegister(instr->context()).is(esi));
3902 CallRuntime(instr->function(), instr->arity(), instr, instr->save_doubles());
3906 void LCodeGen::DoStoreCodeEntry(LStoreCodeEntry* instr) {
3907 Register function = ToRegister(instr->function());
3908 Register code_object = ToRegister(instr->code_object());
3909 __ lea(code_object, FieldOperand(code_object, Code::kHeaderSize));
3910 __ mov(FieldOperand(function, JSFunction::kCodeEntryOffset), code_object);
3914 void LCodeGen::DoInnerAllocatedObject(LInnerAllocatedObject* instr) {
3915 Register result = ToRegister(instr->result());
3916 Register base = ToRegister(instr->base_object());
3917 if (instr->offset()->IsConstantOperand()) {
3918 LConstantOperand* offset = LConstantOperand::cast(instr->offset());
3919 __ lea(result, Operand(base, ToInteger32(offset)));
3921 Register offset = ToRegister(instr->offset());
3922 __ lea(result, Operand(base, offset, times_1, 0));
3927 void LCodeGen::DoStoreNamedField(LStoreNamedField* instr) {
3928 Representation representation = instr->hydrogen()->field_representation();
3930 HObjectAccess access = instr->hydrogen()->access();
3931 int offset = access.offset();
3933 if (access.IsExternalMemory()) {
3934 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
3935 MemOperand operand = instr->object()->IsConstantOperand()
3936 ? MemOperand::StaticVariable(
3937 ToExternalReference(LConstantOperand::cast(instr->object())))
3938 : MemOperand(ToRegister(instr->object()), offset);
3939 if (instr->value()->IsConstantOperand()) {
3940 LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
3941 __ mov(operand, Immediate(ToInteger32(operand_value)));
3943 Register value = ToRegister(instr->value());
3944 __ Store(value, operand, representation);
3949 Register object = ToRegister(instr->object());
3950 __ AssertNotSmi(object);
3952 DCHECK(!representation.IsSmi() ||
3953 !instr->value()->IsConstantOperand() ||
3954 IsSmi(LConstantOperand::cast(instr->value())));
3955 if (representation.IsDouble()) {
3956 DCHECK(access.IsInobject());
3957 DCHECK(!instr->hydrogen()->has_transition());
3958 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
3959 XMMRegister value = ToDoubleRegister(instr->value());
3960 __ movsd(FieldOperand(object, offset), value);
3964 if (instr->hydrogen()->has_transition()) {
3965 Handle<Map> transition = instr->hydrogen()->transition_map();
3966 AddDeprecationDependency(transition);
3967 __ mov(FieldOperand(object, HeapObject::kMapOffset), transition);
3968 if (instr->hydrogen()->NeedsWriteBarrierForMap()) {
3969 Register temp = ToRegister(instr->temp());
3970 Register temp_map = ToRegister(instr->temp_map());
3971 // Update the write barrier for the map field.
3972 __ RecordWriteForMap(object, transition, temp_map, temp, kSaveFPRegs);
3977 Register write_register = object;
3978 if (!access.IsInobject()) {
3979 write_register = ToRegister(instr->temp());
3980 __ mov(write_register, FieldOperand(object, JSObject::kPropertiesOffset));
3983 MemOperand operand = FieldOperand(write_register, offset);
3984 if (instr->value()->IsConstantOperand()) {
3985 LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
3986 if (operand_value->IsRegister()) {
3987 Register value = ToRegister(operand_value);
3988 __ Store(value, operand, representation);
3989 } else if (representation.IsInteger32() || representation.IsExternal()) {
3990 Immediate immediate = ToImmediate(operand_value, representation);
3991 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
3992 __ mov(operand, immediate);
3994 Handle<Object> handle_value = ToHandle(operand_value);
3995 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
3996 __ mov(operand, handle_value);
3999 Register value = ToRegister(instr->value());
4000 __ Store(value, operand, representation);
4003 if (instr->hydrogen()->NeedsWriteBarrier()) {
4004 Register value = ToRegister(instr->value());
4005 Register temp = access.IsInobject() ? ToRegister(instr->temp()) : object;
4006 // Update the write barrier for the object for in-object properties.
4007 __ RecordWriteField(write_register,
4012 EMIT_REMEMBERED_SET,
4013 instr->hydrogen()->SmiCheckForWriteBarrier(),
4014 instr->hydrogen()->PointersToHereCheckForValue());
4019 void LCodeGen::DoStoreNamedGeneric(LStoreNamedGeneric* instr) {
4020 DCHECK(ToRegister(instr->context()).is(esi));
4021 DCHECK(ToRegister(instr->object()).is(StoreDescriptor::ReceiverRegister()));
4022 DCHECK(ToRegister(instr->value()).is(StoreDescriptor::ValueRegister()));
4024 if (instr->hydrogen()->HasVectorAndSlot()) {
4025 EmitVectorStoreICRegisters<LStoreNamedGeneric>(instr);
4028 __ mov(StoreDescriptor::NameRegister(), instr->name());
4029 Handle<Code> ic = CodeFactory::StoreICInOptimizedCode(
4030 isolate(), instr->language_mode(),
4031 instr->hydrogen()->initialization_state()).code();
4032 CallCode(ic, RelocInfo::CODE_TARGET, instr);
4036 void LCodeGen::DoStoreGlobalViaContext(LStoreGlobalViaContext* instr) {
4037 DCHECK(ToRegister(instr->context()).is(esi));
4038 DCHECK(ToRegister(instr->value())
4039 .is(StoreGlobalViaContextDescriptor::ValueRegister()));
4041 int const slot = instr->slot_index();
4042 int const depth = instr->depth();
4043 if (depth <= StoreGlobalViaContextStub::kMaximumDepth) {
4044 __ mov(StoreGlobalViaContextDescriptor::SlotRegister(), Immediate(slot));
4045 Handle<Code> stub = CodeFactory::StoreGlobalViaContext(
4046 isolate(), depth, instr->language_mode())
4048 CallCode(stub, RelocInfo::CODE_TARGET, instr);
4050 __ Push(Smi::FromInt(slot));
4051 __ Push(StoreGlobalViaContextDescriptor::ValueRegister());
4052 __ CallRuntime(is_strict(instr->language_mode())
4053 ? Runtime::kStoreGlobalViaContext_Strict
4054 : Runtime::kStoreGlobalViaContext_Sloppy,
4060 void LCodeGen::DoBoundsCheck(LBoundsCheck* instr) {
4061 Condition cc = instr->hydrogen()->allow_equality() ? above : above_equal;
4062 if (instr->index()->IsConstantOperand()) {
4063 __ cmp(ToOperand(instr->length()),
4064 ToImmediate(LConstantOperand::cast(instr->index()),
4065 instr->hydrogen()->length()->representation()));
4066 cc = CommuteCondition(cc);
4067 } else if (instr->length()->IsConstantOperand()) {
4068 __ cmp(ToOperand(instr->index()),
4069 ToImmediate(LConstantOperand::cast(instr->length()),
4070 instr->hydrogen()->index()->representation()));
4072 __ cmp(ToRegister(instr->index()), ToOperand(instr->length()));
4074 if (FLAG_debug_code && instr->hydrogen()->skip_check()) {
4076 __ j(NegateCondition(cc), &done, Label::kNear);
4080 DeoptimizeIf(cc, instr, Deoptimizer::kOutOfBounds);
4085 void LCodeGen::DoStoreKeyedExternalArray(LStoreKeyed* instr) {
4086 ElementsKind elements_kind = instr->elements_kind();
4087 LOperand* key = instr->key();
4088 if (!key->IsConstantOperand() &&
4089 ExternalArrayOpRequiresTemp(instr->hydrogen()->key()->representation(),
4091 __ SmiUntag(ToRegister(key));
4093 Operand operand(BuildFastArrayOperand(
4096 instr->hydrogen()->key()->representation(),
4098 instr->base_offset()));
4099 if (elements_kind == FLOAT32_ELEMENTS) {
4100 XMMRegister xmm_scratch = double_scratch0();
4101 __ cvtsd2ss(xmm_scratch, ToDoubleRegister(instr->value()));
4102 __ movss(operand, xmm_scratch);
4103 } else if (elements_kind == FLOAT64_ELEMENTS) {
4104 __ movsd(operand, ToDoubleRegister(instr->value()));
4106 Register value = ToRegister(instr->value());
4107 switch (elements_kind) {
4108 case UINT8_ELEMENTS:
4110 case UINT8_CLAMPED_ELEMENTS:
4111 __ mov_b(operand, value);
4113 case UINT16_ELEMENTS:
4114 case INT16_ELEMENTS:
4115 __ mov_w(operand, value);
4117 case UINT32_ELEMENTS:
4118 case INT32_ELEMENTS:
4119 __ mov(operand, value);
4121 case FLOAT32_ELEMENTS:
4122 case FLOAT64_ELEMENTS:
4123 case FAST_SMI_ELEMENTS:
4125 case FAST_DOUBLE_ELEMENTS:
4126 case FAST_HOLEY_SMI_ELEMENTS:
4127 case FAST_HOLEY_ELEMENTS:
4128 case FAST_HOLEY_DOUBLE_ELEMENTS:
4129 case DICTIONARY_ELEMENTS:
4130 case FAST_SLOPPY_ARGUMENTS_ELEMENTS:
4131 case SLOW_SLOPPY_ARGUMENTS_ELEMENTS:
4139 void LCodeGen::DoStoreKeyedFixedDoubleArray(LStoreKeyed* instr) {
4140 Operand double_store_operand = BuildFastArrayOperand(
4143 instr->hydrogen()->key()->representation(),
4144 FAST_DOUBLE_ELEMENTS,
4145 instr->base_offset());
4147 XMMRegister value = ToDoubleRegister(instr->value());
4149 if (instr->NeedsCanonicalization()) {
4150 XMMRegister xmm_scratch = double_scratch0();
4151 // Turn potential sNaN value into qNaN.
4152 __ xorps(xmm_scratch, xmm_scratch);
4153 __ subsd(value, xmm_scratch);
4156 __ movsd(double_store_operand, value);
4160 void LCodeGen::DoStoreKeyedFixedArray(LStoreKeyed* instr) {
4161 Register elements = ToRegister(instr->elements());
4162 Register key = instr->key()->IsRegister() ? ToRegister(instr->key()) : no_reg;
4164 Operand operand = BuildFastArrayOperand(
4167 instr->hydrogen()->key()->representation(),
4169 instr->base_offset());
4170 if (instr->value()->IsRegister()) {
4171 __ mov(operand, ToRegister(instr->value()));
4173 LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
4174 if (IsSmi(operand_value)) {
4175 Immediate immediate = ToImmediate(operand_value, Representation::Smi());
4176 __ mov(operand, immediate);
4178 DCHECK(!IsInteger32(operand_value));
4179 Handle<Object> handle_value = ToHandle(operand_value);
4180 __ mov(operand, handle_value);
4184 if (instr->hydrogen()->NeedsWriteBarrier()) {
4185 DCHECK(instr->value()->IsRegister());
4186 Register value = ToRegister(instr->value());
4187 DCHECK(!instr->key()->IsConstantOperand());
4188 SmiCheck check_needed =
4189 instr->hydrogen()->value()->type().IsHeapObject()
4190 ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
4191 // Compute address of modified element and store it into key register.
4192 __ lea(key, operand);
4193 __ RecordWrite(elements,
4197 EMIT_REMEMBERED_SET,
4199 instr->hydrogen()->PointersToHereCheckForValue());
4204 void LCodeGen::DoStoreKeyed(LStoreKeyed* instr) {
4205 // By cases...external, fast-double, fast
4206 if (instr->is_fixed_typed_array()) {
4207 DoStoreKeyedExternalArray(instr);
4208 } else if (instr->hydrogen()->value()->representation().IsDouble()) {
4209 DoStoreKeyedFixedDoubleArray(instr);
4211 DoStoreKeyedFixedArray(instr);
4216 void LCodeGen::DoStoreKeyedGeneric(LStoreKeyedGeneric* instr) {
4217 DCHECK(ToRegister(instr->context()).is(esi));
4218 DCHECK(ToRegister(instr->object()).is(StoreDescriptor::ReceiverRegister()));
4219 DCHECK(ToRegister(instr->key()).is(StoreDescriptor::NameRegister()));
4220 DCHECK(ToRegister(instr->value()).is(StoreDescriptor::ValueRegister()));
4222 if (instr->hydrogen()->HasVectorAndSlot()) {
4223 EmitVectorStoreICRegisters<LStoreKeyedGeneric>(instr);
4226 Handle<Code> ic = CodeFactory::KeyedStoreICInOptimizedCode(
4227 isolate(), instr->language_mode(),
4228 instr->hydrogen()->initialization_state()).code();
4229 CallCode(ic, RelocInfo::CODE_TARGET, instr);
4233 void LCodeGen::DoTrapAllocationMemento(LTrapAllocationMemento* instr) {
4234 Register object = ToRegister(instr->object());
4235 Register temp = ToRegister(instr->temp());
4236 Label no_memento_found;
4237 __ TestJSArrayForAllocationMemento(object, temp, &no_memento_found);
4238 DeoptimizeIf(equal, instr, Deoptimizer::kMementoFound);
4239 __ bind(&no_memento_found);
4243 void LCodeGen::DoMaybeGrowElements(LMaybeGrowElements* instr) {
4244 class DeferredMaybeGrowElements final : public LDeferredCode {
4246 DeferredMaybeGrowElements(LCodeGen* codegen, LMaybeGrowElements* instr)
4247 : LDeferredCode(codegen), instr_(instr) {}
4248 void Generate() override { codegen()->DoDeferredMaybeGrowElements(instr_); }
4249 LInstruction* instr() override { return instr_; }
4252 LMaybeGrowElements* instr_;
4255 Register result = eax;
4256 DeferredMaybeGrowElements* deferred =
4257 new (zone()) DeferredMaybeGrowElements(this, instr);
4258 LOperand* key = instr->key();
4259 LOperand* current_capacity = instr->current_capacity();
4261 DCHECK(instr->hydrogen()->key()->representation().IsInteger32());
4262 DCHECK(instr->hydrogen()->current_capacity()->representation().IsInteger32());
4263 DCHECK(key->IsConstantOperand() || key->IsRegister());
4264 DCHECK(current_capacity->IsConstantOperand() ||
4265 current_capacity->IsRegister());
4267 if (key->IsConstantOperand() && current_capacity->IsConstantOperand()) {
4268 int32_t constant_key = ToInteger32(LConstantOperand::cast(key));
4269 int32_t constant_capacity =
4270 ToInteger32(LConstantOperand::cast(current_capacity));
4271 if (constant_key >= constant_capacity) {
4273 __ jmp(deferred->entry());
4275 } else if (key->IsConstantOperand()) {
4276 int32_t constant_key = ToInteger32(LConstantOperand::cast(key));
4277 __ cmp(ToOperand(current_capacity), Immediate(constant_key));
4278 __ j(less_equal, deferred->entry());
4279 } else if (current_capacity->IsConstantOperand()) {
4280 int32_t constant_capacity =
4281 ToInteger32(LConstantOperand::cast(current_capacity));
4282 __ cmp(ToRegister(key), Immediate(constant_capacity));
4283 __ j(greater_equal, deferred->entry());
4285 __ cmp(ToRegister(key), ToRegister(current_capacity));
4286 __ j(greater_equal, deferred->entry());
4289 __ mov(result, ToOperand(instr->elements()));
4290 __ bind(deferred->exit());
4294 void LCodeGen::DoDeferredMaybeGrowElements(LMaybeGrowElements* instr) {
4295 // TODO(3095996): Get rid of this. For now, we need to make the
4296 // result register contain a valid pointer because it is already
4297 // contained in the register pointer map.
4298 Register result = eax;
4299 __ Move(result, Immediate(0));
4301 // We have to call a stub.
4303 PushSafepointRegistersScope scope(this);
4304 if (instr->object()->IsRegister()) {
4305 __ Move(result, ToRegister(instr->object()));
4307 __ mov(result, ToOperand(instr->object()));
4310 LOperand* key = instr->key();
4311 if (key->IsConstantOperand()) {
4312 __ mov(ebx, ToImmediate(key, Representation::Smi()));
4314 __ Move(ebx, ToRegister(key));
4318 GrowArrayElementsStub stub(isolate(), instr->hydrogen()->is_js_array(),
4319 instr->hydrogen()->kind());
4321 RecordSafepointWithLazyDeopt(
4322 instr, RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
4323 __ StoreToSafepointRegisterSlot(result, result);
4326 // Deopt on smi, which means the elements array changed to dictionary mode.
4327 __ test(result, Immediate(kSmiTagMask));
4328 DeoptimizeIf(equal, instr, Deoptimizer::kSmi);
4332 void LCodeGen::DoTransitionElementsKind(LTransitionElementsKind* instr) {
4333 Register object_reg = ToRegister(instr->object());
4335 Handle<Map> from_map = instr->original_map();
4336 Handle<Map> to_map = instr->transitioned_map();
4337 ElementsKind from_kind = instr->from_kind();
4338 ElementsKind to_kind = instr->to_kind();
4340 Label not_applicable;
4341 bool is_simple_map_transition =
4342 IsSimpleMapChangeTransition(from_kind, to_kind);
4343 Label::Distance branch_distance =
4344 is_simple_map_transition ? Label::kNear : Label::kFar;
4345 __ cmp(FieldOperand(object_reg, HeapObject::kMapOffset), from_map);
4346 __ j(not_equal, ¬_applicable, branch_distance);
4347 if (is_simple_map_transition) {
4348 Register new_map_reg = ToRegister(instr->new_map_temp());
4349 __ mov(FieldOperand(object_reg, HeapObject::kMapOffset),
4352 DCHECK_NOT_NULL(instr->temp());
4353 __ RecordWriteForMap(object_reg, to_map, new_map_reg,
4354 ToRegister(instr->temp()),
4357 DCHECK(ToRegister(instr->context()).is(esi));
4358 DCHECK(object_reg.is(eax));
4359 PushSafepointRegistersScope scope(this);
4360 __ mov(ebx, to_map);
4361 bool is_js_array = from_map->instance_type() == JS_ARRAY_TYPE;
4362 TransitionElementsKindStub stub(isolate(), from_kind, to_kind, is_js_array);
4364 RecordSafepointWithLazyDeopt(instr,
4365 RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
4367 __ bind(¬_applicable);
4371 void LCodeGen::DoStringCharCodeAt(LStringCharCodeAt* instr) {
4372 class DeferredStringCharCodeAt final : public LDeferredCode {
4374 DeferredStringCharCodeAt(LCodeGen* codegen,
4375 LStringCharCodeAt* instr)
4376 : LDeferredCode(codegen), instr_(instr) { }
4377 void Generate() override { codegen()->DoDeferredStringCharCodeAt(instr_); }
4378 LInstruction* instr() override { return instr_; }
4381 LStringCharCodeAt* instr_;
4384 DeferredStringCharCodeAt* deferred =
4385 new(zone()) DeferredStringCharCodeAt(this, instr);
4387 StringCharLoadGenerator::Generate(masm(),
4389 ToRegister(instr->string()),
4390 ToRegister(instr->index()),
4391 ToRegister(instr->result()),
4393 __ bind(deferred->exit());
4397 void LCodeGen::DoDeferredStringCharCodeAt(LStringCharCodeAt* instr) {
4398 Register string = ToRegister(instr->string());
4399 Register result = ToRegister(instr->result());
4401 // TODO(3095996): Get rid of this. For now, we need to make the
4402 // result register contain a valid pointer because it is already
4403 // contained in the register pointer map.
4404 __ Move(result, Immediate(0));
4406 PushSafepointRegistersScope scope(this);
4408 // Push the index as a smi. This is safe because of the checks in
4409 // DoStringCharCodeAt above.
4410 STATIC_ASSERT(String::kMaxLength <= Smi::kMaxValue);
4411 if (instr->index()->IsConstantOperand()) {
4412 Immediate immediate = ToImmediate(LConstantOperand::cast(instr->index()),
4413 Representation::Smi());
4416 Register index = ToRegister(instr->index());
4420 CallRuntimeFromDeferred(Runtime::kStringCharCodeAtRT, 2,
4421 instr, instr->context());
4424 __ StoreToSafepointRegisterSlot(result, eax);
4428 void LCodeGen::DoStringCharFromCode(LStringCharFromCode* instr) {
4429 class DeferredStringCharFromCode final : public LDeferredCode {
4431 DeferredStringCharFromCode(LCodeGen* codegen,
4432 LStringCharFromCode* instr)
4433 : LDeferredCode(codegen), instr_(instr) { }
4434 void Generate() override {
4435 codegen()->DoDeferredStringCharFromCode(instr_);
4437 LInstruction* instr() override { return instr_; }
4440 LStringCharFromCode* instr_;
4443 DeferredStringCharFromCode* deferred =
4444 new(zone()) DeferredStringCharFromCode(this, instr);
4446 DCHECK(instr->hydrogen()->value()->representation().IsInteger32());
4447 Register char_code = ToRegister(instr->char_code());
4448 Register result = ToRegister(instr->result());
4449 DCHECK(!char_code.is(result));
4451 __ cmp(char_code, String::kMaxOneByteCharCode);
4452 __ j(above, deferred->entry());
4453 __ Move(result, Immediate(factory()->single_character_string_cache()));
4454 __ mov(result, FieldOperand(result,
4455 char_code, times_pointer_size,
4456 FixedArray::kHeaderSize));
4457 __ cmp(result, factory()->undefined_value());
4458 __ j(equal, deferred->entry());
4459 __ bind(deferred->exit());
4463 void LCodeGen::DoDeferredStringCharFromCode(LStringCharFromCode* instr) {
4464 Register char_code = ToRegister(instr->char_code());
4465 Register result = ToRegister(instr->result());
4467 // TODO(3095996): Get rid of this. For now, we need to make the
4468 // result register contain a valid pointer because it is already
4469 // contained in the register pointer map.
4470 __ Move(result, Immediate(0));
4472 PushSafepointRegistersScope scope(this);
4473 __ SmiTag(char_code);
4475 CallRuntimeFromDeferred(Runtime::kCharFromCode, 1, instr, instr->context());
4476 __ StoreToSafepointRegisterSlot(result, eax);
4480 void LCodeGen::DoStringAdd(LStringAdd* instr) {
4481 DCHECK(ToRegister(instr->context()).is(esi));
4482 DCHECK(ToRegister(instr->left()).is(edx));
4483 DCHECK(ToRegister(instr->right()).is(eax));
4484 StringAddStub stub(isolate(),
4485 instr->hydrogen()->flags(),
4486 instr->hydrogen()->pretenure_flag());
4487 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
4491 void LCodeGen::DoInteger32ToDouble(LInteger32ToDouble* instr) {
4492 LOperand* input = instr->value();
4493 LOperand* output = instr->result();
4494 DCHECK(input->IsRegister() || input->IsStackSlot());
4495 DCHECK(output->IsDoubleRegister());
4496 __ Cvtsi2sd(ToDoubleRegister(output), ToOperand(input));
4500 void LCodeGen::DoUint32ToDouble(LUint32ToDouble* instr) {
4501 LOperand* input = instr->value();
4502 LOperand* output = instr->result();
4503 __ LoadUint32(ToDoubleRegister(output), ToRegister(input));
4507 void LCodeGen::DoNumberTagI(LNumberTagI* instr) {
4508 class DeferredNumberTagI final : public LDeferredCode {
4510 DeferredNumberTagI(LCodeGen* codegen,
4512 : LDeferredCode(codegen), instr_(instr) { }
4513 void Generate() override {
4514 codegen()->DoDeferredNumberTagIU(
4515 instr_, instr_->value(), instr_->temp(), SIGNED_INT32);
4517 LInstruction* instr() override { return instr_; }
4520 LNumberTagI* instr_;
4523 LOperand* input = instr->value();
4524 DCHECK(input->IsRegister() && input->Equals(instr->result()));
4525 Register reg = ToRegister(input);
4527 DeferredNumberTagI* deferred =
4528 new(zone()) DeferredNumberTagI(this, instr);
4530 __ j(overflow, deferred->entry());
4531 __ bind(deferred->exit());
4535 void LCodeGen::DoNumberTagU(LNumberTagU* instr) {
4536 class DeferredNumberTagU final : public LDeferredCode {
4538 DeferredNumberTagU(LCodeGen* codegen, LNumberTagU* instr)
4539 : LDeferredCode(codegen), instr_(instr) { }
4540 void Generate() override {
4541 codegen()->DoDeferredNumberTagIU(
4542 instr_, instr_->value(), instr_->temp(), UNSIGNED_INT32);
4544 LInstruction* instr() override { return instr_; }
4547 LNumberTagU* instr_;
4550 LOperand* input = instr->value();
4551 DCHECK(input->IsRegister() && input->Equals(instr->result()));
4552 Register reg = ToRegister(input);
4554 DeferredNumberTagU* deferred =
4555 new(zone()) DeferredNumberTagU(this, instr);
4556 __ cmp(reg, Immediate(Smi::kMaxValue));
4557 __ j(above, deferred->entry());
4559 __ bind(deferred->exit());
4563 void LCodeGen::DoDeferredNumberTagIU(LInstruction* instr,
4566 IntegerSignedness signedness) {
4568 Register reg = ToRegister(value);
4569 Register tmp = ToRegister(temp);
4570 XMMRegister xmm_scratch = double_scratch0();
4572 if (signedness == SIGNED_INT32) {
4573 // There was overflow, so bits 30 and 31 of the original integer
4574 // disagree. Try to allocate a heap number in new space and store
4575 // the value in there. If that fails, call the runtime system.
4577 __ xor_(reg, 0x80000000);
4578 __ Cvtsi2sd(xmm_scratch, Operand(reg));
4580 __ LoadUint32(xmm_scratch, reg);
4583 if (FLAG_inline_new) {
4584 __ AllocateHeapNumber(reg, tmp, no_reg, &slow);
4585 __ jmp(&done, Label::kNear);
4588 // Slow case: Call the runtime system to do the number allocation.
4591 // TODO(3095996): Put a valid pointer value in the stack slot where the
4592 // result register is stored, as this register is in the pointer map, but
4593 // contains an integer value.
4594 __ Move(reg, Immediate(0));
4596 // Preserve the value of all registers.
4597 PushSafepointRegistersScope scope(this);
4599 // NumberTagI and NumberTagD use the context from the frame, rather than
4600 // the environment's HContext or HInlinedContext value.
4601 // They only call Runtime::kAllocateHeapNumber.
4602 // The corresponding HChange instructions are added in a phase that does
4603 // not have easy access to the local context.
4604 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4605 __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
4606 RecordSafepointWithRegisters(
4607 instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
4608 __ StoreToSafepointRegisterSlot(reg, eax);
4611 // Done. Put the value in xmm_scratch into the value of the allocated heap
4614 __ movsd(FieldOperand(reg, HeapNumber::kValueOffset), xmm_scratch);
4618 void LCodeGen::DoNumberTagD(LNumberTagD* instr) {
4619 class DeferredNumberTagD final : public LDeferredCode {
4621 DeferredNumberTagD(LCodeGen* codegen, LNumberTagD* instr)
4622 : LDeferredCode(codegen), instr_(instr) { }
4623 void Generate() override { codegen()->DoDeferredNumberTagD(instr_); }
4624 LInstruction* instr() override { return instr_; }
4627 LNumberTagD* instr_;
4630 Register reg = ToRegister(instr->result());
4632 DeferredNumberTagD* deferred =
4633 new(zone()) DeferredNumberTagD(this, instr);
4634 if (FLAG_inline_new) {
4635 Register tmp = ToRegister(instr->temp());
4636 __ AllocateHeapNumber(reg, tmp, no_reg, deferred->entry());
4638 __ jmp(deferred->entry());
4640 __ bind(deferred->exit());
4641 XMMRegister input_reg = ToDoubleRegister(instr->value());
4642 __ movsd(FieldOperand(reg, HeapNumber::kValueOffset), input_reg);
4646 void LCodeGen::DoDeferredNumberTagD(LNumberTagD* instr) {
4647 // TODO(3095996): Get rid of this. For now, we need to make the
4648 // result register contain a valid pointer because it is already
4649 // contained in the register pointer map.
4650 Register reg = ToRegister(instr->result());
4651 __ Move(reg, Immediate(0));
4653 PushSafepointRegistersScope scope(this);
4654 // NumberTagI and NumberTagD use the context from the frame, rather than
4655 // the environment's HContext or HInlinedContext value.
4656 // They only call Runtime::kAllocateHeapNumber.
4657 // The corresponding HChange instructions are added in a phase that does
4658 // not have easy access to the local context.
4659 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4660 __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
4661 RecordSafepointWithRegisters(
4662 instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
4663 __ StoreToSafepointRegisterSlot(reg, eax);
4667 void LCodeGen::DoSmiTag(LSmiTag* instr) {
4668 HChange* hchange = instr->hydrogen();
4669 Register input = ToRegister(instr->value());
4670 if (hchange->CheckFlag(HValue::kCanOverflow) &&
4671 hchange->value()->CheckFlag(HValue::kUint32)) {
4672 __ test(input, Immediate(0xc0000000));
4673 DeoptimizeIf(not_zero, instr, Deoptimizer::kOverflow);
4676 if (hchange->CheckFlag(HValue::kCanOverflow) &&
4677 !hchange->value()->CheckFlag(HValue::kUint32)) {
4678 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
4683 void LCodeGen::DoSmiUntag(LSmiUntag* instr) {
4684 LOperand* input = instr->value();
4685 Register result = ToRegister(input);
4686 DCHECK(input->IsRegister() && input->Equals(instr->result()));
4687 if (instr->needs_check()) {
4688 __ test(result, Immediate(kSmiTagMask));
4689 DeoptimizeIf(not_zero, instr, Deoptimizer::kNotASmi);
4691 __ AssertSmi(result);
4693 __ SmiUntag(result);
4697 void LCodeGen::EmitNumberUntagD(LNumberUntagD* instr, Register input_reg,
4698 Register temp_reg, XMMRegister result_reg,
4699 NumberUntagDMode mode) {
4700 bool can_convert_undefined_to_nan =
4701 instr->hydrogen()->can_convert_undefined_to_nan();
4702 bool deoptimize_on_minus_zero = instr->hydrogen()->deoptimize_on_minus_zero();
4704 Label convert, load_smi, done;
4706 if (mode == NUMBER_CANDIDATE_IS_ANY_TAGGED) {
4708 __ JumpIfSmi(input_reg, &load_smi, Label::kNear);
4710 // Heap number map check.
4711 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
4712 factory()->heap_number_map());
4713 if (can_convert_undefined_to_nan) {
4714 __ j(not_equal, &convert, Label::kNear);
4716 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
4719 // Heap number to XMM conversion.
4720 __ movsd(result_reg, FieldOperand(input_reg, HeapNumber::kValueOffset));
4722 if (deoptimize_on_minus_zero) {
4723 XMMRegister xmm_scratch = double_scratch0();
4724 __ xorps(xmm_scratch, xmm_scratch);
4725 __ ucomisd(result_reg, xmm_scratch);
4726 __ j(not_zero, &done, Label::kNear);
4727 __ movmskpd(temp_reg, result_reg);
4728 __ test_b(temp_reg, 1);
4729 DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
4731 __ jmp(&done, Label::kNear);
4733 if (can_convert_undefined_to_nan) {
4736 // Convert undefined to NaN.
4737 __ cmp(input_reg, factory()->undefined_value());
4738 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumberUndefined);
4740 __ pcmpeqd(result_reg, result_reg);
4741 __ jmp(&done, Label::kNear);
4744 DCHECK(mode == NUMBER_CANDIDATE_IS_SMI);
4748 // Smi to XMM conversion. Clobbering a temp is faster than re-tagging the
4749 // input register since we avoid dependencies.
4750 __ mov(temp_reg, input_reg);
4751 __ SmiUntag(temp_reg); // Untag smi before converting to float.
4752 __ Cvtsi2sd(result_reg, Operand(temp_reg));
4757 void LCodeGen::DoDeferredTaggedToI(LTaggedToI* instr, Label* done) {
4758 Register input_reg = ToRegister(instr->value());
4760 // The input was optimistically untagged; revert it.
4761 STATIC_ASSERT(kSmiTagSize == 1);
4762 __ lea(input_reg, Operand(input_reg, times_2, kHeapObjectTag));
4764 if (instr->truncating()) {
4765 Label no_heap_number, check_bools, check_false;
4767 // Heap number map check.
4768 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
4769 factory()->heap_number_map());
4770 __ j(not_equal, &no_heap_number, Label::kNear);
4771 __ TruncateHeapNumberToI(input_reg, input_reg);
4774 __ bind(&no_heap_number);
4775 // Check for Oddballs. Undefined/False is converted to zero and True to one
4776 // for truncating conversions.
4777 __ cmp(input_reg, factory()->undefined_value());
4778 __ j(not_equal, &check_bools, Label::kNear);
4779 __ Move(input_reg, Immediate(0));
4782 __ bind(&check_bools);
4783 __ cmp(input_reg, factory()->true_value());
4784 __ j(not_equal, &check_false, Label::kNear);
4785 __ Move(input_reg, Immediate(1));
4788 __ bind(&check_false);
4789 __ cmp(input_reg, factory()->false_value());
4790 DeoptimizeIf(not_equal, instr,
4791 Deoptimizer::kNotAHeapNumberUndefinedBoolean);
4792 __ Move(input_reg, Immediate(0));
4794 XMMRegister scratch = ToDoubleRegister(instr->temp());
4795 DCHECK(!scratch.is(xmm0));
4796 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
4797 isolate()->factory()->heap_number_map());
4798 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
4799 __ movsd(xmm0, FieldOperand(input_reg, HeapNumber::kValueOffset));
4800 __ cvttsd2si(input_reg, Operand(xmm0));
4801 __ Cvtsi2sd(scratch, Operand(input_reg));
4802 __ ucomisd(xmm0, scratch);
4803 DeoptimizeIf(not_equal, instr, Deoptimizer::kLostPrecision);
4804 DeoptimizeIf(parity_even, instr, Deoptimizer::kNaN);
4805 if (instr->hydrogen()->GetMinusZeroMode() == FAIL_ON_MINUS_ZERO) {
4806 __ test(input_reg, Operand(input_reg));
4807 __ j(not_zero, done);
4808 __ movmskpd(input_reg, xmm0);
4809 __ and_(input_reg, 1);
4810 DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
4816 void LCodeGen::DoTaggedToI(LTaggedToI* instr) {
4817 class DeferredTaggedToI final : public LDeferredCode {
4819 DeferredTaggedToI(LCodeGen* codegen, LTaggedToI* instr)
4820 : LDeferredCode(codegen), instr_(instr) { }
4821 void Generate() override { codegen()->DoDeferredTaggedToI(instr_, done()); }
4822 LInstruction* instr() override { return instr_; }
4828 LOperand* input = instr->value();
4829 DCHECK(input->IsRegister());
4830 Register input_reg = ToRegister(input);
4831 DCHECK(input_reg.is(ToRegister(instr->result())));
4833 if (instr->hydrogen()->value()->representation().IsSmi()) {
4834 __ SmiUntag(input_reg);
4836 DeferredTaggedToI* deferred =
4837 new(zone()) DeferredTaggedToI(this, instr);
4838 // Optimistically untag the input.
4839 // If the input is a HeapObject, SmiUntag will set the carry flag.
4840 STATIC_ASSERT(kSmiTagSize == 1 && kSmiTag == 0);
4841 __ SmiUntag(input_reg);
4842 // Branch to deferred code if the input was tagged.
4843 // The deferred code will take care of restoring the tag.
4844 __ j(carry, deferred->entry());
4845 __ bind(deferred->exit());
4850 void LCodeGen::DoNumberUntagD(LNumberUntagD* instr) {
4851 LOperand* input = instr->value();
4852 DCHECK(input->IsRegister());
4853 LOperand* temp = instr->temp();
4854 DCHECK(temp->IsRegister());
4855 LOperand* result = instr->result();
4856 DCHECK(result->IsDoubleRegister());
4858 Register input_reg = ToRegister(input);
4859 Register temp_reg = ToRegister(temp);
4861 HValue* value = instr->hydrogen()->value();
4862 NumberUntagDMode mode = value->representation().IsSmi()
4863 ? NUMBER_CANDIDATE_IS_SMI : NUMBER_CANDIDATE_IS_ANY_TAGGED;
4865 XMMRegister result_reg = ToDoubleRegister(result);
4866 EmitNumberUntagD(instr, input_reg, temp_reg, result_reg, mode);
4870 void LCodeGen::DoDoubleToI(LDoubleToI* instr) {
4871 LOperand* input = instr->value();
4872 DCHECK(input->IsDoubleRegister());
4873 LOperand* result = instr->result();
4874 DCHECK(result->IsRegister());
4875 Register result_reg = ToRegister(result);
4877 if (instr->truncating()) {
4878 XMMRegister input_reg = ToDoubleRegister(input);
4879 __ TruncateDoubleToI(result_reg, input_reg);
4881 Label lost_precision, is_nan, minus_zero, done;
4882 XMMRegister input_reg = ToDoubleRegister(input);
4883 XMMRegister xmm_scratch = double_scratch0();
4884 Label::Distance dist = DeoptEveryNTimes() ? Label::kFar : Label::kNear;
4885 __ DoubleToI(result_reg, input_reg, xmm_scratch,
4886 instr->hydrogen()->GetMinusZeroMode(), &lost_precision,
4887 &is_nan, &minus_zero, dist);
4888 __ jmp(&done, dist);
4889 __ bind(&lost_precision);
4890 DeoptimizeIf(no_condition, instr, Deoptimizer::kLostPrecision);
4892 DeoptimizeIf(no_condition, instr, Deoptimizer::kNaN);
4893 __ bind(&minus_zero);
4894 DeoptimizeIf(no_condition, instr, Deoptimizer::kMinusZero);
4900 void LCodeGen::DoDoubleToSmi(LDoubleToSmi* instr) {
4901 LOperand* input = instr->value();
4902 DCHECK(input->IsDoubleRegister());
4903 LOperand* result = instr->result();
4904 DCHECK(result->IsRegister());
4905 Register result_reg = ToRegister(result);
4907 Label lost_precision, is_nan, minus_zero, done;
4908 XMMRegister input_reg = ToDoubleRegister(input);
4909 XMMRegister xmm_scratch = double_scratch0();
4910 Label::Distance dist = DeoptEveryNTimes() ? Label::kFar : Label::kNear;
4911 __ DoubleToI(result_reg, input_reg, xmm_scratch,
4912 instr->hydrogen()->GetMinusZeroMode(), &lost_precision, &is_nan,
4914 __ jmp(&done, dist);
4915 __ bind(&lost_precision);
4916 DeoptimizeIf(no_condition, instr, Deoptimizer::kLostPrecision);
4918 DeoptimizeIf(no_condition, instr, Deoptimizer::kNaN);
4919 __ bind(&minus_zero);
4920 DeoptimizeIf(no_condition, instr, Deoptimizer::kMinusZero);
4922 __ SmiTag(result_reg);
4923 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
4927 void LCodeGen::DoCheckSmi(LCheckSmi* instr) {
4928 LOperand* input = instr->value();
4929 __ test(ToOperand(input), Immediate(kSmiTagMask));
4930 DeoptimizeIf(not_zero, instr, Deoptimizer::kNotASmi);
4934 void LCodeGen::DoCheckNonSmi(LCheckNonSmi* instr) {
4935 if (!instr->hydrogen()->value()->type().IsHeapObject()) {
4936 LOperand* input = instr->value();
4937 __ test(ToOperand(input), Immediate(kSmiTagMask));
4938 DeoptimizeIf(zero, instr, Deoptimizer::kSmi);
4943 void LCodeGen::DoCheckArrayBufferNotNeutered(
4944 LCheckArrayBufferNotNeutered* instr) {
4945 Register view = ToRegister(instr->view());
4946 Register scratch = ToRegister(instr->scratch());
4948 __ mov(scratch, FieldOperand(view, JSArrayBufferView::kBufferOffset));
4949 __ test_b(FieldOperand(scratch, JSArrayBuffer::kBitFieldOffset),
4950 1 << JSArrayBuffer::WasNeutered::kShift);
4951 DeoptimizeIf(not_zero, instr, Deoptimizer::kOutOfBounds);
4955 void LCodeGen::DoCheckInstanceType(LCheckInstanceType* instr) {
4956 Register input = ToRegister(instr->value());
4957 Register temp = ToRegister(instr->temp());
4959 __ mov(temp, FieldOperand(input, HeapObject::kMapOffset));
4961 if (instr->hydrogen()->is_interval_check()) {
4964 instr->hydrogen()->GetCheckInterval(&first, &last);
4966 __ cmpb(FieldOperand(temp, Map::kInstanceTypeOffset),
4967 static_cast<int8_t>(first));
4969 // If there is only one type in the interval check for equality.
4970 if (first == last) {
4971 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongInstanceType);
4973 DeoptimizeIf(below, instr, Deoptimizer::kWrongInstanceType);
4974 // Omit check for the last type.
4975 if (last != LAST_TYPE) {
4976 __ cmpb(FieldOperand(temp, Map::kInstanceTypeOffset),
4977 static_cast<int8_t>(last));
4978 DeoptimizeIf(above, instr, Deoptimizer::kWrongInstanceType);
4984 instr->hydrogen()->GetCheckMaskAndTag(&mask, &tag);
4986 if (base::bits::IsPowerOfTwo32(mask)) {
4987 DCHECK(tag == 0 || base::bits::IsPowerOfTwo32(tag));
4988 __ test_b(FieldOperand(temp, Map::kInstanceTypeOffset), mask);
4989 DeoptimizeIf(tag == 0 ? not_zero : zero, instr,
4990 Deoptimizer::kWrongInstanceType);
4992 __ movzx_b(temp, FieldOperand(temp, Map::kInstanceTypeOffset));
4993 __ and_(temp, mask);
4995 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongInstanceType);
5001 void LCodeGen::DoCheckValue(LCheckValue* instr) {
5002 Handle<HeapObject> object = instr->hydrogen()->object().handle();
5003 if (instr->hydrogen()->object_in_new_space()) {
5004 Register reg = ToRegister(instr->value());
5005 Handle<Cell> cell = isolate()->factory()->NewCell(object);
5006 __ cmp(reg, Operand::ForCell(cell));
5008 Operand operand = ToOperand(instr->value());
5009 __ cmp(operand, object);
5011 DeoptimizeIf(not_equal, instr, Deoptimizer::kValueMismatch);
5015 void LCodeGen::DoDeferredInstanceMigration(LCheckMaps* instr, Register object) {
5017 PushSafepointRegistersScope scope(this);
5020 __ CallRuntimeSaveDoubles(Runtime::kTryMigrateInstance);
5021 RecordSafepointWithRegisters(
5022 instr->pointer_map(), 1, Safepoint::kNoLazyDeopt);
5024 __ test(eax, Immediate(kSmiTagMask));
5026 DeoptimizeIf(zero, instr, Deoptimizer::kInstanceMigrationFailed);
5030 void LCodeGen::DoCheckMaps(LCheckMaps* instr) {
5031 class DeferredCheckMaps final : public LDeferredCode {
5033 DeferredCheckMaps(LCodeGen* codegen, LCheckMaps* instr, Register object)
5034 : LDeferredCode(codegen), instr_(instr), object_(object) {
5035 SetExit(check_maps());
5037 void Generate() override {
5038 codegen()->DoDeferredInstanceMigration(instr_, object_);
5040 Label* check_maps() { return &check_maps_; }
5041 LInstruction* instr() override { return instr_; }
5049 if (instr->hydrogen()->IsStabilityCheck()) {
5050 const UniqueSet<Map>* maps = instr->hydrogen()->maps();
5051 for (int i = 0; i < maps->size(); ++i) {
5052 AddStabilityDependency(maps->at(i).handle());
5057 LOperand* input = instr->value();
5058 DCHECK(input->IsRegister());
5059 Register reg = ToRegister(input);
5061 DeferredCheckMaps* deferred = NULL;
5062 if (instr->hydrogen()->HasMigrationTarget()) {
5063 deferred = new(zone()) DeferredCheckMaps(this, instr, reg);
5064 __ bind(deferred->check_maps());
5067 const UniqueSet<Map>* maps = instr->hydrogen()->maps();
5069 for (int i = 0; i < maps->size() - 1; i++) {
5070 Handle<Map> map = maps->at(i).handle();
5071 __ CompareMap(reg, map);
5072 __ j(equal, &success, Label::kNear);
5075 Handle<Map> map = maps->at(maps->size() - 1).handle();
5076 __ CompareMap(reg, map);
5077 if (instr->hydrogen()->HasMigrationTarget()) {
5078 __ j(not_equal, deferred->entry());
5080 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongMap);
5087 void LCodeGen::DoClampDToUint8(LClampDToUint8* instr) {
5088 XMMRegister value_reg = ToDoubleRegister(instr->unclamped());
5089 XMMRegister xmm_scratch = double_scratch0();
5090 Register result_reg = ToRegister(instr->result());
5091 __ ClampDoubleToUint8(value_reg, xmm_scratch, result_reg);
5095 void LCodeGen::DoClampIToUint8(LClampIToUint8* instr) {
5096 DCHECK(instr->unclamped()->Equals(instr->result()));
5097 Register value_reg = ToRegister(instr->result());
5098 __ ClampUint8(value_reg);
5102 void LCodeGen::DoClampTToUint8(LClampTToUint8* instr) {
5103 DCHECK(instr->unclamped()->Equals(instr->result()));
5104 Register input_reg = ToRegister(instr->unclamped());
5105 XMMRegister temp_xmm_reg = ToDoubleRegister(instr->temp_xmm());
5106 XMMRegister xmm_scratch = double_scratch0();
5107 Label is_smi, done, heap_number;
5109 __ JumpIfSmi(input_reg, &is_smi);
5111 // Check for heap number
5112 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
5113 factory()->heap_number_map());
5114 __ j(equal, &heap_number, Label::kNear);
5116 // Check for undefined. Undefined is converted to zero for clamping
5118 __ cmp(input_reg, factory()->undefined_value());
5119 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumberUndefined);
5120 __ mov(input_reg, 0);
5121 __ jmp(&done, Label::kNear);
5124 __ bind(&heap_number);
5125 __ movsd(xmm_scratch, FieldOperand(input_reg, HeapNumber::kValueOffset));
5126 __ ClampDoubleToUint8(xmm_scratch, temp_xmm_reg, input_reg);
5127 __ jmp(&done, Label::kNear);
5131 __ SmiUntag(input_reg);
5132 __ ClampUint8(input_reg);
5137 void LCodeGen::DoDoubleBits(LDoubleBits* instr) {
5138 XMMRegister value_reg = ToDoubleRegister(instr->value());
5139 Register result_reg = ToRegister(instr->result());
5140 if (instr->hydrogen()->bits() == HDoubleBits::HIGH) {
5141 if (CpuFeatures::IsSupported(SSE4_1)) {
5142 CpuFeatureScope scope2(masm(), SSE4_1);
5143 __ pextrd(result_reg, value_reg, 1);
5145 XMMRegister xmm_scratch = double_scratch0();
5146 __ pshufd(xmm_scratch, value_reg, 1);
5147 __ movd(result_reg, xmm_scratch);
5150 __ movd(result_reg, value_reg);
5155 void LCodeGen::DoConstructDouble(LConstructDouble* instr) {
5156 Register hi_reg = ToRegister(instr->hi());
5157 Register lo_reg = ToRegister(instr->lo());
5158 XMMRegister result_reg = ToDoubleRegister(instr->result());
5160 if (CpuFeatures::IsSupported(SSE4_1)) {
5161 CpuFeatureScope scope2(masm(), SSE4_1);
5162 __ movd(result_reg, lo_reg);
5163 __ pinsrd(result_reg, hi_reg, 1);
5165 XMMRegister xmm_scratch = double_scratch0();
5166 __ movd(result_reg, hi_reg);
5167 __ psllq(result_reg, 32);
5168 __ movd(xmm_scratch, lo_reg);
5169 __ orps(result_reg, xmm_scratch);
5174 void LCodeGen::DoAllocate(LAllocate* instr) {
5175 class DeferredAllocate final : public LDeferredCode {
5177 DeferredAllocate(LCodeGen* codegen, LAllocate* instr)
5178 : LDeferredCode(codegen), instr_(instr) { }
5179 void Generate() override { codegen()->DoDeferredAllocate(instr_); }
5180 LInstruction* instr() override { return instr_; }
5186 DeferredAllocate* deferred = new(zone()) DeferredAllocate(this, instr);
5188 Register result = ToRegister(instr->result());
5189 Register temp = ToRegister(instr->temp());
5191 // Allocate memory for the object.
5192 AllocationFlags flags = TAG_OBJECT;
5193 if (instr->hydrogen()->MustAllocateDoubleAligned()) {
5194 flags = static_cast<AllocationFlags>(flags | DOUBLE_ALIGNMENT);
5196 if (instr->hydrogen()->IsOldSpaceAllocation()) {
5197 DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
5198 flags = static_cast<AllocationFlags>(flags | PRETENURE);
5201 if (instr->size()->IsConstantOperand()) {
5202 int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
5203 if (size <= Page::kMaxRegularHeapObjectSize) {
5204 __ Allocate(size, result, temp, no_reg, deferred->entry(), flags);
5206 __ jmp(deferred->entry());
5209 Register size = ToRegister(instr->size());
5210 __ Allocate(size, result, temp, no_reg, deferred->entry(), flags);
5213 __ bind(deferred->exit());
5215 if (instr->hydrogen()->MustPrefillWithFiller()) {
5216 if (instr->size()->IsConstantOperand()) {
5217 int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
5218 __ mov(temp, (size / kPointerSize) - 1);
5220 temp = ToRegister(instr->size());
5221 __ shr(temp, kPointerSizeLog2);
5226 __ mov(FieldOperand(result, temp, times_pointer_size, 0),
5227 isolate()->factory()->one_pointer_filler_map());
5229 __ j(not_zero, &loop);
5234 void LCodeGen::DoDeferredAllocate(LAllocate* instr) {
5235 Register result = ToRegister(instr->result());
5237 // TODO(3095996): Get rid of this. For now, we need to make the
5238 // result register contain a valid pointer because it is already
5239 // contained in the register pointer map.
5240 __ Move(result, Immediate(Smi::FromInt(0)));
5242 PushSafepointRegistersScope scope(this);
5243 if (instr->size()->IsRegister()) {
5244 Register size = ToRegister(instr->size());
5245 DCHECK(!size.is(result));
5246 __ SmiTag(ToRegister(instr->size()));
5249 int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
5250 if (size >= 0 && size <= Smi::kMaxValue) {
5251 __ push(Immediate(Smi::FromInt(size)));
5253 // We should never get here at runtime => abort
5259 int flags = AllocateDoubleAlignFlag::encode(
5260 instr->hydrogen()->MustAllocateDoubleAligned());
5261 if (instr->hydrogen()->IsOldSpaceAllocation()) {
5262 DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
5263 flags = AllocateTargetSpace::update(flags, OLD_SPACE);
5265 flags = AllocateTargetSpace::update(flags, NEW_SPACE);
5267 __ push(Immediate(Smi::FromInt(flags)));
5269 CallRuntimeFromDeferred(
5270 Runtime::kAllocateInTargetSpace, 2, instr, instr->context());
5271 __ StoreToSafepointRegisterSlot(result, eax);
5275 void LCodeGen::DoToFastProperties(LToFastProperties* instr) {
5276 DCHECK(ToRegister(instr->value()).is(eax));
5278 CallRuntime(Runtime::kToFastProperties, 1, instr);
5282 void LCodeGen::DoRegExpLiteral(LRegExpLiteral* instr) {
5283 DCHECK(ToRegister(instr->context()).is(esi));
5285 // Registers will be used as follows:
5286 // ecx = literals array.
5287 // ebx = regexp literal.
5288 // eax = regexp literal clone.
5290 int literal_offset =
5291 FixedArray::OffsetOfElementAt(instr->hydrogen()->literal_index());
5292 __ LoadHeapObject(ecx, instr->hydrogen()->literals());
5293 __ mov(ebx, FieldOperand(ecx, literal_offset));
5294 __ cmp(ebx, factory()->undefined_value());
5295 __ j(not_equal, &materialized, Label::kNear);
5297 // Create regexp literal using runtime function
5298 // Result will be in eax.
5300 __ push(Immediate(Smi::FromInt(instr->hydrogen()->literal_index())));
5301 __ push(Immediate(instr->hydrogen()->pattern()));
5302 __ push(Immediate(instr->hydrogen()->flags()));
5303 CallRuntime(Runtime::kMaterializeRegExpLiteral, 4, instr);
5306 __ bind(&materialized);
5307 int size = JSRegExp::kSize + JSRegExp::kInObjectFieldCount * kPointerSize;
5308 Label allocated, runtime_allocate;
5309 __ Allocate(size, eax, ecx, edx, &runtime_allocate, TAG_OBJECT);
5310 __ jmp(&allocated, Label::kNear);
5312 __ bind(&runtime_allocate);
5314 __ push(Immediate(Smi::FromInt(size)));
5315 CallRuntime(Runtime::kAllocateInNewSpace, 1, instr);
5318 __ bind(&allocated);
5319 // Copy the content into the newly allocated memory.
5320 // (Unroll copy loop once for better throughput).
5321 for (int i = 0; i < size - kPointerSize; i += 2 * kPointerSize) {
5322 __ mov(edx, FieldOperand(ebx, i));
5323 __ mov(ecx, FieldOperand(ebx, i + kPointerSize));
5324 __ mov(FieldOperand(eax, i), edx);
5325 __ mov(FieldOperand(eax, i + kPointerSize), ecx);
5327 if ((size % (2 * kPointerSize)) != 0) {
5328 __ mov(edx, FieldOperand(ebx, size - kPointerSize));
5329 __ mov(FieldOperand(eax, size - kPointerSize), edx);
5334 void LCodeGen::DoFunctionLiteral(LFunctionLiteral* instr) {
5335 DCHECK(ToRegister(instr->context()).is(esi));
5336 // Use the fast case closure allocation code that allocates in new
5337 // space for nested functions that don't need literals cloning.
5338 bool pretenure = instr->hydrogen()->pretenure();
5339 if (!pretenure && instr->hydrogen()->has_no_literals()) {
5340 FastNewClosureStub stub(isolate(), instr->hydrogen()->language_mode(),
5341 instr->hydrogen()->kind());
5342 __ mov(ebx, Immediate(instr->hydrogen()->shared_info()));
5343 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
5346 __ push(Immediate(instr->hydrogen()->shared_info()));
5347 __ push(Immediate(pretenure ? factory()->true_value()
5348 : factory()->false_value()));
5349 CallRuntime(Runtime::kNewClosure, 3, instr);
5354 void LCodeGen::DoTypeof(LTypeof* instr) {
5355 DCHECK(ToRegister(instr->context()).is(esi));
5356 DCHECK(ToRegister(instr->value()).is(ebx));
5358 Register value_register = ToRegister(instr->value());
5359 __ JumpIfNotSmi(value_register, &do_call);
5360 __ mov(eax, Immediate(isolate()->factory()->number_string()));
5363 TypeofStub stub(isolate());
5364 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
5369 void LCodeGen::DoTypeofIsAndBranch(LTypeofIsAndBranch* instr) {
5370 Register input = ToRegister(instr->value());
5371 Condition final_branch_condition = EmitTypeofIs(instr, input);
5372 if (final_branch_condition != no_condition) {
5373 EmitBranch(instr, final_branch_condition);
5378 Condition LCodeGen::EmitTypeofIs(LTypeofIsAndBranch* instr, Register input) {
5379 Label* true_label = instr->TrueLabel(chunk_);
5380 Label* false_label = instr->FalseLabel(chunk_);
5381 Handle<String> type_name = instr->type_literal();
5382 int left_block = instr->TrueDestination(chunk_);
5383 int right_block = instr->FalseDestination(chunk_);
5384 int next_block = GetNextEmittedBlock();
5386 Label::Distance true_distance = left_block == next_block ? Label::kNear
5388 Label::Distance false_distance = right_block == next_block ? Label::kNear
5390 Condition final_branch_condition = no_condition;
5391 if (String::Equals(type_name, factory()->number_string())) {
5392 __ JumpIfSmi(input, true_label, true_distance);
5393 __ cmp(FieldOperand(input, HeapObject::kMapOffset),
5394 factory()->heap_number_map());
5395 final_branch_condition = equal;
5397 } else if (String::Equals(type_name, factory()->string_string())) {
5398 __ JumpIfSmi(input, false_label, false_distance);
5399 __ CmpObjectType(input, FIRST_NONSTRING_TYPE, input);
5400 final_branch_condition = below;
5402 } else if (String::Equals(type_name, factory()->symbol_string())) {
5403 __ JumpIfSmi(input, false_label, false_distance);
5404 __ CmpObjectType(input, SYMBOL_TYPE, input);
5405 final_branch_condition = equal;
5407 } else if (String::Equals(type_name, factory()->boolean_string())) {
5408 __ cmp(input, factory()->true_value());
5409 __ j(equal, true_label, true_distance);
5410 __ cmp(input, factory()->false_value());
5411 final_branch_condition = equal;
5413 } else if (String::Equals(type_name, factory()->undefined_string())) {
5414 __ cmp(input, factory()->undefined_value());
5415 __ j(equal, true_label, true_distance);
5416 __ JumpIfSmi(input, false_label, false_distance);
5417 // Check for undetectable objects => true.
5418 __ mov(input, FieldOperand(input, HeapObject::kMapOffset));
5419 __ test_b(FieldOperand(input, Map::kBitFieldOffset),
5420 1 << Map::kIsUndetectable);
5421 final_branch_condition = not_zero;
5423 } else if (String::Equals(type_name, factory()->function_string())) {
5424 STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
5425 __ JumpIfSmi(input, false_label, false_distance);
5426 __ CmpObjectType(input, JS_FUNCTION_TYPE, input);
5427 __ j(equal, true_label, true_distance);
5428 __ CmpInstanceType(input, JS_FUNCTION_PROXY_TYPE);
5429 final_branch_condition = equal;
5431 } else if (String::Equals(type_name, factory()->object_string())) {
5432 __ JumpIfSmi(input, false_label, false_distance);
5433 __ cmp(input, factory()->null_value());
5434 __ j(equal, true_label, true_distance);
5435 __ CmpObjectType(input, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE, input);
5436 __ j(below, false_label, false_distance);
5437 __ CmpInstanceType(input, LAST_NONCALLABLE_SPEC_OBJECT_TYPE);
5438 __ j(above, false_label, false_distance);
5439 // Check for undetectable objects => false.
5440 __ test_b(FieldOperand(input, Map::kBitFieldOffset),
5441 1 << Map::kIsUndetectable);
5442 final_branch_condition = zero;
5445 #define SIMD128_TYPE(TYPE, Type, type, lane_count, lane_type) \
5446 } else if (String::Equals(type_name, factory()->type##_string())) { \
5447 __ JumpIfSmi(input, false_label, false_distance); \
5448 __ cmp(FieldOperand(input, HeapObject::kMapOffset), \
5449 factory()->type##_map()); \
5450 final_branch_condition = equal;
5451 SIMD128_TYPES(SIMD128_TYPE)
5456 __ jmp(false_label, false_distance);
5458 return final_branch_condition;
5462 void LCodeGen::DoIsConstructCallAndBranch(LIsConstructCallAndBranch* instr) {
5463 Register temp = ToRegister(instr->temp());
5465 EmitIsConstructCall(temp);
5466 EmitBranch(instr, equal);
5470 void LCodeGen::EmitIsConstructCall(Register temp) {
5471 // Get the frame pointer for the calling frame.
5472 __ mov(temp, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
5474 // Skip the arguments adaptor frame if it exists.
5475 Label check_frame_marker;
5476 __ cmp(Operand(temp, StandardFrameConstants::kContextOffset),
5477 Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
5478 __ j(not_equal, &check_frame_marker, Label::kNear);
5479 __ mov(temp, Operand(temp, StandardFrameConstants::kCallerFPOffset));
5481 // Check the marker in the calling frame.
5482 __ bind(&check_frame_marker);
5483 __ cmp(Operand(temp, StandardFrameConstants::kMarkerOffset),
5484 Immediate(Smi::FromInt(StackFrame::CONSTRUCT)));
5488 void LCodeGen::EnsureSpaceForLazyDeopt(int space_needed) {
5489 if (!info()->IsStub()) {
5490 // Ensure that we have enough space after the previous lazy-bailout
5491 // instruction for patching the code here.
5492 int current_pc = masm()->pc_offset();
5493 if (current_pc < last_lazy_deopt_pc_ + space_needed) {
5494 int padding_size = last_lazy_deopt_pc_ + space_needed - current_pc;
5495 __ Nop(padding_size);
5498 last_lazy_deopt_pc_ = masm()->pc_offset();
5502 void LCodeGen::DoLazyBailout(LLazyBailout* instr) {
5503 last_lazy_deopt_pc_ = masm()->pc_offset();
5504 DCHECK(instr->HasEnvironment());
5505 LEnvironment* env = instr->environment();
5506 RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt);
5507 safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
5511 void LCodeGen::DoDeoptimize(LDeoptimize* instr) {
5512 Deoptimizer::BailoutType type = instr->hydrogen()->type();
5513 // TODO(danno): Stubs expect all deopts to be lazy for historical reasons (the
5514 // needed return address), even though the implementation of LAZY and EAGER is
5515 // now identical. When LAZY is eventually completely folded into EAGER, remove
5516 // the special case below.
5517 if (info()->IsStub() && type == Deoptimizer::EAGER) {
5518 type = Deoptimizer::LAZY;
5520 DeoptimizeIf(no_condition, instr, instr->hydrogen()->reason(), type);
5524 void LCodeGen::DoDummy(LDummy* instr) {
5525 // Nothing to see here, move on!
5529 void LCodeGen::DoDummyUse(LDummyUse* instr) {
5530 // Nothing to see here, move on!
5534 void LCodeGen::DoDeferredStackCheck(LStackCheck* instr) {
5535 PushSafepointRegistersScope scope(this);
5536 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
5537 __ CallRuntimeSaveDoubles(Runtime::kStackGuard);
5538 RecordSafepointWithLazyDeopt(
5539 instr, RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
5540 DCHECK(instr->HasEnvironment());
5541 LEnvironment* env = instr->environment();
5542 safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
5546 void LCodeGen::DoStackCheck(LStackCheck* instr) {
5547 class DeferredStackCheck final : public LDeferredCode {
5549 DeferredStackCheck(LCodeGen* codegen, LStackCheck* instr)
5550 : LDeferredCode(codegen), instr_(instr) { }
5551 void Generate() override { codegen()->DoDeferredStackCheck(instr_); }
5552 LInstruction* instr() override { return instr_; }
5555 LStackCheck* instr_;
5558 DCHECK(instr->HasEnvironment());
5559 LEnvironment* env = instr->environment();
5560 // There is no LLazyBailout instruction for stack-checks. We have to
5561 // prepare for lazy deoptimization explicitly here.
5562 if (instr->hydrogen()->is_function_entry()) {
5563 // Perform stack overflow check.
5565 ExternalReference stack_limit =
5566 ExternalReference::address_of_stack_limit(isolate());
5567 __ cmp(esp, Operand::StaticVariable(stack_limit));
5568 __ j(above_equal, &done, Label::kNear);
5570 DCHECK(instr->context()->IsRegister());
5571 DCHECK(ToRegister(instr->context()).is(esi));
5572 CallCode(isolate()->builtins()->StackCheck(),
5573 RelocInfo::CODE_TARGET,
5577 DCHECK(instr->hydrogen()->is_backwards_branch());
5578 // Perform stack overflow check if this goto needs it before jumping.
5579 DeferredStackCheck* deferred_stack_check =
5580 new(zone()) DeferredStackCheck(this, instr);
5581 ExternalReference stack_limit =
5582 ExternalReference::address_of_stack_limit(isolate());
5583 __ cmp(esp, Operand::StaticVariable(stack_limit));
5584 __ j(below, deferred_stack_check->entry());
5585 EnsureSpaceForLazyDeopt(Deoptimizer::patch_size());
5586 __ bind(instr->done_label());
5587 deferred_stack_check->SetExit(instr->done_label());
5588 RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt);
5589 // Don't record a deoptimization index for the safepoint here.
5590 // This will be done explicitly when emitting call and the safepoint in
5591 // the deferred code.
5596 void LCodeGen::DoOsrEntry(LOsrEntry* instr) {
5597 // This is a pseudo-instruction that ensures that the environment here is
5598 // properly registered for deoptimization and records the assembler's PC
5600 LEnvironment* environment = instr->environment();
5602 // If the environment were already registered, we would have no way of
5603 // backpatching it with the spill slot operands.
5604 DCHECK(!environment->HasBeenRegistered());
5605 RegisterEnvironmentForDeoptimization(environment, Safepoint::kNoLazyDeopt);
5607 GenerateOsrPrologue();
5611 void LCodeGen::DoForInPrepareMap(LForInPrepareMap* instr) {
5612 DCHECK(ToRegister(instr->context()).is(esi));
5613 __ test(eax, Immediate(kSmiTagMask));
5614 DeoptimizeIf(zero, instr, Deoptimizer::kSmi);
5616 STATIC_ASSERT(FIRST_JS_PROXY_TYPE == FIRST_SPEC_OBJECT_TYPE);
5617 __ CmpObjectType(eax, LAST_JS_PROXY_TYPE, ecx);
5618 DeoptimizeIf(below_equal, instr, Deoptimizer::kWrongInstanceType);
5620 Label use_cache, call_runtime;
5621 __ CheckEnumCache(&call_runtime);
5623 __ mov(eax, FieldOperand(eax, HeapObject::kMapOffset));
5624 __ jmp(&use_cache, Label::kNear);
5626 // Get the set of properties to enumerate.
5627 __ bind(&call_runtime);
5629 CallRuntime(Runtime::kGetPropertyNamesFast, 1, instr);
5631 __ cmp(FieldOperand(eax, HeapObject::kMapOffset),
5632 isolate()->factory()->meta_map());
5633 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongMap);
5634 __ bind(&use_cache);
5638 void LCodeGen::DoForInCacheArray(LForInCacheArray* instr) {
5639 Register map = ToRegister(instr->map());
5640 Register result = ToRegister(instr->result());
5641 Label load_cache, done;
5642 __ EnumLength(result, map);
5643 __ cmp(result, Immediate(Smi::FromInt(0)));
5644 __ j(not_equal, &load_cache, Label::kNear);
5645 __ mov(result, isolate()->factory()->empty_fixed_array());
5646 __ jmp(&done, Label::kNear);
5648 __ bind(&load_cache);
5649 __ LoadInstanceDescriptors(map, result);
5651 FieldOperand(result, DescriptorArray::kEnumCacheOffset));
5653 FieldOperand(result, FixedArray::SizeFor(instr->idx())));
5655 __ test(result, result);
5656 DeoptimizeIf(equal, instr, Deoptimizer::kNoCache);
5660 void LCodeGen::DoCheckMapValue(LCheckMapValue* instr) {
5661 Register object = ToRegister(instr->value());
5662 __ cmp(ToRegister(instr->map()),
5663 FieldOperand(object, HeapObject::kMapOffset));
5664 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongMap);
5668 void LCodeGen::DoDeferredLoadMutableDouble(LLoadFieldByIndex* instr,
5671 PushSafepointRegistersScope scope(this);
5675 __ CallRuntimeSaveDoubles(Runtime::kLoadMutableDouble);
5676 RecordSafepointWithRegisters(
5677 instr->pointer_map(), 2, Safepoint::kNoLazyDeopt);
5678 __ StoreToSafepointRegisterSlot(object, eax);
5682 void LCodeGen::DoLoadFieldByIndex(LLoadFieldByIndex* instr) {
5683 class DeferredLoadMutableDouble final : public LDeferredCode {
5685 DeferredLoadMutableDouble(LCodeGen* codegen,
5686 LLoadFieldByIndex* instr,
5689 : LDeferredCode(codegen),
5694 void Generate() override {
5695 codegen()->DoDeferredLoadMutableDouble(instr_, object_, index_);
5697 LInstruction* instr() override { return instr_; }
5700 LLoadFieldByIndex* instr_;
5705 Register object = ToRegister(instr->object());
5706 Register index = ToRegister(instr->index());
5708 DeferredLoadMutableDouble* deferred;
5709 deferred = new(zone()) DeferredLoadMutableDouble(
5710 this, instr, object, index);
5712 Label out_of_object, done;
5713 __ test(index, Immediate(Smi::FromInt(1)));
5714 __ j(not_zero, deferred->entry());
5718 __ cmp(index, Immediate(0));
5719 __ j(less, &out_of_object, Label::kNear);
5720 __ mov(object, FieldOperand(object,
5722 times_half_pointer_size,
5723 JSObject::kHeaderSize));
5724 __ jmp(&done, Label::kNear);
5726 __ bind(&out_of_object);
5727 __ mov(object, FieldOperand(object, JSObject::kPropertiesOffset));
5729 // Index is now equal to out of object property index plus 1.
5730 __ mov(object, FieldOperand(object,
5732 times_half_pointer_size,
5733 FixedArray::kHeaderSize - kPointerSize));
5734 __ bind(deferred->exit());
5739 void LCodeGen::DoStoreFrameContext(LStoreFrameContext* instr) {
5740 Register context = ToRegister(instr->context());
5741 __ mov(Operand(ebp, StandardFrameConstants::kContextOffset), context);
5745 void LCodeGen::DoAllocateBlockContext(LAllocateBlockContext* instr) {
5746 Handle<ScopeInfo> scope_info = instr->scope_info();
5747 __ Push(scope_info);
5748 __ push(ToRegister(instr->function()));
5749 CallRuntime(Runtime::kPushBlockContext, 2, instr);
5750 RecordSafepoint(Safepoint::kNoLazyDeopt);
5756 } // namespace internal
5759 #endif // V8_TARGET_ARCH_IA32