1 /* Smoketest example for libgccjit.so C++ API
2 Copyright (C) 2014-2016 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:
30 greet (const char *name)
32 printf ("hello %s\n", name);
35 gccjit::type void_type
= ctxt
.get_type (GCC_JIT_TYPE_VOID
);
36 gccjit::type const_char_ptr_type
=
37 ctxt
.get_type (GCC_JIT_TYPE_CONST_CHAR_PTR
);
38 gccjit::param param_name
=
39 ctxt
.new_param (const_char_ptr_type
, "name");
40 std::vector
<gccjit::param
> func_params
;
41 func_params
.push_back (param_name
);
42 gccjit::function func
=
43 ctxt
.new_function (GCC_JIT_FUNCTION_EXPORTED
,
48 gccjit::param param_format
=
49 ctxt
.new_param (const_char_ptr_type
, "format");
50 std::vector
<gccjit::param
> printf_params
;
51 printf_params
.push_back (param_format
);
52 gccjit::function printf_func
=
53 ctxt
.new_function (GCC_JIT_FUNCTION_IMPORTED
,
54 ctxt
.get_type (GCC_JIT_TYPE_INT
),
58 gccjit::block block
= func
.new_block ();
59 block
.add_eval (ctxt
.new_call (printf_func
,
60 ctxt
.new_rvalue ("hello %s\n"),
62 block
.end_with_return ();
66 main (int argc
, char **argv
)
69 gcc_jit_result
*result
;
71 /* Get a "context" object for working with the library. */
72 ctxt
= gccjit::context::acquire ();
74 /* Set some options on the context.
75 Turn this on to see the code being generated, in assembler form. */
76 ctxt
.set_bool_option (GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE
, 0);
78 /* Populate the context. */
81 /* Compile the code. */
82 result
= ctxt
.compile ();
85 fprintf (stderr
, "NULL result");
91 /* Extract the generated code from "result". */
92 typedef void (*fn_type
) (const char *);
94 (fn_type
)gcc_jit_result_get_code (result
, "greet");
97 fprintf (stderr
, "NULL greet");
101 /* Now call the generated function: */
105 gcc_jit_result_release (result
);