Compare commits
8 Commits
7d7a456d63
...
4666275a0b
| Author | SHA1 | Date |
|---|---|---|
|
|
4666275a0b | |
|
|
dce6d0eade | |
|
|
cd951ea29b | |
|
|
ab7b167270 | |
|
|
97517cc5b1 | |
|
|
d39ee30a4c | |
|
|
afc4587596 | |
|
|
2ed08b08e1 |
|
|
@ -187,6 +187,8 @@ const Options = struct {
|
||||||
dump_ast: bool = false,
|
dump_ast: bool = false,
|
||||||
sema: bool = false,
|
sema: bool = false,
|
||||||
dump_ir: bool = false,
|
dump_ir: bool = false,
|
||||||
|
/// -zdxc-no-opt: no SPIR-V IR optimizations.
|
||||||
|
no_opt: bool = false,
|
||||||
/// -O0..-O3 / -Od (default -O3, as in dxc).
|
/// -O0..-O3 / -Od (default -O3, as in dxc).
|
||||||
opt_level: enum { od, o0, o1, o2, o3 } = .o3,
|
opt_level: enum { od, o0, o1, o2, o3 } = .o3,
|
||||||
/// Accepted options with no effect yet, reported once each.
|
/// Accepted options with no effect yet, reported once each.
|
||||||
|
|
@ -219,6 +221,7 @@ fn parseArgs(ctx: *Ctx, arena: std.mem.Allocator, args: []const []const u8) !?Op
|
||||||
},
|
},
|
||||||
.zdxc_sema => opts.sema = true,
|
.zdxc_sema => opts.sema = true,
|
||||||
.zdxc_ir => opts.dump_ir = true,
|
.zdxc_ir => opts.dump_ir = true,
|
||||||
|
.zdxc_no_opt => opts.no_opt = true,
|
||||||
.job => opts.job = a.value(),
|
.job => opts.job = a.value(),
|
||||||
.fcolor_diagnostics => opts.color = true,
|
.fcolor_diagnostics => opts.color = true,
|
||||||
.fno_color_diagnostics => opts.color = false,
|
.fno_color_diagnostics => opts.color = false,
|
||||||
|
|
@ -493,10 +496,6 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void {
|
||||||
if (profile == null) return ctx.fail("missing -T <profile>", .{});
|
if (profile == null) return ctx.fail("missing -T <profile>", .{});
|
||||||
if (module) |*m| {
|
if (module) |*m| {
|
||||||
try zdxc.ir.opt.run(arena, m);
|
try zdxc.ir.opt.run(arena, m);
|
||||||
if (opts.dump_ir) {
|
|
||||||
try zdxc.ir.ir.dump(m, ctx.stdout);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (opts.spirv) {
|
if (opts.spirv) {
|
||||||
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 => {
|
||||||
|
|
@ -505,6 +504,18 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void {
|
||||||
},
|
},
|
||||||
else => |x| return x,
|
else => |x| return x,
|
||||||
};
|
};
|
||||||
|
// Legalization and cleanup dxc's SPIR-V gets from its
|
||||||
|
// optimizer (skipped for -Od).
|
||||||
|
if (!opts.no_opt and opts.opt_level != .od) {
|
||||||
|
try zdxc.ir.inline_calls.run(m);
|
||||||
|
try zdxc.ir.ssa.run(m);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (opts.dump_ir) {
|
||||||
|
try zdxc.ir.ir.dump(m, ctx.stdout);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (opts.spirv) {
|
||||||
const bytes = zdxc.spirv.emit.emit(arena, m, &diags, zdxc.spirv.emit.TargetEnv.parse(opts.target_env) orelse return ctx.fail("unknown SPIR-V target environment '{s}'", .{opts.target_env})) catch |err| switch (err) {
|
const bytes = zdxc.spirv.emit.emit(arena, m, &diags, zdxc.spirv.emit.TargetEnv.parse(opts.target_env) orelse return ctx.fail("unknown SPIR-V target environment '{s}'", .{opts.target_env})) 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 });
|
||||||
|
|
@ -520,7 +531,7 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void {
|
||||||
if (opts.rootsig_define) |macro| if (m.entries.items.len == 1) {
|
if (opts.rootsig_define) |macro| if (m.entries.items.len == 1) {
|
||||||
m.entries.items[0].root_signature = try rootSignatureMacroText(ctx, arena, opts, input, macro) orelse return error.CompileFailed;
|
m.entries.items[0].root_signature = try rootSignatureMacroText(ctx, arena, opts, input, macro) orelse return error.CompileFailed;
|
||||||
};
|
};
|
||||||
const bytes = zdxc.dxil.emit.emit(arena, m, profile.?, &diags) catch |err| switch (err) {
|
const bytes = zdxc.dxil.emit.emit(arena, m, profile.?, &diags, !opts.no_opt and opts.opt_level != .od) 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 });
|
||||||
return error.CompileFailed;
|
return error.CompileFailed;
|
||||||
|
|
|
||||||
|
|
@ -34,10 +34,13 @@ const Value = module.Value;
|
||||||
|
|
||||||
pub const Error = Allocator.Error || error{Unsupported};
|
pub const Error = Allocator.Error || error{Unsupported};
|
||||||
|
|
||||||
pub fn emit(gpa: Allocator, m: *const ir.Module, profile: shader.Profile, diags: *diag.Diagnostics) Error![]u8 {
|
/// `optimize` (off for -Od and -zdxc-no-opt) promotes locals to SSA values,
|
||||||
|
/// passes arrays to callees that only read them in place and reuses
|
||||||
|
/// inlined callees' arrays.
|
||||||
|
pub fn emit(gpa: Allocator, m: *const ir.Module, profile: shader.Profile, diags: *diag.Diagnostics, optimize: bool) Error![]u8 {
|
||||||
var arena_state = std.heap.ArenaAllocator.init(gpa);
|
var arena_state = std.heap.ArenaAllocator.init(gpa);
|
||||||
defer arena_state.deinit();
|
defer arena_state.deinit();
|
||||||
var e: Emitter = .{ .arena = arena_state.allocator(), .dm = .init(gpa), .m = m, .t = m.types, .profile = profile, .diags = diags };
|
var e: Emitter = .{ .arena = arena_state.allocator(), .dm = .init(gpa), .m = m, .t = m.types, .profile = profile, .diags = diags, .optimize = optimize };
|
||||||
defer e.dm.deinit();
|
defer e.dm.deinit();
|
||||||
// Native 16-bit types are laid out at their own size.
|
// Native 16-bit types are laid out at their own size.
|
||||||
if (m.native_16bit) e.dm.datalayout = "e-m:e-p:32:32-i1:32-i8:8-i16:16-i32:32-i64:64-f16:16-f32:32-f64:64-n8:16:32:64";
|
if (m.native_16bit) e.dm.datalayout = "e-m:e-p:32:32-i1:32-i8:8-i16:16-i32:32-i64:64-f16:16-f32:32-f64:64-n8:16:32:64";
|
||||||
|
|
@ -155,13 +158,16 @@ const Frame = struct {
|
||||||
rets: std.ArrayList(struct { block: u32, vals: []const Value }) = .empty,
|
rets: std.ArrayList(struct { block: u32, vals: []const Value }) = .empty,
|
||||||
/// The resources a function returns (every return the same ones).
|
/// The resources a function returns (every return the same ones).
|
||||||
ret_res: ?[]const Lowered = null,
|
ret_res: ?[]const Lowered = null,
|
||||||
/// Loads of locals: where from, and the block and write count when
|
/// Loads of locals and constant buffers: the place (a `.ptr` or
|
||||||
/// read, so a call right after can pass the local itself.
|
/// `.cbuf`), and the block and write count when read, so a call right
|
||||||
load_srcs: std.AutoHashMapUnmanaged(u32, struct { ptr: Ptr, block: u32, writes: u32 }) = .empty,
|
/// after can pass the place itself.
|
||||||
/// By-value parameters passed as the caller's storage (see paramCopies).
|
load_srcs: std.AutoHashMapUnmanaged(u32, struct { src: Lowered, block: u32, writes: u32 }) = .empty,
|
||||||
param_ptrs: []const ?Ptr = &.{},
|
/// By-value parameters passed as the caller's place (see paramCopies).
|
||||||
|
param_srcs: []const ?Lowered = &.{},
|
||||||
/// paramCopies of the function, when some parameter is aliased.
|
/// paramCopies of the function, when some parameter is aliased.
|
||||||
param_copies: []const u32 = &.{},
|
param_copies: []const u32 = &.{},
|
||||||
|
/// Array locals of an inlined callee, back to the pool on return.
|
||||||
|
arrays: std.ArrayList(struct { ty: TypeId, ptr: Ptr }) = .empty,
|
||||||
};
|
};
|
||||||
|
|
||||||
const PInst = struct { inst: module.Inst, id: u32 };
|
const PInst = struct { inst: module.Inst, id: u32 };
|
||||||
|
|
@ -230,6 +236,11 @@ const Emitter = struct {
|
||||||
/// Dynamically indexed getelementptrs into locals (by id) and the
|
/// Dynamically indexed getelementptrs into locals (by id) and the
|
||||||
/// components they can reach, for promote.run.
|
/// components they can reach, for promote.run.
|
||||||
dyn_ranges: std.AutoHashMapUnmanaged(u32, [2]u32) = .empty,
|
dyn_ranges: std.AutoHashMapUnmanaged(u32, [2]u32) = .empty,
|
||||||
|
/// See `emit`.
|
||||||
|
optimize: bool = true,
|
||||||
|
/// Arrays of inlined callees that have returned, by type, for later
|
||||||
|
/// callees' locals of that type (per function).
|
||||||
|
array_pool: std.AutoHashMapUnmanaged(TypeId, std.ArrayList(Ptr)) = .empty,
|
||||||
/// Instructions emitted so far that may write memory.
|
/// Instructions emitted so far that may write memory.
|
||||||
writes: u32 = 0,
|
writes: u32 = 0,
|
||||||
/// paramCopies per IR function.
|
/// paramCopies per IR function.
|
||||||
|
|
@ -1255,7 +1266,8 @@ const Emitter = struct {
|
||||||
var it = e.dyn_ranges.iterator();
|
var it = e.dyn_ranges.iterator();
|
||||||
while (it.next()) |kv| try ranges.put(e.arena, map[kv.key_ptr.*], kv.value_ptr.*);
|
while (it.next()) |kv| try ranges.put(e.arena, map[kv.key_ptr.*], kv.value_ptr.*);
|
||||||
e.dyn_ranges.clearRetainingCapacity();
|
e.dyn_ranges.clearRetainingCapacity();
|
||||||
try promote.run(e.arena, &e.dm, func, &ranges);
|
e.array_pool.clearRetainingCapacity();
|
||||||
|
if (e.optimize) try promote.run(e.arena, &e.dm, func, &ranges);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Drops removable prologue instructions nothing uses (repeatedly: a
|
/// Drops removable prologue instructions nothing uses (repeatedly: a
|
||||||
|
|
@ -1370,9 +1382,10 @@ const Emitter = struct {
|
||||||
return e.inlineCallAliased(fi, args, &.{});
|
return e.inlineCallAliased(fi, args, &.{});
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `aliases[k]`, when set, is caller storage holding by-value argument
|
/// `aliases[k]`, when set, is the caller's place holding by-value
|
||||||
/// `k`, which the callee may read in place of a copy (see argAliases).
|
/// argument `k`, which the callee may read in place of a copy (see
|
||||||
fn inlineCallAliased(e: *Emitter, fi: u32, args: []const Lowered, aliases: []const ?Ptr) Error![]const Value {
|
/// argAliases).
|
||||||
|
fn inlineCallAliased(e: *Emitter, fi: u32, args: []const Lowered, aliases: []const ?Lowered) Error![]const Value {
|
||||||
const f = e.m.functions.items[fi];
|
const f = e.m.functions.items[fi];
|
||||||
var frame: Frame = .{
|
var frame: Frame = .{
|
||||||
.f = f,
|
.f = f,
|
||||||
|
|
@ -1381,7 +1394,7 @@ const Emitter = struct {
|
||||||
.blocks = try e.arena.alloc(?u32, f.blocks.items.len),
|
.blocks = try e.arena.alloc(?u32, f.blocks.items.len),
|
||||||
};
|
};
|
||||||
for (aliases) |al| if (al != null) {
|
for (aliases) |al| if (al != null) {
|
||||||
frame.param_ptrs = aliases;
|
frame.param_srcs = aliases;
|
||||||
frame.param_copies = try e.paramCopies(fi);
|
frame.param_copies = try e.paramCopies(fi);
|
||||||
break;
|
break;
|
||||||
};
|
};
|
||||||
|
|
@ -1398,6 +1411,14 @@ const Emitter = struct {
|
||||||
try e.emitBlock(&frame, @intCast(bi));
|
try e.emitBlock(&frame, @intCast(bi));
|
||||||
}
|
}
|
||||||
e.last_ret_res = frame.ret_res;
|
e.last_ret_res = frame.ret_res;
|
||||||
|
// The callee's arrays are dead now: later callees can have them
|
||||||
|
// (with no values forwarded from what they held).
|
||||||
|
if (frame.arrays.items.len > 0) e.forwarded.clearRetainingCapacity();
|
||||||
|
for (frame.arrays.items) |x| {
|
||||||
|
const gop = try e.array_pool.getOrPut(e.arena, x.ty);
|
||||||
|
if (!gop.found_existing) gop.value_ptr.* = .empty;
|
||||||
|
try gop.value_ptr.append(e.arena, x.ptr);
|
||||||
|
}
|
||||||
if (frame.cont) |cont| {
|
if (frame.cont) |cont| {
|
||||||
e.cur = cont;
|
e.cur = cont;
|
||||||
if (f.ret == TypeTable.void_type or frame.rets.items.len == 0) return &.{};
|
if (f.ret == TypeTable.void_type or frame.rets.items.len == 0) return &.{};
|
||||||
|
|
@ -1414,19 +1435,33 @@ const Emitter = struct {
|
||||||
return &.{};
|
return &.{};
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Caller storage the by-value arguments of a call to `fi` can be read
|
/// Places the by-value array and struct arguments of a call to `fi` can
|
||||||
/// from: an argument loaded from a local in the same block, with no
|
/// be read from: a constant buffer they were loaded from (none with
|
||||||
/// write since. Calls with out / inout arguments get none (the callee
|
/// matrices, whose constant buffer access is narrower than a local's),
|
||||||
/// could write the local through one while reading it through another).
|
/// or a local loaded in the same block with no write since. Calls with
|
||||||
fn argAliases(e: *Emitter, frame: *const Frame, fi: u32, refs: []const Ref) Error![]const ?Ptr {
|
/// out / inout arguments get no locals (the callee could write one
|
||||||
|
/// through them while reading it through another).
|
||||||
|
fn argAliases(e: *Emitter, frame: *const Frame, fi: u32, refs: []const Ref) Error![]const ?Lowered {
|
||||||
const params = e.m.functions.items[fi].params;
|
const params = e.m.functions.items[fi].params;
|
||||||
for (params) |p| if (p.by_ref) return &.{};
|
var by_ref = false;
|
||||||
const out = try e.arena.alloc(?Ptr, refs.len);
|
for (params) |p| by_ref = by_ref or p.by_ref;
|
||||||
|
const out = try e.arena.alloc(?Lowered, refs.len);
|
||||||
for (refs, params, out) |r, p, *o| {
|
for (refs, params, out) |r, p, *o| {
|
||||||
o.* = null;
|
o.* = null;
|
||||||
if (e.t.get(p.ty) != .array) continue;
|
if (p.by_ref) continue;
|
||||||
|
switch (e.t.get(p.ty)) {
|
||||||
|
.array, .@"struct" => if (e.holdsResources(p.ty)) continue,
|
||||||
|
else => continue,
|
||||||
|
}
|
||||||
const src = frame.load_srcs.get(r.index()) orelse continue;
|
const src = frame.load_srcs.get(r.index()) orelse continue;
|
||||||
if (src.block == e.cur and src.writes == e.writes) o.* = src.ptr;
|
switch (src.src) {
|
||||||
|
.cbuf => if (!e.containsMatrix(p.ty)) {
|
||||||
|
o.* = src.src;
|
||||||
|
},
|
||||||
|
else => if (!by_ref and src.block == e.cur and src.writes == e.writes) {
|
||||||
|
o.* = src.src;
|
||||||
|
},
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
@ -1741,6 +1776,12 @@ const Emitter = struct {
|
||||||
return .{ .handle = ri };
|
return .{ .handle = ri };
|
||||||
},
|
},
|
||||||
.local_var => {
|
.local_var => {
|
||||||
|
// (First: the store of the parameter is skipped whenever
|
||||||
|
// there is an alias.)
|
||||||
|
if (frame.param_copies.len > 0) {
|
||||||
|
const k = frame.param_copies[r.index()];
|
||||||
|
if (k != std.math.maxInt(u32)) if (frame.param_srcs[k]) |alias| return alias;
|
||||||
|
}
|
||||||
if (e.payload_local) |pl| if (pl.func == f and pl.inst == r.index()) {
|
if (e.payload_local) |pl| if (pl.func == f and pl.inst == r.index()) {
|
||||||
const dty = try e.memoryType(i.ty);
|
const dty = try e.memoryType(i.ty);
|
||||||
const base = try e.addPrologue(try e.dm.ptrType(dty), .{ .alloca = .{ .elem = dty, .size = try e.i32Const(1) } });
|
const base = try e.addPrologue(try e.dm.ptrType(dty), .{ .alloca = .{ .elem = dty, .size = try e.i32Const(1) } });
|
||||||
|
|
@ -1767,9 +1808,11 @@ const Emitter = struct {
|
||||||
const base = try e.addPrologue(try e.dm.ptrType(dty), .{ .alloca = .{ .elem = dty, .size = try e.i32Const(1) } });
|
const base = try e.addPrologue(try e.dm.ptrType(dty), .{ .alloca = .{ .elem = dty, .size = try e.i32Const(1) } });
|
||||||
return .{ .typed = .{ .base = base, .dty = dty, .addr_space = 0, .ty = i.ty } };
|
return .{ .typed = .{ .base = base, .dty = dty, .addr_space = 0, .ty = i.ty } };
|
||||||
}
|
}
|
||||||
if (frame.param_copies.len > 0) {
|
if (e.optimize and frame.cont != null and e.t.get(i.ty) == .array) {
|
||||||
const k = frame.param_copies[r.index()];
|
const pooled = if (e.array_pool.getPtr(i.ty)) |l| l.pop() else null;
|
||||||
if (k != std.math.maxInt(u32)) if (frame.param_ptrs[k]) |alias| return .{ .ptr = alias };
|
const ptr = pooled orelse try e.alloca(i.ty);
|
||||||
|
try frame.arrays.append(e.arena, .{ .ty = i.ty, .ptr = ptr });
|
||||||
|
return .{ .ptr = ptr };
|
||||||
}
|
}
|
||||||
return .{ .ptr = try e.alloca(i.ty) };
|
return .{ .ptr = try e.alloca(i.ty) };
|
||||||
},
|
},
|
||||||
|
|
@ -1801,6 +1844,7 @@ const Emitter = struct {
|
||||||
return .{ .scalars = try e.textureLoad(res, mip, tx.coords, null, i.ty) };
|
return .{ .scalars = try e.textureLoad(res, mip, tx.coords, null, i.ty) };
|
||||||
},
|
},
|
||||||
.cbuf => |c| {
|
.cbuf => |c| {
|
||||||
|
if (c.dyn_comp == null) try frame.load_srcs.put(e.arena, r.index(), .{ .src = .{ .cbuf = c }, .block = e.cur, .writes = e.writes });
|
||||||
const dc = c.dyn_comp orelse return e.cbufferLoad(c.res, c.offset, c.dyn_regs, c.row_major, i.ty);
|
const dc = c.dyn_comp orelse return e.cbufferLoad(c.res, c.offset, c.dyn_regs, c.row_major, i.ty);
|
||||||
const whole = (try e.cbufferLoad(c.res, c.offset, c.dyn_regs, c.row_major, c.vec)).scalars;
|
const whole = (try e.cbufferLoad(c.res, c.offset, c.dyn_regs, c.row_major, c.vec)).scalars;
|
||||||
return .{ .scalars = try e.arena.dupe(Value, &.{try e.pickComponent(whole, dc, i.ty)}) };
|
return .{ .scalars = try e.arena.dupe(Value, &.{try e.pickComponent(whole, dc, i.ty)}) };
|
||||||
|
|
@ -1831,7 +1875,7 @@ const Emitter = struct {
|
||||||
return .{ .scalars = out };
|
return .{ .scalars = out };
|
||||||
},
|
},
|
||||||
.ptr => |ptr| {
|
.ptr => |ptr| {
|
||||||
if (ptr.addr_space == 0 and localRoot(f, p)) try frame.load_srcs.put(e.arena, r.index(), .{ .ptr = ptr, .block = e.cur, .writes = e.writes });
|
if (ptr.addr_space == 0 and localRoot(f, p)) try frame.load_srcs.put(e.arena, r.index(), .{ .src = .{ .ptr = ptr }, .block = e.cur, .writes = e.writes });
|
||||||
return e.loadPtr(ptr, i.ty);
|
return e.loadPtr(ptr, i.ty);
|
||||||
},
|
},
|
||||||
.typed => |tp| return e.typedLoad(tp, i.ty),
|
.typed => |tp| return e.typedLoad(tp, i.ty),
|
||||||
|
|
@ -1841,7 +1885,7 @@ const Emitter = struct {
|
||||||
.store => |s| {
|
.store => |s| {
|
||||||
if (frame.param_copies.len > 0) if (f.inst(s.value).op == .param) {
|
if (frame.param_copies.len > 0) if (f.inst(s.value).op == .param) {
|
||||||
const k = f.inst(s.value).op.param;
|
const k = f.inst(s.value).op.param;
|
||||||
if (frame.param_copies[s.ptr.index()] == k and frame.param_ptrs[k] != null) return .none;
|
if (frame.param_copies[s.ptr.index()] == k and frame.param_srcs[k] != null) return .none;
|
||||||
};
|
};
|
||||||
if (frame.vals[s.ptr.index()] == .rq_local) {
|
if (frame.vals[s.ptr.index()] == .rq_local) {
|
||||||
// A copy of a query is the same query.
|
// A copy of a query is the same query.
|
||||||
|
|
@ -2103,7 +2147,7 @@ const Emitter = struct {
|
||||||
if (e.lib_calls.get(c.func)) |func| return e.libCall(frame, c.func, func, c.args);
|
if (e.lib_calls.get(c.func)) |func| return e.libCall(frame, c.func, func, c.args);
|
||||||
const args = try e.arena.alloc(Lowered, c.args.len);
|
const args = try e.arena.alloc(Lowered, c.args.len);
|
||||||
for (c.args, args) |a, *o| o.* = frame.vals[a.index()];
|
for (c.args, args) |a, *o| o.* = frame.vals[a.index()];
|
||||||
const res = try e.inlineCallAliased(c.func, args, try e.argAliases(frame, c.func, c.args));
|
const res = try e.inlineCallAliased(c.func, args, if (e.optimize) try e.argAliases(frame, c.func, c.args) else &.{});
|
||||||
// Functions returning resources (or structs of them).
|
// Functions returning resources (or structs of them).
|
||||||
if (isResourceType(e.t, i.ty) and !isRayQuery(e.t, i.ty)) {
|
if (isResourceType(e.t, i.ty) and !isRayQuery(e.t, i.ty)) {
|
||||||
const rr = e.last_ret_res orelse return e.unsupported("a function returning a resource with no return value", .{});
|
const rr = e.last_ret_res orelse return e.unsupported("a function returning a resource with no return value", .{});
|
||||||
|
|
@ -2138,6 +2182,7 @@ const Emitter = struct {
|
||||||
},
|
},
|
||||||
.output_vertex => |x| return e.outputControlPoint(x.element, i.ty, x.vertex),
|
.output_vertex => |x| return e.outputControlPoint(x.element, i.ty, x.vertex),
|
||||||
.phi => return e.unsupported("phi", .{}),
|
.phi => return e.unsupported("phi", .{}),
|
||||||
|
.undef => return e.unsupported("undef", .{}),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -4733,6 +4778,17 @@ const Emitter = struct {
|
||||||
return dty;
|
return dty;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn containsMatrix(e: *Emitter, ty: TypeId) bool {
|
||||||
|
return switch (e.t.get(ty)) {
|
||||||
|
.matrix => true,
|
||||||
|
.array => |a| e.containsMatrix(a.elem),
|
||||||
|
.@"struct" => |st| for (st.fields.items) |fld| {
|
||||||
|
if (e.containsMatrix(fld.type)) break true;
|
||||||
|
} else false,
|
||||||
|
else => false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
fn containsLinAlg(e: *Emitter, ty: TypeId) bool {
|
fn containsLinAlg(e: *Emitter, ty: TypeId) bool {
|
||||||
return switch (e.t.get(ty)) {
|
return switch (e.t.get(ty)) {
|
||||||
.linalg => true,
|
.linalg => true,
|
||||||
|
|
|
||||||
|
|
@ -585,6 +585,15 @@ pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashM
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Peepholes on what promotion exposes, in instruction order so they
|
||||||
|
// cascade: bitcast round trips (locals mixing ints and floats store
|
||||||
|
// i32s), constant integer arithmetic and comparisons, identities, and
|
||||||
|
// selects on a constant.
|
||||||
|
for (insts, 0..) |inst, i| {
|
||||||
|
if (repl[i] != null) continue;
|
||||||
|
repl[i] = try simplify(m, f, repl, n, phi_var.items, var_ty, inst);
|
||||||
|
}
|
||||||
|
|
||||||
// The instructions that go: promoted allocas, their getelementptrs,
|
// The instructions that go: promoted allocas, their getelementptrs,
|
||||||
// loads and stores.
|
// loads and stores.
|
||||||
const removed = try a.alloc(bool, n);
|
const removed = try a.alloc(bool, n);
|
||||||
|
|
@ -684,12 +693,163 @@ pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashM
|
||||||
while (i < block_start[b + 1]) : (i += 1) if (live[i]) {
|
while (i < block_start[b + 1]) : (i += 1) if (live[i]) {
|
||||||
var inst = insts[i];
|
var inst = insts[i];
|
||||||
try operands(true, ma, &inst, &map);
|
try operands(true, ma, &inst, &map);
|
||||||
|
if (inst.op == .gep) try clampIndex(m, &inst.op.gep);
|
||||||
out.appendAssumeCapacity(inst);
|
out.appendAssumeCapacity(inst);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
f.insts = out;
|
f.insts = out;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// An index into an array that folding made a constant out of range (on
|
||||||
|
/// a path that cannot run: the access would be undefined) becomes 0, as
|
||||||
|
/// the validator rejects constant out-of-bounds accesses.
|
||||||
|
fn clampIndex(m: *module.Module, g: *@FieldType(@FieldType(Inst, "op"), "gep")) Allocator.Error!void {
|
||||||
|
if (g.indices.len != 2) return;
|
||||||
|
const len = switch (m.types.items[g.elem]) {
|
||||||
|
.array => |arr| arr.len,
|
||||||
|
else => return,
|
||||||
|
};
|
||||||
|
const k = constInt(m, g.indices[1]) orelse return;
|
||||||
|
if (k >= 0 and k < len) return;
|
||||||
|
const ix = try m.allocator().dupe(Value, g.indices);
|
||||||
|
ix[1] = try m.constant(.{ .ty = m.constants.items[g.indices[1].constant].ty, .kind = .{ .int = 0 } });
|
||||||
|
g.indices = ix;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A simpler value for `inst`, or null.
|
||||||
|
fn simplify(m: *module.Module, f: *const module.Function, repl: []const ?Value, n: u32, phi_var: []const u32, var_ty: []const TypeId, inst: Inst) Allocator.Error!?Value {
|
||||||
|
const S = struct {
|
||||||
|
fn ty(mm: *const module.Module, ff: *const module.Function, nn: u32, pv: []const u32, vt: []const TypeId, v: Value) TypeId {
|
||||||
|
if (v == .inst and v.inst >= nn) return vt[pv[v.inst - nn]];
|
||||||
|
return typeOf(mm, ff, v);
|
||||||
|
}
|
||||||
|
fn intWidth(mm: *const module.Module, t: TypeId) ?u32 {
|
||||||
|
return switch (mm.types.items[t]) {
|
||||||
|
.int => |w| w,
|
||||||
|
else => null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
/// `v` as a `w`-bit pattern.
|
||||||
|
fn bits(v: i64, w: u32) u64 {
|
||||||
|
const u: u64 = @bitCast(v);
|
||||||
|
return if (w >= 64) u else u & ((@as(u64, 1) << @intCast(w)) - 1);
|
||||||
|
}
|
||||||
|
/// A `w`-bit pattern as stored: 0 / 1 for i1, sign-extended above.
|
||||||
|
fn stored(p: u64, w: u32) i64 {
|
||||||
|
if (w == 1) return @intCast(p & 1);
|
||||||
|
if (w >= 64) return @bitCast(p);
|
||||||
|
const sh: u6 = @intCast(64 - w);
|
||||||
|
return @as(i64, @bitCast(p << sh)) >> sh;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
switch (inst.op) {
|
||||||
|
.cast => |c| {
|
||||||
|
if (c.op != .bitcast) return null;
|
||||||
|
const x = resolve(repl, c.val);
|
||||||
|
if (x == .inst and x.inst < n) {
|
||||||
|
const inner = f.insts.items[x.inst].op;
|
||||||
|
if (inner == .cast and inner.cast.op == .bitcast) {
|
||||||
|
const src = resolve(repl, inner.cast.val);
|
||||||
|
if (S.ty(m, f, n, phi_var, var_ty, src) == inst.ty) return src;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (x == .constant) {
|
||||||
|
const k = m.constants.items[x.constant].kind;
|
||||||
|
const w: u32 = switch (m.types.items[inst.ty]) {
|
||||||
|
.int => |iw| iw,
|
||||||
|
.half => 16,
|
||||||
|
.float => 32,
|
||||||
|
.double => 64,
|
||||||
|
else => return null,
|
||||||
|
};
|
||||||
|
const p: u64 = switch (k) {
|
||||||
|
.int => |v| S.bits(v, w),
|
||||||
|
.float_bits => |b| b,
|
||||||
|
else => return null,
|
||||||
|
};
|
||||||
|
return try m.constant(.{ .ty = inst.ty, .kind = switch (m.types.items[inst.ty]) {
|
||||||
|
.int => .{ .int = S.stored(p, w) },
|
||||||
|
else => .{ .float_bits = p },
|
||||||
|
} });
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
},
|
||||||
|
.binop => |b| {
|
||||||
|
const w = S.intWidth(m, inst.ty) orelse return null;
|
||||||
|
const l = resolve(repl, b.lhs);
|
||||||
|
const r = resolve(repl, b.rhs);
|
||||||
|
const lc = constInt(m, l);
|
||||||
|
const rc = constInt(m, r);
|
||||||
|
if (lc != null and rc != null) {
|
||||||
|
const x = S.bits(lc.?, w);
|
||||||
|
const y = S.bits(rc.?, w);
|
||||||
|
const sx = S.stored(x, w);
|
||||||
|
const sy = S.stored(y, w);
|
||||||
|
const p: u64 = switch (b.op) {
|
||||||
|
.add => x +% y,
|
||||||
|
.sub => x -% y,
|
||||||
|
.mul => x *% y,
|
||||||
|
.@"and" => x & y,
|
||||||
|
.@"or" => x | y,
|
||||||
|
.xor => x ^ y,
|
||||||
|
.shl => if (y < w) x << @intCast(y) else return null,
|
||||||
|
.lshr => if (y < w) x >> @intCast(y) else return null,
|
||||||
|
.ashr => if (y < w) @bitCast(sx >> @intCast(y)) else return null,
|
||||||
|
.udiv => if (y != 0) x / y else return null,
|
||||||
|
.urem => if (y != 0) x % y else return null,
|
||||||
|
.sdiv => if (sy != 0 and !(sy == -1 and sx == std.math.minInt(i64))) @bitCast(@divTrunc(sx, sy)) else return null,
|
||||||
|
.srem => if (sy != 0 and sy != -1) @bitCast(@rem(sx, sy)) else return null,
|
||||||
|
};
|
||||||
|
return try m.constant(.{ .ty = inst.ty, .kind = .{ .int = S.stored(S.bits(@bitCast(p), w), w) } });
|
||||||
|
}
|
||||||
|
if (rc) |y| switch (b.op) {
|
||||||
|
.add, .sub, .@"or", .xor, .shl, .lshr, .ashr => if (y == 0) return l,
|
||||||
|
.mul, .udiv, .sdiv => if (S.bits(y, w) == 1) return l,
|
||||||
|
.@"and" => if (S.bits(y, w) == S.bits(-1, w)) return l,
|
||||||
|
else => {},
|
||||||
|
};
|
||||||
|
if (lc) |x| switch (b.op) {
|
||||||
|
.add, .@"or", .xor => if (x == 0) return r,
|
||||||
|
.mul => if (S.bits(x, w) == 1) return r,
|
||||||
|
.@"and" => if (S.bits(x, w) == S.bits(-1, w)) return r,
|
||||||
|
else => {},
|
||||||
|
};
|
||||||
|
return null;
|
||||||
|
},
|
||||||
|
.cmp => |c| {
|
||||||
|
if (c.pred < 32 or c.pred > 41) return null; // integer predicates only
|
||||||
|
const l = resolve(repl, c.lhs);
|
||||||
|
const r = resolve(repl, c.rhs);
|
||||||
|
const w = S.intWidth(m, S.ty(m, f, n, phi_var, var_ty, l)) orelse return null;
|
||||||
|
const x = S.bits(constInt(m, l) orelse return null, w);
|
||||||
|
const y = S.bits(constInt(m, r) orelse return null, w);
|
||||||
|
const sx = S.stored(x, w);
|
||||||
|
const sy = S.stored(y, w);
|
||||||
|
const t = switch (c.pred) {
|
||||||
|
32 => x == y,
|
||||||
|
33 => x != y,
|
||||||
|
34 => x > y,
|
||||||
|
35 => x >= y,
|
||||||
|
36 => x < y,
|
||||||
|
37 => x <= y,
|
||||||
|
38 => sx > sy,
|
||||||
|
39 => sx >= sy,
|
||||||
|
40 => sx < sy,
|
||||||
|
else => sx <= sy,
|
||||||
|
};
|
||||||
|
return try m.constant(.{ .ty = inst.ty, .kind = .{ .int = @intFromBool(t) } });
|
||||||
|
},
|
||||||
|
.select => |sl| {
|
||||||
|
const t = resolve(repl, sl.t);
|
||||||
|
const fv = resolve(repl, sl.f);
|
||||||
|
if (std.meta.eql(t, fv)) return t;
|
||||||
|
const c = constInt(m, resolve(repl, sl.cond)) orelse return null;
|
||||||
|
return if (c != 0) t else fv;
|
||||||
|
},
|
||||||
|
else => return null,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Instructions that must stay even when nothing reads their result.
|
/// Instructions that must stay even when nothing reads their result.
|
||||||
fn hasEffects(m: *const module.Module, inst: Inst) bool {
|
fn hasEffects(m: *const module.Module, inst: Inst) bool {
|
||||||
return switch (inst.op) {
|
return switch (inst.op) {
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,418 @@
|
||||||
|
//! Inlining for SPIR-V: calls are replaced by copies of their callees, as
|
||||||
|
//! dxc's legalization does, so drivers get one function per entry point
|
||||||
|
//! (and later passes see across call boundaries).
|
||||||
|
//!
|
||||||
|
//! Calls are inlined top-down from the entry points. The calling block is
|
||||||
|
//! split at the call:
|
||||||
|
//! it branches to the copy of the callee's entry, and the rest of the block
|
||||||
|
//! (with its terminator and merge) moves to a continuation block. A callee
|
||||||
|
//! with one return outside every construct branches from it to the
|
||||||
|
//! continuation. Returns inside selections first become breaks out of a
|
||||||
|
//! loop that runs once (the callee wrapped in it), with the return value in
|
||||||
|
//! a local; the loop's merge block is where the callee returns, once.
|
||||||
|
//! Returns inside loops would need a break per loop level: those callees
|
||||||
|
//! stay functions.
|
||||||
|
//!
|
||||||
|
//! Functions no root reaches any more are marked dead (and not emitted).
|
||||||
|
|
||||||
|
const std = @import("std");
|
||||||
|
const Allocator = std.mem.Allocator;
|
||||||
|
const ir = @import("ir.zig");
|
||||||
|
const types = @import("../sema/types.zig");
|
||||||
|
const opt = @import("opt.zig");
|
||||||
|
|
||||||
|
const Ref = ir.Ref;
|
||||||
|
const BlockId = ir.BlockId;
|
||||||
|
const TypeTable = types.TypeTable;
|
||||||
|
|
||||||
|
pub const Error = Allocator.Error;
|
||||||
|
|
||||||
|
/// Whether the module is one the pass handles: graphics and compute entry
|
||||||
|
/// points only (the emitter treats hull, mesh, geometry and ray tracing
|
||||||
|
/// functions specially), and no rasterizer-ordered views (the pixel
|
||||||
|
/// shader's call of its entry function is the interlocked region).
|
||||||
|
pub fn eligible(m: *const ir.Module) bool {
|
||||||
|
if (m.entries.items.len == 0) return false;
|
||||||
|
for (m.entries.items) |e| switch (e.stage) {
|
||||||
|
.vertex, .pixel, .compute => {},
|
||||||
|
else => return false,
|
||||||
|
};
|
||||||
|
for (m.globals.items) |g| {
|
||||||
|
var t = g.ty;
|
||||||
|
while (m.types.get(t) == .array) t = m.types.get(t).array.elem;
|
||||||
|
if (m.types.get(t) == .resource and std.mem.startsWith(u8, m.types.get(t).resource.name, "RasterizerOrdered")) return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn run(m: *ir.Module) Error!void {
|
||||||
|
if (!eligible(m)) return;
|
||||||
|
const a = m.arena;
|
||||||
|
const n = m.functions.items.len;
|
||||||
|
// Shapes from the original bodies (inlining a function's callees does
|
||||||
|
// not change how it returns).
|
||||||
|
const shapes = try a.alloc(?Shape, n);
|
||||||
|
for (m.functions.items, shapes) |f, *sh| sh.* = try shapeOf(a, m, f);
|
||||||
|
// Top-down from the roots: each call is replaced by a copy of the
|
||||||
|
// callee's own body, whose calls are inlined in turn as the scan
|
||||||
|
// reaches the copied blocks; a function only gets expanded where it
|
||||||
|
// ends up. Callees that stay functions are expanded as roots.
|
||||||
|
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.
|
||||||
|
keep,
|
||||||
|
/// One return, outside every construct: that block.
|
||||||
|
single: u32,
|
||||||
|
/// Returns inside selections (or several): wrap in a one-trip loop.
|
||||||
|
wrap,
|
||||||
|
};
|
||||||
|
|
||||||
|
fn shapeOf(a: Allocator, m: *const ir.Module, f: *const ir.Function) Error!Shape {
|
||||||
|
if (f.no_inline) return .keep;
|
||||||
|
for (f.params) |p| {
|
||||||
|
if (isRayQuery(m.types, p.ty)) return .keep;
|
||||||
|
if (p.by_ref and isResource(m.types, p.ty)) return .keep;
|
||||||
|
}
|
||||||
|
const nb = f.blocks.items.len;
|
||||||
|
// The innermost construct (header block) around each block, from a
|
||||||
|
// structured walk: a header's merge is at the header's level, its other
|
||||||
|
// successors are inside; exits to an enclosing merge or continue are
|
||||||
|
// not followed (their header places those blocks).
|
||||||
|
const root = std.math.maxInt(u32);
|
||||||
|
const ctx = try a.alloc(u32, nb);
|
||||||
|
const seen = try a.alloc(bool, nb);
|
||||||
|
const parent = try a.alloc(u32, nb);
|
||||||
|
@memset(seen, false);
|
||||||
|
@memset(parent, root);
|
||||||
|
var stack: std.ArrayList(struct { b: u32, c: u32 }) = .empty;
|
||||||
|
try stack.append(a, .{ .b = 0, .c = root });
|
||||||
|
while (stack.pop()) |it| {
|
||||||
|
if (seen[it.b]) continue;
|
||||||
|
seen[it.b] = true;
|
||||||
|
ctx[it.b] = it.c;
|
||||||
|
const blk = f.blocks.items[it.b];
|
||||||
|
var inner = it.c;
|
||||||
|
switch (blk.merge) {
|
||||||
|
.none => {},
|
||||||
|
.selection => |mb| {
|
||||||
|
try stack.append(a, .{ .b = mb.index(), .c = it.c });
|
||||||
|
parent[it.b] = it.c;
|
||||||
|
inner = it.b;
|
||||||
|
},
|
||||||
|
.loop => |l| {
|
||||||
|
try stack.append(a, .{ .b = l.merge.index(), .c = it.c });
|
||||||
|
try stack.append(a, .{ .b = l.@"continue".index(), .c = it.b });
|
||||||
|
parent[it.b] = it.c;
|
||||||
|
inner = it.b;
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for (try successors(a, blk.term)) |s| {
|
||||||
|
if (s == .none) continue;
|
||||||
|
if (isExit(f, inner, parent, s.index())) continue;
|
||||||
|
try stack.append(a, .{ .b = s.index(), .c = inner });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var rets: u32 = 0;
|
||||||
|
var ret_block: u32 = 0;
|
||||||
|
var nested = false;
|
||||||
|
for (f.blocks.items, 0..) |blk, bi| {
|
||||||
|
if (!seen[bi] or blk.term != .ret) continue;
|
||||||
|
rets += 1;
|
||||||
|
ret_block = @intCast(bi);
|
||||||
|
// Inside a loop: not inlinable.
|
||||||
|
var c = ctx[bi];
|
||||||
|
while (c != root) : (c = parent[c]) {
|
||||||
|
if (f.blocks.items[c].merge == .loop) return .keep;
|
||||||
|
}
|
||||||
|
if (ctx[bi] != root) nested = true;
|
||||||
|
}
|
||||||
|
if (rets == 0) return .keep; // (never returns: leave it alone)
|
||||||
|
if (rets == 1 and !nested) return .{ .single = ret_block };
|
||||||
|
// A resource returned through a local would be a resource local
|
||||||
|
// assigned in several places.
|
||||||
|
if (isResource(m.types, f.ret)) return .keep;
|
||||||
|
return .wrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether `s`, a successor of a block whose innermost construct is headed
|
||||||
|
/// by `inner`, is that construct's (or an enclosing one's) merge or
|
||||||
|
/// continue target.
|
||||||
|
fn isExit(f: *const ir.Function, inner: u32, parent: []const u32, s: u32) bool {
|
||||||
|
var c = inner;
|
||||||
|
while (c != std.math.maxInt(u32)) : (c = parent[c]) {
|
||||||
|
switch (f.blocks.items[c].merge) {
|
||||||
|
.none => {},
|
||||||
|
.selection => |mb| if (mb.index() == s) return true,
|
||||||
|
.loop => |l| if (l.merge.index() == s or l.@"continue".index() == s) return true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn successors(a: Allocator, term: ir.Terminator) Error![]const BlockId {
|
||||||
|
return switch (term) {
|
||||||
|
.br => |b| try a.dupe(BlockId, &.{b}),
|
||||||
|
.cond_br => |c| try a.dupe(BlockId, &.{ c.then, c.@"else" }),
|
||||||
|
.@"switch" => |sw| blk: {
|
||||||
|
const out = try a.alloc(BlockId, sw.cases.len + 1);
|
||||||
|
out[0] = sw.default;
|
||||||
|
for (sw.cases, out[1..]) |c, *o| o.* = c.block;
|
||||||
|
break :blk out;
|
||||||
|
},
|
||||||
|
else => &.{},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
fn isRayQuery(t: *TypeTable, ty: types.TypeId) bool {
|
||||||
|
return switch (t.get(ty)) {
|
||||||
|
.resource => |r| r.kind == .other and std.mem.eql(u8, r.name, "RayQuery"),
|
||||||
|
else => false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
fn isResource(t: *TypeTable, ty: types.TypeId) bool {
|
||||||
|
return switch (t.get(ty)) {
|
||||||
|
.resource => !isRayQuery(t, ty),
|
||||||
|
.sampler => true,
|
||||||
|
.array => |x| isResource(t, x.elem),
|
||||||
|
else => false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
fn newBlock(a: Allocator, f: *ir.Function, blk: ir.Block) Error!u32 {
|
||||||
|
try f.blocks.append(a, blk);
|
||||||
|
return @intCast(f.blocks.items.len - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn newInst(a: Allocator, f: *ir.Function, inst: ir.Inst) Error!Ref {
|
||||||
|
try f.insts.append(a, inst);
|
||||||
|
return @fromBackingInt(@intCast(f.insts.items.len - 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Inlines every call in `f` whose callee has an inlinable shape (calls
|
||||||
|
/// in the copies included); callees of calls that stay go to `work`.
|
||||||
|
fn inlineCalls(m: *ir.Module, f: *ir.Function, shapes: []const ?Shape, work: *std.ArrayList(u32)) Error!void {
|
||||||
|
const a = m.arena;
|
||||||
|
// Call results, replaced by the callees' return values at the end.
|
||||||
|
var results: std.AutoHashMapUnmanaged(u32, Ref) = .empty;
|
||||||
|
var bi: usize = 0;
|
||||||
|
while (bi < f.blocks.items.len) : (bi += 1) {
|
||||||
|
var pos: usize = 0;
|
||||||
|
while (pos < f.blocks.items[bi].insts.items.len) : (pos += 1) {
|
||||||
|
const r = f.blocks.items[bi].insts.items[pos];
|
||||||
|
const call = switch (f.inst(r).op) {
|
||||||
|
.call => |c| c,
|
||||||
|
else => continue,
|
||||||
|
};
|
||||||
|
const shape = shapes[call.func] orelse .keep;
|
||||||
|
// A loop header keeps its instructions (its back edges target it).
|
||||||
|
if (shape == .keep or f.blocks.items[bi].merge == .loop) {
|
||||||
|
try work.append(a, call.func);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const callee = m.functions.items[call.func];
|
||||||
|
const value = try inlineOne(a, f, @intCast(bi), pos, call.args, callee, shape);
|
||||||
|
try results.put(a, r.index(), value);
|
||||||
|
// The rest of the block moved to the continuation block, which
|
||||||
|
// is later in the block list.
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (results.count() == 0) return;
|
||||||
|
const Map = struct {
|
||||||
|
res: *const std.AutoHashMapUnmanaged(u32, Ref),
|
||||||
|
pub fn map(c: @This(), x: Ref) Ref {
|
||||||
|
var y = x;
|
||||||
|
while (y != .none) {
|
||||||
|
y = c.res.get(y.index()) orelse return y;
|
||||||
|
}
|
||||||
|
return y;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const mp = Map{ .res = &results };
|
||||||
|
const Hit = struct {
|
||||||
|
res: *const std.AutoHashMapUnmanaged(u32, Ref),
|
||||||
|
hit: *bool,
|
||||||
|
pub fn use(c: @This(), x: Ref) void {
|
||||||
|
if (x != .none and c.res.contains(x.index())) c.hit.* = true;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
for (f.blocks.items) |*blk| {
|
||||||
|
for (blk.insts.items) |r| {
|
||||||
|
var hit = false;
|
||||||
|
opt.eachOperand(f.inst(r).op, Hit{ .res = &results, .hit = &hit });
|
||||||
|
if (hit) f.insts.items[r.index()].op = try opt.mapOp(a, f.inst(r).op, mp);
|
||||||
|
}
|
||||||
|
blk.term = mapTerm(blk.term, mp);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn mapTerm(term: ir.Terminator, mp: anytype) ir.Terminator {
|
||||||
|
return switch (term) {
|
||||||
|
.ret => |v| .{ .ret = mp.map(v) },
|
||||||
|
.cond_br => |c| .{ .cond_br = .{ .cond = mp.map(c.cond), .then = c.then, .@"else" = c.@"else" } },
|
||||||
|
.@"switch" => |s| .{ .@"switch" = .{ .value = mp.map(s.value), .default = s.default, .cases = s.cases } },
|
||||||
|
else => term,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Inlines `callee(args)`, the instruction at `pos` of block `bi` of `f`.
|
||||||
|
/// Returns the value the call produced (`.none` for void).
|
||||||
|
fn inlineOne(a: Allocator, f: *ir.Function, bi: u32, pos: usize, args: []const Ref, callee: *const ir.Function, shape: Shape) Error!Ref {
|
||||||
|
// Continuation: the instructions after the call, the terminator and
|
||||||
|
// the merge.
|
||||||
|
const cont = try newBlock(a, f, .{});
|
||||||
|
{
|
||||||
|
const blk = &f.blocks.items[bi];
|
||||||
|
try f.blocks.items[cont].insts.appendSlice(a, blk.insts.items[pos + 1 ..]);
|
||||||
|
f.blocks.items[cont].term = blk.term;
|
||||||
|
f.blocks.items[cont].merge = blk.merge;
|
||||||
|
f.blocks.items[cont].selection_control = blk.selection_control;
|
||||||
|
blk.insts.shrinkRetainingCapacity(pos);
|
||||||
|
blk.merge = .none;
|
||||||
|
blk.selection_control = .none;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Copies of the callee's blocks and instructions (parameters become
|
||||||
|
// the arguments). Only instructions in its blocks are copied up front;
|
||||||
|
// others it refers to (locals live in no block) are copied on first
|
||||||
|
// use: the callee's array also holds what earlier inlining left behind.
|
||||||
|
const bmap = try a.alloc(u32, callee.blocks.items.len);
|
||||||
|
for (bmap) |*b| b.* = try newBlock(a, f, .{});
|
||||||
|
const imap = try a.alloc(Ref, callee.insts.items.len);
|
||||||
|
@memset(imap, .none);
|
||||||
|
for (callee.blocks.items) |blk| for (blk.insts.items) |r| {
|
||||||
|
const inst = callee.inst(r);
|
||||||
|
imap[r.index()] = switch (inst.op) {
|
||||||
|
.param => |p| args[p],
|
||||||
|
else => try newInst(a, f, inst),
|
||||||
|
};
|
||||||
|
};
|
||||||
|
const Map = struct {
|
||||||
|
imap: []Ref,
|
||||||
|
f: *ir.Function,
|
||||||
|
callee: *const ir.Function,
|
||||||
|
args: []const Ref,
|
||||||
|
al: Allocator,
|
||||||
|
pub fn map(c: *const @This(), x: Ref) Ref {
|
||||||
|
if (x == .none) return x;
|
||||||
|
if (c.imap[x.index()] != .none) return c.imap[x.index()];
|
||||||
|
const inst = c.callee.inst(x);
|
||||||
|
const y = switch (inst.op) {
|
||||||
|
.param => |p| c.args[p],
|
||||||
|
else => newInst(c.al, c.f, inst) catch return x,
|
||||||
|
};
|
||||||
|
c.imap[x.index()] = y;
|
||||||
|
if (inst.op != .param) c.f.insts.items[y.index()].op = opt.mapOp(c.al, inst.op, c) catch inst.op;
|
||||||
|
return y;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const mp = &Map{ .imap = imap, .f = f, .callee = callee, .args = args, .al = a };
|
||||||
|
for (callee.blocks.items) |blk| for (blk.insts.items) |r| {
|
||||||
|
const inst = callee.inst(r);
|
||||||
|
if (inst.op == .param) continue;
|
||||||
|
f.insts.items[imap[r.index()].index()].op = try opt.mapOp(a, inst.op, mp);
|
||||||
|
};
|
||||||
|
const B = struct {
|
||||||
|
fn map(bm: []const u32, b: BlockId) BlockId {
|
||||||
|
return if (b == .none) b else @fromBackingInt(@intCast(bm[b.index()]));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Wrapping: header -> (callee entry) ... -> exit; an unreachable
|
||||||
|
// continue block; the return value in a local.
|
||||||
|
var exit: u32 = cont;
|
||||||
|
var ret_var: Ref = .none;
|
||||||
|
var result: Ref = .none;
|
||||||
|
var entry_target: u32 = bmap[0];
|
||||||
|
if (shape == .wrap) {
|
||||||
|
exit = try newBlock(a, f, .{});
|
||||||
|
const header = try newBlock(a, f, .{});
|
||||||
|
const latch = try newBlock(a, f, .{ .term = .{ .br = @fromBackingInt(@intCast(header)) } });
|
||||||
|
f.blocks.items[header].merge = .{ .loop = .{ .merge = @fromBackingInt(@intCast(exit)), .@"continue" = @fromBackingInt(@intCast(latch)), .unroll = .auto } };
|
||||||
|
f.blocks.items[header].term = .{ .br = @fromBackingInt(@intCast(bmap[0])) };
|
||||||
|
entry_target = header;
|
||||||
|
if (callee.ret != TypeTable.void_type) {
|
||||||
|
ret_var = try newInst(a, f, .{ .op = .local_var, .ty = callee.ret, .ptr = .function });
|
||||||
|
result = try newInst(a, f, .{ .op = .{ .load = ret_var }, .ty = callee.ret });
|
||||||
|
try f.blocks.items[exit].insts.append(a, result);
|
||||||
|
}
|
||||||
|
f.blocks.items[exit].term = .{ .br = @fromBackingInt(@intCast(cont)) };
|
||||||
|
}
|
||||||
|
|
||||||
|
for (callee.blocks.items, 0..) |src, k| {
|
||||||
|
var insts: std.ArrayList(Ref) = .empty;
|
||||||
|
for (src.insts.items) |r| {
|
||||||
|
if (callee.inst(r).op == .param) continue;
|
||||||
|
try insts.append(a, mp.map(r));
|
||||||
|
}
|
||||||
|
var term: ir.Terminator = switch (src.term) {
|
||||||
|
.ret => |v| blk: {
|
||||||
|
if (shape == .wrap) {
|
||||||
|
if (ret_var != .none and v != .none) {
|
||||||
|
const st = try newInst(a, f, .{ .op = .{ .store = .{ .ptr = ret_var, .value = mp.map(v) } }, .ty = TypeTable.void_type });
|
||||||
|
try insts.append(a, st);
|
||||||
|
}
|
||||||
|
break :blk .{ .br = @fromBackingInt(@intCast(exit)) };
|
||||||
|
}
|
||||||
|
if (v != .none) result = mp.map(v);
|
||||||
|
break :blk .{ .br = @fromBackingInt(@intCast(cont)) };
|
||||||
|
},
|
||||||
|
.br => |b| .{ .br = B.map(bmap, b) },
|
||||||
|
.cond_br => |c| .{ .cond_br = .{ .cond = mp.map(c.cond), .then = B.map(bmap, c.then), .@"else" = B.map(bmap, c.@"else") } },
|
||||||
|
.@"switch" => |sw| blk: {
|
||||||
|
const cases = try a.alloc(@typeInfo(@TypeOf(sw.cases)).pointer.child, sw.cases.len);
|
||||||
|
for (sw.cases, cases) |c, *o| o.* = .{ .value = c.value, .block = B.map(bmap, c.block) };
|
||||||
|
break :blk .{ .@"switch" = .{ .value = mp.map(sw.value), .default = B.map(bmap, sw.default), .cases = cases } };
|
||||||
|
},
|
||||||
|
else => src.term,
|
||||||
|
};
|
||||||
|
_ = &term;
|
||||||
|
const merge: ir.Merge = switch (src.merge) {
|
||||||
|
.none => .none,
|
||||||
|
.selection => |mb| .{ .selection = B.map(bmap, mb) },
|
||||||
|
.loop => |l| .{ .loop = .{ .merge = B.map(bmap, l.merge), .@"continue" = B.map(bmap, l.@"continue"), .unroll = l.unroll } },
|
||||||
|
};
|
||||||
|
f.blocks.items[bmap[k]] = .{ .insts = insts, .term = term, .merge = merge, .selection_control = src.selection_control };
|
||||||
|
}
|
||||||
|
f.blocks.items[bi].term = .{ .br = @fromBackingInt(@intCast(entry_target)) };
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Marks functions no root (entry wrappers and patch wrappers, exports)
|
||||||
|
/// reaches through calls as dead.
|
||||||
|
fn markDead(m: *ir.Module) Error!void {
|
||||||
|
const a = m.arena;
|
||||||
|
const n = m.functions.items.len;
|
||||||
|
const live = try a.alloc(bool, n);
|
||||||
|
@memset(live, false);
|
||||||
|
var stack: std.ArrayList(u32) = .empty;
|
||||||
|
for (m.entries.items) |e| {
|
||||||
|
try stack.append(a, e.wrapper);
|
||||||
|
if (e.patch_wrapper) |p| try stack.append(a, p);
|
||||||
|
}
|
||||||
|
try stack.appendSlice(a, m.exports.items);
|
||||||
|
while (stack.pop()) |fi| {
|
||||||
|
if (live[fi]) continue;
|
||||||
|
live[fi] = true;
|
||||||
|
const f = m.functions.items[fi];
|
||||||
|
for (f.blocks.items) |blk| for (blk.insts.items) |r| if (f.inst(r).op == .call) try stack.append(a, f.inst(r).op.call.func);
|
||||||
|
}
|
||||||
|
for (m.functions.items, live) |f, l| f.dead = !l;
|
||||||
|
}
|
||||||
|
|
@ -141,6 +141,9 @@ pub const Op = union(enum) {
|
||||||
emit: u32,
|
emit: u32,
|
||||||
cut: u32,
|
cut: u32,
|
||||||
phi: []const struct { value: Ref, block: BlockId },
|
phi: []const struct { value: Ref, block: BlockId },
|
||||||
|
/// An undefined value of the result type (a read before any write,
|
||||||
|
/// after promotion to SSA values).
|
||||||
|
undef,
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const Inst = struct {
|
pub const Inst = struct {
|
||||||
|
|
@ -177,8 +180,12 @@ pub const Block = struct {
|
||||||
insts: std.ArrayList(Ref) = .empty,
|
insts: std.ArrayList(Ref) = .empty,
|
||||||
term: Terminator = .none,
|
term: Terminator = .none,
|
||||||
merge: Merge = .none,
|
merge: Merge = .none,
|
||||||
|
/// `[flatten]` / `[branch]` on the selection this block heads.
|
||||||
|
selection_control: SelectionControl = .none,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
pub const SelectionControl = enum { none, flatten, dont_flatten };
|
||||||
|
|
||||||
pub const Param = struct {
|
pub const Param = struct {
|
||||||
name: []const u8,
|
name: []const u8,
|
||||||
ty: TypeId,
|
ty: TypeId,
|
||||||
|
|
@ -208,6 +215,8 @@ pub const Function = struct {
|
||||||
/// `[noinline]` (plain functions, not methods or template instances):
|
/// `[noinline]` (plain functions, not methods or template instances):
|
||||||
/// libraries keep it a function of its own.
|
/// libraries keep it a function of its own.
|
||||||
no_inline: bool = false,
|
no_inline: bool = false,
|
||||||
|
/// Nothing calls it any more (inlined everywhere): not emitted.
|
||||||
|
dead: bool = false,
|
||||||
insts: std.ArrayList(Inst) = .empty,
|
insts: std.ArrayList(Inst) = .empty,
|
||||||
blocks: std.ArrayList(Block) = .empty,
|
blocks: std.ArrayList(Block) = .empty,
|
||||||
|
|
||||||
|
|
@ -703,6 +712,7 @@ fn dumpInst(m: *const Module, f: *const Function, r: Ref, w: *std.Io.Writer) !vo
|
||||||
},
|
},
|
||||||
.input => |i| try w.print("input {d}", .{i}),
|
.input => |i| try w.print("input {d}", .{i}),
|
||||||
.output => |o| try w.print("output {d}, %{d}", .{ o.element, o.value.index() }),
|
.output => |o| try w.print("output {d}, %{d}", .{ o.element, o.value.index() }),
|
||||||
|
.undef => try w.writeAll("undef"),
|
||||||
.phi => |ins| {
|
.phi => |ins| {
|
||||||
try w.writeAll("phi");
|
try w.writeAll("phi");
|
||||||
for (ins, 0..) |in, i| try w.print("{s} [%{d}, b{d}]", .{ if (i > 0) "," else "", in.value.index(), in.block.index() });
|
for (ins, 0..) |in, i| try w.print("{s} [%{d}, b{d}]", .{ if (i > 0) "," else "", in.value.index(), in.block.index() });
|
||||||
|
|
|
||||||
|
|
@ -565,6 +565,7 @@ const Lowerer = struct {
|
||||||
const merge = try l.b.newBlock();
|
const merge = try l.b.newBlock();
|
||||||
const else_b = if (x.@"else" != null) try l.b.newBlock() else merge;
|
const else_b = if (x.@"else" != null) try l.b.newBlock() else merge;
|
||||||
l.b.f.block(l.b.cur).merge = .{ .selection = merge };
|
l.b.f.block(l.b.cur).merge = .{ .selection = merge };
|
||||||
|
l.b.f.block(l.b.cur).selection_control = selectionControl(st.attrs);
|
||||||
l.b.terminate(.{ .cond_br = .{ .cond = cond, .then = then_b, .@"else" = else_b } });
|
l.b.terminate(.{ .cond_br = .{ .cond = cond, .then = then_b, .@"else" = else_b } });
|
||||||
l.b.setBlock(then_b);
|
l.b.setBlock(then_b);
|
||||||
try l.stmt(x.then);
|
try l.stmt(x.then);
|
||||||
|
|
@ -597,7 +598,7 @@ const Lowerer = struct {
|
||||||
l.b.terminate(.{ .br = target.cont });
|
l.b.terminate(.{ .br = target.cont });
|
||||||
},
|
},
|
||||||
.discard => l.b.terminate(.discard),
|
.discard => l.b.terminate(.discard),
|
||||||
.@"switch" => |x| try l.switchStmt(x),
|
.@"switch" => |x| try l.switchStmt(x, st.attrs),
|
||||||
.case, .default => {
|
.case, .default => {
|
||||||
l.unsupported(st.loc, "case labels outside a switch body", .{});
|
l.unsupported(st.loc, "case labels outside a switch body", .{});
|
||||||
return error.Unsupported;
|
return error.Unsupported;
|
||||||
|
|
@ -607,7 +608,16 @@ const Lowerer = struct {
|
||||||
|
|
||||||
/// `switch`: the header branches to one block per label (labels in a
|
/// `switch`: the header branches to one block per label (labels in a
|
||||||
/// row get their own, falling through); `break` goes to the merge.
|
/// row get their own, falling through); `break` goes to the merge.
|
||||||
fn switchStmt(l: *Lowerer, x: @FieldType(ast.Stmt.Kind, "switch")) Error!void {
|
/// `[flatten]` / `[branch]` on an `if` or `switch`.
|
||||||
|
fn selectionControl(attrs: []const ast.Attribute) ir.SelectionControl {
|
||||||
|
for (attrs) |a| {
|
||||||
|
if (std.ascii.eqlIgnoreCase(a.name, "flatten")) return .flatten;
|
||||||
|
if (std.ascii.eqlIgnoreCase(a.name, "branch")) return .dont_flatten;
|
||||||
|
}
|
||||||
|
return .none;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn switchStmt(l: *Lowerer, x: @FieldType(ast.Stmt.Kind, "switch"), attrs: []const ast.Attribute) Error!void {
|
||||||
if (x.cond_decl) |d| try l.localDecl(d);
|
if (x.cond_decl) |d| try l.localDecl(d);
|
||||||
const t = l.types();
|
const t = l.types();
|
||||||
var cond_ty = x.cond.ty;
|
var cond_ty = x.cond.ty;
|
||||||
|
|
@ -648,6 +658,7 @@ const Lowerer = struct {
|
||||||
if (sg.value) |v| try cases.append(l.arena, .{ .value = v, .block = sg.block }) else default = sg.block;
|
if (sg.value) |v| try cases.append(l.arena, .{ .value = v, .block = sg.block }) else default = sg.block;
|
||||||
}
|
}
|
||||||
l.b.f.block(header).merge = .{ .selection = merge };
|
l.b.f.block(header).merge = .{ .selection = merge };
|
||||||
|
l.b.f.block(header).selection_control = selectionControl(attrs);
|
||||||
l.b.terminate(.{ .@"switch" = .{ .value = cond, .default = default, .cases = cases.items } });
|
l.b.terminate(.{ .@"switch" = .{ .value = cond, .default = default, .cases = cases.items } });
|
||||||
const cont: BlockId = if (l.loops.items.len > 0) l.loops.getLast().cont else .none;
|
const cont: BlockId = if (l.loops.items.len > 0) l.loops.getLast().cont else .none;
|
||||||
try l.loops.append(l.arena, .{ .brk = merge, .cont = cont });
|
try l.loops.append(l.arena, .{ .brk = merge, .cont = cont });
|
||||||
|
|
|
||||||
|
|
@ -181,7 +181,7 @@ fn mapRefs(a: Allocator, xs: []const Ref, ctx: anytype) Allocator.Error![]const
|
||||||
/// `op` with every operand passed through `ctx.map`.
|
/// `op` with every operand passed through `ctx.map`.
|
||||||
pub fn mapOp(a: Allocator, op: Op, ctx: anytype) Allocator.Error!Op {
|
pub fn mapOp(a: Allocator, op: Op, ctx: anytype) Allocator.Error!Op {
|
||||||
return switch (op) {
|
return switch (op) {
|
||||||
.constant, .param, .global, .local_var, .input, .input_vertex, .emit, .cut, .patch_input, .output_vertex, .mesh_output, .mesh_payload, .ray_incoming, .spec_constant => op,
|
.constant, .param, .global, .local_var, .input, .input_vertex, .emit, .cut, .patch_input, .output_vertex, .mesh_output, .mesh_payload, .ray_incoming, .spec_constant, .undef => op,
|
||||||
.load => |p| .{ .load = ctx.map(p) },
|
.load => |p| .{ .load = ctx.map(p) },
|
||||||
.store => |x| .{ .store = .{ .ptr = ctx.map(x.ptr), .value = ctx.map(x.value) } },
|
.store => |x| .{ .store = .{ .ptr = ctx.map(x.ptr), .value = ctx.map(x.value) } },
|
||||||
.access => |x| .{ .access = .{ .base = ctx.map(x.base), .indices = try mapRefs(a, x.indices, ctx) } },
|
.access => |x| .{ .access = .{ .base = ctx.map(x.base), .indices = try mapRefs(a, x.indices, ctx) } },
|
||||||
|
|
@ -223,6 +223,68 @@ pub fn mapOp(a: Allocator, op: Op, ctx: anytype) Allocator.Error!Op {
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Calls `ctx.use(r)` for every operand of `op` (none skipped), without
|
||||||
|
/// allocating.
|
||||||
|
pub fn eachOperand(op: Op, ctx: anytype) void {
|
||||||
|
switch (op) {
|
||||||
|
.constant, .param, .global, .local_var, .input, .input_vertex, .emit, .cut, .patch_input, .output_vertex, .mesh_output, .mesh_payload, .ray_incoming, .spec_constant, .undef => {},
|
||||||
|
.load => |p| ctx.use(p),
|
||||||
|
.store => |x| {
|
||||||
|
ctx.use(x.ptr);
|
||||||
|
ctx.use(x.value);
|
||||||
|
},
|
||||||
|
.access => |x| {
|
||||||
|
ctx.use(x.base);
|
||||||
|
for (x.indices) |r| ctx.use(r);
|
||||||
|
},
|
||||||
|
.binary => |x| {
|
||||||
|
ctx.use(x.lhs);
|
||||||
|
ctx.use(x.rhs);
|
||||||
|
},
|
||||||
|
.unary => |x| ctx.use(x.operand),
|
||||||
|
.cmp => |x| {
|
||||||
|
ctx.use(x.lhs);
|
||||||
|
ctx.use(x.rhs);
|
||||||
|
},
|
||||||
|
.convert, .bitcast, .splat => |x| ctx.use(x),
|
||||||
|
.extract => |x| ctx.use(x.agg),
|
||||||
|
.insert => |x| {
|
||||||
|
ctx.use(x.agg);
|
||||||
|
ctx.use(x.value);
|
||||||
|
},
|
||||||
|
.construct => |xs| for (xs) |r| ctx.use(r),
|
||||||
|
.shuffle => |x| ctx.use(x.vec),
|
||||||
|
.select => |x| {
|
||||||
|
ctx.use(x.cond);
|
||||||
|
ctx.use(x.t);
|
||||||
|
ctx.use(x.f);
|
||||||
|
},
|
||||||
|
.call => |x| for (x.args) |r| ctx.use(r),
|
||||||
|
.intrinsic => |x| for (x.args) |r| ctx.use(r),
|
||||||
|
.res_load => |x| {
|
||||||
|
ctx.use(x.res);
|
||||||
|
ctx.use(x.index);
|
||||||
|
},
|
||||||
|
.res_store => |x| {
|
||||||
|
ctx.use(x.res);
|
||||||
|
ctx.use(x.index);
|
||||||
|
ctx.use(x.value);
|
||||||
|
},
|
||||||
|
.method => |x| {
|
||||||
|
ctx.use(x.res);
|
||||||
|
for (x.args) |r| ctx.use(r);
|
||||||
|
},
|
||||||
|
.output => |x| ctx.use(x.value),
|
||||||
|
.heap_resource => |h| ctx.use(h.index),
|
||||||
|
.spirv_inst => |x| for (x.operands) |o| switch (o) {
|
||||||
|
.value => |v| ctx.use(v),
|
||||||
|
.literal, .type => {},
|
||||||
|
},
|
||||||
|
.patch_output => |x| ctx.use(x.value),
|
||||||
|
.phi => |ps| for (ps) |pp| ctx.use(pp.value),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Calls `ctx.use(r)` for every operand of `op` and of terminator `term`.
|
/// Calls `ctx.use(r)` for every operand of `op` and of terminator `term`.
|
||||||
fn forOperands(a: Allocator, op: Op, ctx: anytype) Allocator.Error!void {
|
fn forOperands(a: Allocator, op: Op, ctx: anytype) Allocator.Error!void {
|
||||||
const Collect = struct {
|
const Collect = struct {
|
||||||
|
|
@ -672,7 +734,7 @@ fn unrollOne(a: Allocator, t: *TypeTable, f: *ir.Function, h: u32, set: []const
|
||||||
.selection => |b| .{ .selection = mapBlock(&bmap, b) },
|
.selection => |b| .{ .selection = mapBlock(&bmap, b) },
|
||||||
.loop => |l| .{ .loop = .{ .merge = mapBlock(&bmap, l.merge), .@"continue" = mapBlock(&bmap, l.@"continue"), .unroll = l.unroll } },
|
.loop => |l| .{ .loop = .{ .merge = mapBlock(&bmap, l.merge), .@"continue" = mapBlock(&bmap, l.@"continue"), .unroll = l.unroll } },
|
||||||
};
|
};
|
||||||
f.blocks.items[nb] = .{ .insts = insts, .term = term, .merge = mg };
|
f.blocks.items[nb] = .{ .insts = insts, .term = term, .merge = mg, .selection_control = src.selection_control };
|
||||||
}
|
}
|
||||||
entries[iter] = bmap.get(body).?;
|
entries[iter] = bmap.get(body).?;
|
||||||
conts[iter] = bmap.get(cont).?;
|
conts[iter] = bmap.get(cont).?;
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,811 @@
|
||||||
|
//! Promotion of locals to SSA values for SPIR-V (dxc's SPIR-V gets it from
|
||||||
|
//! its optimizer's ssa-rewrite and local-access-chain-convert): drivers get
|
||||||
|
//! values instead of Function variables, and inlined code its parameters
|
||||||
|
//! and temporaries as values.
|
||||||
|
//!
|
||||||
|
//! 1. A local struct or array accessed only with constant indices (and
|
||||||
|
//! whole) is split into one local per leaf member / element (scalar
|
||||||
|
//! replacement): whole reads construct the value, whole writes store
|
||||||
|
//! each part. Promoting whole aggregates instead would turn each member
|
||||||
|
//! write into a copy of the aggregate, which drivers do not undo.
|
||||||
|
//! 2. Locals then only loaded and stored whole (not resources) are
|
||||||
|
//! promoted: phis where values of a variable live across blocks meet
|
||||||
|
//! (semi-pruned SSA over dominance frontiers), loads replaced by the
|
||||||
|
//! value reaching them, stores and the locals removed. A read before any
|
||||||
|
//! write is `undef`.
|
||||||
|
//!
|
||||||
|
//! Phis get one incoming value per predecessor the emitter writes out,
|
||||||
|
//! unreachable merge and continue targets included (`undef` from those).
|
||||||
|
|
||||||
|
const std = @import("std");
|
||||||
|
const Allocator = std.mem.Allocator;
|
||||||
|
const ir = @import("ir.zig");
|
||||||
|
const types = @import("../sema/types.zig");
|
||||||
|
const opt = @import("opt.zig");
|
||||||
|
|
||||||
|
const Ref = ir.Ref;
|
||||||
|
const BlockId = ir.BlockId;
|
||||||
|
const TypeId = types.TypeId;
|
||||||
|
const TypeTable = types.TypeTable;
|
||||||
|
|
||||||
|
pub const Error = Allocator.Error;
|
||||||
|
|
||||||
|
pub fn run(m: *ir.Module) Error!void {
|
||||||
|
// (The same modules as inlining, for now.)
|
||||||
|
if (!@import("inline.zig").eligible(m)) return;
|
||||||
|
for (m.functions.items) |f| {
|
||||||
|
if (f.dead) continue;
|
||||||
|
try splitLocals(m, f);
|
||||||
|
try promote(m, f);
|
||||||
|
// Values that were behind locals may fold now.
|
||||||
|
try opt.fold(m.arena, m.types, f);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----------------------------------------------------------------------
|
||||||
|
// Uses
|
||||||
|
|
||||||
|
fn addInst(a: Allocator, f: *ir.Function, inst: ir.Inst) Error!Ref {
|
||||||
|
try f.insts.append(a, inst);
|
||||||
|
return @fromBackingInt(@intCast(f.insts.items.len - 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Calls `ctx.use(r)` for every operand of `op` (not `.none`).
|
||||||
|
fn forOperands(a: Allocator, op: ir.Op, ctx: anytype) Error!void {
|
||||||
|
_ = a;
|
||||||
|
const Skip = struct {
|
||||||
|
inner: @TypeOf(ctx),
|
||||||
|
pub fn use(c: @This(), r: Ref) void {
|
||||||
|
if (r != .none) c.inner.use(r);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
opt.eachOperand(op, Skip{ .inner = ctx });
|
||||||
|
}
|
||||||
|
|
||||||
|
fn termOperand(term: ir.Terminator) Ref {
|
||||||
|
return switch (term) {
|
||||||
|
.ret => |r| r,
|
||||||
|
.cond_br => |c| c.cond,
|
||||||
|
.@"switch" => |s| s.value,
|
||||||
|
else => .none,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
fn successors(a: Allocator, term: ir.Terminator) Error![]const BlockId {
|
||||||
|
return switch (term) {
|
||||||
|
.br => |b| try a.dupe(BlockId, &.{b}),
|
||||||
|
.cond_br => |c| if (c.then == c.@"else") try a.dupe(BlockId, &.{c.then}) else try a.dupe(BlockId, &.{ c.then, c.@"else" }),
|
||||||
|
.@"switch" => |sw| blk: {
|
||||||
|
var out: std.ArrayList(BlockId) = .empty;
|
||||||
|
try out.append(a, sw.default);
|
||||||
|
for (sw.cases) |c| {
|
||||||
|
if (std.mem.indexOfScalar(BlockId, out.items, c.block) == null) try out.append(a, c.block);
|
||||||
|
}
|
||||||
|
break :blk out.items;
|
||||||
|
},
|
||||||
|
else => &.{},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A local's type is promotable: no resources, ray queries or other opaque
|
||||||
|
/// values anywhere in it.
|
||||||
|
fn plainType(t: *TypeTable, ty: TypeId) bool {
|
||||||
|
return switch (t.get(ty)) {
|
||||||
|
.scalar, .vector, .matrix, .@"enum" => true,
|
||||||
|
.array => |x| x.len > 0 and plainType(t, x.elem),
|
||||||
|
.@"struct" => |st| {
|
||||||
|
for (st.fields.items) |fld| if (!plainType(t, fld.type)) return false;
|
||||||
|
for (st.bases.items) |_| return false;
|
||||||
|
return true;
|
||||||
|
},
|
||||||
|
else => false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----------------------------------------------------------------------
|
||||||
|
// 1. Scalar replacement
|
||||||
|
|
||||||
|
/// Where each instruction is: block and position (for instructions in a
|
||||||
|
/// block).
|
||||||
|
const Place = struct { block: u32, pos: u32 };
|
||||||
|
|
||||||
|
fn constIndex(f: *const ir.Function, r: Ref) ?u32 {
|
||||||
|
const i = f.inst(r);
|
||||||
|
if (i.op != .constant or i.op.constant != .int) return null;
|
||||||
|
const v = i.op.constant.int;
|
||||||
|
if (v < 0 or v > std.math.maxInt(u32)) return null;
|
||||||
|
return @intCast(v);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The type one constant index into `ty` selects (structs and arrays).
|
||||||
|
fn stepType(t: *TypeTable, ty: TypeId, k: u32) ?TypeId {
|
||||||
|
return switch (t.get(ty)) {
|
||||||
|
.@"struct" => |st| if (k < st.fields.items.len) st.fields.items[k].type else null,
|
||||||
|
.array => |x| if (k < x.len) x.elem else null,
|
||||||
|
else => null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
fn splitLocals(m: *ir.Module, f: *ir.Function) Error!void {
|
||||||
|
const a = m.arena;
|
||||||
|
const t = m.types;
|
||||||
|
const n = f.insts.items.len;
|
||||||
|
// Uses of every instruction (in blocks), and whether each is in one.
|
||||||
|
const in_block = try a.alloc(bool, n);
|
||||||
|
@memset(in_block, false);
|
||||||
|
for (f.blocks.items) |blk| for (blk.insts.items) |r| {
|
||||||
|
in_block[r.index()] = true;
|
||||||
|
};
|
||||||
|
// root[x]: the local an access chain `x` is rooted at (none if not one
|
||||||
|
// of a convertible chain); path from the root.
|
||||||
|
const root = try a.alloc(Ref, n);
|
||||||
|
@memset(root, .none);
|
||||||
|
const paths = try a.alloc([]const u32, n);
|
||||||
|
// Candidate locals: struct / array locals of plain types.
|
||||||
|
const cand = try a.alloc(bool, n);
|
||||||
|
@memset(cand, false);
|
||||||
|
var any = false;
|
||||||
|
for (f.insts.items, 0..) |inst, i| {
|
||||||
|
// (Locals are function-wide: some live in no block.)
|
||||||
|
if (inst.op != .local_var or inst.ptr != .function) continue;
|
||||||
|
const k = t.get(inst.ty);
|
||||||
|
if ((k == .@"struct" or k == .array) and plainType(t, inst.ty)) {
|
||||||
|
cand[i] = true;
|
||||||
|
root[i] = @fromBackingInt(@intCast(i));
|
||||||
|
paths[i] = &.{};
|
||||||
|
any = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!any) return;
|
||||||
|
// Chains in instruction order: an access's base precedes it in f.insts
|
||||||
|
// when lowering made it; iterate to a fixed point to be safe.
|
||||||
|
var changed = true;
|
||||||
|
while (changed) {
|
||||||
|
changed = false;
|
||||||
|
for (f.insts.items, 0..) |inst, i| {
|
||||||
|
if (!in_block[i] or root[i] != .none) continue;
|
||||||
|
const acc = switch (inst.op) {
|
||||||
|
.access => |x| x,
|
||||||
|
else => continue,
|
||||||
|
};
|
||||||
|
const rb = root[acc.base.index()];
|
||||||
|
if (rb == .none or !cand[rb.index()]) continue;
|
||||||
|
var ty = f.inst(acc.base).ty;
|
||||||
|
var path: std.ArrayList(u32) = .empty;
|
||||||
|
try path.appendSlice(a, paths[acc.base.index()]);
|
||||||
|
const ok = for (acc.indices) |x| {
|
||||||
|
const k = constIndex(f, x) orelse break false;
|
||||||
|
ty = stepType(t, ty, k) orelse break false;
|
||||||
|
try path.append(a, k);
|
||||||
|
} else true;
|
||||||
|
if (!ok) {
|
||||||
|
cand[rb.index()] = false;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
root[i] = rb;
|
||||||
|
paths[i] = path.items;
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Every use of a chain (or of the local) must be a load, a store to it
|
||||||
|
// or a further chain; anything else disqualifies the local.
|
||||||
|
const Check = struct {
|
||||||
|
f: *const ir.Function,
|
||||||
|
root: []const Ref,
|
||||||
|
cand: []bool,
|
||||||
|
user: Ref,
|
||||||
|
pub fn use(c: @This(), x: Ref) void {
|
||||||
|
const rt = c.root[x.index()];
|
||||||
|
if (rt == .none) return;
|
||||||
|
const u = c.f.inst(c.user).op;
|
||||||
|
const fine = switch (u) {
|
||||||
|
.load => true,
|
||||||
|
.store => |s| s.ptr == x and s.value != x,
|
||||||
|
.access => |acc| acc.base == x and c.root[c.user.index()] == rt,
|
||||||
|
else => false,
|
||||||
|
};
|
||||||
|
if (!fine) c.cand[rt.index()] = false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
for (f.blocks.items) |blk| {
|
||||||
|
for (blk.insts.items) |r| try forOperands(a, f.inst(r).op, Check{ .f = f, .root = root, .cand = cand, .user = r });
|
||||||
|
const tr = termOperand(blk.term);
|
||||||
|
if (tr != .none and root[tr.index()] != .none) cand[root[tr.index()].index()] = false;
|
||||||
|
}
|
||||||
|
// Split each remaining candidate into one local per leaf (scalar,
|
||||||
|
// vector or matrix member / element), in depth-first order; aggregates
|
||||||
|
// with too many leaves stay whole.
|
||||||
|
const leaf_base = try a.alloc(u32, n); // first leaf local of a candidate
|
||||||
|
var leaves: std.ArrayList(Ref) = .empty;
|
||||||
|
for (0..n) |i| {
|
||||||
|
if (!cand[i]) continue;
|
||||||
|
const count = leafCount(t, f.inst(@fromBackingInt(@intCast(i))).ty);
|
||||||
|
if (count > max_leaves) {
|
||||||
|
cand[i] = false;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
leaf_base[i] = @intCast(leaves.items.len);
|
||||||
|
try addLeaves(a, f, t, f.inst(@fromBackingInt(@intCast(i))).ty, &leaves);
|
||||||
|
}
|
||||||
|
defer for (0..n) |i| if (cand[i]) {
|
||||||
|
// Split: the aggregate local is gone (the emitter declares every
|
||||||
|
// local_var).
|
||||||
|
f.insts.items[i] = .{ .op = .undef, .ty = f.insts.items[i].ty };
|
||||||
|
};
|
||||||
|
// Rewrite loads and stores through the candidates and their chains.
|
||||||
|
for (f.blocks.items) |*blk| {
|
||||||
|
var out: std.ArrayList(Ref) = .empty;
|
||||||
|
for (blk.insts.items) |r| {
|
||||||
|
const inst = f.inst(r);
|
||||||
|
switch (inst.op) {
|
||||||
|
.access => if (root[r.index()] != .none and cand[root[r.index()].index()]) continue,
|
||||||
|
.local_var => if (cand[r.index()]) continue,
|
||||||
|
.load => |p| {
|
||||||
|
const rt = root[p.index()];
|
||||||
|
if (rt != .none and cand[rt.index()]) {
|
||||||
|
const at = leafAt(t, f.inst(rt).ty, paths[p.index()]);
|
||||||
|
const base = leaves.items[leaf_base[rt.index()] + at.offset ..];
|
||||||
|
const v = try gather(a, f, t, at.ty, base, &out);
|
||||||
|
// The load becomes the gathered value.
|
||||||
|
f.insts.items[r.index()].op = f.inst(v).op;
|
||||||
|
if (out.items.len > 0 and out.items[out.items.len - 1] == v) out.items[out.items.len - 1] = r else try out.append(a, r);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
.store => |st| {
|
||||||
|
const rt = root[st.ptr.index()];
|
||||||
|
if (rt != .none and cand[rt.index()]) {
|
||||||
|
const at = leafAt(t, f.inst(rt).ty, paths[st.ptr.index()]);
|
||||||
|
const base = leaves.items[leaf_base[rt.index()] + at.offset ..];
|
||||||
|
try scatter(a, f, t, at.ty, base, st.value, &out);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
else => {},
|
||||||
|
}
|
||||||
|
try out.append(a, r);
|
||||||
|
}
|
||||||
|
blk.insts = out;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Aggregates split into at most this many locals.
|
||||||
|
const max_leaves = 64;
|
||||||
|
|
||||||
|
fn isAggregate(t: *TypeTable, ty: TypeId) bool {
|
||||||
|
return switch (t.get(ty)) {
|
||||||
|
.@"struct", .array => true,
|
||||||
|
else => false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
fn leafCount(t: *TypeTable, ty: TypeId) u32 {
|
||||||
|
return switch (t.get(ty)) {
|
||||||
|
.@"struct" => |st| blk: {
|
||||||
|
var c: u32 = 0;
|
||||||
|
for (st.fields.items) |fld| c +|= leafCount(t, fld.type);
|
||||||
|
break :blk c;
|
||||||
|
},
|
||||||
|
.array => |x| x.len *| leafCount(t, x.elem),
|
||||||
|
else => 1,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
fn addLeaves(a: Allocator, f: *ir.Function, t: *TypeTable, ty: TypeId, out: *std.ArrayList(Ref)) Error!void {
|
||||||
|
switch (t.get(ty)) {
|
||||||
|
.@"struct" => |st| for (st.fields.items) |fld| try addLeaves(a, f, t, fld.type, out),
|
||||||
|
.array => |x| for (0..x.len) |_| try addLeaves(a, f, t, x.elem, out),
|
||||||
|
else => try out.append(a, try addInst(a, f, .{ .op = .local_var, .ty = ty, .ptr = .function })),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The member a path selects: its type and first leaf (depth-first).
|
||||||
|
fn leafAt(t: *TypeTable, ty0: TypeId, path: []const u32) struct { ty: TypeId, offset: u32 } {
|
||||||
|
var ty = ty0;
|
||||||
|
var off: u32 = 0;
|
||||||
|
for (path) |k| switch (t.get(ty)) {
|
||||||
|
.@"struct" => |st| {
|
||||||
|
for (st.fields.items[0..k]) |fld| off += leafCount(t, fld.type);
|
||||||
|
ty = st.fields.items[k].type;
|
||||||
|
},
|
||||||
|
.array => |x| {
|
||||||
|
off += k * leafCount(t, x.elem);
|
||||||
|
ty = x.elem;
|
||||||
|
},
|
||||||
|
else => unreachable,
|
||||||
|
};
|
||||||
|
return .{ .ty = ty, .offset = off };
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The value of type `ty` held in the leaf locals from `leaves[0]`: a load
|
||||||
|
/// of a leaf, or a construct of its members' values.
|
||||||
|
fn gather(a: Allocator, f: *ir.Function, t: *TypeTable, ty: TypeId, leaves: []const Ref, out: *std.ArrayList(Ref)) Error!Ref {
|
||||||
|
if (!isAggregate(t, ty)) {
|
||||||
|
const v = try addInst(a, f, .{ .op = .{ .load = leaves[0] }, .ty = ty });
|
||||||
|
try out.append(a, v);
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
var parts: std.ArrayList(Ref) = .empty;
|
||||||
|
var off: u32 = 0;
|
||||||
|
switch (t.get(ty)) {
|
||||||
|
.@"struct" => |st| for (st.fields.items) |fld| {
|
||||||
|
try parts.append(a, try gather(a, f, t, fld.type, leaves[off..], out));
|
||||||
|
off += leafCount(t, fld.type);
|
||||||
|
},
|
||||||
|
.array => |x| for (0..x.len) |_| {
|
||||||
|
try parts.append(a, try gather(a, f, t, x.elem, leaves[off..], out));
|
||||||
|
off += leafCount(t, x.elem);
|
||||||
|
},
|
||||||
|
else => unreachable,
|
||||||
|
}
|
||||||
|
const v = try addInst(a, f, .{ .op = .{ .construct = parts.items }, .ty = ty });
|
||||||
|
try out.append(a, v);
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stores value `v` of type `ty` into the leaf locals from `leaves[0]`.
|
||||||
|
fn scatter(a: Allocator, f: *ir.Function, t: *TypeTable, ty: TypeId, leaves: []const Ref, v: Ref, out: *std.ArrayList(Ref)) Error!void {
|
||||||
|
if (!isAggregate(t, ty)) {
|
||||||
|
try out.append(a, try addInst(a, f, .{ .op = .{ .store = .{ .ptr = leaves[0], .value = v } }, .ty = TypeTable.void_type }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
var off: u32 = 0;
|
||||||
|
switch (t.get(ty)) {
|
||||||
|
.@"struct" => |st| for (st.fields.items, 0..) |fld, k| {
|
||||||
|
const x = try addInst(a, f, .{ .op = .{ .extract = .{ .agg = v, .index = @intCast(k) } }, .ty = fld.type });
|
||||||
|
try out.append(a, x);
|
||||||
|
try scatter(a, f, t, fld.type, leaves[off..], x, out);
|
||||||
|
off += leafCount(t, fld.type);
|
||||||
|
},
|
||||||
|
.array => |arr| for (0..arr.len) |k| {
|
||||||
|
const x = try addInst(a, f, .{ .op = .{ .extract = .{ .agg = v, .index = @intCast(k) } }, .ty = arr.elem });
|
||||||
|
try out.append(a, x);
|
||||||
|
try scatter(a, f, t, arr.elem, leaves[off..], x, out);
|
||||||
|
off += leafCount(t, arr.elem);
|
||||||
|
},
|
||||||
|
else => unreachable,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----------------------------------------------------------------------
|
||||||
|
// 2. Promotion
|
||||||
|
|
||||||
|
fn promote(m: *ir.Module, f: *ir.Function) Error!void {
|
||||||
|
const a = m.arena;
|
||||||
|
const t = m.types;
|
||||||
|
const nb = f.blocks.items.len;
|
||||||
|
const ni = f.insts.items.len;
|
||||||
|
|
||||||
|
// Promotable locals: plain types, every use a whole load or a store to
|
||||||
|
// them.
|
||||||
|
const var_of = try a.alloc(u32, ni); // inst -> var index (maxInt: none)
|
||||||
|
const none = std.math.maxInt(u32);
|
||||||
|
@memset(var_of, none);
|
||||||
|
var vars: std.ArrayList(Ref) = .empty;
|
||||||
|
const in_block = try a.alloc(bool, ni);
|
||||||
|
@memset(in_block, false);
|
||||||
|
for (f.blocks.items) |blk| for (blk.insts.items) |r| {
|
||||||
|
in_block[r.index()] = true;
|
||||||
|
};
|
||||||
|
for (f.insts.items, 0..) |inst, i| {
|
||||||
|
if (inst.op != .local_var or inst.ptr != .function or !plainType(t, inst.ty)) continue;
|
||||||
|
var_of[i] = @intCast(vars.items.len);
|
||||||
|
try vars.append(a, @fromBackingInt(@intCast(i)));
|
||||||
|
}
|
||||||
|
if (vars.items.len == 0) return;
|
||||||
|
const ok = try a.alloc(bool, vars.items.len);
|
||||||
|
@memset(ok, true);
|
||||||
|
const Check = struct {
|
||||||
|
f: *const ir.Function,
|
||||||
|
var_of: []const u32,
|
||||||
|
ok: []bool,
|
||||||
|
user: Ref,
|
||||||
|
pub fn use(c: @This(), x: Ref) void {
|
||||||
|
const v = c.var_of[x.index()];
|
||||||
|
if (v == std.math.maxInt(u32)) return;
|
||||||
|
const fine = switch (c.f.inst(c.user).op) {
|
||||||
|
.load => true,
|
||||||
|
.store => |s| s.ptr == x and s.value != x,
|
||||||
|
else => false,
|
||||||
|
};
|
||||||
|
if (!fine) c.ok[v] = false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
for (f.blocks.items) |blk| {
|
||||||
|
for (blk.insts.items) |r| try forOperands(a, f.inst(r).op, Check{ .f = f, .var_of = var_of, .ok = ok, .user = r });
|
||||||
|
const tr = termOperand(blk.term);
|
||||||
|
if (tr != .none and var_of[tr.index()] != none) ok[var_of[tr.index()]] = false;
|
||||||
|
}
|
||||||
|
// Renumber the promoted ones.
|
||||||
|
var pvars: std.ArrayList(Ref) = .empty;
|
||||||
|
for (vars.items, 0..) |v, k| {
|
||||||
|
if (ok[k]) {
|
||||||
|
var_of[v.index()] = @intCast(pvars.items.len);
|
||||||
|
try pvars.append(a, v);
|
||||||
|
} else var_of[v.index()] = none;
|
||||||
|
}
|
||||||
|
const nv = pvars.items.len;
|
||||||
|
if (nv == 0) return;
|
||||||
|
// CFG: reachable blocks (from the entry) and emitted ones (reachable,
|
||||||
|
// plus unreachable merge / continue targets and what they reach, as
|
||||||
|
// the emitter's block order).
|
||||||
|
const succs = try a.alloc([]const BlockId, nb);
|
||||||
|
for (f.blocks.items, succs) |blk, *s| s.* = try successors(a, blk.term);
|
||||||
|
const reach = try a.alloc(bool, nb);
|
||||||
|
@memset(reach, false);
|
||||||
|
var rpo: std.ArrayList(u32) = .empty;
|
||||||
|
{
|
||||||
|
// Iterative DFS post-order.
|
||||||
|
var post: std.ArrayList(u32) = .empty;
|
||||||
|
var stack: std.ArrayList(struct { b: u32, next: u32 }) = .empty;
|
||||||
|
reach[0] = true;
|
||||||
|
try stack.append(a, .{ .b = 0, .next = 0 });
|
||||||
|
while (stack.items.len > 0) {
|
||||||
|
const top = &stack.items[stack.items.len - 1];
|
||||||
|
const ss = succs[top.b];
|
||||||
|
if (top.next < ss.len) {
|
||||||
|
const s = ss[top.next].index();
|
||||||
|
top.next += 1;
|
||||||
|
if (!reach[s]) {
|
||||||
|
reach[s] = true;
|
||||||
|
try stack.append(a, .{ .b = s, .next = 0 });
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
try post.append(a, top.b);
|
||||||
|
_ = stack.pop();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var i = post.items.len;
|
||||||
|
while (i > 0) {
|
||||||
|
i -= 1;
|
||||||
|
try rpo.append(a, post.items[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const emitted = try a.alloc(bool, nb);
|
||||||
|
@memcpy(emitted, reach);
|
||||||
|
{
|
||||||
|
var changed = true;
|
||||||
|
while (changed) {
|
||||||
|
changed = false;
|
||||||
|
for (f.blocks.items, 0..) |blk, bi| {
|
||||||
|
if (!emitted[bi]) continue;
|
||||||
|
const targets: [2]BlockId = switch (blk.merge) {
|
||||||
|
.none => .{ .none, .none },
|
||||||
|
.selection => |mb| .{ mb, .none },
|
||||||
|
.loop => |l| .{ l.merge, l.@"continue" },
|
||||||
|
};
|
||||||
|
for (targets) |tb| if (tb != .none and !emitted[tb.index()]) {
|
||||||
|
emitted[tb.index()] = true;
|
||||||
|
changed = true;
|
||||||
|
};
|
||||||
|
for (succs[bi]) |s| if (!emitted[s.index()]) {
|
||||||
|
emitted[s.index()] = true;
|
||||||
|
changed = true;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Predecessors (emitted ones).
|
||||||
|
var preds = try a.alloc(std.ArrayList(u32), nb);
|
||||||
|
for (preds) |*p| p.* = .empty;
|
||||||
|
for (0..nb) |bi| {
|
||||||
|
if (!emitted[bi]) continue;
|
||||||
|
for (succs[bi]) |s| try preds[s.index()].append(a, @intCast(bi));
|
||||||
|
}
|
||||||
|
// Dominators over reachable blocks (Cooper, Harvey, Kennedy).
|
||||||
|
const rpo_num = try a.alloc(u32, nb);
|
||||||
|
@memset(rpo_num, none);
|
||||||
|
for (rpo.items, 0..) |b, k| rpo_num[b] = @intCast(k);
|
||||||
|
const idom = try a.alloc(u32, nb);
|
||||||
|
@memset(idom, none);
|
||||||
|
idom[0] = 0;
|
||||||
|
{
|
||||||
|
var changed = true;
|
||||||
|
while (changed) {
|
||||||
|
changed = false;
|
||||||
|
for (rpo.items[1..]) |b| {
|
||||||
|
var new: u32 = none;
|
||||||
|
for (preds[b].items) |p| {
|
||||||
|
if (!reach[p] or idom[p] == none) continue;
|
||||||
|
if (new == none) {
|
||||||
|
new = p;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// intersect
|
||||||
|
var x = p;
|
||||||
|
var y = new;
|
||||||
|
while (x != y) {
|
||||||
|
while (rpo_num[x] > rpo_num[y]) x = idom[x];
|
||||||
|
while (rpo_num[y] > rpo_num[x]) y = idom[y];
|
||||||
|
}
|
||||||
|
new = x;
|
||||||
|
}
|
||||||
|
if (new != none and idom[b] != new) {
|
||||||
|
idom[b] = new;
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Dominance frontiers.
|
||||||
|
var df = try a.alloc(std.ArrayList(u32), nb);
|
||||||
|
for (df) |*d| d.* = .empty;
|
||||||
|
for (rpo.items) |b| {
|
||||||
|
var rp: u32 = 0;
|
||||||
|
for (preds[b].items) |p| if (reach[p]) {
|
||||||
|
rp += 1;
|
||||||
|
};
|
||||||
|
if (rp < 2) continue;
|
||||||
|
for (preds[b].items) |p| {
|
||||||
|
if (!reach[p]) continue;
|
||||||
|
var runner = p;
|
||||||
|
while (runner != idom[b]) {
|
||||||
|
if (std.mem.indexOfScalar(u32, df[runner].items, b) == null) try df[runner].append(a, b);
|
||||||
|
runner = idom[runner];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Semi-pruned: variables read in some block before being written there
|
||||||
|
// (live into it) get phis; the others are block-local.
|
||||||
|
const global = try a.alloc(bool, nv);
|
||||||
|
@memset(global, false);
|
||||||
|
var def_blocks = try a.alloc(std.ArrayList(u32), nv);
|
||||||
|
for (def_blocks) |*d| d.* = .empty;
|
||||||
|
{
|
||||||
|
const written = try a.alloc(u32, nv); // block that last wrote it (+1)
|
||||||
|
@memset(written, 0);
|
||||||
|
for (rpo.items) |b| {
|
||||||
|
for (f.blocks.items[b].insts.items) |r| switch (f.inst(r).op) {
|
||||||
|
.load => |p| {
|
||||||
|
const v = var_of[p.index()];
|
||||||
|
if (v != none and written[v] != b + 1) global[v] = true;
|
||||||
|
},
|
||||||
|
.store => |s| {
|
||||||
|
const v = var_of[s.ptr.index()];
|
||||||
|
if (v != none) {
|
||||||
|
if (written[v] != b + 1) try def_blocks[v].append(a, b);
|
||||||
|
written[v] = b + 1;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
else => {},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Phi placement: phi_of[b] lists (var, phi ref).
|
||||||
|
var phis = try a.alloc(std.ArrayList(struct { v: u32, r: Ref }), nb);
|
||||||
|
for (phis) |*p| p.* = .empty;
|
||||||
|
{
|
||||||
|
const has_phi = try a.alloc(u32, nb); // var + 1 that last placed one
|
||||||
|
const in_work = try a.alloc(u32, nb);
|
||||||
|
@memset(has_phi, 0);
|
||||||
|
@memset(in_work, 0);
|
||||||
|
var work: std.ArrayList(u32) = .empty;
|
||||||
|
for (0..nv) |v| {
|
||||||
|
if (!global[v]) continue;
|
||||||
|
const tag: u32 = @intCast(v + 1);
|
||||||
|
work.clearRetainingCapacity();
|
||||||
|
for (def_blocks[v].items) |b| {
|
||||||
|
in_work[b] = tag;
|
||||||
|
try work.append(a, b);
|
||||||
|
}
|
||||||
|
while (work.pop()) |b| {
|
||||||
|
for (df[b].items) |d| {
|
||||||
|
if (has_phi[d] == tag) continue;
|
||||||
|
has_phi[d] = tag;
|
||||||
|
const ty = f.inst(pvars.items[v]).ty;
|
||||||
|
const r = try addInst(a, f, .{ .op = .{ .phi = &.{} }, .ty = ty });
|
||||||
|
try phis[d].append(a, .{ .v = @intCast(v), .r = r });
|
||||||
|
if (in_work[d] != tag) {
|
||||||
|
in_work[d] = tag;
|
||||||
|
try work.append(a, d);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Undefined values, one per variable (made on first use).
|
||||||
|
const undefs = try a.alloc(Ref, nv);
|
||||||
|
@memset(undefs, .none);
|
||||||
|
const Undef = struct {
|
||||||
|
fn get(al: Allocator, fx: *ir.Function, us: []Ref, pv: []const Ref, v: u32) Error!Ref {
|
||||||
|
if (us[v] == .none) us[v] = try addInst(al, fx, .{ .op = .undef, .ty = fx.inst(pv[v]).ty });
|
||||||
|
return us[v];
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Renaming over the dominator tree.
|
||||||
|
var children = try a.alloc(std.ArrayList(u32), nb);
|
||||||
|
for (children) |*c| c.* = .empty;
|
||||||
|
for (rpo.items[1..]) |b| if (idom[b] != none) try children[idom[b]].append(a, b);
|
||||||
|
// Incoming values: per phi, (value, block) as preds are processed.
|
||||||
|
var incoming = try a.alloc(std.ArrayList(@typeInfo(@FieldType(ir.Op, "phi")).pointer.child), f.insts.items.len);
|
||||||
|
for (incoming) |*x| x.* = .empty;
|
||||||
|
// Replacements (promoted loads, trivial phis), by instruction; the
|
||||||
|
// values made later (undefs) have none.
|
||||||
|
const Repl = struct {
|
||||||
|
to: []Ref,
|
||||||
|
fn put(r: *@This(), k: u32, v: Ref) void {
|
||||||
|
r.to[k] = v;
|
||||||
|
}
|
||||||
|
fn get(r: *const @This(), k: u32) ?Ref {
|
||||||
|
if (k >= r.to.len or r.to[k] == .none) return null;
|
||||||
|
return r.to[k];
|
||||||
|
}
|
||||||
|
fn contains(r: *const @This(), k: u32) bool {
|
||||||
|
return r.get(k) != null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var repl = Repl{ .to = try a.alloc(Ref, f.insts.items.len) };
|
||||||
|
@memset(repl.to, .none);
|
||||||
|
const cur = try a.alloc(Ref, nv);
|
||||||
|
for (cur, 0..) |*c, v| c.* = try Undef.get(a, f, undefs, pvars.items, @intCast(v));
|
||||||
|
var log: std.ArrayList(struct { v: u32, old: Ref }) = .empty;
|
||||||
|
var stack: std.ArrayList(struct { b: u32, mark: usize, enter: bool }) = .empty;
|
||||||
|
try stack.append(a, .{ .b = 0, .mark = 0, .enter = true });
|
||||||
|
while (stack.pop()) |fr| {
|
||||||
|
if (!fr.enter) {
|
||||||
|
while (log.items.len > fr.mark) {
|
||||||
|
const e = log.pop().?;
|
||||||
|
cur[e.v] = e.old;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const b = fr.b;
|
||||||
|
try stack.append(a, .{ .b = b, .mark = log.items.len, .enter = false });
|
||||||
|
for (phis[b].items) |p| {
|
||||||
|
try log.append(a, .{ .v = p.v, .old = cur[p.v] });
|
||||||
|
cur[p.v] = p.r;
|
||||||
|
}
|
||||||
|
for (f.blocks.items[b].insts.items) |r| switch (f.inst(r).op) {
|
||||||
|
.load => |p| {
|
||||||
|
const v = var_of[p.index()];
|
||||||
|
if (v != none) repl.put(r.index(), cur[v]);
|
||||||
|
},
|
||||||
|
.store => |s| {
|
||||||
|
const v = var_of[s.ptr.index()];
|
||||||
|
if (v != none) {
|
||||||
|
try log.append(a, .{ .v = v, .old = cur[v] });
|
||||||
|
cur[v] = s.value;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
else => {},
|
||||||
|
};
|
||||||
|
for (succs[b]) |s| for (phis[s.index()].items) |p| {
|
||||||
|
try incoming[p.r.index()].append(a, .{ .value = cur[p.v], .block = @fromBackingInt(@intCast(b)) });
|
||||||
|
};
|
||||||
|
for (children[b].items) |c| try stack.append(a, .{ .b = c, .mark = 0, .enter = true });
|
||||||
|
}
|
||||||
|
// Unreachable emitted blocks: loads read undef; their edges into phis
|
||||||
|
// carry undef.
|
||||||
|
for (0..nb) |bi| {
|
||||||
|
if (reach[bi]) continue;
|
||||||
|
for (f.blocks.items[bi].insts.items) |r| switch (f.inst(r).op) {
|
||||||
|
.load => |p| {
|
||||||
|
const v = var_of[p.index()];
|
||||||
|
if (v != none) repl.put(r.index(), try Undef.get(a, f, undefs, pvars.items, v));
|
||||||
|
},
|
||||||
|
else => {},
|
||||||
|
};
|
||||||
|
if (!emitted[bi]) continue;
|
||||||
|
for (succs[bi]) |s| for (phis[s.index()].items) |p| {
|
||||||
|
try incoming[p.r.index()].append(a, .{ .value = try Undef.get(a, f, undefs, pvars.items, p.v), .block = @fromBackingInt(@intCast(bi)) });
|
||||||
|
};
|
||||||
|
}
|
||||||
|
// Resolve: replacements may name other replaced loads; trivial phis
|
||||||
|
// (one distinct incoming value besides themselves) become that value.
|
||||||
|
const Resolve = struct {
|
||||||
|
repl: *const Repl,
|
||||||
|
pub fn map(c: @This(), x: Ref) Ref {
|
||||||
|
var y = x;
|
||||||
|
var n: u32 = 0;
|
||||||
|
while (y != .none and n < 1 << 20) : (n += 1) {
|
||||||
|
y = c.repl.get(y.index()) orelse return y;
|
||||||
|
}
|
||||||
|
return y;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const rs = Resolve{ .repl = &repl };
|
||||||
|
const Hit = struct {
|
||||||
|
repl: *const Repl,
|
||||||
|
hit: *bool,
|
||||||
|
pub fn use(c: @This(), x: Ref) void {
|
||||||
|
if (c.repl.contains(x.index())) c.hit.* = true;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
// Phi incoming lists in place; then fold trivial phis to a fixed point.
|
||||||
|
var all_phis: std.ArrayList(Ref) = .empty;
|
||||||
|
for (phis) |ps| for (ps.items) |p| {
|
||||||
|
f.insts.items[p.r.index()].op = .{ .phi = incoming[p.r.index()].items };
|
||||||
|
try all_phis.append(a, p.r);
|
||||||
|
};
|
||||||
|
var changed = true;
|
||||||
|
while (changed) {
|
||||||
|
changed = false;
|
||||||
|
for (all_phis.items) |p| {
|
||||||
|
if (repl.contains(p.index())) continue;
|
||||||
|
var same: Ref = .none;
|
||||||
|
var trivial = true;
|
||||||
|
for (f.inst(p).op.phi) |in| {
|
||||||
|
const v = rs.map(in.value);
|
||||||
|
if (v == p or v == same) continue;
|
||||||
|
if (same != .none) {
|
||||||
|
trivial = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
same = v;
|
||||||
|
}
|
||||||
|
if (trivial and same != .none) {
|
||||||
|
repl.put(p.index(), same);
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Rewrite every block: drop promoted loads / stores / locals, place the
|
||||||
|
// remaining phis first, map operands.
|
||||||
|
for (f.blocks.items, 0..) |*blk, bi| {
|
||||||
|
var out: std.ArrayList(Ref) = .empty;
|
||||||
|
for (phis[bi].items) |p| if (!repl.contains(p.r.index())) try out.append(a, p.r);
|
||||||
|
for (blk.insts.items) |r| {
|
||||||
|
const op = f.inst(r).op;
|
||||||
|
switch (op) {
|
||||||
|
.local_var => if (var_of[r.index()] != none) continue,
|
||||||
|
.load => |p| if (var_of[p.index()] != none) continue,
|
||||||
|
.store => |s| if (var_of[s.ptr.index()] != none) continue,
|
||||||
|
else => {},
|
||||||
|
}
|
||||||
|
try out.append(a, r);
|
||||||
|
}
|
||||||
|
for (out.items) |r| {
|
||||||
|
var hit = false;
|
||||||
|
try forOperands(a, f.inst(r).op, Hit{ .repl = &repl, .hit = &hit });
|
||||||
|
if (hit) f.insts.items[r.index()].op = try opt.mapOp(a, f.inst(r).op, rs);
|
||||||
|
}
|
||||||
|
blk.insts = out;
|
||||||
|
blk.term = switch (blk.term) {
|
||||||
|
.ret => |v| .{ .ret = rs.map(v) },
|
||||||
|
.cond_br => |c| .{ .cond_br = .{ .cond = rs.map(c.cond), .then = c.then, .@"else" = c.@"else" } },
|
||||||
|
.@"switch" => |s| .{ .@"switch" = .{ .value = rs.map(s.value), .default = s.default, .cases = s.cases } },
|
||||||
|
else => blk.term,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
// The promoted locals are gone (the emitter declares every local_var).
|
||||||
|
for (pvars.items) |v| f.insts.items[v.index()] = .{ .op = .undef, .ty = f.inst(v).ty };
|
||||||
|
try removeDeadPhis(a, f);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Drops phis nothing but dead phis uses: phis are live when a non-phi
|
||||||
|
/// instruction or a terminator uses them, or a live phi does (dead cycles
|
||||||
|
/// through loop headers go too).
|
||||||
|
fn removeDeadPhis(a: Allocator, f: *ir.Function) Error!void {
|
||||||
|
const n = f.insts.items.len;
|
||||||
|
const live = try a.alloc(bool, n);
|
||||||
|
@memset(live, false);
|
||||||
|
var work: std.ArrayList(Ref) = .empty;
|
||||||
|
const Mark = struct {
|
||||||
|
f: *const ir.Function,
|
||||||
|
live: []bool,
|
||||||
|
work: *std.ArrayList(Ref),
|
||||||
|
al: Allocator,
|
||||||
|
pub fn use(c: @This(), x: Ref) void {
|
||||||
|
if (c.live[x.index()] or c.f.inst(x).op != .phi) return;
|
||||||
|
c.live[x.index()] = true;
|
||||||
|
c.work.append(c.al, x) catch {};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const mk = Mark{ .f = f, .live = live, .work = &work, .al = a };
|
||||||
|
for (f.blocks.items) |blk| {
|
||||||
|
for (blk.insts.items) |r| if (f.inst(r).op != .phi) try forOperands(a, f.inst(r).op, mk);
|
||||||
|
const tr = termOperand(blk.term);
|
||||||
|
if (tr != .none) mk.use(tr);
|
||||||
|
}
|
||||||
|
while (work.pop()) |r| for (f.inst(r).op.phi) |in| mk.use(in.value);
|
||||||
|
for (f.blocks.items) |*blk| {
|
||||||
|
var k: usize = 0;
|
||||||
|
while (k < blk.insts.items.len) {
|
||||||
|
const r = blk.insts.items[k];
|
||||||
|
if (f.inst(r).op == .phi and !live[r.index()]) {
|
||||||
|
_ = blk.insts.orderedRemove(k);
|
||||||
|
} else k += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -29,6 +29,7 @@ pub const Extra = enum {
|
||||||
zdxc_ast,
|
zdxc_ast,
|
||||||
zdxc_sema,
|
zdxc_sema,
|
||||||
zdxc_ir,
|
zdxc_ir,
|
||||||
|
zdxc_no_opt,
|
||||||
job,
|
job,
|
||||||
fcolor_diagnostics,
|
fcolor_diagnostics,
|
||||||
fno_color_diagnostics,
|
fno_color_diagnostics,
|
||||||
|
|
@ -42,6 +43,7 @@ const extra_options = [_]struct { id: Extra, spelling: []const u8, help: []const
|
||||||
.{ .id = .zdxc_ast, .spelling = "zdxc-ast", .help = "Preprocess, parse and dump the syntax tree (development)" },
|
.{ .id = .zdxc_ast, .spelling = "zdxc-ast", .help = "Preprocess, parse and dump the syntax tree (development)" },
|
||||||
.{ .id = .zdxc_sema, .spelling = "zdxc-sema", .help = "Run the front end through semantic analysis only (development)" },
|
.{ .id = .zdxc_sema, .spelling = "zdxc-sema", .help = "Run the front end through semantic analysis only (development)" },
|
||||||
.{ .id = .zdxc_ir, .spelling = "zdxc-ir", .help = "Print the lowered IR instead of compiling (development)" },
|
.{ .id = .zdxc_ir, .spelling = "zdxc-ir", .help = "Print the lowered IR instead of compiling (development)" },
|
||||||
|
.{ .id = .zdxc_no_opt, .spelling = "zdxc-no-opt", .help = "Skip the SPIR-V IR optimizations: inlining, promotion to SSA values (development)" },
|
||||||
.{ .id = .job, .spelling = "-job=", .kind = .joined, .meta = "<job.json>", .help = "Compile every shader a JSON job file lists, in one process, on all cores (see docs/batch.md)" },
|
.{ .id = .job, .spelling = "-job=", .kind = .joined, .meta = "<job.json>", .help = "Compile every shader a JSON job file lists, in one process, on all cores (see docs/batch.md)" },
|
||||||
.{ .id = .fcolor_diagnostics, .spelling = "fcolor-diagnostics", .help = "Always use colors in diagnostics" },
|
.{ .id = .fcolor_diagnostics, .spelling = "fcolor-diagnostics", .help = "Always use colors in diagnostics" },
|
||||||
.{ .id = .fno_color_diagnostics, .spelling = "fno-color-diagnostics", .help = "Never use colors in diagnostics" },
|
.{ .id = .fno_color_diagnostics, .spelling = "fno-color-diagnostics", .help = "Never use colors in diagnostics" },
|
||||||
|
|
|
||||||
|
|
@ -35,6 +35,8 @@ pub const ir = struct {
|
||||||
pub const texture = @import("ir/texture.zig");
|
pub const texture = @import("ir/texture.zig");
|
||||||
pub const opt = @import("ir/opt.zig");
|
pub const opt = @import("ir/opt.zig");
|
||||||
pub const split_resources = @import("ir/split_resources.zig");
|
pub const split_resources = @import("ir/split_resources.zig");
|
||||||
|
pub const inline_calls = @import("ir/inline.zig");
|
||||||
|
pub const ssa = @import("ir/ssa.zig");
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const sema = struct {
|
pub const sema = struct {
|
||||||
|
|
|
||||||
|
|
@ -226,6 +226,13 @@ const Emitter = struct {
|
||||||
/// through them).
|
/// through them).
|
||||||
nonuniform_ids: std.AutoHashMapUnmanaged(Id, void) = .empty,
|
nonuniform_ids: std.AutoHashMapUnmanaged(Id, void) = .empty,
|
||||||
variants: std.ArrayList(struct { fi: u32, bindings: []const Id, id: Id }) = .empty,
|
variants: std.ArrayList(struct { fi: u32, bindings: []const Id, id: Id }) = .empty,
|
||||||
|
/// The current function's block labels, and phi operands (word
|
||||||
|
/// positions in the functions section) naming values emitted after the
|
||||||
|
/// phi, patched when the function is done.
|
||||||
|
labels: []const Id = &.{},
|
||||||
|
phi_patches: std.ArrayList(struct { pos: usize, ref: Ref }) = .empty,
|
||||||
|
/// OpUndef by type.
|
||||||
|
undef_ids: std.AutoHashMapUnmanaged(TypeId, Id) = .empty,
|
||||||
/// The bindings of the function being emitted (a specialization).
|
/// The bindings of the function being emitted (a specialization).
|
||||||
cur_bindings: []const Id = &.{},
|
cur_bindings: []const Id = &.{},
|
||||||
/// Per instruction (current function): resource locals assigned
|
/// Per instruction (current function): resource locals assigned
|
||||||
|
|
@ -945,6 +952,7 @@ const Emitter = struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
for (m.functions.items, e.func_ids) |f, id| {
|
for (m.functions.items, e.func_ids) |f, id| {
|
||||||
|
if (f.dead) continue;
|
||||||
e.setEntry(f.entry);
|
e.setEntry(f.entry);
|
||||||
if (!e.hasResourceParams(f)) try e.emitFunction(f, id, &.{});
|
if (!e.hasResourceParams(f)) try e.emitFunction(f, id, &.{});
|
||||||
}
|
}
|
||||||
|
|
@ -984,7 +992,7 @@ const Emitter = struct {
|
||||||
try e.entryPoint(entry);
|
try e.entryPoint(entry);
|
||||||
}
|
}
|
||||||
for (m.functions.items, e.func_ids) |f, id| {
|
for (m.functions.items, e.func_ids) |f, id| {
|
||||||
if (!e.hasResourceParams(f)) try e.b.emitWithString(.debug_names, .name, &.{id}, f.name, &.{});
|
if (!f.dead and !e.hasResourceParams(f)) try e.b.emitWithString(.debug_names, .name, &.{id}, f.name, &.{});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -2130,10 +2138,13 @@ const Emitter = struct {
|
||||||
const order = try blockOrder(e.arena, f);
|
const order = try blockOrder(e.arena, f);
|
||||||
const labels = try e.arena.alloc(Id, f.blocks.items.len);
|
const labels = try e.arena.alloc(Id, f.blocks.items.len);
|
||||||
for (labels) |*l| l.* = e.b.newId();
|
for (labels) |*l| l.* = e.b.newId();
|
||||||
|
e.labels = labels;
|
||||||
|
e.phi_patches = .empty;
|
||||||
|
|
||||||
// Constants and parameters first (they may be used in any block).
|
// Constants and parameters first (they may be used in any block).
|
||||||
for (f.insts.items, 0..) |inst, i| switch (inst.op) {
|
for (f.insts.items, 0..) |inst, i| switch (inst.op) {
|
||||||
.constant => |c| e.vals[i] = try e.constant(inst.ty, c),
|
.constant => |c| e.vals[i] = try e.constant(inst.ty, c),
|
||||||
|
.undef => e.vals[i] = try e.undefOf(inst.ty),
|
||||||
.param => |p| {
|
.param => |p| {
|
||||||
e.vals[i] = param_ids[p];
|
e.vals[i] = param_ids[p];
|
||||||
if (e.mesh_params.get(.{ f, p })) |kind| try e.mesh_places.put(e.arena, @intCast(i), .{ .kind = kind, .ty = inst.ty });
|
if (e.mesh_params.get(.{ f, p })) |kind| try e.mesh_places.put(e.arena, @intCast(i), .{ .kind = kind, .ty = inst.ty });
|
||||||
|
|
@ -2188,8 +2199,21 @@ const Emitter = struct {
|
||||||
for (blk.insts.items) |r| try e.emitInst(r);
|
for (blk.insts.items) |r| try e.emitInst(r);
|
||||||
switch (blk.merge) {
|
switch (blk.merge) {
|
||||||
.none => {},
|
.none => {},
|
||||||
.selection => |mb| try e.b.emit(.functions, .selection_merge, &.{ labels[mb.index()], 0 }),
|
// [flatten] / [branch]: SelectionControl Flatten /
|
||||||
.loop => |l| try e.b.emit(.functions, .loop_merge, &.{ labels[l.merge.index()], labels[l.@"continue".index()], 0 }),
|
// DontFlatten, as in dxc.
|
||||||
|
.selection => |mb| try e.b.emit(.functions, .selection_merge, &.{ labels[mb.index()], switch (blk.selection_control) {
|
||||||
|
.none => 0,
|
||||||
|
.flatten => 1,
|
||||||
|
.dont_flatten => 2,
|
||||||
|
} }),
|
||||||
|
// [unroll] / [loop] the IR could not act on are the
|
||||||
|
// driver's to honor (LoopControl Unroll / DontUnroll), as
|
||||||
|
// in dxc.
|
||||||
|
.loop => |l| try e.b.emit(.functions, .loop_merge, &.{ labels[l.merge.index()], labels[l.@"continue".index()], switch (l.unroll) {
|
||||||
|
.auto => 0,
|
||||||
|
.unroll => 1,
|
||||||
|
.dont => 2,
|
||||||
|
} }),
|
||||||
}
|
}
|
||||||
switch (blk.term) {
|
switch (blk.term) {
|
||||||
.none, .@"unreachable" => try e.b.emit(.functions, .@"unreachable", &.{}),
|
.none, .@"unreachable" => try e.b.emit(.functions, .@"unreachable", &.{}),
|
||||||
|
|
@ -2223,9 +2247,22 @@ const Emitter = struct {
|
||||||
.discard => try e.b.emit(.functions, .kill, &.{}),
|
.discard => try e.b.emit(.functions, .kill, &.{}),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
const words = e.b.sections.getPtr(.functions).items;
|
||||||
|
for (e.phi_patches.items) |p| {
|
||||||
|
words[p.pos] = e.val(p.ref);
|
||||||
|
if (words[p.pos] == 0) return e.unsupported("internal: a phi names a value that is never emitted", .{});
|
||||||
|
}
|
||||||
try e.b.emit(.functions, .function_end, &.{});
|
try e.b.emit(.functions, .function_end, &.{});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn undefOf(e: *Emitter, ty: TypeId) Error!Id {
|
||||||
|
if (e.undef_ids.get(ty)) |id| return id;
|
||||||
|
const id = e.b.newId();
|
||||||
|
try e.b.emit(.types_globals, .undef, &.{ try e.typeId(ty), id });
|
||||||
|
try e.undef_ids.put(e.arena, ty, id);
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
/// For the hull shader's entry wrapper: the patch constant wrapper it
|
/// For the hull shader's entry wrapper: the patch constant wrapper it
|
||||||
/// calls before returning.
|
/// calls before returning.
|
||||||
fn hullEpilogue(e: *Emitter, fn_id: Id) ?Id {
|
fn hullEpilogue(e: *Emitter, fn_id: Id) ?Id {
|
||||||
|
|
@ -2910,7 +2947,22 @@ const Emitter = struct {
|
||||||
try e.b.emit(.functions, .store, &.{ ptr, v });
|
try e.b.emit(.functions, .store, &.{ ptr, v });
|
||||||
} else try e.b.emit(.functions, .store, &.{ iface.var_id, v });
|
} else try e.b.emit(.functions, .store, &.{ iface.var_id, v });
|
||||||
},
|
},
|
||||||
.phi => return e.unsupported("phi", .{}),
|
.undef => {},
|
||||||
|
.phi => |ins| {
|
||||||
|
// Values from back edges are emitted later: patched at the
|
||||||
|
// end of the function.
|
||||||
|
const id = e.b.newId();
|
||||||
|
var ops: std.ArrayList(u32) = .empty;
|
||||||
|
try ops.appendSlice(e.arena, &.{ try e.typeId(i.ty), id });
|
||||||
|
const base = e.b.sections.getPtr(.functions).items.len + 1;
|
||||||
|
for (ins) |in| {
|
||||||
|
const v = e.val(in.value);
|
||||||
|
if (v == 0) try e.phi_patches.append(e.arena, .{ .pos = base + ops.items.len, .ref = in.value });
|
||||||
|
try ops.appendSlice(e.arena, &.{ v, e.labels[in.block.index()] });
|
||||||
|
}
|
||||||
|
try e.b.emit(.functions, .phi, ops.items);
|
||||||
|
e.vals[ri] = id;
|
||||||
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue