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: replace modulo operations with truncations where possible #4329

Merged
merged 1 commit into from
Feb 12, 2024
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
17 changes: 17 additions & 0 deletions compiler/noirc_evaluator/src/ssa/ir/instruction/binary.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,9 @@
Or,
/// Bitwise xor (^)
Xor,
/// Bitshift left (<<)

Check warning on line 41 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 43 in compiler/noirc_evaluator/src/ssa/ir/instruction/binary.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (Bitshift)
Shr,
}

Expand Down Expand Up @@ -141,6 +141,23 @@
let zero = dfg.make_constant(FieldElement::zero(), operand_type);
return SimplifyResult::SimplifiedTo(zero);
}
if operand_type.is_unsigned() {
// lhs % 2**bit_size is equivalent to truncating `lhs` to `bit_size` bits.
// We then convert to a truncation for consistency, allowing more optimizations.
TomAFrench marked this conversation as resolved.
Show resolved Hide resolved
if let Some(modulus) = rhs {
let modulus = modulus.to_u128();
if modulus.is_power_of_two() {
let bit_size = modulus.ilog2();

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

View workflow job for this annotation

GitHub Actions / Code

Unknown word (ilog)
return SimplifyResult::SimplifiedToInstruction(
Instruction::Truncate {
value: self.lhs,
bit_size,
max_bit_size: operand_type.bit_size(),
},
);
}
}
}
}
BinaryOp::Eq => {
if dfg.resolve(self.lhs) == dfg.resolve(self.rhs) {
Expand Down Expand Up @@ -231,7 +248,7 @@
return SimplifyResult::SimplifiedTo(zero);
}

// `two_pow_rhs` is limited to be at most `2 ^ {operand_bitsize - 1}` so it fits in `operand_type`.

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

View workflow job for this annotation

GitHub Actions / Code

Unknown word (bitsize)
let two_pow_rhs = FieldElement::from(2u128).pow(&rhs_const);
let two_pow_rhs = dfg.make_constant(two_pow_rhs, operand_type);
return SimplifyResult::SimplifiedToInstruction(Instruction::binary(
Expand Down
Loading