blob: 0b3d72945f59c81024075b9829eed4e5be86128b [file] [log] [blame]
// Copyright 2014 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <assert.h> // For assert
#include <limits.h> // For LONG_MIN, LONG_MAX.
#include "src/v8.h"
#if V8_TARGET_ARCH_PPC
#include "src/base/bits.h"
#include "src/base/division-by-constant.h"
#include "src/bootstrapper.h"
#include "src/codegen.h"
#include "src/cpu-profiler.h"
#include "src/debug.h"
#include "src/isolate-inl.h"
#include "src/runtime/runtime.h"
namespace v8 {
namespace internal {
MacroAssembler::MacroAssembler(Isolate* arg_isolate, void* buffer, int size)
: Assembler(arg_isolate, buffer, size),
generating_stub_(false),
has_frame_(false) {
if (isolate() != NULL) {
code_object_ =
Handle<Object>(isolate()->heap()->undefined_value(), isolate());
}
}
void MacroAssembler::Jump(Register target) {
mtctr(target);
bctr();
}
void MacroAssembler::JumpToJSEntry(Register target) {
Move(ip, target);
Jump(ip);
}
void MacroAssembler::Jump(intptr_t target, RelocInfo::Mode rmode,
Condition cond, CRegister cr) {
Label skip;
if (cond != al) b(NegateCondition(cond), &skip, cr);
DCHECK(rmode == RelocInfo::CODE_TARGET || rmode == RelocInfo::RUNTIME_ENTRY);
mov(ip, Operand(target, rmode));
mtctr(ip);
bctr();
bind(&skip);
}
void MacroAssembler::Jump(Address target, RelocInfo::Mode rmode, Condition cond,
CRegister cr) {
DCHECK(!RelocInfo::IsCodeTarget(rmode));
Jump(reinterpret_cast<intptr_t>(target), rmode, cond, cr);
}
void MacroAssembler::Jump(Handle<Code> code, RelocInfo::Mode rmode,
Condition cond) {
DCHECK(RelocInfo::IsCodeTarget(rmode));
// 'code' is always generated ppc code, never THUMB code
AllowDeferredHandleDereference embedding_raw_address;
Jump(reinterpret_cast<intptr_t>(code.location()), rmode, cond);
}
int MacroAssembler::CallSize(Register target) { return 2 * kInstrSize; }
void MacroAssembler::Call(Register target) {
BlockTrampolinePoolScope block_trampoline_pool(this);
Label start;
bind(&start);
// Statement positions are expected to be recorded when the target
// address is loaded.
positions_recorder()->WriteRecordedPositions();
// branch via link register and set LK bit for return point
mtctr(target);
bctrl();
DCHECK_EQ(CallSize(target), SizeOfCodeGeneratedSince(&start));
}
void MacroAssembler::CallJSEntry(Register target) {
DCHECK(target.is(ip));
Call(target);
}
int MacroAssembler::CallSize(Address target, RelocInfo::Mode rmode,
Condition cond) {
Operand mov_operand = Operand(reinterpret_cast<intptr_t>(target), rmode);
return (2 + instructions_required_for_mov(mov_operand)) * kInstrSize;
}
int MacroAssembler::CallSizeNotPredictableCodeSize(Address target,
RelocInfo::Mode rmode,
Condition cond) {
return (2 + kMovInstructionsNoConstantPool) * kInstrSize;
}
void MacroAssembler::Call(Address target, RelocInfo::Mode rmode,
Condition cond) {
BlockTrampolinePoolScope block_trampoline_pool(this);
DCHECK(cond == al);
#ifdef DEBUG
// Check the expected size before generating code to ensure we assume the same
// constant pool availability (e.g., whether constant pool is full or not).
int expected_size = CallSize(target, rmode, cond);
Label start;
bind(&start);
#endif
// Statement positions are expected to be recorded when the target
// address is loaded.
positions_recorder()->WriteRecordedPositions();
// This can likely be optimized to make use of bc() with 24bit relative
//
// RecordRelocInfo(x.rmode_, x.imm_);
// bc( BA, .... offset, LKset);
//
mov(ip, Operand(reinterpret_cast<intptr_t>(target), rmode));
mtctr(ip);
bctrl();
DCHECK_EQ(expected_size, SizeOfCodeGeneratedSince(&start));
}
int MacroAssembler::CallSize(Handle<Code> code, RelocInfo::Mode rmode,
TypeFeedbackId ast_id, Condition cond) {
AllowDeferredHandleDereference using_raw_address;
return CallSize(reinterpret_cast<Address>(code.location()), rmode, cond);
}
void MacroAssembler::Call(Handle<Code> code, RelocInfo::Mode rmode,
TypeFeedbackId ast_id, Condition cond) {
BlockTrampolinePoolScope block_trampoline_pool(this);
DCHECK(RelocInfo::IsCodeTarget(rmode));
#ifdef DEBUG
// Check the expected size before generating code to ensure we assume the same
// constant pool availability (e.g., whether constant pool is full or not).
int expected_size = CallSize(code, rmode, ast_id, cond);
Label start;
bind(&start);
#endif
if (rmode == RelocInfo::CODE_TARGET && !ast_id.IsNone()) {
SetRecordedAstId(ast_id);
rmode = RelocInfo::CODE_TARGET_WITH_ID;
}
AllowDeferredHandleDereference using_raw_address;
Call(reinterpret_cast<Address>(code.location()), rmode, cond);
DCHECK_EQ(expected_size, SizeOfCodeGeneratedSince(&start));
}
void MacroAssembler::Ret(Condition cond) {
DCHECK(cond == al);
blr();
}
void MacroAssembler::Drop(int count, Condition cond) {
DCHECK(cond == al);
if (count > 0) {
Add(sp, sp, count * kPointerSize, r0);
}
}
void MacroAssembler::Ret(int drop, Condition cond) {
Drop(drop, cond);
Ret(cond);
}
void MacroAssembler::Call(Label* target) { b(target, SetLK); }
void MacroAssembler::Push(Handle<Object> handle) {
mov(r0, Operand(handle));
push(r0);
}
void MacroAssembler::Move(Register dst, Handle<Object> value) {
AllowDeferredHandleDereference smi_check;
if (value->IsSmi()) {
LoadSmiLiteral(dst, reinterpret_cast<Smi*>(*value));
} else {
DCHECK(value->IsHeapObject());
if (isolate()->heap()->InNewSpace(*value)) {
Handle<Cell> cell = isolate()->factory()->NewCell(value);
mov(dst, Operand(cell));
LoadP(dst, FieldMemOperand(dst, Cell::kValueOffset));
} else {
mov(dst, Operand(value));
}
}
}
void MacroAssembler::Move(Register dst, Register src, Condition cond) {
DCHECK(cond == al);
if (!dst.is(src)) {
mr(dst, src);
}
}
void MacroAssembler::Move(DoubleRegister dst, DoubleRegister src) {
if (!dst.is(src)) {
fmr(dst, src);
}
}
void MacroAssembler::MultiPush(RegList regs) {
int16_t num_to_push = NumberOfBitsSet(regs);
int16_t stack_offset = num_to_push * kPointerSize;
subi(sp, sp, Operand(stack_offset));
for (int16_t i = kNumRegisters - 1; i >= 0; i--) {
if ((regs & (1 << i)) != 0) {
stack_offset -= kPointerSize;
StoreP(ToRegister(i), MemOperand(sp, stack_offset));
}
}
}
void MacroAssembler::MultiPop(RegList regs) {
int16_t stack_offset = 0;
for (int16_t i = 0; i < kNumRegisters; i++) {
if ((regs & (1 << i)) != 0) {
LoadP(ToRegister(i), MemOperand(sp, stack_offset));
stack_offset += kPointerSize;
}
}
addi(sp, sp, Operand(stack_offset));
}
void MacroAssembler::LoadRoot(Register destination, Heap::RootListIndex index,
Condition cond) {
DCHECK(cond == al);
LoadP(destination, MemOperand(kRootRegister, index << kPointerSizeLog2), r0);
}
void MacroAssembler::StoreRoot(Register source, Heap::RootListIndex index,
Condition cond) {
DCHECK(cond == al);
StoreP(source, MemOperand(kRootRegister, index << kPointerSizeLog2), r0);
}
void MacroAssembler::InNewSpace(Register object, Register scratch,
Condition cond, Label* branch) {
// N.B. scratch may be same register as object
DCHECK(cond == eq || cond == ne);
mov(r0, Operand(ExternalReference::new_space_mask(isolate())));
and_(scratch, object, r0);
mov(r0, Operand(ExternalReference::new_space_start(isolate())));
cmp(scratch, r0);
b(cond, branch);
}
void MacroAssembler::RecordWriteField(
Register object, int offset, Register value, Register dst,
LinkRegisterStatus lr_status, SaveFPRegsMode save_fp,
RememberedSetAction remembered_set_action, SmiCheck smi_check,
PointersToHereCheck pointers_to_here_check_for_value) {
// First, check if a write barrier is even needed. The tests below
// catch stores of Smis.
Label done;
// Skip barrier if writing a smi.
if (smi_check == INLINE_SMI_CHECK) {
JumpIfSmi(value, &done);
}
// Although the object register is tagged, the offset is relative to the start
// of the object, so so offset must be a multiple of kPointerSize.
DCHECK(IsAligned(offset, kPointerSize));
Add(dst, object, offset - kHeapObjectTag, r0);
if (emit_debug_code()) {
Label ok;
andi(r0, dst, Operand((1 << kPointerSizeLog2) - 1));
beq(&ok, cr0);
stop("Unaligned cell in write barrier");
bind(&ok);
}
RecordWrite(object, dst, value, lr_status, save_fp, remembered_set_action,
OMIT_SMI_CHECK, pointers_to_here_check_for_value);
bind(&done);
// Clobber clobbered input registers when running with the debug-code flag
// turned on to provoke errors.
if (emit_debug_code()) {
mov(value, Operand(bit_cast<intptr_t>(kZapValue + 4)));
mov(dst, Operand(bit_cast<intptr_t>(kZapValue + 8)));
}
}
// Will clobber 4 registers: object, map, dst, ip. The
// register 'object' contains a heap object pointer.
void MacroAssembler::RecordWriteForMap(Register object, Register map,
Register dst,
LinkRegisterStatus lr_status,
SaveFPRegsMode fp_mode) {
if (emit_debug_code()) {
LoadP(dst, FieldMemOperand(map, HeapObject::kMapOffset));
Cmpi(dst, Operand(isolate()->factory()->meta_map()), r0);
Check(eq, kWrongAddressOrValuePassedToRecordWrite);
}
if (!FLAG_incremental_marking) {
return;
}
if (emit_debug_code()) {
LoadP(ip, FieldMemOperand(object, HeapObject::kMapOffset));
cmp(ip, map);
Check(eq, kWrongAddressOrValuePassedToRecordWrite);
}
Label done;
// A single check of the map's pages interesting flag suffices, since it is
// only set during incremental collection, and then it's also guaranteed that
// the from object's page's interesting flag is also set. This optimization
// relies on the fact that maps can never be in new space.
CheckPageFlag(map,
map, // Used as scratch.
MemoryChunk::kPointersToHereAreInterestingMask, eq, &done);
addi(dst, object, Operand(HeapObject::kMapOffset - kHeapObjectTag));
if (emit_debug_code()) {
Label ok;
andi(r0, dst, Operand((1 << kPointerSizeLog2) - 1));
beq(&ok, cr0);
stop("Unaligned cell in write barrier");
bind(&ok);
}
// Record the actual write.
if (lr_status == kLRHasNotBeenSaved) {
mflr(r0);
push(r0);
}
RecordWriteStub stub(isolate(), object, map, dst, OMIT_REMEMBERED_SET,
fp_mode);
CallStub(&stub);
if (lr_status == kLRHasNotBeenSaved) {
pop(r0);
mtlr(r0);
}
bind(&done);
// Count number of write barriers in generated code.
isolate()->counters()->write_barriers_static()->Increment();
IncrementCounter(isolate()->counters()->write_barriers_dynamic(), 1, ip, dst);
// Clobber clobbered registers when running with the debug-code flag
// turned on to provoke errors.
if (emit_debug_code()) {
mov(dst, Operand(bit_cast<intptr_t>(kZapValue + 12)));
mov(map, Operand(bit_cast<intptr_t>(kZapValue + 16)));
}
}
// Will clobber 4 registers: object, address, scratch, ip. The
// register 'object' contains a heap object pointer. The heap object
// tag is shifted away.
void MacroAssembler::RecordWrite(
Register object, Register address, Register value,
LinkRegisterStatus lr_status, SaveFPRegsMode fp_mode,
RememberedSetAction remembered_set_action, SmiCheck smi_check,
PointersToHereCheck pointers_to_here_check_for_value) {
DCHECK(!object.is(value));
if (emit_debug_code()) {
LoadP(r0, MemOperand(address));
cmp(r0, value);
Check(eq, kWrongAddressOrValuePassedToRecordWrite);
}
if (remembered_set_action == OMIT_REMEMBERED_SET &&
!FLAG_incremental_marking) {
return;
}
// First, check if a write barrier is even needed. The tests below
// catch stores of smis and stores into the young generation.
Label done;
if (smi_check == INLINE_SMI_CHECK) {
JumpIfSmi(value, &done);
}
if (pointers_to_here_check_for_value != kPointersToHereAreAlwaysInteresting) {
CheckPageFlag(value,
value, // Used as scratch.
MemoryChunk::kPointersToHereAreInterestingMask, eq, &done);
}
CheckPageFlag(object,
value, // Used as scratch.
MemoryChunk::kPointersFromHereAreInterestingMask, eq, &done);
// Record the actual write.
if (lr_status == kLRHasNotBeenSaved) {
mflr(r0);
push(r0);
}
RecordWriteStub stub(isolate(), object, value, address, remembered_set_action,
fp_mode);
CallStub(&stub);
if (lr_status == kLRHasNotBeenSaved) {
pop(r0);
mtlr(r0);
}
bind(&done);
// Count number of write barriers in generated code.
isolate()->counters()->write_barriers_static()->Increment();
IncrementCounter(isolate()->counters()->write_barriers_dynamic(), 1, ip,
value);
// Clobber clobbered registers when running with the debug-code flag
// turned on to provoke errors.
if (emit_debug_code()) {
mov(address, Operand(bit_cast<intptr_t>(kZapValue + 12)));
mov(value, Operand(bit_cast<intptr_t>(kZapValue + 16)));
}
}
void MacroAssembler::RememberedSetHelper(Register object, // For debug tests.
Register address, Register scratch,
SaveFPRegsMode fp_mode,
RememberedSetFinalAction and_then) {
Label done;
if (emit_debug_code()) {
Label ok;
JumpIfNotInNewSpace(object, scratch, &ok);
stop("Remembered set pointer is in new space");
bind(&ok);
}
// Load store buffer top.
ExternalReference store_buffer =
ExternalReference::store_buffer_top(isolate());
mov(ip, Operand(store_buffer));
LoadP(scratch, MemOperand(ip));
// Store pointer to buffer and increment buffer top.
StoreP(address, MemOperand(scratch));
addi(scratch, scratch, Operand(kPointerSize));
// Write back new top of buffer.
StoreP(scratch, MemOperand(ip));
// Call stub on end of buffer.
// Check for end of buffer.
mov(r0, Operand(StoreBuffer::kStoreBufferOverflowBit));
and_(r0, scratch, r0, SetRC);
if (and_then == kFallThroughAtEnd) {
beq(&done, cr0);
} else {
DCHECK(and_then == kReturnAtEnd);
beq(&done, cr0);
}
mflr(r0);
push(r0);
StoreBufferOverflowStub store_buffer_overflow(isolate(), fp_mode);
CallStub(&store_buffer_overflow);
pop(r0);
mtlr(r0);
bind(&done);
if (and_then == kReturnAtEnd) {
Ret();
}
}
void MacroAssembler::PushFixedFrame(Register marker_reg) {
mflr(r0);
#if V8_OOL_CONSTANT_POOL
if (marker_reg.is_valid()) {
Push(r0, fp, kConstantPoolRegister, cp, marker_reg);
} else {
Push(r0, fp, kConstantPoolRegister, cp);
}
#else
if (marker_reg.is_valid()) {
Push(r0, fp, cp, marker_reg);
} else {
Push(r0, fp, cp);
}
#endif
}
void MacroAssembler::PopFixedFrame(Register marker_reg) {
#if V8_OOL_CONSTANT_POOL
if (marker_reg.is_valid()) {
Pop(r0, fp, kConstantPoolRegister, cp, marker_reg);
} else {
Pop(r0, fp, kConstantPoolRegister, cp);
}
#else
if (marker_reg.is_valid()) {
Pop(r0, fp, cp, marker_reg);
} else {
Pop(r0, fp, cp);
}
#endif
mtlr(r0);
}
// Push and pop all registers that can hold pointers.
void MacroAssembler::PushSafepointRegisters() {
// Safepoints expect a block of kNumSafepointRegisters values on the
// stack, so adjust the stack for unsaved registers.
const int num_unsaved = kNumSafepointRegisters - kNumSafepointSavedRegisters;
DCHECK(num_unsaved >= 0);
if (num_unsaved > 0) {
subi(sp, sp, Operand(num_unsaved * kPointerSize));
}
MultiPush(kSafepointSavedRegisters);
}
void MacroAssembler::PopSafepointRegisters() {
const int num_unsaved = kNumSafepointRegisters - kNumSafepointSavedRegisters;
MultiPop(kSafepointSavedRegisters);
if (num_unsaved > 0) {
addi(sp, sp, Operand(num_unsaved * kPointerSize));
}
}
void MacroAssembler::StoreToSafepointRegisterSlot(Register src, Register dst) {
StoreP(src, SafepointRegisterSlot(dst));
}
void MacroAssembler::LoadFromSafepointRegisterSlot(Register dst, Register src) {
LoadP(dst, SafepointRegisterSlot(src));
}
int MacroAssembler::SafepointRegisterStackIndex(int reg_code) {
// The registers are pushed starting with the highest encoding,
// which means that lowest encodings are closest to the stack pointer.
RegList regs = kSafepointSavedRegisters;
int index = 0;
DCHECK(reg_code >= 0 && reg_code < kNumRegisters);
for (int16_t i = 0; i < reg_code; i++) {
if ((regs & (1 << i)) != 0) {
index++;
}
}
return index;
}
MemOperand MacroAssembler::SafepointRegisterSlot(Register reg) {
return MemOperand(sp, SafepointRegisterStackIndex(reg.code()) * kPointerSize);
}
MemOperand MacroAssembler::SafepointRegistersAndDoublesSlot(Register reg) {
// General purpose registers are pushed last on the stack.
int doubles_size = DoubleRegister::NumAllocatableRegisters() * kDoubleSize;
int register_offset = SafepointRegisterStackIndex(reg.code()) * kPointerSize;
return MemOperand(sp, doubles_size + register_offset);
}
void MacroAssembler::CanonicalizeNaN(const DoubleRegister dst,
const DoubleRegister src) {
Label done;
// Test for NaN
fcmpu(src, src);
if (dst.is(src)) {
bordered(&done);
} else {
Label is_nan;
bunordered(&is_nan);
fmr(dst, src);
b(&done);
bind(&is_nan);
}
// Replace with canonical NaN.
double nan_value = FixedDoubleArray::canonical_not_the_hole_nan_as_double();
LoadDoubleLiteral(dst, nan_value, r0);
bind(&done);
}
void MacroAssembler::ConvertIntToDouble(Register src,
DoubleRegister double_dst) {
MovIntToDouble(double_dst, src, r0);
fcfid(double_dst, double_dst);
}
void MacroAssembler::ConvertUnsignedIntToDouble(Register src,
DoubleRegister double_dst) {
MovUnsignedIntToDouble(double_dst, src, r0);
fcfid(double_dst, double_dst);
}
void MacroAssembler::ConvertIntToFloat(const DoubleRegister dst,
const Register src,
const Register int_scratch) {
MovIntToDouble(dst, src, int_scratch);
fcfid(dst, dst);
frsp(dst, dst);
}
void MacroAssembler::ConvertDoubleToInt64(const DoubleRegister double_input,
#if !V8_TARGET_ARCH_PPC64
const Register dst_hi,
#endif
const Register dst,
const DoubleRegister double_dst,
FPRoundingMode rounding_mode) {
if (rounding_mode == kRoundToZero) {
fctidz(double_dst, double_input);
} else {
SetRoundingMode(rounding_mode);
fctid(double_dst, double_input);
ResetRoundingMode();
}
MovDoubleToInt64(
#if !V8_TARGET_ARCH_PPC64
dst_hi,
#endif
dst, double_dst);
}
#if V8_OOL_CONSTANT_POOL
void MacroAssembler::LoadConstantPoolPointerRegister(
CodeObjectAccessMethod access_method, int ip_code_entry_delta) {
Register base;
int constant_pool_offset = Code::kConstantPoolOffset - Code::kHeaderSize;
if (access_method == CAN_USE_IP) {
base = ip;
constant_pool_offset += ip_code_entry_delta;
} else {
DCHECK(access_method == CONSTRUCT_INTERNAL_REFERENCE);
base = kConstantPoolRegister;
ConstantPoolUnavailableScope constant_pool_unavailable(this);
// CheckBuffer() is called too frequently. This will pre-grow
// the buffer if needed to avoid spliting the relocation and instructions
EnsureSpaceFor(kMovInstructionsNoConstantPool * kInstrSize);
uintptr_t code_start = reinterpret_cast<uintptr_t>(pc_) - pc_offset();
mov(base, Operand(code_start, RelocInfo::INTERNAL_REFERENCE));
}
LoadP(kConstantPoolRegister, MemOperand(base, constant_pool_offset));
}
#endif
void MacroAssembler::StubPrologue(int prologue_offset) {
LoadSmiLiteral(r11, Smi::FromInt(StackFrame::STUB));
PushFixedFrame(r11);
// Adjust FP to point to saved FP.
addi(fp, sp, Operand(StandardFrameConstants::kFixedFrameSizeFromFp));
#if V8_OOL_CONSTANT_POOL
// ip contains prologue address
LoadConstantPoolPointerRegister(CAN_USE_IP, -prologue_offset);
set_ool_constant_pool_available(true);
#endif
}
void MacroAssembler::Prologue(bool code_pre_aging, int prologue_offset) {
{
PredictableCodeSizeScope predictible_code_size_scope(
this, kNoCodeAgeSequenceLength);
Assembler::BlockTrampolinePoolScope block_trampoline_pool(this);
// The following instructions must remain together and unmodified
// for code aging to work properly.
if (code_pre_aging) {
// Pre-age the code.
// This matches the code found in PatchPlatformCodeAge()
Code* stub = Code::GetPreAgedCodeAgeStub(isolate());
intptr_t target = reinterpret_cast<intptr_t>(stub->instruction_start());
// Don't use Call -- we need to preserve ip and lr
nop(); // marker to detect sequence (see IsOld)
mov(r3, Operand(target));
Jump(r3);
for (int i = 0; i < kCodeAgingSequenceNops; i++) {
nop();
}
} else {
// This matches the code found in GetNoCodeAgeSequence()
PushFixedFrame(r4);
// Adjust fp to point to saved fp.
addi(fp, sp, Operand(StandardFrameConstants::kFixedFrameSizeFromFp));
for (int i = 0; i < kNoCodeAgeSequenceNops; i++) {
nop();
}
}
}
#if V8_OOL_CONSTANT_POOL
// ip contains prologue address
LoadConstantPoolPointerRegister(CAN_USE_IP, -prologue_offset);
set_ool_constant_pool_available(true);
#endif
}
void MacroAssembler::EnterFrame(StackFrame::Type type,
bool load_constant_pool_pointer_reg) {
if (FLAG_enable_ool_constant_pool && load_constant_pool_pointer_reg) {
PushFixedFrame();
#if V8_OOL_CONSTANT_POOL
// This path should not rely on ip containing code entry.
LoadConstantPoolPointerRegister(CONSTRUCT_INTERNAL_REFERENCE);
#endif
LoadSmiLiteral(ip, Smi::FromInt(type));
push(ip);
} else {
LoadSmiLiteral(ip, Smi::FromInt(type));
PushFixedFrame(ip);
}
// Adjust FP to point to saved FP.
addi(fp, sp, Operand(StandardFrameConstants::kFixedFrameSizeFromFp));
mov(r0, Operand(CodeObject()));
push(r0);
}
int MacroAssembler::LeaveFrame(StackFrame::Type type, int stack_adjustment) {
#if V8_OOL_CONSTANT_POOL
ConstantPoolUnavailableScope constant_pool_unavailable(this);
#endif
// r3: preserved
// r4: preserved
// r5: preserved
// Drop the execution stack down to the frame pointer and restore
// the caller frame pointer, return address and constant pool pointer.
int frame_ends;
LoadP(r0, MemOperand(fp, StandardFrameConstants::kCallerPCOffset));
LoadP(ip, MemOperand(fp, StandardFrameConstants::kCallerFPOffset));
#if V8_OOL_CONSTANT_POOL
const int exitOffset = ExitFrameConstants::kConstantPoolOffset;
const int standardOffset = StandardFrameConstants::kConstantPoolOffset;
const int offset = ((type == StackFrame::EXIT) ? exitOffset : standardOffset);
LoadP(kConstantPoolRegister, MemOperand(fp, offset));
#endif
mtlr(r0);
frame_ends = pc_offset();
Add(sp, fp, StandardFrameConstants::kCallerSPOffset + stack_adjustment, r0);
mr(fp, ip);
return frame_ends;
}
// ExitFrame layout (probably wrongish.. needs updating)
//
// SP -> previousSP
// LK reserved
// code
// sp_on_exit (for debug?)
// oldSP->prev SP
// LK
// <parameters on stack>
// Prior to calling EnterExitFrame, we've got a bunch of parameters
// on the stack that we need to wrap a real frame around.. so first
// we reserve a slot for LK and push the previous SP which is captured
// in the fp register (r31)
// Then - we buy a new frame
void MacroAssembler::EnterExitFrame(bool save_doubles, int stack_space) {
// Set up the frame structure on the stack.
DCHECK_EQ(2 * kPointerSize, ExitFrameConstants::kCallerSPDisplacement);
DCHECK_EQ(1 * kPointerSize, ExitFrameConstants::kCallerPCOffset);
DCHECK_EQ(0 * kPointerSize, ExitFrameConstants::kCallerFPOffset);
DCHECK(stack_space > 0);
// This is an opportunity to build a frame to wrap
// all of the pushes that have happened inside of V8
// since we were called from C code
// replicate ARM frame - TODO make this more closely follow PPC ABI
mflr(r0);
Push(r0, fp);
mr(fp, sp);
// Reserve room for saved entry sp and code object.
subi(sp, sp, Operand(ExitFrameConstants::kFrameSize));
if (emit_debug_code()) {
li(r8, Operand::Zero());
StoreP(r8, MemOperand(fp, ExitFrameConstants::kSPOffset));
}
#if V8_OOL_CONSTANT_POOL
StoreP(kConstantPoolRegister,
MemOperand(fp, ExitFrameConstants::kConstantPoolOffset));
#endif
mov(r8, Operand(CodeObject()));
StoreP(r8, MemOperand(fp, ExitFrameConstants::kCodeOffset));
// Save the frame pointer and the context in top.
mov(r8, Operand(ExternalReference(Isolate::kCEntryFPAddress, isolate())));
StoreP(fp, MemOperand(r8));
mov(r8, Operand(ExternalReference(Isolate::kContextAddress, isolate())));
StoreP(cp, MemOperand(r8));
// Optionally save all volatile double registers.
if (save_doubles) {
SaveFPRegs(sp, 0, DoubleRegister::kNumVolatileRegisters);
// Note that d0 will be accessible at
// fp - ExitFrameConstants::kFrameSize -
// kNumVolatileRegisters * kDoubleSize,
// since the sp slot and code slot were pushed after the fp.
}
addi(sp, sp, Operand(-stack_space * kPointerSize));
// Allocate and align the frame preparing for calling the runtime
// function.
const int frame_alignment = ActivationFrameAlignment();
if (frame_alignment > kPointerSize) {
DCHECK(base::bits::IsPowerOfTwo32(frame_alignment));
ClearRightImm(sp, sp, Operand(WhichPowerOf2(frame_alignment)));
}
li(r0, Operand::Zero());
StorePU(r0, MemOperand(sp, -kNumRequiredStackFrameSlots * kPointerSize));
// Set the exit frame sp value to point just before the return address
// location.
addi(r8, sp, Operand((kStackFrameExtraParamSlot + 1) * kPointerSize));
StoreP(r8, MemOperand(fp, ExitFrameConstants::kSPOffset));
}
void MacroAssembler::InitializeNewString(Register string, Register length,
Heap::RootListIndex map_index,
Register scratch1, Register scratch2) {
SmiTag(scratch1, length);
LoadRoot(scratch2, map_index);
StoreP(scratch1, FieldMemOperand(string, String::kLengthOffset), r0);
li(scratch1, Operand(String::kEmptyHashField));
StoreP(scratch2, FieldMemOperand(string, HeapObject::kMapOffset), r0);
StoreP(scratch1, FieldMemOperand(string, String::kHashFieldSlot), r0);
}
int MacroAssembler::ActivationFrameAlignment() {
#if !defined(USE_SIMULATOR)
// Running on the real platform. Use the alignment as mandated by the local
// environment.
// Note: This will break if we ever start generating snapshots on one PPC
// platform for another PPC platform with a different alignment.
return base::OS::ActivationFrameAlignment();
#else // Simulated
// If we are using the simulator then we should always align to the expected
// alignment. As the simulator is used to generate snapshots we do not know
// if the target platform will need alignment, so this is controlled from a
// flag.
return FLAG_sim_stack_alignment;
#endif
}
void MacroAssembler::LeaveExitFrame(bool save_doubles, Register argument_count,
bool restore_context) {
#if V8_OOL_CONSTANT_POOL
ConstantPoolUnavailableScope constant_pool_unavailable(this);
#endif
// Optionally restore all double registers.
if (save_doubles) {
// Calculate the stack location of the saved doubles and restore them.
const int kNumRegs = DoubleRegister::kNumVolatileRegisters;
const int offset =
(ExitFrameConstants::kFrameSize + kNumRegs * kDoubleSize);
addi(r6, fp, Operand(-offset));
RestoreFPRegs(r6, 0, kNumRegs);
}
// Clear top frame.
li(r6, Operand::Zero());
mov(ip, Operand(ExternalReference(Isolate::kCEntryFPAddress, isolate())));
StoreP(r6, MemOperand(ip));
// Restore current context from top and clear it in debug mode.
if (restore_context) {
mov(ip, Operand(ExternalReference(Isolate::kContextAddress, isolate())));
LoadP(cp, MemOperand(ip));
}
#ifdef DEBUG
mov(ip, Operand(ExternalReference(Isolate::kContextAddress, isolate())));
StoreP(r6, MemOperand(ip));
#endif
// Tear down the exit frame, pop the arguments, and return.
LeaveFrame(StackFrame::EXIT);
if (argument_count.is_valid()) {
ShiftLeftImm(argument_count, argument_count, Operand(kPointerSizeLog2));
add(sp, sp, argument_count);
}
}
void MacroAssembler::MovFromFloatResult(const DoubleRegister dst) {
Move(dst, d1);
}
void MacroAssembler::MovFromFloatParameter(const DoubleRegister dst) {
Move(dst, d1);
}
void MacroAssembler::InvokePrologue(const ParameterCount& expected,
const ParameterCount& actual,
Handle<Code> code_constant,
Register code_reg, Label* done,
bool* definitely_mismatches,
InvokeFlag flag,
const CallWrapper& call_wrapper) {
bool definitely_matches = false;
*definitely_mismatches = false;
Label regular_invoke;
// Check whether the expected and actual arguments count match. If not,
// setup registers according to contract with ArgumentsAdaptorTrampoline:
// r3: actual arguments count
// r4: function (passed through to callee)
// r5: expected arguments count
// The code below is made a lot easier because the calling code already sets
// up actual and expected registers according to the contract if values are
// passed in registers.
// ARM has some sanity checks as per below, considering add them for PPC
// DCHECK(actual.is_immediate() || actual.reg().is(r3));
// DCHECK(expected.is_immediate() || expected.reg().is(r5));
// DCHECK((!code_constant.is_null() && code_reg.is(no_reg))
// || code_reg.is(r6));
if (expected.is_immediate()) {
DCHECK(actual.is_immediate());
if (expected.immediate() == actual.immediate()) {
definitely_matches = true;
} else {
mov(r3, Operand(actual.immediate()));
const int sentinel = SharedFunctionInfo::kDontAdaptArgumentsSentinel;
if (expected.immediate() == sentinel) {
// Don't worry about adapting arguments for builtins that
// don't want that done. Skip adaption code by making it look
// like we have a match between expected and actual number of
// arguments.
definitely_matches = true;
} else {
*definitely_mismatches = true;
mov(r5, Operand(expected.immediate()));
}
}
} else {
if (actual.is_immediate()) {
cmpi(expected.reg(), Operand(actual.immediate()));
beq(&regular_invoke);
mov(r3, Operand(actual.immediate()));
} else {
cmp(expected.reg(), actual.reg());
beq(&regular_invoke);
}
}
if (!definitely_matches) {
if (!code_constant.is_null()) {
mov(r6, Operand(code_constant));
addi(r6, r6, Operand(Code::kHeaderSize - kHeapObjectTag));
}
Handle<Code> adaptor = isolate()->builtins()->ArgumentsAdaptorTrampoline();
if (flag == CALL_FUNCTION) {
call_wrapper.BeforeCall(CallSize(adaptor));
Call(adaptor);
call_wrapper.AfterCall();
if (!*definitely_mismatches) {
b(done);
}
} else {
Jump(adaptor, RelocInfo::CODE_TARGET);
}
bind(&regular_invoke);
}
}
void MacroAssembler::InvokeCode(Register code, const ParameterCount& expected,
const ParameterCount& actual, InvokeFlag flag,
const CallWrapper& call_wrapper) {
// You can't call a function without a valid frame.
DCHECK(flag == JUMP_FUNCTION || has_frame());
Label done;
bool definitely_mismatches = false;
InvokePrologue(expected, actual, Handle<Code>::null(), code, &done,
&definitely_mismatches, flag, call_wrapper);
if (!definitely_mismatches) {
if (flag == CALL_FUNCTION) {
call_wrapper.BeforeCall(CallSize(code));
CallJSEntry(code);
call_wrapper.AfterCall();
} else {
DCHECK(flag == JUMP_FUNCTION);
JumpToJSEntry(code);
}
// Continue here if InvokePrologue does handle the invocation due to
// mismatched parameter counts.
bind(&done);
}
}
void MacroAssembler::InvokeFunction(Register fun, const ParameterCount& actual,
InvokeFlag flag,
const CallWrapper& call_wrapper) {
// You can't call a function without a valid frame.
DCHECK(flag == JUMP_FUNCTION || has_frame());
// Contract with called JS functions requires that function is passed in r4.
DCHECK(fun.is(r4));
Register expected_reg = r5;
Register code_reg = ip;
LoadP(code_reg, FieldMemOperand(r4, JSFunction::kSharedFunctionInfoOffset));
LoadP(cp, FieldMemOperand(r4, JSFunction::kContextOffset));
LoadWordArith(expected_reg,
FieldMemOperand(
code_reg, SharedFunctionInfo::kFormalParameterCountOffset));
#if !defined(V8_TARGET_ARCH_PPC64)
SmiUntag(expected_reg);
#endif
LoadP(code_reg, FieldMemOperand(r4, JSFunction::kCodeEntryOffset));
ParameterCount expected(expected_reg);
InvokeCode(code_reg, expected, actual, flag, call_wrapper);
}
void MacroAssembler::InvokeFunction(Register function,
const ParameterCount& expected,
const ParameterCount& actual,
InvokeFlag flag,
const CallWrapper& call_wrapper) {
// You can't call a function without a valid frame.
DCHECK(flag == JUMP_FUNCTION || has_frame());
// Contract with called JS functions requires that function is passed in r4.
DCHECK(function.is(r4));
// Get the function and setup the context.
LoadP(cp, FieldMemOperand(r4, JSFunction::kContextOffset));
// We call indirectly through the code field in the function to
// allow recompilation to take effect without changing any of the
// call sites.
LoadP(ip, FieldMemOperand(r4, JSFunction::kCodeEntryOffset));
InvokeCode(ip, expected, actual, flag, call_wrapper);
}
void MacroAssembler::InvokeFunction(Handle<JSFunction> function,
const ParameterCount& expected,
const ParameterCount& actual,
InvokeFlag flag,
const CallWrapper& call_wrapper) {
Move(r4, function);
InvokeFunction(r4, expected, actual, flag, call_wrapper);
}
void MacroAssembler::IsObjectJSObjectType(Register heap_object, Register map,
Register scratch, Label* fail) {
LoadP(map, FieldMemOperand(heap_object, HeapObject::kMapOffset));
IsInstanceJSObjectType(map, scratch, fail);
}
void MacroAssembler::IsInstanceJSObjectType(Register map, Register scratch,
Label* fail) {
lbz(scratch, FieldMemOperand(map, Map::kInstanceTypeOffset));
cmpi(scratch, Operand(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE));
blt(fail);
cmpi(scratch, Operand(LAST_NONCALLABLE_SPEC_OBJECT_TYPE));
bgt(fail);
}
void MacroAssembler::IsObjectJSStringType(Register object, Register scratch,
Label* fail) {
DCHECK(kNotStringTag != 0);
LoadP(scratch, FieldMemOperand(object, HeapObject::kMapOffset));
lbz(scratch, FieldMemOperand(scratch, Map::kInstanceTypeOffset));
andi(r0, scratch, Operand(kIsNotStringMask));
bne(fail, cr0);
}
void MacroAssembler::IsObjectNameType(Register object, Register scratch,
Label* fail) {
LoadP(scratch, FieldMemOperand(object, HeapObject::kMapOffset));
lbz(scratch, FieldMemOperand(scratch, Map::kInstanceTypeOffset));
cmpi(scratch, Operand(LAST_NAME_TYPE));
bgt(fail);
}
void MacroAssembler::DebugBreak() {
li(r3, Operand::Zero());
mov(r4, Operand(ExternalReference(Runtime::kDebugBreak, isolate())));
CEntryStub ces(isolate(), 1);
DCHECK(AllowThisStubCall(&ces));
Call(ces.GetCode(), RelocInfo::DEBUG_BREAK);
}
void MacroAssembler::PushTryHandler(StackHandler::Kind kind,
int handler_index) {
// Adjust this code if not the case.
STATIC_ASSERT(StackHandlerConstants::kSize == 5 * kPointerSize);
STATIC_ASSERT(StackHandlerConstants::kNextOffset == 0 * kPointerSize);
STATIC_ASSERT(StackHandlerConstants::kCodeOffset == 1 * kPointerSize);
STATIC_ASSERT(StackHandlerConstants::kStateOffset == 2 * kPointerSize);
STATIC_ASSERT(StackHandlerConstants::kContextOffset == 3 * kPointerSize);
STATIC_ASSERT(StackHandlerConstants::kFPOffset == 4 * kPointerSize);
// For the JSEntry handler, we must preserve r1-r7, r0,r8-r15 are available.
// We want the stack to look like
// sp -> NextOffset
// CodeObject
// state
// context
// frame pointer
// Link the current handler as the next handler.
mov(r8, Operand(ExternalReference(Isolate::kHandlerAddress, isolate())));
LoadP(r0, MemOperand(r8));
StorePU(r0, MemOperand(sp, -StackHandlerConstants::kSize));
// Set this new handler as the current one.
StoreP(sp, MemOperand(r8));
if (kind == StackHandler::JS_ENTRY) {
li(r8, Operand::Zero()); // NULL frame pointer.
StoreP(r8, MemOperand(sp, StackHandlerConstants::kFPOffset));
LoadSmiLiteral(r8, Smi::FromInt(0)); // Indicates no context.
StoreP(r8, MemOperand(sp, StackHandlerConstants::kContextOffset));
} else {
// still not sure if fp is right
StoreP(fp, MemOperand(sp, StackHandlerConstants::kFPOffset));
StoreP(cp, MemOperand(sp, StackHandlerConstants::kContextOffset));
}
unsigned state = StackHandler::IndexField::encode(handler_index) |
StackHandler::KindField::encode(kind);
LoadIntLiteral(r8, state);
StoreP(r8, MemOperand(sp, StackHandlerConstants::kStateOffset));
mov(r8, Operand(CodeObject()));
StoreP(r8, MemOperand(sp, StackHandlerConstants::kCodeOffset));
}
void MacroAssembler::PopTryHandler() {
STATIC_ASSERT(StackHandlerConstants::kNextOffset == 0);
pop(r4);
mov(ip, Operand(ExternalReference(Isolate::kHandlerAddress, isolate())));
addi(sp, sp, Operand(StackHandlerConstants::kSize - kPointerSize));
StoreP(r4, MemOperand(ip));
}
// PPC - make use of ip as a temporary register
void MacroAssembler::JumpToHandlerEntry() {
// Compute the handler entry address and jump to it. The handler table is
// a fixed array of (smi-tagged) code offsets.
// r3 = exception, r4 = code object, r5 = state.
#if V8_OOL_CONSTANT_POOL
ConstantPoolUnavailableScope constant_pool_unavailable(this);
LoadP(kConstantPoolRegister, FieldMemOperand(r4, Code::kConstantPoolOffset));
#endif
LoadP(r6, FieldMemOperand(r4, Code::kHandlerTableOffset)); // Handler table.
addi(r6, r6, Operand(FixedArray::kHeaderSize - kHeapObjectTag));
srwi(r5, r5, Operand(StackHandler::kKindWidth)); // Handler index.
slwi(ip, r5, Operand(kPointerSizeLog2));
add(ip, r6, ip);
LoadP(r5, MemOperand(ip)); // Smi-tagged offset.
addi(r4, r4, Operand(Code::kHeaderSize - kHeapObjectTag)); // Code start.
SmiUntag(ip, r5);
add(r0, r4, ip);
mtctr(r0);
bctr();
}
void MacroAssembler::Throw(Register value) {
// Adjust this code if not the case.
STATIC_ASSERT(StackHandlerConstants::kSize == 5 * kPointerSize);
STATIC_ASSERT(StackHandlerConstants::kNextOffset == 0);
STATIC_ASSERT(StackHandlerConstants::kCodeOffset == 1 * kPointerSize);
STATIC_ASSERT(StackHandlerConstants::kStateOffset == 2 * kPointerSize);
STATIC_ASSERT(StackHandlerConstants::kContextOffset == 3 * kPointerSize);
STATIC_ASSERT(StackHandlerConstants::kFPOffset == 4 * kPointerSize);
Label skip;
// The exception is expected in r3.
if (!value.is(r3)) {
mr(r3, value);
}
// Drop the stack pointer to the top of the top handler.
mov(r6, Operand(ExternalReference(Isolate::kHandlerAddress, isolate())));
LoadP(sp, MemOperand(r6));
// Restore the next handler.
pop(r5);
StoreP(r5, MemOperand(r6));
// Get the code object (r4) and state (r5). Restore the context and frame
// pointer.
pop(r4);
pop(r5);
pop(cp);
pop(fp);
// If the handler is a JS frame, restore the context to the frame.
// (kind == ENTRY) == (fp == 0) == (cp == 0), so we could test either fp
// or cp.
cmpi(cp, Operand::Zero());
beq(&skip);
StoreP(cp, MemOperand(fp, StandardFrameConstants::kContextOffset));
bind(&skip);
JumpToHandlerEntry();
}
void MacroAssembler::ThrowUncatchable(Register value) {
// Adjust this code if not the case.
STATIC_ASSERT(StackHandlerConstants::kSize == 5 * kPointerSize);
STATIC_ASSERT(StackHandlerConstants::kNextOffset == 0 * kPointerSize);
STATIC_ASSERT(StackHandlerConstants::kCodeOffset == 1 * kPointerSize);
STATIC_ASSERT(StackHandlerConstants::kStateOffset == 2 * kPointerSize);
STATIC_ASSERT(StackHandlerConstants::kContextOffset == 3 * kPointerSize);
STATIC_ASSERT(StackHandlerConstants::kFPOffset == 4 * kPointerSize);
// The exception is expected in r3.
if (!value.is(r3)) {
mr(r3, value);
}
// Drop the stack pointer to the top of the top stack handler.
mov(r6, Operand(ExternalReference(Isolate::kHandlerAddress, isolate())));
LoadP(sp, MemOperand(r6));
// Unwind the handlers until the ENTRY handler is found.
Label fetch_next, check_kind;
b(&check_kind);
bind(&fetch_next);
LoadP(sp, MemOperand(sp, StackHandlerConstants::kNextOffset));
bind(&check_kind);
STATIC_ASSERT(StackHandler::JS_ENTRY == 0);
LoadP(r5, MemOperand(sp, StackHandlerConstants::kStateOffset));
andi(r0, r5, Operand(StackHandler::KindField::kMask));
bne(&fetch_next, cr0);
// Set the top handler address to next handler past the top ENTRY handler.
pop(r5);
StoreP(r5, MemOperand(r6));
// Get the code object (r4) and state (r5). Clear the context and frame
// pointer (0 was saved in the handler).
pop(r4);
pop(r5);
pop(cp);
pop(fp);
JumpToHandlerEntry();
}
void MacroAssembler::CheckAccessGlobalProxy(Register holder_reg,
Register scratch, Label* miss) {
Label same_contexts;
DCHECK(!holder_reg.is(scratch));
DCHECK(!holder_reg.is(ip));
DCHECK(!scratch.is(ip));
// Load current lexical context from the stack frame.
LoadP(scratch, MemOperand(fp, StandardFrameConstants::kContextOffset));
// In debug mode, make sure the lexical context is set.
#ifdef DEBUG
cmpi(scratch, Operand::Zero());
Check(ne, kWeShouldNotHaveAnEmptyLexicalContext);
#endif
// Load the native context of the current context.
int offset =
Context::kHeaderSize + Context::GLOBAL_OBJECT_INDEX * kPointerSize;
LoadP(scratch, FieldMemOperand(scratch, offset));
LoadP(scratch, FieldMemOperand(scratch, GlobalObject::kNativeContextOffset));
// Check the context is a native context.
if (emit_debug_code()) {
// Cannot use ip as a temporary in this verification code. Due to the fact
// that ip is clobbered as part of cmp with an object Operand.
push(holder_reg); // Temporarily save holder on the stack.
// Read the first word and compare to the native_context_map.
LoadP(holder_reg, FieldMemOperand(scratch, HeapObject::kMapOffset));
LoadRoot(ip, Heap::kNativeContextMapRootIndex);
cmp(holder_reg, ip);
Check(eq, kJSGlobalObjectNativeContextShouldBeANativeContext);
pop(holder_reg); // Restore holder.
}
// Check if both contexts are the same.
LoadP(ip, FieldMemOperand(holder_reg, JSGlobalProxy::kNativeContextOffset));
cmp(scratch, ip);
beq(&same_contexts);
// Check the context is a native context.
if (emit_debug_code()) {
// Cannot use ip as a temporary in this verification code. Due to the fact
// that ip is clobbered as part of cmp with an object Operand.
push(holder_reg); // Temporarily save holder on the stack.
mr(holder_reg, ip); // Move ip to its holding place.
LoadRoot(ip, Heap::kNullValueRootIndex);
cmp(holder_reg, ip);
Check(ne, kJSGlobalProxyContextShouldNotBeNull);
LoadP(holder_reg, FieldMemOperand(holder_reg, HeapObject::kMapOffset));
LoadRoot(ip, Heap::kNativeContextMapRootIndex);
cmp(holder_reg, ip);
Check(eq, kJSGlobalObjectNativeContextShouldBeANativeContext);
// Restore ip is not needed. ip is reloaded below.
pop(holder_reg); // Restore holder.
// Restore ip to holder's context.
LoadP(ip, FieldMemOperand(holder_reg, JSGlobalProxy::kNativeContextOffset));
}
// Check that the security token in the calling global object is
// compatible with the security token in the receiving global
// object.
int token_offset =
Context::kHeaderSize + Context::SECURITY_TOKEN_INDEX * kPointerSize;
LoadP(scratch, FieldMemOperand(scratch, token_offset));
LoadP(ip, FieldMemOperand(ip, token_offset));
cmp(scratch, ip);
bne(miss);
bind(&same_contexts);
}
// Compute the hash code from the untagged key. This must be kept in sync with
// ComputeIntegerHash in utils.h and KeyedLoadGenericStub in
// code-stub-hydrogen.cc
void MacroAssembler::GetNumberHash(Register t0, Register scratch) {
// First of all we assign the hash seed to scratch.
LoadRoot(scratch, Heap::kHashSeedRootIndex);
SmiUntag(scratch);
// Xor original key with a seed.
xor_(t0, t0, scratch);
// Compute the hash code from the untagged key. This must be kept in sync
// with ComputeIntegerHash in utils.h.
//
// hash = ~hash + (hash << 15);
notx(scratch, t0);
slwi(t0, t0, Operand(15));
add(t0, scratch, t0);
// hash = hash ^ (hash >> 12);
srwi(scratch, t0, Operand(12));
xor_(t0, t0, scratch);
// hash = hash + (hash << 2);
slwi(scratch, t0, Operand(2));
add(t0, t0, scratch);
// hash = hash ^ (hash >> 4);
srwi(scratch, t0, Operand(4));
xor_(t0, t0, scratch);
// hash = hash * 2057;
mr(r0, t0);
slwi(scratch, t0, Operand(3));
add(t0, t0, scratch);
slwi(scratch, r0, Operand(11));
add(t0, t0, scratch);
// hash = hash ^ (hash >> 16);
srwi(scratch, t0, Operand(16));
xor_(t0, t0, scratch);
}
void MacroAssembler::LoadFromNumberDictionary(Label* miss, Register elements,
Register key, Register result,
Register t0, Register t1,
Register t2) {
// Register use:
//
// elements - holds the slow-case elements of the receiver on entry.
// Unchanged unless 'result' is the same register.
//
// key - holds the smi key on entry.
// Unchanged unless 'result' is the same register.
//
// result - holds the result on exit if the load succeeded.
// Allowed to be the same as 'key' or 'result'.
// Unchanged on bailout so 'key' or 'result' can be used
// in further computation.
//
// Scratch registers:
//
// t0 - holds the untagged key on entry and holds the hash once computed.
//
// t1 - used to hold the capacity mask of the dictionary
//
// t2 - used for the index into the dictionary.
Label done;
GetNumberHash(t0, t1);
// Compute the capacity mask.
LoadP(t1, FieldMemOperand(elements, SeededNumberDictionary::kCapacityOffset));
SmiUntag(t1);
subi(t1, t1, Operand(1));
// Generate an unrolled loop that performs a few probes before giving up.
for (int i = 0; i < kNumberDictionaryProbes; i++) {
// Use t2 for index calculations and keep the hash intact in t0.
mr(t2, t0);
// Compute the masked index: (hash + i + i * i) & mask.
if (i > 0) {
addi(t2, t2, Operand(SeededNumberDictionary::GetProbeOffset(i)));
}
and_(t2, t2, t1);
// Scale the index by multiplying by the element size.
DCHECK(SeededNumberDictionary::kEntrySize == 3);
slwi(ip, t2, Operand(1));
add(t2, t2, ip); // t2 = t2 * 3
// Check if the key is identical to the name.
slwi(t2, t2, Operand(kPointerSizeLog2));
add(t2, elements, t2);
LoadP(ip,
FieldMemOperand(t2, SeededNumberDictionary::kElementsStartOffset));
cmp(key, ip);
if (i != kNumberDictionaryProbes - 1) {
beq(&done);
} else {
bne(miss);
}
}
bind(&done);
// Check that the value is a field property.
// t2: elements + (index * kPointerSize)
const int kDetailsOffset =
SeededNumberDictionary::kElementsStartOffset + 2 * kPointerSize;
LoadP(t1, FieldMemOperand(t2, kDetailsOffset));
LoadSmiLiteral(ip, Smi::FromInt(PropertyDetails::TypeField::kMask));
DCHECK_EQ(FIELD, 0);
and_(r0, t1, ip, SetRC);
bne(miss, cr0);
// Get the value at the masked, scaled index and return.
const int kValueOffset =
SeededNumberDictionary::kElementsStartOffset + kPointerSize;
LoadP(result, FieldMemOperand(t2, kValueOffset));
}
void MacroAssembler::Allocate(int object_size, Register result,
Register scratch1, Register scratch2,
Label* gc_required, AllocationFlags flags) {
DCHECK(object_size <= Page::kMaxRegularHeapObjectSize);
if (!FLAG_inline_new) {
if (emit_debug_code()) {
// Trash the registers to simulate an allocation failure.
li(result, Operand(0x7091));
li(scratch1, Operand(0x7191));
li(scratch2, Operand(0x7291));
}
b(gc_required);
return;
}
DCHECK(!result.is(scratch1));
DCHECK(!result.is(scratch2));
DCHECK(!scratch1.is(scratch2));
DCHECK(!scratch1.is(ip));
DCHECK(!scratch2.is(ip));
// Make object size into bytes.
if ((flags & SIZE_IN_WORDS) != 0) {
object_size *= kPointerSize;
}
DCHECK_EQ(0, static_cast<int>(object_size & kObjectAlignmentMask));
// Check relative positions of allocation top and limit addresses.
ExternalReference allocation_top =
AllocationUtils::GetAllocationTopReference(isolate(), flags);
ExternalReference allocation_limit =
AllocationUtils::GetAllocationLimitReference(isolate(), flags);
intptr_t top = reinterpret_cast<intptr_t>(allocation_top.address());
intptr_t limit = reinterpret_cast<intptr_t>(allocation_limit.address());
DCHECK((limit - top) == kPointerSize);
// Set up allocation top address register.
Register topaddr = scratch1;
mov(topaddr, Operand(allocation_top));
// This code stores a temporary value in ip. This is OK, as the code below
// does not need ip for implicit literal generation.
if ((flags & RESULT_CONTAINS_TOP) == 0) {
// Load allocation top into result and allocation limit into ip.
LoadP(result, MemOperand(topaddr));
LoadP(ip, MemOperand(topaddr, kPointerSize));
} else {
if (emit_debug_code()) {
// Assert that result actually contains top on entry. ip is used
// immediately below so this use of ip does not cause difference with
// respect to register content between debug and release mode.
LoadP(ip, MemOperand(topaddr));
cmp(result, ip);
Check(eq, kUnexpectedAllocationTop);
}
// Load allocation limit into ip. Result already contains allocation top.
LoadP(ip, MemOperand(topaddr, limit - top), r0);
}
if ((flags & DOUBLE_ALIGNMENT) != 0) {
// Align the next allocation. Storing the filler map without checking top is
// safe in new-space because the limit of the heap is aligned there.
DCHECK((flags & PRETENURE_OLD_POINTER_SPACE) == 0);
#if V8_TARGET_ARCH_PPC64
STATIC_ASSERT(kPointerAlignment == kDoubleAlignment);
#else
STATIC_ASSERT(kPointerAlignment * 2 == kDoubleAlignment);
andi(scratch2, result, Operand(kDoubleAlignmentMask));
Label aligned;
beq(&aligned, cr0);
if ((flags & PRETENURE_OLD_DATA_SPACE) != 0) {
cmpl(result, ip);
bge(gc_required);
}
mov(scratch2, Operand(isolate()->factory()->one_pointer_filler_map()));
stw(scratch2, MemOperand(result));
addi(result, result, Operand(kDoubleSize / 2));
bind(&aligned);
#endif
}
// Calculate new top and bail out if new space is exhausted. Use result
// to calculate the new top.
sub(r0, ip, result);
if (is_int16(object_size)) {
cmpi(r0, Operand(object_size));
blt(gc_required);
addi(scratch2, result, Operand(object_size));
} else {
Cmpi(r0, Operand(object_size), scratch2);
blt(gc_required);
add(scratch2, result, scratch2);
}
StoreP(scratch2, MemOperand(topaddr));
// Tag object if requested.
if ((flags & TAG_OBJECT) != 0) {
addi(result, result, Operand(kHeapObjectTag));
}
}
void MacroAssembler::Allocate(Register object_size, Register result,
Register scratch1, Register scratch2,
Label* gc_required, AllocationFlags flags) {
if (!FLAG_inline_new) {
if (emit_debug_code()) {
// Trash the registers to simulate an allocation failure.
li(result, Operand(0x7091));
li(scratch1, Operand(0x7191));
li(scratch2, Operand(0x7291));
}
b(gc_required);
return;
}
// Assert that the register arguments are different and that none of
// them are ip. ip is used explicitly in the code generated below.
DCHECK(!result.is(scratch1));
DCHECK(!result.is(scratch2));
DCHECK(!scratch1.is(scratch2));
DCHECK(!object_size.is(ip));
DCHECK(!result.is(ip));
DCHECK(!scratch1.is(ip));
DCHECK(!scratch2.is(ip));
// Check relative positions of allocation top and limit addresses.
ExternalReference allocation_top =
AllocationUtils::GetAllocationTopReference(isolate(), flags);
ExternalReference allocation_limit =
AllocationUtils::GetAllocationLimitReference(isolate(), flags);
intptr_t top = reinterpret_cast<intptr_t>(allocation_top.address());
intptr_t limit = reinterpret_cast<intptr_t>(allocation_limit.address());
DCHECK((limit - top) == kPointerSize);
// Set up allocation top address.
Register topaddr = scratch1;
mov(topaddr, Operand(allocation_top));
// This code stores a temporary value in ip. This is OK, as the code below
// does not need ip for implicit literal generation.
if ((flags & RESULT_CONTAINS_TOP) == 0) {
// Load allocation top into result and allocation limit into ip.
LoadP(result, MemOperand(topaddr));
LoadP(ip, MemOperand(topaddr, kPointerSize));
} else {
if (emit_debug_code()) {
// Assert that result actually contains top on entry. ip is used
// immediately below so this use of ip does not cause difference with
// respect to register content between debug and release mode.
LoadP(ip, MemOperand(topaddr));
cmp(result, ip);
Check(eq, kUnexpectedAllocationTop);
}
// Load allocation limit into ip. Result already contains allocation top.
LoadP(ip, MemOperand(topaddr, limit - top));
}
if ((flags & DOUBLE_ALIGNMENT) != 0) {
// Align the next allocation. Storing the filler map without checking top is
// safe in new-space because the limit of the heap is aligned there.
DCHECK((flags & PRETENURE_OLD_POINTER_SPACE) == 0);
#if V8_TARGET_ARCH_PPC64
STATIC_ASSERT(kPointerAlignment == kDoubleAlignment);
#else
STATIC_ASSERT(kPointerAlignment * 2 == kDoubleAlignment);
andi(scratch2, result, Operand(kDoubleAlignmentMask));
Label aligned;
beq(&aligned, cr0);
if ((flags & PRETENURE_OLD_DATA_SPACE) != 0) {
cmpl(result, ip);
bge(gc_required);
}
mov(scratch2, Operand(isolate()->factory()->one_pointer_filler_map()));
stw(scratch2, MemOperand(result));
addi(result, result, Operand(kDoubleSize / 2));
bind(&aligned);
#endif
}
// Calculate new top and bail out if new space is exhausted. Use result
// to calculate the new top. Object size may be in words so a shift is
// required to get the number of bytes.
sub(r0, ip, result);
if ((flags & SIZE_IN_WORDS) != 0) {
ShiftLeftImm(scratch2, object_size, Operand(kPointerSizeLog2));
cmp(r0, scratch2);
blt(gc_required);
add(scratch2, result, scratch2);
} else {
cmp(r0, object_size);
blt(gc_required);
add(scratch2, result, object_size);
}
// Update allocation top. result temporarily holds the new top.
if (emit_debug_code()) {
andi(r0, scratch2, Operand(kObjectAlignmentMask));
Check(eq, kUnalignedAllocationInNewSpace, cr0);
}
StoreP(scratch2, MemOperand(topaddr));
// Tag object if requested.
if ((flags & TAG_OBJECT) != 0) {
addi(result, result, Operand(kHeapObjectTag));
}
}
void MacroAssembler::UndoAllocationInNewSpace(Register object,
Register scratch) {
ExternalReference new_space_allocation_top =
ExternalReference::new_space_allocation_top_address(isolate());
// Make sure the object has no tag before resetting top.
mov(r0, Operand(~kHeapObjectTagMask));
and_(object, object, r0);
// was.. and_(object, object, Operand(~kHeapObjectTagMask));
#ifdef DEBUG
// Check that the object un-allocated is below the current top.
mov(scratch, Operand(new_space_allocation_top));
LoadP(scratch, MemOperand(scratch));
cmp(object, scratch);
Check(lt, kUndoAllocationOfNonAllocatedMemory);
#endif
// Write the address of the object to un-allocate as the current top.
mov(scratch, Operand(new_space_allocation_top));
StoreP(object, MemOperand(scratch));
}
void MacroAssembler::AllocateTwoByteString(Register result, Register length,
Register scratch1, Register scratch2,
Register scratch3,
Label* gc_required) {
// Calculate the number of bytes needed for the characters in the string while
// observing object alignment.
DCHECK((SeqTwoByteString::kHeaderSize & kObjectAlignmentMask) == 0);
slwi(scratch1, length, Operand(1)); // Length in bytes, not chars.
addi(scratch1, scratch1,
Operand(kObjectAlignmentMask + SeqTwoByteString::kHeaderSize));
mov(r0, Operand(~kObjectAlignmentMask));
and_(scratch1, scratch1, r0);
// Allocate two-byte string in new space.
Allocate(scratch1, result, scratch2, scratch3, gc_required, TAG_OBJECT);
// Set the map, length and hash field.
InitializeNewString(result, length, Heap::kStringMapRootIndex, scratch1,
scratch2);
}
void MacroAssembler::AllocateOneByteString(Register result, Register length,
Register scratch1, Register scratch2,
Register scratch3,
Label* gc_required) {
// Calculate the number of bytes needed for the characters in the string while
// observing object alignment.
DCHECK((SeqOneByteString::kHeaderSize & kObjectAlignmentMask) == 0);
DCHECK(kCharSize == 1);
addi(scratch1, length,
Operand(kObjectAlignmentMask + SeqOneByteString::kHeaderSize));
li(r0, Operand(~kObjectAlignmentMask));
and_(scratch1, scratch1, r0);
// Allocate one-byte string in new space.
Allocate(scratch1, result, scratch2, scratch3, gc_required, TAG_OBJECT);
// Set the map, length and hash field.
InitializeNewString(result, length, Heap::kOneByteStringMapRootIndex,
scratch1, scratch2);
}
void MacroAssembler::AllocateTwoByteConsString(Register result, Register length,
Register scratch1,
Register scratch2,
Label* gc_required) {
Allocate(ConsString::kSize, result, scratch1, scratch2, gc_required,
TAG_OBJECT);
InitializeNewString(result, length, Heap::kConsStringMapRootIndex, scratch1,
scratch2);
}
void MacroAssembler::AllocateOneByteConsString(Register result, Register length,
Register scratch1,
Register scratch2,
Label* gc_required) {
Allocate(ConsString::kSize, result, scratch1, scratch2, gc_required,
TAG_OBJECT);
InitializeNewString(result, length, Heap::kConsOneByteStringMapRootIndex,
scratch1, scratch2);
}
void MacroAssembler::AllocateTwoByteSlicedString(Register result,
Register length,
Register scratch1,
Register scratch2,
Label* gc_required) {
Allocate(SlicedString::kSize, result, scratch1, scratch2, gc_required,
TAG_OBJECT);
InitializeNewString(result, length, Heap::kSlicedStringMapRootIndex, scratch1,
scratch2);
}
void MacroAssembler::AllocateOneByteSlicedString(Register result,
Register length,
Register scratch1,
Register scratch2,
Label* gc_required) {
Allocate(SlicedString::kSize, result, scratch1, scratch2, gc_required,
TAG_OBJECT);
InitializeNewString(result, length, Heap::kSlicedOneByteStringMapRootIndex,
scratch1, scratch2);
}
void MacroAssembler::CompareObjectType(Register object, Register map,
Register type_reg, InstanceType type) {
const Register temp = type_reg.is(no_reg) ? r0 : type_reg;
LoadP(map, FieldMemOperand(object, HeapObject::kMapOffset));
CompareInstanceType(map, temp, type);
}
void MacroAssembler::CheckObjectTypeRange(Register object, Register map,
InstanceType min_type,
InstanceType max_type,
Label* false_label) {
STATIC_ASSERT(Map::kInstanceTypeOffset < 4096);
STATIC_ASSERT(LAST_TYPE < 256);
LoadP(map, FieldMemOperand(object, HeapObject::kMapOffset));
lbz(ip, FieldMemOperand(map, Map::kInstanceTypeOffset));
subi(ip, ip, Operand(min_type));
cmpli(ip, Operand(max_type - min_type));
bgt(false_label);
}
void MacroAssembler::CompareInstanceType(Register map, Register type_reg,
InstanceType type) {
STATIC_ASSERT(Map::kInstanceTypeOffset < 4096);
STATIC_ASSERT(LAST_TYPE < 256);
lbz(type_reg, FieldMemOperand(map, Map::kInstanceTypeOffset));
cmpi(type_reg, Operand(type));
}
void MacroAssembler::CompareRoot(Register obj, Heap::RootListIndex index) {
DCHECK(!obj.is(r0));
LoadRoot(r0, index);
cmp(obj, r0);
}
void MacroAssembler::CheckFastElements(Register map, Register scratch,
Label* fail) {
STATIC_ASSERT(FAST_SMI_ELEMENTS == 0);
STATIC_ASSERT(FAST_HOLEY_SMI_ELEMENTS == 1);
STATIC_ASSERT(FAST_ELEMENTS == 2);
STATIC_ASSERT(FAST_HOLEY_ELEMENTS == 3);
lbz(scratch, FieldMemOperand(map, Map::kBitField2Offset));
STATIC_ASSERT(Map::kMaximumBitField2FastHoleyElementValue < 0x8000);
cmpli(scratch, Operand(Map::kMaximumBitField2FastHoleyElementValue));
bgt(fail);
}
void MacroAssembler::CheckFastObjectElements(Register map, Register scratch,
Label* fail) {
STATIC_ASSERT(FAST_SMI_ELEMENTS == 0);
STATIC_ASSERT(FAST_HOLEY_SMI_ELEMENTS == 1);
STATIC_ASSERT(FAST_ELEMENTS == 2);
STATIC_ASSERT(FAST_HOLEY_ELEMENTS == 3);
lbz(scratch, FieldMemOperand(map, Map::kBitField2Offset));
cmpli(scratch, Operand(Map::kMaximumBitField2FastHoleySmiElementValue));
ble(fail);
cmpli(scratch, Operand(Map::kMaximumBitField2FastHoleyElementValue));
bgt(fail);
}
void MacroAssembler::CheckFastSmiElements(Register map, Register scratch,
Label* fail) {
STATIC_ASSERT(FAST_SMI_ELEMENTS == 0);
STATIC_ASSERT(FAST_HOLEY_SMI_ELEMENTS == 1);
lbz(scratch, FieldMemOperand(map, Map::kBitField2Offset));
cmpli(scratch, Operand(Map::kMaximumBitField2FastHoleySmiElementValue));
bgt(fail);
}
void MacroAssembler::StoreNumberToDoubleElements(
Register value_reg, Register key_reg, Register elements_reg,
Register scratch1, DoubleRegister double_scratch, Label* fail,
int elements_offset) {
Label smi_value, store;
// Handle smi values specially.
JumpIfSmi(value_reg, &smi_value);
// Ensure that the object is a heap number
CheckMap(value_reg, scratch1, isolate()->factory()->heap_number_map(), fail,
DONT_DO_SMI_CHECK);
lfd(double_scratch, FieldMemOperand(value_reg, HeapNumber::kValueOffset));
// Force a canonical NaN.
CanonicalizeNaN(double_scratch);
b(&store);
bind(&smi_value);
SmiToDouble(double_scratch, value_reg);
bind(&store);
SmiToDoubleArrayOffset(scratch1, key_reg);
add(scratch1, elements_reg, scratch1);
stfd(double_scratch, FieldMemOperand(scratch1, FixedDoubleArray::kHeaderSize -
elements_offset));
}
void MacroAssembler::AddAndCheckForOverflow(Register dst, Register left,
Register right,
Register overflow_dst,
Register scratch) {
DCHECK(!dst.is(overflow_dst));
DCHECK(!dst.is(scratch));
DCHECK(!overflow_dst.is(scratch));
DCHECK(!overflow_dst.is(left));
DCHECK(!overflow_dst.is(right));
// C = A+B; C overflows if A/B have same sign and C has diff sign than A
if (dst.is(left)) {
mr(scratch, left); // Preserve left.
add(dst, left, right); // Left is overwritten.
xor_(scratch, dst, scratch); // Original left.
xor_(overflow_dst, dst, right);
} else if (dst.is(right)) {
mr(scratch, right); // Preserve right.
add(dst, left, right); // Right is overwritten.
xor_(scratch, dst, scratch); // Original right.
xor_(overflow_dst, dst, left);
} else {
add(dst, left, right);
xor_(overflow_dst, dst, left);
xor_(scratch, dst, right);
}
and_(overflow_dst, scratch, overflow_dst, SetRC);
}
void MacroAssembler::AddAndCheckForOverflow(Register dst, Register left,
intptr_t right,
Register overflow_dst,
Register scratch) {
Register original_left = left;
DCHECK(!dst.is(overflow_dst));
DCHECK(!dst.is(scratch));
DCHECK(!overflow_dst.is(scratch));
DCHECK(!overflow_dst.is(left));
// C = A+B; C overflows if A/B have same sign and C has diff sign than A
if (dst.is(left)) {
// Preserve left.
original_left = overflow_dst;
mr(original_left, left);
}
Add(dst, left, right, scratch);
xor_(overflow_dst, dst, original_left);
if (right >= 0) {
and_(overflow_dst, overflow_dst, dst, SetRC);
} else {
andc(overflow_dst, overflow_dst, dst, SetRC);
}
}
void MacroAssembler::SubAndCheckForOverflow(Register dst, Register left,
Register right,
Register overflow_dst,
Register scratch) {
DCHECK(!dst.is(overflow_dst));
DCHECK(!dst.is(scratch));
DCHECK(!overflow_dst.is(scratch));
DCHECK(!overflow_dst.is(left));
DCHECK(!overflow_dst.is(right));
// C = A-B; C overflows if A/B have diff signs and C has diff sign than A
if (dst.is(left)) {
mr(scratch, left); // Preserve left.
sub(dst, left, right); // Left is overwritten.
xor_(overflow_dst, dst, scratch);
xor_(scratch, scratch, right);
and_(overflow_dst, overflow_dst, scratch, SetRC);
} else if (dst.is(right)) {
mr(scratch, right); // Preserve right.
sub(dst, left, right); // Right is overwritten.
xor_(overflow_dst, dst, left);
xor_(scratch, left, scratch);
and_(overflow_dst, overflow_dst, scratch, SetRC);
} else {
sub(dst, left, right);
xor_(overflow_dst, dst, left);
xor_(scratch, left, right);
and_(overflow_dst, scratch, overflow_dst, SetRC);
}
}
void MacroAssembler::CompareMap(Register obj, Register scratch, Handle<Map> map,
Label* early_success) {
LoadP(scratch, FieldMemOperand(obj, HeapObject::kMapOffset));
CompareMap(scratch, map, early_success);
}
void MacroAssembler::CompareMap(Register obj_map, Handle<Map> map,
Label* early_success) {
mov(r0, Operand(map));
cmp(obj_map, r0);
}
void MacroAssembler::CheckMap(Register obj, Register scratch, Handle<Map> map,
Label* fail, SmiCheckType smi_check_type) {
if (smi_check_type == DO_SMI_CHECK) {
JumpIfSmi(obj, fail);
}
Label success;
CompareMap(obj, scratch, map, &success);
bne(fail);
bind(&success);
}
void MacroAssembler::CheckMap(Register obj, Register scratch,
Heap::RootListIndex index, Label* fail,
SmiCheckType smi_check_type) {
if (smi_check_type == DO_SMI_CHECK) {
JumpIfSmi(obj, fail);
}
LoadP(scratch, FieldMemOperand(obj, HeapObject::kMapOffset));
LoadRoot(r0, index);
cmp(scratch, r0);
bne(fail);
}
void MacroAssembler::DispatchMap(Register obj, Register scratch,
Handle<Map> map, Handle<Code> success,
SmiCheckType smi_check_type) {
Label fail;
if (smi_check_type == DO_SMI_CHECK) {
JumpIfSmi(obj, &fail);
}
LoadP(scratch, FieldMemOperand(obj, HeapObject::kMapOffset));
mov(r0, Operand(map));
cmp(scratch, r0);
bne(&fail);
Jump(success, RelocInfo::CODE_TARGET, al);
bind(&fail);
}
void MacroAssembler::TryGetFunctionPrototype(Register function, Register result,
Register scratch, Label* miss,
bool miss_on_bound_function) {
Label non_instance;
if (miss_on_bound_function) {
// Check that the receiver isn't a smi.
JumpIfSmi(function, miss);
// Check that the function really is a function. Load map into result reg.
CompareObjectType(function, result, scratch, JS_FUNCTION_TYPE);
bne(miss);
LoadP(scratch,
FieldMemOperand(function, JSFunction::kSharedFunctionInfoOffset));
lwz(scratch,
FieldMemOperand(scratch, SharedFunctionInfo::kCompilerHintsOffset));
TestBit(scratch,
#if V8_TARGET_ARCH_PPC64
SharedFunctionInfo::kBoundFunction,
#else
SharedFunctionInfo::kBoundFunction + kSmiTagSize,
#endif
r0);
bne(miss, cr0);
// Make sure that the function has an instance prototype.
lbz(scratch, FieldMemOperand(result, Map::kBitFieldOffset));
andi(r0, scratch, Operand(1 << Map::kHasNonInstancePrototype));
bne(&non_instance, cr0);
}
// Get the prototype or initial map from the function.
LoadP(result,
FieldMemOperand(function, JSFunction::kPrototypeOrInitialMapOffset));
// If the prototype or initial map is the hole, don't return it and
// simply miss the cache instead. This will allow us to allocate a
// prototype object on-demand in the runtime system.
LoadRoot(r0, Heap::kTheHoleValueRootIndex);
cmp(result, r0);
beq(miss);
// If the function does not have an initial map, we're done.
Label done;
CompareObjectType(result, scratch, scratch, MAP_TYPE);
bne(&done);
// Get the prototype from the initial map.
LoadP(result, FieldMemOperand(result, Map::kPrototypeOffset));
if (miss_on_bound_function) {
b(&done);
// Non-instance prototype: Fetch prototype from constructor field
// in initial map.
bind(&non_instance);
LoadP(result, FieldMemOperand(result, Map::kConstructorOffset));
}
// All done.
bind(&done);
}
void MacroAssembler::CallStub(CodeStub* stub, TypeFeedbackId ast_id,
Condition cond) {
DCHECK(AllowThisStubCall(stub)); // Stub calls are not allowed in some stubs.
Call(stub->GetCode(), RelocInfo::CODE_TARGET, ast_id, cond);
}
void MacroAssembler::TailCallStub(CodeStub* stub, Condition cond) {
Jump(stub->GetCode(), RelocInfo::CODE_TARGET, cond);
}
static int AddressOffset(ExternalReference ref0, ExternalReference ref1) {
return ref0.address() - ref1.address();
}
void MacroAssembler::CallApiFunctionAndReturn(
Register function_address, ExternalReference thunk_ref, int stack_space,
MemOperand return_value_operand, MemOperand* context_restore_operand) {
ExternalReference next_address =
ExternalReference::handle_scope_next_address(isolate());
const int kNextOffset = 0;
const int kLimitOffset = AddressOffset(
ExternalReference::handle_scope_limit_address(isolate()), next_address);
const int kLevelOffset = AddressOffset(
ExternalReference::handle_scope_level_address(isolate()), next_address);
DCHECK(function_address.is(r4) || function_address.is(r5));
Register scratch = r6;
Label profiler_disabled;
Label end_profiler_check;
mov(scratch, Operand(ExternalReference::is_profiling_address(isolate())));
lbz(scratch, MemOperand(scratch, 0));
cmpi(scratch, Operand::Zero());
beq(&profiler_disabled);
// Additional parameter is the address of the actual callback.
mov(scratch, Operand(thunk_ref));
jmp(&end_profiler_check);
bind(&profiler_disabled);
mr(scratch, function_address);
bind(&end_profiler_check);
// Allocate HandleScope in callee-save registers.
// r17 - next_address
// r14 - next_address->kNextOffset
// r15 - next_address->kLimitOffset
// r16 - next_address->kLevelOffset
mov(r17, Operand(next_address));
LoadP(r14, MemOperand(r17, kNextOffset));
LoadP(r15, MemOperand(r17, kLimitOffset));
lwz(r16, MemOperand(r17, kLevelOffset));
addi(r16, r16, Operand(1));
stw(r16, MemOperand(r17, kLevelOffset));
if (FLAG_log_timer_events) {
FrameScope frame(this, StackFrame::MANUAL);
PushSafepointRegisters();
PrepareCallCFunction(1, r3);
mov(r3, Operand(ExternalReference::isolate_address(isolate())));
CallCFunction(ExternalReference::log_enter_external_function(isolate()), 1);
PopSafepointRegisters();
}
// Native call returns to the DirectCEntry stub which redirects to the
// return address pushed on stack (could have moved after GC).
// DirectCEntry stub itself is generated early and never moves.
DirectCEntryStub stub(isolate());
stub.GenerateCall(this, scratch);
if (FLAG_log_timer_events) {
FrameScope frame(this, StackFrame::MANUAL);
PushSafepointRegisters();
PrepareCallCFunction(1, r3);
mov(r3, Operand(ExternalReference::isolate_address(isolate())));
CallCFunction(ExternalReference::log_leave_external_function(isolate()), 1);
PopSafepointRegisters();
}
Label promote_scheduled_exception;
Label exception_handled;
Label delete_allocated_handles;
Label leave_exit_frame;
Label return_value_loaded;
// load value from ReturnValue
LoadP(r3, return_value_operand);
bind(&return_value_loaded);
// No more valid handles (the result handle was the last one). Restore
// previous handle scope.
StoreP(r14, MemOperand(r17, kNextOffset));
if (emit_debug_code()) {
lwz(r4, MemOperand(r17, kLevelOffset));
cmp(r4, r16);
Check(eq, kUnexpectedLevelAfterReturnFromApiCall);
}
subi(r16, r16, Operand(1));
stw(r16, MemOperand(r17, kLevelOffset));
LoadP(r0, MemOperand(r17, kLimitOffset));
cmp(r15, r0);
bne(&delete_allocated_handles);
// Check if the function scheduled an exception.
bind(&leave_exit_frame);
LoadRoot(r14, Heap::kTheHoleValueRootIndex);
mov(r15, Operand(ExternalReference::scheduled_exception_address(isolate())));
LoadP(r15, MemOperand(r15));
cmp(r14, r15);
bne(&promote_scheduled_exception);
bind(&exception_handled);
bool restore_context = context_restore_operand != NULL;
if (restore_context) {
LoadP(cp, *context_restore_operand);
}
// LeaveExitFrame expects unwind space to be in a register.
mov(r14, Operand(stack_space));
LeaveExitFrame(false, r14, !restore_context);
blr();
bind(&promote_scheduled_exception);
{
FrameScope frame(this, StackFrame::INTERNAL);
CallExternalReference(
ExternalReference(Runtime::kPromoteScheduledException, isolate()), 0);
}
jmp(&exception_handled);
// HandleScope limit has changed. Delete allocated extensions.
bind(&delete_allocated_handles);
StoreP(r15, MemOperand(r17, kLimitOffset));
mr(r14, r3);
PrepareCallCFunction(1, r15);
mov(r3, Operand(ExternalReference::isolate_address(isolate())));
CallCFunction(ExternalReference::delete_handle_scope_extensions(isolate()),
1);
mr(r3, r14);
b(&leave_exit_frame);
}
bool MacroAssembler::AllowThisStubCall(CodeStub* stub) {
return has_frame_ || !stub->SometimesSetsUpAFrame();
}
void MacroAssembler::IndexFromHash(Register hash, Register index) {
// If the hash field contains an array index pick it out. The assert checks
// that the constants for the maximum number of digits for an array index
// cached in the hash field and the number of bits reserved for it does not
// conflict.
DCHECK(TenToThe(String::kMaxCachedArrayIndexLength) <
(1 << String::kArrayIndexValueBits));
DecodeFieldToSmi<String::ArrayIndexValueBits>(index, hash);
}
void MacroAssembler::SmiToDouble(DoubleRegister value, Register smi) {
SmiUntag(ip, smi);
ConvertIntToDouble(ip, value);
}
void MacroAssembler::TestDoubleIsInt32(DoubleRegister double_input,
Register scratch1, Register scratch2,
DoubleRegister double_scratch) {
TryDoubleToInt32Exact(scratch1, double_input, scratch2, double_scratch);
}
void MacroAssembler::TryDoubleToInt32Exact(Register result,
DoubleRegister double_input,
Register scratch,
DoubleRegister double_scratch) {
Label done;
DCHECK(!double_input.is(double_scratch));
ConvertDoubleToInt64(double_input,
#if !V8_TARGET_ARCH_PPC64
scratch,
#endif
result, double_scratch);
#if V8_TARGET_ARCH_PPC64
TestIfInt32(result, scratch, r0);
#else
TestIfInt32(scratch, result, r0);
#endif
bne(&done);
// convert back and compare
fcfid(double_scratch, double_scratch);
fcmpu(double_scratch, double_input);
bind(&done);
}
void MacroAssembler::TryInt32Floor(Register result, DoubleRegister double_input,
Register input_high, Register scratch,
DoubleRegister double_scratch, Label* done,
Label* exact) {
DCHECK(!result.is(input_high));
DCHECK(!double_input.is(double_scratch));
Label exception;
MovDoubleHighToInt(input_high, double_input);
// Test for NaN/Inf
ExtractBitMask(result, input_high, HeapNumber::kExponentMask);
cmpli(result, Operand(0x7ff));
beq(&exception);
// Convert (rounding to -Inf)
ConvertDoubleToInt64(double_input,
#if !V8_TARGET_ARCH_PPC64
scratch,
#endif
result, double_scratch, kRoundToMinusInf);
// Test for overflow
#if V8_TARGET_ARCH_PPC64
TestIfInt32(result, scratch, r0);
#else
TestIfInt32(scratch, result, r0);
#endif
bne(&exception);
// Test for exactness
fcfid(double_scratch, double_scratch);
fcmpu(double_scratch, double_input);
beq(exact);
b(done);
bind(&exception);
}
void MacroAssembler::TryInlineTruncateDoubleToI(Register result,
DoubleRegister double_input,
Label* done) {
DoubleRegister double_scratch = kScratchDoubleReg;
Register scratch = ip;
ConvertDoubleToInt64(double_input,
#if !V8_TARGET_ARCH_PPC64
scratch,
#endif
result, double_scratch);
// Test for overflow
#if V8_TARGET_ARCH_PPC64
TestIfInt32(result, scratch, r0);
#else
TestIfInt32(scratch, result, r0);
#endif
beq(done);
}
void MacroAssembler::TruncateDoubleToI(Register result,
DoubleRegister double_input) {
Label done;
TryInlineTruncateDoubleToI(result, double_input, &done);
// If we fell through then inline version didn't succeed - call stub instead.
mflr(r0);
push(r0);
// Put input on stack.
stfdu(double_input, MemOperand(sp, -kDoubleSize));
DoubleToIStub stub(isolate(), sp, result, 0, true, true);
CallStub(&stub);
addi(sp, sp, Operand(kDoubleSize));
pop(r0);
mtlr(r0);
bind(&done);
}
void MacroAssembler::TruncateHeapNumberToI(Register result, Register object) {
Label done;
DoubleRegister double_scratch = kScratchDoubleReg;
DCHECK(!result.is(object));
lfd(double_scratch, FieldMemOperand(object, HeapNumber::kValueOffset));
TryInlineTruncateDoubleToI(result, double_scratch, &done);
// If we fell through then inline version didn't succeed - call stub instead.
mflr(r0);
push(r0);
DoubleToIStub stub(isolate(), object, result,
HeapNumber::kValueOffset - kHeapObjectTag, true, true);
CallStub(&stub);
pop(r0);
mtlr(r0);
bind(&done);
}
void MacroAssembler::TruncateNumberToI(Register object, Register result,
Register heap_number_map,
Register scratch1, Label* not_number) {
Label done;
DCHECK(!result.is(object));
UntagAndJumpIfSmi(result, object, &done);
JumpIfNotHeapNumber(object, heap_number_map, scratch1, not_number);
TruncateHeapNumberToI(result, object);
bind(&done);
}
void MacroAssembler::GetLeastBitsFromSmi(Register dst, Register src,
int num_least_bits) {
#if V8_TARGET_ARCH_PPC64
rldicl(dst, src, kBitsPerPointer - kSmiShift,
kBitsPerPointer - num_least_bits);
#else
rlwinm(dst, src, kBitsPerPointer - kSmiShift,
kBitsPerPointer - num_least_bits, 31);
#endif
}
void MacroAssembler::GetLeastBitsFromInt32(Register dst, Register src,
int num_least_bits) {
rlwinm(dst, src, 0, 32 - num_least_bits, 31);
}
void MacroAssembler::CallRuntime(const Runtime::Function* f, int num_arguments,
SaveFPRegsMode save_doubles) {
// All parameters are on the stack. r3 has the return value after call.
// If the expected number of arguments of the runtime function is
// constant, we check that the actual number of arguments match the
// expectation.
CHECK(f->nargs < 0 || f->nargs == num_arguments);
// TODO(1236192): Most runtime routines don't need the number of
// arguments passed in because it is constant. At some point we
// should remove this need and make the runtime routine entry code
// smarter.
mov(r3, Operand(num_arguments));
mov(r4, Operand(ExternalReference(f, isolate())));
CEntryStub stub(isolate(),
#if V8_TARGET_ARCH_PPC64
f->result_size,
#else
1,
#endif
save_doubles);
CallStub(&stub);
}
void MacroAssembler::CallExternalReference(const ExternalReference& ext,
int num_arguments) {
mov(r3, Operand(num_arguments));
mov(r4, Operand(ext));
CEntryStub stub(isolate(), 1);
CallStub(&stub);
}
void MacroAssembler::TailCallExternalReference(const ExternalReference& ext,
int num_arguments,
int result_size) {
// TODO(1236192): Most runtime routines don't need the number of
// arguments passed in because it is constant. At some point we
// should remove this need and make the runtime routine entry code
// smarter.
mov(r3, Operand(num_arguments));
JumpToExternalReference(ext);
}
void MacroAssembler::TailCallRuntime(Runtime::FunctionId fid, int num_arguments,
int result_size) {
TailCallExternalReference(ExternalReference(fid, isolate()), num_arguments,
result_size);
}
void MacroAssembler::JumpToExternalReference(const ExternalReference& builtin) {
mov(r4, Operand(builtin));
CEntryStub stub(isolate(), 1);
Jump(stub.GetCode(), RelocInfo::CODE_TARGET);
}
void MacroAssembler::InvokeBuiltin(Builtins::JavaScript id, InvokeFlag flag,
const CallWrapper& call_wrapper) {
// You can't call a builtin without a valid frame.
DCHECK(flag == JUMP_FUNCTION || has_frame());
GetBuiltinEntry(ip, id);
if (flag == CALL_FUNCTION) {
call_wrapper.BeforeCall(CallSize(ip));
CallJSEntry(ip);
call_wrapper.AfterCall();
} else {
DCHECK(flag == JUMP_FUNCTION);
JumpToJSEntry(ip);
}
}
void MacroAssembler::GetBuiltinFunction(Register target,
Builtins::JavaScript id) {
// Load the builtins object into target register.
LoadP(target,
MemOperand(cp, Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX)));
LoadP(target, FieldMemOperand(target, GlobalObject::kBuiltinsOffset));
// Load the JavaScript builtin function from the builtins object.
LoadP(target,
FieldMemOperand(target, JSBuiltinsObject::OffsetOfFunctionWithId(id)),
r0);
}
void MacroAssembler::GetBuiltinEntry(Register target, Builtins::JavaScript id) {
DCHECK(!target.is(r4));
GetBuiltinFunction(r4, id);
// Load the code entry point from the builtins object.
LoadP(target, FieldMemOperand(r4, JSFunction::kCodeEntryOffset));
}
void MacroAssembler::SetCounter(StatsCounter* counter, int value,
Register scratch1, Register scratch2) {
if (FLAG_native_code_counters && counter->Enabled()) {
mov(scratch1, Operand(value));
mov(scratch2, Operand(ExternalReference(counter)));
stw(scratch1, MemOperand(scratch2));
}
}
void MacroAssembler::IncrementCounter(StatsCounter* counter, int value,
Register scratch1, Register scratch2) {
DCHECK(value > 0);
if (FLAG_native_code_counters && counter->Enabled()) {
mov(scratch2, Operand(ExternalReference(counter)));
lwz(scratch1, MemOperand(scratch2));
addi(scratch1, scratch1, Operand(value));
stw(scratch1, MemOperand(scratch2));
}
}
void MacroAssembler::DecrementCounter(StatsCounter* counter, int value,
Register scratch1, Register scratch2) {
DCHECK(value > 0);
if (FLAG_native_code_counters && counter->Enabled()) {
mov(scratch2, Operand(ExternalReference(counter)));
lwz(scratch1, MemOperand(scratch2));
subi(scratch1, scratch1, Operand(value));
stw(scratch1, MemOperand(scratch2));
}
}
void MacroAssembler::Assert(Condition cond, BailoutReason reason,
CRegister cr) {
if (emit_debug_code()) Check(cond,</