use fireline_grammar::{OpTag, PatternNode};
use fuel_cpu_backend::epilogue::{EpiBinary, EpiCompare, EpiExpr, EpiUnary};
use fuel_ir::{Error, Result};
fn decline(what: impl std::fmt::Display) -> Error {
Error::Msg(format!("conv2d_epilogue: {what}")).bt()
}
pub(crate) fn compile_epilogue(
recipe: &PatternNode,
scalars: &[f64],
extras: usize,
) -> Result<EpiExpr> {
let mut slots = scalars.iter().copied();
let expr = compile(recipe, &mut slots, extras)?;
if slots.next().is_some() {
return Err(decline("more scalars than the recipe has slots"));
}
Ok(expr)
}
fn compile(
node: &PatternNode,
slots: &mut impl Iterator<Item = f64>,
extras: usize,
) -> Result<EpiExpr> {
let (op, operands) = match node {
PatternNode::Bind { index: 0 } => return Ok(EpiExpr::ConvOut),
PatternNode::Bind { index } if usize::from(*index) <= extras => {
return Ok(EpiExpr::Extra(usize::from(*index) - 1));
}
PatternNode::Op { op, operands, .. } => (*op, operands),
other => return Err(decline(format!("unsupported recipe node {other:?}"))),
};
let mut slot = || {
slots
.next()
.ok_or_else(|| decline("a scalar slot is unfilled"))
};
let own = match op {
OpTag::AddScalar | OpTag::MulScalar => [slot()?, 0.0],
OpTag::Clamp => [slot()?, slot()?],
_ => [0.0, 0.0],
};
let arity = |n: usize| {
if operands.len() == n {
Ok(())
} else {
Err(decline(format!(
"{op:?} takes {n} operands, got {}",
operands.len()
)))
}
};
if op == OpTag::Where {
arity(3)?;
let PatternNode::Op {
op: cmp_tag,
operands: cmp_args,
..
} = &operands[0]
else {
return Err(decline(
"a select's condition must be a comparison in the region",
));
};
let cmp = match cmp_tag {
OpTag::Equal => EpiCompare::Eq,
OpTag::Ne => EpiCompare::Ne,
OpTag::Lt => EpiCompare::Lt,
OpTag::Le => EpiCompare::Le,
OpTag::Gt => EpiCompare::Gt,
OpTag::Ge => EpiCompare::Ge,
other => return Err(decline(format!("{other:?} is not a comparison"))),
};
if cmp_args.len() != 2 {
return Err(decline("a comparison takes 2 operands"));
}
return Ok(EpiExpr::Where {
cmp,
lhs: Box::new(compile(&cmp_args[0], slots, extras)?),
rhs: Box::new(compile(&cmp_args[1], slots, extras)?),
a: Box::new(compile(&operands[1], slots, extras)?),
b: Box::new(compile(&operands[2], slots, extras)?),
});
}
let binary = match op {
OpTag::Add => Some(EpiBinary::Add),
OpTag::Sub => Some(EpiBinary::Sub),
OpTag::Mul => Some(EpiBinary::Mul),
OpTag::Div => Some(EpiBinary::Div),
OpTag::Maximum => Some(EpiBinary::Maximum),
OpTag::Minimum => Some(EpiBinary::Minimum),
_ => None,
};
if let Some(op) = binary {
arity(2)?;
let lhs = compile(&operands[0], slots, extras)?;
let rhs = compile(&operands[1], slots, extras)?;
return Ok(EpiExpr::Binary(op, Box::new(lhs), Box::new(rhs)));
}
arity(1)?;
let x = Box::new(compile(&operands[0], slots, extras)?);
let unary = match op {
OpTag::AddScalar => {
return Ok(EpiExpr::Affine {
mul: 1.0,
add: own[0],
x,
});
}
OpTag::MulScalar => {
return Ok(EpiExpr::Affine {
mul: own[0],
add: 0.0,
x,
});
}
OpTag::Clamp => {
return Ok(EpiExpr::Clamp {
min: own[0],
max: own[1],
x,
});
}
OpTag::Neg => EpiUnary::Neg,
OpTag::Abs => EpiUnary::Abs,
OpTag::Sqr => EpiUnary::Sqr,
OpTag::Sqrt => EpiUnary::Sqrt,
OpTag::Rsqrt => EpiUnary::Rsqrt,
OpTag::Recip => EpiUnary::Recip,
OpTag::Exp => EpiUnary::Exp,
OpTag::Log => EpiUnary::Log,
OpTag::Sin => EpiUnary::Sin,
OpTag::Cos => EpiUnary::Cos,
OpTag::Tanh => EpiUnary::Tanh,
OpTag::Sigmoid => EpiUnary::Sigmoid,
OpTag::Silu => EpiUnary::Silu,
OpTag::GeluTanh => EpiUnary::GeluTanh,
OpTag::Gelu => EpiUnary::GeluErf,
OpTag::Relu => EpiUnary::Relu,
OpTag::Erf => EpiUnary::Erf,
OpTag::Step => EpiUnary::Step,
OpTag::Floor => EpiUnary::Floor,
OpTag::Ceil => EpiUnary::Ceil,
OpTag::Round => EpiUnary::Round,
OpTag::Sign => EpiUnary::Sign,
other => return Err(decline(format!("{other:?} is not an epilogue op"))),
};
Ok(EpiExpr::Unary(unary, x))
}