Skip to content

Commit

Permalink
chore: optimize mul for constant expressions (#932)
Browse files Browse the repository at this point in the history
* chore: optimize `mul` for constant expressions

* chore: optimize another instance

* chore: add early returns to `add` for const inputs
  • Loading branch information
TomAFrench authored Mar 2, 2023
1 parent ba947a7 commit cfa9701
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 6 deletions.
14 changes: 9 additions & 5 deletions crates/noirc_evaluator/src/ssa/acir_gen/constraints.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,11 +58,10 @@ pub(crate) fn mul_with_witness(

//a*b
pub(crate) fn mul(a: &Expression, b: &Expression) -> Expression {
let zero = Expression::zero();
if a.is_const() {
return add(&zero, a.q_c, b);
return b * &a.q_c;
} else if b.is_const() {
return add(&zero, b.q_c, a);
return a * &b.q_c;
} else if !(a.is_linear() && b.is_linear()) {
unreachable!("Can only multiply linear terms");
}
Expand Down Expand Up @@ -130,7 +129,13 @@ pub(crate) fn subtract(a: &Expression, k: FieldElement, b: &Expression) -> Expre
// TODO also check why we are doing all of this complicated logic with i1 and i2
// TODO in either case, we can put this in ACIR, if its useful
pub(crate) fn add(a: &Expression, k: FieldElement, b: &Expression) -> Expression {
let mut output = Expression::default();
if a.is_const() {
return (b * &k) + &a.q_c;
} else if b.is_const() {
return a.clone() + &(k * b.q_c);
}

let mut output = Expression::from_field(a.q_c + k * b.q_c);

//linear combinations
let mut i1 = 0; //a
Expand Down Expand Up @@ -211,7 +216,6 @@ pub(crate) fn add(a: &Expression, k: FieldElement, b: &Expression) -> Expression
i2 += 1;
}

output.q_c = a.q_c + k * b.q_c;
output
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ pub(crate) fn evaluate(
if r_value.is_zero() {
panic!("Panic - division by zero");
} else {
constraints::add(&Expression::zero(), r_value.inverse(), l_c.expression()).into()
(l_c.expression() * &r_value.inverse()).into()
}
} else {
//TODO avoid creating witnesses here.
Expand Down

0 comments on commit cfa9701

Please sign in to comment.