1 // Copyright 2011 the V8 project authors. All rights reserved.
2 // Redistribution and use in source and binary forms, with or without
3 // modification, are permitted provided that the following conditions are
6 // * Redistributions of source code must retain the above copyright
7 // notice, this list of conditions and the following disclaimer.
8 // * Redistributions in binary form must reproduce the above
9 // copyright notice, this list of conditions and the following
10 // disclaimer in the documentation and/or other materials provided
11 // with the distribution.
12 // * Neither the name of Google Inc. nor the names of its
13 // contributors may be used to endorse or promote products derived
14 // from this software without specific prior written permission.
16 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 #if defined(V8_TARGET_ARCH_IA32)
32 #include "bootstrapper.h"
36 #include "serialize.h"
41 // -------------------------------------------------------------------------
42 // MacroAssembler implementation.
44 MacroAssembler::MacroAssembler(Isolate* arg_isolate, void* buffer, int size)
45 : Assembler(arg_isolate, buffer, size),
46 generating_stub_(false),
47 allow_stub_calls_(true),
49 if (isolate() != NULL) {
50 code_object_ = Handle<Object>(isolate()->heap()->undefined_value(),
56 void MacroAssembler::InNewSpace(
61 Label::Distance condition_met_distance) {
62 ASSERT(cc == equal || cc == not_equal);
63 if (scratch.is(object)) {
64 and_(scratch, Immediate(~Page::kPageAlignmentMask));
66 mov(scratch, Immediate(~Page::kPageAlignmentMask));
67 and_(scratch, object);
69 // Check that we can use a test_b.
70 ASSERT(MemoryChunk::IN_FROM_SPACE < 8);
71 ASSERT(MemoryChunk::IN_TO_SPACE < 8);
72 int mask = (1 << MemoryChunk::IN_FROM_SPACE)
73 | (1 << MemoryChunk::IN_TO_SPACE);
74 // If non-zero, the page belongs to new-space.
75 test_b(Operand(scratch, MemoryChunk::kFlagsOffset),
76 static_cast<uint8_t>(mask));
77 j(cc, condition_met, condition_met_distance);
81 void MacroAssembler::RememberedSetHelper(
82 Register object, // Only used for debug checks.
85 SaveFPRegsMode save_fp,
86 MacroAssembler::RememberedSetFinalAction and_then) {
88 if (FLAG_debug_code) {
90 JumpIfNotInNewSpace(object, scratch, &ok, Label::kNear);
94 // Load store buffer top.
95 ExternalReference store_buffer =
96 ExternalReference::store_buffer_top(isolate());
97 mov(scratch, Operand::StaticVariable(store_buffer));
98 // Store pointer to buffer.
99 mov(Operand(scratch, 0), addr);
100 // Increment buffer top.
101 add(scratch, Immediate(kPointerSize));
102 // Write back new top of buffer.
103 mov(Operand::StaticVariable(store_buffer), scratch);
104 // Call stub on end of buffer.
105 // Check for end of buffer.
106 test(scratch, Immediate(StoreBuffer::kStoreBufferOverflowBit));
107 if (and_then == kReturnAtEnd) {
108 Label buffer_overflowed;
109 j(not_equal, &buffer_overflowed, Label::kNear);
111 bind(&buffer_overflowed);
113 ASSERT(and_then == kFallThroughAtEnd);
114 j(equal, &done, Label::kNear);
116 StoreBufferOverflowStub store_buffer_overflow =
117 StoreBufferOverflowStub(save_fp);
118 CallStub(&store_buffer_overflow);
119 if (and_then == kReturnAtEnd) {
122 ASSERT(and_then == kFallThroughAtEnd);
128 void MacroAssembler::ClampDoubleToUint8(XMMRegister input_reg,
129 XMMRegister scratch_reg,
130 Register result_reg) {
132 ExternalReference zero_ref = ExternalReference::address_of_zero();
133 movdbl(scratch_reg, Operand::StaticVariable(zero_ref));
134 Set(result_reg, Immediate(0));
135 ucomisd(input_reg, scratch_reg);
136 j(below, &done, Label::kNear);
137 ExternalReference half_ref = ExternalReference::address_of_one_half();
138 movdbl(scratch_reg, Operand::StaticVariable(half_ref));
139 addsd(scratch_reg, input_reg);
140 cvttsd2si(result_reg, Operand(scratch_reg));
141 test(result_reg, Immediate(0xFFFFFF00));
142 j(zero, &done, Label::kNear);
143 Set(result_reg, Immediate(255));
148 void MacroAssembler::ClampUint8(Register reg) {
150 test(reg, Immediate(0xFFFFFF00));
151 j(zero, &done, Label::kNear);
152 setcc(negative, reg); // 1 if negative, 0 if positive.
153 dec_b(reg); // 0 if negative, 255 if positive.
158 void MacroAssembler::RecordWriteArray(Register object,
161 SaveFPRegsMode save_fp,
162 RememberedSetAction remembered_set_action,
163 SmiCheck smi_check) {
164 // First, check if a write barrier is even needed. The tests below
165 // catch stores of Smis.
168 // Skip barrier if writing a smi.
169 if (smi_check == INLINE_SMI_CHECK) {
170 ASSERT_EQ(0, kSmiTag);
171 test(value, Immediate(kSmiTagMask));
175 // Array access: calculate the destination address in the same manner as
176 // KeyedStoreIC::GenerateGeneric. Multiply a smi by 2 to get an offset
177 // into an array of words.
178 Register dst = index;
179 lea(dst, Operand(object, index, times_half_pointer_size,
180 FixedArray::kHeaderSize - kHeapObjectTag));
183 object, dst, value, save_fp, remembered_set_action, OMIT_SMI_CHECK);
187 // Clobber clobbered input registers when running with the debug-code flag
188 // turned on to provoke errors.
189 if (emit_debug_code()) {
190 mov(value, Immediate(BitCast<int32_t>(kZapValue)));
191 mov(index, Immediate(BitCast<int32_t>(kZapValue)));
196 void MacroAssembler::RecordWriteField(
201 SaveFPRegsMode save_fp,
202 RememberedSetAction remembered_set_action,
203 SmiCheck smi_check) {
204 // First, check if a write barrier is even needed. The tests below
205 // catch stores of Smis.
208 // Skip barrier if writing a smi.
209 if (smi_check == INLINE_SMI_CHECK) {
210 JumpIfSmi(value, &done, Label::kNear);
213 // Although the object register is tagged, the offset is relative to the start
214 // of the object, so so offset must be a multiple of kPointerSize.
215 ASSERT(IsAligned(offset, kPointerSize));
217 lea(dst, FieldOperand(object, offset));
218 if (emit_debug_code()) {
220 test_b(dst, (1 << kPointerSizeLog2) - 1);
221 j(zero, &ok, Label::kNear);
227 object, dst, value, save_fp, remembered_set_action, OMIT_SMI_CHECK);
231 // Clobber clobbered input registers when running with the debug-code flag
232 // turned on to provoke errors.
233 if (emit_debug_code()) {
234 mov(value, Immediate(BitCast<int32_t>(kZapValue)));
235 mov(dst, Immediate(BitCast<int32_t>(kZapValue)));
240 void MacroAssembler::RecordWrite(Register object,
243 SaveFPRegsMode fp_mode,
244 RememberedSetAction remembered_set_action,
245 SmiCheck smi_check) {
246 ASSERT(!object.is(value));
247 ASSERT(!object.is(address));
248 ASSERT(!value.is(address));
249 if (emit_debug_code()) {
253 if (remembered_set_action == OMIT_REMEMBERED_SET &&
254 !FLAG_incremental_marking) {
258 if (FLAG_debug_code) {
260 cmp(value, Operand(address, 0));
261 j(equal, &ok, Label::kNear);
266 // First, check if a write barrier is even needed. The tests below
267 // catch stores of Smis and stores into young gen.
270 if (smi_check == INLINE_SMI_CHECK) {
271 // Skip barrier if writing a smi.
272 JumpIfSmi(value, &done, Label::kNear);
276 value, // Used as scratch.
277 MemoryChunk::kPointersToHereAreInterestingMask,
281 CheckPageFlag(object,
282 value, // Used as scratch.
283 MemoryChunk::kPointersFromHereAreInterestingMask,
288 RecordWriteStub stub(object, value, address, remembered_set_action, fp_mode);
293 // Clobber clobbered registers when running with the debug-code flag
294 // turned on to provoke errors.
295 if (emit_debug_code()) {
296 mov(address, Immediate(BitCast<int32_t>(kZapValue)));
297 mov(value, Immediate(BitCast<int32_t>(kZapValue)));
302 #ifdef ENABLE_DEBUGGER_SUPPORT
303 void MacroAssembler::DebugBreak() {
304 Set(eax, Immediate(0));
305 mov(ebx, Immediate(ExternalReference(Runtime::kDebugBreak, isolate())));
307 call(ces.GetCode(), RelocInfo::DEBUG_BREAK);
312 void MacroAssembler::Set(Register dst, const Immediate& x) {
314 xor_(dst, dst); // Shorter than mov.
321 void MacroAssembler::Set(const Operand& dst, const Immediate& x) {
326 bool MacroAssembler::IsUnsafeImmediate(const Immediate& x) {
327 static const int kMaxImmediateBits = 17;
328 if (x.rmode_ != RelocInfo::NONE) return false;
329 return !is_intn(x.x_, kMaxImmediateBits);
333 void MacroAssembler::SafeSet(Register dst, const Immediate& x) {
334 if (IsUnsafeImmediate(x) && jit_cookie() != 0) {
335 Set(dst, Immediate(x.x_ ^ jit_cookie()));
336 xor_(dst, jit_cookie());
343 void MacroAssembler::SafePush(const Immediate& x) {
344 if (IsUnsafeImmediate(x) && jit_cookie() != 0) {
345 push(Immediate(x.x_ ^ jit_cookie()));
346 xor_(Operand(esp, 0), Immediate(jit_cookie()));
353 void MacroAssembler::CompareRoot(Register with, Heap::RootListIndex index) {
354 // see ROOT_ACCESSOR macro in factory.h
355 Handle<Object> value(&isolate()->heap()->roots_array_start()[index]);
360 void MacroAssembler::CompareRoot(const Operand& with,
361 Heap::RootListIndex index) {
362 // see ROOT_ACCESSOR macro in factory.h
363 Handle<Object> value(&isolate()->heap()->roots_array_start()[index]);
368 void MacroAssembler::CmpObjectType(Register heap_object,
371 mov(map, FieldOperand(heap_object, HeapObject::kMapOffset));
372 CmpInstanceType(map, type);
376 void MacroAssembler::CmpInstanceType(Register map, InstanceType type) {
377 cmpb(FieldOperand(map, Map::kInstanceTypeOffset),
378 static_cast<int8_t>(type));
382 void MacroAssembler::CheckFastElements(Register map,
384 Label::Distance distance) {
385 STATIC_ASSERT(FAST_SMI_ONLY_ELEMENTS == 0);
386 STATIC_ASSERT(FAST_ELEMENTS == 1);
387 cmpb(FieldOperand(map, Map::kBitField2Offset),
388 Map::kMaximumBitField2FastElementValue);
389 j(above, fail, distance);
393 void MacroAssembler::CheckFastObjectElements(Register map,
395 Label::Distance distance) {
396 STATIC_ASSERT(FAST_SMI_ONLY_ELEMENTS == 0);
397 STATIC_ASSERT(FAST_ELEMENTS == 1);
398 cmpb(FieldOperand(map, Map::kBitField2Offset),
399 Map::kMaximumBitField2FastSmiOnlyElementValue);
400 j(below_equal, fail, distance);
401 cmpb(FieldOperand(map, Map::kBitField2Offset),
402 Map::kMaximumBitField2FastElementValue);
403 j(above, fail, distance);
407 void MacroAssembler::CheckFastSmiOnlyElements(Register map,
409 Label::Distance distance) {
410 STATIC_ASSERT(FAST_SMI_ONLY_ELEMENTS == 0);
411 cmpb(FieldOperand(map, Map::kBitField2Offset),
412 Map::kMaximumBitField2FastSmiOnlyElementValue);
413 j(above, fail, distance);
417 void MacroAssembler::StoreNumberToDoubleElements(
418 Register maybe_number,
422 XMMRegister scratch2,
424 bool specialize_for_processor) {
425 Label smi_value, done, maybe_nan, not_nan, is_nan, have_double_value;
426 JumpIfSmi(maybe_number, &smi_value, Label::kNear);
428 CheckMap(maybe_number,
429 isolate()->factory()->heap_number_map(),
433 // Double value, canonicalize NaN.
434 uint32_t offset = HeapNumber::kValueOffset + sizeof(kHoleNanLower32);
435 cmp(FieldOperand(maybe_number, offset),
436 Immediate(kNaNOrInfinityLowerBoundUpper32));
437 j(greater_equal, &maybe_nan, Label::kNear);
440 ExternalReference canonical_nan_reference =
441 ExternalReference::address_of_canonical_non_hole_nan();
442 if (CpuFeatures::IsSupported(SSE2) && specialize_for_processor) {
443 CpuFeatures::Scope use_sse2(SSE2);
444 movdbl(scratch2, FieldOperand(maybe_number, HeapNumber::kValueOffset));
445 bind(&have_double_value);
446 movdbl(FieldOperand(elements, key, times_4, FixedDoubleArray::kHeaderSize),
449 fld_d(FieldOperand(maybe_number, HeapNumber::kValueOffset));
450 bind(&have_double_value);
451 fstp_d(FieldOperand(elements, key, times_4, FixedDoubleArray::kHeaderSize));
456 // Could be NaN or Infinity. If fraction is not zero, it's NaN, otherwise
457 // it's an Infinity, and the non-NaN code path applies.
458 j(greater, &is_nan, Label::kNear);
459 cmp(FieldOperand(maybe_number, HeapNumber::kValueOffset), Immediate(0));
462 if (CpuFeatures::IsSupported(SSE2) && specialize_for_processor) {
463 CpuFeatures::Scope use_sse2(SSE2);
464 movdbl(scratch2, Operand::StaticVariable(canonical_nan_reference));
466 fld_d(Operand::StaticVariable(canonical_nan_reference));
468 jmp(&have_double_value, Label::kNear);
471 // Value is a smi. Convert to a double and store.
472 // Preserve original value.
473 mov(scratch1, maybe_number);
475 if (CpuFeatures::IsSupported(SSE2) && specialize_for_processor) {
476 CpuFeatures::Scope fscope(SSE2);
477 cvtsi2sd(scratch2, scratch1);
478 movdbl(FieldOperand(elements, key, times_4, FixedDoubleArray::kHeaderSize),
482 fild_s(Operand(esp, 0));
484 fstp_d(FieldOperand(elements, key, times_4, FixedDoubleArray::kHeaderSize));
490 void MacroAssembler::CheckMap(Register obj,
493 SmiCheckType smi_check_type) {
494 if (smi_check_type == DO_SMI_CHECK) {
495 JumpIfSmi(obj, fail);
497 cmp(FieldOperand(obj, HeapObject::kMapOffset), Immediate(map));
502 void MacroAssembler::DispatchMap(Register obj,
504 Handle<Code> success,
505 SmiCheckType smi_check_type) {
507 if (smi_check_type == DO_SMI_CHECK) {
508 JumpIfSmi(obj, &fail);
510 cmp(FieldOperand(obj, HeapObject::kMapOffset), Immediate(map));
517 Condition MacroAssembler::IsObjectStringType(Register heap_object,
519 Register instance_type) {
520 mov(map, FieldOperand(heap_object, HeapObject::kMapOffset));
521 movzx_b(instance_type, FieldOperand(map, Map::kInstanceTypeOffset));
522 STATIC_ASSERT(kNotStringTag != 0);
523 test(instance_type, Immediate(kIsNotStringMask));
528 void MacroAssembler::IsObjectJSObjectType(Register heap_object,
532 mov(map, FieldOperand(heap_object, HeapObject::kMapOffset));
533 IsInstanceJSObjectType(map, scratch, fail);
537 void MacroAssembler::IsInstanceJSObjectType(Register map,
540 movzx_b(scratch, FieldOperand(map, Map::kInstanceTypeOffset));
541 sub(scratch, Immediate(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE));
543 LAST_NONCALLABLE_SPEC_OBJECT_TYPE - FIRST_NONCALLABLE_SPEC_OBJECT_TYPE);
548 void MacroAssembler::FCmp() {
549 if (CpuFeatures::IsSupported(CMOV)) {
562 void MacroAssembler::AbortIfNotNumber(Register object) {
564 JumpIfSmi(object, &ok);
565 cmp(FieldOperand(object, HeapObject::kMapOffset),
566 isolate()->factory()->heap_number_map());
567 Assert(equal, "Operand not a number");
572 void MacroAssembler::AbortIfNotSmi(Register object) {
573 test(object, Immediate(kSmiTagMask));
574 Assert(equal, "Operand is not a smi");
578 void MacroAssembler::AbortIfNotString(Register object) {
579 test(object, Immediate(kSmiTagMask));
580 Assert(not_equal, "Operand is not a string");
582 mov(object, FieldOperand(object, HeapObject::kMapOffset));
583 CmpInstanceType(object, FIRST_NONSTRING_TYPE);
585 Assert(below, "Operand is not a string");
589 void MacroAssembler::AbortIfSmi(Register object) {
590 test(object, Immediate(kSmiTagMask));
591 Assert(not_equal, "Operand is a smi");
595 void MacroAssembler::EnterFrame(StackFrame::Type type) {
599 push(Immediate(Smi::FromInt(type)));
600 push(Immediate(CodeObject()));
601 if (emit_debug_code()) {
602 cmp(Operand(esp, 0), Immediate(isolate()->factory()->undefined_value()));
603 Check(not_equal, "code object not properly patched");
608 void MacroAssembler::LeaveFrame(StackFrame::Type type) {
609 if (emit_debug_code()) {
610 cmp(Operand(ebp, StandardFrameConstants::kMarkerOffset),
611 Immediate(Smi::FromInt(type)));
612 Check(equal, "stack frame types must match");
618 void MacroAssembler::EnterExitFramePrologue() {
619 // Setup the frame structure on the stack.
620 ASSERT(ExitFrameConstants::kCallerSPDisplacement == +2 * kPointerSize);
621 ASSERT(ExitFrameConstants::kCallerPCOffset == +1 * kPointerSize);
622 ASSERT(ExitFrameConstants::kCallerFPOffset == 0 * kPointerSize);
626 // Reserve room for entry stack pointer and push the code object.
627 ASSERT(ExitFrameConstants::kSPOffset == -1 * kPointerSize);
628 push(Immediate(0)); // Saved entry sp, patched before call.
629 push(Immediate(CodeObject())); // Accessed from ExitFrame::code_slot.
631 // Save the frame pointer and the context in top.
632 ExternalReference c_entry_fp_address(Isolate::kCEntryFPAddress,
634 ExternalReference context_address(Isolate::kContextAddress,
636 mov(Operand::StaticVariable(c_entry_fp_address), ebp);
637 mov(Operand::StaticVariable(context_address), esi);
641 void MacroAssembler::EnterExitFrameEpilogue(int argc, bool save_doubles) {
642 // Optionally save all XMM registers.
644 CpuFeatures::Scope scope(SSE2);
645 int space = XMMRegister::kNumRegisters * kDoubleSize + argc * kPointerSize;
646 sub(esp, Immediate(space));
647 const int offset = -2 * kPointerSize;
648 for (int i = 0; i < XMMRegister::kNumRegisters; i++) {
649 XMMRegister reg = XMMRegister::from_code(i);
650 movdbl(Operand(ebp, offset - ((i + 1) * kDoubleSize)), reg);
653 sub(esp, Immediate(argc * kPointerSize));
656 // Get the required frame alignment for the OS.
657 const int kFrameAlignment = OS::ActivationFrameAlignment();
658 if (kFrameAlignment > 0) {
659 ASSERT(IsPowerOf2(kFrameAlignment));
660 and_(esp, -kFrameAlignment);
663 // Patch the saved entry sp.
664 mov(Operand(ebp, ExitFrameConstants::kSPOffset), esp);
668 void MacroAssembler::EnterExitFrame(bool save_doubles) {
669 EnterExitFramePrologue();
671 // Setup argc and argv in callee-saved registers.
672 int offset = StandardFrameConstants::kCallerSPOffset - kPointerSize;
674 lea(esi, Operand(ebp, eax, times_4, offset));
676 // Reserve space for argc, argv and isolate.
677 EnterExitFrameEpilogue(3, save_doubles);
681 void MacroAssembler::EnterApiExitFrame(int argc) {
682 EnterExitFramePrologue();
683 EnterExitFrameEpilogue(argc, false);
687 void MacroAssembler::LeaveExitFrame(bool save_doubles) {
688 // Optionally restore all XMM registers.
690 CpuFeatures::Scope scope(SSE2);
691 const int offset = -2 * kPointerSize;
692 for (int i = 0; i < XMMRegister::kNumRegisters; i++) {
693 XMMRegister reg = XMMRegister::from_code(i);
694 movdbl(reg, Operand(ebp, offset - ((i + 1) * kDoubleSize)));
698 // Get the return address from the stack and restore the frame pointer.
699 mov(ecx, Operand(ebp, 1 * kPointerSize));
700 mov(ebp, Operand(ebp, 0 * kPointerSize));
702 // Pop the arguments and the receiver from the caller stack.
703 lea(esp, Operand(esi, 1 * kPointerSize));
705 // Push the return address to get ready to return.
708 LeaveExitFrameEpilogue();
711 void MacroAssembler::LeaveExitFrameEpilogue() {
712 // Restore current context from top and clear it in debug mode.
713 ExternalReference context_address(Isolate::kContextAddress, isolate());
714 mov(esi, Operand::StaticVariable(context_address));
716 mov(Operand::StaticVariable(context_address), Immediate(0));
719 // Clear the top frame.
720 ExternalReference c_entry_fp_address(Isolate::kCEntryFPAddress,
722 mov(Operand::StaticVariable(c_entry_fp_address), Immediate(0));
726 void MacroAssembler::LeaveApiExitFrame() {
730 LeaveExitFrameEpilogue();
734 void MacroAssembler::PushTryHandler(CodeLocation try_location,
737 // Adjust this code if not the case.
738 STATIC_ASSERT(StackHandlerConstants::kSize == 5 * kPointerSize);
739 STATIC_ASSERT(StackHandlerConstants::kNextOffset == 0);
740 STATIC_ASSERT(StackHandlerConstants::kCodeOffset == 1 * kPointerSize);
741 STATIC_ASSERT(StackHandlerConstants::kStateOffset == 2 * kPointerSize);
742 STATIC_ASSERT(StackHandlerConstants::kContextOffset == 3 * kPointerSize);
743 STATIC_ASSERT(StackHandlerConstants::kFPOffset == 4 * kPointerSize);
745 // We will build up the handler from the bottom by pushing on the stack.
746 // First compute the state and push the frame pointer and context.
747 unsigned state = StackHandler::OffsetField::encode(handler_index);
748 if (try_location == IN_JAVASCRIPT) {
751 state |= (type == TRY_CATCH_HANDLER)
752 ? StackHandler::KindField::encode(StackHandler::TRY_CATCH)
753 : StackHandler::KindField::encode(StackHandler::TRY_FINALLY);
755 ASSERT(try_location == IN_JS_ENTRY);
756 // The frame pointer does not point to a JS frame so we save NULL for
757 // ebp. We expect the code throwing an exception to check ebp before
758 // dereferencing it to restore the context.
759 push(Immediate(0)); // NULL frame pointer.
760 push(Immediate(Smi::FromInt(0))); // No context.
761 state |= StackHandler::KindField::encode(StackHandler::ENTRY);
764 // Push the state and the code object.
765 push(Immediate(state));
768 // Link the current handler as the next handler.
769 ExternalReference handler_address(Isolate::kHandlerAddress, isolate());
770 push(Operand::StaticVariable(handler_address));
771 // Set this new handler as the current one.
772 mov(Operand::StaticVariable(handler_address), esp);
776 void MacroAssembler::PopTryHandler() {
777 STATIC_ASSERT(StackHandlerConstants::kNextOffset == 0);
778 ExternalReference handler_address(Isolate::kHandlerAddress, isolate());
779 pop(Operand::StaticVariable(handler_address));
780 add(esp, Immediate(StackHandlerConstants::kSize - kPointerSize));
784 void MacroAssembler::JumpToHandlerEntry() {
785 // Compute the handler entry address and jump to it. The handler table is
786 // a fixed array of (smi-tagged) code offsets.
787 // eax = exception, edi = code object, edx = state.
788 mov(ebx, FieldOperand(edi, Code::kHandlerTableOffset));
789 shr(edx, StackHandler::kKindWidth);
790 mov(edx, FieldOperand(ebx, edx, times_4, FixedArray::kHeaderSize));
792 lea(edi, FieldOperand(edi, edx, times_1, Code::kHeaderSize));
797 void MacroAssembler::Throw(Register value) {
798 // Adjust this code if not the case.
799 STATIC_ASSERT(StackHandlerConstants::kSize == 5 * kPointerSize);
800 STATIC_ASSERT(StackHandlerConstants::kNextOffset == 0);
801 STATIC_ASSERT(StackHandlerConstants::kCodeOffset == 1 * kPointerSize);
802 STATIC_ASSERT(StackHandlerConstants::kStateOffset == 2 * kPointerSize);
803 STATIC_ASSERT(StackHandlerConstants::kContextOffset == 3 * kPointerSize);
804 STATIC_ASSERT(StackHandlerConstants::kFPOffset == 4 * kPointerSize);
806 // The exception is expected in eax.
807 if (!value.is(eax)) {
810 // Drop the stack pointer to the top of the top handler.
811 ExternalReference handler_address(Isolate::kHandlerAddress, isolate());
812 mov(esp, Operand::StaticVariable(handler_address));
813 // Restore the next handler.
814 pop(Operand::StaticVariable(handler_address));
816 // Remove the code object and state, compute the handler address in edi.
817 pop(edi); // Code object.
818 pop(edx); // Index and state.
820 // Restore the context and frame pointer.
821 pop(esi); // Context.
822 pop(ebp); // Frame pointer.
824 // If the handler is a JS frame, restore the context to the frame.
825 // (kind == ENTRY) == (ebp == 0) == (esi == 0), so we could test either
829 j(zero, &skip, Label::kNear);
830 mov(Operand(ebp, StandardFrameConstants::kContextOffset), esi);
833 JumpToHandlerEntry();
837 void MacroAssembler::ThrowUncatchable(UncatchableExceptionType type,
839 // Adjust this code if not the case.
840 STATIC_ASSERT(StackHandlerConstants::kSize == 5 * kPointerSize);
841 STATIC_ASSERT(StackHandlerConstants::kNextOffset == 0);
842 STATIC_ASSERT(StackHandlerConstants::kCodeOffset == 1 * kPointerSize);
843 STATIC_ASSERT(StackHandlerConstants::kStateOffset == 2 * kPointerSize);
844 STATIC_ASSERT(StackHandlerConstants::kContextOffset == 3 * kPointerSize);
845 STATIC_ASSERT(StackHandlerConstants::kFPOffset == 4 * kPointerSize);
847 // The exception is expected in eax.
848 if (type == OUT_OF_MEMORY) {
849 // Set external caught exception to false.
850 ExternalReference external_caught(Isolate::kExternalCaughtExceptionAddress,
852 mov(Operand::StaticVariable(external_caught), Immediate(false));
854 // Set pending exception and eax to out of memory exception.
855 ExternalReference pending_exception(Isolate::kPendingExceptionAddress,
857 mov(eax, reinterpret_cast<int32_t>(Failure::OutOfMemoryException()));
858 mov(Operand::StaticVariable(pending_exception), eax);
859 } else if (!value.is(eax)) {
863 // Drop the stack pointer to the top of the top stack handler.
864 ExternalReference handler_address(Isolate::kHandlerAddress, isolate());
865 mov(esp, Operand::StaticVariable(handler_address));
867 // Unwind the handlers until the top ENTRY handler is found.
868 Label fetch_next, check_kind;
869 jmp(&check_kind, Label::kNear);
871 mov(esp, Operand(esp, StackHandlerConstants::kNextOffset));
874 STATIC_ASSERT(StackHandler::ENTRY == 0);
875 test(Operand(esp, StackHandlerConstants::kStateOffset),
876 Immediate(StackHandler::KindField::kMask));
877 j(not_zero, &fetch_next);
879 // Set the top handler address to next handler past the top ENTRY handler.
880 pop(Operand::StaticVariable(handler_address));
882 // Remove the code object and state, compute the handler address in edi.
883 pop(edi); // Code object.
884 pop(edx); // Index and state.
886 // Clear the context pointer and frame pointer (0 was saved in the handler).
890 JumpToHandlerEntry();
894 void MacroAssembler::CheckAccessGlobalProxy(Register holder_reg,
899 ASSERT(!holder_reg.is(scratch));
901 // Load current lexical context from the stack frame.
902 mov(scratch, Operand(ebp, StandardFrameConstants::kContextOffset));
904 // When generating debug code, make sure the lexical context is set.
905 if (emit_debug_code()) {
906 cmp(scratch, Immediate(0));
907 Check(not_equal, "we should not have an empty lexical context");
909 // Load the global context of the current context.
910 int offset = Context::kHeaderSize + Context::GLOBAL_INDEX * kPointerSize;
911 mov(scratch, FieldOperand(scratch, offset));
912 mov(scratch, FieldOperand(scratch, GlobalObject::kGlobalContextOffset));
914 // Check the context is a global context.
915 if (emit_debug_code()) {
917 // Read the first word and compare to global_context_map.
918 mov(scratch, FieldOperand(scratch, HeapObject::kMapOffset));
919 cmp(scratch, isolate()->factory()->global_context_map());
920 Check(equal, "JSGlobalObject::global_context should be a global context.");
924 // Check if both contexts are the same.
925 cmp(scratch, FieldOperand(holder_reg, JSGlobalProxy::kContextOffset));
926 j(equal, &same_contexts);
928 // Compare security tokens, save holder_reg on the stack so we can use it
929 // as a temporary register.
931 // TODO(119): avoid push(holder_reg)/pop(holder_reg)
933 // Check that the security token in the calling global object is
934 // compatible with the security token in the receiving global
936 mov(holder_reg, FieldOperand(holder_reg, JSGlobalProxy::kContextOffset));
938 // Check the context is a global context.
939 if (emit_debug_code()) {
940 cmp(holder_reg, isolate()->factory()->null_value());
941 Check(not_equal, "JSGlobalProxy::context() should not be null.");
944 // Read the first word and compare to global_context_map(),
945 mov(holder_reg, FieldOperand(holder_reg, HeapObject::kMapOffset));
946 cmp(holder_reg, isolate()->factory()->global_context_map());
947 Check(equal, "JSGlobalObject::global_context should be a global context.");
951 int token_offset = Context::kHeaderSize +
952 Context::SECURITY_TOKEN_INDEX * kPointerSize;
953 mov(scratch, FieldOperand(scratch, token_offset));
954 cmp(scratch, FieldOperand(holder_reg, token_offset));
958 bind(&same_contexts);
962 void MacroAssembler::LoadFromNumberDictionary(Label* miss,
971 // elements - holds the slow-case elements of the receiver and is unchanged.
973 // key - holds the smi key on entry and is unchanged.
975 // Scratch registers:
977 // r0 - holds the untagged key on entry and holds the hash once computed.
979 // r1 - used to hold the capacity mask of the dictionary
981 // r2 - used for the index into the dictionary.
983 // result - holds the result on exit if the load succeeds and we fall through.
987 // Compute the hash code from the untagged key. This must be kept in sync
988 // with ComputeIntegerHash in utils.h.
990 // hash = ~hash + (hash << 15);
995 // hash = hash ^ (hash >> 12);
999 // hash = hash + (hash << 2);
1000 lea(r0, Operand(r0, r0, times_4, 0));
1001 // hash = hash ^ (hash >> 4);
1005 // hash = hash * 2057;
1007 // hash = hash ^ (hash >> 16);
1012 // Compute capacity mask.
1013 mov(r1, FieldOperand(elements, NumberDictionary::kCapacityOffset));
1014 shr(r1, kSmiTagSize); // convert smi to int
1017 // Generate an unrolled loop that performs a few probes before giving up.
1018 const int kProbes = 4;
1019 for (int i = 0; i < kProbes; i++) {
1020 // Use r2 for index calculations and keep the hash intact in r0.
1022 // Compute the masked index: (hash + i + i * i) & mask.
1024 add(r2, Immediate(NumberDictionary::GetProbeOffset(i)));
1028 // Scale the index by multiplying by the entry size.
1029 ASSERT(NumberDictionary::kEntrySize == 3);
1030 lea(r2, Operand(r2, r2, times_2, 0)); // r2 = r2 * 3
1032 // Check if the key matches.
1033 cmp(key, FieldOperand(elements,
1036 NumberDictionary::kElementsStartOffset));
1037 if (i != (kProbes - 1)) {
1045 // Check that the value is a normal propety.
1046 const int kDetailsOffset =
1047 NumberDictionary::kElementsStartOffset + 2 * kPointerSize;
1048 ASSERT_EQ(NORMAL, 0);
1049 test(FieldOperand(elements, r2, times_pointer_size, kDetailsOffset),
1050 Immediate(PropertyDetails::TypeField::kMask << kSmiTagSize));
1053 // Get the value at the masked, scaled index.
1054 const int kValueOffset =
1055 NumberDictionary::kElementsStartOffset + kPointerSize;
1056 mov(result, FieldOperand(elements, r2, times_pointer_size, kValueOffset));
1060 void MacroAssembler::LoadAllocationTopHelper(Register result,
1062 AllocationFlags flags) {
1063 ExternalReference new_space_allocation_top =
1064 ExternalReference::new_space_allocation_top_address(isolate());
1066 // Just return if allocation top is already known.
1067 if ((flags & RESULT_CONTAINS_TOP) != 0) {
1068 // No use of scratch if allocation top is provided.
1069 ASSERT(scratch.is(no_reg));
1071 // Assert that result actually contains top on entry.
1072 cmp(result, Operand::StaticVariable(new_space_allocation_top));
1073 Check(equal, "Unexpected allocation top");
1078 // Move address of new object to result. Use scratch register if available.
1079 if (scratch.is(no_reg)) {
1080 mov(result, Operand::StaticVariable(new_space_allocation_top));
1082 mov(scratch, Immediate(new_space_allocation_top));
1083 mov(result, Operand(scratch, 0));
1088 void MacroAssembler::UpdateAllocationTopHelper(Register result_end,
1090 if (emit_debug_code()) {
1091 test(result_end, Immediate(kObjectAlignmentMask));
1092 Check(zero, "Unaligned allocation in new space");
1095 ExternalReference new_space_allocation_top =
1096 ExternalReference::new_space_allocation_top_address(isolate());
1098 // Update new top. Use scratch if available.
1099 if (scratch.is(no_reg)) {
1100 mov(Operand::StaticVariable(new_space_allocation_top), result_end);
1102 mov(Operand(scratch, 0), result_end);
1107 void MacroAssembler::AllocateInNewSpace(int object_size,
1109 Register result_end,
1112 AllocationFlags flags) {
1113 if (!FLAG_inline_new) {
1114 if (emit_debug_code()) {
1115 // Trash the registers to simulate an allocation failure.
1116 mov(result, Immediate(0x7091));
1117 if (result_end.is_valid()) {
1118 mov(result_end, Immediate(0x7191));
1120 if (scratch.is_valid()) {
1121 mov(scratch, Immediate(0x7291));
1127 ASSERT(!result.is(result_end));
1129 // Load address of new object into result.
1130 LoadAllocationTopHelper(result, scratch, flags);
1132 Register top_reg = result_end.is_valid() ? result_end : result;
1134 // Calculate new top and bail out if new space is exhausted.
1135 ExternalReference new_space_allocation_limit =
1136 ExternalReference::new_space_allocation_limit_address(isolate());
1138 if (!top_reg.is(result)) {
1139 mov(top_reg, result);
1141 add(top_reg, Immediate(object_size));
1142 j(carry, gc_required);
1143 cmp(top_reg, Operand::StaticVariable(new_space_allocation_limit));
1144 j(above, gc_required);
1146 // Update allocation top.
1147 UpdateAllocationTopHelper(top_reg, scratch);
1149 // Tag result if requested.
1150 if (top_reg.is(result)) {
1151 if ((flags & TAG_OBJECT) != 0) {
1152 sub(result, Immediate(object_size - kHeapObjectTag));
1154 sub(result, Immediate(object_size));
1156 } else if ((flags & TAG_OBJECT) != 0) {
1157 add(result, Immediate(kHeapObjectTag));
1162 void MacroAssembler::AllocateInNewSpace(int header_size,
1163 ScaleFactor element_size,
1164 Register element_count,
1166 Register result_end,
1169 AllocationFlags flags) {
1170 if (!FLAG_inline_new) {
1171 if (emit_debug_code()) {
1172 // Trash the registers to simulate an allocation failure.
1173 mov(result, Immediate(0x7091));
1174 mov(result_end, Immediate(0x7191));
1175 if (scratch.is_valid()) {
1176 mov(scratch, Immediate(0x7291));
1178 // Register element_count is not modified by the function.
1183 ASSERT(!result.is(result_end));
1185 // Load address of new object into result.
1186 LoadAllocationTopHelper(result, scratch, flags);
1188 // Calculate new top and bail out if new space is exhausted.
1189 ExternalReference new_space_allocation_limit =
1190 ExternalReference::new_space_allocation_limit_address(isolate());
1192 // We assume that element_count*element_size + header_size does not
1194 lea(result_end, Operand(element_count, element_size, header_size));
1195 add(result_end, result);
1196 j(carry, gc_required);
1197 cmp(result_end, Operand::StaticVariable(new_space_allocation_limit));
1198 j(above, gc_required);
1200 // Tag result if requested.
1201 if ((flags & TAG_OBJECT) != 0) {
1202 lea(result, Operand(result, kHeapObjectTag));
1205 // Update allocation top.
1206 UpdateAllocationTopHelper(result_end, scratch);
1210 void MacroAssembler::AllocateInNewSpace(Register object_size,
1212 Register result_end,
1215 AllocationFlags flags) {
1216 if (!FLAG_inline_new) {
1217 if (emit_debug_code()) {
1218 // Trash the registers to simulate an allocation failure.
1219 mov(result, Immediate(0x7091));
1220 mov(result_end, Immediate(0x7191));
1221 if (scratch.is_valid()) {
1222 mov(scratch, Immediate(0x7291));
1224 // object_size is left unchanged by this function.
1229 ASSERT(!result.is(result_end));
1231 // Load address of new object into result.
1232 LoadAllocationTopHelper(result, scratch, flags);
1234 // Calculate new top and bail out if new space is exhausted.
1235 ExternalReference new_space_allocation_limit =
1236 ExternalReference::new_space_allocation_limit_address(isolate());
1237 if (!object_size.is(result_end)) {
1238 mov(result_end, object_size);
1240 add(result_end, result);
1241 j(carry, gc_required);
1242 cmp(result_end, Operand::StaticVariable(new_space_allocation_limit));
1243 j(above, gc_required);
1245 // Tag result if requested.
1246 if ((flags & TAG_OBJECT) != 0) {
1247 lea(result, Operand(result, kHeapObjectTag));
1250 // Update allocation top.
1251 UpdateAllocationTopHelper(result_end, scratch);
1255 void MacroAssembler::UndoAllocationInNewSpace(Register object) {
1256 ExternalReference new_space_allocation_top =
1257 ExternalReference::new_space_allocation_top_address(isolate());
1259 // Make sure the object has no tag before resetting top.
1260 and_(object, Immediate(~kHeapObjectTagMask));
1262 cmp(object, Operand::StaticVariable(new_space_allocation_top));
1263 Check(below, "Undo allocation of non allocated memory");
1265 mov(Operand::StaticVariable(new_space_allocation_top), object);
1269 void MacroAssembler::AllocateHeapNumber(Register result,
1272 Label* gc_required) {
1273 // Allocate heap number in new space.
1274 AllocateInNewSpace(HeapNumber::kSize,
1282 mov(FieldOperand(result, HeapObject::kMapOffset),
1283 Immediate(isolate()->factory()->heap_number_map()));
1287 void MacroAssembler::AllocateTwoByteString(Register result,
1292 Label* gc_required) {
1293 // Calculate the number of bytes needed for the characters in the string while
1294 // observing object alignment.
1295 ASSERT((SeqTwoByteString::kHeaderSize & kObjectAlignmentMask) == 0);
1296 ASSERT(kShortSize == 2);
1297 // scratch1 = length * 2 + kObjectAlignmentMask.
1298 lea(scratch1, Operand(length, length, times_1, kObjectAlignmentMask));
1299 and_(scratch1, Immediate(~kObjectAlignmentMask));
1301 // Allocate two byte string in new space.
1302 AllocateInNewSpace(SeqTwoByteString::kHeaderSize,
1311 // Set the map, length and hash field.
1312 mov(FieldOperand(result, HeapObject::kMapOffset),
1313 Immediate(isolate()->factory()->string_map()));
1314 mov(scratch1, length);
1316 mov(FieldOperand(result, String::kLengthOffset), scratch1);
1317 mov(FieldOperand(result, String::kHashFieldOffset),
1318 Immediate(String::kEmptyHashField));
1322 void MacroAssembler::AllocateAsciiString(Register result,
1327 Label* gc_required) {
1328 // Calculate the number of bytes needed for the characters in the string while
1329 // observing object alignment.
1330 ASSERT((SeqAsciiString::kHeaderSize & kObjectAlignmentMask) == 0);
1331 mov(scratch1, length);
1332 ASSERT(kCharSize == 1);
1333 add(scratch1, Immediate(kObjectAlignmentMask));
1334 and_(scratch1, Immediate(~kObjectAlignmentMask));
1336 // Allocate ascii string in new space.
1337 AllocateInNewSpace(SeqAsciiString::kHeaderSize,
1346 // Set the map, length and hash field.
1347 mov(FieldOperand(result, HeapObject::kMapOffset),
1348 Immediate(isolate()->factory()->ascii_string_map()));
1349 mov(scratch1, length);
1351 mov(FieldOperand(result, String::kLengthOffset), scratch1);
1352 mov(FieldOperand(result, String::kHashFieldOffset),
1353 Immediate(String::kEmptyHashField));
1357 void MacroAssembler::AllocateAsciiString(Register result,
1361 Label* gc_required) {
1364 // Allocate ascii string in new space.
1365 AllocateInNewSpace(SeqAsciiString::SizeFor(length),
1372 // Set the map, length and hash field.
1373 mov(FieldOperand(result, HeapObject::kMapOffset),
1374 Immediate(isolate()->factory()->ascii_string_map()));
1375 mov(FieldOperand(result, String::kLengthOffset),
1376 Immediate(Smi::FromInt(length)));
1377 mov(FieldOperand(result, String::kHashFieldOffset),
1378 Immediate(String::kEmptyHashField));
1382 void MacroAssembler::AllocateTwoByteConsString(Register result,
1385 Label* gc_required) {
1386 // Allocate heap number in new space.
1387 AllocateInNewSpace(ConsString::kSize,
1394 // Set the map. The other fields are left uninitialized.
1395 mov(FieldOperand(result, HeapObject::kMapOffset),
1396 Immediate(isolate()->factory()->cons_string_map()));
1400 void MacroAssembler::AllocateAsciiConsString(Register result,
1403 Label* gc_required) {
1404 // Allocate heap number in new space.
1405 AllocateInNewSpace(ConsString::kSize,
1412 // Set the map. The other fields are left uninitialized.
1413 mov(FieldOperand(result, HeapObject::kMapOffset),
1414 Immediate(isolate()->factory()->cons_ascii_string_map()));
1418 void MacroAssembler::AllocateTwoByteSlicedString(Register result,
1421 Label* gc_required) {
1422 // Allocate heap number in new space.
1423 AllocateInNewSpace(SlicedString::kSize,
1430 // Set the map. The other fields are left uninitialized.
1431 mov(FieldOperand(result, HeapObject::kMapOffset),
1432 Immediate(isolate()->factory()->sliced_string_map()));
1436 void MacroAssembler::AllocateAsciiSlicedString(Register result,
1439 Label* gc_required) {
1440 // Allocate heap number in new space.
1441 AllocateInNewSpace(SlicedString::kSize,
1448 // Set the map. The other fields are left uninitialized.
1449 mov(FieldOperand(result, HeapObject::kMapOffset),
1450 Immediate(isolate()->factory()->sliced_ascii_string_map()));
1454 // Copy memory, byte-by-byte, from source to destination. Not optimized for
1455 // long or aligned copies. The contents of scratch and length are destroyed.
1456 // Source and destination are incremented by length.
1457 // Many variants of movsb, loop unrolling, word moves, and indexed operands
1458 // have been tried here already, and this is fastest.
1459 // A simpler loop is faster on small copies, but 30% slower on large ones.
1460 // The cld() instruction must have been emitted, to set the direction flag(),
1461 // before calling this function.
1462 void MacroAssembler::CopyBytes(Register source,
1463 Register destination,
1466 Label loop, done, short_string, short_loop;
1467 // Experimentation shows that the short string loop is faster if length < 10.
1468 cmp(length, Immediate(10));
1469 j(less_equal, &short_string);
1471 ASSERT(source.is(esi));
1472 ASSERT(destination.is(edi));
1473 ASSERT(length.is(ecx));
1475 // Because source is 4-byte aligned in our uses of this function,
1476 // we keep source aligned for the rep_movs call by copying the odd bytes
1477 // at the end of the ranges.
1478 mov(scratch, Operand(source, length, times_1, -4));
1479 mov(Operand(destination, length, times_1, -4), scratch);
1483 and_(scratch, Immediate(0x3));
1484 add(destination, scratch);
1487 bind(&short_string);
1488 test(length, length);
1492 mov_b(scratch, Operand(source, 0));
1493 mov_b(Operand(destination, 0), scratch);
1497 j(not_zero, &short_loop);
1503 void MacroAssembler::InitializeFieldsWithFiller(Register start_offset,
1504 Register end_offset,
1509 mov(Operand(start_offset, 0), filler);
1510 add(start_offset, Immediate(kPointerSize));
1512 cmp(start_offset, end_offset);
1517 void MacroAssembler::BooleanBitTest(Register object,
1520 bit_index += kSmiTagSize + kSmiShiftSize;
1521 ASSERT(IsPowerOf2(kBitsPerByte));
1522 int byte_index = bit_index / kBitsPerByte;
1523 int byte_bit_index = bit_index & (kBitsPerByte - 1);
1524 test_b(FieldOperand(object, field_offset + byte_index),
1525 static_cast<byte>(1 << byte_bit_index));
1530 void MacroAssembler::NegativeZeroTest(Register result,
1532 Label* then_label) {
1534 test(result, result);
1537 j(sign, then_label);
1542 void MacroAssembler::NegativeZeroTest(Register result,
1546 Label* then_label) {
1548 test(result, result);
1552 j(sign, then_label);
1557 void MacroAssembler::TryGetFunctionPrototype(Register function,
1561 bool miss_on_bound_function) {
1562 // Check that the receiver isn't a smi.
1563 JumpIfSmi(function, miss);
1565 // Check that the function really is a function.
1566 CmpObjectType(function, JS_FUNCTION_TYPE, result);
1569 if (miss_on_bound_function) {
1570 // If a bound function, go to miss label.
1572 FieldOperand(function, JSFunction::kSharedFunctionInfoOffset));
1573 BooleanBitTest(scratch, SharedFunctionInfo::kCompilerHintsOffset,
1574 SharedFunctionInfo::kBoundFunction);
1578 // Make sure that the function has an instance prototype.
1580 movzx_b(scratch, FieldOperand(result, Map::kBitFieldOffset));
1581 test(scratch, Immediate(1 << Map::kHasNonInstancePrototype));
1582 j(not_zero, &non_instance);
1584 // Get the prototype or initial map from the function.
1586 FieldOperand(function, JSFunction::kPrototypeOrInitialMapOffset));
1588 // If the prototype or initial map is the hole, don't return it and
1589 // simply miss the cache instead. This will allow us to allocate a
1590 // prototype object on-demand in the runtime system.
1591 cmp(result, Immediate(isolate()->factory()->the_hole_value()));
1594 // If the function does not have an initial map, we're done.
1596 CmpObjectType(result, MAP_TYPE, scratch);
1597 j(not_equal, &done);
1599 // Get the prototype from the initial map.
1600 mov(result, FieldOperand(result, Map::kPrototypeOffset));
1603 // Non-instance prototype: Fetch prototype from constructor field
1605 bind(&non_instance);
1606 mov(result, FieldOperand(result, Map::kConstructorOffset));
1613 void MacroAssembler::CallStub(CodeStub* stub, unsigned ast_id) {
1614 ASSERT(AllowThisStubCall(stub)); // Calls are not allowed in some stubs.
1615 call(stub->GetCode(), RelocInfo::CODE_TARGET, ast_id);
1619 void MacroAssembler::TailCallStub(CodeStub* stub) {
1620 ASSERT(allow_stub_calls_ || stub->CompilingCallsToThisStubIsGCSafe());
1621 jmp(stub->GetCode(), RelocInfo::CODE_TARGET);
1625 void MacroAssembler::StubReturn(int argc) {
1626 ASSERT(argc >= 1 && generating_stub());
1627 ret((argc - 1) * kPointerSize);
1631 bool MacroAssembler::AllowThisStubCall(CodeStub* stub) {
1632 if (!has_frame_ && stub->SometimesSetsUpAFrame()) return false;
1633 return allow_stub_calls_ || stub->CompilingCallsToThisStubIsGCSafe();
1637 void MacroAssembler::IllegalOperation(int num_arguments) {
1638 if (num_arguments > 0) {
1639 add(esp, Immediate(num_arguments * kPointerSize));
1641 mov(eax, Immediate(isolate()->factory()->undefined_value()));
1645 void MacroAssembler::IndexFromHash(Register hash, Register index) {
1646 // The assert checks that the constants for the maximum number of digits
1647 // for an array index cached in the hash field and the number of bits
1648 // reserved for it does not conflict.
1649 ASSERT(TenToThe(String::kMaxCachedArrayIndexLength) <
1650 (1 << String::kArrayIndexValueBits));
1651 // We want the smi-tagged index in key. kArrayIndexValueMask has zeros in
1652 // the low kHashShift bits.
1653 and_(hash, String::kArrayIndexValueMask);
1654 STATIC_ASSERT(String::kHashShift >= kSmiTagSize && kSmiTag == 0);
1655 if (String::kHashShift > kSmiTagSize) {
1656 shr(hash, String::kHashShift - kSmiTagSize);
1658 if (!index.is(hash)) {
1664 void MacroAssembler::CallRuntime(Runtime::FunctionId id, int num_arguments) {
1665 CallRuntime(Runtime::FunctionForId(id), num_arguments);
1669 void MacroAssembler::CallRuntimeSaveDoubles(Runtime::FunctionId id) {
1670 const Runtime::Function* function = Runtime::FunctionForId(id);
1671 Set(eax, Immediate(function->nargs));
1672 mov(ebx, Immediate(ExternalReference(function, isolate())));
1673 CEntryStub ces(1, kSaveFPRegs);
1678 void MacroAssembler::CallRuntime(const Runtime::Function* f,
1679 int num_arguments) {
1680 // If the expected number of arguments of the runtime function is
1681 // constant, we check that the actual number of arguments match the
1683 if (f->nargs >= 0 && f->nargs != num_arguments) {
1684 IllegalOperation(num_arguments);
1688 // TODO(1236192): Most runtime routines don't need the number of
1689 // arguments passed in because it is constant. At some point we
1690 // should remove this need and make the runtime routine entry code
1692 Set(eax, Immediate(num_arguments));
1693 mov(ebx, Immediate(ExternalReference(f, isolate())));
1699 void MacroAssembler::CallExternalReference(ExternalReference ref,
1700 int num_arguments) {
1701 mov(eax, Immediate(num_arguments));
1702 mov(ebx, Immediate(ref));
1709 void MacroAssembler::TailCallExternalReference(const ExternalReference& ext,
1712 // TODO(1236192): Most runtime routines don't need the number of
1713 // arguments passed in because it is constant. At some point we
1714 // should remove this need and make the runtime routine entry code
1716 Set(eax, Immediate(num_arguments));
1717 JumpToExternalReference(ext);
1721 void MacroAssembler::TailCallRuntime(Runtime::FunctionId fid,
1724 TailCallExternalReference(ExternalReference(fid, isolate()),
1730 // If true, a Handle<T> returned by value from a function with cdecl calling
1731 // convention will be returned directly as a value of location_ field in a
1733 // If false, it is returned as a pointer to a preallocated by caller memory
1734 // region. Pointer to this region should be passed to a function as an
1735 // implicit first argument.
1736 #if defined(USING_BSD_ABI) || defined(__MINGW32__) || defined(__CYGWIN__)
1737 static const bool kReturnHandlesDirectly = true;
1739 static const bool kReturnHandlesDirectly = false;
1743 Operand ApiParameterOperand(int index) {
1745 esp, (index + (kReturnHandlesDirectly ? 0 : 1)) * kPointerSize);
1749 void MacroAssembler::PrepareCallApiFunction(int argc) {
1750 if (kReturnHandlesDirectly) {
1751 EnterApiExitFrame(argc);
1752 // When handles are returned directly we don't have to allocate extra
1753 // space for and pass an out parameter.
1754 if (emit_debug_code()) {
1755 mov(esi, Immediate(BitCast<int32_t>(kZapValue)));
1758 // We allocate two additional slots: return value and pointer to it.
1759 EnterApiExitFrame(argc + 2);
1761 // The argument slots are filled as follows:
1763 // n + 1: output slot
1767 // 0: pointer to the output slot
1769 lea(esi, Operand(esp, (argc + 1) * kPointerSize));
1770 mov(Operand(esp, 0 * kPointerSize), esi);
1771 if (emit_debug_code()) {
1772 mov(Operand(esi, 0), Immediate(0));
1778 void MacroAssembler::CallApiFunctionAndReturn(Address function_address,
1780 ExternalReference next_address =
1781 ExternalReference::handle_scope_next_address();
1782 ExternalReference limit_address =
1783 ExternalReference::handle_scope_limit_address();
1784 ExternalReference level_address =
1785 ExternalReference::handle_scope_level_address();
1787 // Allocate HandleScope in callee-save registers.
1788 mov(ebx, Operand::StaticVariable(next_address));
1789 mov(edi, Operand::StaticVariable(limit_address));
1790 add(Operand::StaticVariable(level_address), Immediate(1));
1792 // Call the api function.
1793 call(function_address, RelocInfo::RUNTIME_ENTRY);
1795 if (!kReturnHandlesDirectly) {
1796 // PrepareCallApiFunction saved pointer to the output slot into
1797 // callee-save register esi.
1798 mov(eax, Operand(esi, 0));
1803 Label promote_scheduled_exception;
1804 Label delete_allocated_handles;
1805 Label leave_exit_frame;
1807 // Check if the result handle holds 0.
1809 j(zero, &empty_handle);
1810 // It was non-zero. Dereference to get the result value.
1811 mov(eax, Operand(eax, 0));
1813 // No more valid handles (the result handle was the last one). Restore
1814 // previous handle scope.
1815 mov(Operand::StaticVariable(next_address), ebx);
1816 sub(Operand::StaticVariable(level_address), Immediate(1));
1817 Assert(above_equal, "Invalid HandleScope level");
1818 cmp(edi, Operand::StaticVariable(limit_address));
1819 j(not_equal, &delete_allocated_handles);
1820 bind(&leave_exit_frame);
1822 // Check if the function scheduled an exception.
1823 ExternalReference scheduled_exception_address =
1824 ExternalReference::scheduled_exception_address(isolate());
1825 cmp(Operand::StaticVariable(scheduled_exception_address),
1826 Immediate(isolate()->factory()->the_hole_value()));
1827 j(not_equal, &promote_scheduled_exception);
1828 LeaveApiExitFrame();
1829 ret(stack_space * kPointerSize);
1830 bind(&promote_scheduled_exception);
1831 TailCallRuntime(Runtime::kPromoteScheduledException, 0, 1);
1833 bind(&empty_handle);
1834 // It was zero; the result is undefined.
1835 mov(eax, isolate()->factory()->undefined_value());
1838 // HandleScope limit has changed. Delete allocated extensions.
1839 ExternalReference delete_extensions =
1840 ExternalReference::delete_handle_scope_extensions(isolate());
1841 bind(&delete_allocated_handles);
1842 mov(Operand::StaticVariable(limit_address), edi);
1844 mov(Operand(esp, 0), Immediate(ExternalReference::isolate_address()));
1845 mov(eax, Immediate(delete_extensions));
1848 jmp(&leave_exit_frame);
1852 void MacroAssembler::JumpToExternalReference(const ExternalReference& ext) {
1853 // Set the entry point and jump to the C entry runtime stub.
1854 mov(ebx, Immediate(ext));
1856 jmp(ces.GetCode(), RelocInfo::CODE_TARGET);
1860 void MacroAssembler::SetCallKind(Register dst, CallKind call_kind) {
1861 // This macro takes the dst register to make the code more readable
1862 // at the call sites. However, the dst register has to be ecx to
1863 // follow the calling convention which requires the call type to be
1865 ASSERT(dst.is(ecx));
1866 if (call_kind == CALL_AS_FUNCTION) {
1867 // Set to some non-zero smi by updating the least significant
1869 mov_b(dst, 1 << kSmiTagSize);
1871 // Set to smi zero by clearing the register.
1877 void MacroAssembler::InvokePrologue(const ParameterCount& expected,
1878 const ParameterCount& actual,
1879 Handle<Code> code_constant,
1880 const Operand& code_operand,
1883 Label::Distance done_near,
1884 const CallWrapper& call_wrapper,
1885 CallKind call_kind) {
1886 bool definitely_matches = false;
1888 if (expected.is_immediate()) {
1889 ASSERT(actual.is_immediate());
1890 if (expected.immediate() == actual.immediate()) {
1891 definitely_matches = true;
1893 mov(eax, actual.immediate());
1894 const int sentinel = SharedFunctionInfo::kDontAdaptArgumentsSentinel;
1895 if (expected.immediate() == sentinel) {
1896 // Don't worry about adapting arguments for builtins that
1897 // don't want that done. Skip adaption code by making it look
1898 // like we have a match between expected and actual number of
1900 definitely_matches = true;
1902 mov(ebx, expected.immediate());
1906 if (actual.is_immediate()) {
1907 // Expected is in register, actual is immediate. This is the
1908 // case when we invoke function values without going through the
1910 cmp(expected.reg(), actual.immediate());
1912 ASSERT(expected.reg().is(ebx));
1913 mov(eax, actual.immediate());
1914 } else if (!expected.reg().is(actual.reg())) {
1915 // Both expected and actual are in (different) registers. This
1916 // is the case when we invoke functions using call and apply.
1917 cmp(expected.reg(), actual.reg());
1919 ASSERT(actual.reg().is(eax));
1920 ASSERT(expected.reg().is(ebx));
1924 if (!definitely_matches) {
1925 Handle<Code> adaptor =
1926 isolate()->builtins()->ArgumentsAdaptorTrampoline();
1927 if (!code_constant.is_null()) {
1928 mov(edx, Immediate(code_constant));
1929 add(edx, Immediate(Code::kHeaderSize - kHeapObjectTag));
1930 } else if (!code_operand.is_reg(edx)) {
1931 mov(edx, code_operand);
1934 if (flag == CALL_FUNCTION) {
1935 call_wrapper.BeforeCall(CallSize(adaptor, RelocInfo::CODE_TARGET));
1936 SetCallKind(ecx, call_kind);
1937 call(adaptor, RelocInfo::CODE_TARGET);
1938 call_wrapper.AfterCall();
1939 jmp(done, done_near);
1941 SetCallKind(ecx, call_kind);
1942 jmp(adaptor, RelocInfo::CODE_TARGET);
1949 void MacroAssembler::InvokeCode(const Operand& code,
1950 const ParameterCount& expected,
1951 const ParameterCount& actual,
1953 const CallWrapper& call_wrapper,
1954 CallKind call_kind) {
1955 // You can't call a function without a valid frame.
1956 ASSERT(flag == JUMP_FUNCTION || has_frame());
1959 InvokePrologue(expected, actual, Handle<Code>::null(), code,
1960 &done, flag, Label::kNear, call_wrapper,
1962 if (flag == CALL_FUNCTION) {
1963 call_wrapper.BeforeCall(CallSize(code));
1964 SetCallKind(ecx, call_kind);
1966 call_wrapper.AfterCall();
1968 ASSERT(flag == JUMP_FUNCTION);
1969 SetCallKind(ecx, call_kind);
1976 void MacroAssembler::InvokeCode(Handle<Code> code,
1977 const ParameterCount& expected,
1978 const ParameterCount& actual,
1979 RelocInfo::Mode rmode,
1981 const CallWrapper& call_wrapper,
1982 CallKind call_kind) {
1983 // You can't call a function without a valid frame.
1984 ASSERT(flag == JUMP_FUNCTION || has_frame());
1987 Operand dummy(eax, 0);
1988 InvokePrologue(expected, actual, code, dummy, &done, flag, Label::kNear,
1989 call_wrapper, call_kind);
1990 if (flag == CALL_FUNCTION) {
1991 call_wrapper.BeforeCall(CallSize(code, rmode));
1992 SetCallKind(ecx, call_kind);
1994 call_wrapper.AfterCall();
1996 ASSERT(flag == JUMP_FUNCTION);
1997 SetCallKind(ecx, call_kind);
2004 void MacroAssembler::InvokeFunction(Register fun,
2005 const ParameterCount& actual,
2007 const CallWrapper& call_wrapper,
2008 CallKind call_kind) {
2009 // You can't call a function without a valid frame.
2010 ASSERT(flag == JUMP_FUNCTION || has_frame());
2012 ASSERT(fun.is(edi));
2013 mov(edx, FieldOperand(edi, JSFunction::kSharedFunctionInfoOffset));
2014 mov(esi, FieldOperand(edi, JSFunction::kContextOffset));
2015 mov(ebx, FieldOperand(edx, SharedFunctionInfo::kFormalParameterCountOffset));
2018 ParameterCount expected(ebx);
2019 InvokeCode(FieldOperand(edi, JSFunction::kCodeEntryOffset),
2020 expected, actual, flag, call_wrapper, call_kind);
2024 void MacroAssembler::InvokeFunction(Handle<JSFunction> function,
2025 const ParameterCount& actual,
2027 const CallWrapper& call_wrapper,
2028 CallKind call_kind) {
2029 // You can't call a function without a valid frame.
2030 ASSERT(flag == JUMP_FUNCTION || has_frame());
2032 // Get the function and setup the context.
2033 LoadHeapObject(edi, function);
2034 mov(esi, FieldOperand(edi, JSFunction::kContextOffset));
2036 ParameterCount expected(function->shared()->formal_parameter_count());
2037 // We call indirectly through the code field in the function to
2038 // allow recompilation to take effect without changing any of the
2040 InvokeCode(FieldOperand(edi, JSFunction::kCodeEntryOffset),
2041 expected, actual, flag, call_wrapper, call_kind);
2045 void MacroAssembler::InvokeBuiltin(Builtins::JavaScript id,
2047 const CallWrapper& call_wrapper) {
2048 // You can't call a builtin without a valid frame.
2049 ASSERT(flag == JUMP_FUNCTION || has_frame());
2051 // Rely on the assertion to check that the number of provided
2052 // arguments match the expected number of arguments. Fake a
2053 // parameter count to avoid emitting code to do the check.
2054 ParameterCount expected(0);
2055 GetBuiltinFunction(edi, id);
2056 InvokeCode(FieldOperand(edi, JSFunction::kCodeEntryOffset),
2057 expected, expected, flag, call_wrapper, CALL_AS_METHOD);
2061 void MacroAssembler::GetBuiltinFunction(Register target,
2062 Builtins::JavaScript id) {
2063 // Load the JavaScript builtin function from the builtins object.
2064 mov(target, Operand(esi, Context::SlotOffset(Context::GLOBAL_INDEX)));
2065 mov(target, FieldOperand(target, GlobalObject::kBuiltinsOffset));
2066 mov(target, FieldOperand(target,
2067 JSBuiltinsObject::OffsetOfFunctionWithId(id)));
2071 void MacroAssembler::GetBuiltinEntry(Register target, Builtins::JavaScript id) {
2072 ASSERT(!target.is(edi));
2073 // Load the JavaScript builtin function from the builtins object.
2074 GetBuiltinFunction(edi, id);
2075 // Load the code entry point from the function into the target register.
2076 mov(target, FieldOperand(edi, JSFunction::kCodeEntryOffset));
2080 void MacroAssembler::LoadContext(Register dst, int context_chain_length) {
2081 if (context_chain_length > 0) {
2082 // Move up the chain of contexts to the context containing the slot.
2083 mov(dst, Operand(esi, Context::SlotOffset(Context::PREVIOUS_INDEX)));
2084 for (int i = 1; i < context_chain_length; i++) {
2085 mov(dst, Operand(dst, Context::SlotOffset(Context::PREVIOUS_INDEX)));
2088 // Slot is in the current function context. Move it into the
2089 // destination register in case we store into it (the write barrier
2090 // cannot be allowed to destroy the context in esi).
2094 // We should not have found a with context by walking the context chain
2095 // (i.e., the static scope chain and runtime context chain do not agree).
2096 // A variable occurring in such a scope should have slot type LOOKUP and
2098 if (emit_debug_code()) {
2099 cmp(FieldOperand(dst, HeapObject::kMapOffset),
2100 isolate()->factory()->with_context_map());
2101 Check(not_equal, "Variable resolved to with context.");
2106 void MacroAssembler::LoadGlobalFunction(int index, Register function) {
2107 // Load the global or builtins object from the current context.
2108 mov(function, Operand(esi, Context::SlotOffset(Context::GLOBAL_INDEX)));
2109 // Load the global context from the global or builtins object.
2110 mov(function, FieldOperand(function, GlobalObject::kGlobalContextOffset));
2111 // Load the function from the global context.
2112 mov(function, Operand(function, Context::SlotOffset(index)));
2116 void MacroAssembler::LoadGlobalFunctionInitialMap(Register function,
2118 // Load the initial map. The global functions all have initial maps.
2119 mov(map, FieldOperand(function, JSFunction::kPrototypeOrInitialMapOffset));
2120 if (emit_debug_code()) {
2122 CheckMap(map, isolate()->factory()->meta_map(), &fail, DO_SMI_CHECK);
2125 Abort("Global functions must have initial map");
2131 // Store the value in register src in the safepoint register stack
2132 // slot for register dst.
2133 void MacroAssembler::StoreToSafepointRegisterSlot(Register dst, Register src) {
2134 mov(SafepointRegisterSlot(dst), src);
2138 void MacroAssembler::StoreToSafepointRegisterSlot(Register dst, Immediate src) {
2139 mov(SafepointRegisterSlot(dst), src);
2143 void MacroAssembler::LoadFromSafepointRegisterSlot(Register dst, Register src) {
2144 mov(dst, SafepointRegisterSlot(src));
2148 Operand MacroAssembler::SafepointRegisterSlot(Register reg) {
2149 return Operand(esp, SafepointRegisterStackIndex(reg.code()) * kPointerSize);
2153 int MacroAssembler::SafepointRegisterStackIndex(int reg_code) {
2154 // The registers are pushed starting with the lowest encoding,
2155 // which means that lowest encodings are furthest away from
2156 // the stack pointer.
2157 ASSERT(reg_code >= 0 && reg_code < kNumSafepointRegisters);
2158 return kNumSafepointRegisters - reg_code - 1;
2162 void MacroAssembler::LoadHeapObject(Register result,
2163 Handle<HeapObject> object) {
2164 if (isolate()->heap()->InNewSpace(*object)) {
2165 Handle<JSGlobalPropertyCell> cell =
2166 isolate()->factory()->NewJSGlobalPropertyCell(object);
2167 mov(result, Operand::Cell(cell));
2169 mov(result, object);
2174 void MacroAssembler::PushHeapObject(Handle<HeapObject> object) {
2175 if (isolate()->heap()->InNewSpace(*object)) {
2176 Handle<JSGlobalPropertyCell> cell =
2177 isolate()->factory()->NewJSGlobalPropertyCell(object);
2178 push(Operand::Cell(cell));
2185 void MacroAssembler::Ret() {
2190 void MacroAssembler::Ret(int bytes_dropped, Register scratch) {
2191 if (is_uint16(bytes_dropped)) {
2195 add(esp, Immediate(bytes_dropped));
2202 void MacroAssembler::Drop(int stack_elements) {
2203 if (stack_elements > 0) {
2204 add(esp, Immediate(stack_elements * kPointerSize));
2209 void MacroAssembler::Move(Register dst, Register src) {
2216 void MacroAssembler::SetCounter(StatsCounter* counter, int value) {
2217 if (FLAG_native_code_counters && counter->Enabled()) {
2218 mov(Operand::StaticVariable(ExternalReference(counter)), Immediate(value));
2223 void MacroAssembler::IncrementCounter(StatsCounter* counter, int value) {
2225 if (FLAG_native_code_counters && counter->Enabled()) {
2226 Operand operand = Operand::StaticVariable(ExternalReference(counter));
2230 add(operand, Immediate(value));
2236 void MacroAssembler::DecrementCounter(StatsCounter* counter, int value) {
2238 if (FLAG_native_code_counters && counter->Enabled()) {
2239 Operand operand = Operand::StaticVariable(ExternalReference(counter));
2243 sub(operand, Immediate(value));
2249 void MacroAssembler::IncrementCounter(Condition cc,
2250 StatsCounter* counter,
2253 if (FLAG_native_code_counters && counter->Enabled()) {
2255 j(NegateCondition(cc), &skip);
2257 IncrementCounter(counter, value);
2264 void MacroAssembler::DecrementCounter(Condition cc,
2265 StatsCounter* counter,
2268 if (FLAG_native_code_counters && counter->Enabled()) {
2270 j(NegateCondition(cc), &skip);
2272 DecrementCounter(counter, value);
2279 void MacroAssembler::Assert(Condition cc, const char* msg) {
2280 if (emit_debug_code()) Check(cc, msg);
2284 void MacroAssembler::AssertFastElements(Register elements) {
2285 if (emit_debug_code()) {
2286 Factory* factory = isolate()->factory();
2288 cmp(FieldOperand(elements, HeapObject::kMapOffset),
2289 Immediate(factory->fixed_array_map()));
2291 cmp(FieldOperand(elements, HeapObject::kMapOffset),
2292 Immediate(factory->fixed_double_array_map()));
2294 cmp(FieldOperand(elements, HeapObject::kMapOffset),
2295 Immediate(factory->fixed_cow_array_map()));
2297 Abort("JSObject with fast elements map has slow elements");
2303 void MacroAssembler::Check(Condition cc, const char* msg) {
2307 // will not return here
2312 void MacroAssembler::CheckStackAlignment() {
2313 int frame_alignment = OS::ActivationFrameAlignment();
2314 int frame_alignment_mask = frame_alignment - 1;
2315 if (frame_alignment > kPointerSize) {
2316 ASSERT(IsPowerOf2(frame_alignment));
2317 Label alignment_as_expected;
2318 test(esp, Immediate(frame_alignment_mask));
2319 j(zero, &alignment_as_expected);
2320 // Abort if stack is not aligned.
2322 bind(&alignment_as_expected);
2327 void MacroAssembler::Abort(const char* msg) {
2328 // We want to pass the msg string like a smi to avoid GC
2329 // problems, however msg is not guaranteed to be aligned
2330 // properly. Instead, we pass an aligned pointer that is
2331 // a proper v8 smi, but also pass the alignment difference
2332 // from the real pointer as a smi.
2333 intptr_t p1 = reinterpret_cast<intptr_t>(msg);
2334 intptr_t p0 = (p1 & ~kSmiTagMask) + kSmiTag;
2335 ASSERT(reinterpret_cast<Object*>(p0)->IsSmi());
2338 RecordComment("Abort message: ");
2344 push(Immediate(p0));
2345 push(Immediate(reinterpret_cast<intptr_t>(Smi::FromInt(p1 - p0))));
2346 // Disable stub call restrictions to always allow calls to abort.
2348 // We don't actually want to generate a pile of code for this, so just
2349 // claim there is a stack frame, without generating one.
2350 FrameScope scope(this, StackFrame::NONE);
2351 CallRuntime(Runtime::kAbort, 2);
2353 CallRuntime(Runtime::kAbort, 2);
2355 // will not return here
2360 void MacroAssembler::LoadInstanceDescriptors(Register map,
2361 Register descriptors) {
2363 FieldOperand(map, Map::kInstanceDescriptorsOrBitField3Offset));
2365 JumpIfNotSmi(descriptors, ¬_smi);
2366 mov(descriptors, isolate()->factory()->empty_descriptor_array());
2371 void MacroAssembler::LoadPowerOf2(XMMRegister dst,
2374 ASSERT(is_uintn(power + HeapNumber::kExponentBias,
2375 HeapNumber::kExponentBits));
2376 mov(scratch, Immediate(power + HeapNumber::kExponentBias));
2378 psllq(dst, HeapNumber::kMantissaBits);
2382 void MacroAssembler::JumpIfInstanceTypeIsNotSequentialAscii(
2383 Register instance_type,
2386 if (!scratch.is(instance_type)) {
2387 mov(scratch, instance_type);
2390 kIsNotStringMask | kStringRepresentationMask | kStringEncodingMask);
2391 cmp(scratch, kStringTag | kSeqStringTag | kAsciiStringTag);
2392 j(not_equal, failure);
2396 void MacroAssembler::JumpIfNotBothSequentialAsciiStrings(Register object1,
2401 // Check that both objects are not smis.
2402 STATIC_ASSERT(kSmiTag == 0);
2403 mov(scratch1, object1);
2404 and_(scratch1, object2);
2405 JumpIfSmi(scratch1, failure);
2407 // Load instance type for both strings.
2408 mov(scratch1, FieldOperand(object1, HeapObject::kMapOffset));
2409 mov(scratch2, FieldOperand(object2, HeapObject::kMapOffset));
2410 movzx_b(scratch1, FieldOperand(scratch1, Map::kInstanceTypeOffset));
2411 movzx_b(scratch2, FieldOperand(scratch2, Map::kInstanceTypeOffset));
2413 // Check that both are flat ascii strings.
2414 const int kFlatAsciiStringMask =
2415 kIsNotStringMask | kStringRepresentationMask | kStringEncodingMask;
2416 const int kFlatAsciiStringTag = ASCII_STRING_TYPE;
2417 // Interleave bits from both instance types and compare them in one check.
2418 ASSERT_EQ(0, kFlatAsciiStringMask & (kFlatAsciiStringMask << 3));
2419 and_(scratch1, kFlatAsciiStringMask);
2420 and_(scratch2, kFlatAsciiStringMask);
2421 lea(scratch1, Operand(scratch1, scratch2, times_8, 0));
2422 cmp(scratch1, kFlatAsciiStringTag | (kFlatAsciiStringTag << 3));
2423 j(not_equal, failure);
2427 void MacroAssembler::PrepareCallCFunction(int num_arguments, Register scratch) {
2428 int frame_alignment = OS::ActivationFrameAlignment();
2429 if (frame_alignment != 0) {
2430 // Make stack end at alignment and make room for num_arguments words
2431 // and the original value of esp.
2433 sub(esp, Immediate((num_arguments + 1) * kPointerSize));
2434 ASSERT(IsPowerOf2(frame_alignment));
2435 and_(esp, -frame_alignment);
2436 mov(Operand(esp, num_arguments * kPointerSize), scratch);
2438 sub(esp, Immediate(num_arguments * kPointerSize));
2443 void MacroAssembler::CallCFunction(ExternalReference function,
2444 int num_arguments) {
2445 // Trashing eax is ok as it will be the return value.
2446 mov(eax, Immediate(function));
2447 CallCFunction(eax, num_arguments);
2451 void MacroAssembler::CallCFunction(Register function,
2452 int num_arguments) {
2453 ASSERT(has_frame());
2454 // Check stack alignment.
2455 if (emit_debug_code()) {
2456 CheckStackAlignment();
2460 if (OS::ActivationFrameAlignment() != 0) {
2461 mov(esp, Operand(esp, num_arguments * kPointerSize));
2463 add(esp, Immediate(num_arguments * kPointerSize));
2468 bool AreAliased(Register r1, Register r2, Register r3, Register r4) {
2469 if (r1.is(r2)) return true;
2470 if (r1.is(r3)) return true;
2471 if (r1.is(r4)) return true;
2472 if (r2.is(r3)) return true;
2473 if (r2.is(r4)) return true;
2474 if (r3.is(r4)) return true;
2479 CodePatcher::CodePatcher(byte* address, int size)
2480 : address_(address),
2482 masm_(Isolate::Current(), address, size + Assembler::kGap) {
2483 // Create a new macro assembler pointing to the address of the code to patch.
2484 // The size is adjusted with kGap on order for the assembler to generate size
2485 // bytes of instructions without failing with buffer size constraints.
2486 ASSERT(masm_.reloc_info_writer.pos() == address_ + size_ + Assembler::kGap);
2490 CodePatcher::~CodePatcher() {
2491 // Indicate that code has changed.
2492 CPU::FlushICache(address_, size_);
2494 // Check that the code was patched as expected.
2495 ASSERT(masm_.pc_ == address_ + size_);
2496 ASSERT(masm_.reloc_info_writer.pos() == address_ + size_ + Assembler::kGap);
2500 void MacroAssembler::CheckPageFlag(
2505 Label* condition_met,
2506 Label::Distance condition_met_distance) {
2507 ASSERT(cc == zero || cc == not_zero);
2508 if (scratch.is(object)) {
2509 and_(scratch, Immediate(~Page::kPageAlignmentMask));
2511 mov(scratch, Immediate(~Page::kPageAlignmentMask));
2512 and_(scratch, object);
2514 if (mask < (1 << kBitsPerByte)) {
2515 test_b(Operand(scratch, MemoryChunk::kFlagsOffset),
2516 static_cast<uint8_t>(mask));
2518 test(Operand(scratch, MemoryChunk::kFlagsOffset), Immediate(mask));
2520 j(cc, condition_met, condition_met_distance);
2524 void MacroAssembler::JumpIfBlack(Register object,
2528 Label::Distance on_black_near) {
2529 HasColor(object, scratch0, scratch1,
2530 on_black, on_black_near,
2531 1, 0); // kBlackBitPattern.
2532 ASSERT(strcmp(Marking::kBlackBitPattern, "10") == 0);
2536 void MacroAssembler::HasColor(Register object,
2537 Register bitmap_scratch,
2538 Register mask_scratch,
2540 Label::Distance has_color_distance,
2543 ASSERT(!AreAliased(object, bitmap_scratch, mask_scratch, ecx));
2545 GetMarkBits(object, bitmap_scratch, mask_scratch);
2547 Label other_color, word_boundary;
2548 test(mask_scratch, Operand(bitmap_scratch, MemoryChunk::kHeaderSize));
2549 j(first_bit == 1 ? zero : not_zero, &other_color, Label::kNear);
2550 add(mask_scratch, mask_scratch); // Shift left 1 by adding.
2551 j(zero, &word_boundary, Label::kNear);
2552 test(mask_scratch, Operand(bitmap_scratch, MemoryChunk::kHeaderSize));
2553 j(second_bit == 1 ? not_zero : zero, has_color, has_color_distance);
2554 jmp(&other_color, Label::kNear);
2556 bind(&word_boundary);
2557 test_b(Operand(bitmap_scratch, MemoryChunk::kHeaderSize + kPointerSize), 1);
2559 j(second_bit == 1 ? not_zero : zero, has_color, has_color_distance);
2564 void MacroAssembler::GetMarkBits(Register addr_reg,
2565 Register bitmap_reg,
2566 Register mask_reg) {
2567 ASSERT(!AreAliased(addr_reg, mask_reg, bitmap_reg, ecx));
2568 mov(bitmap_reg, Immediate(~Page::kPageAlignmentMask));
2569 and_(bitmap_reg, addr_reg);
2572 Bitmap::kBitsPerCellLog2 + kPointerSizeLog2 - Bitmap::kBytesPerCellLog2;
2575 (Page::kPageAlignmentMask >> shift) & ~(Bitmap::kBytesPerCell - 1));
2577 add(bitmap_reg, ecx);
2579 shr(ecx, kPointerSizeLog2);
2580 and_(ecx, (1 << Bitmap::kBitsPerCellLog2) - 1);
2581 mov(mask_reg, Immediate(1));
2586 void MacroAssembler::EnsureNotWhite(
2588 Register bitmap_scratch,
2589 Register mask_scratch,
2590 Label* value_is_white_and_not_data,
2591 Label::Distance distance) {
2592 ASSERT(!AreAliased(value, bitmap_scratch, mask_scratch, ecx));
2593 GetMarkBits(value, bitmap_scratch, mask_scratch);
2595 // If the value is black or grey we don't need to do anything.
2596 ASSERT(strcmp(Marking::kWhiteBitPattern, "00") == 0);
2597 ASSERT(strcmp(Marking::kBlackBitPattern, "10") == 0);
2598 ASSERT(strcmp(Marking::kGreyBitPattern, "11") == 0);
2599 ASSERT(strcmp(Marking::kImpossibleBitPattern, "01") == 0);
2603 // Since both black and grey have a 1 in the first position and white does
2604 // not have a 1 there we only need to check one bit.
2605 test(mask_scratch, Operand(bitmap_scratch, MemoryChunk::kHeaderSize));
2606 j(not_zero, &done, Label::kNear);
2608 if (FLAG_debug_code) {
2609 // Check for impossible bit pattern.
2612 // shl. May overflow making the check conservative.
2613 add(mask_scratch, mask_scratch);
2614 test(mask_scratch, Operand(bitmap_scratch, MemoryChunk::kHeaderSize));
2615 j(zero, &ok, Label::kNear);
2621 // Value is white. We check whether it is data that doesn't need scanning.
2622 // Currently only checks for HeapNumber and non-cons strings.
2623 Register map = ecx; // Holds map while checking type.
2624 Register length = ecx; // Holds length of object after checking type.
2625 Label not_heap_number;
2626 Label is_data_object;
2628 // Check for heap-number
2629 mov(map, FieldOperand(value, HeapObject::kMapOffset));
2630 cmp(map, FACTORY->heap_number_map());
2631 j(not_equal, ¬_heap_number, Label::kNear);
2632 mov(length, Immediate(HeapNumber::kSize));
2633 jmp(&is_data_object, Label::kNear);
2635 bind(¬_heap_number);
2636 // Check for strings.
2637 ASSERT(kIsIndirectStringTag == 1 && kIsIndirectStringMask == 1);
2638 ASSERT(kNotStringTag == 0x80 && kIsNotStringMask == 0x80);
2639 // If it's a string and it's not a cons string then it's an object containing
2641 Register instance_type = ecx;
2642 movzx_b(instance_type, FieldOperand(map, Map::kInstanceTypeOffset));
2643 test_b(instance_type, kIsIndirectStringMask | kIsNotStringMask);
2644 j(not_zero, value_is_white_and_not_data);
2645 // It's a non-indirect (non-cons and non-slice) string.
2646 // If it's external, the length is just ExternalString::kSize.
2647 // Otherwise it's String::kHeaderSize + string->length() * (1 or 2).
2649 // External strings are the only ones with the kExternalStringTag bit
2651 ASSERT_EQ(0, kSeqStringTag & kExternalStringTag);
2652 ASSERT_EQ(0, kConsStringTag & kExternalStringTag);
2653 test_b(instance_type, kExternalStringTag);
2654 j(zero, ¬_external, Label::kNear);
2655 mov(length, Immediate(ExternalString::kSize));
2656 jmp(&is_data_object, Label::kNear);
2658 bind(¬_external);
2659 // Sequential string, either ASCII or UC16.
2660 ASSERT(kAsciiStringTag == 0x04);
2661 and_(length, Immediate(kStringEncodingMask));
2662 xor_(length, Immediate(kStringEncodingMask));
2663 add(length, Immediate(0x04));
2664 // Value now either 4 (if ASCII) or 8 (if UC16), i.e., char-size shifted
2665 // by 2. If we multiply the string length as smi by this, it still
2666 // won't overflow a 32-bit value.
2667 ASSERT_EQ(SeqAsciiString::kMaxSize, SeqTwoByteString::kMaxSize);
2668 ASSERT(SeqAsciiString::kMaxSize <=
2669 static_cast<int>(0xffffffffu >> (2 + kSmiTagSize)));
2670 imul(length, FieldOperand(value, String::kLengthOffset));
2671 shr(length, 2 + kSmiTagSize + kSmiShiftSize);
2672 add(length, Immediate(SeqString::kHeaderSize + kObjectAlignmentMask));
2673 and_(length, Immediate(~kObjectAlignmentMask));
2675 bind(&is_data_object);
2676 // Value is a data object, and it is white. Mark it black. Since we know
2677 // that the object is white we can make it black by flipping one bit.
2678 or_(Operand(bitmap_scratch, MemoryChunk::kHeaderSize), mask_scratch);
2680 and_(bitmap_scratch, Immediate(~Page::kPageAlignmentMask));
2681 add(Operand(bitmap_scratch, MemoryChunk::kLiveBytesOffset),
2683 if (FLAG_debug_code) {
2684 mov(length, Operand(bitmap_scratch, MemoryChunk::kLiveBytesOffset));
2685 cmp(length, Operand(bitmap_scratch, MemoryChunk::kSizeOffset));
2686 Check(less_equal, "Live Bytes Count overflow chunk size");
2692 } } // namespace v8::internal
2694 #endif // V8_TARGET_ARCH_IA32