Skip to content

Commit

Permalink
chore: Add short circuit in ssa-gen for known if conditions (#7007)
Browse files Browse the repository at this point in the history
  • Loading branch information
jfecher authored Jan 9, 2025
1 parent fc61c21 commit e0d6840
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions compiler/noirc_evaluator/src/ssa/ssa_gen/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ pub(crate) mod context;
mod program;
mod value;

use acvm::AcirField;
use noirc_frontend::token::FmtStrFragment;
pub(crate) use program::Ssa;

Expand Down Expand Up @@ -595,6 +596,9 @@ impl<'a> FunctionContext<'a> {
/// ```
fn codegen_if(&mut self, if_expr: &ast::If) -> Result<Values, RuntimeError> {
let condition = self.codegen_non_tuple_expression(&if_expr.condition)?;
if let Some(result) = self.try_codegen_constant_if(condition, if_expr) {
return result;
}

let then_block = self.builder.insert_block();
let else_block = self.builder.insert_block();
Expand Down Expand Up @@ -633,6 +637,25 @@ impl<'a> FunctionContext<'a> {
Ok(result)
}

/// If the condition is known, skip codegen for the then/else branch and only compile the
/// relevant branch.
fn try_codegen_constant_if(
&mut self,
condition: ValueId,
if_expr: &ast::If,
) -> Option<Result<Values, RuntimeError>> {
let condition = self.builder.current_function.dfg.get_numeric_constant(condition)?;

Some(if condition.is_zero() {
match if_expr.alternative.as_ref() {
Some(alternative) => self.codegen_expression(alternative),
None => Ok(Self::unit_value()),
}
} else {
self.codegen_expression(&if_expr.consequence)
})
}

fn codegen_tuple(&mut self, tuple: &[Expression]) -> Result<Values, RuntimeError> {
Ok(Tree::Branch(try_vecmap(tuple, |expr| self.codegen_expression(expr))?))
}
Expand Down

0 comments on commit e0d6840

Please sign in to comment.