Commit 54040fff authored by Clemens Hammacher's avatar Clemens Hammacher Committed by Commit Bot

Reland "[wasm] Refactor function body decoder"

This is a reland of 6b4dc039
Original change's description:
> [wasm] Refactor function body decoder
> 
> This refactoring separates graph building from wasm decoding. The
> WasmGraphBuilder is just a consumer of the decoded information.
> Decoding without any consumer (i.e. just validation) gets 16% faster by
> this refactoring, because no TFNode* have to be stored in the value
> stack, and all dynamic tests to determine whether the graph should be
> build are gone (measured on AngryBots; before: 110.2 +- 3.3ms, after:
> 92.2 +- 3.1 ms).
> 
> This new design will allow us to also attach other consumers, e.g. a
> new baseline compiler.
> 
> R=titzer@chromium.org
> 
> Bug: v8:6600
> Change-Id: I4b60f2409d871a16c3c52a37e515bcfb9dbb8f54
> Reviewed-on: https://chromium-review.googlesource.com/571010
> Commit-Queue: Clemens Hammacher <clemensh@chromium.org>
> Reviewed-by: Ben Titzer <titzer@chromium.org>
> Cr-Commit-Position: refs/heads/master@{#47671}

TBR=titzer@chromium.org

Bug: v8:6600
Change-Id: Idd867c5a1917437de5b6e3de5917cc1c9f194489
Reviewed-on: https://chromium-review.googlesource.com/640591Reviewed-by: 's avatarClemens Hammacher <clemensh@chromium.org>
Commit-Queue: Clemens Hammacher <clemensh@chromium.org>
Cr-Commit-Position: refs/heads/master@{#47678}
parent 5c9f0831
......@@ -3777,8 +3777,7 @@ Node* WasmGraphBuilder::Simd8x16ShuffleOp(const uint8_t shuffle[16],
V(I32AtomicCompareExchange8U, CompareExchange, Uint8) \
V(I32AtomicCompareExchange16U, CompareExchange, Uint16)
Node* WasmGraphBuilder::AtomicOp(wasm::WasmOpcode opcode,
const NodeVector& inputs,
Node* WasmGraphBuilder::AtomicOp(wasm::WasmOpcode opcode, Node* const* inputs,
wasm::WasmCodePosition position) {
Node* node;
switch (opcode) {
......
......@@ -315,7 +315,7 @@ class WasmGraphBuilder {
Node* Simd8x16ShuffleOp(const uint8_t shuffle[16], Node* const* inputs);
Node* AtomicOp(wasm::WasmOpcode opcode, const NodeVector& inputs,
Node* AtomicOp(wasm::WasmOpcode opcode, Node* const* inputs,
wasm::WasmCodePosition position);
bool has_simd() const { return has_simd_; }
......
......@@ -5,7 +5,14 @@
#ifndef V8_WASM_FUNCTION_BODY_DECODER_IMPL_H_
#define V8_WASM_FUNCTION_BODY_DECODER_IMPL_H_
// Do only include this header for implementing new Interface of the
// WasmFullDecoder.
#include "src/bit-vector.h"
#include "src/wasm/decoder.h"
#include "src/wasm/function-body-decoder.h"
#include "src/wasm/wasm-limits.h"
#include "src/wasm/wasm-module.h"
#include "src/wasm/wasm-opcodes.h"
namespace v8 {
......@@ -15,14 +22,59 @@ namespace wasm {
struct WasmGlobal;
struct WasmException;
#if DEBUG
#define TRACE(...) \
do { \
if (FLAG_trace_wasm_decoder) PrintF(__VA_ARGS__); \
} while (false)
#else
#define TRACE(...)
#endif
// Return the evaluation of `condition` if validate==true, DCHECK
// and always return true otherwise.
#define VALIDATE(condition) \
(validate ? (condition) : [&] { \
DCHECK(condition); \
return true; \
}())
// Return the evaluation of `condition` if validate==true, DCHECK that it's
// false and always return false otherwise.
#define CHECK_ERROR(condition) \
(validate ? (condition) : [&] { \
DCHECK(!(condition)); \
return false; \
}())
// Use this macro to check a condition if checked == true, and DCHECK the
// condition otherwise.
// TODO(clemensh): Rename all "checked" to "validate" and replace
// "CHECKED_COND" with "CHECK_ERROR".
#define CHECKED_COND(cond) \
(checked ? (cond) : ([&] { \
DCHECK(cond); \
return true; \
})())
#define CHECK_PROTOTYPE_OPCODE(flag) \
if (this->module_ != nullptr && this->module_->is_asm_js()) { \
this->error("Opcode not supported for asmjs modules"); \
} \
if (!FLAG_experimental_wasm_##flag) { \
this->error("Invalid opcode (enable with --experimental-wasm-" #flag ")"); \
break; \
}
#define OPCODE_ERROR(opcode, message) \
(this->errorf(this->pc_, "%s: %s", WasmOpcodes::OpcodeName(opcode), \
(message)))
template <typename T>
Vector<T> vec2vec(std::vector<T>& vec) {
return Vector<T>(vec.data(), vec.size());
}
// Helpers for decoding different kinds of operands which follow bytecodes.
template <bool checked>
struct LocalIndexOperand {
......@@ -169,19 +221,20 @@ struct BlockTypeOperand {
return false;
}
}
ValueType read_entry(unsigned index) {
DCHECK_LT(index, arity);
ValueType result;
CHECK(decode_local_type(types[index], &result));
bool success = decode_local_type(types[index], &result);
DCHECK(success);
USE(success);
return result;
}
};
struct Control;
template <bool checked>
struct BreakDepthOperand {
uint32_t depth;
Control* target = nullptr;
unsigned length;
inline BreakDepthOperand(Decoder* decoder, const byte* pc) {
depth = decoder->read_u32v<checked>(pc + 1, &length, "break depth");
......@@ -265,7 +318,8 @@ class BranchTableIterator {
}
const byte* pc() { return pc_; }
BranchTableIterator(Decoder* decoder, BranchTableOperand<checked>& operand)
BranchTableIterator(Decoder* decoder,
const BranchTableOperand<checked>& operand)
: decoder_(decoder),
start_(operand.start),
pc_(operand.table),
......@@ -337,7 +391,1777 @@ struct Simd8x16ShuffleOperand {
}
};
// An entry on the value stack.
template <typename Interface>
struct AbstractValue {
const byte* pc;
ValueType type;
typename Interface::IValue interface_data;
// Named constructors.
static AbstractValue Unreachable(const byte* pc) {
return {pc, kWasmVar, Interface::IValue::Unreachable()};
}
static AbstractValue New(const byte* pc, ValueType type) {
return {pc, type, Interface::IValue::New()};
}
};
template <typename Interface>
struct AbstractMerge {
uint32_t arity;
union {
AbstractValue<Interface>* array;
AbstractValue<Interface> first;
} vals; // Either multiple values or a single value.
AbstractValue<Interface>& operator[](size_t i) {
DCHECK_GT(arity, i);
return arity == 1 ? vals.first : vals.array[i];
}
};
enum ControlKind {
kControlIf,
kControlIfElse,
kControlBlock,
kControlLoop,
kControlTry,
kControlTryCatch
};
// An entry on the control stack (i.e. if, block, loop, or try).
template <typename Interface>
struct AbstractControl {
const byte* pc;
ControlKind kind;
size_t stack_depth; // stack height at the beginning of the construct.
typename Interface::IControl interface_data;
bool unreachable; // The current block has been ended.
// Values merged into the end of this control construct.
AbstractMerge<Interface> merge;
inline bool is_if() const { return is_onearmed_if() || is_if_else(); }
inline bool is_onearmed_if() const { return kind == kControlIf; }
inline bool is_if_else() const { return kind == kControlIfElse; }
inline bool is_block() const { return kind == kControlBlock; }
inline bool is_loop() const { return kind == kControlLoop; }
inline bool is_try() const { return is_incomplete_try() || is_try_catch(); }
inline bool is_incomplete_try() const { return kind == kControlTry; }
inline bool is_try_catch() const { return kind == kControlTryCatch; }
// Named constructors.
static AbstractControl Block(const byte* pc, size_t stack_depth) {
return {pc, kControlBlock, stack_depth, Interface::IControl::Block(), false,
{}};
}
static AbstractControl If(const byte* pc, size_t stack_depth) {
return {pc, kControlIf, stack_depth, Interface::IControl::If(), false, {}};
}
static AbstractControl Loop(const byte* pc, size_t stack_depth) {
return {pc, kControlLoop, stack_depth, Interface::IControl::Loop(), false,
{}};
}
static AbstractControl Try(const byte* pc, size_t stack_depth) {
return {pc, kControlTry, stack_depth, Interface::IControl::Try(),
false, {}};
}
};
// This is the list of callback functions that an interface for the
// WasmFullDecoder should implement.
// F(Name, args...)
#define INTERFACE_FUNCTIONS(F) \
/* General: */ \
F(StartFunction) \
F(StartFunctionBody, Control* block) \
F(FinishFunction) \
/* Control: */ \
F(Block, Control* block) \
F(Loop, Control* block) \
F(Try, Control* block) \
F(If, const Value& cond, Control* if_block) \
F(FallThruTo, Control* c) \
F(PopControl, const Control& block) \
F(EndControl, Control* block) \
/* Instructions: */ \
F(UnOp, WasmOpcode opcode, FunctionSig*, const Value& value, Value* result) \
F(BinOp, WasmOpcode opcode, FunctionSig*, const Value& lhs, \
const Value& rhs, Value* result) \
F(I32Const, Value* result, int32_t value) \
F(I64Const, Value* result, int64_t value) \
F(F32Const, Value* result, float value) \
F(F64Const, Value* result, double value) \
F(DoReturn, Vector<Value> values) \
F(GetLocal, Value* result, const LocalIndexOperand<validate>& operand) \
F(SetLocal, const Value& value, const LocalIndexOperand<validate>& operand) \
F(TeeLocal, const Value& value, Value* result, \
const LocalIndexOperand<validate>& operand) \
F(GetGlobal, Value* result, const GlobalIndexOperand<validate>& operand) \
F(SetGlobal, const Value& value, \
const GlobalIndexOperand<validate>& operand) \
F(Unreachable) \
F(Select, const Value& cond, const Value& fval, const Value& tval, \
Value* result) \
F(BreakTo, Control* block) \
F(BrIf, const Value& cond, Control* block) \
F(BrTable, const BranchTableOperand<validate>& operand, const Value& key) \
F(Else, Control* if_block) \
F(LoadMem, ValueType type, MachineType mem_type, \
const MemoryAccessOperand<validate>& operand, const Value& index, \
Value* result) \
F(StoreMem, ValueType type, MachineType mem_type, \
const MemoryAccessOperand<validate>& operand, const Value& index, \
const Value& value) \
F(CurrentMemoryPages, Value* result) \
F(GrowMemory, const Value& value, Value* result) \
F(CallDirect, const CallFunctionOperand<validate>& operand, \
const Value args[], Value returns[]) \
F(CallIndirect, const Value& index, \
const CallIndirectOperand<validate>& operand, const Value args[], \
Value returns[]) \
F(SimdOp, WasmOpcode opcode, Vector<Value> args, Value* result) \
F(SimdLaneOp, WasmOpcode opcode, const SimdLaneOperand<validate>& operand, \
const Vector<Value> inputs, Value* result) \
F(SimdShiftOp, WasmOpcode opcode, const SimdShiftOperand<validate>& operand, \
const Value& input, Value* result) \
F(Simd8x16ShuffleOp, const Simd8x16ShuffleOperand<validate>& operand, \
const Value& input0, const Value& input1, Value* result) \
F(Throw, const ExceptionIndexOperand<validate>&) \
F(Catch, const ExceptionIndexOperand<validate>& operand, Control* block) \
F(AtomicOp, WasmOpcode opcode, Vector<Value> args, Value* result)
// Generic Wasm bytecode decoder with utilities for decoding operands,
// lengths, etc.
template <bool validate>
class WasmDecoder : public Decoder {
public:
WasmDecoder(const WasmModule* module, FunctionSig* sig, const byte* start,
const byte* end, uint32_t buffer_offset = 0)
: Decoder(start, end, buffer_offset),
module_(module),
sig_(sig),
local_types_(nullptr) {}
const WasmModule* module_;
FunctionSig* sig_;
ZoneVector<ValueType>* local_types_;
size_t total_locals() const {
return local_types_ == nullptr ? 0 : local_types_->size();
}
static bool DecodeLocals(Decoder* decoder, const FunctionSig* sig,
ZoneVector<ValueType>* type_list) {
DCHECK_NOT_NULL(type_list);
DCHECK_EQ(0, type_list->size());
// Initialize from signature.
if (sig != nullptr) {
type_list->assign(sig->parameters().begin(), sig->parameters().end());
}
// Decode local declarations, if any.
uint32_t entries = decoder->consume_u32v("local decls count");
if (decoder->failed()) return false;
TRACE("local decls count: %u\n", entries);
while (entries-- > 0 && decoder->ok() && decoder->more()) {
uint32_t count = decoder->consume_u32v("local count");
if (decoder->failed()) return false;
if ((count + type_list->size()) > kV8MaxWasmFunctionLocals) {
decoder->error(decoder->pc() - 1, "local count too large");
return false;
}
byte code = decoder->consume_u8("local type");
if (decoder->failed()) return false;
ValueType type;
switch (code) {
case kLocalI32:
type = kWasmI32;
break;
case kLocalI64:
type = kWasmI64;
break;
case kLocalF32:
type = kWasmF32;
break;
case kLocalF64:
type = kWasmF64;
break;
case kLocalS128:
type = kWasmS128;
break;
default:
decoder->error(decoder->pc() - 1, "invalid local type");
return false;
}
type_list->insert(type_list->end(), count, type);
}
DCHECK(decoder->ok());
return true;
}
static BitVector* AnalyzeLoopAssignment(Decoder* decoder, const byte* pc,
int locals_count, Zone* zone) {
if (pc >= decoder->end()) return nullptr;
if (*pc != kExprLoop) return nullptr;
BitVector* assigned = new (zone) BitVector(locals_count, zone);
int depth = 0;
// Iteratively process all AST nodes nested inside the loop.
while (pc < decoder->end() && decoder->ok()) {
WasmOpcode opcode = static_cast<WasmOpcode>(*pc);
unsigned length = 1;
switch (opcode) {
case kExprLoop:
case kExprIf:
case kExprBlock:
case kExprTry:
length = OpcodeLength(decoder, pc);
depth++;
break;
case kExprSetLocal: // fallthru
case kExprTeeLocal: {
LocalIndexOperand<validate> operand(decoder, pc);
if (assigned->length() > 0 &&
operand.index < static_cast<uint32_t>(assigned->length())) {
// Unverified code might have an out-of-bounds index.
assigned->Add(operand.index);
}
length = 1 + operand.length;
break;
}
case kExprEnd:
depth--;
break;
default:
length = OpcodeLength(decoder, pc);
break;
}
if (depth <= 0) break;
pc += length;
}
return decoder->ok() ? assigned : nullptr;
}
inline bool Validate(const byte* pc, LocalIndexOperand<validate>& operand) {
if (VALIDATE(operand.index < total_locals())) {
if (local_types_) {
operand.type = local_types_->at(operand.index);
} else {
operand.type = kWasmStmt;
}
return true;
}
errorf(pc + 1, "invalid local index: %u", operand.index);
return false;
}
inline bool Validate(const byte* pc,
ExceptionIndexOperand<validate>& operand) {
if (module_ != nullptr && operand.index < module_->exceptions.size()) {
operand.exception = &module_->exceptions[operand.index];
return true;
}
errorf(pc + 1, "Invalid exception index: %u", operand.index);
return false;
}
inline bool Validate(const byte* pc, GlobalIndexOperand<validate>& operand) {
if (VALIDATE(module_ != nullptr &&
operand.index < module_->globals.size())) {
operand.global = &module_->globals[operand.index];
operand.type = operand.global->type;
return true;
}
errorf(pc + 1, "invalid global index: %u", operand.index);
return false;
}
inline bool Complete(const byte* pc, CallFunctionOperand<validate>& operand) {
if (VALIDATE(module_ != nullptr &&
operand.index < module_->functions.size())) {
operand.sig = module_->functions[operand.index].sig;
return true;
}
return false;
}
inline bool Validate(const byte* pc, CallFunctionOperand<validate>& operand) {
if (Complete(pc, operand)) {
return true;
}
errorf(pc + 1, "invalid function index: %u", operand.index);
return false;
}
inline bool Complete(const byte* pc, CallIndirectOperand<validate>& operand) {
if (VALIDATE(module_ != nullptr &&
operand.index < module_->signatures.size())) {
operand.sig = module_->signatures[operand.index];
return true;
}
return false;
}
inline bool Validate(const byte* pc, CallIndirectOperand<validate>& operand) {
if (CHECK_ERROR(module_ == nullptr || module_->function_tables.empty())) {
error("function table has to exist to execute call_indirect");
return false;
}
if (Complete(pc, operand)) {
return true;
}
errorf(pc + 1, "invalid signature index: #%u", operand.index);
return false;
}
inline bool Validate(const byte* pc, BreakDepthOperand<validate>& operand,
size_t control_depth) {
if (VALIDATE(operand.depth < control_depth)) {
return true;
}
errorf(pc + 1, "invalid break depth: %u", operand.depth);
return false;
}
bool Validate(const byte* pc, BranchTableOperand<validate>& operand,
size_t block_depth) {
if (CHECK_ERROR(operand.table_count >= kV8MaxWasmFunctionSize)) {
errorf(pc + 1, "invalid table count (> max function size): %u",
operand.table_count);
return false;
}
return checkAvailable(operand.table_count);
}
inline bool Validate(const byte* pc, WasmOpcode opcode,
SimdLaneOperand<validate>& operand) {
uint8_t num_lanes = 0;
switch (opcode) {
case kExprF32x4ExtractLane:
case kExprF32x4ReplaceLane:
case kExprI32x4ExtractLane:
case kExprI32x4ReplaceLane:
num_lanes = 4;
break;
case kExprI16x8ExtractLane:
case kExprI16x8ReplaceLane:
num_lanes = 8;
break;
case kExprI8x16ExtractLane:
case kExprI8x16ReplaceLane:
num_lanes = 16;
break;
default:
UNREACHABLE();
break;
}
if (CHECK_ERROR(operand.lane < 0 || operand.lane >= num_lanes)) {
error(pc_ + 2, "invalid lane index");
return false;
} else {
return true;
}
}
inline bool Validate(const byte* pc, WasmOpcode opcode,
SimdShiftOperand<validate>& operand) {
uint8_t max_shift = 0;
switch (opcode) {
case kExprI32x4Shl:
case kExprI32x4ShrS:
case kExprI32x4ShrU:
max_shift = 32;
break;
case kExprI16x8Shl:
case kExprI16x8ShrS:
case kExprI16x8ShrU:
max_shift = 16;
break;
case kExprI8x16Shl:
case kExprI8x16ShrS:
case kExprI8x16ShrU:
max_shift = 8;
break;
default:
UNREACHABLE();
break;
}
if (CHECK_ERROR(operand.shift < 0 || operand.shift >= max_shift)) {
error(pc_ + 2, "invalid shift amount");
return false;
} else {
return true;
}
}
inline bool Validate(const byte* pc,
Simd8x16ShuffleOperand<validate>& operand) {
uint8_t max_lane = 0;
for (uint32_t i = 0; i < kSimd128Size; ++i)
max_lane = std::max(max_lane, operand.shuffle[i]);
// Shuffle indices must be in [0..31] for a 16 lane shuffle.
if (CHECK_ERROR(max_lane > 2 * kSimd128Size)) {
error(pc_ + 2, "invalid shuffle mask");
return false;
} else {
return true;
}
}
static unsigned OpcodeLength(Decoder* decoder, const byte* pc) {
WasmOpcode opcode = static_cast<WasmOpcode>(*pc);
switch (opcode) {
#define DECLARE_OPCODE_CASE(name, opcode, sig) case kExpr##name:
FOREACH_LOAD_MEM_OPCODE(DECLARE_OPCODE_CASE)
FOREACH_STORE_MEM_OPCODE(DECLARE_OPCODE_CASE)
#undef DECLARE_OPCODE_CASE
{
MemoryAccessOperand<validate> operand(decoder, pc, UINT32_MAX);
return 1 + operand.length;
}
case kExprBr:
case kExprBrIf: {
BreakDepthOperand<validate> operand(decoder, pc);
return 1 + operand.length;
}
case kExprSetGlobal:
case kExprGetGlobal: {
GlobalIndexOperand<validate> operand(decoder, pc);
return 1 + operand.length;
}
case kExprCallFunction: {
CallFunctionOperand<validate> operand(decoder, pc);
return 1 + operand.length;
}
case kExprCallIndirect: {
CallIndirectOperand<validate> operand(decoder, pc);
return 1 + operand.length;
}
case kExprTry:
case kExprIf: // fall through
case kExprLoop:
case kExprBlock: {
BlockTypeOperand<validate> operand(decoder, pc);
return 1 + operand.length;
}
case kExprThrow:
case kExprCatch: {
ExceptionIndexOperand<validate> operand(decoder, pc);
return 1 + operand.length;
}
case kExprSetLocal:
case kExprTeeLocal:
case kExprGetLocal: {
LocalIndexOperand<validate> operand(decoder, pc);
return 1 + operand.length;
}
case kExprBrTable: {
BranchTableOperand<validate> operand(decoder, pc);
BranchTableIterator<validate> iterator(decoder, operand);
return 1 + iterator.length();
}
case kExprI32Const: {
ImmI32Operand<validate> operand(decoder, pc);
return 1 + operand.length;
}
case kExprI64Const: {
ImmI64Operand<validate> operand(decoder, pc);
return 1 + operand.length;
}
case kExprGrowMemory:
case kExprMemorySize: {
MemoryIndexOperand<validate> operand(decoder, pc);
return 1 + operand.length;
}
case kExprF32Const:
return 5;
case kExprF64Const:
return 9;
case kSimdPrefix: {
byte simd_index = decoder->read_u8<validate>(pc + 1, "simd_index");
WasmOpcode opcode =
static_cast<WasmOpcode>(kSimdPrefix << 8 | simd_index);
switch (opcode) {
#define DECLARE_OPCODE_CASE(name, opcode, sig) case kExpr##name:
FOREACH_SIMD_0_OPERAND_OPCODE(DECLARE_OPCODE_CASE)
#undef DECLARE_OPCODE_CASE
return 2;
#define DECLARE_OPCODE_CASE(name, opcode, sig) case kExpr##name:
FOREACH_SIMD_1_OPERAND_OPCODE(DECLARE_OPCODE_CASE)
#undef DECLARE_OPCODE_CASE
return 3;
#define DECLARE_OPCODE_CASE(name, opcode, sig) case kExpr##name:
FOREACH_SIMD_MEM_OPCODE(DECLARE_OPCODE_CASE)
#undef DECLARE_OPCODE_CASE
{
MemoryAccessOperand<validate> operand(decoder, pc + 1, UINT32_MAX);
return 2 + operand.length;
}
// Shuffles require a byte per lane, or 16 immediate bytes.
case kExprS8x16Shuffle:
return 2 + kSimd128Size;
default:
decoder->error(pc, "invalid SIMD opcode");
return 2;
}
}
default:
return 1;
}
}
std::pair<uint32_t, uint32_t> StackEffect(const byte* pc) {
WasmOpcode opcode = static_cast<WasmOpcode>(*pc);
// Handle "simple" opcodes with a fixed signature first.
FunctionSig* sig = WasmOpcodes::Signature(opcode);
if (!sig) sig = WasmOpcodes::AsmjsSignature(opcode);
if (sig) return {sig->parameter_count(), sig->return_count()};
if (WasmOpcodes::IsPrefixOpcode(opcode)) {
opcode = static_cast<WasmOpcode>(opcode << 8 | *(pc + 1));
}
#define DECLARE_OPCODE_CASE(name, opcode, sig) case kExpr##name:
// clang-format off
switch (opcode) {
case kExprSelect:
return {3, 1};
case kExprS128StoreMem:
FOREACH_STORE_MEM_OPCODE(DECLARE_OPCODE_CASE)
return {2, 0};
case kExprS128LoadMem:
FOREACH_LOAD_MEM_OPCODE(DECLARE_OPCODE_CASE)
case kExprTeeLocal:
case kExprGrowMemory:
return {1, 1};
case kExprSetLocal:
case kExprSetGlobal:
case kExprDrop:
case kExprBrIf:
case kExprBrTable:
case kExprIf:
return {1, 0};
case kExprGetLocal:
case kExprGetGlobal:
case kExprI32Const:
case kExprI64Const:
case kExprF32Const:
case kExprF64Const:
case kExprMemorySize:
return {0, 1};
case kExprCallFunction: {
CallFunctionOperand<validate> operand(this, pc);
CHECK(Complete(pc, operand));
return {operand.sig->parameter_count(), operand.sig->return_count()};
}
case kExprCallIndirect: {
CallIndirectOperand<validate> operand(this, pc);
CHECK(Complete(pc, operand));
// Indirect calls pop an additional argument for the table index.
return {operand.sig->parameter_count() + 1,
operand.sig->return_count()};
}
case kExprBr:
case kExprBlock:
case kExprLoop:
case kExprEnd:
case kExprElse:
case kExprNop:
case kExprReturn:
case kExprUnreachable:
return {0, 0};
default:
V8_Fatal(__FILE__, __LINE__, "unimplemented opcode: %x (%s)", opcode,
WasmOpcodes::OpcodeName(opcode));
return {0, 0};
}
#undef DECLARE_OPCODE_CASE
// clang-format on
}
};
template <bool validate, typename Interface>
class WasmFullDecoder : public WasmDecoder<validate> {
using Value = AbstractValue<Interface>;
using Control = AbstractControl<Interface>;
using MergeValues = AbstractMerge<Interface>;
// All Value and Control types should be trivially copyable for
// performance. We push and pop them, and store them in local variables.
static_assert(IS_TRIVIALLY_COPYABLE(Value),
"all Value<...> types should be trivially copyable");
static_assert(IS_TRIVIALLY_COPYABLE(Control),
"all Control<...> types should be trivially copyable");
public:
template <typename... InterfaceArgs>
WasmFullDecoder(Zone* zone, const wasm::WasmModule* module,
const FunctionBody& body, InterfaceArgs&&... interface_args)
: WasmDecoder<validate>(module, body.sig, body.start, body.end,
body.offset),
zone_(zone),
interface_(std::forward<InterfaceArgs>(interface_args)...),
local_type_vec_(zone),
stack_(zone),
control_(zone),
last_end_found_(false) {
this->local_types_ = &local_type_vec_;
}
Interface& interface() { return interface_; }
bool Decode() {
DCHECK(stack_.empty());
DCHECK(control_.empty());
if (FLAG_wasm_code_fuzzer_gen_test) {
PrintRawWasmCode(this->start_, this->end_);
}
base::ElapsedTimer decode_timer;
if (FLAG_trace_wasm_decode_time) {
decode_timer.Start();
}
if (this->end_ < this->pc_) {
this->error("function body end < start");
return false;
}
DCHECK_EQ(0, this->local_types_->size());
WasmDecoder<validate>::DecodeLocals(this, this->sig_, this->local_types_);
interface_.StartFunction(this);
DecodeFunctionBody();
if (!this->failed()) interface_.FinishFunction(this);
if (this->failed()) return this->TraceFailed();
if (!control_.empty()) {
// Generate a better error message whether the unterminated control
// structure is the function body block or an innner structure.
if (control_.size() > 1) {
this->error(control_.back().pc, "unterminated control structure");
} else {
this->error("function body must end with \"end\" opcode");
}
return TraceFailed();
}
if (!last_end_found_) {
this->error("function body must end with \"end\" opcode");
return false;
}
if (FLAG_trace_wasm_decode_time) {
double ms = decode_timer.Elapsed().InMillisecondsF();
PrintF("wasm-decode %s (%0.3f ms)\n\n", this->ok() ? "ok" : "failed", ms);
} else {
TRACE("wasm-decode %s\n\n", this->ok() ? "ok" : "failed");
}
return true;
}
bool TraceFailed() {
TRACE("wasm-error module+%-6d func+%d: %s\n\n", this->error_offset_,
this->GetBufferRelativeOffset(this->error_offset_),
this->error_msg_.c_str());
return false;
}
const char* SafeOpcodeNameAt(const byte* pc) {
if (pc >= this->end_) return "<end>";
return WasmOpcodes::OpcodeName(static_cast<WasmOpcode>(*pc));
}
inline Zone* zone() const { return zone_; }
inline uint32_t NumLocals() {
return static_cast<uint32_t>(local_type_vec_.size());
}
inline ValueType GetLocalType(uint32_t index) {
return local_type_vec_[index];
}
inline wasm::WasmCodePosition position() {
int offset = static_cast<int>(this->pc_ - this->start_);
DCHECK_EQ(this->pc_ - this->start_, offset); // overflows cannot happen
return offset;
}
inline uint32_t control_depth() const {
return static_cast<uint32_t>(control_.size());
}
inline Control* control_at(uint32_t depth) {
DCHECK_GT(control_.size(), depth);
return &control_[control_.size() - depth - 1];
}
inline uint32_t stack_size() const {
return static_cast<uint32_t>(stack_.size());
}
inline Value* stack_value(uint32_t depth) {
DCHECK_GT(stack_.size(), depth);
return &stack_[stack_.size() - depth - 1];
}
inline const Value& GetMergeValueFromStack(Control* c, size_t i) {
DCHECK_GT(c->merge.arity, i);
DCHECK_GE(stack_.size(), c->merge.arity);
return stack_[stack_.size() - c->merge.arity + i];
}
private:
static constexpr size_t kErrorMsgSize = 128;
Zone* zone_;
Interface interface_;
ZoneVector<ValueType> local_type_vec_; // types of local variables.
ZoneVector<Value> stack_; // stack of values.
ZoneVector<Control> control_; // stack of blocks, loops, and ifs.
bool last_end_found_;
bool CheckHasMemory() {
if (VALIDATE(this->module_->has_memory)) return true;
this->error(this->pc_ - 1, "memory instruction with no memory");
return false;
}
// Decodes the body of a function.
void DecodeFunctionBody() {
TRACE("wasm-decode %p...%p (module+%u, %d bytes)\n",
reinterpret_cast<const void*>(this->start()),
reinterpret_cast<const void*>(this->end()), this->pc_offset(),
static_cast<int>(this->end() - this->start()));
// Set up initial function block.
{
auto* c = PushBlock();
c->merge.arity = static_cast<uint32_t>(this->sig_->return_count());
if (c->merge.arity == 1) {
c->merge.vals.first = Value::New(this->pc_, this->sig_->GetReturn(0));
} else if (c->merge.arity > 1) {
c->merge.vals.array = zone_->NewArray<Value>(c->merge.arity);
for (unsigned i = 0; i < c->merge.arity; i++) {
c->merge.vals.array[i] =
Value::New(this->pc_, this->sig_->GetReturn(i));
}
}
interface_.StartFunctionBody(this, c);
}
while (this->pc_ < this->end_) { // decoding loop.
unsigned len = 1;
WasmOpcode opcode = static_cast<WasmOpcode>(*this->pc_);
#if DEBUG
if (FLAG_trace_wasm_decoder && !WasmOpcodes::IsPrefixOpcode(opcode)) {
TRACE(" @%-8d #%-20s|", startrel(this->pc_),
WasmOpcodes::OpcodeName(opcode));
}
#endif
FunctionSig* sig = WasmOpcodes::Signature(opcode);
if (sig) {
BuildSimpleOperator(opcode, sig);
} else {
// Complex bytecode.
switch (opcode) {
case kExprNop:
break;
case kExprBlock: {
BlockTypeOperand<validate> operand(this, this->pc_);
auto* block = PushBlock();
SetBlockType(block, operand);
len = 1 + operand.length;
interface_.Block(this, block);
break;
}
case kExprRethrow: {
// TODO(kschimpf): Implement.
CHECK_PROTOTYPE_OPCODE(eh);
OPCODE_ERROR(opcode, "not implemented yet");
break;
}
case kExprThrow: {
CHECK_PROTOTYPE_OPCODE(eh);
ExceptionIndexOperand<true> operand(this, this->pc_);
len = 1 + operand.length;
if (!this->Validate(this->pc_, operand)) break;
if (operand.exception->sig->parameter_count() > 0) {
// TODO(kschimpf): Fix to pull values off stack and build throw.
OPCODE_ERROR(opcode, "can't handle exceptions with values yet");
break;
}
interface_.Throw(this, operand);
// TODO(titzer): Throw should end control, but currently we build a
// (reachable) runtime call instead of connecting it directly to
// end.
// EndControl();
break;
}
case kExprTry: {
CHECK_PROTOTYPE_OPCODE(eh);
BlockTypeOperand<validate> operand(this, this->pc_);
auto* try_block = PushTry();
SetBlockType(try_block, operand);
len = 1 + operand.length;
interface_.Try(this, try_block);
break;
}
case kExprCatch: {
// TODO(kschimpf): Fix to use type signature of exception.
CHECK_PROTOTYPE_OPCODE(eh);
ExceptionIndexOperand<true> operand(this, this->pc_);
len = 1 + operand.length;
if (!this->Validate(this->pc_, operand)) break;
if (CHECK_ERROR(control_.empty())) {
this->error("catch does not match any try");
break;
}
Control* c = &control_.back();
if (CHECK_ERROR(!c->is_try())) {
this->error("catch does not match any try");
break;
}
if (c->is_try_catch()) {
OPCODE_ERROR(opcode, "multiple catch blocks not implemented");
break;
}
c->kind = kControlTryCatch;
FallThruTo(c);
stack_.resize(c->stack_depth);
interface_.Catch(this, operand, c);
break;
}
case kExprCatchAll: {
// TODO(kschimpf): Implement.
CHECK_PROTOTYPE_OPCODE(eh);
OPCODE_ERROR(opcode, "not implemented yet");
break;
}
case kExprLoop: {
BlockTypeOperand<validate> operand(this, this->pc_);
// The continue environment is the inner environment.
auto* block = PushLoop();
SetBlockType(&control_.back(), operand);
len = 1 + operand.length;
interface_.Loop(this, block);
break;
}
case kExprIf: {
// Condition on top of stack. Split environments for branches.
BlockTypeOperand<validate> operand(this, this->pc_);
auto cond = Pop(0, kWasmI32);
auto* if_block = PushIf();
SetBlockType(if_block, operand);
interface_.If(this, cond, if_block);
len = 1 + operand.length;
break;
}
case kExprElse: {
if (CHECK_ERROR(control_.empty())) {
this->error("else does not match any if");
break;
}
Control* c = &control_.back();
if (CHECK_ERROR(!c->is_if())) {
this->error(this->pc_, "else does not match an if");
break;
}
if (c->is_if_else()) {
this->error(this->pc_, "else already present for if");
break;
}
c->kind = kControlIfElse;
FallThruTo(c);
stack_.resize(c->stack_depth);
interface_.Else(this, c);
break;
}
case kExprEnd: {
if (CHECK_ERROR(control_.empty())) {
this->error("end does not match any if, try, or block");
return;
}
Control* c = &control_.back();
if (c->is_loop()) {
// A loop just leaves the values on the stack.
TypeCheckFallThru(c);
if (c->unreachable) PushEndValues(c);
PopControl(c);
break;
}
if (c->is_onearmed_if()) {
// End the true branch of a one-armed if.
if (CHECK_ERROR(!c->unreachable &&
stack_.size() != c->stack_depth)) {
this->error("end of if expected empty stack");
stack_.resize(c->stack_depth);
}
if (CHECK_ERROR(c->merge.arity > 0)) {
this->error("non-void one-armed if");
}
} else if (CHECK_ERROR(c->is_incomplete_try())) {
this->error(this->pc_, "missing catch in try");
break;
}
FallThruTo(c);
PushEndValues(c);
if (control_.size() == 1) {
// If at the last (implicit) control, check we are at end.
if (CHECK_ERROR(this->pc_ + 1 != this->end_)) {
this->error(this->pc_ + 1, "trailing code after function end");
break;
}
last_end_found_ = true;
if (c->unreachable) {
TypeCheckFallThru(c);
} else {
// The result of the block is the return value.
TRACE(" @%-8d #xx:%-20s|", startrel(this->pc_),
"(implicit) return");
DoReturn();
TRACE("\n");
}
}
PopControl(c);
break;
}
case kExprSelect: {
auto cond = Pop(2, kWasmI32);
auto fval = Pop();
auto tval = Pop(0, fval.type);
auto* result = Push(tval.type == kWasmVar ? fval.type : tval.type);
interface_.Select(this, cond, fval, tval, result);
break;
}
case kExprBr: {
BreakDepthOperand<validate> operand(this, this->pc_);
if (VALIDATE(this->Validate(this->pc_, operand, control_.size()) &&
TypeCheckBreak(operand.depth))) {
interface_.BreakTo(this, control_at(operand.depth));
}
len = 1 + operand.length;
EndControl();
break;
}
case kExprBrIf: {
BreakDepthOperand<validate> operand(this, this->pc_);
auto cond = Pop(0, kWasmI32);
if (VALIDATE(this->ok() &&
this->Validate(this->pc_, operand, control_.size()) &&
TypeCheckBreak(operand.depth))) {
interface_.BrIf(this, cond, control_at(operand.depth));
}
len = 1 + operand.length;
break;
}
case kExprBrTable: {
BranchTableOperand<validate> operand(this, this->pc_);
BranchTableIterator<validate> iterator(this, operand);
if (!this->Validate(this->pc_, operand, control_.size())) break;
auto key = Pop(0, kWasmI32);
MergeValues* merge = nullptr;
while (iterator.has_next()) {
const uint32_t i = iterator.cur_index();
const byte* pos = iterator.pc();
uint32_t target = iterator.next();
if (CHECK_ERROR(target >= control_.size())) {
this->error(pos, "improper branch in br_table");
break;
}
// Check that label types match up.
static MergeValues loop_dummy = {0, {nullptr}};
Control* c = control_at(target);
MergeValues* current = c->is_loop() ? &loop_dummy : &c->merge;
if (i == 0) {
merge = current;
} else if (CHECK_ERROR(merge->arity != current->arity)) {
this->errorf(pos,
"inconsistent arity in br_table target %d"
" (previous was %u, this one %u)",
i, merge->arity, current->arity);
} else if (control_at(0)->unreachable) {
for (uint32_t j = 0; VALIDATE(this->ok()) && j < merge->arity;
++j) {
if (CHECK_ERROR((*merge)[j].type != (*current)[j].type)) {
this->errorf(pos,
"type error in br_table target %d operand %d"
" (previous expected %s, this one %s)",
i, j, WasmOpcodes::TypeName((*merge)[j].type),
WasmOpcodes::TypeName((*current)[j].type));
}
}
}
bool valid = TypeCheckBreak(target);
if (CHECK_ERROR(!valid)) break;
}
if (CHECK_ERROR(this->failed())) break;
if (operand.table_count > 0) {
interface_.BrTable(this, operand, key);
} else {
// Only a default target. Do the equivalent of br.
BranchTableIterator<validate> iterator(this, operand);
const byte* pos = iterator.pc();
uint32_t target = iterator.next();
if (CHECK_ERROR(target >= control_.size())) {
this->error(pos, "improper branch in br_table");
break;
}
interface_.BreakTo(this, control_at(target));
}
len = 1 + iterator.length();
EndControl();
break;
}
case kExprReturn: {
DoReturn();
break;
}
case kExprUnreachable: {
interface_.Unreachable(this);
EndControl();
break;
}
case kExprI32Const: {
ImmI32Operand<validate> operand(this, this->pc_);
auto* value = Push(kWasmI32);
interface_.I32Const(this, value, operand.value);
len = 1 + operand.length;
break;
}
case kExprI64Const: {
ImmI64Operand<validate> operand(this, this->pc_);
auto* value = Push(kWasmI64);
interface_.I64Const(this, value, operand.value);
len = 1 + operand.length;
break;
}
case kExprF32Const: {
ImmF32Operand<validate> operand(this, this->pc_);
auto* value = Push(kWasmF32);
interface_.F32Const(this, value, operand.value);
len = 1 + operand.length;
break;
}
case kExprF64Const: {
ImmF64Operand<validate> operand(this, this->pc_);
auto* value = Push(kWasmF64);
interface_.F64Const(this, value, operand.value);
len = 1 + operand.length;
break;
}
case kExprGetLocal: {
LocalIndexOperand<validate> operand(this, this->pc_);
if (!this->Validate(this->pc_, operand)) break;
auto* value = Push(operand.type);
interface_.GetLocal(this, value, operand);
len = 1 + operand.length;
break;
}
case kExprSetLocal: {
LocalIndexOperand<validate> operand(this, this->pc_);
if (!this->Validate(this->pc_, operand)) break;
auto value = Pop(0, local_type_vec_[operand.index]);
interface_.SetLocal(this, value, operand);
len = 1 + operand.length;
break;
}
case kExprTeeLocal: {
LocalIndexOperand<validate> operand(this, this->pc_);
if (!this->Validate(this->pc_, operand)) break;
auto value = Pop(0, local_type_vec_[operand.index]);
auto* result = Push(value.type);
interface_.TeeLocal(this, value, result, operand);
len = 1 + operand.length;
break;
}
case kExprDrop: {
Pop();
break;
}
case kExprGetGlobal: {
GlobalIndexOperand<validate> operand(this, this->pc_);
len = 1 + operand.length;
if (!this->Validate(this->pc_, operand)) break;
auto* result = Push(operand.type);
interface_.GetGlobal(this, result, operand);
break;
}
case kExprSetGlobal: {
GlobalIndexOperand<validate> operand(this, this->pc_);
len = 1 + operand.length;
if (!this->Validate(this->pc_, operand)) break;
if (CHECK_ERROR(!operand.global->mutability)) {
this->errorf(this->pc_, "immutable global #%u cannot be assigned",
operand.index);
break;
}
auto value = Pop(0, operand.type);
interface_.SetGlobal(this, value, operand);
break;
}
case kExprI32LoadMem8S:
len = DecodeLoadMem(kWasmI32, MachineType::Int8());
break;
case kExprI32LoadMem8U:
len = DecodeLoadMem(kWasmI32, MachineType::Uint8());
break;
case kExprI32LoadMem16S:
len = DecodeLoadMem(kWasmI32, MachineType::Int16());
break;
case kExprI32LoadMem16U:
len = DecodeLoadMem(kWasmI32, MachineType::Uint16());
break;
case kExprI32LoadMem:
len = DecodeLoadMem(kWasmI32, MachineType::Int32());
break;
case kExprI64LoadMem8S:
len = DecodeLoadMem(kWasmI64, MachineType::Int8());
break;
case kExprI64LoadMem8U:
len = DecodeLoadMem(kWasmI64, MachineType::Uint8());
break;
case kExprI64LoadMem16S:
len = DecodeLoadMem(kWasmI64, MachineType::Int16());
break;
case kExprI64LoadMem16U:
len = DecodeLoadMem(kWasmI64, MachineType::Uint16());
break;
case kExprI64LoadMem32S:
len = DecodeLoadMem(kWasmI64, MachineType::Int32());
break;
case kExprI64LoadMem32U:
len = DecodeLoadMem(kWasmI64, MachineType::Uint32());
break;
case kExprI64LoadMem:
len = DecodeLoadMem(kWasmI64, MachineType::Int64());
break;
case kExprF32LoadMem:
len = DecodeLoadMem(kWasmF32, MachineType::Float32());
break;
case kExprF64LoadMem:
len = DecodeLoadMem(kWasmF64, MachineType::Float64());
break;
case kExprI32StoreMem8:
len = DecodeStoreMem(kWasmI32, MachineType::Int8());
break;
case kExprI32StoreMem16:
len = DecodeStoreMem(kWasmI32, MachineType::Int16());
break;
case kExprI32StoreMem:
len = DecodeStoreMem(kWasmI32, MachineType::Int32());
break;
case kExprI64StoreMem8:
len = DecodeStoreMem(kWasmI64, MachineType::Int8());
break;
case kExprI64StoreMem16:
len = DecodeStoreMem(kWasmI64, MachineType::Int16());
break;
case kExprI64StoreMem32:
len = DecodeStoreMem(kWasmI64, MachineType::Int32());
break;
case kExprI64StoreMem:
len = DecodeStoreMem(kWasmI64, MachineType::Int64());
break;
case kExprF32StoreMem:
len = DecodeStoreMem(kWasmF32, MachineType::Float32());
break;
case kExprF64StoreMem:
len = DecodeStoreMem(kWasmF64, MachineType::Float64());
break;
case kExprGrowMemory: {
if (!CheckHasMemory()) break;
MemoryIndexOperand<validate> operand(this, this->pc_);
len = 1 + operand.length;
DCHECK_NOT_NULL(this->module_);
if (CHECK_ERROR(!this->module_->is_wasm())) {
this->error("grow_memory is not supported for asmjs modules");
break;
}
auto value = Pop(0, kWasmI32);
auto* result = Push(kWasmI32);
interface_.GrowMemory(this, value, result);
break;
}
case kExprMemorySize: {
if (!CheckHasMemory()) break;
MemoryIndexOperand<validate> operand(this, this->pc_);
auto* result = Push(kWasmI32);
len = 1 + operand.length;
interface_.CurrentMemoryPages(this, result);
break;
}
case kExprCallFunction: {
CallFunctionOperand<validate> operand(this, this->pc_);
len = 1 + operand.length;
if (!this->Validate(this->pc_, operand)) break;
// TODO(clemensh): Better memory management.
std::vector<Value> args;
PopArgs(operand.sig, &args);
auto* returns = PushReturns(operand.sig);
interface_.CallDirect(this, operand, args.data(), returns);
break;
}
case kExprCallIndirect: {
CallIndirectOperand<validate> operand(this, this->pc_);
len = 1 + operand.length;
if (!this->Validate(this->pc_, operand)) break;
auto index = Pop(0, kWasmI32);
// TODO(clemensh): Better memory management.
std::vector<Value> args;
PopArgs(operand.sig, &args);
auto* returns = PushReturns(operand.sig);
interface_.CallIndirect(this, index, operand, args.data(), returns);
break;
}
case kSimdPrefix: {
CHECK_PROTOTYPE_OPCODE(simd);
len++;
byte simd_index =
this->template read_u8<validate>(this->pc_ + 1, "simd index");
opcode = static_cast<WasmOpcode>(opcode << 8 | simd_index);
TRACE(" @%-4d #%-20s|", startrel(this->pc_),
WasmOpcodes::OpcodeName(opcode));
len += DecodeSimdOpcode(opcode);
break;
}
case kAtomicPrefix: {
CHECK_PROTOTYPE_OPCODE(threads);
len++;
byte atomic_index =
this->template read_u8<validate>(this->pc_ + 1, "atomic index");
opcode = static_cast<WasmOpcode>(opcode << 8 | atomic_index);
TRACE(" @%-4d #%-20s|", startrel(this->pc_),
WasmOpcodes::OpcodeName(opcode));
len += DecodeAtomicOpcode(opcode);
break;
}
default: {
// Deal with special asmjs opcodes.
if (this->module_ != nullptr && this->module_->is_asm_js()) {
sig = WasmOpcodes::AsmjsSignature(opcode);
if (sig) {
BuildSimpleOperator(opcode, sig);
}
} else {
this->error("Invalid opcode");
return;
}
}
}
}
#if DEBUG
if (FLAG_trace_wasm_decoder) {
PrintF(" ");
for (size_t i = 0; i < control_.size(); ++i) {
Control* c = &control_[i];
switch (c->kind) {
case kControlIf:
PrintF("I");
break;
case kControlBlock:
PrintF("B");
break;
case kControlLoop:
PrintF("L");
break;
case kControlTry:
PrintF("T");
break;
default:
break;
}
PrintF("%u", c->merge.arity);
if (c->unreachable) PrintF("*");
}
PrintF(" | ");
for (size_t i = 0; i < stack_.size(); ++i) {
auto& val = stack_[i];
WasmOpcode opcode = static_cast<WasmOpcode>(*val.pc);
if (WasmOpcodes::IsPrefixOpcode(opcode)) {
opcode = static_cast<WasmOpcode>(opcode << 8 | *(val.pc + 1));
}
PrintF(" %c@%d:%s", WasmOpcodes::ShortNameOf(val.type),
static_cast<int>(val.pc - this->start_),
WasmOpcodes::OpcodeName(opcode));
switch (opcode) {
case kExprI32Const: {
ImmI32Operand<validate> operand(this, val.pc);
PrintF("[%d]", operand.value);
break;
}
case kExprGetLocal: {
LocalIndexOperand<validate> operand(this, val.pc);
PrintF("[%u]", operand.index);
break;
}
case kExprSetLocal: // fallthru
case kExprTeeLocal: {
LocalIndexOperand<validate> operand(this, val.pc);
PrintF("[%u]", operand.index);
break;
}
default:
break;
}
}
PrintF("\n");
}
#endif
this->pc_ += len;
} // end decode loop
if (this->pc_ > this->end_ && this->ok()) this->error("Beyond end of code");
}
void EndControl() {
DCHECK(!control_.empty());
auto* current = &control_.back();
stack_.resize(current->stack_depth);
current->unreachable = true;
interface_.EndControl(this, current);
}
void SetBlockType(Control* c, BlockTypeOperand<validate>& operand) {
c->merge.arity = operand.arity;
if (c->merge.arity == 1) {
c->merge.vals.first = Value::New(this->pc_, operand.read_entry(0));
} else if (c->merge.arity > 1) {
c->merge.vals.array = zone_->NewArray<Value>(c->merge.arity);
for (unsigned i = 0; i < c->merge.arity; i++) {
c->merge.vals.array[i] = Value::New(this->pc_, operand.read_entry(i));
}
}
}
// TODO(clemensh): Better memory management.
void PopArgs(FunctionSig* sig, std::vector<Value>* result) {
DCHECK(result->empty());
int count = static_cast<int>(sig->parameter_count());
result->resize(count);
for (int i = count - 1; i >= 0; --i) {
(*result)[i] = Pop(i, sig->GetParam(i));
}
}
ValueType GetReturnType(FunctionSig* sig) {
DCHECK_GE(1, sig->return_count());
return sig->return_count() == 0 ? kWasmStmt : sig->GetReturn();
}
Control* PushBlock() {
control_.emplace_back(Control::Block(this->pc_, stack_.size()));
return &control_.back();
}
Control* PushLoop() {
control_.emplace_back(Control::Loop(this->pc_, stack_.size()));
return &control_.back();
}
Control* PushIf() {
control_.emplace_back(Control::If(this->pc_, stack_.size()));
return &control_.back();
}
Control* PushTry() {
control_.emplace_back(Control::Try(this->pc_, stack_.size()));
// current_catch_ = static_cast<int32_t>(control_.size() - 1);
return &control_.back();
}
void PopControl(Control* c) {
DCHECK_EQ(c, &control_.back());
interface_.PopControl(this, *c);
control_.pop_back();
}
int DecodeLoadMem(ValueType type, MachineType mem_type) {
if (!CheckHasMemory()) return 0;
MemoryAccessOperand<validate> operand(
this, this->pc_, ElementSizeLog2Of(mem_type.representation()));
auto index = Pop(0, kWasmI32);
auto* result = Push(type);
interface_.LoadMem(this, type, mem_type, operand, index, result);
return 1 + operand.length;
}
int DecodeStoreMem(ValueType type, MachineType mem_type) {
if (!CheckHasMemory()) return 0;
MemoryAccessOperand<validate> operand(
this, this->pc_, ElementSizeLog2Of(mem_type.representation()));
auto value = Pop(1, type);
auto index = Pop(0, kWasmI32);
interface_.StoreMem(this, type, mem_type, operand, index, value);
return 1 + operand.length;
}
int DecodePrefixedLoadMem(ValueType type, MachineType mem_type) {
if (!CheckHasMemory()) return 0;
MemoryAccessOperand<validate> operand(
this, this->pc_ + 1, ElementSizeLog2Of(mem_type.representation()));
auto index = Pop(0, kWasmI32);
auto* result = Push(type);
interface_.LoadMem(this, type, mem_type, operand, index, result);
return operand.length;
}
int DecodePrefixedStoreMem(ValueType type, MachineType mem_type) {
if (!CheckHasMemory()) return 0;
MemoryAccessOperand<validate> operand(
this, this->pc_ + 1, ElementSizeLog2Of(mem_type.representation()));
auto value = Pop(1, type);
auto index = Pop(0, kWasmI32);
interface_.StoreMem(this, type, mem_type, operand, index, value);
return operand.length;
}
unsigned SimdExtractLane(WasmOpcode opcode, ValueType type) {
SimdLaneOperand<validate> operand(this, this->pc_);
if (this->Validate(this->pc_, opcode, operand)) {
Value inputs[] = {Pop(0, ValueType::kSimd128)};
auto* result = Push(type);
interface_.SimdLaneOp(this, opcode, operand, ArrayVector(inputs), result);
}
return operand.length;
}
unsigned SimdReplaceLane(WasmOpcode opcode, ValueType type) {
SimdLaneOperand<validate> operand(this, this->pc_);
if (this->Validate(this->pc_, opcode, operand)) {
Value inputs[2];
inputs[1] = Pop(1, type);
inputs[0] = Pop(0, ValueType::kSimd128);
auto* result = Push(ValueType::kSimd128);
interface_.SimdLaneOp(this, opcode, operand, ArrayVector(inputs), result);
}
return operand.length;
}
unsigned SimdShiftOp(WasmOpcode opcode) {
SimdShiftOperand<validate> operand(this, this->pc_);
if (this->Validate(this->pc_, opcode, operand)) {
auto input = Pop(0, ValueType::kSimd128);
auto* result = Push(ValueType::kSimd128);
interface_.SimdShiftOp(this, opcode, operand, input, result);
}
return operand.length;
}
unsigned Simd8x16ShuffleOp() {
Simd8x16ShuffleOperand<validate> operand(this, this->pc_);
if (this->Validate(this->pc_, operand)) {
auto input1 = Pop(1, ValueType::kSimd128);
auto input0 = Pop(0, ValueType::kSimd128);
auto* result = Push(ValueType::kSimd128);
interface_.Simd8x16ShuffleOp(this, operand, input0, input1, result);
}
return 16;
}
unsigned DecodeSimdOpcode(WasmOpcode opcode) {
unsigned len = 0;
switch (opcode) {
case kExprF32x4ExtractLane: {
len = SimdExtractLane(opcode, ValueType::kFloat32);
break;
}
case kExprI32x4ExtractLane:
case kExprI16x8ExtractLane:
case kExprI8x16ExtractLane: {
len = SimdExtractLane(opcode, ValueType::kWord32);
break;
}
case kExprF32x4ReplaceLane: {
len = SimdReplaceLane(opcode, ValueType::kFloat32);
break;
}
case kExprI32x4ReplaceLane:
case kExprI16x8ReplaceLane:
case kExprI8x16ReplaceLane: {
len = SimdReplaceLane(opcode, ValueType::kWord32);
break;
}
case kExprI32x4Shl:
case kExprI32x4ShrS:
case kExprI32x4ShrU:
case kExprI16x8Shl:
case kExprI16x8ShrS:
case kExprI16x8ShrU:
case kExprI8x16Shl:
case kExprI8x16ShrS:
case kExprI8x16ShrU: {
len = SimdShiftOp(opcode);
break;
}
case kExprS8x16Shuffle: {
len = Simd8x16ShuffleOp();
break;
}
case kExprS128LoadMem:
len = DecodePrefixedLoadMem(kWasmS128, MachineType::Simd128());
break;
case kExprS128StoreMem:
len = DecodePrefixedStoreMem(kWasmS128, MachineType::Simd128());
break;
default: {
FunctionSig* sig = WasmOpcodes::Signature(opcode);
if (CHECK_ERROR(sig == nullptr)) {
this->error("invalid simd opcode");
break;
}
std::vector<Value> args;
PopArgs(sig, &args);
auto* result =
sig->return_count() == 0 ? nullptr : Push(GetReturnType(sig));
interface_.SimdOp(this, opcode, vec2vec(args), result);
}
}
return len;
}
unsigned DecodeAtomicOpcode(WasmOpcode opcode) {
unsigned len = 0;
FunctionSig* sig = WasmOpcodes::AtomicSignature(opcode);
if (sig != nullptr) {
// TODO(clemensh): Better memory management here.
std::vector<Value> args(sig->parameter_count());
for (int i = static_cast<int>(sig->parameter_count() - 1); i >= 0; --i) {
args[i] = Pop(i, sig->GetParam(i));
}
auto* result = Push(GetReturnType(sig));
interface_.AtomicOp(this, opcode, vec2vec(args), result);
} else {
this->error("invalid atomic opcode");
}
return len;
}
void DoReturn() {
// TODO(clemensh): Optimize memory usage here (it will be mostly 0 or 1
// returned values).
int return_count = static_cast<int>(this->sig_->return_count());
std::vector<Value> values(return_count);
// Pop return values off the stack in reverse order.
for (int i = return_count - 1; i >= 0; --i) {
values[i] = Pop(i, this->sig_->GetReturn(i));
}
interface_.DoReturn(this, vec2vec(values));
EndControl();
}
inline Value* Push(ValueType type) {
DCHECK(type != kWasmStmt);
stack_.push_back(Value::New(this->pc_, type));
return &stack_.back();
}
void PushEndValues(Control* c) {
DCHECK_EQ(c, &control_.back());
stack_.resize(c->stack_depth);
if (c->merge.arity == 1) {
stack_.push_back(c->merge.vals.first);
} else {
for (unsigned i = 0; i < c->merge.arity; i++) {
stack_.push_back(c->merge.vals.array[i]);
}
}
DCHECK_EQ(c->stack_depth + c->merge.arity, stack_.size());
}
Value* PushReturns(FunctionSig* sig) {
size_t return_count = sig->return_count();
if (return_count == 0) return nullptr;
size_t old_size = stack_.size();
for (size_t i = 0; i < return_count; ++i) {
Push(sig->GetReturn(i));
}
return stack_.data() + old_size;
}
Value Pop(int index, ValueType expected) {
auto val = Pop();
if (CHECK_ERROR(val.type != expected && val.type != kWasmVar &&
expected != kWasmVar)) {
this->errorf(val.pc, "%s[%d] expected type %s, found %s of type %s",
SafeOpcodeNameAt(this->pc_), index,
WasmOpcodes::TypeName(expected), SafeOpcodeNameAt(val.pc),
WasmOpcodes::TypeName(val.type));
}
return val;
}
Value Pop() {
DCHECK(!control_.empty());
size_t limit = control_.back().stack_depth;
if (stack_.size() <= limit) {
// Popping past the current control start in reachable code.
if (CHECK_ERROR(!control_.back().unreachable)) {
this->errorf(this->pc_, "%s found empty stack",
SafeOpcodeNameAt(this->pc_));
}
return Value::Unreachable(this->pc_);
}
auto val = stack_.back();
stack_.pop_back();
return val;
}
int startrel(const byte* ptr) { return static_cast<int>(ptr - this->start_); }
bool TypeCheckBreak(unsigned depth) {
DCHECK(validate); // Only call this for validation.
Control* c = control_at(depth);
if (c->is_loop()) {
// This is the inner loop block, which does not have a value.
return true;
}
size_t expected = control_.back().stack_depth + c->merge.arity;
if (stack_.size() < expected && !control_.back().unreachable) {
this->errorf(
this->pc_,
"expected at least %u values on the stack for br to @%d, found %d",
c->merge.arity, startrel(c->pc),
static_cast<int>(stack_.size() - c->stack_depth));
return false;
}
return TypeCheckMergeValues(c);
}
void FallThruTo(Control* c) {
DCHECK_EQ(c, &control_.back());
if (!TypeCheckFallThru(c)) return;
c->unreachable = false;
interface_.FallThruTo(this, c);
}
bool TypeCheckMergeValues(Control* c) {
// Typecheck the values left on the stack.
size_t avail = stack_.size() - c->stack_depth;
size_t start = avail >= c->merge.arity ? 0 : c->merge.arity - avail;
for (size_t i = start; i < c->merge.arity; ++i) {
auto& val = GetMergeValueFromStack(c, i);
auto& old = c->merge[i];
if (val.type != old.type && val.type != kWasmVar) {
this->errorf(
this->pc_, "type error in merge[%zu] (expected %s, got %s)", i,
WasmOpcodes::TypeName(old.type), WasmOpcodes::TypeName(val.type));
return false;
}
}
return true;
}
bool TypeCheckFallThru(Control* c) {
DCHECK_EQ(c, &control_.back());
if (!validate) return true;
// Fallthru must match arity exactly.
size_t expected = c->stack_depth + c->merge.arity;
if (stack_.size() != expected &&
(stack_.size() > expected || !c->unreachable)) {
this->errorf(this->pc_,
"expected %u elements on the stack for fallthru to @%d",
c->merge.arity, startrel(c->pc));
return false;
}
return TypeCheckMergeValues(c);
}
virtual void onFirstError() {
this->end_ = this->pc_; // Terminate decoding loop.
TRACE(" !%s\n", this->error_msg_.c_str());
}
inline void BuildSimpleOperator(WasmOpcode opcode, FunctionSig* sig) {
switch (sig->parameter_count()) {
case 1: {
auto val = Pop(0, sig->GetParam(0));
auto* ret =
sig->return_count() == 0 ? nullptr : Push(sig->GetReturn(0));
interface_.UnOp(this, opcode, sig, val, ret);
break;
}
case 2: {
auto rval = Pop(1, sig->GetParam(1));
auto lval = Pop(0, sig->GetParam(0));
auto* ret =
sig->return_count() == 0 ? nullptr : Push(sig->GetReturn(0));
interface_.BinOp(this, opcode, sig, lval, rval, ret);
break;
}
default:
UNREACHABLE();
}
}
};
template <bool decoder_validate, typename Interface>
class InterfaceTemplate {
public:
constexpr static bool validate = decoder_validate;
using Decoder = WasmFullDecoder<validate, Interface>;
using Control = AbstractControl<Interface>;
using Value = AbstractValue<Interface>;
using MergeValues = AbstractMerge<Interface>;
};
class EmptyInterface : public InterfaceTemplate<true, EmptyInterface> {
public:
struct IValue {
static IValue Unreachable() { return {}; }
static IValue New() { return {}; }
};
struct IControl {
static IControl Block() { return {}; }
static IControl If() { return {}; }
static IControl Loop() { return {}; }
static IControl Try() { return {}; }
};
#define DEFINE_EMPTY_CALLBACK(name, ...) \
void name(Decoder* decoder, ##__VA_ARGS__) {}
INTERFACE_FUNCTIONS(DEFINE_EMPTY_CALLBACK)
#undef DEFINE_EMPTY_CALLBACK
};
#undef CHECKED_COND
#undef VALIDATE
#undef CHECK_ERROR
#undef TRACE
#undef CHECK_PROTOTYPE_OPCODE
#undef PROTOTYPE_NOT_FUNCTIONAL
} // namespace wasm
} // namespace internal
......
......@@ -5,7 +5,6 @@
#include "src/signature.h"
#include "src/base/platform/elapsed-timer.h"
#include "src/bit-vector.h"
#include "src/flags.h"
#include "src/handles.h"
#include "src/objects-inl.h"
......@@ -26,26 +25,7 @@ namespace v8 {
namespace internal {
namespace wasm {
#if DEBUG
#define TRACE(...) \
do { \
if (FLAG_trace_wasm_decoder) PrintF(__VA_ARGS__); \
} while (false)
#else
#define TRACE(...)
#endif
#define CHECK_PROTOTYPE_OPCODE(flag) \
if (module_ != nullptr && module_->is_asm_js()) { \
error("Opcode not supported for asmjs modules"); \
} \
if (!FLAG_experimental_wasm_##flag) { \
error("Invalid opcode (enable with --experimental-wasm-" #flag ")"); \
break; \
}
#define OPCODE_ERROR(opcode, message) \
(errorf(pc_, "%s: %s", WasmOpcodes::OpcodeName(opcode), (message)))
namespace {
// An SsaEnv environment carries the current local variable renaming
// as well as the current effect and control dependency in the TF graph.
......@@ -71,1793 +51,409 @@ struct SsaEnv {
}
};
// An entry on the value stack.
struct Value {
const byte* pc;
TFNode* node;
ValueType type;
};
struct TryInfo : public ZoneObject {
SsaEnv* catch_env;
TFNode* exception;
size_t catch_count; // Number of catch blocks associated with the try.
explicit TryInfo(SsaEnv* c)
: catch_env(c), exception(nullptr), catch_count(0) {}
};
struct MergeValues {
uint32_t arity;
union {
Value* array;
Value first;
} vals; // Either multiple values or a single value.
Value& operator[](size_t i) {
DCHECK_GT(arity, i);
return arity == 1 ? vals.first : vals.array[i];
}
};
static Value* NO_VALUE = nullptr;
enum ControlKind { kControlIf, kControlBlock, kControlLoop, kControlTry };
// An entry on the control stack (i.e. if, block, loop).
struct Control {
const byte* pc;
ControlKind kind;
size_t stack_depth; // stack height at the beginning of the construct.
SsaEnv* end_env; // end environment for the construct.
SsaEnv* false_env; // false environment (only for if).
TryInfo* try_info; // Information used for compiling try statements.
int32_t previous_catch; // The previous Control (on the stack) with a catch.
bool unreachable; // The current block has been ended.
// Values merged into the end of this control construct.
MergeValues merge;
inline bool is_if() const { return kind == kControlIf; }
inline bool is_block() const { return kind == kControlBlock; }
inline bool is_loop() const { return kind == kControlLoop; }
inline bool is_try() const { return kind == kControlTry; }
// Named constructors.
static Control Block(const byte* pc, size_t stack_depth, SsaEnv* end_env,
int32_t previous_catch) {
return {pc, kControlBlock, stack_depth, end_env, nullptr,
nullptr, previous_catch, false, {0, {NO_VALUE}}};
}
static Control If(const byte* pc, size_t stack_depth, SsaEnv* end_env,
SsaEnv* false_env, int32_t previous_catch) {
return {pc, kControlIf, stack_depth, end_env, false_env,
nullptr, previous_catch, false, {0, {NO_VALUE}}};
}
static Control Loop(const byte* pc, size_t stack_depth, SsaEnv* end_env,
int32_t previous_catch) {
return {pc, kControlLoop, stack_depth, end_env, nullptr,
nullptr, previous_catch, false, {0, {NO_VALUE}}};
}
static Control Try(const byte* pc, size_t stack_depth, SsaEnv* end_env,
Zone* zone, SsaEnv* catch_env, int32_t previous_catch) {
DCHECK_NOT_NULL(catch_env);
TryInfo* try_info = new (zone) TryInfo(catch_env);
return {pc, kControlTry, stack_depth, end_env, nullptr,
try_info, previous_catch, false, {0, {NO_VALUE}}};
}
};
// Macros that build nodes only if there is a graph and the current SSA
// environment is reachable from start. This avoids problems with malformed
// TF graphs when decoding inputs that have unreachable code.
#define BUILD(func, ...) \
(build() ? CheckForException(builder_->func(__VA_ARGS__)) : nullptr)
#define BUILD0(func) (build() ? CheckForException(builder_->func()) : nullptr)
#define BUILD(func, ...) \
(build(decoder) ? CheckForException(decoder, builder_->func(__VA_ARGS__)) \
: nullptr)
// Generic Wasm bytecode decoder with utilities for decoding operands,
// lengths, etc.
class WasmDecoder : public Decoder {
public:
WasmDecoder(const WasmModule* module, FunctionSig* sig, const byte* start,
const byte* end, uint32_t buffer_offset = 0)
: Decoder(start, end, buffer_offset),
module_(module),
sig_(sig),
local_types_(nullptr) {}
const WasmModule* module_;
FunctionSig* sig_;
ZoneVector<ValueType>* local_types_;
size_t total_locals() const {
return local_types_ == nullptr ? 0 : local_types_->size();
}
constexpr uint32_t kNullCatch = static_cast<uint32_t>(-1);
static bool DecodeLocals(Decoder* decoder, const FunctionSig* sig,
ZoneVector<ValueType>* type_list) {
DCHECK_NOT_NULL(type_list);
DCHECK_EQ(0, type_list->size());
// Initialize from signature.
if (sig != nullptr) {
type_list->assign(sig->parameters().begin(), sig->parameters().end());
}
// Decode local declarations, if any.
uint32_t entries = decoder->consume_u32v("local decls count");
if (decoder->failed()) return false;
TRACE("local decls count: %u\n", entries);
while (entries-- > 0 && decoder->ok() && decoder->more()) {
uint32_t count = decoder->consume_u32v("local count");
if (decoder->failed()) return false;
if ((count + type_list->size()) > kV8MaxWasmFunctionLocals) {
decoder->error(decoder->pc() - 1, "local count too large");
return false;
}
byte code = decoder->consume_u8("local type");
if (decoder->failed()) return false;
ValueType type;
switch (code) {
case kLocalI32:
type = kWasmI32;
break;
case kLocalI64:
type = kWasmI64;
break;
case kLocalF32:
type = kWasmF32;
break;
case kLocalF64:
type = kWasmF64;
break;
case kLocalS128:
type = kWasmS128;
break;
default:
decoder->error(decoder->pc() - 1, "invalid local type");
return false;
}
type_list->insert(type_list->end(), count, type);
}
DCHECK(decoder->ok());
return true;
}
class WasmGraphBuildingInterface
: public InterfaceTemplate<true, WasmGraphBuildingInterface> {
public:
struct IValue {
TFNode* node;
static BitVector* AnalyzeLoopAssignment(Decoder* decoder, const byte* pc,
int locals_count, Zone* zone) {
if (pc >= decoder->end()) return nullptr;
if (*pc != kExprLoop) return nullptr;
BitVector* assigned = new (zone) BitVector(locals_count, zone);
int depth = 0;
// Iteratively process all AST nodes nested inside the loop.
while (pc < decoder->end() && decoder->ok()) {
WasmOpcode opcode = static_cast<WasmOpcode>(*pc);
unsigned length = 1;
switch (opcode) {
case kExprLoop:
case kExprIf:
case kExprBlock:
case kExprTry:
length = OpcodeLength(decoder, pc);
depth++;
break;
case kExprSetLocal: // fallthru
case kExprTeeLocal: {
LocalIndexOperand<true> operand(decoder, pc);
if (assigned->length() > 0 &&
operand.index < static_cast<uint32_t>(assigned->length())) {
// Unverified code might have an out-of-bounds index.
assigned->Add(operand.index);
}
length = 1 + operand.length;
break;
}
case kExprEnd:
depth--;
break;
default:
length = OpcodeLength(decoder, pc);
break;
}
if (depth <= 0) break;
pc += length;
}
return decoder->ok() ? assigned : nullptr;
}
static IValue Unreachable() { return {nullptr}; }
static IValue New() { return {nullptr}; }
};
inline bool Validate(const byte* pc, LocalIndexOperand<true>& operand) {
if (operand.index < total_locals()) {
if (local_types_) {
operand.type = local_types_->at(operand.index);
} else {
operand.type = kWasmStmt;
}
return true;
}
errorf(pc + 1, "invalid local index: %u", operand.index);
return false;
}
struct TryInfo : public ZoneObject {
SsaEnv* catch_env;
TFNode* exception;
inline bool Validate(const byte* pc, ExceptionIndexOperand<true>& operand) {
if (module_ != nullptr && operand.index < module_->exceptions.size()) {
operand.exception = &module_->exceptions[operand.index];
return true;
}
errorf(pc + 1, "Invalid exception index: %u", operand.index);
return false;
}
explicit TryInfo(SsaEnv* c) : catch_env(c), exception(nullptr) {}
};
inline bool Validate(const byte* pc, GlobalIndexOperand<true>& operand) {
if (module_ != nullptr && operand.index < module_->globals.size()) {
operand.global = &module_->globals[operand.index];
operand.type = operand.global->type;
return true;
}
errorf(pc + 1, "invalid global index: %u", operand.index);
return false;
}
struct IControl {
SsaEnv* end_env; // end environment for the construct.
SsaEnv* false_env; // false environment (only for if).
TryInfo* try_info; // information used for compiling try statements.
int32_t previous_catch; // previous Control (on the stack) with a catch.
inline bool Complete(const byte* pc, CallFunctionOperand<true>& operand) {
if (module_ != nullptr && operand.index < module_->functions.size()) {
operand.sig = module_->functions[operand.index].sig;
return true;
}
return false;
}
static IControl Block() { return {}; }
static IControl If() { return {}; }
static IControl Loop() { return {}; }
static IControl Try() { return {}; }
};
inline bool Validate(const byte* pc, CallFunctionOperand<true>& operand) {
if (Complete(pc, operand)) {
return true;
}
errorf(pc + 1, "invalid function index: %u", operand.index);
return false;
}
explicit WasmGraphBuildingInterface(TFBuilder* builder) : builder_(builder) {}
inline bool Complete(const byte* pc, CallIndirectOperand<true>& operand) {
if (module_ != nullptr && operand.index < module_->signatures.size()) {
operand.sig = module_->signatures[operand.index];
return true;
}
return false;
}
void StartFunction(Decoder* decoder) {
SsaEnv* ssa_env =
reinterpret_cast<SsaEnv*>(decoder->zone()->New(sizeof(SsaEnv)));
uint32_t env_count = decoder->NumLocals();
size_t size = sizeof(TFNode*) * env_count;
ssa_env->state = SsaEnv::kReached;
ssa_env->locals =
size > 0 ? reinterpret_cast<TFNode**>(decoder->zone()->New(size))
: nullptr;
inline bool Validate(const byte* pc, CallIndirectOperand<true>& operand) {
if (module_ == nullptr || module_->function_tables.empty()) {
error("function table has to exist to execute call_indirect");
return false;
TFNode* start =
builder_->Start(static_cast<int>(decoder->sig_->parameter_count() + 1));
// Initialize local variables.
uint32_t index = 0;
for (; index < decoder->sig_->parameter_count(); ++index) {
ssa_env->locals[index] = builder_->Param(index);
}
if (Complete(pc, operand)) {
return true;
while (index < env_count) {
ValueType type = decoder->GetLocalType(index);
TFNode* node = DefaultValue(type);
while (index < env_count && decoder->GetLocalType(index) == type) {
// Do a whole run of like-typed locals at a time.
ssa_env->locals[index++] = node;
}
}
errorf(pc + 1, "invalid signature index: #%u", operand.index);
return false;
ssa_env->control = start;
ssa_env->effect = start;
SetEnv(ssa_env);
}
inline bool Validate(const byte* pc, BreakDepthOperand<true>& operand,
ZoneVector<Control>& control) {
if (operand.depth < control.size()) {
operand.target = &control[control.size() - operand.depth - 1];
return true;
}
errorf(pc + 1, "invalid break depth: %u", operand.depth);
return false;
void StartFunctionBody(Decoder* decoder, Control* block) {
SsaEnv* break_env = ssa_env_;
SetEnv(Steal(decoder->zone(), break_env));
block->interface_data.end_env = break_env;
}
bool Validate(const byte* pc, BranchTableOperand<true>& operand,
size_t block_depth) {
if (operand.table_count >= kV8MaxWasmFunctionSize) {
errorf(pc + 1, "invalid table count (> max function size): %u",
operand.table_count);
return false;
}
return checkAvailable(operand.table_count);
void FinishFunction(Decoder* decoder) {
builder_->PatchInStackCheckIfNeeded();
}
inline bool Validate(const byte* pc, WasmOpcode opcode,
SimdLaneOperand<true>& operand) {
uint8_t num_lanes = 0;
switch (opcode) {
case kExprF32x4ExtractLane:
case kExprF32x4ReplaceLane:
case kExprI32x4ExtractLane:
case kExprI32x4ReplaceLane:
num_lanes = 4;
break;
case kExprI16x8ExtractLane:
case kExprI16x8ReplaceLane:
num_lanes = 8;
break;
case kExprI8x16ExtractLane:
case kExprI8x16ReplaceLane:
num_lanes = 16;
break;
default:
UNREACHABLE();
break;
}
if (operand.lane < 0 || operand.lane >= num_lanes) {
error(pc_ + 2, "invalid lane index");
return false;
} else {
return true;
}
void Block(Decoder* decoder, Control* block) {
// The break environment is the outer environment.
block->interface_data.end_env = ssa_env_;
SetEnv(Steal(decoder->zone(), ssa_env_));
}
inline bool Validate(const byte* pc, WasmOpcode opcode,
SimdShiftOperand<true>& operand) {
uint8_t max_shift = 0;
switch (opcode) {
case kExprI32x4Shl:
case kExprI32x4ShrS:
case kExprI32x4ShrU:
max_shift = 32;
break;
case kExprI16x8Shl:
case kExprI16x8ShrS:
case kExprI16x8ShrU:
max_shift = 16;
break;
case kExprI8x16Shl:
case kExprI8x16ShrS:
case kExprI8x16ShrU:
max_shift = 8;
break;
default:
UNREACHABLE();
break;
}
if (operand.shift < 0 || operand.shift >= max_shift) {
error(pc_ + 2, "invalid shift amount");
return false;
} else {
return true;
}
void Loop(Decoder* decoder, Control* block) {
SsaEnv* finish_try_env = Steal(decoder->zone(), ssa_env_);
block->interface_data.end_env = finish_try_env;
// The continue environment is the inner environment.
SetEnv(PrepareForLoop(decoder, finish_try_env));
ssa_env_->SetNotMerged();
}
inline bool Validate(const byte* pc, Simd8x16ShuffleOperand<true>& operand) {
uint8_t max_lane = 0;
for (uint32_t i = 0; i < kSimd128Size; ++i)
max_lane = std::max(max_lane, operand.shuffle[i]);
// Shuffle indices must be in [0..31] for a 16 lane shuffle.
if (max_lane > 2 * kSimd128Size) {
error(pc_ + 2, "invalid shuffle mask");
return false;
} else {
return true;
}
void Try(Decoder* decoder, Control* block) {
SsaEnv* outer_env = ssa_env_;
SsaEnv* try_env = Steal(decoder->zone(), outer_env);
SsaEnv* catch_env = UnreachableEnv(decoder->zone());
SetEnv(try_env);
TryInfo* try_info = new (decoder->zone()) TryInfo(catch_env);
block->interface_data.end_env = outer_env;
block->interface_data.try_info = try_info;
block->interface_data.previous_catch = current_catch_;
current_catch_ = static_cast<int32_t>(decoder->control_depth() - 1);
}
static unsigned OpcodeLength(Decoder* decoder, const byte* pc) {
WasmOpcode opcode = static_cast<WasmOpcode>(*pc);
switch (opcode) {
#define DECLARE_OPCODE_CASE(name, opcode, sig) case kExpr##name:
FOREACH_LOAD_MEM_OPCODE(DECLARE_OPCODE_CASE)
FOREACH_STORE_MEM_OPCODE(DECLARE_OPCODE_CASE)
#undef DECLARE_OPCODE_CASE
{
MemoryAccessOperand<true> operand(decoder, pc, UINT32_MAX);
return 1 + operand.length;
}
case kExprBr:
case kExprBrIf: {
BreakDepthOperand<true> operand(decoder, pc);
return 1 + operand.length;
}
case kExprSetGlobal:
case kExprGetGlobal: {
GlobalIndexOperand<true> operand(decoder, pc);
return 1 + operand.length;
}
case kExprCallFunction: {
CallFunctionOperand<true> operand(decoder, pc);
return 1 + operand.length;
}
case kExprCallIndirect: {
CallIndirectOperand<true> operand(decoder, pc);
return 1 + operand.length;
}
case kExprTry:
case kExprIf: // fall through
case kExprLoop:
case kExprBlock: {
BlockTypeOperand<true> operand(decoder, pc);
return 1 + operand.length;
}
case kExprThrow:
case kExprCatch: {
ExceptionIndexOperand<true> operand(decoder, pc);
return 1 + operand.length;
}
case kExprSetLocal:
case kExprTeeLocal:
case kExprGetLocal: {
LocalIndexOperand<true> operand(decoder, pc);
return 1 + operand.length;
}
case kExprBrTable: {
BranchTableOperand<true> operand(decoder, pc);
BranchTableIterator<true> iterator(decoder, operand);
return 1 + iterator.length();
}
case kExprI32Const: {
ImmI32Operand<true> operand(decoder, pc);
return 1 + operand.length;
}
case kExprI64Const: {
ImmI64Operand<true> operand(decoder, pc);
return 1 + operand.length;
}
case kExprGrowMemory:
case kExprMemorySize: {
MemoryIndexOperand<true> operand(decoder, pc);
return 1 + operand.length;
}
case kExprF32Const:
return 5;
case kExprF64Const:
return 9;
case kSimdPrefix: {
byte simd_index = decoder->read_u8<true>(pc + 1, "simd_index");
WasmOpcode opcode =
static_cast<WasmOpcode>(kSimdPrefix << 8 | simd_index);
switch (opcode) {
#define DECLARE_OPCODE_CASE(name, opcode, sig) case kExpr##name:
FOREACH_SIMD_0_OPERAND_OPCODE(DECLARE_OPCODE_CASE)
#undef DECLARE_OPCODE_CASE
return 2;
#define DECLARE_OPCODE_CASE(name, opcode, sig) case kExpr##name:
FOREACH_SIMD_1_OPERAND_OPCODE(DECLARE_OPCODE_CASE)
#undef DECLARE_OPCODE_CASE
return 3;
#define DECLARE_OPCODE_CASE(name, opcode, sig) case kExpr##name:
FOREACH_SIMD_MEM_OPCODE(DECLARE_OPCODE_CASE)
#undef DECLARE_OPCODE_CASE
{
MemoryAccessOperand<true> operand(decoder, pc + 1, UINT32_MAX);
return 2 + operand.length;
}
// Shuffles require a byte per lane, or 16 immediate bytes.
case kExprS8x16Shuffle:
return 2 + kSimd128Size;
default:
decoder->error(pc, "invalid SIMD opcode");
return 2;
}
}
default:
return 1;
}
void If(Decoder* decoder, const Value& cond, Control* if_block) {
TFNode* if_true = nullptr;
TFNode* if_false = nullptr;
BUILD(BranchNoHint, cond.interface_data.node, &if_true, &if_false);
SsaEnv* end_env = ssa_env_;
SsaEnv* false_env = Split(decoder, ssa_env_);
false_env->control = if_false;
SsaEnv* true_env = Steal(decoder->zone(), ssa_env_);
true_env->control = if_true;
if_block->interface_data.end_env = end_env;
if_block->interface_data.false_env = false_env;
SetEnv(true_env);
}
std::pair<uint32_t, uint32_t> StackEffect(const byte* pc) {
WasmOpcode opcode = static_cast<WasmOpcode>(*pc);
// Handle "simple" opcodes with a fixed signature first.
FunctionSig* sig = WasmOpcodes::Signature(opcode);
if (!sig) sig = WasmOpcodes::AsmjsSignature(opcode);
if (sig) return {sig->parameter_count(), sig->return_count()};
if (WasmOpcodes::IsPrefixOpcode(opcode)) {
opcode = static_cast<WasmOpcode>(opcode << 8 | *(pc + 1));
}
#define DECLARE_OPCODE_CASE(name, opcode, sig) case kExpr##name:
// clang-format off
switch (opcode) {
case kExprSelect:
return {3, 1};
case kExprS128StoreMem:
FOREACH_STORE_MEM_OPCODE(DECLARE_OPCODE_CASE)
return {2, 0};
case kExprS128LoadMem:
FOREACH_LOAD_MEM_OPCODE(DECLARE_OPCODE_CASE)
case kExprTeeLocal:
case kExprGrowMemory:
return {1, 1};
case kExprSetLocal:
case kExprSetGlobal:
case kExprDrop:
case kExprBrIf:
case kExprBrTable:
case kExprIf:
return {1, 0};
case kExprGetLocal:
case kExprGetGlobal:
case kExprI32Const:
case kExprI64Const:
case kExprF32Const:
case kExprF64Const:
case kExprMemorySize:
return {0, 1};
case kExprCallFunction: {
CallFunctionOperand<true> operand(this, pc);
CHECK(Complete(pc, operand));
return {operand.sig->parameter_count(), operand.sig->return_count()};
}
case kExprCallIndirect: {
CallIndirectOperand<true> operand(this, pc);
CHECK(Complete(pc, operand));
// Indirect calls pop an additional argument for the table index.
return {operand.sig->parameter_count() + 1,
operand.sig->return_count()};
}
case kExprBr:
case kExprBlock:
case kExprLoop:
case kExprEnd:
case kExprElse:
case kExprNop:
case kExprReturn:
case kExprUnreachable:
return {0, 0};
default:
V8_Fatal(__FILE__, __LINE__, "unimplemented opcode: %x (%s)", opcode,
WasmOpcodes::OpcodeName(opcode));
return {0, 0};
}
#undef DECLARE_OPCODE_CASE
// clang-format on
void FallThruTo(Decoder* decoder, Control* c) {
MergeValuesInto(decoder, c);
SetEnv(c->interface_data.end_env);
}
};
static const int32_t kNullCatch = -1;
// The full wasm decoder for bytecode. Verifies bytecode and, optionally,
// generates a TurboFan IR graph.
class WasmFullDecoder : public WasmDecoder {
public:
WasmFullDecoder(Zone* zone, const wasm::WasmModule* module,
const FunctionBody& body)
: WasmFullDecoder(zone, module, nullptr, body) {}
WasmFullDecoder(Zone* zone, TFBuilder* builder, const FunctionBody& body)
: WasmFullDecoder(zone, builder->module(), builder, body) {}
bool Decode() {
if (FLAG_wasm_code_fuzzer_gen_test) {
PrintRawWasmCode(start_, end_);
}
base::ElapsedTimer decode_timer;
if (FLAG_trace_wasm_decode_time) {
decode_timer.Start();
}
stack_.clear();
control_.clear();
if (end_ < pc_) {
error("function body end < start");
return false;
}
DCHECK_EQ(0, local_types_->size());
WasmDecoder::DecodeLocals(this, sig_, local_types_);
InitSsaEnv();
DecodeFunctionBody();
FinishFunction();
if (failed()) return TraceFailed();
if (!control_.empty()) {
// Generate a better error message whether the unterminated control
// structure is the function body block or an innner structure.
if (control_.size() > 1) {
error(control_.back().pc, "unterminated control structure");
} else {
error("function body must end with \"end\" opcode");
}
return TraceFailed();
void PopControl(Decoder* decoder, const Control& block) {
if (block.is_onearmed_if()) {
Goto(decoder, block.interface_data.false_env,
block.interface_data.end_env);
} else if (block.is_try_catch()) {
SsaEnv* fallthru_ssa_env = ssa_env_;
DCHECK_NOT_NULL(block.interface_data.try_info->catch_env);
SetEnv(block.interface_data.try_info->catch_env);
BUILD(Rethrow);
// TODO(clemensh): Make this work again.
// FallThruTo(decoder, &block);
SetEnv(fallthru_ssa_env);
}
if (!last_end_found_) {
error("function body must end with \"end\" opcode");
return false;
}
if (FLAG_trace_wasm_decode_time) {
double ms = decode_timer.Elapsed().InMillisecondsF();
PrintF("wasm-decode %s (%0.3f ms)\n\n", ok() ? "ok" : "failed", ms);
} else {
TRACE("wasm-decode %s\n\n", ok() ? "ok" : "failed");
}
return true;
}
bool TraceFailed() {
TRACE("wasm-error module+%-6d func+%d: %s\n\n", error_offset_,
GetBufferRelativeOffset(error_offset_), error_msg_.c_str());
return false;
}
void EndControl(Decoder* decoder, Control* block) { ssa_env_->Kill(); }
private:
WasmFullDecoder(Zone* zone, const wasm::WasmModule* module,
TFBuilder* builder, const FunctionBody& body)
: WasmDecoder(module, body.sig, body.start, body.end, body.offset),
zone_(zone),
builder_(builder),
local_type_vec_(zone),
stack_(zone),
control_(zone),
last_end_found_(false),
current_catch_(kNullCatch) {
local_types_ = &local_type_vec_;
void UnOp(Decoder* decoder, WasmOpcode opcode, FunctionSig* sig,
const Value& value, Value* result) {
result->interface_data.node =
BUILD(Unop, opcode, value.interface_data.node, decoder->position());
}
static const size_t kErrorMsgSize = 128;
Zone* zone_;
TFBuilder* builder_;
SsaEnv* ssa_env_;
ZoneVector<ValueType> local_type_vec_; // types of local variables.
ZoneVector<Value> stack_; // stack of values.
ZoneVector<Control> control_; // stack of blocks, loops, and ifs.
bool last_end_found_;
int32_t current_catch_;
TryInfo* current_try_info() { return control_[current_catch_].try_info; }
inline bool build() { return builder_ && ssa_env_->go(); }
void InitSsaEnv() {
TFNode* start = nullptr;
SsaEnv* ssa_env = reinterpret_cast<SsaEnv*>(zone_->New(sizeof(SsaEnv)));
size_t size = sizeof(TFNode*) * EnvironmentCount();
ssa_env->state = SsaEnv::kReached;
ssa_env->locals =
size > 0 ? reinterpret_cast<TFNode**>(zone_->New(size)) : nullptr;
if (builder_) {
start = builder_->Start(static_cast<int>(sig_->parameter_count() + 1));
// Initialize local variables.
uint32_t index = 0;
while (index < sig_->parameter_count()) {
ssa_env->locals[index] = builder_->Param(index);
index++;
}
while (index < local_type_vec_.size()) {
ValueType type = local_type_vec_[index];
TFNode* node = DefaultValue(type);
while (index < local_type_vec_.size() &&
local_type_vec_[index] == type) {
// Do a whole run of like-typed locals at a time.
ssa_env->locals[index++] = node;
}
}
}
ssa_env->control = start;
ssa_env->effect = start;
SetEnv("initial", ssa_env);
void BinOp(Decoder* decoder, WasmOpcode opcode, FunctionSig* sig,
const Value& lhs, const Value& rhs, Value* result) {
result->interface_data.node =
BUILD(Binop, opcode, lhs.interface_data.node, rhs.interface_data.node,
decoder->position());
}
TFNode* DefaultValue(ValueType type) {
switch (type) {
case kWasmI32:
return builder_->Int32Constant(0);
case kWasmI64:
return builder_->Int64Constant(0);
case kWasmF32:
return builder_->Float32Constant(0);
case kWasmF64:
return builder_->Float64Constant(0);
case kWasmS128:
return builder_->S128Zero();
default:
UNREACHABLE();
}
void I32Const(Decoder* decoder, Value* result, int32_t value) {
result->interface_data.node = builder_->Int32Constant(value);
}
bool CheckHasMemory() {
if (!module_->has_memory) {
error(pc_ - 1, "memory instruction with no memory");
}
return module_->has_memory;
void I64Const(Decoder* decoder, Value* result, int64_t value) {
result->interface_data.node = builder_->Int64Constant(value);
}
template <bool check>
inline TFNode* GetExceptionTag(ExceptionIndexOperand<check>& operand) {
// TODO(kschimpf): Need to get runtime exception tag values. This
// code only handles non-imported/exported exceptions.
return BUILD(Int32Constant, operand.index);
void F32Const(Decoder* decoder, Value* result, float value) {
result->interface_data.node = builder_->Float32Constant(value);
}
// Decodes the body of a function.
void DecodeFunctionBody() {
TRACE("wasm-decode %p...%p (module+%u, %d bytes) %s\n",
reinterpret_cast<const void*>(start()),
reinterpret_cast<const void*>(end()), pc_offset(),
static_cast<int>(end_ - start_), builder_ ? "graph building" : "");
{
// Set up initial function block.
SsaEnv* break_env = ssa_env_;
SetEnv("initial env", Steal(break_env));
PushBlock(break_env);
Control* c = &control_.back();
c->merge.arity = static_cast<uint32_t>(sig_->return_count());
if (c->merge.arity == 1) {
c->merge.vals.first = {pc_, nullptr, sig_->GetReturn(0)};
} else if (c->merge.arity > 1) {
c->merge.vals.array = zone_->NewArray<Value>(c->merge.arity);
for (unsigned i = 0; i < c->merge.arity; i++) {
c->merge.vals.array[i] = {pc_, nullptr, sig_->GetReturn(i)};
}
}
}
while (pc_ < end_) { // decoding loop.
unsigned len = 1;
WasmOpcode opcode = static_cast<WasmOpcode>(*pc_);
#if DEBUG
if (FLAG_trace_wasm_decoder && !WasmOpcodes::IsPrefixOpcode(opcode)) {
TRACE(" @%-8d #%-20s|", startrel(pc_),
WasmOpcodes::OpcodeName(opcode));
}
#endif
FunctionSig* sig = WasmOpcodes::Signature(opcode);
if (sig) {
BuildSimpleOperator(opcode, sig);
} else {
// Complex bytecode.
switch (opcode) {
case kExprNop:
break;
case kExprBlock: {
// The break environment is the outer environment.
BlockTypeOperand<true> operand(this, pc_);
SsaEnv* break_env = ssa_env_;
PushBlock(break_env);
SetEnv("block:start", Steal(break_env));
SetBlockType(&control_.back(), operand);
len = 1 + operand.length;
break;
}
case kExprRethrow: {
// TODO(kschimpf): Implement.
CHECK_PROTOTYPE_OPCODE(eh);
OPCODE_ERROR(opcode, "not implemented yet");
break;
}
case kExprThrow: {
CHECK_PROTOTYPE_OPCODE(eh);
ExceptionIndexOperand<true> operand(this, pc_);
len = 1 + operand.length;
if (!Validate(pc_, operand)) break;
if (operand.exception->sig->parameter_count() > 0) {
// TODO(kschimpf): Fix to pull values off stack and build throw.
OPCODE_ERROR(opcode, "can't handle exceptions with values yet");
break;
}
BUILD(Throw, GetExceptionTag(operand));
// TODO(titzer): Throw should end control, but currently we build a
// (reachable) runtime call instead of connecting it directly to
// end.
// EndControl();
break;
}
case kExprTry: {
CHECK_PROTOTYPE_OPCODE(eh);
BlockTypeOperand<true> operand(this, pc_);
SsaEnv* outer_env = ssa_env_;
SsaEnv* try_env = Steal(outer_env);
SsaEnv* catch_env = UnreachableEnv();
PushTry(outer_env, catch_env);
SetEnv("try_catch:start", try_env);
SetBlockType(&control_.back(), operand);
len = 1 + operand.length;
break;
}
case kExprCatch: {
// TODO(kschimpf): Fix to use type signature of exception.
CHECK_PROTOTYPE_OPCODE(eh);
ExceptionIndexOperand<true> operand(this, pc_);
len = 1 + operand.length;
if (!Validate(pc_, operand)) break;
if (control_.empty()) {
error("catch does not match any try");
break;
}
Control* c = &control_.back();
DCHECK_NOT_NULL(c->try_info);
if (!c->is_try()) {
error("catch does not match any try");
break;
}
if (c->try_info->catch_count > 0) {
OPCODE_ERROR(opcode, "multiple catch blocks not implemented");
break;
}
++c->try_info->catch_count;
FallThruTo(c);
stack_.resize(c->stack_depth);
SsaEnv* catch_env = c->try_info->catch_env;
SetEnv("catch:begin", catch_env);
current_catch_ = c->previous_catch;
// Get the exception and see if wanted exception.
TFNode* exception_as_i32 =
BUILD(Catch, c->try_info->exception, position());
TFNode* exception_tag = GetExceptionTag(operand);
TFNode* compare_i32 = BUILD(Binop, kExprI32Eq, exception_as_i32,
exception_tag, position());
TFNode* if_true = nullptr;
TFNode* if_false = nullptr;
BUILD(BranchNoHint, compare_i32, &if_true, &if_false);
SsaEnv* end_env = ssa_env_;
SsaEnv* false_env = Split(end_env);
false_env->control = if_false;
SsaEnv* true_env = Steal(ssa_env_);
true_env->control = if_true;
c->try_info->catch_env = false_env;
SetEnv("Try:catch", true_env);
len = 1 + operand.length;
// TODO(kschimpf): Add code to pop caught exception from isolate.
break;
}
case kExprCatchAll: {
// TODO(kschimpf): Implement.
CHECK_PROTOTYPE_OPCODE(eh);
OPCODE_ERROR(opcode, "not implemented yet");
break;
}
case kExprLoop: {
BlockTypeOperand<true> operand(this, pc_);
SsaEnv* finish_try_env = Steal(ssa_env_);
// The continue environment is the inner environment.
SsaEnv* loop_body_env = PrepareForLoop(pc_, finish_try_env);
SetEnv("loop:start", loop_body_env);
ssa_env_->SetNotMerged();
PushLoop(finish_try_env);
SetBlockType(&control_.back(), operand);
len = 1 + operand.length;
break;
}
case kExprIf: {
// Condition on top of stack. Split environments for branches.
BlockTypeOperand<true> operand(this, pc_);
Value cond = Pop(0, kWasmI32);
TFNode* if_true = nullptr;
TFNode* if_false = nullptr;
BUILD(BranchNoHint, cond.node, &if_true, &if_false);
SsaEnv* end_env = ssa_env_;
SsaEnv* false_env = Split(ssa_env_);
false_env->control = if_false;
SsaEnv* true_env = Steal(ssa_env_);
true_env->control = if_true;
PushIf(end_env, false_env);
SetEnv("if:true", true_env);
SetBlockType(&control_.back(), operand);
len = 1 + operand.length;
break;
}
case kExprElse: {
if (control_.empty()) {
error("else does not match any if");
break;
}
Control* c = &control_.back();
if (!c->is_if()) {
error(pc_, "else does not match an if");
break;
}
if (c->false_env == nullptr) {
error(pc_, "else already present for if");
break;
}
FallThruTo(c);
stack_.resize(c->stack_depth);
// Switch to environment for false branch.
SetEnv("if_else:false", c->false_env);
c->false_env = nullptr; // record that an else is already seen
break;
}
case kExprEnd: {
if (control_.empty()) {
error("end does not match any if, try, or block");
return;
}
const char* name = "block:end";
Control* c = &control_.back();
if (c->is_loop()) {
// A loop just leaves the values on the stack.
TypeCheckFallThru(c);
if (c->unreachable) PushEndValues(c);
PopControl();
SetEnv("loop:end", ssa_env_);
break;
}
if (c->is_if()) {
if (c->false_env != nullptr) {
// End the true branch of a one-armed if.
Goto(c->false_env, c->end_env);
if (!c->unreachable && stack_.size() != c->stack_depth) {
error("end of if expected empty stack");
stack_.resize(c->stack_depth);
}
if (c->merge.arity > 0) {
error("non-void one-armed if");
}
name = "if:merge";
} else {
// End the false branch of a two-armed if.
name = "if_else:merge";
}
} else if (c->is_try()) {
name = "try:end";
// validate that catch was seen.
if (c->try_info->catch_count == 0) {
error(pc_, "missing catch in try");
break;
}
SsaEnv* fallthru_ssa_env = ssa_env_;
DCHECK_NOT_NULL(c->try_info->catch_env);
SetEnv("Catch fail", c->try_info->catch_env);
BUILD0(Rethrow);
// TODO(karlschimpf): Why not use EndControl ()? (currently fails)
FallThruTo(c);
SetEnv("Catch fallthru", fallthru_ssa_env);
}
FallThruTo(c);
SetEnv(name, c->end_env);
PushEndValues(c);
if (control_.size() == 1) {
// If at the last (implicit) control, check we are at end.
if (pc_ + 1 != end_) {
error(pc_ + 1, "trailing code after function end");
break;
}
last_end_found_ = true;
if (ssa_env_->go()) {
// The result of the block is the return value.
TRACE(" @%-8d #xx:%-20s|", startrel(pc_), "(implicit) return");
DoReturn();
TRACE("\n");
} else {
TypeCheckFallThru(c);
}
}
PopControl();
break;
}
case kExprSelect: {
Value cond = Pop(2, kWasmI32);
Value fval = Pop();
Value tval = Pop(0, fval.type);
if (build()) {
TFNode* controls[2];
builder_->BranchNoHint(cond.node, &controls[0], &controls[1]);
TFNode* merge = builder_->Merge(2, controls);
TFNode* vals[2] = {tval.node, fval.node};
TFNode* phi = builder_->Phi(tval.type, 2, vals, merge);
Push(tval.type, phi);
ssa_env_->control = merge;
} else {
Push(tval.type == kWasmVar ? fval.type : tval.type, nullptr);
}
break;
}
case kExprBr: {
BreakDepthOperand<true> operand(this, pc_);
if (Validate(pc_, operand, control_)) {
BreakTo(operand.depth);
}
len = 1 + operand.length;
EndControl();
break;
}
case kExprBrIf: {
BreakDepthOperand<true> operand(this, pc_);
Value cond = Pop(0, kWasmI32);
if (ok() && Validate(pc_, operand, control_)) {
SsaEnv* fenv = ssa_env_;
SsaEnv* tenv = Split(fenv);
fenv->SetNotMerged();
BUILD(BranchNoHint, cond.node, &tenv->control, &fenv->control);
ssa_env_ = tenv;
BreakTo(operand.depth);
ssa_env_ = fenv;
}
len = 1 + operand.length;
break;
}
case kExprBrTable: {
BranchTableOperand<true> operand(this, pc_);
BranchTableIterator<true> iterator(this, operand);
if (Validate(pc_, operand, control_.size())) {
Value key = Pop(0, kWasmI32);
if (failed()) break;
SsaEnv* break_env = ssa_env_;
if (operand.table_count > 0) {
// Build branches to the various blocks based on the table.
TFNode* sw = BUILD(Switch, operand.table_count + 1, key.node);
SsaEnv* copy = Steal(break_env);
ssa_env_ = copy;
MergeValues* merge = nullptr;
while (ok() && iterator.has_next()) {
uint32_t i = iterator.cur_index();
const byte* pos = iterator.pc();
uint32_t target = iterator.next();
if (target >= control_.size()) {
error(pos, "improper branch in br_table");
break;
}
ssa_env_ = Split(copy);
ssa_env_->control = (i == operand.table_count)
? BUILD(IfDefault, sw)
: BUILD(IfValue, i, sw);
BreakTo(target);
// Check that label types match up.
static MergeValues loop_dummy = {0, {nullptr}};
Control* c = &control_[control_.size() - target - 1];
MergeValues* current = c->is_loop() ? &loop_dummy : &c->merge;
if (i == 0) {
merge = current;
} else if (merge->arity != current->arity) {
errorf(pos,
"inconsistent arity in br_table target %d"
" (previous was %u, this one %u)",
i, merge->arity, current->arity);
} else if (control_.back().unreachable) {
for (uint32_t j = 0; ok() && j < merge->arity; ++j) {
if ((*merge)[j].type != (*current)[j].type) {
errorf(pos,
"type error in br_table target %d operand %d"
" (previous expected %s, this one %s)",
i, j, WasmOpcodes::TypeName((*merge)[j].type),
WasmOpcodes::TypeName((*current)[j].type));
}
}
}
}
if (failed()) break;
} else {
// Only a default target. Do the equivalent of br.
const byte* pos = iterator.pc();
uint32_t target = iterator.next();
if (target >= control_.size()) {
error(pos, "improper branch in br_table");
break;
}
BreakTo(target);
}
// br_table ends the control flow like br.
ssa_env_ = break_env;
}
len = 1 + iterator.length();
EndControl();
break;
}
case kExprReturn: {
DoReturn();
break;
}
case kExprUnreachable: {
BUILD(Unreachable, position());
EndControl();
break;
}
case kExprI32Const: {
ImmI32Operand<true> operand(this, pc_);
Push(kWasmI32, BUILD(Int32Constant, operand.value));
len = 1 + operand.length;
break;
}
case kExprI64Const: {
ImmI64Operand<true> operand(this, pc_);
Push(kWasmI64, BUILD(Int64Constant, operand.value));
len = 1 + operand.length;
break;
}
case kExprF32Const: {
ImmF32Operand<true> operand(this, pc_);
Push(kWasmF32, BUILD(Float32Constant, operand.value));
len = 1 + operand.length;
break;
}
case kExprF64Const: {
ImmF64Operand<true> operand(this, pc_);
Push(kWasmF64, BUILD(Float64Constant, operand.value));
len = 1 + operand.length;
break;
}
case kExprGetLocal: {
LocalIndexOperand<true> operand(this, pc_);
if (Validate(pc_, operand)) {
if (build()) {
Push(operand.type, ssa_env_->locals[operand.index]);
} else {
Push(operand.type, nullptr);
}
}
len = 1 + operand.length;
break;
}
case kExprSetLocal: {
LocalIndexOperand<true> operand(this, pc_);
if (Validate(pc_, operand)) {
Value val = Pop(0, local_type_vec_[operand.index]);
if (ssa_env_->locals) ssa_env_->locals[operand.index] = val.node;
}
len = 1 + operand.length;
break;
}
case kExprTeeLocal: {
LocalIndexOperand<true> operand(this, pc_);
if (Validate(pc_, operand)) {
Value val = Pop(0, local_type_vec_[operand.index]);
if (ssa_env_->locals) ssa_env_->locals[operand.index] = val.node;
Push(val.type, val.node);
}
len = 1 + operand.length;
break;
}
case kExprDrop: {
Pop();
break;
}
case kExprGetGlobal: {
GlobalIndexOperand<true> operand(this, pc_);
if (Validate(pc_, operand)) {
Push(operand.type, BUILD(GetGlobal, operand.index));
}
len = 1 + operand.length;
break;
}
case kExprSetGlobal: {
GlobalIndexOperand<true> operand(this, pc_);
if (Validate(pc_, operand)) {
if (operand.global->mutability) {
Value val = Pop(0, operand.type);
BUILD(SetGlobal, operand.index, val.node);
} else {
errorf(pc_, "immutable global #%u cannot be assigned",
operand.index);
}
}
len = 1 + operand.length;
break;
}
case kExprI32LoadMem8S:
len = DecodeLoadMem(kWasmI32, MachineType::Int8());
break;
case kExprI32LoadMem8U:
len = DecodeLoadMem(kWasmI32, MachineType::Uint8());
break;
case kExprI32LoadMem16S:
len = DecodeLoadMem(kWasmI32, MachineType::Int16());
break;
case kExprI32LoadMem16U:
len = DecodeLoadMem(kWasmI32, MachineType::Uint16());
break;
case kExprI32LoadMem:
len = DecodeLoadMem(kWasmI32, MachineType::Int32());
break;
case kExprI64LoadMem8S:
len = DecodeLoadMem(kWasmI64, MachineType::Int8());
break;
case kExprI64LoadMem8U:
len = DecodeLoadMem(kWasmI64, MachineType::Uint8());
break;
case kExprI64LoadMem16S:
len = DecodeLoadMem(kWasmI64, MachineType::Int16());
break;
case kExprI64LoadMem16U:
len = DecodeLoadMem(kWasmI64, MachineType::Uint16());
break;
case kExprI64LoadMem32S:
len = DecodeLoadMem(kWasmI64, MachineType::Int32());
break;
case kExprI64LoadMem32U:
len = DecodeLoadMem(kWasmI64, MachineType::Uint32());
break;
case kExprI64LoadMem:
len = DecodeLoadMem(kWasmI64, MachineType::Int64());
break;
case kExprF32LoadMem:
len = DecodeLoadMem(kWasmF32, MachineType::Float32());
break;
case kExprF64LoadMem:
len = DecodeLoadMem(kWasmF64, MachineType::Float64());
break;
case kExprI32StoreMem8:
len = DecodeStoreMem(kWasmI32, MachineType::Int8());
break;
case kExprI32StoreMem16:
len = DecodeStoreMem(kWasmI32, MachineType::Int16());
break;
case kExprI32StoreMem:
len = DecodeStoreMem(kWasmI32, MachineType::Int32());
break;
case kExprI64StoreMem8:
len = DecodeStoreMem(kWasmI64, MachineType::Int8());
break;
case kExprI64StoreMem16:
len = DecodeStoreMem(kWasmI64, MachineType::Int16());
break;
case kExprI64StoreMem32:
len = DecodeStoreMem(kWasmI64, MachineType::Int32());
break;
case kExprI64StoreMem:
len = DecodeStoreMem(kWasmI64, MachineType::Int64());
break;
case kExprF32StoreMem:
len = DecodeStoreMem(kWasmF32, MachineType::Float32());
break;
case kExprF64StoreMem:
len = DecodeStoreMem(kWasmF64, MachineType::Float64());
break;
case kExprGrowMemory: {
if (!CheckHasMemory()) break;
MemoryIndexOperand<true> operand(this, pc_);
DCHECK_NOT_NULL(module_);
if (module_->is_wasm()) {
Value val = Pop(0, kWasmI32);
Push(kWasmI32, BUILD(GrowMemory, val.node));
} else {
error("grow_memory is not supported for asmjs modules");
}
len = 1 + operand.length;
break;
}
case kExprMemorySize: {
if (!CheckHasMemory()) break;
MemoryIndexOperand<true> operand(this, pc_);
Push(kWasmI32, BUILD(CurrentMemoryPages));
len = 1 + operand.length;
break;
}
case kExprCallFunction: {
CallFunctionOperand<true> operand(this, pc_);
if (Validate(pc_, operand)) {
TFNode** buffer = PopArgs(operand.sig);
TFNode** rets = nullptr;
BUILD(CallDirect, operand.index, buffer, &rets, position());
PushReturns(operand.sig, rets);
}
len = 1 + operand.length;
break;
}
case kExprCallIndirect: {
CallIndirectOperand<true> operand(this, pc_);
if (Validate(pc_, operand)) {
Value index = Pop(0, kWasmI32);
TFNode** buffer = PopArgs(operand.sig);
if (buffer) buffer[0] = index.node;
TFNode** rets = nullptr;
BUILD(CallIndirect, operand.index, buffer, &rets, position());
PushReturns(operand.sig, rets);
}
len = 1 + operand.length;
break;
}
case kSimdPrefix: {
CHECK_PROTOTYPE_OPCODE(simd);
len++;
byte simd_index = read_u8<true>(pc_ + 1, "simd index");
opcode = static_cast<WasmOpcode>(opcode << 8 | simd_index);
TRACE(" @%-4d #%-20s|", startrel(pc_),
WasmOpcodes::OpcodeName(opcode));
len += DecodeSimdOpcode(opcode);
break;
}
case kAtomicPrefix: {
CHECK_PROTOTYPE_OPCODE(threads);
len++;
byte atomic_index = read_u8<true>(pc_ + 1, "atomic index");
opcode = static_cast<WasmOpcode>(opcode << 8 | atomic_index);
TRACE(" @%-4d #%-20s|", startrel(pc_),
WasmOpcodes::OpcodeName(opcode));
len += DecodeAtomicOpcode(opcode);
break;
}
default: {
// Deal with special asmjs opcodes.
if (module_ != nullptr && module_->is_asm_js()) {
sig = WasmOpcodes::AsmjsSignature(opcode);
if (sig) {
BuildSimpleOperator(opcode, sig);
}
} else {
error("Invalid opcode");
return;
}
}
}
}
#if DEBUG
if (FLAG_trace_wasm_decoder) {
PrintF(" ");
for (size_t i = 0; i < control_.size(); ++i) {
Control* c = &control_[i];
switch (c->kind) {
case v8::internal::wasm::kControlIf:
PrintF("I");
break;
case v8::internal::wasm::kControlBlock:
PrintF("B");
break;
case v8::internal::wasm::kControlLoop:
PrintF("L");
break;
case v8::internal::wasm::kControlTry:
PrintF("T");
break;
default:
break;
}
PrintF("%u", c->merge.arity);
if (c->unreachable) PrintF("*");
}
PrintF(" | ");
for (size_t i = 0; i < stack_.size(); ++i) {
Value& val = stack_[i];
WasmOpcode opcode = static_cast<WasmOpcode>(*val.pc);
if (WasmOpcodes::IsPrefixOpcode(opcode)) {
opcode = static_cast<WasmOpcode>(opcode << 8 | *(val.pc + 1));
}
PrintF(" %c@%d:%s", WasmOpcodes::ShortNameOf(val.type),
static_cast<int>(val.pc - start_),
WasmOpcodes::OpcodeName(opcode));
switch (opcode) {
case kExprI32Const: {
ImmI32Operand<true> operand(this, val.pc);
PrintF("[%d]", operand.value);
break;
}
case kExprGetLocal: {
LocalIndexOperand<true> operand(this, val.pc);
PrintF("[%u]", operand.index);
break;
}
case kExprSetLocal: // fallthru
case kExprTeeLocal: {
LocalIndexOperand<true> operand(this, val.pc);
PrintF("[%u]", operand.index);
break;
}
default:
break;
}
if (val.node == nullptr) PrintF("?");
}
PrintF("\n");
}
#endif
pc_ += len;
} // end decode loop
if (pc_ > end_ && ok()) error("Beyond end of code");
}
void FinishFunction() {
if (builder_) builder_->PatchInStackCheckIfNeeded();
void F64Const(Decoder* decoder, Value* result, double value) {
result->interface_data.node = builder_->Float64Constant(value);
}
void EndControl() {
ssa_env_->Kill(SsaEnv::kControlEnd);
if (!control_.empty()) {
stack_.resize(control_.back().stack_depth);
control_.back().unreachable = true;
void DoReturn(Decoder* decoder, Vector<Value> values) {
size_t num_values = values.size();
TFNode** buffer = GetNodes(values);
for (size_t i = 0; i < num_values; ++i) {
buffer[i] = values[i].interface_data.node;
}
BUILD(Return, static_cast<unsigned>(values.size()), buffer);
}
void SetBlockType(Control* c, BlockTypeOperand<true>& operand) {
c->merge.arity = operand.arity;
if (c->merge.arity == 1) {
c->merge.vals.first = {pc_, nullptr, operand.read_entry(0)};
} else if (c->merge.arity > 1) {
c->merge.vals.array = zone_->NewArray<Value>(c->merge.arity);
for (unsigned i = 0; i < c->merge.arity; i++) {
c->merge.vals.array[i] = {pc_, nullptr, operand.read_entry(i)};
}
}
void GetLocal(Decoder* decoder, Value* result,
const LocalIndexOperand<true>& operand) {
if (!ssa_env_->locals) return; // unreachable
result->interface_data.node = ssa_env_->locals[operand.index];
}
TFNode** PopArgs(FunctionSig* sig) {
if (build()) {
int count = static_cast<int>(sig->parameter_count());
TFNode** buffer = builder_->Buffer(count + 1);
buffer[0] = nullptr; // reserved for code object or function index.
for (int i = count - 1; i >= 0; i--) {
buffer[i + 1] = Pop(i, sig->GetParam(i)).node;
}
return buffer;
} else {
int count = static_cast<int>(sig->parameter_count());
for (int i = count - 1; i >= 0; i--) {
Pop(i, sig->GetParam(i));
}
return nullptr;
}
void SetLocal(Decoder* decoder, const Value& value,
const LocalIndexOperand<true>& operand) {
if (!ssa_env_->locals) return; // unreachable
ssa_env_->locals[operand.index] = value.interface_data.node;
}
ValueType GetReturnType(FunctionSig* sig) {
return sig->return_count() == 0 ? kWasmStmt : sig->GetReturn();
void TeeLocal(Decoder* decoder, const Value& value, Value* result,
const LocalIndexOperand<true>& operand) {
result->interface_data.node = value.interface_data.node;
if (!ssa_env_->locals) return; // unreachable
ssa_env_->locals[operand.index] = value.interface_data.node;
}
void PushBlock(SsaEnv* end_env) {
control_.emplace_back(
Control::Block(pc_, stack_.size(), end_env, current_catch_));
void GetGlobal(Decoder* decoder, Value* result,
const GlobalIndexOperand<true>& operand) {
result->interface_data.node = BUILD(GetGlobal, operand.index);
}
void PushLoop(SsaEnv* end_env) {
control_.emplace_back(
Control::Loop(pc_, stack_.size(), end_env, current_catch_));
void SetGlobal(Decoder* decoder, const Value& value,
const GlobalIndexOperand<true>& operand) {
BUILD(SetGlobal, operand.index, value.interface_data.node);
}
void PushIf(SsaEnv* end_env, SsaEnv* false_env) {
control_.emplace_back(
Control::If(pc_, stack_.size(), end_env, false_env, current_catch_));
void Unreachable(Decoder* decoder) {
BUILD(Unreachable, decoder->position());
}
void PushTry(SsaEnv* end_env, SsaEnv* catch_env) {
control_.emplace_back(Control::Try(pc_, stack_.size(), end_env, zone_,
catch_env, current_catch_));
current_catch_ = static_cast<int32_t>(control_.size() - 1);
void Select(Decoder* decoder, const Value& cond, const Value& fval,
const Value& tval, Value* result) {
TFNode* controls[2];
BUILD(BranchNoHint, cond.interface_data.node, &controls[0], &controls[1]);
TFNode* merge = BUILD(Merge, 2, controls);
TFNode* vals[2] = {tval.interface_data.node, fval.interface_data.node};
TFNode* phi = BUILD(Phi, tval.type, 2, vals, merge);
result->interface_data.node = phi;
ssa_env_->control = merge;
}
void PopControl() { control_.pop_back(); }
int DecodeLoadMem(ValueType type, MachineType mem_type) {
if (!CheckHasMemory()) return 0;
MemoryAccessOperand<true> operand(
this, pc_, ElementSizeLog2Of(mem_type.representation()));
Value index = Pop(0, kWasmI32);
TFNode* node = BUILD(LoadMem, type, mem_type, index.node, operand.offset,
operand.alignment, position());
Push(type, node);
return 1 + operand.length;
void BreakTo(Decoder* decoder, Control* block) {
if (block->is_loop()) {
Goto(decoder, ssa_env_, block->interface_data.end_env);
} else {
MergeValuesInto(decoder, block);
}
}
void BrIf(Decoder* decoder, const Value& cond, Control* block) {
SsaEnv* fenv = ssa_env_;
SsaEnv* tenv = Split(decoder, fenv);
fenv->SetNotMerged();
BUILD(BranchNoHint, cond.interface_data.node, &tenv->control,
&fenv->control);
ssa_env_ = tenv;
BreakTo(decoder, block);
ssa_env_ = fenv;
}
void BrTable(Decoder* decoder, const BranchTableOperand<true>& operand,
const Value& key) {
SsaEnv* break_env = ssa_env_;
// Build branches to the various blocks based on the table.
TFNode* sw =
BUILD(Switch, operand.table_count + 1, key.interface_data.node);
SsaEnv* copy = Steal(decoder->zone(), break_env);
ssa_env_ = copy;
BranchTableIterator<true> iterator(decoder, operand);
while (iterator.has_next()) {
uint32_t i = iterator.cur_index();
uint32_t target = iterator.next();
ssa_env_ = Split(decoder, copy);
ssa_env_->control = (i == operand.table_count) ? BUILD(IfDefault, sw)
: BUILD(IfValue, i, sw);
BreakTo(decoder, decoder->control_at(target));
}
DCHECK(decoder->ok());
ssa_env_ = break_env;
}
int DecodeStoreMem(ValueType type, MachineType mem_type) {
if (!CheckHasMemory()) return 0;
MemoryAccessOperand<true> operand(
this, pc_, ElementSizeLog2Of(mem_type.representation()));
Value val = Pop(1, type);
Value index = Pop(0, kWasmI32);
BUILD(StoreMem, mem_type, index.node, operand.offset, operand.alignment,
val.node, position(), type);
return 1 + operand.length;
void Else(Decoder* decoder, Control* if_block) {
SetEnv(if_block->interface_data.false_env);
}
int DecodePrefixedLoadMem(ValueType type, MachineType mem_type) {
if (!CheckHasMemory()) return 0;
MemoryAccessOperand<true> operand(
this, pc_ + 1, ElementSizeLog2Of(mem_type.representation()));
Value index = Pop(0, kWasmI32);
TFNode* node = BUILD(LoadMem, type, mem_type, index.node, operand.offset,
operand.alignment, position());
Push(type, node);
return operand.length;
void LoadMem(Decoder* decoder, ValueType type, MachineType mem_type,
const MemoryAccessOperand<true>& operand, const Value& index,
Value* result) {
result->interface_data.node =
BUILD(LoadMem, type, mem_type, index.interface_data.node,
operand.offset, operand.alignment, decoder->position());
}
int DecodePrefixedStoreMem(ValueType type, MachineType mem_type) {
if (!CheckHasMemory()) return 0;
MemoryAccessOperand<true> operand(
this, pc_ + 1, ElementSizeLog2Of(mem_type.representation()));
Value val = Pop(1, type);
Value index = Pop(0, kWasmI32);
BUILD(StoreMem, mem_type, index.node, operand.offset, operand.alignment,
val.node, position(), type);
return operand.length;
void StoreMem(Decoder* decoder, ValueType type, MachineType mem_type,
const MemoryAccessOperand<true>& operand, const Value& index,
const Value& value) {
BUILD(StoreMem, mem_type, index.interface_data.node, operand.offset,
operand.alignment, value.interface_data.node, decoder->position());
}
unsigned SimdExtractLane(WasmOpcode opcode, ValueType type) {
SimdLaneOperand<true> operand(this, pc_);
if (Validate(pc_, opcode, operand)) {
compiler::NodeVector inputs(1, zone_);
inputs[0] = Pop(0, ValueType::kSimd128).node;
TFNode* node = BUILD(SimdLaneOp, opcode, operand.lane, inputs.data());
Push(type, node);
}
return operand.length;
void CurrentMemoryPages(Decoder* decoder, Value* result) {
result->interface_data.node = BUILD(CurrentMemoryPages);
}
unsigned SimdReplaceLane(WasmOpcode opcode, ValueType type) {
SimdLaneOperand<true> operand(this, pc_);
if (Validate(pc_, opcode, operand)) {
compiler::NodeVector inputs(2, zone_);
inputs[1] = Pop(1, type).node;
inputs[0] = Pop(0, ValueType::kSimd128).node;
TFNode* node = BUILD(SimdLaneOp, opcode, operand.lane, inputs.data());
Push(ValueType::kSimd128, node);
}
return operand.length;
void GrowMemory(Decoder* decoder, const Value& value, Value* result) {
result->interface_data.node = BUILD(GrowMemory, value.interface_data.node);
}
unsigned SimdShiftOp(WasmOpcode opcode) {
SimdShiftOperand<true> operand(this, pc_);
if (Validate(pc_, opcode, operand)) {
compiler::NodeVector inputs(1, zone_);
inputs[0] = Pop(0, ValueType::kSimd128).node;
TFNode* node = BUILD(SimdShiftOp, opcode, operand.shift, inputs.data());
Push(ValueType::kSimd128, node);
}
return operand.length;
void CallDirect(Decoder* decoder, const CallFunctionOperand<true>& operand,
const Value args[], Value returns[]) {
DoCall(decoder, nullptr, operand, args, returns, false);
}
unsigned Simd8x16ShuffleOp() {
Simd8x16ShuffleOperand<true> operand(this, pc_);
if (Validate(pc_, operand)) {
compiler::NodeVector inputs(2, zone_);
inputs[1] = Pop(1, ValueType::kSimd128).node;
inputs[0] = Pop(0, ValueType::kSimd128).node;
TFNode* node = BUILD(Simd8x16ShuffleOp, operand.shuffle, inputs.data());
Push(ValueType::kSimd128, node);
}
return 16;
void CallIndirect(Decoder* decoder, const Value& index,
const CallIndirectOperand<true>& operand,
const Value args[], Value returns[]) {
DoCall(decoder, index.interface_data.node, operand, args, returns, true);
}
unsigned DecodeSimdOpcode(WasmOpcode opcode) {
unsigned len = 0;
switch (opcode) {
case kExprF32x4ExtractLane: {
len = SimdExtractLane(opcode, ValueType::kFloat32);
break;
}
case kExprI32x4ExtractLane:
case kExprI16x8ExtractLane:
case kExprI8x16ExtractLane: {
len = SimdExtractLane(opcode, ValueType::kWord32);
break;
}
case kExprF32x4ReplaceLane: {
len = SimdReplaceLane(opcode, ValueType::kFloat32);
break;
}
case kExprI32x4ReplaceLane:
case kExprI16x8ReplaceLane:
case kExprI8x16ReplaceLane: {
len = SimdReplaceLane(opcode, ValueType::kWord32);
break;
}
case kExprI32x4Shl:
case kExprI32x4ShrS:
case kExprI32x4ShrU:
case kExprI16x8Shl:
case kExprI16x8ShrS:
case kExprI16x8ShrU:
case kExprI8x16Shl:
case kExprI8x16ShrS:
case kExprI8x16ShrU: {
len = SimdShiftOp(opcode);
break;
}
case kExprS8x16Shuffle: {
len = Simd8x16ShuffleOp();
break;
}
case kExprS128LoadMem:
len = DecodePrefixedLoadMem(kWasmS128, MachineType::Simd128());
break;
case kExprS128StoreMem:
len = DecodePrefixedStoreMem(kWasmS128, MachineType::Simd128());
break;
default: {
FunctionSig* sig = WasmOpcodes::Signature(opcode);
if (sig != nullptr) {
compiler::NodeVector inputs(sig->parameter_count(), zone_);
for (size_t i = sig->parameter_count(); i > 0; i--) {
Value val = Pop(static_cast<int>(i - 1), sig->GetParam(i - 1));
inputs[i - 1] = val.node;
}
TFNode* node = BUILD(SimdOp, opcode, inputs.data());
Push(GetReturnType(sig), node);
} else {
error("invalid simd opcode");
}
}
}
return len;
void SimdOp(Decoder* decoder, WasmOpcode opcode, Vector<Value> args,
Value* result) {
TFNode** inputs = GetNodes(args);
TFNode* node = BUILD(SimdOp, opcode, inputs);
if (result) result->interface_data.node = node;
}
unsigned DecodeAtomicOpcode(WasmOpcode opcode) {
unsigned len = 0;
FunctionSig* sig = WasmOpcodes::AtomicSignature(opcode);
if (sig != nullptr) {
compiler::NodeVector inputs(sig->parameter_count(), zone_);
for (int i = static_cast<int>(sig->parameter_count() - 1); i >= 0; --i) {
Value val = Pop(i, sig->GetParam(i));
inputs[i] = val.node;
}
TFNode* node = BUILD(AtomicOp, opcode, inputs, position());
Push(GetReturnType(sig), node);
} else {
error("invalid atomic opcode");
}
return len;
void SimdLaneOp(Decoder* decoder, WasmOpcode opcode,
const SimdLaneOperand<true> operand, Vector<Value> inputs,
Value* result) {
TFNode** nodes = GetNodes(inputs);
result->interface_data.node =
BUILD(SimdLaneOp, opcode, operand.lane, nodes);
}
void DoReturn() {
int count = static_cast<int>(sig_->return_count());
TFNode** buffer = nullptr;
if (build()) buffer = builder_->Buffer(count);
// Pop return values off the stack in reverse order.
for (int i = count - 1; i >= 0; i--) {
Value val = Pop(i, sig_->GetReturn(i));
if (buffer) buffer[i] = val.node;
}
BUILD(Return, count, buffer);
EndControl();
void SimdShiftOp(Decoder* decoder, WasmOpcode opcode,
const SimdShiftOperand<true> operand, const Value& input,
Value* result) {
TFNode* inputs[] = {input.interface_data.node};
result->interface_data.node =
BUILD(SimdShiftOp, opcode, operand.shift, inputs);
}
void Push(ValueType type, TFNode* node) {
if (type != kWasmStmt) {
stack_.push_back({pc_, node, type});
}
void Simd8x16ShuffleOp(Decoder* decoder,
const Simd8x16ShuffleOperand<true>& operand,
const Value& input0, const Value& input1,
Value* result) {
TFNode* input_nodes[] = {input0.interface_data.node,
input1.interface_data.node};
result->interface_data.node =
BUILD(Simd8x16ShuffleOp, operand.shuffle, input_nodes);
}
void PushEndValues(Control* c) {
DCHECK_EQ(c, &control_.back());
stack_.resize(c->stack_depth);
if (c->merge.arity == 1) {
stack_.push_back(c->merge.vals.first);
} else {
for (unsigned i = 0; i < c->merge.arity; i++) {
stack_.push_back(c->merge.vals.array[i]);
}
}
DCHECK_EQ(c->stack_depth + c->merge.arity, stack_.size());
TFNode* GetExceptionTag(Decoder* decoder,
const ExceptionIndexOperand<true>& operand) {
// TODO(kschimpf): Need to get runtime exception tag values. This
// code only handles non-imported/exported exceptions.
return BUILD(Int32Constant, operand.index);
}
void PushReturns(FunctionSig* sig, TFNode** rets) {
for (size_t i = 0; i < sig->return_count(); i++) {
// When verifying only, then {rets} will be null, so push null.
Push(sig->GetReturn(i), rets ? rets[i] : nullptr);
}
void Throw(Decoder* decoder, const ExceptionIndexOperand<true>& operand) {
BUILD(Throw, GetExceptionTag(decoder, operand));
}
const char* SafeOpcodeNameAt(const byte* pc) {
if (pc >= end_) return "<end>";
return WasmOpcodes::OpcodeName(static_cast<WasmOpcode>(*pc));
}
void Catch(Decoder* decoder, const ExceptionIndexOperand<true>& operand,
Control* block) {
DCHECK_NOT_NULL(block->interface_data.try_info);
current_catch_ = block->interface_data.previous_catch;
Value Pop(int index, ValueType expected) {
Value val = Pop();
if (val.type != expected && val.type != kWasmVar && expected != kWasmVar) {
errorf(val.pc, "%s[%d] expected type %s, found %s of type %s",
SafeOpcodeNameAt(pc_), index, WasmOpcodes::TypeName(expected),
SafeOpcodeNameAt(val.pc), WasmOpcodes::TypeName(val.type));
}
return val;
// Get the exception and see if wanted exception.
TFNode* exception_as_i32 = BUILD(
Catch, block->interface_data.try_info->exception, decoder->position());
TFNode* exception_tag = GetExceptionTag(decoder, operand);
TFNode* compare_i32 = BUILD(Binop, kExprI32Eq, exception_as_i32,
exception_tag, decoder->position());
TFNode* if_true = nullptr;
TFNode* if_false = nullptr;
BUILD(BranchNoHint, compare_i32, &if_true, &if_false);
SsaEnv* end_env = ssa_env_;
SsaEnv* false_env = Split(decoder, end_env);
false_env->control = if_false;
SsaEnv* true_env = Steal(decoder->zone(), ssa_env_);
true_env->control = if_true;
block->interface_data.try_info->catch_env = false_env;
SetEnv(true_env);
// TODO(kschimpf): Add code to pop caught exception from isolate.
}
Value Pop() {
size_t limit = control_.empty() ? 0 : control_.back().stack_depth;
if (stack_.size() <= limit) {
// Popping past the current control start in reachable code.
Value val = {pc_, nullptr, kWasmVar};
if (!control_.back().unreachable) {
errorf(pc_, "%s found empty stack", SafeOpcodeNameAt(pc_));
}
return val;
}
Value val = stack_.back();
stack_.pop_back();
return val;
void AtomicOp(Decoder* decoder, WasmOpcode opcode, Vector<Value> args,
Value* result) {
TFNode** inputs = GetNodes(args);
TFNode* node = BUILD(AtomicOp, opcode, inputs, decoder->position());
if (result) result->interface_data.node = node;
}
int startrel(const byte* ptr) { return static_cast<int>(ptr - start_); }
void BreakTo(unsigned depth) {
Control* c = &control_[control_.size() - depth - 1];
if (c->is_loop()) {
// This is the inner loop block, which does not have a value.
Goto(ssa_env_, c->end_env);
} else {
// Merge the value(s) into the end of the block.
size_t expected = control_.back().stack_depth + c->merge.arity;
if (stack_.size() < expected && !control_.back().unreachable) {
errorf(
pc_,
"expected at least %u values on the stack for br to @%d, found %d",
c->merge.arity, startrel(c->pc),
static_cast<int>(stack_.size() - c->stack_depth));
return;
}
MergeValuesInto(c);
}
}
private:
SsaEnv* ssa_env_;
TFBuilder* builder_;
uint32_t current_catch_ = kNullCatch;
void FallThruTo(Control* c) {
DCHECK_EQ(c, &control_.back());
// Merge the value(s) into the end of the block.
size_t expected = c->stack_depth + c->merge.arity;
if (stack_.size() == expected ||
(stack_.size() < expected && c->unreachable)) {
MergeValuesInto(c);
c->unreachable = false;
return;
}
errorf(pc_, "expected %u elements on the stack for fallthru to @%d",
c->merge.arity, startrel(c->pc));
}
bool build(Decoder* decoder) { return ssa_env_->go() && decoder->ok(); }
inline Value& GetMergeValueFromStack(Control* c, size_t i) {
return stack_[stack_.size() - c->merge.arity + i];
TryInfo* current_try_info(Decoder* decoder) {
return decoder->control_at(decoder->control_depth() - 1 - current_catch_)
->interface_data.try_info;
}
void TypeCheckFallThru(Control* c) {
DCHECK_EQ(c, &control_.back());
// Fallthru must match arity exactly.
int arity = static_cast<int>(c->merge.arity);
if (c->stack_depth + arity < stack_.size() ||
(c->stack_depth + arity != stack_.size() && !c->unreachable)) {
errorf(pc_, "expected %d elements on the stack for fallthru to @%d",
arity, startrel(c->pc));
return;
}
// Typecheck the values left on the stack.
size_t avail = stack_.size() - c->stack_depth;
for (size_t i = avail >= c->merge.arity ? 0 : c->merge.arity - avail;
i < c->merge.arity; i++) {
Value& val = GetMergeValueFromStack(c, i);
Value& old = c->merge[i];
if (val.type != old.type) {
errorf(pc_, "type error in merge[%zu] (expected %s, got %s)", i,
WasmOpcodes::TypeName(old.type),
WasmOpcodes::TypeName(val.type));
return;
}
TFNode** GetNodes(Value* values, size_t count) {
TFNode** nodes = builder_->Buffer(count);
for (size_t i = 0; i < count; ++i) {
nodes[i] = values[i].interface_data.node;
}
return nodes;
}
void MergeValuesInto(Control* c) {
SsaEnv* target = c->end_env;
bool first = target->state == SsaEnv::kUnreachable;
bool reachable = ssa_env_->go();
Goto(ssa_env_, target);
size_t avail = stack_.size() - control_.back().stack_depth;
for (size_t i = avail >= c->merge.arity ? 0 : c->merge.arity - avail;
i < c->merge.arity; i++) {
Value& val = GetMergeValueFromStack(c, i);
Value& old = c->merge[i];
if (val.type != old.type && val.type != kWasmVar) {
errorf(pc_, "type error in merge[%zu] (expected %s, got %s)", i,
WasmOpcodes::TypeName(old.type),
WasmOpcodes::TypeName(val.type));
return;
}
if (builder_ && reachable) {
DCHECK_NOT_NULL(val.node);
old.node =
first ? val.node : CreateOrMergeIntoPhi(old.type, target->control,
old.node, val.node);
}
}
TFNode** GetNodes(Vector<Value> values) {
return GetNodes(values.start(), values.size());
}
void SetEnv(const char* reason, SsaEnv* env) {
void SetEnv(SsaEnv* env) {
#if DEBUG
if (FLAG_trace_wasm_decoder) {
char state = 'X';
......@@ -1877,8 +473,7 @@ class WasmFullDecoder : public WasmDecoder {
break;
}
}
PrintF("{set_env = %p, state = %c, reason = %s", static_cast<void*>(env),
state, reason);
PrintF("{set_env = %p, state = %c", static_cast<void*>(env), state);
if (env && env->control) {
PrintF(", control = ");
compiler::WasmGraphBuilder::PrintDebugName(env->control);
......@@ -1887,22 +482,16 @@ class WasmFullDecoder : public WasmDecoder {
}
#endif
ssa_env_ = env;
if (builder_) {
builder_->set_control_ptr(&env->control);
builder_->set_effect_ptr(&env->effect);
}
builder_->set_control_ptr(&env->control);
builder_->set_effect_ptr(&env->effect);
}
TFNode* CheckForException(TFNode* node) {
if (node == nullptr) {
return nullptr;
}
TFNode* CheckForException(Decoder* decoder, TFNode* node) {
if (node == nullptr) return nullptr;
const bool inside_try_scope = current_catch_ != kNullCatch;
if (!inside_try_scope) {
return node;
}
if (!inside_try_scope) return node;
TFNode* if_success = nullptr;
TFNode* if_exception = nullptr;
......@@ -1910,13 +499,13 @@ class WasmFullDecoder : public WasmDecoder {
return node;
}
SsaEnv* success_env = Steal(ssa_env_);
SsaEnv* success_env = Steal(decoder->zone(), ssa_env_);
success_env->control = if_success;
SsaEnv* exception_env = Split(success_env);
SsaEnv* exception_env = Split(decoder, success_env);
exception_env->control = if_exception;
TryInfo* try_info = current_try_info();
Goto(exception_env, try_info->catch_env);
TryInfo* try_info = current_try_info(decoder);
Goto(decoder, exception_env, try_info->catch_env);
TFNode* exception = try_info->exception;
if (exception == nullptr) {
DCHECK_EQ(SsaEnv::kReached, try_info->catch_env->state);
......@@ -1928,11 +517,52 @@ class WasmFullDecoder : public WasmDecoder {
try_info->exception, if_exception);
}
SetEnv("if_success", success_env);
SetEnv(success_env);
return node;
}
void Goto(SsaEnv* from, SsaEnv* to) {
TFNode* DefaultValue(ValueType type) {
switch (type) {
case kWasmI32:
return builder_->Int32Constant(0);
case kWasmI64:
return builder_->Int64Constant(0);
case kWasmF32:
return builder_->Float32Constant(0);
case kWasmF64:
return builder_->Float64Constant(0);
case kWasmS128:
return builder_->S128Zero();
default:
UNREACHABLE();
}
}
void MergeValuesInto(Decoder* decoder, Control* c) {
if (!ssa_env_->go()) return;
SsaEnv* target = c->interface_data.end_env;
const bool first = target->state == SsaEnv::kUnreachable;
Goto(decoder, ssa_env_, target);
size_t avail = decoder->stack_size() - decoder->control_at(0)->stack_depth;
size_t start = avail >= c->merge.arity ? 0 : c->merge.arity - avail;
for (size_t i = start; i < c->merge.arity; ++i) {
auto& val = decoder->GetMergeValueFromStack(c, i);
auto& old = c->merge[i];
DCHECK_NOT_NULL(val.interface_data.node);
// TODO(clemensh): Remove first.
DCHECK_EQ(first, old.interface_data.node == nullptr);
DCHECK(val.type == old.type || val.type == kWasmVar);
old.interface_data.node =
first ? val.interface_data.node
: CreateOrMergeIntoPhi(old.type, target->control,
old.interface_data.node,
val.interface_data.node);
}
}
void Goto(Decoder* decoder, SsaEnv* from, SsaEnv* to) {
DCHECK_NOT_NULL(to);
if (!from->go()) return;
switch (to->state) {
......@@ -1945,7 +575,6 @@ class WasmFullDecoder : public WasmDecoder {
}
case SsaEnv::kReached: { // Create a new merge.
to->state = SsaEnv::kMerged;
if (!builder_) break;
// Merge control.
TFNode* controls[] = {to->control, from->control};
TFNode* merge = builder_->Merge(2, controls);
......@@ -1956,18 +585,18 @@ class WasmFullDecoder : public WasmDecoder {
to->effect = builder_->EffectPhi(2, effects, merge);
}
// Merge SSA values.
for (int i = EnvironmentCount() - 1; i >= 0; i--) {
for (int i = decoder->NumLocals() - 1; i >= 0; i--) {
TFNode* a = to->locals[i];
TFNode* b = from->locals[i];
if (a != b) {
TFNode* vals[] = {a, b};
to->locals[i] = builder_->Phi(local_type_vec_[i], 2, vals, merge);
to->locals[i] =
builder_->Phi(decoder->GetLocalType(i), 2, vals, merge);
}
}
break;
}
case SsaEnv::kMerged: {
if (!builder_) break;
TFNode* merge = to->control;
// Extend the existing merge.
builder_->AppendToMerge(merge, from->control);
......@@ -1984,7 +613,7 @@ class WasmFullDecoder : public WasmDecoder {
to->effect = builder_->EffectPhi(count, effects, merge);
}
// Merge locals.
for (int i = EnvironmentCount() - 1; i >= 0; i--) {
for (int i = decoder->NumLocals() - 1; i >= 0; i--) {
TFNode* tnode = to->locals[i];
TFNode* fnode = from->locals[i];
if (builder_->IsPhiWithMerge(tnode, merge)) {
......@@ -1997,7 +626,7 @@ class WasmFullDecoder : public WasmDecoder {
}
vals[count - 1] = fnode;
to->locals[i] =
builder_->Phi(local_type_vec_[i], count, vals, merge);
builder_->Phi(decoder->GetLocalType(i), count, vals, merge);
}
}
break;
......@@ -2010,7 +639,6 @@ class WasmFullDecoder : public WasmDecoder {
TFNode* CreateOrMergeIntoPhi(ValueType type, TFNode* merge, TFNode* tnode,
TFNode* fnode) {
DCHECK_NOT_NULL(builder_);
if (builder_->IsPhiWithMerge(tnode, merge)) {
builder_->AppendToPhi(tnode, fnode);
} else if (tnode != fnode) {
......@@ -2023,54 +651,56 @@ class WasmFullDecoder : public WasmDecoder {
return tnode;
}
SsaEnv* PrepareForLoop(const byte* pc, SsaEnv* env) {
if (!builder_) return Split(env);
if (!env->go()) return Split(env);
SsaEnv* PrepareForLoop(Decoder* decoder, SsaEnv* env) {
if (!env->go()) return Split(decoder, env);
env->state = SsaEnv::kMerged;
env->control = builder_->Loop(env->control);
env->effect = builder_->EffectPhi(1, &env->effect, env->control);
builder_->Terminate(env->effect, env->control);
BitVector* assigned = AnalyzeLoopAssignment(
this, pc, static_cast<int>(total_locals()), zone_);
if (failed()) return env;
BitVector* assigned = WasmDecoder<true>::AnalyzeLoopAssignment(
decoder, decoder->pc(), static_cast<int>(decoder->total_locals()),
decoder->zone());
if (decoder->failed()) return env;
if (assigned != nullptr) {
// Only introduce phis for variables assigned in this loop.
for (int i = EnvironmentCount() - 1; i >= 0; i--) {
for (int i = decoder->NumLocals() - 1; i >= 0; i--) {
if (!assigned->Contains(i)) continue;
env->locals[i] =
builder_->Phi(local_type_vec_[i], 1, &env->locals[i], env->control);
env->locals[i] = builder_->Phi(decoder->GetLocalType(i), 1,
&env->locals[i], env->control);
}
SsaEnv* loop_body_env = Split(env);
builder_->StackCheck(position(), &(loop_body_env->effect),
SsaEnv* loop_body_env = Split(decoder, env);
builder_->StackCheck(decoder->position(), &(loop_body_env->effect),
&(loop_body_env->control));
return loop_body_env;
}
// Conservatively introduce phis for all local variables.
for (int i = EnvironmentCount() - 1; i >= 0; i--) {
env->locals[i] =
builder_->Phi(local_type_vec_[i], 1, &env->locals[i], env->control);
for (int i = decoder->NumLocals() - 1; i >= 0; i--) {
env->locals[i] = builder_->Phi(decoder->GetLocalType(i), 1,
&env->locals[i], env->control);
}
SsaEnv* loop_body_env = Split(env);
builder_->StackCheck(position(), &(loop_body_env->effect),
&(loop_body_env->control));
SsaEnv* loop_body_env = Split(decoder, env);
builder_->StackCheck(decoder->position(), &loop_body_env->effect,
&loop_body_env->control);
return loop_body_env;
}
// Create a complete copy of the {from}.
SsaEnv* Split(SsaEnv* from) {
SsaEnv* Split(Decoder* decoder, SsaEnv* from) {
DCHECK_NOT_NULL(from);
SsaEnv* result = reinterpret_cast<SsaEnv*>(zone_->New(sizeof(SsaEnv)));
size_t size = sizeof(TFNode*) * EnvironmentCount();
SsaEnv* result =
reinterpret_cast<SsaEnv*>(decoder->zone()->New(sizeof(SsaEnv)));
size_t size = sizeof(TFNode*) * decoder->NumLocals();
result->control = from->control;
result->effect = from->effect;
if (from->go()) {
result->state = SsaEnv::kReached;
result->locals =
size > 0 ? reinterpret_cast<TFNode**>(zone_->New(size)) : nullptr;
size > 0 ? reinterpret_cast<TFNode**>(decoder->zone()->New(size))
: nullptr;
memcpy(result->locals, from->locals, size);
} else {
result->state = SsaEnv::kUnreachable;
......@@ -2082,10 +712,10 @@ class WasmFullDecoder : public WasmDecoder {
// Create a copy of {from} that steals its state and leaves {from}
// unreachable.
SsaEnv* Steal(SsaEnv* from) {
SsaEnv* Steal(Zone* zone, SsaEnv* from) {
DCHECK_NOT_NULL(from);
if (!from->go()) return UnreachableEnv();
SsaEnv* result = reinterpret_cast<SsaEnv*>(zone_->New(sizeof(SsaEnv)));
if (!from->go()) return UnreachableEnv(zone);
SsaEnv* result = reinterpret_cast<SsaEnv*>(zone->New(sizeof(SsaEnv)));
result->state = SsaEnv::kReached;
result->locals = from->locals;
result->control = from->control;
......@@ -2095,8 +725,8 @@ class WasmFullDecoder : public WasmDecoder {
}
// Create an unreachable environment.
SsaEnv* UnreachableEnv() {
SsaEnv* result = reinterpret_cast<SsaEnv*>(zone_->New(sizeof(SsaEnv)));
SsaEnv* UnreachableEnv(Zone* zone) {
SsaEnv* result = reinterpret_cast<SsaEnv*>(zone->New(sizeof(SsaEnv)));
result->state = SsaEnv::kUnreachable;
result->control = nullptr;
result->effect = nullptr;
......@@ -2104,50 +734,38 @@ class WasmFullDecoder : public WasmDecoder {
return result;
}
int EnvironmentCount() {
if (builder_) return static_cast<int>(local_type_vec_.size());
return 0; // if we aren't building a graph, don't bother with SSA renaming.
}
virtual void onFirstError() {
end_ = pc_; // Terminate decoding loop.
builder_ = nullptr; // Don't build any more nodes.
TRACE(" !%s\n", error_msg_.c_str());
}
inline wasm::WasmCodePosition position() {
int offset = static_cast<int>(pc_ - start_);
DCHECK_EQ(pc_ - start_, offset); // overflows cannot happen
return offset;
}
inline void BuildSimpleOperator(WasmOpcode opcode, FunctionSig* sig) {
TFNode* node;
switch (sig->parameter_count()) {
case 1: {
Value val = Pop(0, sig->GetParam(0));
node = BUILD(Unop, opcode, val.node, position());
break;
}
case 2: {
Value rval = Pop(1, sig->GetParam(1));
Value lval = Pop(0, sig->GetParam(0));
node = BUILD(Binop, opcode, lval.node, rval.node, position());
break;
}
default:
UNREACHABLE();
node = nullptr;
break;
template <typename Operand>
void DoCall(WasmFullDecoder<true, WasmGraphBuildingInterface>* decoder,
TFNode* index_node, const Operand& operand, const Value args[],
Value returns[], bool is_indirect) {
if (!build(decoder)) return;
int param_count = static_cast<int>(operand.sig->parameter_count());
TFNode** arg_nodes = builder_->Buffer(param_count + 1);
TFNode** return_nodes = nullptr;
arg_nodes[0] = index_node;
for (int i = 0; i < param_count; ++i) {
arg_nodes[i + 1] = args[i].interface_data.node;
}
if (is_indirect) {
builder_->CallIndirect(operand.index, arg_nodes, &return_nodes,
decoder->position());
} else {
builder_->CallDirect(operand.index, arg_nodes, &return_nodes,
decoder->position());
}
int return_count = static_cast<int>(operand.sig->return_count());
for (int i = 0; i < return_count; ++i) {
returns[i].interface_data.node = return_nodes[i];
}
Push(GetReturnType(sig), node);
}
};
} // namespace
bool DecodeLocalDecls(BodyLocalDecls* decls, const byte* start,
const byte* end) {
Decoder decoder(start, end);
if (WasmDecoder::DecodeLocals(&decoder, nullptr, &decls->type_list)) {
if (WasmDecoder<true>::DecodeLocals(&decoder, nullptr, &decls->type_list)) {
DCHECK(decoder.ok());
decls->encoded_size = decoder.pc_offset();
return true;
......@@ -2170,7 +788,7 @@ DecodeResult VerifyWasmCode(AccountingAllocator* allocator,
const wasm::WasmModule* module,
FunctionBody& body) {
Zone zone(allocator, ZONE_NAME);
WasmFullDecoder decoder(&zone, module, body);
WasmFullDecoder<true, EmptyInterface> decoder(&zone, module, body);
decoder.Decode();
return decoder.toResult(nullptr);
}
......@@ -2193,20 +811,21 @@ DecodeResult VerifyWasmCodeWithStats(AccountingAllocator* allocator,
DecodeResult BuildTFGraph(AccountingAllocator* allocator, TFBuilder* builder,
FunctionBody& body) {
Zone zone(allocator, ZONE_NAME);
WasmFullDecoder decoder(&zone, builder, body);
WasmFullDecoder<true, WasmGraphBuildingInterface> decoder(
&zone, builder->module(), body, builder);
decoder.Decode();
return decoder.toResult(nullptr);
}
unsigned OpcodeLength(const byte* pc, const byte* end) {
Decoder decoder(pc, end);
return WasmDecoder::OpcodeLength(&decoder, pc);
return WasmDecoder<false>::OpcodeLength(&decoder, pc);
}
std::pair<uint32_t, uint32_t> StackEffect(const WasmModule* module,
FunctionSig* sig, const byte* pc,
const byte* end) {
WasmDecoder decoder(module, sig, pc, end);
WasmDecoder<false> decoder(module, sig, pc, end);
return decoder.StackEffect(pc);
}
......@@ -2234,7 +853,7 @@ bool PrintRawWasmCode(AccountingAllocator* allocator, const FunctionBody& body,
const wasm::WasmModule* module) {
OFStream os(stdout);
Zone zone(allocator, ZONE_NAME);
WasmFullDecoder decoder(&zone, module, body);
WasmDecoder<false> decoder(module, body.sig, body.start, body.end);
int line_nr = 0;
// Print the function signature.
......@@ -2275,7 +894,7 @@ bool PrintRawWasmCode(AccountingAllocator* allocator, const FunctionBody& body,
++line_nr;
unsigned control_depth = 0;
for (; i.has_next(); i.next()) {
unsigned length = WasmDecoder::OpcodeLength(&decoder, i.pc());
unsigned length = WasmDecoder<false>::OpcodeLength(&decoder, i.pc());
WasmOpcode opcode = i.current();
if (opcode == kExprElse) control_depth--;
......@@ -2302,7 +921,7 @@ bool PrintRawWasmCode(AccountingAllocator* allocator, const FunctionBody& body,
case kExprIf:
case kExprBlock:
case kExprTry: {
BlockTypeOperand<true> operand(&i, i.pc());
BlockTypeOperand<false> operand(&i, i.pc());
os << " // @" << i.pc_offset();
for (unsigned i = 0; i < operand.arity; i++) {
os << " " << WasmOpcodes::TypeName(operand.read_entry(i));
......@@ -2315,22 +934,22 @@ bool PrintRawWasmCode(AccountingAllocator* allocator, const FunctionBody& body,
control_depth--;
break;
case kExprBr: {
BreakDepthOperand<true> operand(&i, i.pc());
BreakDepthOperand<false> operand(&i, i.pc());
os << " // depth=" << operand.depth;
break;
}
case kExprBrIf: {
BreakDepthOperand<true> operand(&i, i.pc());
BreakDepthOperand<false> operand(&i, i.pc());
os << " // depth=" << operand.depth;
break;
}
case kExprBrTable: {
BranchTableOperand<true> operand(&i, i.pc());
BranchTableOperand<false> operand(&i, i.pc());
os << " // entries=" << operand.table_count;
break;
}
case kExprCallIndirect: {
CallIndirectOperand<true> operand(&i, i.pc());
CallIndirectOperand<false> operand(&i, i.pc());
os << " // sig #" << operand.index;
if (decoder.Complete(i.pc(), operand)) {
os << ": " << *operand.sig;
......@@ -2338,7 +957,7 @@ bool PrintRawWasmCode(AccountingAllocator* allocator, const FunctionBody& body,
break;
}
case kExprCallFunction: {
CallFunctionOperand<true> operand(&i, i.pc());
CallFunctionOperand<false> operand(&i, i.pc());
os << " // function #" << operand.index;
if (decoder.Complete(i.pc(), operand)) {
os << ": " << *operand.sig;
......@@ -2358,8 +977,8 @@ bool PrintRawWasmCode(AccountingAllocator* allocator, const FunctionBody& body,
BitVector* AnalyzeLoopAssignmentForTesting(Zone* zone, size_t num_locals,
const byte* start, const byte* end) {
Decoder decoder(start, end);
return WasmDecoder::AnalyzeLoopAssignment(&decoder, start,
static_cast<int>(num_locals), zone);
return WasmDecoder<true>::AnalyzeLoopAssignment(
&decoder, start, static_cast<int>(num_locals), zone);
}
#undef TRACE
......
......@@ -34,6 +34,8 @@ assertFalse(test_throw === 0);
assertEquals("object", typeof test_throw.exports);
assertEquals("function", typeof test_throw.exports.throw_if_param_not_zero);
/* TODO(kschimpf) Convert these tests to work for the proposed exceptions.
// Test expected behavior of throws
assertEquals(1, test_throw.exports.throw_if_param_not_zero(0));
assertWasmThrows([], function() { test_throw.exports.throw_if_param_not_zero(10) });
......@@ -72,8 +74,6 @@ assertEquals("function", typeof test_catch.exports.simple_throw_catch_to_0_1);
assertEquals(0, test_catch.exports.simple_throw_catch_to_0_1(0));
assertEquals(1, test_catch.exports.simple_throw_catch_to_0_1(1));
/* TODO(kschimpf) Convert these tests to work for the proposed exceptions.
// The following methods do not attempt to catch the exception they raise.
var test_throw = (function () {
var builder = new WasmModuleBuilder();
......
......@@ -2442,17 +2442,17 @@ class WasmOpcodeLengthTest : public TestWithZone {
TEST_F(WasmOpcodeLengthTest, Statements) {
EXPECT_LENGTH(1, kExprNop);
EXPECT_LENGTH(2, kExprBlock);
EXPECT_LENGTH(2, kExprLoop);
EXPECT_LENGTH(2, kExprIf);
EXPECT_LENGTH(1, kExprElse);
EXPECT_LENGTH(1, kExprEnd);
EXPECT_LENGTH(1, kExprSelect);
EXPECT_LENGTH(2, kExprBr);
EXPECT_LENGTH(2, kExprBrIf);
EXPECT_LENGTH(2, kExprThrow);
EXPECT_LENGTH(2, kExprTry);
EXPECT_LENGTH(2, kExprCatch);
EXPECT_LENGTH_N(2, kExprBlock, kLocalI32);
EXPECT_LENGTH_N(2, kExprLoop, kLocalI32);
EXPECT_LENGTH_N(2, kExprIf, kLocalI32);
EXPECT_LENGTH_N(2, kExprTry, kLocalI32);
}
TEST_F(WasmOpcodeLengthTest, MiscExpressions) {
......
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