diff --git a/src/compile.zig b/src/compile.zig index 52baea1..b393efe 100644 --- a/src/compile.zig +++ b/src/compile.zig @@ -528,6 +528,7 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void { const zv = stats.begin(.spirv); defer if (opts.spirv) zv.end(); if (opts.spirv) { + try zdxc.ir.inline_calls.runResourceReturns(m); zdxc.ir.split_resources.run(arena, m, &diags) catch |err| switch (err) { error.Unsupported => { try diags.render(&sm, ctx.stderr, .{ .format = opts.diag_format, .color = false }); diff --git a/src/dxcapi.zig b/src/dxcapi.zig index b068937..7cbd414 100644 --- a/src/dxcapi.zig +++ b/src/dxcapi.zig @@ -112,6 +112,8 @@ const IID_IDxcIncludeHandler = GUID.parse("7f61fc7d-950d-467f-b3e3-3c02fb49187c" const IID_IDxcOperationResult = GUID.parse("cedb484a-d4e9-445a-b991-ca21ca157dc2"); const IID_IDxcResult = GUID.parse("58346cda-dde7-4497-9461-6f87af5e0659"); const IID_IDxcCompiler3 = GUID.parse("228b4687-5a6a-4730-900c-9702b2203f54"); +const IID_IDxcCompiler = GUID.parse("8c210bf3-011f-4422-8d70-6f9acb8db617"); +const IID_IDxcCompiler2 = GUID.parse("a005a9d9-b8bb-4594-b5c9-0e633bec4d37"); const IID_IDxcUtils = GUID.parse("4605c4cb-2019-492a-ada4-65f20bb7d67f"); const IID_IDxcVersionInfo = GUID.parse("b04f5b50-2059-4f12-a8ff-a1e0cde1cc7e"); @@ -739,6 +741,18 @@ const Compiler3Vtbl = extern struct { Disassemble: *const fn (This, ?*const Buffer, *const GUID, ?Out) callconv(cc) HRESULT, }; +const DxcDefine = extern struct { Name: ?[*:0]const WCHAR, Value: ?[*:0]const WCHAR }; + +/// IDxcCompiler and IDxcCompiler2 (hassle-rs and other older clients): +/// entry point, profile and defines as parameters, the source as a blob. +const Compiler2Vtbl = extern struct { + unknown: UnknownVtbl, + Compile: *const fn (This, ?*anyopaque, ?[*:0]const WCHAR, ?[*:0]const WCHAR, ?[*:0]const WCHAR, ?[*]const ?[*:0]const WCHAR, u32, ?[*]const DxcDefine, u32, ?*anyopaque, ?Out) callconv(cc) HRESULT, + Preprocess: *const fn (This, ?*anyopaque, ?[*:0]const WCHAR, ?[*]const ?[*:0]const WCHAR, u32, ?[*]const DxcDefine, u32, ?*anyopaque, ?Out) callconv(cc) HRESULT, + Disassemble: *const fn (This, ?*anyopaque, ?Out) callconv(cc) HRESULT, + CompileWithDebug: *const fn (This, ?*anyopaque, ?[*:0]const WCHAR, ?[*:0]const WCHAR, ?[*:0]const WCHAR, ?[*]const ?[*:0]const WCHAR, u32, ?[*]const DxcDefine, u32, ?*anyopaque, ?Out, ?*?[*:0]WCHAR, ?Out) callconv(cc) HRESULT, +}; + const VersionInfoVtbl = extern struct { unknown: UnknownVtbl, GetVersion: *const fn (This, ?*u32, ?*u32) callconv(cc) HRESULT, @@ -748,8 +762,17 @@ const VersionInfoVtbl = extern struct { const Compiler = struct { compiler: Iface(Compiler3Vtbl) = .{ .vtbl = &compiler_vtbl }, version: Iface(VersionInfoVtbl) = .{ .vtbl = &version_vtbl }, + legacy: Iface(Compiler2Vtbl) = .{ .vtbl = &legacy_vtbl }, rc: RefCount = .{}, + const legacy_vtbl: Compiler2Vtbl = .{ + .unknown = .{ .QueryInterface = legacyQueryInterface, .AddRef = legacyAddRef, .Release = legacyRelease }, + .Compile = legacyCompile, + .Preprocess = legacyPreprocess, + .Disassemble = legacyDisassemble, + .CompileWithDebug = legacyCompileWithDebug, + }; + const compiler_vtbl: Compiler3Vtbl = .{ .unknown = .{ .QueryInterface = queryInterface, .AddRef = addRef, .Release = release }, .Compile = compileFn, @@ -770,6 +793,8 @@ const Compiler = struct { &c.compiler else if (iid.eql(IID_IDxcVersionInfo)) &c.version + else if (iid.eql(IID_IDxcCompiler) or iid.eql(IID_IDxcCompiler2)) + &c.legacy else null; if (p == null) { @@ -834,6 +859,85 @@ const Compiler = struct { _ = put(out, null); return E_NOTIMPL; } + + fn legacyOf(this: This) *Compiler { + return parent(Compiler, "legacy", this); + } + fn legacyQueryInterface(this: This, iid: *const GUID, out: ?Out) callconv(cc) HRESULT { + return legacyOf(this).query(iid, out); + } + fn legacyAddRef(this: This) callconv(cc) ULONG { + return legacyOf(this).rc.addRef(); + } + fn legacyRelease(this: This) callconv(cc) ULONG { + return release(&legacyOf(this).compiler); + } + + fn legacyCompile(_: This, source: ?*anyopaque, name: ?[*:0]const WCHAR, entry: ?[*:0]const WCHAR, profile: ?[*:0]const WCHAR, args: ?[*]const ?[*:0]const WCHAR, count: u32, defines: ?[*]const DxcDefine, define_count: u32, include: ?*anyopaque, out: ?Out) callconv(cc) HRESULT { + const p = profile orelse { + _ = put(out, null); + return E_INVALIDARG; + }; + return legacyRun(source, name, .{ .compile = .{ .entry = entry, .profile = p } }, args, count, defines, define_count, include, out); + } + fn legacyCompileWithDebug(this: This, source: ?*anyopaque, name: ?[*:0]const WCHAR, entry: ?[*:0]const WCHAR, profile: ?[*:0]const WCHAR, args: ?[*]const ?[*:0]const WCHAR, count: u32, defines: ?[*]const DxcDefine, define_count: u32, include: ?*anyopaque, out: ?Out, debug_name: ?*?[*:0]WCHAR, debug_blob: ?Out) callconv(cc) HRESULT { + // No separate debug blob (zdxc writes no PDBs). + if (debug_name) |d| d.* = null; + if (debug_blob) |d| d.* = null; + return legacyCompile(this, source, name, entry, profile, args, count, defines, define_count, include, out); + } + fn legacyPreprocess(_: This, source: ?*anyopaque, name: ?[*:0]const WCHAR, args: ?[*]const ?[*:0]const WCHAR, count: u32, defines: ?[*]const DxcDefine, define_count: u32, include: ?*anyopaque, out: ?Out) callconv(cc) HRESULT { + return legacyRun(source, name, .preprocess, args, count, defines, define_count, include, out); + } + fn legacyDisassemble(_: This, _: ?*anyopaque, out: ?Out) callconv(cc) HRESULT { + _ = put(out, null); + return E_NOTIMPL; + } + + const LegacyMode = union(enum) { + compile: struct { entry: ?[*:0]const WCHAR, profile: [*:0]const WCHAR }, + preprocess, + }; + + /// The legacy calls as IDxcCompiler3 arguments: `-E entry -T profile` + /// (or `-P`), the arguments, then `-D name=value` per define. + fn legacyRun(source: ?*anyopaque, name: ?[*:0]const WCHAR, mode: LegacyMode, args: ?[*]const ?[*:0]const WCHAR, count: u32, defines: ?[*]const DxcDefine, define_count: u32, include: ?*anyopaque, out: ?Out) HRESULT { + const o = out orelse return E_POINTER; + o.* = null; + const blob = source orelse return E_INVALIDARG; + if ((count > 0 and args == null) or (define_count > 0 and defines == null)) return E_INVALIDARG; + const r = runLegacy(blob, name, mode, if (args) |a| a[0..count] else &.{}, if (defines) |d| d[0..define_count] else &.{}, include) catch |e| return switch (e) { + error.OutOfMemory => E_OUTOFMEMORY, + error.InvalidArgument => E_INVALIDARG, + }; + o.* = &r.iface; + return S_OK; + } + + fn runLegacy(blob: *anyopaque, name: ?[*:0]const WCHAR, mode: LegacyMode, wargs: []const ?[*:0]const WCHAR, defines: []const DxcDefine, include: ?*anyopaque) error{ OutOfMemory, InvalidArgument }!*Result { + if (thread_arena == null) thread_arena = .init(gpa); + const arena = &thread_arena.?; + defer _ = arena.reset(.{ .retain_with_limit = retain_limit }); + const a = arena.allocator(); + var args: std.ArrayList([]const u8) = .empty; + switch (mode) { + .compile => |c| { + if (c.entry) |e| try args.appendSlice(a, &.{ "-E", try fromWide(a, e) }); + try args.appendSlice(a, &.{ "-T", try fromWide(a, c.profile) }); + }, + .preprocess => try args.append(a, "-P"), + } + for (wargs) |w| try args.append(a, try fromWide(a, w orelse return error.InvalidArgument)); + for (defines) |d| { + const n = try fromWide(a, d.Name orelse continue); + try args.appendSlice(a, &.{ "-D", if (d.Value) |v| try std.fmt.allocPrint(a, "{s}={s}", .{ n, try fromWide(a, v) }) else n }); + } + const text = Utils.blobText(a, blob) catch |e| return switch (e) { + error.OutOfMemory => error.OutOfMemory, + else => error.InvalidArgument, + }; + return runText(a, args.items, text, if (name) |n| try fromWide(a, n) else null, include); + } }; /// Each thread's compile arena, kept between calls. Freeing it per call @@ -851,11 +955,17 @@ fn run(source: *const Buffer, wargs: []const ?[*:0]const WCHAR, include: ?*anyop const args = try a.alloc([]const u8, wargs.len); for (args, wargs) |*d, w| d.* = try fromWide(a, w orelse return error.InvalidArgument); const bytes: []const u8 = if (source.ptr) |p| p[0..source.size] else &.{}; + return runText(a, args, try decodeText(a, bytes, source.encoding), null, include); +} + +/// A compile of `text` (in the caller's thread arena). +fn runText(a: std.mem.Allocator, args: []const []const u8, text: []const u8, source_name: ?[]const u8, include: ?*anyopaque) error{ OutOfMemory, InvalidArgument }!*Result { var client: ClientFs = undefined; var threaded: std.Io.Threaded = .init_single_threaded; var req: compile.Request = .{ .args = args, - .source = try decodeText(a, bytes, source.encoding), + .source = text, + .source_name = source_name, .io = threaded.io(), .fs = NoFs.fileSystem(), .compat_notes = false, diff --git a/src/front/parser.zig b/src/front/parser.zig index c74f9f0..e772cd0 100644 --- a/src/front/parser.zig +++ b/src/front/parser.zig @@ -41,6 +41,8 @@ pub const Parser = struct { /// Name of the struct most recently parsed by parseStructDeclInto /// (synthesized for anonymous structs), for `typedef struct ...`. last_struct_name: []const u8 = "", + /// The last parseType read `const` after the type (`float const x`). + type_const: bool = false, /// The qualifier words read by the last parseQualifiers call. last_quals: []const ast.QualWord = &.{}, /// Qualifier words for the next parseDeclaratorsInto call. @@ -410,6 +412,8 @@ pub const Parser = struct { fn skipTypeAttrs(p: *const Parser, start: usize) usize { var i = start; + // `T const`: a type qualifier written after the type. + while (p.toks[i].isIdent("const")) i += 1; if (!(p.toks[i].kind == .l_square and p.toks[i + 1].kind == .l_square)) return i; var depth: u32 = 0; while (true) : (i += 1) { @@ -565,10 +569,19 @@ pub const Parser = struct { t.pack_matrix = p.packMatrixAt(type_pos); if (norm != .none) t.norm = norm; if (words.items.len > 0) t.attr_words = words.items; + p.type_const = false; + while (p.eatIdent("const")) p.type_const = true; if (p.at(.l_square) and p.peek(1).kind == .l_square) t.attrs = try p.parseAttributes(); return t; } + /// parseType for a declaration: `const` after the type joins `quals`. + fn parseDeclType(p: *Parser, quals: *ast.Qualifiers) Error!*ast.TypeRef { + const t = try p.parseType(); + if (p.type_const) quals.@"const" = true; + return t; + } + fn parseTypeInner(p: *Parser) Error!*ast.TypeRef { // An elaborated type: `struct S` names S (declaring it if needed). const elaborated = (p.atIdent("struct") or p.atIdent("class")) and p.peek(1).kind == .identifier and p.peek(2).kind != .l_brace and p.peek(2).kind != .colon; @@ -835,9 +848,9 @@ pub const Parser = struct { return out.append(p.arena, d); } - const quals = p.parseQualifiers(); + var quals = p.parseQualifiers(); const words = p.last_quals; - const ty = try p.parseType(); + const ty = try p.parseDeclType(&quals); p.decl_quals = words; const first = out.items.len; try p.parseDeclaratorsInto(out, attrs, quals, template_params, ty, ctx); @@ -1299,9 +1312,9 @@ pub const Parser = struct { if (p.atIdent("void") and p.peek(1).kind == .r_paren) _ = p.advance(); while (!p.at(.r_paren)) { const pattrs = try p.parseAttributes(); - const pquals = p.parseQualifiers(); + var pquals = p.parseQualifiers(); const pwords = p.last_quals; - const pty = try p.parseType(); + const pty = try p.parseDeclType(&pquals); var pname: []const u8 = ""; var pname_loc = p.tok().loc; if (p.at(.identifier) and !isReserved(p.tok().text)) { @@ -1507,8 +1520,8 @@ pub const Parser = struct { /// `expr`, or `T name = init` (C++ condition declaration). fn parseCondition(p: *Parser) Error!struct { decl: ?*ast.Decl, cond: *ast.Expr } { if (!p.startsLocalDecl()) return .{ .decl = null, .cond = try p.parseExpr() }; - const quals = p.parseQualifiers(); - const ty = try p.parseType(); + var quals = p.parseQualifiers(); + const ty = try p.parseDeclType(&quals); const name = try p.expectIdent("variable name"); _ = try p.expect(.equal, "'='"); const init_expr = try p.parseAssign(); diff --git a/src/ir/inline.zig b/src/ir/inline.zig index 6d69561..a432bf8 100644 --- a/src/ir/inline.zig +++ b/src/ir/inline.zig @@ -20,6 +20,7 @@ const Allocator = std.mem.Allocator; const ir = @import("ir.zig"); const types = @import("../sema/types.zig"); const opt = @import("opt.zig"); +const split_resources = @import("split_resources.zig"); const Ref = ir.Ref; const BlockId = ir.BlockId; @@ -73,6 +74,41 @@ pub fn run(m: *ir.Module) Error!void { try markDead(m); } +/// Inlines only the calls of functions that return a resource or a struct +/// holding one, in every kind of module (ray-tracing libraries included), +/// before resources are split out of structs: what such a function +/// returns can be an element of a resource array picked by an index it +/// computes (`bindless[NonUniformResourceIndex(i)]`), which no function +/// signature can pass back. dxc's legalization inlines everything. +pub fn runResourceReturns(m: *ir.Module) Error!void { + const a = m.arena; + const n = m.functions.items.len; + const shapes = try a.alloc(?Shape, n); + var any = false; + for (m.functions.items, shapes) |f, *sh| { + sh.* = .keep; + if (!isResource(m.types, f.ret) and !split_resources.holdsResources(m.types, f.ret)) continue; + const shape = try shapeOf(a, m, f); + sh.* = shape; + if (shape != .keep) any = true; + } + if (!any) return; + const done = try a.alloc(bool, n); + @memset(done, false); + var work: std.ArrayList(u32) = .empty; + for (m.entries.items) |e| { + try work.append(a, e.wrapper); + if (e.patch_wrapper) |pw| try work.append(a, pw); + } + try work.appendSlice(a, m.exports.items); + while (work.pop()) |fi| { + if (done[fi]) continue; + done[fi] = true; + try inlineCalls(m, m.functions.items[fi], shapes, &work); + } + try markDead(m); +} + /// How a function returns, for inlining it. const Shape = union(enum) { /// Not inlinable. diff --git a/src/ir/ir.zig b/src/ir/ir.zig index 60aa17d..063679d 100644 --- a/src/ir/ir.zig +++ b/src/ir/ir.zig @@ -533,8 +533,9 @@ pub const SpirvExt = struct { pub const SpirvInst = struct { opcode: u32, set: ?[]const u8 = null, - /// Values, pointers (`[[vk::ext_reference]]`) or literal words. - operands: []const union(enum) { value: Ref, literal: u32, type: TypeId }, + /// Values, pointers (`[[vk::ext_reference]]`), literal words, types, + /// or the id of an OpString (printf's format). + operands: []const union(enum) { value: Ref, literal: u32, type: TypeId, string: []const u8 }, capabilities: []const u32 = &.{}, extensions: []const []const u8 = &.{}, }; diff --git a/src/ir/lower.zig b/src/ir/lower.zig index a9c82fd..2b53209 100644 --- a/src/ir/lower.zig +++ b/src/ir/lower.zig @@ -1565,6 +1565,16 @@ const Lowerer = struct { }; return result; } + // printf: NonSemantic.DebugPrintf's DebugPrintf (opcode 1) + // with the format as an OpString (SPIR-V only). + if (std.mem.eql(u8, name, "printf") and l.s.opts.spirv and args.len >= 1 and args[0].kind == .string_lit) { + const p = try l.arena.create(ir.SpirvInst); + const ops = try l.arena.alloc(@typeInfo(@TypeOf(p.operands)).pointer.child, args.len); + ops[0] = .{ .string = try stringContents(l.arena, args[0].kind.string_lit) }; + for (ops[1..], args[1..]) |*o, a| o.* = .{ .value = try l.converted(a, try l.concrete(a.ty)) }; + p.* = .{ .opcode = 1, .set = "NonSemantic.DebugPrintf", .operands = ops, .extensions = try l.arena.dupe([]const u8, &.{"SPV_KHR_non_semantic_info"}) }; + return l.b.add(.{ .op = .{ .spirv_inst = p }, .ty = TypeTable.void_type }); + } if (std.mem.eql(u8, name, "DispatchMesh") and args.len == 4) { // The payload goes by reference (a groupshared // variable). diff --git a/src/ir/opt.zig b/src/ir/opt.zig index d135021..e561dda 100644 --- a/src/ir/opt.zig +++ b/src/ir/opt.zig @@ -207,7 +207,7 @@ pub fn mapOp(a: Allocator, op: Op, ctx: anytype) Allocator.Error!Op { const ops = try a.dupe(@typeInfo(@TypeOf(x.operands)).pointer.child, x.operands); for (ops) |*o| switch (o.*) { .value => |*v| v.* = ctx.map(v.*), - .literal, .type => {}, + .literal, .type, .string => {}, }; const n = try a.create(ir.SpirvInst); n.* = x.*; @@ -278,7 +278,7 @@ pub fn eachOperand(op: Op, ctx: anytype) void { .heap_resource => |h| ctx.use(h.index), .spirv_inst => |x| for (x.operands) |o| switch (o) { .value => |v| ctx.use(v), - .literal, .type => {}, + .literal, .type, .string => {}, }, .patch_output => |x| ctx.use(x.value), .phi => |ps| for (ps) |pp| ctx.use(pp.value), diff --git a/src/ir/split_resources.zig b/src/ir/split_resources.zig index d5f4aa1..3179c23 100644 --- a/src/ir/split_resources.zig +++ b/src/ir/split_resources.zig @@ -189,6 +189,8 @@ const Pass = struct { if (info.done) return; info.done = true; const f = p.m.functions.items[fi]; + // (Inlined everywhere: not emitted.) + if (f.dead) return; // Callees first: their returns may be resources. for (f.insts.items) |inst| if (inst.op == .call) try p.function(inst.op.call.func); @@ -209,7 +211,10 @@ const Pass = struct { const n_old = f.insts.items.len; const ret_holds = holdsResources(p.t, f.ret) or isOpaque(p.t, f.ret); - for (f.blocks.items, 0..) |*blk, bi| { + // Definitions before uses: inlining leaves a call's continuation + // ahead of the callee's blocks. + for (try reversePostorder(p.a, f)) |bi| { + const blk = &f.blocks.items[bi]; var out: std.ArrayList(Ref) = .empty; for (blk.insts.items) |r| { const old = f.insts.items[r.index()]; @@ -421,7 +426,6 @@ const Pass = struct { .@"switch" => |sw| blk.term = .{ .@"switch" = .{ .value = mp.map(sw.value), .default = sw.default, .cases = sw.cases } }, else => {}, } - _ = bi; } _ = n_old; // What each out / inout resource holds when the function returns: @@ -480,6 +484,42 @@ const Pass = struct { } }; +/// `f`'s blocks in reverse postorder from the entry (each block after its +/// dominators), then any unreachable ones in list order. +fn reversePostorder(a: Allocator, f: *const ir.Function) Allocator.Error![]const u32 { + const n = f.blocks.items.len; + const seen = try a.alloc(bool, n); + @memset(seen, false); + var post: std.ArrayList(u32) = try .initCapacity(a, n); + // (block, whether its successors were pushed) + var stack: std.ArrayList(struct { b: u32, expanded: bool }) = .empty; + if (n > 0) try stack.append(a, .{ .b = 0, .expanded = false }); + while (stack.pop()) |it| { + if (it.expanded) { + post.appendAssumeCapacity(it.b); + continue; + } + if (seen[it.b]) continue; + seen[it.b] = true; + try stack.append(a, .{ .b = it.b, .expanded = true }); + const succs: []const ir.BlockId = switch (f.blocks.items[it.b].term) { + .br => |t| &.{t}, + .cond_br => |c| &.{ c.@"else", c.then }, + .@"switch" => |sw| blk: { + const out = try a.alloc(ir.BlockId, sw.cases.len + 1); + for (sw.cases, 0..) |c, i| out[sw.cases.len - 1 - i] = c.block; + out[sw.cases.len] = sw.default; + break :blk out; + }, + else => &.{}, + }; + for (succs) |sb| if (sb != .none and !seen[sb.index()]) try stack.append(a, .{ .b = @intCast(sb.index()), .expanded = false }); + } + std.mem.reverse(u32, post.items); + for (0..n) |bi| if (!seen[bi]) post.appendAssumeCapacity(@intCast(bi)); + return post.items; +} + /// Splits every function's resource-holding aggregates (SPIR-V only). pub fn run(a: Allocator, m: *ir.Module, diags: *diag.Diagnostics) Error!void { var any = false; diff --git a/src/sema/intrinsics.zig b/src/sema/intrinsics.zig index f0dba72..156a97d 100644 --- a/src/sema/intrinsics.zig +++ b/src/sema/intrinsics.zig @@ -197,6 +197,16 @@ const Bindings = struct { return null; } + /// Bind `name` to `v` unless it is bound to a smaller value. + fn lower(b: *Bindings, name: []const u8, v: u16) void { + if (std.fmt.parseInt(u16, name, 10)) |_| return else |_| {} + for (b.names[0..b.n], b.values[0..b.n]) |k, *old| if (std.mem.eql(u8, k, name)) { + old.* = @min(old.*, v); + return; + }; + _ = b.bind(name, v); + } + /// Bind or check; false on conflict. fn bind(b: *Bindings, name: []const u8, v: u16) bool { if (b.get(name)) |old| return old == v; @@ -298,6 +308,22 @@ fn matchOne(sema: anytype, it: *const table.Intrinsic, object: ?TypeId, args: [] const sh = t.shape(a.ty) orelse continue; if (bindings.any_shape == null or sh.count() > bindings.any_shape.?.count()) bindings.any_shape = sh; } + // A dimension shared by several arguments (`dot(numeric, + // numeric)`, mul's `numeric` and `numeric`) is the + // smallest one: dxc truncates the larger arguments (with a warning). + // Scalars splat and do not bind it. + for (args[0..it.params.len], 1..) |a, i| { + const ls = if (specs[i].dims.len > 0) specs[i] else specs[layout_group[i]]; + const sh = t.shape(a.ty) orelse continue; + switch (ls.dims.len) { + 1 => if (sh.kind == .vector) bindings.lower(ls.dims[0], sh.cols), + 2 => if (sh.kind == .matrix) { + bindings.lower(ls.dims[0], sh.rows); + bindings.lower(ls.dims[1], sh.cols); + }, + else => {}, + } + } var sum: u32 = 0; var worst: u32 = 0; const out_params = try sema.arena.alloc(bool, args.len); diff --git a/src/sema/sema.zig b/src/sema/sema.zig index 9fa2d52..c9844c4 100644 --- a/src/sema/sema.zig +++ b/src/sema/sema.zig @@ -99,6 +99,10 @@ pub const Param = struct { type: TypeId, dir: enum { in, out, inout }, has_default: bool, + /// A template instance's default argument that does not convert to + /// the parameter's type: an error only where a call uses it (C++ + /// instantiates default arguments on use). + bad_default: bool = false, /// `groupshared` parameter (SM 6.8 groupshared arguments). groupshared: bool = false, }; @@ -2521,7 +2525,16 @@ pub const Sema = struct { .has_default = p.init != null, .groupshared = p.quals.groupshared, }; - if (p.init) |init_e| _ = try s.checkInitializer(pt, init_e); + if (p.init) |init_e| { + if (s.instance_depth > 0) { + const m = s.diags.mark(); + _ = try s.checkInitializer(pt, init_e); + if (s.diags.error_count != m.errors) { + s.diags.rollback(m); + out.bad_default = true; + } + } else _ = try s.checkInitializer(pt, init_e); + } } const func = try s.arena.create(Function); func.* = .{ .name = name, .decl = f, .loc = d.loc, .ret = ret, .params = params, .defined = f.body != null, .owner = owner }; @@ -3843,7 +3856,17 @@ pub const Sema = struct { var explicit: ?TypeId = null; if (template_args.len > 0) explicit = try s.typeArg(template_args[0]); const r = try s.intrinsic_db.resolve(s, e.loc, if (s.opts.spirv and isVkQualified(callee)) "VkIntrinsics" else "Intrinsics", name, null, arg_types, explicit); - if (r.ok) s.record(e, .{ .intrinsic = .{ .index = r.index, .params = r.params } }); + if (r.ok) { + s.record(e, .{ .intrinsic = .{ .index = r.index, .params = r.params } }); + // `dot(float4, float3)`: the longer argument is truncated. + for (arg_types, r.params[0..@min(arg_types.len, r.params.len)], 0..) |a, pt, i| { + const as = s.types.shape(a.ty) orelse continue; + const ps = s.types.shape(pt) orelse continue; + if (as.kind == .scalar or ps.kind == .scalar or (ps.rows >= as.rows and ps.cols >= as.cols)) continue; + const loc = if (e.kind == .call and i < e.kind.call.args.len) startLoc(e.kind.call.args[i]) else a.loc; + s.warn(loc, "conversion", "implicit truncation of vector type", .{}); + } + } return rvalue(r.ret); } @@ -3897,6 +3920,10 @@ pub const Sema = struct { s.err(a.loc, "cannot bind non-lvalue argument to {s} parameter", .{if (f.params[i].dir == .out) "out" else "inout"}); } } + for (f.params[@min(args.len, f.params.len)..]) |p| if (p.bad_default) { + s.err(callee.loc, "cannot initialize a parameter of type '{s}' with its default argument", .{s.typeName(p.type)}); + return TypeTable.error_type; + }; if (s.current_fn) |caller| caller.callees.append(s.arena, f) catch {}; s.record(e, .{ .function = f }); s.ensureBody(f) catch {}; @@ -4138,6 +4165,9 @@ pub fn parseIntLiteral(text: []const u8) ?i64 { if (digits.len > 2 and digits[0] == '0' and (digits[1] == 'x' or digits[1] == 'X')) { base = 16; body = digits[2..]; + } else if (isBinaryLiteral(digits)) { + base = 2; + body = digits[2..]; } else if (digits.len > 1 and digits[0] == '0') { base = 8; body = digits[1..]; @@ -4157,6 +4187,11 @@ pub fn parseFloatLiteral(text: []const u8) ?f64 { /// dxc's `.#INF`): where the suffix starts and whether it is floating. fn scanLiteral(text: []const u8) struct { end: usize, float: bool, inf: bool = false } { var i: usize = 0; + if (isBinaryLiteral(text)) { + i = 2; + while (i < text.len and (text[i] == '0' or text[i] == '1')) i += 1; + return .{ .end = i, .float = false }; + } const hex = text.len > 1 and text[0] == '0' and (text[1] == 'x' or text[1] == 'X'); if (hex) i = 2; const isDigit = struct { @@ -4185,6 +4220,24 @@ fn scanLiteral(text: []const u8) struct { end: usize, float: bool, inf: bool = f return .{ .end = i, .float = float }; } +/// `0b101`: a binary integer literal (clang accepts them in HLSL). +/// Where an expression's text starts (clang's getBeginLoc): `i` in `i.T`. +fn startLoc(e: *const ast.Expr) Loc { + return switch (e.kind) { + .member => |m| startLoc(m.base), + .index => |x| startLoc(x.base), + .binary => |b| startLoc(b.lhs), + .assign => |b| startLoc(b.lhs), + .conditional => |c| startLoc(c.cond), + .call => |c| startLoc(c.callee), + else => e.loc, + }; +} + +fn isBinaryLiteral(text: []const u8) bool { + return text.len > 2 and text[0] == '0' and (text[1] == 'b' or text[1] == 'B') and (text[2] == '0' or text[2] == '1'); +} + /// `f16` / `f32` / `f64` (any case) at the end of a float literal. fn fixedFloatSuffix(text: []const u8) ?[]const u8 { if (text.len < 4) return null; diff --git a/src/spirv/builder.zig b/src/spirv/builder.zig index 3f02d15..7ef7880 100644 --- a/src/spirv/builder.zig +++ b/src/spirv/builder.zig @@ -10,6 +10,7 @@ pub const Id = u32; pub const Op = enum(u16) { undef = 1, source = 3, + string = 7, name = 5, member_name = 6, extension = 10, @@ -259,6 +260,8 @@ pub const Section = enum { memory_model, entry_points, execution_modes, + /// OpString (before OpSource and the names). + debug_strings, debug_names, annotations, types_globals, diff --git a/src/spirv/emit.zig b/src/spirv/emit.zig index c64105c..a2dadbf 100644 --- a/src/spirv/emit.zig +++ b/src/spirv/emit.zig @@ -202,6 +202,10 @@ const Emitter = struct { used_bindings: std.AutoHashMapUnmanaged(struct { u32, u32 }, void) = .empty, spec_ids: std.AutoHashMapUnmanaged(u32, Id) = .empty, ext_imports: std.StringHashMapUnmanaged(Id) = .empty, + string_ids: std.StringHashMapUnmanaged(Id) = .empty, + /// Reads of resource locals nothing assigns: the resource of the same + /// type each stands in with where it is used. + undef_resources: std.AutoHashMapUnmanaged(u32, Id) = .empty, /// Flattened resource arrays: a variable per element. flat_vars: std.AutoHashMapUnmanaged(u32, []const Id) = .empty, flat_iface: std.ArrayList(Id) = .empty, @@ -837,12 +841,30 @@ const Emitter = struct { .value => |r| e.val(r), .literal => |w| w, .type => |t| try e.typeId(t), + .string => |str| try e.stringId(str), }); const op: Op = if (x.set != null) .ext_inst else @enumFromInt(@as(u16, @intCast(x.opcode))); try e.b.emit(.functions, op, words.items); return id; } + /// A declared resource global of type `ty`. + fn anyGlobalOf(e: *Emitter, ty: TypeId) ?u32 { + for (e.m.globals.items, 0..) |g, gi| { + if (g.ty == ty and g.space == .resource and e.global_vars[gi] != 0) return @intCast(gi); + } + return null; + } + + /// An OpString of `str` (made once). + fn stringId(e: *Emitter, str: []const u8) Error!Id { + if (e.string_ids.get(str)) |id| return id; + const id = e.b.newId(); + try e.b.emitWithString(.debug_strings, .string, &.{id}, str, &.{}); + try e.string_ids.put(e.arena, str, id); + return id; + } + /// An OpExtInstImport of `name` (made once). fn extInstImport(e: *Emitter, name: []const u8) Error!Id { if (std.mem.eql(u8, name, "GLSL.std.450")) { @@ -2373,7 +2395,9 @@ const Emitter = struct { } fn val(e: *Emitter, r: Ref) Id { - return e.vals[r.index()]; + const v = e.vals[r.index()]; + if (v == 0) if (e.undef_resources.get(r.index())) |stand_in| return stand_in; + return v; } fn compOf(e: *Emitter, ty: TypeId) Scalar { @@ -2438,7 +2462,28 @@ const Emitter = struct { try e.indexed_loads.put(e.arena, @intCast(ri), .{ .global = il.global, .indices = idx, .types = il.index_types, .nonuniform = il.nonuniform }); return; } - if (e.val(p) == 0 and f.inst(p).op == .local_var) return e.unsupported("a resource local read before it is assigned", .{}); + if (e.val(p) == 0 and f.inst(p).op == .local_var) { + // A resource local nothing assigns (a struct copied + // with a resource member left unset, read where dxc's + // legalization folds the read away): its value is + // undefined, so any resource of its type will do. + // An OpUndef pointer would break logical addressing. + // Copies (`res = this`) pass the undefined value on + // without assigning it; the first real use takes the + // stand-in. + const only_copies = for (f.insts.items) |x| { + if (x.op != .store or x.op.store.ptr != p) continue; + const v = f.inst(x.op.store.value); + if (v.op != .load or f.inst(v.op.load).op != .local_var) break false; + } else true; + if (only_copies) if (e.anyGlobalOf(i.ty)) |g| { + if (e.spv_minor >= 4) try e.useVar(e.global_vars[g]); + e.vals[ri] = 0; + try e.undef_resources.put(e.arena, @intCast(ri), e.global_vars[g]); + return; + }; + return e.unsupported("a resource local read before it is assigned", .{}); + } e.vals[ri] = e.val(p); return; } @@ -2475,6 +2520,8 @@ const Emitter = struct { } return; } + // Copying an undefined resource assigns nothing. + if (target.op == .local_var and e.undef_resources.contains(s.value.index())) return; if (target.op == .local_var and isResourceType(e.t, target.ty)) { const old = e.vals[s.ptr.index()]; if (old != 0 and old != e.val(s.value)) return e.unsupported("assigning different resources to one variable is not supported yet", .{}); @@ -4278,12 +4325,20 @@ const Emitter = struct { } fn globalOf(e: *Emitter, r: Ref) ?u32 { + return e.globalOfDepth(r, 0); + } + + /// (Copies between resource locals can form cycles: give up after + /// `max_depth` steps.) + fn globalOfDepth(e: *Emitter, r: Ref, depth: u32) ?u32 { + const max_depth = 256; + if (depth > max_depth) return null; const i = e.f.inst(r); return switch (i.op) { .global => |g| g, - .load => |p| e.globalOf(p), + .load => |p| e.globalOfDepth(p, depth + 1), .local_var => for (e.f.insts.items) |inst| { - if (inst.op == .store and inst.op.store.ptr == r) break e.globalOf(inst.op.store.value); + if (inst.op == .store and inst.op.store.ptr == r) break e.globalOfDepth(inst.op.store.value, depth + 1); } else null, // A specialized parameter: the global it is bound to. .param => |pi| blk: {