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

fix(ssa): Change array_set to not mutate slices coming from function inputs #6463

Merged
merged 3 commits into from
Nov 8, 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
42 changes: 30 additions & 12 deletions compiler/noirc_evaluator/src/ssa/opt/array_set.rs
Original file line number Diff line number Diff line change
@@ -34,8 +34,11 @@
assert_eq!(reachable_blocks.len(), 1, "Expected there to be 1 block remaining in Acir function for array_set optimization");
}

let mut context =
Context::new(&self.dfg, matches!(self.runtime(), RuntimeType::Brillig(_)));
let mut context = Context::new(
&self.dfg,
self.parameters(),
matches!(self.runtime(), RuntimeType::Brillig(_)),
);

for block in reachable_blocks.iter() {
context.analyze_last_uses(*block);
@@ -50,19 +53,25 @@

struct Context<'f> {
dfg: &'f DataFlowGraph,
function_parameters: &'f [ValueId],
is_brillig_runtime: bool,
array_to_last_use: HashMap<ValueId, InstructionId>,
instructions_that_can_be_made_mutable: HashSet<InstructionId>,
// Mapping of an array that comes from a load and whether the address
// it was loaded from is a reference parameter.
// it was loaded from is a reference parameter passed to the block.
arrays_from_load: HashMap<ValueId, bool>,
inner_nested_arrays: HashMap<ValueId, InstructionId>,
}

impl<'f> Context<'f> {
fn new(dfg: &'f DataFlowGraph, is_brillig_runtime: bool) -> Self {
fn new(
dfg: &'f DataFlowGraph,
function_parameters: &'f [ValueId],
is_brillig_runtime: bool,
) -> Self {
Context {
dfg,
function_parameters,
is_brillig_runtime,
array_to_last_use: HashMap::default(),
instructions_that_can_be_made_mutable: HashSet::default(),
@@ -109,21 +118,30 @@
// If we are in a return block we are not concerned about the array potentially being mutated again.
let is_return_block =
matches!(terminator, TerminatorInstruction::Return { .. });

// We also want to check that the array is not part of the terminator arguments, as this means it is used again.
let mut array_in_terminator = false;
let mut is_array_in_terminator = false;
terminator.for_each_value(|value| {
// The terminator can contain original IDs, while the SSA has replaced the array value IDs; we need to resolve to compare.
if !array_in_terminator && self.dfg.resolve(value) == array {
array_in_terminator = true;
if !is_array_in_terminator && self.dfg.resolve(value) == array {
is_array_in_terminator = true;
}
});
if let Some(is_from_param) = self.arrays_from_load.get(&array) {

// We cannot safely mutate slices that are inputs to the function, as they might be shared with the caller.
// NB checking the block parameters is not enough, as we might have jumped into a parameterless blocks inside the function.

Check warning on line 132 in compiler/noirc_evaluator/src/ssa/opt/array_set.rs

GitHub Actions / Code

Unknown word (parameterless)
let is_function_param = self.function_parameters.contains(&array);

let can_mutate = if let Some(is_from_param) = self.arrays_from_load.get(&array)
{
// If the array was loaded from a reference parameter, we cannot
// safely mark that array mutable as it may be shared by another value.
if !is_from_param && is_return_block {
self.instructions_that_can_be_made_mutable.insert(*instruction_id);
}
} else if !array_in_terminator {
!is_from_param && is_return_block
} else {
!is_array_in_terminator && !is_function_param
};

if can_mutate {
self.instructions_that_can_be_made_mutable.insert(*instruction_id);
}
}

Unchanged files with check annotations Beta

Self::Public => write!(f, "pub"),
Self::Private => write!(f, "priv"),
Self::CallData(id) => write!(f, "calldata{id}"),
Self::ReturnData => write!(f, "returndata"),

Check warning on line 537 in compiler/noirc_frontend/src/ast/mod.rs

GitHub Actions / Code

Unknown word (returndata)
}
}
}
// TODO(https://github.com/noir-lang/noir/issues/6238):
// support non-u32 generics here
if !kind.unifies(&Kind::u32()) {
let error = TypeCheckError::EvaluatedGlobalIsntU32 {

Check warning on line 423 in compiler/noirc_frontend/src/elaborator/types.rs

GitHub Actions / Code

Unknown word (Isnt)
expected_kind: Kind::u32().to_string(),
expr_kind: kind.to_string(),
expr_span: path.span(),
} else {
let to = *to.clone();
let from = *from.clone();
Err(TypeCheckError::TypeCanonicalizationMismatch {

Check warning on line 2068 in compiler/noirc_frontend/src/hir_def/types.rs

GitHub Actions / Code

Unknown word (Canonicalization)
to,
from,
to_value,
}
let recur_on_binding = |id, replacement: &Type| {
// Prevent recuring forever if there's a `T := T` binding

Check warning on line 2246 in compiler/noirc_frontend/src/hir_def/types.rs

GitHub Actions / Code

Unknown word (recuring)
if replacement.type_variable_id() == Some(id) {
replacement.clone()
} else {
Type::Tuple(fields)
}
Type::Forall(typevars, typ) => {
// Trying to substitute_helper a variable de, substitute_bound_typevarsfined within a nested Forall

Check warning on line 2331 in compiler/noirc_frontend/src/hir_def/types.rs

GitHub Actions / Code

Unknown word (typevarsfined)
// is usually impossible and indicative of an error in the type checker somewhere.
for var in typevars {
assert!(!type_bindings.contains_key(&var.id()));
/// Replace any `Type::NamedGeneric` in this type with a `Type::TypeVariable`
/// using to the same inner `TypeVariable`. This is used during monomorphization
/// to bind to named generics since they are unbindable during type checking.

Check warning on line 2503 in compiler/noirc_frontend/src/hir_def/types.rs

GitHub Actions / Code

Unknown word (unbindable)
pub fn replace_named_generics_with_type_variables(&mut self) {
match self {
Type::FieldElement
len.hash(state);
env.hash(state);
}
Type::Tuple(elems) => elems.hash(state),

Check warning on line 2964 in compiler/noirc_frontend/src/hir_def/types.rs

GitHub Actions / Code

Unknown word (elems)

Check warning on line 2964 in compiler/noirc_frontend/src/hir_def/types.rs

GitHub Actions / Code

Unknown word (elems)
Type::Struct(def, args) => {
def.hash(state);
args.hash(state);
// Special case: we consider unbound named generics and type variables to be equal to each
// other if their type variable ids match. This is important for some corner cases in
// monomorphization where we call `replace_named_generics_with_type_variables` but
// still want them to be equal for canonicalization checks in arithmetic generics.

Check warning on line 3067 in compiler/noirc_frontend/src/hir_def/types.rs

GitHub Actions / Code

Unknown word (canonicalization)
// Without this we'd fail the `serialize` test.
(
NamedGeneric(lhs_var, _) | TypeVariable(lhs_var),