From 141ecddf79b27244a52097577395c7b41cd4d331 Mon Sep 17 00:00:00 2001 From: Tom French <15848336+TomAFrench@users.noreply.github.com> Date: Fri, 12 Jul 2024 16:59:45 +0100 Subject: [PATCH] feat: skip reading values immediately after it being written into an array (#5449) # Description ## Problem\* Resolves ## Summary\* I noticed a couple of cases where we were writing into an array and then immediately reading the same index from it. This seems like something that we should be able to unwind. Draft as I want to do more thinking on how `EnableSideEffects` can interact with this. ## Additional Context ## Documentation\* Check one: - [x] No documentation needed. - [ ] Documentation included in this PR. - [ ] **[For Experimental Features]** Documentation to be submitted in a separate PR. # PR Checklist\* - [x] I have tested the changes locally. - [x] I have formatted the changes with [Prettier](https://prettier.io/) and/or `cargo fmt` on default settings. --- compiler/noirc_evaluator/src/ssa/ir/instruction.rs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/compiler/noirc_evaluator/src/ssa/ir/instruction.rs b/compiler/noirc_evaluator/src/ssa/ir/instruction.rs index 8cbae732ef9..9146fe94832 100644 --- a/compiler/noirc_evaluator/src/ssa/ir/instruction.rs +++ b/compiler/noirc_evaluator/src/ssa/ir/instruction.rs @@ -602,6 +602,18 @@ impl Instruction { } } Instruction::ArrayGet { array, index } => { + if let Value::Instruction { instruction, .. } = &dfg[*array] { + if let Instruction::ArraySet { index: write_index, value, .. } = + dfg[*instruction] + { + // If we're reading from an index of the array which we just wrote to, we can return + // the value which we wrote without performing the read. + if dfg.resolve(write_index) == dfg.resolve(*index) { + return SimplifiedTo(value); + } + } + } + let array = dfg.get_array_constant(*array); let index = dfg.get_numeric_constant(*index); if let (Some((array, _)), Some(index)) = (array, index) {