Skip to content

Commit

Permalink
fix(ssa refactor): truncate when simplifying constant casts (#1714)
Browse files Browse the repository at this point in the history
* fix(ssa refactor): truncate when simplifying constant casts

* fix(ssa refactor): simplify cast Field -> unsigned
  • Loading branch information
joss-aztec authored Jun 15, 2023
1 parent 65b91f2 commit a2108d7
Showing 1 changed file with 22 additions and 1 deletion.
23 changes: 22 additions & 1 deletion crates/noirc_evaluator/src/ssa_refactor/ir/instruction.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
use acvm::{acir::BlackBoxFunc, FieldElement};
use iter_extended::vecmap;
use num_bigint::BigUint;

use crate::ssa_refactor::ir::types::NumericType;

use super::{
basic_block::BasicBlockId,
Expand Down Expand Up @@ -238,7 +241,25 @@ impl Instruction {
Instruction::Binary(binary) => binary.simplify(dfg),
Instruction::Cast(value, typ) => {
if let Some(constant) = dfg.get_numeric_constant(*value) {
SimplifiedTo(dfg.make_constant(constant, typ.clone()))
let src_typ = dfg.type_of_value(*value);
match (typ, src_typ) {
(
Type::Numeric(NumericType::Unsigned { bit_size }),
Type::Numeric(NumericType::Unsigned { .. }),
)
| (
Type::Numeric(NumericType::Unsigned { bit_size }),
Type::Numeric(NumericType::NativeField),
) => {
let integer_modulus = BigUint::from(2u128).pow(*bit_size);
let constant: BigUint = BigUint::from_bytes_be(&constant.to_be_bytes());
let truncated = constant % integer_modulus;
let truncated =
FieldElement::from_be_bytes_reduce(&truncated.to_bytes_be());
SimplifiedTo(dfg.make_constant(truncated, typ.clone()))
}
_ => None,
}
} else if let Some(value) = (*typ == dfg.type_of_value(*value)).then_some(*value) {
SimplifiedTo(value)
} else {
Expand Down

0 comments on commit a2108d7

Please sign in to comment.