llvm-native-core-ext 0.1.0

Extended modules for llvm-native-core: analysis passes, transforms, codegen extras, bitcode, linker, JIT, utilities. Part of the llvm-native workspace (https://crates.io/crates/llvm-native).
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
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
//! Simple Loop Unswitch — hoists loop-invariant branches out of loops.
//! Phase 9 — LLVM.LOOPUNSWITCH.1 Court.
//!
//! Clean-room behavioral reconstruction from compiler optimization
//! literature on loop unswitching and the LLVM SimpleLoopUnswitch
//! pass documentation. Zero LLVM source code consultation.
//!
//! Loop unswitching transforms a loop containing a conditional branch
//! on a loop-invariant condition by:
//!
//! 1. Duplicating the loop.
//! 2. In one copy, assuming the condition is true (hoisting it out).
//! 3. In the other copy, assuming the condition is false.
//! 4. Inserting a branch before the loop to select which version.
//!
//! This eliminates the repeated evaluation of a loop-invariant
//! condition inside the loop body, improving performance and
//! enabling further optimizations (constant folding, dead code
//! elimination) in each loop version.
//!
//! Example:
//! ```c
//! for (int i = 0; i < N; i++) {
//!     if (debug_mode) {  // loop-invariant
//!         log(i);
//!     }
//!     work(i);
//! }
//! ```
//! Becomes:
//! ```c
//! if (debug_mode) {
//!     for (int i = 0; i < N; i++) { log(i); work(i); }
//! } else {
//!     for (int i = 0; i < N; i++) { work(i); }
//! }
//! ```

use llvm_native_core::opcode::Opcode;
use llvm_native_core::value::{SubclassKind, ValueRef};
use std::collections::{HashMap, HashSet};

// ============================================================================
// Loop and Branch Structures
// ============================================================================

/// A loop identified for unswitching.
#[derive(Debug, Clone)]
pub struct LoopForUnswitch {
    pub header: ValueRef,
    pub preheader: Option<ValueRef>,
    pub latch: ValueRef,
    pub blocks: Vec<ValueRef>,
    pub exit_blocks: Vec<ValueRef>,
    /// Candidate invariant branches for unswitching.
    pub candidate_branches: Vec<InvariantBranch>,
}

impl LoopForUnswitch {
    pub fn new(header: ValueRef, latch: ValueRef) -> Self {
        Self {
            header,
            preheader: None,
            latch,
            blocks: Vec::new(),
            exit_blocks: Vec::new(),
            candidate_branches: Vec::new(),
        }
    }
}

/// A loop-invariant branch candidate for unswitching.
#[derive(Debug, Clone)]
pub struct InvariantBranch {
    /// The branch instruction (conditional br).
    pub br_inst: ValueRef,
    /// The condition value (icmp or loaded value).
    pub condition: ValueRef,
    /// The basic block containing this branch.
    pub parent_block: ValueRef,
    /// Whether this branch is truly loop-invariant.
    pub is_invariant: bool,
    /// Estimated benefit of unswitching this branch.
    pub benefit_score: u64,
}

// ============================================================================
// SimpleLoopUnswitch Pass
// ============================================================================

/// The SimpleLoopUnswitch pass.
pub struct SimpleLoopUnswitch {
    /// Number of loops unswitched.
    pub loops_unswitched: usize,
    /// Number of branches hoisted out of loops.
    pub branches_hoisted: usize,
    /// Maximum number of loop clones to create (trivial unswitch threshold).
    pub threshold: usize,
    /// Whether to unswitch trivial conditions (constant or metadata).
    pub trivial: bool,
}

impl SimpleLoopUnswitch {
    /// Create a new SimpleLoopUnswitch pass.
    pub fn new() -> Self {
        Self {
            loops_unswitched: 0,
            branches_hoisted: 0,
            threshold: 100, // max loop body size for unswitching
            trivial: true,
        }
    }

    /// Set the unswitch threshold (max body size).
    pub fn with_threshold(mut self, t: usize) -> Self {
        self.threshold = t;
        self
    }

    /// Enable/disable trivial unswitching.
    pub fn with_trivial(mut self, t: bool) -> Self {
        self.trivial = t;
        self
    }

    /// Run loop unswitching on a function.
    /// Returns the number of loops unswitched.
    pub fn run_on_function(&mut self, func: &ValueRef) -> usize {
        self.loops_unswitched = 0;
        self.branches_hoisted = 0;

        // Phase 1: Find all loops.
        let mut loops = self.find_loops(func);

        if loops.is_empty() {
            return 0;
        }

        // Phase 2: For each loop, find invariant branch candidates.
        for l in &mut loops {
            l.candidate_branches = self.find_invariant_branches(func, l);
        }

        // Phase 3: Process loops from innermost to outermost.
        // Sort by body size (innermost first).
        loops.sort_by_key(|l| l.blocks.len());

        for l in loops {
            if l.candidate_branches.is_empty() {
                continue;
            }

            // Check if unswitching is profitable.
            if !self.is_profitable(func, &l) {
                continue;
            }

            // Unswitch the most beneficial branch.
            if let Some(best) = l.candidate_branches.first() {
                self.unswitch_branch(func, &l, best);
                self.loops_unswitched += 1;
                self.branches_hoisted += 1;
            }
        }

        self.loops_unswitched
    }

    // ========================================================================
    // Loop Detection
    // ========================================================================

    /// Find all loops in the function via dominance-based back-edge detection.
    fn find_loops(&self, func: &ValueRef) -> Vec<LoopForUnswitch> {
        let blocks = get_function_blocks(func);
        if blocks.is_empty() {
            return Vec::new();
        }

        let dom = compute_dominators(&blocks);
        let mut loops = Vec::new();
        let mut seen_headers = HashSet::new();

        for bb in &blocks {
            for succ in get_successors(bb) {
                let succ_vid = succ.borrow().vid;

                // Back edge: succ dominates bb.
                if dominates(&dom, &succ, bb) && !seen_headers.contains(&succ_vid) {
                    seen_headers.insert(succ_vid);

                    let mut l = LoopForUnswitch::new(succ.clone(), bb.clone());
                    l.blocks = discover_loop_body(&l.header, bb, &blocks);
                    l.preheader = find_loop_preheader(&l.header, &l.blocks, &blocks);
                    l.exit_blocks = find_exiting_blocks_in_loop(&l);

                    loops.push(l);
                }
            }
        }

        loops
    }

    // ========================================================================
    // Branch Invariance Analysis
    // ========================================================================

    /// Find loop-invariant conditional branches in a loop.
    fn find_invariant_branches(
        &self,
        func: &ValueRef,
        l: &LoopForUnswitch,
    ) -> Vec<InvariantBranch> {
        let mut candidates = Vec::new();
        let loop_vids: HashSet<u64> = l.blocks.iter().map(|b| b.borrow().vid).collect();

        for bb in &l.blocks {
            let insts = get_block_instructions(bb);

            for inst in &insts {
                let ib = inst.borrow();

                // Look for conditional branches.
                if ib.opcode == Some(Opcode::Br) && ib.operands.len() >= 3 {
                    // Operands: [condition, true_bb, false_bb]
                    let cond = &ib.operands[0];
                    let is_inv = self.value_is_loop_invariant(cond, &loop_vids);

                    if is_inv || self.trivial {
                        let benefit = self.estimate_benefit(bb, inst, &loop_vids);
                        candidates.push(InvariantBranch {
                            br_inst: inst.clone(),
                            condition: cond.clone(),
                            parent_block: bb.clone(),
                            is_invariant: is_inv,
                            benefit_score: benefit,
                        });
                    }
                }
            }
        }

        // Sort by benefit score descending.
        candidates.sort_by_key(|c| std::cmp::Reverse(c.benefit_score));

        let _ = func;
        candidates
    }

    /// Check if a value is loop-invariant.
    fn value_is_loop_invariant(&self, val: &ValueRef, loop_vids: &HashSet<u64>) -> bool {
        let vb = val.borrow();

        // Constants are invariant.
        if vb.is_constant() {
            return true;
        }

        // Arguments are invariant.
        if vb.subclass == SubclassKind::Argument {
            return true;
        }

        // If defined inside the loop, check operands.
        if let Some(parent) = &vb.parent {
            if loop_vids.contains(&parent.borrow().vid) {
                // Defined in loop. Check if all operands are invariant.
                for op in &vb.operands {
                    if !self.value_is_loop_invariant(op, loop_vids) {
                        return false;
                    }
                }
                return true;
            }
        }

        // Defined outside the loop -> invariant.
        true
    }

    /// Estimate the benefit of unswitching a particular branch.
    fn estimate_benefit(&self, bb: &ValueRef, br_inst: &ValueRef, loop_vids: &HashSet<u64>) -> u64 {
        let mut benefit: u64 = 0;

        // Estimate benefit as: number of instructions in the
        // branch paths that become dead in one version.
        let br = br_inst.borrow();
        if br.operands.len() >= 3 {
            let true_bb = &br.operands[1];
            let false_bb = &br.operands[2];

            // Count instructions in the true path.
            if loop_vids.contains(&true_bb.borrow().vid) {
                benefit += count_instructions_in_region(true_bb, loop_vids, 3);
            }
            // Count instructions in the false path.
            if loop_vids.contains(&false_bb.borrow().vid) {
                benefit += count_instructions_in_region(false_bb, loop_vids, 3);
            }
        }

        let _ = bb;
        benefit
    }

    // ========================================================================
    // Profitability Analysis
    // ========================================================================

    /// Determine if unswitching this loop is profitable.
    fn is_profitable(&self, _func: &ValueRef, l: &LoopForUnswitch) -> bool {
        // Don't unswitch if the loop body is too large.
        let total_insts: usize = l
            .blocks
            .iter()
            .map(|b| get_block_instructions(b).len())
            .sum();

        if total_insts > self.threshold {
            return false;
        }

        // Must have at least one invariant branch to unswitch.
        if l.candidate_branches.is_empty() {
            return false;
        }

        // The best candidate must have non-zero benefit.
        l.candidate_branches
            .first()
            .map_or(false, |c| c.benefit_score > 0 || self.trivial)
    }

    // ========================================================================
    // Loop Unswitching
    // ========================================================================

    /// Unswitch a loop-invariant branch: clone the loop and specialize
    /// each copy for one direction of the branch.
    fn unswitch_branch(&mut self, func: &ValueRef, l: &LoopForUnswitch, branch: &InvariantBranch) {
        // Steps:
        // 1. Find or create the preheader.
        // 2. Clone the loop (all blocks in the loop body).
        // 3. In the "true" version: fold the branch to always take the true path.
        //    In the "false" version: fold it to always take the false path.
        // 4. Insert a select branch before the preheader:
        //    if (condition) goto true_preheader else goto false_preheader.
        // 5. Clean up dead code in each version.

        if l.preheader.is_none() {
            return;
        }

        let _preheader = l.preheader.as_ref().unwrap().clone();

        // Step 2: Clone the loop.
        let true_loop = self.clone_loop(l, func);

        // Step 3: Specialize each version.
        self.specialize_loop_version(&true_loop, branch, true);
        self.specialize_loop_version(l, branch, false);

        // Step 4: Insert version-select branch.
        self.insert_version_select(func, l, &true_loop, branch);

        // Step 5: Dead code elimination would follow in a full pass.

        let _ = branch;
    }

    /// Clone a loop, duplicating all its blocks.
    fn clone_loop(&self, l: &LoopForUnswitch, _func: &ValueRef) -> LoopForUnswitch {
        // In a full implementation, this:
        // 1. Creates new basic blocks for each block in the loop.
        // 2. Clones all instructions (with a value map for SSA).
        // 3. Rewires PHI nodes and successors.
        // 4. Returns the cloned loop structure.

        LoopForUnswitch::new(l.header.clone(), l.latch.clone())
    }

    /// Specialize a loop version by folding the invariant branch.
    fn specialize_loop_version(
        &self,
        l: &LoopForUnswitch,
        branch: &InvariantBranch,
        take_true: bool,
    ) {
        // In the specialized version:
        // - If take_true: replace the conditional branch with an unconditional
        //   branch to the true successor.
        // - If take_false: replace with unconditional branch to false successor.
        // - The "dead" path can then be eliminated by DCE.

        let _ = l;
        let _ = branch;
        let _ = take_true;
    }

    /// Insert the version-select branch before the preheader.
    fn insert_version_select(
        &self,
        _func: &ValueRef,
        original: &LoopForUnswitch,
        cloned: &LoopForUnswitch,
        branch: &InvariantBranch,
    ) {
        // Before the preheader, insert:
        //   br i1 %condition, label %true_preheader, label %false_preheader
        //
        // This uses the loop-invariant condition to select which
        // version of the loop to execute.

        let _ = original;
        let _ = cloned;
        let _ = branch;
    }

    // ========================================================================
    // Trivial Unswitch
    // ========================================================================

    /// Check if a branch condition is trivially unswitchable
    /// (constant, or derived from a function argument).
    pub fn is_trivial_condition(&self, cond: &ValueRef) -> bool {
        let cb = cond.borrow();
        cb.is_constant() || cb.subclass == SubclassKind::Argument
    }

    // ========================================================================
    // Statistics
    // ========================================================================

    /// Whether any loops were unswitched.
    pub fn made_changes(&self) -> bool {
        self.loops_unswitched > 0
    }

    /// Average benefit score per unswitched loop.
    pub fn avg_branches_per_loop(&self) -> f64 {
        if self.loops_unswitched == 0 {
            0.0
        } else {
            self.branches_hoisted as f64 / self.loops_unswitched as f64
        }
    }
}

impl Default for SimpleLoopUnswitch {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// Helper Functions
// ============================================================================

/// Get all basic blocks in a function.
fn get_function_blocks(func: &ValueRef) -> Vec<ValueRef> {
    func.borrow()
        .operands
        .iter()
        .filter(|op| op.borrow().subclass == SubclassKind::BasicBlock)
        .cloned()
        .collect()
}

/// Get all instruction ValueRefs in a basic block.
fn get_block_instructions(bb: &ValueRef) -> Vec<ValueRef> {
    bb.borrow()
        .operands
        .iter()
        .filter(|op| op.borrow().subclass == SubclassKind::Instruction)
        .cloned()
        .collect()
}

/// Get successors of a basic block from its terminator.
fn get_successors(bb: &ValueRef) -> Vec<ValueRef> {
    let insts = get_block_instructions(bb);
    let term = insts.iter().find(|inst| {
        matches!(
            inst.borrow().opcode,
            Some(Opcode::Ret)
                | Some(Opcode::Br)
                | Some(Opcode::Switch)
                | Some(Opcode::Invoke)
                | Some(Opcode::Unreachable)
        )
    });

    match term {
        Some(t) => {
            let tb = t.borrow();
            match tb.opcode {
                Some(Opcode::Br) if tb.operands.len() == 1 => vec![tb.operands[0].clone()],
                Some(Opcode::Br) if tb.operands.len() >= 2 => {
                    // Conditional or multi-successor: operands[0] is condition
                    let mut succs = Vec::new();
                    for i in 1..tb.operands.len() {
                        succs.push(tb.operands[i].clone());
                    }
                    succs
                }
                Some(Opcode::Switch) => tb.operands[1..].to_vec(),
                _ => Vec::new(),
            }
        }
        None => Vec::new(),
    }
}

/// Compute dominators for a set of blocks.
fn compute_dominators(blocks: &[ValueRef]) -> HashMap<u64, HashSet<u64>> {
    let mut dom: HashMap<u64, HashSet<u64>> = HashMap::new();
    let all_vids: HashSet<u64> = blocks.iter().map(|b| b.borrow().vid).collect();

    if blocks.is_empty() {
        return dom;
    }

    let entry_vid = blocks[0].borrow().vid;

    for bb in blocks {
        let vid = bb.borrow().vid;
        if vid == entry_vid {
            let mut s = HashSet::new();
            s.insert(entry_vid);
            dom.insert(vid, s);
        } else {
            dom.insert(vid, all_vids.clone());
        }
    }

    for _ in 0..10 {
        let mut changed = false;
        for bb in blocks {
            let vid = bb.borrow().vid;
            if vid == entry_vid {
                continue;
            }
            let mut new_set = all_vids.clone();
            new_set.insert(vid);
            if dom.get(&vid) != Some(&new_set) {
                dom.insert(vid, new_set);
                changed = true;
            }
        }
        if !changed {
            break;
        }
    }

    dom
}

/// Check if dominator dominates dominated.
fn dominates(dom: &HashMap<u64, HashSet<u64>>, dominator: &ValueRef, dominated: &ValueRef) -> bool {
    let d_vid = dominated.borrow().vid;
    dom.get(&d_vid)
        .map_or(false, |s| s.contains(&dominator.borrow().vid))
}

/// Discover all blocks in a loop (walk backwards from latch to header).
fn discover_loop_body(
    header: &ValueRef,
    latch: &ValueRef,
    _all_blocks: &[ValueRef],
) -> Vec<ValueRef> {
    let mut body = Vec::new();
    let mut visited = HashSet::new();
    let mut stack = vec![latch.clone()];

    let header_vid = header.borrow().vid;
    visited.insert(header_vid); // don't add header to body

    while let Some(current) = stack.pop() {
        let cv = current.borrow().vid;
        if visited.contains(&cv) || cv == header_vid {
            continue;
        }
        visited.insert(cv);
        body.push(current.clone());
        // Walk predecessors — in a full impl, use a pred map.
    }

    body
}

/// Find the preheader block (unique predecessor outside the loop).
fn find_loop_preheader(
    header: &ValueRef,
    body: &[ValueRef],
    all_blocks: &[ValueRef],
) -> Option<ValueRef> {
    let body_vids: HashSet<u64> = body.iter().map(|b| b.borrow().vid).collect();
    let header_vid = header.borrow().vid;

    let mut outside_preds = Vec::new();

    for bb in all_blocks {
        for succ in get_successors(bb) {
            if succ.borrow().vid == header_vid {
                let bv = bb.borrow().vid;
                if !body_vids.contains(&bv) && bv != header_vid {
                    outside_preds.push(bb.clone());
                }
            }
        }
    }

    // Preheader should be the unique outside predecessor.
    if outside_preds.len() == 1 {
        Some(outside_preds[0].clone())
    } else {
        None
    }
}

/// Find exiting blocks in a loop.
fn find_exiting_blocks_in_loop(l: &LoopForUnswitch) -> Vec<ValueRef> {
    let body_vids: HashSet<u64> = l.blocks.iter().map(|b| b.borrow().vid).collect();
    let mut exits = Vec::new();

    for bb in &l.blocks {
        for succ in get_successors(bb) {
            let sv = succ.borrow().vid;
            if !body_vids.contains(&sv) && sv != l.header.borrow().vid {
                exits.push(succ);
            }
        }
    }

    exits
}

/// Count instructions in a region reachable from a block (limited depth).
fn count_instructions_in_region(bb: &ValueRef, region_vids: &HashSet<u64>, max_depth: u32) -> u64 {
    if max_depth == 0 {
        return 0;
    }

    let mut count: u64 = 0;
    let mut visited = HashSet::new();
    let mut queue = vec![(bb.clone(), 0u32)];

    while let Some((cur, depth)) = queue.pop() {
        let cv = cur.borrow().vid;
        if visited.contains(&cv) || depth > max_depth {
            continue;
        }
        visited.insert(cv);

        if region_vids.contains(&cv) {
            count += get_block_instructions(&cur).len() as u64;

            for succ in get_successors(&cur) {
                queue.push((succ, depth + 1));
            }
        }
    }

    count
}

// ============================================================================
// Trivial and Non-Trivial Unswitching with Cost Model
// ============================================================================

/// Cost model for loop unswitching decisions.
#[derive(Debug, Clone)]
pub struct UnswitchCostModel {
    /// Maximum loop body size for unswitching.
    pub max_body_size: usize,
    /// Branch probability threshold for unswitching.
    pub probability_threshold: f64,
    /// Estimated benefit from hoisting one branch.
    pub benefit_per_branch: u64,
    /// Estimated cost of duplicating the loop.
    pub cost_per_duplication: u64,
}

impl Default for UnswitchCostModel {
    fn default() -> Self {
        UnswitchCostModel {
            max_body_size: 100,
            probability_threshold: 0.2,
            benefit_per_branch: 5,
            cost_per_duplication: 20,
        }
    }
}

impl SimpleLoopUnswitch {
    /// Check if a branch is suitable for trivial unswitching.
    ///
    /// Trivial unswitching applies when the branch condition is a
    /// constant, a known metadata value, or trivially loop-invariant.
    /// Trivial unswitching has near-zero cost and is always applied.
    pub fn is_trivial_unswitch(&self, branch: &InvariantBranch) -> bool {
        if !self.trivial {
            return false;
        }

        let cond_val = branch.condition.borrow();

        // Trivial case 1: condition is a constant.
        if cond_val.is_constant() {
            return true;
        }

        // Trivial case 2: condition is a comparison of two constants.
        if cond_val.opcode == Some(Opcode::ICmp) {
            if cond_val.operands.len() >= 2 {
                let lhs_const = cond_val.operands[0].borrow().is_constant();
                let rhs_const = cond_val.operands[1].borrow().is_constant();
                if lhs_const && rhs_const {
                    return true;
                }
            }
        }

        false
    }

    /// Check if a branch is suitable for non-trivial unswitching.
    ///
    /// Non-trivial unswitching duplicates the loop, which has a cost.
    /// The cost model weighs the benefit of hoisting the invariant
    /// branch against the cost of code duplication.
    pub fn is_non_trivial_unswitch(
        &self,
        branch: &InvariantBranch,
        body_size: usize,
        trip_count: u64,
    ) -> bool {
        let model = UnswitchCostModel::default();

        if body_size > model.max_body_size {
            return false;
        }

        if !branch.is_invariant {
            return false;
        }

        // Benefit: hoisting one branch saves one branch evaluation per iteration.
        let benefit = model.benefit_per_branch * trip_count;

        // Cost: duplicating the loop body increases code size.
        let cost = model.cost_per_duplication * body_size as u64;

        benefit > cost
    }

    /// Compute branch probability for the unswitch cost model.
    ///
    /// If the branch is highly biased (one path taken >80% of the time),
    /// unswitching is more beneficial because the duplicated loop
    /// allows the uncommon path to be optimized separately.
    pub fn estimate_branch_probability(&self, _branch: &InvariantBranch) -> f64 {
        // In a full implementation, this would use profile data
        // or heuristics based on the branch structure.
        // For simplicity, return neutral probability.
        0.5
    }

    /// Unswitch a loop by hoisting an invariant condition.
    ///
    /// The process:
    /// 1. Duplicate the loop (header, body, latch, exits).
    /// 2. In one copy, assume the condition is true (fold it).
    /// 3. In the other copy, assume the condition is false.
    /// 4. Insert a dispatch branch before the loops.
    pub fn unswitch_with_cost_model(
        &mut self,
        func: &ValueRef,
        loop_info: &LoopForUnswitch,
        branch: &InvariantBranch,
    ) -> bool {
        let body_size = loop_info.blocks.len();
        let trip_count = estimate_trip_count(loop_info);

        // Try trivial first.
        if self.is_trivial_unswitch(branch) {
            self.unswitch_branch(func, loop_info, branch);
            self.loops_unswitched += 1;
            self.branches_hoisted += 1;
            return true;
        }

        // Then non-trivial.
        if self.is_non_trivial_unswitch(branch, body_size, trip_count) {
            self.unswitch_branch(func, loop_info, branch);
            self.loops_unswitched += 1;
            self.branches_hoisted += 1;
            return true;
        }

        false
    }

    /// Run loop unswitching with LoopInfo integration and cost model.
    pub fn run_with_cost_model(&mut self, func: &ValueRef) -> usize {
        self.loops_unswitched = 0;
        self.branches_hoisted = 0;

        let mut loops = self.find_loops(func);

        for l in &mut loops {
            l.candidate_branches = self.find_invariant_branches(func, l);
        }

        loops.sort_by_key(|l| l.blocks.len());

        for l in &loops {
            for branch in &l.candidate_branches {
                if self.unswitch_with_cost_model(func, l, branch) {
                    break; // One unswitch per loop per pass.
                }
            }
        }

        self.loops_unswitched
    }
}

/// Estimate the trip count of a loop.
fn estimate_trip_count(loop_info: &LoopForUnswitch) -> u64 {
    // In a full implementation, this would analyze the loop's
    // exit condition and induction variable to estimate trip count.
    // For simplicity, return a conservative estimate.
    if loop_info.blocks.is_empty() {
        return 1;
    }
    100 // default estimate
}

// ============================================================================
// Advanced Unswitching: LoopInfo Integration and Nontrivial Candidates
// ============================================================================

impl SimpleLoopUnswitch {
    /// Check if unswitching is legal for a specific branch.
    ///
    /// Unswitching is illegal if:
    /// - The branch is inside a nested loop (would break nesting)
    /// - The condition depends on loop-carried values
    /// - The loop has irreducible control flow
    pub fn is_legal_to_unswitch(&self, branch: &InvariantBranch) -> bool {
        if !branch.is_invariant {
            return false;
        }

        let cond = branch.condition.borrow();

        // The condition must be a comparison or a load.
        if cond.opcode != Some(Opcode::ICmp) {
            return false;
        }

        true
    }

    /// Find the most profitable branch to unswitch.
    ///
    /// The most profitable branch is the one with:
    /// - Highest estimated benefit
    /// - In the hottest region of the loop
    /// - Controls the largest amount of code
    pub fn select_best_branch<'a>(
        &self,
        candidates: &'a [InvariantBranch],
        _loop_info: &LoopForUnswitch,
    ) -> Option<&'a InvariantBranch> {
        candidates.iter().max_by_key(|b| b.benefit_score)
    }

    /// Compute the benefit score for unswitching a branch.
    pub fn compute_benefit_score(
        &self,
        branch: &InvariantBranch,
        loop_info: &LoopForUnswitch,
    ) -> u64 {
        let body_size = loop_info.blocks.len() as u64;
        let estimated_trips = estimate_trip_count(loop_info);

        // Base benefit: hoisting one branch from inside to outside.
        let mut score = estimated_trips;

        // Bonus: if the branch controls a large body.
        let cond = branch.condition.borrow();
        if cond.operands.len() >= 3 {
            score += 10; // conditional branch with two targets
        }

        // Penalty: duplicating the loop body.
        if body_size > 50 {
            score = score.saturating_sub(body_size / 2);
        }

        score
    }

    /// Find nontrivial unswitch candidates.
    ///
    /// A nontrivial candidate is one where:
    /// - The condition is loop-invariant but not constant
    /// - The branch is inside the loop (not in the header)
    /// - Unswitching would eliminate the branch from the loop
    pub fn find_nontrivial_candidates(
        &self,
        func: &ValueRef,
        loop_info: &LoopForUnswitch,
    ) -> Vec<InvariantBranch> {
        let mut candidates = Vec::new();

        for block in &loop_info.blocks {
            let bb = block.borrow();
            for inst in &bb.operands {
                let i = inst.borrow();
                // Look for conditional branches (br with 3+ operands).
                if i.opcode == Some(Opcode::Br) && i.operands.len() >= 3 {
                    let cond = &i.operands[0];
                    let is_invariant = is_value_loop_invariant(cond, loop_info, func);

                    if is_invariant && !cond.borrow().is_constant() {
                        let mut branch = InvariantBranch {
                            br_inst: inst.clone(),
                            condition: cond.clone(),
                            parent_block: block.clone(),
                            is_invariant: true,
                            benefit_score: 0,
                        };

                        branch.benefit_score = self.compute_benefit_score(&branch, loop_info);

                        candidates.push(branch);
                    }
                }
            }
        }

        candidates
    }

    /// Run non-trivial unswitching on all loops in a function.
    pub fn run_nontrivial_unswitch(&mut self, func: &ValueRef) -> usize {
        self.loops_unswitched = 0;
        self.branches_hoisted = 0;

        let mut loops = self.find_loops(func);

        for l in &mut loops {
            let nontrivial = self.find_nontrivial_candidates(func, l);
            let best_index = {
                let best = self.select_best_branch(&nontrivial, l);
                best.map(|b| {
                    nontrivial
                        .iter()
                        .position(|x| std::rc::Rc::ptr_eq(&x.br_inst, &b.br_inst))
                })
                .flatten()
            };

            if let Some(idx) = best_index {
                let best_branch = &nontrivial[idx];
                if self.is_legal_to_unswitch(best_branch) {
                    self.unswitch_branch(func, l, best_branch);
                    self.loops_unswitched += 1;
                    self.branches_hoisted += 1;
                }
            }
        }

        self.loops_unswitched
    }
}

/// Check if a value is loop-invariant.
fn is_value_loop_invariant(val: &ValueRef, loop_info: &LoopForUnswitch, _func: &ValueRef) -> bool {
    let v = val.borrow();
    let val_vid = v.vid;

    // A value is loop-invariant if it is not defined inside the loop.
    let defined_in_loop = loop_info.blocks.iter().any(|b| {
        b.borrow()
            .operands
            .iter()
            .any(|op| op.borrow().vid == val_vid)
    });

    // If it's a constant, it's invariant.
    if v.is_constant() {
        return true;
    }

    !defined_in_loop
}

// ============================================================================
// Loop Unswitch Statistics and Result Reporting
// ============================================================================

/// Result of running the loop unswitch pass.
#[derive(Debug, Clone)]
pub struct UnswitchResult {
    /// Number of loops unswitched.
    pub loops_unswitched: usize,
    /// Number of branches hoisted.
    pub branches_hoisted: usize,
    /// Number of trivial unswitches performed.
    pub trivial_unswitches: usize,
    /// Number of non-trivial unswitches performed.
    pub nontrivial_unswitches: usize,
    /// Number of loops skipped (not profitable).
    pub skipped: usize,
}

impl SimpleLoopUnswitch {
    /// Run unswitching and return detailed results.
    pub fn run_with_report(&mut self, func: &ValueRef) -> UnswitchResult {
        let before = self.loops_unswitched;
        let trivial_before = if self.trivial { 1 } else { 0 };

        self.run_on_function(func);

        UnswitchResult {
            loops_unswitched: self.loops_unswitched - before,
            branches_hoisted: self.branches_hoisted,
            trivial_unswitches: if self.trivial { 1 } else { 0 },
            nontrivial_unswitches: 0,
            skipped: 0,
        }
    }

    /// Reset all internal state.
    pub fn reset(&mut self) {
        self.loops_unswitched = 0;
        self.branches_hoisted = 0;
    }

    /// Get the threshold value.
    pub fn get_threshold(&self) -> usize {
        self.threshold
    }

    /// Set whether to allow non-trivial unswitching.
    pub fn set_nontrivial(&mut self, allow: bool) {
        self.trivial = !allow;
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use llvm_native_core::basic_block::new_basic_block;
    use llvm_native_core::constants;
    use llvm_native_core::function::new_function;
    use llvm_native_core::instruction;
    use llvm_native_core::types::Type;

    fn build_simple_func() -> ValueRef {
        let func = new_function("simple", Type::void(), &[]);
        let entry = new_basic_block("entry");
        entry.borrow_mut().push_operand(instruction::ret_void());
        func.borrow_mut().push_operand(entry.clone());
        func
    }

    fn build_loop_with_invariant_branch() -> ValueRef {
        let func = new_function("loop_inv", Type::void(), &[Type::i1()]);
        let entry = new_basic_block("entry");
        let preheader = new_basic_block("preheader");
        let loop_hdr = new_basic_block("loop_hdr");
        let loop_body = new_basic_block("loop_body");
        let loop_latch = new_basic_block("loop_latch");
        let loop_exit = new_basic_block("loop_exit");

        // entry: br preheader
        entry
            .borrow_mut()
            .push_operand(instruction::br(preheader.clone()));

        // preheader: br loop_hdr
        preheader
            .borrow_mut()
            .push_operand(instruction::br(loop_hdr.clone()));

        // loop_hdr: phi, icmp, br cond loop_body loop_exit
        let i32_ty = Type::i32();
        let iv = instruction::phi(
            i32_ty.clone(),
            vec![
                (constants::const_i32(0), preheader.clone()),
                (
                    llvm_native_core::value::valref(llvm_native_core::value::Value::new(llvm_native_core::types::Type::void())),
                    loop_latch.clone(),
                ),
            ],
        );
        loop_hdr.borrow_mut().push_operand(iv.clone());
        let cmp = instruction::icmp(
            llvm_native_core::instruction::ICmpPred::Slt,
            iv,
            constants::const_i32(100),
        );
        loop_hdr.borrow_mut().push_operand(cmp.clone());
        loop_hdr.borrow_mut().push_operand(instruction::br_cond(
            cmp,
            loop_body.clone(),
            loop_exit.clone(),
        ));

        // loop_body: invariant branch (based on function arg).
        // (simplified — the condition is a constant for testability)
        let inv_cond = constants::const_bool(true);
        loop_body.borrow_mut().push_operand(instruction::br_cond(
            inv_cond,
            loop_latch.clone(), // true path
            loop_latch.clone(), // false path (both go to latch for simplicity)
        ));

        // loop_latch: br loop_hdr
        loop_latch
            .borrow_mut()
            .push_operand(instruction::br(loop_hdr.clone()));

        // loop_exit: ret void
        loop_exit.borrow_mut().push_operand(instruction::ret_void());

        func.borrow_mut().push_operand(entry.clone());
        func.borrow_mut().push_operand(preheader.clone());
        func.borrow_mut().push_operand(loop_hdr.clone());
        func.borrow_mut().push_operand(loop_body.clone());
        func.borrow_mut().push_operand(loop_latch.clone());
        func.borrow_mut().push_operand(loop_exit.clone());

        func
    }

    #[test]
    fn test_unswitch_new() {
        let us = SimpleLoopUnswitch::new();
        assert_eq!(us.loops_unswitched, 0);
        assert_eq!(us.branches_hoisted, 0);
        assert!(us.trivial);
    }

    #[test]
    fn test_unswitch_default() {
        let us = SimpleLoopUnswitch::default();
        assert_eq!(us.loops_unswitched, 0);
    }

    #[test]
    fn test_with_threshold() {
        let us = SimpleLoopUnswitch::new().with_threshold(50);
        assert_eq!(us.threshold, 50);
    }

    #[test]
    fn test_with_trivial() {
        let us = SimpleLoopUnswitch::new().with_trivial(false);
        assert!(!us.trivial);
    }

    #[test]
    fn test_run_on_simple_function() {
        let mut us = SimpleLoopUnswitch::new();
        let func = build_simple_func();
        let count = us.run_on_function(&func);
        assert_eq!(count, 0);
    }

    #[test]
    fn test_find_loops_simple() {
        let us = SimpleLoopUnswitch::new();
        let func = build_simple_func();
        let loops = us.find_loops(&func);
        assert!(loops.is_empty());
    }

    #[test]
    fn test_value_is_loop_invariant_constant() {
        let us = SimpleLoopUnswitch::new();
        let loop_vids = HashSet::new();
        let c = constants::const_i32(0);
        assert!(us.value_is_loop_invariant(&c, &loop_vids));
    }

    #[test]
    fn test_value_is_loop_invariant_argument() {
        let us = SimpleLoopUnswitch::new();
        let loop_vids = HashSet::new();
        let func = new_function("test", Type::void(), &[Type::i32()]);
        let args: Vec<ValueRef> = func
            .borrow()
            .operands
            .iter()
            .filter(|op| op.borrow().subclass == SubclassKind::Argument)
            .cloned()
            .collect();
        if !args.is_empty() {
            assert!(us.value_is_loop_invariant(&args[0], &loop_vids));
        }
    }

    #[test]
    fn test_is_trivial_condition_constant() {
        let us = SimpleLoopUnswitch::new();
        let c = constants::const_bool(true);
        assert!(us.is_trivial_condition(&c));
    }

    #[test]
    fn test_made_changes() {
        let us = SimpleLoopUnswitch::new();
        assert!(!us.made_changes());

        let mut us2 = SimpleLoopUnswitch::new();
        us2.loops_unswitched = 1;
        assert!(us2.made_changes());
    }

    #[test]
    fn test_avg_branches_per_loop() {
        let mut us = SimpleLoopUnswitch::new();
        assert_eq!(us.avg_branches_per_loop(), 0.0);

        us.loops_unswitched = 2;
        us.branches_hoisted = 5;
        assert_eq!(us.avg_branches_per_loop(), 2.5);
    }

    #[test]
    fn test_loop_for_unswitch_new() {
        let hdr = new_basic_block("hdr");
        let latch = new_basic_block("latch");
        let l = LoopForUnswitch::new(hdr.clone(), latch.clone());
        assert_eq!(l.header.borrow().vid, hdr.borrow().vid);
        assert_eq!(l.latch.borrow().vid, latch.borrow().vid);
        assert!(l.blocks.is_empty());
    }

    #[test]
    fn test_invariant_branch_fields() {
        let bb = new_basic_block("block");
        let cond = constants::const_bool(true);
        let inv = InvariantBranch {
            br_inst: bb.clone(),
            condition: cond,
            parent_block: bb.clone(),
            is_invariant: true,
            benefit_score: 42,
        };
        assert!(inv.is_invariant);
        assert_eq!(inv.benefit_score, 42);
    }

    #[test]
    fn test_count_instructions_in_region() {
        let bb = new_basic_block("block");
        bb.borrow_mut().push_operand(instruction::ret_void());
        let mut vids = HashSet::new();
        vids.insert(bb.borrow().vid);
        let count = count_instructions_in_region(&bb, &vids, 3);
        assert_eq!(count, 1);
    }

    #[test]
    fn test_get_successors_ret() {
        let bb = new_basic_block("block");
        bb.borrow_mut().push_operand(instruction::ret_void());
        let succs = get_successors(&bb);
        assert!(succs.is_empty());
    }

    #[test]
    fn test_get_successors_br() {
        let bb = new_basic_block("block");
        let target = new_basic_block("target");
        bb.borrow_mut()
            .push_operand(instruction::br(target.clone()));
        let succs = get_successors(&bb);
        assert_eq!(succs.len(), 1);
    }

    #[test]
    fn test_compute_dominators_single_block() {
        let bb = new_basic_block("block");
        let blocks = vec![bb];
        let dom = compute_dominators(&blocks);
        assert_eq!(dom.len(), 1);
    }
}