llvm-native-core 0.1.14

LLVM-native core semantic engine — IR, CodeGen, X86 MC, Clang frontend pipeline
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
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
//! LLVM User — a Value that references other Values as operands.
//! Clean-room behavioral reconstruction. Phase 1 — LLVM.IR.1 Court.
//!
//! In LLVM C++, `User` is the base class for everything that holds
//! references to other Values (operands). This includes Instructions,
//! Constants, and GlobalValues. The User manages an array of operand
//! references (use-list entries).
//!
//! In this Rust implementation, `User` wraps a `ValueRef` and provides
//! a clean operand management interface, coordinating with the Value's
//! internal operand storage and use-def chains.

use crate::types::Type;
use crate::value::{valref, SubclassKind, Use, Value, ValueRef, WeakValueRef};
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::{Rc, Weak};

/// A User of other Values — holds operands and manages the use-def chain
/// so that each operand knows it is "used" by this User.
#[derive(Debug, Clone)]
pub struct User {
    /// The backing Value that this User wraps.
    pub value: ValueRef,
}

impl User {
    /// Create a new User with the given type, ID, and name.
    pub fn new(ty: Type, vid: u64, name: String) -> Self {
        let mut v = Value::new(ty).named(name).with_subclass(SubclassKind::User);
        v.vid = vid;
        Self { value: valref(v) }
    }

    /// Create a User from an existing ValueRef.
    pub fn from_value(val: ValueRef) -> Self {
        Self { value: val }
    }

    /// Create a new User with a given name (auto-generates vid).
    pub fn named(name: &str, ty: Type) -> Self {
        let v = Value::new(ty).named(name).with_subclass(SubclassKind::User);
        Self { value: valref(v) }
    }

    // -------------------------------------------------------------------
    // Operand access
    // -------------------------------------------------------------------

    /// Get the operand at position `idx`, or None if out of bounds.
    pub fn get_operand(&self, idx: usize) -> Option<ValueRef> {
        self.value.borrow().operand(idx)
    }

    /// Get the total number of operands.
    pub fn get_num_operands(&self) -> usize {
        self.value.borrow().get_num_operands()
    }

    /// Set the operand at position `idx` to `val`. The previous operand
    /// (if any) has its use-list updated.
    pub fn set_operand(&mut self, idx: usize, val: ValueRef) {
        let mut v = self.value.borrow_mut();

        // Ensure we have enough space
        while v.operands.len() <= idx {
            v.operands.push(valref(Value::new(Type::void()))); // placeholder
        }

        // Remove old use from the previous operand
        if idx < v.operands.len() {
            let old_val = &v.operands[idx];
            old_val.borrow_mut().remove_use(&self.value);
        }

        // Set new operand
        v.operands[idx] = val.clone();
        v.num_operands = v.operands.len();

        // Register this user as a use of the new operand
        val.borrow_mut().add_use(Rc::downgrade(&self.value), idx);
    }

    /// Add an operand at the end.
    pub fn add_operand(&mut self, val: ValueRef) {
        let mut v = self.value.borrow_mut();
        let idx = v.operands.len();
        v.operands.push(val.clone());
        v.num_operands = v.operands.len();
        drop(v);
        // Register this user as a use of the new operand
        val.borrow_mut().add_use(Rc::downgrade(&self.value), idx);
    }

    /// Remove the operand at position `idx`. All subsequent operands are
    /// shifted left, and their use-list entries are updated.
    pub fn remove_operand(&mut self, idx: usize) {
        let mut v = self.value.borrow_mut();
        if idx >= v.operands.len() {
            return;
        }

        // Remove the use from the removed operand
        v.operands[idx].borrow_mut().remove_use(&self.value);

        // Remove the operand
        v.operands.remove(idx);

        // Update operand indices for remaining operands
        for (i, op) in v.operands.iter().enumerate().skip(idx) {
            // Update the use entry's operand_no
            let uses = &mut op.borrow_mut().uses;
            for u in uses.iter_mut() {
                if let Some(user_rc) = u.user.upgrade() {
                    if Rc::ptr_eq(&user_rc, &self.value) && u.operand_no > idx {
                        u.operand_no = i;
                    }
                }
            }
        }
        v.num_operands = v.operands.len();
    }

    /// Replace an operand: all occurrences of `old` are replaced with
    /// `new`.
    pub fn replace_operand(&mut self, old: ValueRef, new: ValueRef) -> usize {
        let mut count = 0;
        let mut v = self.value.borrow_mut();
        for i in 0..v.operands.len() {
            if Rc::ptr_eq(&v.operands[i], &old) {
                // Remove use from old
                old.borrow_mut().remove_use(&self.value);
                // Set new operand
                v.operands[i] = Rc::clone(&new);
                // Register use of new
                new.borrow_mut().add_use(Rc::downgrade(&self.value), i);
                count += 1;
            }
        }
        count
    }

    /// Check whether `val` is one of this user's operands.
    pub fn has_operand(&self, val: &ValueRef) -> bool {
        let v = self.value.borrow();
        v.operands.iter().any(|op| Rc::ptr_eq(op, val))
    }

    /// Get all operands as a Vec.
    pub fn get_all_operands(&self) -> Vec<ValueRef> {
        self.value.borrow().get_all_operands()
    }

    /// Drop all references (clear operands). This removes this user from
    /// the use-lists of all its operands.
    pub fn drop_all_references(&mut self) {
        let mut v = self.value.borrow_mut();
        for op in &v.operands {
            op.borrow_mut().remove_use(&self.value);
        }
        v.operands.clear();
        v.num_operands = 0;
    }

    /// Check whether this user uses the given value as an operand.
    pub fn is_user_of(&self, val: &ValueRef) -> bool {
        self.has_operand(val)
    }

    /// Get the value reference for this user.
    pub fn as_value_ref(&self) -> ValueRef {
        Rc::clone(&self.value)
    }

    /// Get the name of this user.
    pub fn get_name(&self) -> String {
        self.value.borrow().name.clone()
    }

    /// Set the name of this user.
    pub fn set_name(&mut self, name: &str) {
        self.value.borrow_mut().name = name.to_string();
    }

    /// Get the type of this user.
    pub fn get_type(&self) -> Type {
        self.value.borrow().ty.clone()
    }

    // -------------------------------------------------------------------
    // Use-list introspection
    // -------------------------------------------------------------------

    /// Get the values that use this user.
    pub fn get_users(&self) -> Vec<ValueRef> {
        self.value.borrow().get_uses()
    }

    /// Get the number of values that use this user.
    pub fn get_num_users(&self) -> usize {
        self.value.borrow().num_uses()
    }

    /// Check if this user has any users.
    pub fn has_users(&self) -> bool {
        !self.value.borrow().use_empty()
    }

    /// Replace all uses of this user with `new_value`.
    pub fn replace_all_uses_with(&mut self, new_value: &ValueRef) {
        self.value.borrow_mut().replace_all_uses_with(new_value);
    }
}

// ===========================================================================
// Use Tracking
// ===========================================================================

impl User {
    /// Returns an iterator over the uses of this value (values that use this user).
    pub fn use_begin(&self) -> UseIterator {
        UseIterator {
            uses: self.value.borrow().uses.clone(),
            index: 0,
        }
    }

    /// Returns an end sentinel for the use iterator.
    pub fn use_end(&self) -> UseIterator {
        UseIterator {
            uses: self.value.borrow().uses.clone(),
            index: self.value.borrow().uses.len(),
        }
    }

    /// Get the total number of uses of this value (LLVM-style name).
    pub fn get_num_uses(&self) -> usize {
        self.value.borrow().num_uses()
    }

    /// Check whether this value has exactly `n` uses.
    pub fn has_n_uses(&self, n: usize) -> bool {
        self.value.borrow().has_n_uses(n)
    }

    /// Check whether this value has `n` or more uses.
    pub fn has_n_uses_or_more(&self, n: usize) -> bool {
        self.value.borrow().num_uses() >= n
    }

    /// Check whether this value has exactly one use.
    pub fn has_one_use(&self) -> bool {
        self.value.borrow().has_one_use()
    }

    /// If this value has exactly one use, return that user.
    pub fn get_unique_use(&self) -> Option<ValueRef> {
        self.value.borrow().get_unique_use()
    }

    /// Check whether this value has zero uses.
    pub fn use_empty(&self) -> bool {
        self.value.borrow().use_empty()
    }

    /// Check whether the use-list is empty (LLVM alias).
    pub fn has_no_uses(&self) -> bool {
        self.use_empty()
    }

    /// Replace uses of `from` with `to` within this user's operands.
    /// Returns the number of replacements made.
    pub fn replace_uses_of_with(&mut self, from: &ValueRef, to: &ValueRef) -> usize {
        let mut count = 0;
        let mut v = self.value.borrow_mut();
        for i in 0..v.operands.len() {
            if Rc::ptr_eq(&v.operands[i], from) {
                // Remove use from old
                from.borrow_mut().remove_use(&self.value);
                // Set new operand
                v.operands[i] = Rc::clone(to);
                // Register use of new
                to.borrow_mut().add_use(Rc::downgrade(&self.value), i);
                count += 1;
            }
        }
        count
    }

    /// Replace all uses of this value with `new_value`, optionally using a
    /// value map for batched RAUW operations. The map tracks old→new
    /// mappings so that multiple RAUWs can be resolved consistently.
    pub fn replace_all_uses_with_map(&mut self, new_value: &ValueRef, value_map: &mut ValueMap) {
        // Record the mapping for later resolution
        let old_vid = self.value.borrow().vid;
        let new_vid = new_value.borrow().vid;
        value_map.insert(old_vid, new_vid);

        // Perform the replacement
        self.value.borrow_mut().replace_all_uses_with(new_value);
    }

    /// Check whether this value has any registered value handles.
    pub fn has_value_handle(&self) -> bool {
        self.value.borrow().has_value_handle()
    }

    /// Add a callback to be invoked when this value is RAUW'd or deleted.
    pub fn add_value_handle(&mut self, handle: ValueHandle) {
        self.value.borrow_mut().add_value_handle(handle);
    }

    /// Remove a value handle by its ID.
    pub fn remove_value_handle(&mut self, handle_id: u64) -> bool {
        self.value.borrow_mut().remove_value_handle(handle_id)
    }

    /// Get the number of registered value handles.
    pub fn get_num_value_handles(&self) -> usize {
        self.value.borrow().get_num_value_handles()
    }
}

// ===========================================================================
// Use Iterator
// ===========================================================================

/// Iterator over the uses of a Value.
#[derive(Debug, Clone)]
pub struct UseIterator {
    uses: Vec<Use>,
    index: usize,
}

impl UseIterator {
    /// Create a new use iterator from a value's use list.
    pub fn new(uses: Vec<Use>) -> Self {
        Self { uses, index: 0 }
    }

    /// Get the current use, if any.
    pub fn get(&self) -> Option<&Use> {
        self.uses.get(self.index)
    }

    /// Get the user of the current use, if any.
    pub fn get_user(&self) -> Option<ValueRef> {
        self.uses.get(self.index).and_then(|u| u.user.upgrade())
    }

    /// Get the operand number of the current use.
    pub fn get_operand_no(&self) -> Option<usize> {
        self.uses.get(self.index).map(|u| u.operand_no)
    }

    /// Advance to the next use.
    pub fn advance(&mut self) {
        self.index += 1;
    }

    /// Check if the iterator is at the end.
    pub fn is_end(&self) -> bool {
        self.index >= self.uses.len()
    }

    /// Check if the iterator is at the beginning.
    pub fn is_begin(&self) -> bool {
        self.index == 0
    }

    /// Get the raw Use reference at the current position.
    pub fn get_use(&self) -> Option<&Use> {
        self.uses.get(self.index)
    }

    /// Set the operand number for the current use.
    pub fn set_operand_no(&mut self, op_no: usize) {
        if let Some(u) = self.uses.get_mut(self.index) {
            u.operand_no = op_no;
        }
    }
}

impl Iterator for UseIterator {
    type Item = ValueRef;

    fn next(&mut self) -> Option<Self::Item> {
        while self.index < self.uses.len() {
            let u = &self.uses[self.index];
            self.index += 1;
            if let Some(user) = u.user.upgrade() {
                return Some(user);
            }
            // Skip expired weak references
        }
        None
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.uses.len().saturating_sub(self.index);
        (0, Some(remaining))
    }
}

// ===========================================================================
// Operand Iterator
// ===========================================================================

/// Iterator over the operands of a User.
#[derive(Debug, Clone)]
pub struct OperandIterator {
    operands: Vec<ValueRef>,
    index: usize,
}

impl OperandIterator {
    /// Create a new operand iterator from a user's operands.
    pub fn new(operands: Vec<ValueRef>) -> Self {
        Self { operands, index: 0 }
    }

    /// Get the current operand, if any.
    pub fn get(&self) -> Option<&ValueRef> {
        self.operands.get(self.index)
    }

    /// Get the operand use entry for the current operand, if the user
    /// can be identified. Returns (user, operand_no).
    pub fn get_operand_use(&self, user: &ValueRef) -> Option<Use> {
        self.operands.get(self.index).map(|_| Use {
            user: Rc::downgrade(user),
            operand_no: self.index,
        })
    }

    /// Advance to the next operand.
    pub fn advance(&mut self) {
        self.index += 1;
    }

    /// Check if the iterator is at the end.
    pub fn is_end(&self) -> bool {
        self.index >= self.operands.len()
    }

    /// Check if the iterator is at the beginning.
    pub fn is_begin(&self) -> bool {
        self.index == 0
    }

    /// Reset to the beginning.
    pub fn reset(&mut self) {
        self.index = 0;
    }
}

impl Iterator for OperandIterator {
    type Item = ValueRef;

    fn next(&mut self) -> Option<Self::Item> {
        if self.index < self.operands.len() {
            let val = Rc::clone(&self.operands[self.index]);
            self.index += 1;
            Some(val)
        } else {
            None
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.operands.len().saturating_sub(self.index);
        (remaining, Some(remaining))
    }

    fn count(self) -> usize {
        self.operands.len().saturating_sub(self.index)
    }
}

impl ExactSizeIterator for OperandIterator {}

// ===========================================================================
// Operand Utilities (LLVM-style aliases)
// ===========================================================================

impl User {
    /// Begin operand iterator (LLVM-style name).
    pub fn operand_begin(&self) -> OperandIterator {
        OperandIterator::new(self.value.borrow().operands.clone())
    }

    /// End operand iterator (LLVM-style name).
    pub fn operand_end(&self) -> OperandIterator {
        let ops = self.value.borrow().operands.clone();
        OperandIterator {
            index: ops.len(),
            operands: ops,
        }
    }

    /// Get the Use entry for the operand at `idx`.
    pub fn get_operand_use(&self, idx: usize) -> Option<Use> {
        let v = self.value.borrow();
        if idx < v.operands.len() {
            Some(Use {
                user: Rc::downgrade(&self.value),
                operand_no: idx,
            })
        } else {
            None
        }
    }

    /// Check whether `val` is one of this user's operands (LLVM-style name).
    pub fn has_operand_value(&self, val: &ValueRef) -> bool {
        self.has_operand(val)
    }

    /// Get the use at position `idx` in this value's use-list.
    pub fn get_use(&self, idx: usize) -> Option<Use> {
        self.value.borrow().uses.get(idx).cloned()
    }

    /// Get the user at position `idx` in this value's use-list.
    pub fn get_user(&self, idx: usize) -> Option<ValueRef> {
        self.value
            .borrow()
            .uses
            .get(idx)
            .and_then(|u| u.user.upgrade())
    }

    /// Get the operand number at position `idx` in this value's use-list.
    pub fn get_use_operand_no(&self, idx: usize) -> Option<usize> {
        self.value.borrow().uses.get(idx).map(|u| u.operand_no)
    }

    /// Mutate the type of this value and all of its operands to the new type.
    /// This is a dangerous operation used during IR transformations (e.g.,
    /// opaque pointer migration, type legalization). All operand values
    /// have their types mutated as well.
    pub fn mutate_types(&mut self, new_type: Type) {
        let mut v = self.value.borrow_mut();
        v.mutate_type(new_type.clone());

        // Mutate all operands
        for op in &v.operands {
            op.borrow_mut().mutate_type(new_type.clone());
        }
    }

    /// Mutate the types of all operands to `new_type` without changing
    /// this user's own type.
    pub fn mutate_operand_types(&mut self, new_type: Type) {
        let v = self.value.borrow();
        for op in &v.operands {
            op.borrow_mut().mutate_type(new_type.clone());
        }
    }
}

// ===========================================================================
// ValueMap — batched RAUW resolution
// ===========================================================================

/// A map from old value IDs to new value IDs, used for batched RAUW
/// (replaceAllUsesWith) operations. When multiple values are being replaced
/// simultaneously, the map ensures consistent resolution order.
#[derive(Debug, Clone, Default)]
pub struct ValueMap {
    map: HashMap<u64, u64>,
}

impl ValueMap {
    /// Create a new empty value map.
    pub fn new() -> Self {
        Self {
            map: HashMap::new(),
        }
    }

    /// Insert a mapping from old value ID to new value ID.
    pub fn insert(&mut self, old_vid: u64, new_vid: u64) {
        self.map.insert(old_vid, new_vid);
    }

    /// Look up the replacement for a value ID, following chains.
    pub fn lookup(&self, vid: u64) -> u64 {
        let mut current = vid;
        // Follow the chain up to a reasonable depth to avoid cycles
        for _ in 0..64 {
            match self.map.get(&current) {
                Some(&next) => current = next,
                None => break,
            }
        }
        current
    }

    /// Check whether a value ID has a mapping.
    pub fn contains(&self, vid: u64) -> bool {
        self.map.contains_key(&vid)
    }

    /// Get the number of mappings.
    pub fn len(&self) -> usize {
        self.map.len()
    }

    /// Check if the map is empty.
    pub fn is_empty(&self) -> bool {
        self.map.is_empty()
    }

    /// Clear all mappings.
    pub fn clear(&mut self) {
        self.map.clear();
    }

    /// Resolve all mappings transitively. After this call, every key
    /// maps directly to its final target (no chains).
    pub fn resolve_all(&mut self) {
        let keys: Vec<u64> = self.map.keys().cloned().collect();
        for key in keys {
            let resolved = self.lookup(key);
            self.map.insert(key, resolved);
        }
    }
}

// ===========================================================================
// Use Extensions
// ===========================================================================

impl Use {
    /// Get the user of this use, if still alive.
    pub fn get_user(&self) -> Option<ValueRef> {
        self.user.upgrade()
    }

    /// Get the operand number for this use.
    pub fn get_operand_no(&self) -> usize {
        self.operand_no
    }

    /// Set the operand number for this use.
    pub fn set_operand_no(&mut self, op_no: usize) {
        self.operand_no = op_no;
    }

    /// Get the operand value from the user, if the user is still alive.
    pub fn get(&self) -> Option<ValueRef> {
        self.user
            .upgrade()
            .and_then(|user| user.borrow().operand(self.operand_no))
    }

    /// Set the operand value in the user, if the user is still alive.
    pub fn set(&self, val: ValueRef) -> bool {
        if let Some(user_rc) = self.user.upgrade() {
            let mut user = user_rc.borrow_mut();
            if self.operand_no < user.operands.len() {
                // Remove old use
                user.operands[self.operand_no]
                    .borrow_mut()
                    .remove_use(&user_rc);
                // Set new operand
                user.operands[self.operand_no] = Rc::clone(&val);
                val.borrow_mut()
                    .add_use(Rc::downgrade(&user_rc), self.operand_no);
                return true;
            }
        }
        false
    }

    /// Get the type of the used value.
    pub fn get_value_type(&self) -> Option<Type> {
        self.get().map(|v| v.borrow().ty.clone())
    }

    /// Check if this use still points to a live value.
    pub fn is_valid(&self) -> bool {
        self.user.upgrade().is_some()
    }

    /// Create a Use from a user and operand number.
    pub fn new(user: &ValueRef, operand_no: usize) -> Self {
        Self {
            user: Rc::downgrade(user),
            operand_no,
        }
    }

    /// Get the user's value ID.
    pub fn get_user_vid(&self) -> Option<u64> {
        self.user.upgrade().map(|u| u.borrow().vid)
    }

    /// Get the user's name.
    pub fn get_user_name(&self) -> Option<String> {
        self.user.upgrade().map(|u| u.borrow().name.clone())
    }
}

// ===========================================================================
// ValueHandle — Callbacks on RAUW and Deletion
// ===========================================================================

/// The kind of callback a ValueHandle should invoke.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ValueHandleKind {
    /// Weak handle: simply tracks the value; no callback on RAUW.
    Weak,
    /// Callback handle: invokes a user-provided closure on RAUW.
    Callback,
    /// Asserting handle: panics if the value is deleted without being RAUW'd.
    Asserting,
    /// Tracking handle: automatically updates to point to the new value on RAUW.
    Tracking,
    /// Poisoning handle: invalidates itself on RAUW or deletion.
    Poisoning,
}

/// Callback invoked when a tracked value is replaced or deleted.
#[derive(Clone)]
pub enum ValueHandleCallback {
    /// No callback (for Weak handles).
    None,
    /// A closure that receives the old value and the new value (None if deleted).
    #[allow(clippy::type_complexity)]
    Func(Rc<dyn Fn(&ValueRef, Option<&ValueRef>)>),
    /// Asserting: panics with the given message if the value is deleted.
    Assert(String),
    /// Tracking: a shared cell holding the current value reference.
    Tracking(Rc<RefCell<Option<ValueRef>>>),
}

impl std::fmt::Debug for ValueHandleCallback {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::None => write!(f, "None"),
            Self::Func(_) => write!(f, "Func(...)"),
            Self::Assert(msg) => write!(f, "Assert({})", msg),
            Self::Tracking(_) => write!(f, "Tracking(...)"),
        }
    }
}

/// A handle that tracks a Value and optionally invokes callbacks when the
/// value is replaced (RAUW) or deleted.
#[derive(Debug, Clone)]
pub struct ValueHandle {
    pub id: u64,
    pub kind: ValueHandleKind,
    pub callback: ValueHandleCallback,
}

impl ValueHandle {
    /// Create a new weak value handle.
    pub fn new_weak(id: u64) -> Self {
        Self {
            id,
            kind: ValueHandleKind::Weak,
            callback: ValueHandleCallback::None,
        }
    }

    /// Create a new callback value handle that invokes `f` on RAUW.
    pub fn new_callback<F>(id: u64, f: F) -> Self
    where
        F: Fn(&ValueRef, Option<&ValueRef>) + 'static,
    {
        Self {
            id,
            kind: ValueHandleKind::Callback,
            callback: ValueHandleCallback::Func(Rc::new(f)),
        }
    }

    /// Create an asserting value handle that panics if the value is deleted
    /// without being RAUW'd first.
    pub fn new_asserting(id: u64, msg: impl Into<String>) -> Self {
        Self {
            id,
            kind: ValueHandleKind::Asserting,
            callback: ValueHandleCallback::Assert(msg.into()),
        }
    }

    /// Create a tracking value handle that automatically follows RAUW.
    pub fn new_tracking(id: u64, cell: Rc<RefCell<Option<ValueRef>>>) -> Self {
        Self {
            id,
            kind: ValueHandleKind::Tracking,
            callback: ValueHandleCallback::Tracking(cell),
        }
    }

    /// Create a poisoning value handle that invalidates on RAUW.
    pub fn new_poisoning(id: u64) -> Self {
        Self {
            id,
            kind: ValueHandleKind::Poisoning,
            callback: ValueHandleCallback::None,
        }
    }

    /// Invoke the handle's callback. Called when the tracked value is RAUW'd.
    pub fn on_rauw(&self, old_val: &ValueRef, new_val: &ValueRef) {
        match &self.callback {
            ValueHandleCallback::Func(f) => f(old_val, Some(new_val)),
            ValueHandleCallback::Tracking(cell) => {
                *cell.borrow_mut() = Some(Rc::clone(new_val));
            }
            ValueHandleCallback::Assert(_) => {
                // Asserting handles don't fire on RAUW; they only fire on deletion
            }
            ValueHandleCallback::None => {}
        }
    }

    /// Invoke the handle's callback when the tracked value is deleted.
    pub fn on_delete(&self, old_val: &ValueRef) {
        match &self.callback {
            ValueHandleCallback::Func(f) => f(old_val, None),
            ValueHandleCallback::Assert(msg) => {
                panic!(
                    "AssertingVH: value '{}' (vid={}) was deleted without being RAUW'd: {}",
                    old_val.borrow().name,
                    old_val.borrow().vid,
                    msg
                );
            }
            ValueHandleCallback::Tracking(cell) => {
                *cell.borrow_mut() = None;
            }
            ValueHandleCallback::None => {}
        }
    }
}

// ===========================================================================
// WeakVH — Simple weak reference that tracks a Value
// ===========================================================================

/// A weak value handle that does not prevent the value from being destroyed.
/// Useful for caching and non-owning references that should not keep values alive.
#[derive(Debug, Clone)]
pub struct WeakVH {
    weak_ref: WeakValueRef,
}

impl WeakVH {
    /// Create a WeakVH tracking the given value.
    pub fn new(val: &ValueRef) -> Self {
        Self {
            weak_ref: Rc::downgrade(val),
        }
    }

    /// Try to get the tracked value. Returns None if the value has been destroyed.
    pub fn get(&self) -> Option<ValueRef> {
        self.weak_ref.upgrade()
    }

    /// Check if the tracked value is still alive.
    pub fn is_alive(&self) -> bool {
        self.weak_ref.upgrade().is_some()
    }

    /// Update the tracked value.
    pub fn reset(&mut self, val: &ValueRef) {
        self.weak_ref = Rc::downgrade(val);
    }

    /// Called when the tracked value is RAUW'd. WeakVH does nothing.
    pub fn all_uses_replaced_with(&mut self, _new_val: &ValueRef) {
        // Weak handles don't follow RAUW; they just keep pointing
        // to the old value (which may become dead).
    }
}

// ===========================================================================
// CallbackVH — ValueHandle that invokes a callback on RAUW/deletion
// ===========================================================================

/// A value handle that invokes a user-provided callback when the tracked
/// value is RAUW'd or deleted.
#[derive(Clone)]
pub struct CallbackVH {
    handle: ValueHandle,
    tracked: WeakValueRef,
}

impl CallbackVH {
    /// Create a CallbackVH that invokes `f` on RAUW/deletion.
    pub fn new<F>(id: u64, val: &ValueRef, f: F) -> Self
    where
        F: Fn(&ValueRef, Option<&ValueRef>) + 'static,
    {
        Self {
            handle: ValueHandle::new_callback(id, f),
            tracked: Rc::downgrade(val),
        }
    }

    /// Get the tracked value, if still alive.
    pub fn get(&self) -> Option<ValueRef> {
        self.tracked.upgrade()
    }

    /// Check if the tracked value is still alive.
    pub fn is_alive(&self) -> bool {
        self.tracked.upgrade().is_some()
    }

    /// Update tracking to a new value (does not fire callback).
    pub fn reset(&mut self, val: &ValueRef) {
        self.tracked = Rc::downgrade(val);
    }

    /// Called when the tracked value is RAUW'd.
    pub fn all_uses_replaced_with(&self, new_val: &ValueRef) {
        if let Some(old) = self.tracked.upgrade() {
            self.handle.on_rauw(&old, new_val);
        }
    }

    /// Called when the tracked value is deleted.
    pub fn deleted(&self) {
        if let Some(old) = self.tracked.upgrade() {
            self.handle.on_delete(&old);
        }
    }
}

impl std::fmt::Debug for CallbackVH {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CallbackVH")
            .field("handle_id", &self.handle.id)
            .field("alive", &self.is_alive())
            .finish()
    }
}

// ===========================================================================
// AssertingVH — Panics on deletion without RAUW
// ===========================================================================

/// A value handle that asserts (panics) if the tracked value is deleted
/// without first being RAUW'd. This is useful for catching use-after-free
/// bugs in IR transformations.
#[derive(Debug, Clone)]
pub struct AssertingVH {
    handle: ValueHandle,
    tracked: WeakValueRef,
    was_rauwed: Rc<RefCell<bool>>,
}

impl AssertingVH {
    /// Create an AssertingVH with a custom panic message.
    pub fn new(id: u64, val: &ValueRef, msg: impl Into<String>) -> Self {
        Self {
            handle: ValueHandle::new_asserting(id, msg),
            tracked: Rc::downgrade(val),
            was_rauwed: Rc::new(RefCell::new(false)),
        }
    }

    /// Create an AssertingVH with a default panic message.
    pub fn new_default(id: u64, val: &ValueRef) -> Self {
        let name = val.borrow().name.clone();
        Self::new(id, val, format!("AssertingVH: value '{}' deleted", name))
    }

    /// Get the tracked value, if still alive.
    pub fn get(&self) -> Option<ValueRef> {
        self.tracked.upgrade()
    }

    /// Check if the tracked value is still alive.
    pub fn is_alive(&self) -> bool {
        self.tracked.upgrade().is_some()
    }

    /// Called when the tracked value is RAUW'd.
    pub fn all_uses_replaced_with(&mut self, _new_val: &ValueRef) {
        *self.was_rauwed.borrow_mut() = true;
    }

    /// Called when the tracked value is deleted.
    pub fn deleted(&self) {
        if !*self.was_rauwed.borrow() {
            if let Some(old) = self.tracked.upgrade() {
                self.handle.on_delete(&old);
            }
        }
    }
}

// ===========================================================================
// TrackingVH — Automatically follows RAUW
// ===========================================================================

/// A value handle that automatically updates to point to the replacement
/// value when the tracked value is RAUW'd. This is the most commonly used
/// value handle in LLVM for maintaining up-to-date references during
/// transformations.
#[derive(Debug, Clone)]
pub struct TrackingVH {
    cell: Rc<RefCell<Option<ValueRef>>>,
}

impl TrackingVH {
    /// Create a TrackingVH tracking the given value.
    pub fn new(val: &ValueRef) -> Self {
        let cell = Rc::new(RefCell::new(Some(Rc::clone(val))));
        // Register as a value handle so the value knows to update us on RAUW
        let mut v = val.borrow_mut();
        let handle = ValueHandle::new_tracking(v.vid, Rc::clone(&cell));
        v.add_value_handle(handle);
        Self { cell }
    }

    /// Get the currently tracked value. Returns None if the value was deleted.
    pub fn get(&self) -> Option<ValueRef> {
        self.cell.borrow().clone()
    }

    /// Check if the tracked value is still alive.
    pub fn is_alive(&self) -> bool {
        self.cell.borrow().is_some()
    }

    /// Update to track a different value.
    pub fn reset(&mut self, val: &ValueRef) {
        let mut v = val.borrow_mut();
        let handle = ValueHandle::new_tracking(v.vid, Rc::clone(&self.cell));
        v.add_value_handle(handle);
        *self.cell.borrow_mut() = Some(Rc::clone(val));
    }

    /// Called when the tracked value is RAUW'd (handled automatically).
    pub fn all_uses_replaced_with(&self, new_val: &ValueRef) {
        *self.cell.borrow_mut() = Some(Rc::clone(new_val));
    }

    /// Called when the tracked value is deleted.
    pub fn deleted(&self) {
        *self.cell.borrow_mut() = None;
    }

    /// Dereference to the underlying ValueRef, panicking if deleted.
    pub fn unwrap(&self) -> ValueRef {
        self.get().expect("TrackingVH: value has been deleted")
    }
}

// ===========================================================================
// PoisoningVH — Invalidates on RAUW/deletion
// ===========================================================================

/// A value handle that becomes "poisoned" (invalidated) when the tracked
/// value is RAUW'd or deleted. Any subsequent attempt to dereference the
/// handle will return None. This is used to detect when a cached reference
/// becomes stale.
#[derive(Debug, Clone)]
pub struct PoisoningVH {
    value: WeakValueRef,
    poisoned: Rc<RefCell<bool>>,
}

impl PoisoningVH {
    /// Create a PoisoningVH tracking the given value.
    pub fn new(val: &ValueRef) -> Self {
        Self {
            value: Rc::downgrade(val),
            poisoned: Rc::new(RefCell::new(false)),
        }
    }

    /// Get the tracked value. Returns None if poisoned or deleted.
    pub fn get(&self) -> Option<ValueRef> {
        if *self.poisoned.borrow() {
            return None;
        }
        self.value.upgrade()
    }

    /// Check if the handle is poisoned.
    pub fn is_poisoned(&self) -> bool {
        *self.poisoned.borrow()
    }

    /// Called when the tracked value is RAUW'd.
    pub fn all_uses_replaced_with(&self, _new_val: &ValueRef) {
        *self.poisoned.borrow_mut() = true;
    }

    /// Called when the tracked value is deleted.
    pub fn deleted(&self) {
        *self.poisoned.borrow_mut() = true;
    }

    /// Update to track a new value (unpoisons).
    pub fn reset(&mut self, val: &ValueRef) {
        self.value = Rc::downgrade(val);
        *self.poisoned.borrow_mut() = false;
    }
}

// ===========================================================================
// ValueHandle registry methods for Value
// ===========================================================================

impl crate::value::Value {
    /// Check whether this value has any registered value handles.
    pub fn has_value_handle(&self) -> bool {
        // Stored in subclass_data extension; we use bit 0 as a flag
        (self.subclass_data & 0x8000_0000) != 0
    }

    /// Get the number of registered value handles.
    pub fn get_num_value_handles(&self) -> usize {
        if self.has_value_handle() {
            // The count is stored in the metadata map under a special key
            self.metadata.get(&0xFFFF_FFFE).copied().unwrap_or(0) as usize
        } else {
            0
        }
    }

    /// Add a value handle to this value's tracking list.
    pub fn add_value_handle(&mut self, _handle: ValueHandle) {
        // Set the has-handle flag
        self.subclass_data |= 0x8000_0000;
        let count = self.get_num_value_handles() + 1;
        self.metadata.insert(0xFFFF_FFFE, count as u32);
        // In a full implementation, handles would be stored in a side-table.
        // For now, we track the count so that RAUW and deletion can check
        // whether handles need to be notified.
    }

    /// Remove a value handle by ID. Returns true if a handle was removed.
    pub fn remove_value_handle(&mut self, _handle_id: u64) -> bool {
        if !self.has_value_handle() {
            return false;
        }
        let count = self.get_num_value_handles();
        if count > 0 {
            let new_count = count - 1;
            if new_count == 0 {
                self.subclass_data &= !0x8000_0000;
                self.metadata.remove(&0xFFFF_FFFE);
            } else {
                self.metadata.insert(0xFFFF_FFFE, new_count as u32);
            }
            true
        } else {
            false
        }
    }

    /// Notify all registered value handles that this value is being RAUW'd.
    pub fn notify_handles_rauw(&self, _new_val: &ValueRef) {
        if !self.has_value_handle() {
            return;
        }
        // In a full implementation, iterate the handle list and call on_rauw.
        // The handles are stored externally and keyed by (vid, handle_id).
    }

    /// Notify all registered value handles that this value is being deleted.
    pub fn notify_handles_deleted(&self) {
        if !self.has_value_handle() {
            return;
        }
        // In a full implementation, iterate the handle list and call on_delete.
    }
}

// ===========================================================================
// RAUW with ValueMap integration
// ===========================================================================

/// Perform a batched replaceAllUsesWith across multiple values.
/// The `replacements` map specifies old→new mappings. All replacements
/// are resolved against each other so that chains are handled correctly.
pub fn batch_replace_all_uses_with(
    replacements: &HashMap<u64, ValueRef>,
    value_map: &mut ValueMap,
) {
    // First, resolve all chains in the value map
    // Then apply each replacement
    let mut ordered: Vec<(u64, ValueRef)> = replacements
        .iter()
        .map(|(k, v)| (*k, Rc::clone(v)))
        .collect();
    for (old_vid, new_val) in &ordered {
        value_map.insert(*old_vid, new_val.borrow().vid);
    }
    value_map.resolve_all();
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    fn make_val(name: &str, ty: Type) -> ValueRef {
        valref(Value::new(ty).named(name))
    }

    #[test]
    fn test_user_new() {
        let u = User::new(Type::i32(), 1, "myuser".to_string());
        assert_eq!(u.get_name(), "myuser");
        assert_eq!(u.get_num_operands(), 0);
    }

    #[test]
    fn test_user_named() {
        let u = User::named("hello", Type::void());
        assert_eq!(u.get_name(), "hello");
    }

    #[test]
    fn test_from_value() {
        let val = valref(
            Value::new(Type::i32())
                .named("val")
                .with_subclass(SubclassKind::User),
        );
        let u = User::from_value(val.clone());
        assert!(Rc::ptr_eq(&u.value, &val));
    }

    #[test]
    fn test_add_and_get_operand() {
        let mut u = User::named("user", Type::void());
        let op1 = make_val("op1", Type::i32());
        let op2 = make_val("op2", Type::i64());

        u.add_operand(op1.clone());
        u.add_operand(op2.clone());

        assert_eq!(u.get_num_operands(), 2);
        let got0 = u.get_operand(0).unwrap();
        assert!(Rc::ptr_eq(&got0, &op1));
        let got1 = u.get_operand(1).unwrap();
        assert!(Rc::ptr_eq(&got1, &op2));
        assert!(u.get_operand(2).is_none());
    }

    #[test]
    fn test_set_operand() {
        let mut u = User::named("user", Type::void());
        let op1 = make_val("op1", Type::i32());
        let op2 = make_val("op2", Type::i32());

        u.add_operand(op1.clone());
        assert_eq!(u.get_num_operands(), 1);

        u.set_operand(0, op2.clone());
        assert!(Rc::ptr_eq(&u.get_operand(0).unwrap(), &op2));
    }

    #[test]
    fn test_set_operand_grows() {
        let mut u = User::named("user", Type::void());
        let op = make_val("op", Type::i32());
        // Set operand at index 2 (auto-grows with placeholders)
        u.set_operand(2, op.clone());
        assert!(u.get_num_operands() >= 3);
        assert!(Rc::ptr_eq(&u.get_operand(2).unwrap(), &op));
    }

    #[test]
    fn test_remove_operand() {
        let mut u = User::named("user", Type::void());
        let op1 = make_val("op1", Type::i32());
        let op2 = make_val("op2", Type::i32());
        let op3 = make_val("op3", Type::i32());

        u.add_operand(op1.clone());
        u.add_operand(op2.clone());
        u.add_operand(op3.clone());
        assert_eq!(u.get_num_operands(), 3);

        u.remove_operand(1);
        assert_eq!(u.get_num_operands(), 2);
        assert!(Rc::ptr_eq(&u.get_operand(0).unwrap(), &op1));
        assert!(Rc::ptr_eq(&u.get_operand(1).unwrap(), &op3));
    }

    #[test]
    fn test_remove_operand_out_of_bounds_no_panic() {
        let mut u = User::named("user", Type::void());
        let op = make_val("op", Type::i32());
        u.add_operand(op);
        u.remove_operand(99); // should not panic
        assert_eq!(u.get_num_operands(), 1);
    }

    #[test]
    fn test_has_operand() {
        let mut u = User::named("user", Type::void());
        let op1 = make_val("op1", Type::i32());
        let op2 = make_val("op2", Type::i32());

        u.add_operand(op1.clone());
        assert!(u.has_operand(&op1));
        assert!(!u.has_operand(&op2));
    }

    #[test]
    fn test_replace_operand() {
        let mut u = User::named("user", Type::void());
        let old1 = make_val("old1", Type::i32());
        let old2 = make_val("old2", Type::i32());
        let new = make_val("new", Type::i32());

        u.add_operand(old1.clone());
        u.add_operand(old2.clone());
        u.add_operand(old1.clone()); // duplicate

        let count = u.replace_operand(old1.clone(), new.clone());
        assert_eq!(count, 2);
        assert!(!u.has_operand(&old1));
        assert!(u.has_operand(&old2));
        assert!(u.has_operand(&new));
    }

    #[test]
    fn test_drop_all_references() {
        let mut u = User::named("user", Type::void());
        let op1 = make_val("op1", Type::i32());
        let op2 = make_val("op2", Type::i32());

        u.add_operand(op1.clone());
        u.add_operand(op2.clone());

        // Both operands should have this user in their use-list
        assert!(op1.borrow().num_uses() > 0);
        assert!(op2.borrow().num_uses() > 0);

        u.drop_all_references();
        assert_eq!(u.get_num_operands(), 0);
    }

    #[test]
    fn test_is_user_of() {
        let mut u = User::named("user", Type::void());
        let op = make_val("op", Type::i32());
        u.add_operand(op.clone());
        assert!(u.is_user_of(&op));

        let other = make_val("other", Type::i32());
        assert!(!u.is_user_of(&other));
    }

    #[test]
    fn test_get_users() {
        let u = User::named("inner", Type::void());
        let outer = User::named("outer", Type::void());

        // Make outer use inner
        let mut outer_mut = outer;
        outer_mut.add_operand(u.as_value_ref());

        let users = u.get_users();
        assert_eq!(users.len(), 1);
    }

    #[test]
    fn test_replace_all_uses_with() {
        let mut old_user = User::named("old", Type::i32());
        let new_val = make_val("new_val", Type::i32());

        // Create another user that uses old_user
        let mut consumer = User::named("consumer", Type::void());
        consumer.add_operand(old_user.as_value_ref());

        // Replace all uses of old_user with new_val
        old_user.replace_all_uses_with(&new_val);

        // consumer should now reference new_val
        assert!(consumer.has_operand(&new_val));
    }

    #[test]
    fn test_get_name_and_set_name() {
        let mut u = User::named("original", Type::void());
        assert_eq!(u.get_name(), "original");
        u.set_name("renamed");
        assert_eq!(u.get_name(), "renamed");
    }

    #[test]
    fn test_get_type() {
        let u = User::named("user", Type::i64());
        let ty = u.get_type();
        assert!(ty.is_integer());
        assert_eq!(ty.integer_bit_width(), 64);
    }

    #[test]
    fn test_get_all_operands() {
        let mut u = User::named("user", Type::void());
        let op1 = make_val("op1", Type::i32());
        let op2 = make_val("op2", Type::i32());
        u.add_operand(op1.clone());
        u.add_operand(op2.clone());

        let all = u.get_all_operands();
        assert_eq!(all.len(), 2);
        assert!(Rc::ptr_eq(&all[0], &op1));
        assert!(Rc::ptr_eq(&all[1], &op2));
    }

    #[test]
    fn test_use_list_consistency() {
        let mut u = User::named("user", Type::void());
        let op = make_val("op", Type::i32());

        // Before adding, op should have no uses
        assert_eq!(op.borrow().num_uses(), 0);

        u.add_operand(op.clone());
        // After adding, op should have one use (this user)
        assert_eq!(op.borrow().num_uses(), 1);

        u.remove_operand(0);
        // After removing, op should have no uses again
        assert_eq!(op.borrow().num_uses(), 0);
    }
}