forked from nulang-org/nulang
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodegen.rs
More file actions
1618 lines (1521 loc) · 67 KB
/
Copy pathcodegen.rs
File metadata and controls
1618 lines (1521 loc) · 67 KB
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
//! AOT code generation: MIR → Cranelift CLIF.
//!
//! Compiles whole MIR functions to native code with unboxed parameter and
//! return types when type metadata is available. Falls back to NaN-tagged
//! runtime helpers when types are unknown.
//!
//! # Calling convention
//!
//! Compiled functions follow the C ABI:
//! ```c
//! uint64_t nulang_fn_N(uint64_t arg0, uint64_t arg1, ...);
//! ```
//! All arguments and return values are `u64` (NaN-tagged when type is
//! unknown, raw bits when unboxed). The AOT runtime trampoline handles
//! boxing/unboxing at function boundaries.
use cranelift::codegen::ir::{BlockArg, FuncRef};
use cranelift::prelude::*;
use cranelift_frontend::{FunctionBuilder, FunctionBuilderContext};
use cranelift_jit::JITModule;
use cranelift_module::{Linkage, Module};
use std::collections::{HashMap, HashSet};
use crate::mir;
use crate::type_metadata::{KnownType, TypeMetadata};
// Reuse NaN-tag constants and CLIF helpers from `cranelift_utils`.
use crate::cranelift_utils::{emit_sext48, emit_tag_bool, emit_tag_int, TAG_BOOL_I64, TAG_NIL_I64};
// ---------------------------------------------------------------------------
// Error type
// ---------------------------------------------------------------------------
/// Errors that can occur during AOT compilation.
#[derive(Debug)]
pub enum AotCompileError {
/// A MIR construct that isn't yet supported by the AOT backend.
Unsupported(String),
/// Internal compiler error.
Internal(String),
/// Cranelift compilation failure.
Cranelift(String),
}
impl std::fmt::Display for AotCompileError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
AotCompileError::Unsupported(msg) => write!(f, "AOT unsupported: {}", msg),
AotCompileError::Internal(msg) => write!(f, "AOT internal error: {}", msg),
AotCompileError::Cranelift(msg) => write!(f, "AOT cranelift error: {}", msg),
}
}
}
impl std::error::Error for AotCompileError {}
pub type AotResult<T> = Result<T, AotCompileError>;
// CLIF helpers imported from `cranelift_utils` (above).
// ---------------------------------------------------------------------------
// Compilation context
// ---------------------------------------------------------------------------
/// State maintained during compilation of one MIR module.
pub struct AotContext<'a> {
/// The Cranelift JIT module.
pub module: &'a mut JITModule,
/// Reusable function builder context.
pub builder_context: &'a mut FunctionBuilderContext,
/// Cranelift codegen context (holds the current function being compiled).
pub codegen_ctx: codegen::Context,
/// Runtime helpers registered with the JIT module.
pub helpers: HashMap<&'static str, FuncRef>,
/// FuncIds of already-compiled functions, indexed by MIR function index.
pub func_ids: Vec<cranelift_module::FuncId>,
/// Compilation mode: boxed (NaN-tagged) or unboxed (raw i64 for Int).
pub mode: CompileMode,
/// Module-wide field name → slot index mapping for records.
pub field_map: HashMap<String, u8>,
/// Module constant pool (for String constant resolution).
pub constants: Vec<crate::bytecode::Constant>,
}
impl<'a> AotContext<'a> {
pub fn new(module: &'a mut JITModule, builder_context: &'a mut FunctionBuilderContext) -> Self {
let codegen_ctx = module.make_context();
AotContext {
module,
builder_context,
codegen_ctx,
helpers: HashMap::new(),
func_ids: Vec::new(),
mode: CompileMode::Boxed,
field_map: HashMap::new(),
constants: Vec::new(),
}
}
}
// ---------------------------------------------------------------------------
// SSA construction helpers
// ---------------------------------------------------------------------------
/// Compute block predecessors from terminators.
fn compute_predecessors(func: &mir::Function) -> HashMap<mir::BlockId, Vec<mir::BlockId>> {
let mut preds: HashMap<mir::BlockId, Vec<mir::BlockId>> = HashMap::new();
for block in &func.blocks {
match &block.terminator {
mir::Terminator::Jump(target) => {
preds.entry(*target).or_default().push(block.id);
}
mir::Terminator::Branch { then_, else_, .. } => {
preds.entry(*then_).or_default().push(block.id);
preds.entry(*else_).or_default().push(block.id);
}
_ => {}
}
}
preds
}
/// Compute successors of each block for topological traversal.
fn compute_successors(func: &mir::Function) -> HashMap<mir::BlockId, Vec<mir::BlockId>> {
let mut succs: HashMap<mir::BlockId, Vec<mir::BlockId>> = HashMap::new();
for block in &func.blocks {
let targets = match &block.terminator {
mir::Terminator::Jump(target) => vec![*target],
mir::Terminator::Branch { then_, else_, .. } => vec![*then_, *else_],
_ => vec![],
};
succs.insert(block.id, targets);
}
succs
}
/// Compute reverse post-order (topological order) starting from the entry block.
fn reverse_postorder(func: &mir::Function) -> Vec<mir::BlockId> {
let succs = compute_successors(func);
let mut order = Vec::new();
let mut visited = HashSet::new();
// Recursive post-order DFS from entry.
fn dfs(
node: mir::BlockId,
succs: &HashMap<mir::BlockId, Vec<mir::BlockId>>,
visited: &mut HashSet<mir::BlockId>,
order: &mut Vec<mir::BlockId>,
) {
if !visited.insert(node) {
return;
}
if let Some(children) = succs.get(&node) {
for &child in children {
dfs(child, succs, visited, order);
}
}
order.push(node);
}
dfs(func.entry, &succs, &mut visited, &mut order);
order.reverse();
order
}
/// For each block, collect the set of register indices that are:
/// - Last assigned in at least one predecessor, AND
/// - The block has >1 predecessor.
///
/// These locals need CLIF block parameters for proper SSA merging.
fn compute_liveins(
func: &mir::Function,
preds: &HashMap<mir::BlockId, Vec<mir::BlockId>>,
local_base: u32,
) -> HashMap<mir::BlockId, Vec<u32>> {
// First, for each block, find which locals are last-assigned in that block.
let mut block_defs: HashMap<mir::BlockId, HashSet<u32>> = HashMap::new();
for block in &func.blocks {
let mut defs = HashSet::new();
for stmt in &block.stmts {
if let mir::Stmt::Assign { dst, .. } = stmt {
defs.insert(local_base + dst.0);
}
}
block_defs.insert(block.id, defs);
}
// For each block with >1 predecessor, compute locals defined in ALL predecessors.
let mut liveins: HashMap<mir::BlockId, Vec<u32>> = HashMap::new();
for block in &func.blocks {
let pids = match preds.get(&block.id) {
Some(p) if p.len() > 1 => p,
_ => continue,
};
// Start with definitions from first predecessor.
let mut merged: HashSet<u32> = block_defs.get(&pids[0]).cloned().unwrap_or_default();
for pid in &pids[1..] {
if let Some(defs) = block_defs.get(pid) {
merged = merged.intersection(defs).copied().collect();
} else {
merged.clear();
break;
}
}
if !merged.is_empty() {
let mut sorted: Vec<u32> = merged.into_iter().collect();
sorted.sort();
liveins.insert(block.id, sorted);
}
}
liveins
}
/// Like `compile_terminator` but passes block-param values for merged locals.
fn compile_terminator_with_params(
builder: &mut FunctionBuilder,
term: &mir::Terminator,
block_map: &HashMap<mir::BlockId, cranelift::prelude::Block>,
block_params: &HashMap<mir::BlockId, Vec<u32>>,
local_vals: &HashMap<u32, Value>,
_mode: CompileMode,
) -> AotResult<()> {
match term {
mir::Terminator::Return(val) => {
if let Some(id) = val {
let reg = mir::FunctionBuilder::LOCAL_BASE + id.0;
let v = *local_vals.get(®).ok_or_else(|| {
AotCompileError::Internal("return value uninitialized".into())
})?;
builder.ins().return_(&[v]);
} else {
let nil = builder
.ins()
.iconst(types::I64, 0x7FF8_0000_0000_0000u64 as i64);
builder.ins().return_(&[nil]);
}
Ok(())
}
mir::Terminator::Jump(target) => {
let clif_block = *block_map
.get(target)
.ok_or_else(|| AotCompileError::Internal("jump to unknown block".into()))?;
let args = block_param_args(block_params, target, local_vals);
builder.ins().jump(clif_block, &args);
Ok(())
}
mir::Terminator::Branch { cond, then_, else_ } => {
let cond_reg = mir::FunctionBuilder::LOCAL_BASE + cond.0;
let cond_val = *local_vals
.get(&cond_reg)
.ok_or_else(|| AotCompileError::Internal("branch cond uninitialized".into()))?;
let then_block = *block_map
.get(then_)
.ok_or_else(|| AotCompileError::Internal("branch then unknown".into()))?;
let else_block = *block_map
.get(else_)
.ok_or_else(|| AotCompileError::Internal("branch else unknown".into()))?;
let false_val = builder.ins().iconst(types::I64, TAG_BOOL_I64);
let is_true = builder.ins().icmp(IntCC::NotEqual, cond_val, false_val);
let then_args = block_param_args(block_params, then_, local_vals);
let else_args = block_param_args(block_params, else_, local_vals);
builder
.ins()
.brif(is_true, then_block, &then_args, else_block, &else_args);
Ok(())
}
mir::Terminator::Resume(id) => {
// In the interpreter a handler body ends with `Resume`,
// which restores the captured continuation with a value.
// At the AOT level we compile it as a normal return — the
// resume value is the function's result.
let reg = mir::FunctionBuilder::LOCAL_BASE + id.0;
let v = *local_vals
.get(®)
.ok_or_else(|| AotCompileError::Internal("resume value uninitialized".into()))?;
builder.ins().return_(&[v]);
Ok(())
}
mir::Terminator::Unterminated => Err(AotCompileError::Internal(
"reached Unterminated terminator in codegen — this is a compiler bug".into(),
)),
}
}
/// Build the argument list for a jump/branch to `target`: one Value per
/// block parameter, taken from the current `local_vals`.
fn block_param_args(
block_params: &HashMap<mir::BlockId, Vec<u32>>,
target: &mir::BlockId,
local_vals: &HashMap<u32, Value>,
) -> Vec<BlockArg> {
if let Some(params) = block_params.get(target) {
params
.iter()
.map(|reg| {
let val = *local_vals.get(reg).expect("block param local missing");
BlockArg::from(val)
})
.collect()
} else {
vec![]
}
}
// ---------------------------------------------------------------------------
// Main entry point: compile a MIR function to a native function pointer
// ---------------------------------------------------------------------------
/// Whether to emit NaN-tagged (boxed) or raw (unboxed) integer values.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum CompileMode {
/// NaN-tagged i64 — the default, interoperable representation.
Boxed,
/// Raw i64 for Int types — faster, but requires type knowledge at call sites.
Unboxed,
}
/// Check whether a function is eligible for unboxed compilation:
/// all params are `KnownType::Int` and the return type is Int or void.
pub fn is_all_int(func: &mir::Function) -> bool {
let local_base = mir::FunctionBuilder::LOCAL_BASE as usize;
for param in &func.params {
let reg = local_base + param.0 as usize;
if func.type_metadata.get_type(reg) != KnownType::Int {
return false;
}
}
// Return type: None (unit) is fine, Some(Int) is fine, anything else disqualifies.
if let Some(ref ret_ty) = func.ret {
match ret_ty {
crate::types::Type::Primitive(crate::types::PrimitiveType::Int) => {}
_ => return false,
}
}
true
}
/// Compile the body of a MIR function that was already declared.
///
pub fn compile_mir_function_body(
aot: &mut AotContext,
mir_func: &mir::Function,
_func_index: usize,
func_id: cranelift_module::FuncId,
mode: CompileMode,
) -> AotResult<()> {
aot.mode = mode;
// Reconstruct the signature for the codegen context.
let mut sig = aot.module.make_signature();
for _ in &mir_func.params {
sig.params.push(AbiParam::new(types::I64));
}
sig.returns.push(AbiParam::new(types::I64));
aot.codegen_ctx.func.signature = sig;
// Split module and codegen_ctx for independent borrows.
// Extract refs to constants and field_map before the split.
let constants: &[crate::bytecode::Constant] = &aot.constants;
let field_map: &HashMap<String, u8> = &aot.field_map;
let module: &mut JITModule = aot.module;
let codegen_ctx: &mut codegen::Context = &mut aot.codegen_ctx;
let builder_ctx: &mut FunctionBuilderContext = aot.builder_context;
let local_base = mir::FunctionBuilder::LOCAL_BASE;
let type_meta = mir_func.type_metadata.clone();
// Analyze block predecessors.
let preds = compute_predecessors(mir_func);
// For each block, collect locals assigned in any predecessor that are
// used in this block — these need block params when multiple preds exist.
let block_liveins = compute_liveins(mir_func, &preds, local_base);
// Pre-resolve cross-function call targets (will fill inside builder scope).
let mut call_targets: HashMap<usize, FuncRef> = HashMap::new();
let _helpers = {
let mut builder = FunctionBuilder::new(&mut codegen_ctx.func, builder_ctx);
let entry_block = builder.create_block();
builder.switch_to_block(entry_block);
builder.append_block_params_for_function_params(entry_block);
// Register runtime helpers with proper signatures.
let mut h: HashMap<&str, FuncRef> = HashMap::new();
// Binary helpers: (i64, i64) -> i64
let bin_helpers: &[&str] = &[
"nulang_iadd",
"nulang_isub",
"nulang_imul",
"nulang_idiv",
"nulang_imod",
"nulang_icmp_eq",
"nulang_icmp_lt",
"nulang_icmp_gt",
"nulang_icmp_le",
"nulang_icmp_ge",
"nulang_fadd",
"nulang_fsub",
"nulang_fmul",
"nulang_fdiv",
"nulang_fcmp_eq",
"nulang_fcmp_lt",
"nulang_fcmp_gt",
"nulang_and",
"nulang_or",
"nulang_xor",
"nulang_shl",
"nulang_shr",
"nulang_bitand",
"nulang_bitor",
];
for name in bin_helpers {
let mut h_sig = module.make_signature();
h_sig.params.push(AbiParam::new(types::I64));
h_sig.params.push(AbiParam::new(types::I64));
h_sig.returns.push(AbiParam::new(types::I64));
let h_id = module
.declare_function(name, Linkage::Import, &h_sig)
.map_err(|e| AotCompileError::Cranelift(e.to_string()))?;
let func_ref = module.declare_func_in_func(h_id, builder.func);
h.insert(*name, func_ref);
}
// Unary helpers: (i64) -> i64
let unary_helpers: &[&str] = &[
"nulang_ineg",
"nulang_iinc",
"nulang_idec",
"nulang_not",
"nulang_itof",
"nulang_ftoi",
"nulang_fneg",
];
for name in unary_helpers {
let mut h_sig = module.make_signature();
h_sig.params.push(AbiParam::new(types::I64));
h_sig.returns.push(AbiParam::new(types::I64));
let h_id = module
.declare_function(name, Linkage::Import, &h_sig)
.map_err(|e| AotCompileError::Cranelift(e.to_string()))?;
let func_ref = module.declare_func_in_func(h_id, builder.func);
h.insert(*name, func_ref);
}
// Add new AOT helpers (bin: pow, str_eq, str_concat, obj_get)
let extra_bin: &[&str] = &[
"nulang_pow",
"nulang_str_eq",
"nulang_str_concat",
"nulang_obj_get",
];
for name in extra_bin {
let mut h_sig = module.make_signature();
h_sig.params.push(AbiParam::new(types::I64));
h_sig.params.push(AbiParam::new(types::I64));
h_sig.returns.push(AbiParam::new(types::I64));
let h_id = module
.declare_function(name, Linkage::Import, &h_sig)
.map_err(|e| AotCompileError::Cranelift(e.to_string()))?;
let func_ref = module.declare_func_in_func(h_id, builder.func);
h.insert(*name, func_ref);
}
// Add unary helpers for obj_len, rec_copy
let extra_unary: &[&str] = &["nulang_obj_len", "nulang_rec_copy"];
for name in extra_unary {
let mut h_sig = module.make_signature();
h_sig.params.push(AbiParam::new(types::I64));
h_sig.returns.push(AbiParam::new(types::I64));
let h_id = module
.declare_function(name, Linkage::Import, &h_sig)
.map_err(|e| AotCompileError::Cranelift(e.to_string()))?;
let func_ref = module.declare_func_in_func(h_id, builder.func);
h.insert(*name, func_ref);
}
// alloc_obj: (i64, i32) -> i64
{
let mut h_sig = module.make_signature();
h_sig.params.push(AbiParam::new(types::I64));
h_sig.params.push(AbiParam::new(types::I32));
h_sig.returns.push(AbiParam::new(types::I64));
let h_id = module
.declare_function("nulang_alloc_obj", Linkage::Import, &h_sig)
.map_err(|e| AotCompileError::Cranelift(e.to_string()))?;
let func_ref = module.declare_func_in_func(h_id, builder.func);
h.insert("nulang_alloc_obj", func_ref);
}
// obj_set: (i64, i64, i64) -> void
{
let mut h_sig = module.make_signature();
h_sig.params.push(AbiParam::new(types::I64));
h_sig.params.push(AbiParam::new(types::I64));
h_sig.params.push(AbiParam::new(types::I64));
let h_id = module
.declare_function("nulang_obj_set", Linkage::Import, &h_sig)
.map_err(|e| AotCompileError::Cranelift(e.to_string()))?;
let func_ref = module.declare_func_in_func(h_id, builder.func);
h.insert("nulang_obj_set", func_ref);
}
// Helper to register a call target FuncRef.
let mut register_call_target = |n: usize| {
if !call_targets.contains_key(&n) {
if let Some(&callee_fid) = aot.func_ids.get(n) {
let local_ref = module.declare_func_in_func(callee_fid, builder.func);
call_targets.insert(n, local_ref);
}
}
};
// Pre-scan: register all call targets from Call and Closure rvalues.
for block in &mir_func.blocks {
for stmt in &block.stmts {
match stmt {
mir::Stmt::Assign {
op:
mir::RValue::Call {
func: mir::FuncRef::Index(n),
..
},
..
} => {
register_call_target(*n);
}
mir::Stmt::Assign {
op: mir::RValue::Closure { func, captures },
..
} if captures.is_empty() => {
register_call_target(*func);
}
_ => {}
}
}
}
// Track which locals hold zero-capture closures for call resolution.
let mut closure_targets: HashMap<u32, usize> = HashMap::new();
let mut local_vals: HashMap<u32, Value> = HashMap::new();
for (i, param_id) in mir_func.params.iter().enumerate() {
let reg = local_base + param_id.0;
let val = builder.block_params(entry_block)[i];
local_vals.insert(reg, val);
}
// Create CLIF blocks — allocate block params for merge blocks.
let mut block_map: HashMap<mir::BlockId, cranelift::prelude::Block> = HashMap::new();
// Track which locals have block params in each block.
let mut block_params: HashMap<mir::BlockId, Vec<u32>> = HashMap::new();
for block in &mir_func.blocks {
let clif_block = if block.id == mir_func.entry {
entry_block
} else {
let blk = builder.create_block();
// Add block params for locals that need merging.
if let Some(liveins) = block_liveins.get(&block.id) {
let mut params = Vec::new();
for ® in liveins {
builder.append_block_param(blk, types::I64);
params.push(reg);
}
block_params.insert(block.id, params);
}
blk
};
block_map.insert(block.id, clif_block);
}
// Compute topological block order so that each block's predecessors
// are compiled before it, ensuring local_vals is populated.
let block_order = reverse_postorder(mir_func);
// Debug: dump MIR when verbose.
if std::env::var("NULANG_DUMP_MIR").is_ok() {
eprintln!(
"=== AOT compiling fn_{} ({}) ===",
_func_index, mir_func.name
);
for &bid in &block_order {
let block = &mir_func.blocks[bid.0 as usize];
eprintln!(" Block[{}] (preds: {:?}):", bid.0, preds.get(&bid));
for stmt in &block.stmts {
eprintln!(" {:?}", stmt);
}
eprintln!(" term: {:?}", block.terminator);
}
eprintln!(" block_params: {:?}", block_params);
}
// Compile blocks in topological order.
for &bid in &block_order {
let block = &mir_func.blocks[bid.0 as usize];
let clif_block = block_map[&bid];
builder.switch_to_block(clif_block);
// Read block parameters into local_vals for non-entry blocks.
if block.id != mir_func.entry {
if let Some(params) = block_params.get(&block.id) {
for (i, ®) in params.iter().enumerate() {
let val = builder.block_params(clif_block)[i];
local_vals.insert(reg, val);
}
}
}
for stmt in &block.stmts {
compile_stmt(
&mut builder,
stmt,
&type_meta,
&h,
&call_targets,
&mut closure_targets,
&mut local_vals,
mode,
constants,
field_map,
)?;
}
compile_terminator_with_params(
&mut builder,
&block.terminator,
&block_map,
&block_params,
&local_vals,
mode,
)?;
}
builder.seal_all_blocks();
builder.finalize();
h
};
// Debug: dump CLIF when verbose.
if std::env::var("NULANG_DUMP_CLIF").is_ok() {
eprintln!("=== CLIF for fn_{} ===", _func_index);
eprintln!("{}", codegen_ctx.func.display());
}
module
.define_function(func_id, codegen_ctx)
.map_err(|e| AotCompileError::Cranelift(e.to_string()))?;
module.clear_context(codegen_ctx);
Ok(())
}
/// Generate a thin boxing wrapper for an all-Int function.
///
/// The wrapper takes tagged i64 arguments, untags them, calls the unboxed
/// variant, tags the result, and returns. This replaces the boxed body so
/// that callers always go through the wrapper — the original boxed body
/// is never compiled.
pub fn compile_boxing_wrapper(
aot: &mut AotContext,
param_count: usize,
boxed_fid: cranelift_module::FuncId,
unboxed_fid: cranelift_module::FuncId,
) -> AotResult<()> {
// Split module and codegen_ctx for independent borrows.
let module: &mut JITModule = aot.module;
let codegen_ctx: &mut codegen::Context = &mut aot.codegen_ctx;
let builder_ctx: &mut FunctionBuilderContext = aot.builder_context;
// Set up function signature: tagged i64 params, tagged i64 return.
let mut sig = module.make_signature();
for _ in 0..param_count {
sig.params.push(AbiParam::new(types::I64));
}
sig.returns.push(AbiParam::new(types::I64));
codegen_ctx.func.signature = sig;
let mut builder = FunctionBuilder::new(&mut codegen_ctx.func, builder_ctx);
let entry_block = builder.create_block();
builder.switch_to_block(entry_block);
builder.append_block_params_for_function_params(entry_block);
// Get unboxed function reference.
let callee_ref = module.declare_func_in_func(unboxed_fid, builder.func);
// Untag each parameter.
let params: Vec<Value> = builder.block_params(entry_block).to_vec();
let unboxed_args: Vec<Value> = params
.iter()
.map(|&p| emit_sext48(&mut builder, p))
.collect();
// Call unboxed variant.
let call = builder.ins().call(callee_ref, &unboxed_args);
let raw_result = builder.inst_results(call)[0];
// Tag result and return.
let tagged = emit_tag_int(&mut builder, raw_result);
builder.ins().return_(&[tagged]);
builder.seal_all_blocks();
builder.finalize();
// Debug: dump CLIF when verbose.
if std::env::var("NULANG_DUMP_CLIF").is_ok() {
eprintln!("=== CLIF for boxing wrapper ({}) ===", param_count);
eprintln!("{}", codegen_ctx.func.display());
}
module
.define_function(boxed_fid, codegen_ctx)
.map_err(|e| AotCompileError::Cranelift(e.to_string()))?;
module.clear_context(codegen_ctx);
Ok(())
}
// ---------------------------------------------------------------------------
// Statement compilation
// ---------------------------------------------------------------------------
fn compile_stmt(
builder: &mut FunctionBuilder,
stmt: &mir::Stmt,
type_meta: &TypeMetadata,
helpers: &HashMap<&str, FuncRef>,
call_targets: &HashMap<usize, FuncRef>,
closure_targets: &mut HashMap<u32, usize>,
local_vals: &mut HashMap<u32, Value>,
mode: CompileMode,
constants: &[crate::bytecode::Constant],
field_map: &HashMap<String, u8>,
) -> AotResult<()> {
match stmt {
mir::Stmt::Assign { dst, op } => {
if let mir::RValue::Closure { func, captures } = op {
if captures.is_empty() {
let reg = mir::FunctionBuilder::LOCAL_BASE + dst.0;
closure_targets.insert(reg, *func);
}
}
let val = compile_rvalue(
builder,
op,
type_meta,
helpers,
call_targets,
closure_targets,
local_vals,
mode,
constants,
field_map,
)?;
let reg = mir::FunctionBuilder::LOCAL_BASE + dst.0;
local_vals.insert(reg, val);
Ok(())
}
mir::Stmt::EnterHandle { .. } | mir::Stmt::PopHandler => {
// Handler tables and the handler stack are a runtime (VM)
// concept — at the AOT level these are no-ops. The handler
// body is compiled inline as ordinary blocks.
Ok(())
}
mir::Stmt::StoreFieldNamed { obj, field, src } => {
let obj_reg = mir::FunctionBuilder::LOCAL_BASE + obj.0;
let obj_val = *local_vals.get(&obj_reg).ok_or_else(|| {
AotCompileError::Internal("StoreFieldNamed obj uninitialized".into())
})?;
let src_reg = mir::FunctionBuilder::LOCAL_BASE + src.0;
let src_val = *local_vals.get(&src_reg).ok_or_else(|| {
AotCompileError::Internal("StoreFieldNamed src uninitialized".into())
})?;
let slot = field_map.get(field).copied().unwrap_or(0);
let slot_val = builder.ins().iconst(types::I64, slot as i64);
call_void_helper(
builder,
helpers,
"nulang_obj_set",
&[obj_val, slot_val, src_val],
)?;
Ok(())
}
mir::Stmt::ArrayStore { arr, idx, src } => {
let arr_reg = mir::FunctionBuilder::LOCAL_BASE + arr.0;
let arr_val = *local_vals
.get(&arr_reg)
.ok_or_else(|| AotCompileError::Internal("ArrayStore arr uninitialized".into()))?;
let idx_reg = mir::FunctionBuilder::LOCAL_BASE + idx.0;
let idx_val = *local_vals
.get(&idx_reg)
.ok_or_else(|| AotCompileError::Internal("ArrayStore idx uninitialized".into()))?;
let src_reg = mir::FunctionBuilder::LOCAL_BASE + src.0;
let src_val = *local_vals
.get(&src_reg)
.ok_or_else(|| AotCompileError::Internal("ArrayStore src uninitialized".into()))?;
call_void_helper(
builder,
helpers,
"nulang_obj_set",
&[arr_val, idx_val, src_val],
)?;
Ok(())
}
mir::Stmt::Emit { .. } => Err(AotCompileError::Unsupported(
"Emit: effect emission requires the bytecode backend (unavailable with --backend native)".into(),
)),
mir::Stmt::StateSet { .. } => Err(AotCompileError::Unsupported(
"StateSet: actor state mutation requires the bytecode backend (unavailable with --backend native)".into(),
)),
}
}
// ---------------------------------------------------------------------------
// RValue compilation
// ---------------------------------------------------------------------------
fn compile_rvalue(
builder: &mut FunctionBuilder,
rv: &mir::RValue,
type_meta: &TypeMetadata,
helpers: &HashMap<&str, FuncRef>,
call_targets: &HashMap<usize, FuncRef>,
closure_targets: &mut HashMap<u32, usize>,
local_vals: &HashMap<u32, Value>,
mode: CompileMode,
constants: &[crate::bytecode::Constant],
field_map: &HashMap<String, u8>,
) -> AotResult<Value> {
match rv {
mir::RValue::Const(c) => compile_const(builder, c, mode, constants),
mir::RValue::Load(id) => {
let reg = mir::FunctionBuilder::LOCAL_BASE + id.0;
local_vals
.get(®)
.copied()
.ok_or_else(|| AotCompileError::Internal(format!("uninitialized local {}", id.0)))
}
mir::RValue::Binary(op, lhs, rhs) => compile_binary(
builder, *op, *lhs, *rhs, type_meta, helpers, local_vals, mode,
),
mir::RValue::Unary(op, operand) => {
compile_unary(builder, *op, *operand, type_meta, helpers, local_vals, mode)
}
mir::RValue::Call { func, args } => {
let callee_ref = match func {
mir::FuncRef::Index(n) => call_targets.get(n).copied().ok_or_else(|| {
AotCompileError::Internal(format!("call target fn {} not compiled yet", n))
})?,
mir::FuncRef::Local(closure_id) => {
let reg = mir::FunctionBuilder::LOCAL_BASE + closure_id.0;
let target_idx = closure_targets.get(®).copied().ok_or_else(|| {
AotCompileError::Unsupported(
"indirect call: closure target unknown at compile time".into(),
)
})?;
call_targets.get(&target_idx).copied().ok_or_else(|| {
AotCompileError::Internal(format!(
"call target fn {} not compiled yet",
target_idx
))
})?
}
};
let arg_vals: Vec<Value> =
args.iter()
.map(|id| {
let reg = mir::FunctionBuilder::LOCAL_BASE + id.0;
local_vals.get(®).copied().ok_or_else(|| {
AotCompileError::Internal("call arg uninitialized".into())
})
})
.collect::<AotResult<Vec<_>>>()?;
let call = builder.ins().call(callee_ref, &arg_vals);
Ok(builder.inst_results(call)[0])
}
mir::RValue::Closure { func, captures } => {
if captures.is_empty() {
// Return tagged function index — also register for call resolution.
let idx = builder.ins().iconst(types::I64, *func as i64);
Ok(emit_tag_int(builder, idx))
} else {
Err(AotCompileError::Unsupported(
"closures with captures".into(),
))
}
}
mir::RValue::Perform {
resolved_handler: Some(_),
..
} => {
// PerformDirect (statically-resolved handler) is not yet
// supported in the AOT backend. Use the bytecode backend
// for effectful code, or the JIT which yields to the
// interpreter for PerformDirect.
Err(AotCompileError::Unsupported(
"PerformDirect: effectful code requires the bytecode backend (unavailable with --backend native). \
Use --backend bytecode instead."
.into(),
))
}
mir::RValue::Perform {
resolved_handler: None,
..
} => Err(AotCompileError::Unsupported(
"Perform with dynamic dispatch is not supported in the native backend".into(),
)),
// ---- Record ----
mir::RValue::Record(fields) => {
let max_slot: u8 = fields
.iter()
.filter_map(|(name, _)| field_map.get(name))
.copied()
.max()
.unwrap_or(0);
let slot_count = (max_slot as u64).saturating_add(1);
// alloc_obj(slot_count, type_tag=3 for Record)
let count_val = builder.ins().iconst(types::I64, slot_count as i64);
let tag_val = builder.ins().iconst(types::I32, 3);
let ptr = call_helper(builder, helpers, "nulang_alloc_obj", &[count_val, tag_val])?;
for (name, val_id) in fields {
let val_reg = mir::FunctionBuilder::LOCAL_BASE + val_id.0;
let val_val = *local_vals.get(&val_reg).ok_or_else(|| {
AotCompileError::Internal("record field uninitialized".into())
})?;
let slot = field_map.get(name).copied().unwrap_or(0);
let slot_val = builder.ins().iconst(types::I64, slot as i64);
call_void_helper(
builder,
helpers,
"nulang_obj_set",
&[ptr, slot_val, val_val],
)?;
}
Ok(ptr)
}
// ---- Tuple ----
mir::RValue::Tuple(elements) => {
let count = elements.len() as u64;
let count_val = builder.ins().iconst(types::I64, count as i64);
let tag_val = builder.ins().iconst(types::I32, 6);
let ptr = call_helper(builder, helpers, "nulang_alloc_obj", &[count_val, tag_val])?;
for (i, val_id) in elements.iter().enumerate() {
let val_reg = mir::FunctionBuilder::LOCAL_BASE + val_id.0;
let val_val = *local_vals.get(&val_reg).ok_or_else(|| {
AotCompileError::Internal("tuple element uninitialized".into())
})?;
let idx_val = builder.ins().iconst(types::I64, i as i64);
call_void_helper(builder, helpers, "nulang_obj_set", &[ptr, idx_val, val_val])?;
}
Ok(ptr)
}
// ---- ArrayLit ----
mir::RValue::ArrayLit(elements) => {
let count = elements.len() as u64;
let count_val = builder.ins().iconst(types::I64, count as i64);
let tag_val = builder.ins().iconst(types::I32, 1);
let ptr = call_helper(builder, helpers, "nulang_alloc_obj", &[count_val, tag_val])?;
for (i, val_id) in elements.iter().enumerate() {
let val_reg = mir::FunctionBuilder::LOCAL_BASE + val_id.0;
let val_val = *local_vals.get(&val_reg).ok_or_else(|| {
AotCompileError::Internal("array element uninitialized".into())
})?;
let idx_val = builder.ins().iconst(types::I64, i as i64);
call_void_helper(builder, helpers, "nulang_obj_set", &[ptr, idx_val, val_val])?;
}
Ok(ptr)
}
// ---- LoadFieldNamed (record field access) ----
mir::RValue::LoadFieldNamed { obj, field } => {
let obj_reg = mir::FunctionBuilder::LOCAL_BASE + obj.0;
let obj_val = *local_vals.get(&obj_reg).ok_or_else(|| {
AotCompileError::Internal("LoadFieldNamed obj uninitialized".into())
})?;
let slot = field_map.get(field).copied().unwrap_or(0);
let slot_val = builder.ins().iconst(types::I64, slot as i64);
call_helper(builder, helpers, "nulang_obj_get", &[obj_val, slot_val])
}
// ---- LoadFieldPos (tuple field access) ----
mir::RValue::LoadFieldPos { obj, index } => {
let obj_reg = mir::FunctionBuilder::LOCAL_BASE + obj.0;
let obj_val = *local_vals.get(&obj_reg).ok_or_else(|| {
AotCompileError::Internal("LoadFieldPos obj uninitialized".into())
})?;
let idx_val = builder.ins().iconst(types::I64, *index as i64);
call_helper(builder, helpers, "nulang_obj_get", &[obj_val, idx_val])
}
// ---- ArrayLoad ----
mir::RValue::ArrayLoad { arr, idx } => {
let arr_reg = mir::FunctionBuilder::LOCAL_BASE + arr.0;
let arr_val = *local_vals
.get(&arr_reg)
.ok_or_else(|| AotCompileError::Internal("ArrayLoad arr uninitialized".into()))?;
let idx_reg = mir::FunctionBuilder::LOCAL_BASE + idx.0;
let idx_val = *local_vals