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: unchecked math operations in SSA #7011

Merged
merged 28 commits into from
Jan 10, 2025
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
6331a91
Add some unchecked math operations
asterite Jan 9, 2025
3bb465a
Use unchecked add in `make_offset`
asterite Jan 9, 2025
41ee955
Use correct names when printing
asterite Jan 9, 2025
63af351
Parse unchecked ops
asterite Jan 9, 2025
a308767
Induction variable now uses unchecked add
asterite Jan 9, 2025
199a980
A few more cases where we need to check for unchecked ops
asterite Jan 9, 2025
f279e3d
A few more
asterite Jan 9, 2025
a2beb78
Use a boolean instead of another variant
asterite Jan 9, 2025
84de854
increment and decrement slice length
asterite Jan 9, 2025
20b323e
Merge branch 'master' into ab/unchecked-math
TomAFrench Jan 10, 2025
d230098
Merge branch 'master' into ab/unchecked-math
TomAFrench Jan 10, 2025
7dff466
Handle some TODOs
asterite Jan 10, 2025
626f0a2
Merge branch 'ab/unchecked-math' of github.com:noir-lang/noir into ab…
asterite Jan 10, 2025
dfad378
chore: address some todos
TomAFrench Jan 10, 2025
7840ced
Handle more TODOs
asterite Jan 10, 2025
c10520c
Merge branch 'ab/unchecked-math' of github.com:noir-lang/noir into ab…
asterite Jan 10, 2025
0df89c0
Handle one more TODO
asterite Jan 10, 2025
6f9d1c7
Fix tests
asterite Jan 10, 2025
f34fb51
Handle the final TODO
asterite Jan 10, 2025
e0ff78f
Don't emit unchecked operations for Fields, or when multiplying bools
asterite Jan 10, 2025
bacccc2
Add missing cast in remove_bit_shifts
asterite Jan 10, 2025
83f1fd8
Extract `self.check_binary_instruction`
asterite Jan 10, 2025
820c16c
Check binary instruction before simplification
asterite Jan 10, 2025
4683b0d
clippy
asterite Jan 10, 2025
cf1a9e7
Do cast in both cases
asterite Jan 10, 2025
ef30d7c
Only check and simplify binary instructions in `Binary::simplify`
asterite Jan 10, 2025
63cfd12
Fix comptime to_le_bits returning `[u8; N]` instead of `[u1; N]`
asterite Jan 10, 2025
9b42fd8
Allow casting u1 in comptime
asterite Jan 10, 2025
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
6 changes: 3 additions & 3 deletions compiler/noirc_evaluator/src/acir/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1949,9 +1949,9 @@ impl<'a> Context<'a> {
let bit_count = binary_type.bit_size::<FieldElement>();
let num_type = binary_type.to_numeric_type();
let result = match binary.operator {
BinaryOp::Add => self.acir_context.add_var(lhs, rhs),
BinaryOp::Sub => self.acir_context.sub_var(lhs, rhs),
BinaryOp::Mul => self.acir_context.mul_var(lhs, rhs),
BinaryOp::Add | BinaryOp::UncheckedAdd => self.acir_context.add_var(lhs, rhs),
BinaryOp::Sub | BinaryOp::UncheckedSub => self.acir_context.sub_var(lhs, rhs),
BinaryOp::Mul | BinaryOp::UncheckedMul => self.acir_context.mul_var(lhs, rhs),
BinaryOp::Div => self.acir_context.div_var(
lhs,
rhs,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1318,9 +1318,9 @@ impl<'block> BrilligBlock<'block> {
BrilligBinaryOp::Modulo
}
}
BinaryOp::Add => BrilligBinaryOp::Add,
BinaryOp::Sub => BrilligBinaryOp::Sub,
BinaryOp::Mul => BrilligBinaryOp::Mul,
BinaryOp::Add | BinaryOp::UncheckedAdd => BrilligBinaryOp::Add,
BinaryOp::Sub | BinaryOp::UncheckedSub => BrilligBinaryOp::Sub,
BinaryOp::Mul | BinaryOp::UncheckedMul => BrilligBinaryOp::Mul,
BinaryOp::Eq => BrilligBinaryOp::Equals,
BinaryOp::Lt => {
if is_signed {
Expand Down
10 changes: 8 additions & 2 deletions compiler/noirc_evaluator/src/ssa/ir/instruction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -407,7 +407,7 @@
// These can fail.
Constrain(..) | RangeCheck { .. } => true,

// This should never be side-effectful

Check warning on line 410 in compiler/noirc_evaluator/src/ssa/ir/instruction.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (effectful)
MakeArray { .. } | Noop => false,

// Some binary math can overflow or underflow
Expand All @@ -415,7 +415,10 @@
BinaryOp::Add | BinaryOp::Sub | BinaryOp::Mul | BinaryOp::Div | BinaryOp::Mod => {
true
}
BinaryOp::Eq
BinaryOp::UncheckedAdd
| BinaryOp::UncheckedSub
| BinaryOp::UncheckedMul
| BinaryOp::Eq
| BinaryOp::Lt
| BinaryOp::And
| BinaryOp::Or
Expand Down Expand Up @@ -575,7 +578,10 @@
// for unsigned types (here we assume the type of binary.lhs is the same)
dfg.type_of_value(binary.rhs).is_unsigned()
}
BinaryOp::Eq
BinaryOp::UncheckedAdd
| BinaryOp::UncheckedSub
| BinaryOp::UncheckedMul
| BinaryOp::Eq
| BinaryOp::Lt
| BinaryOp::And
| BinaryOp::Or
Expand Down
33 changes: 21 additions & 12 deletions compiler/noirc_evaluator/src/ssa/ir/instruction/binary.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,16 @@
pub(crate) enum BinaryOp {
/// Addition of lhs + rhs.
Add,
/// Addition of lhs + rhs without an overflow check.
UncheckedAdd,
/// Subtraction of lhs - rhs.
Sub,
/// Subtraction of lhs - rhs without an overflow check.
UncheckedSub,
/// Multiplication of lhs * rhs.
Mul,
/// Multiplication of lhs * rhs without an overflow check.
UncheckedMul,
asterite marked this conversation as resolved.
Show resolved Hide resolved
/// Division of lhs / rhs.
Div,
TomAFrench marked this conversation as resolved.
Show resolved Hide resolved
/// Modulus of lhs % rhs.
Expand All @@ -39,9 +45,9 @@
Or,
/// Bitwise xor (^)
Xor,
/// Bitshift left (<<)

Check warning on line 48 in compiler/noirc_evaluator/src/ssa/ir/instruction/binary.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (Bitshift)
Shl,
/// Bitshift right (>>)

Check warning on line 50 in compiler/noirc_evaluator/src/ssa/ir/instruction/binary.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (Bitshift)
Shr,
}

Expand All @@ -49,8 +55,11 @@
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
BinaryOp::Add => write!(f, "add"),
BinaryOp::UncheckedAdd => write!(f, "unchecked_add"),
BinaryOp::Sub => write!(f, "sub"),
BinaryOp::UncheckedSub => write!(f, "unchecked_sub"),
BinaryOp::Mul => write!(f, "mul"),
BinaryOp::UncheckedMul => write!(f, "unchecked_mul"),
BinaryOp::Div => write!(f, "div"),
BinaryOp::Eq => write!(f, "eq"),
BinaryOp::Mod => write!(f, "mod"),
Expand Down Expand Up @@ -107,20 +116,20 @@
let rhs_is_one = rhs.map_or(false, |rhs| rhs.is_one());

match self.operator {
BinaryOp::Add => {
BinaryOp::Add | BinaryOp::UncheckedAdd => {
if lhs_is_zero {
return SimplifyResult::SimplifiedTo(self.rhs);
}
if rhs_is_zero {
return SimplifyResult::SimplifiedTo(self.lhs);
}
}
BinaryOp::Sub => {
BinaryOp::Sub | BinaryOp::UncheckedSub => {
if rhs_is_zero {
return SimplifyResult::SimplifiedTo(self.lhs);
}
}
BinaryOp::Mul => {
BinaryOp::Mul | BinaryOp::UncheckedMul => {
if lhs_is_one {
return SimplifyResult::SimplifiedTo(self.rhs);
}
Expand Down Expand Up @@ -470,9 +479,9 @@
impl BinaryOp {
fn get_field_function(self) -> Option<fn(FieldElement, FieldElement) -> FieldElement> {
match self {
BinaryOp::Add => Some(std::ops::Add::add),
BinaryOp::Sub => Some(std::ops::Sub::sub),
BinaryOp::Mul => Some(std::ops::Mul::mul),
BinaryOp::Add | BinaryOp::UncheckedAdd => Some(std::ops::Add::add),
BinaryOp::Sub | BinaryOp::UncheckedSub => Some(std::ops::Sub::sub),
BinaryOp::Mul | BinaryOp::UncheckedMul => Some(std::ops::Mul::mul),
BinaryOp::Div => Some(std::ops::Div::div),
BinaryOp::Eq => Some(|x, y| (x == y).into()),
BinaryOp::Lt => Some(|x, y| (x < y).into()),
Expand All @@ -488,9 +497,9 @@

fn get_u128_function(self) -> fn(u128, u128) -> Option<u128> {
match self {
BinaryOp::Add => u128::checked_add,
BinaryOp::Sub => u128::checked_sub,
BinaryOp::Mul => u128::checked_mul,
BinaryOp::Add | BinaryOp::UncheckedAdd => u128::checked_add,
BinaryOp::Sub | BinaryOp::UncheckedSub => u128::checked_sub,
BinaryOp::Mul | BinaryOp::UncheckedMul => u128::checked_mul,
BinaryOp::Div => u128::checked_div,
BinaryOp::Mod => u128::checked_rem,
BinaryOp::And => |x, y| Some(x & y),
Expand All @@ -505,9 +514,9 @@

fn get_i128_function(self) -> fn(i128, i128) -> Option<i128> {
match self {
BinaryOp::Add => i128::checked_add,
BinaryOp::Sub => i128::checked_sub,
BinaryOp::Mul => i128::checked_mul,
BinaryOp::Add | BinaryOp::UncheckedAdd => i128::checked_add,
BinaryOp::Sub | BinaryOp::UncheckedSub => i128::checked_sub,
BinaryOp::Mul | BinaryOp::UncheckedMul => i128::checked_mul,
BinaryOp::Div => i128::checked_div,
BinaryOp::Mod => i128::checked_rem,
BinaryOp::And => |x, y| Some(x & y),
Expand Down
5 changes: 4 additions & 1 deletion compiler/noirc_evaluator/src/ssa/opt/loop_invariant.rs
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,10 @@ impl<'f> LoopInvariantContext<'f> {
}
}
Instruction::Binary(binary) => {
if !matches!(binary.operator, BinaryOp::Add | BinaryOp::Mul) {
if !matches!(
binary.operator,
BinaryOp::Add | BinaryOp::UncheckedAdd | BinaryOp::Mul | BinaryOp::UncheckedMul
) {
return false;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -126,9 +126,12 @@ impl Context {
use Instruction::*;
match instruction {
Binary(binary) => match binary.operator {
BinaryOp::Add | BinaryOp::Sub | BinaryOp::Mul => {
dfg.type_of_value(binary.lhs).is_unsigned()
}
BinaryOp::Add
| BinaryOp::UncheckedAdd
| BinaryOp::Sub
| BinaryOp::UncheckedSub
| BinaryOp::Mul
| BinaryOp::UncheckedMul => dfg.type_of_value(binary.lhs).is_unsigned(),
BinaryOp::Div | BinaryOp::Mod => {
if let Some(rhs) = dfg.get_numeric_constant(binary.rhs) {
rhs == FieldElement::zero()
Expand Down
15 changes: 11 additions & 4 deletions compiler/noirc_evaluator/src/ssa/opt/unrolling.rs
Original file line number Diff line number Diff line change
Expand Up @@ -619,10 +619,17 @@
let header = &function.dfg[self.header];
let induction_var = header.parameters()[0];

back.instructions().iter().filter(|instruction| {
let instruction = &function.dfg[**instruction];
matches!(instruction, Instruction::Binary(Binary { lhs, operator: BinaryOp::Add, rhs: _ }) if *lhs == induction_var)
}).count()
back.instructions()
.iter()
.filter(|instruction| {
let instruction = &function.dfg[**instruction];
matches!(instruction,
Instruction::Binary(Binary { lhs, operator: BinaryOp::Add, rhs: _ }) |
Instruction::Binary(Binary { lhs, operator: BinaryOp::UncheckedAdd, rhs: _ })
if *lhs == induction_var
)
})
.count()
}

/// Decide if this loop is small enough that it can be inlined in a way that the number
Expand Down Expand Up @@ -1010,7 +1017,7 @@
use super::{is_new_size_ok, BoilerplateStats, Loops};

/// Tries to unroll all loops in each SSA function once, calling the `Function` directly,
/// bypassing the iterative loop done by the SSA which does further optimisations.

Check warning on line 1020 in compiler/noirc_evaluator/src/ssa/opt/unrolling.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (optimisations)
///
/// If any loop cannot be unrolled, it is left as-is or in a partially unrolled state.
fn try_unroll_loops(mut ssa: Ssa) -> (Ssa, Vec<RuntimeError>) {
Expand Down
3 changes: 3 additions & 0 deletions compiler/noirc_evaluator/src/ssa/parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,9 @@ impl<'a> Parser<'a> {
Token::Keyword(Keyword::Xor) => BinaryOp::Xor,
Token::Keyword(Keyword::Shl) => BinaryOp::Shl,
Token::Keyword(Keyword::Shr) => BinaryOp::Shr,
Token::Keyword(Keyword::UncheckedAdd) => BinaryOp::UncheckedAdd,
Token::Keyword(Keyword::UncheckedSub) => BinaryOp::UncheckedSub,
Token::Keyword(Keyword::UncheckedMul) => BinaryOp::UncheckedMul,
_ => return Ok(None),
};

Expand Down
18 changes: 17 additions & 1 deletion compiler/noirc_evaluator/src/ssa/parser/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -326,7 +326,23 @@ fn test_array_get_set_bug() {

#[test]
fn test_binary() {
for op in ["add", "sub", "mul", "div", "eq", "mod", "lt", "and", "or", "xor", "shl", "shr"] {
for op in [
"add",
"sub",
"mul",
"div",
"eq",
"mod",
"lt",
"and",
"or",
"xor",
"shl",
"shr",
"unchecked_add",
"unchecked_sub",
"unchecked_mul",
] {
let src = format!(
"
acir(inline) fn main f0 {{
Expand Down
9 changes: 9 additions & 0 deletions compiler/noirc_evaluator/src/ssa/parser/token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,9 @@ pub(crate) enum Keyword {
Then,
To,
Truncate,
UncheckedAdd,
UncheckedSub,
UncheckedMul,
Value,
Xor,
}
Expand Down Expand Up @@ -217,6 +220,9 @@ impl Keyword {
"then" => Keyword::Then,
"to" => Keyword::To,
"truncate" => Keyword::Truncate,
"unchecked_add" => Keyword::UncheckedAdd,
"unchecked_sub" => Keyword::UncheckedSub,
"unchecked_mul" => Keyword::UncheckedMul,
"value" => Keyword::Value,
"xor" => Keyword::Xor,
_ => return None,
Expand Down Expand Up @@ -278,6 +284,9 @@ impl Display for Keyword {
Keyword::Then => write!(f, "then"),
Keyword::To => write!(f, "to"),
Keyword::Truncate => write!(f, "truncate"),
Keyword::UncheckedAdd => write!(f, "unchecked_add"),
Keyword::UncheckedSub => write!(f, "unchecked_sub"),
Keyword::UncheckedMul => write!(f, "unchecked_mul"),
Keyword::Value => write!(f, "value"),
Keyword::Xor => write!(f, "xor"),
}
Expand Down
2 changes: 1 addition & 1 deletion compiler/noirc_evaluator/src/ssa/ssa_gen/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -610,7 +610,7 @@ impl<'a> FunctionContext<'a> {
if offset != 0 {
let typ = self.builder.type_of_value(address).unwrap_numeric();
let offset = self.builder.numeric_constant(offset, typ);
address = self.builder.insert_binary(address, BinaryOp::Add, offset);
address = self.builder.insert_binary(address, BinaryOp::UncheckedAdd, offset);
}
address
}
Expand Down
Loading