try a new github issue template
[pcsx_rearmed.git] / deps / lightning / doc / rfib.c
CommitLineData
4a71579b
PC
1#include <stdio.h>
2#include <lightning.h>
3
4static jit_state_t *_jit;
5
6typedef int (*pifi)(int); /* Pointer to Int Function of Int */
7
8int main(int argc, char *argv[])
9{
10 pifi fib;
11 jit_node_t *label;
12 jit_node_t *call;
13 jit_node_t *in; /* offset of the argument */
14 jit_node_t *ref; /* to patch the forward reference */
15 jit_node_t *zero; /* to patch the forward reference */
16
17 init_jit(argv[0]);
18 _jit = jit_new_state();
19
20 label = jit_label();
21 jit_prolog ();
22 in = jit_arg ();
23 jit_getarg (JIT_R0, in); /* R0 = n */
24 zero = jit_beqi (JIT_R0, 0);
25 jit_movr (JIT_V0, JIT_R0); /* V0 = R0 */
26 jit_movi (JIT_R0, 1);
27 ref = jit_blei (JIT_V0, 2);
28 jit_subi (JIT_V1, JIT_V0, 1); /* V1 = n-1 */
29 jit_subi (JIT_V2, JIT_V0, 2); /* V2 = n-2 */
30 jit_prepare();
31 jit_pushargr(JIT_V1);
32 call = jit_finishi(NULL);
33 jit_patch_at(call, label);
34 jit_retval(JIT_V1); /* V1 = fib(n-1) */
35 jit_prepare();
36 jit_pushargr(JIT_V2);
37 call = jit_finishi(NULL);
38 jit_patch_at(call, label);
39 jit_retval(JIT_R0); /* R0 = fib(n-2) */
40 jit_addr(JIT_R0, JIT_R0, JIT_V1); /* R0 = R0 + V1 */
41
42 jit_patch(ref); /* patch jump */
43 jit_patch(zero); /* patch jump */
44 jit_retr(JIT_R0);
45
46 /* call the generated code, passing 32 as an argument */
47 fib = jit_emit();
48 jit_clear_state();
49 printf("fib(%d) = %d\n", 32, fib(32));
50 jit_destroy_state();
51 finish_jit();
52 return 0;
53}