-
Notifications
You must be signed in to change notification settings - Fork 406
Expand file tree
/
Copy pathmem2reg.rs
More file actions
1975 lines (1706 loc) · 81.1 KB
/
Copy pathmem2reg.rs
File metadata and controls
1975 lines (1706 loc) · 81.1 KB
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
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! 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.
//! - We also track the last load instruction to each address per 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.
//! - We also track the last instance of a load instruction to each address in a block.
//! If we see that the last load instruction was from the same address as the current load instruction,
//! we move to replace the result of the current load with the result of the previous load.
//! This removal requires a couple conditions:
//! - No store occurs to that address before the next load,
//! - The address is not used as an argument to a call
//! This optimization helps us remove repeated loads for which there are not known values.
//! - 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.
//! - Remove the instance of the last load instruction to the address and its aliases
//! - 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.
//! - Remove the instance of the last load instruction for any reference arguments and their aliases
//!
//! 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.
//!
//! As stated above, the algorithm above can sometimes miss known references.
//! This most commonly occurs in the case of loops, where we may have allocations preceding a loop that are known,
//! but the loop body's blocks are predecessors to the loop header block, causing those known allocations to be marked unknown.
//! In certain cases we may be able to remove these allocations that precede a loop.
//! For example, if a reference is not stored to again in the loop we should be able to remove that store which precedes the loop.
//!
//! To handle cases such as the one laid out above, we maintain some extra state per function,
//! that we will analyze after the initial run through all of the blocks.
//! We refer to this as the "function cleanup" and it requires having already iterated through all blocks.
//!
//! The state contains the following:
//! - For each load address we store the number of loads from a given address,
//! the last load instruction from a given address across all blocks, and the respective block id of that instruction.
//! - A mapping of each load result to its number of uses, the load instruction that produced the given result, and the respective block id of that instruction.
//! - A set of the references and their aliases passed as an argument to a call.
//! - Maps the references which have been aliased to the instructions that aliased that reference.
//! - As we go through each instruction, if a load result has been used we increment its usage counter.
//! Upon removing an instruction, we decrement the load result counter.
//! After analyzing all of a function's blocks we can analyze the per function state:
//! - If we find that a load result's usage counter equals zero, we can remove that load.
//! - We can then remove a store if the following conditions are met:
//! - All loads to a given address have been removed
//! - None of the aliases of a reference are used in any of the following:
//! - Block parameters, function parameters, call arguments, terminator arguments
//! - The store address is not aliased.
//! - If a store is in a return block, we can have special handling that only checks if there is a load after
//! that store in the return block. In the case of a return block, even if there are other loads
//! in preceding blocks we can safely remove those stores.
//! - To further catch any stores to references which are never loaded, we can count the number of stores
//! that were removed in the previous step. If there is only a single store leftover, we can safely map
//! the value of this final store to any loads of that store.
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() {
let mut context = PerFunctionContext::new(function);
context.mem2reg();
context.remove_instructions();
context.update_data_bus();
}
self
}
}
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, PerFuncLastLoadContext>,
/// Track whether a load result was used across all blocks.
load_results: HashMap<ValueId, PerFuncLoadResultContext>,
/// 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>>,
// The index of the last load instruction in a given block
return_block_load_locations: HashMap<(ValueId, BasicBlockId), usize>,
}
#[derive(Debug, Clone)]
struct PerFuncLastLoadContext {
/// Reference counter that keeps track of how many times we loaded from a given address
num_loads: u32,
/// Last load instruction from a given address
load_instruction: InstructionId,
/// Block of the last load instruction
block_id: BasicBlockId,
}
impl PerFuncLastLoadContext {
fn new(load_instruction: InstructionId, block_id: BasicBlockId, num_loads: u32) -> Self {
Self { num_loads, load_instruction, block_id }
}
}
#[derive(Debug, Clone)]
struct PerFuncLoadResultContext {
/// Reference counter that keeps track of how many times a load was used in other instructions
uses: u32,
/// Load instruction that produced a given load result
load_instruction: InstructionId,
/// Block of the load instruction that produced a given result
block_id: BasicBlockId,
}
impl PerFuncLoadResultContext {
fn new(load_instruction: InstructionId, block_id: BasicBlockId) -> Self {
Self { uses: 0, load_instruction, block_id }
}
}
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(),
load_results: HashMap::default(),
calls_reference_input: HashSet::default(),
aliased_references: HashMap::default(),
return_block_load_locations: 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);
}
self.cleanup_function();
}
/// 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);
}
// Last loads are truly "per block". During unification we are creating a new block from the current one,
// so we must clear the last loads of the current block before return the new block.
references.last_loads.clear();
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);
if let Some(context) = self.load_results.get_mut(allocation) {
context.uses -= 1;
}
}
}
}
}
}
fn increase_load_ref_counts(&mut self, value: ValueId) {
if let Some(context) = self.load_results.get_mut(&value) {
context.uses += 1;
}
let array_const = self.inserter.function.dfg.get_array_constant(value);
if let Some((values, _)) = array_const {
for array_value in values {
self.increase_load_ref_counts(array_value);
}
}
}
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;
}
let mut collect_values = Vec::new();
// Track whether any load results were used in the instruction
self.inserter.function.dfg[instruction].for_each_value(|value| {
collect_values.push(value);
});
for value in collect_values {
self.increase_load_ref_counts(value);
}
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) {
self.inserter.map_value(result, value);
self.instructions_to_remove.insert(instruction);
} else {
references.mark_value_used(address, self.inserter.function);
let expression =
references.expressions.entry(result).or_insert(Expression::Other(result));
// Make sure this load result is marked an alias to itself
if let Some(aliases) = references.aliases.get_mut(expression) {
// If we have an alias set, add to the set
aliases.insert(result);
} else {
// Otherwise, create a new alias set containing just the load result
references
.aliases
.insert(Expression::Other(result), AliasSet::known(result));
}
// Mark that we know a load result is equivalent to the address of a load.
references.set_known_value(result, address);
self.load_results
.insert(result, PerFuncLoadResultContext::new(instruction, block_id));
let num_loads =
self.last_loads.get(&address).map_or(1, |context| context.num_loads + 1);
let last_load = PerFuncLastLoadContext::new(instruction, block_id, num_loads);
self.last_loads.insert(address, last_load);
// If we are in a return block we want to save the last location of a load
let terminator = self.inserter.function.dfg[block_id].unwrap_terminator();
let is_return = matches!(terminator, TerminatorInstruction::Return { .. });
if is_return {
let instruction_index =
self.inserter.function.dfg[block_id].instructions().len();
self.return_block_load_locations
.insert((address, block_id), instruction_index);
}
}
// Check whether the block has a repeat load from the same address (w/ no calls or stores in between the loads).
// If we do have a repeat load, we can remove the current load and map its result to the previous loads result.
if let Some(last_load) = references.last_loads.get(&address) {
let Instruction::Load { address: previous_address } =
&self.inserter.function.dfg[*last_load]
else {
panic!("Expected a Load instruction here");
};
let result = self.inserter.function.dfg.instruction_results(instruction)[0];
let previous_result =
self.inserter.function.dfg.instruction_results(*last_load)[0];
if *previous_address == address {
self.inserter.map_value(result, previous_result);
self.instructions_to_remove.insert(instruction);
}
}
// We want to set the load for every load even if the address has a known value
// and the previous load instruction was removed.
// We are safe to still remove a repeat load in this case as we are mapping from the current load's
// result to the previous load, which if it was removed should already have a mapping to the known value.
references.set_last_load(address, instruction);
}
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 address 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);
let Instruction::Store { address, value } =
self.inserter.function.dfg[*last_store]
else {
panic!("Should have a store instruction here");
};
if let Some(context) = self.load_results.get_mut(&address) {
context.uses -= 1;
}
if let Some(context) = self.load_results.get_mut(&value) {
context.uses -= 1;
}
}
let known_value = references.get_known_value(value);
if let Some(known_value) = known_value {
let known_value_is_address = known_value == address;
if known_value_is_address {
self.instructions_to_remove.insert(instruction);
if let Some(context) = self.load_results.get_mut(&address) {
context.uses -= 1;
}
if let Some(context) = self.load_results.get_mut(&value) {
context.uses -= 1;
}
} else {
references.last_stores.insert(address, instruction);
}
} else {
references.last_stores.insert(address, instruction);
}
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);
// If we see a store to an address, the last load to that address needs to remain.
references.keep_last_load_for(address, self.inserter.function);
}
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);
// If a reference is an argument to a call, the last load to that address and its aliases needs to remain.
references.keep_last_load_for(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) {
self.inserter.map_data_bus_in_place();
}
fn handle_terminator(&mut self, block: BasicBlockId, references: &mut Block) {
self.inserter.map_terminator_in_place(block);
let terminator: &TerminatorInstruction =
self.inserter.function.dfg[block].unwrap_terminator();
let mut collect_values = Vec::new();
terminator.for_each_value(|value| {
collect_values.push(value);
});
let terminator = terminator.clone();
for value in collect_values.iter() {
self.increase_load_ref_counts(*value);
}
match &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);
}
}
}
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 mem2reg pass is sometimes unable to determine certain known values
/// when iterating over a function's block in reverse post order.
/// We collect state about any final loads and stores to a given address during the initial mem2reg pass.
/// We can then utilize this state to clean up any loads and stores that may have been missed.
fn cleanup_function(&mut self) {
// Removing remaining unused loads during mem2reg can help expose removable stores that the initial
// mem2reg pass deemed we could not remove due to the existence of those unused loads.
let removed_loads = self.remove_unused_loads();
let remaining_last_stores = self.remove_unloaded_last_stores(&removed_loads);
let stores_were_removed =
self.remove_remaining_last_stores(&removed_loads, &remaining_last_stores);
// When removing some last loads with the last stores we will map the load result to the store value.
// We need to then map all the instructions again as we do not know which instructions are reliant on the load result.
if stores_were_removed {
let mut block_order = PostOrder::with_function(self.inserter.function).into_vec();
block_order.reverse();
for block in block_order {
let instructions = self.inserter.function.dfg[block].take_instructions();
for instruction in instructions {
if !self.instructions_to_remove.contains(&instruction) {
self.inserter.push_instruction(instruction, block);
}
}
self.inserter.map_terminator_in_place(block);
}
}
}
/// Cleanup remaining loads across the entire function
/// Remove any loads whose reference counter is zero.
/// Returns a map of the removed load address to the number of load instructions removed for that address
fn remove_unused_loads(&mut self) -> HashMap<ValueId, u32> {
let mut removed_loads = HashMap::default();
for (_, PerFuncLoadResultContext { uses, load_instruction, block_id, .. }) in
self.load_results.iter()
{
let Instruction::Load { address } = self.inserter.function.dfg[*load_instruction]
else {
unreachable!("Should only have a load instruction here");
};
// If the load result's counter is equal to zero we can safely remove that load instruction.
if *uses == 0 {
self.return_block_load_locations.remove(&(address, *block_id));
removed_loads.entry(address).and_modify(|counter| *counter += 1).or_insert(1);
self.instructions_to_remove.insert(*load_instruction);
}
}
removed_loads
}
fn recursively_check_address_in_terminator(
&self,
return_value: ValueId,
store_address: ValueId,
is_return_value: &mut bool,
) {
*is_return_value = return_value == store_address || *is_return_value;
let array_const = self.inserter.function.dfg.get_array_constant(return_value);
if let Some((values, _)) = array_const {
for array_value in values {
self.recursively_check_address_in_terminator(
array_value,
store_address,
is_return_value,
);
}
}
}
/// Cleanup remaining stores across the entire function.
/// 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.
/// Returns a map of any remaining stores which may still have loads in use.
fn remove_unloaded_last_stores(
&mut self,
removed_loads: &HashMap<ValueId, u32>,
) -> HashMap<ValueId, (InstructionId, u32)> {
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);
});
}
let mut remaining_last_stores: HashMap<ValueId, (InstructionId, u32)> = HashMap::default();
for (block_id, block) in self.blocks.iter() {
for (store_address, store_instruction) in block.last_stores.iter() {
if self.instructions_to_remove.contains(store_instruction) {
continue;
}
let all_loads_removed = self.all_loads_removed_for_address(
store_address,
*store_instruction,
*block_id,
removed_loads,
);
let store_alias_used = self.is_store_alias_used(
store_address,
block,
&all_terminator_values,
&per_func_block_params,
);
if all_loads_removed && !store_alias_used {
self.instructions_to_remove.insert(*store_instruction);
if let Some((_, counter)) = remaining_last_stores.get_mut(store_address) {
*counter -= 1;
}
} else if let Some((_, counter)) = remaining_last_stores.get_mut(store_address) {
*counter += 1;
} else {
remaining_last_stores.insert(*store_address, (*store_instruction, 1));
}
}
}
remaining_last_stores
}
fn all_loads_removed_for_address(
&self,
store_address: &ValueId,
store_instruction: InstructionId,
block_id: BasicBlockId,
removed_loads: &HashMap<ValueId, u32>,
) -> bool {
let terminator = self.inserter.function.dfg[block_id].unwrap_terminator();
let is_return = matches!(terminator, TerminatorInstruction::Return { .. });
// Determine whether any loads that reference this store address
// have been removed while cleaning up unused loads.
if is_return {
// If we are in a return terminator, and the last loads of a reference
// come before a store to that reference, we can safely remove that store.
let store_after_load = if let Some(max_load_index) =
self.return_block_load_locations.get(&(*store_address, block_id))
{
let store_index = self.inserter.function.dfg[block_id]
.instructions()
.iter()
.position(|id| *id == store_instruction)
.expect("Store instruction should exist in the return block");
store_index > *max_load_index
} else {
// Otherwise there is no load in this block
true
};
store_after_load
} else if let (Some(context), Some(loads_removed_counter)) =
(self.last_loads.get(store_address), removed_loads.get(store_address))
{
// `last_loads` contains the total number of loads for a given load address
// If the number of removed loads for a given address is equal to the total number of loads for that address,
// we know we can safely remove any stores to that load address.
context.num_loads == *loads_removed_counter
} else {
self.last_loads.get(store_address).is_none()
}
}
// 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
}
/// Check if any remaining last stores are only used in a single load
/// Returns true if any stores were removed.
fn remove_remaining_last_stores(
&mut self,
removed_loads: &HashMap<ValueId, u32>,
remaining_last_stores: &HashMap<ValueId, (InstructionId, u32)>,
) -> bool {
let mut stores_were_removed = false;
// Filter out any still in use load results and any load results that do not contain addresses from the remaining last stores
self.load_results.retain(|_, PerFuncLoadResultContext { load_instruction, uses, .. }| {
let Instruction::Load { address } = self.inserter.function.dfg[*load_instruction]
else {
unreachable!("Should only have a load instruction here");
};
remaining_last_stores.contains_key(&address) && *uses > 0
});
for (store_address, (store_instruction, store_counter)) in remaining_last_stores {
let Instruction::Store { value, .. } = self.inserter.function.dfg[*store_instruction]
else {
unreachable!("Should only have a store instruction");
};
if let (Some(context), Some(loads_removed_counter)) =
(self.last_loads.get(store_address), removed_loads.get(store_address))
{
assert!(
context.num_loads >= *loads_removed_counter,
"The number of loads removed should not be more than all loads"
);
}
// We only want to remove last stores referencing a single address.
if *store_counter != 0 {
continue;
}
self.instructions_to_remove.insert(*store_instruction);
// Map any remaining load results to the value from the removed store
for (result, context) in self.load_results.iter() {
let Instruction::Load { address } =
self.inserter.function.dfg[context.load_instruction]
else {
unreachable!("Should only have a load instruction here");
};
if address != *store_address {
continue;
}
// Map the load result to its respective store value
// We will have to map all instructions following this method
// as we do not know what instructions depend upon this result
self.inserter.map_value(*result, value);
self.instructions_to_remove.insert(context.load_instruction);
stores_were_removed = true;
}
}
stores_were_removed
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use acvm::{acir::AcirField, FieldElement};
use im::vector;
use noirc_frontend::monomorphization::ast::InlineType;
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);