-
Notifications
You must be signed in to change notification settings - Fork 159
Expand file tree
/
Copy pathjit_aarch64.erl
More file actions
3151 lines (3031 loc) · 118 KB
/
Copy pathjit_aarch64.erl
File metadata and controls
3151 lines (3031 loc) · 118 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
%
% This file is part of AtomVM.
%
% Copyright 2025 Paul Guyot <pguyot@kallisys.net>
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
%
% SPDX-License-Identifier: Apache-2.0 OR LGPL-2.1-or-later
%
-module(jit_aarch64).
-export([
word_size/0,
new/3,
stream/1,
offset/1,
flush/1,
debugger/1,
used_regs/1,
available_regs/1,
free_native_registers/2,
assert_all_native_free/1,
jump_table/2,
update_branches/1,
call_primitive/3,
call_primitive_last/3,
call_primitive_with_cp/3,
return_if_not_equal_to_ctx/2,
jump_to_label/2,
jump_to_continuation/2,
jump_to_offset/2,
if_block/3,
if_else_block/4,
shift_right/3,
shift_left/3,
move_to_vm_register/3,
move_to_native_register/2,
move_to_native_register/3,
move_to_cp/2,
move_array_element/4,
move_to_array_element/4,
move_to_array_element/5,
set_bs/2,
copy_to_native_register/2,
get_array_element/3,
increment_sp/2,
set_continuation_to_label/2,
set_continuation_to_offset/1,
continuation_entry_point/1,
get_module_index/1,
and_/3,
or_/3,
add/3,
sub/3,
mul/3,
div_/3,
rem_/3,
shift_right_arith/3,
decrement_reductions_and_maybe_schedule_next/1,
call_or_schedule_next/2,
call_only_or_schedule_next/2,
call_func_ptr/3,
return_labels_and_lines/2,
add_label/2,
add_label/3,
xor_/3
]).
-export([dwarf_x_reg_offset/0]).
-ifdef(JIT_DWARF).
-export([
dwarf_opcode/2,
dwarf_label/2,
dwarf_function/3,
dwarf_line/2,
dwarf_variables/2,
dwarf_ctx_register/0
]).
-endif.
-compile([warnings_as_errors]).
-include_lib("jit.hrl").
-include("primitives.hrl").
-ifdef(JIT_DWARF).
-include("jit_dwarf.hrl").
-endif.
%-define(ASSERT(Expr), true = Expr).
-define(ASSERT(_Expr), ok).
%% AArch64 ABI: r0-r7 are used for argument passing and return value.
%% r8 is the indirect result location register (platform-specific),
%% r9-r15 are caller-saved scratch registers (used by JIT),
%% r16-r17 are intra-procedure-call scratch registers,
%% r18 is platform register (reserved),
%% r19-r28 are callee-saved,
%% r29 is frame pointer, r30 is link register, r31 is stack pointer/zero.
%% d0-d7 are used for FP argument passing and return value.
%% d8-d15 are callee-saved FP registers.
%%
%% https://github.com/ARM-software/abi-aa/blob/main/aapcs64/aapcs64.rst
%%
%% Registers used by the JIT backend:
%% - Scratch GPRs: r9-r15
%% - Argument/return: r0-r7, d0-d7
%% - Stack pointer: r31 (sp)
%% - Frame pointer: r29
%% - Link register: r30
%% - Indirect result: r8
%%
%% Note: r18 is reserved for platform use and must not be used.
-type aarch64_register() ::
r0
| r1
| r2
| r3
| r4
| r5
| r6
| r7
| r8
| r9
| r10
| r11
| r12
| r13
| r14
| r15.
-define(IS_GPR(Reg),
(Reg =:= r0 orelse Reg =:= r1 orelse Reg =:= r2 orelse Reg =:= r3 orelse Reg =:= r4 orelse
Reg =:= r5 orelse Reg =:= r6 orelse Reg =:= r7 orelse Reg =:= r8 orelse Reg =:= r9 orelse
Reg =:= r10 orelse Reg =:= r11 orelse Reg =:= r12 orelse Reg =:= r13 orelse Reg =:= r14 orelse
Reg =:= r15)
).
-type stream() :: any().
-record(state, {
stream_module :: module(),
stream :: stream(),
offset :: non_neg_integer(),
branches :: #{integer() | reference() => [{non_neg_integer(), non_neg_integer()}]},
jump_table_start :: non_neg_integer(),
available_regs :: non_neg_integer(),
used_regs :: non_neg_integer(),
labels :: #{integer() | reference() => integer()},
variant :: non_neg_integer(),
regs :: jit_regs:regs()
}).
-type state() :: #state{}.
-type immediate() :: non_neg_integer().
-type vm_register() ::
{x_reg, non_neg_integer()} | {y_reg, non_neg_integer()} | {ptr, aarch64_register()}.
-type value() :: immediate() | vm_register() | aarch64_register() | {ptr, aarch64_register()}.
-type arg() :: ctx | jit_state | offset | value() | {free, value()} | {avm_int64_t, integer()}.
-type maybe_free_aarch64_register() ::
{free, aarch64_register()} | aarch64_register().
-type condition() ::
{aarch64_register(), '<', integer()}
| {maybe_free_aarch64_register(), '<', aarch64_register()}
| {integer(), '<', maybe_free_aarch64_register()}
| {maybe_free_aarch64_register(), '==', integer()}
| {maybe_free_aarch64_register(), '!=', aarch64_register() | integer()}
| {'(int)', maybe_free_aarch64_register(), '==', integer()}
| {'(int)', maybe_free_aarch64_register(), '!=', aarch64_register() | integer()}
| {'(bool)', maybe_free_aarch64_register(), '==', false}
| {'(bool)', maybe_free_aarch64_register(), '!=', false}
| {maybe_free_aarch64_register(), '&', non_neg_integer(), '!=', integer()}
| {{free, aarch64_register()}, '==', {free, aarch64_register()}}.
% ctx->e is 0x50
% ctx->x is 0x58
-define(WORD_SIZE, 8).
-define(CTX_REG, r0).
-define(JITSTATE_REG, r1).
-define(NATIVE_INTERFACE_REG, r2).
-define(Y_REGS, {?CTX_REG, 16#50}).
-define(X_REG(N), {?CTX_REG, 16#58 + (N * ?WORD_SIZE)}).
-define(CP, {?CTX_REG, 16#E0}).
-define(FP_REGS, {?CTX_REG, 16#E8}).
-define(FP_REG_OFFSET(State, F),
(F *
case (State)#state.variant band ?JIT_VARIANT_FLOAT32 of
0 -> 8;
_ -> 4
end)
).
-define(BS, {?CTX_REG, 16#F0}).
-define(BS_OFFSET, {?CTX_REG, 16#F8}).
-define(JITSTATE_MODULE, {?JITSTATE_REG, 0}).
-define(JITSTATE_CONTINUATION, {?JITSTATE_REG, 16#8}).
-define(JITSTATE_REDUCTIONCOUNT, {?JITSTATE_REG, 16#10}).
-define(PRIMITIVE(N), {?NATIVE_INTERFACE_REG, N * ?WORD_SIZE}).
-define(MODULE_INDEX(ModuleReg), {ModuleReg, 0}).
% aarch64 ABI specific
-define(LR_REG, r30).
-define(IP0_REG, r16).
-define(IS_SINT8_T(X), is_integer(X) andalso X >= -128 andalso X =< 127).
-define(IS_SINT32_T(X), is_integer(X) andalso X >= -16#80000000 andalso X < 16#80000000).
-define(IS_UINT8_T(X), is_integer(X) andalso X >= 0 andalso X =< 255).
-define(IS_UINT32_T(X), is_integer(X) andalso X >= 0 andalso X < 16#100000000).
-define(PARAMETER_REGS, [r0, r1, r2, r3, r4, r5]).
-define(REG_BIT_R0, (1 bsl 0)).
-define(REG_BIT_R1, (1 bsl 1)).
-define(REG_BIT_R2, (1 bsl 2)).
-define(REG_BIT_R3, (1 bsl 3)).
-define(REG_BIT_R4, (1 bsl 4)).
-define(REG_BIT_R5, (1 bsl 5)).
-define(REG_BIT_R6, (1 bsl 6)).
-define(REG_BIT_R7, (1 bsl 7)).
-define(REG_BIT_R8, (1 bsl 8)).
-define(REG_BIT_R9, (1 bsl 9)).
-define(REG_BIT_R10, (1 bsl 10)).
-define(REG_BIT_R11, (1 bsl 11)).
-define(REG_BIT_R12, (1 bsl 12)).
-define(REG_BIT_R13, (1 bsl 13)).
-define(REG_BIT_R14, (1 bsl 14)).
-define(REG_BIT_R15, (1 bsl 15)).
-define(REG_BIT_R16, (1 bsl 16)).
-define(REG_BIT_R17, (1 bsl 17)).
-define(AVAILABLE_REGS_MASK,
(?REG_BIT_R7 bor ?REG_BIT_R8 bor ?REG_BIT_R9 bor ?REG_BIT_R10 bor ?REG_BIT_R11 bor
?REG_BIT_R12 bor ?REG_BIT_R13 bor ?REG_BIT_R14 bor ?REG_BIT_R15 bor
?REG_BIT_R3 bor ?REG_BIT_R4 bor ?REG_BIT_R5 bor ?REG_BIT_R6)
).
-define(SCRATCH_REGS_MASK,
(?REG_BIT_R7 bor ?REG_BIT_R8 bor ?REG_BIT_R9 bor ?REG_BIT_R10 bor ?REG_BIT_R11 bor
?REG_BIT_R12 bor ?REG_BIT_R13 bor ?REG_BIT_R14 bor ?REG_BIT_R15 bor
?REG_BIT_R3 bor ?REG_BIT_R4 bor ?REG_BIT_R5 bor ?REG_BIT_R6 bor ?REG_BIT_R17)
).
-include("jit_backend_dwarf_impl.hrl").
%%-----------------------------------------------------------------------------
%% @doc Return the word size in bytes, i.e. the sizeof(term) i.e.
%% sizeof(uintptr_t)
%%
%% C code equivalent is:
%% #if UINTPTR_MAX == UINT32_MAX
%% #define TERM_BYTES 4
%% #elif UINTPTR_MAX == UINT64_MAX
%% #define TERM_BYTES 8
%% #else
%% #error "Term size must be either 32 bit or 64 bit."
%% #endif
%%
%% @end
%% @return Word size in bytes
%%-----------------------------------------------------------------------------
-spec word_size() -> 4 | 8.
word_size() -> ?WORD_SIZE.
%%-----------------------------------------------------------------------------
%% @doc Create a new backend state for provided variant, module and stream.
%% @end
%% @param Variant JIT variant to use (currently ?JIT_VARIANT_PIC)
%% @param StreamModule module to stream instructions
%% @param Stream stream state
%% @return New backend state
%%-----------------------------------------------------------------------------
-spec new(any(), module(), stream()) -> state().
new(Variant, StreamModule, Stream) ->
#state{
stream_module = StreamModule,
stream = Stream,
branches = #{},
jump_table_start = 0,
offset = StreamModule:offset(Stream),
available_regs = ?AVAILABLE_REGS_MASK,
used_regs = 0,
labels = #{},
variant = Variant,
regs = jit_regs:new()
}.
%%-----------------------------------------------------------------------------
%% @doc Access the stream object.
%% @end
%% @param State current backend state
%% @return The stream object
%%-----------------------------------------------------------------------------
-spec stream(state()) -> stream().
stream(#state{stream = Stream}) ->
Stream.
%%-----------------------------------------------------------------------------
%% @doc Get the current offset in the stream
%% @end
%% @param State current backend state
%% @return The current offset
%%-----------------------------------------------------------------------------
-spec offset(state()) -> non_neg_integer().
offset(#state{stream_module = StreamModule, stream = Stream}) ->
StreamModule:offset(Stream).
%%-----------------------------------------------------------------------------
%% @doc Flush the current state (unused on aarch64)
%% @end
%% @param State current backend state
%% @return The flushed state
%%-----------------------------------------------------------------------------
-spec flush(state()) -> state().
flush(#state{} = State) ->
State.
%%-----------------------------------------------------------------------------
%% @doc Emit a debugger of breakpoint instruction. This is used for debugging
%% and not in production.
%% @end
%% @param State current backend state
%% @return The updated backend state
%%-----------------------------------------------------------------------------
-spec debugger(state()) -> state().
debugger(#state{stream_module = StreamModule, stream = Stream0} = State) ->
Stream1 = StreamModule:append(Stream0, jit_aarch64_asm:brk(0)),
State#state{stream = Stream1}.
%%-----------------------------------------------------------------------------
%% @doc Return the list of currently used native registers. This is used for
%% debugging and not in production.
%% @end
%% @param State current backend state
%% @return The list of used registers
%%-----------------------------------------------------------------------------
-spec used_regs(state()) -> [aarch64_register()].
used_regs(#state{used_regs = Used}) -> mask_to_list(Used).
%%-----------------------------------------------------------------------------
%% @doc Return the list of currently available native scratch registers. This
%% is used for debugging and not in production.
%% @end
%% @param State current backend state
%% @return The list of available registers
%%-----------------------------------------------------------------------------
-spec available_regs(state()) -> [aarch64_register()].
available_regs(#state{available_regs = Available}) -> mask_to_list(Available).
%%-----------------------------------------------------------------------------
%% @doc Free native registers. The passed list of registers can contain
%% registers, pointer to registers or other values that are ignored.
%% @end
%% @param State current backend state
%% @param Regs list of registers or other values
%% @return The updated backend state
%%-----------------------------------------------------------------------------
-spec free_native_registers(state(), [value()]) -> state().
free_native_registers(State, []) ->
State;
free_native_registers(State, [Reg | Rest]) ->
State1 = free_native_register(State, Reg),
free_native_registers(State1, Rest).
-spec free_native_register(state(), value()) -> state().
free_native_register(
#state{available_regs = Available0, used_regs = Used0} = State,
Reg
) when
is_atom(Reg)
->
Bit = reg_bit(Reg),
State#state{
available_regs = Available0 bor Bit,
used_regs = Used0 band (bnot Bit)
};
free_native_register(State, {ptr, Reg}) ->
free_native_register(State, Reg);
free_native_register(State, _Other) ->
State.
%%-----------------------------------------------------------------------------
%% @doc Assert that all native scratch registers are available. This is used
%% for debugging and not in production.
%% @end
%% @param State current backend state
%% @return ok
%%-----------------------------------------------------------------------------
-spec assert_all_native_free(state()) -> ok.
assert_all_native_free(State) ->
0 = State#state.used_regs,
?AVAILABLE_REGS_MASK = State#state.available_regs,
ok.
%%-----------------------------------------------------------------------------
%% @doc Emit the jump table at the beginning of the module. Branches will be
%% updated afterwards with update_branches/2. Emit branches for labels from
%% 0 (special entry for lines and labels information) to LabelsCount included
%% (special entry for OP_INT_CALL_END).
%% @end
%% @param State current backend state
%% @param LabelsCount number of labels in the module.
%% @return Updated backend state
%%-----------------------------------------------------------------------------
-spec jump_table(state(), pos_integer()) -> state().
jump_table(#state{stream_module = StreamModule, stream = Stream0} = State, LabelsCount) ->
JumpTableStart = StreamModule:offset(Stream0),
jump_table0(State#state{jump_table_start = JumpTableStart}, 0, LabelsCount).
-spec jump_table0(state(), non_neg_integer(), pos_integer()) -> state().
jump_table0(State, N, LabelsCount) when N > LabelsCount ->
State;
jump_table0(
#state{stream_module = StreamModule, stream = Stream0} = State,
N,
LabelsCount
) ->
% Placeholder jumps to next entry
BranchInstr = jit_aarch64_asm:b(4),
Stream1 = StreamModule:append(Stream0, BranchInstr),
jump_table0(State#state{stream = Stream1}, N + 1, LabelsCount).
%%-----------------------------------------------------------------------------
%% @doc Patch a single branch in the stream
%% @end
%% @param StreamModule stream module
%% @param Stream stream state
%% @param Offset offset of the branch to patch
%% @param Type type of the branch
%% @param LabelOffset target label offset
%% @return Updated stream
%%-----------------------------------------------------------------------------
-spec patch_branch(module(), stream(), non_neg_integer(), any(), non_neg_integer()) -> stream().
patch_branch(StreamModule, Stream, Offset, Type, LabelOffset) ->
Rel = LabelOffset - Offset,
NewInstr =
case Type of
{bcc, CC} -> jit_aarch64_asm:bcc(CC, Rel);
{adr, Reg} -> jit_aarch64_asm:adr(Reg, Rel);
b -> jit_aarch64_asm:b(Rel)
end,
StreamModule:replace(Stream, Offset, NewInstr).
%%-----------------------------------------------------------------------------
%% @doc Patch all branches targeting a specific label and return remaining branches
%% @end
%% @param StreamModule stream module
%% @param Stream stream state
%% @param TargetLabel label to patch branches for
%% @param LabelOffset offset of the target label
%% @param Branches list of pending branches
%% @return {UpdatedStream, RemainingBranches}
%%-----------------------------------------------------------------------------
-spec patch_branches_for_label(
module(),
stream(),
integer() | reference(),
non_neg_integer(),
#{integer() | reference() => [{non_neg_integer(), non_neg_integer()}]}
) ->
{stream(), #{integer() | reference() => [{non_neg_integer(), non_neg_integer()}]}}.
patch_branches_for_label(StreamModule, Stream, TargetLabel, LabelOffset, Branches) ->
case Branches of
#{TargetLabel := BrList} ->
Stream1 = lists:foldl(
fun({Offset, Type}, AccStream) ->
patch_branch(StreamModule, AccStream, Offset, Type, LabelOffset)
end,
Stream,
BrList
),
{Stream1, maps:remove(TargetLabel, Branches)};
_ ->
{Stream, Branches}
end.
%%-----------------------------------------------------------------------------
%% @doc Rewrite stream to update all branches for labels.
%% @end
%% @param State current backend state
%% @return Updated backend state
%%-----------------------------------------------------------------------------
-spec update_branches(state()) -> state().
update_branches(
#state{
stream_module = StreamModule,
stream = Stream0,
branches = Branches,
labels = Labels
} = State
) ->
Stream1 = maps:fold(
fun(Label, BrList, AccStream) ->
#{Label := LabelOffset} = Labels,
lists:foldl(
fun({Offset, Type}, AccStream2) ->
patch_branch(StreamModule, AccStream2, Offset, Type, LabelOffset)
end,
AccStream,
BrList
)
end,
Stream0,
Branches
),
State#state{stream = Stream1, branches = #{}}.
%%-----------------------------------------------------------------------------
%% @doc Emit a call (call with return) to a primitive with arguments. This
%% function converts arguments and pass them following the backend ABI
%% convention. It also saves scratch registers we need to preserve.
%% @end
%% @param State current backend state
%% @param Primitive index to the primitive to call
%% @param Args arguments to pass to the primitive
%% @return Updated backend state
%%-----------------------------------------------------------------------------
-spec call_primitive(state(), non_neg_integer(), [arg()]) -> {state(), aarch64_register()}.
call_primitive(
#state{
stream_module = StreamModule,
stream = Stream0
} = State,
Primitive,
Args
) ->
PrepCall =
case Primitive of
0 ->
jit_aarch64_asm:ldr(?IP0_REG, {?NATIVE_INTERFACE_REG, 0});
N ->
jit_aarch64_asm:ldr(?IP0_REG, {?NATIVE_INTERFACE_REG, N * ?WORD_SIZE})
end,
Stream1 = StreamModule:append(Stream0, PrepCall),
StateCall = State#state{stream = Stream1},
call_func_ptr(StateCall, {free, ?IP0_REG}, Args).
%%-----------------------------------------------------------------------------
%% @doc Emit a jump (call without return) to a primitive with arguments. This
%% function converts arguments and pass them following the backend ABI
%% convention.
%% @end
%% @param State current backend state
%% @param Primitive index to the primitive to call
%% @param Args arguments to pass to the primitive
%% @return Updated backend state
%%-----------------------------------------------------------------------------
-spec call_primitive_last(state(), non_neg_integer(), [arg()]) -> state().
call_primitive_last(
#state{
stream_module = StreamModule,
stream = Stream0
} = State0,
Primitive,
Args
) ->
% We need a register for the function pointer that should not be used as a parameter
% Since we're not returning, we can use all scratch registers except
% registers used for parameters
ParamRegs = lists:sublist(?PARAMETER_REGS, length(Args)),
ArgsRegs = args_regs(Args),
ArgsMask = jit_regs:regs_to_mask(ArgsRegs, fun reg_bit/1),
ParamMask = jit_regs:regs_to_mask(ParamRegs, fun reg_bit/1),
ScratchMask = ?AVAILABLE_REGS_MASK band (bnot (ArgsMask bor ParamMask)),
Temp = first_avail(ScratchMask),
TempBit = reg_bit(Temp),
AvailableRegs1 = ScratchMask band (bnot TempBit),
UsedRegs = ?AVAILABLE_REGS_MASK band (bnot AvailableRegs1),
PrepCall =
case Primitive of
0 ->
jit_aarch64_asm:ldr(Temp, {?NATIVE_INTERFACE_REG, 0});
N ->
jit_aarch64_asm:ldr(Temp, {?NATIVE_INTERFACE_REG, N * ?WORD_SIZE})
end,
Stream1 = StreamModule:append(Stream0, PrepCall),
State1 = set_args(
State0#state{
stream = Stream1,
available_regs = AvailableRegs1,
used_regs = UsedRegs,
regs = jit_regs:invalidate_reg(State0#state.regs, Temp)
},
Args
),
#state{stream = Stream2} = State1,
Call = jit_aarch64_asm:br(Temp),
Stream3 = StreamModule:append(Stream2, Call),
State1#state{
stream = Stream3,
available_regs = ?AVAILABLE_REGS_MASK,
used_regs = 0,
regs = jit_regs:unreachable(State1#state.regs)
}.
%%-----------------------------------------------------------------------------
%% @doc Emit a return of a value if it's not equal to ctx.
%% This logic is used to break out to the scheduler, typically after signal
%% messages have been processed.
%% @end
%% @param State current backend state
%% @param Reg register to compare to (should be {free, Reg} as it's always freed)
%% @return Updated backend state
%%-----------------------------------------------------------------------------
-spec return_if_not_equal_to_ctx(state(), {free, aarch64_register()}) -> state().
return_if_not_equal_to_ctx(
#state{
stream_module = StreamModule,
stream = Stream0,
available_regs = AvailableRegs0,
used_regs = UsedRegs0
} = State,
{free, Reg}
) ->
I1 = jit_aarch64_asm:cmp(Reg, ?CTX_REG),
I3 =
case Reg of
% Return value is already in r0
r0 -> <<>>;
% Move to r0 (return register)
_ -> jit_aarch64_asm:orr(r0, xzr, Reg)
end,
I4 = jit_aarch64_asm:ret(),
I2 = jit_aarch64_asm:bcc(eq, 4 + byte_size(I3) + byte_size(I4)),
Stream1 = StreamModule:append(Stream0, <<I1/binary, I2/binary, I3/binary, I4/binary>>),
Bit = reg_bit(Reg),
AvailableRegs1 = AvailableRegs0 bor Bit,
UsedRegs1 = UsedRegs0 band (bnot Bit),
State#state{
stream = Stream1,
available_regs = AvailableRegs1,
used_regs = UsedRegs1
}.
%%-----------------------------------------------------------------------------
%% @doc Emit a jump to a label. The offset of the relocation is saved and will
%% be updated with `update_branches/2`.
%% @end
%% @param State current backend state
%% @param Label to jump to
%% @return Updated backend state
%%-----------------------------------------------------------------------------
-spec jump_to_label(state(), integer() | reference()) -> state().
jump_to_label(
#state{stream_module = StreamModule, stream = Stream0, branches = AccBranches, labels = Labels} =
State,
Label
) ->
Offset = StreamModule:offset(Stream0),
case Labels of
#{Label := LabelOffset} ->
% Label is already known, emit direct branch without relocation
Rel = LabelOffset - Offset,
I1 = jit_aarch64_asm:b(Rel),
Stream1 = StreamModule:append(Stream0, I1),
State#state{stream = Stream1, regs = jit_regs:unreachable(State#state.regs)};
_ ->
% Label not yet known, emit placeholder and add relocation
I1 = jit_aarch64_asm:b(0),
BrEntry = {Offset, b},
ExistingBrs = maps:get(Label, AccBranches, []),
Stream1 = StreamModule:append(Stream0, I1),
State#state{
stream = Stream1,
branches = AccBranches#{Label => [BrEntry | ExistingBrs]},
regs = jit_regs:unreachable(State#state.regs)
}
end.
jump_to_offset(#state{stream_module = StreamModule, stream = Stream0} = State, TargetOffset) ->
Offset = StreamModule:offset(Stream0),
Rel = TargetOffset - Offset,
I1 = jit_aarch64_asm:b(Rel),
Stream1 = StreamModule:append(Stream0, I1),
State#state{stream = Stream1, regs = jit_regs:unreachable(State#state.regs)}.
%%-----------------------------------------------------------------------------
%% @doc Jump to a continuation address stored in a register.
%% This is used for optimized intra-module returns.
%% @end
%% @param State current backend state
%% @param OffsetReg register containing the continuation offset
%% @return Updated backend state
%%-----------------------------------------------------------------------------
jump_to_continuation(
#state{
stream_module = StreamModule,
stream = Stream0,
offset = BaseOffset,
available_regs = Available
} = State,
{free, OffsetReg}
) ->
TempReg = first_avail(Available),
% Calculate absolute address: native_code_base + target_offset
% where native_code_base = current_pc + (BaseOffset - CurrentStreamOffset)
CurrentStreamOffset = StreamModule:offset(Stream0),
NetOffset = BaseOffset - CurrentStreamOffset,
% Get native code base address into temporary register
I1 = jit_aarch64_asm:adr(TempReg, NetOffset),
% Add target offset to get final absolute address
I2 = jit_aarch64_asm:add(TempReg, TempReg, OffsetReg),
% Indirect branch to the calculated absolute address
I3 = jit_aarch64_asm:br(TempReg),
Code = <<I1/binary, I2/binary, I3/binary>>,
Stream1 = StreamModule:append(Stream0, Code),
% Free all registers since this is a tail jump
State#state{
stream = Stream1,
available_regs = ?AVAILABLE_REGS_MASK,
used_regs = 0,
regs = jit_regs:unreachable(State#state.regs)
}.
%% @private
-spec rewrite_branch_instruction(
jit_aarch64_asm:cc() | {tbz | tbnz, atom(), 0..63} | {cbz, atom()}, integer()
) -> binary().
rewrite_branch_instruction({cbnz, Reg}, Offset) ->
jit_aarch64_asm:cbnz(Reg, Offset);
rewrite_branch_instruction({cbnz_w, Reg}, Offset) ->
jit_aarch64_asm:cbnz_w(Reg, Offset);
rewrite_branch_instruction({cbz, Reg}, Offset) ->
jit_aarch64_asm:cbz(Reg, Offset);
rewrite_branch_instruction({cbz_w, Reg}, Offset) ->
jit_aarch64_asm:cbz_w(Reg, Offset);
rewrite_branch_instruction({tbz, Reg, Bit}, Offset) ->
jit_aarch64_asm:tbz(Reg, Bit, Offset);
rewrite_branch_instruction({tbnz, Reg, Bit}, Offset) ->
jit_aarch64_asm:tbnz(Reg, Bit, Offset);
rewrite_branch_instruction(CC, Offset) when is_atom(CC) ->
jit_aarch64_asm:bcc(CC, Offset).
%%-----------------------------------------------------------------------------
%% @doc Emit an if block, i.e. emit a test of a condition and conditionnally
%% execute a block.
%% @end
%% @param State current backend state
%% @param Cond condition to test
%% @param BlockFn function to emit the block that may be executed
%% @return Updated backend state
%%-----------------------------------------------------------------------------
-spec if_block(state(), condition() | {'and', [condition()]}, fun((state()) -> state())) -> state().
if_block(
#state{stream_module = StreamModule} = State0,
{'and', CondList},
BlockFn
) ->
{Replacements, State1} = lists:foldl(
fun(Cond, {AccReplacements, AccState}) ->
Offset = StreamModule:offset(AccState#state.stream),
{NewAccState, CC, ReplaceDelta} = if_block_cond(AccState, Cond),
{[{Offset + ReplaceDelta, CC} | AccReplacements], NewAccState}
end,
{[], State0},
CondList
),
State2 = BlockFn(State1),
Stream2 = State2#state.stream,
OffsetAfter = StreamModule:offset(Stream2),
Stream3 = lists:foldl(
fun({ReplacementOffset, CC}, AccStream) ->
BranchOffset = OffsetAfter - ReplacementOffset,
NewBranchInstr = jit_aarch64_asm:bcc(CC, BranchOffset),
StreamModule:replace(AccStream, ReplacementOffset, NewBranchInstr)
end,
Stream2,
Replacements
),
State4 = merge_used_regs(State2#state{stream = Stream3}, State1#state.used_regs),
MergedRegs = jit_regs:merge(State1#state.regs, State2#state.regs),
State4#state{regs = MergedRegs};
if_block(
#state{stream_module = StreamModule, stream = Stream0} = State0,
Cond,
BlockFn
) ->
Offset = StreamModule:offset(Stream0),
{State1, CC, BranchInstrOffset} = if_block_cond(State0, Cond),
State2 = BlockFn(State1),
Stream2 = State2#state.stream,
OffsetAfter = StreamModule:offset(Stream2),
%% Patch the conditional branch instruction to jump to the end of the block
BranchOffset = OffsetAfter - (Offset + BranchInstrOffset),
NewBranchInstr = rewrite_branch_instruction(CC, BranchOffset),
Stream3 = StreamModule:replace(Stream2, Offset + BranchInstrOffset, NewBranchInstr),
State3 = merge_used_regs(State2#state{stream = Stream3}, State1#state.used_regs),
MergedRegs = jit_regs:merge(State1#state.regs, State2#state.regs),
State3#state{regs = MergedRegs}.
%%-----------------------------------------------------------------------------
%% @doc Emit an if else block, i.e. emit a test of a condition and
%% conditionnally execute a block or another block.
%% @end
%% @param State current backend state
%% @param Cond condition to test
%% @param BlockTrueFn function to emit the block that is executed if condition is true
%% @param BlockFalseFn function to emit the block that is executed if condition is false
%% @return Updated backend state
%%-----------------------------------------------------------------------------
-spec if_else_block(state(), condition(), fun((state()) -> state()), fun((state()) -> state())) ->
state().
if_else_block(
#state{stream_module = StreamModule, stream = Stream0} = State0,
Cond,
BlockTrueFn,
BlockFalseFn
) ->
Offset = StreamModule:offset(Stream0),
{State1, CC, BranchInstrOffset} = if_block_cond(State0, Cond),
State2 = BlockTrueFn(State1),
Stream2 = State2#state.stream,
%% Emit unconditional branch to skip the else block (will be replaced)
ElseJumpOffset = StreamModule:offset(Stream2),
ElseJumpInstr = jit_aarch64_asm:b(0),
Stream3 = StreamModule:append(Stream2, ElseJumpInstr),
%% Else block starts here.
OffsetAfter = StreamModule:offset(Stream3),
%% Patch the conditional branch to jump to the else block
ElseBranchOffset = OffsetAfter - (Offset + BranchInstrOffset),
NewBranchInstr = rewrite_branch_instruction(CC, ElseBranchOffset),
Stream4 = StreamModule:replace(Stream3, Offset + BranchInstrOffset, NewBranchInstr),
%% Build the else block
StateElse = State2#state{
stream = Stream4,
used_regs = State1#state.used_regs,
available_regs = State1#state.available_regs,
regs = State1#state.regs
},
State3 = BlockFalseFn(StateElse),
Stream5 = State3#state.stream,
OffsetFinal = StreamModule:offset(Stream5),
%% Patch the unconditional branch to jump to the end
FinalJumpOffset = OffsetFinal - ElseJumpOffset,
NewElseJumpInstr = jit_aarch64_asm:b(FinalJumpOffset),
Stream6 = StreamModule:replace(Stream5, ElseJumpOffset, NewElseJumpInstr),
State4 = merge_used_regs(State3#state{stream = Stream6}, State2#state.used_regs),
MergedRegs = jit_regs:merge(State2#state.regs, State3#state.regs),
State4#state{regs = MergedRegs}.
%% @private
-spec if_block_cond(state(), condition()) ->
{
state(),
jit_aarch64_asm:cc() | {tbz | tbnz, atom(), 0..63} | {cbz, atom()},
non_neg_integer()
}.
if_block_cond(
#state{stream_module = StreamModule, stream = Stream0} = State0, {RegOrTuple, '<', 0}
) ->
Reg =
case RegOrTuple of
{free, Reg0} -> Reg0;
RegOrTuple -> RegOrTuple
end,
I = jit_aarch64_asm:tbz(Reg, 63, 0),
Stream1 = StreamModule:append(Stream0, I),
State1 = if_block_free_reg(RegOrTuple, State0),
State2 = State1#state{stream = Stream1},
{State2, {tbz, Reg, 63}, 0};
% Handle {Val, '<', Reg} - means Val < Reg, jump if false (i.e., if Val >= Reg or Reg <= Val)
if_block_cond(
#state{stream_module = StreamModule, stream = Stream0} = State0,
{Val, '<', RegOrTuple}
) when is_integer(Val) ->
Reg =
case RegOrTuple of
{free, Reg0} -> Reg0;
RegOrTuple -> RegOrTuple
end,
I1 = jit_aarch64_asm:cmp(Reg, Val),
% le = less than or equal
I2 = jit_aarch64_asm:bcc(le, 0),
Code = <<
I1/binary,
I2/binary
>>,
Stream1 = StreamModule:append(Stream0, Code),
State1 = if_block_free_reg(RegOrTuple, State0),
State2 = State1#state{stream = Stream1},
{State2, le, byte_size(I1)};
if_block_cond(
#state{stream_module = StreamModule, stream = Stream0} = State0,
{RegOrTuple, '<', Val}
) when is_integer(Val), Val =/= 0 ->
Reg =
case RegOrTuple of
{free, Reg0} -> Reg0;
RegOrTuple -> RegOrTuple
end,
I1 = jit_aarch64_asm:cmp(Reg, Val),
% ge = greater than or equal
I2 = jit_aarch64_asm:bcc(ge, 0),
Code = <<
I1/binary,
I2/binary
>>,
Stream1 = StreamModule:append(Stream0, Code),
State1 = if_block_free_reg(RegOrTuple, State0),
State2 = State1#state{stream = Stream1},
{State2, ge, byte_size(I1)};
if_block_cond(
#state{stream_module = StreamModule, stream = Stream0} = State0,
{RegOrTuple, '<', RegB}
) when is_atom(RegB) ->
Reg =
case RegOrTuple of
{free, Reg0} -> Reg0;
RegOrTuple -> RegOrTuple
end,
I1 = jit_aarch64_asm:cmp(Reg, RegB),
% ge = greater than or equal
I2 = jit_aarch64_asm:bcc(ge, 0),
Code = <<
I1/binary,
I2/binary
>>,
Stream1 = StreamModule:append(Stream0, Code),
State1 = if_block_free_reg(RegOrTuple, State0),
State2 = State1#state{stream = Stream1},
{State2, ge, byte_size(I1)};
if_block_cond(
#state{stream_module = StreamModule, stream = Stream0} = State0, {RegOrTuple, '==', 0}
) ->
Reg =
case RegOrTuple of
{free, Reg0} -> Reg0;
RegOrTuple -> RegOrTuple
end,
I = jit_aarch64_asm:cbnz(Reg, 0),
Stream1 = StreamModule:append(Stream0, I),
State1 = if_block_free_reg(RegOrTuple, State0),
State2 = State1#state{stream = Stream1},
{State2, {cbnz, Reg}, 0};
if_block_cond(
#state{stream_module = StreamModule, stream = Stream0} = State0, {'(int)', RegOrTuple, '==', 0}
) ->
Reg =
case RegOrTuple of
{free, Reg0} -> Reg0;
RegOrTuple -> RegOrTuple
end,
I = jit_aarch64_asm:cbnz_w(Reg, 0),
Stream1 = StreamModule:append(Stream0, I),
State1 = if_block_free_reg(RegOrTuple, State0),
State2 = State1#state{stream = Stream1},
{State2, {cbnz_w, Reg}, 0};
if_block_cond(
#state{stream_module = StreamModule, stream = Stream0} = State0,
{'(int)', RegOrTuple, '==', Val}
) when is_integer(Val) ->
Reg =
case RegOrTuple of
{free, Reg0} -> Reg0;
RegOrTuple -> RegOrTuple
end,
I1 = jit_aarch64_asm:cmp_w(Reg, Val),
I2 = jit_aarch64_asm:bcc(ne, 0),
Code = <<
I1/binary,
I2/binary
>>,
Stream1 = StreamModule:append(Stream0, Code),
State1 = if_block_free_reg(RegOrTuple, State0),
State2 = State1#state{stream = Stream1},
{State2, ne, byte_size(I1)};
if_block_cond(
#state{stream_module = StreamModule, stream = Stream0} = State0,
{RegOrTuple, '!=', 0}
) ->
Reg =
case RegOrTuple of
{free, Reg0} -> Reg0;
RegOrTuple -> RegOrTuple
end,
I = jit_aarch64_asm:cbz(Reg, 0),
Stream1 = StreamModule:append(Stream0, I),
State1 = if_block_free_reg(RegOrTuple, State0),
State2 = State1#state{stream = Stream1},
{State2, {cbz, Reg}, 0};
if_block_cond(
#state{stream_module = StreamModule, stream = Stream0} = State0,
{RegOrTuple, '!=', Val}
) when is_integer(Val) orelse ?IS_GPR(Val) ->
Reg =