authorgravatar for robin@voetter.nlRobin Voetter <robin@voetter.nl> 2021-05-15 01:04:02+02:00
committergravatar for robin@voetter.nlRobin Voetter <robin@voetter.nl> 2021-05-16 14:13:23+02:00
logde6df2bc12c1cec81bb3c562a9395098c92d8239
treebb12821965274723ae2ddec27657650498967e9f
parent6461b9516371d22d347c27b5fcd2e8c22fafd03d

SPIR-V: Restructure codegen a bit


2 files changed, 68 insertions(+), 32 deletions(-)

src/codegen/spirv.zig+39-25
......@@ -6,6 +6,7 @@ const spec = @import("spirv/spec.zig");
66const Module = @import("../Module.zig");
77const Decl = Module.Decl;
88const Type = @import("../type.zig").Type;
9const LazySrcLoc = Module.LazySrcLoc;
910
1011pub const TypeMap = std.HashMap(Type, u32, Type.hash, Type.eql, std.hash_map.default_max_load_percentage);
1112
......@@ -15,30 +16,24 @@ pub fn writeInstruction(code: *std.ArrayList(u32), instr: spec.Opcode, args: []c
1516 try code.appendSlice(args);
1617}
1718
19/// This structure represents a SPIR-V binary module being compiled, and keeps track of relevant information
20/// such as code for the different logical sections, and the next result-id.
1821pub const SPIRVModule = struct {
19 next_result_id: u32 = 0,
20
21 target: std.Target,
22
23 types: TypeMap,
24
22 next_result_id: u32,
2523 types_and_globals: std.ArrayList(u32),
2624 fn_decls: std.ArrayList(u32),
2725
28 pub fn init(target: std.Target, allocator: *Allocator) SPIRVModule {
26 pub fn init(allocator: *Allocator) SPIRVModule {
2927 return .{
30 .target = target,
31 .types = TypeMap.init(allocator),
28 .next_result_id = 0,
3229 .types_and_globals = std.ArrayList(u32).init(allocator),
3330 .fn_decls = std.ArrayList(u32).init(allocator),
3431 };
3532 }
3633
3734 pub fn deinit(self: *SPIRVModule) void {
38 self.fn_decls.deinit();
3935 self.types_and_globals.deinit();
40 self.types.deinit();
41 self.* = undefined;
36 self.fn_decls.deinit();
4237 }
4338
4439 pub fn allocResultId(self: *SPIRVModule) u32 {
......@@ -49,21 +44,40 @@ pub const SPIRVModule = struct {
4944 pub fn resultIdBound(self: *SPIRVModule) u32 {
5045 return self.next_result_id;
5146 }
47};
48
49/// This structure is used to compile a declaration, and contains all relevant meta-information to deal with that.
50pub const DeclGen = struct {
51 module: *Module,
52 spv: *SPIRVModule,
53
54 types: TypeMap,
55
56 decl: *Decl,
57 error_msg: ?*Module.ErrorMsg,
58
59 fn fail(self: *DeclGen, src: LazySrcLoc, comptime format: []const u8, args: anytype) error{ AnalysisFail, OutOfMemory } {
60 @setCold(true);
61 const src_loc = src.toSrcLocWithDecl(self.decl);
62 self.error_msg = try Module.ErrorMsg.create(self.module.gpa, src_loc, format, args);
63 return error.AnalysisFail;
64 }
5265
53 pub fn getOrGenType(self: *SPIRVModule, t: Type) !u32 {
66 pub fn getOrGenType(self: *DeclGen, t: Type) !u32 {
5467 // We can't use getOrPut here so we can recursively generate types.
5568 if (self.types.get(t)) |already_generated| {
5669 return already_generated;
5770 }
5871
59 const result = self.allocResultId();
72 const result = self.spv.allocResultId();
6073
6174 switch (t.zigTypeTag()) {
62 .Void => try writeInstruction(&self.types_and_globals, .OpTypeVoid, &[_]u32{ result }),
63 .Bool => try writeInstruction(&self.types_and_globals, .OpTypeBool, &[_]u32{ result }),
75 .Void => try writeInstruction(&self.spv.types_and_globals, .OpTypeVoid, &[_]u32{ result }),
76 .Bool => try writeInstruction(&self.spv.types_and_globals, .OpTypeBool, &[_]u32{ result }),
6477 .Int => {
65 const int_info = t.intInfo(self.target);
66 try writeInstruction(&self.types_and_globals, .OpTypeInt, &[_]u32{
78 const int_info = t.intInfo(self.module.getTarget());
79 // TODO: Capabilities.
80 try writeInstruction(&self.spv.types_and_globals, .OpTypeInt, &[_]u32{
6781 result,
6882 int_info.bits,
6983 switch (int_info.signedness) {
......@@ -72,8 +86,8 @@ pub const SPIRVModule = struct {
7286 },
7387 });
7488 },
75 // TODO: Verify that floatBits() will be correct.
76 .Float => try writeInstruction(&self.types_and_globals, .OpTypeFloat, &[_]u32{ result, t.floatBits(self.target) }),
89 // TODO: Capabilities.
90 .Float => try writeInstruction(&self.spv.types_and_globals, .OpTypeFloat, &[_]u32{ result, t.floatBits(self.module.getTarget()) }),
7791 .Null,
7892 .Undefined,
7993 .EnumLiteral,
......@@ -84,23 +98,23 @@ pub const SPIRVModule = struct {
8498
8599 .BoundFn => unreachable, // this type will be deleted from the language.
86100
87 else => return error.TODO,
101 else => |tag| return self.fail(.{ .node_offset = 0 }, "TODO: SPIR-V backend: implement type with tag {}", .{ tag }),
88102 }
89103
90104 try self.types.put(t, result);
91105 return result;
92106 }
93107
94 pub fn gen(self: *SPIRVModule, decl: *Decl) !void {
95 const typed_value = decl.typed_value.most_recent.typed_value;
108 pub fn gen(self: *DeclGen) !void {
109 const typed_value = self.decl.typed_value.most_recent.typed_value;
96110
97111 switch (typed_value.ty.zigTypeTag()) {
98112 .Fn => {
99 log.debug("Generating code for function '{s}'", .{ std.mem.spanZ(decl.name) });
113 log.debug("Generating code for function '{s}'", .{ std.mem.spanZ(self.decl.name) });
100114
101115 _ = try self.getOrGenType(typed_value.ty.fnReturnType());
102116 },
103 else => return error.TODO,
117 else => |tag| return self.fail(.{ .node_offset = 0 }, "TODO: SPIR-V backend: generate decl with tag {}", .{ tag }),
104118 }
105119 }
106120};
src/link/SpirV.zig+29-7
......@@ -118,8 +118,8 @@ pub fn flushModule(self: *SpirV, comp: *Compilation) !void {
118118 const module = self.base.options.module.?;
119119 const target = comp.getTarget();
120120
121 var spirv_module = codegen.SPIRVModule.init(target, self.base.allocator);
122 defer spirv_module.deinit();
121 var spv = codegen.SPIRVModule.init(self.base.allocator);
122 defer spv.deinit();
123123
124124 // Allocate an ID for every declaration before generating code,
125125 // so that we can access them before processing them.
......@@ -132,19 +132,41 @@ pub fn flushModule(self: *SpirV, comp: *Compilation) !void {
132132 if (decl.typed_value != .most_recent)
133133 continue;
134134
135 decl.fn_link.spirv.id = spirv_module.allocResultId();
135 decl.fn_link.spirv.id = spv.allocResultId();
136136 log.debug("Allocating id {} to '{s}'", .{ decl.fn_link.spirv.id, std.mem.spanZ(decl.name) });
137137 }
138138 }
139139
140140 // Now, actually generate the code for all declarations.
141141 {
142 // We are just going to re-use this same DeclGen for every Decl, and we are just going to
143 // change the decl. Otherwise, we would have to keep a separate `types`, and re-construct this
144 // structure every time.
145 var decl_gen = codegen.DeclGen{
146 .module = module,
147 .spv = &spv,
148 .types = codegen.TypeMap.init(self.base.allocator),
149 .decl = undefined,
150 .error_msg = undefined,
151 };
152
153 defer decl_gen.types.deinit();
154
142155 for (module.decl_table.items()) |entry| {
143156 const decl = entry.value;
144157 if (decl.typed_value != .most_recent)
145158 continue;
146159
147 try spirv_module.gen(decl);
160 decl_gen.decl = decl;
161 decl_gen.error_msg = null;
162
163 decl_gen.gen() catch |err| switch (err) {
164 error.AnalysisFail => {
165 try module.failed_decls.put(module.gpa, decl, decl_gen.error_msg.?);
166 return;
167 },
168 else => |e| return e,
169 };
148170 }
149171 }
150172
......@@ -155,7 +177,7 @@ pub fn flushModule(self: *SpirV, comp: *Compilation) !void {
155177 spec.magic_number,
156178 (spec.version.major << 16) | (spec.version.minor << 8),
157179 0, // TODO: Register Zig compiler magic number.
158 spirv_module.resultIdBound(), // ID bound.
180 spv.resultIdBound(), // ID bound.
159181 0, // Schema (currently reserved for future use in the SPIR-V spec).
160182 });
161183
......@@ -166,8 +188,8 @@ pub fn flushModule(self: *SpirV, comp: *Compilation) !void {
166188 // follows the SPIR-V logical module format!
167189 var all_buffers = [_]std.os.iovec_const{
168190 wordsToIovConst(binary.items),
169 wordsToIovConst(spirv_module.types_and_globals.items),
170 wordsToIovConst(spirv_module.fn_decls.items),
191 wordsToIovConst(spv.types_and_globals.items),
192 wordsToIovConst(spv.fn_decls.items),
171193 };
172194
173195 const file = self.base.file.?;