1 #include "sljitLir.h"
2
3 #include <stdio.h>
4 #include <stdlib.h>
5
6 typedef long SLJIT_CALL (*func_arr_t)(long *arr, long narr);
7
print_num(long a)8 static long SLJIT_CALL print_num(long a)
9 {
10 printf("num = %ld\n", a);
11 return a + 1;
12 }
13
14 /*
15 This example, we generate a function like this:
16
17 long func(long *array, long narray)
18 {
19 long i;
20 for (i = 0; i < narray; ++i)
21 print_num(array[i]);
22 return narray;
23 }
24
25 */
26
array_access(long * arr,long narr)27 static int array_access(long *arr, long narr)
28 {
29 void *code;
30 unsigned long len;
31 func_arr_t func;
32
33 /* Create a SLJIT compiler */
34 struct sljit_compiler *C = sljit_create_compiler();
35
36 sljit_emit_enter(C, 0, 2, 1, 3, 0, 0, 0);
37 /* opt arg R S FR FS local_size */
38 sljit_emit_op2(C, SLJIT_XOR, SLJIT_S2, 0, SLJIT_S2, 0, SLJIT_S2, 0); // S2 = 0
39 struct sljit_label *loopstart = sljit_emit_label(C); // loopstart:
40 struct sljit_jump *out = sljit_emit_cmp(C, SLJIT_GREATER_EQUAL, SLJIT_S2, 0, SLJIT_S1, 0); // S2 >= a --> jump out
41
42 sljit_emit_op1(C, SLJIT_MOV, SLJIT_R0, 0, SLJIT_MEM2(SLJIT_S0, SLJIT_S2), SLJIT_WORD_SHIFT);// R0 = (long *)S0[S2];
43 sljit_emit_ijump(C, SLJIT_CALL1, SLJIT_IMM, SLJIT_FUNC_OFFSET(print_num)); // print_num(R0);
44
45 sljit_emit_op2(C, SLJIT_ADD, SLJIT_S2, 0, SLJIT_S2, 0, SLJIT_IMM, 1); // S2 += 1
46 sljit_set_label(sljit_emit_jump(C, SLJIT_JUMP), loopstart); // jump loopstart
47 sljit_set_label(out, sljit_emit_label(C)); // out:
48 sljit_emit_return(C, SLJIT_MOV, SLJIT_S1, 0); // return RET
49
50 /* Generate machine code */
51 code = sljit_generate_code(C);
52 len = sljit_get_generated_code_size(C);
53
54 /* Execute code */
55 func = (func_arr_t)code;
56 printf("func return %ld\n", func(arr, narr));
57
58 /* dump_code(code, len); */
59
60 /* Clean up */
61 sljit_free_compiler(C);
62 sljit_free_code(code);
63 return 0;
64 }
65
main()66 int main()
67 {
68 long arr[8] = { 3, -10, 4, 6, 8, 12, 2000 };
69 return array_access(arr, 8);
70 }
71