const std = @import("std"); const ast = @import("ast.zig"); const llvm = @import("llvm.zig"); fn sliceify(non_slice: ?[*]const u8) []const u8 { if (non_slice == null) return ""; return non_slice.?[0..std.mem.len(u8, non_slice.?)]; } pub const CompileError = error{LLVMError}; pub const Codegen = struct { allocator: *std.mem.Allocator, pub fn init(allocator: *std.mem.Allocator) Codegen { return Codegen{ .allocator = allocator }; } fn genExpr(self: *Codegen, builder: var, expr: *const ast.Expr) !llvm.LLVMValueRef { // TODO if expr is Variable, we should do a variable lookup // in a symbol table, going up in scope, etc. // TODO VarDecl add things to the symbol table // TODO Assign modify symbol table // TODO Calls fetch symbol table, check arity of it at codegen level switch (expr.*) { // TODO handle all literals, construct llvm values for them .Literal => |literal| {}, .Binary => |binary| { var left = try self.genExpr(builder, binary.left); var right = try self.genExpr(builder, binary.right); return switch (binary.op.lexeme[0]) { // TODO other operators '+' => llvm.LLVMBuildAdd(builder, left, right, c"addtmp"), // TODO codegen errors else => @panic("invalid binary operator"), }; }, // TODO codegen errors else => @panic("invalid expr"), } } fn genFuncStmt(self: *Codegen, builder: var, stmt: *const ast.Stmt) !void { switch (stmt.*) { .Expr => |expr| try self.genExpr(builder, expr), else => unreachable, } } fn genNode( self: *Codegen, mod: llvm.LLVMModuleRef, node: *const ast.Node, ) !void { switch (node.*) { .Root => @panic("Should not have gotten Root"), .FnDecl => |decl| { const name = decl.func_name.lexeme; const name_cstr = try std.cstr.addNullByte(self.allocator, name); errdefer self.allocator.free(name_cstr); //const ret_type = decl.return_type.lexeme; var param_types = llvm.LLVMTypeList.init(self.allocator); errdefer param_types.deinit(); for (decl.params.toSlice()) |param| { try param_types.append(llvm.LLVMInt32Type()); } var ret_type = llvm.LLVMFunctionType( llvm.LLVMInt32Type(), param_types.toSlice().ptr, @intCast(c_uint, param_types.len), 0, ); var func = llvm.LLVMAddFunction(mod, name_cstr.ptr, ret_type); var entry = llvm.LLVMAppendBasicBlock(func, c"entry"); var builder = llvm.LLVMCreateBuilder(); llvm.LLVMPositionBuilderAtEnd(builder, entry); for (decl.body.toSlice()) |stmt| { // TODO custom function context for us try self.genFuncStmt(builder, stmt); } // TODO codegen decl.body var tmp = llvm.LLVMBuildAdd( builder, llvm.LLVMGetParam(func, 0), llvm.LLVMGetParam(func, 1), c"tmp", ); _ = llvm.LLVMBuildRet(builder, tmp); std.debug.warn("cgen: fn decl done\n"); }, else => { std.debug.warn("got unhandled Node {}\n", node.*); unreachable; }, } } pub fn gen(self: *Codegen, root: *ast.Node) !void { std.debug.warn("cgen: start gen\n"); _ = llvm.LLVMInitializeNativeTarget(); var mod = llvm.LLVMModuleCreateWithName(c"awoo").?; defer llvm.LLVMDisposeModule(mod); for (root.Root.toSlice()) |child| { std.debug.warn("cgen: gen child {}\n", child); try self.genNode(mod, &child); } var err: ?[*]u8 = null; defer llvm.LLVMDisposeMessage(err); _ = llvm.LLVMVerifyModule( mod, llvm.LLVMVerifierFailureAction.LLVMAbortProcessAction, &err, ); if (llvm.LLVMWriteBitcodeToFile(mod, c"awoo.bc") != 0) { std.debug.warn("error writing bitcode to file: {}\n", sliceify(err)); return CompileError.LLVMError; } llvm.LLVMInitializeAllTargetInfos(); llvm.LLVMInitializeAllTargets(); llvm.LLVMInitializeAllTargetMCs(); llvm.LLVMInitializeAllAsmParsers(); llvm.LLVMInitializeAllAsmPrinters(); var engine: llvm.LLVMExecutionEngineRef = undefined; if (llvm.LLVMCreateExecutionEngineForModule(&engine, mod, &err) != 0) { std.debug.warn("failed to create execution engine: {}\n", sliceify(err)); return CompileError.LLVMError; } var machine = llvm.LLVMGetExecutionEngineTargetMachine(engine); defer llvm.LLVMDisposeTargetMachine(machine); var target = llvm.LLVMGetTargetMachineTarget(machine); var target_data = llvm.LLVMCreateTargetDataLayout(machine); var data_layout = llvm.LLVMCopyStringRepOfTargetData(target_data); llvm.LLVMSetDataLayout(mod, data_layout); var outpath = try std.mem.dupe(self.allocator, u8, "output.o"); var outpath_cstr = try std.cstr.addNullByte(self.allocator, outpath); //var asmpath = try std.mem.dupe(self.allocator, u8, "output.S"); //var asmpath_cstr = try std.cstr.addNullByte(self.allocator, asmpath); var desc = llvm.LLVMGetTargetDescription(target); var features = llvm.LLVMGetTargetMachineFeatureString(machine); var triple = llvm.LLVMGetTargetMachineTriple(machine); std.debug.warn("target: {}\n", sliceify(desc)); std.debug.warn("triple: {}\n", sliceify(triple)); std.debug.warn("features: {}\n", sliceify(features)); //if (llvm.LLVMTargetMachineEmitToFile( // machine, // mod, // asmpath_cstr.ptr, // llvm.LLVMCodeGenFileType.LLVMAssemblyFile, // &err, //) != 0) { // std.debug.warn("failed to emit to assembly file: {}\n", sliceify(err)); // return CompileError.LLVMError; //} if (llvm.LLVMTargetMachineEmitToFile( machine, mod, outpath_cstr.ptr, llvm.LLVMCodeGenFileType.LLVMObjectFile, &err, ) != 0) { std.debug.warn("failed to emit to file: {}\n", sliceify(err)); return CompileError.LLVMError; } } };