Commit 347fa906 authored by oth's avatar oth Committed by Commit bot

[Interpreter] Basic flow control.

+ Add bytecodes for conditional and unconditional jumps.
+ Add bytecodes for test/compare operations.
+ Expose jumps in bytecode-array-builder and add BytecodeLabel class for
  identifying jump targets.
+ Add support for if..then...else in the bytecode-generator.
+ Implement jump bytecodes in the interpreter. Test/compare operations
  dependent on runtime call for comparisons.

BUG=v8:4280
LOG=N

Review URL: https://codereview.chromium.org/1343363002

Cr-Commit-Position: refs/heads/master@{#30918}
parent fac9e220
...@@ -332,6 +332,108 @@ void BytecodeGraphBuilder::VisitMod( ...@@ -332,6 +332,108 @@ void BytecodeGraphBuilder::VisitMod(
} }
void BytecodeGraphBuilder::VisitTestEqual(
const interpreter::BytecodeArrayIterator& iterator) {
UNIMPLEMENTED();
}
void BytecodeGraphBuilder::VisitTestNotEqual(
const interpreter::BytecodeArrayIterator& iterator) {
UNIMPLEMENTED();
}
void BytecodeGraphBuilder::VisitTestEqualStrict(
const interpreter::BytecodeArrayIterator& iterator) {
UNIMPLEMENTED();
}
void BytecodeGraphBuilder::VisitTestNotEqualStrict(
const interpreter::BytecodeArrayIterator& iterator) {
UNIMPLEMENTED();
}
void BytecodeGraphBuilder::VisitTestLessThan(
const interpreter::BytecodeArrayIterator& iterator) {
UNIMPLEMENTED();
}
void BytecodeGraphBuilder::VisitTestGreaterThan(
const interpreter::BytecodeArrayIterator& iterator) {
UNIMPLEMENTED();
}
void BytecodeGraphBuilder::VisitTestLessThanEqual(
const interpreter::BytecodeArrayIterator& iterator) {
UNIMPLEMENTED();
}
void BytecodeGraphBuilder::VisitTestGreaterThanEqual(
const interpreter::BytecodeArrayIterator& iterator) {
UNIMPLEMENTED();
}
void BytecodeGraphBuilder::VisitTestIn(
const interpreter::BytecodeArrayIterator& iterator) {
UNIMPLEMENTED();
}
void BytecodeGraphBuilder::VisitTestInstanceOf(
const interpreter::BytecodeArrayIterator& iterator) {
UNIMPLEMENTED();
}
void BytecodeGraphBuilder::VisitToBoolean(
const interpreter::BytecodeArrayIterator& ToBoolean) {
UNIMPLEMENTED();
}
void BytecodeGraphBuilder::VisitJump(
const interpreter::BytecodeArrayIterator& iterator) {
UNIMPLEMENTED();
}
void BytecodeGraphBuilder::VisitJumpConstant(
const interpreter::BytecodeArrayIterator& iterator) {
UNIMPLEMENTED();
}
void BytecodeGraphBuilder::VisitJumpIfTrue(
const interpreter::BytecodeArrayIterator& iterator) {
UNIMPLEMENTED();
}
void BytecodeGraphBuilder::VisitJumpIfTrueConstant(
const interpreter::BytecodeArrayIterator& iterator) {
UNIMPLEMENTED();
}
void BytecodeGraphBuilder::VisitJumpIfFalse(
const interpreter::BytecodeArrayIterator& iterator) {
UNIMPLEMENTED();
}
void BytecodeGraphBuilder::VisitJumpIfFalseConstant(
const interpreter::BytecodeArrayIterator& iterator) {
UNIMPLEMENTED();
}
void BytecodeGraphBuilder::VisitReturn( void BytecodeGraphBuilder::VisitReturn(
const interpreter::BytecodeArrayIterator& iterator) { const interpreter::BytecodeArrayIterator& iterator) {
Node* control = Node* control =
......
...@@ -32,7 +32,7 @@ InterpreterAssembler::InterpreterAssembler(Isolate* isolate, Zone* zone, ...@@ -32,7 +32,7 @@ InterpreterAssembler::InterpreterAssembler(Isolate* isolate, Zone* zone,
isolate, new (zone) Graph(zone), isolate, new (zone) Graph(zone),
Linkage::GetInterpreterDispatchDescriptor(zone), kMachPtr, Linkage::GetInterpreterDispatchDescriptor(zone), kMachPtr,
InstructionSelector::SupportedMachineOperatorFlags())), InstructionSelector::SupportedMachineOperatorFlags())),
end_node_(nullptr), end_nodes_(zone),
accumulator_( accumulator_(
raw_assembler_->Parameter(Linkage::kInterpreterAccumulatorParameter)), raw_assembler_->Parameter(Linkage::kInterpreterAccumulatorParameter)),
code_generated_(false) {} code_generated_(false) {}
...@@ -193,6 +193,11 @@ Node* InterpreterAssembler::HeapConstant(Handle<HeapObject> object) { ...@@ -193,6 +193,11 @@ Node* InterpreterAssembler::HeapConstant(Handle<HeapObject> object) {
} }
Node* InterpreterAssembler::BooleanConstant(bool value) {
return raw_assembler_->BooleanConstant(value);
}
Node* InterpreterAssembler::SmiShiftBitsConstant() { Node* InterpreterAssembler::SmiShiftBitsConstant() {
return Int32Constant(kSmiShiftSize + kSmiTagSize); return Int32Constant(kSmiShiftSize + kSmiTagSize);
} }
...@@ -348,7 +353,7 @@ void InterpreterAssembler::Return() { ...@@ -348,7 +353,7 @@ void InterpreterAssembler::Return() {
Node* tail_call = raw_assembler_->TailCallN( Node* tail_call = raw_assembler_->TailCallN(
call_descriptor(), exit_trampoline_code_object, args); call_descriptor(), exit_trampoline_code_object, args);
// This should always be the end node. // This should always be the end node.
SetEndInput(tail_call); AddEndInput(tail_call);
} }
...@@ -357,8 +362,31 @@ Node* InterpreterAssembler::Advance(int delta) { ...@@ -357,8 +362,31 @@ Node* InterpreterAssembler::Advance(int delta) {
} }
Node* InterpreterAssembler::Advance(Node* delta) {
return raw_assembler_->IntPtrAdd(BytecodeOffset(), delta);
}
void InterpreterAssembler::Jump(Node* delta) { DispatchTo(Advance(delta)); }
void InterpreterAssembler::JumpIfWordEqual(Node* lhs, Node* rhs, Node* delta) {
RawMachineAssembler::Label match, no_match;
Node* condition = raw_assembler_->WordEqual(lhs, rhs);
raw_assembler_->Branch(condition, &match, &no_match);
raw_assembler_->Bind(&match);
DispatchTo(Advance(delta));
raw_assembler_->Bind(&no_match);
Dispatch();
}
void InterpreterAssembler::Dispatch() { void InterpreterAssembler::Dispatch() {
Node* new_bytecode_offset = Advance(interpreter::Bytecodes::Size(bytecode_)); DispatchTo(Advance(interpreter::Bytecodes::Size(bytecode_)));
}
void InterpreterAssembler::DispatchTo(Node* new_bytecode_offset) {
Node* target_bytecode = raw_assembler_->Load( Node* target_bytecode = raw_assembler_->Load(
kMachUint8, BytecodeArrayTaggedPointer(), new_bytecode_offset); kMachUint8, BytecodeArrayTaggedPointer(), new_bytecode_offset);
...@@ -385,20 +413,21 @@ void InterpreterAssembler::Dispatch() { ...@@ -385,20 +413,21 @@ void InterpreterAssembler::Dispatch() {
Node* tail_call = Node* tail_call =
raw_assembler_->TailCallN(call_descriptor(), target_code_object, args); raw_assembler_->TailCallN(call_descriptor(), target_code_object, args);
// This should always be the end node. // This should always be the end node.
SetEndInput(tail_call); AddEndInput(tail_call);
} }
void InterpreterAssembler::SetEndInput(Node* input) { void InterpreterAssembler::AddEndInput(Node* input) {
DCHECK(!end_node_); DCHECK_NOT_NULL(input);
end_node_ = input; end_nodes_.push_back(input);
} }
void InterpreterAssembler::End() { void InterpreterAssembler::End() {
DCHECK(end_node_); DCHECK(!end_nodes_.empty());
// TODO(rmcilroy): Support more than 1 end input. int end_count = static_cast<int>(end_nodes_.size());
Node* end = graph()->NewNode(raw_assembler_->common()->End(1), end_node_); Node* end = graph()->NewNode(raw_assembler_->common()->End(end_count),
end_count, &end_nodes_[0]);
graph()->SetEnd(end); graph()->SetEnd(end);
} }
......
...@@ -13,6 +13,7 @@ ...@@ -13,6 +13,7 @@
#include "src/frames.h" #include "src/frames.h"
#include "src/interpreter/bytecodes.h" #include "src/interpreter/bytecodes.h"
#include "src/runtime/runtime.h" #include "src/runtime/runtime.h"
#include "src/zone-containers.h"
namespace v8 { namespace v8 {
namespace internal { namespace internal {
...@@ -68,6 +69,7 @@ class InterpreterAssembler { ...@@ -68,6 +69,7 @@ class InterpreterAssembler {
Node* IntPtrConstant(intptr_t value); Node* IntPtrConstant(intptr_t value);
Node* NumberConstant(double value); Node* NumberConstant(double value);
Node* HeapConstant(Handle<HeapObject> object); Node* HeapConstant(Handle<HeapObject> object);
Node* BooleanConstant(bool value);
// Tag and untag Smi values. // Tag and untag Smi values.
Node* SmiTag(Node* value); Node* SmiTag(Node* value);
...@@ -107,6 +109,13 @@ class InterpreterAssembler { ...@@ -107,6 +109,13 @@ class InterpreterAssembler {
Node* CallRuntime(Runtime::FunctionId function_id, Node* arg1); Node* CallRuntime(Runtime::FunctionId function_id, Node* arg1);
Node* CallRuntime(Runtime::FunctionId function_id, Node* arg1, Node* arg2); Node* CallRuntime(Runtime::FunctionId function_id, Node* arg1, Node* arg2);
// Jump relative to the current bytecode by |jump_offset|.
void Jump(Node* jump_offset);
// Jump relative to the current bytecode by |jump_offset| if the
// word values |lhs| and |rhs| are equal.
void JumpIfWordEqual(Node* lhs, Node* rhs, Node* jump_offset);
// Returns from the function. // Returns from the function.
void Return(); void Return();
...@@ -147,9 +156,13 @@ class InterpreterAssembler { ...@@ -147,9 +156,13 @@ class InterpreterAssembler {
// Returns BytecodeOffset() advanced by delta bytecodes. Note: this does not // Returns BytecodeOffset() advanced by delta bytecodes. Note: this does not
// update BytecodeOffset() itself. // update BytecodeOffset() itself.
Node* Advance(int delta); Node* Advance(int delta);
Node* Advance(Node* delta);
// Starts next instruction dispatch at |new_bytecode_offset|.
void DispatchTo(Node* new_bytecode_offset);
// Sets the end node of the graph. // Adds an end node of the graph.
void SetEndInput(Node* input); void AddEndInput(Node* input);
// Private helpers which delegate to RawMachineAssembler. // Private helpers which delegate to RawMachineAssembler.
Isolate* isolate(); Isolate* isolate();
...@@ -158,7 +171,7 @@ class InterpreterAssembler { ...@@ -158,7 +171,7 @@ class InterpreterAssembler {
interpreter::Bytecode bytecode_; interpreter::Bytecode bytecode_;
base::SmartPointer<RawMachineAssembler> raw_assembler_; base::SmartPointer<RawMachineAssembler> raw_assembler_;
Node* end_node_; ZoneVector<Node*> end_nodes_;
Node* accumulator_; Node* accumulator_;
bool code_generated_; bool code_generated_;
......
...@@ -153,6 +153,7 @@ Node* RawMachineAssembler::TailCallN(CallDescriptor* desc, Node* function, ...@@ -153,6 +153,7 @@ Node* RawMachineAssembler::TailCallN(CallDescriptor* desc, Node* function,
buffer[index++] = graph()->start(); buffer[index++] = graph()->start();
Node* tail_call = MakeNode(common()->TailCall(desc), input_count, buffer); Node* tail_call = MakeNode(common()->TailCall(desc), input_count, buffer);
schedule()->AddTailCall(CurrentBlock(), tail_call); schedule()->AddTailCall(CurrentBlock(), tail_call);
current_block_ = nullptr;
return tail_call; return tail_call;
} }
......
...@@ -73,8 +73,7 @@ class RawMachineAssembler { ...@@ -73,8 +73,7 @@ class RawMachineAssembler {
// hence will not switch the current basic block. // hence will not switch the current basic block.
Node* UndefinedConstant() { Node* UndefinedConstant() {
Handle<HeapObject> undefined = isolate()->factory()->undefined_value(); return HeapConstant(isolate()->factory()->undefined_value());
return AddNode(common()->HeapConstant(undefined));
} }
// Constants. // Constants.
...@@ -104,6 +103,10 @@ class RawMachineAssembler { ...@@ -104,6 +103,10 @@ class RawMachineAssembler {
Node* HeapConstant(Handle<HeapObject> object) { Node* HeapConstant(Handle<HeapObject> object) {
return AddNode(common()->HeapConstant(object)); return AddNode(common()->HeapConstant(object));
} }
Node* BooleanConstant(bool value) {
Handle<Object> object = isolate()->factory()->ToBoolean(value);
return HeapConstant(Handle<HeapObject>::cast(object));
}
Node* ExternalConstant(ExternalReference address) { Node* ExternalConstant(ExternalReference address) {
return AddNode(common()->ExternalConstant(address)); return AddNode(common()->ExternalConstant(address));
} }
......
...@@ -12,6 +12,9 @@ BytecodeArrayBuilder::BytecodeArrayBuilder(Isolate* isolate, Zone* zone) ...@@ -12,6 +12,9 @@ BytecodeArrayBuilder::BytecodeArrayBuilder(Isolate* isolate, Zone* zone)
: isolate_(isolate), : isolate_(isolate),
bytecodes_(zone), bytecodes_(zone),
bytecode_generated_(false), bytecode_generated_(false),
last_block_end_(0),
last_bytecode_start_(~0),
return_seen_in_block_(false),
constants_map_(isolate->heap(), zone), constants_map_(isolate->heap(), zone),
constants_(zone), constants_(zone),
parameter_count_(-1), parameter_count_(-1),
...@@ -37,14 +40,6 @@ void BytecodeArrayBuilder::set_parameter_count(int number_of_parameters) { ...@@ -37,14 +40,6 @@ void BytecodeArrayBuilder::set_parameter_count(int number_of_parameters) {
int BytecodeArrayBuilder::parameter_count() const { return parameter_count_; } int BytecodeArrayBuilder::parameter_count() const { return parameter_count_; }
bool BytecodeArrayBuilder::HasExplicitReturn() {
// TODO(rmcilroy): When we have control flow we should return false here if
// there is an outstanding jump target, even if the last bytecode is kReturn.
return !bytecodes_.empty() &&
bytecodes_.back() == Bytecodes::ToByte(Bytecode::kReturn);
}
Register BytecodeArrayBuilder::Parameter(int parameter_index) { Register BytecodeArrayBuilder::Parameter(int parameter_index) {
DCHECK_GE(parameter_index, 0); DCHECK_GE(parameter_index, 0);
DCHECK_LT(parameter_index, parameter_count_); DCHECK_LT(parameter_index, parameter_count_);
...@@ -56,6 +51,9 @@ Handle<BytecodeArray> BytecodeArrayBuilder::ToBytecodeArray() { ...@@ -56,6 +51,9 @@ Handle<BytecodeArray> BytecodeArrayBuilder::ToBytecodeArray() {
DCHECK_EQ(bytecode_generated_, false); DCHECK_EQ(bytecode_generated_, false);
DCHECK_GE(parameter_count_, 0); DCHECK_GE(parameter_count_, 0);
DCHECK_GE(local_register_count_, 0); DCHECK_GE(local_register_count_, 0);
EnsureReturn();
int bytecode_size = static_cast<int>(bytecodes_.size()); int bytecode_size = static_cast<int>(bytecodes_.size());
int register_count = local_register_count_ + temporary_register_count_; int register_count = local_register_count_ + temporary_register_count_;
int frame_size = register_count * kPointerSize; int frame_size = register_count * kPointerSize;
...@@ -76,9 +74,57 @@ Handle<BytecodeArray> BytecodeArrayBuilder::ToBytecodeArray() { ...@@ -76,9 +74,57 @@ Handle<BytecodeArray> BytecodeArrayBuilder::ToBytecodeArray() {
} }
BytecodeArrayBuilder& BytecodeArrayBuilder::BinaryOperation(Token::Value binop, template <size_t N>
void BytecodeArrayBuilder::Output(uint8_t(&bytes)[N]) {
DCHECK_EQ(Bytecodes::NumberOfOperands(Bytecodes::FromByte(bytes[0])), N - 1);
last_bytecode_start_ = bytecodes()->size();
for (int i = 1; i < static_cast<int>(N); i++) {
DCHECK(OperandIsValid(Bytecodes::FromByte(bytes[0]), i - 1, bytes[i]));
}
bytecodes()->insert(bytecodes()->end(), bytes, bytes + N);
}
void BytecodeArrayBuilder::Output(Bytecode bytecode, uint8_t operand0,
uint8_t operand1, uint8_t operand2) {
uint8_t bytes[] = {Bytecodes::ToByte(bytecode), operand0, operand1, operand2};
Output(bytes);
}
void BytecodeArrayBuilder::Output(Bytecode bytecode, uint8_t operand0,
uint8_t operand1) {
uint8_t bytes[] = {Bytecodes::ToByte(bytecode), operand0, operand1};
Output(bytes);
}
void BytecodeArrayBuilder::Output(Bytecode bytecode, uint8_t operand0) {
uint8_t bytes[] = {Bytecodes::ToByte(bytecode), operand0};
Output(bytes);
}
void BytecodeArrayBuilder::Output(Bytecode bytecode) {
uint8_t bytes[] = {Bytecodes::ToByte(bytecode)};
Output(bytes);
}
BytecodeArrayBuilder& BytecodeArrayBuilder::BinaryOperation(Token::Value op,
Register reg) { Register reg) {
Output(BytecodeForBinaryOperation(binop), reg.ToOperand()); Output(BytecodeForBinaryOperation(op), reg.ToOperand());
return *this;
}
BytecodeArrayBuilder& BytecodeArrayBuilder::CompareOperation(
Token::Value op, Register reg, LanguageMode language_mode) {
if (!is_sloppy(language_mode)) {
UNIMPLEMENTED();
}
Output(BytecodeForCompareOperation(op), reg.ToOperand());
return *this; return *this;
} }
...@@ -99,7 +145,7 @@ BytecodeArrayBuilder& BytecodeArrayBuilder::LoadLiteral( ...@@ -99,7 +145,7 @@ BytecodeArrayBuilder& BytecodeArrayBuilder::LoadLiteral(
BytecodeArrayBuilder& BytecodeArrayBuilder::LoadLiteral(Handle<Object> object) { BytecodeArrayBuilder& BytecodeArrayBuilder::LoadLiteral(Handle<Object> object) {
size_t entry = GetConstantPoolEntry(object); size_t entry = GetConstantPoolEntry(object);
if (FitsInByteOperand(entry)) { if (FitsInIdxOperand(entry)) {
Output(Bytecode::kLdaConstant, static_cast<uint8_t>(entry)); Output(Bytecode::kLdaConstant, static_cast<uint8_t>(entry));
} else { } else {
UNIMPLEMENTED(); UNIMPLEMENTED();
...@@ -154,7 +200,7 @@ BytecodeArrayBuilder& BytecodeArrayBuilder::StoreAccumulatorInRegister( ...@@ -154,7 +200,7 @@ BytecodeArrayBuilder& BytecodeArrayBuilder::StoreAccumulatorInRegister(
BytecodeArrayBuilder& BytecodeArrayBuilder::LoadGlobal(int slot_index) { BytecodeArrayBuilder& BytecodeArrayBuilder::LoadGlobal(int slot_index) {
DCHECK(slot_index >= 0); DCHECK(slot_index >= 0);
if (FitsInByteOperand(slot_index)) { if (FitsInIdxOperand(slot_index)) {
Output(Bytecode::kLdaGlobal, static_cast<uint8_t>(slot_index)); Output(Bytecode::kLdaGlobal, static_cast<uint8_t>(slot_index));
} else { } else {
UNIMPLEMENTED(); UNIMPLEMENTED();
...@@ -168,7 +214,7 @@ BytecodeArrayBuilder& BytecodeArrayBuilder::LoadNamedProperty( ...@@ -168,7 +214,7 @@ BytecodeArrayBuilder& BytecodeArrayBuilder::LoadNamedProperty(
UNIMPLEMENTED(); UNIMPLEMENTED();
} }
if (FitsInByteOperand(feedback_slot)) { if (FitsInIdxOperand(feedback_slot)) {
Output(Bytecode::kLoadIC, object.ToOperand(), Output(Bytecode::kLoadIC, object.ToOperand(),
static_cast<uint8_t>(feedback_slot)); static_cast<uint8_t>(feedback_slot));
} else { } else {
...@@ -184,7 +230,7 @@ BytecodeArrayBuilder& BytecodeArrayBuilder::LoadKeyedProperty( ...@@ -184,7 +230,7 @@ BytecodeArrayBuilder& BytecodeArrayBuilder::LoadKeyedProperty(
UNIMPLEMENTED(); UNIMPLEMENTED();
} }
if (FitsInByteOperand(feedback_slot)) { if (FitsInIdxOperand(feedback_slot)) {
Output(Bytecode::kKeyedLoadIC, object.ToOperand(), Output(Bytecode::kKeyedLoadIC, object.ToOperand(),
static_cast<uint8_t>(feedback_slot)); static_cast<uint8_t>(feedback_slot));
} else { } else {
...@@ -201,7 +247,7 @@ BytecodeArrayBuilder& BytecodeArrayBuilder::StoreNamedProperty( ...@@ -201,7 +247,7 @@ BytecodeArrayBuilder& BytecodeArrayBuilder::StoreNamedProperty(
UNIMPLEMENTED(); UNIMPLEMENTED();
} }
if (FitsInByteOperand(feedback_slot)) { if (FitsInIdxOperand(feedback_slot)) {
Output(Bytecode::kStoreIC, object.ToOperand(), name.ToOperand(), Output(Bytecode::kStoreIC, object.ToOperand(), name.ToOperand(),
static_cast<uint8_t>(feedback_slot)); static_cast<uint8_t>(feedback_slot));
} else { } else {
...@@ -218,7 +264,7 @@ BytecodeArrayBuilder& BytecodeArrayBuilder::StoreKeyedProperty( ...@@ -218,7 +264,7 @@ BytecodeArrayBuilder& BytecodeArrayBuilder::StoreKeyedProperty(
UNIMPLEMENTED(); UNIMPLEMENTED();
} }
if (FitsInByteOperand(feedback_slot)) { if (FitsInIdxOperand(feedback_slot)) {
Output(Bytecode::kKeyedStoreIC, object.ToOperand(), key.ToOperand(), Output(Bytecode::kKeyedStoreIC, object.ToOperand(), key.ToOperand(),
static_cast<uint8_t>(feedback_slot)); static_cast<uint8_t>(feedback_slot));
} else { } else {
...@@ -228,16 +274,179 @@ BytecodeArrayBuilder& BytecodeArrayBuilder::StoreKeyedProperty( ...@@ -228,16 +274,179 @@ BytecodeArrayBuilder& BytecodeArrayBuilder::StoreKeyedProperty(
} }
BytecodeArrayBuilder& BytecodeArrayBuilder::CastAccumulatorToBoolean() {
if (LastBytecodeInSameBlock()) {
// If the previous bytecode puts a boolean in the accumulator
// there is no need to emit an instruction.
switch (Bytecodes::FromByte(bytecodes()->at(last_bytecode_start_))) {
case Bytecode::kToBoolean:
UNREACHABLE();
case Bytecode::kLdaTrue:
case Bytecode::kLdaFalse:
case Bytecode::kTestEqual:
case Bytecode::kTestNotEqual:
case Bytecode::kTestEqualStrict:
case Bytecode::kTestNotEqualStrict:
case Bytecode::kTestLessThan:
case Bytecode::kTestLessThanEqual:
case Bytecode::kTestGreaterThan:
case Bytecode::kTestGreaterThanEqual:
case Bytecode::kTestInstanceOf:
case Bytecode::kTestIn:
break;
default:
Output(Bytecode::kToBoolean);
}
}
return *this;
}
BytecodeArrayBuilder& BytecodeArrayBuilder::Bind(BytecodeLabel* label) {
if (label->is_forward_target()) {
// An earlier jump instruction refers to this label. Update it's location.
PatchJump(bytecodes()->end(), bytecodes()->begin() + label->offset());
// Now treat as if the label will only be back referred to.
}
label->bind_to(bytecodes()->size());
return *this;
}
// static
bool BytecodeArrayBuilder::IsJumpWithImm8Operand(Bytecode jump_bytecode) {
return jump_bytecode == Bytecode::kJump ||
jump_bytecode == Bytecode::kJumpIfTrue ||
jump_bytecode == Bytecode::kJumpIfFalse;
}
// static
Bytecode BytecodeArrayBuilder::GetJumpWithConstantOperand(
Bytecode jump_bytecode) {
switch (jump_bytecode) {
case Bytecode::kJump:
return Bytecode::kJumpConstant;
case Bytecode::kJumpIfTrue:
return Bytecode::kJumpIfTrueConstant;
case Bytecode::kJumpIfFalse:
return Bytecode::kJumpIfFalseConstant;
default:
UNREACHABLE();
return Bytecode::kJumpConstant;
}
}
void BytecodeArrayBuilder::PatchJump(
const ZoneVector<uint8_t>::iterator& jump_target,
ZoneVector<uint8_t>::iterator jump_location) {
Bytecode jump_bytecode = Bytecodes::FromByte(*jump_location);
int delta = static_cast<int>(jump_target - jump_location);
DCHECK(IsJumpWithImm8Operand(jump_bytecode));
DCHECK_EQ(Bytecodes::Size(jump_bytecode), 2);
DCHECK_GE(delta, 0);
if (FitsInImm8Operand(delta)) {
// Just update the operand
jump_location++;
*jump_location = static_cast<uint8_t>(delta);
} else {
// Update the jump type and operand
size_t entry = GetConstantPoolEntry(handle(Smi::FromInt(delta), isolate()));
if (FitsInIdxOperand(entry)) {
*jump_location++ =
Bytecodes::ToByte(GetJumpWithConstantOperand(jump_bytecode));
*jump_location = static_cast<uint8_t>(entry);
} else {
// TODO(oth): OutputJump should reserve a constant pool entry
// when jump is written. The reservation should be used here if
// needed, or cancelled if not. This is due to the patch needing
// to match the size of the code it's replacing. In future,
// there will probably be a jump with 32-bit operand for cases
// when constant pool is full, but that needs to be emitted in
// OutputJump too.
UNIMPLEMENTED();
}
}
}
BytecodeArrayBuilder& BytecodeArrayBuilder::OutputJump(Bytecode jump_bytecode,
BytecodeLabel* label) {
int delta;
if (label->is_bound()) {
// Label has been bound already so this is a backwards jump.
CHECK_GE(bytecodes()->size(), label->offset());
CHECK_LE(bytecodes()->size(), static_cast<size_t>(kMaxInt));
size_t abs_delta = bytecodes()->size() - label->offset();
delta = -static_cast<int>(abs_delta);
} else {
// Label has not yet been bound so this is a forward reference
// that will be patched when the label is bound.
label->set_referrer(bytecodes()->size());
delta = 0;
}
if (FitsInImm8Operand(delta)) {
Output(jump_bytecode, static_cast<uint8_t>(delta));
} else {
size_t entry = GetConstantPoolEntry(handle(Smi::FromInt(delta), isolate()));
if (FitsInIdxOperand(entry)) {
Output(GetJumpWithConstantOperand(jump_bytecode),
static_cast<uint8_t>(entry));
} else {
UNIMPLEMENTED();
}
}
return *this;
}
BytecodeArrayBuilder& BytecodeArrayBuilder::Jump(BytecodeLabel* label) {
return OutputJump(Bytecode::kJump, label);
}
BytecodeArrayBuilder& BytecodeArrayBuilder::JumpIfTrue(BytecodeLabel* label) {
return OutputJump(Bytecode::kJumpIfTrue, label);
}
BytecodeArrayBuilder& BytecodeArrayBuilder::JumpIfFalse(BytecodeLabel* label) {
return OutputJump(Bytecode::kJumpIfFalse, label);
}
BytecodeArrayBuilder& BytecodeArrayBuilder::Return() { BytecodeArrayBuilder& BytecodeArrayBuilder::Return() {
Output(Bytecode::kReturn); Output(Bytecode::kReturn);
return_seen_in_block_ = true;
return *this; return *this;
} }
BytecodeArrayBuilder& BytecodeArrayBuilder::EnterBlock() { return *this; }
BytecodeArrayBuilder& BytecodeArrayBuilder::LeaveBlock() {
last_block_end_ = bytecodes()->size();
return_seen_in_block_ = false;
return *this;
}
void BytecodeArrayBuilder::EnsureReturn() {
if (!return_seen_in_block_) {
LoadUndefined();
Return();
}
}
BytecodeArrayBuilder& BytecodeArrayBuilder::Call(Register callable, BytecodeArrayBuilder& BytecodeArrayBuilder::Call(Register callable,
Register receiver, Register receiver,
size_t arg_count) { size_t arg_count) {
if (FitsInByteOperand(arg_count)) { if (FitsInIdxOperand(arg_count)) {
Output(Bytecode::kCall, callable.ToOperand(), receiver.ToOperand(), Output(Bytecode::kCall, callable.ToOperand(), receiver.ToOperand(),
static_cast<uint8_t>(arg_count)); static_cast<uint8_t>(arg_count));
} else { } else {
...@@ -308,42 +517,9 @@ bool BytecodeArrayBuilder::OperandIsValid(Bytecode bytecode, int operand_index, ...@@ -308,42 +517,9 @@ bool BytecodeArrayBuilder::OperandIsValid(Bytecode bytecode, int operand_index,
return false; return false;
} }
bool BytecodeArrayBuilder::LastBytecodeInSameBlock() const {
void BytecodeArrayBuilder::Output(Bytecode bytecode, uint8_t operand0, return last_bytecode_start_ < bytecodes()->size() &&
uint8_t operand1, uint8_t operand2) { last_bytecode_start_ >= last_block_end_;
DCHECK_EQ(Bytecodes::NumberOfOperands(bytecode), 3);
DCHECK(OperandIsValid(bytecode, 0, operand0) &&
OperandIsValid(bytecode, 1, operand1) &&
OperandIsValid(bytecode, 2, operand2));
bytecodes_.push_back(Bytecodes::ToByte(bytecode));
bytecodes_.push_back(operand0);
bytecodes_.push_back(operand1);
bytecodes_.push_back(operand2);
}
void BytecodeArrayBuilder::Output(Bytecode bytecode, uint8_t operand0,
uint8_t operand1) {
DCHECK_EQ(Bytecodes::NumberOfOperands(bytecode), 2);
DCHECK(OperandIsValid(bytecode, 0, operand0) &&
OperandIsValid(bytecode, 1, operand1));
bytecodes_.push_back(Bytecodes::ToByte(bytecode));
bytecodes_.push_back(operand0);
bytecodes_.push_back(operand1);
}
void BytecodeArrayBuilder::Output(Bytecode bytecode, uint8_t operand0) {
DCHECK_EQ(Bytecodes::NumberOfOperands(bytecode), 1);
DCHECK(OperandIsValid(bytecode, 0, operand0));
bytecodes_.push_back(Bytecodes::ToByte(bytecode));
bytecodes_.push_back(operand0);
}
void BytecodeArrayBuilder::Output(Bytecode bytecode) {
DCHECK_EQ(Bytecodes::NumberOfOperands(bytecode), 0);
bytecodes_.push_back(Bytecodes::ToByte(bytecode));
} }
...@@ -361,21 +537,57 @@ Bytecode BytecodeArrayBuilder::BytecodeForBinaryOperation(Token::Value op) { ...@@ -361,21 +537,57 @@ Bytecode BytecodeArrayBuilder::BytecodeForBinaryOperation(Token::Value op) {
case Token::Value::MOD: case Token::Value::MOD:
return Bytecode::kMod; return Bytecode::kMod;
default: default:
UNIMPLEMENTED(); UNREACHABLE();
return static_cast<Bytecode>(-1); return static_cast<Bytecode>(-1);
} }
} }
// static // static
bool BytecodeArrayBuilder::FitsInByteOperand(int value) { Bytecode BytecodeArrayBuilder::BytecodeForCompareOperation(Token::Value op) {
return 0 <= value && value <= 255; switch (op) {
case Token::Value::EQ:
return Bytecode::kTestEqual;
case Token::Value::NE:
return Bytecode::kTestNotEqual;
case Token::Value::EQ_STRICT:
return Bytecode::kTestEqualStrict;
case Token::Value::NE_STRICT:
return Bytecode::kTestNotEqualStrict;
case Token::Value::LT:
return Bytecode::kTestLessThan;
case Token::Value::GT:
return Bytecode::kTestGreaterThan;
case Token::Value::LTE:
return Bytecode::kTestLessThanEqual;
case Token::Value::GTE:
return Bytecode::kTestGreaterThanEqual;
case Token::Value::INSTANCEOF:
return Bytecode::kTestInstanceOf;
case Token::Value::IN:
return Bytecode::kTestIn;
default:
UNREACHABLE();
return static_cast<Bytecode>(-1);
}
}
// static
bool BytecodeArrayBuilder::FitsInIdxOperand(int value) {
return kMinUInt8 <= value && value <= kMaxUInt8;
}
// static
bool BytecodeArrayBuilder::FitsInIdxOperand(size_t value) {
return value <= static_cast<size_t>(kMaxUInt8);
} }
// static // static
bool BytecodeArrayBuilder::FitsInByteOperand(size_t value) { bool BytecodeArrayBuilder::FitsInImm8Operand(int value) {
return value <= 255; return kMinInt8 <= value && value < kMaxInt8;
} }
......
...@@ -20,6 +20,7 @@ class Isolate; ...@@ -20,6 +20,7 @@ class Isolate;
namespace interpreter { namespace interpreter {
class BytecodeLabel;
class Register; class Register;
class BytecodeArrayBuilder { class BytecodeArrayBuilder {
...@@ -35,9 +36,6 @@ class BytecodeArrayBuilder { ...@@ -35,9 +36,6 @@ class BytecodeArrayBuilder {
void set_locals_count(int number_of_locals); void set_locals_count(int number_of_locals);
int locals_count() const; int locals_count() const;
// Returns true if the bytecode has an explicit return at the end.
bool HasExplicitReturn();
Register Parameter(int parameter_index); Register Parameter(int parameter_index);
// Constant loads to accumulator. // Constant loads to accumulator.
...@@ -77,33 +75,69 @@ class BytecodeArrayBuilder { ...@@ -77,33 +75,69 @@ class BytecodeArrayBuilder {
BytecodeArrayBuilder& Call(Register callable, Register receiver, BytecodeArrayBuilder& Call(Register callable, Register receiver,
size_t arg_count); size_t arg_count);
// Operators. // Operators (register == lhs, accumulator = rhs).
BytecodeArrayBuilder& BinaryOperation(Token::Value binop, Register reg); BytecodeArrayBuilder& BinaryOperation(Token::Value binop, Register reg);
// Tests.
BytecodeArrayBuilder& CompareOperation(Token::Value op, Register reg,
LanguageMode language_mode);
// Casts
BytecodeArrayBuilder& CastAccumulatorToBoolean();
// Flow Control. // Flow Control.
BytecodeArrayBuilder& Bind(BytecodeLabel* label);
BytecodeArrayBuilder& Jump(BytecodeLabel* label);
BytecodeArrayBuilder& JumpIfTrue(BytecodeLabel* label);
BytecodeArrayBuilder& JumpIfFalse(BytecodeLabel* label);
BytecodeArrayBuilder& Return(); BytecodeArrayBuilder& Return();
BytecodeArrayBuilder& EnterBlock();
BytecodeArrayBuilder& LeaveBlock();
private: private:
static Bytecode BytecodeForBinaryOperation(Token::Value op); ZoneVector<uint8_t>* bytecodes() { return &bytecodes_; }
static bool FitsInByteOperand(int value); const ZoneVector<uint8_t>* bytecodes() const { return &bytecodes_; }
static bool FitsInByteOperand(size_t value); Isolate* isolate() const { return isolate_; }
void Output(Bytecode bytecode, uint8_t r0, uint8_t r1, uint8_t r2); static Bytecode BytecodeForBinaryOperation(Token::Value op);
void Output(Bytecode bytecode, uint8_t r0, uint8_t r1); static Bytecode BytecodeForCompareOperation(Token::Value op);
void Output(Bytecode bytecode, uint8_t r0); static bool FitsInIdxOperand(int value);
static bool FitsInIdxOperand(size_t value);
static bool FitsInImm8Operand(int value);
static bool IsJumpWithImm8Operand(Bytecode jump_bytecode);
static Bytecode GetJumpWithConstantOperand(Bytecode jump_with_smi8_operand);
template <size_t N>
INLINE(void Output(uint8_t(&bytes)[N]));
void Output(Bytecode bytecode, uint8_t operand0, uint8_t operand1,
uint8_t operand2);
void Output(Bytecode bytecode, uint8_t operand0, uint8_t operand1);
void Output(Bytecode bytecode, uint8_t operand0);
void Output(Bytecode bytecode); void Output(Bytecode bytecode);
void PatchJump(const ZoneVector<uint8_t>::iterator& jump_target,
ZoneVector<uint8_t>::iterator jump_location);
BytecodeArrayBuilder& OutputJump(Bytecode jump_bytecode,
BytecodeLabel* label);
void EnsureReturn();
bool OperandIsValid(Bytecode bytecode, int operand_index, bool OperandIsValid(Bytecode bytecode, int operand_index,
uint8_t operand_value) const; uint8_t operand_value) const;
bool LastBytecodeInSameBlock() const;
size_t GetConstantPoolEntry(Handle<Object> object); size_t GetConstantPoolEntry(Handle<Object> object);
// Scope helpers used by TemporaryRegisterScope
int BorrowTemporaryRegister(); int BorrowTemporaryRegister();
void ReturnTemporaryRegister(int reg_index); void ReturnTemporaryRegister(int reg_index);
Isolate* isolate_; Isolate* isolate_;
ZoneVector<uint8_t> bytecodes_; ZoneVector<uint8_t> bytecodes_;
bool bytecode_generated_; bool bytecode_generated_;
size_t last_block_end_;
size_t last_bytecode_start_;
bool return_seen_in_block_;
IdentityMap<size_t> constants_map_; IdentityMap<size_t> constants_map_;
ZoneVector<Handle<Object>> constants_; ZoneVector<Handle<Object>> constants_;
...@@ -117,6 +151,47 @@ class BytecodeArrayBuilder { ...@@ -117,6 +151,47 @@ class BytecodeArrayBuilder {
DISALLOW_IMPLICIT_CONSTRUCTORS(BytecodeArrayBuilder); DISALLOW_IMPLICIT_CONSTRUCTORS(BytecodeArrayBuilder);
}; };
// A label representing a branch target in a bytecode array. When a
// label is bound, it represents a known position in the bytecode
// array. For labels that are forward references there can be at most
// one reference whilst it is unbound.
class BytecodeLabel final {
public:
BytecodeLabel() : bound_(false), offset_(kInvalidOffset) {}
~BytecodeLabel() { DCHECK(bound_ && offset_ != kInvalidOffset); }
private:
static const size_t kInvalidOffset = static_cast<size_t>(-1);
INLINE(void bind_to(size_t offset)) {
DCHECK(!bound_ && offset != kInvalidOffset);
offset_ = offset;
bound_ = true;
}
INLINE(void set_referrer(size_t offset)) {
DCHECK(!bound_ && offset != kInvalidOffset);
offset_ = offset;
}
INLINE(size_t offset() const) { return offset_; }
INLINE(bool is_bound() const) { return bound_; }
INLINE(bool is_forward_target() const) {
return offset() != kInvalidOffset && !is_bound();
}
// There are three states for a label:
// bound_ offset_
// UNSET false kInvalidOffset
// FORWARD_TARGET false Offset of referring jump
// BACKWARD_TARGET true Offset of label in bytecode array when bound
bool bound_;
size_t offset_;
friend class BytecodeArrayBuilder;
DISALLOW_COPY_AND_ASSIGN(BytecodeLabel);
};
// A stack-allocated class than allows the instantiator to allocate // A stack-allocated class than allows the instantiator to allocate
// temporary registers that are cleaned up when scope is closed. // temporary registers that are cleaned up when scope is closed.
class TemporaryRegisterScope { class TemporaryRegisterScope {
......
...@@ -20,6 +20,7 @@ class BytecodeArrayIterator { ...@@ -20,6 +20,7 @@ class BytecodeArrayIterator {
void Advance(); void Advance();
bool done() const; bool done() const;
Bytecode current_bytecode() const; Bytecode current_bytecode() const;
int current_offset() const { return bytecode_offset_; }
const Handle<BytecodeArray>& bytecode_array() const { const Handle<BytecodeArray>& bytecode_array() const {
return bytecode_array_; return bytecode_array_;
} }
......
...@@ -45,13 +45,6 @@ Handle<BytecodeArray> BytecodeGenerator::MakeBytecode(CompilationInfo* info) { ...@@ -45,13 +45,6 @@ Handle<BytecodeArray> BytecodeGenerator::MakeBytecode(CompilationInfo* info) {
// Visit statements in the function body. // Visit statements in the function body.
VisitStatements(info->literal()->body()); VisitStatements(info->literal()->body());
// If the last bytecode wasn't a return, then return 'undefined' to avoid
// falling off the end.
if (!builder_.HasExplicitReturn()) {
builder_.LoadUndefined();
builder_.Return();
}
set_scope(nullptr); set_scope(nullptr);
set_info(nullptr); set_info(nullptr);
return builder_.ToBytecodeArray(); return builder_.ToBytecodeArray();
...@@ -59,6 +52,7 @@ Handle<BytecodeArray> BytecodeGenerator::MakeBytecode(CompilationInfo* info) { ...@@ -59,6 +52,7 @@ Handle<BytecodeArray> BytecodeGenerator::MakeBytecode(CompilationInfo* info) {
void BytecodeGenerator::VisitBlock(Block* node) { void BytecodeGenerator::VisitBlock(Block* node) {
builder().EnterBlock();
if (node->scope() == NULL) { if (node->scope() == NULL) {
// Visit statements in the same scope, no declarations. // Visit statements in the same scope, no declarations.
VisitStatements(node->statements()); VisitStatements(node->statements());
...@@ -71,6 +65,7 @@ void BytecodeGenerator::VisitBlock(Block* node) { ...@@ -71,6 +65,7 @@ void BytecodeGenerator::VisitBlock(Block* node) {
VisitStatements(node->statements()); VisitStatements(node->statements());
} }
} }
builder().LeaveBlock();
} }
...@@ -114,11 +109,26 @@ void BytecodeGenerator::VisitExpressionStatement(ExpressionStatement* stmt) { ...@@ -114,11 +109,26 @@ void BytecodeGenerator::VisitExpressionStatement(ExpressionStatement* stmt) {
void BytecodeGenerator::VisitEmptyStatement(EmptyStatement* stmt) { void BytecodeGenerator::VisitEmptyStatement(EmptyStatement* stmt) {
UNIMPLEMENTED(); // TODO(oth): For control-flow it could be useful to signal empty paths here.
} }
void BytecodeGenerator::VisitIfStatement(IfStatement* stmt) { UNIMPLEMENTED(); } void BytecodeGenerator::VisitIfStatement(IfStatement* stmt) {
BytecodeLabel else_start, else_end;
// TODO(oth): Spot easy cases where there code would not need to
// emit the then block or the else block, e.g. condition is
// obviously true/1/false/0.
Visit(stmt->condition());
builder().CastAccumulatorToBoolean();
builder().JumpIfFalse(&else_start);
Visit(stmt->then_statement());
builder().Jump(&else_end);
builder().Bind(&else_start);
Visit(stmt->else_statement());
builder().Bind(&else_end);
}
void BytecodeGenerator::VisitSloppyBlockFunctionStatement( void BytecodeGenerator::VisitSloppyBlockFunctionStatement(
...@@ -478,7 +488,17 @@ void BytecodeGenerator::VisitBinaryOperation(BinaryOperation* binop) { ...@@ -478,7 +488,17 @@ void BytecodeGenerator::VisitBinaryOperation(BinaryOperation* binop) {
void BytecodeGenerator::VisitCompareOperation(CompareOperation* expr) { void BytecodeGenerator::VisitCompareOperation(CompareOperation* expr) {
UNIMPLEMENTED(); Token::Value op = expr->op();
Expression* left = expr->left();
Expression* right = expr->right();
TemporaryRegisterScope temporary_register_scope(&builder_);
Register temporary = temporary_register_scope.NewRegister();
Visit(left);
builder().StoreAccumulatorInRegister(temporary);
Visit(right);
builder().CompareOperation(op, temporary, language_mode());
} }
......
...@@ -133,7 +133,7 @@ std::ostream& Bytecodes::Decode(std::ostream& os, const uint8_t* bytecode_start, ...@@ -133,7 +133,7 @@ std::ostream& Bytecodes::Decode(std::ostream& os, const uint8_t* bytecode_start,
os << "[" << static_cast<unsigned int>(operand) << "]"; os << "[" << static_cast<unsigned int>(operand) << "]";
break; break;
case interpreter::OperandType::kImm8: case interpreter::OperandType::kImm8:
os << "#" << static_cast<int>(operand); os << "#" << static_cast<int>(static_cast<int8_t>(operand));
break; break;
case interpreter::OperandType::kReg: { case interpreter::OperandType::kReg: {
Register reg = Register::FromOperand(operand); Register reg = Register::FromOperand(operand);
......
...@@ -61,7 +61,28 @@ namespace interpreter { ...@@ -61,7 +61,28 @@ namespace interpreter {
/* Call operations. */ \ /* Call operations. */ \
V(Call, OperandType::kReg, OperandType::kReg, OperandType::kCount) \ V(Call, OperandType::kReg, OperandType::kReg, OperandType::kCount) \
\ \
/* Test Operators */ \
V(TestEqual, OperandType::kReg) \
V(TestNotEqual, OperandType::kReg) \
V(TestEqualStrict, OperandType::kReg) \
V(TestNotEqualStrict, OperandType::kReg) \
V(TestLessThan, OperandType::kReg) \
V(TestGreaterThan, OperandType::kReg) \
V(TestLessThanEqual, OperandType::kReg) \
V(TestGreaterThanEqual, OperandType::kReg) \
V(TestInstanceOf, OperandType::kReg) \
V(TestIn, OperandType::kReg) \
\
/* Cast operators */ \
V(ToBoolean, OperandType::kNone) \
\
/* Control Flow */ \ /* Control Flow */ \
V(Jump, OperandType::kImm8) \
V(JumpConstant, OperandType::kIdx) \
V(JumpIfTrue, OperandType::kImm8) \
V(JumpIfTrueConstant, OperandType::kIdx) \
V(JumpIfFalse, OperandType::kImm8) \
V(JumpIfFalseConstant, OperandType::kIdx) \
V(Return, OperandType::kNone) V(Return, OperandType::kNone)
......
...@@ -294,6 +294,15 @@ void Interpreter::DoBinaryOp(Runtime::FunctionId function_id, ...@@ -294,6 +294,15 @@ void Interpreter::DoBinaryOp(Runtime::FunctionId function_id,
} }
void Interpreter::DoCompareOp(Token::Value op,
compiler::InterpreterAssembler* assembler) {
// TODO(oth): placeholder until compare path fixed.
// The accumulator should be set to true on success (or false otherwise)
// by the comparisons so it can be used for conditional jumps.
DoLdaTrue(assembler);
}
// Add <src> // Add <src>
// //
// Add register <src> to accumulator. // Add register <src> to accumulator.
...@@ -350,6 +359,178 @@ void Interpreter::DoCall(compiler::InterpreterAssembler* assembler) { ...@@ -350,6 +359,178 @@ void Interpreter::DoCall(compiler::InterpreterAssembler* assembler) {
} }
// TestEqual <src>
//
// Test if the value in the <src> register equals the accumulator.
void Interpreter::DoTestEqual(compiler::InterpreterAssembler* assembler) {
DoCompareOp(Token::Value::EQ, assembler);
}
// TestNotEqual <src>
//
// Test if the value in the <src> register is not equal to the accumulator.
void Interpreter::DoTestNotEqual(compiler::InterpreterAssembler* assembler) {
DoCompareOp(Token::Value::NE, assembler);
}
// TestEqualStrict <src>
//
// Test if the value in the <src> register is strictly equal to the accumulator.
void Interpreter::DoTestEqualStrict(compiler::InterpreterAssembler* assembler) {
DoCompareOp(Token::Value::EQ_STRICT, assembler);
}
// TestNotEqualStrict <src>
//
// Test if the value in the <src> register is not strictly equal to the
// accumulator.
void Interpreter::DoTestNotEqualStrict(
compiler::InterpreterAssembler* assembler) {
DoCompareOp(Token::Value::NE_STRICT, assembler);
}
// TestLessThan <src>
//
// Test if the value in the <src> register is less than the accumulator.
void Interpreter::DoTestLessThan(compiler::InterpreterAssembler* assembler) {
DoCompareOp(Token::Value::LT, assembler);
}
// TestGreaterThan <src>
//
// Test if the value in the <src> register is greater than the accumulator.
void Interpreter::DoTestGreaterThan(compiler::InterpreterAssembler* assembler) {
DoCompareOp(Token::Value::GT, assembler);
}
// TestLessThanEqual <src>
//
// Test if the value in the <src> register is less than or equal to the
// accumulator.
void Interpreter::DoTestLessThanEqual(
compiler::InterpreterAssembler* assembler) {
DoCompareOp(Token::Value::LTE, assembler);
}
// TestGreaterThanEqual <src>
//
// Test if the value in the <src> register is greater than or equal to the
// accumulator.
void Interpreter::DoTestGreaterThanEqual(
compiler::InterpreterAssembler* assembler) {
DoCompareOp(Token::Value::GTE, assembler);
}
// TestIn <src>
//
// Test if the value in the <src> register is in the collection referenced
// by the accumulator.
void Interpreter::DoTestIn(compiler::InterpreterAssembler* assembler) {
DoCompareOp(Token::Value::IN, assembler);
}
// TestInstanceOf <src>
//
// Test if the object referenced by the <src> register is an an instance of type
// referenced by the accumulator.
void Interpreter::DoTestInstanceOf(compiler::InterpreterAssembler* assembler) {
DoCompareOp(Token::Value::INSTANCEOF, assembler);
}
// ToBoolean
//
// Cast the object referenced by the accumulator to a boolean.
void Interpreter::DoToBoolean(compiler::InterpreterAssembler* assembler) {
// TODO(oth): The next CL for test operations has interpreter specific
// runtime calls. This looks like another candidate.
__ Dispatch();
}
// Jump <imm8>
//
// Jump by number of bytes represented by an immediate operand.
void Interpreter::DoJump(compiler::InterpreterAssembler* assembler) {
Node* relative_jump = __ BytecodeOperandImm8(0);
__ Jump(relative_jump);
}
// JumpConstant <idx>
//
// Jump by number of bytes in the Smi in the |idx| entry in the constant pool.
void Interpreter::DoJumpConstant(compiler::InterpreterAssembler* assembler) {
Node* index = __ BytecodeOperandIdx(0);
Node* constant = __ LoadConstantPoolEntry(index);
Node* relative_jump = __ SmiUntag(constant);
__ Jump(relative_jump);
}
// JumpIfTrue <imm8>
//
// Jump by number of bytes represented by an immediate operand if the
// accumulator contains true.
void Interpreter::DoJumpIfTrue(compiler::InterpreterAssembler* assembler) {
Node* accumulator = __ GetAccumulator();
Node* relative_jump = __ BytecodeOperandImm8(0);
Node* true_value = __ BooleanConstant(true);
__ JumpIfWordEqual(accumulator, true_value, relative_jump);
}
// JumpIfTrueConstant <idx>
//
// Jump by number of bytes in the Smi in the |idx| entry in the constant pool
// if the accumulator contains true.
void Interpreter::DoJumpIfTrueConstant(
compiler::InterpreterAssembler* assembler) {
Node* accumulator = __ GetAccumulator();
Node* index = __ BytecodeOperandIdx(0);
Node* constant = __ LoadConstantPoolEntry(index);
Node* relative_jump = __ SmiUntag(constant);
Node* true_value = __ BooleanConstant(true);
__ JumpIfWordEqual(accumulator, true_value, relative_jump);
}
// JumpIfFalse <imm8>
//
// Jump by number of bytes represented by an immediate operand if the
// accumulator contains false.
void Interpreter::DoJumpIfFalse(compiler::InterpreterAssembler* assembler) {
Node* accumulator = __ GetAccumulator();
Node* relative_jump = __ BytecodeOperandImm8(0);
Node* false_value = __ BooleanConstant(false);
__ JumpIfWordEqual(accumulator, false_value, relative_jump);
}
// JumpIfFalseConstant <idx>
//
// Jump by number of bytes in the Smi in the |idx| entry in the constant pool
// if the accumulator contains false.
void Interpreter::DoJumpIfFalseConstant(
compiler::InterpreterAssembler* assembler) {
Node* accumulator = __ GetAccumulator();
Node* index = __ BytecodeOperandIdx(0);
Node* constant = __ LoadConstantPoolEntry(index);
Node* relative_jump = __ SmiUntag(constant);
Node* false_value = __ BooleanConstant(false);
__ JumpIfWordEqual(accumulator, false_value, relative_jump);
}
// Return // Return
// //
// Return the value in register 0. // Return the value in register 0.
......
...@@ -12,6 +12,7 @@ ...@@ -12,6 +12,7 @@
#include "src/builtins.h" #include "src/builtins.h"
#include "src/interpreter/bytecodes.h" #include "src/interpreter/bytecodes.h"
#include "src/runtime/runtime.h" #include "src/runtime/runtime.h"
#include "src/token.h"
namespace v8 { namespace v8 {
namespace internal { namespace internal {
...@@ -53,6 +54,11 @@ class Interpreter { ...@@ -53,6 +54,11 @@ class Interpreter {
void DoBinaryOp(Runtime::FunctionId function_id, void DoBinaryOp(Runtime::FunctionId function_id,
compiler::InterpreterAssembler* assembler); compiler::InterpreterAssembler* assembler);
// Generates code to perform the comparison operation associated with
// |compare_op|.
void DoCompareOp(Token::Value compare_op,
compiler::InterpreterAssembler* assembler);
// Generates code to perform a property load via |ic|. // Generates code to perform a property load via |ic|.
void DoPropertyLoadIC(Callable ic, compiler::InterpreterAssembler* assembler); void DoPropertyLoadIC(Callable ic, compiler::InterpreterAssembler* assembler);
......
...@@ -72,9 +72,9 @@ struct ExpectedSnippet { ...@@ -72,9 +72,9 @@ struct ExpectedSnippet {
int frame_size; int frame_size;
int parameter_count; int parameter_count;
int bytecode_length; int bytecode_length;
const uint8_t bytecode[32]; const uint8_t bytecode[512];
int constant_count; int constant_count;
T constants[16]; T constants[4];
}; };
...@@ -95,6 +95,11 @@ static void CheckConstant(const char* expected, Object* actual) { ...@@ -95,6 +95,11 @@ static void CheckConstant(const char* expected, Object* actual) {
} }
static void CheckConstant(Handle<Object> expected, Object* actual) {
CHECK(actual == *expected || expected->StrictEquals(actual));
}
template <typename T> template <typename T>
static void CheckBytecodeArrayEqual(struct ExpectedSnippet<T> expected, static void CheckBytecodeArrayEqual(struct ExpectedSnippet<T> expected,
Handle<BytecodeArray> actual, Handle<BytecodeArray> actual,
...@@ -166,8 +171,7 @@ TEST(PrimitiveReturnStatements) { ...@@ -166,8 +171,7 @@ TEST(PrimitiveReturnStatements) {
{"return -128;", 0, 1, 3, {B(LdaSmi8), U8(-128), B(Return)}, 0}, {"return -128;", 0, 1, 3, {B(LdaSmi8), U8(-128), B(Return)}, 0},
}; };
size_t num_snippets = sizeof(snippets) / sizeof(snippets[0]); for (size_t i = 0; i < arraysize(snippets); i++) {
for (size_t i = 0; i < num_snippets; i++) {
Handle<BytecodeArray> bytecode_array = Handle<BytecodeArray> bytecode_array =
helper.MakeBytecodeForFunctionBody(snippets[i].code_snippet); helper.MakeBytecodeForFunctionBody(snippets[i].code_snippet);
CheckBytecodeArrayEqual(snippets[i], bytecode_array); CheckBytecodeArrayEqual(snippets[i], bytecode_array);
...@@ -208,8 +212,7 @@ TEST(PrimitiveExpressions) { ...@@ -208,8 +212,7 @@ TEST(PrimitiveExpressions) {
0 0
}}; }};
size_t num_snippets = sizeof(snippets) / sizeof(snippets[0]); for (size_t i = 0; i < arraysize(snippets); i++) {
for (size_t i = 0; i < num_snippets; i++) {
Handle<BytecodeArray> bytecode_array = Handle<BytecodeArray> bytecode_array =
helper.MakeBytecodeForFunctionBody(snippets[i].code_snippet); helper.MakeBytecodeForFunctionBody(snippets[i].code_snippet);
CheckBytecodeArrayEqual(snippets[i], bytecode_array); CheckBytecodeArrayEqual(snippets[i], bytecode_array);
...@@ -234,8 +237,7 @@ TEST(Parameters) { ...@@ -234,8 +237,7 @@ TEST(Parameters) {
0, 8, 3, {B(Ldar), R(helper.kLastParamIndex - 7), B(Return)}, 0} 0, 8, 3, {B(Ldar), R(helper.kLastParamIndex - 7), B(Return)}, 0}
}; };
size_t num_snippets = sizeof(snippets) / sizeof(snippets[0]); for (size_t i = 0; i < arraysize(snippets); i++) {
for (size_t i = 0; i < num_snippets; i++) {
Handle<BytecodeArray> bytecode_array = Handle<BytecodeArray> bytecode_array =
helper.MakeBytecodeForFunction(snippets[i].code_snippet); helper.MakeBytecodeForFunction(snippets[i].code_snippet);
CheckBytecodeArrayEqual(snippets[i], bytecode_array); CheckBytecodeArrayEqual(snippets[i], bytecode_array);
...@@ -243,122 +245,145 @@ TEST(Parameters) { ...@@ -243,122 +245,145 @@ TEST(Parameters) {
} }
TEST(Constants) { TEST(IntegerConstants) {
InitializedHandleScope handle_scope; InitializedHandleScope handle_scope;
BytecodeGeneratorHelper helper; BytecodeGeneratorHelper helper;
// Check large SMIs. ExpectedSnippet<int> snippets[] = {
{ {"return 12345678;",
ExpectedSnippet<int> snippets[] = { 0,
{"return 12345678;", 0, 1, 3, 1,
{ 3,
B(LdaConstant), U8(0), {
B(Return) B(LdaConstant), U8(0), //
}, 1, { 12345678 } B(Return) //
}, },
{"var a = 1234; return 5678;", 1 * kPointerSize, 1, 7, 1,
{ {12345678}},
B(LdaConstant), U8(0), {"var a = 1234; return 5678;",
B(Star), R(0), 1 * kPointerSize,
B(LdaConstant), U8(1), 1,
B(Return) 7,
}, 2, { 1234, 5678 } {
}, B(LdaConstant), U8(0), //
{"var a = 1234; return 1234;", B(Star), R(0), //
1 * kPointerSize, 1, 7, B(LdaConstant), U8(1), //
{ B(Return) //
B(LdaConstant), U8(0), },
B(Star), R(0), 2,
B(LdaConstant), U8(0), {1234, 5678}},
B(Return) {"var a = 1234; return 1234;",
}, 1, { 1234 } 1 * kPointerSize,
} 1,
}; 7,
{
B(LdaConstant), U8(0), //
B(Star), R(0), //
B(LdaConstant), U8(0), //
B(Return) //
},
1,
{1234}}};
size_t num_snippets = sizeof(snippets) / sizeof(snippets[0]); for (size_t i = 0; i < arraysize(snippets); i++) {
for (size_t i = 0; i < num_snippets; i++) { Handle<BytecodeArray> bytecode_array =
Handle<BytecodeArray> bytecode_array = helper.MakeBytecodeForFunctionBody(snippets[i].code_snippet);
helper.MakeBytecodeForFunctionBody(snippets[i].code_snippet);
CheckBytecodeArrayEqual(snippets[i], bytecode_array); CheckBytecodeArrayEqual(snippets[i], bytecode_array);
}
} }
}
// Check heap number double constants
{
ExpectedSnippet<double> snippets[] = {
{"return 1.2;",
0, 1, 3,
{
B(LdaConstant), U8(0),
B(Return)
}, 1, { 1.2 }
},
{"var a = 1.2; return 2.6;", 1 * kPointerSize, 1, 7,
{
B(LdaConstant), U8(0),
B(Star), R(0),
B(LdaConstant), U8(1),
B(Return)
}, 2, { 1.2, 2.6 }
},
{"var a = 3.14; return 3.14;", 1 * kPointerSize, 1, 7,
{
B(LdaConstant), U8(0),
B(Star), R(0),
B(LdaConstant), U8(1),
B(Return)
}, 2,
// TODO(rmcilroy): Currently multiple identical double literals end up
// being allocated as new HeapNumbers and so require multiple constant
// pool entries. De-dup identical values.
{ 3.14, 3.14 }
}
};
size_t num_snippets = sizeof(snippets) / sizeof(snippets[0]); TEST(HeapNumberConstants) {
for (size_t i = 0; i < num_snippets; i++) { InitializedHandleScope handle_scope;
Handle<BytecodeArray> bytecode_array = BytecodeGeneratorHelper helper;
helper.MakeBytecodeForFunctionBody(snippets[i].code_snippet);
CheckBytecodeArrayEqual(snippets[i], bytecode_array); ExpectedSnippet<double> snippets[] = {
} {"return 1.2;",
0,
1,
3,
{
B(LdaConstant), U8(0), //
B(Return) //
},
1,
{1.2}},
{"var a = 1.2; return 2.6;",
1 * kPointerSize,
1,
7,
{
B(LdaConstant), U8(0), //
B(Star), R(0), //
B(LdaConstant), U8(1), //
B(Return) //
},
2,
{1.2, 2.6}},
{"var a = 3.14; return 3.14;",
1 * kPointerSize,
1,
7,
{
B(LdaConstant), U8(0), //
B(Star), R(0), //
B(LdaConstant), U8(1), //
B(Return) //
},
2,
{3.14, 3.14}}};
for (size_t i = 0; i < arraysize(snippets); i++) {
Handle<BytecodeArray> bytecode_array =
helper.MakeBytecodeForFunctionBody(snippets[i].code_snippet);
CheckBytecodeArrayEqual(snippets[i], bytecode_array);
} }
}
// Check string literals
{
ExpectedSnippet<const char*> snippets[] = {
{"return \"This is a string\";", 0, 1, 3,
{
B(LdaConstant), U8(0),
B(Return)
}, 1,
{ "This is a string" }
},
{"var a = \"First string\"; return \"Second string\";",
1 * kPointerSize, 1, 7,
{
B(LdaConstant), U8(0),
B(Star), R(0),
B(LdaConstant), U8(1),
B(Return)
}, 2, { "First string", "Second string"}
},
{"var a = \"Same string\"; return \"Same string\";",
1 * kPointerSize, 1, 7,
{
B(LdaConstant), U8(0),
B(Star), R(0),
B(LdaConstant), U8(0),
B(Return)
}, 1, { "Same string" }
}
};
size_t num_snippets = sizeof(snippets) / sizeof(snippets[0]); TEST(StringConstants) {
for (size_t i = 0; i < num_snippets; i++) { InitializedHandleScope handle_scope;
Handle<BytecodeArray> bytecode_array = BytecodeGeneratorHelper helper;
helper.MakeBytecodeForFunctionBody(snippets[i].code_snippet);
CheckBytecodeArrayEqual(snippets[i], bytecode_array); ExpectedSnippet<const char*> snippets[] = {
} {"return \"This is a string\";",
0,
1,
3,
{
B(LdaConstant), U8(0), //
B(Return) //
},
1,
{"This is a string"}},
{"var a = \"First string\"; return \"Second string\";",
1 * kPointerSize,
1,
7,
{
B(LdaConstant), U8(0), //
B(Star), R(0), //
B(LdaConstant), U8(1), //
B(Return) //
},
2,
{"First string", "Second string"}},
{"var a = \"Same string\"; return \"Same string\";",
1 * kPointerSize,
1,
7,
{
B(LdaConstant), U8(0), //
B(Star), R(0), //
B(LdaConstant), U8(0), //
B(Return) //
},
1,
{"Same string"}}};
for (size_t i = 0; i < arraysize(snippets); i++) {
Handle<BytecodeArray> bytecode_array =
helper.MakeBytecodeForFunctionBody(snippets[i].code_snippet);
CheckBytecodeArrayEqual(snippets[i], bytecode_array);
} }
} }
...@@ -374,67 +399,75 @@ TEST(PropertyLoads) { ...@@ -374,67 +399,75 @@ TEST(PropertyLoads) {
ExpectedSnippet<const char*> snippets[] = { ExpectedSnippet<const char*> snippets[] = {
{"function f(a) { return a.name; }\nf({name : \"test\"})", {"function f(a) { return a.name; }\nf({name : \"test\"})",
1 * kPointerSize, 2, 10, 1 * kPointerSize,
2,
10,
{ {
B(Ldar), R(helper.kLastParamIndex), B(Ldar), R(helper.kLastParamIndex), //
B(Star), R(0), B(Star), R(0), //
B(LdaConstant), U8(0), B(LdaConstant), U8(0), //
B(LoadIC), R(0), U8(vector->first_ic_slot_index()), B(LoadIC), R(0), U8(vector->first_ic_slot_index()), //
B(Return) B(Return) //
}, },
1, { "name" } 1,
}, {"name"}},
{"function f(a) { return a[\"key\"]; }\nf({key : \"test\"})", {"function f(a) { return a[\"key\"]; }\nf({key : \"test\"})",
1 * kPointerSize, 2, 10, 1 * kPointerSize,
2,
10,
{ {
B(Ldar), R(helper.kLastParamIndex), B(Ldar), R(helper.kLastParamIndex), //
B(Star), R(0), B(Star), R(0), //
B(LdaConstant), U8(0), B(LdaConstant), U8(0), //
B(LoadIC), R(0), U8(vector->first_ic_slot_index()), B(LoadIC), R(0), U8(vector->first_ic_slot_index()), //
B(Return) B(Return) //
}, },
1, { "key" } 1,
}, {"key"}},
{"function f(a) { return a[100]; }\nf({100 : \"test\"})", {"function f(a) { return a[100]; }\nf({100 : \"test\"})",
1 * kPointerSize, 2, 10, 1 * kPointerSize,
2,
10,
{ {
B(Ldar), R(helper.kLastParamIndex), B(Ldar), R(helper.kLastParamIndex), //
B(Star), R(0), B(Star), R(0), //
B(LdaSmi8), U8(100), B(LdaSmi8), U8(100), //
B(KeyedLoadIC), R(0), U8(vector->first_ic_slot_index()), B(KeyedLoadIC), R(0), U8(vector->first_ic_slot_index()), //
B(Return) B(Return) //
}, 0 },
}, 0},
{"function f(a, b) { return a[b]; }\nf({arg : \"test\"}, \"arg\")", {"function f(a, b) { return a[b]; }\nf({arg : \"test\"}, \"arg\")",
1 * kPointerSize, 3, 10, 1 * kPointerSize,
3,
10,
{ {
B(Ldar), R(helper.kLastParamIndex - 1), B(Ldar), R(helper.kLastParamIndex - 1), //
B(Star), R(0), B(Star), R(0), //
B(Ldar), R(helper.kLastParamIndex), B(Ldar), R(helper.kLastParamIndex), //
B(KeyedLoadIC), R(0), U8(vector->first_ic_slot_index()), B(KeyedLoadIC), R(0), U8(vector->first_ic_slot_index()), //
B(Return) B(Return) //
}, 0 },
}, 0},
{"function f(a) { var b = a.name; return a[-124]; }\n" {"function f(a) { var b = a.name; return a[-124]; }\n"
"f({\"-124\" : \"test\", name : 123 })", "f({\"-124\" : \"test\", name : 123 })",
2 * kPointerSize, 2, 21, 2 * kPointerSize,
2,
21,
{ {
B(Ldar), R(helper.kLastParamIndex), B(Ldar), R(helper.kLastParamIndex), //
B(Star), R(1), B(Star), R(1), //
B(LdaConstant), U8(0), B(LdaConstant), U8(0), //
B(LoadIC), R(1), U8(vector->first_ic_slot_index()), B(LoadIC), R(1), U8(vector->first_ic_slot_index()), //
B(Star), R(0), B(Star), R(0), //
B(Ldar), R(helper.kLastParamIndex), B(Ldar), R(helper.kLastParamIndex), //
B(Star), R(1), B(Star), R(1), //
B(LdaSmi8), U8(-124), B(LdaSmi8), U8(-124), //
B(KeyedLoadIC), R(1), U8(vector->first_ic_slot_index() + 2), B(KeyedLoadIC), R(1), U8(vector->first_ic_slot_index() + 2), //
B(Return) B(Return) //
}, },
1, { "name" } 1,
} {"name"}}};
}; for (size_t i = 0; i < arraysize(snippets); i++) {
size_t num_snippets = sizeof(snippets) / sizeof(snippets[0]);
for (size_t i = 0; i < num_snippets; i++) {
Handle<BytecodeArray> bytecode_array = Handle<BytecodeArray> bytecode_array =
helper.MakeBytecode(snippets[i].code_snippet, "f"); helper.MakeBytecode(snippets[i].code_snippet, "f");
CheckBytecodeArrayEqual(snippets[i], bytecode_array); CheckBytecodeArrayEqual(snippets[i], bytecode_array);
...@@ -453,82 +486,90 @@ TEST(PropertyStores) { ...@@ -453,82 +486,90 @@ TEST(PropertyStores) {
ExpectedSnippet<const char*> snippets[] = { ExpectedSnippet<const char*> snippets[] = {
{"function f(a) { a.name = \"val\"; }\nf({name : \"test\"})", {"function f(a) { a.name = \"val\"; }\nf({name : \"test\"})",
2 * kPointerSize, 2, 16, 2 * kPointerSize,
2,
16,
{ {
B(Ldar), R(helper.kLastParamIndex), B(Ldar), R(helper.kLastParamIndex), //
B(Star), R(0), B(Star), R(0), //
B(LdaConstant), U8(0), B(LdaConstant), U8(0), //
B(Star), R(1), B(Star), R(1), //
B(LdaConstant), U8(1), B(LdaConstant), U8(1), //
B(StoreIC), R(0), R(1), U8(vector->first_ic_slot_index()), B(StoreIC), R(0), R(1), U8(vector->first_ic_slot_index()), //
B(LdaUndefined), B(LdaUndefined), //
B(Return) B(Return) //
}, },
2, { "name", "val" } 2,
}, {"name", "val"}},
{"function f(a) { a[\"key\"] = \"val\"; }\nf({key : \"test\"})", {"function f(a) { a[\"key\"] = \"val\"; }\nf({key : \"test\"})",
2 * kPointerSize, 2, 16, 2 * kPointerSize,
2,
16,
{ {
B(Ldar), R(helper.kLastParamIndex), B(Ldar), R(helper.kLastParamIndex), //
B(Star), R(0), B(Star), R(0), //
B(LdaConstant), U8(0), B(LdaConstant), U8(0), //
B(Star), R(1), B(Star), R(1), //
B(LdaConstant), U8(1), B(LdaConstant), U8(1), //
B(StoreIC), R(0), R(1), U8(vector->first_ic_slot_index()), B(StoreIC), R(0), R(1), U8(vector->first_ic_slot_index()), //
B(LdaUndefined), B(LdaUndefined), //
B(Return) B(Return) //
}, },
2, { "key", "val" } 2,
}, {"key", "val"}},
{"function f(a) { a[100] = \"val\"; }\nf({100 : \"test\"})", {"function f(a) { a[100] = \"val\"; }\nf({100 : \"test\"})",
2 * kPointerSize, 2, 16, 2 * kPointerSize,
2,
16,
{ {
B(Ldar), R(helper.kLastParamIndex), B(Ldar), R(helper.kLastParamIndex), //
B(Star), R(0), B(Star), R(0), //
B(LdaSmi8), U8(100), B(LdaSmi8), U8(100), //
B(Star), R(1), B(Star), R(1), //
B(LdaConstant), U8(0), B(LdaConstant), U8(0), //
B(KeyedStoreIC), R(0), R(1), U8(vector->first_ic_slot_index()), B(KeyedStoreIC), R(0), R(1), U8(vector->first_ic_slot_index()), //
B(LdaUndefined), B(LdaUndefined), //
B(Return) B(Return) //
}, },
1, { "val" } 1,
}, {"val"}},
{"function f(a, b) { a[b] = \"val\"; }\nf({arg : \"test\"}, \"arg\")", {"function f(a, b) { a[b] = \"val\"; }\nf({arg : \"test\"}, \"arg\")",
2 * kPointerSize, 3, 16, 2 * kPointerSize,
3,
16,
{ {
B(Ldar), R(helper.kLastParamIndex - 1), B(Ldar), R(helper.kLastParamIndex - 1), //
B(Star), R(0), B(Star), R(0), //
B(Ldar), R(helper.kLastParamIndex), B(Ldar), R(helper.kLastParamIndex), //
B(Star), R(1), B(Star), R(1), //
B(LdaConstant), U8(0), B(LdaConstant), U8(0), //
B(KeyedStoreIC), R(0), R(1), U8(vector->first_ic_slot_index()), B(KeyedStoreIC), R(0), R(1), U8(vector->first_ic_slot_index()), //
B(LdaUndefined), B(LdaUndefined), //
B(Return) B(Return) //
}, },
1, { "val" } 1,
}, {"val"}},
{"function f(a) { a.name = a[-124]; }\n" {"function f(a) { a.name = a[-124]; }\n"
"f({\"-124\" : \"test\", name : 123 })", "f({\"-124\" : \"test\", name : 123 })",
3 * kPointerSize, 2, 23, 3 * kPointerSize,
2,
23,
{ {
B(Ldar), R(helper.kLastParamIndex), B(Ldar), R(helper.kLastParamIndex), //
B(Star), R(0), B(Star), R(0), //
B(LdaConstant), U8(0), B(LdaConstant), U8(0), //
B(Star), R(1), B(Star), R(1), //
B(Ldar), R(helper.kLastParamIndex), B(Ldar), R(helper.kLastParamIndex), //
B(Star), R(2), B(Star), R(2), //
B(LdaSmi8), U8(-124), B(LdaSmi8), U8(-124), //
B(KeyedLoadIC), R(2), U8(vector->first_ic_slot_index()), B(KeyedLoadIC), R(2), U8(vector->first_ic_slot_index()), //
B(StoreIC), R(0), R(1), U8(vector->first_ic_slot_index() + 2), B(StoreIC), R(0), R(1), U8(vector->first_ic_slot_index() + 2), //
B(LdaUndefined), B(LdaUndefined), //
B(Return) B(Return) //
}, },
1, { "name" } 1,
} {"name"}}};
}; for (size_t i = 0; i < arraysize(snippets); i++) {
size_t num_snippets = sizeof(snippets) / sizeof(snippets[0]);
for (size_t i = 0; i < num_snippets; i++) {
Handle<BytecodeArray> bytecode_array = Handle<BytecodeArray> bytecode_array =
helper.MakeBytecode(snippets[i].code_snippet, "f"); helper.MakeBytecode(snippets[i].code_snippet, "f");
CheckBytecodeArrayEqual(snippets[i], bytecode_array); CheckBytecodeArrayEqual(snippets[i], bytecode_array);
...@@ -541,7 +582,7 @@ TEST(PropertyStores) { ...@@ -541,7 +582,7 @@ TEST(PropertyStores) {
TEST(PropertyCall) { TEST(PropertyCall) {
InitializedHandleScope handle_scope; InitializedHandleScope handle_scope;
BytecodeGeneratorHelper helper; BytecodeGeneratorHelper helper; //
Code::Kind ic_kinds[] = { i::Code::LOAD_IC, i::Code::LOAD_IC }; Code::Kind ic_kinds[] = { i::Code::LOAD_IC, i::Code::LOAD_IC };
FeedbackVectorSpec feedback_spec(0, 2, ic_kinds); FeedbackVectorSpec feedback_spec(0, 2, ic_kinds);
...@@ -550,58 +591,62 @@ TEST(PropertyCall) { ...@@ -550,58 +591,62 @@ TEST(PropertyCall) {
ExpectedSnippet<const char*> snippets[] = { ExpectedSnippet<const char*> snippets[] = {
{"function f(a) { return a.func(); }\nf(" FUNC_ARG ")", {"function f(a) { return a.func(); }\nf(" FUNC_ARG ")",
2 * kPointerSize, 2, 16, 2 * kPointerSize,
2,
16,
{ {
B(Ldar), R(helper.kLastParamIndex), B(Ldar), R(helper.kLastParamIndex), //
B(Star), R(1), B(Star), R(1), //
B(LdaConstant), U8(0), B(LdaConstant), U8(0), //
B(LoadIC), R(1), U8(vector->first_ic_slot_index() + 2), B(LoadIC), R(1), U8(vector->first_ic_slot_index() + 2), //
B(Star), R(0), B(Star), R(0), //
B(Call), R(0), R(1), U8(0), B(Call), R(0), R(1), U8(0), //
B(Return) B(Return) //
}, },
1, { "func" } 1,
}, {"func"}},
{"function f(a, b, c) { return a.func(b, c); }\nf(" FUNC_ARG ", 1, 2)", {"function f(a, b, c) { return a.func(b, c); }\nf(" FUNC_ARG ", 1, 2)",
4 * kPointerSize, 4, 24, 4 * kPointerSize,
4,
24,
{ {
B(Ldar), R(helper.kLastParamIndex - 2), B(Ldar), R(helper.kLastParamIndex - 2), //
B(Star), R(1), B(Star), R(1), //
B(LdaConstant), U8(0), B(LdaConstant), U8(0), //
B(LoadIC), R(1), U8(vector->first_ic_slot_index() + 2), B(LoadIC), R(1), U8(vector->first_ic_slot_index() + 2), //
B(Star), R(0), B(Star), R(0), //
B(Ldar), R(helper.kLastParamIndex - 1), B(Ldar), R(helper.kLastParamIndex - 1), //
B(Star), R(2), B(Star), R(2), //
B(Ldar), R(helper.kLastParamIndex), B(Ldar), R(helper.kLastParamIndex), //
B(Star), R(3), B(Star), R(3), //
B(Call), R(0), R(1), U8(2), B(Call), R(0), R(1), U8(2), //
B(Return) B(Return) //
}, },
1, { "func" } 1,
}, {"func"}},
{"function f(a, b) { return a.func(b + b, b); }\nf(" FUNC_ARG ", 1)", {"function f(a, b) { return a.func(b + b, b); }\nf(" FUNC_ARG ", 1)",
4 * kPointerSize, 3, 30, 4 * kPointerSize,
{ 3,
B(Ldar), R(helper.kLastParamIndex - 1), 30,
B(Star), R(1), {
B(LdaConstant), U8(0), B(Ldar), R(helper.kLastParamIndex - 1), //
B(LoadIC), R(1), U8(vector->first_ic_slot_index() + 2), B(Star), R(1), //
B(Star), R(0), B(LdaConstant), U8(0), //
B(Ldar), R(helper.kLastParamIndex), B(LoadIC), R(1), U8(vector->first_ic_slot_index() + 2), //
B(Star), R(2), B(Star), R(0), //
B(Ldar), R(helper.kLastParamIndex), B(Ldar), R(helper.kLastParamIndex), //
B(Add), R(2), B(Star), R(2), //
B(Star), R(2), B(Ldar), R(helper.kLastParamIndex), //
B(Ldar), R(helper.kLastParamIndex), B(Add), R(2), //
B(Star), R(3), B(Star), R(2), //
B(Call), R(0), R(1), U8(2), B(Ldar), R(helper.kLastParamIndex), //
B(Return) B(Star), R(3), //
B(Call), R(0), R(1), U8(2), //
B(Return) //
}, },
1, { "func" } 1,
} {"func"}}};
}; for (size_t i = 0; i < arraysize(snippets); i++) {
size_t num_snippets = sizeof(snippets) / sizeof(snippets[0]);
for (size_t i = 0; i < num_snippets; i++) {
Handle<BytecodeArray> bytecode_array = Handle<BytecodeArray> bytecode_array =
helper.MakeBytecode(snippets[i].code_snippet, "f"); helper.MakeBytecode(snippets[i].code_snippet, "f");
CheckBytecodeArrayEqual(snippets[i], bytecode_array); CheckBytecodeArrayEqual(snippets[i], bytecode_array);
...@@ -630,8 +675,7 @@ TEST(LoadGlobal) { ...@@ -630,8 +675,7 @@ TEST(LoadGlobal) {
}, },
}; };
size_t num_snippets = sizeof(snippets) / sizeof(snippets[0]); for (size_t i = 0; i < arraysize(snippets); i++) {
for (size_t i = 0; i < num_snippets; i++) {
Handle<BytecodeArray> bytecode_array = Handle<BytecodeArray> bytecode_array =
helper.MakeBytecode(snippets[i].code_snippet, "f"); helper.MakeBytecode(snippets[i].code_snippet, "f");
bytecode_array->Print(); bytecode_array->Print();
...@@ -675,14 +719,162 @@ TEST(CallGlobal) { ...@@ -675,14 +719,162 @@ TEST(CallGlobal) {
}, },
}; };
size_t num_snippets = sizeof(snippets) / sizeof(snippets[0]); for (size_t i = 0; i < arraysize(snippets); i++) {
for (size_t i = 0; i < num_snippets; i++) {
Handle<BytecodeArray> bytecode_array = Handle<BytecodeArray> bytecode_array =
helper.MakeBytecode(snippets[i].code_snippet, "f"); helper.MakeBytecode(snippets[i].code_snippet, "f");
CheckBytecodeArrayEqual(snippets[i], bytecode_array, true); CheckBytecodeArrayEqual(snippets[i], bytecode_array, true);
} }
} }
TEST(IfConditions) {
InitializedHandleScope handle_scope;
BytecodeGeneratorHelper helper;
Handle<Object> unused = helper.factory()->undefined_value();
ExpectedSnippet<Handle<Object>> snippets[] = {
{"function f() { if (0) { return 1; } else { return -1; } }",
0,
1,
14,
{B(LdaZero), //
B(ToBoolean), //
B(JumpIfFalse), U8(7), //
B(LdaSmi8), U8(1), //
B(Return), //
B(Jump), U8(5), // TODO(oth): Unreachable jump after return
B(LdaSmi8), U8(-1), //
B(Return), //
B(LdaUndefined), //
B(Return)}, //
0,
{unused, unused, unused, unused}},
{"function f() { if ('lucky') { return 1; } else { return -1; } }",
0,
1,
15,
{B(LdaConstant), U8(0), //
B(ToBoolean), //
B(JumpIfFalse), U8(7), //
B(LdaSmi8), U8(1), //
B(Return), //
B(Jump), U8(5), // TODO(oth): Unreachable jump after return
B(LdaSmi8), U8(-1), //
B(Return), //
B(LdaUndefined), //
B(Return)}, //
1,
{helper.factory()->NewStringFromStaticChars("lucky"), unused,
unused, unused}},
{"function f() { if (false) { return 1; } else { return -1; } }",
0,
1,
13,
{B(LdaFalse), //
B(JumpIfFalse), U8(7), //
B(LdaSmi8), U8(1), //
B(Return), //
B(Jump), U8(5), // TODO(oth): Unreachable jump after return
B(LdaSmi8), U8(-1), //
B(Return), //
B(LdaUndefined), //
B(Return)}, //
0,
{unused, unused, unused, unused}},
{"function f(a) { if (a <= 0) { return 200; } else { return -200; } }",
kPointerSize,
2,
19,
{B(Ldar), R(-5), //
B(Star), R(0), //
B(LdaZero), //
B(TestLessThanEqual), R(0), //
B(JumpIfFalse), U8(7), //
B(LdaConstant), U8(0), //
B(Return), //
B(Jump), U8(5), // TODO(oth): Unreachable jump after return
B(LdaConstant), U8(1), //
B(Return), //
B(LdaUndefined), //
B(Return)}, //
2,
{helper.factory()->NewNumberFromInt(200),
helper.factory()->NewNumberFromInt(-200), unused, unused}},
{"function f(a, b) { if (a in b) { return 200; } }",
kPointerSize,
3,
17,
{B(Ldar), R(-6), //
B(Star), R(0), //
B(Ldar), R(-5), //
B(TestIn), R(0), //
B(JumpIfFalse), U8(7), //
B(LdaConstant), U8(0), //
B(Return), //
B(Jump), U8(2), // TODO(oth): Unreachable jump after return
B(LdaUndefined), //
B(Return)}, //
1,
{helper.factory()->NewNumberFromInt(200), unused, unused, unused}},
{"function f(a, b) { if (a instanceof b) { return 200; } }",
kPointerSize,
3,
17,
{B(Ldar), R(-6), //
B(Star), R(0), //
B(Ldar), R(-5), //
B(TestInstanceOf), R(0), //
B(JumpIfFalse), U8(7), //
B(LdaConstant), U8(0), //
B(Return), //
B(Jump), U8(2), // TODO(oth): Unreachable jump after return
B(LdaUndefined), //
B(Return)}, //
1,
{helper.factory()->NewNumberFromInt(200), unused, unused, unused}},
{"function f(z) { var a = 0; var b = 0; if (a === 0.01) { "
#define X "b = a; a = b; "
X X X X X X X X X X X X X X X X X X X X X X X X
#undef X
" return 200; } else { return -200; } }",
3 * kPointerSize,
2,
218,
{B(LdaZero), //
B(Star), R(0), //
B(LdaZero), //
B(Star), R(1), //
B(Ldar), R(0), //
B(Star), R(2), //
B(LdaConstant), U8(0), //
B(TestEqualStrict), R(2), //
B(JumpIfFalseConstant), U8(2), //
#define X B(Ldar), R(0), B(Star), R(1), B(Ldar), R(1), B(Star), R(0),
X X X X X X X X X X X X X X X X X X X X X X X X
#undef X
B(LdaConstant),
U8(1), //
B(Return), //
B(Jump), U8(5), // TODO(oth): Unreachable jump after return
B(LdaConstant), U8(3), //
B(Return), //
B(LdaUndefined), //
B(Return)}, //
4,
{helper.factory()->NewHeapNumber(0.01),
helper.factory()->NewNumberFromInt(200),
helper.factory()->NewNumberFromInt(199),
helper.factory()->NewNumberFromInt(-200)}}};
for (size_t i = 0; i < arraysize(snippets); i++) {
Handle<BytecodeArray> bytecode_array =
helper.MakeBytecodeForFunction(snippets[i].code_snippet);
CheckBytecodeArrayEqual(snippets[i], bytecode_array);
}
}
} // namespace interpreter } // namespace interpreter
} // namespace internal } // namespace internal
} // namespance v8 } // namespance v8
...@@ -891,3 +891,86 @@ TEST(InterpreterCall) { ...@@ -891,3 +891,86 @@ TEST(InterpreterCall) {
CHECK(i::String::cast(*return_val)->Equals(*expected)); CHECK(i::String::cast(*return_val)->Equals(*expected));
} }
} }
static BytecodeArrayBuilder& SetRegister(BytecodeArrayBuilder& builder,
Register reg, int value,
Register scratch) {
return builder.StoreAccumulatorInRegister(scratch)
.LoadLiteral(Smi::FromInt(value))
.StoreAccumulatorInRegister(reg)
.LoadAccumulatorWithRegister(scratch);
}
static BytecodeArrayBuilder& IncrementRegister(BytecodeArrayBuilder& builder,
Register reg, int value,
Register scratch) {
return builder.StoreAccumulatorInRegister(scratch)
.LoadLiteral(Smi::FromInt(value))
.BinaryOperation(Token::Value::ADD, reg)
.StoreAccumulatorInRegister(reg)
.LoadAccumulatorWithRegister(scratch);
}
TEST(InterpreterJumps) {
HandleAndZoneScope handles;
BytecodeArrayBuilder builder(handles.main_isolate(), handles.main_zone());
builder.set_locals_count(2);
builder.set_parameter_count(0);
Register reg(0), scratch(1);
BytecodeLabel label[3];
builder.LoadLiteral(Smi::FromInt(0))
.StoreAccumulatorInRegister(reg)
.Jump(&label[1]);
SetRegister(builder, reg, 1024, scratch).Bind(&label[0]);
IncrementRegister(builder, reg, 1, scratch).Jump(&label[2]);
SetRegister(builder, reg, 2048, scratch).Bind(&label[1]);
IncrementRegister(builder, reg, 2, scratch).Jump(&label[0]);
SetRegister(builder, reg, 4096, scratch).Bind(&label[2]);
IncrementRegister(builder, reg, 4, scratch)
.LoadAccumulatorWithRegister(reg)
.Return();
Handle<BytecodeArray> bytecode_array = builder.ToBytecodeArray();
InterpreterTester tester(handles.main_isolate(), bytecode_array);
auto callable = tester.GetCallable<>();
Handle<Object> return_value = callable().ToHandleChecked();
CHECK_EQ(Smi::cast(*return_value)->value(), 7);
}
TEST(InterpreterConditionalJumps) {
HandleAndZoneScope handles;
BytecodeArrayBuilder builder(handles.main_isolate(), handles.main_zone());
builder.set_locals_count(2);
builder.set_parameter_count(0);
Register reg(0), scratch(1);
BytecodeLabel label[2];
BytecodeLabel done, done1;
builder.LoadLiteral(Smi::FromInt(0))
.StoreAccumulatorInRegister(reg)
.LoadFalse()
.JumpIfFalse(&label[0]);
IncrementRegister(builder, reg, 1024, scratch)
.Bind(&label[0])
.LoadTrue()
.JumpIfFalse(&done);
IncrementRegister(builder, reg, 1, scratch).LoadTrue().JumpIfTrue(&label[1]);
IncrementRegister(builder, reg, 2048, scratch).Bind(&label[1]);
IncrementRegister(builder, reg, 2, scratch).LoadFalse().JumpIfTrue(&done1);
IncrementRegister(builder, reg, 4, scratch)
.LoadAccumulatorWithRegister(reg)
.Bind(&done)
.Bind(&done1)
.Return();
Handle<BytecodeArray> bytecode_array = builder.ToBytecodeArray();
InterpreterTester tester(handles.main_isolate(), bytecode_array);
auto callable = tester.GetCallable<>();
Handle<Object> return_value = callable().ToHandleChecked();
CHECK_EQ(Smi::cast(*return_value)->value(), 7);
}
...@@ -152,6 +152,89 @@ TARGET_TEST_F(InterpreterAssemblerTest, Dispatch) { ...@@ -152,6 +152,89 @@ TARGET_TEST_F(InterpreterAssemblerTest, Dispatch) {
} }
TARGET_TEST_F(InterpreterAssemblerTest, Jump) {
int jump_offsets[] = {-9710, -77, 0, +3, +97109};
TRACED_FOREACH(int, jump_offset, jump_offsets) {
TRACED_FOREACH(interpreter::Bytecode, bytecode, kBytecodes) {
InterpreterAssemblerForTest m(this, bytecode);
m.Jump(m.Int32Constant(jump_offset));
Graph* graph = m.GetCompletedGraph();
Node* end = graph->end();
EXPECT_EQ(1, end->InputCount());
Node* tail_call_node = end->InputAt(0);
Matcher<Node*> next_bytecode_offset_matcher =
IsIntPtrAdd(IsParameter(Linkage::kInterpreterBytecodeOffsetParameter),
IsInt32Constant(jump_offset));
Matcher<Node*> target_bytecode_matcher = m.IsLoad(
kMachUint8, IsParameter(Linkage::kInterpreterBytecodeArrayParameter),
next_bytecode_offset_matcher);
Matcher<Node*> code_target_matcher = m.IsLoad(
kMachPtr, IsParameter(Linkage::kInterpreterDispatchTableParameter),
IsWord32Shl(target_bytecode_matcher,
IsInt32Constant(kPointerSizeLog2)));
EXPECT_EQ(CallDescriptor::kCallCodeObject, m.call_descriptor()->kind());
EXPECT_TRUE(m.call_descriptor()->flags() & CallDescriptor::kCanUseRoots);
EXPECT_THAT(
tail_call_node,
IsTailCall(m.call_descriptor(), code_target_matcher,
IsParameter(Linkage::kInterpreterAccumulatorParameter),
IsParameter(Linkage::kInterpreterRegisterFileParameter),
next_bytecode_offset_matcher,
IsParameter(Linkage::kInterpreterBytecodeArrayParameter),
IsParameter(Linkage::kInterpreterDispatchTableParameter),
IsParameter(Linkage::kInterpreterContextParameter),
graph->start(), graph->start()));
}
}
}
TARGET_TEST_F(InterpreterAssemblerTest, JumpIfWordEqual) {
static const int kJumpIfTrueOffset = 73;
MachineOperatorBuilder machine(zone());
TRACED_FOREACH(interpreter::Bytecode, bytecode, kBytecodes) {
InterpreterAssemblerForTest m(this, bytecode);
Node* lhs = m.IntPtrConstant(0);
Node* rhs = m.IntPtrConstant(1);
m.JumpIfWordEqual(lhs, rhs, m.Int32Constant(kJumpIfTrueOffset));
Graph* graph = m.GetCompletedGraph();
Node* end = graph->end();
EXPECT_EQ(2, end->InputCount());
int jump_offsets[] = {kJumpIfTrueOffset,
interpreter::Bytecodes::Size(bytecode)};
for (int i = 0; i < static_cast<int>(arraysize(jump_offsets)); i++) {
Matcher<Node*> next_bytecode_offset_matcher =
IsIntPtrAdd(IsParameter(Linkage::kInterpreterBytecodeOffsetParameter),
IsInt32Constant(jump_offsets[i]));
Matcher<Node*> target_bytecode_matcher = m.IsLoad(
kMachUint8, IsParameter(Linkage::kInterpreterBytecodeArrayParameter),
next_bytecode_offset_matcher);
Matcher<Node*> code_target_matcher = m.IsLoad(
kMachPtr, IsParameter(Linkage::kInterpreterDispatchTableParameter),
IsWord32Shl(target_bytecode_matcher,
IsInt32Constant(kPointerSizeLog2)));
EXPECT_THAT(
end->InputAt(i),
IsTailCall(m.call_descriptor(), code_target_matcher,
IsParameter(Linkage::kInterpreterAccumulatorParameter),
IsParameter(Linkage::kInterpreterRegisterFileParameter),
next_bytecode_offset_matcher,
IsParameter(Linkage::kInterpreterBytecodeArrayParameter),
IsParameter(Linkage::kInterpreterDispatchTableParameter),
IsParameter(Linkage::kInterpreterContextParameter),
graph->start(), graph->start()));
}
// TODO(oth): test control flow paths.
}
}
TARGET_TEST_F(InterpreterAssemblerTest, Return) { TARGET_TEST_F(InterpreterAssemblerTest, Return) {
TRACED_FOREACH(interpreter::Bytecode, bytecode, kBytecodes) { TRACED_FOREACH(interpreter::Bytecode, bytecode, kBytecodes) {
InterpreterAssemblerForTest m(this, bytecode); InterpreterAssemblerForTest m(this, bytecode);
......
...@@ -5,6 +5,7 @@ ...@@ -5,6 +5,7 @@
#include "src/v8.h" #include "src/v8.h"
#include "src/interpreter/bytecode-array-builder.h" #include "src/interpreter/bytecode-array-builder.h"
#include "src/interpreter/bytecode-array-iterator.h"
#include "test/unittests/test-utils.h" #include "test/unittests/test-utils.h"
namespace v8 { namespace v8 {
...@@ -51,14 +52,39 @@ TEST_F(BytecodeArrayBuilderTest, AllBytecodesGenerated) { ...@@ -51,14 +52,39 @@ TEST_F(BytecodeArrayBuilderTest, AllBytecodesGenerated) {
// Call operations. // Call operations.
builder.Call(reg, reg, 0); builder.Call(reg, reg, 0);
// Emit binary operators invocations. // Emit binary operator invocations.
builder.BinaryOperation(Token::Value::ADD, reg) builder.BinaryOperation(Token::Value::ADD, reg)
.BinaryOperation(Token::Value::SUB, reg) .BinaryOperation(Token::Value::SUB, reg)
.BinaryOperation(Token::Value::MUL, reg) .BinaryOperation(Token::Value::MUL, reg)
.BinaryOperation(Token::Value::DIV, reg) .BinaryOperation(Token::Value::DIV, reg)
.BinaryOperation(Token::Value::MOD, reg); .BinaryOperation(Token::Value::MOD, reg);
// Emit test operator invocations.
builder.CompareOperation(Token::Value::EQ, reg, LanguageMode::SLOPPY)
.CompareOperation(Token::Value::NE, reg, LanguageMode::SLOPPY)
.CompareOperation(Token::Value::EQ_STRICT, reg, LanguageMode::SLOPPY)
.CompareOperation(Token::Value::NE_STRICT, reg, LanguageMode::SLOPPY)
.CompareOperation(Token::Value::LT, reg, LanguageMode::SLOPPY)
.CompareOperation(Token::Value::GT, reg, LanguageMode::SLOPPY)
.CompareOperation(Token::Value::LTE, reg, LanguageMode::SLOPPY)
.CompareOperation(Token::Value::GTE, reg, LanguageMode::SLOPPY)
.CompareOperation(Token::Value::INSTANCEOF, reg, LanguageMode::SLOPPY)
.CompareOperation(Token::Value::IN, reg, LanguageMode::SLOPPY);
// Emit cast operator invocations.
builder.LoadNull().CastAccumulatorToBoolean();
// Emit control flow. Return must be the last instruction. // Emit control flow. Return must be the last instruction.
BytecodeLabel start;
builder.Bind(&start);
// Short jumps with Imm8 operands
builder.Jump(&start).JumpIfTrue(&start).JumpIfFalse(&start);
// Insert dummy ops to force longer jumps
for (int i = 0; i < 128; i++) {
builder.LoadTrue();
}
// Longer jumps requiring Constant operand
builder.Jump(&start).JumpIfTrue(&start).JumpIfFalse(&start);
builder.Return(); builder.Return();
// Generate BytecodeArray. // Generate BytecodeArray.
...@@ -183,6 +209,189 @@ TEST_F(BytecodeArrayBuilderTest, Constants) { ...@@ -183,6 +209,189 @@ TEST_F(BytecodeArrayBuilderTest, Constants) {
CHECK_EQ(array->constant_pool()->length(), 3); CHECK_EQ(array->constant_pool()->length(), 3);
} }
TEST_F(BytecodeArrayBuilderTest, ForwardJumps) {
static const int kFarJumpDistance = 256;
BytecodeArrayBuilder builder(isolate(), zone());
builder.set_parameter_count(0);
builder.set_locals_count(0);
BytecodeLabel far0, far1, far2;
BytecodeLabel near0, near1, near2;
builder.Jump(&near0)
.JumpIfTrue(&near1)
.JumpIfFalse(&near2)
.Bind(&near0)
.Bind(&near1)
.Bind(&near2)
.Jump(&far0)
.JumpIfTrue(&far1)
.JumpIfFalse(&far2);
for (int i = 0; i < kFarJumpDistance - 6; i++) {
builder.LoadUndefined();
}
builder.Bind(&far0).Bind(&far1).Bind(&far2);
builder.Return();
Handle<BytecodeArray> array = builder.ToBytecodeArray();
DCHECK_EQ(array->length(), 12 + kFarJumpDistance - 6 + 1);
BytecodeArrayIterator iterator(array);
CHECK_EQ(iterator.current_bytecode(), Bytecode::kJump);
CHECK_EQ(iterator.GetSmi8Operand(0), 6);
iterator.Advance();
CHECK_EQ(iterator.current_bytecode(), Bytecode::kJumpIfTrue);
CHECK_EQ(iterator.GetSmi8Operand(0), 4);
iterator.Advance();
CHECK_EQ(iterator.current_bytecode(), Bytecode::kJumpIfFalse);
CHECK_EQ(iterator.GetSmi8Operand(0), 2);
iterator.Advance();
CHECK_EQ(iterator.current_bytecode(), Bytecode::kJumpConstant);
CHECK_EQ(*iterator.GetConstantForIndexOperand(0),
Smi::FromInt(kFarJumpDistance));
CHECK_EQ(
array->get(iterator.current_offset() +
Smi::cast(*iterator.GetConstantForIndexOperand(0))->value()),
Bytecodes::ToByte(Bytecode::kReturn));
iterator.Advance();
CHECK_EQ(iterator.current_bytecode(), Bytecode::kJumpIfTrueConstant);
CHECK_EQ(*iterator.GetConstantForIndexOperand(0),
Smi::FromInt(kFarJumpDistance - 2));
CHECK_EQ(
array->get(iterator.current_offset() +
Smi::cast(*iterator.GetConstantForIndexOperand(0))->value()),
Bytecodes::ToByte(Bytecode::kReturn));
iterator.Advance();
CHECK_EQ(iterator.current_bytecode(), Bytecode::kJumpIfFalseConstant);
CHECK_EQ(*iterator.GetConstantForIndexOperand(0),
Smi::FromInt(kFarJumpDistance - 4));
CHECK_EQ(
array->get(iterator.current_offset() +
Smi::cast(*iterator.GetConstantForIndexOperand(0))->value()),
Bytecodes::ToByte(Bytecode::kReturn));
iterator.Advance();
}
TEST_F(BytecodeArrayBuilderTest, BackwardJumps) {
BytecodeArrayBuilder builder(isolate(), zone());
builder.set_parameter_count(0);
builder.set_locals_count(0);
BytecodeLabel label0, label1, label2;
builder.Bind(&label0)
.Jump(&label0)
.Bind(&label1)
.JumpIfTrue(&label1)
.Bind(&label2)
.JumpIfFalse(&label2);
for (int i = 0; i < 64; i++) {
builder.Jump(&label2);
}
builder.JumpIfFalse(&label2);
builder.JumpIfTrue(&label1);
builder.Jump(&label0);
builder.Return();
Handle<BytecodeArray> array = builder.ToBytecodeArray();
BytecodeArrayIterator iterator(array);
CHECK_EQ(iterator.current_bytecode(), Bytecode::kJump);
CHECK_EQ(iterator.GetSmi8Operand(0), 0);
iterator.Advance();
CHECK_EQ(iterator.current_bytecode(), Bytecode::kJumpIfTrue);
CHECK_EQ(iterator.GetSmi8Operand(0), 0);
iterator.Advance();
CHECK_EQ(iterator.current_bytecode(), Bytecode::kJumpIfFalse);
CHECK_EQ(iterator.GetSmi8Operand(0), 0);
iterator.Advance();
for (int i = 0; i < 64; i++) {
CHECK_EQ(iterator.current_bytecode(), Bytecode::kJump);
CHECK_EQ(iterator.GetSmi8Operand(0), -i * 2 - 2);
iterator.Advance();
}
CHECK_EQ(iterator.current_bytecode(), Bytecode::kJumpIfFalseConstant);
CHECK_EQ(Smi::cast(*iterator.GetConstantForIndexOperand(0))->value(), -130);
iterator.Advance();
CHECK_EQ(iterator.current_bytecode(), Bytecode::kJumpIfTrueConstant);
CHECK_EQ(Smi::cast(*iterator.GetConstantForIndexOperand(0))->value(), -134);
iterator.Advance();
CHECK_EQ(iterator.current_bytecode(), Bytecode::kJumpConstant);
CHECK_EQ(Smi::cast(*iterator.GetConstantForIndexOperand(0))->value(), -138);
iterator.Advance();
CHECK_EQ(iterator.current_bytecode(), Bytecode::kReturn);
iterator.Advance();
CHECK(iterator.done());
}
TEST_F(BytecodeArrayBuilderTest, LabelReuse) {
BytecodeArrayBuilder builder(isolate(), zone());
builder.set_parameter_count(0);
builder.set_locals_count(0);
// Labels can only have 1 forward reference, but
// can be referred to mulitple times once bound.
BytecodeLabel label;
builder.Jump(&label).Bind(&label).Jump(&label).Jump(&label).Return();
Handle<BytecodeArray> array = builder.ToBytecodeArray();
BytecodeArrayIterator iterator(array);
CHECK_EQ(iterator.current_bytecode(), Bytecode::kJump);
CHECK_EQ(iterator.GetSmi8Operand(0), 2);
iterator.Advance();
CHECK_EQ(iterator.current_bytecode(), Bytecode::kJump);
CHECK_EQ(iterator.GetSmi8Operand(0), 0);
iterator.Advance();
CHECK_EQ(iterator.current_bytecode(), Bytecode::kJump);
CHECK_EQ(iterator.GetSmi8Operand(0), -2);
iterator.Advance();
CHECK_EQ(iterator.current_bytecode(), Bytecode::kReturn);
iterator.Advance();
CHECK(iterator.done());
}
TEST_F(BytecodeArrayBuilderTest, LabelAddressReuse) {
static const int kRepeats = 3;
BytecodeArrayBuilder builder(isolate(), zone());
builder.set_parameter_count(0);
builder.set_locals_count(0);
for (int i = 0; i < kRepeats; i++) {
BytecodeLabel label;
builder.Jump(&label).Bind(&label).Jump(&label).Jump(&label);
}
builder.Return();
Handle<BytecodeArray> array = builder.ToBytecodeArray();
BytecodeArrayIterator iterator(array);
for (int i = 0; i < kRepeats; i++) {
CHECK_EQ(iterator.current_bytecode(), Bytecode::kJump);
CHECK_EQ(iterator.GetSmi8Operand(0), 2);
iterator.Advance();
CHECK_EQ(iterator.current_bytecode(), Bytecode::kJump);
CHECK_EQ(iterator.GetSmi8Operand(0), 0);
iterator.Advance();
CHECK_EQ(iterator.current_bytecode(), Bytecode::kJump);
CHECK_EQ(iterator.GetSmi8Operand(0), -2);
iterator.Advance();
}
CHECK_EQ(iterator.current_bytecode(), Bytecode::kReturn);
iterator.Advance();
CHECK(iterator.done());
}
} // namespace interpreter } // namespace interpreter
} // namespace internal } // namespace internal
} // namespace v8 } // namespace v8
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment