aboutsummaryrefslogtreecommitdiff
path: root/src/link/SpirV.zig
blob: 03acf3c31e4cc5290fd55c1c4d95f09db5143f5c (plain)
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
const SpirV = @This();

const std = @import("std");
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;

const Module = @import("../Module.zig");
const Compilation = @import("../Compilation.zig");
const link = @import("../link.zig");
const codegen = @import("../codegen/spirv.zig");
const trace = @import("../tracy.zig").trace;
const build_options = @import("build_options");
const spec = @import("../codegen/spirv/spec.zig");

//! SPIR-V Spec documentation: https://www.khronos.org/registry/spir-v/specs/unified1/SPIRV.html
//! According to above documentation, a SPIR-V module has the following logical layout:
//! Header.
//! OpCapability instructions.
//! OpExtension instructions.
//! OpExtInstImport instructions.
//! A single OpMemoryModel instruction.
//! All entry points, declared with OpEntryPoint instructions.
//! All execution-mode declarators; OpExecutionMode and OpExecutionModeId instructions.
//! Debug instructions:
//! - First, OpString, OpSourceExtension, OpSource, OpSourceContinued (no forward references).
//! - OpName and OpMemberName instructions.
//! - OpModuleProcessed instructions.
//! All annotation (decoration) instructions.
//! All type declaration instructions, constant instructions, global variable declarations, (preferrably) OpUndef instructions.
//! All function declarations without a body (extern functions presumably).
//! All regular functions.

pub const FnData = struct {
    id: ?u32 = null,
    code: std.ArrayListUnmanaged(u32) = .{},
};

base: link.File,

// TODO: Does this file need to support multiple independent modules?
spirv_module: codegen.SPIRVModule = .{},

pub fn createEmpty(gpa: *Allocator, options: link.Options) !*SpirV {
    const spirv = try gpa.create(SpirV);
    spirv.* = .{
        .base = .{
            .tag = .spirv,
            .options = options,
            .file = null,
            .allocator = gpa,
        },
    };

    // TODO: Figure out where to put all of these
    switch (options.target.cpu.arch) {
        .spirv32, .spirv64 => {},
        else => return error.TODOArchNotSupported,
    }

    switch (options.target.os.tag) {
        .opencl, .glsl450, .vulkan => {},
        else => return error.TODOOsNotSupported,
    }

    if (options.target.abi != .none) {
        return error.TODOAbiNotSupported;
    }

    return spirv;
}

pub fn openPath(allocator: *Allocator, sub_path: []const u8, options: link.Options) !*SpirV {
    assert(options.object_format == .spirv);

    if (options.use_llvm) return error.LLVM_BackendIsTODO_ForSpirV; // TODO: LLVM Doesn't support SpirV at all.
    if (options.use_lld) return error.LLD_LinkingIsTODO_ForSpirV; // TODO: LLD Doesn't support SpirV at all.

    // TODO: read the file and keep vaild parts instead of truncating
    const file = try options.emit.?.directory.handle.createFile(sub_path, .{ .truncate = true, .read = true });
    errdefer file.close();

    const spirv = try createEmpty(allocator, options);
    errdefer spirv.base.destroy();

    spirv.base.file = file;
    return spirv;
}

pub fn deinit(self: *SpirV) void {
}

pub fn updateDecl(self: *SpirV, module: *Module, decl: *Module.Decl) !void {
    const tracy = trace(@src());
    defer tracy.end();

    const fn_data = &decl.fn_link.spirv;
    if (fn_data.id == null) {
        fn_data.id = self.spirv_module.allocId();
    }

    var managed_code = fn_data.code.toManaged(self.base.allocator);
    managed_code.items.len = 0;

    try self.spirv_module.genDecl(fn_data.id.?, &managed_code, decl);
    fn_data.code = managed_code.toUnmanaged();

    // Free excess allocated memory for this Decl.
    fn_data.code.shrinkAndFree(self.base.allocator, fn_data.code.items.len);
}

pub fn updateDeclExports(
    self: *SpirV,
    module: *Module,
    decl: *const Module.Decl,
    exports: []const *Module.Export,
) !void {}

pub fn freeDecl(self: *SpirV, decl: *Module.Decl) void {
    decl.fn_link.spirv.code.deinit(self.base.allocator);
    decl.fn_link.spirv = undefined;
}
pub fn flush(self: *SpirV, comp: *Compilation) !void {
    if (build_options.have_llvm and self.base.options.use_lld) {
        return error.LLD_LinkingIsTODO_ForSpirV; // TODO: LLD Doesn't support SpirV at all.
    } else {
        return self.flushModule(comp);
    }
}

pub fn flushModule(self: *SpirV, comp: *Compilation) !void {
    const tracy = trace(@src());
    defer tracy.end();

    const module = self.base.options.module.?;

    var binary = std.ArrayList(u32).init(self.base.allocator);
    defer binary.deinit();

    // Header
    {
        const header = [_]u32{
            spec.magic_number,
            (spec.version.major << 16) | (spec.version.minor << 8),
            0, // TODO: Register Zig compiler magic number.
            self.spirv_module.idBound(),
            0, // Schema (currently reserved for future use in the SPIR-V spec).
        };
        try binary.appendSlice(&header);
    }

    // Collect list of buffers to write.
    // SPIR-V files support both little and big endian words. The actual format is
    // disambiguated by the magic number, and so theoretically we don't need to worry
    // about endian-ness when writing the final binary.
    var all_buffers = std.ArrayList(std.os.iovec_const).init(self.base.allocator);
    defer all_buffers.deinit();

    // Pre-allocate enough for the binary info + all functions
    try all_buffers.ensureCapacity(module.decl_table.count() + 1);

    all_buffers.appendAssumeCapacity(wordsToIovConst(binary.items));

    // Functions
    for (module.decl_table.items()) |entry| {
        const decl = entry.value;
        switch (decl.typed_value) {
            .most_recent => |tvm| {
                const fn_data = &decl.fn_link.spirv;
                all_buffers.appendAssumeCapacity(wordsToIovConst(fn_data.code.items));
            },
            .never_succeeded => continue,
        }
    }

    var file_size: u64 = 0;
    for (all_buffers.items) |iov| {
        file_size += iov.iov_len;
    }

    const file = self.base.file.?;
    try file.seekTo(0);
    try file.setEndPos(file_size);
    try file.pwritevAll(all_buffers.items, 0);
}

fn wordsToIovConst(words: []const u32) std.os.iovec_const {
    const bytes = std.mem.sliceAsBytes(words);
    return .{
        .iov_base = bytes.ptr,
        .iov_len = bytes.len,
    };
}