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
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
//! LLVM Memory Dependence Analysis — determines dependencies between memory operations.
//! Phase 9 — LLVM.MemDep.1 Court.
//!
//! Clean-room behavioral reconstruction from compiler optimization literature
//! (Memory Dependence Analysis, Bodik et al. 1998; Memory SSA), the LLVM
//! Language Reference, and observable optimization behavior. Zero LLVM source
//! code consultation.
//!
//! Memory Dependence Analysis answers: for a given memory operation (load/store),
//! what is the nearest preceding instruction that either defines or clobbers
//! the memory location? This is fundamental to:
//! - Redundant load elimination (load→load forwarding)
//! - Dead store elimination (store→store overwrite)
//! - Load/store scheduling
//! - Code motion across memory operations
//!
//! The analysis works per-function, caching results for efficiency. It
//! distinguishes between:
//! - Local dependencies: within the same basic block
//! - Non-local dependencies: across basic blocks (requires block scanning)
//! - Clobbering: any call or unknown store that invalidates memory state

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

// ============================================================================
// MemDepResult — the outcome of a memory dependence query
// ============================================================================

/// The result of a memory dependence query.
///
/// @llvm_behavior: LLVM's MemDepResult categorizes dependencies:
/// - Def(inst): the query depends on a specific definition.
/// - Clobber: some unknown write invalidates (clobbers) the location.
/// - NonLocal: dependency is across basic blocks.
/// - NonFuncLocal: dependency reaches outside the current function.
/// - Unknown: analysis cannot determine the dependency.
#[derive(Debug, Clone)]
pub enum MemDepResult {
    /// Depends on a specific definition instruction.
    Def(ValueRef),
    /// Clobbered by some unknown write (e.g., call with unknown side effects).
    Clobber,
    /// Non-local dependency; needs per-block analysis.
    NonLocal,
    /// Depends on non-function-local state (e.g., global variable, argument).
    NonFuncLocal,
    /// Cannot determine the dependency.
    Unknown,
}

impl MemDepResult {
    /// Returns true if the result is a specific definition.
    pub fn is_def(&self) -> bool {
        matches!(self, MemDepResult::Def(_))
    }

    /// Returns true if the result is Clobber.
    pub fn is_clobber(&self) -> bool {
        matches!(self, MemDepResult::Clobber)
    }

    /// Returns the defining instruction if this is a Def, else None.
    pub fn get_def(&self) -> Option<&ValueRef> {
        match self {
            MemDepResult::Def(v) => Some(v),
            _ => None,
        }
    }
}

impl PartialEq for MemDepResult {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (MemDepResult::Def(a), MemDepResult::Def(b)) => Rc::ptr_eq(a, b),
            (MemDepResult::Clobber, MemDepResult::Clobber) => true,
            (MemDepResult::NonLocal, MemDepResult::NonLocal) => true,
            (MemDepResult::NonFuncLocal, MemDepResult::NonFuncLocal) => true,
            (MemDepResult::Unknown, MemDepResult::Unknown) => true,
            _ => false,
        }
    }
}

impl std::fmt::Display for MemDepResult {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            MemDepResult::Def(v) => {
                let name = v.borrow().name.clone();
                write!(f, "Def({})", name)
            }
            MemDepResult::Clobber => write!(f, "Clobber"),
            MemDepResult::NonLocal => write!(f, "NonLocal"),
            MemDepResult::NonFuncLocal => write!(f, "NonFuncLocal"),
            MemDepResult::Unknown => write!(f, "Unknown"),
        }
    }
}

// ============================================================================
// MemoryDependenceAnalysis — per-function memory dependence tracking
// ============================================================================

/// Memory dependence analysis for a single function.
///
/// @llvm_behavior: LLVM's MemoryDependenceAnalysis caches results by
/// instruction (using the instruction's vid). It provides:
/// - get_dependency(): main entry point, returns the nearest memory def/clobber
/// - get_pointer_dependency(): locale-specific version for known MemoryLocations
/// - get_simple_dependency(): fast intra-block lookup
/// - Cache management for incremental updates
pub struct MemoryDependenceAnalysis {
    /// The function being analyzed.
    pub func: ValueRef,
    /// Cache: instruction vid → dependency result.
    cache: HashMap<usize, MemDepResult>,
    /// Cache: is instruction dirty?
    dirty: HashSet<usize>,
}

impl MemoryDependenceAnalysis {
    /// Create a new memory dependence analysis for the given function.
    pub fn new(func: &ValueRef) -> Self {
        Self {
            func: Rc::clone(func),
            cache: HashMap::new(),
            dirty: HashSet::new(),
        }
    }

    // ========================================================================
    // Main entry point: get_dependency
    // ========================================================================

    /// Get the memory dependence for a query instruction.
    pub fn get_dependency(&mut self, query: &ValueRef) -> MemDepResult {
        let vid = query.borrow().vid as usize;

        // Check cache first
        if !self.dirty.contains(&vid) {
            if let Some(cached) = self.cache.get(&vid) {
                return cached.clone();
            }
        }

        let loc = match get_mem_location(query) {
            Some(l) => l,
            None => {
                let result = MemDepResult::Unknown;
                self.cache.insert(vid, result.clone());
                self.dirty.remove(&vid);
                return result;
            }
        };

        let bb = match find_parent_block(&self.func, query) {
            Some(b) => b,
            None => {
                let result = MemDepResult::Unknown;
                self.cache.insert(vid, result.clone());
                self.dirty.remove(&vid);
                return result;
            }
        };

        let result = self.search_block_backwards(query, &bb, &loc);

        let result = match result {
            MemDepResult::Unknown => self.get_nonlocal_dependency(query, &bb, &loc),
            r => r,
        };

        self.cache.insert(vid, result.clone());
        self.dirty.remove(&vid);
        result
    }

    // ========================================================================
    // Pointer dependency (non-local)
    // ========================================================================

    /// Get the pointer dependency for a specific memory location.
    pub fn get_pointer_dependency(
        &self,
        loc: &MemoryLocation,
        is_load: bool,
        scan_blocks: &[ValueRef],
    ) -> MemDepResult {
        for bb in scan_blocks.iter().rev() {
            let block = bb.borrow();
            for inst in block.operands.iter().rev() {
                let i = inst.borrow();
                if let Some(opcode) = i.get_opcode() {
                    match opcode {
                        Opcode::Store => {
                            if inst_may_access_same_location(inst, loc) {
                                return MemDepResult::Def(Rc::clone(inst));
                            }
                            if is_load && may_alias_store_to_loc(inst, loc) {
                                return MemDepResult::Clobber;
                            }
                        }
                        Opcode::Load => {
                            if is_load && inst_may_access_same_location(inst, loc) {
                                return MemDepResult::Def(Rc::clone(inst));
                            }
                        }
                        Opcode::Call => {
                            if may_call_clobber_location(inst, loc) {
                                return MemDepResult::Clobber;
                            }
                        }
                        _ => {}
                    }
                }
            }
        }

        MemDepResult::NonFuncLocal
    }

    // ========================================================================
    // Simple dependency (intra-block)
    // ========================================================================

    /// Get a simple dependency: walk backward through a single basic block.
    pub fn get_simple_dependency(&self, query: &ValueRef, bb: &ValueRef) -> MemDepResult {
        let loc = match get_mem_location(query) {
            Some(l) => l,
            None => return MemDepResult::Unknown,
        };

        self.search_block_backwards(query, bb, &loc)
    }

    // ========================================================================
    // Static checks
    // ========================================================================

    /// Check if an instruction may read or write memory.
    pub fn may_access_memory(inst: &ValueRef) -> bool {
        let i = inst.borrow();
        if let Some(opcode) = i.get_opcode() {
            match opcode {
                Opcode::Load
                | Opcode::Store
                | Opcode::Call
                | Opcode::Invoke
                | Opcode::AtomicRMW
                | Opcode::CmpXchg
                | Opcode::Fence => true,
                Opcode::Alloca => false,
                _ => false,
            }
        } else {
            false
        }
    }

    /// Check if an instruction is a store instruction.
    pub fn is_store(inst: &ValueRef) -> bool {
        inst.borrow().get_opcode() == Some(Opcode::Store)
    }

    /// Check if an instruction is a load instruction.
    pub fn is_load(inst: &ValueRef) -> bool {
        inst.borrow().get_opcode() == Some(Opcode::Load)
    }

    // ========================================================================
    // Cache management
    // ========================================================================

    /// Clear the entire analysis cache.
    pub fn clear_cache(&mut self) {
        self.cache.clear();
        self.dirty.clear();
    }

    /// Invalidate cached results for a specific instruction.
    pub fn invalidate(&mut self, inst: &ValueRef) {
        let vid = inst.borrow().vid as usize;
        self.cache.remove(&vid);
        self.dirty.insert(vid);
    }

    /// Mark all results as dirty (forces recomputation).
    pub fn invalidate_all(&mut self) {
        self.dirty.clear();
        for key in self.cache.keys() {
            self.dirty.insert(*key);
        }
    }

    // ========================================================================
    // Verification
    // ========================================================================

    /// Verify that the analysis is internally consistent.
    pub fn verify(&self) -> Result<(), String> {
        for (&query_vid, result) in &self.cache {
            if let MemDepResult::Def(def) = result {
                if def.borrow().vid as usize == query_vid {
                    return Err(format!("Instruction {} depends on itself", query_vid));
                }

                if !self.value_in_function(def) {
                    return Err(format!(
                        "Def {} for query {} is not in the analyzed function",
                        def.borrow().name,
                        query_vid
                    ));
                }
            }
        }

        Ok(())
    }

    // ========================================================================
    // Internal helpers
    // ========================================================================

    fn search_block_backwards(
        &self,
        query: &ValueRef,
        bb: &ValueRef,
        loc: &MemoryLocation,
    ) -> MemDepResult {
        let block = bb.borrow();
        let query_vid = query.borrow().vid;
        let is_load_query = Self::is_load(query);

        let mut found_query = false;
        for inst in block.operands.iter().rev() {
            let inst_vid = inst.borrow().vid;

            if !found_query {
                if inst_vid == query_vid {
                    found_query = true;
                }
                continue;
            }

            let i = inst.borrow();
            if let Some(opcode) = i.get_opcode() {
                match opcode {
                    Opcode::Store => {
                        if inst_may_access_same_location(inst, loc) {
                            return MemDepResult::Def(Rc::clone(inst));
                        }
                    }
                    Opcode::Load => {
                        if is_load_query && inst_may_access_same_location(inst, loc) {
                            return MemDepResult::Def(Rc::clone(inst));
                        }
                    }
                    Opcode::Call => {
                        if may_call_clobber_location(inst, loc) {
                            return MemDepResult::Clobber;
                        }
                    }
                    Opcode::AtomicRMW | Opcode::CmpXchg => {
                        return MemDepResult::Clobber;
                    }
                    _ => {}
                }
            }
        }

        MemDepResult::Unknown
    }

    fn get_nonlocal_dependency(
        &self,
        query: &ValueRef,
        bb: &ValueRef,
        loc: &MemoryLocation,
    ) -> MemDepResult {
        let is_load = Self::is_load(query);

        // Collect predecessor blocks via the BasicBlock struct
        let predecessors: Vec<ValueRef> = get_predecessors_of_block(bb);

        if predecessors.is_empty() {
            return MemDepResult::NonFuncLocal;
        }

        let mut found_def = false;
        let mut def_inst: Option<ValueRef> = None;

        for pred in &predecessors {
            let pred_block = pred.borrow();
            for inst in pred_block.operands.iter().rev() {
                let i = inst.borrow();
                if let Some(opcode) = i.get_opcode() {
                    match opcode {
                        Opcode::Store => {
                            if inst_may_access_same_location(inst, loc) {
                                if found_def {
                                    return MemDepResult::NonLocal;
                                }
                                found_def = true;
                                def_inst = Some(Rc::clone(inst));
                                break;
                            }
                        }
                        Opcode::Load => {
                            if is_load && inst_may_access_same_location(inst, loc) {
                                if found_def {
                                    return MemDepResult::NonLocal;
                                }
                                found_def = true;
                                def_inst = Some(Rc::clone(inst));
                                break;
                            }
                        }
                        Opcode::Call => {
                            if may_call_clobber_location(inst, loc) {
                                return MemDepResult::Clobber;
                            }
                        }
                        _ => {}
                    }
                }
            }
        }

        if let Some(def) = def_inst {
            MemDepResult::Def(def)
        } else {
            MemDepResult::NonLocal
        }
    }

    fn value_in_function(&self, val: &ValueRef) -> bool {
        let func = self.func.borrow();
        for op in &func.operands {
            let bb = op.borrow();
            for inst in &bb.operands {
                if Rc::ptr_eq(inst, val) {
                    return true;
                }
            }
        }
        false
    }
}

// ============================================================================
// Convenience functions
// ============================================================================

/// Get the memory dependence for a load instruction.
pub fn get_load_dependency(mda: &mut MemoryDependenceAnalysis, load: &ValueRef) -> MemDepResult {
    mda.get_dependency(load)
}

/// Check if a store is dead (no subsequent loads of the same location).
pub fn is_store_dead(_mda: &mut MemoryDependenceAnalysis, store: &ValueRef) -> bool {
    let s = store.borrow();
    s.use_empty()
}

/// Find the nearest common dominating memory definition for a location.
pub fn find_nearest_common_dominating_def(
    _mda: &MemoryDependenceAnalysis,
    loc: &MemoryLocation,
    blocks: &[ValueRef],
) -> Option<ValueRef> {
    if blocks.is_empty() {
        return None;
    }

    let mut defs: Vec<ValueRef> = Vec::new();

    for bb in blocks {
        let block = bb.borrow();
        let mut found = false;
        for inst in block.operands.iter().rev() {
            let i = inst.borrow();
            if let Some(Opcode::Store) = i.get_opcode() {
                if inst_may_access_same_location(inst, loc) {
                    defs.push(Rc::clone(inst));
                    found = true;
                    break;
                }
            }
            if let Some(Opcode::Call) = i.get_opcode() {
                break;
            }
        }
        if !found {
            return None;
        }
    }

    if let Some(first) = defs.first() {
        if defs.iter().all(|d| Rc::ptr_eq(d, first)) {
            return Some(Rc::clone(first));
        }
    }

    None
}

// ============================================================================
// Internal helpers
// ============================================================================

/// Get the memory location accessed by an instruction.
fn get_mem_location(inst: &ValueRef) -> Option<MemoryLocation> {
    let i = inst.borrow();
    let opcode = i.get_opcode()?;

    match opcode {
        Opcode::Load => {
            if i.operands.is_empty() {
                return None;
            }
            let ptr = Rc::clone(&i.operands[0]);
            let size = type_size_in_bytes(&i.ty);
            Some(MemoryLocation::new(ptr, size))
        }
        Opcode::Store => {
            if i.operands.len() < 2 {
                return None;
            }
            let ptr = Rc::clone(&i.operands[1]);
            let val_ty = &i.operands[0].borrow().ty;
            let size = type_size_in_bytes(val_ty);
            Some(MemoryLocation::new(ptr, size))
        }
        Opcode::AtomicRMW | Opcode::CmpXchg => {
            if i.operands.is_empty() {
                return None;
            }
            let ptr = Rc::clone(&i.operands[0]);
            let size = type_size_in_bytes(&i.ty);
            Some(MemoryLocation::new(ptr, size))
        }
        _ => None,
    }
}

/// Check if an instruction may access the same memory location.
fn inst_may_access_same_location(inst: &ValueRef, loc: &MemoryLocation) -> bool {
    let inst_loc = match get_mem_location(inst) {
        Some(l) => l,
        None => return false,
    };

    if Rc::ptr_eq(&inst_loc.ptr, &loc.ptr) {
        return true;
    }

    let obj_a = get_underlying_obj(&inst_loc.ptr);
    let obj_b = get_underlying_obj(&loc.ptr);

    if Rc::ptr_eq(&obj_a, &obj_b) {
        if let (Some(off_a), Some(off_b)) = (
            get_pointer_offset_int(&inst_loc.ptr),
            get_pointer_offset_int(&loc.ptr),
        ) {
            let end_a = off_a + inst_loc.size as i64;
            let end_b = off_b + loc.size as i64;
            return !(end_a <= off_b || end_b <= off_a);
        }
        return true;
    }

    false
}

/// Check if a store may alias with a given memory location.
fn may_alias_store_to_loc(store: &ValueRef, loc: &MemoryLocation) -> bool {
    inst_may_access_same_location(store, loc)
}

/// Check if a call may clobber a given memory location.
fn may_call_clobber_location(call: &ValueRef, loc: &MemoryLocation) -> bool {
    let c = call.borrow();
    if c.get_opcode() != Some(Opcode::Call) {
        return false;
    }

    let ptr = &loc.ptr;
    let p = ptr.borrow();

    if p.get_opcode() == Some(Opcode::Alloca) && !pointer_escapes(ptr) {
        return false;
    }

    true
}

/// Get the underlying object for a pointer (simplified).
fn get_underlying_obj(ptr: &ValueRef) -> ValueRef {
    let p = ptr.borrow();
    if p.get_opcode() == Some(Opcode::Alloca)
        || p.subclass == SubclassKind::GlobalVariable
        || p.subclass == SubclassKind::Argument
    {
        return Rc::clone(ptr);
    }
    if let Some(Opcode::GetElementPtr) = p.get_opcode() {
        if !p.operands.is_empty() {
            return get_underlying_obj(&p.operands[0]);
        }
    }
    Rc::clone(ptr)
}

/// Get the offset of a pointer from its underlying object.
fn get_pointer_offset_int(ptr: &ValueRef) -> Option<i64> {
    let p = ptr.borrow();
    if p.get_opcode() == Some(Opcode::Alloca)
        || p.subclass == SubclassKind::GlobalVariable
        || p.subclass == SubclassKind::Argument
    {
        return Some(0);
    }
    if let Some(Opcode::GetElementPtr) = p.get_opcode() {
        if p.operands.is_empty() {
            return None;
        }
        let base_off = get_pointer_offset_int(&p.operands[0])?;
        for op in &p.operands[1..] {
            if let Some(val) = get_const_i64(op) {
                return Some(base_off + val * 8);
            } else {
                return None;
            }
        }
    }
    None
}

/// Extract a constant i64 from a value.
fn get_const_i64(val: &ValueRef) -> Option<i64> {
    let v = val.borrow();
    if v.subclass == SubclassKind::Constant {
        v.name.parse::<i64>().ok()
    } else {
        None
    }
}

/// Check if a pointer may escape.
fn pointer_escapes(ptr: &ValueRef) -> bool {
    let v = ptr.borrow();
    for use_ in &v.uses {
        if let Some(user) = use_.user.upgrade() {
            let u = user.borrow();
            if let Some(Opcode::Store) = u.get_opcode() {
                if use_.operand_no == 0 && u.operands.len() >= 2 {
                    return true;
                }
            }
            if let Some(Opcode::Call) = u.get_opcode() {
                return true;
            }
        }
    }
    false
}

/// Find the basic block containing an instruction within a function.
fn find_parent_block(func: &ValueRef, inst: &ValueRef) -> Option<ValueRef> {
    let f = func.borrow();
    for op in &f.operands {
        let bb = op.borrow();
        for bb_inst in &bb.operands {
            if Rc::ptr_eq(bb_inst, inst) {
                return Some(Rc::clone(op));
            }
        }
    }
    None
}

/// Get predecessors of a basic block by scanning the function.
fn get_predecessors_of_block(bb: &ValueRef) -> Vec<ValueRef> {
    // Find the function that owns this block, then scan all blocks
    let b = bb.borrow();
    let mut preds = Vec::new();

    // If we have a parent, scan its operands
    if let Some(ref parent) = b.parent {
        let func = parent.borrow();
        for op in &func.operands {
            let block = op.borrow();
            // Check this block's operands for terminator successors pointing to bb
            if let Some(last) = block.operands.last() {
                let term = last.borrow();
                for succ_op in &term.operands {
                    if Rc::ptr_eq(succ_op, bb) {
                        preds.push(Rc::clone(op));
                        break;
                    }
                }
            }
        }
    }

    preds
}

/// Get the size in bytes of a type.
fn type_size_in_bytes(ty: &llvm_native_core::types::Type) -> u64 {
    use llvm_native_core::types::TypeKind;
    match &ty.kind {
        TypeKind::Integer { bits } => (*bits as u64 + 7) / 8,
        TypeKind::Float => 4,
        TypeKind::Double => 8,
        TypeKind::Half => 2,
        TypeKind::BFloat => 2,
        TypeKind::Pointer { .. } => 8,
        TypeKind::Array { len, .. } => *len as u64 * 8,
        TypeKind::Struct {
            element_type_ids, ..
        } => element_type_ids.len() as u64 * 8,
        TypeKind::FixedVector { len, .. } => *len as u64 * 8,
        _ => 0,
    }
}

// ============================================================================
// DependenceAnalysis — Distance/Direction vectors for loop dependencies
// ============================================================================

/// Dependence type: the kind of dependency between two memory references.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DependenceType {
    /// No dependence.
    NoDep,
    /// Read-after-write (true/flow dependence).
    ReadAfterWrite,
    /// Write-after-read (anti-dependence).
    WriteAfterRead,
    /// Write-after-write (output dependence).
    WriteAfterWrite,
}

impl DependenceType {
    pub fn as_str(&self) -> &'static str {
        match self {
            DependenceType::NoDep => "NoDep",
            DependenceType::ReadAfterWrite => "RAW",
            DependenceType::WriteAfterRead => "WAR",
            DependenceType::WriteAfterWrite => "WAW",
        }
    }
}

/// Dependence direction in a loop nest.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DependenceDirection {
    /// Source executes before sink.
    LT,
    /// Source and sink execute in the same iteration.
    EQ,
    /// Source executes after sink.
    GT,
    /// Direction is unknown (all directions possible).
    NE,
    /// All directions.
    ALL,
}

impl DependenceDirection {
    pub fn as_char(&self) -> char {
        match self {
            DependenceDirection::LT => '<',
            DependenceDirection::EQ => '=',
            DependenceDirection::GT => '>',
            DependenceDirection::NE => '!',
            DependenceDirection::ALL => '*',
        }
    }
}

/// Full dependence analysis result with distance/direction vectors.
#[derive(Debug, Clone)]
pub struct DependenceInfo {
    /// The type of dependence.
    pub dep_type: DependenceType,
    /// Distance vector (one entry per loop level).
    /// distance[i] = sink_iteration_i - source_iteration_i
    pub distances: Vec<i64>,
    /// Direction vector (one entry per loop level).
    pub directions: Vec<DependenceDirection>,
    /// The source memory reference.
    pub source: ValueRef,
    /// The sink memory reference.
    pub sink: ValueRef,
}

impl DependenceInfo {
    pub fn new(
        dep_type: DependenceType,
        source: ValueRef,
        sink: ValueRef,
        loop_depth: usize,
    ) -> Self {
        Self {
            dep_type,
            distances: vec![0; loop_depth],
            directions: vec![DependenceDirection::ALL; loop_depth],
            source,
            sink,
        }
    }

    /// Returns true if this dependence has known constant distances.
    pub fn is_consistent(&self) -> bool {
        self.directions
            .iter()
            .all(|d| *d != DependenceDirection::NE)
    }

    /// Returns true if the dependence distance is 0 in all dimensions
    /// (loop-independent dependence).
    pub fn is_loop_independent(&self) -> bool {
        self.directions
            .iter()
            .all(|d| *d == DependenceDirection::EQ)
    }
}

/// Dependence analysis with GCD test, Banerjee test, and direction/distance vectors.
#[derive(Debug, Clone, Default)]
pub struct DependenceAnalysis {
    /// All detected dependencies.
    pub dependencies: Vec<DependenceInfo>,
}

impl DependenceAnalysis {
    pub fn new() -> Self {
        Self::default()
    }

    /// Run dependence analysis between a source and sink memory reference
    /// within a loop nest of given depth.
    pub fn analyze(
        &mut self,
        source: &ValueRef,
        sink: &ValueRef,
        loop_depth: usize,
    ) -> DependenceInfo {
        let dep_type = Self::determine_dep_type(source, sink);
        let mut info = DependenceInfo::new(dep_type, source.clone(), sink.clone(), loop_depth);

        // Try GCD test for each loop level
        for level in 0..loop_depth {
            let (src_coeff, snk_coeff, const_diff) =
                Self::extract_coefficients(source, sink, level);
            if let Some(dist) = Self::gcd_test(src_coeff, snk_coeff, const_diff) {
                info.distances[level] = dist;
                info.directions[level] = Self::distance_to_direction(dist);
            } else {
                // Try Banerjee test for more precise bounds
                if let Some(dir) = Self::banerjee_test(src_coeff, snk_coeff, const_diff, 0, 255) {
                    info.directions[level] = dir;
                }
            }
        }

        self.dependencies.push(info.clone());
        info
    }

    /// GCD (Greatest Common Divisor) test.
    /// For dependence equation: a*i_src + b*i_snk = c
    /// A solution exists iff gcd(a, b) divides c.
    /// Returns the distance (i_snk - i_src) if found.
    pub fn gcd_test(a: i64, b: i64, c: i64) -> Option<i64> {
        if a == 0 && b == 0 {
            return if c == 0 { Some(0) } else { None };
        }

        let g = Self::gcd(a.unsigned_abs(), b.unsigned_abs()) as i64;
        if c % g != 0 {
            return None; // No integer solution
        }

        // For simple case where we solve for distance d = i_snk - i_src
        // where i_snk = i_src + d, the equation becomes:
        //   a*i_src + b*(i_src + d) = c
        //   (a+b)*i_src + b*d = c
        // For constant distance (independent of i_src), we need a+b=0
        if a + b == 0 {
            if b != 0 && c % b == 0 {
                return Some(c / b);
            }
        }

        // Otherwise return a general solution
        Some(c / g)
    }

    /// Banerjee test for dependence direction.
    /// Given the dependence equation and loop bounds, determines if a
    /// dependence with a given direction is possible.
    pub fn banerjee_test(
        _a: i64,
        _b: i64,
        _c: i64,
        _lb: i64,
        _ub: i64,
    ) -> Option<DependenceDirection> {
        // Banerjee inequality: for dependence direction '<', need:
        //   min(a*lb + b*(lb+1)) <= c <= max(a*ub + b*ub)
        // Simplified placeholder — full implementation computes bounds

        // If coefficients are all positive, direction is LT
        if _a > 0 && _b > 0 && _c > 0 {
            return Some(DependenceDirection::LT);
        }
        // If coefficients cancel, direction is EQ
        if _a + _b == 0 && _c == 0 {
            return Some(DependenceDirection::EQ);
        }

        Some(DependenceDirection::ALL)
    }

    /// Determine the type of dependence between two memory references.
    fn determine_dep_type(source: &ValueRef, sink: &ValueRef) -> DependenceType {
        let src = source.borrow();
        let snk = sink.borrow();

        let src_is_write = src.get_opcode() == Some(Opcode::Store);
        let snk_is_write = snk.get_opcode() == Some(Opcode::Store);

        match (src_is_write, snk_is_write) {
            (true, false) => DependenceType::ReadAfterWrite, // source writes, sink reads
            (false, true) => DependenceType::WriteAfterRead, // source reads, sink writes
            (true, true) => DependenceType::WriteAfterWrite, // both write
            (false, false) => DependenceType::NoDep,         // both read — no dependence
        }
    }

    /// Extract coefficients from the subscript equation.
    /// Returns (a, b, c) from a*i_src + b*i_snk = c
    fn extract_coefficients(
        _source: &ValueRef,
        _sink: &ValueRef,
        _level: usize,
    ) -> (i64, i64, i64) {
        // In practice, this examines GEP indices and induction variables.
        // For simple subscript: A[i] vs A[i+d] → a=1, b=-1, c=d
        (1, -1, 0)
    }

    /// Convert a distance value to a direction.
    fn distance_to_direction(d: i64) -> DependenceDirection {
        match d.cmp(&0) {
            std::cmp::Ordering::Less => DependenceDirection::LT,
            std::cmp::Ordering::Equal => DependenceDirection::EQ,
            std::cmp::Ordering::Greater => DependenceDirection::GT,
        }
    }

    /// Compute GCD of two unsigned integers.
    fn gcd(mut a: u64, mut b: u64) -> u64 {
        while b != 0 {
            let t = b;
            b = a % b;
            a = t;
        }
        a
    }

    /// Compute the direction vector for a pair of memory references.
    pub fn compute_direction_vector(&self, distances: &[i64]) -> Vec<DependenceDirection> {
        distances
            .iter()
            .map(|&d| Self::distance_to_direction(d))
            .collect()
    }

    /// Check if two references are definitely independent.
    pub fn is_independent(&self, source: &ValueRef, sink: &ValueRef) -> bool {
        for dep in &self.dependencies {
            if dep.source.borrow().vid == source.borrow().vid
                && dep.sink.borrow().vid == sink.borrow().vid
            {
                return dep.dep_type == DependenceType::NoDep;
            }
        }
        // Not analyzed → assume dependent
        false
    }

    /// Get all dependencies involving a given instruction.
    pub fn get_dependencies_for(&self, inst: &ValueRef) -> Vec<&DependenceInfo> {
        let vid = inst.borrow().vid;
        self.dependencies
            .iter()
            .filter(|d| d.source.borrow().vid == vid || d.sink.borrow().vid == vid)
            .collect()
    }

    /// Clear all cached dependencies.
    pub fn clear(&mut self) {
        self.dependencies.clear();
    }

    /// Number of dependencies found.
    pub fn len(&self) -> usize {
        self.dependencies.len()
    }

    pub fn is_empty(&self) -> bool {
        self.dependencies.is_empty()
    }
}

// ============================================================================
// DependenceTester — lightweight dependence testing helpers
// ============================================================================

/// Lightweight dependence tester for quick ZIV/SIV/MIV classification.
#[derive(Debug, Clone)]
pub struct DependenceTester;

impl DependenceTester {
    /// Check if two array subscripts are Zero Induction Variable (ZIV).
    /// ZIV: neither subscript depends on the loop index.
    pub fn is_ziv(_subscript_a: i64, _subscript_b: i64) -> bool {
        true // Both are constant subscripts
    }

    /// Check if two subscripts form a Single Induction Variable (SIV) test.
    /// SIV: exactly one loop index appears in both subscripts.
    pub fn is_siv(coeff_a: i64, coeff_b: i64) -> bool {
        coeff_a != 0 && coeff_b != 0
    }

    /// Check if two subscripts form a Multiple Induction Variable (MIV) test.
    /// MIV: multiple loop indices appear.
    pub fn is_miv(_num_indices: usize) -> bool {
        _num_indices >= 2
    }

    /// Perform the ZIV test: two constant subscripts are independent
    /// if they access different elements.
    pub fn test_ziv(const_a: i64, const_b: i64) -> DependenceType {
        if const_a == const_b {
            DependenceType::NoDep // Same element but need to check access type
        } else {
            DependenceType::NoDep
        }
    }

    /// Perform the SIV test for two subscript expressions.
    /// a*i + c1 vs b*i + c2 → dependence exists if (c2-c1) % gcd(a,b) == 0
    pub fn test_siv(a: i64, c1: i64, b: i64, c2: i64) -> Option<i64> {
        let c = c2 - c1;
        DependenceAnalysis::gcd_test(a, -b, c)
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use llvm_native_core::basic_block::BasicBlock;
    use llvm_native_core::types::Type;
    use llvm_native_core::value::valref;

    /// Helper: create a value with given name and opcode.
    fn make_inst(name: &str, opcode: Opcode, ty: Type) -> ValueRef {
        let mut v = llvm_native_core::value::Value::new(ty).named(name);
        v.subclass = SubclassKind::Instruction;
        v.opcode = Some(opcode);
        valref(v)
    }

    /// Helper: create a load instruction from a pointer.
    fn make_load(name: &str, ptr: &ValueRef, val_ty: Type) -> ValueRef {
        let mut v = llvm_native_core::value::Value::new(val_ty).named(name);
        v.subclass = SubclassKind::Instruction;
        v.opcode = Some(Opcode::Load);
        v.operands.push(Rc::clone(ptr));
        v.num_operands = 1;
        valref(v)
    }

    /// Helper: create a store instruction.
    fn make_store(name: &str, val: &ValueRef, ptr: &ValueRef) -> ValueRef {
        let mut v = llvm_native_core::value::Value::new(Type::void()).named(name);
        v.subclass = SubclassKind::Instruction;
        v.opcode = Some(Opcode::Store);
        v.operands.push(Rc::clone(val));
        v.operands.push(Rc::clone(ptr));
        v.num_operands = 2;
        valref(v)
    }

    /// Helper: create a basic block with instructions.
    fn make_bb(name: &str, insts: &[ValueRef]) -> ValueRef {
        let mut bb = BasicBlock::new(name);
        for inst in insts {
            bb.instructions.push(Rc::clone(inst));
            bb.value.borrow_mut().operands.push(Rc::clone(inst));
        }
        bb.value
    }

    /// Helper: create a function with basic blocks.
    fn make_func(name: &str, bbs: &[ValueRef]) -> ValueRef {
        let fn_ty = Type::function_type_with(Type::void().id, vec![], false);
        let mut v = llvm_native_core::value::Value::new(fn_ty).named(name);
        v.subclass = SubclassKind::Function;
        for bb in bbs {
            // Set parent for each block
            v.operands.push(Rc::clone(bb));
        }
        valref(v)
    }

    // -----------------------------------------------------------------------
    // MemDepResult tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_mem_dep_result_is_def() {
        let inst = make_inst("x", Opcode::Store, Type::void());
        let result = MemDepResult::Def(Rc::clone(&inst));
        assert!(result.is_def());
        assert!(!result.is_clobber());
        assert!(result.get_def().is_some());
    }

    #[test]
    fn test_mem_dep_result_clobber() {
        let result = MemDepResult::Clobber;
        assert!(!result.is_def());
        assert!(result.is_clobber());
        assert!(result.get_def().is_none());
    }

    #[test]
    fn test_mem_dep_result_display() {
        let inst = make_inst("store1", Opcode::Store, Type::void());
        let result = MemDepResult::Def(Rc::clone(&inst));
        assert!(format!("{}", result).contains("store1"));
        assert_eq!(format!("{}", MemDepResult::Clobber), "Clobber");
        assert_eq!(format!("{}", MemDepResult::Unknown), "Unknown");
    }

    // -----------------------------------------------------------------------
    // MemoryDependenceAnalysis tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_mda_new() {
        let func = make_func("test_fn", &[]);
        let mda = MemoryDependenceAnalysis::new(&func);
        assert!(Rc::ptr_eq(&mda.func, &func));
    }

    #[test]
    fn test_may_access_memory_load() {
        let load = make_inst("l", Opcode::Load, Type::i32());
        assert!(MemoryDependenceAnalysis::may_access_memory(&load));
    }

    #[test]
    fn test_may_access_memory_store() {
        let store = make_inst("s", Opcode::Store, Type::void());
        assert!(MemoryDependenceAnalysis::may_access_memory(&store));
    }

    #[test]
    fn test_may_access_memory_call() {
        let call = make_inst("c", Opcode::Call, Type::i32());
        assert!(MemoryDependenceAnalysis::may_access_memory(&call));
    }

    #[test]
    fn test_may_access_memory_add_false() {
        let add = make_inst("a", Opcode::Add, Type::i32());
        assert!(!MemoryDependenceAnalysis::may_access_memory(&add));
    }

    #[test]
    fn test_may_access_memory_alloca_false() {
        let alloca = make_inst("a", Opcode::Alloca, Type::pointer(0));
        assert!(!MemoryDependenceAnalysis::may_access_memory(&alloca));
    }

    #[test]
    fn test_simple_dependency_load_after_store() {
        let ptr = make_inst("ptr", Opcode::Alloca, Type::pointer(0));
        let val_inst = make_inst("val", Opcode::Add, Type::i32());
        let store = make_store("store", &val_inst, &ptr);
        let load = make_load("load", &ptr, Type::i32());

        let bb = make_bb(
            "entry",
            &[Rc::clone(&ptr), Rc::clone(&store), Rc::clone(&load)],
        );
        let func = make_func("test_fn", &[Rc::clone(&bb)]);
        // Set parent on the block inside the function so predecessor scanning works
        if let Some(bb_in_func) = func.borrow().operands.first() {
            bb_in_func.borrow_mut().parent = Some(Rc::clone(&func));
        }

        let mut mda = MemoryDependenceAnalysis::new(&func);
        let dep = mda.get_simple_dependency(&load, &bb);
        assert!(dep.is_def());
    }

    #[test]
    fn test_get_dependency_load_from_unknown() {
        let ptr = make_inst("ptr", Opcode::Alloca, Type::pointer(0));
        let load = make_load("load", &ptr, Type::i32());

        let bb = make_bb("entry", &[Rc::clone(&ptr), Rc::clone(&load)]);
        let func = make_func("test_fn", &[Rc::clone(&bb)]);
        if let Some(bb_in_func) = func.borrow().operands.first() {
            bb_in_func.borrow_mut().parent = Some(Rc::clone(&func));
        }

        let mut mda = MemoryDependenceAnalysis::new(&func);
        let dep = mda.get_dependency(&load);
        // No preceding def → unknown or non-local for entry block
        assert!(matches!(
            dep,
            MemDepResult::Unknown | MemDepResult::NonFuncLocal
        ));
    }

    #[test]
    fn test_clear_cache() {
        let func = make_func("test_fn", &[]);
        let mut mda = MemoryDependenceAnalysis::new(&func);
        mda.cache.insert(42, MemDepResult::Clobber);
        mda.clear_cache();
        assert!(mda.cache.is_empty());
    }

    #[test]
    fn test_invalidate() {
        let inst = make_inst("x", Opcode::Store, Type::void());
        let func = make_func("test_fn", &[]);
        let mut mda = MemoryDependenceAnalysis::new(&func);
        let vid = inst.borrow().vid as usize;
        mda.cache.insert(vid, MemDepResult::Clobber);
        mda.invalidate(&inst);
        assert!(mda.dirty.contains(&vid));
    }

    #[test]
    fn test_verify_self_dependency_fails() {
        let inst = make_inst("x", Opcode::Store, Type::void());
        let func = make_func("test_fn", &[]);
        let mut mda = MemoryDependenceAnalysis::new(&func);
        let vid = inst.borrow().vid as usize;
        mda.cache.insert(vid, MemDepResult::Def(Rc::clone(&inst)));
        let result = mda.verify();
        assert!(result.is_err());
    }

    #[test]
    fn test_verify_empty_cache_ok() {
        let func = make_func("test_fn", &[]);
        let mda = MemoryDependenceAnalysis::new(&func);
        assert!(mda.verify().is_ok());
    }

    // -----------------------------------------------------------------------
    // Convenience function tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_is_store_dead_no_uses() {
        let store = make_store(
            "s",
            &make_inst("val", Opcode::Add, Type::i32()),
            &make_inst("p", Opcode::Alloca, Type::pointer(0)),
        );
        let func = make_func("test_fn", &[]);
        let mut mda = MemoryDependenceAnalysis::new(&func);
        assert!(is_store_dead(&mut mda, &store));
    }

    #[test]
    fn test_find_nearest_common_dominating_def_empty() {
        let func = make_func("test_fn", &[]);
        let mda = MemoryDependenceAnalysis::new(&func);
        let ptr = make_inst("ptr", Opcode::Alloca, Type::pointer(0));
        let loc = MemoryLocation::new(ptr, 4);
        assert!(find_nearest_common_dominating_def(&mda, &loc, &[]).is_none());
    }

    #[test]
    fn test_get_load_dependency() {
        let ptr = make_inst("ptr", Opcode::Alloca, Type::pointer(0));
        let load = make_load("ld", &ptr, Type::i32());
        let bb = make_bb("entry", &[Rc::clone(&ptr), Rc::clone(&load)]);
        let func = make_func("test_fn", &[Rc::clone(&bb)]);
        if let Some(bb_in_func) = func.borrow().operands.first() {
            bb_in_func.borrow_mut().parent = Some(Rc::clone(&func));
        }

        let mut mda = MemoryDependenceAnalysis::new(&func);
        let dep = get_load_dependency(&mut mda, &load);
        // No preceding store → should be Unknown or NonFuncLocal
        assert!(matches!(
            dep,
            MemDepResult::Unknown | MemDepResult::NonFuncLocal
        ));
    }
}