1.3 Tutorial part 3: Loops and variables

Consider this C function:

int loop_test (int n)
{
  int sum = 0;
  for (int i = 0; i < n; i++)
    sum += i * i;
  return sum;
}

This example demonstrates some more features of libgccjit, with local variables and a loop.

To break this down into libgccjit terms, it’s usually easier to reword the for loop as a while loop, giving:

int loop_test (int n)
{
  int sum = 0;
  int i = 0;
  while (i < n)
  {
    sum += i * i;
    i++;
  }
  return sum;
}

Here’s what the final control flow graph will look like:

image of a control flow graph

Figure

As before, we include the libgccjit header and make a gcc_jit_context *.

#include <libgccjit.h>

void test (void)
{
  gcc_jit_context *ctxt;
  ctxt = gcc_jit_context_acquire ();

The function works with the C int type:

gcc_jit_type *the_type =
  gcc_jit_context_get_type (ctxt, GCC_JIT_TYPE_INT);
gcc_jit_type *return_type = the_type;

though we could equally well make it work on, say, double:

gcc_jit_type *the_type =
  gcc_jit_context_get_type (ctxt, GCC_JIT_TYPE_DOUBLE);

Let’s build the function:

gcc_jit_param *n =
  gcc_jit_context_new_param (ctxt, NULL, the_type, "n");
gcc_jit_param *params[1] = {n};
gcc_jit_function *func =
  gcc_jit_context_new_function (ctxt, NULL,
                                GCC_JIT_FUNCTION_EXPORTED,
                                return_type,
                                "loop_test",
                                1, params, 0);