Compare commits

...

9 Commits

Author SHA1 Message Date
peterino2 06222920e5 Merge dev/windows-fix: DXIL local promotion and copy elision, on the SPIR-V IR passes
Glide (Hyperion engine) now runs on zdxc's DXIL.

# Conflicts:
#	src/dxil/emit.zig
2026-11-02 01:16:31 -08:00
peterino2 4666275a0b DXIL: fold promoted values, pass constant buffer structs in place
GlimmerProbeTrace (Glide) still came out at 374 KB of DXIL against
dxc's 155 KB, with 130 allocas against 40. Most of the remainder:
by-value struct parameters copied out of the constant buffer at every
call (GlimmerGroundParams and GlimmerSpanParams, 32 i32s each), then
indexed dynamically, which pinned each copy in memory.

- Arguments loaded from a constant buffer are passed as the constant
  buffer place itself, structs as well as arrays (not with matrices,
  whose constant buffer access is narrower than a local's). Locals still
  alias only within a block with no write since. The alias now comes
  first in local_var lowering, so the skipped parameter store always
  matches.
- Peepholes on promoted values: bitcast round trips (int/float mixing
  locals store i32s), constant integer arithmetic and comparisons,
  identities, selects on a constant. A constant out-of-bounds array
  index this exposes (on a path that cannot run) becomes 0, since the
  validator rejects it.
- Inlined callees' array locals return to a per-type pool on return,
  for later callees to reuse.
- -Od and -zdxc-no-opt skip promotion, aliasing and reuse, as they skip
  the SPIR-V IR passes.

GlimmerProbeTrace: 374 KB to 191 KB, 21 allocas, 282 bitcasts (from
7198). Its pipeline builds in 3.6 s on an RX 9070 XT (was 5.1 s). All
of Glide's 400 DXIL compiles: 5.91 MB (dxc: 6.11 MB), 7.1x faster than
dxc. All pass dxc 1.8.2505's validator, and Glide renders.
2026-11-02 01:13:16 -08:00
peterino2 dce6d0eade DXIL: promote locals to SSA, elide by-value array copies
Locals were left as allocas, so every access was a store or a reload.
Glide's GlimmerProbeTrace came out as 2.3 MB of DXIL (DXC: 155 KB) that
AMD's driver took over ten minutes to build into a pipeline, and the game
stalled on a black screen.

- promote.zig: SROA + mem2reg over the finished function. An alloca whose
  accesses are loads and stores through constant indices becomes one SSA
  variable per element, with phis at the iterated dominance frontiers.
  Trivial phis fold away, and dead instructions go. Locals read before
  they are written read zero, since the validator rejects reads of undef.
- Dynamically indexed locals pin only what the index can reach. The
  emitter records each dynamic getelementptr's range (the indexed array's
  extent), and the rest of the local is still promoted.
- A by-value array parameter that the callee only reads aliases the
  caller's storage when the argument was loaded from a local in the same
  block with no write since. This drops the per-call copies.
- Declarations that lose their last call are pruned before writing, since
  the validator rejects unused external functions.

On Glide's 400 DXIL compiles, total output goes from 34.5 MB to 6.8 MB
(DXC: 6.1 MB), and GlimmerProbeTrace from 2.3 MB to 374 KB. Its
pipeline now builds in about 5 s. All 400 objects pass DXC 1.8.2505's
validator (checked with a copy built to claim validator 1.8), and Glide
renders on zdxc.
2026-11-02 00:57:49 -08:00
Peter Li cd951ea29b DXIL: dynamic constant buffer vector indices, library resource arrays, selected resource locals
- A constant buffer vector indexed at run time loads the whole vector and
  selects the component.
- Resource arrays in libraries: globals of class arrays, mangled as
  pointers to their element (as dxc); each access loads its element for
  createHandleForLib. NonUniform indices put !dx.nonuniform on the
  getelementptr, so the bitcode writer now writes metadata kinds and
  instruction attachments.
- Array types in mangled names count their dimensions as dxc does.
- A resource local assigned different elements of one resource array keeps
  the element's index and makes the handle where it is read.
2026-11-02 00:57:49 -08:00
Peter Li ab7b167270 DXIL: keep the library prologue's use marks per thread
markUses kept the array it marks in a static, which concurrent library
compiles under --job shared: one could mark into another's array, or index
past its own. Make it thread-local.
2026-11-02 00:57:49 -08:00
Peterino2 97517cc5b1 SPIR-V: selection controls from [branch] and [flatten]
[branch] and [flatten] on if and switch were dropped: every
OpSelectionMerge had selection control None, leaving the driver to
flatten or keep the branch by its own heuristics. They now become
DontFlatten and Flatten, as in dxc (the Hyperion engine's shaders use
them 21 times). The IR keeps them on the header block; unrolling and
inlining carry them over.
2026-11-02 08:00:54 +00:00
Peterino2 d39ee30a4c SPIR-V: promote locals to SSA values; inline top-down
ir/ssa.zig, after inlining:

1. A local struct or array accessed only whole and with constant
   indices is split into one local per leaf member / element (scalar
   replacement, up to 64 leaves): whole reads construct the value,
   whole writes store each part. Promoting whole aggregates instead
   made each member write a copy of the aggregate; on the Glide shader
   that has many of them RADV then spilled ten times as many scalar
   registers.
2. Locals loaded and stored only whole (no resources) become SSA
   values: semi-pruned phi placement over dominance frontiers,
   renaming over the dominator tree, trivial phis folded, dead phis
   (cycles included) dropped. Reads before any write are the new IR
   `undef` (OpUndef). Phis take one value per predecessor the emitter
   writes, unreachable merge and continue targets included.

Constants that were behind locals fold afterwards. The SPIR-V emitter
emits OpPhi, patching operands emitted after the phi.

The inliner now works top-down from the entry points (each call gets a
copy of the callee's own body, whose calls are inlined as the scan
reaches them), copies only instructions in the callee's blocks (and
locals on first use), and remaps only instructions naming a call
result; scans use a non-allocating operand visitor (opt.eachOperand).

On Glide: loads 115040 -> 20322, stores 63644 -> 5832 (dxc: 11423,
2498), SPIR-V 12.0 -> 13.2 MB (callee bodies copied); compile time
587 -> 771 ms on 327 shaders (dxc: 8.6 s). Two more corpus files
compile (texel offsets that are constants once promoted).
2026-11-02 07:54:10 +00:00
Peterino2 afc4587596 SPIR-V: inline calls in the IR
dxc's SPIR-V gets its calls inlined by legalization; zdxc emitted every
function and left inlining to the driver, with 10361 calls across the
Hyperion engine's Glide shaders. ir/inline.zig now inlines bottom-up
before emission:

- The calling block is split at the call: it branches to a copy of the
  callee, and the rest of the block (terminator and merge included)
  moves to a continuation block. Parameters become the arguments.
- A callee with one return outside every construct branches from it to
  the continuation. Returns inside selections or switches become
  breaks out of a loop that runs once around the callee, the return
  value going through a local.
- Callees that return from inside a loop, [noinline] ones, ones with
  RayQuery or by-reference resource parameters, and ones returning a
  resource from several places stay functions (resource arguments then
  still get specializations).
- Functions nothing reaches any more are marked dead and not emitted.

Only modules with vertex, pixel and compute entry points and no
rasterizer-ordered views for now (the emitter treats the others'
functions specially). -Od and the new -zdxc-no-opt skip it; -zdxc-ir
prints the IR after the SPIR-V passes.

On Glide: 37 calls left; the SPIR-V grows (517k to 838k instructions,
callee bodies copied, one-trip loops) until promotion to SSA values
removes the locals; compile time 597 to 765 ms. The driver's own
statistics barely move, except one compute shader passing float4[28]
arrays by value, whose copies now take more scratch.
2026-11-02 07:10:23 +00:00
Peterino2 2ed08b08e1 SPIR-V: loop controls from [unroll] and [loop]
Loops the IR keeps (its unrolling gave up, or [loop] asked it not to)
lost their attribute: every OpLoopMerge had loop control None. The
driver now gets Unroll for [unroll] and DontUnroll for [loop], as from
dxc.

On the Hyperion engine's Glide shaders this is what made its half
resolution Glimmer irradiance pass about 5% slower than with dxc: an
[unroll] loop over a run-time count that RADV unrolls for dxc's output
stayed a loop for zdxc's (2381 instructions against dxc's 5765; now
5856).
2026-11-02 06:55:33 +00:00
11 changed files with 2568 additions and 22 deletions

View File

@ -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;

View File

@ -1,8 +1,9 @@
//! IR -> DXIL. Everything is inlined into the entry function while //! IR -> DXIL. Everything is inlined into the entry function while
//! emitting (each call instantiates its callee); values are scalarized //! emitting (each call instantiates its callee); values are scalarized
//! (DXIL has no vectors); locals become flattened `[N x scalar]` allocas; //! (DXIL has no vectors); locals become flattened `[N x scalar]` allocas,
//! resources become handles created on entry. The result is a signed DXIL //! which promote.zig turns into SSA values where they are not indexed
//! container. //! dynamically; resources become handles created on entry. The result is a
//! signed DXIL container.
const std = @import("std"); const std = @import("std");
const Allocator = std.mem.Allocator; const Allocator = std.mem.Allocator;
@ -21,6 +22,8 @@ const rdat = @import("rdat.zig");
const linalg_info = @import("linalg_info.zig"); const linalg_info = @import("linalg_info.zig");
const libinfo = @import("libinfo.zig"); const libinfo = @import("libinfo.zig");
const rootsig = @import("rootsig.zig"); const rootsig = @import("rootsig.zig");
const promote = @import("promote.zig");
const opt = @import("../ir/opt.zig");
const TypeId = types.TypeId; const TypeId = types.TypeId;
const TypeTable = types.TypeTable; const TypeTable = types.TypeTable;
@ -31,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";
@ -102,6 +108,9 @@ const Ptr = struct {
scalar_ty: DType, scalar_ty: DType,
offset_const: u32 = 0, offset_const: u32 = 0,
offset_dyn: ?Value = null, offset_dyn: ?Value = null,
/// The components `offset_dyn` can reach: the extent of the array (or
/// vector or matrix) it indexes. Null when not known.
dyn_range: ?[2]u32 = null,
/// bools are stored as i32. /// bools are stored as i32.
bool_storage: bool = false, bool_storage: bool = false,
/// Mixed 32-bit component types share i32 storage (floats bitcast). /// Mixed 32-bit component types share i32 storage (floats bitcast).
@ -149,6 +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 and constant buffers: the place (a `.ptr` or
/// `.cbuf`), and the block and write count when read, so a call right
/// after can pass the place itself.
load_srcs: std.AutoHashMapUnmanaged(u32, struct { src: Lowered, block: u32, writes: u32 }) = .empty,
/// By-value parameters passed as the caller's place (see paramCopies).
param_srcs: []const ?Lowered = &.{},
/// paramCopies of the function, when some parameter is aliased.
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 };
@ -214,6 +233,18 @@ const Emitter = struct {
/// validator wants CheckAccessFullyMapped's operand to be one. /// validator wants CheckAccessFullyMapped's operand to be one.
status_vals: std.AutoHashMapUnmanaged(Value, void) = .empty, status_vals: std.AutoHashMapUnmanaged(Value, void) = .empty,
forwarded: std.AutoHashMapUnmanaged(struct { Value, u32 }, struct { v: Value, block: u32 }) = .empty, forwarded: std.AutoHashMapUnmanaged(struct { Value, u32 }, struct { v: Value, block: u32 }) = .empty,
/// Dynamically indexed getelementptrs into locals (by id) and the
/// components they can reach, for promote.run.
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.
writes: u32 = 0,
/// paramCopies per IR function.
param_copies: std.AutoHashMapUnmanaged(u32, []const u32) = .empty,
uses_barycentrics: bool = false, uses_barycentrics: bool = false,
uses_sampler_heap: bool = false, uses_sampler_heap: bool = false,
@ -262,6 +293,13 @@ const Emitter = struct {
fn add(e: *Emitter, ty: DType, op: @FieldType(module.Inst, "op")) Error!Value { fn add(e: *Emitter, ty: DType, op: @FieldType(module.Inst, "op")) Error!Value {
const id = e.next_id; const id = e.next_id;
e.next_id += 1; e.next_id += 1;
switch (op) {
.store, .atomicrmw, .cmpxchg => e.writes += 1,
.call => |c| if (!std.mem.startsWith(u8, e.dm.functions.items[c.callee].name, "dx.op.")) {
e.writes += 1;
},
else => {},
}
try e.blocks.items[e.cur].append(e.arena, .{ .inst = .{ .ty = ty, .op = op }, .id = id }); try e.blocks.items[e.cur].append(e.arena, .{ .inst = .{ .ty = ty, .op = op }, .id = id });
return .{ .inst = id }; return .{ .inst = id };
} }
@ -634,6 +672,9 @@ const Emitter = struct {
return x.func < y.func; return x.func < y.func;
} }
}.lt); }.lt);
if (try promote.pruneDeclarations(e.arena, &e.dm)) |index| for (funcs.items) |*lf| {
lf.func = index[lf.func];
};
const bitcode = try e.writeLibraryModule(funcs.items); const bitcode = try e.writeLibraryModule(funcs.items);
defer gpa.free(bitcode); defer gpa.free(bitcode);
return e.assembleLibrary(gpa, funcs.items, bitcode); return e.assembleLibrary(gpa, funcs.items, bitcode);
@ -1221,6 +1262,12 @@ const Emitter = struct {
const all = [_][]const PInst{e.prologue.items}; const all = [_][]const PInst{e.prologue.items};
for (all) |items| for (items) |pi| try f.insts.append(e.dm.allocator(), try remapInst(e.arena, map, pi.inst, remap)); for (all) |items| for (items) |pi| try f.insts.append(e.dm.allocator(), try remapInst(e.arena, map, pi.inst, remap));
for (e.blocks.items) |blk| for (blk.items) |pi| try f.insts.append(e.dm.allocator(), try remapInst(e.arena, map, pi.inst, remap)); for (e.blocks.items) |blk| for (blk.items) |pi| try f.insts.append(e.dm.allocator(), try remapInst(e.arena, map, pi.inst, remap));
var ranges: std.AutoHashMapUnmanaged(u32, [2]u32) = .empty;
var it = e.dyn_ranges.iterator();
while (it.next()) |kv| try ranges.put(e.arena, map[kv.key_ptr.*], kv.value_ptr.*);
e.dyn_ranges.clearRetainingCapacity();
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
@ -1332,6 +1379,13 @@ const Emitter = struct {
/// Emits function `fi` inline at the current block with `args`; returns /// Emits function `fi` inline at the current block with `args`; returns
/// its result components and leaves the current block after the call. /// its result components and leaves the current block after the call.
fn inlineCall(e: *Emitter, fi: u32, args: []const Lowered) Error![]const Value { fn inlineCall(e: *Emitter, fi: u32, args: []const Lowered) Error![]const Value {
return e.inlineCallAliased(fi, args, &.{});
}
/// `aliases[k]`, when set, is the caller's place holding by-value
/// argument `k`, which the callee may read in place of a copy (see
/// 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,
@ -1339,6 +1393,11 @@ const Emitter = struct {
.params = args, .params = args,
.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) {
frame.param_srcs = aliases;
frame.param_copies = try e.paramCopies(fi);
break;
};
@memset(frame.vals, .none); @memset(frame.vals, .none);
@memset(frame.blocks, null); @memset(frame.blocks, null);
const is_entry = e.cur == 0 and e.blocks.items[0].items.len == 0 and (fi == e.entry.wrapper or fi == e.entry.patch_wrapper); const is_entry = e.cur == 0 and e.blocks.items[0].items.len == 0 and (fi == e.entry.wrapper or fi == e.entry.patch_wrapper);
@ -1352,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 &.{};
@ -1368,6 +1435,101 @@ const Emitter = struct {
return &.{}; return &.{};
} }
/// Places the by-value array and struct arguments of a call to `fi` can
/// be read from: a constant buffer they were loaded from (none with
/// matrices, whose constant buffer access is narrower than a local's),
/// or a local loaded in the same block with no write since. Calls with
/// 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;
var by_ref = false;
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| {
o.* = null;
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;
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;
}
/// For each instruction of IR function `fi`: the parameter a
/// `local_var` only ever holds a copy of (stored once, from that
/// by-value parameter, and otherwise only read), else maxInt.
fn paramCopies(e: *Emitter, fi: u32) Error![]const u32 {
const gop = try e.param_copies.getOrPut(e.arena, fi);
if (gop.found_existing) return gop.value_ptr.*;
const none = std.math.maxInt(u32);
const f = e.m.functions.items[fi];
const n = f.insts.items.len;
// The local each pointer is into.
const root = try e.arena.alloc(u32, n);
@memset(root, none);
var changed = true;
while (changed) {
changed = false;
for (f.insts.items, 0..) |inst, k| {
const want: u32 = switch (inst.op) {
.local_var => @intCast(k),
.access => |x| root[x.base.index()],
else => none,
};
if (want != root[k]) {
root[k] = want;
changed = true;
}
}
}
const out = try e.arena.alloc(u32, n);
@memset(out, none);
const ok = try e.arena.alloc(bool, n);
@memset(ok, true);
const Use = struct {
root: []const u32,
ok: []bool,
pub fn map(s: @This(), x: Ref) Ref {
if (x != .none and s.root[x.index()] != none) s.ok[s.root[x.index()]] = false;
return x;
}
};
for (f.insts.items) |inst| switch (inst.op) {
.local_var => {},
.load => {},
.access => |x| for (x.indices) |ix| {
_ = (Use{ .root = root, .ok = ok }).map(ix);
},
.store => |x| {
_ = (Use{ .root = root, .ok = ok }).map(x.value);
const l = root[x.ptr.index()];
if (l == none) continue;
const v = f.inst(x.value).op;
if (x.ptr.index() == l and v == .param and !f.params[v.param].by_ref and out[l] == none) {
out[l] = v.param;
} else ok[l] = false;
},
else => _ = try opt.mapOp(e.arena, inst.op, Use{ .root = root, .ok = ok }),
};
// Terminators returning pointers do not occur.
for (out, ok) |*o, good| if (!good) {
o.* = none;
};
gop.value_ptr.* = out;
return out;
}
/// A call of `[noinline]` function `fi` (module function `func`), as /// A call of `[noinline]` function `fi` (module function `func`), as
/// exportSignature passes values: out / inout values and structs /// exportSignature passes values: out / inout values and structs
/// through temporaries. /// through temporaries.
@ -1614,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) } });
@ -1640,6 +1808,12 @@ 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 (e.optimize and frame.cont != null and e.t.get(i.ty) == .array) {
const pooled = if (e.array_pool.getPtr(i.ty)) |l| l.pop() else null;
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) };
}, },
.load => |p| switch (frame.vals[p.index()]) { .load => |p| switch (frame.vals[p.index()]) {
@ -1670,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)}) };
@ -1699,12 +1874,19 @@ const Emitter = struct {
} }
return .{ .scalars = out }; return .{ .scalars = out };
}, },
.ptr => |ptr| return e.loadPtr(ptr, i.ty), .ptr => |ptr| {
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);
},
.typed => |tp| return e.typedLoad(tp, i.ty), .typed => |tp| return e.typedLoad(tp, i.ty),
.mesh => return e.unsupported("reading mesh shader outputs is not supported", .{}), .mesh => return e.unsupported("reading mesh shader outputs is not supported", .{}),
else => return e.unsupported("internal: load from a non-pointer", .{}), else => return e.unsupported("internal: load from a non-pointer", .{}),
}, },
.store => |s| { .store => |s| {
if (frame.param_copies.len > 0) if (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_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.
const v = frame.vals[s.value.index()]; const v = frame.vals[s.value.index()];
@ -1830,6 +2012,7 @@ const Emitter = struct {
} else { } else {
const idx = (try e.scalars(frame, x))[0]; const idx = (try e.scalars(frame, x))[0];
const scaled = if (s == 1) idx else try e.add(try e.dm.intType(32), .{ .binop = .{ .op = .mul, .lhs = idx, .rhs = try e.i32Const(s) } }); const scaled = if (s == 1) idx else try e.add(try e.dm.intType(32), .{ .binop = .{ .op = .mul, .lhs = idx, .rhs = try e.i32Const(s) } });
if (ptr.offset_dyn == null) ptr.dyn_range = .{ ptr.offset_const, ptr.offset_const + try e.flatCount(cur) };
ptr.offset_dyn = if (ptr.offset_dyn) |d| try e.add(try e.dm.intType(32), .{ .binop = .{ .op = .add, .lhs = d, .rhs = scaled } }) else scaled; ptr.offset_dyn = if (ptr.offset_dyn) |d| try e.add(try e.dm.intType(32), .{ .binop = .{ .op = .add, .lhs = d, .rhs = scaled } }) else scaled;
} }
cur = elem; cur = elem;
@ -1964,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.inlineCall(c.func, 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", .{});
@ -1999,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", .{}),
} }
} }
@ -2093,6 +2277,7 @@ const Emitter = struct {
const konst: ?u32 = if (xi.op == .constant) @intCast(xi.op.constant.int) else null; const konst: ?u32 = if (xi.op == .constant) @intCast(xi.op.constant.int) else null;
var data_off: u32 = 0; var data_off: u32 = 0;
var data_dyn: ?Value = null; var data_dyn: ?Value = null;
var data_extent: u32 = 0;
switch (e.t.get(cur)) { switch (e.t.get(cur)) {
.@"struct" => |st| { .@"struct" => |st| {
const k = konst.?; const k = konst.?;
@ -2113,6 +2298,7 @@ const Emitter = struct {
const idx = (try e.scalars(frame, x))[0]; const idx = (try e.scalars(frame, x))[0];
const n = try e.flatCount(arr.elem); const n = try e.flatCount(arr.elem);
data_dyn = if (n == 1) idx else try e.add(try e.dm.intType(32), .{ .binop = .{ .op = .mul, .lhs = idx, .rhs = try e.i32Const(n) } }); data_dyn = if (n == 1) idx else try e.add(try e.dm.intType(32), .{ .binop = .{ .op = .mul, .lhs = idx, .rhs = try e.i32Const(n) } });
data_extent = try e.flatCount(cur);
} }
cur = arr.elem; cur = arr.elem;
}, },
@ -2121,7 +2307,10 @@ const Emitter = struct {
if (data) |*d| switch (d.*) { if (data) |*d| switch (d.*) {
.ptr => |*ptr| { .ptr => |*ptr| {
ptr.offset_const += data_off; ptr.offset_const += data_off;
if (data_dyn) |dd| ptr.offset_dyn = if (ptr.offset_dyn) |old| try e.add(try e.dm.intType(32), .{ .binop = .{ .op = .add, .lhs = old, .rhs = dd } }) else dd; if (data_dyn) |dd| {
if (ptr.offset_dyn == null) ptr.dyn_range = .{ ptr.offset_const, ptr.offset_const + data_extent };
ptr.offset_dyn = if (ptr.offset_dyn) |old| try e.add(try e.dm.intType(32), .{ .binop = .{ .op = .add, .lhs = old, .rhs = dd } }) else dd;
}
}, },
.typed => try path.append(e.arena, (try e.scalars(frame, x))[0]), .typed => try path.append(e.arena, (try e.scalars(frame, x))[0]),
else => {}, else => {},
@ -2299,7 +2488,9 @@ const Emitter = struct {
var idx = try e.i32Const(ptr.offset_const + c); var idx = try e.i32Const(ptr.offset_const + c);
if (ptr.offset_dyn) |d| idx = try e.add(try e.dm.intType(32), .{ .binop = .{ .op = .add, .lhs = d, .rhs = idx } }); if (ptr.offset_dyn) |d| idx = try e.add(try e.dm.intType(32), .{ .binop = .{ .op = .add, .lhs = d, .rhs = idx } });
const pt = try e.dm.getType(.{ .pointer = .{ .elem = ptr.scalar_ty, .addr_space = ptr.addr_space } }); const pt = try e.dm.getType(.{ .pointer = .{ .elem = ptr.scalar_ty, .addr_space = ptr.addr_space } });
return e.add(pt, .{ .gep = .{ .elem = ptr.array_ty, .ptr = ptr.base, .indices = try e.arena.dupe(Value, &.{ try e.i32Const(0), idx }) } }); const gep = try e.add(pt, .{ .gep = .{ .elem = ptr.array_ty, .ptr = ptr.base, .indices = try e.arena.dupe(Value, &.{ try e.i32Const(0), idx }) } });
if (ptr.offset_dyn != null) if (ptr.dyn_range) |r| try e.dyn_ranges.put(e.arena, gep.inst, r);
return gep;
} }
fn convertScalar(e: *Emitter, v: Value, from: Scalar, to: Scalar) Error!Value { fn convertScalar(e: *Emitter, v: Value, from: Scalar, to: Scalar) Error!Value {
@ -4587,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,
@ -5500,6 +5702,7 @@ const Emitter = struct {
try dm.addNamedMetadata("dx.shaderModel", &.{sm}); try dm.addNamedMetadata("dx.shaderModel", &.{sm});
if (resources) |r| try dm.addNamedMetadata("dx.resources", &.{r}); if (resources) |r| try dm.addNamedMetadata("dx.resources", &.{r});
try dm.addNamedMetadata("dx.entryPoints", &.{entry_md}); try dm.addNamedMetadata("dx.entryPoints", &.{entry_md});
_ = try promote.pruneDeclarations(e.arena, dm);
return dm.writeBitcode(dm.arena.child_allocator); return dm.writeBitcode(dm.arena.child_allocator);
} }
@ -5699,3 +5902,11 @@ fn reachableBlocks(a: Allocator, f: *const ir.Function) Allocator.Error![]bool {
} }
return seen; return seen;
} }
/// Whether pointer `p` is into a function's own local (not a global or a
/// parameter's storage).
fn localRoot(f: *const ir.Function, p: Ref) bool {
var x = p;
while (f.inst(x).op == .access) x = f.inst(x).op.access.base;
return f.inst(x).op == .local_var;
}

956
src/dxil/promote.zig Normal file
View File

@ -0,0 +1,956 @@
//! Promotes locals from memory to SSA values, as LLVM's SROA and mem2reg do
//! for dxc. The emitter gives every local a flattened `[N x scalar]` alloca
//! (or a scalar one); an alloca whose every access is a load or store,
//! directly or through a getelementptr with constant indices, becomes one
//! SSA variable per element, with phis where control flow merges. Locals
//! indexed dynamically stay in memory, but only the components the dynamic
//! index can reach (`dyn`, from the emitter: the indexed array's extent);
//! the rest of such a local is still promoted. Locals used any other way
//! stay in memory.
//!
//! The phis go at the iterated dominance frontiers of the stores (Cytron et
//! al.), dominators by Cooper, Harvey and Kennedy's iteration. Phis whose
//! inputs are all one value, and phis nothing reads, are removed again.
const std = @import("std");
const Allocator = std.mem.Allocator;
const module = @import("module.zig");
const Value = module.Value;
const Inst = module.Inst;
const TypeId = module.TypeId;
const none = std.math.maxInt(u32);
const Role = enum { load_ptr, store_ptr, gep_base, other };
const Edge = @typeInfo(@FieldType(@FieldType(@FieldType(Inst, "op"), "phi"), "incoming")).pointer.child;
/// Visits each operand of `inst` (with the way it is used) through
/// `ctx.visit(value, role) Value`. With `write`, the results replace the
/// operands, in newly allocated slices where the operands are slices.
fn operands(comptime write: bool, a: Allocator, inst: *Inst, ctx: anytype) Allocator.Error!void {
const S = struct {
fn one(c: anytype, v: *Value, role: Role) void {
const r = c.visit(v.*, role);
if (write) v.* = r;
}
fn many(al: Allocator, c: anytype, vs: *[]const Value) Allocator.Error!void {
if (!write) {
for (vs.*) |v| _ = c.visit(v, .other);
return;
}
const out = try al.alloc(Value, vs.len);
for (vs.*, out) |v, *o| o.* = c.visit(v, .other);
vs.* = out;
}
};
switch (inst.op) {
.ret => |*v| if (v.*) |*x| S.one(ctx, x, .other),
.br => |*b| if (b.cond) |*c| S.one(ctx, c, .other),
.@"switch" => |*sw| S.one(ctx, &sw.cond, .other),
.call => |*c| try S.many(a, ctx, &c.args),
.binop => |*b| {
S.one(ctx, &b.lhs, .other);
S.one(ctx, &b.rhs, .other);
},
.cast => |*c| S.one(ctx, &c.val, .other),
.cmp => |*c| {
S.one(ctx, &c.lhs, .other);
S.one(ctx, &c.rhs, .other);
},
.select => |*s| {
S.one(ctx, &s.cond, .other);
S.one(ctx, &s.t, .other);
S.one(ctx, &s.f, .other);
},
.extractvalue => |*x| S.one(ctx, &x.agg, .other),
.phi => |*p| {
if (!write) {
for (p.incoming) |in| _ = ctx.visit(in.val, .other);
} else {
const out = try a.alloc(Edge, p.incoming.len);
for (p.incoming, out) |in, *o| o.* = .{ .val = ctx.visit(in.val, .other), .block = in.block };
p.incoming = out;
}
},
.alloca => |*x| S.one(ctx, &x.size, .other),
.load => |*x| S.one(ctx, &x.ptr, .load_ptr),
.store => |*x| {
S.one(ctx, &x.ptr, .store_ptr);
S.one(ctx, &x.val, .other);
},
.gep => |*x| {
S.one(ctx, &x.ptr, .gep_base);
try S.many(a, ctx, &x.indices);
},
.atomicrmw => |*x| {
S.one(ctx, &x.ptr, .other);
S.one(ctx, &x.val, .other);
},
.cmpxchg => |*x| {
S.one(ctx, &x.ptr, .other);
S.one(ctx, &x.cmp, .other);
S.one(ctx, &x.new, .other);
},
.@"unreachable" => {},
.extractelement => |*x| {
S.one(ctx, &x.vec, .other);
S.one(ctx, &x.index, .other);
},
.insertelement => |*x| {
S.one(ctx, &x.vec, .other);
S.one(ctx, &x.val, .other);
S.one(ctx, &x.index, .other);
},
}
}
fn isTerminator(inst: Inst) bool {
return switch (inst.op) {
.ret, .br, .@"switch", .@"unreachable" => true,
else => false,
};
}
fn isScalar(m: *const module.Module, ty: TypeId) bool {
return switch (m.types.items[ty]) {
.half, .float, .double, .int => true,
else => false,
};
}
/// `dyn` maps the dynamically indexed getelementptrs into locals to the
/// components [lo, hi) they can reach; one missing from it can reach all.
pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashMapUnmanaged(u32, [2]u32)) Allocator.Error!void {
const f = &m.functions.items[func];
const insts = f.insts.items;
const n: u32 = @intCast(insts.len);
const nb = f.num_blocks;
if (n == 0 or nb == 0) return;
// Blocks: instruction ranges, successors and predecessors (one entry
// per edge, so a switch's repeated target counts once per case).
const block_start = try a.alloc(u32, nb + 1);
const block_of = try a.alloc(u32, n);
{
var b: u32 = 0;
block_start[0] = 0;
for (insts, 0..) |inst, i| {
if (b >= nb) return; // not the block layout this pass expects
block_of[i] = b;
if (isTerminator(inst)) {
b += 1;
block_start[b] = @intCast(i + 1);
}
}
if (b != nb) return;
}
const succ_off = try a.alloc(u32, nb + 1);
var succs: std.ArrayList(u32) = .empty;
for (0..nb) |b| {
succ_off[b] = @intCast(succs.items.len);
switch (insts[block_start[b + 1] - 1].op) {
.br => |br| {
try succs.append(a, br.then);
if (br.@"else") |e| try succs.append(a, e);
},
.@"switch" => |sw| {
try succs.append(a, sw.default);
for (sw.cases) |c| try succs.append(a, c.block);
},
else => {},
}
}
succ_off[nb] = @intCast(succs.items.len);
const pred_off = try a.alloc(u32, nb + 1);
@memset(pred_off, 0);
for (succs.items) |s| pred_off[s + 1] += 1;
for (1..nb + 1) |b| pred_off[b] += pred_off[b - 1];
const preds = try a.alloc(u32, succs.items.len);
{
const fill = try a.dupe(u32, pred_off[0..nb]);
for (0..nb) |b| for (succs.items[succ_off[b]..succ_off[b + 1]]) |s| {
preds[fill[s]] = @intCast(b);
fill[s] += 1;
};
}
// Reverse postorder from the entry; unreachable blocks stay `none`.
const rpo_index = try a.alloc(u32, nb);
@memset(rpo_index, none);
const rpo = try a.alloc(u32, nb);
var nr: u32 = 0;
{
const post = try a.alloc(u32, nb);
var np: u32 = 0;
const seen = try a.alloc(bool, nb);
@memset(seen, false);
const Frame = struct { b: u32, next: u32 };
var stack: std.ArrayList(Frame) = .empty;
try stack.append(a, .{ .b = 0, .next = succ_off[0] });
seen[0] = true;
while (stack.items.len > 0) {
const top = &stack.items[stack.items.len - 1];
if (top.next < succ_off[top.b + 1]) {
const s = succs.items[top.next];
top.next += 1;
if (!seen[s]) {
seen[s] = true;
try stack.append(a, .{ .b = s, .next = succ_off[s] });
}
} else {
post[np] = top.b;
np += 1;
_ = stack.pop();
}
}
for (0..np) |k| {
rpo[k] = post[np - 1 - k];
rpo_index[rpo[k]] = @intCast(k);
}
nr = np;
}
// Immediate dominators.
const idom = try a.alloc(u32, nb);
@memset(idom, none);
idom[0] = 0;
{
var changed = true;
while (changed) {
changed = false;
for (rpo[1..nr]) |b| {
var new: u32 = none;
for (preds[pred_off[b]..pred_off[b + 1]]) |p| {
if (idom[p] == none) continue;
if (new == none) {
new = p;
continue;
}
var x = p;
var y = new;
while (x != y) {
while (rpo_index[x] > rpo_index[y]) x = idom[x];
while (rpo_index[y] > rpo_index[x]) y = idom[y];
}
new = x;
}
if (new != idom[b]) {
idom[b] = new;
changed = true;
}
}
}
}
// Dominance frontiers.
const df = try a.alloc(std.ArrayList(u32), nb);
@memset(df, .empty);
for (rpo[0..nr]) |b| {
const ps = preds[pred_off[b]..pred_off[b + 1]];
if (ps.len < 2) continue;
for (ps) |p| {
if (rpo_index[p] == none) continue;
var r = p;
while (r != idom[b]) {
const l = &df[r];
if (l.items.len == 0 or l.items[l.items.len - 1] != b) try l.append(a, b);
r = idom[r];
}
}
}
// Candidate allocas: arrays of scalars and scalars. `var_base[i]` is
// the variable of an alloca's element 0, `none` if it stays in memory.
const var_base = try a.alloc(u32, n);
@memset(var_base, none);
const elem_ty = try a.alloc(TypeId, n);
const direct = try a.alloc(bool, n);
for (insts, 0..) |inst, i| switch (inst.op) {
.alloca => |x| switch (m.types.items[x.elem]) {
.array => |arr| if (isScalar(m, arr.elem) and arr.len > 0) {
var_base[i] = 0;
elem_ty[i] = arr.elem;
direct[i] = false;
},
else => if (isScalar(m, x.elem)) {
var_base[i] = 0;
elem_ty[i] = x.elem;
direct[i] = true;
},
},
else => {},
};
// getelementptrs of candidates: the alloca and the element they
// address (`none` for a dynamic index, which pins its range).
const gep_alloca = try a.alloc(u32, n);
@memset(gep_alloca, none);
const gep_k = try a.alloc(u32, n);
const Scan = struct {
insts: []const Inst,
var_base: []u32,
direct: []const bool,
gep_alloca: []const u32,
fn visit(s: *@This(), v: Value, role: Role) Value {
if (v != .inst) return v;
const i = v.inst;
if (s.var_base[i] != none and s.insts[i].op == .alloca) {
const ok = switch (role) {
.gep_base => !s.direct[i],
.load_ptr, .store_ptr => s.direct[i],
.other => false,
};
if (!ok) s.var_base[i] = none;
} else if (s.gep_alloca[i] != none and role != .load_ptr and role != .store_ptr) {
s.var_base[s.gep_alloca[i]] = none;
}
return v;
}
};
for (insts, 0..) |inst, i| switch (inst.op) {
.gep => |g| if (g.ptr == .inst and var_base[g.ptr.inst] != none and insts[g.ptr.inst].op == .alloca) {
const al = g.ptr.inst;
if (direct[al]) {
var_base[al] = none;
continue;
}
const k = constIndex(m, g.indices, m.types.items[insts[al].op.alloca.elem].array.len);
if (k) |kk| {
gep_alloca[i] = al;
gep_k[i] = kk;
} else if (dyn.contains(@intCast(i)) and g.indices.len == 2 and constInt(m, g.indices[0]) == 0) {
gep_alloca[i] = al;
gep_k[i] = none;
} else var_base[al] = none;
},
else => {},
};
{
var scan: Scan = .{ .insts = insts, .var_base = var_base, .direct = direct, .gep_alloca = gep_alloca };
for (insts) |*inst| try operands(false, a, inst, &scan);
}
// Loads and stores must move whole elements of the element type.
for (insts) |inst| {
const ptr, const ty = switch (inst.op) {
.load => |x| .{ x.ptr, inst.ty },
.store => |x| .{ x.ptr, typeOf(m, f, x.val) },
else => continue,
};
if (ptr != .inst) continue;
const al = if (gep_alloca[ptr.inst] != none) gep_alloca[ptr.inst] else ptr.inst;
if (var_base[al] != none and insts[al].op == .alloca and ty != elem_ty[al]) var_base[al] = none;
}
// Variables.
var nv: u32 = 0;
for (insts, 0..) |inst, i| {
if (inst.op != .alloca or var_base[i] == none) continue;
var_base[i] = nv;
nv += if (direct[i]) 1 else @intCast(m.types.items[inst.op.alloca.elem].array.len);
}
if (nv == 0) return;
const var_ty = try a.alloc(TypeId, nv);
for (insts, 0..) |inst, i| {
if (inst.op != .alloca or var_base[i] == none) continue;
const len: u32 = if (direct[i]) 1 else @intCast(m.types.items[inst.op.alloca.elem].array.len);
@memset(var_ty[var_base[i]..][0..len], elem_ty[i]);
}
// Components a dynamic index can reach stay in memory, and so does
// their alloca.
const pinned = try a.alloc(bool, nv);
@memset(pinned, false);
const keep = try a.alloc(bool, n);
@memset(keep, false);
for (insts, 0..) |inst, i| {
if (inst.op != .gep or gep_alloca[i] == none or gep_k[i] != none) continue;
const al = gep_alloca[i];
if (var_base[al] == none) continue;
const len: u32 = @intCast(m.types.items[insts[al].op.alloca.elem].array.len);
const r = dyn.get(@intCast(i)).?;
const lo = @min(r[0], len);
const hi = @min(r[1], len);
@memset(pinned[var_base[al] + lo .. var_base[al] + hi], true);
keep[al] = true;
}
// The variable an instruction loads or stores, or `none`.
const access = try a.alloc(u32, n);
@memset(access, none);
for (insts, 0..) |inst, i| {
const ptr = switch (inst.op) {
.load => |x| x.ptr,
.store => |x| x.ptr,
else => continue,
};
if (ptr != .inst) continue;
const p = ptr.inst;
if (gep_alloca[p] != none and var_base[gep_alloca[p]] != none) {
if (gep_k[p] != none and !pinned[var_base[gep_alloca[p]] + gep_k[p]]) access[i] = var_base[gep_alloca[p]] + gep_k[p];
} else if (insts[p].op == .alloca and var_base[p] != none) {
access[i] = var_base[p];
}
}
// A variable needs phis unless all its accesses are in one block and
// the first is a store. Collect the blocks that store the others.
const first_block = try a.alloc(u32, nv);
@memset(first_block, none);
const global = try a.alloc(bool, nv);
@memset(global, false);
for (insts, 0..) |inst, i| {
const v = access[i];
if (v == none) continue;
if (first_block[v] == none) {
first_block[v] = block_of[i];
if (inst.op == .load) global[v] = true;
} else if (first_block[v] != block_of[i]) global[v] = true;
}
const Def = struct { v: u32, b: u32 };
var defs: std.ArrayList(Def) = .empty;
for (insts, 0..) |inst, i| {
const v = access[i];
if (v == none or inst.op != .store or !global[v] or rpo_index[block_of[i]] == none) continue;
try defs.append(a, .{ .v = v, .b = block_of[i] });
}
std.sort.pdq(Def, defs.items, {}, struct {
fn lt(_: void, x: Def, y: Def) bool {
return if (x.v != y.v) x.v < y.v else x.b < y.b;
}
}.lt);
// Phis at the iterated dominance frontiers.
var phi_var: std.ArrayList(u32) = .empty;
var phi_block: std.ArrayList(u32) = .empty;
{
const has_phi = try a.alloc(u32, nb);
@memset(has_phi, none);
const queued = try a.alloc(u32, nb);
@memset(queued, none);
var work: std.ArrayList(u32) = .empty;
var k: usize = 0;
while (k < defs.items.len) {
const v = defs.items[k].v;
work.clearRetainingCapacity();
while (k < defs.items.len and defs.items[k].v == v) : (k += 1) {
const b = defs.items[k].b;
if (queued[b] != v) {
queued[b] = v;
try work.append(a, b);
}
}
while (work.pop()) |b| for (df[b].items) |y| {
if (has_phi[y] == v) continue;
has_phi[y] = v;
try phi_var.append(a, v);
try phi_block.append(a, y);
if (queued[y] != v) {
queued[y] = v;
try work.append(a, y);
}
};
}
}
const np: u32 = @intCast(phi_var.items.len);
// Phis per block, and their incoming edges (filled while renaming).
const bphi_off = try a.alloc(u32, nb + 1);
@memset(bphi_off, 0);
for (phi_block.items) |b| bphi_off[b + 1] += 1;
for (1..nb + 1) |b| bphi_off[b] += bphi_off[b - 1];
const bphis = try a.alloc(u32, np);
{
const fill = try a.dupe(u32, bphi_off[0..nb]);
for (phi_block.items, 0..) |b, j| {
bphis[fill[b]] = @intCast(j);
fill[b] += 1;
}
}
const incoming = try a.alloc([]Edge, np);
const filled = try a.alloc(u32, np);
@memset(filled, 0);
for (incoming, phi_block.items) |*in, b| in.* = try a.alloc(Edge, pred_off[b + 1] - pred_off[b]);
// Renaming, over the dominator tree. A load's replacement goes to
// `repl`; phi `j` is the value `.{ .inst = n + j }` until rebuilt.
// A local read before any store reads zero: the validator rejects
// instructions that read undef.
var zeros: std.AutoHashMapUnmanaged(TypeId, Value) = .empty;
const Zero = struct {
fn get(al: Allocator, mm: *module.Module, cache: *std.AutoHashMapUnmanaged(TypeId, Value), ty: TypeId) Allocator.Error!Value {
const gop = try cache.getOrPut(al, ty);
if (!gop.found_existing) gop.value_ptr.* = try mm.constant(.{ .ty = ty, .kind = switch (mm.types.items[ty]) {
.int => .{ .int = 0 },
else => .{ .float_bits = 0 },
} });
return gop.value_ptr.*;
}
};
const repl = try a.alloc(?Value, n + np);
@memset(repl, null);
const cur = try a.alloc(Value, nv);
for (cur, var_ty) |*c, t| c.* = try Zero.get(a, m, &zeros, t);
{
const child_off = try a.alloc(u32, nb + 1);
@memset(child_off, 0);
for (rpo[1..nr]) |b| child_off[idom[b] + 1] += 1;
for (1..nb + 1) |b| child_off[b] += child_off[b - 1];
const children = try a.alloc(u32, nr);
{
const fill = try a.dupe(u32, child_off[0..nb]);
for (rpo[1..nr]) |b| {
children[fill[idom[b]]] = b;
fill[idom[b]] += 1;
}
}
const Undo = struct { v: u32, old: Value };
var log: std.ArrayList(Undo) = .empty;
const Visit = struct { b: u32, mark: u32, enter: bool };
var stack: std.ArrayList(Visit) = .empty;
try stack.append(a, .{ .b = 0, .mark = 0, .enter = true });
while (stack.pop()) |top| {
if (!top.enter) {
while (log.items.len > top.mark) {
const u = log.pop().?;
cur[u.v] = u.old;
}
continue;
}
const b = top.b;
try stack.append(a, .{ .b = b, .mark = @intCast(log.items.len), .enter = false });
for (bphis[bphi_off[b]..bphi_off[b + 1]]) |j| {
const v = phi_var.items[j];
try log.append(a, .{ .v = v, .old = cur[v] });
cur[v] = .{ .inst = n + j };
}
for (block_start[b]..block_start[b + 1]) |i| {
const v = access[i];
if (v == none) continue;
switch (insts[i].op) {
.load => repl[i] = cur[v],
.store => |x| {
try log.append(a, .{ .v = v, .old = cur[v] });
cur[v] = resolve(repl, x.val);
},
else => unreachable,
}
}
for (succs.items[succ_off[b]..succ_off[b + 1]]) |s| for (bphis[bphi_off[s]..bphi_off[s + 1]]) |j| {
incoming[j][filled[j]] = .{ .val = cur[phi_var.items[j]], .block = b };
filled[j] += 1;
};
for (children[child_off[b]..child_off[b + 1]]) |c| try stack.append(a, .{ .b = c, .mark = 0, .enter = true });
}
}
// Edges from unreachable blocks bring zero; loads there read zero.
for (0..np) |j| {
const b = phi_block.items[j];
for (preds[pred_off[b]..pred_off[b + 1]]) |p| {
if (rpo_index[p] != none) continue;
incoming[j][filled[j]] = .{ .val = try Zero.get(a, m, &zeros, var_ty[phi_var.items[j]]), .block = p };
filled[j] += 1;
}
}
for (insts, 0..) |inst, i| {
if (access[i] != none and inst.op == .load and repl[i] == null)
repl[i] = try Zero.get(a, m, &zeros, var_ty[access[i]]);
}
// Phis whose inputs (besides themselves) are one value become it.
const removed_phi = try a.alloc(bool, np);
@memset(removed_phi, false);
{
var changed = true;
while (changed) {
changed = false;
for (0..np) |j| {
if (removed_phi[j]) continue;
const self: Value = .{ .inst = n + @as(u32, @intCast(j)) };
var same: ?Value = null;
var trivial = true;
for (incoming[j]) |in| {
const x = resolve(repl, in.val);
if (std.meta.eql(x, self)) continue;
if (same) |s| {
if (!std.meta.eql(s, x)) {
trivial = false;
break;
}
} else same = x;
}
if (!trivial) continue;
repl[n + j] = same orelse try Zero.get(a, m, &zeros, var_ty[phi_var.items[j]]);
removed_phi[j] = true;
changed = true;
}
}
}
// 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,
// loads and stores.
const removed = try a.alloc(bool, n);
for (insts, 0..) |inst, i| removed[i] = switch (inst.op) {
.alloca => var_base[i] != none and !keep[i],
.gep => gep_alloca[i] != none and var_base[gep_alloca[i]] != none and gep_k[i] != none and !pinned[var_base[gep_alloca[i]] + gep_k[i]],
.load, .store => access[i] != none,
else => false,
};
// What stays: instructions with effects, and what they read,
// transitively; new phis likewise. (The loads promotion leaves dead,
// such as copies of arguments never read, go too.)
const live = try a.alloc(bool, n + np);
@memset(live, false);
{
var work: std.ArrayList(u32) = .empty;
const Mark = struct {
repl: []const ?Value,
live: []bool,
removed: []const bool,
work: *std.ArrayList(u32),
a: Allocator,
failed: bool = false,
fn visit(s: *@This(), v: Value, _: Role) Value {
const x = resolve(s.repl, v);
if (x == .inst and !s.live[x.inst] and !(x.inst < s.removed.len and s.removed[x.inst])) {
s.live[x.inst] = true;
s.work.append(s.a, x.inst) catch {
s.failed = true;
};
}
return v;
}
};
var mark: Mark = .{ .repl = repl, .live = live, .removed = removed, .work = &work, .a = a };
for (insts, 0..) |inst, i| if (!removed[i] and hasEffects(m, inst)) {
live[i] = true;
try work.append(a, @intCast(i));
};
while (work.pop()) |x| {
if (x < n) {
var inst = insts[x];
try operands(false, a, &inst, &mark);
} else for (incoming[x - n]) |in| {
_ = mark.visit(in.val, .other);
}
}
if (mark.failed) return error.OutOfMemory;
}
// New indices: in each block the existing phis, then the new ones,
// then the rest.
const index = try a.alloc(u32, n + np);
@memset(index, none);
var count: u32 = 0;
for (0..nb) |b| {
var i = block_start[b];
while (i < block_start[b + 1] and insts[i].op == .phi) : (i += 1) if (live[i]) {
index[i] = count;
count += 1;
};
for (bphis[bphi_off[b]..bphi_off[b + 1]]) |j| if (live[n + j]) {
index[n + j] = count;
count += 1;
};
while (i < block_start[b + 1]) : (i += 1) if (live[i]) {
index[i] = count;
count += 1;
};
}
const Map = struct {
repl: []const ?Value,
index: []const u32,
fn visit(s: *@This(), v: Value, _: Role) Value {
const x = resolve(s.repl, v);
return if (x == .inst) .{ .inst = s.index[x.inst] } else x;
}
};
var map: Map = .{ .repl = repl, .index = index };
const ma = m.allocator();
var out: std.ArrayList(Inst) = .empty;
try out.ensureTotalCapacityPrecise(ma, count);
for (0..nb) |b| {
var i = block_start[b];
while (i < block_start[b + 1] and insts[i].op == .phi) : (i += 1) if (live[i]) {
var inst = insts[i];
try operands(true, ma, &inst, &map);
out.appendAssumeCapacity(inst);
};
for (bphis[bphi_off[b]..bphi_off[b + 1]]) |j| if (live[n + j]) {
const edges = try ma.alloc(Edge, incoming[j].len);
for (incoming[j], edges) |in, *e| e.* = .{ .val = map.visit(in.val, .other), .block = in.block };
out.appendAssumeCapacity(.{ .ty = var_ty[phi_var.items[j]], .op = .{ .phi = .{ .incoming = edges } } });
};
while (i < block_start[b + 1]) : (i += 1) if (live[i]) {
var inst = insts[i];
try operands(true, ma, &inst, &map);
if (inst.op == .gep) try clampIndex(m, &inst.op.gep);
out.appendAssumeCapacity(inst);
};
}
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.
fn hasEffects(m: *const module.Module, inst: Inst) bool {
return switch (inst.op) {
.ret, .br, .@"switch", .@"unreachable", .store, .atomicrmw, .cmpxchg => true,
.call => |c| switch (m.functions.items[c.callee].attrs) {
.nounwind_readnone, .nounwind_readonly => false,
else => true,
},
else => false,
};
}
/// `v` with replaced loads and phis followed to their final value.
fn resolve(repl: []const ?Value, v: Value) Value {
var x = v;
while (x == .inst) {
const r = repl[x.inst] orelse break;
x = r;
}
return x;
}
/// Element `k` of `getelementptr [len x T], %a, 0, k`, or null.
fn constIndex(m: *const module.Module, indices: []const Value, len: u64) ?u32 {
if (indices.len != 2) return null;
const first = constInt(m, indices[0]) orelse return null;
const k = constInt(m, indices[1]) orelse return null;
if (first != 0 or k < 0 or k >= len) return null;
return @intCast(k);
}
fn constInt(m: *const module.Module, v: Value) ?i64 {
if (v != .constant) return null;
return switch (m.constants.items[v.constant].kind) {
.int => |x| x,
else => null,
};
}
fn typeOf(m: *const module.Module, f: *const module.Function, v: Value) TypeId {
return switch (v) {
.inst => |i| f.insts.items[i].ty,
.constant => |c| m.constants.items[c].ty,
.arg => |k| m.types.items[f.ty].function.params[k],
.global => |g| m.globals.items[g].ptr_ty,
.function => none,
};
}
/// Drops the function declarations nothing calls or refers to any more
/// (dead code removal can take a dx.op's last call, and the validator
/// rejects unused external functions), renumbering the other functions.
/// Run last: indices the emitter holds go stale. Returns the new index of
/// each old function (`none` for dropped ones), or null if none went.
pub fn pruneDeclarations(a: Allocator, m: *module.Module) Allocator.Error!?[]const u32 {
const funcs = m.functions.items;
const used = try a.alloc(bool, funcs.len);
for (funcs, used) |f, *u| u.* = f.num_blocks > 0;
const Use = struct {
used: []bool,
fn visit(s: *@This(), v: Value, _: Role) Value {
if (v == .function) s.used[v.function] = true;
return v;
}
};
var use: Use = .{ .used = used };
for (funcs) |f| for (f.insts.items) |*inst| {
if (inst.op == .call) used[inst.op.call.callee] = true;
try operands(false, a, inst, &use);
};
for (m.metadata.items) |md| if (md == .value and md.value.val == .function) {
used[md.value.val.function] = true;
};
if (std.mem.indexOfScalar(bool, used, false) == null) return null;
const index = try a.alloc(u32, funcs.len);
var count: u32 = 0;
for (used, index) |u, *x| {
x.* = if (u) count else none;
if (u) count += 1;
}
const Map = struct {
index: []const u32,
fn visit(s: *@This(), v: Value, _: Role) Value {
return if (v == .function) .{ .function = s.index[v.function] } else v;
}
};
var map: Map = .{ .index = index };
const ma = m.allocator();
for (funcs) |*f| for (f.insts.items) |*inst| {
try operands(true, ma, inst, &map);
if (inst.op == .call) inst.op.call.callee = index[inst.op.call.callee];
};
for (m.metadata.items) |*md| if (md.* == .value and md.value.val == .function) {
md.value.val = .{ .function = index[md.value.val.function] };
};
var k: usize = 0;
for (funcs, used) |f, u| if (u) {
funcs[k] = f;
k += 1;
};
m.functions.shrinkRetainingCapacity(k);
return index;
}

418
src/ir/inline.zig Normal file
View File

@ -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;
}

View File

@ -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() });

View File

@ -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 });

View File

@ -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).?;

811
src/ir/ssa.zig Normal file
View File

@ -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;
}
}
}

View File

@ -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" },

View File

@ -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 {

View File

@ -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;
},
} }
} }