1 /* Usage example for libgccjit.so's C++ API
2 Copyright (C) 2014-2020 Free Software Foundation, Inc.
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3, or (at your option)
11 GCC is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
20 #include <libgccjit++.h>
26 create_code (gccjit::context ctxt
)
28 /* Let's try to inject the equivalent of this C code:
35 gccjit::type int_type
= ctxt
.get_type (GCC_JIT_TYPE_INT
);
36 gccjit::param param_i
= ctxt
.new_param (int_type
, "i");
37 std::vector
<gccjit::param
> params
;
38 params
.push_back (param_i
);
39 gccjit::function func
= ctxt
.new_function (GCC_JIT_FUNCTION_EXPORTED
,
44 gccjit::block block
= func
.new_block ();
47 ctxt
.new_binary_op (GCC_JIT_BINARY_OP_MULT
, int_type
,
50 block
.end_with_return (expr
);
54 main (int argc
, char **argv
)
56 /* Get a "context" object for working with the library. */
57 gccjit::context ctxt
= gccjit::context::acquire ();
59 /* Set some options on the context.
60 Turn this on to see the code being generated, in assembler form. */
61 ctxt
.set_bool_option (
62 GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE
,
65 /* Populate the context. */
68 /* Compile the code. */
69 gcc_jit_result
*result
= ctxt
.compile ();
71 /* We're done with the context; we can release it: */
76 fprintf (stderr
, "NULL result");
80 /* Extract the generated code from "result". */
81 void *fn_ptr
= gcc_jit_result_get_code (result
, "square");
84 fprintf (stderr
, "NULL fn_ptr");
85 gcc_jit_result_release (result
);
89 typedef int (*fn_type
) (int);
90 fn_type square
= (fn_type
)fn_ptr
;
91 printf ("result: %d\n", square (5));
93 gcc_jit_result_release (result
);