forked from nulang-org/nulang
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompiler.rs
More file actions
994 lines (925 loc) · 33.8 KB
/
Copy pathcompiler.rs
File metadata and controls
994 lines (925 loc) · 33.8 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
//! Bytecode to Cranelift IR compiler.
//!
//! Translates a contiguous region of Nulang bytecode into native machine
//! code via Cranelift. Each opcode is mapped to one or more CLIF
//! instructions, with NaN-tag-aware arithmetic delegated to runtime
//! helper functions (see `runtime.rs`).
//!
//! # Supported Opcodes
//!
//! | Category | Opcodes |
//! |----------|---------|
//! | Special | Nop, Halt, Const0-2, ConstM1 |
//! | Register | Load, Store, Move, Swap, Dup |
//! | Integer Arith | IAdd, ISub, IMul, IDiv, IMod, INeg, IInc, IDec |
//! | Bitwise | Xor, Shl, Shr, BitAnd, BitOr |
//! | Float Arith | FAdd, FSub, FMul, FDiv, FNeg |
//! | Compare | ICmp{Eq,Lt,Gt,Le,Ge}, FCmp{Eq,Lt,Gt} |
//! | Logic | Not, And, Or |
//! | Control | Jmp, JmpT, JmpF |
//! | Effects | PerformDirect (yields to interpreter) |
//! | Convert | IToF, FToI |
//! | Debug | DbgPrint |
use std::collections::HashMap;
use cranelift::codegen::ir::FuncRef;
use cranelift::prelude::*;
use cranelift_frontend::FunctionBuilder;
use cranelift_jit::JITModule;
use cranelift_module::{Linkage, Module};
use crate::bytecode::{Instruction, OpCode};
use crate::jit::JitSession;
use crate::runtime::heap::{ActorHeap, OrcaHeader, TypeTag};
use crate::value_layout::{PAYLOAD_MASK, TAG_INT, TAG_MASK, TAG_NIL, TAG_PTR};
// ---------------------------------------------------------------------------
// Opcode Support Matrix
// ---------------------------------------------------------------------------
/// Check if an opcode can be compiled by the JIT.
pub fn is_opcode_compilable(op: OpCode) -> bool {
matches!(
op,
OpCode::Nop
| OpCode::Halt
| OpCode::Const0
| OpCode::Const1
| OpCode::Const2
| OpCode::ConstM1
| OpCode::ConstU
| OpCode::Load
| OpCode::Store
| OpCode::Move
| OpCode::Swap
| OpCode::Dup
| OpCode::IAdd
| OpCode::ISub
| OpCode::IMul
| OpCode::IDiv
| OpCode::IMod
| OpCode::INeg
| OpCode::IInc
| OpCode::IDec
| OpCode::Xor
| OpCode::Shl
| OpCode::Shr
| OpCode::BitAnd
| OpCode::BitOr
| OpCode::FAdd
| OpCode::FSub
| OpCode::FMul
| OpCode::FDiv
| OpCode::FNeg
| OpCode::ICmpEq
| OpCode::ICmpLt
| OpCode::ICmpGt
| OpCode::ICmpLe
| OpCode::ICmpGe
| OpCode::FCmpEq
| OpCode::FCmpLt
| OpCode::FCmpGt
| OpCode::Not
| OpCode::And
| OpCode::Or
| OpCode::Jmp
| OpCode::JmpT
| OpCode::JmpF
| OpCode::IToF
| OpCode::FToI
| OpCode::DbgPrint
| OpCode::Ret
| OpCode::RetVal
| OpCode::ArrLoad
| OpCode::ArrStore
| OpCode::ArrLen
| OpCode::FieldL
| OpCode::PerformDirect
)
}
// ---------------------------------------------------------------------------
// Signature Helpers
// ---------------------------------------------------------------------------
pub(crate) fn make_bin_sig<M: Module>(module: &M) -> Signature {
let mut sig = module.make_signature();
sig.params.push(AbiParam::new(types::I64));
sig.params.push(AbiParam::new(types::I64));
sig.returns.push(AbiParam::new(types::I64));
sig
}
pub(crate) fn make_unary_sig<M: Module>(module: &M) -> Signature {
let mut sig = module.make_signature();
sig.params.push(AbiParam::new(types::I64));
sig.returns.push(AbiParam::new(types::I64));
sig
}
pub(crate) fn make_void_reg3_sig<M: Module>(module: &M) -> Signature {
let mut sig = module.make_signature();
sig.params.push(AbiParam::new(types::I64));
sig.params.push(AbiParam::new(types::I32));
sig.params.push(AbiParam::new(types::I32));
sig
}
pub(crate) fn make_void_reg4_sig<M: Module>(module: &M) -> Signature {
let mut sig = module.make_signature();
sig.params.push(AbiParam::new(types::I64));
sig.params.push(AbiParam::new(types::I32));
sig.params.push(AbiParam::new(types::I32));
sig.params.push(AbiParam::new(types::I32));
sig
}
// ---------------------------------------------------------------------------
// Runtime Helper Registration
// ---------------------------------------------------------------------------
// Re-export from the single source of truth.
pub use crate::jit::helpers::RuntimeHelper;
fn register_runtime_helpers<M: Module>(
module: &mut M,
builder: &mut FunctionBuilder,
) -> Result<HashMap<RuntimeHelper, FuncRef>, CompileError> {
crate::jit::helpers::register_with_module(module, builder)
}
// ---------------------------------------------------------------------------
// Compilation
// ---------------------------------------------------------------------------
#[derive(Debug)]
pub enum CompileError {
DeclareFailed(String),
CompileFailed(String),
/// The region contains an opcode this compiler does not support;
/// callers should fall back to another compiler.
UnsupportedOpcode(String),
/// An internal invariant was violated (missing block, missing helper).
Internal(String),
}
impl std::fmt::Display for CompileError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
CompileError::DeclareFailed(msg) => write!(f, "function declaration failed: {}", msg),
CompileError::CompileFailed(msg) => write!(f, "compilation failed: {}", msg),
CompileError::UnsupportedOpcode(msg) => write!(f, "unsupported opcode: {}", msg),
CompileError::Internal(msg) => write!(f, "internal compiler error: {}", msg),
}
}
}
impl std::error::Error for CompileError {}
/// Compile a bytecode region to a native function.
pub fn compile_bytecode_region(
module: &mut JITModule,
builder_context: &mut FunctionBuilderContext,
ctx: &mut codegen::Context,
func_name: &str,
start_offset: usize,
num_instrs: usize,
instructions: &[Instruction],
) -> Result<*const u8, CompileError> {
ctx.clear();
let pointer_type = module.isa().pointer_type();
ctx.func.signature.params.push(AbiParam::new(pointer_type));
ctx.func.signature.params.push(AbiParam::new(pointer_type));
let mut builder = FunctionBuilder::new(&mut ctx.func, builder_context);
let entry_block = builder.create_block();
builder.append_block_params_for_function_params(entry_block);
builder.switch_to_block(entry_block);
builder.seal_block(entry_block);
let regs_ptr = builder.block_params(entry_block)[0];
let consts_ptr = builder.block_params(entry_block)[1];
let helpers = register_runtime_helpers(module, &mut builder)?;
let end_offset = (start_offset + num_instrs).min(instructions.len());
let mut blocks: HashMap<usize, Block> = HashMap::new();
for i in start_offset..end_offset {
blocks.insert(i, builder.create_block());
}
let return_block = builder.create_block();
// Inject JIT safepoint: decrement counter, yield if exhausted.
// Pointer is never null (initialized to a VM-owned dummy).
let safepoint_ptr_addr = JitSession::safepoint_ptr_addr();
let ptr_addr = builder.ins().iconst(types::I64, safepoint_ptr_addr);
let counter_ptr = builder.ins().load(types::I64, MemFlags::new(), ptr_addr, 0);
let counter = builder
.ins()
.load(types::I64, MemFlags::new(), counter_ptr, 0);
let one = builder.ins().iconst(types::I64, 1);
let new_counter = builder.ins().isub(counter, one);
builder
.ins()
.store(MemFlags::new(), new_counter, counter_ptr, 0);
let zero = builder.ins().iconst(types::I64, 0);
let exhausted = builder
.ins()
.icmp(IntCC::SignedLessThanOrEqual, new_counter, zero);
let yield_block = builder.create_block();
if let Some(&first_block) = blocks.get(&start_offset) {
builder
.ins()
.brif(exhausted, yield_block, &[], first_block, &[]);
} else {
builder
.ins()
.brif(exhausted, yield_block, &[], return_block, &[]);
}
// Yield block: store 0 to JIT_YIELD_PC, then return.
builder.switch_to_block(yield_block);
let yield_pc_addr = JitSession::yield_pc_addr();
let yield_pc_ptr = builder.ins().iconst(types::I64, yield_pc_addr);
let zero = builder.ins().iconst(types::I64, 0);
builder.ins().store(MemFlags::new(), zero, yield_pc_ptr, 0);
builder.ins().jump(return_block, &[]);
// Seal all new blocks.
builder.seal_block(yield_block);
for pc in start_offset..end_offset {
let instr = instructions[pc];
let block = *blocks
.get(&pc)
.ok_or_else(|| CompileError::Internal("missing block in compiled region".into()))?;
builder.switch_to_block(block);
match instr.opcode {
OpCode::Nop => {}
OpCode::Halt => {
builder.ins().jump(return_block, &[]);
}
OpCode::Const0 => {
emit_const(&mut builder, regs_ptr, instr.op1 as usize, 0);
}
OpCode::Const1 => {
emit_const(&mut builder, regs_ptr, instr.op1 as usize, 1);
}
OpCode::Const2 => {
emit_const(&mut builder, regs_ptr, instr.op1 as usize, 2);
}
OpCode::ConstM1 => {
emit_const(&mut builder, regs_ptr, instr.op1 as usize, -1);
}
OpCode::ConstU => {
let idx = instr.imm16() as usize;
let offset = (idx * 8) as i32;
let addr = if offset == 0 {
consts_ptr
} else {
let off = builder.ins().iconst(types::I64, offset as i64);
builder.ins().iadd(consts_ptr, off)
};
let val = builder.ins().load(types::I64, MemFlags::new(), addr, 0);
store_reg(&mut builder, regs_ptr, instr.op3 as usize, val);
}
OpCode::Load | OpCode::Store | OpCode::Move | OpCode::Dup => {
let v = load_reg(&mut builder, regs_ptr, instr.op1 as usize);
store_reg(&mut builder, regs_ptr, instr.op2 as usize, v);
}
OpCode::Swap => {
let v1 = load_reg(&mut builder, regs_ptr, instr.op1 as usize);
let v2 = load_reg(&mut builder, regs_ptr, instr.op2 as usize);
store_reg(&mut builder, regs_ptr, instr.op1 as usize, v2);
store_reg(&mut builder, regs_ptr, instr.op2 as usize, v1);
}
OpCode::IAdd => emit_binop(
&mut builder,
&helpers,
regs_ptr,
instr.op1 as usize,
instr.op2 as usize,
instr.op3 as usize,
RuntimeHelper::IAdd,
),
OpCode::ISub => emit_binop(
&mut builder,
&helpers,
regs_ptr,
instr.op1 as usize,
instr.op2 as usize,
instr.op3 as usize,
RuntimeHelper::ISub,
),
OpCode::IMul => emit_binop(
&mut builder,
&helpers,
regs_ptr,
instr.op1 as usize,
instr.op2 as usize,
instr.op3 as usize,
RuntimeHelper::IMul,
),
OpCode::IDiv => emit_binop(
&mut builder,
&helpers,
regs_ptr,
instr.op1 as usize,
instr.op2 as usize,
instr.op3 as usize,
RuntimeHelper::IDiv,
),
OpCode::IMod => emit_binop(
&mut builder,
&helpers,
regs_ptr,
instr.op1 as usize,
instr.op2 as usize,
instr.op3 as usize,
RuntimeHelper::IMod,
),
OpCode::INeg => emit_unary(
&mut builder,
&helpers,
regs_ptr,
instr.op1 as usize,
instr.op2 as usize,
RuntimeHelper::INeg,
),
OpCode::IInc => emit_self_unary(
&mut builder,
&helpers,
regs_ptr,
instr.op1 as usize,
RuntimeHelper::IInc,
),
OpCode::IDec => emit_self_unary(
&mut builder,
&helpers,
regs_ptr,
instr.op1 as usize,
RuntimeHelper::IDec,
),
OpCode::Xor => emit_binop(
&mut builder,
&helpers,
regs_ptr,
instr.op1 as usize,
instr.op2 as usize,
instr.op3 as usize,
RuntimeHelper::Xor,
),
OpCode::Shl => emit_binop(
&mut builder,
&helpers,
regs_ptr,
instr.op1 as usize,
instr.op2 as usize,
instr.op3 as usize,
RuntimeHelper::Shl,
),
OpCode::Shr => emit_binop(
&mut builder,
&helpers,
regs_ptr,
instr.op1 as usize,
instr.op2 as usize,
instr.op3 as usize,
RuntimeHelper::Shr,
),
OpCode::BitAnd => emit_binop(
&mut builder,
&helpers,
regs_ptr,
instr.op1 as usize,
instr.op2 as usize,
instr.op3 as usize,
RuntimeHelper::BitAnd,
),
OpCode::BitOr => emit_binop(
&mut builder,
&helpers,
regs_ptr,
instr.op1 as usize,
instr.op2 as usize,
instr.op3 as usize,
RuntimeHelper::BitOr,
),
OpCode::FAdd => emit_binop(
&mut builder,
&helpers,
regs_ptr,
instr.op1 as usize,
instr.op2 as usize,
instr.op3 as usize,
RuntimeHelper::FAdd,
),
OpCode::FSub => emit_binop(
&mut builder,
&helpers,
regs_ptr,
instr.op1 as usize,
instr.op2 as usize,
instr.op3 as usize,
RuntimeHelper::FSub,
),
OpCode::FMul => emit_binop(
&mut builder,
&helpers,
regs_ptr,
instr.op1 as usize,
instr.op2 as usize,
instr.op3 as usize,
RuntimeHelper::FMul,
),
OpCode::FDiv => emit_binop(
&mut builder,
&helpers,
regs_ptr,
instr.op1 as usize,
instr.op2 as usize,
instr.op3 as usize,
RuntimeHelper::FDiv,
),
// Interpreter reads src from op1 and writes dst to op3 for FNeg.
OpCode::FNeg => emit_unary(
&mut builder,
&helpers,
regs_ptr,
instr.op1 as usize,
instr.op3 as usize,
RuntimeHelper::FNeg,
),
OpCode::ICmpEq => emit_binop(
&mut builder,
&helpers,
regs_ptr,
instr.op1 as usize,
instr.op2 as usize,
instr.op3 as usize,
RuntimeHelper::ICmpEq,
),
OpCode::ICmpLt => emit_binop(
&mut builder,
&helpers,
regs_ptr,
instr.op1 as usize,
instr.op2 as usize,
instr.op3 as usize,
RuntimeHelper::ICmpLt,
),
OpCode::ICmpGt => emit_binop(
&mut builder,
&helpers,
regs_ptr,
instr.op1 as usize,
instr.op2 as usize,
instr.op3 as usize,
RuntimeHelper::ICmpGt,
),
OpCode::ICmpLe => emit_binop(
&mut builder,
&helpers,
regs_ptr,
instr.op1 as usize,
instr.op2 as usize,
instr.op3 as usize,
RuntimeHelper::ICmpLe,
),
OpCode::ICmpGe => emit_binop(
&mut builder,
&helpers,
regs_ptr,
instr.op1 as usize,
instr.op2 as usize,
instr.op3 as usize,
RuntimeHelper::ICmpGe,
),
OpCode::FCmpEq => emit_binop(
&mut builder,
&helpers,
regs_ptr,
instr.op1 as usize,
instr.op2 as usize,
instr.op3 as usize,
RuntimeHelper::FCmpEq,
),
OpCode::FCmpLt => emit_binop(
&mut builder,
&helpers,
regs_ptr,
instr.op1 as usize,
instr.op2 as usize,
instr.op3 as usize,
RuntimeHelper::FCmpLt,
),
OpCode::FCmpGt => emit_binop(
&mut builder,
&helpers,
regs_ptr,
instr.op1 as usize,
instr.op2 as usize,
instr.op3 as usize,
RuntimeHelper::FCmpGt,
),
OpCode::Not => emit_unary(
&mut builder,
&helpers,
regs_ptr,
instr.op1 as usize,
instr.op2 as usize,
RuntimeHelper::Not,
),
OpCode::And => emit_binop(
&mut builder,
&helpers,
regs_ptr,
instr.op1 as usize,
instr.op2 as usize,
instr.op3 as usize,
RuntimeHelper::And,
),
OpCode::Or => emit_binop(
&mut builder,
&helpers,
regs_ptr,
instr.op1 as usize,
instr.op2 as usize,
instr.op3 as usize,
RuntimeHelper::Or,
),
OpCode::Jmp => {
let target = (pc as i64 + instr.simm16() as i64) as usize;
if let Some(&target_block) = blocks.get(&target) {
builder.ins().jump(target_block, &[]);
} else {
builder.ins().jump(return_block, &[]);
}
}
OpCode::JmpT => {
let target = (pc as i64 + instr.offset16() as i64) as usize;
let cond_val = load_reg(&mut builder, regs_ptr, instr.op1 as usize);
let zero = builder.ins().iconst(types::I64, 0);
let is_nonzero = builder.ins().icmp(IntCC::NotEqual, cond_val, zero);
let fallthrough = *blocks.get(&(pc + 1)).unwrap_or(&return_block);
if let Some(&target_block) = blocks.get(&target) {
builder
.ins()
.brif(is_nonzero, target_block, &[], fallthrough, &[]);
} else {
builder.ins().jump(fallthrough, &[]);
}
}
OpCode::JmpF => {
let target = (pc as i64 + instr.offset16() as i64) as usize;
let cond_val = load_reg(&mut builder, regs_ptr, instr.op1 as usize);
let zero = builder.ins().iconst(types::I64, 0);
let is_zero = builder.ins().icmp(IntCC::Equal, cond_val, zero);
let fallthrough = *blocks.get(&(pc + 1)).unwrap_or(&return_block);
if let Some(&target_block) = blocks.get(&target) {
builder
.ins()
.brif(is_zero, target_block, &[], fallthrough, &[]);
} else {
builder.ins().jump(fallthrough, &[]);
}
}
OpCode::IToF => emit_unary(
&mut builder,
&helpers,
regs_ptr,
instr.op1 as usize,
instr.op2 as usize,
RuntimeHelper::IToF,
),
OpCode::FToI => emit_unary(
&mut builder,
&helpers,
regs_ptr,
instr.op1 as usize,
instr.op2 as usize,
RuntimeHelper::FToI,
),
OpCode::Ret | OpCode::RetVal => {
builder.ins().jump(return_block, &[]);
}
OpCode::DbgPrint => {}
OpCode::ArrLoad => {
emit_arr_load(
&mut builder,
regs_ptr,
instr.op1 as usize,
instr.op2 as usize,
instr.op3 as usize,
);
}
OpCode::ArrStore => {
emit_reg_call4(
&mut builder,
&helpers,
regs_ptr,
instr.op1,
instr.op2,
instr.op3,
RuntimeHelper::ArrStore,
);
}
OpCode::ArrLen => {
emit_reg_call3(
&mut builder,
&helpers,
regs_ptr,
instr.op1,
instr.op3,
RuntimeHelper::ArrLen,
);
}
OpCode::FieldL => {
emit_reg_call4(
&mut builder,
&helpers,
regs_ptr,
instr.op1,
instr.op2,
instr.op3,
RuntimeHelper::FieldL,
);
}
OpCode::PerformDirect => {
// Yield to interpreter at this exact instruction.
// The interpreter handles continuation capture and
// handler dispatch. Store the relative PC offset
// so try_jit_execute re-enters the interpreter at
// the PerformDirect instruction.
let yield_pc_addr = JitSession::yield_pc_addr();
let yield_pc_ptr = builder.ins().iconst(types::I64, yield_pc_addr);
let rel_offset = builder.ins().iconst(types::I64, (pc - start_offset) as i64);
builder
.ins()
.store(MemFlags::new(), rel_offset, yield_pc_ptr, 0);
builder.ins().jump(return_block, &[]);
}
_ => {
builder.ins().jump(return_block, &[]);
}
}
let is_terminator = matches!(
instr.opcode,
OpCode::Jmp
| OpCode::JmpT
| OpCode::JmpF
| OpCode::Halt
| OpCode::Ret
| OpCode::RetVal
| OpCode::PerformDirect
);
if !is_terminator {
if let Some(&next_block) = blocks.get(&(pc + 1)) {
builder.ins().jump(next_block, &[]);
} else {
builder.ins().jump(return_block, &[]);
}
}
}
for block in blocks.values() {
builder.seal_block(*block);
}
builder.switch_to_block(return_block);
builder.seal_block(return_block);
builder.ins().return_(&[]);
builder.finalize();
let func_id = module
.declare_function(func_name, Linkage::Local, &ctx.func.signature.clone())
.map_err(|e| CompileError::DeclareFailed(format!("{}", e)))?;
module
.define_function(func_id, ctx)
.map_err(|e| CompileError::CompileFailed(format!("{}", e)))?;
module
.finalize_definitions()
.map_err(|e| CompileError::CompileFailed(format!("finalize: {}", e)))?;
let code = module.get_finalized_function(func_id);
Ok(code as *const u8)
}
// ---------------------------------------------------------------------------
// CLIF Generation Helpers — shared with typed_compiler.rs
// ---------------------------------------------------------------------------
use crate::jit::typed_compiler::{emit_const, load_reg, store_reg};
pub(crate) fn emit_arr_load(
builder: &mut FunctionBuilder,
regs_ptr: Value,
arr_reg: usize,
idx_reg: usize,
dst: usize,
) {
// Load NaN-boxed array pointer and index.
let arr_val = load_reg(builder, regs_ptr, arr_reg);
let idx_val = load_reg(builder, regs_ptr, idx_reg);
// Interpreter parity (vm.rs `OpCode::ArrLoad`): the load yields nil
// unless the array register holds a non-null heap pointer to an
// Array-typed object AND the index is in bounds — never a raw
// dereference. The `#[repr(C)]` `OrcaHeader` sits immediately before
// the payload pointer; field offsets come from `offset_of!` so they
// track the struct layout.
let header_size = builder
.ins()
.iconst(types::I64, ActorHeap::HEADER_SIZE as i64);
let nil_bits = builder.ins().iconst(types::I64, TAG_NIL as i64);
let arr_tag = builder.ins().band_imm(arr_val, TAG_MASK as i64);
let is_ptr = builder
.ins()
.icmp_imm(IntCC::Equal, arr_tag, TAG_PTR as i64);
// Extract raw pointer (mask off tag bits from NaN-boxed pointer).
let arr_ptr = builder.ins().band_imm(arr_val, PAYLOAD_MASK as i64);
let non_null = builder.ins().icmp_imm(IntCC::NotEqual, arr_ptr, 0);
let can_read_header = builder.ins().band(is_ptr, non_null);
let header_blk = builder.create_block();
let bounds_blk = builder.create_block();
let load_blk = builder.create_block();
let nil_blk = builder.create_block();
let merge_blk = builder.create_block();
builder
.ins()
.brif(can_read_header, header_blk, &[], nil_blk, &[]);
// Header check: the object must carry the Array type tag.
builder.switch_to_block(header_blk);
let header = builder.ins().isub(arr_ptr, header_size);
let type_tag = builder.ins().load(
types::I8,
MemFlags::new(),
header,
std::mem::offset_of!(OrcaHeader, type_tag) as i32,
);
let is_array = builder
.ins()
.icmp_imm(IntCC::Equal, type_tag, TypeTag::Array as i64);
builder.ins().brif(is_array, bounds_blk, &[], nil_blk, &[]);
// Bounds check: len = (header.size - header_size) / 8. The unsigned
// compare also rejects negative indices (huge when viewed unsigned),
// and the int-tag select mirrors `as_int().unwrap_or(0)`.
builder.switch_to_block(bounds_blk);
let size = builder.ins().load(
types::I64,
MemFlags::new(),
header,
std::mem::offset_of!(OrcaHeader, size) as i32,
);
let payload = builder.ins().isub(size, header_size);
let len = builder.ins().ushr_imm(payload, 3);
let shifted = builder.ins().ishl_imm(idx_val, 16);
let idx_sext = builder.ins().sshr_imm(shifted, 16);
let idx_tag = builder.ins().band_imm(idx_val, TAG_MASK as i64);
let is_int = builder
.ins()
.icmp_imm(IntCC::Equal, idx_tag, TAG_INT as i64);
let zero = builder.ins().iconst(types::I64, 0);
let idx_raw = builder.ins().select(is_int, idx_sext, zero);
let in_bounds = builder.ins().icmp(IntCC::UnsignedLessThan, idx_raw, len);
builder.ins().brif(in_bounds, load_blk, &[], nil_blk, &[]);
// In bounds: load the tagged Value at arr_ptr + idx * 8.
builder.switch_to_block(load_blk);
let offset = builder.ins().ishl_imm(idx_raw, 3);
let addr = builder.ins().iadd(arr_ptr, offset);
let result = builder.ins().load(types::I64, MemFlags::new(), addr, 0);
store_reg(builder, regs_ptr, dst, result);
builder.ins().jump(merge_blk, &[]);
// Any failed check produces nil, exactly like the interpreter.
builder.switch_to_block(nil_blk);
store_reg(builder, regs_ptr, dst, nil_bits);
builder.ins().jump(merge_blk, &[]);
// Every predecessor edge is emitted now; the caller adds the
// fallthrough jump out of merge_blk.
builder.seal_block(header_blk);
builder.seal_block(bounds_blk);
builder.seal_block(load_blk);
builder.seal_block(nil_blk);
builder.seal_block(merge_blk);
builder.switch_to_block(merge_blk);
}
fn emit_binop(
builder: &mut FunctionBuilder,
helpers: &HashMap<RuntimeHelper, FuncRef>,
regs_ptr: Value,
op1: usize,
op2: usize,
dst: usize,
helper: RuntimeHelper,
) {
let a = load_reg(builder, regs_ptr, op1);
let b = load_reg(builder, regs_ptr, op2);
let func_ref = *helpers
.get(&helper)
.expect("runtime helper not registered in helpers map");
let call = builder.ins().call(func_ref, &[a, b]);
let result = builder.inst_results(call)[0];
store_reg(builder, regs_ptr, dst, result);
}
fn emit_unary(
builder: &mut FunctionBuilder,
helpers: &HashMap<RuntimeHelper, FuncRef>,
regs_ptr: Value,
src: usize,
dst: usize,
helper: RuntimeHelper,
) {
let a = load_reg(builder, regs_ptr, src);
let func_ref = *helpers
.get(&helper)
.expect("runtime helper not registered in helpers map");
let call = builder.ins().call(func_ref, &[a]);
let result = builder.inst_results(call)[0];
store_reg(builder, regs_ptr, dst, result);
}
fn emit_self_unary(
builder: &mut FunctionBuilder,
helpers: &HashMap<RuntimeHelper, FuncRef>,
regs_ptr: Value,
reg: usize,
helper: RuntimeHelper,
) {
emit_unary(builder, helpers, regs_ptr, reg, reg, helper);
}
fn emit_reg_call3(
builder: &mut FunctionBuilder,
helpers: &HashMap<RuntimeHelper, FuncRef>,
regs_ptr: Value,
r1: u8,
r2: u8,
helper: RuntimeHelper,
) {
let func_ref = *helpers.get(&helper).expect("helper not registered");
let a = builder.ins().iconst(types::I32, r1 as i64);
let b = builder.ins().iconst(types::I32, r2 as i64);
builder.ins().call(func_ref, &[regs_ptr, a, b]);
}
fn emit_reg_call4(
builder: &mut FunctionBuilder,
helpers: &HashMap<RuntimeHelper, FuncRef>,
regs_ptr: Value,
r1: u8,
r2: u8,
r3: u8,
helper: RuntimeHelper,
) {
let func_ref = *helpers.get(&helper).expect("helper not registered");
let a = builder.ins().iconst(types::I32, r1 as i64);
let b = builder.ins().iconst(types::I32, r2 as i64);
let c = builder.ins().iconst(types::I32, r3 as i64);
builder.ins().call(func_ref, &[regs_ptr, a, b, c]);
}
#[cfg(test)]
mod tests {
use super::*;
use crate::bytecode::OpCode;
#[test]
fn test_is_opcode_compilable_mvp() {
assert!(is_opcode_compilable(OpCode::IAdd));
assert!(is_opcode_compilable(OpCode::ISub));
assert!(is_opcode_compilable(OpCode::Move));
assert!(is_opcode_compilable(OpCode::Jmp));
assert!(is_opcode_compilable(OpCode::Ret));
}
#[test]
fn test_is_opcode_compilable_extended() {
// Register copies.
assert!(is_opcode_compilable(OpCode::Load));
assert!(is_opcode_compilable(OpCode::Store));
// Bitwise integer ops.
assert!(is_opcode_compilable(OpCode::Xor));
assert!(is_opcode_compilable(OpCode::Shl));
assert!(is_opcode_compilable(OpCode::Shr));
assert!(is_opcode_compilable(OpCode::BitAnd));
assert!(is_opcode_compilable(OpCode::BitOr));
// Float negate.
assert!(is_opcode_compilable(OpCode::FNeg));
// Opcodes the interpreter itself does not implement stay unsupported.
assert!(!is_opcode_compilable(OpCode::IPow));
assert!(!is_opcode_compilable(OpCode::FMod));
assert!(!is_opcode_compilable(OpCode::ConstL));
}
#[test]
fn test_is_opcode_compilable_not_mvp() {
assert!(!is_opcode_compilable(OpCode::Spawn));
assert!(!is_opcode_compilable(OpCode::Send));
assert!(!is_opcode_compilable(OpCode::FFICall));
}
#[test]
fn test_is_opcode_compilable_float_ops() {
assert!(is_opcode_compilable(OpCode::FAdd));
assert!(is_opcode_compilable(OpCode::FSub));
assert!(is_opcode_compilable(OpCode::FMul));
assert!(is_opcode_compilable(OpCode::FDiv));
assert!(is_opcode_compilable(OpCode::FCmpEq));
assert!(is_opcode_compilable(OpCode::FCmpLt));
assert!(is_opcode_compilable(OpCode::FCmpGt));
}
#[test]
fn test_is_opcode_compilable_conversion() {
assert!(is_opcode_compilable(OpCode::IToF));
assert!(is_opcode_compilable(OpCode::FToI));
assert!(is_opcode_compilable(OpCode::INeg));
assert!(is_opcode_compilable(OpCode::IInc));
assert!(is_opcode_compilable(OpCode::IDec));
}
#[test]
fn test_is_opcode_compilable_logical() {
assert!(is_opcode_compilable(OpCode::Not));
assert!(is_opcode_compilable(OpCode::And));
assert!(is_opcode_compilable(OpCode::Or));
assert!(is_opcode_compilable(OpCode::DbgPrint));
}
#[test]
fn test_is_opcode_compilable_compare() {
assert!(is_opcode_compilable(OpCode::ICmpEq));
assert!(is_opcode_compilable(OpCode::ICmpLt));
assert!(is_opcode_compilable(OpCode::ICmpGt));
assert!(is_opcode_compilable(OpCode::ICmpLe));
assert!(is_opcode_compilable(OpCode::ICmpGe));
}
#[test]
fn test_is_opcode_compilable_special() {
assert!(is_opcode_compilable(OpCode::Nop));
assert!(is_opcode_compilable(OpCode::Halt));
assert!(is_opcode_compilable(OpCode::Const0));
assert!(is_opcode_compilable(OpCode::ConstU));
}
#[test]
fn test_is_opcode_compilable_swap_dup() {
assert!(is_opcode_compilable(OpCode::Swap));
assert!(is_opcode_compilable(OpCode::Dup));
}
}