authorgravatar for mail@isaacfreund.comIsaac Freund <mail@isaacfreund.com> 2020-08-19 01:48:09+02:00
committergravatar for mail@isaacfreund.comIsaac Freund <mail@isaacfreund.com> 2020-08-19 02:05:13+02:00
log6242ae35f37a6e67d9da514fa7a3508843515667
treea6c43da4312a4aba2d853908b5f6c1e4cb10bfe2
parentfe3aa4ccd0bc157e1dd9d84b7c57b0cb2f0a77a9
signaturelock-open Commit is signed but in an unrecognized format.

stage2/wasm: implement function calls

During codegen we do not yet know the indexes that will be used for called functions. Therefore, we store the offset into the in-memory code where the index is needed with a pointer to the Decl and use this data to insert the proper indexes while writing the binary in the flush function.

3 files changed, 110 insertions(+), 39 deletions(-)

src-self-hosted/codegen/wasm.zig+59-37
......@@ -62,58 +62,80 @@ pub fn genCode(buf: *ArrayList(u8), decl: *Decl) !void {
6262 // TODO: check for and handle death of instructions
6363 const tv = decl.typed_value.most_recent.typed_value;
6464 const mod_fn = tv.val.cast(Value.Payload.Function).?.func;
65 for (mod_fn.analysis.success.instructions) |inst| try genInst(writer, inst);
65 for (mod_fn.analysis.success.instructions) |inst| try genInst(buf, decl, inst);
6666
6767 // Write 'end' opcode
6868 try writer.writeByte(0x0B);
6969
7070 // Fill in the size of the generated code to the reserved space at the
7171 // beginning of the buffer.
72 leb.writeUnsignedFixed(5, buf.items[0..5], @intCast(u32, buf.items.len - 5));
72 const size = buf.items.len - 5 + decl.fn_link.wasm.?.idx_refs.items.len * 5;
73 leb.writeUnsignedFixed(5, buf.items[0..5], @intCast(u32, size));
7374}
7475
75fn genInst(writer: ArrayList(u8).Writer, inst: *Inst) !void {
76fn genInst(buf: *ArrayList(u8), decl: *Decl, inst: *Inst) !void {
7677 return switch (inst.tag) {
78 .call => genCall(buf, decl, inst.castTag(.call).?),
79 .constant => genConstant(buf, decl, inst.castTag(.constant).?),
7780 .dbg_stmt => {},
78 .ret => genRet(writer, inst.castTag(.ret).?),
81 .ret => genRet(buf, decl, inst.castTag(.ret).?),
82 .retvoid => {},
7983 else => error.TODOImplementMoreWasmCodegen,
8084 };
8185}
8286
83fn genRet(writer: ArrayList(u8).Writer, inst: *Inst.UnOp) !void {
84 switch (inst.operand.tag) {
85 .constant => {
86 const constant = inst.operand.castTag(.constant).?;
87 switch (inst.operand.ty.tag()) {
88 .u32 => {
89 try writer.writeByte(0x41); // i32.const
90 try leb.writeILEB128(writer, constant.val.toUnsignedInt());
91 },
92 .i32 => {
93 try writer.writeByte(0x41); // i32.const
94 try leb.writeILEB128(writer, constant.val.toSignedInt());
95 },
96 .u64 => {
97 try writer.writeByte(0x42); // i64.const
98 try leb.writeILEB128(writer, constant.val.toUnsignedInt());
99 },
100 .i64 => {
101 try writer.writeByte(0x42); // i64.const
102 try leb.writeILEB128(writer, constant.val.toSignedInt());
103 },
104 .f32 => {
105 try writer.writeByte(0x43); // f32.const
106 // TODO: enforce LE byte order
107 try writer.writeAll(mem.asBytes(&constant.val.toFloat(f32)));
108 },
109 .f64 => {
110 try writer.writeByte(0x44); // f64.const
111 // TODO: enforce LE byte order
112 try writer.writeAll(mem.asBytes(&constant.val.toFloat(f64)));
113 },
114 else => return error.TODOImplementMoreWasmCodegen,
115 }
87fn genConstant(buf: *ArrayList(u8), decl: *Decl, inst: *Inst.Constant) !void {
88 const writer = buf.writer();
89 switch (inst.base.ty.tag()) {
90 .u32 => {
91 try writer.writeByte(0x41); // i32.const
92 try leb.writeILEB128(writer, inst.val.toUnsignedInt());
93 },
94 .i32 => {
95 try writer.writeByte(0x41); // i32.const
96 try leb.writeILEB128(writer, inst.val.toSignedInt());
97 },
98 .u64 => {
99 try writer.writeByte(0x42); // i64.const
100 try leb.writeILEB128(writer, inst.val.toUnsignedInt());
101 },
102 .i64 => {
103 try writer.writeByte(0x42); // i64.const
104 try leb.writeILEB128(writer, inst.val.toSignedInt());
116105 },
106 .f32 => {
107 try writer.writeByte(0x43); // f32.const
108 // TODO: enforce LE byte order
109 try writer.writeAll(mem.asBytes(&inst.val.toFloat(f32)));
110 },
111 .f64 => {
112 try writer.writeByte(0x44); // f64.const
113 // TODO: enforce LE byte order
114 try writer.writeAll(mem.asBytes(&inst.val.toFloat(f64)));
115 },
116 .void => {},
117117 else => return error.TODOImplementMoreWasmCodegen,
118118 }
119119}
120
121fn genRet(buf: *ArrayList(u8), decl: *Decl, inst: *Inst.UnOp) !void {
122 try genInst(buf, decl, inst.operand);
123}
124
125fn genCall(buf: *ArrayList(u8), decl: *Decl, inst: *Inst.Call) !void {
126 const func_inst = inst.func.castTag(.constant).?;
127 const func_val = func_inst.val.cast(Value.Payload.Function).?;
128 const target = func_val.func.owner_decl;
129 const target_ty = target.typed_value.most_recent.typed_value.ty;
130
131 if (inst.args.len != 0) return error.TODOImplementMoreWasmCodegen;
132
133 try buf.append(0x10); // call
134
135 // The function index immediate argument will be filled in using this data
136 // in link.Wasm.flush().
137 try decl.fn_link.wasm.?.idx_refs.append(buf.allocator, .{
138 .offset = @intCast(u32, buf.items.len),
139 .decl = target,
140 });
141}
src-self-hosted/link/Wasm.zig+25-1
......@@ -36,6 +36,9 @@ pub const FnData = struct {
3636 functype: std.ArrayListUnmanaged(u8) = .{},
3737 /// Generated code for the body of the function
3838 code: std.ArrayListUnmanaged(u8) = .{},
39 /// Locations in the generated code where function indexes must be filled in.
40 /// This must be kept ordered by offset.
41 idx_refs: std.ArrayListUnmanaged(struct { offset: u32, decl: *Module.Decl }) = .{},
3942};
4043
4144base: link.File,
......@@ -74,6 +77,7 @@ pub fn deinit(self: *Wasm) void {
7477 for (self.funcs.items) |decl| {
7578 decl.fn_link.wasm.?.functype.deinit(self.base.allocator);
7679 decl.fn_link.wasm.?.code.deinit(self.base.allocator);
80 decl.fn_link.wasm.?.idx_refs.deinit(self.base.allocator);
7781 }
7882 self.funcs.deinit(self.base.allocator);
7983}
......@@ -87,6 +91,7 @@ pub fn updateDecl(self: *Wasm, module: *Module, decl: *Module.Decl) !void {
8791 if (decl.fn_link.wasm) |*fn_data| {
8892 fn_data.functype.items.len = 0;
8993 fn_data.code.items.len = 0;
94 fn_data.idx_refs.items.len = 0;
9095 } else {
9196 decl.fn_link.wasm = .{};
9297 try self.funcs.append(self.base.allocator, decl);
......@@ -114,6 +119,7 @@ pub fn freeDecl(self: *Wasm, decl: *Module.Decl) void {
114119 _ = self.funcs.swapRemove(self.getFuncidx(decl).?);
115120 decl.fn_link.wasm.?.functype.deinit(self.base.allocator);
116121 decl.fn_link.wasm.?.code.deinit(self.base.allocator);
122 decl.fn_link.wasm.?.idx_refs.deinit(self.base.allocator);
117123 decl.fn_link.wasm = null;
118124}
119125
......@@ -190,7 +196,25 @@ pub fn flush(self: *Wasm, module: *Module) !void {
190196 // Code section
191197 {
192198 const header_offset = try reserveVecSectionHeader(file);
193 for (self.funcs.items) |decl| try file.writeAll(decl.fn_link.wasm.?.code.items);
199 const writer = file.writer();
200 for (self.funcs.items) |decl| {
201 const fn_data = &decl.fn_link.wasm.?;
202
203 // Write the already generated code to the file, inserting
204 // function indexes where required.
205 var current: u32 = 0;
206 for (fn_data.idx_refs.items) |idx_ref| {
207 try writer.writeAll(fn_data.code.items[current..idx_ref.offset]);
208 current = idx_ref.offset;
209 // Use a fixed width here to make calculating the code size
210 // in codegen.wasm.genCode() simpler.
211 var buf: [5]u8 = undefined;
212 leb.writeUnsignedFixed(5, &buf, self.getFuncidx(idx_ref.decl).?);
213 try writer.writeAll(&buf);
214 }
215
216 try writer.writeAll(fn_data.code.items[current..]);
217 }
194218 try writeVecSectionHeader(
195219 file,
196220 header_offset,
test/stage2/compare_output.zig+26-1
......@@ -546,28 +546,53 @@ pub fn addCases(ctx: *TestContext) !void {
546546 }
547547
548548 {
549 var case = ctx.exe("wasm returns", wasi);
549 var case = ctx.exe("wasm function calls", wasi);
550550
551551 case.addCompareOutput(
552552 \\export fn _start() u32 {
553 \\ foo();
554 \\ bar();
553555 \\ return 42;
554556 \\}
557 \\fn foo() void {
558 \\ bar();
559 \\ bar();
560 \\}
561 \\fn bar() void {}
555562 ,
556563 "42\n",
557564 );
558565
559566 case.addCompareOutput(
560567 \\export fn _start() i64 {
568 \\ bar();
569 \\ foo();
570 \\ foo();
571 \\ bar();
572 \\ foo();
573 \\ bar();
561574 \\ return 42;
562575 \\}
576 \\fn foo() void {
577 \\ bar();
578 \\}
579 \\fn bar() void {}
563580 ,
564581 "42\n",
565582 );
566583
567584 case.addCompareOutput(
568585 \\export fn _start() f32 {
586 \\ bar();
587 \\ foo();
569588 \\ return 42.0;
570589 \\}
590 \\fn foo() void {
591 \\ bar();
592 \\ bar();
593 \\ bar();
594 \\}
595 \\fn bar() void {}
571596 ,
572597 // This is what you get when you take the bits of the IEE-754
573598 // representation of 42.0 and reinterpret them as an unsigned