Open engine corpora: kajiya and Sascha Willems' samples

Fixes from replaying kajiya's and SaschaWillems/Vulkan's HLSL through the
drop-in against dxc 1.7.2308:

- parser: `const` after the type (`float const x`, `uint const pass`)
  joins the declaration's qualifiers.
- sema: binary integer literals (`0b10u`).
- sema: a function template instance's default argument that does not
  convert to its parameter is an error only at a call that uses it, as
  C++ instantiates defaults on use.
- intrinsics: a dimension several arguments share (`dot`'s `numeric<c>`,
  `mul`'s `<r, c>`) takes the smallest argument's value; longer arguments
  are truncated with dxc's -Wconversion warning at the argument.
  `float4 a = mul(float3x3, float4)` is now rejected, as in dxc.
- SPIR-V: calls of functions returning resources (or structs holding
  them) are inlined before resources are split out of structs, in every
  stage; the splitter skips dead functions and walks blocks in reverse
  postorder.
- SPIR-V: printf as NonSemantic.DebugPrintf with an OpString format.
This commit is contained in:
peterino2 2026-11-03 22:12:27 -08:00
parent 987b2a573c
commit 886b64da89
11 changed files with 208 additions and 14 deletions

View File

@ -528,6 +528,7 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void {
const zv = stats.begin(.spirv); const zv = stats.begin(.spirv);
defer if (opts.spirv) zv.end(); defer if (opts.spirv) zv.end();
if (opts.spirv) { if (opts.spirv) {
try zdxc.ir.inline_calls.runResourceReturns(m);
zdxc.ir.split_resources.run(arena, m, &diags) catch |err| switch (err) { zdxc.ir.split_resources.run(arena, m, &diags) catch |err| switch (err) {
error.Unsupported => { error.Unsupported => {
try diags.render(&sm, ctx.stderr, .{ .format = opts.diag_format, .color = false }); try diags.render(&sm, ctx.stderr, .{ .format = opts.diag_format, .color = false });

View File

@ -41,6 +41,8 @@ pub const Parser = struct {
/// Name of the struct most recently parsed by parseStructDeclInto /// Name of the struct most recently parsed by parseStructDeclInto
/// (synthesized for anonymous structs), for `typedef struct ...`. /// (synthesized for anonymous structs), for `typedef struct ...`.
last_struct_name: []const u8 = "", 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. /// The qualifier words read by the last parseQualifiers call.
last_quals: []const ast.QualWord = &.{}, last_quals: []const ast.QualWord = &.{},
/// Qualifier words for the next parseDeclaratorsInto call. /// Qualifier words for the next parseDeclaratorsInto call.
@ -410,6 +412,8 @@ pub const Parser = struct {
fn skipTypeAttrs(p: *const Parser, start: usize) usize { fn skipTypeAttrs(p: *const Parser, start: usize) usize {
var i = start; 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; if (!(p.toks[i].kind == .l_square and p.toks[i + 1].kind == .l_square)) return i;
var depth: u32 = 0; var depth: u32 = 0;
while (true) : (i += 1) { while (true) : (i += 1) {
@ -565,10 +569,19 @@ pub const Parser = struct {
t.pack_matrix = p.packMatrixAt(type_pos); t.pack_matrix = p.packMatrixAt(type_pos);
if (norm != .none) t.norm = norm; if (norm != .none) t.norm = norm;
if (words.items.len > 0) t.attr_words = words.items; 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(); if (p.at(.l_square) and p.peek(1).kind == .l_square) t.attrs = try p.parseAttributes();
return t; 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 { fn parseTypeInner(p: *Parser) Error!*ast.TypeRef {
// An elaborated type: `struct S` names S (declaring it if needed). // 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; 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); return out.append(p.arena, d);
} }
const quals = p.parseQualifiers(); var quals = p.parseQualifiers();
const words = p.last_quals; const words = p.last_quals;
const ty = try p.parseType(); const ty = try p.parseDeclType(&quals);
p.decl_quals = words; p.decl_quals = words;
const first = out.items.len; const first = out.items.len;
try p.parseDeclaratorsInto(out, attrs, quals, template_params, ty, ctx); 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(); if (p.atIdent("void") and p.peek(1).kind == .r_paren) _ = p.advance();
while (!p.at(.r_paren)) { while (!p.at(.r_paren)) {
const pattrs = try p.parseAttributes(); const pattrs = try p.parseAttributes();
const pquals = p.parseQualifiers(); var pquals = p.parseQualifiers();
const pwords = p.last_quals; const pwords = p.last_quals;
const pty = try p.parseType(); const pty = try p.parseDeclType(&pquals);
var pname: []const u8 = ""; var pname: []const u8 = "";
var pname_loc = p.tok().loc; var pname_loc = p.tok().loc;
if (p.at(.identifier) and !isReserved(p.tok().text)) { 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). /// `expr`, or `T name = init` (C++ condition declaration).
fn parseCondition(p: *Parser) Error!struct { decl: ?*ast.Decl, cond: *ast.Expr } { fn parseCondition(p: *Parser) Error!struct { decl: ?*ast.Decl, cond: *ast.Expr } {
if (!p.startsLocalDecl()) return .{ .decl = null, .cond = try p.parseExpr() }; if (!p.startsLocalDecl()) return .{ .decl = null, .cond = try p.parseExpr() };
const quals = p.parseQualifiers(); var quals = p.parseQualifiers();
const ty = try p.parseType(); const ty = try p.parseDeclType(&quals);
const name = try p.expectIdent("variable name"); const name = try p.expectIdent("variable name");
_ = try p.expect(.equal, "'='"); _ = try p.expect(.equal, "'='");
const init_expr = try p.parseAssign(); const init_expr = try p.parseAssign();

View File

@ -20,6 +20,7 @@ const Allocator = std.mem.Allocator;
const ir = @import("ir.zig"); const ir = @import("ir.zig");
const types = @import("../sema/types.zig"); const types = @import("../sema/types.zig");
const opt = @import("opt.zig"); const opt = @import("opt.zig");
const split_resources = @import("split_resources.zig");
const Ref = ir.Ref; const Ref = ir.Ref;
const BlockId = ir.BlockId; const BlockId = ir.BlockId;
@ -73,6 +74,41 @@ pub fn run(m: *ir.Module) Error!void {
try markDead(m); 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. /// How a function returns, for inlining it.
const Shape = union(enum) { const Shape = union(enum) {
/// Not inlinable. /// Not inlinable.

View File

@ -533,8 +533,9 @@ pub const SpirvExt = struct {
pub const SpirvInst = struct { pub const SpirvInst = struct {
opcode: u32, opcode: u32,
set: ?[]const u8 = null, set: ?[]const u8 = null,
/// Values, pointers (`[[vk::ext_reference]]`) or literal words. /// Values, pointers (`[[vk::ext_reference]]`), literal words, types,
operands: []const union(enum) { value: Ref, literal: u32, type: TypeId }, /// 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 = &.{}, capabilities: []const u32 = &.{},
extensions: []const []const u8 = &.{}, extensions: []const []const u8 = &.{},
}; };

View File

@ -1565,6 +1565,16 @@ const Lowerer = struct {
}; };
return result; 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) { if (std.mem.eql(u8, name, "DispatchMesh") and args.len == 4) {
// The payload goes by reference (a groupshared // The payload goes by reference (a groupshared
// variable). // variable).

View File

@ -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); const ops = try a.dupe(@typeInfo(@TypeOf(x.operands)).pointer.child, x.operands);
for (ops) |*o| switch (o.*) { for (ops) |*o| switch (o.*) {
.value => |*v| v.* = ctx.map(v.*), .value => |*v| v.* = ctx.map(v.*),
.literal, .type => {}, .literal, .type, .string => {},
}; };
const n = try a.create(ir.SpirvInst); const n = try a.create(ir.SpirvInst);
n.* = x.*; n.* = x.*;
@ -278,7 +278,7 @@ pub fn eachOperand(op: Op, ctx: anytype) void {
.heap_resource => |h| ctx.use(h.index), .heap_resource => |h| ctx.use(h.index),
.spirv_inst => |x| for (x.operands) |o| switch (o) { .spirv_inst => |x| for (x.operands) |o| switch (o) {
.value => |v| ctx.use(v), .value => |v| ctx.use(v),
.literal, .type => {}, .literal, .type, .string => {},
}, },
.patch_output => |x| ctx.use(x.value), .patch_output => |x| ctx.use(x.value),
.phi => |ps| for (ps) |pp| ctx.use(pp.value), .phi => |ps| for (ps) |pp| ctx.use(pp.value),

View File

@ -189,6 +189,8 @@ const Pass = struct {
if (info.done) return; if (info.done) return;
info.done = true; info.done = true;
const f = p.m.functions.items[fi]; const f = p.m.functions.items[fi];
// (Inlined everywhere: not emitted.)
if (f.dead) return;
// Callees first: their returns may be resources. // Callees first: their returns may be resources.
for (f.insts.items) |inst| if (inst.op == .call) try p.function(inst.op.call.func); 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 n_old = f.insts.items.len;
const ret_holds = holdsResources(p.t, f.ret) or isOpaque(p.t, f.ret); 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; var out: std.ArrayList(Ref) = .empty;
for (blk.insts.items) |r| { for (blk.insts.items) |r| {
const old = f.insts.items[r.index()]; 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 } }, .@"switch" => |sw| blk.term = .{ .@"switch" = .{ .value = mp.map(sw.value), .default = sw.default, .cases = sw.cases } },
else => {}, else => {},
} }
_ = bi;
} }
_ = n_old; _ = n_old;
// What each out / inout resource holds when the function returns: // 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). /// Splits every function's resource-holding aggregates (SPIR-V only).
pub fn run(a: Allocator, m: *ir.Module, diags: *diag.Diagnostics) Error!void { pub fn run(a: Allocator, m: *ir.Module, diags: *diag.Diagnostics) Error!void {
var any = false; var any = false;

View File

@ -197,6 +197,16 @@ const Bindings = struct {
return null; 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. /// Bind or check; false on conflict.
fn bind(b: *Bindings, name: []const u8, v: u16) bool { fn bind(b: *Bindings, name: []const u8, v: u16) bool {
if (b.get(name)) |old| return old == v; if (b.get(name)) |old| return old == v;
@ -260,6 +270,22 @@ fn matchOne(sema: anytype, it: *const table.Intrinsic, object: ?TypeId, args: []
const sh = t.shape(a.ty) orelse continue; const sh = t.shape(a.ty) orelse continue;
if (bindings.any_shape == null or sh.count() > bindings.any_shape.?.count()) bindings.any_shape = sh; if (bindings.any_shape == null or sh.count() > bindings.any_shape.?.count()) bindings.any_shape = sh;
} }
// A dimension shared by several arguments (`dot(numeric<c>,
// numeric<c>)`, mul's `numeric<r, c>` and `numeric<c>`) 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 sum: u32 = 0;
var worst: u32 = 0; var worst: u32 = 0;
const out_params = try sema.arena.alloc(bool, args.len); const out_params = try sema.arena.alloc(bool, args.len);

View File

@ -99,6 +99,10 @@ pub const Param = struct {
type: TypeId, type: TypeId,
dir: enum { in, out, inout }, dir: enum { in, out, inout },
has_default: bool, 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` parameter (SM 6.8 groupshared arguments).
groupshared: bool = false, groupshared: bool = false,
}; };
@ -2521,7 +2525,16 @@ pub const Sema = struct {
.has_default = p.init != null, .has_default = p.init != null,
.groupshared = p.quals.groupshared, .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); 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 }; 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; var explicit: ?TypeId = null;
if (template_args.len > 0) explicit = try s.typeArg(template_args[0]); 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); 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); 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"}); 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 {}; if (s.current_fn) |caller| caller.callees.append(s.arena, f) catch {};
s.record(e, .{ .function = f }); s.record(e, .{ .function = f });
s.ensureBody(f) catch {}; 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')) { if (digits.len > 2 and digits[0] == '0' and (digits[1] == 'x' or digits[1] == 'X')) {
base = 16; base = 16;
body = digits[2..]; body = digits[2..];
} else if (isBinaryLiteral(digits)) {
base = 2;
body = digits[2..];
} else if (digits.len > 1 and digits[0] == '0') { } else if (digits.len > 1 and digits[0] == '0') {
base = 8; base = 8;
body = digits[1..]; 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. /// 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 } { fn scanLiteral(text: []const u8) struct { end: usize, float: bool, inf: bool = false } {
var i: usize = 0; 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'); const hex = text.len > 1 and text[0] == '0' and (text[1] == 'x' or text[1] == 'X');
if (hex) i = 2; if (hex) i = 2;
const isDigit = struct { 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 }; 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. /// `f16` / `f32` / `f64` (any case) at the end of a float literal.
fn fixedFloatSuffix(text: []const u8) ?[]const u8 { fn fixedFloatSuffix(text: []const u8) ?[]const u8 {
if (text.len < 4) return null; if (text.len < 4) return null;

View File

@ -10,6 +10,7 @@ pub const Id = u32;
pub const Op = enum(u16) { pub const Op = enum(u16) {
undef = 1, undef = 1,
source = 3, source = 3,
string = 7,
name = 5, name = 5,
member_name = 6, member_name = 6,
extension = 10, extension = 10,
@ -259,6 +260,8 @@ pub const Section = enum {
memory_model, memory_model,
entry_points, entry_points,
execution_modes, execution_modes,
/// OpString (before OpSource and the names).
debug_strings,
debug_names, debug_names,
annotations, annotations,
types_globals, types_globals,

View File

@ -202,6 +202,7 @@ const Emitter = struct {
used_bindings: std.AutoHashMapUnmanaged(struct { u32, u32 }, void) = .empty, used_bindings: std.AutoHashMapUnmanaged(struct { u32, u32 }, void) = .empty,
spec_ids: std.AutoHashMapUnmanaged(u32, Id) = .empty, spec_ids: std.AutoHashMapUnmanaged(u32, Id) = .empty,
ext_imports: std.StringHashMapUnmanaged(Id) = .empty, ext_imports: std.StringHashMapUnmanaged(Id) = .empty,
string_ids: std.StringHashMapUnmanaged(Id) = .empty,
/// Flattened resource arrays: a variable per element. /// Flattened resource arrays: a variable per element.
flat_vars: std.AutoHashMapUnmanaged(u32, []const Id) = .empty, flat_vars: std.AutoHashMapUnmanaged(u32, []const Id) = .empty,
flat_iface: std.ArrayList(Id) = .empty, flat_iface: std.ArrayList(Id) = .empty,
@ -837,12 +838,22 @@ const Emitter = struct {
.value => |r| e.val(r), .value => |r| e.val(r),
.literal => |w| w, .literal => |w| w,
.type => |t| try e.typeId(t), .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))); const op: Op = if (x.set != null) .ext_inst else @enumFromInt(@as(u16, @intCast(x.opcode)));
try e.b.emit(.functions, op, words.items); try e.b.emit(.functions, op, words.items);
return id; return id;
} }
/// 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). /// An OpExtInstImport of `name` (made once).
fn extInstImport(e: *Emitter, name: []const u8) Error!Id { fn extInstImport(e: *Emitter, name: []const u8) Error!Id {
if (std.mem.eql(u8, name, "GLSL.std.450")) { if (std.mem.eql(u8, name, "GLSL.std.450")) {