forked from factor/factor
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjit.zig
More file actions
1421 lines (1188 loc) · 54.9 KB
/
Copy pathjit.zig
File metadata and controls
1421 lines (1188 loc) · 54.9 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
const std = @import("std");
const builtin = @import("builtin");
const code_blocks = @import("code_blocks.zig");
const cpu = @import("cpu.zig");
const growable = @import("growable.zig");
const jit_protect = @import("jit_protect.zig");
const layouts = @import("layouts.zig");
const objects = @import("objects.zig");
const vm_mod = @import("vm.zig");
const Cell = layouts.Cell;
const Fixnum = layouts.Fixnum;
const FactorVM = vm_mod.FactorVM;
// JIT template indices (stored in special_objects)
pub const JitTemplate = enum(u32) {
// Basic templates
prolog = @intFromEnum(objects.SpecialObject.jit_prolog),
primitive_word = @intFromEnum(objects.SpecialObject.jit_primitive_word),
primitive = @intFromEnum(objects.SpecialObject.jit_primitive),
word_jump = @intFromEnum(objects.SpecialObject.jit_word_jump),
word_call = @intFromEnum(objects.SpecialObject.jit_word_call),
if_word = @intFromEnum(objects.SpecialObject.jit_if_word),
jit_if = @intFromEnum(objects.SpecialObject.jit_if),
safepoint = @intFromEnum(objects.SpecialObject.jit_safepoint),
epilog = @intFromEnum(objects.SpecialObject.jit_epilog),
return_template = @intFromEnum(objects.SpecialObject.jit_return),
push_literal = @intFromEnum(objects.SpecialObject.jit_push_literal),
dip_word = @intFromEnum(objects.SpecialObject.jit_dip_word),
dip = @intFromEnum(objects.SpecialObject.jit_dip),
two_dip_word = @intFromEnum(objects.SpecialObject.jit_2dip_word),
two_dip = @intFromEnum(objects.SpecialObject.jit_2dip),
three_dip_word = @intFromEnum(objects.SpecialObject.jit_3dip_word),
three_dip = @intFromEnum(objects.SpecialObject.jit_3dip),
execute = @intFromEnum(objects.SpecialObject.jit_execute),
declare_word = @intFromEnum(objects.SpecialObject.jit_declare_word),
// PIC templates
pic_load = @intFromEnum(objects.SpecialObject.pic_load),
pic_tag = @intFromEnum(objects.SpecialObject.pic_tag),
pic_tuple = @intFromEnum(objects.SpecialObject.pic_tuple),
pic_check_tag = @intFromEnum(objects.SpecialObject.pic_check_tag),
pic_check_tuple = @intFromEnum(objects.SpecialObject.pic_check_tuple),
pic_hit = @intFromEnum(objects.SpecialObject.pic_hit),
pic_miss_word = @intFromEnum(objects.SpecialObject.pic_miss_word),
pic_miss_tail_word = @intFromEnum(objects.SpecialObject.pic_miss_tail_word),
// Megamorphic templates
mega_lookup = @intFromEnum(objects.SpecialObject.mega_lookup),
mega_lookup_word = @intFromEnum(objects.SpecialObject.mega_lookup_word),
mega_miss_word = @intFromEnum(objects.SpecialObject.mega_miss_word),
};
// =============================================================================
// Label and Forward Reference System
// =============================================================================
// Position is -1 if not yet defined (forward reference)
pub const Label = struct {
position: i64,
pub fn init() Label {
return .{ .position = -1 };
}
pub fn isDefined(self: *const Label) bool {
return self.position >= 0;
}
pub fn define(self: *Label, pos: usize) void {
self.position = @intCast(pos);
}
pub fn getPosition(self: *const Label) ?usize {
if (self.isDefined()) {
return @intCast(self.position);
}
return null;
}
};
pub const ForwardReference = struct {
label_id: usize, // Index into label array
patch_offset: usize, // Offset in code buffer where to patch
relocation_class: code_blocks.RelocationClass, // Type of relocation
pub fn init(label_id: usize, patch_offset: usize, rel_class: code_blocks.RelocationClass) ForwardReference {
return .{
.label_id = label_id,
.patch_offset = patch_offset,
.relocation_class = rel_class,
};
}
};
pub const LabelManager = struct {
labels: std.ArrayList(Label),
forward_refs: std.ArrayList(ForwardReference),
allocator: std.mem.Allocator,
const Self = @This();
pub fn init(allocator: std.mem.Allocator) Self {
return .{
.labels = .empty,
.forward_refs = .empty,
.allocator = allocator,
};
}
pub fn deinit(self: *Self) void {
self.labels.deinit(self.allocator);
self.forward_refs.deinit(self.allocator);
}
pub fn clear(self: *Self) void {
self.labels.clearRetainingCapacity();
self.forward_refs.clearRetainingCapacity();
}
pub fn makeLabel(self: *Self) !usize {
const label_id = self.labels.items.len;
try self.labels.append(self.allocator, Label.init());
return label_id;
}
pub fn defineLabel(self: *Self, label_id: usize, position: usize) !void {
if (label_id >= self.labels.items.len) {
return error.InvalidLabelId;
}
self.labels.items[label_id].define(position);
}
pub fn isLabelDefined(self: *const Self, label_id: usize) bool {
if (label_id >= self.labels.items.len) {
return false;
}
return self.labels.items[label_id].isDefined();
}
// Get label position (null if undefined)
pub fn getLabelPosition(self: *const Self, label_id: usize) ?usize {
if (label_id >= self.labels.items.len) {
return null;
}
return self.labels.items[label_id].getPosition();
}
// Add a forward reference
pub fn addForwardRef(self: *Self, label_id: usize, patch_offset: usize, rel_class: code_blocks.RelocationClass) !void {
if (label_id >= self.labels.items.len) {
return error.InvalidLabelId;
}
try self.forward_refs.append(
self.allocator,
ForwardReference.init(label_id, patch_offset, rel_class),
);
}
// Returns the fixup data as an array of [relocation_class, offset, target] triples
pub fn fixupLabels(self: *Self, code_buffer: []u8) !std.ArrayList(Cell) {
var fixups: std.ArrayList(Cell) = .empty;
errdefer fixups.deinit(self.allocator);
try fixups.ensureUnusedCapacity(self.allocator, self.forward_refs.items.len * 3);
for (self.forward_refs.items) |fwd_ref| {
const label_id = fwd_ref.label_id;
if (label_id >= self.labels.items.len) {
return error.InvalidLabelId;
}
const label = self.labels.items[label_id];
if (!label.isDefined()) {
return error.UndefinedLabel;
}
const target_pos = label.getPosition() orelse return error.UndefinedLabel;
// Patch the code directly for relative jumps/calls
try patchRelativeJump(code_buffer, fwd_ref.patch_offset, target_pos);
// Record fixup for code block metadata (Factor format: class, offset, target)
fixups.appendAssumeCapacity(layouts.tagFixnum(@as(Fixnum, @intCast(@intFromEnum(fwd_ref.relocation_class)))));
fixups.appendAssumeCapacity(layouts.tagFixnum(@as(Fixnum, @intCast(fwd_ref.patch_offset))));
fixups.appendAssumeCapacity(layouts.tagFixnum(@as(Fixnum, @intCast(target_pos))));
}
return fixups;
}
};
fn patchRelativeJump(code_buffer: []u8, patch_offset: usize, target_pos: usize) !void {
const arch = cpu.Arch.current();
switch (arch) {
.x86, .x86_64 => {
// x86_64: relative offset is 4 bytes after the opcode
// Jump/call format: [opcode] [4-byte rel offset]
// The offset is calculated from the end of the instruction
const insn_end = patch_offset + 5; // opcode (1 byte) + offset (4 bytes)
const rel_offset: i32 = @intCast(@as(i64, @intCast(target_pos)) - @as(i64, @intCast(insn_end)));
if (patch_offset + 5 > code_buffer.len) {
return error.PatchOffsetOutOfBounds;
}
// Write the offset in little-endian format
std.mem.writeInt(i32, code_buffer[patch_offset + 1 ..][0..4], rel_offset, .little);
},
.aarch64 => {
// ARM64: branch offset is encoded in the instruction
// B/BL format: [6-bit opcode][26-bit signed offset]
// Offset is in instructions (4-byte aligned), so divide by 4
const insn_pos = patch_offset;
const offset_in_bytes: i32 = @intCast(@as(i64, @intCast(target_pos)) - @as(i64, @intCast(insn_pos)));
const offset_in_insns: i32 = @divExact(offset_in_bytes, 4);
if (patch_offset + 4 > code_buffer.len) {
return error.PatchOffsetOutOfBounds;
}
// Read existing instruction
const insn_ptr: *u32 = @ptrCast(@alignCast(&code_buffer[patch_offset]));
var insn = std.mem.readInt(u32, @as(*[4]u8, @ptrCast(insn_ptr)), .little);
// Clear old offset bits (lower 26 bits) and set new offset
const imm26: u32 = @bitCast(offset_in_insns & 0x03ffffff);
insn = (insn & 0xfc000000) | imm26;
// Write back
std.mem.writeInt(u32, @as(*[4]u8, @ptrCast(insn_ptr)), insn, .little);
},
.unsupported => return error.UnsupportedArchitecture,
}
}
// Base JIT compiler
pub const Jit = struct {
vm: *FactorVM,
owner: Cell, // Tagged pointer to word or quotation
code: std.ArrayList(u8),
relocation: std.ArrayList(u8),
parameters: growable.GrowableArray,
literals: growable.GrowableArray,
label_manager: LabelManager,
// For offset computation (debugging/source mapping)
computing_offset_p: bool,
position: i64,
offset: u64,
const Self = @This();
pub fn init(vm: *FactorVM, owner: Cell) Self {
std.debug.assert(vm.current_jit_count >= 0);
vm.current_jit_count += 1;
// Pre-ensure nursery space for BOTH GrowableArray backing arrays.
// Without this, the second allotUninitializedArray could trigger GC,
// moving the first array before it can be rooted (the struct is
// returned by value, so registerRoot() happens only after init).
// immediately after allocation; Zig can't do RAII, so we pre-reserve.
const array_size = layouts.alignCell(
layouts.arraySize(layouts.Array, 10),
layouts.data_alignment,
);
_ = vm.ensureNurserySpace(array_size * 2);
const parameters = growable.GrowableArray.init(vm, 10) orelse {
@panic("JIT.init: failed to allocate parameters growable array");
};
const literals = growable.GrowableArray.init(vm, 10) orelse {
@panic("JIT.init: failed to allocate literals growable array");
};
// NOTE: We do NOT register the owner as a GC root here because in Zig,
// returning Self by value copies the struct. The caller MUST call
// registerRoot() after the struct is in its final location.
return Self{
.vm = vm,
.owner = owner,
.code = .empty,
.relocation = .empty,
.parameters = parameters,
.literals = literals,
.label_manager = LabelManager.init(vm.allocator),
.computing_offset_p = false,
.position = 0,
.offset = 0,
};
}
/// Register the owner as a GC root. MUST be called after init() when the
/// struct is in its final location (not before return-by-value copy).
pub fn registerRoot(self: *Self) void {
self.vm.data_roots.appendAssumeCapacity(&self.owner);
self.vm.data_roots.appendAssumeCapacity(&self.literals.elements);
self.vm.data_roots.appendAssumeCapacity(&self.parameters.elements);
}
pub fn deinit(self: *Self) void {
// Must pop in strict reverse push order to preserve root-stack LIFO.
_ = self.vm.data_roots.pop();
_ = self.vm.data_roots.pop();
_ = self.vm.data_roots.pop();
self.code.deinit(self.vm.allocator);
self.relocation.deinit(self.vm.allocator);
self.label_manager.deinit();
std.debug.assert(self.vm.current_jit_count >= 1);
self.vm.current_jit_count -= 1;
}
// Get a template from special_objects by enum
fn getTemplate(self: *const Self, template: JitTemplate) ?*const layouts.Array {
const template_cell = self.vm.vm_asm.special_objects[@intFromEnum(template)];
return getArrayFromCell(template_cell);
}
// Get a template array from a cell value
fn getArrayFromCell(template_cell: Cell) ?*const layouts.Array {
if (template_cell == layouts.false_object) {
return null;
}
std.debug.assert(layouts.hasTag(template_cell, .array));
return @as(*const layouts.Array, @ptrFromInt(layouts.UNTAG(template_cell)));
}
// Emit a template by enum (append its relocation info and machine code)
pub fn emit(self: *Self, template: JitTemplate) !void {
var template_cell = self.vm.vm_asm.special_objects[@intFromEnum(template)];
self.vm.data_roots.appendAssumeCapacity(&template_cell);
defer _ = self.vm.data_roots.pop();
if (getArrayFromCell(template_cell) == null) return;
try self.emitTemplateCell(template_cell);
}
// Emit a raw template array (2-element: {reloc, code})
pub fn emitRaw(self: *Self, template_cell: Cell) !void {
try self.emitTemplateCell(template_cell);
}
// Emit a template cell (2-element array: { relocation-info, machine-code })
fn emitTemplateCell(self: *Self, template_cell_: Cell) !void {
var template_cell = template_cell_;
self.vm.data_roots.appendAssumeCapacity(&template_cell);
defer _ = self.vm.data_roots.pop();
const tmpl = getArrayFromCell(template_cell) orelse return;
if (layouts.untagFixnumUnsigned(tmpl.capacity) < 2) return;
const data = tmpl.data();
// Emit relocation info
try self.emitRelocation(data[0]);
// Re-derive template after relocation in case GC moved it
const tmpl_after = getArrayFromCell(template_cell) orelse return;
if (layouts.untagFixnumUnsigned(tmpl_after.capacity) < 2) return;
const data_after = tmpl_after.data();
const code_cell = data_after[1];
if (self.computing_offset_p) {
if (code_cell != layouts.false_object and
layouts.hasTag(code_cell, .byte_array))
{
const ba: *const layouts.ByteArray = @ptrFromInt(layouts.UNTAG(code_cell));
const size = layouts.untagFixnumUnsigned(ba.capacity);
if (self.offset == 0) {
self.position -= 1;
self.computing_offset_p = false;
} else if (self.offset < size) {
self.position += 1;
self.computing_offset_p = false;
} else {
self.offset -= size;
}
}
}
// Emit machine code
try self.emitCode(code_cell);
}
pub fn emitWithLiteral(self: *Self, template: JitTemplate, lit: Cell) !void {
var lit_copy = lit;
self.vm.data_roots.appendAssumeCapacity(&lit_copy);
defer _ = self.vm.data_roots.pop();
try self.literal(lit_copy);
try self.emit(template);
}
pub fn emitWithParameter(self: *Self, template: JitTemplate, param: Cell) !void {
var param_copy = param;
self.vm.data_roots.appendAssumeCapacity(¶m_copy);
defer _ = self.vm.data_roots.pop();
try self.parameter(param_copy);
try self.emit(template);
}
// Push a literal onto the data stack (emits code to push at runtime)
pub fn push(self: *Self, value: Cell) !void {
try self.emitWithLiteral(.push_literal, value);
}
// Add a literal for relocation
pub fn literal(self: *Self, value: Cell) !void {
if (!self.literals.add(value)) {
return error.OutOfMemory;
}
}
// Add a parameter for relocation
pub fn parameter(self: *Self, value: Cell) !void {
if (!self.parameters.add(value)) {
return error.OutOfMemory;
}
}
// Append values from a Factor array to parameters
pub fn appendParameters(self: *Self, arr_cell: Cell) !void {
var root = arr_cell;
self.vm.data_roots.appendAssumeCapacity(&root);
defer _ = self.vm.data_roots.pop();
if (root == layouts.false_object) return;
std.debug.assert(layouts.hasTag(root, .array));
if (!self.parameters.append(root)) {
return error.OutOfMemory;
}
}
// Append values from a Factor array to literals
pub fn appendLiterals(self: *Self, arr_cell: Cell) !void {
var root = arr_cell;
self.vm.data_roots.appendAssumeCapacity(&root);
defer _ = self.vm.data_roots.pop();
if (root == layouts.false_object) return;
std.debug.assert(layouts.hasTag(root, .array));
if (!self.literals.append(root)) {
return error.OutOfMemory;
}
}
// Emit a subprimitive (word with subprimitive slot containing template)
// The subprimitive slot contains a 5-element array:
// [0] = parameters array
// [1] = literals array
// [2] = main code template
// [3] = call continuation (for non-tail calls)
// [4] = tail continuation (for tail calls)
// Returns true if this was a tail call (no further code needed)
pub fn emitSubprimitive(self: *Self, word_cell: Cell, tail_call_p: bool, stack_frame_p: bool) !bool {
var word_root = word_cell;
self.vm.data_roots.appendAssumeCapacity(&word_root);
defer _ = self.vm.data_roots.pop();
std.debug.assert(layouts.hasTag(word_root, .word));
const word: *const layouts.Word = @ptrFromInt(layouts.UNTAG(word_root));
var subprim_root = word.subprimitive;
self.vm.data_roots.appendAssumeCapacity(&subprim_root);
defer _ = self.vm.data_roots.pop();
if (subprim_root == layouts.false_object) return false;
std.debug.assert(layouts.hasTag(subprim_root, .array));
const code_template: *const layouts.Array = @ptrFromInt(layouts.UNTAG(subprim_root));
const cap = layouts.untagFixnumUnsigned(code_template.capacity);
if (cap < 3) {
return false;
}
// Append parameters from template[0]
{
const tmpl: *const layouts.Array = @ptrFromInt(layouts.UNTAG(subprim_root));
const data = tmpl.data();
if (data[0] != layouts.false_object and
layouts.hasTag(data[0], .array))
{
try self.appendParameters(data[0]);
}
}
// Append literals from template[1]
{
const tmpl: *const layouts.Array = @ptrFromInt(layouts.UNTAG(subprim_root));
const data = tmpl.data();
if (data[1] != layouts.false_object and
layouts.hasTag(data[1], .array))
{
try self.appendLiterals(data[1]);
}
}
// Emit main code from template[2]
{
const tmpl: *const layouts.Array = @ptrFromInt(layouts.UNTAG(subprim_root));
const data = tmpl.data();
try self.emitRaw(data[2]);
}
// If template has 5 elements, emit continuation code
if (cap == 5) {
if (tail_call_p) {
// Emit epilog before tail continuation if stack frame exists
if (stack_frame_p) {
try self.emit(.epilog);
}
// Emit tail continuation from template[4]
const tmpl: *const layouts.Array = @ptrFromInt(layouts.UNTAG(subprim_root));
const data = tmpl.data();
try self.emitRaw(data[4]);
return true;
} else {
// Emit call continuation from template[3]
const tmpl: *const layouts.Array = @ptrFromInt(layouts.UNTAG(subprim_root));
const data = tmpl.data();
try self.emitRaw(data[3]);
}
}
return false;
}
// Emit relocation entries
fn emitRelocation(self: *Self, reloc_cell: Cell) !void {
// No GC root needed: appendSlice uses system allocator, not Factor heap
if (reloc_cell == layouts.false_object) return;
std.debug.assert(layouts.hasTag(reloc_cell, .byte_array));
const ba: *const layouts.ByteArray = @ptrFromInt(layouts.UNTAG(reloc_cell));
const reloc_data = ba.data();
const reloc_size = layouts.untagFixnumUnsigned(ba.capacity);
// Each relocation entry is 4 bytes
const entry_count = reloc_size / @sizeOf(code_blocks.RelocationEntry);
const current_offset = self.code.items.len;
// Adjust relocation offsets and append
for (0..entry_count) |i| {
const entry_bytes = reloc_data[i * 4 .. (i + 1) * 4];
var entry: code_blocks.RelocationEntry = @bitCast(entry_bytes[0..4].*);
// Adjust offset to account for code already emitted
const new_offset = entry.getOffset() + @as(u24, @intCast(current_offset));
entry = code_blocks.RelocationEntry.init(
entry.getType(),
entry.getClass(),
new_offset,
);
const entry_u32: u32 = @bitCast(entry);
try self.relocation.appendSlice(self.vm.allocator, std.mem.asBytes(&entry_u32));
}
}
// Emit machine code
fn emitCode(self: *Self, code_cell: Cell) !void {
// No GC root needed: appendSlice uses system allocator, not Factor heap
if (code_cell == layouts.false_object) return;
std.debug.assert(layouts.hasTag(code_cell, .byte_array));
const ba: *const layouts.ByteArray = @ptrFromInt(layouts.UNTAG(code_cell));
const code_data = ba.data();
const code_size = layouts.untagFixnumUnsigned(ba.capacity);
try self.code.appendSlice(self.vm.allocator, code_data[0..code_size]);
}
pub fn codeSize(self: *const Self) usize {
return self.code.items.len;
}
// Set position for source mapping
pub fn setPosition(self: *Self, pos: i64) void {
if (self.computing_offset_p) {
self.position = pos;
}
}
// Get current position
pub fn getPosition(self: *const Self) i64 {
return self.position;
}
// Compute position from code offset (for debugging)
pub fn computePosition(self: *Self, offset_: u64) void {
self.computing_offset_p = true;
self.position = 0;
self.offset = offset_;
}
// =============================================================================
// Label manipulation methods
// =============================================================================
pub fn makeLabel(self: *Self) !usize {
return try self.label_manager.makeLabel();
}
pub fn defineLabel(self: *Self, label_id: usize) !void {
const current_pos = self.code.items.len;
try self.label_manager.defineLabel(label_id, current_pos);
}
// Emit a jump to a label (forward or backward)
pub fn emitJumpToLabel(self: *Self, label_id: usize, rel_class: code_blocks.RelocationClass) !void {
const current_pos = self.code.items.len;
if (self.label_manager.isLabelDefined(label_id)) {
// Backward jump - label is already defined
const target_pos = self.label_manager.getLabelPosition(label_id) orelse return error.UndefinedLabel;
try self.emitJumpDirect(target_pos);
} else {
const patch_offset = current_pos;
try self.emitJumpPlaceholder();
try self.label_manager.addForwardRef(label_id, patch_offset, rel_class);
}
}
// Emit a call to a label (forward or backward)
pub fn emitCallToLabel(self: *Self, label_id: usize, rel_class: code_blocks.RelocationClass) !void {
const current_pos = self.code.items.len;
if (self.label_manager.isLabelDefined(label_id)) {
// Backward call - label is already defined
const target_pos = self.label_manager.getLabelPosition(label_id) orelse return error.UndefinedLabel;
try self.emitCallDirect(target_pos);
} else {
const patch_offset = current_pos;
try self.emitCallPlaceholder();
try self.label_manager.addForwardRef(label_id, patch_offset, rel_class);
}
}
fn emitJumpDirect(self: *Self, target_pos: usize) !void {
const current_pos = self.code.items.len;
const arch = cpu.Arch.current();
switch (arch) {
.x86_64 => {
const insn_end = current_pos + 5; // JMP is 5 bytes
const rel_offset: i32 = @intCast(@as(i64, @intCast(target_pos)) - @as(i64, @intCast(insn_end)));
try cpu.X86Instruction.encodeJump(self.vm.allocator, &self.code, rel_offset);
},
.aarch64 => {
const offset_in_bytes: i32 = @intCast(@as(i64, @intCast(target_pos)) - @as(i64, @intCast(current_pos)));
try cpu.ARM64Instruction.encodeJump(self.vm.allocator, &self.code, offset_in_bytes);
},
.unsupported => return error.UnsupportedArchitecture,
}
}
fn emitCallDirect(self: *Self, target_pos: usize) !void {
const current_pos = self.code.items.len;
const arch = cpu.Arch.current();
switch (arch) {
.x86_64 => {
const insn_end = current_pos + 5; // CALL is 5 bytes
const rel_offset: i32 = @intCast(@as(i64, @intCast(target_pos)) - @as(i64, @intCast(insn_end)));
try cpu.X86Instruction.encodeCall(self.vm.allocator, &self.code, rel_offset);
},
.aarch64 => {
const offset_in_bytes: i32 = @intCast(@as(i64, @intCast(target_pos)) - @as(i64, @intCast(current_pos)));
try cpu.ARM64Instruction.encodeCall(self.vm.allocator, &self.code, offset_in_bytes);
},
.unsupported => return error.UnsupportedArchitecture,
}
}
fn emitJumpPlaceholder(self: *Self) !void {
const arch = cpu.Arch.current();
switch (arch) {
.x86_64 => {
// JMP rel32: E9 [4-byte offset]
try self.code.append(self.vm.allocator, cpu.X86Instruction.JMP_OPCODE);
try self.code.appendSlice(self.vm.allocator, &[_]u8{ 0, 0, 0, 0 });
},
.aarch64 => {
// B #0 (branch to self, will be patched)
const insn: u32 = (0b0 << 31) | (0b00101 << 26) | 0; // B with offset 0
var bytes: [4]u8 = undefined;
std.mem.writeInt(u32, &bytes, insn, .little);
try self.code.appendSlice(self.vm.allocator, &bytes);
},
.unsupported => return error.UnsupportedArchitecture,
}
}
fn emitCallPlaceholder(self: *Self) !void {
const arch = cpu.Arch.current();
switch (arch) {
.x86_64 => {
// CALL rel32: E8 [4-byte offset]
try self.code.append(self.vm.allocator, cpu.X86Instruction.CALL_OPCODE);
try self.code.appendSlice(self.vm.allocator, &[_]u8{ 0, 0, 0, 0 });
},
.aarch64 => {
// BL #0 (branch with link to self, will be patched)
const insn: u32 = (0b1 << 31) | (0b00101 << 26) | 0; // BL with offset 0
var bytes: [4]u8 = undefined;
std.mem.writeInt(u32, &bytes, insn, .little);
try self.code.appendSlice(self.vm.allocator, &bytes);
},
.unsupported => return error.UnsupportedArchitecture,
}
}
pub fn fixupLabels(self: *Self) !std.ArrayList(Cell) {
return try self.label_manager.fixupLabels(self.code.items);
}
// Compile to a code block
// frame_size: Stack frame size (must be multiple of 16, max 0xFF0)
pub fn toCodeBlock(self: *Self, block_type: code_blocks.CodeBlockType, frame_size: Cell) !?*code_blocks.CodeBlock {
// Add GC info padding (dummy for non-optimizing compiler)
const alignment = layouts.data_alignment;
const padding = layouts.alignCell(self.code.items.len + 4, alignment) - self.code.items.len - 4;
for (0..padding) |_| {
try self.code.append(self.vm.allocator, 0);
}
// Append dummy GC info (4 bytes of zeros)
try self.code.appendSlice(self.vm.allocator, &[_]u8{ 0, 0, 0, 0 });
if (!self.parameters.trim()) @panic("OOM trimming parameters");
if (!self.literals.trim()) @panic("OOM trimming literals");
// Calculate total size needed
const header_size = @sizeOf(code_blocks.CodeBlock);
const code_size = self.code.items.len;
const total_size = layouts.alignCell(header_size + code_size, alignment);
var jit_scope = jit_protect.Scope.init();
defer jit_scope.deinit();
// Allocate from code heap, triggering compaction if full
const block = self.vm.allotCodeBlock(total_size);
// Initialize the code block header
block.initialize(block_type, total_size, frame_size);
block.owner = self.owner;
// validateFreeList checkpoints removed (root cause: non-contiguous heap fixed)
// CRITICAL: Allocate all nursery objects FIRST, rooting them to protect from GC.
// Then store them into the code block only after all allocations are complete.
// This prevents stale pointers if GC moves objects during allocation.
// Allocate relocation byte array (rooted)
var reloc_cell: Cell = layouts.false_object;
if (self.relocation.items.len > 0) {
reloc_cell = self.vm.allotUninitializedByteArray(self.relocation.items.len);
if (reloc_cell == layouts.false_object) @panic("OOM allocating relocation byte array");
const reloc_ba: *layouts.ByteArray = @ptrFromInt(layouts.UNTAG(reloc_cell));
@memcpy(reloc_ba.data()[0..self.relocation.items.len], self.relocation.items);
}
// Root reloc_cell to protect from GC during subsequent allocations
self.vm.data_roots.appendAssumeCapacity(&reloc_cell);
defer _ = self.vm.data_roots.pop();
const params_cell = self.parameters.toArray();
const literals_cell = self.literals.toArray();
// NOW store into code block - all allocations complete, values are final
block.relocation = reloc_cell;
block.parameters = params_cell;
// Copy machine code
const code_dest = block.codeStart();
@memcpy(code_dest[0..code_size], self.code.items);
// The caller (jitCompileQuotationWithOwner, inline cache, etc.) decides whether
// to initialize immediately (relocate=true) or defer to updateCodeHeapWords.
if (self.vm.code) |ch| {
ch.putUninitializedBlock(self.vm.allocator, @intFromPtr(block), literals_cell) catch {
// Fallback: initialize immediately if map insertion fails
self.vm.initializeCodeBlock(@ptrCast(block), literals_cell);
};
} else {
self.vm.initializeCodeBlock(@ptrCast(block), literals_cell);
}
return block;
}
};
// Stack frame size constants
// Must match cpu-{x86.64,arm.64}.hpp. arm64 frames differ from x86-64.
pub const JIT_FRAME_SIZE: Cell = if (builtin.cpu.arch == .aarch64) 16 else 32;
pub const SIGNAL_HANDLER_STACK_FRAME_SIZE: Cell = if (builtin.cpu.arch == .aarch64) 288 else 192;
// Quotation-specific JIT compiler
// This implements the non-optimizing compiler that compiles quotations by
// concatenating pre-assembled machine code chunks from subprimitive templates.
pub const QuotationJit = struct {
jit: Jit,
elements: Cell, // Tagged array
compiling: bool,
relocate: bool,
const Self = @This();
pub fn init(vm: *FactorVM, owner: Cell, compiling: bool, relocate: bool) Self {
// NOTE: jit.registerRoot() is NOT called here because this struct
// will be returned by value (copied). The caller MUST call registerRoot()
// after this struct is in its final location.
return Self{
.jit = Jit.init(vm, owner),
.elements = layouts.false_object,
.compiling = compiling,
.relocate = relocate,
};
}
/// Register the owner as a GC root. MUST be called after init() when the
/// struct is in its final location.
pub fn registerRoot(self: *Self) void {
// 4 roots: owner, literals.elements, parameters.elements, elements.
// Capacity is guaranteed by emitQuotation's ensureUnusedCapacity(8).
self.jit.vm.data_roots.appendAssumeCapacity(&self.jit.owner);
self.jit.vm.data_roots.appendAssumeCapacity(&self.jit.literals.elements);
self.jit.vm.data_roots.appendAssumeCapacity(&self.jit.parameters.elements);
self.jit.vm.data_roots.appendAssumeCapacity(&self.elements);
}
pub fn deinit(self: *Self) void {
_ = self.jit.vm.data_roots.pop();
self.jit.deinit();
}
// Initialize with quotation's array
pub fn initQuotation(self: *Self, quot_cell: Cell) void {
std.debug.assert(layouts.hasTag(quot_cell, .quotation));
const quot: *const layouts.Quotation = @ptrFromInt(layouts.UNTAG(quot_cell));
self.elements = quot.array;
}
// Get element at index from quotation array
fn nth(self: *const Self, index: Cell) Cell {
std.debug.assert(self.elements != layouts.false_object);
std.debug.assert(layouts.hasTag(self.elements, .array));
const arr: *const layouts.Array = @ptrFromInt(layouts.UNTAG(self.elements));
std.debug.assert(index < layouts.untagFixnumUnsigned(arr.capacity));
return arr.data()[index];
}
// Get array length
fn length(self: *const Self) Cell {
std.debug.assert(self.elements != layouts.false_object);
std.debug.assert(layouts.hasTag(self.elements, .array));
const arr: *const layouts.Array = @ptrFromInt(layouts.UNTAG(self.elements));
return layouts.untagFixnumUnsigned(arr.capacity);
}
// Check for fast-if pattern: [ true-quot ] [ false-quot ] if
fn isFastIf(self: *const Self, i: Cell, len: Cell) bool {
if (i + 3 != len) return false;
if (!layouts.hasTag(self.nth(i + 1), .quotation)) return false;
const if_word = self.jit.vm.vm_asm.special_objects[@intFromEnum(objects.SpecialObject.jit_if_word)];
return self.nth(i + 2) == if_word;
}
// Check for primitive call pattern: byte-array primitive
fn isPrimitiveCall(self: *const Self, i: Cell, len: Cell) bool {
const prim_word = self.jit.vm.vm_asm.special_objects[@intFromEnum(objects.SpecialObject.jit_primitive_word)];
return (i + 2) <= len and self.nth(i + 1) == prim_word;
}
// Check for dip pattern: [ quot ] dip
fn isFastDip(self: *const Self, i: Cell, len: Cell) bool {
const dip_word = self.jit.vm.vm_asm.special_objects[@intFromEnum(objects.SpecialObject.jit_dip_word)];
return (i + 2) <= len and self.nth(i + 1) == dip_word;
}
// Check for 2dip pattern: [ quot ] 2dip
fn isFast2Dip(self: *const Self, i: Cell, len: Cell) bool {
const dip2_word = self.jit.vm.vm_asm.special_objects[@intFromEnum(objects.SpecialObject.jit_2dip_word)];
return (i + 2) <= len and self.nth(i + 1) == dip2_word;
}
// Check for 3dip pattern: [ quot ] 3dip
fn isFast3Dip(self: *const Self, i: Cell, len: Cell) bool {
const dip3_word = self.jit.vm.vm_asm.special_objects[@intFromEnum(objects.SpecialObject.jit_3dip_word)];
return (i + 2) <= len and self.nth(i + 1) == dip3_word;
}
// Check for declare pattern: { decl } declare
fn isDeclare(self: *const Self, i: Cell, len: Cell) bool {
const declare_word = self.jit.vm.vm_asm.special_objects[@intFromEnum(objects.SpecialObject.jit_declare_word)];
return (i + 2) <= len and self.nth(i + 1) == declare_word;
}
// Check for mega lookup pattern: methods index cache mega-lookup
fn isMegaLookup(self: *const Self, i: Cell, len: Cell) bool {
if (i + 4 > len) return false;
if (!layouts.hasTag(self.nth(i + 1), .fixnum)) return false;
if (!layouts.hasTag(self.nth(i + 2), .array)) return false;
const mega_word = self.jit.vm.vm_asm.special_objects[@intFromEnum(objects.SpecialObject.mega_lookup_word)];
return self.nth(i + 3) == mega_word;
}
// Check if word is a special subprimitive (signal handlers, unwinders)
fn isSpecialSubprimitive(self: *const Self, obj: Cell) bool {
const signal_handler = self.jit.vm.vm_asm.special_objects[@intFromEnum(objects.SpecialObject.signal_handler_word)];
const leaf_signal = self.jit.vm.vm_asm.special_objects[@intFromEnum(objects.SpecialObject.leaf_signal_handler_word)];
const unwind = self.jit.vm.vm_asm.special_objects[@intFromEnum(objects.SpecialObject.unwind_native_frames_word)];
return obj == signal_handler or obj == leaf_signal or obj == unwind;
}
// Check if quotation needs a stack frame
// All quotations want a stack frame, except if they contain:
// 1) calls to the special subprimitives
// 2) mega cache lookups
fn hasStackFrame(self: *const Self) bool {
const len = self.length();
for (0..len) |i| {
const obj = self.nth(i);
const tag = layouts.typeTag(obj);
if (tag == .word and self.isSpecialSubprimitive(obj)) {
return false;
}
if (tag == .array and self.isMegaLookup(i, len)) {
return false;
}
}
return true;
}
// Emit epilog if needed
fn emitEpilog(self: *Self, needed: bool) !void {
if (needed) {
try self.jit.emit(.safepoint);
try self.jit.emit(.epilog);
}
}
// Emit a quotation reference (compile if needed)
fn emitQuotation(self: *Self, quot_cell: Cell) !void {
std.debug.assert(layouts.hasTag(quot_cell, .quotation));
// Each recursion level (emitQuotation → jitCompileQuotation →
// jitCompileQuotationWithOwner → registerRoot) pushes 8 data roots.
// Ensure capacity so the appendAssumeCapacity calls below and in the
// recursive compilation path don't overflow.
self.jit.vm.data_roots.ensureUnusedCapacity(self.jit.vm.allocator, 8) catch
self.jit.vm.memoryError();
// CRITICAL: Root the quotation before any operation that can trigger GC.
// jitCompileQuotation (called below) can trigger nursery GC, moving
// this quotation. Without rooting, the stale quot_cell would be
// embedded as a literal in the parent code block, causing crashes
// when the compiled code later dereferences it.
var rooted_quot = quot_cell;
self.jit.vm.data_roots.appendAssumeCapacity(&rooted_quot);
defer _ = self.jit.vm.data_roots.pop();
const quot: *const layouts.Quotation = @ptrFromInt(layouts.UNTAG(rooted_quot));
if (quot.array == layouts.false_object) {
try self.jit.literal(rooted_quot);
return;
}
const arr: *const layouts.Array = @ptrFromInt(layouts.UNTAG(quot.array));
if (layouts.untagFixnumUnsigned(arr.capacity) == 1) {
const first = arr.data()[0];
if (layouts.hasTag(first, .word)) {
try self.jit.literal(first);
return;
}
}
if (self.compiling) {
self.jit.vm.jitCompileQuotation(rooted_quot, self.relocate);
}
try self.jit.literal(rooted_quot);
}
// Main iteration over quotation elements
pub fn iterateQuotation(self: *Self) !void {
const stack_frame = self.hasStackFrame();
self.jit.setPosition(0);
// Emit prolog if needed