llvm-native-core 0.1.12

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
//! C++ Run-Time Type Information (RTTI) — implements type_info emission,
//! type descriptor generation, and dynamic_cast support.
//!
//! Follows the Itanium C++ ABI for RTTI layout:
//! - type_info: basic type descriptor (vtable + name string)
//! - __class_type_info: type_info + nothing extra
//! - __si_class_type_info: single inheritance
//! - __vmi_class_type_info: multiple/virtual inheritance
//! - __pbase_type_info, __pointer_type_info, etc.
//!
//! Clean-room behavioral reconstruction from:
//! - Itanium C++ ABI (v1.86), §2.9 "RTTI"
//! - C++ Standard §18.7 (typeinfo)
//! - No LLVM/Clang source code is consulted.

use std::collections::HashMap;

use super::name_mangling::{MangledName, Mangler};

// ═══════════════════════════════════════════════════════════════════════════════
// RTTI Descriptor Kinds
// ═══════════════════════════════════════════════════════════════════════════════

/// The kind of RTTI descriptor.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RttiKind {
    /// Fundamental type (int, double, etc.)
    Fundamental,
    /// Pointer type
    Pointer,
    /// Pointer to member type
    PointerToMember,
    /// Array type
    Array,
    /// Function type
    Function,
    /// Enum type
    Enum,
    /// Class without bases
    Class,
    /// Class with single non-virtual base
    SiClass,
    /// Class with multiple or virtual bases
    VmiClass,
}

impl RttiKind {
    /// The name of the C++ RTTI class for this kind.
    pub fn class_name(&self) -> &'static str {
        match self {
            RttiKind::Fundamental => "type_info",
            RttiKind::Pointer => "__pointer_type_info",
            RttiKind::PointerToMember => "__pointer_to_member_type_info",
            RttiKind::Array => "__array_type_info",
            RttiKind::Function => "__function_type_info",
            RttiKind::Enum => "__enum_type_info",
            RttiKind::Class => "__class_type_info",
            RttiKind::SiClass => "__si_class_type_info",
            RttiKind::VmiClass => "__vmi_class_type_info",
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// RTTI Descriptor
// ═══════════════════════════════════════════════════════════════════════════════

/// A complete RTTI type descriptor.
#[derive(Debug, Clone)]
pub struct RttiDescriptor {
    /// The type name (demangled, e.g., "MyClass").
    pub type_name: String,
    /// The mangled typeinfo symbol (e.g., `_ZTI7MyClass`).
    pub typeinfo_symbol: MangledName,
    /// The mangled typeinfo name symbol (e.g., `_ZTS7MyClass`).
    pub typeinfo_name_symbol: MangledName,
    /// The RTTI kind.
    pub kind: RttiKind,
    /// The vtable pointer (points to the type_info vtable).
    pub vtable_ptr: String,
    /// The human-readable type name stored in the RTTI.
    pub name_string: String,
    /// For __si_class_type_info: the base class typeinfo.
    pub base_type: Option<Box<RttiDescriptor>>,
    /// For __vmi_class_type_info: base class info with flags/offsets.
    pub base_info: Vec<BaseClassTypeInfo>,
    /// For pointer types: the pointee typeinfo.
    pub pointee_type: Option<Box<RttiDescriptor>>,
}

/// Information about a base class in a vmi_class_type_info descriptor.
#[derive(Debug, Clone)]
pub struct BaseClassTypeInfo {
    /// The typeinfo of the base class.
    pub typeinfo: Box<RttiDescriptor>,
    /// Flags: bit 0 = is_virtual, bit 1 = is_public
    pub flags: u32,
    /// Offset of the base within the derived class.
    pub offset: i64,
}

impl RttiDescriptor {
    pub fn new(
        type_name: &str,
        typeinfo_symbol: MangledName,
        typeinfo_name_symbol: MangledName,
        kind: RttiKind,
    ) -> Self {
        Self {
            type_name: type_name.to_string(),
            typeinfo_symbol,
            typeinfo_name_symbol,
            kind,
            vtable_ptr: String::new(),
            name_string: type_name.to_string(),
            base_type: None,
            base_info: Vec::new(),
            pointee_type: None,
        }
    }

    /// Generate the LLVM IR for the typeinfo name string.
    pub fn emit_name_ir(&self) -> String {
        format!(
            "@{} = private unnamed_addr constant [{} x i8] c\"{}\\00\", align 1\n",
            self.typeinfo_name_symbol,
            self.name_string.len() + 1,
            self.name_string
        )
    }

    /// Generate the LLVM IR for the typeinfo descriptor.
    pub fn emit_typeinfo_ir(&self) -> String {
        let mut ir = String::new();

        match self.kind {
            RttiKind::Fundamental | RttiKind::Enum | RttiKind::Function => {
                ir.push_str(&format!(
                    "@{} = private constant {{ ptr, ptr }} {{\n",
                    self.typeinfo_symbol
                ));
                ir.push_str(&format!("  ptr {}, ; vtable\n", self.vtable_ptr));
                ir.push_str(&format!("  ptr @{} ; name\n", self.typeinfo_name_symbol));
                ir.push_str("}, align 8\n");
            }
            RttiKind::Pointer => {
                ir.push_str(&format!(
                    "@{} = private constant {{ ptr, ptr, ptr }} {{\n",
                    self.typeinfo_symbol
                ));
                ir.push_str(&format!("  ptr {}, ; vtable\n", self.vtable_ptr));
                ir.push_str(&format!("  ptr @{}, ; name\n", self.typeinfo_name_symbol));
                if let Some(ref pointee) = self.pointee_type {
                    ir.push_str(&format!(
                        "  ptr @{} ; pointee typeinfo\n",
                        pointee.typeinfo_symbol
                    ));
                } else {
                    ir.push_str("  ptr null ; pointee typeinfo\n");
                }
                ir.push_str("}, align 8\n");
            }
            RttiKind::Class => {
                ir.push_str(&format!(
                    "@{} = private constant {{ ptr, ptr }} {{\n",
                    self.typeinfo_symbol
                ));
                ir.push_str(&format!("  ptr {}, ; vtable\n", self.vtable_ptr));
                ir.push_str(&format!("  ptr @{} ; name\n", self.typeinfo_name_symbol));
                ir.push_str("}, align 8\n");
            }
            RttiKind::SiClass => {
                ir.push_str(&format!(
                    "@{} = private constant {{ ptr, ptr, ptr }} {{\n",
                    self.typeinfo_symbol
                ));
                ir.push_str(&format!("  ptr {}, ; vtable\n", self.vtable_ptr));
                ir.push_str(&format!("  ptr @{}, ; name\n", self.typeinfo_name_symbol));
                if let Some(ref base) = self.base_type {
                    ir.push_str(&format!(
                        "  ptr @{} ; base typeinfo\n",
                        base.typeinfo_symbol
                    ));
                } else {
                    ir.push_str("  ptr null ; base typeinfo\n");
                }
                ir.push_str("}, align 8\n");
            }
            RttiKind::VmiClass => {
                let base_count = self.base_info.len();
                ir.push_str(&format!(
                    "@{} = private constant {{ ptr, ptr, i32, i32, [{} x {{ ptr, i64 }}] }} {{\n",
                    self.typeinfo_symbol, base_count
                ));
                ir.push_str(&format!("  ptr {}, ; vtable\n", self.vtable_ptr));
                ir.push_str(&format!("  ptr @{}, ; name\n", self.typeinfo_name_symbol));
                ir.push_str(&format!("  i32 {}, ; flags\n", 0u32));
                ir.push_str(&format!("  i32 {}, ; base count\n", base_count));
                ir.push_str("  [");
                for (i, base) in self.base_info.iter().enumerate() {
                    if i > 0 {
                        ir.push_str(", ");
                    }
                    ir.push_str(&format!(
                        "{{ ptr @{}, i64 {} }}",
                        base.typeinfo.typeinfo_symbol, base.offset
                    ));
                }
                ir.push_str("]\n}, align 8\n");
            }
            _ => {}
        }

        ir
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// RTTI Builder
// ═══════════════════════════════════════════════════════════════════════════════

/// Builds RTTI descriptors for types in a translation unit.
pub struct RttiBuilder {
    mangler: Mangler,
    descriptors: HashMap<String, RttiDescriptor>,
    /// The type_info vtable pointer (platform-specific, typically null or
    /// a reference to the C++ ABI library's vtable).
    typeinfo_vtable: String,
}

impl RttiBuilder {
    pub fn new() -> Self {
        Self {
            mangler: Mangler::new(),
            descriptors: HashMap::new(),
            typeinfo_vtable: "null".to_string(),
        }
    }

    /// Set the typeinfo vtable pointer symbol.
    pub fn set_typeinfo_vtable(&mut self, vtable: &str) {
        self.typeinfo_vtable = vtable.to_string();
    }

    /// Build an RTTI descriptor for a class type.
    pub fn build_class_rtti(
        &mut self,
        class_name: &str,
        bases: &[(String, bool, bool)], // (base_name, is_virtual, is_direct)
    ) -> &RttiDescriptor {
        let typeinfo_name = self.mangler.mangle_typeinfo_name(class_name);
        let typeinfo = self.mangler.mangle_typeinfo(class_name);

        let kind = if bases.is_empty() {
            RttiKind::Class
        } else if bases.len() == 1 && !bases[0].1 {
            RttiKind::SiClass
        } else {
            RttiKind::VmiClass
        };

        let mut desc = RttiDescriptor::new(class_name, typeinfo, typeinfo_name, kind);
        desc.vtable_ptr = self.typeinfo_vtable.clone();
        desc.name_string = class_name.to_string();

        match kind {
            RttiKind::SiClass => {
                // Build base typeinfo first
                let base_name = &bases[0].0;
                self.build_class_rtti(base_name, &[]);
                if let Some(base) = self.descriptors.get(base_name) {
                    desc.base_type = Some(Box::new(base.clone()));
                }
            }
            RttiKind::VmiClass => {
                for (base_name, is_virtual, _) in bases {
                    self.build_class_rtti(base_name, &[]);
                    if let Some(base) = self.descriptors.get(base_name) {
                        desc.base_info.push(BaseClassTypeInfo {
                            typeinfo: Box::new(base.clone()),
                            flags: if *is_virtual { 1u32 } else { 0u32 } | 2u32, // public
                            offset: 0,                                           // simplified
                        });
                    }
                }
            }
            _ => {}
        }

        self.descriptors
            .insert(class_name.to_string(), desc.clone());
        self.descriptors.get(class_name).unwrap()
    }

    /// Build an RTTI descriptor for a fundamental type.
    pub fn build_fundamental_rtti(&mut self, type_name: &str) -> &RttiDescriptor {
        let typeinfo_name = self.mangler.mangle_typeinfo_name(type_name);
        let typeinfo = self.mangler.mangle_typeinfo(type_name);

        let desc = RttiDescriptor::new(type_name, typeinfo, typeinfo_name, RttiKind::Fundamental);
        self.descriptors.insert(type_name.to_string(), desc.clone());
        self.descriptors.get(type_name).unwrap()
    }

    /// Build an RTTI descriptor for a pointer type.
    pub fn build_pointer_rtti(&mut self, pointee_name: &str) -> &RttiDescriptor {
        let pointer_name = format!("P{}", pointee_name);
        let typeinfo_name = self.mangler.mangle_typeinfo_name(&pointer_name);
        let typeinfo = self.mangler.mangle_typeinfo(&pointer_name);

        let mut desc =
            RttiDescriptor::new(&pointer_name, typeinfo, typeinfo_name, RttiKind::Pointer);
        desc.vtable_ptr = self.typeinfo_vtable.clone();

        // Build pointee typeinfo
        self.build_fundamental_rtti(pointee_name);
        if let Some(pointee) = self.descriptors.get(pointee_name) {
            desc.pointee_type = Some(Box::new(pointee.clone()));
        }

        let pointer_name_clone = pointer_name.clone();
        self.descriptors.insert(pointer_name, desc.clone());
        self.descriptors.get(&pointer_name_clone).unwrap()
    }

    /// Get a previously built descriptor.
    pub fn get_descriptor(&self, name: &str) -> Option<&RttiDescriptor> {
        self.descriptors.get(name)
    }

    /// Emit all RTTI data as LLVM IR.
    pub fn emit_all_ir(&self) -> String {
        let mut ir = String::new();
        ir.push_str("; RTTI Type Descriptors\n");

        // Emit name strings first
        for desc in self.descriptors.values() {
            ir.push_str(&desc.emit_name_ir());
        }
        ir.push('\n');

        // Emit typeinfo descriptors
        for desc in self.descriptors.values() {
            ir.push_str(&desc.emit_typeinfo_ir());
            ir.push('\n');
        }

        ir
    }

    /// Generate the dynamic_cast helper logic (LLVM IR).
    /// This is a simplified version — full dynamic_cast requires
    /// walking the class hierarchy at runtime.
    pub fn emit_dynamic_cast_helper(&self) -> String {
        r#"
; Dynamic cast helper — walks the class hierarchy.
; In a full implementation, this would be in libcxxabi.
define ptr @__dynamic_cast(ptr %obj, ptr %src_typeinfo, ptr %dst_typeinfo, i64 %hint) {
entry:
  ; Simplified: just check if types are equal
  %cmp = icmp eq ptr %src_typeinfo, %dst_typeinfo
  br i1 %cmp, label %success, label %walk_bases

walk_bases:
  ; Check __si_class_type_info base
  %si_vtable = getelementptr ptr, ptr %src_typeinfo, i32 0
  %si_base_ptr = getelementptr ptr, ptr %src_typeinfo, i32 2
  %si_base = load ptr, ptr %si_base_ptr
  %has_base = icmp ne ptr %si_base, null
  br i1 %has_base, label %recurse, label %fail

recurse:
  %result = call ptr @__dynamic_cast(ptr %obj, ptr %si_base, ptr %dst_typeinfo, i64 0)
  %found = icmp ne ptr %result, null
  br i1 %found, label %success, label %fail

success:
  ret ptr %obj

fail:
  ret ptr null
}
"#
        .to_string()
    }
}

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

// ═══════════════════════════════════════════════════════════════════════════════
// RTTI Constants
// ═══════════════════════════════════════════════════════════════════════════════

/// Well-known type_info vtable symbols.
pub mod typeinfo_vtables {
    /// Standard type_info vtable for Linux (provided by libstdc++).
    pub const GCC_LINUX_TYPEINFO_VTABLE: &str = "_ZTVN10__cxxabiv117__class_type_infoE";
    /// SI class type_info vtable.
    pub const GCC_LINUX_SI_CLASS_TYPEINFO_VTABLE: &str = "_ZTVN10__cxxabiv120__si_class_type_infoE";
    /// VMI class type_info vtable.
    pub const GCC_LINUX_VMI_CLASS_TYPEINFO_VTABLE: &str =
        "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
    /// Pointer type_info vtable.
    pub const GCC_LINUX_POINTER_TYPEINFO_VTABLE: &str = "_ZTVN10__cxxabiv119__pointer_type_infoE";
}

// ═══════════════════════════════════════════════════════════════════════════════
// type_info Generation Per Class with Mangled Name
// ═══════════════════════════════════════════════════════════════════════════════

/// Generates the complete type_info for a class, including mangled name
/// and vtable pointer.
#[derive(Debug, Clone)]
pub struct TypeInfoGenerator {
    /// The class name (demangled).
    pub class_name: String,
    /// The mangled type_info symbol.
    pub typeinfo_sym: String,
    /// The mangled type_info name symbol.
    pub typeinfo_name_sym: String,
    /// The type_info vtable symbol to reference.
    pub vtable_sym: String,
}

impl TypeInfoGenerator {
    pub fn new(class_name: &str, mangler: &mut Mangler) -> Self {
        let typeinfo_name_sym = mangler.mangle_typeinfo_name(class_name).into_string();
        let typeinfo_sym = mangler.mangle_typeinfo(class_name).into_string();
        Self {
            class_name: class_name.to_string(),
            typeinfo_sym,
            typeinfo_name_sym,
            vtable_sym: String::new(),
        }
    }

    /// Set the type_info vtable pointer.
    pub fn with_vtable(mut self, vtable: &str) -> Self {
        self.vtable_sym = vtable.to_string();
        self
    }

    /// Emit the complete type_info object as LLVM IR.
    pub fn emit_complete_ir(&self, kind: RttiKind) -> String {
        let mut ir = String::new();

        // Emit the type_info name string in .rodata
        ir.push_str(&format!(
            "@{} = private unnamed_addr constant [{} x i8] c\"{}\\00\", align 1, section \".rodata\"\n",
            self.typeinfo_name_sym,
            self.class_name.len() + 1,
            self.class_name
        ));

        // Emit the type_info descriptor in .data.rel.ro
        let section = get_rtti_section(kind);
        match kind {
            RttiKind::Class | RttiKind::Fundamental | RttiKind::Enum => {
                ir.push_str(&format!(
                    "@{} = private constant {{ ptr, ptr }} {{ ptr {}, ptr @{} }}, align 8, section \"{}\"\n",
                    self.typeinfo_sym,
                    self.vtable_sym,
                    self.typeinfo_name_sym,
                    section
                ));
            }
            RttiKind::SiClass => {
                ir.push_str(&format!(
                    "@{} = private constant {{ ptr, ptr, ptr }} {{ ptr {}, ptr @{}, ptr null }}, align 8, section \"{}\"\n",
                    self.typeinfo_sym,
                    self.vtable_sym,
                    self.typeinfo_name_sym,
                    section
                ));
            }
            RttiKind::VmiClass => {
                ir.push_str(&format!(
                    "@{} = private constant {{ ptr, ptr, i32, i32, [0 x {{ ptr, i64 }}] }} {{ ptr {}, ptr @{}, i32 0, i32 0, zeroinitializer }}, align 8, section \"{}\"\n",
                    self.typeinfo_sym,
                    self.vtable_sym,
                    self.typeinfo_name_sym,
                    section
                ));
            }
            RttiKind::Pointer => {
                ir.push_str(&format!(
                    "@{} = private constant {{ ptr, ptr, ptr }} {{ ptr {}, ptr @{}, ptr null }}, align 8, section \"{}\"\n",
                    self.typeinfo_sym,
                    self.vtable_sym,
                    self.typeinfo_name_sym,
                    section
                ));
            }
            _ => {}
        }

        ir
    }
}

/// Get the ELF section for a given RTTI kind.
fn get_rtti_section(kind: RttiKind) -> &'static str {
    match kind {
        RttiKind::Fundamental
        | RttiKind::Class
        | RttiKind::SiClass
        | RttiKind::VmiClass
        | RttiKind::Pointer
        | RttiKind::PointerToMember
        | RttiKind::Array
        | RttiKind::Function
        | RttiKind::Enum => ".data.rel.ro",
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// type_info Comparison Operator (before)
// ═══════════════════════════════════════════════════════════════════════════════

/// The `type_info::before()` comparison — orders type_info objects for use
/// in associative containers.
#[derive(Debug, Clone)]
pub struct TypeInfoOrdering {
    /// The first type_info symbol.
    pub lhs: String,
    /// The second type_info symbol.
    pub rhs: String,
    /// The comparison result.
    pub result: bool,
}

impl TypeInfoOrdering {
    pub fn new(lhs: &str, rhs: &str) -> Self {
        Self {
            lhs: lhs.to_string(),
            rhs: rhs.to_string(),
            result: false,
        }
    }

    /// Compare two type_info objects: returns `true` if `lhs` is before `rhs`.
    /// Per the Itanium ABI, the ordering is based on the mangled name string.
    pub fn compare(&mut self) -> bool {
        self.result = self.lhs < self.rhs;
        self.result
    }

    /// Generate the IR for `type_info::before(const type_info&) const`.
    pub fn gen_before_ir(&self) -> String {
        format!(
            r#"; type_info::before comparison
  %lhs.name.ptr = getelementptr inbounds {{ ptr, ptr }}, ptr %{}, i32 0, i32 1
  %lhs.name = load ptr, ptr %lhs.name.ptr
  %rhs.name.ptr = getelementptr inbounds {{ ptr, ptr }}, ptr %{}, i32 0, i32 1
  %rhs.name = load ptr, ptr %rhs.name.ptr
  %cmp = call i32 @strcmp(ptr %lhs.name, ptr %rhs.name)
  %result = icmp slt i32 %cmp, 0
  ret i1 %result
"#,
            self.lhs, self.rhs
        )
    }

    /// Generate the `operator==` comparison (simple pointer equality).
    pub fn gen_equals_ir(lhs: &str, rhs: &str) -> String {
        format!("  %eq = icmp eq ptr @{}, ptr @{}\n  ret i1 %eq\n", lhs, rhs)
    }

    /// Generate the `operator!=` comparison.
    pub fn gen_not_equals_ir(lhs: &str, rhs: &str) -> String {
        format!(
            "  %neq = icmp ne ptr @{}, ptr @{}\n  ret i1 %neq\n",
            lhs, rhs
        )
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// dynamic_cast Lowering
// ═══════════════════════════════════════════════════════════════════════════════

/// Lowering strategy for dynamic_cast operations.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DynCastStrategy {
    /// Same type — no conversion needed.
    Identity,
    /// Downcast — check type_info equality and adjust pointer.
    Downcast,
    /// Cross-cast — walk both hierarchies to find a common base.
    CrossCast,
    /// Cast to void* — return the most-derived object address.
    ToVoid,
}

/// Configuration for dynamic_cast lowering.
#[derive(Debug, Clone)]
pub struct DynCastLowering {
    /// The source type.
    pub source_type: String,
    /// The target type.
    pub target_type: String,
    /// The strategy to use.
    pub strategy: DynCastStrategy,
    /// Whether this is a reference cast (throws std::bad_cast on failure).
    pub is_ref_cast: bool,
    /// Class hierarchy depth for runtime walk.
    pub hierarchy_depth: usize,
}

impl DynCastLowering {
    pub fn new(source: &str, target: &str) -> Self {
        let strategy = if source == target {
            DynCastStrategy::Identity
        } else if target == "void" {
            DynCastStrategy::ToVoid
        } else {
            DynCastStrategy::Downcast
        };

        Self {
            source_type: source.to_string(),
            target_type: target.to_string(),
            strategy,
            is_ref_cast: false,
            hierarchy_depth: 0,
        }
    }

    /// Generate the IR for the dynamic_cast operation.
    pub fn gen_dynamic_cast_ir(&self, object: &str) -> String {
        match self.strategy {
            DynCastStrategy::Identity => {
                format!(
                    "  ; dynamic_cast: {}{} (identity)\n  ret ptr {}\n",
                    self.source_type, self.target_type, object
                )
            }
            DynCastStrategy::ToVoid => {
                format!(
                    "  ; dynamic_cast: {} → void*\n  %vtable = load ptr, ptr {}\n  %offset = getelementptr inbounds i64, ptr %vtable, i64 -1\n  %offset.val = load i64, ptr %offset\n  %adj = getelementptr inbounds i8, ptr {}, i64 %offset.val\n  ret ptr %adj\n",
                    self.source_type, object, object
                )
            }
            DynCastStrategy::Downcast | DynCastStrategy::CrossCast => {
                if self.is_ref_cast {
                    format!(
                        r#"; dynamic_cast throw-on-fail: {}{}
  %result = call ptr @__dynamic_cast(ptr {}, ptr @_ZTI{}, ptr @_ZTI{}, i64 0)
  %is_null = icmp eq ptr %result, null
  br i1 %is_null, label %throw_bad_cast, label %success
throw_bad_cast:
  call void @__cxa_bad_cast()
  unreachable
success:
  ret ptr %result
"#,
                        self.source_type,
                        self.target_type,
                        object,
                        self.source_type,
                        self.target_type
                    )
                } else {
                    format!(
                        "  %result = call ptr @__dynamic_cast(ptr {}, ptr @_ZTI{}, ptr @_ZTI{}, i64 0)\n  ret ptr %result\n",
                        object, self.source_type, self.target_type
                    )
                }
            }
        }
    }

    /// Check if the class hierarchy supports this cast.
    /// Walks the class hierarchy looking for the target type.
    pub fn check_hierarchy(source_hierarchy: &[String], target: &str) -> Option<DynCastStrategy> {
        if source_hierarchy.is_empty() {
            return None;
        }

        if source_hierarchy[0] == target || source_hierarchy.iter().any(|t| t == target) {
            // source is target or target is a base
            Some(if source_hierarchy[0] == target {
                DynCastStrategy::Identity
            } else {
                DynCastStrategy::Downcast
            })
        } else if target == "void" {
            Some(DynCastStrategy::ToVoid)
        } else {
            None
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// typeid Operator
// ═══════════════════════════════════════════════════════════════════════════════

/// Represents the `typeid` operator evaluation.
#[derive(Debug, Clone)]
pub struct TypeidOperator {
    /// The type operand.
    pub type_name: String,
    /// Whether this is `typeid(type)` or `typeid(expr)`.
    pub is_type: bool,
    /// Whether the result is the dynamic type (for polymorphic objects).
    pub is_dynamic: bool,
}

impl TypeidOperator {
    pub fn new(type_name: &str) -> Self {
        Self {
            type_name: type_name.to_string(),
            is_type: true,
            is_dynamic: false,
        }
    }

    /// Create a dynamic typeid (for polymorphic expressions).
    pub fn dynamic(expr_type: &str) -> Self {
        Self {
            type_name: expr_type.to_string(),
            is_type: false,
            is_dynamic: true,
        }
    }

    /// Generate IR for `typeid(type)` — static type, returns type_info reference.
    pub fn gen_static_typeid_ir(&self) -> String {
        format!(
            "  ; typeid({})\n  ret ptr @_ZTI{}\n",
            self.type_name, self.type_name
        )
    }

    /// Generate IR for `typeid(expr)` — dynamic type, uses vtable lookup.
    pub fn gen_dynamic_typeid_ir(&self, object_ptr: &str) -> String {
        format!(
            r#"; typeid(dynamic expr of type {})
  %vtable = load ptr, ptr {}
  %typeinfo.ptr = getelementptr inbounds ptr, ptr %vtable, i64 -1
  %typeinfo = load ptr, ptr %typeinfo.ptr
  ret ptr %typeinfo
"#,
            self.type_name, object_ptr
        )
    }

    /// Check if typeid requires RTTI to be enabled.
    pub fn requires_rtti(&self) -> bool {
        true // typeid always requires RTTI
    }

    /// Generate the IR for a typeid comparison: `typeid(a) == typeid(b)`.
    pub fn gen_typeid_compare_ir(a_type: &str, b_type: &str) -> String {
        format!(
            "  %eq = icmp eq ptr @_ZTI{}, ptr @_ZTI{}\n  ret i1 %eq\n",
            a_type, b_type
        )
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// RTTI Emission: Sections, VTable Pointer, Name String
// ═══════════════════════════════════════════════════════════════════════════════

/// Configures the emission of RTTI data.
#[derive(Debug, Clone)]
pub struct RttiEmissionConfig {
    /// The target triple (affects RTTI layout).
    pub target_triple: String,
    /// Whether to emit type_info in COMDAT groups.
    pub use_comdat: bool,
    /// The data section for type_info objects.
    pub data_section: String,
    /// Whether to emit vtable pointers inline or as references.
    pub inline_vtable_ptrs: bool,
    /// Whether RTTI is enabled at all.
    pub rtti_enabled: bool,
}

impl RttiEmissionConfig {
    pub fn new(target_triple: &str) -> Self {
        Self {
            target_triple: target_triple.to_string(),
            use_comdat: true,
            data_section: ".data.rel.ro".to_string(),
            inline_vtable_ptrs: false,
            rtti_enabled: true,
        }
    }

    /// Disable RTTI emission (equivalent to -fno-rtti).
    pub fn disable_rtti(mut self) -> Self {
        self.rtti_enabled = false;
        self
    }

    /// Emit a type_info global with proper linkage and section.
    pub fn emit_global_typeinfo(
        &self,
        sym: &str,
        vtable: &str,
        name_sym: &str,
        kind: RttiKind,
    ) -> String {
        if !self.rtti_enabled {
            return format!("; RTTI disabled, skipping type_info for '{}'\n", sym);
        }

        let linkage = if self.use_comdat {
            format!("linkonce_odr")
        } else {
            "private".to_string()
        };

        let section = &self.data_section;

        match kind {
            RttiKind::Class | RttiKind::Fundamental => {
                format!(
                    "@{} = {} constant {{ ptr, ptr }} {{ ptr {}, ptr @{} }}, align 8, section \"{}\"\n",
                    sym, linkage, vtable, name_sym, section
                )
            }
            RttiKind::SiClass => {
                format!(
                    "@{} = {} constant {{ ptr, ptr, ptr }} {{ ptr {}, ptr @{}, ptr null }}, align 8, section \"{}\"\n",
                    sym, linkage, vtable, name_sym, section
                )
            }
            _ => {
                format!(
                    "@{} = {} constant {{ ptr, ptr }} {{ ptr {}, ptr @{} }}, align 8, section \"{}\"\n",
                    sym, linkage, vtable, name_sym, section
                )
            }
        }
    }

    /// Emit the type_info name string (the demangled class name).
    pub fn emit_name_string(&self, sym: &str, class_name: &str) -> String {
        if !self.rtti_enabled {
            return String::new();
        }

        format!(
            "@{} = private unnamed_addr constant [{} x i8] c\"{}\\00\", align 1\n",
            sym,
            class_name.len() + 1,
            class_name
        )
    }

    /// Emit a vtable pointer reference for type_info.
    pub fn emit_vtable_ptr_decl(sym: &str) -> String {
        format!("@{} = external constant ptr ; type_info vtable\n", sym)
    }
}

impl Default for RttiEmissionConfig {
    fn default() -> Self {
        Self::new("x86_64-unknown-linux-gnu")
    }
}

/// Emit the complete RTTI for a translation unit as a combined LLVM IR module.
pub fn emit_rtti_module(
    config: &RttiEmissionConfig,
    types: &[(String, RttiKind, Option<String>)],
) -> String {
    let mut ir = String::new();
    ir.push_str("; RTTI Module\n");
    ir.push_str("; Target: ");
    ir.push_str(&config.target_triple);
    ir.push_str("\n\n");

    for (name, kind, vtable) in types {
        let name_sym = format!("_ZTS{}", name);
        let typeinfo_sym = format!("_ZTI{}", name);
        let vtable_sym = vtable.as_deref().unwrap_or("null");

        ir.push_str(&config.emit_name_string(&name_sym, name));
        ir.push_str(&config.emit_global_typeinfo(&typeinfo_sym, vtable_sym, &name_sym, *kind));
        ir.push('\n');
    }

    ir
}

// ═══════════════════════════════════════════════════════════════════════════════
// RTTI Class Hierarchy Walking
// ═══════════════════════════════════════════════════════════════════════════════

/// Walks the class hierarchy for dynamic_cast and typeid.
#[derive(Debug, Clone)]
pub struct ClassHierarchyWalker {
    /// The root class of the walk.
    pub root: String,
    /// All classes in the hierarchy.
    pub hierarchy: Vec<HierarchyEntry>,
    /// Depth of the deepest base.
    pub max_depth: usize,
}

/// An entry in the class hierarchy.
#[derive(Debug, Clone)]
pub struct HierarchyEntry {
    /// The class name.
    pub class_name: String,
    /// The RTTI descriptor.
    pub typeinfo: Option<String>,
    /// The base class name.
    pub base: Option<String>,
    /// Whether the base is virtual.
    pub is_virtual: bool,
    /// The offset from derived to base.
    pub offset: i64,
    /// Depth in the hierarchy.
    pub depth: usize,
}

impl ClassHierarchyWalker {
    pub fn new(root: &str) -> Self {
        Self {
            root: root.to_string(),
            hierarchy: vec![HierarchyEntry {
                class_name: root.to_string(),
                typeinfo: Some(format!("_ZTI{}", root)),
                base: None,
                is_virtual: false,
                offset: 0,
                depth: 0,
            }],
            max_depth: 0,
        }
    }

    /// Add a derived class with its base.
    pub fn add_derived(&mut self, class: &str, base: &str, is_virtual: bool, offset: i64) {
        let depth = self
            .hierarchy
            .iter()
            .find(|e| e.class_name == base)
            .map(|e| e.depth + 1)
            .unwrap_or(0);
        if depth > self.max_depth {
            self.max_depth = depth;
        }
        self.hierarchy.push(HierarchyEntry {
            class_name: class.to_string(),
            typeinfo: Some(format!("_ZTI{}", class)),
            base: Some(base.to_string()),
            is_virtual,
            offset,
            depth,
        });
    }

    /// Find the path from `derived` to `base` in the hierarchy.
    pub fn find_path(&self, derived: &str, base: &str) -> Option<Vec<String>> {
        if derived == base {
            return Some(vec![derived.to_string()]);
        }
        let mut current = derived;
        let mut path = vec![current.to_string()];
        let mut visited = std::collections::HashSet::new();
        visited.insert(current.to_string());

        while let Some(entry) = self.hierarchy.iter().find(|e| e.class_name == current) {
            if let Some(ref b) = entry.base {
                if b == base {
                    path.push(b.clone());
                    return Some(path);
                }
                if visited.contains(b.as_str()) {
                    return None; // cycle
                }
                visited.insert(b.clone());
                path.push(b.clone());
                current = b.as_str();
            } else {
                return None; // no base, path incomplete
            }
        }
        None
    }

    /// Calculate the total offset from derived to base.
    pub fn calculate_offset(&self, derived: &str, base: &str) -> Option<i64> {
        let mut total = 0i64;
        let mut current = derived;
        while let Some(entry) = self.hierarchy.iter().find(|e| e.class_name == current) {
            if entry.class_name == base {
                return Some(total);
            }
            if let Some(ref b) = entry.base {
                total += entry.offset;
                current = b;
            } else {
                return None;
            }
        }
        None
    }

    /// Generate the IR to walk the hierarchy at runtime for dynamic_cast.
    pub fn gen_hierarchy_walk_ir(&self, obj: &str, target_typeinfo: &str) -> String {
        let mut ir = String::new();
        ir.push_str(&format!("; Hierarchy walk from '{}'\n", self.root));

        for entry in &self.hierarchy {
            if let Some(ref ti) = entry.typeinfo {
                ir.push_str(&format!(
                    "  %check.{} = icmp eq ptr @{}, ptr @{}\n",
                    entry.class_name, ti, target_typeinfo
                ));
                ir.push_str(&format!(
                    "  br i1 %check.{}, label %found.{}, label %next.{}\n",
                    entry.class_name, entry.class_name, entry.class_name
                ));
                ir.push_str(&format!(
                    "found.{}:\n  ret ptr {}\n\n",
                    entry.class_name, obj
                ));
                ir.push_str(&format!("next.{}:\n", entry.class_name));
            }
        }

        ir.push_str("  ret ptr null ; cast failed\n");
        ir
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// RTTI Linkonce ODR COMDAT Emission
// ═══════════════════════════════════════════════════════════════════════════════

/// Emits RTTI objects with linkonce_odr linkage and COMDAT grouping.
#[derive(Debug, Clone)]
pub struct ComdatRttiEmitter {
    /// The COMDAT key generator.
    pub comdat_counter: usize,
}

impl ComdatRttiEmitter {
    pub fn new() -> Self {
        Self { comdat_counter: 0 }
    }

    /// Emit a type_info with COMDAT support.
    pub fn emit_comdat_typeinfo(
        &mut self,
        type_name: &str,
        kind: RttiKind,
        vtable_sym: &str,
    ) -> String {
        self.comdat_counter += 1;
        let comdat_key = format!("__typeinfo_{}", type_name);
        let mut ir = String::new();

        ir.push_str(&format!("${} = comdat any\n", comdat_key));
        ir.push_str(&format!(
            "@_ZTI{} = linkonce_odr constant {{ ptr, ptr }} {{ ptr {}, ptr @_ZTS{} }}, comdat(${})\n",
            type_name, vtable_sym, type_name, comdat_key
        ));

        ir
    }

    /// Emit a type_info name string with COMDAT.
    pub fn emit_comdat_name_string(&mut self, type_name: &str) -> String {
        let comdat_key = format!("__typeinfo_name_{}", type_name);
        format!(
            "@_ZTS{} = linkonce_odr constant [{} x i8] c\"{}\\00\", comdat(${}), align 1\n",
            type_name,
            type_name.len() + 1,
            type_name,
            comdat_key
        )
    }

    /// Emit a complete type_info + name pair with COMDAT.
    pub fn emit_typeinfo_pair(
        &mut self,
        type_name: &str,
        kind: RttiKind,
        vtable_sym: &str,
    ) -> String {
        let mut ir = self.emit_comdat_name_string(type_name);
        ir.push_str(&self.emit_comdat_typeinfo(type_name, kind, vtable_sym));
        ir
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// RTTI Flags and Base-Class Encoding
// ═══════════════════════════════════════════════════════════════════════════════

/// RTTI flags for base class descriptors per Itanium ABI.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RttiBaseFlags(u32);

impl RttiBaseFlags {
    /// No flags set.
    pub const NONE: Self = Self(0);
    /// Base is virtual.
    pub const VIRTUAL: Self = Self(1 << 0);
    /// Base is public.
    pub const PUBLIC: Self = Self(1 << 1);
    /// Base is protected.
    pub const PROTECTED: Self = Self(1 << 2);
    /// Base is private.
    pub const PRIVATE: Self = Self(1 << 3);

    /// Check if a flag is set.
    pub fn has(&self, flag: Self) -> bool {
        (self.0 & flag.0) != 0
    }

    /// Set a flag.
    pub fn set(&mut self, flag: Self) {
        self.0 |= flag.0;
    }

    /// Get the raw flags value.
    pub fn raw(&self) -> u32 {
        self.0
    }

    /// Parse from access specifier and virtual flag.
    pub fn from_access(is_virtual: bool, is_public: bool, is_protected: bool) -> Self {
        let mut flags = Self::NONE;
        if is_virtual {
            flags.set(Self::VIRTUAL);
        }
        if is_public {
            flags.set(Self::PUBLIC);
        } else if is_protected {
            flags.set(Self::PROTECTED);
        } else {
            flags.set(Self::PRIVATE);
        }
        flags
    }
}

/// Encodes base class information in __vmi_class_type_info.
#[derive(Debug, Clone)]
pub struct VmiBaseEncoder {
    /// The base classes.
    pub bases: Vec<VmiBaseEntry>,
    /// The vmi flags.
    pub flags: u32,
}

/// A base class entry in VMI.
#[derive(Debug, Clone)]
pub struct VmiBaseEntry {
    /// The base type_info.
    pub typeinfo: String,
    /// The offset flags.
    pub offset_flags: u32,
    /// The offset from derived to this base.
    pub offset: i64,
}

impl VmiBaseEncoder {
    pub fn new() -> Self {
        Self {
            bases: Vec::new(),
            flags: 0,
        }
    }

    /// Add a base class with its offset.
    pub fn add_base(&mut self, typeinfo: &str, offset: i64, is_virtual: bool, is_public: bool) {
        let flags = RttiBaseFlags::from_access(is_virtual, is_public, false);
        self.bases.push(VmiBaseEntry {
            typeinfo: typeinfo.to_string(),
            offset_flags: flags.raw(),
            offset,
        });
    }

    /// Generate the LLVM IR for the VMI base array.
    pub fn gen_base_array_ir(&self) -> String {
        let mut ir = String::new();
        ir.push_str(&format!("  [{} x {{ ptr, i64 }}] [\n", self.bases.len()));
        for (i, base) in self.bases.iter().enumerate() {
            if i > 0 {
                ir.push_str(",\n");
            }
            ir.push_str(&format!(
                "    {{ ptr @{}, i64 {} }}",
                base.typeinfo, base.offset
            ));
        }
        ir.push_str("\n  ]");
        ir
    }

    /// Generate the full __vmi_class_type_info descriptor.
    pub fn gen_vmi_typeinfo_ir(&self, sym: &str, name_sym: &str, vtable: &str) -> String {
        format!(
            "@{} = private constant {{ ptr, ptr, i32, i32, [{} x {{ ptr, i64 }}] }} {{ ptr {}, ptr @{}, i32 {}, i32 {}, {}\n}}, align 8\n",
            sym,
            self.bases.len(),
            vtable,
            name_sym,
            self.flags,
            self.bases.len(),
            self.gen_base_array_ir()
        )
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Pointer-to-Member and Array Type Info
// ═══════════════════════════════════════════════════════════════════════════════

/// RTTI for pointer-to-member types.
#[derive(Debug, Clone)]
pub struct PointerToMemberTypeInfo {
    /// The class type for the pointer-to-member.
    pub class_type: String,
    /// The member type.
    pub member_type: String,
    /// The member type's typeinfo.
    pub member_typeinfo: Option<String>,
}

impl PointerToMemberTypeInfo {
    pub fn new(class_type: &str, member_type: &str) -> Self {
        Self {
            class_type: class_type.to_string(),
            member_type: member_type.to_string(),
            member_typeinfo: None,
        }
    }

    /// Emit the pointer-to-member RTTI descriptor.
    pub fn emit_ir(&self, sym: &str, name_sym: &str, vtable: &str) -> String {
        let member_ti = self.member_typeinfo.as_deref().unwrap_or("null");
        format!(
            "@{} = private constant {{ ptr, ptr, ptr, ptr }} {{ ptr {}, ptr @{}, ptr @_ZTI{}, ptr @{} }}\n",
            sym, vtable, name_sym, self.class_type, member_ti
        )
    }
}

/// RTTI for array types.
#[derive(Debug, Clone)]
pub struct ArrayTypeInfo {
    /// The element type info.
    pub element_type: String,
    /// The array bounds (None for unbounded).
    pub bounds: Option<usize>,
}

impl ArrayTypeInfo {
    pub fn new(element_type: &str) -> Self {
        Self {
            element_type: element_type.to_string(),
            bounds: None,
        }
    }

    /// Emit the array type RTTI descriptor.
    pub fn emit_ir(&self, sym: &str, name_sym: &str, vtable: &str) -> String {
        let bounds_str = self
            .bounds
            .map(|n| n.to_string())
            .unwrap_or_else(|| "0".to_string());
        format!(
            "@{} = private constant {{ ptr, ptr, ptr, i64 }} {{ ptr {}, ptr @{}, ptr @_ZTI{}, i64 {} }}, align 8\n",
            sym, vtable, name_sym, self.element_type, bounds_str
        )
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Tests
// ═══════════════════════════════════════════════════════════════════════════════

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

    #[test]
    fn test_rtti_kind_class_name() {
        assert_eq!(RttiKind::Fundamental.class_name(), "type_info");
        assert_eq!(RttiKind::Class.class_name(), "__class_type_info");
        assert_eq!(RttiKind::SiClass.class_name(), "__si_class_type_info");
        assert_eq!(RttiKind::VmiClass.class_name(), "__vmi_class_type_info");
        assert_eq!(RttiKind::Pointer.class_name(), "__pointer_type_info");
    }

    #[test]
    fn test_build_fundamental_rtti() {
        let mut builder = RttiBuilder::new();
        let desc = builder.build_fundamental_rtti("int");
        assert_eq!(desc.kind, RttiKind::Fundamental);
        assert!(desc.typeinfo_symbol.as_str().starts_with("_ZTI"));
        assert!(desc.typeinfo_name_symbol.as_str().starts_with("_ZTS"));
    }

    #[test]
    fn test_build_class_rtti_no_bases() {
        let mut builder = RttiBuilder::new();
        let desc = builder.build_class_rtti("MyClass", &[]);
        assert_eq!(desc.kind, RttiKind::Class);
        assert!(desc.name_string.contains("MyClass"));
    }

    #[test]
    fn test_build_class_rtti_single_base() {
        let mut builder = RttiBuilder::new();
        let desc = builder.build_class_rtti("Derived", &[("Base".into(), false, true)]);
        assert_eq!(desc.kind, RttiKind::SiClass);
        assert!(desc.base_type.is_some());
        assert_eq!(desc.base_type.as_ref().unwrap().type_name, "Base");
    }

    #[test]
    fn test_build_class_rtti_virtual_base() {
        let mut builder = RttiBuilder::new();
        let desc = builder.build_class_rtti(
            "Derived",
            &[("Base1".into(), false, true), ("Base2".into(), true, true)],
        );
        assert_eq!(desc.kind, RttiKind::VmiClass);
        assert_eq!(desc.base_info.len(), 2);
    }

    #[test]
    fn test_build_pointer_rtti() {
        let mut builder = RttiBuilder::new();
        let desc = builder.build_pointer_rtti("int");
        assert_eq!(desc.kind, RttiKind::Pointer);
        assert!(desc.pointee_type.is_some());
    }

    #[test]
    fn test_emit_rtti_ir() {
        let mut builder = RttiBuilder::new();
        builder.build_class_rtti("Foo", &[]);
        let ir = builder.emit_all_ir();
        assert!(ir.contains("_ZTS3Foo"));
        assert!(ir.contains("_ZTI3Foo"));
    }

    #[test]
    fn test_emit_name_ir() {
        let mut builder = RttiBuilder::new();
        let desc = builder.build_class_rtti("Bar", &[]);
        let ir = desc.emit_name_ir();
        assert!(ir.contains("Bar"));
        assert!(ir.contains("_ZTS"));
    }

    #[test]
    fn test_rtti_descriptor_clone() {
        let mut builder = RttiBuilder::new();
        builder.build_fundamental_rtti("double");
        let desc = builder.get_descriptor("double").unwrap();
        let cloned = desc.clone();
        assert_eq!(cloned.type_name, desc.type_name);
    }

    #[test]
    fn test_typeinfo_vtable_constants() {
        assert!(typeinfo_vtables::GCC_LINUX_TYPEINFO_VTABLE.contains("class_type_info"));
        assert!(typeinfo_vtables::GCC_LINUX_SI_CLASS_TYPEINFO_VTABLE.contains("si_class_type_info"));
    }
}