1 #include "sljitLir.h"
2
3 #include <stdio.h>
4 #include <stdlib.h>
5
6 typedef long SLJIT_CALL (*func3_t)(long a, long b, long c);
7
8 /*
9 This example, we generate a function like this:
10
11 long func(long a, long b, long c)
12 {
13 if ((a & 1) == 0)
14 return c;
15 return b;
16 }
17
18 */
branch(long a,long b,long c)19 static int branch(long a, long b, long c)
20 {
21 void *code;
22 unsigned long len;
23 func3_t func;
24
25 struct sljit_jump *ret_c;
26 struct sljit_jump *out;
27
28 /* Create a SLJIT compiler */
29 struct sljit_compiler *C = sljit_create_compiler();
30
31 /* 3 arg, 1 temp reg, 3 save reg */
32 sljit_emit_enter(C, 0, 3, 1, 3, 0, 0, 0);
33
34 /* R0 = a & 1, S0 is argument a */
35 sljit_emit_op2(C, SLJIT_AND, SLJIT_R0, 0, SLJIT_S0, 0, SLJIT_IMM, 1);
36
37 /* if R0 == 0 then jump to ret_c, where is ret_c? we assign it later */
38 ret_c = sljit_emit_cmp(C, SLJIT_EQUAL, SLJIT_R0, 0, SLJIT_IMM, 0);
39
40 /* R0 = b, S1 is argument b */
41 sljit_emit_op1(C, SLJIT_MOV, SLJIT_RETURN_REG, 0, SLJIT_S1, 0);
42
43 /* jump to out */
44 out = sljit_emit_jump(C, SLJIT_JUMP);
45
46 /* here is the 'ret_c' should jump, we emit a label and set it to ret_c */
47 sljit_set_label(ret_c, sljit_emit_label(C));
48
49 /* R0 = c, S2 is argument c */
50 sljit_emit_op1(C, SLJIT_MOV, SLJIT_RETURN_REG, 0, SLJIT_S2, 0);
51
52 /* here is the 'out' should jump */
53 sljit_set_label(out, sljit_emit_label(C));
54
55 /* end of function */
56 sljit_emit_return(C, SLJIT_MOV, SLJIT_RETURN_REG, 0);
57
58 /* Generate machine code */
59 code = sljit_generate_code(C);
60 len = sljit_get_generated_code_size(C);
61
62 /* Execute code */
63 func = (func3_t)code;
64 printf("func return %ld\n", func(a, b, c));
65
66 /* dump_code(code, len); */
67
68 /* Clean up */
69 sljit_free_compiler(C);
70 sljit_free_code(code);
71 return 0;
72 }
73
main()74 int main()
75 {
76 return branch(4, 5, 6);
77 }
78