1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
|
const std = @import("std");
const Allocator = std.mem.Allocator;
const root = @import("root");
const Token = root.Lexer.Token;
const parse = root.parse;
const Location = root.Lexer.Location;
pub const VReg = enum(u32) { _ };
pub const BlockRef = enum(u32) { _ };
pub const Instr = struct {
loc: Location,
type: Type,
pub const Type = union(enum) {
constant: Constant,
bin_op: BinOp,
proc_call: ProcCall,
branch: Branch,
jump: Jump,
exit: Exit,
};
pub const Constant = struct {
dest: VReg,
value: u64,
pub fn sources(_: Constant) Sources {
return Sources.init(0) catch unreachable;
}
};
pub const BinOp = struct {
dest: VReg,
lhs: VReg,
rhs: VReg,
op: Op,
const Op = enum {
add,
sub,
};
pub fn sources(self: BinOp) Sources {
return Sources.fromSlice(&.{ self.lhs, self.rhs }) catch unreachable;
}
};
pub const ProcCall = struct {
dest: VReg,
arg: VReg,
proc: Proc,
const Proc = enum {
print,
read_int,
};
pub fn sources(self: ProcCall) Sources {
return Sources.fromSlice(&.{self.arg}) catch unreachable;
}
};
pub const Branch = struct {
cond: VReg,
true: BlockRef,
false: BlockRef,
pub fn sources(self: Branch) Sources {
return Sources.fromSlice(&.{self.cond}) catch unreachable;
}
};
pub const Jump = struct {
to: BlockRef,
pub fn sources(_: Jump) Sources {
return Sources.init(0) catch unreachable;
}
};
pub const Exit = struct {
pub fn sources(_: Exit) Sources {
return Sources.init(0) catch unreachable;
}
};
pub fn sources(self: Instr) Sources {
return switch (self.type) {
inline else => |instr| instr.sources(),
};
}
pub fn dest(self: *const Instr) ?VReg {
return switch (self.type) {
inline .constant, .bin_op, .proc_call => |s| s.dest,
.branch, .jump, .exit => null,
};
}
pub const Sources = std.BoundedArray(VReg, 2);
pub fn format(self: Instr, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
_ = .{ fmt, options };
switch (self.type) {
.constant => |constant| try writer.print(
"%{} = {}",
.{ @intFromEnum(constant.dest), constant.value },
),
.bin_op => |bin_op| try writer.print(
"%{} = %{} {s} %{}",
.{
@intFromEnum(bin_op.dest),
@intFromEnum(bin_op.lhs),
@tagName(bin_op.op),
@intFromEnum(bin_op.rhs),
},
),
.proc_call => |proc_call| try writer.print(
"%{} = {s} %{}",
.{
@intFromEnum(proc_call.dest),
@tagName(proc_call.proc),
@intFromEnum(proc_call.arg),
},
),
.branch => |branch| try writer.print(
"branch %{} ? ${} : ${}",
.{
@intFromEnum(branch.cond),
@intFromEnum(branch.true),
@intFromEnum(branch.false),
},
),
.jump => |jump| try writer.print("jump ${}", .{@intFromEnum(jump.to)}),
.exit => |_| try writer.print("exit", .{}),
}
}
};
pub const Procedure = struct {
blocks: []BasicBlock,
fn init(allocator: Allocator, blocks: []BasicBlock) !Procedure {
for (blocks) |*block| {
try block.finalize(allocator);
}
return .{ .blocks = blocks };
}
};
pub const BasicBlock = struct {
// arguments: []Reg,
instrs: std.ArrayListUnmanaged(Instr) = .empty,
vreg_last_use: std.AutoHashMapUnmanaged(VReg, usize) = .empty,
fn finalize(self: *BasicBlock, allocator: Allocator) !void {
self.vreg_last_use = .empty;
for (0.., self.instrs.items) |i, instr| {
for (instr.sources().slice()) |src|
try self.vreg_last_use.put(allocator, src, i);
if (instr.dest()) |dest|
try self.vreg_last_use.put(allocator, dest, i);
}
}
};
pub fn compile(allocator: Allocator, source: []const u8, block: parse.Block) !Procedure {
var ctx: CompileContext = .{
.allocator = allocator,
.source = source,
.register_counter = 0,
.scope = .{ .locals = .empty, .parent = null },
.blocks = .empty,
.current_block = @enumFromInt(0),
};
try ctx.compileBlock(block);
try ctx.addInstr(.{
.loc = .{ .start = 0, .end = 0 },
.type = .{ .exit = .{} },
});
return try .init(allocator, try ctx.blocks.toOwnedSlice(allocator));
}
const CompileError = error{
OutOfMemory,
CanOnlyCallIdentifiers,
UnknownProcedure,
UnknownVariable,
};
const CompileContext = struct {
allocator: Allocator,
source: []const u8,
register_counter: u32,
scope: Scope,
blocks: std.ArrayListUnmanaged(BasicBlock),
current_block: BlockRef,
// instrs: std.ArrayListUnmanaged(Instr),
const Scope = struct {
locals: std.StringHashMapUnmanaged(VReg),
parent: ?*Scope,
};
fn compileBlock(self: *CompileContext, block: parse.Block) !void {
_ = try self.switchToNewBlock();
var parent = self.scope;
self.scope = .{
.locals = .empty,
.parent = &parent,
};
for (block.stmts) |stmt| {
try self.compileStmt(stmt);
}
self.scope.locals.deinit(self.allocator);
self.scope = parent;
}
fn compileStmt(self: *CompileContext, stmt: parse.Stmt) CompileError!void {
switch (stmt.type) {
.expr => |expr| _ = try self.compileExpr(expr),
.block => |block| {
const curr = self.current_block;
const after = try self.switchToNewBlock();
try self.compileBlock(block);
const b = self.current_block;
try self.addInstr(.{
.loc = stmt.loc,
.type = .{ .jump = .{ .to = after } },
});
self.current_block = curr;
try self.addInstr(.{
.loc = stmt.loc,
.type = .{ .jump = .{ .to = b } },
});
self.current_block = after;
},
.declare_var => |declare_var| {
const val = try self.compileExpr(declare_var.value);
const name = declare_var.ident.getIdent(self.source);
try self.scope.locals.put(self.allocator, name, val);
},
}
}
fn compileExpr(self: *CompileContext, expr: *const parse.Expr) !VReg {
// This is not used by all expression types, but creating an unused virtual register is not a problem.
const dest = self.register();
switch (expr.type) {
.integer_literal => try self.addInstr(.{
.loc = expr.loc,
.type = .{ .constant = .{ .dest = dest, .value = expr.loc.getInt(self.source) } },
}),
.bin_op => |binop| {
const lhs = try self.compileExpr(binop.lhs);
const rhs = try self.compileExpr(binop.rhs);
try self.addInstr(.{
.loc = expr.loc,
.type = .{
.bin_op = .{
.dest = dest,
.lhs = lhs,
.rhs = rhs,
.op = switch (binop.op) {
.plus => .add,
.minus => .sub,
},
},
},
});
},
.call => |call| {
if (call.proc.type != .identifier) return error.CanOnlyCallIdentifiers;
const proc = std.meta.stringToEnum(Instr.ProcCall.Proc, call.proc.loc.getIdent(self.source)) orelse return error.UnknownProcedure;
const arg = try self.compileExpr(call.arg);
try self.addInstr(.{
.loc = expr.loc,
.type = .{ .proc_call = .{
.dest = dest,
.arg = arg,
.proc = proc,
} },
});
},
.identifier => {
var scope: ?*Scope = &self.scope;
while (scope) |s| : (scope = s.parent) {
if (s.locals.get(expr.loc.getIdent(self.source))) |reg| {
return reg;
}
}
return error.UnknownVariable;
},
.@"if" => |@"if"| {
const cond = try self.compileExpr(@"if".cond);
const curr = self.current_block;
const after = try self.switchToNewBlock();
try self.compileBlock(@"if".then);
try self.addInstr(.{
.loc = expr.loc,
.type = .{ .jump = .{ .to = after } },
});
const t = self.current_block;
const f = if (@"if".@"else") |@"else"| blk: {
try self.compileBlock(@"else");
try self.addInstr(.{
.loc = expr.loc,
.type = .{ .jump = .{ .to = after } },
});
break :blk self.current_block;
} else after;
self.current_block = curr;
try self.addInstr(.{
.loc = expr.loc,
.type = .{ .branch = .{
.cond = cond,
.true = t,
.false = f,
} },
});
self.current_block = after;
},
}
return dest;
}
fn switchToNewBlock(self: *CompileContext) !BlockRef {
const ref: BlockRef = @enumFromInt(self.blocks.items.len);
try self.blocks.append(self.allocator, .{});
self.current_block = ref;
return ref;
}
fn addInstr(self: *CompileContext, instr: Instr) !void {
try self.blocks.items[@intFromEnum(self.current_block)]
.instrs.append(self.allocator, instr);
}
fn register(self: *CompileContext) VReg {
const reg: VReg = @enumFromInt(self.register_counter);
self.register_counter += 1;
return reg;
}
};
|