llvm-native-core 0.1.15

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
//! LLVM IR Core — unified Value/User/Instruction/Function hierarchy.
//! Clean-room behavioral reconstruction. Phase 1 — LLVM.IR.1 Court.
//!
//! Design: In LLVM C++, Value is the base class with virtual dispatch.
//! In Rust, we use a flat Value struct with an enum SubclassKind for
//! LLVM-style RTTI (isa<>, cast<>), and optional extension data for
//! operands (User), basic blocks, functions, etc.

use crate::opcode::Opcode;
use crate::types::Type;
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::{Rc, Weak};

/// Strong reference to a Value.
pub type ValueRef = Rc<RefCell<Value>>;
/// Weak reference to a Value.
pub type WeakValueRef = Weak<RefCell<Value>>;

/// A use of a Value by another Value (at a specific operand position).
#[derive(Debug, Clone)]
pub struct Use {
    pub user: WeakValueRef,
    pub operand_no: usize,
}

/// LLVM-style subclass discriminator for isa<>/cast<>.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SubclassKind {
    Value = 0,
    User = 1,
    Instruction = 2,
    Constant = 3,
    BasicBlock = 4,
    Function = 5,
    Argument = 6,
    GlobalVariable = 7,
    // Phase 2+ additions
    GlobalAlias = 8,
    GlobalIFunc = 9,
    ConstantInt = 10,
    ConstantFP = 11,
    ConstantAggregate = 12,
    ConstantData = 13,
    BinaryOp = 14,
    CastOp = 15,
    CmpOp = 16,
    PHINode = 17,
    CallInst = 18,
    LoadInst = 19,
    StoreInst = 20,
    AllocaInst = 21,
    GEPOperator = 22,
    ExtractValue = 23,
    InsertValue = 24,
    InlineAsm = 25,
    MetadataAsValue = 26,
    BlockAddress = 27,
}

impl SubclassKind {
    /// Return a human-readable name for debugging.
    pub fn as_str(&self) -> &'static str {
        match self {
            SubclassKind::Value => "Value",
            SubclassKind::User => "User",
            SubclassKind::Instruction => "Instruction",
            SubclassKind::Constant => "Constant",
            SubclassKind::BasicBlock => "BasicBlock",
            SubclassKind::Function => "Function",
            SubclassKind::Argument => "Argument",
            SubclassKind::GlobalVariable => "GlobalVariable",
            SubclassKind::GlobalAlias => "GlobalAlias",
            SubclassKind::GlobalIFunc => "GlobalIFunc",
            SubclassKind::ConstantInt => "ConstantInt",
            SubclassKind::ConstantFP => "ConstantFP",
            SubclassKind::ConstantAggregate => "ConstantAggregate",
            SubclassKind::ConstantData => "ConstantData",
            SubclassKind::BinaryOp => "BinaryOp",
            SubclassKind::CastOp => "CastOp",
            SubclassKind::CmpOp => "CmpOp",
            SubclassKind::PHINode => "PHINode",
            SubclassKind::CallInst => "CallInst",
            SubclassKind::LoadInst => "LoadInst",
            SubclassKind::StoreInst => "StoreInst",
            SubclassKind::AllocaInst => "AllocaInst",
            SubclassKind::GEPOperator => "GEPOperator",
            SubclassKind::ExtractValue => "ExtractValue",
            SubclassKind::InsertValue => "InsertValue",
            SubclassKind::InlineAsm => "InlineAsm",
            SubclassKind::MetadataAsValue => "MetadataAsValue",
            SubclassKind::BlockAddress => "BlockAddress",
        }
    }

    /// Returns true if this subclass kind is a constant flavor.
    pub fn is_constant(&self) -> bool {
        matches!(
            self,
            SubclassKind::Constant
                | SubclassKind::ConstantInt
                | SubclassKind::ConstantFP
                | SubclassKind::ConstantAggregate
                | SubclassKind::ConstantData
        )
    }

    /// Returns true if this subclass kind is an instruction.
    pub fn is_instruction(&self) -> bool {
        matches!(
            self,
            SubclassKind::Instruction
                | SubclassKind::BinaryOp
                | SubclassKind::CastOp
                | SubclassKind::CmpOp
                | SubclassKind::PHINode
                | SubclassKind::CallInst
                | SubclassKind::LoadInst
                | SubclassKind::StoreInst
                | SubclassKind::AllocaInst
                | SubclassKind::GEPOperator
                | SubclassKind::ExtractValue
                | SubclassKind::InsertValue
        )
    }
}

impl std::fmt::Display for SubclassKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

/// The central IR Value type. Every IR object (instruction, constant,
/// basic block, function, etc.) is a Value with a type, optional name,
/// use list, and subclass-specific extension data.
#[derive(Debug, Clone)]
pub struct Value {
    /// Value name (e.g., "%result", "@foo", "").
    pub name: String,
    /// The LLVM type of this value.
    pub ty: Type,
    /// Unique numeric identifier for this value.
    pub vid: u64,
    /// Subclass discriminator (LLVM-style RTTI).
    pub subclass: SubclassKind,
    /// Use-list: values that use this value.
    pub uses: Vec<Use>,
    /// The instruction opcode (only valid for Instructions).
    pub opcode: Option<Opcode>,
    /// Number of operands (for Users/Instructions).
    pub num_operands: usize,
    /// The operand values (for Users/Instructions).
    pub operands: Vec<ValueRef>,
    /// Parent function (for BasicBlocks) or parent basic block (for
    /// Instructions).
    pub parent: Option<ValueRef>,
    /// Return type (for Function values).
    pub return_type: Option<Type>,
    /// Successor blocks (for terminators).
    pub successors: Vec<ValueRef>,
    /// Additional subclass-specific data.
    pub subclass_data: u32,
    /// Extended subclass data (e.g., constant vector elements, string data).
    pub subclass_extra: Vec<u64>,
    /// Attached metadata: metadata kind ID → metadata node ID.
    pub metadata: HashMap<u32, u32>,
    /// Whether this value is used by any metadata node.
    pub is_used_by_md: bool,
    /// Basic blocks (for Function values).
    pub blocks: Vec<ValueRef>,
    /// Parameter types (for Function values).
    pub params: Vec<Type>,
    /// Instructions (for BasicBlock values).
    pub instructions: Vec<ValueRef>,
    /// Initializer value (for GlobalVariable values).
    pub initializer: Option<ValueRef>,
    /// Whether this is a constant global (for GlobalVariable values).
    pub is_constant: bool,
    /// Whether this function takes a variable number of arguments.
    pub is_vararg: bool,
    /// Result name (for instruction SSA values, aliases name for display).
    pub result: Option<String>,
    /// Linkage: true if this function should have internal (local) linkage.
    pub is_internal: bool,
}

use std::sync::atomic::{AtomicU64, Ordering};
static NEXT_VID: AtomicU64 = AtomicU64::new(0);

impl Default for Value {
    fn default() -> Self {
        Value::new(Type::void())
    }
}

impl Value {
    pub fn new(ty: Type) -> Self {
        Self {
            name: String::new(),
            ty,
            vid: NEXT_VID.fetch_add(1, Ordering::SeqCst),
            subclass: SubclassKind::Value,
            uses: Vec::new(),
            opcode: None,
            num_operands: 0,
            operands: Vec::new(),
            parent: None,
            return_type: None,
            successors: Vec::new(),
            subclass_data: 0,
            subclass_extra: Vec::new(),
            metadata: HashMap::new(),
            is_used_by_md: false,
            blocks: Vec::new(),
            params: Vec::new(),
            instructions: Vec::new(),
            initializer: None,
            is_constant: false,
            is_vararg: false,
            result: None,
            is_internal: false,
        }
    }

    pub fn named(mut self, name: impl Into<String>) -> Self {
        self.name = name.into();
        self
    }

    pub fn with_subclass(mut self, kind: SubclassKind) -> Self {
        self.subclass = kind;
        self
    }

    // === Opcode access ===

    pub fn get_opcode(&self) -> Option<Opcode> {
        self.opcode
    }

    pub fn set_opcode(&mut self, op: Opcode) {
        self.opcode = Some(op);
    }

    // === Use-def chain ===

    /// Register a use of this value by `user` at operand position
    /// `operand_no`.
    pub fn add_use(&mut self, user: WeakValueRef, operand_no: usize) {
        let existing = self
            .uses
            .iter()
            .any(|u| match (u.user.upgrade(), user.upgrade()) {
                (Some(a), Some(b)) => Rc::ptr_eq(&a, &b) && u.operand_no == operand_no,
                _ => false,
            });
        if !existing {
            self.uses.push(Use { user, operand_no });
        }
    }

    /// Remove a specific use of this value by `user`.
    /// Returns true if the use was found and removed.
    pub fn remove_use(&mut self, user: &ValueRef) -> bool {
        let before = self.uses.len();
        self.uses.retain(|u| match u.user.upgrade() {
            Some(rc) => !Rc::ptr_eq(&rc, user),
            _ => false,
        });
        self.uses.len() < before
    }

    /// Get the total number of uses of this value.
    pub fn num_uses(&self) -> usize {
        self.uses.len()
    }

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

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

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

    /// Get the number of uses (alias for num_uses).
    pub fn get_num_uses(&self) -> usize {
        self.num_uses()
    }

    /// Replace all uses of this value with `new_val`.
    /// The use-list of this value is cleared, and `new_val` gains all the
    /// uses.
    pub fn replace_all_uses_with(&mut self, new_val: &ValueRef) {
        for u in &self.uses {
            if let Some(user_rc) = u.user.upgrade() {
                let mut user = user_rc.borrow_mut();
                if u.operand_no < user.operands.len() {
                    user.operands[u.operand_no] = Rc::clone(new_val);
                    // Add use to the new value
                    new_val
                        .borrow_mut()
                        .add_use(Rc::downgrade(&user_rc), u.operand_no);
                }
            }
        }
        self.uses.clear();
    }

    /// Get the list of users (values that use this value) as strong
    /// references. Expired weak references are filtered out.
    pub fn get_uses(&self) -> Vec<ValueRef> {
        self.uses.iter().filter_map(|u| u.user.upgrade()).collect()
    }

    /// If this value has exactly one use, return that user.
    pub fn get_unique_use(&self) -> Option<ValueRef> {
        if self.uses.len() == 1 {
            self.uses[0].user.upgrade()
        } else {
            None
        }
    }

    /// Check whether this value is used outside of the given basic block.
    pub fn is_used_outside_of_block(&self, bb: &ValueRef) -> bool {
        for u in &self.uses {
            if let Some(user_rc) = u.user.upgrade() {
                let user = user_rc.borrow();
                // The user is in a different block if its parent differs
                if let Some(ref user_parent) = user.parent {
                    if !Rc::ptr_eq(user_parent, bb) {
                        return true;
                    }
                } else {
                    // No parent means it's not in the same block
                    return true;
                }
            }
        }
        false
    }

    /// Check whether this value is used within the given basic block.
    pub fn is_used_in_basic_block(&self, bb: &ValueRef) -> bool {
        for u in &self.uses {
            if let Some(user_rc) = u.user.upgrade() {
                let user = user_rc.borrow();
                if let Some(ref user_parent) = user.parent {
                    if Rc::ptr_eq(user_parent, bb) {
                        return true;
                    }
                }
            }
        }
        false
    }

    // === Operands (User interface) ===

    pub fn push_operand(&mut self, val: ValueRef) {
        let idx = self.operands.len();
        val.borrow_mut().add_use(
            Rc::downgrade(&Rc::new(RefCell::new(Value::new(Type::void())))),
            idx,
        );
        self.operands.push(val);
        self.num_operands = self.operands.len();
    }

    pub fn set_operand(&mut self, index: usize, val: ValueRef) {
        if index < self.operands.len() {
            self.operands[index] = val;
        }
    }

    pub fn operand(&self, index: usize) -> Option<ValueRef> {
        self.operands.get(index).cloned()
    }

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

    /// Get all operands.
    pub fn get_all_operands(&self) -> Vec<ValueRef> {
        self.operands.clone()
    }

    // === LLVM-style RTTI ===

    pub fn isa(&self, kind: SubclassKind) -> bool {
        self.subclass == kind
    }
    pub fn is_instruction(&self) -> bool {
        self.subclass == SubclassKind::Instruction || self.subclass.is_instruction()
    }
    pub fn is_basic_block(&self) -> bool {
        self.subclass == SubclassKind::BasicBlock
    }
    pub fn is_function(&self) -> bool {
        self.subclass == SubclassKind::Function
    }
    pub fn is_constant(&self) -> bool {
        self.subclass == SubclassKind::Constant || self.subclass.is_constant()
    }
    pub fn is_argument(&self) -> bool {
        self.subclass == SubclassKind::Argument
    }
    pub fn is_global_variable(&self) -> bool {
        self.subclass == SubclassKind::GlobalVariable
    }

    /// Get the subclass kind of this value.
    pub fn get_subclass_kind(&self) -> SubclassKind {
        self.subclass
    }

    // === Type mutation ===

    /// Mutate the type of this value. This is dangerous and should only be
    /// used during IR transformations that reshape types (e.g., pointer
    /// rewriting, opaque pointer migration).
    pub fn mutate_type(&mut self, new_type: Type) {
        self.ty = new_type;
    }

    // === Metadata ===

    /// Attach metadata to this value.
    /// `kind` is the metadata kind ID (e.g., MD_dbg = 1, MD_tbaa = 2, ...).
    /// `md_id` is the metadata node ID.
    pub fn add_metadata(&mut self, kind: u32, md_id: u32) {
        self.metadata.insert(kind, md_id);
    }

    /// Get the metadata node ID for a given kind.
    pub fn get_metadata(&self, kind: u32) -> Option<u32> {
        self.metadata.get(&kind).copied()
    }

    /// Check whether this value has any attached metadata.
    pub fn has_metadata(&self) -> bool {
        !self.metadata.is_empty()
    }

    /// Check whether this value has metadata of a specific kind.
    pub fn has_metadata_kind(&self, kind: u32) -> bool {
        self.metadata.contains_key(&kind)
    }

    /// Clear all metadata attached to this value.
    pub fn clear_metadata(&mut self) {
        self.metadata.clear();
    }

    /// Remove metadata of a specific kind.
    pub fn erase_metadata(&mut self, kind: u32) -> bool {
        self.metadata.remove(&kind).is_some()
    }

    /// Get all attached metadata as (kind, md_id) pairs.
    pub fn get_all_metadata(&self) -> Vec<(u32, u32)> {
        self.metadata.iter().map(|(k, v)| (*k, *v)).collect()
    }

    /// Mark this value as being used by metadata.
    pub fn set_used_by_md(&mut self, flag: bool) {
        self.is_used_by_md = flag;
    }

    // === Subclass data ===

    /// Set the subclass-specific data field.
    pub fn set_subclass_data(&mut self, data: u32) {
        self.subclass_data = data;
    }

    /// Get the subclass-specific data field.
    pub fn get_subclass_data(&self) -> u32 {
        self.subclass_data
    }

    // === Convenience queries ===

    /// Check if this value is a terminator instruction.
    pub fn is_terminator(&self) -> bool {
        self.opcode.map_or(false, |op| op.is_terminator())
    }

    /// Check if this value has a name.
    pub fn has_name(&self) -> bool {
        !self.name.is_empty()
    }

    /// Get the name, or a placeholder if unnamed.
    pub fn get_name_or(&self, default: &str) -> String {
        if self.name.is_empty() {
            default.to_string()
        } else {
            self.name.clone()
        }
    }
}

/// Wrap a Value in a ValueRef.
pub fn valref(v: Value) -> ValueRef {
    Rc::new(RefCell::new(v))
}

// ============================================================================
// ValueSymbolTable — maps names to ValueRefs within a scope
// ============================================================================

/// A symbol table mapping names to values within a scope (module or function).
///
/// @llvm_behavior: LLVM maintains a ValueSymbolTable for each Module and
/// Function. It ensures that each named value has a unique name within
/// its scope by auto-renaming on collision.
#[derive(Debug, Clone, Default)]
pub struct ValueSymbolTable {
    /// Maps names to values.
    entries: std::collections::HashMap<String, ValueRef>,
    /// Counter for generating unique names.
    next_id: u64,
}

impl ValueSymbolTable {
    pub fn new() -> Self {
        Self {
            entries: std::collections::HashMap::new(),
            next_id: 0,
        }
    }

    /// Look up a value by name. Returns None if not found.
    pub fn lookup(&self, name: &str) -> Option<ValueRef> {
        self.entries.get(name).cloned()
    }

    /// Insert a value into the symbol table. If the name collides,
    /// auto-rename to `name.N` where N is a unique integer.
    pub fn insert(&mut self, name: &str, val: ValueRef) -> String {
        let key = if self.entries.contains_key(name) {
            let new_name = format!("{}.{}", name, self.next_id);
            self.next_id += 1;
            val.borrow_mut().name = new_name.clone();
            new_name
        } else {
            name.to_string()
        };
        self.entries.insert(key.clone(), val);
        key
    }

    /// Remove a value by name.
    pub fn remove(&mut self, name: &str) -> Option<ValueRef> {
        self.entries.remove(name)
    }

    /// Check if a name exists in the table.
    pub fn contains(&self, name: &str) -> bool {
        self.entries.contains_key(name)
    }

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

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

    /// Iterate over all name-value pairs.
    pub fn iter(&self) -> impl Iterator<Item = (&String, &ValueRef)> {
        self.entries.iter()
    }

    /// Clear all entries.
    pub fn clear(&mut self) {
        self.entries.clear();
        self.next_id = 0;
    }
}

// ============================================================================
// ValueMap — maps ValueRef→ValueRef for value replacement
// ============================================================================

/// A mapping from one ValueRef to another, used for RAUW (Replace All Uses
/// With), cloning, and inlining.
#[derive(Debug, Clone, Default)]
pub struct ValueMap {
    entries: std::collections::HashMap<*const Value, ValueRef>,
}

impl ValueMap {
    pub fn new() -> Self {
        Self {
            entries: std::collections::HashMap::new(),
        }
    }

    /// Insert a mapping from `from` to `to`.
    pub fn insert(&mut self, from: &ValueRef, to: ValueRef) {
        let key = Rc::as_ptr(from) as *const Value;
        self.entries.insert(key, to);
    }

    /// Look up the mapped value for `from`, if any.
    pub fn lookup(&self, from: &ValueRef) -> Option<ValueRef> {
        let key = Rc::as_ptr(from) as *const Value;
        self.entries.get(&key).cloned()
    }

    /// Check if a mapping exists for `from`.
    pub fn contains(&self, from: &ValueRef) -> bool {
        let key = Rc::as_ptr(from) as *const Value;
        self.entries.contains_key(&key)
    }

    /// Remove the mapping for `from`.
    pub fn remove(&mut self, from: &ValueRef) -> Option<ValueRef> {
        let key = Rc::as_ptr(from) as *const Value;
        self.entries.remove(&key)
    }

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

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

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

    /// Apply this map to a value: if the value has a mapping, return the
    /// mapped value; otherwise return the original.
    pub fn map_value(&self, val: &ValueRef) -> ValueRef {
        self.lookup(val).unwrap_or_else(|| val.clone())
    }
}

// ============================================================================
// Value utilities
// ============================================================================

/// Strip pointer casts from a value, returning the underlying value.
pub fn strip_pointer_casts(val: &ValueRef) -> ValueRef {
    let mut current = val.clone();
    loop {
        let next = {
            let v = current.borrow();
            if let Some(opcode) = &v.opcode {
                match opcode {
                    crate::opcode::Opcode::BitCast
                    | crate::opcode::Opcode::IntToPtr
                    | crate::opcode::Opcode::PtrToInt => v.operands.first().cloned(),
                    _ => None,
                }
            } else {
                None
            }
        };
        match next {
            Some(n) => current = n,
            None => break,
        }
    }
    current
}

/// Check if a value is a constant (not an instruction or argument).
pub fn is_constant(val: &ValueRef) -> bool {
    let v = val.borrow();
    matches!(
        v.subclass,
        SubclassKind::Constant | SubclassKind::GlobalVariable
    )
}

/// Check if a value is an instruction.
pub fn is_instruction(val: &ValueRef) -> bool {
    val.borrow().subclass == SubclassKind::Instruction
}

/// Check if a value is an argument.
pub fn is_argument(val: &ValueRef) -> bool {
    val.borrow().subclass == SubclassKind::Argument
}

/// Check if a value is a basic block.
pub fn is_basic_block(val: &ValueRef) -> bool {
    val.borrow().subclass == SubclassKind::BasicBlock
}

/// Check if a value is a function.
pub fn is_function(val: &ValueRef) -> bool {
    val.borrow().subclass == SubclassKind::Function
}

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

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

    /// Helper: create a basic ValueRef.
    fn make_value(name: &str, ty: Type) -> ValueRef {
        valref(Value::new(ty).named(name))
    }

    /// Helper: create a user ValueRef that can hold operands.
    fn make_user(name: &str) -> (ValueRef, ValueRef) {
        let self_rc = valref(
            Value::new(Type::void())
                .named(name)
                .with_subclass(SubclassKind::User),
        );
        // Return a self-reference for the downgrade hack
        (self_rc.clone(), self_rc)
    }

    #[test]
    fn test_value_creation() {
        let v = Value::new(Type::i32()).named("x");
        assert_eq!(v.name, "x");
        assert!(v.ty.is_integer());
        assert_eq!(v.subclass, SubclassKind::Value);
        assert_eq!(v.subclass_data, 0);
    }

    #[test]
    fn test_valref() {
        let v = valref(Value::new(Type::float()).named("f"));
        assert_eq!(v.borrow().name, "f");
    }

    #[test]
    fn test_subclass_kind() {
        let v = Value::new(Type::void()).with_subclass(SubclassKind::GlobalVariable);
        assert_eq!(v.get_subclass_kind(), SubclassKind::GlobalVariable);
        assert!(v.is_global_variable());
        assert!(!v.is_instruction());
    }

    #[test]
    fn test_subclass_kind_display() {
        assert_eq!(SubclassKind::Function.to_string(), "Function");
        assert_eq!(SubclassKind::PHINode.to_string(), "PHINode");
        assert_eq!(SubclassKind::BlockAddress.to_string(), "BlockAddress");
    }

    #[test]
    fn test_subclass_kind_is_constant() {
        assert!(SubclassKind::Constant.is_constant());
        assert!(SubclassKind::ConstantInt.is_constant());
        assert!(SubclassKind::ConstantFP.is_constant());
        assert!(!SubclassKind::Instruction.is_constant());
        assert!(!SubclassKind::Function.is_constant());
    }

    #[test]
    fn test_subclass_kind_is_instruction() {
        assert!(SubclassKind::Instruction.is_instruction());
        assert!(SubclassKind::BinaryOp.is_instruction());
        assert!(SubclassKind::PHINode.is_instruction());
        assert!(!SubclassKind::Constant.is_instruction());
        assert!(!SubclassKind::Function.is_instruction());
    }

    #[test]
    fn test_add_use_and_num_uses() {
        let val = make_value("used", Type::i32());
        let user = make_value("user", Type::void());
        {
            val.borrow_mut().add_use(Rc::downgrade(&user), 0);
        }
        assert_eq!(val.borrow().num_uses(), 1);
        assert!(!val.borrow().use_empty());
    }

    #[test]
    fn test_has_one_use() {
        let val = make_value("used", Type::i32());
        let user1 = make_value("user1", Type::void());
        {
            val.borrow_mut().add_use(Rc::downgrade(&user1), 0);
        }
        assert!(val.borrow().has_one_use());
        assert!(val.borrow().has_n_uses(1));
        assert!(!val.borrow().has_n_uses(2));
    }

    #[test]
    fn test_remove_use() {
        let val = make_value("used", Type::i32());
        let user1 = make_value("user1", Type::void());
        let user2 = make_value("user2", Type::void());
        {
            let mut v = val.borrow_mut();
            v.add_use(Rc::downgrade(&user1), 0);
            v.add_use(Rc::downgrade(&user2), 1);
        }
        assert_eq!(val.borrow().num_uses(), 2);

        {
            let mut v = val.borrow_mut();
            assert!(v.remove_use(&user1));
        }
        assert_eq!(val.borrow().num_uses(), 1);
    }

    #[test]
    fn test_get_uses() {
        let val = make_value("used", Type::i32());
        let user = make_value("user", Type::void());
        {
            val.borrow_mut().add_use(Rc::downgrade(&user), 0);
        }
        let users = val.borrow().get_uses();
        assert_eq!(users.len(), 1);
        assert!(Rc::ptr_eq(&users[0], &user));
    }

    #[test]
    fn test_get_unique_use() {
        let val = make_value("used", Type::i32());
        let user = make_value("user", Type::void());
        {
            val.borrow_mut().add_use(Rc::downgrade(&user), 0);
        }
        let unique = val.borrow().get_unique_use().unwrap();
        assert!(Rc::ptr_eq(&unique, &user));

        // Add second use → no longer unique
        let user2 = make_value("user2", Type::void());
        {
            val.borrow_mut().add_use(Rc::downgrade(&user2), 0);
        }
        assert!(val.borrow().get_unique_use().is_none());
    }

    #[test]
    fn test_replace_all_uses_with() {
        let val = make_value("old", Type::i32());
        let new_val = make_value("new", Type::i32());

        // Create a "user" instruction that uses old
        let user = make_value("user", Type::void());
        {
            let mut u = user.borrow_mut();
            u.operands.push(Rc::clone(&val));
            u.num_operands = 1;
        }
        {
            val.borrow_mut().add_use(Rc::downgrade(&user), 0);
        }

        // Replace
        {
            val.borrow_mut().replace_all_uses_with(&new_val);
        }

        // Old should have no uses
        assert!(val.borrow().use_empty());
        // User should now refer to new_val
        let u = user.borrow();
        assert!(Rc::ptr_eq(&u.operands[0], &new_val));
        // New should have the use
        assert_eq!(new_val.borrow().num_uses(), 1);
    }

    #[test]
    fn test_mutate_type() {
        let mut v = Value::new(Type::i32());
        assert!(v.ty.is_integer());
        v.mutate_type(Type::i64());
        assert_eq!(v.ty.integer_bit_width(), 64);
    }

    #[test]
    fn test_metadata() {
        let mut v = Value::new(Type::i32());
        assert!(!v.has_metadata());
        v.add_metadata(1, 42); // kind 1 (dbg), node 42
        assert!(v.has_metadata());
        assert!(v.has_metadata_kind(1));
        assert!(!v.has_metadata_kind(2));
        assert_eq!(v.get_metadata(1), Some(42));
        assert_eq!(v.get_metadata(2), None);

        let all = v.get_all_metadata();
        assert_eq!(all.len(), 1);
        assert_eq!(all[0], (1, 42));

        assert!(v.erase_metadata(1));
        assert!(!v.has_metadata());
        assert!(!v.erase_metadata(1)); // already gone
    }

    #[test]
    fn test_clear_metadata() {
        let mut v = Value::new(Type::i32());
        v.add_metadata(1, 10);
        v.add_metadata(2, 20);
        assert_eq!(v.get_all_metadata().len(), 2);
        v.clear_metadata();
        assert!(!v.has_metadata());
    }

    #[test]
    fn test_subclass_data() {
        let mut v = Value::new(Type::i32());
        assert_eq!(v.get_subclass_data(), 0);
        v.set_subclass_data(0xDEAD);
        assert_eq!(v.get_subclass_data(), 0xDEAD);
    }

    #[test]
    fn test_is_used_by_md() {
        let mut v = Value::new(Type::i32());
        assert!(!v.is_used_by_md);
        v.set_used_by_md(true);
        assert!(v.is_used_by_md);
        v.set_used_by_md(false);
        assert!(!v.is_used_by_md);
    }

    #[test]
    fn test_is_used_outside_of_block() {
        let val = make_value("v", Type::i32());
        let bb1 = make_value("bb1", Type::label());
        let bb2 = make_value("bb2", Type::label());

        let user_in_bb1 = make_value("u1", Type::void());
        user_in_bb1.borrow_mut().parent = Some(Rc::clone(&bb1));

        let user_in_bb2 = make_value("u2", Type::void());
        user_in_bb2.borrow_mut().parent = Some(Rc::clone(&bb2));

        {
            let mut v = val.borrow_mut();
            v.add_use(Rc::downgrade(&user_in_bb1), 0);
            v.add_use(Rc::downgrade(&user_in_bb2), 1);
        }

        // val is used in bb1 and bb2, so it IS used outside of bb1
        assert!(val.borrow().is_used_outside_of_block(&bb1));
        // val IS used in bb1
        assert!(val.borrow().is_used_in_basic_block(&bb1));
        assert!(val.borrow().is_used_in_basic_block(&bb2));
    }

    #[test]
    fn test_is_terminator() {
        let mut v = Value::new(Type::void());
        assert!(!v.is_terminator());
        v.set_opcode(Opcode::Ret);
        assert!(v.is_terminator());
        v.set_opcode(Opcode::Add);
        assert!(!v.is_terminator());
    }

    #[test]
    fn test_has_name() {
        let v = Value::new(Type::i32());
        assert!(!v.has_name());
        let v = Value::new(Type::i32()).named("x");
        assert!(v.has_name());
    }

    #[test]
    fn test_get_name_or() {
        let v = Value::new(Type::i32()).named("real");
        assert_eq!(v.get_name_or("default"), "real");
        let v = Value::new(Type::i32());
        assert_eq!(v.get_name_or("default"), "default");
    }

    #[test]
    fn test_get_num_operands() {
        let mut v = Value::new(Type::void());
        assert_eq!(v.get_num_operands(), 0);
        let op = make_value("op", Type::i32());
        v.push_operand(op);
        assert_eq!(v.get_num_operands(), 1);
    }

    #[test]
    fn test_get_all_operands() {
        let mut v = Value::new(Type::void());
        let op1 = make_value("op1", Type::i32());
        let op2 = make_value("op2", Type::i32());
        v.push_operand(op1.clone());
        v.push_operand(op2.clone());
        let ops = v.get_all_operands();
        assert_eq!(ops.len(), 2);
        assert!(Rc::ptr_eq(&ops[0], &op1));
        assert!(Rc::ptr_eq(&ops[1], &op2));
    }

    #[test]
    fn test_add_use_dedup() {
        let val = make_value("v", Type::i32());
        let user = make_value("u", Type::void());
        {
            let mut v = val.borrow_mut();
            v.add_use(Rc::downgrade(&user), 0);
            v.add_use(Rc::downgrade(&user), 0); // duplicate
        }
        assert_eq!(val.borrow().num_uses(), 1);
    }

    #[test]
    fn test_empty_use_list_queries() {
        let val = make_value("v", Type::i32());
        assert!(val.borrow().get_uses().is_empty());
        assert!(val.borrow().get_unique_use().is_none());
        assert_eq!(val.borrow().get_num_uses(), 0);
        assert!(val.borrow().use_empty());
    }
}