Getting Started
We start with a really simple example---function returning its argument incremented by one. The source code of this example can be found in demo1.c which is part of the MyJIT package.
#include <stdlib.h> #include <stdio.h> // includes the header file #include "myjit/jitlib.h" // pointer to a function accepting one argument of type long and returning long value typedef long (* plfl)(long); int main() { // creates a new instance of the compiler struct jit * p = jit_init(); plfl foo; // the code generated by the compiler will be assigned to the function `foo' jit_prolog(p, &foo); // the first argument of the function jit_declare_arg(p, JIT_SIGNED_NUM, sizeof(long)); // moves the first argument into the register R(0) jit_getarg(p, R(0), 0); // takes the value in R(0), increments it by one, and stores the result into the // register R(1) jit_addi(p, R(1), R(0), 1); // returns from the function and returns the value stored in the register R(1) jit_retr(p, R(1)); // compiles the above defined code jit_generate_code(p); // checks, if it works printf("Check #1: %li\n", foo(1)); printf("Check #2: %li\n", foo(100)); printf("Check #3: %li\n", foo(255)); // if you are interested, you can dump the machine code // this functionality is provided through the `gcc' and `objdump' // jit_dump_ops(p, JIT_DEBUG_CODE); // cleanup jit_free(p); return 0; }
We assume that the code above is quite (self-)explanatory, and thus, we do not include more comments on this. However, let us make a note on compiling programs using MyJIT. To start with MyJIT, it is sufficient to copy the myjit subdirectory into your project. Programs using the MyJIT should include the #include "myjit/jitlib.h" header file. In order to link the application and build a proper executable file, it is necessary to also compile "myjit/libjit-core.c".
For instance, to build a program with gcc you may use the following steps:
gcc -c -g -Winline -Wall -std=c99 -pedantic -D_XOPEN_SOURCE=600 demo1.c gcc -c -g -Winline -Wall -std=c99 -pedantic -D_XOPEN_SOURCE=600 myjit/jitlib-core.c gcc -o demo1 -g -Wall -std=c99 -pedantic demo1.o jitlib-core.o
The first command compiles the example, the second one compiles functions used by MyJIT, and the last one links the object files together and creates an execute file---demo1.
It should be emphasized that MyJIT conforms to the C99 standard and all MyJIT files should be compiled according to this standard.
We also recommend to check out the demo2.c and demo3.c examples which are also included in the MyJIT package.