Use types to distinguish between wasm function body indices and wasm function indices.

This commit is contained in:
Maddy
2018-08-02 01:29:47 +00:00
committed by Dan Gohman
parent f7e481d9ac
commit f5d46cabe7
12 changed files with 71 additions and 53 deletions

View File

@@ -15,6 +15,7 @@ path = "src/clif-util.rs"
[dependencies] [dependencies]
cfg-if = "0.1" cfg-if = "0.1"
cranelift-codegen = { path = "lib/codegen", version = "0.18.1" } cranelift-codegen = { path = "lib/codegen", version = "0.18.1" }
cranelift-entity = { path = "lib/entity", version = "0.18.1" }
cranelift-reader = { path = "lib/reader", version = "0.18.1" } cranelift-reader = { path = "lib/reader", version = "0.18.1" }
cranelift-frontend = { path = "lib/frontend", version = "0.18.1" } cranelift-frontend = { path = "lib/frontend", version = "0.18.1" }
cranelift-serde = { path = "lib/serde", version = "0.18.1", optional = true } cranelift-serde = { path = "lib/serde", version = "0.18.1", optional = true }

View File

@@ -23,6 +23,7 @@ extern crate term;
cfg_if! { cfg_if! {
if #[cfg(feature = "wasm")] { if #[cfg(feature = "wasm")] {
extern crate cranelift_entity;
extern crate cranelift_wasm; extern crate cranelift_wasm;
extern crate wabt; extern crate wabt;
mod wasm; mod wasm;

View File

@@ -7,7 +7,8 @@
use cranelift_codegen::Context; use cranelift_codegen::Context;
use cranelift_codegen::print_errors::{pretty_error, pretty_verifier_error}; use cranelift_codegen::print_errors::{pretty_error, pretty_verifier_error};
use cranelift_codegen::settings::FlagsOrIsa; use cranelift_codegen::settings::FlagsOrIsa;
use cranelift_wasm::{translate_module, DummyEnvironment, ModuleEnvironment}; use cranelift_entity::EntityRef;
use cranelift_wasm::{translate_module, DummyEnvironment, FuncIndex, ModuleEnvironment};
use std::error::Error; use std::error::Error;
use std::path::Path; use std::path::Path;
use std::path::PathBuf; use std::path::PathBuf;
@@ -107,17 +108,17 @@ fn handle_module(
} }
let num_func_imports = dummy_environ.get_num_func_imports(); let num_func_imports = dummy_environ.get_num_func_imports();
for (def_index, func) in dummy_environ.info.function_bodies.iter().enumerate() { for (def_index, func) in dummy_environ.info.function_bodies.iter() {
let func_index = num_func_imports + def_index; let func_index = num_func_imports + def_index.index();
let mut context = Context::new(); let mut context = Context::new();
context.func = func.clone(); context.func = func.clone();
if let Some(start_func) = dummy_environ.info.start_func { if let Some(start_func) = dummy_environ.info.start_func {
if func_index == start_func { if func_index == start_func.index() {
println!("; Selected as wasm start function"); println!("; Selected as wasm start function");
} }
} }
vprintln!(flag_verbose, ""); vprintln!(flag_verbose, "");
for export_name in &dummy_environ.info.functions[func_index].export_names { for export_name in &dummy_environ.info.functions[FuncIndex::new(func_index)].export_names {
println!("; Exported as \"{}\"", export_name); println!("; Exported as \"{}\"", export_name);
} }
println!("{}", context.func.display(None)); println!("{}", context.func.display(None));
@@ -142,10 +143,10 @@ fn handle_module(
let num_func_imports = dummy_environ.get_num_func_imports(); let num_func_imports = dummy_environ.get_num_func_imports();
let mut total_module_code_size = 0; let mut total_module_code_size = 0;
let mut context = Context::new(); let mut context = Context::new();
for (def_index, func) in dummy_environ.info.function_bodies.iter().enumerate() { for (def_index, func) in dummy_environ.info.function_bodies.iter() {
context.func = func.clone(); context.func = func.clone();
let func_index = num_func_imports + def_index; let func_index = num_func_imports + def_index.index();
if flag_check_translation { if flag_check_translation {
context context
.verify(fisa) .verify(fisa)
@@ -162,7 +163,7 @@ fn handle_module(
total_module_code_size += compiled_size; total_module_code_size += compiled_size;
println!( println!(
"Function #{} bytecode size: {} bytes", "Function #{} bytecode size: {} bytes",
func_index, dummy_environ.func_bytecode_sizes[def_index] func_index, dummy_environ.func_bytecode_sizes[def_index.index()]
); );
} }
} }
@@ -170,11 +171,11 @@ fn handle_module(
if flag_print { if flag_print {
vprintln!(flag_verbose, ""); vprintln!(flag_verbose, "");
if let Some(start_func) = dummy_environ.info.start_func { if let Some(start_func) = dummy_environ.info.start_func {
if func_index == start_func { if func_index == start_func.index() {
println!("; Selected as wasm start function"); println!("; Selected as wasm start function");
} }
} }
for export_name in &dummy_environ.info.functions[func_index].export_names { for export_name in &dummy_environ.info.functions[FuncIndex::new(func_index)].export_names {
println!("; Exported as \"{}\"", export_name); println!("; Exported as \"{}\"", export_name);
} }
println!("{}", context.func.display(fisa.isa)); println!("{}", context.func.display(fisa.isa));

View File

@@ -11,6 +11,7 @@ keywords = ["webassembly", "wasm"]
[dependencies] [dependencies]
wasmparser = { version = "0.17.2", default-features = false } wasmparser = { version = "0.17.2", default-features = false }
cranelift-codegen = { path = "../codegen", version = "0.18.1", default-features = false } cranelift-codegen = { path = "../codegen", version = "0.18.1", default-features = false }
cranelift-entity = { path = "../entity", version = "0.18.1", default-features = false }
cranelift-frontend = { path = "../frontend", version = "0.18.1", default-features = false } cranelift-frontend = { path = "../frontend", version = "0.18.1", default-features = false }
hashmap_core = { version = "0.1.9", optional = true } hashmap_core = { version = "0.1.9", optional = true }
failure = { version = "0.1.1", default-features = false, features = ["derive"] } failure = { version = "0.1.1", default-features = false, features = ["derive"] }

View File

@@ -26,6 +26,7 @@ use cranelift_codegen::ir::condcodes::{FloatCC, IntCC};
use cranelift_codegen::ir::types::*; use cranelift_codegen::ir::types::*;
use cranelift_codegen::ir::{self, InstBuilder, JumpTableData, MemFlags}; use cranelift_codegen::ir::{self, InstBuilder, JumpTableData, MemFlags};
use cranelift_codegen::packed_option::ReservedValue; use cranelift_codegen::packed_option::ReservedValue;
use cranelift_entity::EntityRef;
use cranelift_frontend::{FunctionBuilder, Variable}; use cranelift_frontend::{FunctionBuilder, Variable};
use environ::{FuncEnvironment, GlobalVariable, WasmError, WasmResult}; use environ::{FuncEnvironment, GlobalVariable, WasmError, WasmResult};
use state::{ControlStackFrame, TranslationState}; use state::{ControlStackFrame, TranslationState};
@@ -33,7 +34,7 @@ use std::collections::{hash_map, HashMap};
use std::vec::Vec; use std::vec::Vec;
use std::{i32, u32}; use std::{i32, u32};
use translation_utils::{f32_translation, f64_translation, num_return_values, type_to_type}; use translation_utils::{f32_translation, f64_translation, num_return_values, type_to_type};
use translation_utils::{FunctionIndex, MemoryIndex, SignatureIndex, TableIndex}; use translation_utils::{FuncIndex, MemoryIndex, SignatureIndex, TableIndex};
use wasmparser::{MemoryImmediate, Operator}; use wasmparser::{MemoryImmediate, Operator};
// Clippy warns about "flags: _" but its important to document that the flags field is ignored // Clippy warns about "flags: _" but its important to document that the flags field is ignored
@@ -358,7 +359,7 @@ pub fn translate_operator<FE: FuncEnvironment + ?Sized>(
let (fref, num_args) = state.get_direct_func(builder.func, function_index, environ); let (fref, num_args) = state.get_direct_func(builder.func, function_index, environ);
let call = environ.translate_call( let call = environ.translate_call(
builder.cursor(), builder.cursor(),
function_index as FunctionIndex, FuncIndex::new(function_index as usize),
fref, fref,
state.peekn(num_args), state.peekn(num_args),
)?; )?;

View File

@@ -5,19 +5,20 @@ use cranelift_codegen::ir::immediates::Imm64;
use cranelift_codegen::ir::types::*; use cranelift_codegen::ir::types::*;
use cranelift_codegen::ir::{self, InstBuilder}; use cranelift_codegen::ir::{self, InstBuilder};
use cranelift_codegen::settings; use cranelift_codegen::settings;
use cranelift_entity::{EntityRef, PrimaryMap};
use environ::{FuncEnvironment, GlobalVariable, ModuleEnvironment, WasmResult}; use environ::{FuncEnvironment, GlobalVariable, ModuleEnvironment, WasmResult};
use func_translator::FuncTranslator; use func_translator::FuncTranslator;
use std::string::String; use std::string::String;
use std::vec::Vec; use std::vec::Vec;
use target_lexicon::Triple; use target_lexicon::Triple;
use translation_utils::{ use translation_utils::{
FunctionIndex, Global, GlobalIndex, Memory, MemoryIndex, SignatureIndex, Table, TableIndex, DefinedFuncIndex, FuncIndex, Global, GlobalIndex, Memory, MemoryIndex, SignatureIndex, Table, TableIndex,
}; };
use wasmparser; use wasmparser;
/// Compute a `ir::ExternalName` for a given wasm function index. /// Compute a `ir::ExternalName` for a given wasm function index.
fn get_func_name(func_index: FunctionIndex) -> ir::ExternalName { fn get_func_name(func_index: FuncIndex) -> ir::ExternalName {
ir::ExternalName::user(0, func_index as u32) ir::ExternalName::user(0, func_index.index() as u32)
} }
/// A collection of names under which a given entity is exported. /// A collection of names under which a given entity is exported.
@@ -55,10 +56,10 @@ pub struct DummyModuleInfo {
pub imported_funcs: Vec<(String, String)>, pub imported_funcs: Vec<(String, String)>,
/// Functions, imported and local. /// Functions, imported and local.
pub functions: Vec<Exportable<SignatureIndex>>, pub functions: PrimaryMap<FuncIndex, Exportable<SignatureIndex>>,
/// Function bodies. /// Function bodies.
pub function_bodies: Vec<ir::Function>, pub function_bodies: PrimaryMap<DefinedFuncIndex, ir::Function>,
/// Tables as provided by `declare_table`. /// Tables as provided by `declare_table`.
pub tables: Vec<Exportable<Table>>, pub tables: Vec<Exportable<Table>>,
@@ -70,7 +71,7 @@ pub struct DummyModuleInfo {
pub globals: Vec<Exportable<Global>>, pub globals: Vec<Exportable<Global>>,
/// The start function. /// The start function.
pub start_func: Option<FunctionIndex>, pub start_func: Option<DefinedFuncIndex>,
} }
impl DummyModuleInfo { impl DummyModuleInfo {
@@ -81,8 +82,8 @@ impl DummyModuleInfo {
flags, flags,
signatures: Vec::new(), signatures: Vec::new(),
imported_funcs: Vec::new(), imported_funcs: Vec::new(),
functions: Vec::new(), functions: PrimaryMap::new(),
function_bodies: Vec::new(), function_bodies: PrimaryMap::new(),
tables: Vec::new(), tables: Vec::new(),
memories: Vec::new(), memories: Vec::new(),
globals: Vec::new(), globals: Vec::new(),
@@ -215,7 +216,7 @@ impl<'dummy_environment> FuncEnvironment for DummyFuncEnvironment<'dummy_environ
func.import_signature(self.vmctx_sig(index)) func.import_signature(self.vmctx_sig(index))
} }
fn make_direct_func(&mut self, func: &mut ir::Function, index: FunctionIndex) -> ir::FuncRef { fn make_direct_func(&mut self, func: &mut ir::Function, index: FuncIndex) -> ir::FuncRef {
let sigidx = self.mod_info.functions[index].entity; let sigidx = self.mod_info.functions[index].entity;
// A real implementation would probably add a `vmctx` argument. // A real implementation would probably add a `vmctx` argument.
// And maybe attempt some signature de-duplication. // And maybe attempt some signature de-duplication.
@@ -275,7 +276,7 @@ impl<'dummy_environment> FuncEnvironment for DummyFuncEnvironment<'dummy_environ
fn translate_call( fn translate_call(
&mut self, &mut self,
mut pos: FuncCursor, mut pos: FuncCursor,
_callee_index: FunctionIndex, _callee_index: FuncIndex,
callee: ir::FuncRef, callee: ir::FuncRef,
call_args: &[ir::Value], call_args: &[ir::Value],
) -> WasmResult<ir::Inst> { ) -> WasmResult<ir::Inst> {
@@ -319,7 +320,7 @@ impl<'data> ModuleEnvironment<'data> for DummyEnvironment {
&self.info.flags &self.info.flags
} }
fn get_func_name(&self, func_index: FunctionIndex) -> ir::ExternalName { fn get_func_name(&self, func_index: FuncIndex) -> ir::ExternalName {
get_func_name(func_index) get_func_name(func_index)
} }
@@ -356,7 +357,7 @@ impl<'data> ModuleEnvironment<'data> for DummyEnvironment {
self.info.functions.push(Exportable::new(sig_index)); self.info.functions.push(Exportable::new(sig_index));
} }
fn get_func_type(&self, func_index: FunctionIndex) -> SignatureIndex { fn get_func_type(&self, func_index: FuncIndex) -> SignatureIndex {
self.info.functions[func_index].entity self.info.functions[func_index].entity
} }
@@ -376,7 +377,7 @@ impl<'data> ModuleEnvironment<'data> for DummyEnvironment {
_table_index: TableIndex, _table_index: TableIndex,
_base: Option<GlobalIndex>, _base: Option<GlobalIndex>,
_offset: usize, _offset: usize,
_elements: Vec<FunctionIndex>, _elements: Vec<FuncIndex>,
) { ) {
// We do nothing // We do nothing
} }
@@ -393,7 +394,7 @@ impl<'data> ModuleEnvironment<'data> for DummyEnvironment {
// We do nothing // We do nothing
} }
fn declare_func_export(&mut self, func_index: FunctionIndex, name: &'data str) { fn declare_func_export(&mut self, func_index: FuncIndex, name: &'data str) {
self.info.functions[func_index] self.info.functions[func_index]
.export_names .export_names
.push(String::from(name)); .push(String::from(name));
@@ -417,7 +418,7 @@ impl<'data> ModuleEnvironment<'data> for DummyEnvironment {
.push(String::from(name)); .push(String::from(name));
} }
fn declare_start_func(&mut self, func_index: FunctionIndex) { fn declare_start_func(&mut self, func_index: DefinedFuncIndex) {
debug_assert!(self.info.start_func.is_none()); debug_assert!(self.info.start_func.is_none());
self.info.start_func = Some(func_index); self.info.start_func = Some(func_index);
} }
@@ -425,9 +426,9 @@ impl<'data> ModuleEnvironment<'data> for DummyEnvironment {
fn define_function_body(&mut self, body_bytes: &'data [u8]) -> WasmResult<()> { fn define_function_body(&mut self, body_bytes: &'data [u8]) -> WasmResult<()> {
let func = { let func = {
let mut func_environ = DummyFuncEnvironment::new(&self.info); let mut func_environ = DummyFuncEnvironment::new(&self.info);
let function_index = self.get_num_func_imports() + self.info.function_bodies.len(); let func_index = FuncIndex::new(self.get_num_func_imports() + self.info.function_bodies.len());
let name = get_func_name(function_index); let name = get_func_name(func_index);
let sig = func_environ.vmctx_sig(self.get_func_type(function_index)); let sig = func_environ.vmctx_sig(self.get_func_type(func_index));
let mut func = ir::Function::with_name_signature(name, sig); let mut func = ir::Function::with_name_signature(name, sig);
let reader = wasmparser::BinaryReader::new(body_bytes); let reader = wasmparser::BinaryReader::new(body_bytes);
self.trans self.trans

View File

@@ -6,7 +6,7 @@ use cranelift_codegen::settings::Flags;
use std::vec::Vec; use std::vec::Vec;
use target_lexicon::Triple; use target_lexicon::Triple;
use translation_utils::{ use translation_utils::{
FunctionIndex, Global, GlobalIndex, Memory, MemoryIndex, SignatureIndex, Table, TableIndex, DefinedFuncIndex, FuncIndex, Global, GlobalIndex, Memory, MemoryIndex, SignatureIndex, Table, TableIndex,
}; };
use wasmparser::BinaryReaderError; use wasmparser::BinaryReaderError;
@@ -137,7 +137,7 @@ pub trait FuncEnvironment {
/// ///
/// The function's signature will only be used for direct calls, even if the module has /// The function's signature will only be used for direct calls, even if the module has
/// indirect calls with the same WebAssembly type. /// indirect calls with the same WebAssembly type.
fn make_direct_func(&mut self, func: &mut ir::Function, index: FunctionIndex) -> ir::FuncRef; fn make_direct_func(&mut self, func: &mut ir::Function, index: FuncIndex) -> ir::FuncRef;
/// Translate a `call_indirect` WebAssembly instruction at `pos`. /// Translate a `call_indirect` WebAssembly instruction at `pos`.
/// ///
@@ -169,7 +169,7 @@ pub trait FuncEnvironment {
fn translate_call( fn translate_call(
&mut self, &mut self,
mut pos: FuncCursor, mut pos: FuncCursor,
_callee_index: FunctionIndex, _callee_index: FuncIndex,
callee: ir::FuncRef, callee: ir::FuncRef,
call_args: &[ir::Value], call_args: &[ir::Value],
) -> WasmResult<ir::Inst> { ) -> WasmResult<ir::Inst> {
@@ -222,7 +222,7 @@ pub trait ModuleEnvironment<'data> {
fn flags(&self) -> &Flags; fn flags(&self) -> &Flags;
/// Return the name for the given function index. /// Return the name for the given function index.
fn get_func_name(&self, func_index: FunctionIndex) -> ir::ExternalName; fn get_func_name(&self, func_index: FuncIndex) -> ir::ExternalName;
/// Declares a function signature to the environment. /// Declares a function signature to the environment.
fn declare_signature(&mut self, sig: &ir::Signature); fn declare_signature(&mut self, sig: &ir::Signature);
@@ -245,7 +245,7 @@ pub trait ModuleEnvironment<'data> {
fn declare_func_type(&mut self, sig_index: SignatureIndex); fn declare_func_type(&mut self, sig_index: SignatureIndex);
/// Return the signature index for the given function index. /// Return the signature index for the given function index.
fn get_func_type(&self, func_index: FunctionIndex) -> SignatureIndex; fn get_func_type(&self, func_index: FuncIndex) -> SignatureIndex;
/// Declares a global to the environment. /// Declares a global to the environment.
fn declare_global(&mut self, global: Global); fn declare_global(&mut self, global: Global);
@@ -261,7 +261,7 @@ pub trait ModuleEnvironment<'data> {
table_index: TableIndex, table_index: TableIndex,
base: Option<GlobalIndex>, base: Option<GlobalIndex>,
offset: usize, offset: usize,
elements: Vec<FunctionIndex>, elements: Vec<FuncIndex>,
); );
/// Declares a memory to the environment /// Declares a memory to the environment
fn declare_memory(&mut self, memory: Memory); fn declare_memory(&mut self, memory: Memory);
@@ -275,7 +275,7 @@ pub trait ModuleEnvironment<'data> {
); );
/// Declares a function export to the environment. /// Declares a function export to the environment.
fn declare_func_export(&mut self, func_index: FunctionIndex, name: &'data str); fn declare_func_export(&mut self, func_index: FuncIndex, name: &'data str);
/// Declares a table export to the environment. /// Declares a table export to the environment.
fn declare_table_export(&mut self, table_index: TableIndex, name: &'data str); fn declare_table_export(&mut self, table_index: TableIndex, name: &'data str);
/// Declares a memory export to the environment. /// Declares a memory export to the environment.
@@ -284,7 +284,7 @@ pub trait ModuleEnvironment<'data> {
fn declare_global_export(&mut self, global_index: GlobalIndex, name: &'data str); fn declare_global_export(&mut self, global_index: GlobalIndex, name: &'data str);
/// Declares a start function. /// Declares a start function.
fn declare_start_func(&mut self, index: FunctionIndex); fn declare_start_func(&mut self, index: DefinedFuncIndex);
/// Provides the contents of a function body. /// Provides the contents of a function body.
fn define_function_body(&mut self, body_bytes: &'data [u8]) -> WasmResult<()>; fn define_function_body(&mut self, body_bytes: &'data [u8]) -> WasmResult<()>;

View File

@@ -26,6 +26,8 @@
#[macro_use(dbg)] #[macro_use(dbg)]
extern crate cranelift_codegen; extern crate cranelift_codegen;
#[macro_use]
extern crate cranelift_entity;
extern crate cranelift_frontend; extern crate cranelift_frontend;
extern crate target_lexicon; extern crate target_lexicon;
extern crate wasmparser; extern crate wasmparser;
@@ -48,7 +50,7 @@ pub use environ::{
pub use func_translator::FuncTranslator; pub use func_translator::FuncTranslator;
pub use module_translator::translate_module; pub use module_translator::translate_module;
pub use translation_utils::{ pub use translation_utils::{
FunctionIndex, Global, GlobalIndex, GlobalInit, Memory, MemoryIndex, SignatureIndex, Table, DefinedFuncIndex, FuncIndex, Global, GlobalIndex, GlobalInit, Memory, MemoryIndex, SignatureIndex, Table,
TableIndex, TableIndex,
}; };

View File

@@ -8,11 +8,12 @@
//! is handled, according to the semantics of WebAssembly, to only specific expressions that are //! is handled, according to the semantics of WebAssembly, to only specific expressions that are
//! interpreted on the fly. //! interpreted on the fly.
use cranelift_codegen::ir::{self, AbiParam, Signature}; use cranelift_codegen::ir::{self, AbiParam, Signature};
use cranelift_entity::EntityRef;
use environ::{ModuleEnvironment, WasmError, WasmResult}; use environ::{ModuleEnvironment, WasmError, WasmResult};
use std::str::from_utf8; use std::str::from_utf8;
use std::vec::Vec; use std::vec::Vec;
use translation_utils::{ use translation_utils::{
type_to_type, FunctionIndex, Global, GlobalIndex, GlobalInit, Memory, MemoryIndex, type_to_type, DefinedFuncIndex, FuncIndex, Global, GlobalIndex, GlobalInit, Memory, MemoryIndex,
SignatureIndex, Table, TableElementType, TableIndex, SignatureIndex, Table, TableElementType, TableIndex,
}; };
use wasmparser; use wasmparser;
@@ -150,12 +151,12 @@ pub fn parse_export_section<'data>(
// assume valid UTF-8 and use `from_utf8_unchecked` if performance // assume valid UTF-8 and use `from_utf8_unchecked` if performance
// becomes a concern here. // becomes a concern here.
let name = from_utf8(field).unwrap(); let name = from_utf8(field).unwrap();
let func_index = index as FunctionIndex; let func_index = FuncIndex::new(index as usize);
match *kind { match *kind {
ExternalKind::Function => environ.declare_func_export(func_index, name), ExternalKind::Function => environ.declare_func_export(func_index, name),
ExternalKind::Table => environ.declare_table_export(func_index, name), ExternalKind::Table => environ.declare_table_export(func_index.index(), name),
ExternalKind::Memory => environ.declare_memory_export(func_index, name), ExternalKind::Memory => environ.declare_memory_export(func_index.index(), name),
ExternalKind::Global => environ.declare_global_export(func_index, name), ExternalKind::Global => environ.declare_global_export(func_index.index(), name),
} }
} }
ParserState::EndSection => break, ParserState::EndSection => break,
@@ -171,7 +172,7 @@ pub fn parse_start_section(parser: &mut Parser, environ: &mut ModuleEnvironment)
loop { loop {
match *parser.read() { match *parser.read() {
ParserState::StartSectionEntry(index) => { ParserState::StartSectionEntry(index) => {
environ.declare_start_func(index as FunctionIndex); environ.declare_start_func(DefinedFuncIndex::new(index as usize));
} }
ParserState::EndSection => break, ParserState::EndSection => break,
ParserState::Error(e) => return Err(WasmError::from_binary_reader_error(e)), ParserState::Error(e) => return Err(WasmError::from_binary_reader_error(e)),
@@ -382,8 +383,8 @@ pub fn parse_elements_section(
}; };
match *parser.read() { match *parser.read() {
ParserState::ElementSectionEntryBody(ref elements) => { ParserState::ElementSectionEntryBody(ref elements) => {
let elems: Vec<FunctionIndex> = let elems: Vec<FuncIndex> =
elements.iter().map(|&x| x as FunctionIndex).collect(); elements.iter().map(|&x| FuncIndex::new(x as usize)).collect();
environ.declare_table_elements(table_index, base, offset, elems) environ.declare_table_elements(table_index, base, offset, elems)
} }
ParserState::Error(e) => return Err(WasmError::from_binary_reader_error(e)), ParserState::Error(e) => return Err(WasmError::from_binary_reader_error(e)),

View File

@@ -4,10 +4,11 @@
//! value and control stacks during the translation of a single function. //! value and control stacks during the translation of a single function.
use cranelift_codegen::ir::{self, Ebb, Inst, Value}; use cranelift_codegen::ir::{self, Ebb, Inst, Value};
use cranelift_entity::EntityRef;
use environ::{FuncEnvironment, GlobalVariable}; use environ::{FuncEnvironment, GlobalVariable};
use std::collections::HashMap; use std::collections::HashMap;
use std::vec::Vec; use std::vec::Vec;
use translation_utils::{FunctionIndex, GlobalIndex, MemoryIndex, SignatureIndex, TableIndex}; use translation_utils::{FuncIndex, GlobalIndex, MemoryIndex, SignatureIndex, TableIndex};
/// A control stack frame can be an `if`, a `block` or a `loop`, each one having the following /// A control stack frame can be an `if`, a `block` or a `loop`, each one having the following
/// fields: /// fields:
@@ -151,7 +152,7 @@ pub struct TranslationState {
// Imported and local functions that have been created by // Imported and local functions that have been created by
// `FuncEnvironment::make_direct_func()`. // `FuncEnvironment::make_direct_func()`.
// Stores both the function reference and the number of WebAssembly arguments // Stores both the function reference and the number of WebAssembly arguments
functions: HashMap<FunctionIndex, (ir::FuncRef, usize)>, functions: HashMap<FuncIndex, (ir::FuncRef, usize)>,
} }
impl TranslationState { impl TranslationState {
@@ -349,7 +350,7 @@ impl TranslationState {
index: u32, index: u32,
environ: &mut FE, environ: &mut FE,
) -> (ir::FuncRef, usize) { ) -> (ir::FuncRef, usize) {
let index = index as FunctionIndex; let index = FuncIndex::new(index as usize);
*self.functions.entry(index).or_insert_with(|| { *self.functions.entry(index).or_insert_with(|| {
let fref = environ.make_direct_func(func, index); let fref = environ.make_direct_func(func, index);
let sig = func.dfg.ext_funcs[fref].signature; let sig = func.dfg.ext_funcs[fref].signature;

View File

@@ -3,8 +3,16 @@ use cranelift_codegen::ir;
use std::u32; use std::u32;
use wasmparser; use wasmparser;
/// Index of a function (imported or defined) inside the WebAssembly module. /// Index type of a function (imported or defined) inside the WebAssembly module.
pub type FunctionIndex = usize; #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct FuncIndex(u32);
entity_impl!(FuncIndex);
/// Index type of a defined function inside the WebAssembly module.
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct DefinedFuncIndex(u32);
entity_impl!(DefinedFuncIndex);
/// Index of a table (imported or defined) inside the WebAssembly module. /// Index of a table (imported or defined) inside the WebAssembly module.
pub type TableIndex = usize; pub type TableIndex = usize;
/// Index of a global variable (imported or defined) inside the WebAssembly module. /// Index of a global variable (imported or defined) inside the WebAssembly module.

View File

@@ -75,7 +75,7 @@ fn handle_module(path: &Path, flags: &Flags) {
}; };
let mut dummy_environ = DummyEnvironment::with_triple_flags(triple!("riscv64"), flags.clone()); let mut dummy_environ = DummyEnvironment::with_triple_flags(triple!("riscv64"), flags.clone());
translate_module(&data, &mut dummy_environ).unwrap(); translate_module(&data, &mut dummy_environ).unwrap();
for func in &dummy_environ.info.function_bodies { for func in dummy_environ.info.function_bodies.values() {
verifier::verify_function(func, flags) verifier::verify_function(func, flags)
.map_err(|err| panic!(pretty_verifier_error(func, None, None, &err))) .map_err(|err| panic!(pretty_verifier_error(func, None, None, &err)))
.unwrap(); .unwrap();