Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: optimize logic gate ACIR-gen #3897

Merged
merged 1 commit into from
Dec 21, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions compiler/noirc_evaluator/src/ssa/acir_gen/acir_ir/acir_variable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -368,6 +368,21 @@ impl AcirContext {
rhs: AcirVar,
typ: AcirType,
) -> Result<AcirVar, RuntimeError> {
let lhs_expr = self.var_to_expression(lhs)?;
let rhs_expr = self.var_to_expression(rhs)?;

if lhs_expr == rhs_expr {
// x ^ x == 0
let zero = self.add_constant(FieldElement::zero());
return Ok(zero);
} else if lhs_expr.is_zero() {
// 0 ^ x == x
return Ok(rhs);
} else if rhs_expr.is_zero() {
// x ^ 0 == x
return Ok(lhs);
}

let inputs = vec![AcirValue::Var(lhs, typ.clone()), AcirValue::Var(rhs, typ)];
let outputs = self.black_box_function(BlackBoxFunc::XOR, inputs, 1)?;
Ok(outputs[0])
Expand All @@ -380,6 +395,18 @@ impl AcirContext {
rhs: AcirVar,
typ: AcirType,
) -> Result<AcirVar, RuntimeError> {
let lhs_expr = self.var_to_expression(lhs)?;
let rhs_expr = self.var_to_expression(rhs)?;

if lhs_expr == rhs_expr {
// x & x == x
return Ok(lhs);
} else if lhs_expr.is_zero() || rhs_expr.is_zero() {
// x & 0 == 0 and 0 & x == 0
let zero = self.add_constant(FieldElement::zero());
return Ok(zero);
}

let bit_size = typ.bit_size();
if bit_size == 1 {
// Operands are booleans.
Expand All @@ -398,6 +425,16 @@ impl AcirContext {
rhs: AcirVar,
typ: AcirType,
) -> Result<AcirVar, RuntimeError> {
let lhs_expr = self.var_to_expression(lhs)?;
let rhs_expr = self.var_to_expression(rhs)?;
if lhs_expr.is_zero() {
// 0 | x == x
return Ok(rhs);
} else if rhs_expr.is_zero() {
// x | 0 == x
return Ok(lhs);
}

let bit_size = typ.bit_size();
if bit_size == 1 {
// Operands are booleans
Expand Down
Loading