Add a calling convention to all function signatures.

A CallConv enum on every function signature makes it possible to
generate calls to functions with different calling conventions within
the same ISA / within a single function.

The calling conventions also serve as a way of customizing Cretonne's
behavior when embedded inside a VM. As an example, the SpiderWASM
calling convention is used to compile WebAssembly functions that run
inside the SpiderMonkey virtual machine.

All function signatures must have a calling convention at the end, so
this changes the textual IL syntax.

Before:

    sig1 = signature(i32, f64) -> f64

After

    sig1 = (i32, f64) -> f64 native
    sig2 = (i32) spiderwasm

When printing functions, the signature goes after the return types:

    function %r1() -> i32, f32 spiderwasm {
    ebb1:
        ...
    }

In the parser, this calling convention is optional and defaults to
"native". This is mostly to avoid updating all the existing test cases
under filetests/. When printing a function, the calling convention is
always included, including for "native" functions.
This commit is contained in:
Jakob Stoklund Olesen
2017-08-02 16:40:35 -07:00
committed by Jakob Stoklund Olesen
parent 5fa991e325
commit c96d4daa20
27 changed files with 211 additions and 144 deletions

View File

@@ -25,6 +25,9 @@ pub struct Signature {
/// Types returned from the function.
pub return_types: Vec<ArgumentType>,
/// Calling convention.
pub call_conv: CallConv,
/// When the signature has been legalized to a specific ISA, this holds the size of the
/// argument array on the stack. Before legalization, this is `None`.
///
@@ -35,10 +38,11 @@ pub struct Signature {
impl Signature {
/// Create a new blank signature.
pub fn new() -> Signature {
pub fn new(call_conv: CallConv) -> Signature {
Signature {
argument_types: Vec::new(),
return_types: Vec::new(),
call_conv,
argument_bytes: None,
}
}
@@ -94,7 +98,7 @@ impl<'a> fmt::Display for DisplaySignature<'a> {
write!(f, " -> ")?;
write_list(f, &self.0.return_types, self.1)?;
}
Ok(())
write!(f, " {}", self.0.call_conv)
}
}
@@ -278,6 +282,46 @@ impl fmt::Display for ExtFuncData {
}
}
/// A Calling convention.
///
/// A function's calling convention determines exactly how arguments and return values are passed,
/// and how stack frames are managed. Since all of these details depend on both the instruction set
/// architecture and possibly the operating system, a function's calling convention is only fully
/// determined by a `(TargetIsa, CallConv)` tuple.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CallConv {
/// The C calling convention.
///
/// This is the native calling convention that a C compiler would use on the platform.
Native,
/// A JIT-compiled WebAssembly function in the SpiderMonkey VM.
SpiderWASM,
}
impl fmt::Display for CallConv {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use self::CallConv::*;
f.write_str(match *self {
Native => "native",
SpiderWASM => "spiderwasm",
})
}
}
impl FromStr for CallConv {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
use self::CallConv::*;
match s {
"native" => Ok(Native),
"spiderwasm" => Ok(SpiderWASM),
_ => Err(()),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -306,19 +350,26 @@ mod tests {
}
}
#[test]
fn call_conv() {
for &cc in &[CallConv::Native, CallConv::SpiderWASM] {
assert_eq!(Ok(cc), cc.to_string().parse())
}
}
#[test]
fn signatures() {
let mut sig = Signature::new();
assert_eq!(sig.to_string(), "()");
let mut sig = Signature::new(CallConv::SpiderWASM);
assert_eq!(sig.to_string(), "() spiderwasm");
sig.argument_types.push(ArgumentType::new(I32));
assert_eq!(sig.to_string(), "(i32)");
assert_eq!(sig.to_string(), "(i32) spiderwasm");
sig.return_types.push(ArgumentType::new(F32));
assert_eq!(sig.to_string(), "(i32) -> f32");
assert_eq!(sig.to_string(), "(i32) -> f32 spiderwasm");
sig.argument_types
.push(ArgumentType::new(I32.by(4).unwrap()));
assert_eq!(sig.to_string(), "(i32, i32x4) -> f32");
assert_eq!(sig.to_string(), "(i32, i32x4) -> f32 spiderwasm");
sig.return_types.push(ArgumentType::new(B8));
assert_eq!(sig.to_string(), "(i32, i32x4) -> f32, b8");
assert_eq!(sig.to_string(), "(i32, i32x4) -> f32, b8 spiderwasm");
// Test the offset computation algorithm.
assert_eq!(sig.argument_bytes, None);
@@ -332,6 +383,7 @@ mod tests {
assert_eq!(sig.argument_bytes, Some(28));
// Writing ABI-annotated signatures.
assert_eq!(sig.to_string(), "(i32 [24], i32x4 [8]) -> f32, b8");
assert_eq!(sig.to_string(),
"(i32 [24], i32x4 [8]) -> f32, b8 spiderwasm");
}
}

View File

@@ -4,7 +4,7 @@
//! instructions.
use entity_map::{EntityMap, PrimaryEntityData};
use ir::{FunctionName, Signature, JumpTableData, DataFlowGraph, Layout};
use ir::{FunctionName, CallConv, Signature, JumpTableData, DataFlowGraph, Layout};
use ir::{JumpTables, InstEncodings, ValueLocations, StackSlots, EbbOffsets};
use isa::TargetIsa;
use std::fmt;
@@ -67,9 +67,9 @@ impl Function {
}
}
/// Create a new empty, anonymous function.
/// Create a new empty, anonymous function with a native calling convention.
pub fn new() -> Function {
Self::with_name_signature(FunctionName::default(), Signature::new())
Self::with_name_signature(FunctionName::default(), Signature::new(CallConv::Native))
}
/// Return an object that can display this function with correct ISA-specific annotations.

View File

@@ -18,7 +18,8 @@ mod progpoint;
mod valueloc;
pub use ir::funcname::FunctionName;
pub use ir::extfunc::{Signature, ArgumentType, ArgumentExtension, ArgumentPurpose, ExtFuncData};
pub use ir::extfunc::{Signature, CallConv, ArgumentType, ArgumentExtension, ArgumentPurpose,
ExtFuncData};
pub use ir::types::Type;
pub use ir::entities::{Ebb, Inst, Value, StackSlot, JumpTable, FuncRef, SigRef};
pub use ir::instructions::{Opcode, InstructionData, VariableArgs, ValueList, ValueListPool};

View File

@@ -54,7 +54,7 @@ fn write_preamble(w: &mut Write,
for sig in func.dfg.signatures.keys() {
any = true;
writeln!(w,
" {} = signature{}",
" {} = {}",
sig,
func.dfg.signatures[sig].display(regs))?;
}
@@ -366,26 +366,27 @@ mod tests {
#[test]
fn basic() {
let mut f = Function::new();
assert_eq!(f.to_string(), "function %() {\n}\n");
assert_eq!(f.to_string(), "function %() native {\n}\n");
f.name = FunctionName::new("foo");
assert_eq!(f.to_string(), "function %foo() {\n}\n");
assert_eq!(f.to_string(), "function %foo() native {\n}\n");
f.stack_slots
.push(StackSlotData::new(StackSlotKind::Local, 4));
assert_eq!(f.to_string(), "function %foo() {\n ss0 = local 4\n}\n");
assert_eq!(f.to_string(),
"function %foo() native {\n ss0 = local 4\n}\n");
let ebb = f.dfg.make_ebb();
f.layout.append_ebb(ebb);
assert_eq!(f.to_string(),
"function %foo() {\n ss0 = local 4\n\nebb0:\n}\n");
"function %foo() native {\n ss0 = local 4\n\nebb0:\n}\n");
f.dfg.append_ebb_arg(ebb, types::I8);
assert_eq!(f.to_string(),
"function %foo() {\n ss0 = local 4\n\nebb0(v0: i8):\n}\n");
"function %foo() native {\n ss0 = local 4\n\nebb0(v0: i8):\n}\n");
f.dfg.append_ebb_arg(ebb, types::F32.by(4).unwrap());
assert_eq!(f.to_string(),
"function %foo() {\n ss0 = local 4\n\nebb0(v0: i8, v1: f32x4):\n}\n");
"function %foo() native {\n ss0 = local 4\n\nebb0(v0: i8, v1: f32x4):\n}\n");
}
}

View File

@@ -572,7 +572,7 @@ impl<'a, Variable> FunctionBuilder<'a, Variable>
mod tests {
use cretonne::entity_ref::EntityRef;
use cretonne::ir::{FunctionName, Function, Signature, ArgumentType, InstBuilder};
use cretonne::ir::{FunctionName, Function, CallConv, Signature, ArgumentType, InstBuilder};
use cretonne::ir::types::*;
use frontend::{ILBuilder, FunctionBuilder};
use cretonne::verifier::verify_function;
@@ -600,7 +600,7 @@ mod tests {
#[test]
fn sample_function() {
let mut sig = Signature::new();
let mut sig = Signature::new(CallConv::Native);
sig.return_types.push(ArgumentType::new(I32));
sig.argument_types.push(ArgumentType::new(I32));

View File

@@ -36,7 +36,7 @@
//! extern crate cton_frontend;
//!
//! use cretonne::entity_ref::EntityRef;
//! use cretonne::ir::{FunctionName, Function, Signature, ArgumentType, InstBuilder};
//! use cretonne::ir::{FunctionName, CallConv, Function, Signature, ArgumentType, InstBuilder};
//! use cretonne::ir::types::*;
//! use cton_frontend::{ILBuilder, FunctionBuilder};
//! use cretonne::verifier::verify_function;
@@ -62,7 +62,7 @@
//! }
//!
//! fn main() {
//! let mut sig = Signature::new();
//! let mut sig = Signature::new(CallConv::Native);
//! sig.return_types.push(ArgumentType::new(I32));
//! sig.argument_types.push(ArgumentType::new(I32));
//! let mut il_builder = ILBuilder::<Variable>::new();

View File

@@ -9,9 +9,9 @@ use std::collections::HashMap;
use std::str::FromStr;
use std::{u16, u32};
use std::mem;
use cretonne::ir::{Function, Ebb, Opcode, Value, Type, FunctionName, StackSlotData, JumpTable,
JumpTableData, Signature, ArgumentType, ArgumentExtension, ExtFuncData, SigRef,
FuncRef, StackSlot, ValueLoc, ArgumentLoc, MemFlags};
use cretonne::ir::{Function, Ebb, Opcode, Value, Type, FunctionName, CallConv, StackSlotData,
JumpTable, JumpTableData, Signature, ArgumentType, ArgumentExtension,
ExtFuncData, SigRef, FuncRef, StackSlot, ValueLoc, ArgumentLoc, MemFlags};
use cretonne::ir::types::VOID;
use cretonne::ir::immediates::{Imm64, Offset32, Uoffset32, Ieee32, Ieee64};
use cretonne::ir::entities::AnyEntity;
@@ -767,13 +767,14 @@ impl<'a> Parser<'a> {
// Parse a function signature.
//
// signature ::= * "(" [arglist] ")" ["->" retlist] [call_conv]
// signature ::= * "(" [arglist] ")" ["->" retlist] [callconv]
//
fn parse_signature(&mut self, unique_isa: Option<&TargetIsa>) -> Result<Signature> {
let mut sig = Signature::new();
// Calling convention defaults to `native`, but can be changed.
let mut sig = Signature::new(CallConv::Native);
self.match_token(Token::LPar, "expected function signature: ( args... )")?;
// signature ::= "(" * [arglist] ")" ["->" retlist] [call_conv]
// signature ::= "(" * [arglist] ")" ["->" retlist] [callconv]
if self.token() != Some(Token::RPar) {
sig.argument_types = self.parse_argument_list(unique_isa)?;
}
@@ -782,12 +783,21 @@ impl<'a> Parser<'a> {
sig.return_types = self.parse_argument_list(unique_isa)?;
}
// The calling convention is optional.
if let Some(Token::Identifier(text)) = self.token() {
match text.parse() {
Ok(cc) => {
self.consume();
sig.call_conv = cc;
}
_ => return err!(self.loc, "unknown calling convention: {}", text),
}
}
if sig.argument_types.iter().all(|a| a.location.is_assigned()) {
sig.compute_argument_bytes();
}
// TBD: calling convention.
Ok(sig)
}
@@ -951,12 +961,11 @@ impl<'a> Parser<'a> {
// Parse a signature decl.
//
// signature-decl ::= SigRef(sigref) "=" "signature" signature
// signature-decl ::= SigRef(sigref) "=" signature
//
fn parse_signature_decl(&mut self, unique_isa: Option<&TargetIsa>) -> Result<(u32, Signature)> {
let number = self.match_sig("expected signature number: sig«n»")?;
self.match_token(Token::Equal, "expected '=' in signature decl")?;
self.match_identifier("signature", "expected 'signature'")?;
let data = self.parse_signature(unique_isa)?;
Ok((number, data))
}
@@ -1755,7 +1764,7 @@ impl<'a> Parser<'a> {
#[cfg(test)]
mod tests {
use super::*;
use cretonne::ir::{ArgumentExtension, ArgumentPurpose};
use cretonne::ir::{CallConv, ArgumentExtension, ArgumentPurpose};
use cretonne::ir::types;
use cretonne::ir::StackSlotKind;
use cretonne::ir::entities::AnyEntity;
@@ -1777,7 +1786,7 @@ mod tests {
#[test]
fn aliases() {
let (func, details) = Parser::new("function %qux() {
let (func, details) = Parser::new("function %qux() native {
ebb0:
v4 = iconst.i8 6
v3 -> v4
@@ -1801,15 +1810,26 @@ mod tests {
#[test]
fn signature() {
let sig = Parser::new("()").parse_signature(None).unwrap();
let sig = Parser::new("()native").parse_signature(None).unwrap();
assert_eq!(sig.argument_types.len(), 0);
assert_eq!(sig.return_types.len(), 0);
assert_eq!(sig.call_conv, CallConv::Native);
let sig2 = Parser::new("(i8 uext, f32, f64, i32 sret) -> i32 sext, f64")
let sig2 = Parser::new("(i8 uext, f32, f64, i32 sret) -> i32 sext, f64 spiderwasm")
.parse_signature(None)
.unwrap();
assert_eq!(sig2.to_string(),
"(i8 uext, f32, f64, i32 sret) -> i32 sext, f64");
"(i8 uext, f32, f64, i32 sret) -> i32 sext, f64 spiderwasm");
assert_eq!(sig2.call_conv, CallConv::SpiderWASM);
// Old-style signature without a calling convention.
assert_eq!(Parser::new("()").parse_signature(None).unwrap().to_string(),
"() native");
assert_eq!(Parser::new("() notacc")
.parse_signature(None)
.unwrap_err()
.to_string(),
"1: unknown calling convention: notacc");
// `void` is not recognized as a type by the lexer. It should not appear in files.
assert_eq!(Parser::new("() -> void")
@@ -1831,7 +1851,7 @@ mod tests {
#[test]
fn stack_slot_decl() {
let (func, _) = Parser::new("function %foo() {
let (func, _) = Parser::new("function %foo() native {
ss3 = incoming_arg 13
ss1 = spill_slot 1
}")
@@ -1850,7 +1870,7 @@ mod tests {
assert_eq!(iter.next(), None);
// Catch duplicate definitions.
assert_eq!(Parser::new("function %bar() {
assert_eq!(Parser::new("function %bar() native {
ss1 = spill_slot 13
ss1 = spill_slot 1
}")
@@ -1862,7 +1882,7 @@ mod tests {
#[test]
fn ebb_header() {
let (func, _) = Parser::new("function %ebbs() {
let (func, _) = Parser::new("function %ebbs() native {
ebb0:
ebb4(v3: i32):
}")
@@ -1884,7 +1904,7 @@ mod tests {
#[test]
fn comments() {
let (func, Details { comments, .. }) = Parser::new("; before
function %comment() { ; decl
function %comment() native { ; decl
ss10 = outgoing_arg 13 ; stackslot.
; Still stackslot.
jt10 = jump_table ebb0
@@ -1924,7 +1944,7 @@ mod tests {
test verify
set enable_float=false
; still preamble
function %comment() {}")
function %comment() native {}")
.unwrap();
assert_eq!(tf.commands.len(), 2);
assert_eq!(tf.commands[0].command, "cfg");
@@ -1947,17 +1967,17 @@ mod tests {
#[cfg(build_riscv)]
fn isa_spec() {
assert!(parse_test("isa
function %foo() {}")
function %foo() native {}")
.is_err());
assert!(parse_test("isa riscv
set enable_float=false
function %foo() {}")
function %foo() native {}")
.is_err());
match parse_test("set enable_float=false
isa riscv
function %foo() {}")
function %foo() native {}")
.unwrap()
.isa_spec {
IsaSpec::None(_) => panic!("Expected some ISA"),
@@ -1971,7 +1991,7 @@ mod tests {
#[test]
fn binary_function_name() {
// Valid characters in the name.
let func = Parser::new("function #1234567890AbCdEf() {
let func = Parser::new("function #1234567890AbCdEf() native {
ebb0:
trap
}")
@@ -1981,21 +2001,21 @@ mod tests {
assert_eq!(func.name.to_string(), "#1234567890abcdef");
// Invalid characters in the name.
let mut parser = Parser::new("function #12ww() {
let mut parser = Parser::new("function #12ww() native {
ebb0:
trap
}");
assert!(parser.parse_function(None).is_err());
// The length of binary function name should be multiple of two.
let mut parser = Parser::new("function #1() {
let mut parser = Parser::new("function #1() native {
ebb0:
trap
}");
assert!(parser.parse_function(None).is_err());
// Empty binary function name should be valid.
let func = Parser::new("function #() {
let func = Parser::new("function #() native {
ebb0:
trap
}")