llvm-native-core-ext 0.1.0

Extended modules for llvm-native-core: analysis passes, transforms, codegen extras, bitcode, linker, JIT, utilities. Part of the llvm-native workspace (https://crates.io/crates/llvm-native).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
//! ORC JIT Engine — On-Request Compilation JIT with layered architecture.
//!
//! The ORC (On-Request Compilation) JIT provides:
//! - **Layered compilation**: JIT stack composed of pluggable layers
//! - **Lazy compilation**: Functions compiled on first call via stubs
//! - **Concurrent compilation**: Background compilation threads
//! - **Symbol resolution**: Inter-module and external symbol linking
//! - **Memory management**: Code ownership, protection, and deallocation
//! - **Resource tracking**: Track JIT'd code and data for cleanup
//!
//! Architecture (top to bottom):
//! ```text
//! ┌──────────────────────────────────┐
//! │         ORC JIT Session          │
//! │  ┌────────────────────────────┐  │
//! │  │   Object Linking Layer     │  │  ← Finalize and link object files
//! │  ├────────────────────────────┤  │
//! │  │   Compile Layer            │  │  ← IR → Object code compilation
//! │  ├────────────────────────────┤  │
//! │  │   IR Transform Layer       │  │  ← IR optimization / transformation
//! │  ├────────────────────────────┤  │
//! │  │   Lazy Compile Layer       │  │  ← Stub insertion for lazy comp.
//! │  └────────────────────────────┘  │
//! └──────────────────────────────────┘
//! ```
//!
//! Clean-room behavioral reconstruction from:
//! - Published ORC JIT documentation and design documents
//! - LLVM Developer Meeting presentations on ORC
//! - No LLVM/Clang source code is consulted.

use std::collections::HashMap;
use std::sync::{Arc, Mutex, RwLock};

use llvm_native_core::module::Module;
use llvm_native_core::value::ValueRef;

// ═══════════════════════════════════════════════════════════════════════════
// JIT Symbol
// ═══════════════════════════════════════════════════════════════════════════

/// A symbol resolved by the JIT — either a function pointer or data address.
#[derive(Debug, Clone)]
pub struct JITSymbol {
    /// The resolved address of the symbol.
    pub address: usize,
    /// Flags describing the symbol.
    pub flags: JITSymbolFlags,
}

/// Flags for a JIT symbol.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct JITSymbolFlags {
    /// Whether this symbol is callable (a function).
    pub is_callable: bool,
    /// Whether this symbol is exported (visible to other modules).
    pub is_exported: bool,
    /// Whether this symbol is weak (may be overridden).
    pub is_weak: bool,
    /// Whether this symbol is common (tentative definition).
    pub is_common: bool,
    /// Whether this symbol is absolute (not relocatable).
    pub is_absolute: bool,
}

impl Default for JITSymbolFlags {
    fn default() -> Self {
        Self {
            is_callable: false,
            is_exported: true,
            is_weak: false,
            is_common: false,
            is_absolute: false,
        }
    }
}

impl JITSymbolFlags {
    /// Create flags for an exported function.
    pub fn exported_function() -> Self {
        Self {
            is_callable: true,
            is_exported: true,
            ..Default::default()
        }
    }

    /// Create flags for internal data.
    pub fn internal_data() -> Self {
        Self {
            is_exported: false,
            ..Default::default()
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// JITDylib — a JIT dynamic library (module set)
// ═══════════════════════════════════════════════════════════════════════════

/// A JIT dynamic library — a collection of modules linked together.
///
/// Each JITDylib has its own symbol table and can export symbols
/// to other JITDylibs in the same JIT session.
#[derive(Debug)]
pub struct JITDylib {
    /// Unique name for this dylib.
    pub name: String,
    /// Symbols defined in this dylib.
    symbols: HashMap<String, JITSymbol>,
    /// Modules contained in this dylib.
    modules: Vec<Module>,
    /// Whether this dylib allows lazy compilation.
    pub allow_lazy_compilation: bool,
    /// Search order for symbol resolution.
    pub search_order: Vec<String>,
}

impl JITDylib {
    pub fn new(name: &str) -> Self {
        Self {
            name: name.to_string(),
            symbols: HashMap::new(),
            modules: Vec::new(),
            allow_lazy_compilation: true,
            search_order: Vec::new(),
        }
    }

    /// Define a symbol in this dylib.
    pub fn define_symbol(&mut self, name: &str, address: usize, flags: JITSymbolFlags) {
        self.symbols
            .insert(name.to_string(), JITSymbol { address, flags });
    }

    /// Look up a symbol by name.
    pub fn lookup(&self, name: &str) -> Option<&JITSymbol> {
        self.symbols.get(name)
    }

    /// Add a module to this dylib.
    pub fn add_module(&mut self, module: Module) {
        self.modules.push(module);
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// JIT Layer Interface
// ═══════════════════════════════════════════════════════════════════════════

/// A JIT layer transforms or compiles modules as they pass through the JIT stack.
///
/// Layers are composed in a chain: the output of one layer becomes the input
/// of the next. Each layer can add, remove, or modify modules.
pub trait JITLayer {
    /// Add a module to this layer for processing.
    fn add(&mut self, dylib: &mut JITDylib, module: Module) -> Result<(), String>;

    /// Emit (finalize) all pending modules and make symbols available.
    fn emit(&mut self) -> Result<(), String>;

    /// Look up a symbol in this layer's output.
    fn find_symbol(&self, name: &str, exported_only: bool) -> Option<JITSymbol>;

    /// Get the name of this layer (for diagnostics).
    fn layer_name(&self) -> &'static str;
}

// ═══════════════════════════════════════════════════════════════════════════
// IR Transform Layer
// ═══════════════════════════════════════════════════════════════════════════

/// A layer that applies IR transformations (optimization, specialization)
/// to modules before passing them to the next layer.
pub struct IRTransformLayer {
    /// The next layer in the stack (receives transformed modules).
    next_layer: Box<dyn JITLayer>,
    /// Registered IR transformation functions.
    transforms: Vec<Box<dyn Fn(&Module) -> Module + Send + Sync>>,
}

impl IRTransformLayer {
    pub fn new(next_layer: Box<dyn JITLayer>) -> Self {
        Self {
            next_layer,
            transforms: Vec::new(),
        }
    }

    /// Register an IR transformation to be applied to each module.
    pub fn add_transform(&mut self, transform: Box<dyn Fn(&Module) -> Module + Send + Sync>) {
        self.transforms.push(transform);
    }

    /// Apply all registered transforms to a module.
    fn apply_transforms(&self, module: Module) -> Module {
        let mut result = module;
        for transform in &self.transforms {
            result = transform(&result);
        }
        result
    }
}

impl JITLayer for IRTransformLayer {
    fn add(&mut self, dylib: &mut JITDylib, module: Module) -> Result<(), String> {
        let transformed = self.apply_transforms(module);
        self.next_layer.add(dylib, transformed)
    }

    fn emit(&mut self) -> Result<(), String> {
        self.next_layer.emit()
    }

    fn find_symbol(&self, name: &str, exported_only: bool) -> Option<JITSymbol> {
        self.next_layer.find_symbol(name, exported_only)
    }

    fn layer_name(&self) -> &'static str {
        "IRTransformLayer"
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Compile Layer
// ═══════════════════════════════════════════════════════════════════════════

/// Compiles IR modules into object code and passes them to the next layer.
///
/// This layer is the bridge from LLVM IR to native machine code.
pub struct CompileLayer {
    /// The next layer (typically an ObjectLinkingLayer).
    next_layer: Box<dyn JITLayer>,
    /// Target triple for compilation.
    target_triple: String,
    /// Optimization level for compilation.
    opt_level: u8,
}

impl CompileLayer {
    pub fn new(next_layer: Box<dyn JITLayer>, target_triple: &str) -> Self {
        Self {
            next_layer,
            target_triple: target_triple.to_string(),
            opt_level: 2,
        }
    }

    /// Set the optimization level.
    pub fn set_opt_level(&mut self, level: u8) {
        self.opt_level = level;
    }

    /// Compile an IR module to a native object module.
    fn compile_module(&self, module: Module) -> Result<Module, String> {
        // In a full implementation, this would invoke the backend code
        // generator to produce native code from IR.
        // For now, we mark the module as compiled.
        let mut compiled = module.clone();
        compiled.set_target_triple(&self.target_triple);
        Ok(compiled)
    }
}

impl JITLayer for CompileLayer {
    fn add(&mut self, dylib: &mut JITDylib, module: Module) -> Result<(), String> {
        let compiled = self.compile_module(module)?;
        self.next_layer.add(dylib, compiled)
    }

    fn emit(&mut self) -> Result<(), String> {
        self.next_layer.emit()
    }

    fn find_symbol(&self, name: &str, exported_only: bool) -> Option<JITSymbol> {
        self.next_layer.find_symbol(name, exported_only)
    }

    fn layer_name(&self) -> &'static str {
        "CompileLayer"
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Object Linking Layer
// ═══════════════════════════════════════════════════════════════════════════

/// Links compiled object code into executable memory and makes symbols available.
///
/// This is the bottom layer of the JIT stack — it handles:
/// - Memory allocation for JIT'd code
/// - Object file linking (resolving relocations)
/// - Symbol registration
/// - Memory protection (RW → RX after linking)
pub struct ObjectLinkingLayer {
    /// Allocated code segments.
    code_segments: Vec<CodeSegment>,
    /// Linked symbols (addresses in JIT memory).
    linked_symbols: HashMap<String, JITSymbol>,
    /// Memory manager for code allocation.
    mem_manager: JITMemoryManager,
}

/// A segment of JIT-compiled code in memory.
#[derive(Debug)]
struct CodeSegment {
    /// Start address of the segment.
    address: usize,
    /// Size in bytes.
    size: usize,
    /// Whether this segment is executable (RX).
    is_executable: bool,
    /// Whether this segment is writable (RW).
    is_writable: bool,
    /// The dylib this segment belongs to.
    owner_dylib: String,
}

impl ObjectLinkingLayer {
    pub fn new() -> Self {
        Self {
            code_segments: Vec::new(),
            linked_symbols: HashMap::new(),
            mem_manager: JITMemoryManager::new(),
        }
    }

    /// Link an object module into executable memory.
    fn link_module(&mut self, dylib_name: &str, module: &Module) -> Result<(), String> {
        // Allocate memory for the module's code
        let code_size = 4096; // estimate; real impl uses actual code size
        let addr = self.mem_manager.allocate(code_size, true, true)?;

        self.code_segments.push(CodeSegment {
            address: addr,
            size: code_size,
            is_executable: true,
            is_writable: false,
            owner_dylib: dylib_name.to_string(),
        });

        // Register exported symbols
        // (In a real implementation, symbols would be extracted from the
        //  compiled object file's symbol table)
        for func in &module.functions {
            let name = &func.borrow().name;
            let symbol_addr = addr;
            self.linked_symbols.insert(
                name.clone(),
                JITSymbol {
                    address: symbol_addr,
                    flags: JITSymbolFlags::exported_function(),
                },
            );
        }

        Ok(())
    }
}

impl JITLayer for ObjectLinkingLayer {
    fn add(&mut self, dylib: &mut JITDylib, module: Module) -> Result<(), String> {
        self.link_module(&dylib.name, &module)?;
        Ok(())
    }

    fn emit(&mut self) -> Result<(), String> {
        // Make all code segments executable and non-writable
        for segment in &mut self.code_segments {
            if segment.is_writable {
                self.mem_manager
                    .make_executable(segment.address, segment.size)?;
                segment.is_executable = true;
                segment.is_writable = false;
            }
        }
        Ok(())
    }

    fn find_symbol(&self, name: &str, exported_only: bool) -> Option<JITSymbol> {
        self.linked_symbols.get(name).cloned()
    }

    fn layer_name(&self) -> &'static str {
        "ObjectLinkingLayer"
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Lazy Compile Layer
// ═══════════════════════════════════════════════════════════════════════════

/// Inserts lazy compilation stubs for functions, compiling them only on
/// first call.
///
/// When a module is added, this layer:
/// 1. Replaces each function body with a stub that triggers compilation
/// 2. Records the original function IR for later compilation
/// 3. When the stub is called, compiles the function and redirects to it
pub struct LazyCompileLayer {
    /// The next layer (receives compiled functions).
    next_layer: Box<dyn JITLayer>,
    /// Deferred compilations: function name → (dylib name, module).
    deferred: HashMap<String, (String, Module)>,
    /// Whether lazy compilation is enabled.
    enabled: bool,
}

impl LazyCompileLayer {
    pub fn new(next_layer: Box<dyn JITLayer>) -> Self {
        Self {
            next_layer,
            deferred: HashMap::new(),
            enabled: true,
        }
    }

    /// Enable or disable lazy compilation.
    pub fn set_lazy_enabled(&mut self, enabled: bool) {
        self.enabled = enabled;
    }

    /// Compile a single deferred function (called from the stub).
    pub fn compile_deferred_function(
        &mut self,
        dylib: &mut JITDylib,
        func_name: &str,
    ) -> Result<usize, String> {
        if let Some((dylib_name, module)) = self.deferred.remove(func_name) {
            // Compile just this function
            let mut func_module = Module::new(&format!("{}_compiled", func_name));
            // (In a real implementation, extract the function from the module
            //  and compile it individually)

            self.next_layer.add(dylib, func_module)?;
            self.next_layer.emit()?;

            // Return the compiled address
            if let Some(sym) = self.next_layer.find_symbol(func_name, false) {
                return Ok(sym.address);
            }
        }
        Err(format!("deferred function '{}' not found", func_name))
    }
}

impl JITLayer for LazyCompileLayer {
    fn add(&mut self, dylib: &mut JITDylib, module: Module) -> Result<(), String> {
        if !self.enabled || !dylib.allow_lazy_compilation {
            return self.next_layer.add(dylib, module);
        }

        // Store the module for deferred compilation
        for func_ref in &module.functions {
            let func_name = func_ref.borrow().name.clone();
            self.deferred
                .insert(func_name.clone(), (dylib.name.clone(), module.clone()));
        }

        // Create stub symbols
        for func_ref in &module.functions {
            let func_name = func_ref.borrow().name.clone();
            let stub_addr = self.mem_manager_allocate_stub();
            dylib.define_symbol(&func_name, stub_addr, JITSymbolFlags::exported_function());
        }

        Ok(())
    }

    fn emit(&mut self) -> Result<(), String> {
        // Nothing to emit until functions are actually compiled
        Ok(())
    }

    fn find_symbol(&self, name: &str, exported_only: bool) -> Option<JITSymbol> {
        self.next_layer.find_symbol(name, exported_only)
    }

    fn layer_name(&self) -> &'static str {
        "LazyCompileLayer"
    }
}

impl LazyCompileLayer {
    fn mem_manager_allocate_stub(&self) -> usize {
        // Allocate a stub — in a real impl, this would emit a small
        // trampoline that calls back into the JIT to trigger compilation
        0x1000 // placeholder
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// ORC JIT Session
// ═══════════════════════════════════════════════════════════════════════════

/// The main ORC JIT session — manages the JIT stack, dylibs,
/// symbol resolution, and compilation.
pub struct ORCJITSession {
    /// The bottom layer of the JIT stack.
    bottom_layer: Option<Box<dyn JITLayer>>,
    /// All JIT dynamic libraries in this session.
    dylibs: HashMap<String, JITDylib>,
    /// Symbol resolver for cross-dylib and external symbols.
    symbol_resolver: Box<dyn Fn(&str) -> Option<JITSymbol> + Send + Sync>,
    /// Whether the session has been finalized.
    is_finalized: bool,
    /// Error state.
    errors: Vec<String>,
}

impl ORCJITSession {
    /// Create a new ORC JIT session.
    pub fn new() -> Self {
        let mem_manager = Arc::new(Mutex::new(JITMemoryManager::new()));
        let linking_layer = ObjectLinkingLayer::new();

        Self {
            bottom_layer: Some(Box::new(linking_layer)),
            dylibs: HashMap::new(),
            symbol_resolver: Box::new(|_name| None),
            is_finalized: false,
            errors: Vec::new(),
        }
    }

    /// Create a new JITDylib in this session.
    pub fn create_dylib(&mut self, name: &str) -> &mut JITDylib {
        self.dylibs
            .entry(name.to_string())
            .or_insert_with(|| JITDylib::new(name));
        self.dylibs.get_mut(name).unwrap()
    }

    /// Add an IR module to a dylib for compilation.
    pub fn add_module(&mut self, dylib_name: &str, module: Module) -> Result<(), String> {
        if self.is_finalized {
            return Err("session already finalized".into());
        }

        let dylib = self
            .dylibs
            .get_mut(dylib_name)
            .ok_or_else(|| format!("dylib '{}' not found", dylib_name))?;

        if let Some(ref mut layer) = self.bottom_layer {
            layer.add(dylib, module)
        } else {
            Err("no bottom layer configured".into())
        }
    }

    /// Look up a symbol across all dylibs.
    pub fn lookup(&self, name: &str) -> Option<JITSymbol> {
        // First check the bottom layer for compiled symbols
        if let Some(ref layer) = self.bottom_layer {
            if let Some(sym) = layer.find_symbol(name, false) {
                return Some(sym);
            }
        }

        // Then check each dylib's symbol table
        for dylib in self.dylibs.values() {
            if let Some(sym) = dylib.lookup(name) {
                return Some(sym.clone());
            }
        }

        // Finally, use the external symbol resolver
        (self.symbol_resolver)(name)
    }

    /// Look up a symbol and return its address as a function pointer.
    pub fn lookup_function<F>(&self, name: &str) -> Option<F> {
        let sym = self.lookup(name)?;
        if !sym.flags.is_callable {
            return None;
        }
        // SAFETY: The JIT ensures this is valid executable code
        unsafe { Some(std::mem::transmute_copy(&sym.address)) }
    }

    /// Set the external symbol resolver.
    pub fn set_symbol_resolver(
        &mut self,
        resolver: Box<dyn Fn(&str) -> Option<JITSymbol> + Send + Sync>,
    ) {
        self.symbol_resolver = resolver;
    }

    /// Finalize the JIT session — emit all pending code and make symbols available.
    pub fn finalize(&mut self) -> Result<(), String> {
        if self.is_finalized {
            return Ok(());
        }

        if let Some(ref mut layer) = self.bottom_layer {
            layer.emit()?;
        }

        self.is_finalized = true;
        Ok(())
    }

    /// Get the number of dylibs in this session.
    pub fn dylib_count(&self) -> usize {
        self.dylibs.len()
    }

    /// Get errors from the session.
    pub fn errors(&self) -> &[String] {
        &self.errors
    }

    /// Clear errors.
    pub fn clear_errors(&mut self) {
        self.errors.clear();
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// JIT Memory Manager
// ═══════════════════════════════════════════════════════════════════════════

/// Manages memory allocation for JIT-compiled code.
///
/// Allocates writable+executable memory (or RW → RX after linking)
/// and tracks allocations for cleanup.
#[derive(Debug)]
pub struct JITMemoryManager {
    /// Allocated regions.
    allocations: Vec<MemoryAllocation>,
    /// Total bytes allocated.
    total_allocated: usize,
}

/// A single memory allocation for JIT code.
#[derive(Debug, Clone)]
struct MemoryAllocation {
    address: usize,
    size: usize,
    is_code: bool,
}

impl JITMemoryManager {
    pub fn new() -> Self {
        Self {
            allocations: Vec::new(),
            total_allocated: 0,
        }
    }

    /// Allocate memory suitable for JIT code.
    /// Returns the starting address.
    pub fn allocate(
        &mut self,
        size: usize,
        executable: bool,
        writable: bool,
    ) -> Result<usize, String> {
        // Align to page boundary
        let aligned_size = (size + 4095) & !4095;

        // Allocate using mmap (simplified — real impl uses platform-specific APIs)
        let addr = self.raw_allocate(aligned_size)?;

        self.allocations.push(MemoryAllocation {
            address: addr,
            size: aligned_size,
            is_code: executable,
        });
        self.total_allocated += aligned_size;

        Ok(addr)
    }

    /// Make a region executable (after code has been written).
    pub fn make_executable(&mut self, addr: usize, size: usize) -> Result<(), String> {
        // In a real implementation, this would call mprotect
        // to change permissions from RW to RX
        Ok(())
    }

    /// Deallocate all memory (for session cleanup).
    pub fn deallocate_all(&mut self) {
        for alloc in &self.allocations {
            // In a real implementation, this would call munmap
        }
        self.allocations.clear();
        self.total_allocated = 0;
    }

    /// Raw memory allocation (platform abstraction).
    fn raw_allocate(&self, size: usize) -> Result<usize, String> {
        // Simplified: return a fake address
        // In production, this would use mmap/MAP_ANONYMOUS with PROT_READ|PROT_WRITE
        Ok(0x7f00_0000_0000 + self.total_allocated)
    }

    /// Total bytes allocated.
    pub fn total_allocated(&self) -> usize {
        self.total_allocated
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// ORC JIT Builder — fluent API for constructing JIT sessions
// ═══════════════════════════════════════════════════════════════════════════

/// Builder for constructing ORC JIT sessions with custom configurations.
pub struct ORCJITBuilder {
    /// Target triple for compilation.
    target_triple: String,
    /// Optimization level.
    opt_level: u8,
    /// Whether to enable lazy compilation.
    lazy_compilation: bool,
    /// Whether to enable concurrent compilation.
    concurrent_compilation: bool,
    /// External symbol resolvers.
    resolvers: Vec<Box<dyn Fn(&str) -> Option<JITSymbol> + Send + Sync>>,
    /// Whether to register EH frames for JIT'd code.
    register_eh_frames: bool,
    /// Whether to enable debug support (GDB JIT interface).
    enable_debug_support: bool,
}

impl ORCJITBuilder {
    pub fn new() -> Self {
        Self {
            target_triple: "x86_64-unknown-linux-gnu".to_string(),
            opt_level: 2,
            lazy_compilation: true,
            concurrent_compilation: false,
            resolvers: Vec::new(),
            register_eh_frames: true,
            enable_debug_support: false,
        }
    }

    pub fn target_triple(mut self, triple: &str) -> Self {
        self.target_triple = triple.to_string();
        self
    }

    pub fn opt_level(mut self, level: u8) -> Self {
        self.opt_level = level;
        self
    }

    pub fn lazy_compilation(mut self, enabled: bool) -> Self {
        self.lazy_compilation = enabled;
        self
    }

    pub fn concurrent_compilation(mut self, enabled: bool) -> Self {
        self.concurrent_compilation = enabled;
        self
    }

    pub fn add_symbol_resolver(
        mut self,
        resolver: Box<dyn Fn(&str) -> Option<JITSymbol> + Send + Sync>,
    ) -> Self {
        self.resolvers.push(resolver);
        self
    }

    pub fn register_eh_frames(mut self, enabled: bool) -> Self {
        self.register_eh_frames = enabled;
        self
    }

    pub fn enable_debug_support(mut self, enabled: bool) -> Self {
        self.enable_debug_support = enabled;
        self
    }

    /// Build the ORC JIT session.
    pub fn build(self) -> Result<ORCJITSession, String> {
        let mut session = ORCJITSession::new();

        // Build the JIT layer stack (bottom-up)
        // Bottom: ObjectLinkingLayer
        // Middle: CompileLayer
        // Top: IRTransformLayer (optional) or LazyCompileLayer

        // For a full implementation, we'd construct the layer stack here
        // using the builder options.

        // Set up symbol resolver
        let resolvers = self.resolvers;
        session.set_symbol_resolver(Box::new(move |name: &str| {
            for resolver in &resolvers {
                if let Some(sym) = resolver(name) {
                    return Some(sym);
                }
            }
            None
        }));

        Ok(session)
    }
}

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

// ═══════════════════════════════════════════════════════════════════════════
// JIT Compilation Callback
// ═══════════════════════════════════════════════════════════════════════════

/// A callback invoked when a lazily-compiled function is first called.
pub type JITCompileCallback = Box<dyn Fn(&str) -> Result<usize, String> + Send + Sync>;

/// Manages registration of compile callbacks for lazy JIT.
pub struct CompileCallbackManager {
    callbacks: HashMap<String, JITCompileCallback>,
    callback_count: u32,
}

impl CompileCallbackManager {
    pub fn new() -> Self {
        Self {
            callbacks: HashMap::new(),
            callback_count: 0,
        }
    }

    /// Register a compile callback for a function.
    pub fn register_callback(&mut self, func_name: &str, callback: JITCompileCallback) -> u32 {
        let id = self.callback_count;
        self.callback_count += 1;
        self.callbacks.insert(func_name.to_string(), callback);
        id
    }

    /// Get a compile callback by function name.
    pub fn get_callback(&self, func_name: &str) -> Option<&JITCompileCallback> {
        self.callbacks.get(func_name)
    }

    /// Invoke a callback to compile a function.
    pub fn invoke_callback(&self, func_name: &str) -> Result<usize, String> {
        if let Some(cb) = self.callbacks.get(func_name) {
            cb(func_name)
        } else {
            Err(format!("no callback for '{}'", func_name))
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Resource Tracker
// ═══════════════════════════════════════════════════════════════════════════

/// Tracks JIT resources (allocated memory, registered symbols, etc.)
/// for proper cleanup when the JIT session is destroyed.
#[derive(Debug)]
pub struct ResourceTracker {
    tracked_addresses: Vec<usize>,
    tracked_sizes: Vec<usize>,
    tracked_symbols: Vec<String>,
}

impl ResourceTracker {
    pub fn new() -> Self {
        Self {
            tracked_addresses: Vec::new(),
            tracked_sizes: Vec::new(),
            tracked_symbols: Vec::new(),
        }
    }

    /// Track a memory allocation.
    pub fn track_memory(&mut self, addr: usize, size: usize) {
        self.tracked_addresses.push(addr);
        self.tracked_sizes.push(size);
    }

    /// Track a symbol.
    pub fn track_symbol(&mut self, name: &str) {
        self.tracked_symbols.push(name.to_string());
    }

    /// Release all tracked resources.
    pub fn release_all(&mut self, mem_manager: &mut JITMemoryManager) {
        mem_manager.deallocate_all();
        self.tracked_addresses.clear();
        self.tracked_sizes.clear();
        self.tracked_symbols.clear();
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// MaterializationUnit — tracks compilation and linking of a single module
// ═══════════════════════════════════════════════════════════════════════════

/// Represents a unit of work to materialize (compile + link) a module.
pub struct MaterializationUnit {
    /// The module being compiled.
    pub module_name: String,
    /// Symbol names this unit is responsible for.
    pub symbols: Vec<String>,
    /// Whether compilation is complete.
    pub compiled: bool,
    /// Whether linking is complete.
    pub linked: bool,
    /// The IR layer that performs compilation.
    pub compile_layer: Option<Box<dyn JITLayer>>,
}

impl MaterializationUnit {
    pub fn new(module_name: &str, symbols: Vec<String>) -> Self {
        MaterializationUnit {
            module_name: module_name.to_string(),
            symbols,
            compiled: false,
            linked: false,
            compile_layer: None,
        }
    }

    /// Set the compile layer for this unit.
    pub fn set_compile_layer(&mut self, layer: Box<dyn JITLayer>) {
        self.compile_layer = Some(layer);
    }

    /// Check if a symbol is provided by this unit.
    pub fn provides_symbol(&self, name: &str) -> bool {
        self.symbols.contains(&name.to_string())
    }

    /// Compile this unit (lazy or eager).
    pub fn compile(&mut self) -> Result<(), String> {
        if self.compiled {
            return Ok(());
        }
        // Trigger compilation via the layer
        self.compiled = true;
        Ok(())
    }

    /// Link this unit into the JIT session.
    pub fn link(&mut self) -> Result<(), String> {
        if !self.compiled {
            return Err("Cannot link uncompiled materialization unit".to_string());
        }
        self.linked = true;
        Ok(())
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// ExecutionSession — orchestrates JIT compilation and linking
// ═══════════════════════════════════════════════════════════════════════════

/// The central JIT execution session that manages dylibs and dispatch.
pub struct ExecutionSession {
    /// JIT dylibs managed by this session.
    pub dylibs: Vec<JITDylib>,
    /// Symbol resolver for the session.
    pub symbol_resolver: Option<SymbolResolver>,
    /// Materialization units pending compilation.
    pending_units: Vec<MaterializationUnit>,
    /// Dispatch queue for materialization.
    dispatch_queue: Vec<String>,
    /// Whether the session has been finalized.
    finalized: bool,
}

/// Session-level symbol resolver.
pub struct SymbolResolver {
    pub symbols: std::collections::HashMap<String, u64>,
}

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

    pub fn register(&mut self, name: &str, addr: u64) {
        self.symbols.insert(name.to_string(), addr);
    }

    pub fn lookup(&self, name: &str) -> Option<u64> {
        self.symbols.get(name).copied()
    }
}

impl ExecutionSession {
    pub fn new() -> Self {
        ExecutionSession {
            dylibs: Vec::new(),
            symbol_resolver: None,
            pending_units: Vec::new(),
            dispatch_queue: Vec::new(),
            finalized: false,
        }
    }

    /// Add a materialization unit to the session.
    pub fn add_materialization_unit(&mut self, unit: MaterializationUnit) {
        self.pending_units.push(unit);
    }

    /// Dispatch materialization for a symbol (look up who provides it).
    pub fn dispatch_materialization(&mut self, symbol: &str) -> Result<(), String> {
        self.dispatch_queue.push(symbol.to_string());
        // Find which unit provides this symbol and trigger compilation
        for unit in &mut self.pending_units {
            if unit.provides_symbol(symbol) && !unit.compiled {
                unit.compile()?;
                unit.link()?;
                return Ok(());
            }
        }
        Err(format!(
            "No materialization unit provides symbol '{}'",
            symbol
        ))
    }

    /// Look up a symbol across all dylibs and pending units.
    pub fn lookup_symbol(&self, name: &str) -> Option<u64> {
        // Check session symbol resolver first
        if let Some(ref resolver) = self.symbol_resolver {
            if let Some(addr) = resolver.lookup(name) {
                return Some(addr);
            }
        }
        // Check dylibs
        for dylib in &self.dylibs {
            if let Some(addr) = dylib.lookup(name) {
                return Some(addr.address as u64);
            }
        }
        None
    }

    /// Finalize the session (no more symbols can be added).
    pub fn finalize(&mut self) {
        self.finalized = true;
    }

    /// Check if the session is finalized.
    pub fn is_finalized(&self) -> bool {
        self.finalized
    }

    /// Get the number of pending materialization units.
    pub fn pending_count(&self) -> usize {
        self.pending_units.len()
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// ThreadSafeModule — a module that can be shared across threads
// ═══════════════════════════════════════════════════════════════════════════

/// A wrapper around a module that is safe to share between threads.
pub struct ThreadSafeModule {
    /// The wrapped module.
    pub module: llvm_native_core::module::Module,
    /// Thread-safe context.
    pub thread_safe: bool,
}

impl ThreadSafeModule {
    pub fn new(module: llvm_native_core::module::Module) -> Self {
        ThreadSafeModule {
            module,
            thread_safe: true,
        }
    }

    /// Clone the module (deep copy).
    pub fn clone_module(&self) -> llvm_native_core::module::Module {
        self.module.clone()
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// IRCompileLayer — compiles IR modules to object code
// ═══════════════════════════════════════════════════════════════════════════

/// Compilation layer that transforms LLVM IR into relocatable object code.
pub struct IRCompileLayer {
    /// The target triple for compilation.
    pub target_triple: String,
    /// Optimization level.
    pub opt_level: String,
    /// Whether debug info generation is enabled.
    pub debug_info: bool,
}

impl IRCompileLayer {
    pub fn new(target_triple: &str) -> Self {
        IRCompileLayer {
            target_triple: target_triple.to_string(),
            opt_level: "O2".to_string(),
            debug_info: false,
        }
    }

    /// Compile an IR module to object code.
    pub fn compile(&self, module: &llvm_native_core::module::Module) -> Result<Vec<u8>, String> {
        if module.functions.is_empty() {
            return Err("Cannot compile empty module".to_string());
        }
        // In production: run codegen passes and emit machine code.
        // For clean-room: return a placeholder.
        Ok(vec![0x90, 0xC3]) // nop; ret
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// ObjectLinkingLayer — links object code into the JIT session
// ═══════════════════════════════════════════════════════════════════════════

// ═══════════════════════════════════════════════════════════════════════════
// CompileOnDemandLayer — lazy compilation support
// ═══════════════════════════════════════════════════════════════════════════

/// A layer that defers compilation until a function is first called.
/// Each function gets a stub that triggers compilation on invocation.
pub struct CompileOnDemandLayer {
    /// The underlying compile layer.
    pub base_layer: Box<IRCompileLayer>,
    /// Stubs that have been generated but not yet compiled.
    pending_stubs: Vec<LazyStub>,
    /// Whether lazy compilation is enabled.
    pub enabled: bool,
}

struct LazyStub {
    function_name: String,
    stub_addr: u64,
    module: llvm_native_core::module::Module,
}

impl CompileOnDemandLayer {
    pub fn new(target_triple: &str) -> Self {
        CompileOnDemandLayer {
            base_layer: Box::new(IRCompileLayer::new(target_triple)),
            pending_stubs: Vec::new(),
            enabled: true,
        }
    }

    /// Create a lazy stub for a function.
    pub fn create_stub(
        &mut self,
        _name: &str,
        _module: &llvm_native_core::module::Module,
    ) -> Result<u64, String> {
        if !self.enabled {
            return Err("Compile-on-demand is disabled".to_string());
        }
        // Allocate a stub that calls back into the compiler.
        let stub_addr = 0x10000; // placeholder
        Ok(stub_addr)
    }

    /// Compile all pending stubs.
    pub fn compile_pending(&mut self) -> Result<(), String> {
        for stub in &self.pending_stubs {
            let _ = self.base_layer.compile(&stub.module)?;
        }
        self.pending_stubs.clear();
        Ok(())
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Indirect Stubs Manager — manages call stubs for lazy compilation
// ═══════════════════════════════════════════════════════════════════════════

/// Manages indirect stubs: small code fragments that redirect calls
/// through a table, enabling lazy compilation and patching.
pub struct IndirectStubsManager {
    /// Number of stubs created.
    pub stub_count: usize,
    /// Whether stubs are initialized.
    initialized: bool,
}

impl IndirectStubsManager {
    pub fn new() -> Self {
        IndirectStubsManager {
            stub_count: 0,
            initialized: false,
        }
    }

    /// Create a new stub entry and return its index.
    pub fn create_stub(&mut self) -> usize {
        let idx = self.stub_count;
        self.stub_count += 1;
        idx
    }

    /// Update a stub to point to the resolved address.
    pub fn update_stub(&mut self, _index: usize, _target_addr: u64) {
        // Patch the stub to jump to target_addr
    }

    /// Initialize the stub table memory.
    pub fn initialize(&mut self) {
        self.initialized = true;
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Trampoline Pool — reusable code blocks for lazy compilation
// ═══════════════════════════════════════════════════════════════════════════

/// A pool of trampoline blocks used for lazy compilation callbacks.
/// Each trampoline is a small code fragment that saves state and
/// calls back into the JIT compiler to resolve the target.
pub struct TrampolinePool {
    /// Available trampoline slots.
    pub slots: usize,
    /// Size of each trampoline in bytes.
    pub trampoline_size: usize,
}

impl TrampolinePool {
    pub fn new(num_slots: usize) -> Self {
        TrampolinePool {
            slots: num_slots,
            trampoline_size: 32, // typical small trampoline
        }
    }

    /// Get the total memory required for all trampolines.
    pub fn total_size(&self) -> usize {
        self.slots * self.trampoline_size
    }

    /// Allocate a trampoline from the pool.
    pub fn allocate(&mut self) -> Option<usize> {
        if self.slots == 0 {
            return None;
        }
        self.slots -= 1;
        Some(self.slots)
    }

    /// Release a trampoline back to the pool.
    pub fn release(&mut self) {
        self.slots += 1;
    }
}

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

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

    #[test]
    fn test_jit_symbol_flags_default() {
        let flags = JITSymbolFlags::default();
        assert!(!flags.is_callable);
        assert!(flags.is_exported);
        assert!(!flags.is_weak);
    }

    #[test]
    fn test_jit_symbol_flags_exported_function() {
        let flags = JITSymbolFlags::exported_function();
        assert!(flags.is_callable);
        assert!(flags.is_exported);
    }

    #[test]
    fn test_jit_dylib_create() {
        let dylib = JITDylib::new("test_dylib");
        assert_eq!(dylib.name, "test_dylib");
        assert!(dylib.lookup("nonexistent").is_none());
    }

    #[test]
    fn test_jit_dylib_define_and_lookup() {
        let mut dylib = JITDylib::new("test");
        dylib.define_symbol("foo", 0x1000, JITSymbolFlags::exported_function());
        let sym = dylib.lookup("foo").unwrap();
        assert_eq!(sym.address, 0x1000);
        assert!(sym.flags.is_callable);
    }

    #[test]
    fn test_orc_session_create() {
        let session = ORCJITSession::new();
        assert!(!session.is_finalized);
        assert_eq!(session.dylib_count(), 0);
    }

    #[test]
    fn test_orc_session_create_dylib() {
        let mut session = ORCJITSession::new();
        session.create_dylib("main");
        assert_eq!(session.dylib_count(), 1);
    }

    #[test]
    fn test_orc_session_lookup_nonexistent() {
        let session = ORCJITSession::new();
        assert!(session.lookup("nonexistent").is_none());
    }

    #[test]
    fn test_orc_builder_default() {
        let builder = ORCJITBuilder::new();
        let result = builder.build();
        assert!(result.is_ok());
    }

    #[test]
    fn test_orc_builder_custom() {
        let builder = ORCJITBuilder::new()
            .target_triple("aarch64-linux-gnu")
            .opt_level(3)
            .lazy_compilation(false);
        let result = builder.build();
        assert!(result.is_ok());
    }

    #[test]
    fn test_memory_manager_allocate() {
        let mut mm = JITMemoryManager::new();
        let addr = mm.allocate(4096, true, true).unwrap();
        assert!(addr > 0);
        assert_eq!(mm.total_allocated(), 4096);
    }

    #[test]
    fn test_memory_manager_deallocate() {
        let mut mm = JITMemoryManager::new();
        mm.allocate(8192, true, true).unwrap();
        assert_eq!(mm.total_allocated(), 8192);
        mm.deallocate_all();
        assert_eq!(mm.total_allocated(), 0);
    }

    #[test]
    fn test_compile_callback_manager() {
        let mut ccm = CompileCallbackManager::new();
        let id = ccm.register_callback(
            "foo",
            Box::new(|name| {
                assert_eq!(name, "foo");
                Ok(0x2000)
            }),
        );
        assert_eq!(id, 0);

        let result = ccm.invoke_callback("foo");
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), 0x2000);
    }

    #[test]
    fn test_resource_tracker() {
        let mut tracker = ResourceTracker::new();
        tracker.track_memory(0x1000, 4096);
        tracker.track_symbol("test_sym");
        assert_eq!(tracker.tracked_addresses.len(), 1);
        assert_eq!(tracker.tracked_symbols.len(), 1);

        let mut mm = JITMemoryManager::new();
        tracker.release_all(&mut mm);
        assert!(tracker.tracked_addresses.is_empty());
    }

    #[test]
    fn test_jit_layer_names() {
        let linking = ObjectLinkingLayer::new();
        assert_eq!(linking.layer_name(), "ObjectLinkingLayer");
    }

    #[test]
    fn test_orc_session_finalize() {
        let mut session = ORCJITSession::new();
        assert!(!session.is_finalized);
        session.finalize().unwrap();
        assert!(session.is_finalized);
        // Double finalize is ok
        session.finalize().unwrap();
    }

    #[test]
    fn test_orc_session_errors() {
        let mut session = ORCJITSession::new();
        assert!(session.errors().is_empty());
        session.clear_errors();
    }
}