10 create_code (gcc_jit_context
*ctxt
, void *user_data
)
12 /* Let's try to inject the equivalent of:
15 my_factorial_must_tail_call (int x)
20 return x * my_factorial_must_tail_call (x - 1);
23 and mark the call as requiring tail-call-optimization.
25 gcc_jit_type
*the_type
=
26 gcc_jit_context_get_type (ctxt
, GCC_JIT_TYPE_INT
);
27 gcc_jit_type
*return_type
= the_type
;
30 gcc_jit_context_new_param (ctxt
, NULL
, the_type
, "x");
31 gcc_jit_param
*params
[1] = {x
};
32 gcc_jit_function
*func
=
33 gcc_jit_context_new_function (ctxt
, NULL
,
34 GCC_JIT_FUNCTION_EXPORTED
,
36 "my_factorial_must_tail_call",
39 gcc_jit_block
*initial
=
40 gcc_jit_function_new_block (func
, "initial");
41 gcc_jit_block
*on_true
=
42 gcc_jit_function_new_block (func
, "on_true");
43 gcc_jit_block
*on_false
=
44 gcc_jit_function_new_block (func
, "on_false");
47 gcc_jit_block_end_with_conditional (
49 gcc_jit_context_new_comparison (
51 GCC_JIT_COMPARISON_LT
,
52 gcc_jit_param_as_rvalue (x
),
53 gcc_jit_context_new_rvalue_from_int (
62 gcc_jit_block_end_with_return (
65 gcc_jit_param_as_rvalue (x
));
68 gcc_jit_rvalue
*x_minus_1
=
69 gcc_jit_context_new_binary_op (
71 GCC_JIT_BINARY_OP_MINUS
, the_type
,
72 gcc_jit_param_as_rvalue (x
),
73 gcc_jit_context_new_rvalue_from_int (
77 /* my_factorial_must_tail_call (x - 1) */
78 gcc_jit_rvalue
*call
=
79 gcc_jit_context_new_call (
84 /* Mark the call as requiring tail-call optimization. */
85 gcc_jit_rvalue_set_bool_require_tail_call (call
, 1);
87 gcc_jit_block_end_with_return (
90 gcc_jit_context_new_binary_op (
92 GCC_JIT_BINARY_OP_MULT
, the_type
,
93 gcc_jit_param_as_rvalue (x
),
98 verify_code (gcc_jit_context
*ctxt
, gcc_jit_result
*result
)
100 typedef int (*my_factorial_fn_type
) (int);
101 CHECK_NON_NULL (result
);
102 my_factorial_fn_type my_factorial_must_tail_call
=
103 (my_factorial_fn_type
)gcc_jit_result_get_code (result
, "my_factorial_must_tail_call");
104 CHECK_NON_NULL (my_factorial_must_tail_call
);
105 int val
= my_factorial_must_tail_call (10);
106 note ("my_factorial_must_tail_call returned: %d", val
);
107 CHECK_VALUE (val
, 3628800);