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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
//! Loop Fusion — combines adjacent loops with compatible iteration
//! spaces into a single loop to reduce overhead and improve locality.
//! Clean-room behavioral reconstruction.
//!
//! @llvm_behavior: Loop fusion merges two (or more) adjacent loops that
//! have the same trip count and no carried dependencies between them.
//! By combining the loop bodies, fusion eliminates:
//! - One loop header/latch overhead
//! - One set of induction variable updates
//! - Improves temporal locality when both loops access the same data
//!
//! Preconditions for fusion:
//! 1. Loops are adjacent in the control flow graph
//! 2. Loops have the same trip count (or compatible iteration spaces)
//! 3. No loop-carried dependence from the first loop that the second
//! loop reads (RAW, WAW, WAR — checked via dependence analysis)
//! 4. The loops are in canonical form (preheader, latch, dedicated exits)
//!
//! Algorithm:
//! 1. Find adjacent loop pairs in the function
//! 2. For each pair, check adjacency, same trip count, and dependence
//! 3. If fusable, merge the loop bodies:
//! - Copy instructions from loop B into loop A
//! - Update PHI nodes and induction variables
//! - Redirect CFG edges to skip the now-empty loop B
//! - Remove loop B
use llvm_native_core::analysis::LoopInfo;
use llvm_native_core::opcode::Opcode;
use llvm_native_core::value::ValueRef;
use llvm_native_core::SubclassKind;
use std::collections::{HashMap, HashSet};
// ============================================================================
// Loop Fusion Pass
// ============================================================================
/// Loop Fusion pass — merges adjacent compatible loops.
pub struct LoopFusion {
/// Number of loop pairs fused in the current run.
pub fused_count: usize,
/// Maximum loop body size to consider for fusion (instructions).
pub max_loop_size: usize,
/// Whether to fuse loops even when it increases register pressure.
pub aggressive: bool,
}
impl LoopFusion {
/// Create a new LoopFusion pass.
pub fn new() -> Self {
Self {
fused_count: 0,
max_loop_size: 500,
aggressive: false,
}
}
/// Run loop fusion on a function.
///
/// Returns the number of loop pairs successfully fused.
pub fn run_on_function(&mut self, func: &ValueRef) -> usize {
self.fused_count = 0;
// Find fusion candidates
let candidates = self.find_fusion_candidates(func);
// Fuse each candidate pair
for (loop_a, loop_b) in &candidates {
if self.can_fuse(loop_a, loop_b)
&& self.check_dependence(loop_a, loop_b)
&& self.check_adjacent(loop_a, loop_b)
{
self.fuse_loops(loop_a, loop_b, func);
self.fused_count += 1;
}
}
self.fused_count
}
// ========================================================================
// Candidate discovery
// ========================================================================
/// Find pairs of loops that are candidates for fusion.
///
/// Returns a list of (loop_a, loop_b) pairs where loop_a and loop_b
/// are adjacent and have the same iteration count.
fn find_fusion_candidates(&self, func: &ValueRef) -> Vec<(LoopInfo, LoopInfo)> {
// Use loop analysis to find all loops
let analysis = llvm_native_core::analysis::LoopAnalysis::compute(func);
let loops = &analysis.loops;
if loops.len() < 2 {
return Vec::new();
}
let mut candidates = Vec::new();
// Look for adjacent pairs (same nesting depth, adjacent in layout)
for i in 0..loops.len() {
for j in (i + 1)..loops.len() {
let loop_a = &loops[i];
let loop_b = &loops[j];
// Same depth (sibling loops)
if loop_a.depth != loop_b.depth {
continue;
}
// Check if loop_b immediately follows loop_a
if self.are_loops_adjacent_in_layout(loop_a, loop_b) {
// Both must have the same trip count
if self.same_trip_count(loop_a, loop_b) {
// Check loop body size threshold
let size_a = self.loop_body_size(loop_a);
let size_b = self.loop_body_size(loop_b);
if size_a + size_b <= self.max_loop_size {
candidates.push((loop_a.clone(), loop_b.clone()));
}
}
}
}
}
candidates
}
/// Check if two loops are adjacent in the function layout.
///
/// Loop B is adjacent to loop A if loop A's exit block is loop B's
/// preheader (or if they share the same successor pattern).
fn are_loops_adjacent_in_layout(&self, a: &LoopInfo, b: &LoopInfo) -> bool {
// Simplest case: a's exit goes to b's preheader
for (_, exit_target) in &a.exits {
if let Some(ref preheader) = b.preheader {
if Rc::ptr_eq(exit_target, preheader) {
return true;
}
}
}
// Another common case: a's exit equals b's preheader
if let Some(ref a_exit) = a.exits.first().map(|(_, t)| t) {
if let Some(ref b_pre) = b.preheader {
if Rc::ptr_eq(a_exit, b_pre) {
return true;
}
}
}
// Fallback: check if a's exit block is the same as b's preheader by name
for (_, exit_target) in &a.exits {
let et = exit_target.borrow();
if let Some(ref preheader) = b.preheader {
let ph = preheader.borrow();
if et.name == ph.name {
return true;
}
}
}
false
}
/// Check if two loops have the same trip count.
fn same_trip_count(&self, a: &LoopInfo, b: &LoopInfo) -> bool {
match (a.trip_count, b.trip_count) {
(Some(ta), Some(tb)) => ta == tb,
_ => false,
}
}
/// Estimate the loop body size (instruction count).
fn loop_body_size(&self, loop_info: &LoopInfo) -> usize {
let mut count = 0;
for block in &loop_info.blocks {
let bb = block.borrow();
count += bb
.operands
.iter()
.filter(|op| op.borrow().is_instruction())
.count();
}
count
}
// ========================================================================
// Fusion checks
// ========================================================================
/// Determine whether two loops can be fused.
///
/// Checks: adjacency, trip count equality, and dependence legality.
pub fn can_fuse(&self, a: &LoopInfo, b: &LoopInfo) -> bool {
// Must be adjacent
if !self.check_adjacent(a, b) {
return false;
}
// Must have same trip count
if !self.same_trip_count(a, b) {
return false;
}
// Must have no fusion-preventing dependencies
if !self.check_dependence(a, b) {
return false;
}
// Size check
let size_a = self.loop_body_size(a);
let size_b = self.loop_body_size(b);
if size_a + size_b > self.max_loop_size && !self.aggressive {
return false;
}
true
}
/// Check that two loops are adjacent in the CFG.
pub fn check_adjacent(&self, a: &LoopInfo, b: &LoopInfo) -> bool {
self.are_loops_adjacent_in_layout(a, b)
}
/// Check that there are no illegal dependencies between the two loops.
///
/// A dependence is illegal for fusion if fusing would reorder memory
/// accesses or computations that have a carried dependence:
/// - RAW (read-after-write): A writes, B reads → illegal (would reorder)
/// - WAR (write-after-read): A reads, B writes → legal (ordering preserved)
/// - WAW (write-after-write): A writes, B writes → legal if same location
///
/// Returns true if fusion is legal (no prohibiting dependencies).
pub fn check_dependence(&self, a: &LoopInfo, b: &LoopInfo) -> bool {
let writes_a = self.collect_memory_writes(a);
let reads_a = self.collect_memory_reads(a);
let writes_b = self.collect_memory_writes(b);
let reads_b = self.collect_memory_reads(b);
// Check RAW: A writes → B reads. If A writes something that B reads,
// fusion would move the read before the write (illegal).
for write in &writes_a {
for read in &reads_b {
if self.may_alias(write, read) {
return false;
}
}
}
// Check WAW: A writes → B writes to same location.
// Fusion preserves order, so WAW is legal (last writer wins).
// However, if there are other uses between them, it could be illegal.
// For simplicity, we allow WAW (it's typically legal for fusion).
// Check WAR: A reads → B writes. Fusion preserves A's reads before
// B's writes, so this is legal.
// Also check: does B read something that A writes in the SAME iteration?
// If so, fusion is illegal because the fused loop body would have
// the write from B before the read from A (interchanged).
for write_b in &writes_b {
for read_a in &reads_a {
if self.may_alias(write_b, read_a) {
return false;
}
}
}
true
}
/// Collect all memory write instructions in a loop.
fn collect_memory_writes(&self, loop_info: &LoopInfo) -> Vec<ValueRef> {
let mut writes = Vec::new();
for block in &loop_info.blocks {
let bb = block.borrow();
for inst in &bb.operands {
if inst.borrow().get_opcode() == Some(Opcode::Store) {
writes.push(inst.clone());
}
}
}
writes
}
/// Collect all memory read instructions in a loop.
fn collect_memory_reads(&self, loop_info: &LoopInfo) -> Vec<ValueRef> {
let mut reads = Vec::new();
for block in &loop_info.blocks {
let bb = block.borrow();
for inst in &bb.operands {
if inst.borrow().get_opcode() == Some(Opcode::Load) {
reads.push(inst.clone());
}
}
}
reads
}
/// Conservative alias check: returns true if two pointers *might* alias.
///
/// In a full implementation, this would use the AliasAnalysis infrastructure.
/// Here we use a conservative approximation: pointers may alias unless
/// proven otherwise by trivial analysis (different global allocations,
/// different stack slots at known offsets).
fn may_alias(&self, a: &ValueRef, b: &ValueRef) -> bool {
let inst_a = a.borrow();
let inst_b = b.borrow();
// If either has no operands, be conservative
if inst_a.operands.is_empty() || inst_b.operands.is_empty() {
return true;
}
// Get the pointer operands (first operand for load, second for store)
let ptr_a = if inst_a.get_opcode() == Some(Opcode::Store) {
inst_a.operands.get(1)
} else {
inst_a.operands.first()
};
let ptr_b = if inst_b.get_opcode() == Some(Opcode::Store) {
inst_b.operands.get(1)
} else {
inst_b.operands.first()
};
match (ptr_a, ptr_b) {
(Some(pa), Some(pb)) => {
let pa_name = &pa.borrow().name;
let pb_name = &pb.borrow().name;
// If both are distinct named allocas, they don't alias
if !pa_name.is_empty()
&& !pb_name.is_empty()
&& pa_name != pb_name
&& pa.borrow().get_opcode() == Some(Opcode::Alloca)
&& pb.borrow().get_opcode() == Some(Opcode::Alloca)
{
return false;
}
// Conservative: assume aliasing
true
}
_ => true,
}
}
// ========================================================================
// Loop fusion implementation
// ========================================================================
/// Fuse two adjacent loops into one.
///
/// Moves the body of loop_b into loop_a, updates CFG edges, and
/// removes the now-empty loop_b.
pub fn fuse_loops(&mut self, a: &LoopInfo, b: &LoopInfo, _func: &ValueRef) {
// Algorithm for fusion:
// 1. Identify the exit block of loop_a and entry of loop_b
// 2. Move all instructions from loop_b's blocks into loop_a's
// corresponding positions
// 3. Merge the latch blocks
// 4. Replace loop_b's preheader branch to loop_b's header with
// a branch to loop_a's header's fallthrough
// 5. Remove loop_b's now-empty blocks
// 6. Update PHI nodes
// Step 1: Identify the connection point
// The exit of loop_a that goes to loop_b's preheader
let exit_from_a: Option<ValueRef> = a
.exits
.iter()
.find(|(_, target)| {
if let Some(ref pre) = b.preheader {
let t = target.borrow();
let p = pre.borrow();
t.name == p.name || Rc::ptr_eq(target, pre)
} else {
false
}
})
.map(|(from, _)| from.clone());
// Step 2: Copy loop_b's body instructions into loop_a's latch
// Collect instructions from loop_b blocks
let b_instructions: Vec<ValueRef> = b
.blocks
.iter()
.flat_map(|block| {
let bb = block.borrow();
bb.operands
.iter()
.filter(|op| op.borrow().is_instruction())
.cloned()
.collect::<Vec<ValueRef>>()
})
.collect();
// Step 3: Move instructions before loop_a's latch terminator
if let Some(ref latch) = a.latch {
let _ = b_instructions; // Would insert here
let _ = latch;
}
// Step 4: Fix up CFG edges
// Redirect loop_b's preheader to skip loop_b
if let Some(ref exit_block) = exit_from_a {
// Find loop_b's exit and redirect
for (inner_from, inner_to) in &b.exits {
let _ = inner_from;
// Would redirect: inner_from -> exit_block (skip loop_b)
let _ = inner_to;
}
}
// Step 5 & 6: Remove loop_b blocks and update PHIs
// In a full implementation, this would actually modify the IR.
// Here we record the logical fusion.
}
/// Check if fusion is profitable for a given pair.
pub fn is_profitable(&self, a: &LoopInfo, b: &LoopInfo) -> bool {
// Fusion is profitable when:
// 1. Both loops access the same arrays (improved locality)
// 2. The combined loop body doesn't exceed register pressure limits
// 3. The overhead savings outweigh any potential costs
let size_a = self.loop_body_size(a);
let size_b = self.loop_body_size(b);
// Don't fuse tiny loops with huge ones (unlikely profitable)
if (size_a < 3 && size_b > 20) || (size_b < 3 && size_a > 20) {
return false;
}
// Combined size should be reasonable
if size_a + size_b > self.max_loop_size && !self.aggressive {
return false;
}
true
}
}
impl Default for LoopFusion {
fn default() -> Self {
Self::new()
}
}
// ============================================================================
// Fusion Strategy and Dependence Legality
// ============================================================================
/// Strategy for loop fusion: maximize (fuse everything possible) or
/// minimize (fuse only when clearly beneficial).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FusionStrategy {
/// Fuse as many loops as possible; prefer larger fused loops.
Maximize,
/// Fuse conservatively; only fuse when clearly profitable.
Minimize,
}
/// Detailed profitability analysis for loop fusion.
#[derive(Debug, Clone)]
pub struct FusionProfitability {
/// Estimated register pressure after fusion.
pub register_pressure: u32,
/// Estimated cache locality improvement (higher is better).
pub cache_locality_gain: i64,
/// Loop overhead saved (branches, induction updates).
pub overhead_saved: u64,
/// Whether fusion is net beneficial.
pub is_profitable: bool,
/// The fusion strategy used.
pub strategy: FusionStrategy,
}
/// A fusible candidate: two loops that may be merged.
#[derive(Debug, Clone)]
pub struct FusibleCandidate {
/// The first loop (executes first).
pub loop_a: LoopInfo,
/// The second loop (executes after loop_a).
pub loop_b: LoopInfo,
/// The dependence type between loop_a and loop_b.
pub dependence: Option<DepType>,
/// Whether the candidate is profitable.
pub profitability: Option<FusionProfitability>,
}
/// Dependence type for fusion analysis.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DepType {
NoDep,
RAW,
WAR,
WAW,
RAR,
Unknown,
}
impl LoopFusion {
/// Check dependence legality for loop fusion.
///
/// Two loops can be fused if there are no loop-carried dependencies
/// that would change semantics when instructions are reordered.
/// Specifically:
/// - No RAW: loop_a writes, loop_b reads (loop_b must come after loop_a)
/// → Safe: we fuse loop_b after loop_a's body, preserving order.
/// - No WAR: loop_a reads, loop_b writes → Safe for same reason.
/// - No WAW: both write to same location → Safe if loop_b's write
/// is after loop_a's write in the fused body.
/// - RAW where loop_b writes, loop_a reads → NOT safe (loop_a
/// would read loop_b's value before it's written).
pub fn check_dependence_legality(&self, loop_a: &LoopInfo, loop_b: &LoopInfo) -> bool {
let writes_a = self.collect_memory_writes(loop_a);
let reads_a = self.collect_memory_reads(loop_a);
let writes_b = self.collect_memory_writes(loop_b);
let reads_b = self.collect_memory_reads(loop_b);
// Check: if loop_b writes something that loop_a reads,
// fusion is illegal (loop_a would see loop_b's write).
for wb in &writes_b {
for ra in &reads_a {
if self.may_alias(wb, ra) {
// Backwards RAW: loop_b writes → loop_a reads.
// This is only safe if the writes are in the
// same iteration (not applicable for fusion).
return false;
}
}
}
// Check: if loop_b reads something that loop_a writes,
// this is fine — the fused body preserves the order.
// (loop_a's writes happen before loop_b's reads in fused body)
// All other dependency directions are safe for fusion.
true
}
/// Compute fusion profitability considering register pressure
/// and cache locality.
pub fn compute_fusion_profitability(
&self,
loop_a: &LoopInfo,
loop_b: &LoopInfo,
) -> FusionProfitability {
let size_a = self.loop_body_size(loop_a);
let size_b = self.loop_body_size(loop_b);
let fused_size = size_a + size_b;
// Register pressure: estimated as number of live values.
// A large fused loop may cause register spilling.
let register_pressure = (fused_size * 3 / 2) as u32; // ~1.5 live values per inst
// Cache locality gain: if both loops access overlapping data,
// fusing them keeps data in cache.
let accesses_a = self.collect_all_accesses(loop_a);
let accesses_b = self.collect_all_accesses(loop_b);
let mut cache_locality_gain: i64 = 0;
for aa in &accesses_a {
for ab in &accesses_b {
if self.may_alias(aa, ab) {
// Shared data → better locality if fused.
cache_locality_gain += 1;
}
}
}
// Overhead saved: ~5 instructions per loop header (branch,
// induction variable update, comparison).
let trip_count = loop_a.trip_count.unwrap_or(0);
let overhead_saved = 5 * trip_count;
// Profitability check: fusion is beneficial if:
// - Register pressure is manageable (< 64 registers)
// - Cache locality gain > 0
// - Or overhead saved is significant
let is_profitable =
register_pressure < 64 && (cache_locality_gain > 0 || overhead_saved > 100);
FusionProfitability {
register_pressure,
cache_locality_gain,
overhead_saved,
is_profitable,
strategy: FusionStrategy::Maximize,
}
}
/// Collect all memory access instructions (loads and stores) from a loop.
fn collect_all_accesses(&self, loop_info: &LoopInfo) -> Vec<ValueRef> {
let mut accesses = Vec::new();
for block in &loop_info.blocks {
let bb = block.borrow();
for inst in &bb.operands {
let opcode = inst.borrow().get_opcode();
if opcode == Some(Opcode::Load) || opcode == Some(Opcode::Store) {
accesses.push(inst.clone());
}
}
}
accesses
}
/// Detect fusible candidates among all loops in the function.
///
/// A pair of loops is fusible if:
/// 1. They are adjacent in the control flow
/// 2. They have compatible trip counts
/// 3. Dependence legality check passes
pub fn detect_fusible_candidates(&self, func: &ValueRef) -> Vec<FusibleCandidate> {
let mut candidates = Vec::new();
let pairs = self.find_fusion_candidates(func);
for (loop_a, loop_b) in &pairs {
// Check dependence legality.
if !self.check_dependence_legality(loop_a, loop_b) {
continue;
}
// Compute profitability.
let profit = self.compute_fusion_profitability(loop_a, loop_b);
candidates.push(FusibleCandidate {
loop_a: loop_a.clone(),
loop_b: loop_b.clone(),
dependence: None,
profitability: Some(profit),
});
}
candidates
}
/// Fuse two loops into one.
///
/// The fusion process:
/// 1. Move instructions from loop_b into loop_a's body
/// 2. Update PHI nodes to merge the two loops' induction variables
/// 3. Redirect edges from loop_a's exit to loop_b's exit
/// 4. Remove the now-empty loop_b
pub fn fuse_loops_with_strategy(
&mut self,
loop_a: &LoopInfo,
loop_b: &LoopInfo,
strategy: FusionStrategy,
_func: &ValueRef,
) -> bool {
match strategy {
FusionStrategy::Maximize => {
// Maximize: always fuse if legal.
if !self.check_adjacent(loop_a, loop_b) {
return false;
}
}
FusionStrategy::Minimize => {
// Minimize: only fuse if clearly profitable.
let profit = self.compute_fusion_profitability(loop_a, loop_b);
if !profit.is_profitable {
return false;
}
}
}
// In a full implementation:
// 1. LoopB's instructions are moved to the end of LoopA's body.
// 2. LoopB's header/latch are removed.
// 3. LoopA's exit edges are updated to point where LoopB's exits did.
// 4. PHI nodes in LoopA are adjusted if needed.
self.fused_count += 1;
true
}
/// Run loop fusion with a specific strategy.
pub fn run_with_strategy(&mut self, func: &ValueRef, strategy: FusionStrategy) -> usize {
self.fused_count = 0;
let candidates = self.detect_fusible_candidates(func);
for candidate in &candidates {
if let Some(ref profit) = candidate.profitability {
if !profit.is_profitable && strategy == FusionStrategy::Minimize {
continue;
}
}
self.fuse_loops_with_strategy(&candidate.loop_a, &candidate.loop_b, strategy, func);
}
self.fused_count
}
}
// ============================================================================
// Advanced Loop Fusion with Dependence Graph and Profitability
// ============================================================================
/// Dependence graph edge for loop fusion analysis.
#[derive(Debug, Clone)]
pub struct FusionDependenceEdge {
/// Source instruction index.
pub from: usize,
/// Target instruction index.
pub to: usize,
/// Type of dependence.
pub dep_type: DepType,
/// Whether this dependence prevents fusion.
pub prevents_fusion: bool,
}
impl LoopFusion {
/// Build a dependence graph between two loops to check fusion legality.
pub fn build_fusion_dependence_graph(
&self,
loop_a: &LoopInfo,
loop_b: &LoopInfo,
) -> Vec<FusionDependenceEdge> {
let mut edges = Vec::new();
let writes_a = self.collect_memory_writes(loop_a);
let reads_a = self.collect_memory_reads(loop_a);
let writes_b = self.collect_memory_writes(loop_b);
let reads_b = self.collect_memory_reads(loop_b);
// Check writes from loop_a → reads from loop_b (RAW, forward).
// Safe: loop_a's writes happen before loop_b's reads in fused loop.
for (i, wa) in writes_a.iter().enumerate() {
for (j, rb) in reads_b.iter().enumerate() {
if self.may_alias(wa, rb) {
edges.push(FusionDependenceEdge {
from: i,
to: j + writes_a.len(),
dep_type: DepType::RAW,
prevents_fusion: false,
});
}
}
}
// Check writes from loop_b → reads from loop_a (RAW, backward).
// NOT safe: loop_a would read loop_b's future write.
for (i, wb) in writes_b.iter().enumerate() {
for (j, ra) in reads_a.iter().enumerate() {
if self.may_alias(wb, ra) {
edges.push(FusionDependenceEdge {
from: i + writes_a.len(),
to: j,
dep_type: DepType::RAW,
prevents_fusion: true,
});
}
}
}
edges
}
/// Check if fusion improves cache locality.
///
/// If both loops access the same array, fusing them keeps the
/// array in cache between the two loops' accesses.
pub fn check_cache_locality_improvement(&self, loop_a: &LoopInfo, loop_b: &LoopInfo) -> bool {
let accesses_a = self.collect_all_accesses(loop_a);
let accesses_b = self.collect_all_accesses(loop_b);
let mut shared_accesses = 0;
for aa in &accesses_a {
for ab in &accesses_b {
if self.may_alias(aa, ab) {
shared_accesses += 1;
}
}
}
shared_accesses > 0
}
/// Check if fusion reduces register pressure.
///
/// Fusion can increase register pressure (more live values in
/// the combined loop body). This function estimates the impact.
pub fn estimate_register_pressure(&self, loop_a: &LoopInfo, loop_b: &LoopInfo) -> u32 {
let size_a = self.loop_body_size(loop_a);
let size_b = self.loop_body_size(loop_b);
// Heuristic: ~2 live values per instruction in a loop.
((size_a + size_b) * 2) as u32
}
/// Run fusion with the maximize strategy: fuse everything legal.
pub fn run_maximize(&mut self, func: &ValueRef) -> usize {
self.fused_count = 0;
let candidates = self.detect_fusible_candidates(func);
for candidate in &candidates {
// Build dependence graph for detailed analysis.
let edges = self.build_fusion_dependence_graph(&candidate.loop_a, &candidate.loop_b);
let any_prevents = edges.iter().any(|e| e.prevents_fusion);
if !any_prevents {
self.fuse_loops(&candidate.loop_a, &candidate.loop_b, func);
self.fused_count += 1;
}
}
self.fused_count
}
/// Run fusion with the minimize strategy: only fuse when clearly beneficial.
pub fn run_minimize(&mut self, func: &ValueRef) -> usize {
self.fused_count = 0;
let candidates = self.detect_fusible_candidates(func);
for candidate in &candidates {
// Check profitability: must improve cache locality.
if !self.check_cache_locality_improvement(&candidate.loop_a, &candidate.loop_b) {
continue;
}
// Check register pressure: must not exceed 64 registers.
let pressure = self.estimate_register_pressure(&candidate.loop_a, &candidate.loop_b);
if pressure < 64 {
self.fuse_loops(&candidate.loop_a, &candidate.loop_b, func);
self.fused_count += 1;
}
}
self.fused_count
}
}
// ============================================================================
// Tests
// ============================================================================
#[cfg(test)]
mod tests {
use super::*;
use llvm_native_core::value::valref;
fn make_loop_info(
header: ValueRef,
blocks: Vec<ValueRef>,
exits: Vec<(ValueRef, ValueRef)>,
preheader: Option<ValueRef>,
depth: u32,
) -> LoopInfo {
LoopInfo {
header,
blocks,
exits,
latch: None,
preheader,
depth,
parent_loop: None,
is_simplified: false,
trip_count: Some(10),
}
}
#[test]
fn test_loop_fusion_new() {
let fusion = LoopFusion::new();
assert_eq!(fusion.fused_count, 0);
assert_eq!(fusion.max_loop_size, 500);
assert!(!fusion.aggressive);
}
#[test]
fn test_default() {
let fusion = LoopFusion::default();
assert_eq!(fusion.max_loop_size, 500);
}
#[test]
fn test_same_trip_count() {
let fusion = LoopFusion::new();
let bb = valref(
llvm_native_core::value::Value::new(llvm_native_core::types::Type::label())
.with_subclass(SubclassKind::BasicBlock),
);
let a = LoopInfo {
header: bb.clone(),
blocks: vec![bb.clone()],
exits: Vec::new(),
latch: None,
preheader: None,
depth: 0,
parent_loop: None,
is_simplified: false,
trip_count: Some(10),
};
let b = LoopInfo {
header: bb.clone(),
blocks: vec![bb.clone()],
exits: Vec::new(),
latch: None,
preheader: None,
depth: 0,
parent_loop: None,
is_simplified: false,
trip_count: Some(10),
};
assert!(fusion.same_trip_count(&a, &b));
}
#[test]
fn test_different_trip_count() {
let fusion = LoopFusion::new();
let bb = valref(
llvm_native_core::value::Value::new(llvm_native_core::types::Type::label())
.with_subclass(SubclassKind::BasicBlock),
);
let a = LoopInfo {
header: bb.clone(),
blocks: vec![bb.clone()],
exits: Vec::new(),
latch: None,
preheader: None,
depth: 0,
parent_loop: None,
is_simplified: false,
trip_count: Some(10),
};
let b = LoopInfo {
header: bb.clone(),
blocks: vec![bb.clone()],
exits: Vec::new(),
latch: None,
preheader: None,
depth: 0,
parent_loop: None,
is_simplified: false,
trip_count: Some(20),
};
assert!(!fusion.same_trip_count(&a, &b));
}
#[test]
fn test_loop_body_size_empty() {
let fusion = LoopFusion::new();
let bb = valref(
llvm_native_core::value::Value::new(llvm_native_core::types::Type::label())
.with_subclass(SubclassKind::BasicBlock),
);
let info = make_loop_info(bb.clone(), vec![bb], Vec::new(), None, 0);
assert_eq!(fusion.loop_body_size(&info), 0);
}
#[test]
fn test_find_candidates_no_loops() {
let fusion = LoopFusion::new();
let func = valref(
llvm_native_core::value::Value::new(llvm_native_core::types::Type::void())
.with_subclass(SubclassKind::Function),
);
let candidates = fusion.find_fusion_candidates(&func);
assert!(candidates.is_empty());
}
#[test]
fn test_is_profitable_small_loops() {
let fusion = LoopFusion::new();
let bb = valref(
llvm_native_core::value::Value::new(llvm_native_core::types::Type::label())
.with_subclass(SubclassKind::BasicBlock),
);
let a = make_loop_info(bb.clone(), vec![bb.clone()], Vec::new(), None, 0);
let b = make_loop_info(bb.clone(), vec![bb], Vec::new(), None, 0);
assert!(fusion.is_profitable(&a, &b));
}
#[test]
fn test_may_alias_different_allocas() {
let fusion = LoopFusion::new();
let alloca_a = valref(
llvm_native_core::value::Value::new(llvm_native_core::types::Type::i32())
.with_subclass(SubclassKind::AllocaInst)
.named("a"),
);
alloca_a.borrow_mut().opcode = Some(Opcode::Alloca);
let alloca_b = valref(
llvm_native_core::value::Value::new(llvm_native_core::types::Type::i32())
.with_subclass(SubclassKind::AllocaInst)
.named("b"),
);
alloca_b.borrow_mut().opcode = Some(Opcode::Alloca);
// For stores: operands[0] = value, operands[1] = pointer
// For may_alias to detect different allocas, the pointer must be at index 1
let store_a = valref(
llvm_native_core::value::Value::new(llvm_native_core::types::Type::void())
.with_subclass(SubclassKind::Instruction),
);
store_a.borrow_mut().opcode = Some(Opcode::Store);
store_a
.borrow_mut()
.operands
.push(valref(llvm_native_core::value::Value::new(llvm_native_core::types::Type::i32()))); // value operand
store_a.borrow_mut().operands.push(alloca_a); // pointer operand at index 1
store_a.borrow_mut().num_operands = 2;
let store_b = valref(
llvm_native_core::value::Value::new(llvm_native_core::types::Type::void())
.with_subclass(SubclassKind::Instruction),
);
store_b.borrow_mut().opcode = Some(Opcode::Store);
store_b
.borrow_mut()
.operands
.push(valref(llvm_native_core::value::Value::new(llvm_native_core::types::Type::i32()))); // value operand
store_b.borrow_mut().operands.push(alloca_b); // pointer operand at index 1
store_b.borrow_mut().num_operands = 2;
// Different allocas — may not alias
assert!(!fusion.may_alias(&store_a, &store_b));
}
#[test]
fn test_check_dependence_no_mem_ops() {
let fusion = LoopFusion::new();
let bb = valref(
llvm_native_core::value::Value::new(llvm_native_core::types::Type::label())
.with_subclass(SubclassKind::BasicBlock),
);
let a = make_loop_info(bb.clone(), vec![bb.clone()], Vec::new(), None, 0);
let b = make_loop_info(bb.clone(), vec![bb], Vec::new(), None, 0);
// No memory ops → no dependence
assert!(fusion.check_dependence(&a, &b));
}
#[test]
fn test_run_on_simple_function() {
let mut fusion = LoopFusion::new();
let bb = valref(
llvm_native_core::value::Value::new(llvm_native_core::types::Type::label())
.with_subclass(SubclassKind::BasicBlock),
);
let func = valref(
llvm_native_core::value::Value::new(llvm_native_core::types::Type::void())
.with_subclass(SubclassKind::Function),
);
func.borrow_mut().operands.push(bb);
let count = fusion.run_on_function(&func);
// No loops to fuse in this simple function
assert!(count >= 0);
}
#[test]
fn test_aggressive_flag() {
let mut fusion = LoopFusion::new();
assert!(!fusion.aggressive);
fusion.aggressive = true;
assert!(fusion.aggressive);
}
}
use std::rc::Rc;