vyre-lower 0.6.2

Substrate-neutral lowering: vyre Program → KernelDescriptor consumed by vyre-emit-* crates.
Documentation
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
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
//! Loop-invariant code motion.
//!
//! Source-of-truth: `PERF_ROADMAP_2026-05-01.md` section A item A17.
//!
//! For each `StructuredForLoop` in the kernel body, walk the loop body
//! and identify ops whose operand chain doesn't depend on the loop
//! variable. Hoist them out of the loop body into the parent body
//! immediately before the loop op.
//!
//! Hoisted ops are assigned fresh parent-body ids, loop-body operands
//! are rewritten to those fresh ids, and child literal-pool references
//! are merged into the parent literal pool. That keeps the per-body id
//! invariant intact while still removing pure loop-invariant work from
//! hot loop bodies.

use rustc_hash::FxHashSet;
use std::collections::BTreeMap;

use super::dataflow_facts::resolve_reaching_def_id as resolve;
use super::memory_address::{
    locations_may_alias, AddressKey, MemoryLocation, MemoryTarget, SlotAliasPolicy,
};
use crate::operand_semantics::operand_is_result_reference;
use crate::{BindingVisibility, KernelBody, KernelDescriptor, KernelOp, KernelOpKind};

/// LICM with a correct cross-body id rewrite.
///
/// For each loop, invariant ops are moved to the parent body before
/// the loop op. Hoisted ops receive fresh result ids that do not
/// collide with any parent-body id. Operand references inside the
/// remaining loop body are rewritten to use the new ids. Literal
/// pool entries referenced by hoisted `Literal` ops are merged into
/// the parent body's literal pool.
#[must_use]
pub fn licm(desc: &KernelDescriptor) -> KernelDescriptor {
    licm_with_optional_dataflow_facts(desc, None, None)
}

#[must_use]
pub fn licm_with_alias_facts(
    desc: &KernelDescriptor,
    alias_facts: &crate::analyses::alias_facts::AliasFactSet,
) -> KernelDescriptor {
    licm_with_optional_dataflow_facts(desc, Some(alias_facts), None)
}

#[must_use]
pub fn licm_with_weir_alias_facts(
    desc: &KernelDescriptor,
    alias_facts: &crate::analyses::weir_alias::AliasFactSet,
) -> KernelDescriptor {
    licm_with_alias_facts(desc, alias_facts)
}

#[must_use]
pub fn licm_with_dataflow_facts(
    desc: &KernelDescriptor,
    alias_facts: &crate::analyses::alias_facts::AliasFactSet,
    reaching_defs: &crate::analyses::reaching_def_facts::ReachingDefFactSet,
) -> KernelDescriptor {
    licm_with_optional_dataflow_facts(desc, Some(alias_facts), Some(reaching_defs))
}

#[must_use]
pub fn licm_with_dataflow_analysis_facts(
    desc: &KernelDescriptor,
    alias_facts: &crate::analyses::weir_alias::AliasFactSet,
    reaching_defs: &crate::analyses::weir_reaching_def::ReachingDefFactSet,
) -> KernelDescriptor {
    licm_with_dataflow_facts(desc, alias_facts, reaching_defs)
}

fn licm_with_optional_dataflow_facts(
    desc: &KernelDescriptor,
    alias_facts: Option<&crate::analyses::alias_facts::AliasFactSet>,
    reaching_defs: Option<&crate::analyses::reaching_def_facts::ReachingDefFactSet>,
) -> KernelDescriptor {
    let mut out = desc.clone();
    let read_only_bindings = desc
        .bindings
        .slots
        .iter()
        .filter(|slot| matches!(slot.visibility, BindingVisibility::ReadOnly))
        .map(|slot| slot.slot)
        .collect::<FxHashSet<_>>();
    // Compute the global next-free-id ONCE from the entire descriptor
    // and thread it through every recursive `licm_body` call. Without
    // this, each recursive call computed its own `next_free_id` from
    // its local body's tree, and two sibling recursions (e.g. inner
    // loops in different branches of an outer if) would independently
    // pick the SAME fresh id for their hoisted ops, producing
    // duplicate-result-id collisions that the cleanup pipeline carried
    // forward into emit. Discovered via off-by-one in
    // `loop_carry_smoke::region_body_let_bind_with_inner_loop_increment_then_store`
    // where a hoisted U32(1) literal in the outer-if body collided with
    // a Bool(true) literal hoisted in a nested if's body.
    let mut next_free_id = max_result_id(&out.body)
        .map(|m| m.wrapping_add(1))
        .unwrap_or(0);
    out.body = licm_body(
        &out.body,
        &mut next_free_id,
        &read_only_bindings,
        alias_facts,
        reaching_defs,
    );
    out
}

fn max_result_id(body: &KernelBody) -> Option<u32> {
    let mut max: Option<u32> = None;
    fn walk(b: &KernelBody, max: &mut Option<u32>) {
        for op in &b.ops {
            for r in op.result_ids() {
                *max = Some(max.map_or(r, |m| m.max(r)));
            }
        }
        for child in &b.child_bodies {
            walk(child, max);
        }
    }
    walk(body, &mut max);
    max
}

fn licm_body(
    body: &KernelBody,
    next_free_id: &mut u32,
    read_only_bindings: &FxHashSet<u32>,
    alias_facts: Option<&crate::analyses::alias_facts::AliasFactSet>,
    reaching_defs: Option<&crate::analyses::reaching_def_facts::ReachingDefFactSet>,
) -> KernelBody {
    let mut new_ops = Vec::with_capacity(body.ops.len());
    let mut new_children = body.child_bodies.clone();
    let mut new_literals = body.literals.clone();
    // Soundness: when a hoisted op produces a result, ALL downstream
    // operands in the SAME parent body that referenced the original
    // (loop-body) id need to point at the new parent-body id. Without
    // this, a `StoreGlobal` (or any op) appearing after the loop in
    // the parent body keeps referencing the dead loop-body id and
    // descriptor verify rejects with `DanglingResultRef`.
    //
    // Note that `remap_body_ids` already rewrites the LOOP body and
    // any ops we push AFTER the loop op need this same treatment in
    // the parent  -  that's what `parent_id_map` captures.
    let mut parent_id_map = BTreeMap::<u32, u32>::new();

    for op in &body.ops {
        if let KernelOpKind::StructuredForLoop { .. } = &op.kind {
            // Find the body child id (operand 2 per descriptor contract).
            if let Some(body_idx) = op.operands.get(2).copied() {
                if let Some(child) = body.child_bodies.get(body_idx as usize).cloned() {
                    // Hoist invariant ops from the child body.
                    let (hoisted, remaining) =
                        hoist_invariants(&child, read_only_bindings, alias_facts, reaching_defs);
                    if !hoisted.is_empty() {
                        // 1. Allocate fresh parent-body ids for every
                        //    hoisted result so we never collide.
                        let mut id_map = BTreeMap::<u32, u32>::new();
                        for h_op in &hoisted {
                            if let Some(r) = h_op.result {
                                id_map.insert(r, *next_free_id);
                                *next_free_id = next_free_id.wrapping_add(1);
                            }
                        }

                        // 2. Merge literals referenced by hoisted ops
                        //    into the parent literal pool and build a
                        //    child-index → parent-index map.
                        let mut lit_map = BTreeMap::<u32, u32>::new();
                        let mut renumbered_hoisted = Vec::with_capacity(hoisted.len());
                        for mut h_op in hoisted {
                            if matches!(h_op.kind, KernelOpKind::Literal) {
                                if let Some(&old_idx) = h_op.operands.first() {
                                    // Soundness: skip the rewrite when
                                    // the source literal is missing.
                                    // Previously the captured `idx` was
                                    // committed to `lit_map` even when
                                    // the conditional `push` was a no-op,
                                    // so the rewritten Literal op pointed
                                    // at a pool slot that was never
                                    // populated → `LiteralPoolOutOfRange`
                                    // at descriptor verify time.
                                    if let Some(val) = child.literals.get(old_idx as usize) {
                                        let new_idx =
                                            *lit_map.entry(old_idx).or_insert_with(|| {
                                                let idx = new_literals.len() as u32;
                                                new_literals.push(val.clone());
                                                idx
                                            });
                                        h_op.operands[0] = new_idx;
                                    }
                                    // When the source literal is missing
                                    // we leave the operand alone  -  the
                                    // op was already invalid in the
                                    // source body; LICM does not have to
                                    // fabricate a slot for it.
                                }
                            }
                            // Rewrite result-id refs inside the hoisted op.
                            h_op.operands = h_op
                                .operands
                                .iter()
                                .enumerate()
                                .map(|(pos, val)| {
                                    if operand_is_result_reference(&h_op.kind, pos) {
                                        *id_map.get(val).unwrap_or(val)
                                    } else {
                                        *val
                                    }
                                })
                                .collect();
                            h_op.result = h_op.result.map(|r| *id_map.get(&r).unwrap_or(&r));
                            renumbered_hoisted.push(h_op);
                        }

                        // 3. Recurse into the remaining body, then remap
                        //    any references to the old hoisted ids so the
                        //    child body still points at the parent results.
                        let recursed = licm_body(
                            &remaining,
                            next_free_id,
                            read_only_bindings,
                            alias_facts,
                            reaching_defs,
                        );
                        let remapped = remap_body_ids(&recursed, &id_map);

                        new_children[body_idx as usize] = remapped;
                        new_ops.extend(renumbered_hoisted);
                        new_ops.push(op.clone());
                        // Carry the id remap forward so any parent-body
                        // op AFTER this loop that referenced the old
                        // (now-hoisted) child id picks up the new
                        // parent-body result id. Without this, the
                        // post-loop reader (e.g. a `StoreGlobal`
                        // consuming the loop accumulator) would point
                        // at a result id that no longer exists in the
                        // descriptor → `DanglingResultRef` at verify.
                        for (&old, &new) in id_map.iter() {
                            parent_id_map.insert(old, new);
                        }
                        continue;
                    }
                    // No invariants to hoist  -  just recurse into child.
                    let recursed = licm_body(
                        &remaining,
                        next_free_id,
                        read_only_bindings,
                        alias_facts,
                        reaching_defs,
                    );
                    new_children[body_idx as usize] = recursed;
                    new_ops.push(op.clone());
                    continue;
                }
            }
        }
        // Recurse into other structured-control-flow children too.
        match &op.kind {
            KernelOpKind::StructuredIfThen
            | KernelOpKind::StructuredIfThenElse
            | KernelOpKind::StructuredBlock
            | KernelOpKind::Region { .. } => {
                for child_id in op.operands.iter() {
                    if let Some(child) = body.child_bodies.get(*child_id as usize) {
                        let recursed = licm_body(
                            child,
                            next_free_id,
                            read_only_bindings,
                            alias_facts,
                            reaching_defs,
                        );
                        new_children[*child_id as usize] = recursed;
                    }
                }
            }
            _ => {}
        }
        // Apply the accumulated parent_id_map to this op's
        // result-reference operands before pushing it. This rewrites
        // post-loop readers to point at the new parent-body result
        // ids that LICM created when it hoisted invariants out of an
        // earlier loop in this same parent body.
        let mut rewritten = op.clone();
        if !parent_id_map.is_empty() {
            for (pos, val) in rewritten.operands.iter_mut().enumerate() {
                if operand_is_result_reference(&op.kind, pos) {
                    if let Some(&new) = parent_id_map.get(val) {
                        *val = new;
                    }
                }
            }
        }
        new_ops.push(rewritten);
    }

    // Recurse into all OTHER children (those not touched above) so
    // nested loops in non-StructuredForLoop children also get LICM'd.
    let final_children: Vec<KernelBody> = new_children
        .into_iter()
        .map(|c| {
            licm_body(
                &c,
                next_free_id,
                read_only_bindings,
                alias_facts,
                reaching_defs,
            )
        })
        .collect();

    KernelBody {
        ops: new_ops,
        child_bodies: final_children,
        literals: new_literals,
    }
}

/// Recursively apply `id_map` to every result-reference operand in
/// `body` and all nested child bodies. Result ids of ops themselves
/// are left unchanged  -  only operand refs are rewritten.
fn remap_body_ids(body: &KernelBody, id_map: &BTreeMap<u32, u32>) -> KernelBody {
    let new_ops: Vec<KernelOp> = body
        .ops
        .iter()
        .map(|op| {
            let new_operands: Vec<u32> = op
                .operands
                .iter()
                .enumerate()
                .map(|(pos, val)| {
                    if operand_is_result_reference(&op.kind, pos) {
                        *id_map.get(val).unwrap_or(val)
                    } else {
                        *val
                    }
                })
                .collect();
            KernelOp {
                kind: op.kind.clone(),
                operands: new_operands,
                result: op.result.map(|r| *id_map.get(&r).unwrap_or(&r)),
            }
        })
        .collect();
    let new_children: Vec<KernelBody> = body
        .child_bodies
        .iter()
        .map(|c| remap_body_ids(c, id_map))
        .collect();
    KernelBody {
        ops: new_ops,
        child_bodies: new_children,
        literals: body.literals.clone(),
    }
}

/// Split a loop body into (invariant_ops_to_hoist, loop_dependent_ops).
/// Invariants don't depend (transitively) on any value produced inside
/// the body, and have no side effects.
fn hoist_invariants(
    body: &KernelBody,
    read_only_bindings: &FxHashSet<u32>,
    alias_facts: Option<&crate::analyses::alias_facts::AliasFactSet>,
    reaching_defs: Option<&crate::analyses::reaching_def_facts::ReachingDefFactSet>,
) -> (Vec<KernelOp>, KernelBody) {
    // Phase-1 conservative rule: an op is loop-dependent if any of its
    // result-id-position operands references a result-id produced
    // earlier in this body. The loop variable doesn't have a result-id
    // (it's implicit) so we treat ANY operand whose value is produced
    // inside the body as loop-dependent.
    // Include result ids produced by descendant child bodies. Hoisting
    // an op that references a child-body-local id (e.g. a phi-Select
    // after a StructuredIfThen) would dangle the reference outside the
    // loop. Top-level straight-line ids are handled by `dependent_ids`
    // below so invariant chains can hoist as a batch.
    fn collect_descendant_ids(body: &KernelBody, out: &mut FxHashSet<u32>) {
        for child in &body.child_bodies {
            for op in &child.ops {
                for r in op.result_ids() {
                    out.insert(r);
                }
            }
            collect_descendant_ids(child, out);
        }
    }
    let mut descendant_ids: FxHashSet<u32> = FxHashSet::default();
    collect_descendant_ids(body, &mut descendant_ids);
    let mut dependent_ids = FxHashSet::<u32>::default();

    let mut invariants = Vec::new();
    let mut remaining_ops = Vec::new();

    for op in &body.ops {
        if !is_hoistable(op, body, read_only_bindings, alias_facts, reaching_defs) {
            // Side effects → never hoist.
            dependent_ids.extend(op.result_ids());
            remaining_ops.push(op.clone());
            continue;
        }
        let depends = op.operands.iter().enumerate().any(|(pos, val)| {
            operand_is_result_reference(&op.kind, pos)
                && (dependent_ids.contains(val) || descendant_ids.contains(val))
        });
        if !depends {
            // Op is invariant. Hoist.
            invariants.push(op.clone());
            // Its result-id is now produced OUTSIDE the loop body, so
            // it's NOT in the dependent set.
        } else {
            // Loop-dependent.
            dependent_ids.extend(op.result_ids());
            remaining_ops.push(op.clone());
        }
    }

    let new_body = KernelBody {
        ops: remaining_ops,
        child_bodies: body.child_bodies.clone(),
        literals: body.literals.clone(),
    };
    (invariants, new_body)
}

fn is_hoistable(
    op: &KernelOp,
    body: &KernelBody,
    read_only_bindings: &FxHashSet<u32>,
    alias_facts: Option<&crate::analyses::alias_facts::AliasFactSet>,
    reaching_defs: Option<&crate::analyses::reaching_def_facts::ReachingDefFactSet>,
) -> bool {
    if is_pure(&op.kind) {
        return true;
    }
    match op.kind {
        KernelOpKind::LoadConstant => true,
        KernelOpKind::LoadGlobal | KernelOpKind::LoadShared => {
            load_is_loop_invariant_memory(op, body, read_only_bindings, alias_facts, reaching_defs)
        }
        _ => false,
    }
}

fn load_is_loop_invariant_memory(
    load: &KernelOp,
    body: &KernelBody,
    read_only_bindings: &FxHashSet<u32>,
    alias_facts: Option<&crate::analyses::alias_facts::AliasFactSet>,
    reaching_defs: Option<&crate::analyses::reaching_def_facts::ReachingDefFactSet>,
) -> bool {
    if !body.child_bodies.is_empty() || load.operands.len() < 2 {
        return false;
    }
    let load_slot = load.operands[0];
    let load_index = resolve(load.operands[1], reaching_defs);
    let load_target = match load.kind {
        KernelOpKind::LoadGlobal => MemoryTarget::global(load_slot),
        KernelOpKind::LoadShared => MemoryTarget::shared(load_slot),
        _ => return false,
    };
    if matches!(load.kind, KernelOpKind::LoadGlobal) {
        let is_read_only = read_only_bindings.contains(&load_slot);
        let has_alias_facts = alias_facts.is_some();
        let has_reaching_defs = reaching_defs.is_some();
        // Conservative path: read-only slot + alias facts → safe.
        // Dataflow path: reaching-defs + alias facts → safe
        // (external facts can prove non-aliasing even on ReadWrite slots).
        // Otherwise: reject the hoist.
        if !(is_read_only && has_alias_facts) && !(has_reaching_defs && has_alias_facts) {
            return false;
        }
    }
    body.ops.iter().all(|candidate| {
        let writes_same_space = matches!(
            (&load.kind, &candidate.kind),
            (KernelOpKind::LoadGlobal, KernelOpKind::StoreGlobal)
                | (KernelOpKind::LoadShared, KernelOpKind::StoreShared)
                | (KernelOpKind::LoadGlobal, KernelOpKind::Atomic { .. })
        );
        if !writes_same_space {
            return !matches!(
                candidate.kind,
                KernelOpKind::Barrier { .. }
                    | KernelOpKind::AsyncLoad { .. }
                    | KernelOpKind::AsyncStore { .. }
                    | KernelOpKind::AsyncWait { .. }
                    | KernelOpKind::Call { .. }
                    | KernelOpKind::OpaqueExpr(..)
                    | KernelOpKind::OpaqueNode(..)
                    | KernelOpKind::Trap { .. }
                    | KernelOpKind::Resume { .. }
                    | KernelOpKind::Return
            );
        }
        if candidate.operands.len() < 2 {
            return false;
        }
        let store_slot = candidate.operands[0];
        let store_index = resolve(candidate.operands[1], reaching_defs);
        let store_target = match candidate.kind {
            KernelOpKind::StoreGlobal | KernelOpKind::Atomic { .. } => {
                MemoryTarget::global(store_slot)
            }
            KernelOpKind::StoreShared => MemoryTarget::shared(store_slot),
            _ => return false,
        };
        !locations_may_alias(
            MemoryLocation::new(load_target, load_index, AddressKey::Result(load_index)),
            MemoryLocation::new(store_target, store_index, AddressKey::Result(store_index)),
            alias_facts,
            SlotAliasPolicy::DistinctSlotsMayAlias,
        )
    })
}

fn is_pure(kind: &KernelOpKind) -> bool {
    !matches!(
        kind,
        KernelOpKind::StoreGlobal
            | KernelOpKind::StoreShared
            | KernelOpKind::Barrier { .. }
            | KernelOpKind::Atomic { .. }
            | KernelOpKind::AsyncLoad { .. }
            | KernelOpKind::AsyncStore { .. }
            | KernelOpKind::AsyncWait { .. }
            | KernelOpKind::Trap { .. }
            | KernelOpKind::Resume { .. }
            | KernelOpKind::IndirectDispatch { .. }
            | KernelOpKind::Return
            | KernelOpKind::StructuredIfThen
            | KernelOpKind::StructuredIfThenElse
            | KernelOpKind::StructuredForLoop { .. }
            | KernelOpKind::StructuredBlock
            | KernelOpKind::Region { .. }
            | KernelOpKind::Call { .. }
            | KernelOpKind::OpaqueExpr(..)
            | KernelOpKind::OpaqueNode(..)
            // Loop induction variable is not invariant.
            | KernelOpKind::LoopIndex { .. }
            | KernelOpKind::LoopCarrierInit { .. }
            | KernelOpKind::LoopCarrier { .. }
            | KernelOpKind::LoopCarrierEnd { .. }
            // Loads aren't safely hoistable  -  the underlying buffer
            // could be written by another thread between iterations.
            | KernelOpKind::LoadGlobal
            | KernelOpKind::LoadShared
            | KernelOpKind::LoadConstant
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        BindingLayout, Dispatch, KernelBody, KernelDescriptor, KernelOp, KernelOpKind, LiteralValue,
    };
    use vyre_foundation::ir::BinOp;

    fn empty_kernel_with_loop(loop_body: KernelBody) -> KernelDescriptor {
        KernelDescriptor {
            id: "loopy".into(),
            bindings: BindingLayout { slots: vec![] },
            dispatch: Dispatch::new(64, 1, 1),
            body: KernelBody {
                ops: vec![
                    KernelOp {
                        kind: KernelOpKind::Literal,
                        operands: vec![0],
                        result: Some(0),
                    },
                    KernelOp {
                        kind: KernelOpKind::Literal,
                        operands: vec![1],
                        result: Some(1),
                    },
                    KernelOp {
                        kind: KernelOpKind::StructuredForLoop {
                            loop_var: "i".into(),
                        },
                        operands: vec![0, 1, 0],
                        result: None,
                    },
                ],
                child_bodies: vec![loop_body],
                literals: vec![LiteralValue::U32(0), LiteralValue::U32(64)],
            },
        }
    }

    #[test]
    fn licm_on_empty_kernel_is_noop() {
        let desc = KernelDescriptor {
            id: "k".into(),
            bindings: BindingLayout { slots: vec![] },
            dispatch: Dispatch::new(1, 1, 1),
            body: KernelBody {
                ops: vec![],
                child_bodies: vec![],
                literals: vec![],
            },
        };
        let out = licm(&desc);
        assert!(out.body.ops.is_empty());
    }

    #[test]
    fn licm_kernel_with_no_loop_is_noop() {
        let desc = KernelDescriptor {
            id: "k".into(),
            bindings: BindingLayout { slots: vec![] },
            dispatch: Dispatch::new(1, 1, 1),
            body: KernelBody {
                ops: vec![
                    KernelOp {
                        kind: KernelOpKind::Literal,
                        operands: vec![0],
                        result: Some(0),
                    },
                    KernelOp {
                        kind: KernelOpKind::Literal,
                        operands: vec![1],
                        result: Some(1),
                    },
                    KernelOp {
                        kind: KernelOpKind::BinOpKind(BinOp::Add),
                        operands: vec![0, 1],
                        result: Some(2),
                    },
                ],
                child_bodies: vec![],
                literals: vec![LiteralValue::U32(3), LiteralValue::U32(4)],
            },
        };
        let out = licm(&desc);
        assert_eq!(out.body.ops.len(), 3);
    }

    #[test]
    fn licm_hoists_constant_out_of_loop() {
        // for i in 0..64 { lit(99); /* nothing else */ }
        // The Literal in the loop body has no operand dependencies; it's
        // a constant, hoistable.
        let desc = empty_kernel_with_loop(KernelBody {
            ops: vec![KernelOp {
                kind: KernelOpKind::Literal,
                operands: vec![0],
                result: Some(2),
            }],
            child_bodies: vec![],
            literals: vec![LiteralValue::U32(99)],
        });
        let out = licm(&desc);
        // Outer body started with 3 ops. After LICM, the hoisted Literal
        // appears before the StructuredForLoop, making it 4.
        assert_eq!(out.body.ops.len(), 4);
        // Hoisted Literal is at position 2 (before the loop op which is now at 3).
        assert!(matches!(out.body.ops[2].kind, KernelOpKind::Literal));
        assert!(matches!(
            out.body.ops[3].kind,
            KernelOpKind::StructuredForLoop { .. }
        ));
        // Loop body should now be empty (the hoisted op moved out).
        let loop_body = out.body.child_bodies[0].clone();
        assert!(loop_body.ops.is_empty());
    }

    #[test]
    fn licm_hoists_straight_line_invariant_chain() {
        // Loop body: lit(5) (invariant); add(lit, lit) (invariant);
        // The Add uses earlier ops from the same invariant chain, so
        // LICM hoists the whole straight-line chain as one batch.
        let desc = empty_kernel_with_loop(KernelBody {
            ops: vec![
                KernelOp {
                    kind: KernelOpKind::Literal,
                    operands: vec![0],
                    result: Some(10),
                },
                KernelOp {
                    kind: KernelOpKind::Literal,
                    operands: vec![1],
                    result: Some(11),
                },
                // This Add USES the prior Literals  -  but those are now
                // hoisted, so the Add itself can also be hoisted.
                KernelOp {
                    kind: KernelOpKind::BinOpKind(BinOp::Add),
                    operands: vec![10, 11],
                    result: Some(12),
                },
            ],
            child_bodies: vec![],
            literals: vec![LiteralValue::U32(5), LiteralValue::U32(7)],
        });
        let out = licm(&desc);
        // After: outer ops = init lits (0,1) + 3 hoisted ops + loop op.
        assert_eq!(out.body.ops.len(), 6);
        let loop_body = &out.body.child_bodies[0];
        assert!(loop_body.ops.is_empty());
        assert!(matches!(
            out.body.ops[4].kind,
            KernelOpKind::BinOpKind(BinOp::Add)
        ));
    }

    #[test]
    fn licm_does_not_hoist_load() {
        // Loads are unsafely hoistable (other threads may write between
        // iterations). Phase 1 forbids hoisting all loads.
        use crate::{BindingSlot, BindingVisibility, MemoryClass};
        use vyre_foundation::ir::DataType;
        let desc = KernelDescriptor {
            id: "load_loop".into(),
            bindings: BindingLayout {
                slots: vec![BindingSlot {
                    slot: 0,
                    element_type: DataType::U32,
                    element_count: None,
                    memory_class: MemoryClass::Global,
                    visibility: BindingVisibility::ReadOnly,
                    name: "buf".into(),
                }],
            },
            dispatch: Dispatch::new(64, 1, 1),
            body: KernelBody {
                ops: vec![
                    KernelOp {
                        kind: KernelOpKind::Literal,
                        operands: vec![0],
                        result: Some(0),
                    },
                    KernelOp {
                        kind: KernelOpKind::Literal,
                        operands: vec![1],
                        result: Some(1),
                    },
                    KernelOp {
                        kind: KernelOpKind::StructuredForLoop {
                            loop_var: "i".into(),
                        },
                        operands: vec![0, 1, 0],
                        result: None,
                    },
                ],
                child_bodies: vec![KernelBody {
                    ops: vec![
                        KernelOp {
                            kind: KernelOpKind::Literal,
                            operands: vec![0],
                            result: Some(10),
                        },
                        // LoadGlobal  -  should NOT hoist.
                        KernelOp {
                            kind: KernelOpKind::LoadGlobal,
                            operands: vec![0, 10],
                            result: Some(11),
                        },
                    ],
                    child_bodies: vec![],
                    literals: vec![LiteralValue::U32(0)],
                }],
                literals: vec![LiteralValue::U32(0), LiteralValue::U32(8)],
            },
        };
        let out = licm(&desc);
        // The Literal hoists; the Load stays.
        let loop_body = &out.body.child_bodies[0];
        let has_load = loop_body
            .ops
            .iter()
            .any(|o| matches!(o.kind, KernelOpKind::LoadGlobal));
        assert!(has_load, "Load must stay inside the loop");
    }

    #[test]
    fn alias_aware_licm_hoists_read_only_loop_invariant_load() {
        use crate::{BindingSlot, BindingVisibility, MemoryClass};
        use vyre_foundation::ir::DataType;
        let desc = KernelDescriptor {
            id: "alias_readonly_load_loop".into(),
            bindings: BindingLayout {
                slots: vec![BindingSlot {
                    slot: 0,
                    element_type: DataType::U32,
                    element_count: None,
                    memory_class: MemoryClass::Global,
                    visibility: BindingVisibility::ReadOnly,
                    name: "buf".into(),
                }],
            },
            dispatch: Dispatch::new(64, 1, 1),
            body: KernelBody {
                ops: vec![
                    KernelOp {
                        kind: KernelOpKind::Literal,
                        operands: vec![0],
                        result: Some(0),
                    },
                    KernelOp {
                        kind: KernelOpKind::Literal,
                        operands: vec![1],
                        result: Some(1),
                    },
                    KernelOp {
                        kind: KernelOpKind::StructuredForLoop {
                            loop_var: "i".into(),
                        },
                        operands: vec![0, 1, 0],
                        result: None,
                    },
                ],
                child_bodies: vec![KernelBody {
                    ops: vec![
                        KernelOp {
                            kind: KernelOpKind::Literal,
                            operands: vec![0],
                            result: Some(10),
                        },
                        KernelOp {
                            kind: KernelOpKind::LoadGlobal,
                            operands: vec![0, 10],
                            result: Some(11),
                        },
                    ],
                    child_bodies: vec![],
                    literals: vec![LiteralValue::U32(0)],
                }],
                literals: vec![LiteralValue::U32(0), LiteralValue::U32(8)],
            },
        };
        let facts = crate::analyses::alias_facts::AliasFactSet::default();
        let out = licm_with_alias_facts(&desc, &facts);
        let loop_body = &out.body.child_bodies[0];
        assert!(
            !loop_body
                .ops
                .iter()
                .any(|op| matches!(op.kind, KernelOpKind::LoadGlobal)),
            "read-only loop-invariant load should hoist through fact-aware LICM"
        );
    }

    #[test]
    fn different_binding_store_blocks_licm_load_hoist_without_external_no_alias_fact() {
        use crate::{BindingSlot, BindingVisibility, MemoryClass};
        use vyre_foundation::ir::DataType;
        let desc = KernelDescriptor {
            id: "licm_cross_binding_alias_conservative".into(),
            bindings: BindingLayout {
                slots: vec![
                    BindingSlot {
                        slot: 0,
                        element_type: DataType::U32,
                        element_count: None,
                        memory_class: MemoryClass::Global,
                        visibility: BindingVisibility::ReadOnly,
                        name: "input".into(),
                    },
                    BindingSlot {
                        slot: 1,
                        element_type: DataType::U32,
                        element_count: None,
                        memory_class: MemoryClass::Global,
                        visibility: BindingVisibility::ReadWrite,
                        name: "scratch".into(),
                    },
                ],
            },
            dispatch: Dispatch::new(64, 1, 1),
            body: KernelBody {
                ops: vec![
                    KernelOp {
                        kind: KernelOpKind::Literal,
                        operands: vec![0],
                        result: Some(0),
                    },
                    KernelOp {
                        kind: KernelOpKind::Literal,
                        operands: vec![1],
                        result: Some(1),
                    },
                    KernelOp {
                        kind: KernelOpKind::StructuredForLoop {
                            loop_var: "i".into(),
                        },
                        operands: vec![0, 1, 0],
                        result: None,
                    },
                ],
                child_bodies: vec![KernelBody {
                    ops: vec![
                        KernelOp {
                            kind: KernelOpKind::LoadGlobal,
                            operands: vec![0, 0],
                            result: Some(10),
                        },
                        KernelOp {
                            kind: KernelOpKind::StoreGlobal,
                            operands: vec![1, 1, 10],
                            result: None,
                        },
                    ],
                    child_bodies: vec![],
                    literals: vec![],
                }],
                literals: vec![LiteralValue::U32(0), LiteralValue::U32(64)],
            },
        };

        let conservative = licm(&desc);
        assert!(
            conservative.body.child_bodies[0]
                .ops
                .iter()
                .any(|op| matches!(op.kind, KernelOpKind::LoadGlobal)),
            "cross-binding stores may alias the load without an external proof, so LICM must keep the load in-loop"
        );

        let mut facts = crate::analyses::alias_facts::AliasFactSet::default();
        facts.insert_no_alias(crate::analyses::alias_facts::NoAliasFact {
            left_binding: 0,
            left_index: 0,
            right_binding: 1,
            right_index: 1,
        });
        let alias_aware = licm_with_alias_facts(&desc, &facts);
        assert!(
            !alias_aware.body.child_bodies[0]
                .ops
                .iter()
                .any(|op| matches!(op.kind, KernelOpKind::LoadGlobal)),
            "external no-alias proof should recover cross-binding LICM load hoisting"
        );
    }

    #[test]
    fn licm_does_not_hoist_store() {
        // Stores are side-effecting. Hoisting changes semantics.
        use crate::{BindingSlot, BindingVisibility, MemoryClass};
        use vyre_foundation::ir::DataType;
        let desc = KernelDescriptor {
            id: "store_loop".into(),
            bindings: BindingLayout {
                slots: vec![BindingSlot {
                    slot: 0,
                    element_type: DataType::U32,
                    element_count: None,
                    memory_class: MemoryClass::Global,
                    visibility: BindingVisibility::WriteOnly,
                    name: "out".into(),
                }],
            },
            dispatch: Dispatch::new(64, 1, 1),
            body: KernelBody {
                ops: vec![
                    KernelOp {
                        kind: KernelOpKind::Literal,
                        operands: vec![0],
                        result: Some(0),
                    },
                    KernelOp {
                        kind: KernelOpKind::Literal,
                        operands: vec![1],
                        result: Some(1),
                    },
                    KernelOp {
                        kind: KernelOpKind::StructuredForLoop {
                            loop_var: "i".into(),
                        },
                        operands: vec![0, 1, 0],
                        result: None,
                    },
                ],
                child_bodies: vec![KernelBody {
                    ops: vec![
                        KernelOp {
                            kind: KernelOpKind::Literal,
                            operands: vec![0],
                            result: Some(10),
                        },
                        KernelOp {
                            kind: KernelOpKind::Literal,
                            operands: vec![1],
                            result: Some(11),
                        },
                        KernelOp {
                            kind: KernelOpKind::StoreGlobal,
                            operands: vec![0, 10, 11],
                            result: None,
                        },
                    ],
                    child_bodies: vec![],
                    literals: vec![LiteralValue::U32(0), LiteralValue::U32(7)],
                }],
                literals: vec![LiteralValue::U32(0), LiteralValue::U32(8)],
            },
        };
        let out = licm(&desc);
        let loop_body = &out.body.child_bodies[0];
        let has_store = loop_body
            .ops
            .iter()
            .any(|o| matches!(o.kind, KernelOpKind::StoreGlobal));
        assert!(has_store, "Store must stay inside the loop");
    }

    #[test]
    fn licm_is_idempotent() {
        let desc = empty_kernel_with_loop(KernelBody {
            ops: vec![KernelOp {
                kind: KernelOpKind::Literal,
                operands: vec![0],
                result: Some(2),
            }],
            child_bodies: vec![],
            literals: vec![LiteralValue::U32(99)],
        });
        let once = licm(&desc);
        let twice = licm(&once);
        assert_eq!(once.body.ops.len(), twice.body.ops.len());
        assert_eq!(
            once.body.child_bodies[0].ops.len(),
            twice.body.child_bodies[0].ops.len()
        );
    }

    #[test]
    fn licm_handles_no_for_loop_op_gracefully() {
        // Body with StructuredIfThen but no for-loop  -  should be a noop on the loop side.
        let desc = KernelDescriptor {
            id: "if_only".into(),
            bindings: BindingLayout { slots: vec![] },
            dispatch: Dispatch::new(64, 1, 1),
            body: KernelBody {
                ops: vec![
                    KernelOp {
                        kind: KernelOpKind::Literal,
                        operands: vec![0],
                        result: Some(0),
                    },
                    KernelOp {
                        kind: KernelOpKind::StructuredIfThen,
                        operands: vec![0, 0],
                        result: None,
                    },
                ],
                child_bodies: vec![KernelBody {
                    ops: vec![],
                    child_bodies: vec![],
                    literals: vec![],
                }],
                literals: vec![LiteralValue::Bool(true)],
            },
        };
        let out = licm(&desc);
        // Outer ops stay at 2; nothing to hoist.
        assert_eq!(out.body.ops.len(), 2);
    }

    #[test]
    fn public_licm_hoists_invariants() {
        // The public `licm` API now performs a correct cross-body
        // hoist with id renumbering and literal-pool merging.
        let desc = empty_kernel_with_loop(KernelBody {
            ops: vec![KernelOp {
                kind: KernelOpKind::Literal,
                operands: vec![0],
                result: Some(2),
            }],
            child_bodies: vec![],
            literals: vec![LiteralValue::U32(99)],
        });
        let out = licm(&desc);
        // Outer body started with 3 ops. After LICM, the hoisted Literal
        // appears before the StructuredForLoop, making it 4.
        assert_eq!(out.body.ops.len(), 4, "hoisted literal adds one parent op");
        assert!(
            matches!(out.body.ops[2].kind, KernelOpKind::Literal),
            "hoisted op is at position 2"
        );
        assert!(
            matches!(out.body.ops[3].kind, KernelOpKind::StructuredForLoop { .. }),
            "loop op follows hoisted literal"
        );
        // Loop body should now be empty (the hoisted op moved out).
        assert!(
            out.body.child_bodies[0].ops.is_empty(),
            "child body empty after hoist"
        );
        // The parent literal pool gained the child's literal.
        assert_eq!(
            out.body.literals.len(),
            desc.body.literals.len() + 1,
            "parent literals grew by one"
        );
    }

    #[test]
    fn dataflow_licm_hoists_load_from_readwrite_buffer() {
        // Reproduces the `dataflow-licm.equivalent_alias_indices` corpus:
        // A ReadWrite buffer with a LoadGlobal(idx=20) and StoreGlobal(idx=40)
        // inside a loop. Reaching-defs: 20→11, 40→12. Alias facts: (0,11)≠(0,12).
        // LICM should hoist the Load because the store's resolved index provably
        // doesn't alias the load's resolved index.
        use crate::{BindingSlot, BindingVisibility, MemoryClass};
        use vyre_foundation::ir::DataType;

        let desc = KernelDescriptor {
            id: "rw_licm".into(),
            bindings: BindingLayout {
                slots: vec![BindingSlot {
                    slot: 0,
                    element_type: DataType::U32,
                    element_count: Some(4096),
                    memory_class: MemoryClass::Global,
                    visibility: BindingVisibility::ReadWrite,
                    name: "buf".into(),
                }],
            },
            dispatch: Dispatch::new(64, 1, 1),
            body: KernelBody {
                ops: vec![
                    KernelOp {
                        kind: KernelOpKind::Literal,
                        operands: vec![0],
                        result: Some(0),
                    },
                    KernelOp {
                        kind: KernelOpKind::Literal,
                        operands: vec![1],
                        result: Some(1),
                    },
                    KernelOp {
                        kind: KernelOpKind::Literal,
                        operands: vec![2],
                        result: Some(11),
                    },
                    KernelOp {
                        kind: KernelOpKind::Copy,
                        operands: vec![11],
                        result: Some(20),
                    },
                    KernelOp {
                        kind: KernelOpKind::Literal,
                        operands: vec![3],
                        result: Some(12),
                    },
                    KernelOp {
                        kind: KernelOpKind::Copy,
                        operands: vec![12],
                        result: Some(40),
                    },
                    KernelOp {
                        kind: KernelOpKind::Literal,
                        operands: vec![4],
                        result: Some(31),
                    },
                    KernelOp {
                        kind: KernelOpKind::StructuredForLoop {
                            loop_var: "i".into(),
                        },
                        operands: vec![0, 1, 0],
                        result: None,
                    },
                ],
                child_bodies: vec![KernelBody {
                    ops: vec![
                        KernelOp {
                            kind: KernelOpKind::LoadGlobal,
                            operands: vec![0, 20],
                            result: Some(50),
                        },
                        KernelOp {
                            kind: KernelOpKind::StoreGlobal,
                            operands: vec![0, 40, 31],
                            result: None,
                        },
                    ],
                    child_bodies: vec![],
                    literals: vec![],
                }],
                literals: vec![
                    LiteralValue::U32(0),
                    LiteralValue::U32(64),
                    LiteralValue::U32(42),
                    LiteralValue::U32(13),
                    LiteralValue::U32(9),
                ],
            },
        };

        let mut alias_facts = crate::analyses::alias_facts::AliasFactSet::default();
        alias_facts.insert_no_alias(crate::analyses::alias_facts::NoAliasFact {
            left_binding: 0,
            left_index: 11,
            right_binding: 0,
            right_index: 12,
        });

        let mut reaching_defs = crate::analyses::reaching_def_facts::ReachingDefFactSet::default();
        reaching_defs.set_reaching_defs(20, vec![11]);
        reaching_defs.set_reaching_defs(40, vec![12]);

        let out = licm_with_dataflow_facts(&desc, &alias_facts, &reaching_defs);

        // After hoist, LoadGlobal should be in the parent body, not the loop body.
        let parent_loads = out
            .body
            .ops
            .iter()
            .filter(|o| matches!(o.kind, KernelOpKind::LoadGlobal))
            .count();
        let child_loads = out.body.child_bodies[0]
            .ops
            .iter()
            .filter(|o| matches!(o.kind, KernelOpKind::LoadGlobal))
            .count();
        assert_eq!(
            child_loads,
            0,
            "LoadGlobal should be hoisted out of loop body; child ops: {:?}",
            out.body.child_bodies[0]
                .ops
                .iter()
                .map(|o| format!("{:?} operands={:?}", o.kind, o.operands))
                .collect::<Vec<_>>()
        );
        assert!(
            parent_loads > 0,
            "LoadGlobal should appear in parent body after hoist"
        );
    }
}