From d40fe3a6503586eb2ce93311cc4bf23febfbeb83 Mon Sep 17 00:00:00 2001
From: Thomas Voss <mail@thomasvoss.com>
Date: Tue, 11 Jun 2024 02:00:43 +0200
Subject: Get building & linking with LLVM working

---
 src/codegen.c | 38 ++++++++++++++++++++++++++++++++++++++
 src/codegen.h |  9 +++++++++
 src/main.c    |  2 ++
 3 files changed, 49 insertions(+)
 create mode 100644 src/codegen.c
 create mode 100644 src/codegen.h

(limited to 'src')

diff --git a/src/codegen.c b/src/codegen.c
new file mode 100644
index 0000000..a9e5006
--- /dev/null
+++ b/src/codegen.c
@@ -0,0 +1,38 @@
+#include <llvm-c/Analysis.h>
+#include <llvm-c/Core.h>
+
+#include "codegen.h"
+
+void
+codegen(struct ast_soa ast, struct lexemes_soa toks)
+{
+	(void)ast;
+	(void)toks;
+
+	/* Create a new module */
+	LLVMModuleRef mod = LLVMModuleCreateWithName("oryx");
+
+	/* Declare the function ‘sum :: (int, int) int’ */
+	LLVMTypeRef param_types[] = {LLVMInt32Type(), LLVMInt32Type()};
+	LLVMTypeRef ret_type = LLVMFunctionType(LLVMInt32Type(), param_types, 2, 0);
+	LLVMValueRef sum = LLVMAddFunction(mod, "sum", ret_type);
+
+	/* Create an entry block, and a builder */
+	LLVMBasicBlockRef entry = LLVMAppendBasicBlock(sum, "entry");
+	LLVMBuilderRef builder = LLVMCreateBuilder();
+	LLVMPositionBuilderAtEnd(builder, entry);
+
+	/* Generate an ADD instruction */
+	LLVMValueRef tmp = LLVMBuildAdd(builder, LLVMGetParam(sum, 0),
+	                                LLVMGetParam(sum, 1), "tmpadd");
+	LLVMBuildRet(builder, tmp);
+
+	/* Verify that all went well and if not we abort */
+	char *error = NULL;
+	LLVMVerifyModule(mod, LLVMAbortProcessAction, &error);
+	LLVMDisposeMessage(error);
+
+	LLVMDumpModule(mod);
+
+	LLVMDisposeBuilder(builder);
+}
diff --git a/src/codegen.h b/src/codegen.h
new file mode 100644
index 0000000..79f3ad7
--- /dev/null
+++ b/src/codegen.h
@@ -0,0 +1,9 @@
+#ifndef ORYX_CODEGEN_H
+#define ORYX_CODEGEN_H
+
+#include "lexer.h"
+#include "parser.h"
+
+void codegen(struct ast_soa ast, struct lexemes_soa toks);
+
+#endif /* !ORYX_CODEGEN_H */
diff --git a/src/main.c b/src/main.c
index b156466..03ce9ca 100644
--- a/src/main.c
+++ b/src/main.c
@@ -5,6 +5,7 @@
 #include <stdlib.h>
 #include <unistd.h>
 
+#include "codegen.h"
 #include "errors.h"
 #include "lexer.h"
 #include "parser.h"
@@ -24,6 +25,7 @@ main(int argc, char **argv)
 
 	struct lexemes_soa toks = lexstring(src, srclen);
 	struct ast_soa ast = parsetoks(toks);
+	codegen(ast, toks);
 
 #if DEBUG
 	free(src);
-- 
cgit v1.2.3