authorgravatar for luuk@degram.devLuuk de Gram <luuk@degram.dev> 2021-01-26 19:47:15+01:00
committergravatar for luuk@degram.devLuuk de Gram <luuk@degram.dev> 2021-01-26 19:47:15+01:00
logcc46c1b9024beefdd82ce8abd07e8849a72db20c
tree5771573eccca912cd46fa1fb090cf57b71913989
parenta0d81caec99fe0d1cd803b0ba461b6e02829b476
signaturelock-open Commit is signed but in an unrecognized format.

Add tests, fix locals that are created in blocks like loops, and handle all breaks correctly


3 files changed, 146 insertions(+), 41 deletions(-)

src/codegen/wasm.zig+46-40
......@@ -163,11 +163,8 @@ pub const Context = struct {
163163 try self.genFunctype();
164164 const writer = self.code.writer();
165165
166 // Reserve space to write the size after generating the code
167 try self.code.resize(5);
168
169 // offset into 'code' section where we will put our locals count
170 var local_offset = self.code.items.len;
166 // Reserve space to write the size after generating the code as well as space for locals count
167 try self.code.resize(10);
171168
172169 // Write instructions
173170 // TODO: check for and handle death of instructions
......@@ -177,10 +174,10 @@ pub const Context = struct {
177174
178175 // finally, write our local types at the 'offset' position
179176 {
180 var totals_buffer: [5]u8 = undefined;
181 leb.writeUnsignedFixed(5, totals_buffer[0..5], @intCast(u32, self.locals.items.len));
182 try self.code.insertSlice(local_offset, &totals_buffer);
183 local_offset += 5;
177 leb.writeUnsignedFixed(5, self.code.items[5..10], @intCast(u32, self.locals.items.len));
178
179 // offset into 'code' section where we will put our locals types
180 var local_offset: usize = 10;
184181
185182 // emit the actual locals amount
186183 for (self.locals.items) |local| {
......@@ -285,8 +282,7 @@ pub const Context = struct {
285282 }
286283
287284 fn genLoad(self: *Context, inst: *Inst.UnOp) InnerError!WValue {
288 const operand = self.resolveInst(inst.operand);
289 return operand;
285 return self.resolveInst(inst.operand);
290286 }
291287
292288 fn genArg(self: *Context, inst: *Inst.Arg) InnerError!WValue {
......@@ -351,35 +347,49 @@ pub const Context = struct {
351347 fn genBlock(self: *Context, block: *Inst.Block) InnerError!WValue {
352348 const block_ty = try self.genBlockType(block.base.src, block.base.ty);
353349
350 try self.startBlock(.block, block_ty, null);
354351 block.codegen = .{
355352 // we don't use relocs, so using `relocs` is illegal behaviour.
356353 .relocs = undefined,
357 // Here we set the current block idx, so conditions know the depth to jump
358 // to when breaking out. This will be set to .none when it is found again within
359 // the same block
354 // Here we set the current block idx, so breaks know the depth to jump
355 // to when breaking out.
360356 .mcv = @bitCast(AnyMCValue, WValue{ .block_idx = self.block_depth }),
361357 };
358 try self.genBody(block.body);
359 try self.endBlock();
360
361 return .none;
362 }
363
364 /// appends a new wasm block to the code section and increases the `block_depth` by 1
365 fn startBlock(self: *Context, block_type: wasm.Opcode, valtype: u8, with_offset: ?usize) !void {
362366 self.block_depth += 1;
367 if (with_offset) |offset| {
368 try self.code.insert(offset, wasm.opcode(block_type));
369 try self.code.insert(offset + 1, valtype);
370 } else {
371 try self.code.append(wasm.opcode(block_type));
372 try self.code.append(valtype);
373 }
374 }
363375
364 try self.code.append(wasm.opcode(.block));
365 try self.code.append(block_ty);
366 try self.genBody(block.body);
376 /// Ends the current wasm block and decreases the `block_depth` by 1
377 fn endBlock(self: *Context) !void {
367378 try self.code.append(wasm.opcode(.end));
368
369379 self.block_depth -= 1;
370 return .none;
371380 }
372381
373382 fn genLoop(self: *Context, loop: *Inst.Loop) InnerError!WValue {
374383 const loop_ty = try self.genBlockType(loop.base.src, loop.base.ty);
375384
376 try self.code.append(wasm.opcode(.loop));
377 try self.code.append(loop_ty);
378 self.block_depth += 1;
385 try self.startBlock(.loop, loop_ty, null);
379386 try self.genBody(loop.body);
380 self.block_depth -= 1;
381387
382 try self.code.append(wasm.opcode(.end));
388 // breaking to the index of a loop block will continue the loop instead
389 try self.code.append(wasm.opcode(.br));
390 try leb.writeULEB128(self.code.writer(), @as(u32, 0));
391
392 try self.endBlock();
383393
384394 return .none;
385395 }
......@@ -388,23 +398,22 @@ pub const Context = struct {
388398 const condition = self.resolveInst(condbr.condition);
389399 const writer = self.code.writer();
390400
401 // TODO: Handle death instructions for then and else body
402
391403 // insert blocks at the position of `offset` so
392404 // the condition can jump to it
393405 const offset = condition.code_offset;
394 try self.code.insert(offset, wasm.opcode(.block));
395 try self.code.insert(offset, try self.genBlockType(condbr.base.src, condbr.base.ty));
406 const block_ty = try self.genBlockType(condbr.base.src, condbr.base.ty);
407 try self.startBlock(.block, block_ty, offset);
396408
397409 // we inserted the block in front of the condition
398410 // so now check if condition matches. If not, break outside this block
399 // and continue with the regular codepath
411 // and continue with the then codepath
400412 try writer.writeByte(wasm.opcode(.br_if));
401413 try leb.writeULEB128(writer, @as(u32, 0));
402414
403 // else body in case condition does not match
404415 try self.genBody(condbr.else_body);
405
406 // finally, tell wasm we have reached the end of the block we inserted above
407 try writer.writeByte(wasm.opcode(.end));
416 try self.endBlock();
408417
409418 // Outer block that matches the condition
410419 try self.genBody(condbr.then_body);
......@@ -417,7 +426,7 @@ pub const Context = struct {
417426
418427 // save offset, so potential conditions can insert blocks in front of
419428 // the comparison that we can later jump back to
420 const offset = self.code.items.len - 1;
429 const offset = self.code.items.len;
421430
422431 const lhs = self.resolveInst(inst.lhs);
423432 const rhs = self.resolveInst(inst.rhs);
......@@ -492,17 +501,14 @@ pub const Context = struct {
492501 try self.emitWValue(operand);
493502 }
494503
495 // if the block contains a block_idx, do a relative jump to it
496 // if `wvalue` was already 'consumed', simply break out of current block
504 // every block contains a `WValue` with its block index.
505 // We then determine how far we have to jump to it by substracting it from current block depth
497506 const wvalue = @bitCast(WValue, br.block.codegen.mcv);
498 const idx: u32 = if (wvalue == .block_idx) blk: {
499 br.block.codegen.mcv = @bitCast(AnyMCValue, WValue{ .none = {} });
500 break :blk self.block_depth - wvalue.block_idx;
501 } else 0;
502
507 const idx: u32 = self.block_depth - wvalue.block_idx;
503508 const writer = self.code.writer();
504509 try writer.writeByte(wasm.opcode(.br));
505510 try leb.writeULEB128(writer, idx);
506 return WValue.none;
511
512 return .none;
507513 }
508514};
src/link/Wasm.zig+8-1
......@@ -122,6 +122,13 @@ pub fn updateDecl(self: *Wasm, module: *Module, decl: *Module.Decl) !void {
122122 else => |e| return err,
123123 };
124124
125 // as locals are patched afterwards, the offsets of funcidx's are off,
126 // here we update them to correct them
127 for (decl.fn_link.wasm.?.idx_refs.items) |*func| {
128 // For each local, add 6 bytes (count + type)
129 func.offset += @intCast(u32, context.locals.items.len * 6);
130 }
131
125132 fn_data.functype = context.func_type_data.toUnmanaged();
126133 fn_data.code = context.code.toUnmanaged();
127134}
......@@ -238,7 +245,7 @@ pub fn flushModule(self: *Wasm, comp: *Compilation) !void {
238245 try writer.writeAll(fn_data.code.items[current..idx_ref.offset]);
239246 current = idx_ref.offset;
240247 // Use a fixed width here to make calculating the code size
241 // in codegen.wasm.genCode() simpler.
248 // in codegen.wasm.gen() simpler.
242249 var buf: [5]u8 = undefined;
243250 leb.writeUnsignedFixed(5, &buf, self.getFuncidx(idx_ref.decl).?);
244251 try writer.writeAll(&buf);
test/stage2/wasm.zig+92
......@@ -122,4 +122,96 @@ pub fn addCases(ctx: *TestContext) !void {
122122 \\}
123123 , "35\n");
124124 }
125
126 {
127 var case = ctx.exe("wasm conditions", wasi);
128
129 case.addCompareOutput(
130 \\export fn _start() u32 {
131 \\ var i: u32 = 5;
132 \\ if (i > @as(u32, 4)) {
133 \\ i += 10;
134 \\ }
135 \\ return i;
136 \\}
137 , "15\n");
138
139 case.addCompareOutput(
140 \\export fn _start() u32 {
141 \\ var i: u32 = 5;
142 \\ if (i < @as(u32, 4)) {
143 \\ i += 10;
144 \\ } else {
145 \\ i = 2;
146 \\ }
147 \\ return i;
148 \\}
149 , "2\n");
150
151 case.addCompareOutput(
152 \\export fn _start() u32 {
153 \\ var i: u32 = 5;
154 \\ if (i < @as(u32, 4)) {
155 \\ i += 10;
156 \\ } else if(i == @as(u32, 5)) {
157 \\ i = 20;
158 \\ }
159 \\ return i;
160 \\}
161 , "20\n");
162
163 case.addCompareOutput(
164 \\export fn _start() u32 {
165 \\ var i: u32 = 11;
166 \\ if (i < @as(u32, 4)) {
167 \\ i += 10;
168 \\ } else {
169 \\ if (i > @as(u32, 10)) {
170 \\ i += 20;
171 \\ } else {
172 \\ i = 20;
173 \\ }
174 \\ }
175 \\ return i;
176 \\}
177 , "31\n");
178 }
179
180 {
181 var case = ctx.exe("wasm while loops", wasi);
182
183 case.addCompareOutput(
184 \\export fn _start() u32 {
185 \\ var i: u32 = 0;
186 \\ while(i < @as(u32, 5)){
187 \\ i += 1;
188 \\ }
189 \\
190 \\ return i;
191 \\}
192 , "5\n");
193
194 case.addCompareOutput(
195 \\export fn _start() u32 {
196 \\ var i: u32 = 0;
197 \\ while(i < @as(u32, 10)){
198 \\ var x: u32 = 1;
199 \\ i += x;
200 \\ }
201 \\ return i;
202 \\}
203 , "10\n");
204
205 case.addCompareOutput(
206 \\export fn _start() u32 {
207 \\ var i: u32 = 0;
208 \\ while(i < @as(u32, 10)){
209 \\ var x: u32 = 1;
210 \\ i += x;
211 \\ if (i == @as(u32, 5)) break;
212 \\ }
213 \\ return i;
214 \\}
215 , "5\n");
216 }
125217}