From b59e2c1e009e8e2df2de02d61d8f4ef463a652be Mon Sep 17 00:00:00 2001 From: Noam Preil Date: Sun, 9 Aug 2020 15:41:43 -0400 Subject: [PATCH 1/9] CBE: improve noreturn definition, support noreturn on MSVC --- src-self-hosted/cbe.h | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src-self-hosted/cbe.h b/src-self-hosted/cbe.h index 66e7b8bd3e..7d0e48eaae 100644 --- a/src-self-hosted/cbe.h +++ b/src-self-hosted/cbe.h @@ -1,7 +1,9 @@ #if __STDC_VERSION__ >= 201112L #define noreturn _Noreturn -#elif __GNUC__ && !__STRICT_ANSI__ +#elif __GNUC__ #define noreturn __attribute__ ((noreturn)) +#elif _MSC_VER +#define noreturn __declspec(noreturn) #else #define noreturn #endif From dd1f1487e436650f93e05648b5ba879d6832c2a7 Mon Sep 17 00:00:00 2001 From: Noam Preil Date: Sun, 9 Aug 2020 17:21:40 -0400 Subject: [PATCH 2/9] CBE: Use zig_noreturn instead of noreturn to avoid namespace conflict --- src-self-hosted/cbe.h | 8 ++++---- src-self-hosted/codegen/c.zig | 3 +-- src-self-hosted/link.zig | 1 - test/stage2/cbe.zig | 17 ++++++++--------- 4 files changed, 13 insertions(+), 16 deletions(-) diff --git a/src-self-hosted/cbe.h b/src-self-hosted/cbe.h index 7d0e48eaae..691aa45725 100644 --- a/src-self-hosted/cbe.h +++ b/src-self-hosted/cbe.h @@ -1,10 +1,10 @@ #if __STDC_VERSION__ >= 201112L -#define noreturn _Noreturn +#define zig_noreturn _Noreturn #elif __GNUC__ -#define noreturn __attribute__ ((noreturn)) +#define zig_noreturn __attribute__ ((noreturn)) #elif _MSC_VER -#define noreturn __declspec(noreturn) +#define zig_noreturn __declspec(noreturn) #else -#define noreturn +#define zig_noreturn #endif diff --git a/src-self-hosted/codegen/c.zig b/src-self-hosted/codegen/c.zig index db9d9a1030..39110d03d7 100644 --- a/src-self-hosted/codegen/c.zig +++ b/src-self-hosted/codegen/c.zig @@ -24,8 +24,7 @@ fn renderType(file: *C, writer: std.ArrayList(u8).Writer, T: Type, src: usize) ! } else { switch (T.zigTypeTag()) { .NoReturn => { - file.need_noreturn = true; - try writer.writeAll("noreturn void"); + try writer.writeAll("zig_noreturn void"); }, .Void => try writer.writeAll("void"), .Int => { diff --git a/src-self-hosted/link.zig b/src-self-hosted/link.zig index 431d510b01..28340a4024 100644 --- a/src-self-hosted/link.zig +++ b/src-self-hosted/link.zig @@ -202,7 +202,6 @@ pub const File = struct { called: std.StringHashMap(void), need_stddef: bool = false, need_stdint: bool = false, - need_noreturn: bool = false, error_msg: *Module.ErrorMsg = undefined, pub fn openPath(allocator: *Allocator, dir: fs.Dir, sub_path: []const u8, options: Options) !*File { diff --git a/test/stage2/cbe.zig b/test/stage2/cbe.zig index 2c3f0631c8..0529c07e2a 100644 --- a/test/stage2/cbe.zig +++ b/test/stage2/cbe.zig @@ -12,7 +12,7 @@ pub fn addCases(ctx: *TestContext) !void { ctx.c("empty start function", linux_x64, \\export fn _start() noreturn {} , - \\noreturn void _start(void) {} + \\zig_noreturn void _start(void) {} \\ ); ctx.c("less empty start function", linux_x64, @@ -22,19 +22,19 @@ pub fn addCases(ctx: *TestContext) !void { \\ main(); \\} , - \\noreturn void main(void); + \\zig_noreturn void main(void); \\ - \\noreturn void _start(void) { + \\zig_noreturn void _start(void) { \\ main(); \\} \\ - \\noreturn void main(void) {} + \\zig_noreturn void main(void) {} \\ ); // TODO: implement return values // TODO: figure out a way to prevent asm constants from being generated ctx.c("inline asm", linux_x64, - \\fn exitGood() void { + \\fn exitGood() noreturn { \\ asm volatile ("syscall" \\ : \\ : [number] "{rax}" (231), @@ -48,21 +48,20 @@ pub fn addCases(ctx: *TestContext) !void { , \\#include \\ - \\void exitGood(void); + \\zig_noreturn void exitGood(void); \\ \\const char *const exitGood__anon_0 = "{rax}"; \\const char *const exitGood__anon_1 = "{rdi}"; \\const char *const exitGood__anon_2 = "syscall"; \\ - \\noreturn void _start(void) { + \\zig_noreturn void _start(void) { \\ exitGood(); \\} \\ - \\void exitGood(void) { + \\zig_noreturn void exitGood(void) { \\ register size_t rax_constant __asm__("rax") = 231; \\ register size_t rdi_constant __asm__("rdi") = 0; \\ __asm volatile ("syscall" :: ""(rax_constant), ""(rdi_constant)); - \\ return; \\} \\ ); From 4d778e630a1902e59e2c0f92674d7f9bda026cf6 Mon Sep 17 00:00:00 2001 From: Noam Preil Date: Sun, 9 Aug 2020 17:53:56 -0400 Subject: [PATCH 3/9] Tests: print generated C on test failure --- src-self-hosted/test.zig | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src-self-hosted/test.zig b/src-self-hosted/test.zig index 7d4cc7d563..265c26b2dc 100644 --- a/src-self-hosted/test.zig +++ b/src-self-hosted/test.zig @@ -478,6 +478,10 @@ pub const TestContext = struct { for (all_errors.list) |err| { std.debug.warn(":{}:{}: error: {}\n================\n", .{ err.line + 1, err.column + 1, err.msg }); } + if (case.cbe) { + const C = module.bin_file.cast(link.File.C).?; + std.debug.warn("Generated C: \n===============\n{}\n\n===========\n\n", .{C.main.items}); + } std.debug.warn("Test failed.\n", .{}); std.process.exit(1); } From d3eec7d46b1dea6c99dd4beea370a3629843c111 Mon Sep 17 00:00:00 2001 From: Noam Preil Date: Sun, 9 Aug 2020 18:45:34 -0400 Subject: [PATCH 4/9] CBE: working parameters --- src-self-hosted/codegen/c.zig | 82 ++++++++++++++++++++++++++--------- test/stage2/cbe.zig | 34 +++++++++++++++ 2 files changed, 96 insertions(+), 20 deletions(-) diff --git a/src-self-hosted/codegen/c.zig b/src-self-hosted/codegen/c.zig index 39110d03d7..ba68a3a5a4 100644 --- a/src-self-hosted/codegen/c.zig +++ b/src-self-hosted/codegen/c.zig @@ -40,16 +40,33 @@ fn renderType(file: *C, writer: std.ArrayList(u8).Writer, T: Type, src: usize) ! } } +fn renderValue(file: *C, writer: std.ArrayList(u8).Writer, val: Value, src: usize) !void { + switch (val.tag()) { + .int_u64 => return writer.print("{}", .{val.toUnsignedInt()}), + else => |e| return file.fail(src, "TODO implement value {}", .{e}), + } +} + fn renderFunctionSignature(file: *C, writer: std.ArrayList(u8).Writer, decl: *Decl) !void { const tv = decl.typed_value.most_recent.typed_value; try renderType(file, writer, tv.ty.fnReturnType(), decl.src()); const name = try map(file.base.allocator, mem.spanZ(decl.name)); defer file.base.allocator.free(name); try writer.print(" {}(", .{name}); - if (tv.ty.fnParamLen() == 0) - try writer.writeAll("void)") - else - return file.fail(decl.src(), "TODO implement parameters", .{}); + var param_len = tv.ty.fnParamLen(); + if (param_len == 0) + try writer.writeAll("void") + else { + var index: usize = 0; + while (index < param_len) : (index += 1) { + if (index > 0) { + try writer.writeAll(", "); + } + try renderType(file, writer, tv.ty.fnParamType(index), decl.src()); + try writer.print(" arg{}", .{index}); + } + } + try writer.writeByte(')'); } pub fn generate(file: *C, decl: *Decl) !void { @@ -87,15 +104,19 @@ fn genFn(file: *C, decl: *Decl) !void { const func: *Module.Fn = tv.val.cast(Value.Payload.Function).?.func; const instructions = func.analysis.success.instructions; + var argdex: usize = 0; if (instructions.len > 0) { try writer.writeAll("\n"); for (instructions) |inst| { switch (inst.tag) { - .assembly => try genAsm(file, inst.castTag(.assembly).?, decl), + .assembly => try genAsm(file, inst.castTag(.assembly).?, decl, &argdex), .call => try genCall(file, inst.castTag(.call).?, decl), .ret => try genRet(file, inst.castTag(.ret).?, decl, tv.ty.fnReturnType()), .retvoid => try file.main.writer().print(" return;\n", .{}), + .arg => {}, .dbg_stmt => try genDbgStmt(file, inst.castTag(.dbg_stmt).?, decl), + .breakpoint => try genBreak(file, inst.castTag(.breakpoint).?, decl), + .unreach => try genUnreach(file, inst.castTag(.unreach).?, decl), else => |e| return file.fail(decl.src(), "TODO implement C codegen for {}", .{e}), } } @@ -126,13 +147,23 @@ fn genCall(file: *C, inst: *Inst.Call, decl: *Decl) !void { try renderFunctionSignature(file, header, target); try header.writeAll(";\n"); } - try writer.print("{}();\n", .{tname}); + try writer.print("{}(", .{tname}); + if (inst.args.len != 0) { + for (inst.args) |arg, i| { + if (i > 0) { + try writer.writeAll(", "); + } + if (arg.cast(Inst.Constant)) |con| { + try renderValue(file, writer, con.val, decl.src()); + } else { + return file.fail(decl.src(), "TODO call pass arg {}", .{arg}); + } + } + } + try writer.writeAll(");\n"); } else { return file.fail(decl.src(), "TODO non-function call target?", .{}); } - if (inst.args.len != 0) { - return file.fail(decl.src(), "TODO function arguments", .{}); - } } else { return file.fail(decl.src(), "TODO non-constant call inst?", .{}); } @@ -142,24 +173,33 @@ fn genDbgStmt(file: *C, inst: *Inst.NoOp, decl: *Decl) !void { // TODO emit #line directive here with line number and filename } -fn genAsm(file: *C, as: *Inst.Assembly, decl: *Decl) !void { +fn genBreak(file: *C, inst: *Inst.NoOp, decl: *Decl) !void { + // TODO ?? +} + +fn genUnreach(file: *C, inst: *Inst.NoOp, decl: *Decl) !void { + // TODO ?? +} + +fn genAsm(file: *C, as: *Inst.Assembly, decl: *Decl, argdex: *usize) !void { const writer = file.main.writer(); try writer.writeAll(" "); for (as.inputs) |i, index| { if (i[0] == '{' and i[i.len - 1] == '}') { const reg = i[1 .. i.len - 1]; const arg = as.args[index]; + try writer.writeAll("register "); + try renderType(file, writer, arg.ty, decl.src()); + try writer.print(" {}_constant __asm__(\"{}\") = ", .{ reg, reg }); if (arg.castTag(.constant)) |c| { - if (c.val.tag() == .int_u64) { - try writer.writeAll("register "); - try renderType(file, writer, arg.ty, decl.src()); - try writer.print(" {}_constant __asm__(\"{}\") = {};\n ", .{ reg, reg, c.val.toUnsignedInt() }); - } else { - return file.fail(decl.src(), "TODO inline asm {} args", .{c.val.tag()}); - } + try renderValue(file, writer, c.val, decl.src()); + } else if (arg.castTag(.arg)) |inst| { + try writer.print("arg{}", .{argdex.*}); + argdex.* += 1; } else { - return file.fail(decl.src(), "TODO non-constant inline asm args", .{}); + return file.fail(decl.src(), "TODO non-constant inline asm args ({})", .{arg.tag}); } + try writer.writeAll(";\n "); } else { return file.fail(decl.src(), "TODO non-explicit inline asm regs", .{}); } @@ -180,12 +220,14 @@ fn genAsm(file: *C, as: *Inst.Assembly, decl: *Decl) !void { if (index > 0) { try writer.writeAll(", "); } - if (arg.castTag(.constant)) |c| { - try writer.print("\"\"({}_constant)", .{reg}); + try writer.writeAll("\"\"("); + if (arg.tag == .constant or arg.tag == .arg) { + try writer.print("{}_constant", .{reg}); } else { // This is blocked by the earlier test unreachable; } + try writer.writeByte(')'); } else { // This is blocked by the earlier test unreachable; diff --git a/test/stage2/cbe.zig b/test/stage2/cbe.zig index 0529c07e2a..36c4514d49 100644 --- a/test/stage2/cbe.zig +++ b/test/stage2/cbe.zig @@ -65,4 +65,38 @@ pub fn addCases(ctx: *TestContext) !void { \\} \\ ); + ctx.c("exit", linux_x64, + \\export fn _start() noreturn { + \\ exit(0); + \\} + \\ + \\fn exit(code: usize) noreturn { + \\ asm volatile ("syscall" + \\ : + \\ : [number] "{rax}" (231), + \\ [arg1] "{rdi}" (code) + \\ ); + \\ unreachable; + \\} + \\ + , + \\#include + \\ + \\zig_noreturn void exit(size_t arg0); + \\ + \\const char *const exit__anon_0 = "{rax}"; + \\const char *const exit__anon_1 = "{rdi}"; + \\const char *const exit__anon_2 = "syscall"; + \\ + \\zig_noreturn void _start(void) { + \\ exit(0); + \\} + \\ + \\zig_noreturn void exit(size_t arg0) { + \\ register size_t rax_constant __asm__("rax") = 231; + \\ register size_t rdi_constant __asm__("rdi") = arg0; + \\ __asm volatile ("syscall" :: ""(rax_constant), ""(rdi_constant)); + \\} + \\ + ); } From 78fe86dcd23821b6a40bc5a0067513c452e50265 Mon Sep 17 00:00:00 2001 From: Noam Preil Date: Sun, 9 Aug 2020 18:52:32 -0400 Subject: [PATCH 5/9] CBE: support unreachable on GCC --- src-self-hosted/cbe.h | 5 +++++ src-self-hosted/codegen/c.zig | 2 +- test/stage2/cbe.zig | 3 ++- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/src-self-hosted/cbe.h b/src-self-hosted/cbe.h index 691aa45725..854032227d 100644 --- a/src-self-hosted/cbe.h +++ b/src-self-hosted/cbe.h @@ -8,3 +8,8 @@ #define zig_noreturn #endif +#if __GNUC__ +#define zig_unreachable() __builtin_unreachable() +#else +#define zig_unreachable() +#endif diff --git a/src-self-hosted/codegen/c.zig b/src-self-hosted/codegen/c.zig index ba68a3a5a4..591e47967e 100644 --- a/src-self-hosted/codegen/c.zig +++ b/src-self-hosted/codegen/c.zig @@ -178,7 +178,7 @@ fn genBreak(file: *C, inst: *Inst.NoOp, decl: *Decl) !void { } fn genUnreach(file: *C, inst: *Inst.NoOp, decl: *Decl) !void { - // TODO ?? + try file.main.writer().writeAll(" zig_unreachable();\n"); } fn genAsm(file: *C, as: *Inst.Assembly, decl: *Decl, argdex: *usize) !void { diff --git a/test/stage2/cbe.zig b/test/stage2/cbe.zig index 36c4514d49..59bc062b74 100644 --- a/test/stage2/cbe.zig +++ b/test/stage2/cbe.zig @@ -65,7 +65,7 @@ pub fn addCases(ctx: *TestContext) !void { \\} \\ ); - ctx.c("exit", linux_x64, + ctx.c("exit with parameter", linux_x64, \\export fn _start() noreturn { \\ exit(0); \\} @@ -96,6 +96,7 @@ pub fn addCases(ctx: *TestContext) !void { \\ register size_t rax_constant __asm__("rax") = 231; \\ register size_t rdi_constant __asm__("rdi") = arg0; \\ __asm volatile ("syscall" :: ""(rax_constant), ""(rdi_constant)); + \\ zig_unreachable(); \\} \\ ); From dbd1e42ef227bf55e9356b2d1a1cbde1fbec0e82 Mon Sep 17 00:00:00 2001 From: Noam Preil Date: Sun, 9 Aug 2020 19:44:16 -0400 Subject: [PATCH 6/9] CBE: Sorta working intcasts? --- src-self-hosted/codegen/c.zig | 27 ++++++++++++++++++-------- test/stage2/cbe.zig | 36 +++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 8 deletions(-) diff --git a/src-self-hosted/codegen/c.zig b/src-self-hosted/codegen/c.zig index 591e47967e..907bbccda1 100644 --- a/src-self-hosted/codegen/c.zig +++ b/src-self-hosted/codegen/c.zig @@ -117,6 +117,8 @@ fn genFn(file: *C, decl: *Decl) !void { .dbg_stmt => try genDbgStmt(file, inst.castTag(.dbg_stmt).?, decl), .breakpoint => try genBreak(file, inst.castTag(.breakpoint).?, decl), .unreach => try genUnreach(file, inst.castTag(.unreach).?, decl), + // This will be handled correctly later? + .intcast => {}, else => |e| return file.fail(decl.src(), "TODO implement C codegen for {}", .{e}), } } @@ -129,6 +131,20 @@ fn genRet(file: *C, inst: *Inst.UnOp, decl: *Decl, expected_return_type: Type) ! return file.fail(decl.src(), "TODO return {}", .{expected_return_type}); } +fn genIntCast(file: *C, inst: *Inst.UnOp, decl: *Decl, argdex: *usize) !void { + const op = inst.operand; + const writer = file.main.writer(); + try writer.writeByte('('); + try renderType(file, writer, inst.base.ty, decl.src()); + try writer.writeByte(')'); + if (op.castTag(.arg)) |_| { + try writer.print("arg{}", .{argdex.*}); + argdex.* += 1; + } else { + return file.fail(decl.src(), "TODO intcast {} to {}", .{ op, inst.base.ty }); + } +} + fn genCall(file: *C, inst: *Inst.Call, decl: *Decl) !void { const writer = file.main.writer(); const header = file.header.writer(); @@ -196,6 +212,8 @@ fn genAsm(file: *C, as: *Inst.Assembly, decl: *Decl, argdex: *usize) !void { } else if (arg.castTag(.arg)) |inst| { try writer.print("arg{}", .{argdex.*}); argdex.* += 1; + } else if (arg.castTag(.intcast)) |inst| { + try genIntCast(file, inst, decl, argdex); } else { return file.fail(decl.src(), "TODO non-constant inline asm args ({})", .{arg.tag}); } @@ -220,14 +238,7 @@ fn genAsm(file: *C, as: *Inst.Assembly, decl: *Decl, argdex: *usize) !void { if (index > 0) { try writer.writeAll(", "); } - try writer.writeAll("\"\"("); - if (arg.tag == .constant or arg.tag == .arg) { - try writer.print("{}_constant", .{reg}); - } else { - // This is blocked by the earlier test - unreachable; - } - try writer.writeByte(')'); + try writer.print("\"\"({}_constant)", .{reg}); } else { // This is blocked by the earlier test unreachable; diff --git a/test/stage2/cbe.zig b/test/stage2/cbe.zig index 59bc062b74..4b35286f94 100644 --- a/test/stage2/cbe.zig +++ b/test/stage2/cbe.zig @@ -100,4 +100,40 @@ pub fn addCases(ctx: *TestContext) !void { \\} \\ ); + ctx.c("exit with u8 parameter", linux_x64, + \\export fn _start() noreturn { + \\ exit(0); + \\} + \\ + \\fn exit(code: u8) noreturn { + \\ asm volatile ("syscall" + \\ : + \\ : [number] "{rax}" (231), + \\ [arg1] "{rdi}" (code) + \\ ); + \\ unreachable; + \\} + \\ + , + \\#include + \\#include + \\ + \\zig_noreturn void exit(uint8_t arg0); + \\ + \\const char *const exit__anon_0 = "{rax}"; + \\const char *const exit__anon_1 = "{rdi}"; + \\const char *const exit__anon_2 = "syscall"; + \\ + \\zig_noreturn void _start(void) { + \\ exit(0); + \\} + \\ + \\zig_noreturn void exit(uint8_t arg0) { + \\ register size_t rax_constant __asm__("rax") = 231; + \\ register size_t rdi_constant __asm__("rdi") = (size_t)arg0; + \\ __asm volatile ("syscall" :: ""(rax_constant), ""(rdi_constant)); + \\ zig_unreachable(); + \\} + \\ + ); } From 5a166cead80d4d77bffba0b116fdeffb5820f5a4 Mon Sep 17 00:00:00 2001 From: Noam Preil Date: Tue, 11 Aug 2020 10:24:32 -0400 Subject: [PATCH 7/9] CBE: fix handling of IR dependencies --- src-self-hosted/codegen/c.zig | 151 ++++++++++++++++++++++------------ src-self-hosted/link.zig | 2 +- test/stage2/cbe.zig | 3 +- 3 files changed, 102 insertions(+), 54 deletions(-) diff --git a/src-self-hosted/codegen/c.zig b/src-self-hosted/codegen/c.zig index 907bbccda1..76585a6dfb 100644 --- a/src-self-hosted/codegen/c.zig +++ b/src-self-hosted/codegen/c.zig @@ -94,6 +94,28 @@ fn genArray(file: *C, decl: *Decl) !void { return file.fail(decl.src(), "TODO non-byte arrays", .{}); } +const Context = struct { + file: *C, + decl: *Decl, + inst_map: std.AutoHashMap(*Inst, []u8), + argdex: usize = 0, + unnamed_index: usize = 0, + + fn name(self: *Context) ![]u8 { + const val = try std.fmt.allocPrint(self.file.base.allocator, "__temp_{}", .{self.unnamed_index}); + self.unnamed_index += 1; + return val; + } + + fn deinit(self: *Context) void { + for (self.inst_map.items()) |kv| { + self.file.base.allocator.free(kv.value); + } + self.inst_map.deinit(); + self.* = undefined; + } +}; + fn genFn(file: *C, decl: *Decl) !void { const writer = file.main.writer(); const tv = decl.typed_value.most_recent.typed_value; @@ -102,24 +124,31 @@ fn genFn(file: *C, decl: *Decl) !void { try writer.writeAll(" {"); + var ctx = Context{ + .file = file, + .decl = decl, + .inst_map = std.AutoHashMap(*Inst, []u8).init(file.base.allocator), + }; + defer ctx.deinit(); + const func: *Module.Fn = tv.val.cast(Value.Payload.Function).?.func; const instructions = func.analysis.success.instructions; - var argdex: usize = 0; if (instructions.len > 0) { try writer.writeAll("\n"); for (instructions) |inst| { - switch (inst.tag) { - .assembly => try genAsm(file, inst.castTag(.assembly).?, decl, &argdex), - .call => try genCall(file, inst.castTag(.call).?, decl), - .ret => try genRet(file, inst.castTag(.ret).?, decl, tv.ty.fnReturnType()), - .retvoid => try file.main.writer().print(" return;\n", .{}), - .arg => {}, - .dbg_stmt => try genDbgStmt(file, inst.castTag(.dbg_stmt).?, decl), - .breakpoint => try genBreak(file, inst.castTag(.breakpoint).?, decl), - .unreach => try genUnreach(file, inst.castTag(.unreach).?, decl), - // This will be handled correctly later? - .intcast => {}, + if (switch (inst.tag) { + .assembly => try genAsm(&ctx, inst.castTag(.assembly).?), + .call => try genCall(&ctx, inst.castTag(.call).?), + .ret => try genRet(&ctx, inst.castTag(.ret).?), + .retvoid => try genRetVoid(&ctx), + .arg => try genArg(&ctx), + .dbg_stmt => try genDbgStmt(&ctx, inst.castTag(.dbg_stmt).?), + .breakpoint => try genBreak(&ctx, inst.castTag(.breakpoint).?), + .unreach => try genUnreach(&ctx, inst.castTag(.unreach).?), + .intcast => try genIntCast(&ctx, inst.castTag(.intcast).?), else => |e| return file.fail(decl.src(), "TODO implement C codegen for {}", .{e}), + }) |name| { + try ctx.inst_map.putNoClobber(inst, name); } } } @@ -127,27 +156,40 @@ fn genFn(file: *C, decl: *Decl) !void { try writer.writeAll("}\n\n"); } -fn genRet(file: *C, inst: *Inst.UnOp, decl: *Decl, expected_return_type: Type) !void { - return file.fail(decl.src(), "TODO return {}", .{expected_return_type}); +fn genArg(ctx: *Context) !?[]u8 { + const name = try std.fmt.allocPrint(ctx.file.base.allocator, "arg{}", .{ctx.argdex}); + ctx.argdex += 1; + return name; } -fn genIntCast(file: *C, inst: *Inst.UnOp, decl: *Decl, argdex: *usize) !void { +fn genRetVoid(ctx: *Context) !?[]u8 { + try ctx.file.main.writer().print(" return;\n", .{}); + return null; +} + +fn genRet(ctx: *Context, inst: *Inst.UnOp) !?[]u8 { + return ctx.file.fail(ctx.decl.src(), "TODO return", .{}); +} + +fn genIntCast(ctx: *Context, inst: *Inst.UnOp) !?[]u8 { + if (inst.base.isUnused()) + return null; const op = inst.operand; - const writer = file.main.writer(); - try writer.writeByte('('); - try renderType(file, writer, inst.base.ty, decl.src()); - try writer.writeByte(')'); - if (op.castTag(.arg)) |_| { - try writer.print("arg{}", .{argdex.*}); - argdex.* += 1; - } else { - return file.fail(decl.src(), "TODO intcast {} to {}", .{ op, inst.base.ty }); - } + const writer = ctx.file.main.writer(); + const name = try ctx.name(); + const from = ctx.inst_map.get(op) orelse + return ctx.file.fail(ctx.decl.src(), "Internal error in C backend: intCast argument not found in inst_map", .{}); + try writer.writeAll(" const "); + try renderType(ctx.file, writer, inst.base.ty, ctx.decl.src()); + try writer.print(" {} = (", .{name}); + try renderType(ctx.file, writer, inst.base.ty, ctx.decl.src()); + try writer.print("){};\n", .{from}); + return name; } -fn genCall(file: *C, inst: *Inst.Call, decl: *Decl) !void { - const writer = file.main.writer(); - const header = file.header.writer(); +fn genCall(ctx: *Context, inst: *Inst.Call) !?[]u8 { + const writer = ctx.file.main.writer(); + const header = ctx.file.header.writer(); try writer.writeAll(" "); if (inst.func.castTag(.constant)) |func_inst| { if (func_inst.val.cast(Value.Payload.Function)) |func_val| { @@ -158,9 +200,9 @@ fn genCall(file: *C, inst: *Inst.Call, decl: *Decl) !void { try writer.print("(void)", .{}); } const tname = mem.spanZ(target.name); - if (file.called.get(tname) == null) { - try file.called.put(tname, void{}); - try renderFunctionSignature(file, header, target); + if (ctx.file.called.get(tname) == null) { + try ctx.file.called.put(tname, void{}); + try renderFunctionSignature(ctx.file, header, target); try header.writeAll(";\n"); } try writer.print("{}(", .{tname}); @@ -170,61 +212,65 @@ fn genCall(file: *C, inst: *Inst.Call, decl: *Decl) !void { try writer.writeAll(", "); } if (arg.cast(Inst.Constant)) |con| { - try renderValue(file, writer, con.val, decl.src()); + try renderValue(ctx.file, writer, con.val, ctx.decl.src()); } else { - return file.fail(decl.src(), "TODO call pass arg {}", .{arg}); + return ctx.file.fail(ctx.decl.src(), "TODO call pass arg {}", .{arg}); } } } try writer.writeAll(");\n"); } else { - return file.fail(decl.src(), "TODO non-function call target?", .{}); + return ctx.file.fail(ctx.decl.src(), "TODO non-function call target?", .{}); } } else { - return file.fail(decl.src(), "TODO non-constant call inst?", .{}); + return ctx.file.fail(ctx.decl.src(), "TODO non-constant call inst?", .{}); } + return null; } -fn genDbgStmt(file: *C, inst: *Inst.NoOp, decl: *Decl) !void { +fn genDbgStmt(ctx: *Context, inst: *Inst.NoOp) !?[]u8 { // TODO emit #line directive here with line number and filename + return null; } -fn genBreak(file: *C, inst: *Inst.NoOp, decl: *Decl) !void { +fn genBreak(ctx: *Context, inst: *Inst.NoOp) !?[]u8 { // TODO ?? + return null; } -fn genUnreach(file: *C, inst: *Inst.NoOp, decl: *Decl) !void { - try file.main.writer().writeAll(" zig_unreachable();\n"); +fn genUnreach(ctx: *Context, inst: *Inst.NoOp) !?[]u8 { + try ctx.file.main.writer().writeAll(" zig_unreachable();\n"); + return null; } -fn genAsm(file: *C, as: *Inst.Assembly, decl: *Decl, argdex: *usize) !void { - const writer = file.main.writer(); +fn genAsm(ctx: *Context, as: *Inst.Assembly) !?[]u8 { + const writer = ctx.file.main.writer(); try writer.writeAll(" "); for (as.inputs) |i, index| { if (i[0] == '{' and i[i.len - 1] == '}') { const reg = i[1 .. i.len - 1]; const arg = as.args[index]; try writer.writeAll("register "); - try renderType(file, writer, arg.ty, decl.src()); + try renderType(ctx.file, writer, arg.ty, ctx.decl.src()); try writer.print(" {}_constant __asm__(\"{}\") = ", .{ reg, reg }); + // TODO merge constant handling into inst_map as well if (arg.castTag(.constant)) |c| { - try renderValue(file, writer, c.val, decl.src()); - } else if (arg.castTag(.arg)) |inst| { - try writer.print("arg{}", .{argdex.*}); - argdex.* += 1; - } else if (arg.castTag(.intcast)) |inst| { - try genIntCast(file, inst, decl, argdex); + try renderValue(ctx.file, writer, c.val, ctx.decl.src()); + try writer.writeAll(";\n "); } else { - return file.fail(decl.src(), "TODO non-constant inline asm args ({})", .{arg.tag}); + const gop = try ctx.inst_map.getOrPut(arg); + if (!gop.found_existing) { + return ctx.file.fail(ctx.decl.src(), "Internal error in C backend: asm argument not found in inst_map", .{}); + } + try writer.print("{};\n ", .{gop.entry.value}); } - try writer.writeAll(";\n "); } else { - return file.fail(decl.src(), "TODO non-explicit inline asm regs", .{}); + return ctx.file.fail(ctx.decl.src(), "TODO non-explicit inline asm regs", .{}); } } try writer.print("__asm {} (\"{}\"", .{ if (as.is_volatile) @as([]const u8, "volatile") else "", as.asm_source }); if (as.output) |o| { - return file.fail(decl.src(), "TODO inline asm output", .{}); + return ctx.file.fail(ctx.decl.src(), "TODO inline asm output", .{}); } if (as.inputs.len > 0) { if (as.output == null) { @@ -246,4 +292,5 @@ fn genAsm(file: *C, as: *Inst.Assembly, decl: *Decl, argdex: *usize) !void { } } try writer.writeAll(");\n"); + return null; } diff --git a/src-self-hosted/link.zig b/src-self-hosted/link.zig index 28340a4024..06917cc490 100644 --- a/src-self-hosted/link.zig +++ b/src-self-hosted/link.zig @@ -229,7 +229,7 @@ pub const File = struct { return &c_file.base; } - pub fn fail(self: *C, src: usize, comptime format: []const u8, args: anytype) !void { + pub fn fail(self: *C, src: usize, comptime format: []const u8, args: anytype) anyerror { self.error_msg = try Module.ErrorMsg.create(self.base.allocator, src, format, args); return error.AnalysisFail; } diff --git a/test/stage2/cbe.zig b/test/stage2/cbe.zig index 4b35286f94..5e2d56b5ed 100644 --- a/test/stage2/cbe.zig +++ b/test/stage2/cbe.zig @@ -129,8 +129,9 @@ pub fn addCases(ctx: *TestContext) !void { \\} \\ \\zig_noreturn void exit(uint8_t arg0) { + \\ const size_t __temp_0 = (size_t)arg0; \\ register size_t rax_constant __asm__("rax") = 231; - \\ register size_t rdi_constant __asm__("rdi") = (size_t)arg0; + \\ register size_t rdi_constant __asm__("rdi") = __temp_0; \\ __asm volatile ("syscall" :: ""(rax_constant), ""(rdi_constant)); \\ zig_unreachable(); \\} From 1eb5aaa4b5bee902bed354ef6ebfbb643a624440 Mon Sep 17 00:00:00 2001 From: Noam Preil Date: Wed, 12 Aug 2020 22:15:09 -0400 Subject: [PATCH 8/9] CBE: renderValue pays attention to Type, not Tag --- src-self-hosted/codegen/c.zig | 80 ++++++++++++++++++----------------- src-self-hosted/value.zig | 75 ++++++++++++++++++++++++++++++++ 2 files changed, 116 insertions(+), 39 deletions(-) diff --git a/src-self-hosted/codegen/c.zig b/src-self-hosted/codegen/c.zig index 76585a6dfb..f0d3d8367a 100644 --- a/src-self-hosted/codegen/c.zig +++ b/src-self-hosted/codegen/c.zig @@ -17,41 +17,43 @@ fn map(allocator: *std.mem.Allocator, name: []const u8) ![]const u8 { return allocator.dupe(u8, name); } -fn renderType(file: *C, writer: std.ArrayList(u8).Writer, T: Type, src: usize) !void { - if (T.tag() == .usize) { - file.need_stddef = true; - try writer.writeAll("size_t"); - } else { - switch (T.zigTypeTag()) { - .NoReturn => { - try writer.writeAll("zig_noreturn void"); - }, - .Void => try writer.writeAll("void"), - .Int => { - if (T.tag() == .u8) { - file.need_stdint = true; - try writer.writeAll("uint8_t"); - } else { - return file.fail(src, "TODO implement int types", .{}); - } - }, - else => |e| return file.fail(src, "TODO implement type {}", .{e}), - } +fn renderType(ctx: *Context, writer: std.ArrayList(u8).Writer, T: Type) !void { + switch (T.zigTypeTag()) { + .NoReturn => { + try writer.writeAll("zig_noreturn void"); + }, + .Void => try writer.writeAll("void"), + .Int => { + if (T.tag() == .u8) { + ctx.file.need_stdint = true; + try writer.writeAll("uint8_t"); + } else if (T.tag() == .usize) { + ctx.file.need_stddef = true; + try writer.writeAll("size_t"); + } else { + return ctx.file.fail(ctx.decl.src(), "TODO implement int types", .{}); + } + }, + else => |e| return ctx.file.fail(ctx.decl.src(), "TODO implement type {}", .{e}), } } -fn renderValue(file: *C, writer: std.ArrayList(u8).Writer, val: Value, src: usize) !void { - switch (val.tag()) { - .int_u64 => return writer.print("{}", .{val.toUnsignedInt()}), - else => |e| return file.fail(src, "TODO implement value {}", .{e}), +fn renderValue(ctx: *Context, writer: std.ArrayList(u8).Writer, T: Type, val: Value) !void { + switch (T.zigTypeTag()) { + .Int => { + if (T.isSignedInt()) + return writer.print("{}", .{val.toSignedInt()}); + return writer.print("{}", .{val.toUnsignedInt()}); + }, + else => |e| return ctx.file.fail(ctx.decl.src(), "TODO implement value {}", .{e}), } } -fn renderFunctionSignature(file: *C, writer: std.ArrayList(u8).Writer, decl: *Decl) !void { +fn renderFunctionSignature(ctx: *Context, writer: std.ArrayList(u8).Writer, decl: *Decl) !void { const tv = decl.typed_value.most_recent.typed_value; - try renderType(file, writer, tv.ty.fnReturnType(), decl.src()); - const name = try map(file.base.allocator, mem.spanZ(decl.name)); - defer file.base.allocator.free(name); + try renderType(ctx, writer, tv.ty.fnReturnType()); + const name = try map(ctx.file.base.allocator, mem.spanZ(decl.name)); + defer ctx.file.base.allocator.free(name); try writer.print(" {}(", .{name}); var param_len = tv.ty.fnParamLen(); if (param_len == 0) @@ -62,7 +64,7 @@ fn renderFunctionSignature(file: *C, writer: std.ArrayList(u8).Writer, decl: *De if (index > 0) { try writer.writeAll(", "); } - try renderType(file, writer, tv.ty.fnParamType(index), decl.src()); + try renderType(ctx, writer, tv.ty.fnParamType(index)); try writer.print(" arg{}", .{index}); } } @@ -120,10 +122,6 @@ fn genFn(file: *C, decl: *Decl) !void { const writer = file.main.writer(); const tv = decl.typed_value.most_recent.typed_value; - try renderFunctionSignature(file, writer, decl); - - try writer.writeAll(" {"); - var ctx = Context{ .file = file, .decl = decl, @@ -131,6 +129,10 @@ fn genFn(file: *C, decl: *Decl) !void { }; defer ctx.deinit(); + try renderFunctionSignature(&ctx, writer, decl); + + try writer.writeAll(" {"); + const func: *Module.Fn = tv.val.cast(Value.Payload.Function).?.func; const instructions = func.analysis.success.instructions; if (instructions.len > 0) { @@ -180,9 +182,9 @@ fn genIntCast(ctx: *Context, inst: *Inst.UnOp) !?[]u8 { const from = ctx.inst_map.get(op) orelse return ctx.file.fail(ctx.decl.src(), "Internal error in C backend: intCast argument not found in inst_map", .{}); try writer.writeAll(" const "); - try renderType(ctx.file, writer, inst.base.ty, ctx.decl.src()); + try renderType(ctx, writer, inst.base.ty); try writer.print(" {} = (", .{name}); - try renderType(ctx.file, writer, inst.base.ty, ctx.decl.src()); + try renderType(ctx, writer, inst.base.ty); try writer.print("){};\n", .{from}); return name; } @@ -202,7 +204,7 @@ fn genCall(ctx: *Context, inst: *Inst.Call) !?[]u8 { const tname = mem.spanZ(target.name); if (ctx.file.called.get(tname) == null) { try ctx.file.called.put(tname, void{}); - try renderFunctionSignature(ctx.file, header, target); + try renderFunctionSignature(ctx, header, target); try header.writeAll(";\n"); } try writer.print("{}(", .{tname}); @@ -212,7 +214,7 @@ fn genCall(ctx: *Context, inst: *Inst.Call) !?[]u8 { try writer.writeAll(", "); } if (arg.cast(Inst.Constant)) |con| { - try renderValue(ctx.file, writer, con.val, ctx.decl.src()); + try renderValue(ctx, writer, arg.ty, con.val); } else { return ctx.file.fail(ctx.decl.src(), "TODO call pass arg {}", .{arg}); } @@ -251,11 +253,11 @@ fn genAsm(ctx: *Context, as: *Inst.Assembly) !?[]u8 { const reg = i[1 .. i.len - 1]; const arg = as.args[index]; try writer.writeAll("register "); - try renderType(ctx.file, writer, arg.ty, ctx.decl.src()); + try renderType(ctx, writer, arg.ty); try writer.print(" {}_constant __asm__(\"{}\") = ", .{ reg, reg }); // TODO merge constant handling into inst_map as well if (arg.castTag(.constant)) |c| { - try renderValue(ctx.file, writer, c.val, ctx.decl.src()); + try renderValue(ctx, writer, arg.ty, c.val); try writer.writeAll(";\n "); } else { const gop = try ctx.inst_map.getOrPut(arg); diff --git a/src-self-hosted/value.zig b/src-self-hosted/value.zig index e71805dc5b..b2fad9207d 100644 --- a/src-self-hosted/value.zig +++ b/src-self-hosted/value.zig @@ -568,6 +568,81 @@ pub const Value = extern union { } } + /// Asserts the value is an integer and it fits in a i64 + pub fn toSignedInt(self: Value) i64 { + switch (self.tag()) { + .ty, + .int_type, + .u8_type, + .i8_type, + .u16_type, + .i16_type, + .u32_type, + .i32_type, + .u64_type, + .i64_type, + .usize_type, + .isize_type, + .c_short_type, + .c_ushort_type, + .c_int_type, + .c_uint_type, + .c_long_type, + .c_ulong_type, + .c_longlong_type, + .c_ulonglong_type, + .c_longdouble_type, + .f16_type, + .f32_type, + .f64_type, + .f128_type, + .c_void_type, + .bool_type, + .void_type, + .type_type, + .anyerror_type, + .comptime_int_type, + .comptime_float_type, + .noreturn_type, + .null_type, + .undefined_type, + .fn_noreturn_no_args_type, + .fn_void_no_args_type, + .fn_naked_noreturn_no_args_type, + .fn_ccc_void_no_args_type, + .single_const_pointer_to_comptime_int_type, + .const_slice_u8_type, + .null_value, + .function, + .ref_val, + .decl_ref, + .elem_ptr, + .bytes, + .repeated, + .float_16, + .float_32, + .float_64, + .float_128, + .void_value, + .unreachable_value, + .empty_array, + => unreachable, + + .undef => unreachable, + + .zero, + .bool_false, + => return 0, + + .bool_true => return 1, + + .int_u64 => return @intCast(i64, self.cast(Payload.Int_i64).?.int), + .int_i64 => return self.cast(Payload.Int_i64).?.int, + .int_big_positive => return self.cast(Payload.IntBigPositive).?.asBigInt().to(i64) catch unreachable, + .int_big_negative => return self.cast(Payload.IntBigNegative).?.asBigInt().to(i64) catch unreachable, + } + } + pub fn toBool(self: Value) bool { return switch (self.tag()) { .bool_true => true, From eec53d67abb3a3d894de945f549994a16cb92474 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Wed, 12 Aug 2020 21:59:40 -0700 Subject: [PATCH 9/9] stage2: anyerror -> explicit error set --- src-self-hosted/link.zig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src-self-hosted/link.zig b/src-self-hosted/link.zig index 06917cc490..7c5e645fb5 100644 --- a/src-self-hosted/link.zig +++ b/src-self-hosted/link.zig @@ -229,7 +229,7 @@ pub const File = struct { return &c_file.base; } - pub fn fail(self: *C, src: usize, comptime format: []const u8, args: anytype) anyerror { + pub fn fail(self: *C, src: usize, comptime format: []const u8, args: anytype) error{AnalysisFail, OutOfMemory} { self.error_msg = try Module.ErrorMsg.create(self.base.allocator, src, format, args); return error.AnalysisFail; }