From c437cc6df6d13801270bd4ae2d056f22eda6de12 Mon Sep 17 00:00:00 2001 From: Anatol Belski Date: Sun, 2 Jul 2023 18:39:30 +0200 Subject: [PATCH] examples: Add native function call example Signed-off-by: Anatol Belski --- Makefile | 2 +- examples/0001-func.c | 61 ++++++++++++++++++++++++++++++++++++++++++++ win32/Makefile | 2 +- 3 files changed, 63 insertions(+), 2 deletions(-) create mode 100644 examples/0001-func.c diff --git a/Makefile b/Makefile index 4c8477a..4a794e4 100644 --- a/Makefile +++ b/Makefile @@ -48,7 +48,7 @@ OBJS_COMMON = $(BUILD_DIR)/ir.o $(BUILD_DIR)/ir_strtab.o $(BUILD_DIR)/ir_cfg.o \ OBJS_IR = $(BUILD_DIR)/ir_main.o OBJS_IR_TEST = $(BUILD_DIR)/ir_test.o EXAMPLE_EXES = $(EXAMPLES_BUILD_DIR)/0001-basic $(EXAMPLES_BUILD_DIR)/0001-while $(EXAMPLES_BUILD_DIR)/0005-basic-runner-func \ - $(EXAMPLES_BUILD_DIR)/0001-pointer + $(EXAMPLES_BUILD_DIR)/0001-pointer $(EXAMPLES_BUILD_DIR)/0001-func all: $(BUILD_DIR) $(BUILD_DIR)/ir $(BUILD_DIR)/ir_test diff --git a/examples/0001-func.c b/examples/0001-func.c new file mode 100644 index 0000000..b73ad31 --- /dev/null +++ b/examples/0001-func.c @@ -0,0 +1,61 @@ +/* + * IR - Lightweight JIT Compilation Framework + * (Exmaples package) + * Copyright (C) 2023 by IR project. + * Authors: Anatol Belski + */ + +#include "ir.h" +#include "ir_builder.h" +#include + +#include + +uint8_t hello(void) +{ + printf("I'm Hello\n"); + return 42; +} + +/* + * uint8_t myfunc() { + * return hello(); + * } + */ +typedef uint8_t (*myfunc_t)(); + +void gen_myfunc(ir_ctx *ctx) +{ + /* Function entry start */ + ir_START(); + + /* Load function address. */ + ir_ref addr = ir_CONST_ADDR(hello); + /* Call function. */ + ir_ref ret = ir_CALL(IR_U8, addr); + + /* Function end, return value */ + ir_RETURN(ret); +} + +int main(int argc, char **argv) +{ + ir_ctx ctx = {0}; + + ir_consistency_check(); + + ir_init(&ctx, IR_FUNCTION | IR_OPT_FOLDING, IR_CONSTS_LIMIT_MIN, IR_INSNS_LIMIT_MIN); + + gen_myfunc(&ctx); + + size_t size; + void *entry = ir_jit_compile(&ctx, 2, &size); + if (entry) { + uint8_t i = ((myfunc_t)entry)(); + printf("i=%u\n", i); + } + + ir_free(&ctx); + + return 0; +} diff --git a/win32/Makefile b/win32/Makefile index 2b508df..5a0ee92 100644 --- a/win32/Makefile +++ b/win32/Makefile @@ -79,7 +79,7 @@ OBJS_COMMON=$(BUILD_DIR)\ir.obj $(BUILD_DIR)\ir_strtab.obj $(BUILD_DIR)\ir_cfg.o OBJS_IR = $(BUILD_DIR)\ir_main.obj OBJS_IR_TEST = $(BUILD_DIR)\ir_test.obj EXAMPLE_EXES = $(EXAMPLES_BUILD_DIR)\0001-basic.exe $(EXAMPLES_BUILD_DIR)\0001-while.exe $(EXAMPLES_BUILD_DIR)\0005-basic-runner-func.exe \ - $(EXAMPLES_BUILD_DIR)\0001-pointer.exe + $(EXAMPLES_BUILD_DIR)\0001-pointer.exe $(EXAMPLES_BUILD_DIR)\0001-func.exe all: $(BUILD_DIR) $(BUILD_DIR)\ir.exe $(BUILD_DIR)\ir_test.exe