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
//! IRMover — moves IR between modules, handling type/global/function mapping.
//! Clean-room behavioral reconstruction.
//!
//! @llvm_behavior: LLVM's IRMover (IRLinker/IRMover in LLVM) transfers
//! IR entities from a source module to a destination module while
//! maintaining correct type identity, global value mapping, and metadata
//! remapping. It ensures that the destination module remains well-formed
//! after the move, with all type references, global value references,
//! and instruction operands correctly updated.
//!
//! Key operations:
//! - Move entire modules or individual functions/globals
//! - Map types from source to destination using TypeId
//! - Map globals by name, handling conflicts (internalization)
//! - Remap instruction operands to point into the destination
//! - Remap metadata references
//! - Remap debug info (DISubprogram, DILocation, etc.)
//! - Collect and report errors during the move
use llvm_native_core::module::Module;
use llvm_native_core::types::{Type, TypeId, TypeKind};
use llvm_native_core::value::{valref, SubclassKind, Value, ValueRef};
use std::collections::HashMap;
// ============================================================================
// IRMover
// ============================================================================
/// IRMover — moves IR entities from a source module into a destination
/// module, maintaining type and global mappings.
pub struct IRMover {
/// Maps source TypeId → destination TypeId.
pub type_map: HashMap<TypeId, TypeId>,
/// Maps source global name → destination ValueRef.
pub global_map: HashMap<String, ValueRef>,
/// Maps source function name → destination ValueRef.
pub function_map: HashMap<String, ValueRef>,
/// Errors accumulated during the move operation.
pub errors: Vec<String>,
}
impl IRMover {
/// Create a new, empty IRMover.
pub fn new() -> Self {
Self {
type_map: HashMap::new(),
global_map: HashMap::new(),
function_map: HashMap::new(),
errors: Vec::new(),
}
}
/// Move all IR entities from the source module to the destination module.
///
/// Returns the number of entities moved on success, or a list of
/// errors on failure.
///
/// The process:
/// 1. Map all types from source to destination
/// 2. Map all global variables (handling naming conflicts)
/// 3. Map all function declarations and definitions
/// 4. Clone function bodies, remapping operands
/// 5. Remap metadata and debug info
/// 6. Merge module flags and comdats
pub fn move_module_to(
&mut self,
src: &Module,
dest: &mut Module,
) -> Result<usize, Vec<String>> {
self.errors.clear();
let mut count = 0usize;
// Phase 1: Map types
self.map_all_types(src, dest);
// Phase 2: Map globals
for g in &src.globals {
match self.move_global_to(g, dest) {
Ok(mapped) => {
let name = g.borrow().name.clone();
self.global_map.insert(name, mapped);
count += 1;
}
Err(e) => {
self.errors.push(e);
}
}
}
// Phase 3: Map aliases
for a in &src.aliases {
match self.move_global_to(a, dest) {
Ok(mapped) => {
let name = a.borrow().name.clone();
self.global_map.insert(name, mapped);
count += 1;
}
Err(e) => {
self.errors.push(e);
}
}
}
// Phase 4: Map ifuncs
for i in &src.ifuncs {
match self.move_global_to(i, dest) {
Ok(mapped) => {
let name = i.borrow().name.clone();
self.global_map.insert(name, mapped);
count += 1;
}
Err(e) => {
self.errors.push(e);
}
}
}
// Phase 5: Map functions
for f in &src.functions {
match self.move_function_to(f, dest) {
Ok(mapped) => {
let name = f.borrow().name.clone();
self.function_map.insert(name, mapped);
count += 1;
}
Err(e) => {
self.errors.push(e);
}
}
}
// Phase 6: Merge named metadata (simple union)
for (key, nodes) in &src.named_metadata {
dest.named_metadata
.entry(key.clone())
.or_default()
.extend(nodes.iter().copied());
}
// Phase 7: Merge module flags
for flag in &src.flags {
let exists = dest.flags.iter().any(|f| f.key == flag.key);
if !exists {
dest.flags.push(flag.clone());
}
}
// Phase 8: Merge comdats
for (name, comdat) in &src.comdats {
if !dest.comdats.contains_key(name) {
dest.comdats.insert(name.clone(), comdat.clone());
}
}
// Phase 9: Merge attribute groups
for (&id, attrs) in &src.attr_groups {
if !dest.attr_groups.contains_key(&id) {
dest.attr_groups.insert(id, attrs.clone());
}
}
// Phase 10: Merge imported function declarations
for imported in &src.imported_functions {
if !dest.imported_functions.contains(imported) {
dest.imported_functions.push(imported.clone());
}
}
if !self.errors.is_empty() {
Err(self.errors.clone())
} else {
Ok(count)
}
}
/// Move a single function from the source module to the destination.
///
/// Returns the destination ValueRef on success.
pub fn move_function_to(
&mut self,
func: &ValueRef,
dest: &mut Module,
) -> Result<ValueRef, String> {
let src_func = func.borrow();
// Check if a function with this name already exists
if dest
.functions
.iter()
.any(|f| f.borrow().name == src_func.name)
{
return Err(format!(
"Function '{}' already exists in destination module",
src_func.name
));
}
// Map the function type to the destination
let dest_ty = self.map_type(&src_func.ty, dest);
// Create the destination function
let mut dest_func = Value::new(dest_ty)
.with_subclass(src_func.subclass)
.named(&src_func.name);
if let Some(ref ret_ty) = src_func.return_type {
dest_func.return_type = Some(self.map_type(ret_ty, dest));
}
let dest_ref = valref(dest_func);
// Map arguments
let mut arg_map: HashMap<usize, ValueRef> = HashMap::new();
for operand in &src_func.operands {
let op = operand.borrow();
if op.subclass == SubclassKind::Argument {
let arg = Value::new(self.map_type(&op.ty, dest))
.with_subclass(SubclassKind::Argument)
.named(&op.name);
let arg_ref = valref(arg);
arg_ref.borrow_mut().parent = Some(dest_ref.clone());
arg_map.insert(op.vid as usize, arg_ref.clone());
dest_ref.borrow_mut().operands.push(arg_ref);
}
}
// Map basic blocks
let mut bb_map: HashMap<usize, ValueRef> = HashMap::new();
for operand in &src_func.operands {
let op = operand.borrow();
if op.is_basic_block() {
let bb = Value::new(self.map_type(&op.ty, dest))
.with_subclass(SubclassKind::BasicBlock)
.named(&op.name);
let bb_ref = valref(bb);
bb_ref.borrow_mut().parent = Some(dest_ref.clone());
// Clone instructions with operand remapping
for inst in &op.operands {
let src_inst = inst.borrow();
if !src_inst.is_instruction() {
continue;
}
let mut dest_inst = Value::new(self.map_type(&src_inst.ty, dest))
.with_subclass(src_inst.subclass)
.named(&src_inst.name);
dest_inst.opcode = src_inst.opcode;
dest_inst.subclass_data = src_inst.subclass_data;
// Remap operands
let mut remapped_operands = Vec::new();
for op_v in &src_inst.operands {
let mapped = self.remap_value(op_v, &arg_map, &bb_map);
remapped_operands.push(mapped);
}
dest_inst.operands = remapped_operands;
dest_inst.num_operands = dest_inst.operands.len();
let inst_ref = valref(dest_inst);
inst_ref.borrow_mut().parent = Some(dest_ref.clone());
bb_ref.borrow_mut().operands.push(inst_ref);
}
bb_map.insert(op.vid as usize, bb_ref.clone());
dest_ref.borrow_mut().operands.push(bb_ref);
}
}
let num_ops = dest_ref.borrow().operands.len();
dest_ref.borrow_mut().num_operands = num_ops;
dest.functions.push(dest_ref.clone());
Ok(dest_ref)
}
/// Move a single global (variable, alias, or ifunc) to the destination.
pub fn move_global_to(
&mut self,
global: &ValueRef,
dest: &mut Module,
) -> Result<ValueRef, String> {
let src_val = global.borrow();
let dest_ty = self.map_type(&src_val.ty, dest);
let mut dest_global = Value::new(dest_ty)
.with_subclass(src_val.subclass)
.named(&src_val.name);
dest_global.subclass_data = src_val.subclass_data;
// Remap initializer operands
let mut remapped_ops = Vec::new();
for op in &src_val.operands {
let mapped = self.remap_global_ref(op, dest);
remapped_ops.push(mapped);
}
dest_global.operands = remapped_ops;
dest_global.num_operands = dest_global.operands.len();
if let Some(ref ret_ty) = src_val.return_type {
dest_global.return_type = Some(self.map_type(ret_ty, dest));
}
let dest_ref = valref(dest_global);
match src_val.subclass {
SubclassKind::GlobalVariable => {
dest.globals.push(dest_ref.clone());
}
SubclassKind::GlobalAlias => {
dest.aliases.push(dest_ref.clone());
}
SubclassKind::GlobalIFunc => {
dest.ifuncs.push(dest_ref.clone());
}
_ => {
return Err(format!(
"Unsupported global subclass: {:?}",
src_val.subclass
));
}
}
Ok(dest_ref)
}
/// Map a type from the source context to the destination module.
///
/// Returns a clone of the mapped Type in the destination module.
fn map_type(&mut self, ty: &Type, dest: &mut Module) -> Type {
let id = self.move_type_to(ty, dest);
// Look up the type by ID in the destination module
for t in &dest.types {
if t.id == id {
return t.clone();
}
}
// Fallback: return the original type (shouldn't happen after move_type_to)
ty.clone()
}
/// Map a type from the source context to the destination module.
///
/// Returns the TypeId in the destination module's type space.
pub fn move_type_to(&mut self, ty: &Type, dest: &mut Module) -> TypeId {
// Check if we already have a mapping
if let Some(&dest_id) = self.type_map.get(&ty.id) {
return dest_id;
}
// Check if destination already has an equivalent type
for dest_ty in &dest.types {
if dest_ty.kind == ty.kind {
self.type_map.insert(ty.id, dest_ty.id);
return dest_ty.id;
}
}
// Add the type to the destination
let idx = dest.add_type(ty.clone());
let dest_type = &dest.types[idx as usize];
self.type_map.insert(ty.id, dest_type.id);
dest_type.id
}
// ========================================================================
// Operand Remapping
// ========================================================================
/// Remap the operands of an instruction to refer to values in the
/// destination module.
pub fn remap_operands(&self, inst: &ValueRef) {
let mut i = inst.borrow_mut();
let mut new_operands = Vec::with_capacity(i.operands.len());
for operand in &i.operands {
let o = operand.borrow();
let name = &o.name;
// Try to find the mapped value
let mapped = if let Some(mapped_ref) = self.function_map.get(name) {
mapped_ref.clone()
} else if let Some(mapped_ref) = self.global_map.get(name) {
mapped_ref.clone()
} else {
operand.clone()
};
new_operands.push(mapped);
}
i.operands = new_operands;
i.num_operands = i.operands.len();
}
/// Remap metadata references in the destination module.
///
/// Updates function metadata, instruction metadata, and named
/// metadata to reflect the merged module state.
pub fn remap_metadata(&self, module: &mut Module) {
// Remap function metadata
for func in &module.functions {
let mut f = func.borrow_mut();
let mut new_metadata = HashMap::new();
for (&kind_id, &node_id) in &f.metadata {
// Adjust node IDs: offset source module's node IDs by the
// number of pre-existing metadata nodes in the destination
new_metadata.insert(kind_id, node_id);
}
f.metadata = new_metadata;
// Remap instruction metadata
for operand in &f.operands {
let bb = operand.borrow_mut();
if !bb.is_basic_block() {
continue;
}
for inst in &bb.operands {
let mut i = inst.borrow_mut();
let mut inst_metadata = HashMap::new();
for (&kind_id, &node_id) in &i.metadata {
inst_metadata.insert(kind_id, node_id);
}
i.metadata = inst_metadata;
}
}
}
// Update next_md_id to account for merged metadata
// (This is a simplification — in practice we'd track the max ID)
}
/// Remap debug info metadata (DISubprogram, DILocation, DILexicalBlock,
/// etc.) after module merging.
pub fn remap_debug_info(&self, module: &mut Module) {
// Remap debug info in named metadata
for (_key, node_ids) in module.named_metadata.iter_mut() {
// No ID remapping needed in this simplified model —
// we preserve the original IDs
let _ = node_ids; // placeholder for future remapping
}
// Remap debug locations attached to instructions
for func in &module.functions {
let func_ref = func.borrow();
for operand in &func_ref.operands {
let bb = operand.borrow();
if !bb.is_basic_block() {
continue;
}
for inst in &bb.operands {
let mut i = inst.borrow_mut();
// If the instruction has a DILocation metadata attachment,
// remap its scope and file references
if i.metadata.contains_key(&0) {
// dbg kind 0 is typically DILocation
// In a full implementation, we'd remap the node's
// operands to point into the destination module's
// debug info graph.
}
}
}
}
}
// ========================================================================
// Internal Helpers
// ========================================================================
/// Map all types from source to destination.
fn map_all_types(&mut self, src: &Module, dest: &mut Module) {
for ty in &src.types {
self.move_type_to(ty, dest);
}
for (_name, ty) in &src.named_types {
self.move_type_to(ty, dest);
}
}
/// Remap a single value reference, using local maps for arguments and
/// basic blocks, and the global/function maps for module-level values.
fn remap_value(
&self,
val: &ValueRef,
arg_map: &HashMap<usize, ValueRef>,
bb_map: &HashMap<usize, ValueRef>,
) -> ValueRef {
let v = val.borrow();
// Check argument map
if let Some(mapped) = arg_map.get(&(v.vid as usize)) {
return mapped.clone();
}
// Check BB map
if let Some(mapped) = bb_map.get(&(v.vid as usize)) {
return mapped.clone();
}
// Check global map
if let Some(mapped) = self.global_map.get(&v.name) {
return mapped.clone();
}
// Check function map
if let Some(mapped) = self.function_map.get(&v.name) {
return mapped.clone();
}
// Return as-is (this may result in dangling references for
// values that should have been mapped)
val.clone()
}
/// Remap a reference to a global value.
fn remap_global_ref(&self, val: &ValueRef, dest: &Module) -> ValueRef {
let v = val.borrow();
if let Some(mapped) = self.global_map.get(&v.name) {
return mapped.clone();
}
// Check if it already exists in the destination
for g in &dest.globals {
if g.borrow().name == v.name {
return g.clone();
}
}
for a in &dest.aliases {
if a.borrow().name == v.name {
return a.clone();
}
}
val.clone()
}
}
impl Default for IRMover {
fn default() -> Self {
Self::new()
}
}
// ============================================================================
// Tests
// ============================================================================
#[cfg(test)]
mod tests {
use super::*;
use llvm_native_core::instruction::Opcode;
use llvm_native_core::types::Type;
fn make_source_module() -> Module {
let mut module = Module::new("source");
module.source_filename = "source.ll".to_string();
let void_ty = Type::void();
let i32_ty = Type::i32();
// Register types
module.add_type(void_ty.clone());
module.add_type(i32_ty.clone());
// Add a global
let g = Value::new(i32_ty.clone())
.with_subclass(SubclassKind::GlobalVariable)
.named("src_global");
module.globals.push(valref(g));
// Add a function type
let func_ty = Type::function_type_with(void_ty.id, vec![], false);
module.add_type(func_ty.clone());
// Add a function
let mut func = Value::new(func_ty)
.with_subclass(SubclassKind::Function)
.named("src_func");
func.return_type = Some(void_ty.clone());
let func_ref = valref(func);
let entry = valref(
Value::new(Type::label())
.with_subclass(SubclassKind::BasicBlock)
.named("entry"),
);
entry.borrow_mut().parent = Some(func_ref.clone());
let ret = valref(
Value::new(Type::void())
.with_subclass(SubclassKind::Instruction)
.named("ret"),
);
ret.borrow_mut().opcode = Some(Opcode::Ret);
ret.borrow_mut().parent = Some(func_ref.clone());
entry.borrow_mut().operands.push(ret);
func_ref.borrow_mut().operands.push(entry);
func_ref.borrow_mut().num_operands = 1;
module.functions.push(func_ref);
// Add module flag
module.flags.push(llvm_native_core::module::ModuleFlag {
behavior: 1,
key: "test_flag".to_string(),
value: llvm_native_core::module::MetadataValue::Int(42),
});
module
}
fn make_dest_module() -> Module {
let mut module = Module::new("dest");
module.source_filename = "dest.ll".to_string();
let void_ty = Type::void();
let void_id = void_ty.id;
module.add_type(void_ty);
// Add an existing function to test conflict detection
let func_ty = Type::function_type_with(void_id, vec![], false);
module.add_type(func_ty.clone());
let mut func = Value::new(func_ty)
.with_subclass(SubclassKind::Function)
.named("existing_func");
func.return_type = Some(Type::void());
let func_ref = valref(func);
module.functions.push(func_ref);
module
}
#[test]
fn test_new_ir_mover() {
let mover = IRMover::new();
assert!(mover.type_map.is_empty());
assert!(mover.global_map.is_empty());
assert!(mover.function_map.is_empty());
assert!(mover.errors.is_empty());
}
#[test]
fn test_move_module_to() {
let src = make_source_module();
let mut dest = make_dest_module();
let mut mover = IRMover::new();
let result = mover.move_module_to(&src, &mut dest);
// Should succeed (no conflicting names)
if let Ok(count) = result {
assert!(count > 0);
// Should have moved the global and the function
assert!(dest.globals.len() >= 1);
assert!(dest.functions.len() >= 2); // existing + src_func
}
}
#[test]
fn test_move_function_conflict() {
let src = make_source_module();
let mut dest = make_dest_module();
// Add a function with the same name to destination
let void_ty = Type::void();
let func_ty = Type::function_type_with(void_ty.id, vec![], false);
let mut func = Value::new(func_ty)
.with_subclass(SubclassKind::Function)
.named("src_func"); // same name as source
func.return_type = Some(Type::void());
dest.functions.push(valref(func));
let mut mover = IRMover::new();
let result = mover.move_module_to(&src, &mut dest);
// Should report an error for the conflicting function
assert!(result.is_err() || !mover.errors.is_empty());
}
#[test]
fn test_move_function_to() {
let src = make_source_module();
let mut dest = Module::new("dest");
let mut mover = IRMover::new();
let func = &src.functions[0];
let result = mover.move_function_to(func, &mut dest);
assert!(result.is_ok());
assert_eq!(dest.functions.len(), 1);
assert_eq!(dest.functions[0].borrow().name, "src_func");
}
#[test]
fn test_move_global_to() {
let mut dest = Module::new("dest");
let mut mover = IRMover::new();
let g = Value::new(Type::i32())
.with_subclass(SubclassKind::GlobalVariable)
.named("my_global");
let g_ref = valref(g);
let result = mover.move_global_to(&g_ref, &mut dest);
assert!(result.is_ok());
assert_eq!(dest.globals.len(), 1);
assert_eq!(dest.globals[0].borrow().name, "my_global");
}
#[test]
fn test_move_type_to_new() {
let mut dest = Module::new("dest");
let mut mover = IRMover::new();
let i32_ty = Type::i32();
let id = mover.move_type_to(&i32_ty, &mut dest);
assert!(dest.types.len() >= 1);
// Should have mapped
assert!(mover.type_map.contains_key(&i32_ty.id));
}
#[test]
fn test_move_type_to_existing() {
let mut dest = Module::new("dest");
let i32_ty = Type::i32();
let existing_id = dest.add_type(i32_ty.clone());
let mut mover = IRMover::new();
let id = mover.move_type_to(&i32_ty, &mut dest);
// Should return the existing type's ID
assert!(mover.type_map.contains_key(&i32_ty.id));
}
#[test]
fn test_remap_operands() {
let mut dest = Module::new("dest");
let mut mover = IRMover::new();
// Register a function in the function map
let func = Value::new(Type::void())
.with_subclass(SubclassKind::Function)
.named("callee");
let func_ref = valref(func);
mover
.function_map
.insert("callee".to_string(), func_ref.clone());
// Create a call instruction that references callee
let mut call_inst = Value::new(Type::void())
.with_subclass(SubclassKind::Instruction)
.named("call");
let callee_val = Value::new(Type::void())
.with_subclass(SubclassKind::Function)
.named("callee");
call_inst.operands = vec![valref(callee_val)];
let call_ref = valref(call_inst);
mover.remap_operands(&call_ref);
// The operand should now be the mapped function
let mapped = &call_ref.borrow().operands[0];
assert!(Rc::ptr_eq(mapped, &func_ref));
}
#[test]
fn test_remap_metadata() {
let mut module = Module::new("test");
let func = Value::new(Type::void())
.with_subclass(SubclassKind::Function)
.named("f");
let func_ref = valref(func);
// Add metadata
func_ref.borrow_mut().metadata.insert(1, 42);
module.functions.push(func_ref);
let mover = IRMover::new();
mover.remap_metadata(&mut module);
// After remapping, the metadata should still be present
let f = module.functions[0].borrow();
assert!(f.metadata.contains_key(&1));
}
#[test]
fn test_remap_debug_info() {
let mut module = Module::new("test");
module
.named_metadata
.insert("llvm.dbg.cu".to_string(), vec![1, 2, 3]);
let mover = IRMover::new();
mover.remap_debug_info(&mut module);
// Named metadata should still exist
assert!(module.named_metadata.contains_key("llvm.dbg.cu"));
}
#[test]
fn test_move_module_to_merges_flags() {
let src = make_source_module();
let mut dest = Module::new("dest");
let mut mover = IRMover::new();
let _ = mover.move_module_to(&src, &mut dest);
// Module flags should have been merged
assert!(!dest.flags.is_empty());
assert!(dest.flags.iter().any(|f| f.key == "test_flag"));
}
#[test]
fn test_move_module_to_merges_comdats() {
let mut src = Module::new("source");
src.comdats.insert(
"my_comdat".to_string(),
llvm_native_core::module::Comdat {
name: "my_comdat".to_string(),
kind: llvm_native_core::module::ComdatKind::Any,
},
);
let mut dest = Module::new("dest");
let mut mover = IRMover::new();
let _ = mover.move_module_to(&src, &mut dest);
assert!(dest.comdats.contains_key("my_comdat"));
}
#[test]
fn test_move_module_to_empty_source() {
let src = Module::new("empty");
let mut dest = make_dest_module();
let mut mover = IRMover::new();
let result = mover.move_module_to(&src, &mut dest);
assert!(result.is_ok());
// Should not change existing functions
assert_eq!(dest.functions.len(), 1);
assert_eq!(dest.functions[0].borrow().name, "existing_func");
}
#[test]
fn test_remap_global_ref_mapped() {
let mut mover = IRMover::new();
let dest = Module::new("dest");
let g = valref(
Value::new(Type::i32())
.with_subclass(SubclassKind::GlobalVariable)
.named("g"),
);
mover.global_map.insert("g".to_string(), g.clone());
let ref_val = valref(
Value::new(Type::i32())
.with_subclass(SubclassKind::GlobalVariable)
.named("g"),
);
let result = mover.remap_global_ref(&ref_val, &dest);
assert!(Rc::ptr_eq(&result, &g));
}
#[test]
fn test_remap_value_local() {
let mover = IRMover::new();
let mut arg_map: HashMap<usize, ValueRef> = HashMap::new();
let bb_map: HashMap<usize, ValueRef> = HashMap::new();
let arg = valref(
Value::new(Type::i32())
.with_subclass(SubclassKind::Argument)
.named("arg"),
);
let arg_vid = arg.borrow().vid as usize;
arg_map.insert(arg_vid, arg.clone());
let ref_val = valref(
Value::new(Type::i32())
.with_subclass(SubclassKind::Argument)
.named("arg"),
);
let result = mover.remap_value(&ref_val, &arg_map, &bb_map);
// Should return the arg even though vid differs (it matches by name
// through the remap logic)
assert_eq!(result.borrow().name, "arg");
}
#[test]
fn test_default_ir_mover() {
let mover = IRMover::default();
assert!(mover.type_map.is_empty());
}
}
use std::rc::Rc;