-
Notifications
You must be signed in to change notification settings - Fork 204
/
mem2reg.rs
964 lines (825 loc) · 39.3 KB
/
mem2reg.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
//! The goal of the mem2reg SSA optimization pass is to replace any `Load` instructions to known
//! addresses with the value stored at that address, if it is also known. This pass will also remove
//! any `Store` instructions within a block that are no longer needed because no more loads occur in
//! between the Store in question and the next Store.
//!
//! The pass works as follows:
//! - Each block in each function is iterated in forward-order.
//! - The starting value of each reference in the block is the unification of the same references
//! at the end of each direct predecessor block to the current block.
//! - At each step, the value of each reference is either Known(ValueId) or Unknown.
//! - Two reference values unify to each other if they are exactly equal, or to Unknown otherwise.
//! - If a block has no predecessors, the starting value of each reference is Unknown.
//! - Throughout this pass, aliases of each reference are also tracked.
//! - References typically have 1 alias - themselves.
//! - A reference with multiple aliases means we will not be able to optimize out loads if the
//! reference is stored to. Note that this means we can still optimize out loads if these
//! aliased references are never stored to, or the store occurs after a load.
//! - A reference with 0 aliases means we were unable to find which reference this reference
//! refers to. If such a reference is stored to, we must conservatively invalidate every
//! reference in the current block.
//!
//! From there, to figure out the value of each reference at the end of block, iterate each instruction:
//! - On `Instruction::Allocate`:
//! - Register a new reference was made with itself as its only alias
//! - On `Instruction::Load { address }`:
//! - If `address` is known to only have a single alias (including itself) and if the value of
//! that alias is known, replace the value of the load with the known value.
//! - Furthermore, if the result of the load is a reference, mark the result as an alias
//! of the reference it dereferences to (if known).
//! - If which reference it dereferences to is not known, this load result has no aliases.
//! - On `Instruction::Store { address, value }`:
//! - If the address of the store is known:
//! - If the address has exactly 1 alias:
//! - Set the value of the address to `Known(value)`.
//! - If the address has more than 1 alias:
//! - Set the value of every possible alias to `Unknown`.
//! - If the address has 0 aliases:
//! - Conservatively mark every alias in the block to `Unknown`.
//! - If the address of the store is not known:
//! - Conservatively mark every alias in the block to `Unknown`.
//! - Additionally, if there were no Loads to any alias of the address between this Store and
//! the previous Store to the same address, the previous store can be removed.
//! - On `Instruction::Call { arguments }`:
//! - If any argument of the call is a reference, set the value of each alias of that
//! reference to `Unknown`
//! - Any builtin functions that may return aliases if their input also contains a
//! reference should be tracked. Examples: `slice_push_back`, `slice_insert`, `slice_remove`, etc.
//!
//! On a terminator instruction:
//! - If the terminator is a `Jmp`:
//! - For each reference argument of the jmp, mark the corresponding block parameter it is passed
//! to as an alias for the jmp argument.
//!
//! Finally, if this is the only block in the function, we can remove any Stores that were not
//! referenced by the terminator instruction.
//!
//! Repeating this algorithm for each block in the function in program order should result in
//! optimizing out most known loads. However, identifying all aliases correctly has been proven
//! undecidable in general (Landi, 1992). So this pass will not always optimize out all loads
//! that could theoretically be optimized out. This pass can be performed at any time in the
//! SSA optimization pipeline, although it will be more successful the simpler the program's CFG is.
//! This pass is currently performed several times to enable other passes - most notably being
//! performed before loop unrolling to try to allow for mutable variables used for loop indices.
mod alias_set;
mod block;
use std::collections::{BTreeMap, BTreeSet};
use fxhash::{FxHashMap as HashMap, FxHashSet as HashSet};
use crate::ssa::{
ir::{
basic_block::BasicBlockId,
cfg::ControlFlowGraph,
function::Function,
function_inserter::FunctionInserter,
instruction::{Instruction, InstructionId, TerminatorInstruction},
post_order::PostOrder,
types::Type,
value::ValueId,
},
ssa_gen::Ssa,
};
use self::alias_set::AliasSet;
use self::block::{Block, Expression};
impl Ssa {
/// Attempts to remove any load instructions that recover values that are already available in
/// scope, and attempts to remove stores that are subsequently redundant.
#[tracing::instrument(level = "trace", skip(self))]
pub(crate) fn mem2reg(mut self) -> Ssa {
for function in self.functions.values_mut() {
function.mem2reg();
}
self
}
}
impl Function {
pub(crate) fn mem2reg(&mut self) {
let mut context = PerFunctionContext::new(self);
context.mem2reg();
context.remove_instructions();
context.update_data_bus();
}
}
struct PerFunctionContext<'f> {
cfg: ControlFlowGraph,
post_order: PostOrder,
blocks: BTreeMap<BasicBlockId, Block>,
inserter: FunctionInserter<'f>,
/// Load and Store instructions that should be removed at the end of the pass.
///
/// We avoid removing individual instructions as we go since removing elements
/// from the middle of Vecs many times will be slower than a single call to `retain`.
instructions_to_remove: HashSet<InstructionId>,
/// Track a value's last load across all blocks.
/// If a value is not used in anymore loads we can remove the last store to that value.
last_loads: HashMap<ValueId, (InstructionId, BasicBlockId)>,
/// Track whether a reference was passed into another entry point
/// This is needed to determine whether we can remove a store.
calls_reference_input: HashSet<ValueId>,
/// Track whether a reference has been aliased, and store the respective
/// instruction that aliased that reference.
/// If that store has been set for removal, we can also remove this instruction.
aliased_references: HashMap<ValueId, HashSet<InstructionId>>,
}
impl<'f> PerFunctionContext<'f> {
fn new(function: &'f mut Function) -> Self {
let cfg = ControlFlowGraph::with_function(function);
let post_order = PostOrder::with_function(function);
PerFunctionContext {
cfg,
post_order,
inserter: FunctionInserter::new(function),
blocks: BTreeMap::new(),
instructions_to_remove: HashSet::default(),
last_loads: HashMap::default(),
calls_reference_input: HashSet::default(),
aliased_references: HashMap::default(),
}
}
/// Apply the mem2reg pass to the given function.
///
/// This function is expected to be the same one that the internal cfg, post_order, and
/// dom_tree were created from.
fn mem2reg(&mut self) {
// Iterate each block in reverse post order = forward order
let mut block_order = PostOrder::with_function(self.inserter.function).into_vec();
block_order.reverse();
for block in block_order {
let references = self.find_starting_references(block);
self.analyze_block(block, references);
}
let mut all_terminator_values = HashSet::default();
let mut per_func_block_params: HashSet<ValueId> = HashSet::default();
for (block_id, _) in self.blocks.iter() {
let block_params = self.inserter.function.dfg.block_parameters(*block_id);
per_func_block_params.extend(block_params.iter());
let terminator = self.inserter.function.dfg[*block_id].unwrap_terminator();
terminator.for_each_value(|value| {
self.recursively_add_values(value, &mut all_terminator_values);
});
}
// If we never load from an address within a function we can remove all stores to that address.
// This rule does not apply to reference parameters, which we must also check for before removing these stores.
for (_, block) in self.blocks.iter() {
for (store_address, store_instruction) in block.last_stores.iter() {
let store_alias_used = self.is_store_alias_used(
store_address,
block,
&all_terminator_values,
&per_func_block_params,
);
let is_dereference = block
.expressions
.get(store_address)
.map_or(false, |expression| matches!(expression, Expression::Dereference(_)));
if self.last_loads.get(store_address).is_none()
&& !store_alias_used
&& !is_dereference
{
self.instructions_to_remove.insert(*store_instruction);
}
}
}
}
// Extra checks on where a reference can be used aside a load instruction.
// Even if all loads to a reference have been removed we need to make sure that
// an allocation did not come from an entry point or was passed to an entry point.
fn is_store_alias_used(
&self,
store_address: &ValueId,
block: &Block,
all_terminator_values: &HashSet<ValueId>,
per_func_block_params: &HashSet<ValueId>,
) -> bool {
let func_params = self.inserter.function.parameters();
let reference_parameters = func_params
.iter()
.filter(|param| self.inserter.function.dfg.value_is_reference(**param))
.collect::<BTreeSet<_>>();
let mut store_alias_used = false;
if let Some(expression) = block.expressions.get(store_address) {
if let Some(aliases) = block.aliases.get(expression) {
let allocation_aliases_parameter =
aliases.any(|alias| reference_parameters.contains(&alias));
if allocation_aliases_parameter == Some(true) {
store_alias_used = true;
}
let allocation_aliases_parameter =
aliases.any(|alias| per_func_block_params.contains(&alias));
if allocation_aliases_parameter == Some(true) {
store_alias_used = true;
}
let allocation_aliases_parameter =
aliases.any(|alias| self.calls_reference_input.contains(&alias));
if allocation_aliases_parameter == Some(true) {
store_alias_used = true;
}
let allocation_aliases_parameter =
aliases.any(|alias| all_terminator_values.contains(&alias));
if allocation_aliases_parameter == Some(true) {
store_alias_used = true;
}
let allocation_aliases_parameter = aliases.any(|alias| {
if let Some(alias_instructions) = self.aliased_references.get(&alias) {
self.instructions_to_remove.is_disjoint(alias_instructions)
} else {
false
}
});
if allocation_aliases_parameter == Some(true) {
store_alias_used = true;
}
}
}
store_alias_used
}
fn recursively_add_values(&self, value: ValueId, set: &mut HashSet<ValueId>) {
set.insert(value);
if let Some((elements, _)) = self.inserter.function.dfg.get_array_constant(value) {
for array_element in elements {
self.recursively_add_values(array_element, set);
}
}
}
/// The value of each reference at the start of the given block is the unification
/// of the value of the same reference at the end of its predecessor blocks.
fn find_starting_references(&mut self, block: BasicBlockId) -> Block {
let mut predecessors = self.cfg.predecessors(block);
if let Some(first_predecessor) = predecessors.next() {
let mut first = self.blocks.get(&first_predecessor).cloned().unwrap_or_default();
first.last_stores.clear();
// Note that we have to start folding with the first block as the accumulator.
// If we started with an empty block, an empty block union'd with any other block
// is always also empty so we'd never be able to track any references across blocks.
predecessors.fold(first, |block, predecessor| {
let predecessor = self.blocks.entry(predecessor).or_default();
block.unify(predecessor)
})
} else {
Block::default()
}
}
/// Analyze a block with the given starting reference values.
///
/// This will remove any known loads in the block and track the value of references
/// as they are stored to. When this function is finished, the value of each reference
/// at the end of this block will be remembered in `self.blocks`.
fn analyze_block(&mut self, block: BasicBlockId, mut references: Block) {
let instructions = self.inserter.function.dfg[block].take_instructions();
for instruction in instructions {
self.analyze_instruction(block, &mut references, instruction);
}
self.handle_terminator(block, &mut references);
// If there's only 1 block in the function total, we can remove any remaining last stores
// as well. We can't do this if there are multiple blocks since subsequent blocks may
// reference these stores.
if self.post_order.as_slice().len() == 1 {
self.remove_stores_that_do_not_alias_parameters(&references);
}
self.blocks.insert(block, references);
}
/// Add all instructions in `last_stores` to `self.instructions_to_remove` which do not
/// possibly alias any parameters of the given function.
fn remove_stores_that_do_not_alias_parameters(&mut self, references: &Block) {
let parameters = self.inserter.function.parameters().iter();
let reference_parameters = parameters
.filter(|param| self.inserter.function.dfg.value_is_reference(**param))
.collect::<BTreeSet<_>>();
for (allocation, instruction) in &references.last_stores {
if let Some(expression) = references.expressions.get(allocation) {
if let Some(aliases) = references.aliases.get(expression) {
let allocation_aliases_parameter =
aliases.any(|alias| reference_parameters.contains(&alias));
// If `allocation_aliases_parameter` is known to be false
if allocation_aliases_parameter == Some(false) {
self.instructions_to_remove.insert(*instruction);
}
}
}
}
}
fn analyze_instruction(
&mut self,
block_id: BasicBlockId,
references: &mut Block,
mut instruction: InstructionId,
) {
// If the instruction was simplified and optimized out of the program we shouldn't analyze
// it. Analyzing it could make tracking aliases less accurate if it is e.g. an ArrayGet
// call that used to hold references but has since been optimized out to a known result.
if let Some(new_id) = self.inserter.push_instruction(instruction, block_id) {
instruction = new_id;
} else {
return;
}
match &self.inserter.function.dfg[instruction] {
Instruction::Load { address } => {
let address = self.inserter.function.dfg.resolve(*address);
let result = self.inserter.function.dfg.instruction_results(instruction)[0];
references.remember_dereference(self.inserter.function, address, result);
// If the load is known, replace it with the known value and remove the load
if let Some(value) = references.get_known_value(address) {
let result = self.inserter.function.dfg.instruction_results(instruction)[0];
self.inserter.map_value(result, value);
self.instructions_to_remove.insert(instruction);
} else {
references.mark_value_used(address, self.inserter.function);
self.last_loads.insert(address, (instruction, block_id));
}
}
Instruction::Store { address, value } => {
let address = self.inserter.function.dfg.resolve(*address);
let value = self.inserter.function.dfg.resolve(*value);
self.check_array_aliasing(references, value);
// If there was another store to this instruction without any (unremoved) loads or
// function calls in-between, we can remove the previous store.
if let Some(last_store) = references.last_stores.get(&address) {
self.instructions_to_remove.insert(*last_store);
}
if self.inserter.function.dfg.value_is_reference(value) {
if let Some(expression) = references.expressions.get(&value) {
if let Some(aliases) = references.aliases.get(expression) {
aliases.for_each(|alias| {
self.aliased_references
.entry(alias)
.or_default()
.insert(instruction);
});
}
}
}
references.set_known_value(address, value);
references.last_stores.insert(address, instruction);
}
Instruction::Allocate => {
// Register the new reference
let result = self.inserter.function.dfg.instruction_results(instruction)[0];
references.expressions.insert(result, Expression::Other(result));
references.aliases.insert(Expression::Other(result), AliasSet::known(result));
}
Instruction::ArrayGet { array, .. } => {
let result = self.inserter.function.dfg.instruction_results(instruction)[0];
references.mark_value_used(*array, self.inserter.function);
if self.inserter.function.dfg.value_is_reference(result) {
let array = self.inserter.function.dfg.resolve(*array);
let expression = Expression::ArrayElement(Box::new(Expression::Other(array)));
if let Some(aliases) = references.aliases.get_mut(&expression) {
aliases.insert(result);
}
}
}
Instruction::ArraySet { array, value, .. } => {
references.mark_value_used(*array, self.inserter.function);
let element_type = self.inserter.function.dfg.type_of_value(*value);
if Self::contains_references(&element_type) {
let result = self.inserter.function.dfg.instruction_results(instruction)[0];
let array = self.inserter.function.dfg.resolve(*array);
let expression = Expression::ArrayElement(Box::new(Expression::Other(array)));
let mut aliases = if let Some(aliases) = references.aliases.get_mut(&expression)
{
aliases.clone()
} else if let Some((elements, _)) =
self.inserter.function.dfg.get_array_constant(array)
{
let aliases = references.collect_all_aliases(elements);
self.set_aliases(references, array, aliases.clone());
aliases
} else {
AliasSet::unknown()
};
aliases.unify(&references.get_aliases_for_value(*value));
references.expressions.insert(result, expression.clone());
references.aliases.insert(expression, aliases);
}
}
Instruction::Call { arguments, .. } => {
for arg in arguments {
if self.inserter.function.dfg.value_is_reference(*arg) {
if let Some(expression) = references.expressions.get(arg) {
if let Some(aliases) = references.aliases.get(expression) {
aliases.for_each(|alias| {
self.calls_reference_input.insert(alias);
});
}
}
}
}
self.mark_all_unknown(arguments, references);
}
_ => (),
}
}
fn check_array_aliasing(&self, references: &mut Block, array: ValueId) {
if let Some((elements, typ)) = self.inserter.function.dfg.get_array_constant(array) {
if Self::contains_references(&typ) {
// TODO: Check if type directly holds references or holds arrays that hold references
let expr = Expression::ArrayElement(Box::new(Expression::Other(array)));
references.expressions.insert(array, expr.clone());
let aliases = references.aliases.entry(expr).or_default();
for element in elements {
aliases.insert(element);
}
}
}
}
fn contains_references(typ: &Type) -> bool {
match typ {
Type::Numeric(_) => false,
Type::Function => false,
Type::Reference(_) => true,
Type::Array(elements, _) | Type::Slice(elements) => {
elements.iter().any(Self::contains_references)
}
}
}
fn set_aliases(&self, references: &mut Block, address: ValueId, new_aliases: AliasSet) {
let expression =
references.expressions.entry(address).or_insert(Expression::Other(address));
let aliases = references.aliases.entry(expression.clone()).or_default();
*aliases = new_aliases;
}
fn mark_all_unknown(&self, values: &[ValueId], references: &mut Block) {
for value in values {
if self.inserter.function.dfg.value_is_reference(*value) {
let value = self.inserter.function.dfg.resolve(*value);
references.set_unknown(value);
references.mark_value_used(value, self.inserter.function);
}
}
}
/// Remove any instructions in `self.instructions_to_remove` from the current function.
/// This is expected to contain any loads which were replaced and any stores which are
/// no longer needed.
fn remove_instructions(&mut self) {
// The order we iterate blocks in is not important
for block in self.post_order.as_slice() {
self.inserter.function.dfg[*block]
.instructions_mut()
.retain(|instruction| !self.instructions_to_remove.contains(instruction));
}
}
fn update_data_bus(&mut self) {
let databus = self.inserter.function.dfg.data_bus.clone();
self.inserter.function.dfg.data_bus = databus.map_values(|t| self.inserter.resolve(t));
}
fn handle_terminator(&mut self, block: BasicBlockId, references: &mut Block) {
self.inserter.map_terminator_in_place(block);
match self.inserter.function.dfg[block].unwrap_terminator() {
TerminatorInstruction::JmpIf { .. } => (), // Nothing to do
TerminatorInstruction::Jmp { destination, arguments, .. } => {
let destination_parameters = self.inserter.function.dfg[*destination].parameters();
assert_eq!(destination_parameters.len(), arguments.len());
// Add an alias for each reference parameter
for (parameter, argument) in destination_parameters.iter().zip(arguments) {
if self.inserter.function.dfg.value_is_reference(*parameter) {
let argument = self.inserter.function.dfg.resolve(*argument);
if let Some(expression) = references.expressions.get(&argument) {
if let Some(aliases) = references.aliases.get_mut(expression) {
// The argument reference is possibly aliased by this block parameter
aliases.insert(*parameter);
}
}
}
}
}
TerminatorInstruction::Return { return_values, .. } => {
// Removing all `last_stores` for each returned reference is more important here
// than setting them all to ReferenceValue::Unknown since no other block should
// have a block with a Return terminator as a predecessor anyway.
self.mark_all_unknown(return_values, references);
}
}
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use acvm::{acir::AcirField, FieldElement};
use im::vector;
use crate::ssa::{
function_builder::FunctionBuilder,
ir::{
basic_block::BasicBlockId,
dfg::DataFlowGraph,
instruction::{BinaryOp, Instruction, Intrinsic, TerminatorInstruction},
map::Id,
types::Type,
},
};
#[test]
fn test_simple() {
// fn func() {
// b0():
// v0 = allocate
// store [Field 1, Field 2] in v0
// v1 = load v0
// v2 = array_get v1, index 1
// return v2
// }
let func_id = Id::test_new(0);
let mut builder = FunctionBuilder::new("func".into(), func_id);
let v0 = builder.insert_allocate(Type::Array(Arc::new(vec![Type::field()]), 2));
let one = builder.field_constant(FieldElement::one());
let two = builder.field_constant(FieldElement::one());
let element_type = Arc::new(vec![Type::field()]);
let array_type = Type::Array(element_type, 2);
let array = builder.array_constant(vector![one, two], array_type.clone());
builder.insert_store(v0, array);
let v1 = builder.insert_load(v0, array_type);
let v2 = builder.insert_array_get(v1, one, Type::field());
builder.terminate_with_return(vec![v2]);
let ssa = builder.finish().mem2reg().fold_constants();
let func = ssa.main();
let block_id = func.entry_block();
assert_eq!(count_loads(block_id, &func.dfg), 0);
assert_eq!(count_stores(block_id, &func.dfg), 0);
let ret_val_id = match func.dfg[block_id].terminator().unwrap() {
TerminatorInstruction::Return { return_values, .. } => return_values.first().unwrap(),
_ => unreachable!(),
};
assert_eq!(func.dfg[*ret_val_id], func.dfg[two]);
}
#[test]
fn test_simple_with_call() {
// fn func {
// b0():
// v0 = allocate
// store v0, Field 1
// v1 = load v0
// call f0(v0)
// return v1
// }
let func_id = Id::test_new(0);
let mut builder = FunctionBuilder::new("func".into(), func_id);
let v0 = builder.insert_allocate(Type::field());
let one = builder.field_constant(FieldElement::one());
builder.insert_store(v0, one);
let v1 = builder.insert_load(v0, Type::field());
let f0 = builder.import_intrinsic_id(Intrinsic::AssertConstant);
builder.insert_call(f0, vec![v0], vec![]);
builder.terminate_with_return(vec![v1]);
let ssa = builder.finish().mem2reg();
let func = ssa.main();
let block_id = func.entry_block();
assert_eq!(count_loads(block_id, &func.dfg), 0);
assert_eq!(count_stores(block_id, &func.dfg), 1);
let ret_val_id = match func.dfg[block_id].terminator().unwrap() {
TerminatorInstruction::Return { return_values, .. } => return_values.first().unwrap(),
_ => unreachable!(),
};
assert_eq!(func.dfg[*ret_val_id], func.dfg[one]);
}
#[test]
fn test_simple_with_return() {
// fn func {
// b0():
// v0 = allocate
// store v0, Field 1
// return v0
// }
let func_id = Id::test_new(0);
let mut builder = FunctionBuilder::new("func".into(), func_id);
let v0 = builder.insert_allocate(Type::field());
let const_one = builder.field_constant(FieldElement::one());
builder.insert_store(v0, const_one);
builder.terminate_with_return(vec![v0]);
let ssa = builder.finish().mem2reg();
let func = ssa.main();
let block_id = func.entry_block();
// Store is needed by the return value, and can't be removed
assert_eq!(count_stores(block_id, &func.dfg), 1);
let instructions = func.dfg[block_id].instructions();
assert_eq!(instructions.len(), 2);
let ret_val_id = match func.dfg[block_id].terminator().unwrap() {
TerminatorInstruction::Return { return_values, .. } => *return_values.first().unwrap(),
_ => unreachable!(),
};
// Since the mem2reg pass simplifies as it goes, the id of the allocate instruction result
// is most likely no longer v0. We have to retrieve the new id here.
let allocate_id = func.dfg.instruction_results(instructions[0])[0];
assert_eq!(ret_val_id, allocate_id);
}
fn count_stores(block: BasicBlockId, dfg: &DataFlowGraph) -> usize {
dfg[block]
.instructions()
.iter()
.filter(|instruction_id| matches!(dfg[**instruction_id], Instruction::Store { .. }))
.count()
}
fn count_loads(block: BasicBlockId, dfg: &DataFlowGraph) -> usize {
dfg[block]
.instructions()
.iter()
.filter(|instruction_id| matches!(dfg[**instruction_id], Instruction::Load { .. }))
.count()
}
// Test that loads across multiple blocks are removed
#[test]
fn multiple_blocks() {
// fn main {
// b0():
// v0 = allocate
// store Field 5 in v0
// v1 = load v0
// jmp b1(v1):
// b1(v2: Field):
// v3 = load v0
// store Field 6 in v0
// v4 = load v0
// return v2, v3, v4
// }
let main_id = Id::test_new(0);
let mut builder = FunctionBuilder::new("main".into(), main_id);
let v0 = builder.insert_allocate(Type::field());
let five = builder.field_constant(5u128);
builder.insert_store(v0, five);
let v1 = builder.insert_load(v0, Type::field());
let b1 = builder.insert_block();
builder.terminate_with_jmp(b1, vec![v1]);
builder.switch_to_block(b1);
let v2 = builder.add_block_parameter(b1, Type::field());
let v3 = builder.insert_load(v0, Type::field());
let six = builder.field_constant(6u128);
builder.insert_store(v0, six);
let v4 = builder.insert_load(v0, Type::field());
builder.terminate_with_return(vec![v2, v3, v4]);
let ssa = builder.finish();
assert_eq!(ssa.main().reachable_blocks().len(), 2);
// Expected result:
// acir fn main f0 {
// b0():
// v7 = allocate
// jmp b1(Field 5)
// b1(v3: Field):
// return v3, Field 5, Field 6
// }
let ssa = ssa.mem2reg();
let main = ssa.main();
assert_eq!(main.reachable_blocks().len(), 2);
// The loads should be removed
assert_eq!(count_loads(main.entry_block(), &main.dfg), 0);
assert_eq!(count_loads(b1, &main.dfg), 0);
// All stores are removed as there are no loads to the values being stored anywhere in the function.
assert_eq!(count_stores(main.entry_block(), &main.dfg), 0);
assert_eq!(count_stores(b1, &main.dfg), 0);
// The jmp to b1 should also be a constant 5 now
match main.dfg[main.entry_block()].terminator() {
Some(TerminatorInstruction::Jmp { arguments, .. }) => {
assert_eq!(arguments.len(), 1);
let argument =
main.dfg.get_numeric_constant(arguments[0]).expect("Expected constant value");
assert_eq!(argument.to_u128(), 5);
}
_ => unreachable!(),
};
}
// Test that a load in a predecessor block has been removed if the value
// is later stored in a successor block
#[test]
fn load_aliases_in_predecessor_block() {
// fn main {
// b0():
// v0 = allocate
// store Field 0 at v0
// v2 = allocate
// store v0 at v2
// v3 = load v2
// v4 = load v2
// jmp b1()
// b1():
// store Field 1 at v3
// store Field 2 at v4
// v7 = load v3
// v8 = eq v7, Field 2
// return
// }
let main_id = Id::test_new(0);
let mut builder = FunctionBuilder::new("main".into(), main_id);
let v0 = builder.insert_allocate(Type::field());
let zero = builder.field_constant(0u128);
builder.insert_store(v0, zero);
let v2 = builder.insert_allocate(Type::Reference(Arc::new(Type::field())));
builder.insert_store(v2, v0);
let v3 = builder.insert_load(v2, Type::field());
let v4 = builder.insert_load(v2, Type::field());
let b1 = builder.insert_block();
builder.terminate_with_jmp(b1, vec![]);
builder.switch_to_block(b1);
let one = builder.field_constant(1u128);
builder.insert_store(v3, one);
let two = builder.field_constant(2u128);
builder.insert_store(v4, two);
let v8 = builder.insert_load(v3, Type::field());
let _ = builder.insert_binary(v8, BinaryOp::Eq, two);
builder.terminate_with_return(vec![]);
let ssa = builder.finish();
assert_eq!(ssa.main().reachable_blocks().len(), 2);
// Expected result:
// acir fn main f0 {
// b0():
// v9 = allocate
// store Field 0 at v9
// v10 = allocate
// jmp b1()
// b1():
// return
// }
let ssa = ssa.mem2reg();
println!("{}", ssa);
let main = ssa.main();
assert_eq!(main.reachable_blocks().len(), 2);
// All loads should be removed
assert_eq!(count_loads(main.entry_block(), &main.dfg), 0);
assert_eq!(count_loads(b1, &main.dfg), 0);
// The first store is not removed as it is used as a nested reference in another store.
// We would need to track whether the store where `v9` is the store value gets removed to know whether
// to remove it.
assert_eq!(count_stores(main.entry_block(), &main.dfg), 1);
// The first store in b1 is removed since there is another store to the same reference
// in the same block, and the store is not needed before the later store.
// The rest of the stores are also removed as no loads are done within any blocks
// to the stored values.
assert_eq!(count_stores(b1, &main.dfg), 0);
let b1_instructions = main.dfg[b1].instructions();
// We expect the last eq to be optimized out
assert_eq!(b1_instructions.len(), 0);
}
#[test]
fn keep_store_to_alias_in_loop_block() {
// This test makes sure the instruction `store Field 2 at v5` in b2 remains after mem2reg.
// Although the only instruction on v5 is a lone store without any loads,
// v5 is an alias of the reference v0 which is stored in v2.
// This test makes sure that we are not inadvertently removing stores to aliases across blocks.
//
// acir(inline) fn main f0 {
// b0():
// v0 = allocate
// store Field 0 at v0
// v2 = allocate
// store v0 at v2
// jmp b1(Field 0)
// b1(v3: Field):
// v4 = eq v3, Field 0
// jmpif v4 then: b2, else: b3
// b2():
// v5 = load v2
// store Field 2 at v5
// v8 = add v3, Field 1
// jmp b1(v8)
// b3():
// v9 = load v0
// v10 = eq v9, Field 2
// constrain v9 == Field 2
// v11 = load v2
// v12 = load v10
// v13 = eq v12, Field 2
// constrain v11 == Field 2
// return
// }
let main_id = Id::test_new(0);
let mut builder = FunctionBuilder::new("main".into(), main_id);
let v0 = builder.insert_allocate(Type::field());
let zero = builder.numeric_constant(0u128, Type::field());
builder.insert_store(v0, zero);
let v2 = builder.insert_allocate(Type::field());
// Construct alias
builder.insert_store(v2, v0);
let v2_type = builder.current_function.dfg.type_of_value(v2);
assert!(builder.current_function.dfg.value_is_reference(v2));
let b1 = builder.insert_block();
builder.terminate_with_jmp(b1, vec![zero]);
// Loop header
builder.switch_to_block(b1);
let v3 = builder.add_block_parameter(b1, Type::field());
let is_zero = builder.insert_binary(v3, BinaryOp::Eq, zero);
let b2 = builder.insert_block();
let b3 = builder.insert_block();
builder.terminate_with_jmpif(is_zero, b2, b3);
// Loop body
builder.switch_to_block(b2);
let v5 = builder.insert_load(v2, v2_type.clone());
let two = builder.numeric_constant(2u128, Type::field());
builder.insert_store(v5, two);
let one = builder.numeric_constant(1u128, Type::field());
let v3_plus_one = builder.insert_binary(v3, BinaryOp::Add, one);
builder.terminate_with_jmp(b1, vec![v3_plus_one]);
builder.switch_to_block(b3);
let v9 = builder.insert_load(v0, Type::field());
let _ = builder.insert_binary(v9, BinaryOp::Eq, two);
builder.insert_constrain(v9, two, None);
let v11 = builder.insert_load(v2, v2_type);
let v12 = builder.insert_load(v11, Type::field());
let _ = builder.insert_binary(v12, BinaryOp::Eq, two);
builder.insert_constrain(v11, two, None);
builder.terminate_with_return(vec![]);
let ssa = builder.finish();
// We expect the same result as above.
let ssa = ssa.mem2reg();
let main = ssa.main();
assert_eq!(main.reachable_blocks().len(), 4);
// The store from the original SSA should remain
assert_eq!(count_stores(main.entry_block(), &main.dfg), 2);
assert_eq!(count_stores(b2, &main.dfg), 1);
assert_eq!(count_loads(b2, &main.dfg), 1);
assert_eq!(count_loads(b3, &main.dfg), 3);
}
}