From a80a77c0b863c8981d119cd2aacb1dc3ec294ade Mon Sep 17 00:00:00 2001 From: peterino2 Date: Mon, 2 Nov 2026 23:34:14 -0800 Subject: [PATCH 1/2] Compile Unreal Engine 5.8's shaders as a DXC drop-in Every shader the editor compiles (11,488 recorded Compile calls) now compiles, passes DXC 1.8's validator, and reflects bindings the engine accepts; the editor runs with the D3D debug layer clean. Front end and semantics: - -HV 2016..2018 and 2021, with HLSL 2018's component-wise &&, || and ?: - overload ranking with DXC's conversion costs (worst, then sum), where intrinsics compete with user functions and templates; ref parameters of intrinsics (Interlocked* destinations) match exactly - template class methods checked on use; elaborated struct declarations; struct fields before globals in methods - layout of structs over 256 fields DXIL backend: - loops with a constant trip count unrolled after promotion (unroll.zig) - sparse conditional constant propagation (sccp.zig) - loops with no effects deleted; constant switches folded; float compares of constants folded; phis read on the edge their branch's condition decides; empty branches folded through chains of empty blocks - unreachable blocks, unused groupshared, and resources no code uses any more dropped; shader flags, PSV and handle properties from what is left - 64-bit typed resources and atomics --- src/compile.zig | 13 +- src/dxil/emit.zig | 631 ++++++++++++++++++++++++++++----- src/dxil/libinfo.zig | 2 +- src/dxil/promote.zig | 472 +++++++++++++++++++++++-- src/dxil/sccp.zig | 322 +++++++++++++++++ src/dxil/unroll.zig | 749 ++++++++++++++++++++++++++++++++++++++++ src/front/ast.zig | 2 + src/front/parser.zig | 26 +- src/front/preproc.zig | 6 +- src/ir/ir.zig | 3 + src/ir/layout.zig | 38 +- src/ir/lower.zig | 26 +- src/ir/opt.zig | 21 +- src/sema/intrinsics.zig | 28 +- src/sema/sema.zig | 319 +++++++++++++---- src/sema/types.zig | 39 +++ 16 files changed, 2465 insertions(+), 232 deletions(-) create mode 100644 src/dxil/sccp.zig create mode 100644 src/dxil/unroll.zig diff --git a/src/compile.zig b/src/compile.zig index 443dd98..6edca7d 100644 --- a/src/compile.zig +++ b/src/compile.zig @@ -168,6 +168,8 @@ const Options = struct { preprocess: bool = false, pp_output: ?[]const u8 = null, enable_16bit: bool = false, + /// -HV: 2021, or 2016-2018 (component-wise `&&`, `||` and `?:`). + hlsl_version: u16 = 2021, row_major: bool = false, col_major: bool = false, /// -force-rootsig-ver, -Qstrip_rootsignature, -rootsig-define, -Frs. @@ -249,8 +251,12 @@ fn parseArgs(ctx: *Ctx, arena: std.mem.Allocator, args: []const []const u8) !?Op try opts.defines.append(arena, .{ .name = v[0..eq], .value = v[eq + 1 ..] }); } else try opts.defines.append(arena, .{ .name = v }), .I => try opts.include_dirs.append(arena, v), - .hlsl_version => if (!std.mem.eql(u8, v, "2021")) { - return ctx.fail("HLSL version {s} is not supported; zdxc implements HLSL 2021 only", .{v}); + .hlsl_version => { + const n = std.fmt.parseInt(u16, v, 10) catch 0; + if (n != 2021 and (n < 2016 or n > 2018)) { + return ctx.fail("HLSL version {s} is not supported; zdxc implements HLSL 2016-2018 and 2021", .{v}); + } + opts.hlsl_version = n; }, .P => opts.preprocess = true, .spirv => opts.spirv = true, @@ -435,6 +441,7 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void { .spirv = opts.spirv, .spirv_minor = if (zdxc.spirv.emit.TargetEnv.parse(opts.target_env)) |t| t.minor else 0, .enable_16bit = opts.enable_16bit, + .hlsl_version = opts.hlsl_version, }); var out: Io.Writer.Allocating = .init(arena); var module: ?zdxc.ir.ir.Module = null; @@ -452,6 +459,7 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void { .entry = if (opts.sema or is_lib) null else opts.entry, .spirv = opts.spirv, .enable_16bit = opts.enable_16bit, + .hlsl_version = opts.hlsl_version, .sm_minor = if (profile) |p| p.minor else 10, .library = is_lib, .root = opts.entry, @@ -502,6 +510,7 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void { if (opts.parse or opts.sema) return; if (profile == null) return ctx.fail("missing -T ", .{}); if (module) |*m| { + m.auto_unroll = !opts.spirv and !opts.no_opt and opts.opt_level != .od; try zdxc.ir.opt.run(arena, m); if (opts.spirv) { zdxc.ir.split_resources.run(arena, m, &diags) catch |err| switch (err) { diff --git a/src/dxil/emit.zig b/src/dxil/emit.zig index 4771612..26acd79 100644 --- a/src/dxil/emit.zig +++ b/src/dxil/emit.zig @@ -24,6 +24,8 @@ const libinfo = @import("libinfo.zig"); const reflect = @import("reflect.zig"); const rootsig = @import("rootsig.zig"); const promote = @import("promote.zig"); +const unroll = @import("unroll.zig"); +const sccp = @import("sccp.zig"); const opt = @import("../ir/opt.zig"); const TypeId = types.TypeId; @@ -149,6 +151,8 @@ const Resource = struct { rov: bool = false, /// Registers in the range (arrays of resources); maxInt for unsized. count: u32 = 1, + /// Used by 64-bit atomics (metadata tag 3). + atomic64: bool = false, /// An array element's handle made at its use: a copy of the array's /// entry, skipped by metadata. (Descriptor heap resources are views /// with no global.) @@ -175,6 +179,14 @@ const Frame = struct { /// `.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, + /// For each block, the target its branch on a constant took (else + /// maxInt), and the blocks still reachable given those (see + /// inlineCallFresh). + taken: []u32 = &.{}, + live: []bool = &.{}, + /// When optimizing: paramCopies of the function (loads of such a local + /// are the argument itself). + copies: []const u32 = &.{}, /// By-value parameters passed as the caller's place (see paramCopies). param_srcs: []const ?Lowered = &.{}, /// paramCopies of the function, when some parameter is aliased. @@ -213,6 +225,11 @@ const Emitter = struct { resource_of_global: std.AutoHashMapUnmanaged(u32, u32) = .empty, private_globals: std.AutoHashMapUnmanaged(u32, Ptr) = .empty, private_typed: std.AutoHashMapUnmanaged(u32, @FieldType(Lowered, "typed")) = .empty, + /// Locals holding a copy of a texel read through an index (see the + /// `access` op): writes through them would not reach the texture. + texel_copies: std.AutoHashMapUnmanaged(Value, void) = .empty, + /// Static globals holding resources (as locals: Emitter.aggLocal). + private_aggs: std.AutoHashMapUnmanaged(u32, Lowered) = .empty, res_locals: std.ArrayList(?Lowered) = .empty, /// Indices marked with NonUniformResourceIndex. nonuniform: std.AutoHashMapUnmanaged(Value, void) = .empty, @@ -228,6 +245,8 @@ const Emitter = struct { uses_inner_coverage: bool = false, uses_resource_heap: bool = false, uses_extended_command_info: bool = false, + /// 64-bit atomics on a typed resource. + uses_atomic64_typed: bool = false, uses_tiled_resources: bool = false, uses_mesh_derivatives: bool = false, uses_ray_query: bool = false, @@ -289,6 +308,10 @@ const Emitter = struct { /// Libraries: `[noinline]` functions kept as functions of their own /// (IR function -> module function). lib_calls: std.AutoHashMapUnmanaged(u32, u32) = .empty, + /// Results of pure uniform functions (see pureUniform), computed once + /// in the prologue. + call_memo: std.AutoHashMapUnmanaged(u32, []const Value) = .empty, + pure_fns: std.AutoHashMapUnmanaged(u32, bool) = .empty, /// Each HLSL struct's module type (struct types are named, and two /// structs may share a name: `A::In`, `A::In`). struct_types: std.AutoHashMapUnmanaged(TypeId, DType) = .empty, @@ -402,6 +425,25 @@ const Emitter = struct { }; } + /// Undefined values for the flattened components of `ty`. + fn undefValues(e: *Emitter, ty: TypeId) Error![]const Value { + var out: std.ArrayList(Value) = .empty; + try e.appendUndef(&out, ty); + return out.items; + } + + fn appendUndef(e: *Emitter, out: *std.ArrayList(Value), ty: TypeId) Error!void { + switch (e.t.get(ty)) { + .array => |a| for (0..a.len) |_| try e.appendUndef(out, a.elem), + .@"struct" => |st| for (st.fields.items) |f| try e.appendUndef(out, f.type), + .resource, .sampler => {}, + else => { + const v = try e.dm.constant(.{ .ty = try e.scalarTy(e.compOf(ty)), .kind = .undef }); + for (0..try e.flatCount(ty)) |_| try out.append(e.arena, v); + }, + } + } + /// The single scalar type all components of `ty` share. fn uniformScalar(e: *Emitter, ty: TypeId) Error!Scalar { return switch (e.t.get(ty)) { @@ -476,10 +518,13 @@ const Emitter = struct { // The patch constant function is a function of its own. e.blocks = .empty; e.prologue = .empty; + e.call_memo = .empty; + e.texel_copies = .empty; e.next_id = 0; e.inst_types = .empty; e.private_globals = .empty; e.private_typed = .empty; + e.private_aggs = .empty; e.nonuniform = .empty; const name = m.functions.items[pw].name; e.pc_fn = try e.dm.addFunction(.{ .name = name[0 .. name.len - ".wrapper".len], .ty = fn_ty, .num_blocks = 1 }); @@ -490,6 +535,7 @@ const Emitter = struct { } if (e.optimize) e.inputUsage(); + if (e.optimize and e.profile.minor >= 6) try e.dropDeadResources(); const bitcode = try e.writeModule(entry); defer gpa.free(bitcode); return e.assemble(gpa, entry, bitcode); @@ -660,10 +706,13 @@ const Emitter = struct { e.entry = entry; e.blocks = .empty; e.prologue = .empty; + e.call_memo = .empty; + e.texel_copies = .empty; e.next_id = 0; e.inst_types = .empty; e.private_globals = .empty; e.private_typed = .empty; + e.private_aggs = .empty; e.nonuniform = .empty; e.res_locals = .empty; e.rq_locals = .empty; @@ -692,10 +741,13 @@ const Emitter = struct { // The patch constant function: a function of its own. e.blocks = .empty; e.prologue = .empty; + e.call_memo = .empty; + e.texel_copies = .empty; e.next_id = 0; e.inst_types = .empty; e.private_globals = .empty; e.private_typed = .empty; + e.private_aggs = .empty; e.nonuniform = .empty; e.pc_fn = patch_fn[k]; e.cur = try e.newBlock(); @@ -721,6 +773,7 @@ const Emitter = struct { return x.func < y.func; } }.lt); + try promote.pruneGlobals(e.arena, &e.dm); if (try promote.pruneDeclarations(e.arena, &e.dm)) |index| for (funcs.items) |*lf| { lf.func = index[lf.func]; }; @@ -858,10 +911,13 @@ const Emitter = struct { e.entry = .{ .func = fi, .name = f.name, .stage = .library, .wrapper = std.math.maxInt(u32) }; e.blocks = .empty; e.prologue = .empty; + e.call_memo = .empty; + e.texel_copies = .empty; e.next_id = 0; e.inst_types = .empty; e.private_globals = .empty; e.private_typed = .empty; + e.private_aggs = .empty; e.nonuniform = .empty; e.res_locals = .empty; e.rq_locals = .empty; @@ -956,16 +1012,16 @@ const Emitter = struct { const void_ty = try e.voidTy(); const Sys = struct { []const u8, i64, []const u8, enum { scalar, vector, m34, m43 } }; const table = [_]Sys{ - .{ "DispatchRaysIndex", 145, "dispatchRaysIndex", .vector }, .{ "DispatchRaysDimensions", 146, "dispatchRaysDimensions", .vector }, - .{ "WorldRayOrigin", 147, "worldRayOrigin", .vector }, .{ "WorldRayDirection", 148, "worldRayDirection", .vector }, - .{ "ObjectRayOrigin", 149, "objectRayOrigin", .vector }, .{ "ObjectRayDirection", 150, "objectRayDirection", .vector }, - .{ "RayTMin", 153, "rayTMin", .scalar }, .{ "RayTCurrent", 154, "rayTCurrent", .scalar }, - .{ "InstanceID", 141, "instanceID", .scalar }, .{ "InstanceIndex", 142, "instanceIndex", .scalar }, - .{ "HitKind", 143, "hitKind", .scalar }, .{ "RayFlags", 144, "rayFlags", .scalar }, - .{ "PrimitiveIndex", 161, "primitiveIndex", .scalar }, .{ "GeometryIndex", 213, "geometryIndex", .scalar }, - .{ "ObjectToWorld3x4", 151, "objectToWorld", .m34 }, .{ "ObjectToWorld", 151, "objectToWorld", .m34 }, - .{ "ObjectToWorld4x3", 151, "objectToWorld", .m43 }, .{ "WorldToObject3x4", 152, "worldToObject", .m34 }, - .{ "WorldToObject", 152, "worldToObject", .m34 }, .{ "WorldToObject4x3", 152, "worldToObject", .m43 }, + .{ "DispatchRaysIndex", 145, "dispatchRaysIndex", .vector }, .{ "DispatchRaysDimensions", 146, "dispatchRaysDimensions", .vector }, + .{ "WorldRayOrigin", 147, "worldRayOrigin", .vector }, .{ "WorldRayDirection", 148, "worldRayDirection", .vector }, + .{ "ObjectRayOrigin", 149, "objectRayOrigin", .vector }, .{ "ObjectRayDirection", 150, "objectRayDirection", .vector }, + .{ "RayTMin", 153, "rayTMin", .scalar }, .{ "RayTCurrent", 154, "rayTCurrent", .scalar }, + .{ "InstanceID", 141, "instanceID", .scalar }, .{ "InstanceIndex", 142, "instanceIndex", .scalar }, + .{ "HitKind", 143, "hitKind", .scalar }, .{ "RayFlags", 144, "rayFlags", .scalar }, + .{ "PrimitiveIndex", 161, "primitiveIndex", .scalar }, .{ "GeometryIndex", 213, "geometryIndex", .scalar }, + .{ "ObjectToWorld3x4", 151, "objectToWorld", .m34 }, .{ "ObjectToWorld", 151, "objectToWorld", .m34 }, + .{ "ObjectToWorld4x3", 151, "objectToWorld", .m43 }, .{ "WorldToObject3x4", 152, "worldToObject", .m34 }, + .{ "WorldToObject", 152, "worldToObject", .m34 }, .{ "WorldToObject4x3", 152, "worldToObject", .m43 }, }; for (table) |x| { if (!eq(u8, name, x[0])) continue; @@ -1254,13 +1310,23 @@ const Emitter = struct { 14 => 0, 1...10 => blk: { const n = try e.flatCount(res.elem); - break :blk try e.compType(e.compOf(res.elem)) | (@as(i64, n) << 8); + break :blk try e.compType(typedComp(e.compOf(res.elem))) | (@as(i64, n) << 8); }, else => 0, }; return .{ basic, extra }; } + /// The component type typed resources declare for `c`: 64-bit + /// integers are held as pairs of 32-bit ones. + fn typedComp(c: Scalar) Scalar { + return switch (c) { + .int64 => .int, + .uint64 => .uint, + else => c, + }; + } + /// Structured buffer element stride (packed layout). fn stride(e: *Emitter, ty: TypeId) Error!i64 { return layout.sizeOf(e.t, ty, false, .dx_packed) catch e.unsupported("buffer element type '{s}'", .{try e.t.format(e.arena, ty)}); @@ -1318,7 +1384,28 @@ const Emitter = struct { 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); + if (e.optimize) { + try promote.run(e.arena, &e.dm, func, &ranges); + // Values only ever one constant (through loops too), and the + // branches they decide. + if (try sccp.run(e.arena, &e.dm, func)) try promote.run(e.arena, &e.dm, func, &.empty); + // Loops promotion showed a constant trip count: unrolled, then + // promoted again (their arrays now constant-indexed). + var rounds: u32 = 0; + while (rounds < 4 and try unroll.run(e.arena, &e.dm, func)) : (rounds += 1) { + try promote.run(e.arena, &e.dm, func, &.empty); + } + // Again until it settles: what one run folds (phis it made, + // branches it decided) lets the next remove more. + for (0..3) |_| { + const before = e.dm.functions.items[func].insts.items.len; + _ = try sccp.run(e.arena, &e.dm, func); + // (Loops that do nothing once folding has run: deleted.) + _ = try unroll.run(e.arena, &e.dm, func); + try promote.run(e.arena, &e.dm, func, &.empty); + if (e.dm.functions.items[func].insts.items.len == before) break; + } + } } /// Drops removable prologue instructions nothing uses (repeatedly: a @@ -1437,6 +1524,125 @@ const Emitter = struct { /// 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 { + if (!e.optimize or args.len != 0 or !try e.pureUniform(fi)) return e.inlineCallFresh(fi, args, aliases); + if (e.call_memo.get(fi)) |vals| { + e.last_ret_res = null; + return vals; + } + // First call: inline it with nothing forwarded from the caller, and + // if that came out straight-line, move it into the prologue for + // every later call to reuse. + e.forwarded.clearRetainingCapacity(); + const start = e.cur; + const start_len = e.blocks.items[start].items.len; + const first_new: u32 = @intCast(e.blocks.items.len); + const vals = try e.inlineCallFresh(fi, args, aliases); + if (!e.straightLine(start, start_len, first_new)) return vals; + var b = start; + var from = start_len; + while (b != e.cur) { + const items = e.blocks.items[b].items; + const br = items[items.len - 1]; + try e.prologue.appendSlice(e.arena, items[from .. items.len - 1]); + items[from] = br; + e.blocks.items[b].items.len = from + 1; + b = br.inst.op.br.then; + from = 0; + } + e.forwarded.clearRetainingCapacity(); + try e.call_memo.put(e.arena, fi, vals); + return vals; + } + + /// Whether the code from `start_len` in block `start` runs straight to + /// the (still empty) current block: unconditional branches through + /// blocks from `first_new` on, each visited once, no phis. + fn straightLine(e: *Emitter, start: u32, start_len: usize, first_new: u32) bool { + var b = start; + var from = start_len; + var seen: usize = 0; + while (b != e.cur) { + const items = e.blocks.items[b].items; + if (items.len <= from) return false; + for (items[from .. items.len - 1]) |pi| switch (pi.inst.op) { + .br, .@"switch", .ret, .phi => return false, + else => {}, + }; + const last = items[items.len - 1].inst.op; + if (last != .br or last.br.cond != null or last.br.then < first_new) return false; + b = last.br.then; + from = 0; + seen += 1; + if (seen > e.blocks.items.len) return false; + } + return e.blocks.items[e.cur].items.len == 0 and seen == e.blocks.items.len - first_new; + } + + /// A function with no parameters whose result depends only on constant + /// buffers and constants: no effects but on its own locals, and calls + /// only to such functions. Every call returns the same value. + fn pureUniform(e: *Emitter, fi: u32) Error!bool { + const f = e.m.functions.items[fi]; + if (f.params.len != 0 or f.ret == TypeTable.void_type) return false; + if (isResourceType(e.t, f.ret) or e.holdsResources(f.ret)) return false; + return e.localEffects(fi); + } + + /// A function whose only effects are on its locals and what its + /// parameters point to, reading nothing but those, constant buffers + /// and constants, and calling only such functions. + fn localEffects(e: *Emitter, fi: u32) Error!bool { + if (e.pure_fns.get(fi)) |v| return v; + try e.pure_fns.put(e.arena, fi, false); // (recursion: no) + const v = try e.checkLocalEffects(fi); + try e.pure_fns.put(e.arena, fi, v); + return v; + } + + fn checkLocalEffects(e: *Emitter, fi: u32) Error!bool { + const f = e.m.functions.items[fi]; + for (f.params) |p| if (p.groupshared or isResourceType(e.t, p.ty) or e.holdsResources(p.ty)) return false; + for (f.insts.items) |i| switch (i.op) { + .constant, .param, .local_var, .access, .binary, .unary, .cmp, .convert, .bitcast, .splat, .extract, .insert, .construct, .shuffle, .select, .undef => {}, + .global => |g| { + const gl = e.m.globals.items[g]; + if (gl.space != .cbuffer or gl.tbuffer) return false; + }, + .load => |p| if (!e.readableRoot(f, p)) return false, + .store => |st| if (!writableRoot(f, st.ptr)) return false, + .call => |c| if (!try e.localEffects(c.func)) return false, + .intrinsic => |x| if (!pureIntrinsic(x.name)) return false, + else => return false, + }; + return true; + } + + fn writableRoot(f: *const ir.Function, p: Ref) bool { + var r = p; + while (true) switch (f.inst(r).op) { + .access => |a| r = a.base, + .local_var, .param => return true, + else => return false, + }; + } + + fn readableRoot(e: *Emitter, f: *const ir.Function, p: Ref) bool { + var r = p; + while (true) switch (f.inst(r).op) { + .access => |a| r = a.base, + .local_var, .param => return true, + .global => |g| return e.m.globals.items[g].space == .cbuffer and !e.m.globals.items[g].tbuffer, + else => return false, + }; + } + + fn pureIntrinsic(name: []const u8) bool { + const ok = [_][]const u8{ "mul", "dot", "cross", "normalize", "length", "abs", "min", "max", "clamp", "saturate", "lerp", "sqrt", "rsqrt", "rcp", "floor", "ceil", "frac", "round", "trunc", "sign", "sin", "cos", "tan", "asin", "acos", "atan", "atan2", "exp", "exp2", "log", "log2", "pow", "transpose", "determinant", "asfloat", "asuint", "asint", "f16tof32", "f32tof16", "select", "and", "or", "any", "all", "step", "smoothstep", "fmod", "mad", "distance", "reflect", "countbits", "firstbithigh", "firstbitlow", "reversebits" }; + for (ok) |n| if (std.mem.eql(u8, n, name)) return true; + return false; + } + + fn inlineCallFresh(e: *Emitter, fi: u32, args: []const Lowered, aliases: []const ?Lowered) Error![]const Value { const f = e.m.functions.items[fi]; var frame: Frame = .{ .f = f, @@ -1451,16 +1657,32 @@ const Emitter = struct { }; @memset(frame.vals, .none); @memset(frame.blocks, null); + if (e.optimize and args.len > 0) frame.copies = try e.paramCopies(fi); 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); if (!is_entry) frame.cont = try e.newBlock(); // The callee's entry continues the current block. frame.blocks[0] = e.cur; const reachable = try reachableBlocks(e.arena, f); + // A branch on a constant (an argument, after inlining) goes one + // way only: blocks then no longer reachable are dead and skipped. + // (dxc's optimizer removes such code, and code it removes may be + // invalid, such as one variable assigned different resources.) + frame.live = reachable; + frame.taken = try e.arena.alloc(u32, f.blocks.items.len); + @memset(frame.taken, std.math.maxInt(u32)); + const emitted = try e.arena.alloc(bool, f.blocks.items.len); + @memset(emitted, false); for (f.blocks.items, 0..) |_, bi| { - if (!reachable[bi]) continue; + if (!frame.live[bi]) continue; e.cur = try e.blockFor(&frame, @intCast(bi)); try e.emitBlock(&frame, @intCast(bi)); + emitted[bi] = true; } + // (Targets of branches emitted before a fold showed them dead.) + for (frame.blocks, emitted) |b, done| if (b != null and !done) { + e.cur = b.?; + _ = try e.add(try e.voidTy(), .@"unreachable"); + }; 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). @@ -1675,6 +1897,13 @@ const Emitter = struct { .br => |t| _ = try e.add(void_ty, .{ .br = .{ .then = try e.blockFor(frame, t.index()) } }), .cond_br => |c| { const cond = (try e.scalars(frame, c.cond))[0]; + if (frame.taken.len > 0) if (e.constIntOf(cond)) |k| { + const taken = if (k != 0) c.then else c.@"else"; + frame.taken[bi] = taken.index(); + frame.live = try reachableBlocksTaken(e.arena, f, frame.taken); + _ = try e.add(void_ty, .{ .br = .{ .then = try e.blockFor(frame, taken.index()) } }); + return; + }; const then_b = try e.blockFor(frame, c.then.index()); const else_b = try e.blockFor(frame, c.@"else".index()); _ = try e.add(void_ty, .{ .br = .{ .then = then_b, .@"else" = else_b, .cond = cond } }); @@ -1692,7 +1921,17 @@ const Emitter = struct { const i1t = try e.dm.intType(1); const fn_i = try e.dxOp("dx.op.discard", void_ty, &.{ i32t, i1t }, .nounwind); _ = try e.callOp(fn_i, void_ty, &.{ try e.i32Const(82), try e.dm.constInt(1, 1) }); - _ = try e.add(void_ty, .{ .ret = null }); + // DXIL's discard does not end the invocation: the entry + // still writes its outputs (the validator wants them all), + // so an inlined function returns from here, its value + // undefined. + if (frame.cont) |cont| { + const rty = frame.f.ret; + if (rty != TypeTable.void_type and !e.holdsResources(rty) and !isResourceType(e.t, rty) and try e.flatCount(rty) > 0) { + try frame.rets.append(e.arena, .{ .block = e.cur, .vals = try e.undefValues(rty) }); + } + _ = try e.add(void_ty, .{ .br = .{ .then = cont } }); + } else _ = try e.add(void_ty, .{ .ret = null }); }, } } @@ -1700,7 +1939,14 @@ const Emitter = struct { fn scalars(e: *Emitter, frame: *Frame, r: Ref) Error![]const Value { return switch (frame.vals[r.index()]) { .scalars => |s| s, - else => e.unsupported("internal: expected a value", .{}), + else => |v| { + // An empty struct's value: no components. + const ty = frame.f.inst(r).ty; + if (v == .none and ty != TypeTable.void_type and e.t.get(ty) == .@"struct" and try e.flatCount(ty) == 0 and !e.holdsResources(ty)) return &.{}; + const op = frame.f.inst(r).op; + const what = if (op == .call) e.m.functions.items[op.call.func].name else @tagName(op); + return e.unsupported("internal: expected a value from '{s}' in '{s}' (found {s})", .{ what, frame.f.name, @tagName(v) }); + }, }; } @@ -1712,7 +1958,7 @@ const Emitter = struct { return .{ .base = undefined, .array_ty = try e.dm.getType(.{ .array = .{ .len = n, .elem = st } }), .scalar_ty = st, .mixed = true }; } const c = try e.uniformScalar(ty); - if (c.size() != 4) return e.unsupported("groupshared values of type '{s}' are not supported yet", .{try e.t.format(e.arena, ty)}); + if (c.size() != 4 and c.size() != 2) return e.unsupported("groupshared values of type '{s}' are not supported yet", .{try e.t.format(e.arena, ty)}); const st = try e.scalarTy(if (c == .bool) Scalar.int else c); return .{ .base = undefined, .array_ty = try e.dm.getType(.{ .array = .{ .len = n, .elem = st } }), .scalar_ty = st, .bool_storage = c == .bool }; } @@ -1791,6 +2037,11 @@ const Emitter = struct { // inlined into it). if (e.m.globals.items[g].space == .private) { const gty = e.m.globals.items[g].ty; + if (e.holdsResources(gty)) { + const ag = try e.private_aggs.getOrPut(e.arena, g); + if (!ag.found_existing) ag.value_ptr.* = try e.aggLocal(gty); + return ag.value_ptr.*; + } if (try e.mixedSizes(gty) or e.containsLinAlg(gty)) { const tg = try e.private_typed.getOrPut(e.arena, g); if (!tg.found_existing) { @@ -1813,7 +2064,8 @@ const Emitter = struct { p.base = gv; p.addr_space = 3; gop.value_ptr.* = p; - e.groupshared_bytes += @intCast(e.dm.types.items[p.array_ty].array.len * 4); + const elem_bytes: u64 = if (p.mixed or p.bool_storage) 4 else (try e.uniformScalar(e.m.globals.items[g].ty)).size(); + e.groupshared_bytes += @intCast(e.dm.types.items[p.array_ty].array.len * elem_bytes); } return .{ .ptr = gop.value_ptr.* }; } @@ -1863,7 +2115,11 @@ const Emitter = struct { } return .{ .ptr = try e.alloca(i.ty) }; }, - .load => |p| switch (frame.vals[p.index()]) { + .load => |p| if (frame.copies.len > 0 and frame.copies[p.index()] != std.math.maxInt(u32) and frame.params[frame.copies[p.index()]] == .scalars and e.t.isNumeric(i.ty)) { + // (A parameter's copy, never written: the argument, so + // constants passed in stay constants.) + return frame.params[frame.copies[p.index()]]; + } else switch (frame.vals[p.index()]) { .handle => |h| return .{ .handle = h }, .agg_ptr => |ap| { const vals: []const Value = if (ap.data) |d| switch (d.*) { @@ -1872,11 +2128,13 @@ const Emitter = struct { else => unreachable, } else &.{}; const res = try e.arena.alloc(Lowered, ap.slots.len); - for (res, ap.slots) |*o, sl| o.* = e.res_locals.items[sl] orelse return e.unsupported("a resource in a local read before it is assigned", .{}); + // (A field never assigned stays unset through copies; + // only using it is an error.) + for (res, ap.slots) |*o, sl| o.* = e.res_locals.items[sl] orelse .none; return .{ .agg = .{ .vals = vals, .res = res } }; }, .rq_local => |k| return .{ .ray_query = try e.rqHandle(k) }, - .res_local => |k| return e.res_locals.items[k] orelse return e.unsupported("a resource local read before it is assigned", .{}), + .res_local => |k| return e.res_locals.items[k] orelse return e.unsetResource(i.ty), .res_index_local => |k| { const il = e.res_index_locals.items[k]; const idx = (try e.loadPtr(il.ptr, try e.t.scalar(.uint))).scalars[0]; @@ -1927,7 +2185,7 @@ const Emitter = struct { }, .typed => |tp| return e.typedLoad(tp, i.ty), .mesh => return e.unsupported("reading mesh shader outputs is not supported", .{}), - else => return e.unsupported("internal: load from a non-pointer", .{}), + else => |v| return e.unsupported("internal: load from a non-pointer ({s} from %{d} '{s}' in '{s}')", .{ @tagName(v), p.index(), @tagName(frame.f.inst(p).op), frame.f.name }), }, .store => |s| { if (frame.param_copies.len > 0) if (f.inst(s.value).op == .param) { @@ -1956,7 +2214,7 @@ const Emitter = struct { if (h != .handle and h != .res_array) return e.unsupported("resources not tied to a global are not supported yet", .{}); // Selecting between resources at run time has no // handle-based lowering here; one assignment is fine. - if (slot.*) |old| if (!std.meta.eql(old, h)) return e.unsupported("assigning different resources to one variable is not supported yet", .{}); + if (slot.*) |old| if (!std.meta.eql(old, h)) return e.unsupported("assigning different resources to one variable is not supported yet (in '{s}')", .{frame.f.name}); slot.* = h; return .none; } @@ -2035,7 +2293,18 @@ const Emitter = struct { if (frame.vals[a.base.index()] == .buf) return e.bufferAccess(frame, frame.vals[a.base.index()].buf, f.inst(a.base).ty, a.indices); var ptr = switch (frame.vals[a.base.index()]) { .ptr => |p| p, - else => return e.unsupported("access into this storage is not supported yet", .{}), + // A component of a texel (`T[p][i]`): of a copy of it. + .texel => |tx| blk: { + const res = e.resources.items[tx.res]; + const ety = f.inst(a.base).ty; + const mip = if (res.class == .uav) try e.dm.constant(.{ .ty = try e.dm.intType(32), .kind = .undef }) else try e.i32Const(0); + const vals = if (res.kind == 10) try e.typedBufferLoad(res, tx.coords[0], ety) else try e.textureLoad(res, mip, tx.coords, null, ety); + const copy = try e.alloca(ety); + try e.storePtr(copy, vals, ety); + try e.texel_copies.put(e.arena, copy.base, {}); + break :blk copy; + }, + else => |v| return e.unsupported("access into this storage is not supported yet ({s} from '{s}' in '{s}')", .{ @tagName(v), @tagName(f.inst(a.base).op), frame.f.name }), }; var cur = f.inst(a.base).ty; for (a.indices) |x| { @@ -2201,6 +2470,8 @@ const Emitter = struct { return rr[0]; } if (e.holdsResources(i.ty)) return .{ .agg = .{ .vals = res, .res = e.last_ret_res orelse return e.unsupported("a function returning resources with no return value", .{}) } }; + // (A function that never returns its value: undefined.) + if (res.len == 0 and i.ty != TypeTable.void_type and try e.flatCount(i.ty) > 0) return .{ .scalars = try e.undefValues(i.ty) }; return if (res.len == 0) .none else .{ .scalars = res }; }, .intrinsic => |c| return e.intrinsic(frame, c.name, i.ty, c.args), @@ -2229,7 +2500,7 @@ const Emitter = struct { }, .output_vertex => |x| return e.outputControlPoint(x.element, i.ty, x.vertex), .phi => return e.unsupported("phi", .{}), - .undef => return e.unsupported("undef", .{}), + .undef => return .{ .scalars = try e.undefValues(i.ty) }, } } @@ -2293,6 +2564,19 @@ const Emitter = struct { }; } + /// A resource read from a local never assigned one. dxc accepts that + /// only in code its optimizer removes (any other use is an error), so + /// it is an undefined handle, outside the metadata. + fn unsetResource(e: *Emitter, ty: TypeId) Error!Lowered { + if (e.t.get(ty) != .resource and e.t.get(ty) != .sampler) return e.unsupported("a resource local read before it is assigned", .{}); + var res = try e.resourceFor(ty); + res.global = std.math.maxInt(u32); + res.view = true; + res.handle = try e.dm.constant(.{ .ty = e.handle_ty, .kind = .undef }); + try e.resources.append(e.arena, res); + return .{ .handle = @intCast(e.resources.items.len - 1) }; + } + fn aggLocal(e: *Emitter, ty: TypeId) Error!Lowered { const slots = try e.arena.alloc(u32, e.resCount(ty)); for (slots) |*sl| { @@ -2389,8 +2673,9 @@ const Emitter = struct { }; if (parts.res.len != ap.slots.len) return e.unsupported("this assignment of resources is not supported yet", .{}); for (ap.slots, parts.res) |sl, r| { + if (r == .none) continue; const slot = &e.res_locals.items[sl]; - if (slot.*) |old| if (!std.meta.eql(old, r)) return e.unsupported("assigning different resources to one variable is not supported yet", .{}); + if (slot.*) |old| if (!std.meta.eql(old, r)) return e.unsupported("assigning different resources to one variable is not supported yet (a struct)", .{}); slot.* = r; } } @@ -2403,7 +2688,7 @@ const Emitter = struct { }; const dr = try e.componentRange(ty, index); const rr = try e.resRange(ty, index); - if (isResourceType(e.t, field)) return a.res[rr[0]]; + if (isResourceType(e.t, field)) return if (a.res[rr[0]] == .none) e.unsetResource(field) else a.res[rr[0]]; if (e.holdsResources(field)) return .{ .agg = .{ .vals = a.vals[dr[0]..dr[1]], .res = a.res[rr[0]..rr[1]] } }; return e.list(a.vals[dr[0]..dr[1]]); } @@ -2497,7 +2782,7 @@ const Emitter = struct { continue; }; const p = try e.elementPtr(ptr, @intCast(c)); - const raw = try e.add(ptr.scalar_ty, .{ .load = .{ .ptr = p, .@"align" = 4 } }); + const raw = try e.add(ptr.scalar_ty, .{ .load = .{ .ptr = p, .@"align" = e.flatAlign(ptr) } }); const ct = e.compOf(try e.componentType(ty, @intCast(c))); o.* = if (ptr.bool_storage or (ptr.mixed and ct == .bool)) try e.add(try e.dm.intType(1), .{ .cmp = .{ .pred = 33, .lhs = raw, .rhs = try e.i32Const(0) } }) @@ -2510,6 +2795,7 @@ const Emitter = struct { } fn storePtr(e: *Emitter, ptr: Ptr, vals: []const Value, ty: TypeId) Error!void { + if (e.texel_copies.contains(ptr.base)) return e.unsupported("writing one component of a texel through an index is not supported yet", .{}); const void_ty = try e.voidTy(); for (vals, 0..) |v, c| { if (ptr.offset_dyn == null) { @@ -2527,10 +2813,19 @@ const Emitter = struct { try e.add(ptr.scalar_ty, .{ .cast = .{ .op = .bitcast, .val = v } }) else v; - _ = try e.add(void_ty, .{ .store = .{ .ptr = p, .val = sv, .@"align" = 4 } }); + _ = try e.add(void_ty, .{ .store = .{ .ptr = p, .val = sv, .@"align" = e.flatAlign(ptr) } }); } } + /// Alignment of a flattened storage element (16-bit ones: 2). + fn flatAlign(e: *Emitter, ptr: Ptr) u32 { + return switch (e.dm.types.items[ptr.scalar_ty]) { + .half => 2, + .int => |bits| if (bits == 16) 2 else 4, + else => 4, + }; + } + fn elementPtr(e: *Emitter, ptr: Ptr, c: u32) Error!Value { 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 } }); @@ -2686,9 +2981,9 @@ const Emitter = struct { } return .{ .scalars = out }; } - if (eq(u8, name, "exp") or eq(u8, name, "log")) { + if (eq(u8, name, "exp") or eq(u8, name, "log") or eq(u8, name, "log10")) { // DXIL's Exp / Log are base 2. - const k2 = try e.constant(try e.t.scalar(ac), .{ .float = if (eq(u8, name, "exp")) 1.4426950408889634 else 0.6931471805599453 }); + const k2 = try e.constant(try e.t.scalar(ac), .{ .float = if (eq(u8, name, "exp")) 1.4426950408889634 else if (eq(u8, name, "log")) 0.6931471805599453 else 0.30102999566398120 }); for (out, 0..) |*o, k| { if (eq(u8, name, "exp")) { const s = try e.add(at, .{ .binop = .{ .op = .mul, .lhs = a[0][k], .rhs = k2 } }); @@ -2785,7 +3080,7 @@ const Emitter = struct { for (out, 0..) |*o, k| o.* = try e.add(at, .{ .binop = .{ .op = .sdiv, .lhs = try e.constant(try e.t.scalar(ac), .{ .float = 1 }), .rhs = a[0][k] } }); return .{ .scalars = out }; } - if (eq(u8, name, "asuint") or eq(u8, name, "asint") or eq(u8, name, "asfloat")) { + if (eq(u8, name, "asuint") or eq(u8, name, "asint") or eq(u8, name, "asfloat") or eq(u8, name, "asuint16") or eq(u8, name, "asint16") or eq(u8, name, "asfloat16")) { if (args.len != 1) return e.unsupported("intrinsic '{s}' with {d} arguments", .{ name, args.len }); for (out, 0..) |*o, k| o.* = if (at == rt) a[0][k] else try e.add(rt, .{ .cast = .{ .op = .bitcast, .val = a[0][k] } }); return .{ .scalars = out }; @@ -2874,8 +3169,8 @@ const Emitter = struct { return .{ .scalars = out }; } const barriers = [_]struct { []const u8, i64 }{ - .{ "GroupMemoryBarrierWithGroupSync", 9 }, .{ "GroupMemoryBarrier", 8 }, - .{ "AllMemoryBarrierWithGroupSync", 11 }, .{ "AllMemoryBarrier", 10 }, + .{ "GroupMemoryBarrierWithGroupSync", 9 }, .{ "GroupMemoryBarrier", 8 }, + .{ "AllMemoryBarrierWithGroupSync", 11 }, .{ "AllMemoryBarrier", 10 }, .{ "DeviceMemoryBarrierWithGroupSync", 3 }, .{ "DeviceMemoryBarrier", 2 }, }; const barrier: ?i64 = for (barriers) |b| { @@ -2899,7 +3194,7 @@ const Emitter = struct { } const Deriv = struct { name: []const u8, op: i64 }; const derivs = [_]Deriv{ - .{ .name = "ddx", .op = 83 }, .{ .name = "ddx_coarse", .op = 83 }, .{ .name = "ddy", .op = 84 }, + .{ .name = "ddx", .op = 83 }, .{ .name = "ddx_coarse", .op = 83 }, .{ .name = "ddy", .op = 84 }, .{ .name = "ddy_coarse", .op = 84 }, .{ .name = "ddx_fine", .op = 85 }, .{ .name = "ddy_fine", .op = 86 }, }; const is_deriv = eq(u8, name, "fwidth") or for (derivs) |d| { @@ -3021,7 +3316,8 @@ const Emitter = struct { const op_name = name["Interlocked".len..]; const dest_ty = frame.f.inst(args[0]).ty; const dc = e.compOf(dest_ty); - if (dc.size() != 4 or dc.isFloat()) return e.unsupported("'{s}' on '{s}' is not supported yet", .{ name, try e.t.format(e.arena, dest_ty) }); + const wide = dc.size() == 8 and !dc.isFloat() and (frame.vals[args[0].index()] == .buf or frame.vals[args[0].index()] == .texel); + if ((dc.size() != 4 and !wide) or dc.isFloat()) return e.unsupported("'{s}' on '{s}' is not supported yet", .{ name, try e.t.format(e.arena, dest_ty) }); const i32t = try e.dm.intType(32); const is_cmp = std.mem.startsWith(u8, op_name, "Compare"); const has_orig = (is_cmp and eq(u8, op_name, "CompareExchange")) or (!is_cmp and args.len == 3); @@ -3040,12 +3336,19 @@ const Emitter = struct { break :blk try e.add(i32t, .{ .atomicrmw = .{ .op = rmw, .ptr = ptr, .val = val } }); }, .buf => |b| blk: { + if (wide) e.resources.items[b.res].atomic64 = true; const res = e.resources.items[b.res]; var off = try e.i32Const(b.offset); if (b.dyn) |d| off = try e.add(i32t, .{ .binop = .{ .op = .add, .lhs = d, .rhs = off } }); break :blk try e.resourceAtomic(res, &.{ b.index, off }, op_name, dc, val, cmp); }, - .texel => |tx| try e.resourceAtomic(e.resources.items[tx.res], tx.coords, op_name, dc, val, cmp), + .texel => |tx| blk: { + if (wide) { + e.resources.items[tx.res].atomic64 = true; + e.uses_atomic64_typed = true; + } + break :blk try e.resourceAtomic(e.resources.items[tx.res], tx.coords, op_name, dc, val, cmp); + }, else => return e.unsupported("'{s}' on this destination is not supported yet", .{name}), }; if (has_orig) try e.storePtr(try e.outPtr(frame, args[args.len - 1]), &.{orig}, frame.f.inst(args[args.len - 1]).ty); @@ -3058,13 +3361,16 @@ const Emitter = struct { const eq = std.mem.eql; const i32t = try e.dm.intType(32); const c = try e.padded(coords, coords.len, 3, i32t); + // (64-bit integers: the i64 overloads.) + const vt = if (dc.size() == 8) try e.dm.intType(64) else i32t; + const ov = if (dc.size() == 8) "i64" else "i32"; if (cmp) |cv| { - const fn_i = try e.dxOp("dx.op.atomicCompareExchange.i32", i32t, &.{ i32t, e.handle_ty, i32t, i32t, i32t, i32t, i32t }, .nounwind); - return e.callOp(fn_i, i32t, &.{ try e.i32Const(79), res.handle, c[0], c[1], c[2], cv, val }); + const fn_i = try e.dxOp(try std.fmt.allocPrint(e.arena, "dx.op.atomicCompareExchange.{s}", .{ov}), vt, &.{ i32t, e.handle_ty, i32t, i32t, i32t, vt, vt }, .nounwind); + return e.callOp(fn_i, vt, &.{ try e.i32Const(79), res.handle, c[0], c[1], c[2], cv, val }); } const op: i64 = if (eq(u8, op_name, "Add")) 0 else if (eq(u8, op_name, "And")) 1 else if (eq(u8, op_name, "Or")) 2 else if (eq(u8, op_name, "Xor")) 3 else if (eq(u8, op_name, "Min")) (if (dc.isUnsigned()) 6 else 4) else if (eq(u8, op_name, "Max")) (if (dc.isUnsigned()) 7 else 5) else if (eq(u8, op_name, "Exchange")) 8 else return e.unsupported("'Interlocked{s}' is not supported yet", .{op_name}); - const fn_i = try e.dxOp("dx.op.atomicBinOp.i32", i32t, &.{ i32t, e.handle_ty, i32t, i32t, i32t, i32t, i32t }, .nounwind); - return e.callOp(fn_i, i32t, &.{ try e.i32Const(78), res.handle, try e.i32Const(op), c[0], c[1], c[2], val }); + const fn_i = try e.dxOp(try std.fmt.allocPrint(e.arena, "dx.op.atomicBinOp.{s}", .{ov}), vt, &.{ i32t, e.handle_ty, i32t, i32t, i32t, i32t, vt }, .nounwind); + return e.callOp(fn_i, vt, &.{ try e.i32Const(78), res.handle, try e.i32Const(op), c[0], c[1], c[2], val }); } /// Wave and quad intrinsics (component-wise on vectors). @@ -3650,6 +3956,10 @@ const Emitter = struct { return switch (c) { .bool => .uint, .float, .int, .uint => c, + // Native 16-bit (-enable-16bit-types). + .float16, .int16, .uint16 => c, + // (Pairs of components; see resRetComponents.) + .int64, .uint64 => .uint, else => e.unsupported("textures of '{s}' are not supported yet", .{try e.t.format(e.arena, elem)}), }; } @@ -3658,6 +3968,22 @@ const Emitter = struct { fn resRetComponents(e: *Emitter, call: Value, st: DType, via: Scalar, ty: TypeId) Error![]const Value { const n = try e.flatCount(ty); const out = try e.arena.alloc(Value, n); + const c = e.compOf(ty); + if (c.size() == 8 and via.size() == 4) { + // 64-bit integers: lo | hi << 32 from component pairs. + const i64t = try e.dm.intType(64); + const sh = try e.dm.constant(.{ .ty = i64t, .kind = .{ .int = 32 } }); + for (out, 0..) |*o, k| { + const lo = try e.add(st, .{ .extractvalue = .{ .agg = call, .index = @intCast(2 * k) } }); + const hi = try e.add(st, .{ .extractvalue = .{ .agg = call, .index = @intCast(2 * k + 1) } }); + const l64 = try e.add(i64t, .{ .cast = .{ .op = .zext, .val = lo } }); + const h64 = try e.add(i64t, .{ .cast = .{ .op = .zext, .val = hi } }); + const hs = try e.add(i64t, .{ .binop = .{ .op = .shl, .lhs = h64, .rhs = sh } }); + o.* = try e.add(i64t, .{ .binop = .{ .op = .@"or", .lhs = hs, .rhs = l64 } }); + } + e.uses_int64 = true; + return out; + } for (out, 0..) |*o, k| { const v = try e.add(st, .{ .extractvalue = .{ .agg = call, .index = @intCast(k) } }); o.* = try e.convertScalar(v, via, e.compOf(ty)); @@ -3718,7 +4044,16 @@ const Emitter = struct { const from = e.compOf(vty); // Typed stores write all four components (replicated, as dxc). var v: [4]Value = undefined; - for (&v, 0..) |*x, k| x.* = try e.convertScalar(vals[if (k < vals.len) k else 0], from, via); + if (e.compOf(res.elem).size() == 8 and from.size() == 8) { + // 64-bit integers: lo / hi in component pairs. + const i64t = try e.dm.intType(64); + const sh = try e.dm.constant(.{ .ty = i64t, .kind = .{ .int = 32 } }); + for (0..2) |k| { + const x = vals[if (k < vals.len) k else 0]; + v[2 * k] = try e.add(i32t, .{ .cast = .{ .op = .trunc, .val = x } }); + v[2 * k + 1] = try e.add(i32t, .{ .cast = .{ .op = .trunc, .val = try e.add(i64t, .{ .binop = .{ .op = .lshr, .lhs = x, .rhs = sh } }) } }); + } + } else for (&v, 0..) |*x, k| x.* = try e.convertScalar(vals[if (k < vals.len) k else 0], from, via); const c = try e.padded(coords, coords.len, 3, i32t); const mask = try e.dm.constant(.{ .ty = i8t, .kind = .{ .int = 15 } }); _ = try e.callOp(fn_i, void_ty, &.{ try e.i32Const(67), res.handle, c[0], c[1], c[2], v[0], v[1], v[2], v[3], mask }); @@ -4011,18 +4346,18 @@ const Emitter = struct { } const State = struct { []const u8, i64 }; const table = [_]State{ - .{ "CommittedStatus", 184 }, .{ "CandidateType", 185 }, .{ "CandidateObjectToWorld3x4", 186 }, - .{ "CandidateWorldToObject3x4", 187 }, .{ "CommittedObjectToWorld3x4", 188 }, .{ "CommittedWorldToObject3x4", 189 }, - .{ "CandidateProceduralPrimitiveNonOpaque", 190 }, .{ "CandidateTriangleFrontFace", 191 }, .{ "CommittedTriangleFrontFace", 192 }, - .{ "CandidateTriangleBarycentrics", 193 }, .{ "CommittedTriangleBarycentrics", 194 }, .{ "RayFlags", 195 }, - .{ "WorldRayOrigin", 196 }, .{ "WorldRayDirection", 197 }, .{ "RayTMin", 198 }, - .{ "CandidateTriangleRayT", 199 }, .{ "CommittedRayT", 200 }, .{ "CandidateInstanceIndex", 201 }, - .{ "CandidateInstanceID", 202 }, .{ "CandidateGeometryIndex", 203 }, .{ "CandidatePrimitiveIndex", 204 }, - .{ "CandidateObjectRayOrigin", 205 }, .{ "CandidateObjectRayDirection", 206 }, .{ "CommittedInstanceIndex", 207 }, - .{ "CommittedInstanceID", 208 }, .{ "CommittedGeometryIndex", 209 }, .{ "CommittedPrimitiveIndex", 210 }, - .{ "CommittedObjectRayOrigin", 211 }, .{ "CommittedObjectRayDirection", 212 }, .{ "CandidateInstanceContributionToHitGroupIndex", 214 }, - .{ "CommittedInstanceContributionToHitGroupIndex", 215 }, .{ "CandidateObjectToWorld4x3", 186 }, .{ "CandidateWorldToObject4x3", 187 }, - .{ "CommittedObjectToWorld4x3", 188 }, .{ "CommittedWorldToObject4x3", 189 }, + .{ "CommittedStatus", 184 }, .{ "CandidateType", 185 }, .{ "CandidateObjectToWorld3x4", 186 }, + .{ "CandidateWorldToObject3x4", 187 }, .{ "CommittedObjectToWorld3x4", 188 }, .{ "CommittedWorldToObject3x4", 189 }, + .{ "CandidateProceduralPrimitiveNonOpaque", 190 }, .{ "CandidateTriangleFrontFace", 191 }, .{ "CommittedTriangleFrontFace", 192 }, + .{ "CandidateTriangleBarycentrics", 193 }, .{ "CommittedTriangleBarycentrics", 194 }, .{ "RayFlags", 195 }, + .{ "WorldRayOrigin", 196 }, .{ "WorldRayDirection", 197 }, .{ "RayTMin", 198 }, + .{ "CandidateTriangleRayT", 199 }, .{ "CommittedRayT", 200 }, .{ "CandidateInstanceIndex", 201 }, + .{ "CandidateInstanceID", 202 }, .{ "CandidateGeometryIndex", 203 }, .{ "CandidatePrimitiveIndex", 204 }, + .{ "CandidateObjectRayOrigin", 205 }, .{ "CandidateObjectRayDirection", 206 }, .{ "CommittedInstanceIndex", 207 }, + .{ "CommittedInstanceID", 208 }, .{ "CommittedGeometryIndex", 209 }, .{ "CommittedPrimitiveIndex", 210 }, + .{ "CommittedObjectRayOrigin", 211 }, .{ "CommittedObjectRayDirection", 212 }, .{ "CandidateInstanceContributionToHitGroupIndex", 214 }, + .{ "CommittedInstanceContributionToHitGroupIndex", 215 }, .{ "CandidateObjectToWorld4x3", 186 }, .{ "CandidateWorldToObject4x3", 187 }, + .{ "CommittedObjectToWorld4x3", 188 }, .{ "CommittedWorldToObject4x3", 189 }, }; const op = for (table) |x| { if (eq(u8, name, x[0])) break x[1]; @@ -5277,10 +5612,42 @@ const Emitter = struct { // ------------------------------------------------------------------ // Module metadata and container + /// Whether wave operations and 64-bit integers are still in the code + /// once dead code is gone (the validator wants flags to match). + fn liveUses(e: *Emitter) struct { wave: bool, int64: bool, typed_uav_load: bool } { + var wave = false; + var int64 = false; + var typed_uav_load = false; + for (e.dm.functions.items) |f| for (f.insts.items) |inst| { + if (e.dm.types.items[inst.ty] == .int and e.dm.types.items[inst.ty].int == 64) int64 = true; + switch (inst.op) { + .call => |c| { + const name = e.dm.functions.items[c.callee].name; + if (std.mem.startsWith(u8, name, "dx.op.wave") or std.mem.startsWith(u8, name, "dx.op.quad")) wave = true; + if (std.mem.startsWith(u8, name, "dx.op.textureLoad.") or std.mem.startsWith(u8, name, "dx.op.bufferLoad.")) { + if (e.handleResource(&f, c.args[1])) |ri| { + const r = e.resources.items[ri]; + if (r.class == .uav and r.kind != 11 and r.kind != 12 and (e.flatCount(r.elem) catch 1) > 1) typed_uav_load = true; + } else typed_uav_load = true; + } + for (c.args) |arg| if (arg == .inst and e.dm.types.items[f.insts.items[arg.inst].ty] == .int and e.dm.types.items[f.insts.items[arg.inst].ty].int == 64) { + int64 = true; + }; + }, + .store => |x| if (x.val == .inst and e.dm.types.items[f.insts.items[x.val.inst].ty] == .int and e.dm.types.items[f.insts.items[x.val.inst].ty].int == 64) { + int64 = true; + }, + else => {}, + } + }; + return .{ .wave = wave, .int64 = int64, .typed_uav_load = typed_uav_load }; + } + fn shaderFlags(e: *Emitter) u64 { var flags: u64 = 0; + const live = e.liveUses(); if (e.uses_double) flags |= 1 << 2; - if (e.uses_int64) flags |= 1 << 20; + if (e.uses_int64 and live.int64) flags |= 1 << 20; if (e.uses_min_precision) flags |= 1 << 5; var uavs: u32 = 0; var rov = false; @@ -5292,7 +5659,7 @@ const Emitter = struct { } if (uavs > 8) flags |= 1 << 15; if (rov) flags |= 1 << 18; - if (e.uses_typed_uav_load) flags |= 1 << 13; + if (e.uses_typed_uav_load and live.typed_uav_load) flags |= 1 << 13; // Resources may not alias (DXIL 1.7+, when UAVs are used). if (uavs > 0 and e.profile.minor >= 7) flags |= 1 << 33; const stage = e.entry.stage; @@ -5314,8 +5681,9 @@ const Emitter = struct { if (e.uses_tiled_resources) flags |= 1 << 12; if (e.uses_mesh_derivatives) flags |= 1 << 29; if (e.uses_extended_command_info) flags |= 1 << 38; + if (e.uses_atomic64_typed) flags |= 1 << 27; if (e.uses_sampler_heap) flags |= 1 << 31; - if (e.uses_wave) flags |= 1 << 19; + if (e.uses_wave and live.wave) flags |= 1 << 19; if (e.uses_inner_coverage) flags |= 1 << 10; if (e.uses_ray_query) flags |= 1 << 25; if (e.uses_linalg) flags |= 1 << 41; @@ -5403,11 +5771,14 @@ const Emitter = struct { if (r.class == .uav) { try fields.appendSlice(e.arena, &.{ try mdBool(dm, i1t, r.coherent), try mdBool(dm, i1t, r.has_counter), try mdBool(dm, i1t, r.rov) }); } else try fields.append(e.arena, try mdI32(dm, 0)); // sample count - const extra: ?module.MdId = switch (r.kind) { - 12 => try dm.mdNode(&.{ try mdI32(dm, 1), try mdI32(dm, try e.stride(r.elem)) }), - 1...10 => try dm.mdNode(&.{ try mdI32(dm, 0), try mdI32(dm, try e.compType(e.compOf(r.elem))) }), - else => null, - }; + var tags: std.ArrayList(?module.MdId) = .empty; + switch (r.kind) { + 12 => try tags.appendSlice(e.arena, &.{ try mdI32(dm, 1), try mdI32(dm, try e.stride(r.elem)) }), + 1...10 => try tags.appendSlice(e.arena, &.{ try mdI32(dm, 0), try mdI32(dm, try e.compType(typedComp(e.compOf(r.elem)))) }), + else => {}, + } + if (r.atomic64) try tags.appendSlice(e.arena, &.{ try mdI32(dm, 3), try mdI32(dm, 1) }); + const extra: ?module.MdId = if (tags.items.len > 0) try dm.mdNode(tags.items) else null; try fields.append(e.arena, extra); try lists[@backingInt(r.class)].append(e.arena, try dm.mdNode(fields.items)); } @@ -5579,6 +5950,71 @@ const Emitter = struct { /// The resource (index into `resources`) a handle in `f` stands for, /// when the handle's creation says. + /// Leaves out of the metadata, PSV and reflection the resources no code + /// makes a handle for any more (as dxc's optimizer removes them), with + /// the others numbered again in each class. (Shader model 6.6 handles + /// name their bindings, not these numbers.) + fn dropDeadResources(e: *Emitter) Error!void { + // Hidden counters: only of buffers whose counter code is left. + // (Handles were annotated before dead code went: again.) + var counted = try e.arena.alloc(bool, e.resources.items.len); + @memset(counted, false); + for (e.dm.functions.items) |*f| for (f.insts.items) |inst| { + const c = switch (inst.op) { + .call => |c| c, + else => continue, + }; + if (!std.mem.eql(u8, e.dm.functions.items[c.callee].name, "dx.op.bufferUpdateCounter")) continue; + if (e.handleResource(f, c.args[1])) |ri| counted[ri] = true; + }; + for (e.resources.items, counted) |*r, c| { + if (r.has_counter and !c and r.kind == 12 and r.class == .uav) r.has_counter = false; + } + for (e.dm.functions.items) |*f| for (f.insts.items, 0..) |*inst, i| { + const c = switch (inst.op) { + .call => |*c| c, + else => continue, + }; + if (!std.mem.eql(u8, e.dm.functions.items[c.callee].name, "dx.op.annotateHandle")) continue; + const ri = e.handleResource(f, .{ .inst = @intCast(i) }) orelse continue; + if (e.resources.items[ri].view) continue; + const args = try e.arena.dupe(Value, c.args); + args[2] = try e.propertiesConst(e.resources.items[ri]); + c.args = args; + }; + counted = &.{}; + const alive = try e.liveResources(); + var counts: [4]u32 = .{ 0, 0, 0, 0 }; + var k: usize = 0; + for (e.resources.items, alive) |r, live| { + if (!live and !r.view) continue; + var x = r; + if (!r.view) { + x.id = counts[@backingInt(r.class)]; + counts[@backingInt(r.class)] += 1; + } + e.resources.items[k] = x; + k += 1; + } + e.resources.shrinkRetainingCapacity(k); + } + + /// The resources a handle is still made for once dead code is gone + /// (dxc reflects only those). + fn liveResources(e: *Emitter) Error![]bool { + const alive = try e.arena.alloc(bool, e.resources.items.len); + @memset(alive, false); + for (e.dm.functions.items) |*f| for (f.insts.items, 0..) |inst, i| { + const c = switch (inst.op) { + .call => |c| c, + else => continue, + }; + if (!std.mem.startsWith(u8, e.dm.functions.items[c.callee].name, "dx.op.createHandle")) continue; + if (e.handleResource(f, .{ .inst = @intCast(i) })) |ri| alive[ri] = true; + }; + return alive; + } + fn handleResource(e: *Emitter, f: *const module.Function, handle: Value) ?u32 { var cur = handle; for (0..8) |_| { @@ -5670,7 +6106,9 @@ const Emitter = struct { if (r.class != .cbuffer and r.kind != 15) continue; const u = &uses[ri]; if (u.all) continue; - const row = e.constInt(c.args[2]) orelse { + // (A dynamic row `i + base` indexes the array variable at + // `base`: that row counts.) + const row = e.constInt(c.args[2]) orelse dynamicBase(f, c.args[2], e) orelse { u.all = true; continue; }; @@ -5686,6 +6124,14 @@ const Emitter = struct { return uses; } + /// The constant term of a row index `x + c` (either order). + fn dynamicBase(f: *const module.Function, v: Value, e: *Emitter) ?i64 { + if (v != .inst) return null; + const op = f.insts.items[v.inst].op; + if (op != .binop or op.binop.op != .add) return null; + return e.constInt(op.binop.rhs) orelse e.constInt(op.binop.lhs); + } + /// D3D_SHADER_VARIABLE_TYPE. fn svType(e: *Emitter, s: Scalar) u32 { return switch (s) { @@ -5793,7 +6239,8 @@ const Emitter = struct { var cbuffers: std.ArrayList(reflect.CBuffer) = .empty; var tys: std.ArrayList(reflect.Type) = .empty; var cbuffer_of: std.ArrayList(?u32) = .empty; - for ([_]Resource.Class{ .cbuffer, .sampler, .srv, .uav }) |cls| for (e.resources.items, 0..) |r, ri| if (r.class == cls and !r.view) { + const alive = try e.liveResources(); + for ([_]Resource.Class{ .cbuffer, .sampler, .srv, .uav }) |cls| for (e.resources.items, 0..) |r, ri| if (r.class == cls and !r.view and alive[ri]) { const g = e.m.globals.items[r.global]; const b = e.binding(r); var bd: reflect.Bind = .{ @@ -6015,7 +6462,7 @@ const Emitter = struct { }); } for (e.m.subobjects.items) |so| { - var rec: [6]u32 = .{ @intFromEnum(so.kind), try b.string(so.name), 0, 0, 0, 0 }; + var rec: [6]u32 = .{ @backingInt(so.kind), try b.string(so.name), 0, 0, 0, 0 }; switch (so.kind) { .state_object_config, .raytracing_pipeline_config => rec[2] = so.ints[0], .raytracing_shader_config, .raytracing_pipeline_config1 => rec[2..4].* = so.ints, @@ -6082,7 +6529,7 @@ const Emitter = struct { // MS state: thread group, max vertices, max primitives, // topology, payload size. const ms = entry.mesh; - const state = try dm.mdNode(&.{ threads, try mdI32(dm, ms.max_vertices), try mdI32(dm, ms.max_primitives), try mdI32(dm, @intFromEnum(ms.topology)), try mdI32(dm, payload_size) }); + const state = try dm.mdNode(&.{ threads, try mdI32(dm, ms.max_vertices), try mdI32(dm, ms.max_primitives), try mdI32(dm, @backingInt(ms.topology)), try mdI32(dm, payload_size) }); try props.appendSlice(e.arena, &.{ try mdI32(dm, 9), state }); } if (entry.stage == .amplification) { @@ -6093,7 +6540,7 @@ const Emitter = struct { // GS state: input primitive, max vertex count, stream mask, // output topology, instance count. const gsi = entry.geometry; - const state = try dm.mdNode(&.{ try mdI32(dm, @intFromEnum(gsi.input)), try mdI32(dm, gsi.max_vertex_count), try mdI32(dm, streamMask(gsi)), try mdI32(dm, gsTopology(gsi)), try mdI32(dm, gsi.instance_count) }); + const state = try dm.mdNode(&.{ try mdI32(dm, @backingInt(gsi.input)), try mdI32(dm, gsi.max_vertex_count), try mdI32(dm, streamMask(gsi)), try mdI32(dm, gsTopology(gsi)), try mdI32(dm, gsi.instance_count) }); try props.appendSlice(e.arena, &.{ try mdI32(dm, 1), state }); } if (entry.stage == .hull) { @@ -6106,15 +6553,15 @@ const Emitter = struct { try dm.mdValue(try dm.ptrType(pc_ty), .{ .function = e.pc_fn.? }), try mdI32(dm, ts.input_control_points), try mdI32(dm, ts.output_control_points), - try mdI32(dm, @intFromEnum(ts.domain)), - try mdI32(dm, @intFromEnum(ts.partitioning)), - try mdI32(dm, @intFromEnum(ts.output_topology)), + try mdI32(dm, @backingInt(ts.domain)), + try mdI32(dm, @backingInt(ts.partitioning)), + try mdI32(dm, @backingInt(ts.output_topology)), try dm.mdValue(ft, try dm.constant(.{ .ty = ft, .kind = .{ .float_bits = @as(u32, @bitCast(ts.max_tess_factor)) } })), }); try props.appendSlice(e.arena, &.{ try mdI32(dm, 3), state }); } if (entry.stage == .domain) { - const state = try dm.mdNode(&.{ try mdI32(dm, @intFromEnum(entry.tess.domain)), try mdI32(dm, entry.tess.input_control_points) }); + const state = try dm.mdNode(&.{ try mdI32(dm, @backingInt(entry.tess.domain)), try mdI32(dm, entry.tess.input_control_points) }); try props.appendSlice(e.arena, &.{ try mdI32(dm, 2), state }); } } @@ -6169,6 +6616,7 @@ const Emitter = struct { try dm.addNamedMetadata("dx.shaderModel", &.{sm}); if (resources) |r| try dm.addNamedMetadata("dx.resources", &.{r}); try dm.addNamedMetadata("dx.entryPoints", &.{entry_md}); + try promote.pruneGlobals(e.arena, dm); _ = try promote.pruneDeclarations(e.arena, dm); return dm.writeBitcode(dm.arena.child_allocator); } @@ -6188,11 +6636,11 @@ const Emitter = struct { const row: i64 = if (el.start_row) |r| r else -1; const col: i64 = if (el.start_row != null) el.start_col else -1; n.* = try dm.mdNode(&.{ - try dm.mdI32(el.id), try dm.mdString(el.name), - try dm.mdValue(i8t, try dm.constInt(8, @intFromEnum(el.comp))), try dm.mdValue(i8t, try dm.constInt(8, @intFromEnum(el.kind))), - try dm.mdNode(idx), try dm.mdValue(i8t, try dm.constInt(8, @intFromEnum(el.interp))), - try dm.mdI32(el.rows), try dm.mdValue(i8t, try dm.constInt(8, el.cols)), - try dm.mdI32(row), try dm.mdValue(i8t, try dm.constInt(8, col)), + try dm.mdI32(el.id), try dm.mdString(el.name), + try dm.mdValue(i8t, try dm.constInt(8, @backingInt(el.comp))), try dm.mdValue(i8t, try dm.constInt(8, @backingInt(el.kind))), + try dm.mdNode(idx), try dm.mdValue(i8t, try dm.constInt(8, @backingInt(el.interp))), + try dm.mdI32(el.rows), try dm.mdValue(i8t, try dm.constInt(8, el.cols)), + try dm.mdI32(row), try dm.mdValue(i8t, try dm.constInt(8, col)), usage, }); } @@ -6221,7 +6669,8 @@ const Emitter = struct { .sampler => 1, }; const upper: u32 = if (r.count == std.math.maxInt(u32)) std.math.maxInt(u32) else b.index + r.count - 1; - try binds.append(e.arena, .{ .res_type = res_type, .space = b.space, .lower = b.index, .upper = upper, .kind = r.kind }); + // (Flags: used by 64-bit atomics.) + try binds.append(e.arena, .{ .res_type = res_type, .space = b.space, .lower = b.index, .upper = upper, .kind = r.kind, .flags = @intFromBool(r.atomic64) }); }; var stage_info: [16]u8 = @splat(0); switch (entry.stage) { @@ -6241,7 +6690,7 @@ const Emitter = struct { } if (entry.stage == .geometry) { const gsi = entry.geometry; - std.mem.writeInt(u32, stage_info[0..4], @intFromEnum(gsi.input), .little); + std.mem.writeInt(u32, stage_info[0..4], @backingInt(gsi.input), .little); std.mem.writeInt(u32, stage_info[4..8], gsTopology(gsi), .little); std.mem.writeInt(u32, stage_info[8..12], streamMask(gsi), .little); for (e.sig_out) |el| { @@ -6252,15 +6701,15 @@ const Emitter = struct { const ts = entry.tess; std.mem.writeInt(u32, stage_info[0..4], ts.input_control_points, .little); std.mem.writeInt(u32, stage_info[4..8], ts.output_control_points, .little); - std.mem.writeInt(u32, stage_info[8..12], @intFromEnum(ts.domain), .little); - std.mem.writeInt(u32, stage_info[12..16], @intFromEnum(ts.output_topology), .little); + std.mem.writeInt(u32, stage_info[8..12], @backingInt(ts.domain), .little); + std.mem.writeInt(u32, stage_info[12..16], @backingInt(ts.output_topology), .little); } if (entry.stage == .domain) { std.mem.writeInt(u32, stage_info[0..4], entry.tess.input_control_points, .little); for (e.sig_out) |el| { if (el.kind == .position) stage_info[4] = 1; // OutputPositionPresent } - std.mem.writeInt(u32, stage_info[8..12], @intFromEnum(entry.tess.domain), .little); + std.mem.writeInt(u32, stage_info[8..12], @backingInt(entry.tess.domain), .little); } const payload_size: u32 = if (entry.mesh.payload) |p| try e.payloadSize(p) else 0; if (entry.stage == .mesh) { @@ -6286,7 +6735,7 @@ const Emitter = struct { .entry = entry.name, .stage_info = stage_info, .num_threads = if (threaded) entry.num_threads else .{ 0, 0, 0 }, - .mesh_topology = if (entry.stage == .mesh) @intFromEnum(entry.mesh.topology) else 0, + .mesh_topology = if (entry.stage == .mesh) @backingInt(entry.mesh.topology) else 0, .uses_view_id = e.uses_view_id, .resources = binds.items, .inputs = e.sig_in, @@ -6297,7 +6746,7 @@ const Emitter = struct { .linalg = try e.linAlgTables(), }); defer gpa.free(psv); - const domain: signature.Domain = if (entry.stage == .hull or entry.stage == .domain) @enumFromInt(@intFromEnum(entry.tess.domain)) else .undefined; + const domain: signature.Domain = if (entry.stage == .hull or entry.stage == .domain) @fromBackingInt(@intCast(@backingInt(entry.tess.domain))) else .undefined; const isg1 = try signature.programSignature(gpa, e.sig_in, true, domain); defer gpa.free(isg1); const osg1 = try signature.programSignature(gpa, e.sig_out, false, domain); @@ -6324,14 +6773,14 @@ const Emitter = struct { .cbuffers = refl.cbuffers, .types = refl.types, // Hull shaders: the input patch (D3D_PRIMITIVE_1_CONTROL_POINT_PATCH is 8). - .input_primitive = if (gs) @intFromEnum(entry.geometry.input) else if (entry.stage == .hull) 7 + entry.tess.input_control_points else 0, + .input_primitive = if (gs) @backingInt(entry.geometry.input) else if (entry.stage == .hull) 7 + entry.tess.input_control_points else 0, .gs_output_topology = if (gs) gsTopology(entry.geometry) else 0, .gs_max_vertices = if (gs) entry.geometry.max_vertex_count else 0, .gs_instances = if (gs) entry.geometry.instance_count else 0, .control_points = if (entry.stage == .hull) entry.tess.output_control_points else if (entry.stage == .domain) entry.tess.input_control_points else 0, - .hs_output_primitive = if (entry.stage == .hull) @intFromEnum(entry.tess.output_topology) else 0, - .hs_partitioning = if (entry.stage == .hull) @intFromEnum(entry.tess.partitioning) else 0, - .tess_domain = if (tess) @intFromEnum(entry.tess.domain) else 0, + .hs_output_primitive = if (entry.stage == .hull) @backingInt(entry.tess.output_topology) else 0, + .hs_partitioning = if (entry.stage == .hull) @backingInt(entry.tess.partitioning) else 0, + .tess_domain = if (tess) @backingInt(entry.tess.domain) else 0, }, &.{ .{ .fourcc = container.fourcc("SFI0"), .data = &sfi0 }, .{ .fourcc = reflect.input_part, .data = refl_in }, @@ -6382,6 +6831,12 @@ fn isResourceType(t: *TypeTable, ty: TypeId) bool { const isRayQuery = @import("../ir/lower.zig").isRayQuery; fn reachableBlocks(a: Allocator, f: *const ir.Function) Allocator.Error![]bool { + return reachableBlocksTaken(a, f, &.{}); +} + +/// Blocks reachable from the entry, where block `b`'s branch goes only to +/// `taken[b]` when that is set. +fn reachableBlocksTaken(a: Allocator, f: *const ir.Function, taken: []const u32) Allocator.Error![]bool { const seen = try a.alloc(bool, f.blocks.items.len); @memset(seen, false); var stack: std.ArrayList(u32) = .empty; @@ -6389,6 +6844,10 @@ fn reachableBlocks(a: Allocator, f: *const ir.Function) Allocator.Error![]bool { while (stack.pop()) |b| { if (seen[b]) continue; seen[b] = true; + if (taken.len > 0 and taken[b] != std.math.maxInt(u32)) { + try stack.append(a, taken[b]); + continue; + } switch (f.blocks.items[b].term) { .br => |t| try stack.append(a, t.index()), .cond_br => |c| try stack.appendSlice(a, &.{ c.then.index(), c.@"else".index() }), diff --git a/src/dxil/libinfo.zig b/src/dxil/libinfo.zig index e36c586..646d867 100644 --- a/src/dxil/libinfo.zig +++ b/src/dxil/libinfo.zig @@ -237,7 +237,7 @@ pub fn featureInfo(fl: u64) u64 { .{ bit.typed_uav_load, 0x800 }, .{ bit.resource_heap, 0x2000000 }, .{ bit.sampler_heap, 0x4000000 }, .{ bit.barycentrics, 0x20000 }, .{ bit.extended_command_info, 0x100000000 }, .{ bit.tiled_resources, 0x100 }, .{ 1 << 29, 0x1000000 }, .{ 1 << 18, 0x1000 }, .{ 1 << 41, 0x200000000 }, .{ bit.raytracing_1_1, 0x100000 }, .{ bit.sampler_feedback, 0x200000 }, - .{ bit.advanced_texture_ops, 0x20000000 }, .{ bit.uses_derivatives, 0x100 << 32 }, .{ bit.requires_group, 0x200 << 32 }, + .{ bit.advanced_texture_ops, 0x20000000 }, .{ 1 << 27, 0x400000 }, .{ bit.uses_derivatives, 0x100 << 32 }, .{ bit.requires_group, 0x200 << 32 }, }; var out: u64 = 0; for (map) |e| if (fl & e[0] != 0) { diff --git a/src/dxil/promote.zig b/src/dxil/promote.zig index 6bbe8ef..8a255d3 100644 --- a/src/dxil/promote.zig +++ b/src/dxil/promote.zig @@ -309,7 +309,9 @@ pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashM return v; } }; - for (insts, 0..) |inst, i| switch (inst.op) { + // (Code no path reaches, such as loops unrolling left behind, does + // not count.) + for (insts, 0..) |inst, i| if (rpo_index[block_of[i]] != none) 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]) { @@ -329,10 +331,11 @@ pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashM }; { var scan: Scan = .{ .insts = insts, .var_base = var_base, .direct = direct, .gep_alloca = gep_alloca }; - for (insts) |*inst| try operands(false, a, inst, &scan); + for (insts, 0..) |*inst, i| if (rpo_index[block_of[i]] != none) try operands(false, a, inst, &scan); } // Loads and stores must move whole elements of the element type. - for (insts) |inst| { + for (insts, 0..) |inst, i| { + if (rpo_index[block_of[i]] == none) continue; const ptr, const ty = switch (inst.op) { .load => |x| .{ x.ptr, inst.ty }, .store => |x| .{ x.ptr, typeOf(m, f, x.val) }, @@ -350,7 +353,6 @@ pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashM 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; @@ -591,9 +593,18 @@ pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashM // selects on a constant. for (insts, 0..) |inst, i| { if (repl[i] != null) continue; + if (inst.op == .phi) if (try edgePhi(m, insts, block_start, repl, n, block_of[i], inst)) |v| { + repl[i] = v; + continue; + }; repl[i] = try simplify(m, f, repl, n, phi_var.items, var_ty, inst); } + // Branches on what is now a constant go one way (as dxc's simplifycfg + // makes them): blocks no longer reachable keep only an `unreachable`, + // and phis lose the edges that are gone. + var reach = try foldConstantBranches(a, m, insts, block_start, repl, bphis, bphi_off, incoming); + // The instructions that go: promoted allocas, their getelementptrs, // loads and stores. const removed = try a.alloc(bool, n); @@ -608,50 +619,66 @@ pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashM // 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, + while (true) { + @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; - }; + 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) and (reach[block_of[i]] or i == block_start[block_of[i] + 1] - 1)) { + 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); } - 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; } - if (mark.failed) return error.OutOfMemory; + // A branch whose arms do nothing (live) and meet again, with the + // same values for the merge's phis, goes nowhere: its condition + // becomes `true` (dxc's simplifycfg removes the branch) and liveness + // runs again without what only the condition read. + if (!try foldEmptyBranches(a, m, insts, block_start, reach, live, repl, n, bphis, bphi_off, incoming)) break; + reach = try foldConstantBranches(a, m, insts, block_start, repl, bphis, bphi_off, incoming); } // New indices: in each block the existing phis, then the new ones, // then the rest. + // (Blocks no path reaches go: the validator rejects `unreachable`.) + const new_block = try a.alloc(u32, nb); + var kept: u32 = 0; + for (new_block, reach) |*nbk, r| { + nbk.* = if (r) kept else none; + if (r) kept += 1; + } const index = try a.alloc(u32, n + np); @memset(index, none); var count: u32 = 0; for (0..nb) |b| { + if (!reach[b]) continue; var i = block_start[b]; while (i < block_start[b + 1] and insts[i].op == .phi) : (i += 1) if (live[i]) { index[i] = count; @@ -679,25 +706,234 @@ pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashM var out: std.ArrayList(Inst) = .empty; try out.ensureTotalCapacityPrecise(ma, count); for (0..nb) |b| { + if (!reach[b]) continue; 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); + const edges = try ma.alloc(Edge, inst.op.phi.incoming.len); + for (inst.op.phi.incoming, edges) |in, *e| e.* = .{ .val = in.val, .block = new_block[in.block] }; + inst.op.phi.incoming = edges; 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 }; + for (incoming[j], edges) |in, *e| e.* = .{ .val = map.visit(in.val, .other), .block = new_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); + switch (inst.op) { + .br => |*br| { + br.then = new_block[br.then]; + if (br.@"else") |*e| e.* = new_block[e.*]; + }, + .@"switch" => |*sw| { + sw.default = new_block[sw.default]; + const cs = try ma.alloc(@typeInfo(@TypeOf(sw.cases)).pointer.child, sw.cases.len); + for (sw.cases, cs) |c, *o| o.* = .{ .val = c.val, .block = new_block[c.block] }; + sw.cases = cs; + }, + else => {}, + } out.appendAssumeCapacity(inst); }; } f.insts = out; + f.num_blocks = kept; +} + +/// See run. Returns the blocks still reachable. +fn foldConstantBranches(a: Allocator, m: *module.Module, insts: []Inst, block_start: []const u32, repl: []const ?Value, bphis: []const u32, bphi_off: []const u32, incoming: [][]Edge) Allocator.Error![]bool { + const nb = block_start.len - 1; + for (0..nb) |b| { + const term = &insts[block_start[b + 1] - 1]; + if (term.op != .br) continue; + const br = term.op.br; + const cond = br.cond orelse continue; + const els = br.@"else" orelse continue; + const c = constInt(m, resolve(repl, cond)) orelse continue; + term.op = .{ .br = .{ .then = if (c != 0) br.then else els } }; + } + // Switches on a constant too. + for (0..nb) |b| { + const term = &insts[block_start[b + 1] - 1]; + if (term.op != .@"switch") continue; + const sw = term.op.@"switch"; + const c = constInt(m, resolve(repl, sw.cond)) orelse continue; + var target = sw.default; + for (sw.cases) |cs| if (constInt(m, cs.val) == c) { + target = cs.block; + }; + term.op = .{ .br = .{ .then = target } }; + } + const reach = try a.alloc(bool, nb); + @memset(reach, false); + var stack: std.ArrayList(u32) = .empty; + try stack.append(a, 0); + while (stack.pop()) |b| { + if (reach[b]) continue; + reach[b] = true; + switch (insts[block_start[b + 1] - 1].op) { + .br => |br| { + try stack.append(a, br.then); + if (br.@"else") |e| try stack.append(a, e); + }, + .@"switch" => |sw| { + try stack.append(a, sw.default); + for (sw.cases) |cs| try stack.append(a, cs.block); + }, + else => {}, + } + } + const Edges = struct { + insts: []const Inst, + block_start: []const u32, + reach: []const bool, + /// How many edges go from `p` to `t` (a phi has an entry per edge). + fn count(s: @This(), p: u32, t: u32) u32 { + if (!s.reach[p]) return 0; + return switch (s.insts[s.block_start[p + 1] - 1].op) { + .br => |br| @as(u32, @intFromBool(br.then == t)) + @intFromBool(br.@"else" == t), + .@"switch" => |sw| blk: { + var k: u32 = @intFromBool(sw.default == t); + for (sw.cases) |cs| k += @intFromBool(cs.block == t); + break :blk k; + }, + else => 0, + }; + } + /// Whether entry `x` of `ins` (from `ins[x].block`) is one of the + /// edges there still are. + fn keeps(s: @This(), ins: []const Edge, x: usize, t: u32) bool { + var before: u32 = 0; + for (ins[0..x]) |in| before += @intFromBool(in.block == ins[x].block); + return before < s.count(ins[x].block, t); + } + }; + const edges: Edges = .{ .insts = insts, .block_start = block_start, .reach = reach }; + for (0..nb) |b| { + const t: u32 = @intCast(b); + const last = block_start[b + 1] - 1; + if (!reach[b]) { + insts[last].op = .@"unreachable"; + continue; + } + var i = block_start[b]; + while (i < last and insts[i].op == .phi) : (i += 1) { + const old = insts[i].op.phi.incoming; + var keep: usize = 0; + for (0..old.len) |x| keep += @intFromBool(edges.keeps(old, x, t)); + if (keep == old.len) continue; + const new = try m.allocator().alloc(Edge, keep); + var k: usize = 0; + for (old, 0..) |in, x| if (edges.keeps(old, x, t)) { + new[k] = in; + k += 1; + }; + insts[i].op.phi.incoming = new; + } + for (bphis[bphi_off[b]..bphi_off[b + 1]]) |j| { + // (Kept entries move down; each is checked against those + // before it in the original order.) + const orig = try a.dupe(Edge, incoming[j]); + var k: usize = 0; + for (orig, 0..) |in, x| if (edges.keeps(orig, x, t)) { + incoming[j][k] = in; + k += 1; + }; + incoming[j] = incoming[j][0..k]; + } + } + return reach; +} + +/// See run: rewrites such branches' conditions; true if any changed. +fn foldEmptyBranches(a: Allocator, m: *module.Module, insts: []Inst, block_start: []const u32, reach: []const bool, live: []const bool, repl: []const ?Value, n: u32, bphis: []const u32, bphi_off: []const u32, incoming: []const []Edge) Allocator.Error!bool { + const nb = block_start.len - 1; + var changed = false; + const from_of = try a.alloc(u32, nb); + @memset(from_of, none); + var marked: std.ArrayList(u32) = .empty; + for (0..nb) |b| { + if (!reach[b]) continue; + const term = &insts[block_start[b + 1] - 1]; + if (term.op != .br) continue; + const br = term.op.br; + const cond = br.cond orelse continue; + if (cond != .inst) continue; + const f_ = br.@"else" orelse continue; + // Each side: the block it lands in, and the predecessor that + // edge reaches it from. + const Side = struct { land: u32, from: u32 }; + // Each side's way on: the blocks it lands in, through empty blocks + // (only an unconditional branch live, and no live phis; other + // branches may enter them too, the way on is the same). The first + // side's marks each block it lands in with the edge it came by; + // the second stops where it lands in a marked one. + var sides: [2]Side = undefined; + var met = false; + marked.clearRetainingCapacity(); + for ([2]u32{ br.then, f_ }, 0..) |t0, k| { + var side: Side = .{ .land = t0, .from = @intCast(b) }; + var steps: usize = 0; + while (steps <= nb) : (steps += 1) { + if (k == 0) { + if (from_of[side.land] != none) break; // a cycle + from_of[side.land] = side.from; + try marked.append(a, side.land); + } else if (from_of[side.land] != none) { + sides = .{ .{ .land = side.land, .from = from_of[side.land] }, side }; + met = true; + break; + } + const t = side.land; + const last = block_start[t + 1] - 1; + if (insts[last].op != .br) break; + // (A branch on a constant goes one way.) + const tb = insts[last].op.br; + const next = if (tb.cond) |c| blk: { + const kc = constInt(m, resolve(repl, c)) orelse break; + break :blk if (kc != 0) tb.then else tb.@"else" orelse tb.then; + } else tb.then; + var empty = true; + for (block_start[t]..last) |i| if (live[i]) { + empty = false; + }; + for (bphis[bphi_off[t]..bphi_off[t + 1]]) |j| if (live[n + j]) { + empty = false; + }; + if (!empty) break; + side = .{ .land = next, .from = t }; + } + } + for (marked.items) |x| from_of[x] = none; + if (!met or sides[0].from == sides[1].from) continue; + const mb = sides[0].land; + // The merge's phis take the same value from both sides. + var same = true; + var i = block_start[mb]; + while (i < block_start[mb + 1] and insts[i].op == .phi) : (i += 1) if (live[i]) { + var vals: [2]?Value = .{ null, null }; + for (insts[i].op.phi.incoming) |in| for (sides, 0..) |sd, k| if (in.block == sd.from) { + vals[k] = resolve(repl, in.val); + }; + if (vals[0] == null or vals[1] == null or !std.meta.eql(vals[0].?, vals[1].?)) same = false; + }; + for (bphis[bphi_off[mb]..bphi_off[mb + 1]]) |j| if (live[n + j]) { + var vals: [2]?Value = .{ null, null }; + for (incoming[j]) |in| for (sides, 0..) |sd, k| if (in.block == sd.from) { + vals[k] = resolve(repl, in.val); + }; + if (vals[0] == null or vals[1] == null or !std.meta.eql(vals[0].?, vals[1].?)) same = false; + }; + if (!same) continue; + term.op.br.cond = try m.constInt(1, 1); + changed = true; + } + return changed; } /// An index into an array that folding made a constant out of range (on @@ -743,7 +979,30 @@ fn simplify(m: *module.Module, f: *const module.Function, repl: []const ?Value, } }; switch (inst.op) { + // A phi taking one value on every edge is that value. + .phi => |p| { + if (p.incoming.len == 0) return null; + const first = resolve(repl, p.incoming[0].val); + if (first == .inst and first.inst < n and std.meta.eql(f.insts.items[first.inst].op, inst.op)) return null; + for (p.incoming[1..]) |in| if (!std.meta.eql(resolve(repl, in.val), first)) return null; + return first; + }, .cast => |c| { + // Integer widening and narrowing of a constant. + if (c.op == .zext or c.op == .sext or c.op == .trunc) { + const v = resolve(repl, c.val); + const k = constInt(m, v) orelse return null; + const from = S.intWidth(m, typeOf(m, f, v)) orelse return null; + const to = S.intWidth(m, inst.ty) orelse return null; + const p = S.bits(k, from); + const out: u64 = switch (c.op) { + .zext => p, + // (i1 is stored as 0 / 1: true sign-extends to all ones.) + .sext => if (from == 1) (if (p & 1 != 0) ~@as(u64, 0) else 0) else @bitCast(S.stored(p, from)), + else => p, + }; + return try m.constant(.{ .ty = inst.ty, .kind = .{ .int = S.stored(S.bits(@bitCast(out), to), to) } }); + } if (c.op != .bitcast) return null; const x = resolve(repl, c.val); if (x == .inst and x.inst < n) { @@ -817,9 +1076,35 @@ fn simplify(m: *module.Module, f: *const module.Function, repl: []const ?Value, 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); + if (c.pred <= 15) { + // Floating-point predicates on two constants (ordered: + // false with a NaN; unordered: true). + const x = constFloat(m, l) orelse return null; + const y = constFloat(m, r) orelse return null; + const uno = std.math.isNan(x) or std.math.isNan(y); + const t = switch (c.pred) { + 0 => false, + 1 => !uno and x == y, + 2 => !uno and x > y, + 3 => !uno and x >= y, + 4 => !uno and x < y, + 5 => !uno and x <= y, + 6 => !uno and x != y, + 7 => !uno, + 8 => uno, + 9 => uno or x == y, + 10 => uno or x > y, + 11 => uno or x >= y, + 12 => uno or x < y, + 13 => uno or x <= y, + 14 => uno or x != y, + else => true, + }; + return try m.constant(.{ .ty = inst.ty, .kind = .{ .int = @intFromBool(t) } }); + } + if (c.pred < 32 or c.pred > 41) return null; // integer predicates 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); @@ -862,6 +1147,71 @@ fn hasEffects(m: *const module.Module, inst: Inst) bool { }; } +/// Wave and quad operations: declared without readnone (so nothing moves +/// them across control flow), but with no effect besides their result. +/// (Only loop deletion drops them, as dxc's does; dxc's dead code removal +/// keeps them, and with them what they read.) +pub fn isWaveOp(name: []const u8) bool { + return std.mem.startsWith(u8, name, "dx.op.wave") or std.mem.startsWith(u8, name, "dx.op.quad"); +} + +/// A phi that is one constant once each input is read on its edge: an input +/// that is the condition of the branch the edge leaves by (or its zext or +/// sext) is known there. (`a && b` with `b` false merges `zext a`, on the +/// edge where `a` is false, with `false`; dxc's optimizer folds it.) +fn edgePhi(m: *module.Module, insts: []const Inst, block_start: []const u32, repl: []const ?Value, n: u32, block: u32, inst: Inst) Allocator.Error!?Value { + var same: ?i64 = null; + var known = false; + for (inst.op.phi.incoming) |in| { + const x = resolve(repl, in.val); + var k = constInt(m, x); + if (k == null) { + const term = insts[block_start[in.block + 1] - 1].op; + const br = switch (term) { + .br => |b| b, + else => return null, + }; + const cond = resolve(repl, br.cond orelse return null); + const other = br.@"else" orelse return null; + if (br.then == other) return null; + const truth: i64 = if (block == br.then) 1 else if (block == other) 0 else return null; + if (std.meta.eql(x, cond)) { + k = truth; + } else if (x == .inst and x.inst < n and insts[x.inst].op == .cast) { + const c = insts[x.inst].op.cast; + if (!std.meta.eql(resolve(repl, c.val), cond)) return null; + k = switch (c.op) { + .zext => truth, + .sext => -truth, + else => return null, + }; + } else return null; + known = true; + } + if (same) |s| { + if (s != k.?) return null; + } else same = k; + } + if (!known) return null; + return try m.constant(.{ .ty = inst.ty, .kind = .{ .int = same orelse return null } }); +} + +/// A half, float or double constant's value. +fn constFloat(m: *const module.Module, v: Value) ?f64 { + if (v != .constant) return null; + const c = m.constants.items[v.constant]; + const b = switch (c.kind) { + .float_bits => |b| b, + else => return null, + }; + return switch (m.types.items[c.ty]) { + .half => @floatCast(@as(f16, @bitCast(@as(u16, @truncate(b))))), + .float => @floatCast(@as(f32, @bitCast(@as(u32, @truncate(b))))), + .double => @bitCast(b), + else => null, + }; +} + /// `v` with replaced loads and phis followed to their final value. fn resolve(repl: []const ?Value, v: Value) Value { var x = v; @@ -904,6 +1254,52 @@ fn typeOf(m: *const module.Module, f: *const module.Function, v: Value) TypeId { /// 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. +/// Drops groupshared variables nothing refers to any more (dead code +/// removal can take their last use, and the validator rejects unused +/// internal declarations), renumbering the other globals. +pub fn pruneGlobals(a: Allocator, m: *module.Module) Allocator.Error!void { + const globals = m.globals.items; + const used = try a.alloc(bool, globals.len); + for (globals, used) |g, *u| u.* = g.addr_space != 3; + const Use = struct { + used: []bool, + fn visit(s: *@This(), v: Value, _: Role) Value { + if (v == .global) s.used[v.global] = true; + return v; + } + }; + var use: Use = .{ .used = used }; + for (m.functions.items) |f| for (f.insts.items) |*inst| try operands(false, a, inst, &use); + for (m.metadata.items) |md| if (md == .value and md.value.val == .global) { + used[md.value.val.global] = true; + }; + if (std.mem.indexOfScalar(bool, used, false) == null) return; + const index = try a.alloc(u32, globals.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 == .global) .{ .global = s.index[v.global] } else v; + } + }; + var map: Map = .{ .index = index }; + const ma = m.allocator(); + for (m.functions.items) |*f| for (f.insts.items) |*inst| try operands(true, ma, inst, &map); + for (m.metadata.items) |*md| if (md.* == .value and md.value.val == .global) { + md.value.val = .{ .global = index[md.value.val.global] }; + }; + var k: usize = 0; + for (globals, used) |g, u| if (u) { + globals[k] = g; + k += 1; + }; + m.globals.shrinkRetainingCapacity(k); +} + 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); diff --git a/src/dxil/sccp.zig b/src/dxil/sccp.zig new file mode 100644 index 0000000..e71c20e --- /dev/null +++ b/src/dxil/sccp.zig @@ -0,0 +1,322 @@ +//! Sparse conditional constant propagation (Wegman and Zadeck) on a DXIL +//! function in SSA form, over integer values: optimistic, so values carried +//! round a loop that only ever hold one constant are found, and code only +//! reachable through branches that never go that way is left out. (A flag +//! that starts false and is passed back unchanged through a loop, or a loop +//! whose first test already fails, as dxc's optimizer finds them.) +//! +//! The results go into the function as constants: the uses of values found +//! constant, and the conditions of branches found to go one way; promotion +//! then drops what that leaves dead or unreachable. + +const std = @import("std"); +const Allocator = std.mem.Allocator; +const module = @import("module.zig"); +const unroll = @import("unroll.zig"); + +const Value = module.Value; +const Inst = module.Inst; + +const none = std.math.maxInt(u32); + +/// Not yet known (optimistically anything), one constant, or varying. +const Lat = union(enum) { + top, + k: i64, + bot, + + fn meet(x: Lat, y: Lat) Lat { + return switch (x) { + .top => y, + .bot => .bot, + .k => |a| switch (y) { + .top => x, + .bot => .bot, + .k => |b| if (a == b) x else .bot, + }, + }; + } + + fn eql(x: Lat, y: Lat) bool { + return std.meta.eql(x, y); + } +}; + +fn intWidth(m: *const module.Module, ty: module.TypeId) ?u32 { + return switch (m.types.items[ty]) { + .int => |w| w, + else => null, + }; +} + +fn bitsOf(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 constants hold it: 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; +} + +fn typeOf(m: *const module.Module, f: *const module.Function, v: Value) ?module.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], + else => null, + }; +} + +fn isTerminator(inst: Inst) bool { + return switch (inst.op) { + .ret, .br, .@"switch", .@"unreachable" => true, + else => false, + }; +} + +/// Runs the propagation on `func`; true if it changed anything. +pub fn run(a: Allocator, m: *module.Module, func: u32) Allocator.Error!bool { + 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 false; + + 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 false; + block_of[i] = b; + if (isTerminator(inst)) { + b += 1; + block_start[b] = @intCast(i + 1); + } + } + if (b != nb) return false; + } + + const lat = try a.alloc(Lat, n); + @memset(lat, .top); + const exec = try a.alloc(bool, nb); + @memset(exec, false); + exec[0] = true; + var edges: std.AutoHashMapUnmanaged(u64, void) = .empty; + const S = struct { + fn key(from: u32, to: u32) u64 { + return @as(u64, from) << 32 | to; + } + }; + + const Eval = struct { + m: *const module.Module, + f: *const module.Function, + lat: []const Lat, + + fn of(s: @This(), v: Value) Lat { + return switch (v) { + .inst => |i| s.lat[i], + .constant => |c| switch (s.m.constants.items[c].kind) { + .int => |x| .{ .k = x }, + else => .bot, + }, + else => .bot, + }; + } + + fn inst(s: @This(), i: u32) Lat { + const in = s.f.insts.items[i]; + const w = intWidth(s.m, in.ty) orelse return .bot; + switch (in.op) { + .binop => |b| { + const l = s.of(b.lhs); + const r = s.of(b.rhs); + if (l == .bot or r == .bot) { + // (Varying, but a zero still decides these.) + const z = if (l == .k and l.k == 0) true else if (r == .k and r.k == 0) true else false; + if (z and (b.op == .@"and" or b.op == .mul)) return .{ .k = 0 }; + return .bot; + } + if (l == .top or r == .top) return .top; + const x = bitsOf(l.k, w); + const y = bitsOf(r.k, w); + const sx = stored(x, w); + const sy = 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 .bot, + .lshr => if (y < w) x >> @intCast(y) else return .bot, + .ashr => if (y < w) @bitCast(sx >> @intCast(y)) else return .bot, + .udiv => if (y != 0) x / y else return .bot, + .urem => if (y != 0) x % y else return .bot, + .sdiv => if (sy != 0 and !(sy == -1 and sx == std.math.minInt(i64))) @bitCast(@divTrunc(sx, sy)) else return .bot, + .srem => if (sy != 0 and sy != -1) @bitCast(@rem(sx, sy)) else return .bot, + }; + return .{ .k = stored(bitsOf(@bitCast(p), w), w) }; + }, + .cast => |c| { + if (c.op != .zext and c.op != .sext and c.op != .trunc) return .bot; + const from = intWidth(s.m, typeOf(s.m, s.f, c.val) orelse return .bot) orelse return .bot; + const v = s.of(c.val); + if (v != .k) return v; + const x = bitsOf(v.k, from); + const out: u64 = switch (c.op) { + .sext => if (from == 1) (if (x & 1 != 0) ~@as(u64, 0) else 0) else @bitCast(stored(x, from)), + else => x, + }; + return .{ .k = stored(bitsOf(@bitCast(out), w), w) }; + }, + .cmp => |c| { + if (c.pred < 32 or c.pred > 41) return .bot; + const cw = intWidth(s.m, typeOf(s.m, s.f, c.lhs) orelse return .bot) orelse return .bot; + const l = s.of(c.lhs); + const r = s.of(c.rhs); + if (l == .bot or r == .bot) return .bot; + if (l == .top or r == .top) return .top; + const x = bitsOf(l.k, cw); + const y = bitsOf(r.k, cw); + const sx = stored(x, cw); + const sy = stored(y, cw); + 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 .{ .k = @intFromBool(t) }; + }, + .select => |sel| { + const c = s.of(sel.cond); + return switch (c) { + .top => .top, + .k => |x| s.of(if (x & 1 != 0) sel.t else sel.f), + .bot => s.of(sel.t).meet(s.of(sel.f)), + }; + }, + else => return .bot, + } + } + }; + const ev: Eval = .{ .m = m, .f = f, .lat = lat }; + + // Iterated to the fixed point in block order (the lattice is three + // levels deep, so this ends quickly). + var changed = true; + var rounds: u32 = 0; + while (changed) : (rounds += 1) { + if (rounds > 1000) return false; + changed = false; + for (0..nb) |bb| { + const b: u32 = @intCast(bb); + if (!exec[b]) continue; + for (block_start[b]..block_start[b + 1]) |ii| { + const i: u32 = @intCast(ii); + const inst = insts[i]; + var new: Lat = undefined; + switch (inst.op) { + .phi => |p| { + if (intWidth(m, inst.ty) == null) { + new = .bot; + } else { + new = .top; + for (p.incoming) |in| { + if (!edges.contains(S.key(in.block, b))) continue; + new = new.meet(ev.of(in.val)); + } + } + }, + .br => |br| { + const targets: [2]?u32 = if (br.cond) |c| switch (ev.of(c)) { + .top => .{ null, null }, + .k => |x| .{ if (x & 1 != 0) br.then else br.@"else", null }, + .bot => .{ br.then, br.@"else" }, + } else .{ br.then, null }; + for (targets) |t| if (t) |tb| { + const gop = try edges.getOrPut(a, S.key(b, tb)); + if (!gop.found_existing) { + exec[tb] = true; + changed = true; + } + }; + continue; + }, + .@"switch" => |sw| { + const c = ev.of(sw.cond); + if (c == .top) continue; + var taken: ?u32 = null; + if (c == .k) { + taken = sw.default; + for (sw.cases) |cs| if (ev.of(cs.val) == .k and ev.of(cs.val).k == c.k) { + taken = cs.block; + }; + } + var list: std.ArrayList(u32) = .empty; + if (taken) |t| try list.append(a, t) else { + try list.append(a, sw.default); + for (sw.cases) |cs| try list.append(a, cs.block); + } + for (list.items) |tb| { + const gop = try edges.getOrPut(a, S.key(b, tb)); + if (!gop.found_existing) { + exec[tb] = true; + changed = true; + } + } + continue; + }, + else => new = ev.inst(i), + } + const merged = lat[i].meet(new); + if (!merged.eql(lat[i])) { + lat[i] = merged; + changed = true; + } + } + } + } + + // Constants into the function: the uses of integer values found + // constant, and branch conditions. + const repl = try a.alloc(?Value, n); + @memset(repl, null); + var any = false; + for (insts, 0..) |inst, i| { + if (!exec[block_of[i]]) continue; + if (lat[i] != .k) continue; + if (intWidth(m, inst.ty) == null) continue; + repl[i] = try m.constant(.{ .ty = inst.ty, .kind = .{ .int = lat[i].k } }); + } + const Mapper = struct { + repl: []const ?Value, + any: *bool, + pub fn visit(c: *@This(), v: Value, _: anytype) Value { + if (v == .inst and v.inst < c.repl.len) if (c.repl[v.inst]) |r| { + c.any.* = true; + return r; + }; + return v; + } + }; + var mapper: Mapper = .{ .repl = repl, .any = &any }; + const ma = m.allocator(); + for (insts) |*inst| try unroll.operandsMap(ma, inst, &mapper); + return any; +} diff --git a/src/dxil/unroll.zig b/src/dxil/unroll.zig new file mode 100644 index 0000000..7f0a5ba --- /dev/null +++ b/src/dxil/unroll.zig @@ -0,0 +1,749 @@ +//! Full unrolling of loops with a constant trip count, on a DXIL function +//! after promotion to SSA values (as dxc's loop unrolling runs after SROA): +//! by then a loop's bound often comes from struct fields and arguments +//! only inlining made constant. Unrolled, indices into local arrays become +//! constants (so promotion can take the arrays out of memory) and code +//! guarded by the counter folds away, as it does for dxc. +//! +//! A loop qualifies when it is innermost, has one block leaving it (a +//! conditional branch out of the loop, to one block), and that branch's +//! condition is decided by header phis that start constant and step by +//! values computed from themselves. Its blocks are copied once per +//! iteration, and once more up to the exit, after the function's last +//! block; the original blocks are left unreachable for promotion to drop. + +const std = @import("std"); +const Allocator = std.mem.Allocator; +const module = @import("module.zig"); +const promote = @import("promote.zig"); + +const Value = module.Value; +const Inst = module.Inst; +const Edge = @typeInfo(@FieldType(@FieldType(@FieldType(Inst, "op"), "phi"), "incoming")).pointer.child; + +const none = std.math.maxInt(u32); + +/// Most iterations unrolled, and most instructions one function may grow +/// by. +const max_trips = 256; +const max_growth = 65536; + +/// Unrolls the qualifying loops of `func`, innermost first; true if any. +pub fn run(a: Allocator, m: *module.Module, func: u32) Allocator.Error!bool { + var budget: usize = max_growth; + var tried: std.AutoHashMapUnmanaged(u32, void) = .empty; + var any = false; + while (try unrollOne(a, m, func, &budget, &tried)) any = true; + return any; +} + +const Cfg = struct { + nb: u32, + block_start: []u32, + succs: [][]u32, + preds: [][]u32, + idom: []u32, + + fn dominates(c: *const Cfg, d: u32, b: u32) bool { + var x = b; + while (true) { + if (x == d) return true; + const p = c.idom[x]; + if (p == none or p == x) return false; + x = p; + } + } +}; + +fn isTerminator(inst: Inst) bool { + return switch (inst.op) { + .ret, .br, .@"switch", .@"unreachable" => true, + else => false, + }; +} + +fn buildCfg(a: Allocator, f: *const module.Function) Allocator.Error!?Cfg { + const nb = f.num_blocks; + const insts = f.insts.items; + const block_start = try a.alloc(u32, nb + 1); + var b: u32 = 0; + block_start[0] = 0; + for (insts, 0..) |inst, i| { + if (b >= nb) return null; + if (isTerminator(inst)) { + b += 1; + block_start[b] = @intCast(i + 1); + } + } + if (b != nb) return null; + const succs = try a.alloc([]u32, nb); + var pred_lists = try a.alloc(std.ArrayList(u32), nb); + for (pred_lists) |*p| p.* = .empty; + for (0..nb) |bi| { + var s: std.ArrayList(u32) = .empty; + switch (insts[block_start[bi + 1] - 1].op) { + .br => |br| { + try s.append(a, br.then); + if (br.@"else") |e| if (e != br.then) try s.append(a, e); + }, + .@"switch" => |sw| { + try s.append(a, sw.default); + for (sw.cases) |c| if (std.mem.indexOfScalar(u32, s.items, c.block) == null) try s.append(a, c.block); + }, + else => {}, + } + succs[bi] = s.items; + for (s.items) |t| try pred_lists[t].append(a, @intCast(bi)); + } + const preds = try a.alloc([]u32, nb); + for (preds, pred_lists) |*p, l| p.* = l.items; + + // Reverse postorder, then Cooper, Harvey and Kennedy's dominators. + const order = try a.alloc(u32, nb); + @memset(order, none); + var rpo: std.ArrayList(u32) = .empty; + { + var post: std.ArrayList(u32) = .empty; + const seen = try a.alloc(bool, nb); + @memset(seen, false); + const Fr = struct { b: u32, next: u32 }; + var stack: std.ArrayList(Fr) = .empty; + try stack.append(a, .{ .b = 0, .next = 0 }); + seen[0] = true; + while (stack.items.len > 0) { + const top = &stack.items[stack.items.len - 1]; + if (top.next < succs[top.b].len) { + const s = succs[top.b][top.next]; + top.next += 1; + if (!seen[s]) { + seen[s] = true; + try stack.append(a, .{ .b = s, .next = 0 }); + } + } else { + try post.append(a, top.b); + _ = stack.pop(); + } + } + var k = post.items.len; + while (k > 0) { + k -= 1; + order[post.items[k]] = @intCast(rpo.items.len); + try rpo.append(a, post.items[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..]) |bb| { + var new: u32 = none; + for (preds[bb]) |p| { + if (idom[p] == none) continue; + if (new == none) { + new = p; + continue; + } + var x = p; + var y = new; + while (x != y) { + while (order[x] > order[y]) x = idom[x]; + while (order[y] > order[x]) y = idom[y]; + } + new = x; + } + if (new != none and idom[bb] != new) { + idom[bb] = new; + changed = true; + } + } + } + return .{ .nb = nb, .block_start = block_start, .succs = succs, .preds = preds, .idom = idom }; +} + +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 intWidth(m: *const module.Module, ty: module.TypeId) ?u32 { + return switch (m.types.items[ty]) { + .int => |w| w, + else => null, + }; +} + +fn bitsOf(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 constants hold it: 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; +} + +/// Integer value of `v` given the header phis' values in `state` (index: +/// instruction), or null. +fn eval(m: *const module.Module, f: *const module.Function, state: *const std.AutoHashMapUnmanaged(u32, i64), v: Value, depth: u32) ?i64 { + if (depth > 64) return null; + if (constInt(m, v)) |c| return c; + if (v != .inst) return null; + if (state.get(v.inst)) |s| return s; + const inst = f.insts.items[v.inst]; + const w = intWidth(m, inst.ty) orelse return null; + switch (inst.op) { + .binop => |b| { + const x = bitsOf(eval(m, f, state, b.lhs, depth + 1) orelse return null, w); + const y = bitsOf(eval(m, f, state, b.rhs, depth + 1) orelse return null, w); + const sx = stored(x, w); + const sy = 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 stored(bitsOf(@bitCast(p), w), w); + }, + .cast => |c| { + const from = intWidth(m, typeOf(m, f, c.val) orelse return null) orelse return null; + const x = bitsOf(eval(m, f, state, c.val, depth + 1) orelse return null, from); + const out: u64 = switch (c.op) { + .zext, .trunc => x, + .sext => if (from == 1) (if (x & 1 != 0) ~@as(u64, 0) else 0) else @bitCast(stored(x, from)), + else => return null, + }; + return stored(bitsOf(@bitCast(out), w), w); + }, + .cmp => |c| { + if (c.pred < 32 or c.pred > 41) return null; + const cw = intWidth(m, typeOf(m, f, c.lhs) orelse return null) orelse return null; + const x = bitsOf(eval(m, f, state, c.lhs, depth + 1) orelse return null, cw); + const y = bitsOf(eval(m, f, state, c.rhs, depth + 1) orelse return null, cw); + const sx = stored(x, cw); + const sy = stored(y, cw); + 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 @intFromBool(t); + }, + .select => |s| { + const c = eval(m, f, state, s.cond, depth + 1) orelse return null; + return eval(m, f, state, if (c & 1 != 0) s.t else s.f, depth + 1); + }, + else => return null, + } +} + +fn typeOf(m: *const module.Module, f: *const module.Function, v: Value) ?module.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], + else => null, + }; +} + +fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried: *std.AutoHashMapUnmanaged(u32, void)) Allocator.Error!bool { + const f = &m.functions.items[func]; + const cfg = (try buildCfg(a, f)) orelse return false; + const nb = cfg.nb; + const insts = f.insts.items; + + // Loops: headers with back edges (from blocks they dominate), and + // their blocks. + const Loop = struct { h: u32, body: []bool, latches: []u32 }; + var loops: std.ArrayList(Loop) = .empty; + for (0..nb) |hb| { + const h: u32 = @intCast(hb); + if (cfg.idom[h] == none) continue; + var latches: std.ArrayList(u32) = .empty; + for (cfg.preds[h]) |p| if (cfg.idom[p] != none and cfg.dominates(h, p)) try latches.append(a, p); + if (latches.items.len == 0) continue; + const body = try a.alloc(bool, nb); + @memset(body, false); + body[h] = true; + var stack: std.ArrayList(u32) = .empty; + try stack.appendSlice(a, latches.items); + while (stack.pop()) |x| { + if (body[x]) continue; + body[x] = true; + for (cfg.preds[x]) |p| if (cfg.idom[p] != none) try stack.append(a, p); + } + try loops.append(a, .{ .h = h, .body = body, .latches = latches.items }); + } + + // Loops that do nothing (as dxc's loop deletion removes them): no + // instruction with an effect, one block they leave to, and nothing + // after them reading their values. Their preheader goes straight to + // that block; their blocks are left unreachable for promotion to drop. + // (Nested ones too: an outer loop whose inner loops do nothing.) + const loop_inst = try a.alloc(bool, insts.len); + dead: for (loops.items) |lp| { + var exit: u32 = none; + for (0..nb) |bb| { + if (!lp.body[bb]) continue; + for (cfg.block_start[bb]..cfg.block_start[bb + 1]) |i| switch (insts[i].op) { + .br, .@"switch" => {}, + .ret, .@"unreachable", .store, .atomicrmw, .cmpxchg => continue :dead, + .call => |c| switch (m.functions.items[c.callee].attrs) { + .nounwind_readnone, .nounwind_readonly => {}, + else => if (!promote.isWaveOp(m.functions.items[c.callee].name)) continue :dead, + }, + else => {}, + }; + for (cfg.succs[bb]) |s| if (!lp.body[s]) { + if (exit != none and exit != s) continue :dead; + exit = s; + }; + } + if (exit == none) continue; + var pre: u32 = none; + for (cfg.preds[lp.h]) |p| if (!lp.body[p]) { + if (pre != none) continue :dead; + pre = p; + }; + if (pre == none) continue; + const pterm = &insts[cfg.block_start[pre + 1] - 1]; + if (pterm.op != .br) continue; + if (pterm.op.br.then == exit or pterm.op.br.@"else" == exit) continue; + + for (0..nb) |bb| for (cfg.block_start[bb]..cfg.block_start[bb + 1]) |i| { + loop_inst[i] = lp.body[bb]; + }; + // The exit's phis: one value from the loop, from before it. + const phi_end = blk: { + var i = cfg.block_start[exit]; + while (insts[i].op == .phi) i += 1; + break :blk i; + }; + const from_loop = try a.alloc(?Value, phi_end - cfg.block_start[exit]); + for (cfg.block_start[exit]..phi_end, from_loop) |i, *fl| { + fl.* = null; + for (insts[i].op.phi.incoming) |in| if (lp.body[in.block]) { + if (in.val == .inst and loop_inst[in.val.inst]) continue :dead; + if (fl.* != null and !std.meta.eql(fl.*.?, in.val)) continue :dead; + fl.* = in.val; + }; + } + // Nothing else outside reads the loop's values. + const Check = struct { + loop_inst: []const bool, + used: bool = false, + pub fn visit(c: *@This(), v: Value, _: anytype) Value { + if (v == .inst and v.inst < c.loop_inst.len and c.loop_inst[v.inst]) c.used = true; + return v; + } + }; + var check: Check = .{ .loop_inst = loop_inst }; + for (0..nb) |bb| { + if (lp.body[bb]) continue; + for (cfg.block_start[bb]..cfg.block_start[bb + 1]) |i| { + if (bb == exit and i < phi_end) continue; + var copy = insts[i]; + try operandsMap(a, ©, &check); + } + } + if (check.used) continue; + + const ma = m.allocator(); + for (cfg.block_start[exit]..phi_end, from_loop) |i, fl| { + var edges: std.ArrayList(Edge) = .empty; + for (insts[i].op.phi.incoming) |in| if (!lp.body[in.block]) try edges.append(ma, in); + if (fl) |v| try edges.append(ma, .{ .val = v, .block = pre }); + insts[i].op.phi.incoming = edges.items; + } + if (pterm.op.br.then == lp.h) pterm.op.br.then = exit; + if (pterm.op.br.@"else") |*e| if (e.* == lp.h) { + e.* = exit; + }; + for (0..nb) |bb| if (lp.body[bb]) { + insts[cfg.block_start[bb + 1] - 1].op = .@"unreachable"; + }; + return true; + } + + candidates: for (loops.items) |lp| { + const h = lp.h; + if (tried.contains(h)) continue; + // Innermost: no other loop's header inside. + for (loops.items) |other| if (other.h != h and lp.body[other.h]) continue :candidates; + try tried.put(a, h, {}); + + // One way out: a conditional branch from one block, to one block. + var exiting: u32 = none; + var exit: u32 = none; + var size: usize = 0; + var body_blocks: std.ArrayList(u32) = .empty; + for (0..nb) |bb| { + if (!lp.body[bb]) continue; + try body_blocks.append(a, @intCast(bb)); + size += cfg.block_start[bb + 1] - cfg.block_start[bb]; + const term = insts[cfg.block_start[bb + 1] - 1].op; + if (term == .@"switch") { + for (cfg.succs[bb]) |s| if (!lp.body[s]) continue :candidates; + } + for (cfg.succs[bb]) |s| if (!lp.body[s]) { + if (exiting != none) continue :candidates; + exiting = @intCast(bb); + exit = s; + }; + } + if (exiting == none) continue; + const xterm = insts[cfg.block_start[exiting + 1] - 1].op; + if (xterm != .br or xterm.br.@"else" == null) continue; + const stay = if (xterm.br.then == exit) xterm.br.@"else".? else xterm.br.then; + if (!lp.body[stay] or stay == exit) continue; + for (lp.latches) |l| if (!cfg.dominates(exiting, l)) continue :candidates; + // One way in. + var pre: u32 = none; + for (cfg.preds[h]) |p| if (!lp.body[p]) { + if (pre != none) continue :candidates; + pre = p; + }; + if (pre == none) continue; + + // The header's phis: the integer ones whose values can be followed. + var phis: std.ArrayList(u32) = .empty; + { + var i = cfg.block_start[h]; + while (insts[i].op == .phi) : (i += 1) try phis.append(a, i); + } + var state: std.AutoHashMapUnmanaged(u32, i64) = .empty; + for (phis.items) |pi| { + if (intWidth(m, insts[pi].ty) == null) continue; + for (insts[pi].op.phi.incoming) |in| if (in.block == pre) { + if (constInt(m, in.val)) |c| try state.put(a, pi, c); + }; + } + const xcond = xterm.br.cond.?; + const stay_on: i64 = if (xterm.br.then == stay) 1 else 0; + var states: std.ArrayList(std.AutoHashMapUnmanaged(u32, i64)) = .empty; + while (true) { + const c = eval(m, f, &state, xcond, 0) orelse continue :candidates; + if ((c & 1) != stay_on) break; + if (states.items.len >= max_trips) continue :candidates; + try states.append(a, try state.clone(a)); + // Next values: what every latch passes back (the same). + var next: std.AutoHashMapUnmanaged(u32, i64) = .empty; + for (phis.items) |pi| { + if (!state.contains(pi)) continue; + var val: ?i64 = null; + var ok = true; + for (insts[pi].op.phi.incoming) |in| { + if (in.block == pre) continue; + const v = eval(m, f, &state, in.val, 0) orelse { + ok = false; + break; + }; + if (val != null and val.? != v) ok = false; + val = v; + } + if (ok) if (val) |v| try next.put(a, pi, v); + } + state = next; + } + const trips = states.items.len; + const growth = (trips + 1) * size; + if (growth > budget.*) continue; + budget.* -= growth; + try states.append(a, state); // the last pass, up to the exit + + // Copies: block `body_blocks[j]` of copy `k` is block + // `nb + k * nbody + j`. + const nbody: u32 = @intCast(body_blocks.items.len); + const index_in = try a.alloc(u32, nb); + @memset(index_in, none); + for (body_blocks.items, 0..) |bb, j| index_in[bb] = @intCast(j); + const n0: u32 = @intCast(insts.len); + const copies: u32 = @intCast(trips + 1); + // Value maps per copy (original instruction -> value). + const maps = try a.alloc(std.AutoHashMapUnmanaged(u32, Value), copies); + for (maps) |*mp| mp.* = .empty; + const S = struct { + fn block(nb_: u32, nbody_: u32, idx: []const u32, k: u32, b: u32) u32 { + return nb_ + k * nbody_ + idx[b]; + } + }; + + var out: std.ArrayList(Inst) = .empty; + const ma = m.allocator(); + // New instruction indices come after the existing ones. + var next_index: u32 = n0; + // First pass: give every copied instruction its index (phis of + // later copies refer back, latch values refer forward to the next + // copy's header). + const new_index = try a.alloc([]u32, copies); + for (0..copies) |k| { + new_index[k] = try a.alloc(u32, n0); + @memset(new_index[k], none); + for (body_blocks.items) |bb| { + var i = cfg.block_start[bb]; + while (i < cfg.block_start[bb + 1]) : (i += 1) { + new_index[k][i] = next_index; + next_index += 1; + } + } + } + // Header phis: a constant where followed, else the value from the + // copy before (or from the preheader). + for (0..copies) |k| { + for (phis.items) |pi| { + if (states.items[k].get(pi)) |c| { + try maps[k].put(a, pi, try m.constant(.{ .ty = insts[pi].ty, .kind = .{ .int = c } })); + continue; + } + if (k == 0) { + for (insts[pi].op.phi.incoming) |in| if (in.block == pre) try maps[0].put(a, pi, in.val); + } + } + } + const Mapper = struct { + maps: []std.AutoHashMapUnmanaged(u32, Value), + new_index: [][]u32, + k: u32, + fn val(c: @This(), v: Value) Value { + if (v != .inst) return v; + if (c.maps[c.k].get(v.inst)) |x| return x; + if (v.inst < c.new_index[c.k].len and c.new_index[c.k][v.inst] != none) return .{ .inst = c.new_index[c.k][v.inst] }; + return v; + } + fn visit(c: *@This(), v: Value, _: anytype) Value { + return c.val(v); + } + }; + for (0..copies) |kk| { + const k: u32 = @intCast(kk); + for (body_blocks.items) |bb| { + var i = cfg.block_start[bb]; + while (i < cfg.block_start[bb + 1]) : (i += 1) { + var inst = insts[i]; + var mapper: Mapper = .{ .maps = maps, .new_index = new_index, .k = k }; + if (bb == h and inst.op == .phi) { + if (maps[k].get(i)) |v| { + // Folded away: a phi of that value on every + // edge keeps the numbering (promotion drops it). + var edges: std.ArrayList(Edge) = .empty; + if (k == 0) { + try edges.append(ma, .{ .val = v, .block = pre }); + } else for (lp.latches) |l| try edges.append(ma, .{ .val = v, .block = S.block(nb, nbody, index_in, k - 1, l) }); + try out.append(ma, .{ .ty = inst.ty, .op = .{ .phi = .{ .incoming = edges.items } } }); + continue; + } + // From the latches of the copy before. + var edges: std.ArrayList(Edge) = .empty; + for (inst.op.phi.incoming) |in| { + if (in.block == pre or k == 0) continue; + const prev: Mapper = .{ .maps = maps, .new_index = new_index, .k = k - 1 }; + try edges.append(ma, .{ .val = prev.val(in.val), .block = S.block(nb, nbody, index_in, k - 1, in.block) }); + } + if (k == 0) { + // (Not followed and no preheader value mapped: + // the preheader's incoming.) + for (inst.op.phi.incoming) |in| if (in.block == pre) try edges.append(ma, .{ .val = in.val, .block = pre }); + } + try out.append(ma, .{ .ty = inst.ty, .op = .{ .phi = .{ .incoming = edges.items } } }); + continue; + } + if (inst.op == .phi) { + const edges = try ma.alloc(Edge, inst.op.phi.incoming.len); + for (inst.op.phi.incoming, edges) |in, *e| e.* = .{ .val = mapper.val(in.val), .block = if (index_in[in.block] != none) S.block(nb, nbody, index_in, k, in.block) else in.block }; + inst.op = .{ .phi = .{ .incoming = edges } }; + try out.append(ma, inst); + continue; + } + try operandsMap(ma, &inst, &mapper); + // Branches: within the copy; back to the header: the + // next copy; out of the exiting block: per copy. + switch (inst.op) { + .br => |*br| { + if (bb == exiting) { + const target = if (k + 1 < copies) stay else exit; + const tb = if (target == exit) exit else S.block(nb, nbody, index_in, k, target); + br.* = .{ .then = tb }; + } else { + br.then = mapBlock(br.then, h, k, copies, nb, nbody, index_in); + if (br.@"else") |*e| e.* = mapBlock(e.*, h, k, copies, nb, nbody, index_in); + } + }, + .@"switch" => |*sw| { + sw.default = mapBlock(sw.default, h, k, copies, nb, nbody, index_in); + const cs = try ma.alloc(@typeInfo(@TypeOf(sw.cases)).pointer.child, sw.cases.len); + for (sw.cases, cs) |c, *o| o.* = .{ .val = c.val, .block = mapBlock(c.block, h, k, copies, nb, nbody, index_in) }; + sw.cases = cs; + }, + else => {}, + } + // Integer values the counter decides: constants. + if (inst.op == .binop or inst.op == .cast or inst.op == .cmp or inst.op == .select) { + if (eval(m, f, &states.items[k], .{ .inst = i }, 0)) |c| { + if (intWidth(m, inst.ty) != null) try maps[k].put(a, i, try m.constant(.{ .ty = inst.ty, .kind = .{ .int = c } })); + } + } + try out.append(ma, inst); + } + } + } + + // The preheader enters the first copy; the exit's phis and the + // code after the loop see the last copy's values. + const last: Mapper = .{ .maps = maps, .new_index = new_index, .k = copies - 1 }; + const in_body = try a.alloc(bool, n0); + for (0..nb) |bb| for (cfg.block_start[bb]..cfg.block_start[bb + 1]) |i| { + in_body[i] = lp.body[bb]; + }; + const Outside = struct { + last: Mapper, + in_body: []const bool, + fn visit(c: *@This(), v: Value, _: anytype) Value { + if (v == .inst and v.inst < c.in_body.len and c.in_body[v.inst]) return c.last.val(v); + return v; + } + }; + var outside: Outside = .{ .last = last, .in_body = in_body }; + for (0..nb) |bb| { + if (lp.body[bb]) { + // The originals: unreachable now. + insts[cfg.block_start[bb + 1] - 1].op = .@"unreachable"; + continue; + } + for (cfg.block_start[bb]..cfg.block_start[bb + 1]) |i| { + var inst = &insts[i]; + if (inst.op == .phi) { + const edges = try ma.alloc(Edge, inst.op.phi.incoming.len); + for (inst.op.phi.incoming, edges) |in, *e| e.* = .{ + .val = outside.visit(in.val, {}), + .block = if (in.block == exiting and bb == exit) S.block(nb, nbody, index_in, copies - 1, exiting) else in.block, + }; + inst.op = .{ .phi = .{ .incoming = edges } }; + continue; + } + try operandsMap(ma, inst, &outside); + if (bb == pre) switch (inst.op) { + .br => |*br| { + if (br.then == h) br.then = S.block(nb, nbody, index_in, 0, h); + if (br.@"else") |*e| if (e.* == h) { + e.* = S.block(nb, nbody, index_in, 0, h); + }; + }, + .@"switch" => |*sw| { + if (sw.default == h) sw.default = S.block(nb, nbody, index_in, 0, h); + const cs = try ma.alloc(@typeInfo(@TypeOf(sw.cases)).pointer.child, sw.cases.len); + for (sw.cases, cs) |c, *o| o.* = .{ .val = c.val, .block = if (c.block == h) S.block(nb, nbody, index_in, 0, h) else c.block }; + sw.cases = cs; + }, + else => {}, + }; + } + } + try f.insts.appendSlice(ma, out.items); + f.num_blocks = nb + copies * nbody; + return true; + } + return false; +} + +/// A branch target in copy `k`: the copy's own block, or (the header) the +/// next copy's. +fn mapBlock(t: u32, h: u32, k: u32, copies: u32, nb: u32, nbody: u32, idx: []const u32) u32 { + if (idx[t] == none) return t; + if (t == h) return nb + @min(k + 1, copies - 1) * nbody + idx[t]; + return nb + k * nbody + idx[t]; +} + +/// Rewrites `inst`'s value operands through `ctx.visit` (block operands +/// are the caller's). +pub fn operandsMap(a: Allocator, inst: *Inst, ctx: anytype) Allocator.Error!void { + const S = struct { + fn one(c: anytype, v: *Value) void { + v.* = c.visit(v.*, {}); + } + fn many(al: Allocator, c: anytype, vs: *[]const Value) Allocator.Error!void { + const o = try al.alloc(Value, vs.len); + for (vs.*, o) |v, *x| x.* = c.visit(v, {}); + vs.* = o; + } + }; + switch (inst.op) { + .ret => |*v| if (v.*) |*x| S.one(ctx, x), + .br => |*b| if (b.cond) |*c| S.one(ctx, c), + .@"switch" => |*sw| S.one(ctx, &sw.cond), + .call => |*c| try S.many(a, ctx, &c.args), + .binop => |*b| { + S.one(ctx, &b.lhs); + S.one(ctx, &b.rhs); + }, + .cast => |*c| S.one(ctx, &c.val), + .cmp => |*c| { + S.one(ctx, &c.lhs); + S.one(ctx, &c.rhs); + }, + .select => |*s| { + S.one(ctx, &s.cond); + S.one(ctx, &s.t); + S.one(ctx, &s.f); + }, + .extractvalue => |*x| S.one(ctx, &x.agg), + .phi => |*p| { + const out = try a.alloc(Edge, p.incoming.len); + for (p.incoming, out) |in, *o| o.* = .{ .val = ctx.visit(in.val, {}), .block = in.block }; + p.incoming = out; + }, + .alloca => |*x| S.one(ctx, &x.size), + .load => |*x| S.one(ctx, &x.ptr), + .store => |*x| { + S.one(ctx, &x.ptr); + S.one(ctx, &x.val); + }, + .gep => |*x| { + S.one(ctx, &x.ptr); + try S.many(a, ctx, &x.indices); + }, + .atomicrmw => |*x| { + S.one(ctx, &x.ptr); + S.one(ctx, &x.val); + }, + .cmpxchg => |*x| { + S.one(ctx, &x.ptr); + S.one(ctx, &x.cmp); + S.one(ctx, &x.new); + }, + .@"unreachable" => {}, + .extractelement => |*x| { + S.one(ctx, &x.vec); + S.one(ctx, &x.index); + }, + .insertelement => |*x| { + S.one(ctx, &x.vec); + S.one(ctx, &x.val); + S.one(ctx, &x.index); + }, + } +} diff --git a/src/front/ast.zig b/src/front/ast.zig index bff7163..6b79a1d 100644 --- a/src/front/ast.zig +++ b/src/front/ast.zig @@ -51,6 +51,8 @@ pub const TypeRef = struct { /// `#pragma pack_matrix` in effect where the type was written (true: /// row_major): the orientation of a matrix declared without one. pack_matrix: ?bool = null, + /// `struct S`: declares S (at namespace scope) if it is not yet a type. + elaborated: bool = false, }; /// Storage classes, type qualifiers and parameter / interpolation diff --git a/src/front/parser.zig b/src/front/parser.zig index 1d88203..5e52e9e 100644 --- a/src/front/parser.zig +++ b/src/front/parser.zig @@ -20,7 +20,8 @@ const Loc = source.Loc; pub const Error = Allocator.Error || error{Syntax}; -const NameKind = enum { type, template_type, template_func, value }; +/// (`function`: a plain function, which may overload function templates.) +const NameKind = enum { type, template_type, template_func, value, function }; pub const Parser = struct { arena: Allocator, @@ -316,6 +317,14 @@ pub const Parser = struct { try p.scopes.items[p.scopes.items.len - 1].append(p.arena, name); } + /// Declares `name` in the outermost scope (under any inner entries). + fn declareGlobalName(p: *Parser, name: []const u8, kind: NameKind) Allocator.Error!void { + const gop = try p.names.getOrPut(p.arena, name); + if (!gop.found_existing) gop.value_ptr.* = .empty; + try gop.value_ptr.insert(p.arena, 0, kind); + try p.scopes.items[0].append(p.arena, name); + } + fn lookupName(p: *const Parser, name: []const u8) ?NameKind { const list = p.names.get(name) orelse return null; if (list.items.len == 0) return null; @@ -336,6 +345,10 @@ pub const Parser = struct { if (p.lookupName(name)) |k| { if (k == .template_type or k == .template_func) return true; if (k == .value) return false; + if (k == .function) { + for (p.names.get(name).?.items) |o| if (o == .template_func) return true; + return false; + } } // Builtin templates keep working when a same-named user type exists // in some namespace (the name table is not namespace-aware). @@ -347,6 +360,7 @@ pub const Parser = struct { fn scanType(p: *const Parser, start: usize) ?usize { var i = start; while (isTypeAttrWord(p.toks[i])) i += 1; + if ((p.toks[i].isIdent("struct") or p.toks[i].isIdent("class")) and p.toks[i + 1].kind == .identifier) i += 1; if (p.toks[i].isIdent("typename")) return p.scanDependentType(i + 1); if (p.toks[i].isIdent("unsigned") or p.toks[i].isIdent("signed")) { i += 1; @@ -555,6 +569,12 @@ pub const Parser = struct { } fn parseTypeInner(p: *Parser) Error!*ast.TypeRef { + // An elaborated type: `struct S` names S (declaring it if needed). + const elaborated = (p.atIdent("struct") or p.atIdent("class")) and p.peek(1).kind == .identifier and p.peek(2).kind != .l_brace and p.peek(2).kind != .colon; + if (elaborated) { + _ = p.advance(); + if (!p.isTypeName(p.tok().text)) try p.declareGlobalName(p.tok().text, .type); + } const start = p.tok(); if (p.eatIdent("typename")) { // Dependent name: `typename X::type`. @@ -586,7 +606,7 @@ pub const Parser = struct { } var args: []const ast.TemplateArg = &.{}; if (p.at(.less) and (p.forced_template or p.isTemplateName(name.last()))) args = try p.parseTemplateArgs(); - return p.mk(ast.TypeRef, .{ .loc = start.loc, .name = name, .args = args }); + return p.mk(ast.TypeRef, .{ .loc = start.loc, .name = name, .args = args, .elaborated = elaborated }); } /// A qualified name whose final part may carry template arguments. @@ -1269,7 +1289,7 @@ pub const Parser = struct { if (template_params.len > 0) { try p.declareNameOuter(name.last(), .template_func, true); } else if (ctx != .member) { - try p.declareName(name.last(), .value); + try p.declareName(name.last(), .function); } _ = try p.expect(.l_paren, "'('"); try p.pushScope(); diff --git a/src/front/preproc.zig b/src/front/preproc.zig index 210f86f..6675b7d 100644 --- a/src/front/preproc.zig +++ b/src/front/preproc.zig @@ -30,6 +30,7 @@ pub const Options = struct { /// SPIR-V 1.x of the target environment. spirv_minor: u32 = 0, enable_16bit: bool = false, + hlsl_version: u16 = 2021, }; const Builtin = enum { @@ -229,7 +230,10 @@ pub const Preprocessor = struct { \\#define __DXC_VERSION_MINOR 10 \\#define __DXC_VERSION_RELEASE 0 \\#define __DXC_VERSION_COMMITS 0 - \\#define __HLSL_VERSION 2021 + \\ + ); + try w.print("#define __HLSL_VERSION {d}\n", .{o.hlsl_version}); + try w.writeAll( \\#define __SHADER_STAGE_VERTEX 1 \\#define __SHADER_STAGE_PIXEL 0 \\#define __SHADER_STAGE_GEOMETRY 2 diff --git a/src/ir/ir.zig b/src/ir/ir.zig index 019fc35..7a50fdd 100644 --- a/src/ir/ir.zig +++ b/src/ir/ir.zig @@ -535,6 +535,9 @@ pub const Module = struct { resource_structs: bool = false, /// -enable-16bit-types: half and 16-bit integers are native types. native_16bit: bool = false, + /// Unroll small loops with a constant trip count too (DXIL with the + /// optimizer on, as dxc's loop unrolling does). + auto_unroll: bool = false, /// -Zpr: matrices that are structured buffer elements themselves /// (not fields, which carry their own orientation) are row_major. /// DXIL only: dxc's SPIR-V keeps those column_major. diff --git a/src/ir/layout.zig b/src/ir/layout.zig index 6591331..ba6af4b 100644 --- a/src/ir/layout.zig +++ b/src/ir/layout.zig @@ -169,9 +169,7 @@ fn structAlign(t: *const TypeTable, info: *const types.StructInfo, rules: Rules) } fn structSize(t: *const TypeTable, info: *const types.StructInfo, rules: Rules) Error!u32 { - var buf: [256]u32 = undefined; - if (info.fields.items.len > buf.len) return error.Unsupported; - const off = try layoutFields(t, info, rules, buf[0..info.fields.items.len]); + const off = try layoutFields(t, info, rules, null); return switch (rules) { .dx_legacy => off, // (Packed structs still round up to their widest component: a @@ -180,9 +178,9 @@ fn structSize(t: *const TypeTable, info: *const types.StructInfo, rules: Rules) }; } -/// Stores the offsets of `info`'s fields in `out`; returns where the last -/// one ends. -fn layoutFields(t: *const TypeTable, info: *const types.StructInfo, rules: Rules, out: []u32) Error!u32 { +/// Stores the offsets of `info`'s fields in `out` (if given); returns where +/// the last one ends. +fn layoutFields(t: *const TypeTable, info: *const types.StructInfo, rules: Rules, out: ?[]u32) Error!u32 { var off: u32 = 0; var first: usize = 0; if (info.bases.items.len > 0 and rules != .dx_legacy and rules != .dx_packed) { @@ -190,7 +188,7 @@ fn layoutFields(t: *const TypeTable, info: *const types.StructInfo, rules: Rules // its alignment); DXIL lays its fields out in place. const base = info.bases.items[0]; first = base.fields.items.len; - _ = try layoutFields(t, base, rules, out[0..first]); + _ = try layoutFields(t, base, rules, if (out) |o| o[0..first] else null); off = try structSize(t, base, rules); } // Explicit offsets (packoffset / register(cN)): the other members @@ -201,20 +199,20 @@ fn layoutFields(t: *const TypeTable, info: *const types.StructInfo, rules: Rules }; if (packed_end) |pe| off = @max(off, pe); var end: u32 = off; - for (info.fields.items[first..], out[first..]) |f, *o| { + for (info.fields.items[first..], first..) |f, i| { // (Resources in structs take no space in buffers.) - if (isOpaque(t, f.type)) { - o.* = off; - continue; - } - if (f.pack_offset) |po| { - o.* = po; - continue; - } - // [[vk::offset]] (SPIR-V only): later members continue from it. - o.* = if (f.vk_offset) |vo| vo else try place(t, off, f.type, f.row_major, rules); - off = o.* + try sizeOf(t, f.type, f.row_major, rules); - end = @max(end, off); + const at = if (isOpaque(t, f.type)) + off + else if (f.pack_offset) |po| + po + else at: { + // [[vk::offset]] (SPIR-V only): later members continue from it. + const o = if (f.vk_offset) |vo| vo else try place(t, off, f.type, f.row_major, rules); + off = o + try sizeOf(t, f.type, f.row_major, rules); + end = @max(end, off); + break :at o; + }; + if (out) |o| o[i] = at; } return @max(end, packed_end orelse 0); } diff --git a/src/ir/lower.zig b/src/ir/lower.zig index 3711239..93d4910 100644 --- a/src/ir/lower.zig +++ b/src/ir/lower.zig @@ -1026,6 +1026,15 @@ const Lowerer = struct { }, .conditional => |x| { const ty = try l.concrete(e.ty); + // HLSL 2018: both operands, then a (per-component) select. + if (l.s.opts.hlsl_version < 2021 and t.isNumeric(ty)) { + const cs = t.shape(x.cond.ty); + const cond_ty = if (cs != null and cs.?.kind != .scalar) try t.withComponent(ty, .bool) else try t.scalar(.bool); + const cond = try l.converted(x.cond, cond_ty); + const a = try l.converted(x.then, ty); + const b = try l.converted(x.@"else", ty); + return l.b.add(.{ .op = .{ .select = .{ .cond = cond, .t = a, .f = b } }, .ty = ty }); + } const tmp = try l.b.add(.{ .op = .local_var, .ty = ty, .ptr = .function }); const cond = try l.condition(x.cond); const then_b = try l.b.newBlock(); @@ -1072,6 +1081,9 @@ const Lowerer = struct { return l.b.load(p); }, .sizeof_type, .sizeof_expr, .is_same => { + // (Sema keeps the size; a template instance's type names + // no longer resolve here.) + if (e.kind == .sizeof_type and e.info != 0) return l.b.constInt(try l.concrete(e.ty), e.info - 1); if (l.s.evalInt(e)) |v| return l.b.constInt(try l.concrete(e.ty), v); return l.fail(e, "this expression"); }, @@ -1103,7 +1115,13 @@ const Lowerer = struct { _ = try l.rvalue(lhs); return l.rvalue(rhs); }, - .log_and, .log_or => { + .log_and, .log_or => if (l.s.opts.hlsl_version < 2021) { + // HLSL 2018: both operands, component-wise. + const ty = try l.concrete(e.ty); + const a = try l.converted(lhs, ty); + const b = try l.converted(rhs, ty); + return l.b.add(.{ .op = .{ .binary = .{ .op = if (op == .log_and) .log_and else .log_or, .lhs = a, .rhs = b } }, .ty = ty }); + } else { // Short-circuit (HLSL 2021: scalar operands). const bool_ty = try t.scalar(.bool); const tmp = try l.b.add(.{ .op = .local_var, .ty = bool_ty, .ptr = .function }); @@ -1756,6 +1774,12 @@ const Lowerer = struct { return l.variableLvalue(e, r.variable); }, .member => |m| { + // One component of a vector (atomics' `ref`, `B[i].x`). + if (l.s.resolution(e) == null and t.get(m.base.ty) == .vector) if (try swizzleComponents(l.arena, m.name)) |comps| if (comps.len == 1) { + const base = try l.lvalue(m.base); + const idx = try l.b.constInt(try t.scalar(.uint), comps[0]); + return l.b.add(.{ .op = .{ .access = .{ .base = base, .indices = try l.arena.dupe(Ref, &.{idx}) } }, .ty = e.ty, .ptr = l.b.f.inst(base).ptr }); + }; const r = l.s.resolution(e) orelse return l.fail(e, "this member"); // A static member through an object. if (r == .variable) return l.variableLvalue(e, r.variable); diff --git a/src/ir/opt.zig b/src/ir/opt.zig index def9e96..d602e4e 100644 --- a/src/ir/opt.zig +++ b/src/ir/opt.zig @@ -19,7 +19,7 @@ const Scalar = types.Scalar; pub fn run(a: Allocator, m: *ir.Module) Allocator.Error!void { for (m.functions.items) |f| { - try unrollLoops(a, m.types, f); + try unrollLoops(a, m.types, f, m.auto_unroll); try fold(a, m.types, f); } } @@ -432,6 +432,9 @@ pub fn fold(a: Allocator, t: *TypeTable, f: *ir.Function) Allocator.Error!void { const unroll_limit = 1024; /// Trip limit for loops unrolled only to make texel offsets constant. const auto_unroll_limit = 64; +/// Instructions a loop may grow to when unrolled for no other reason +/// than its constant trip count (`auto_unroll`). +const auto_unroll_budget = 2048; /// Evaluates scalar `r` with the induction variable `iv` holding `v`. fn eval(t: *TypeTable, f: *ir.Function, r: Ref, iv: Ref, v: ?Constant, depth: u32) ?Constant { @@ -449,7 +452,7 @@ fn eval(t: *TypeTable, f: *ir.Function, r: Ref, iv: Ref, v: ?Constant, depth: u3 }; } -fn unrollLoops(a: Allocator, t: *TypeTable, f: *ir.Function) Allocator.Error!void { +fn unrollLoops(a: Allocator, t: *TypeTable, f: *ir.Function, auto: bool) Allocator.Error!void { var kept: std.AutoHashMapUnmanaged(u32, void) = .empty; while (true) { const live = try reachable(a, f); @@ -470,7 +473,7 @@ fn unrollLoops(a: Allocator, t: *TypeTable, f: *ir.Function) Allocator.Error!voi break; } const h = pick orelse return; - if (!try unrollOne(a, t, f, h, sets.get(h).?, live)) try kept.put(a, h, {}); + if (!try unrollOne(a, t, f, h, sets.get(h).?, live, auto)) try kept.put(a, h, {}); } } @@ -518,7 +521,7 @@ fn hasTexelOffsets(t: *TypeTable, f: *ir.Function, set: []const bool) bool { return false; } -fn unrollOne(a: Allocator, t: *TypeTable, f: *ir.Function, h: u32, set: []const bool, live: []const bool) Allocator.Error!bool { +fn unrollOne(a: Allocator, t: *TypeTable, f: *ir.Function, h: u32, set: []const bool, live: []const bool, auto: bool) Allocator.Error!bool { const hb = f.blocks.items[h]; const lp = hb.merge.loop; if (lp.unroll == .dont) return false; @@ -614,7 +617,7 @@ fn unrollOne(a: Allocator, t: *TypeTable, f: *ir.Function, h: u32, set: []const var v = init orelse return false; const wanted = lp.unroll == .unroll or hasTexelOffsets(t, f, set); - if (!wanted) return false; + if (!wanted and !auto) return false; const limit: usize = if (lp.unroll == .unroll) unroll_limit else auto_unroll_limit; const cond = cb.term.cond_br.cond; var values: std.ArrayList(Constant) = .empty; @@ -625,6 +628,14 @@ fn unrollOne(a: Allocator, t: *TypeTable, f: *ir.Function, h: u32, set: []const try values.append(a, v); v = eval(t, f, step, iv, v, 0) orelse return false; } + // Otherwise only small loops: their size, unrolled, within a budget. + if (!wanted) { + var size: usize = 0; + for (f.blocks.items, 0..) |blk, bi| if (set[bi]) { + size += blk.insts.items.len + 1; + }; + if (values.items.len * size > auto_unroll_budget) return false; + } // The condition block is dropped: nothing else may use its values. { diff --git a/src/sema/intrinsics.zig b/src/sema/intrinsics.zig index 359442b..7febf4c 100644 --- a/src/sema/intrinsics.zig +++ b/src/sema/intrinsics.zig @@ -8,7 +8,8 @@ //! coerced into the group's class (`float_like`, `numeric`, `any_int`...), //! and the layout is taken from the declared dimensions (binding symbolic //! sizes like `c` and `r2` across arguments) or, for `<>`, from the -//! arguments. Candidates are ranked by total conversion cost. +//! arguments. Candidates are ranked by their worst conversion, then their +//! total conversion cost. const std = @import("std"); const Allocator = std.mem.Allocator; @@ -91,6 +92,17 @@ pub const Db = struct { return list.items; } + /// The conversion cost of the best overload of global intrinsic `name` + /// for `args`, or null if none fits (no diagnostics). + pub fn bestCost(db: *const Db, sema: anytype, name: []const u8, args: []const ArgInfo) !?u32 { + var best: ?u32 = null; + for (try db.candidates(sema.arena, "Intrinsics", name)) |ci| { + const m = try matchOne(sema, &table.intrinsics[ci], null, args, null) orelse continue; + if (best == null or m.cost < best.?) best = m.cost; + } + return best; + } + /// Resolve a call; reports a diagnostic and returns the error type when /// no overload matches. `sema` is the calling Sema (for conversions and /// diagnostics); `object` is the method's object type, if any. @@ -211,11 +223,13 @@ fn matchOne(sema: anytype, it: *const table.Intrinsic, object: ?TypeId, args: [] var bindings: Bindings = .{}; for (args[0..it.params.len], 1..) |a, i| { - if (!specs[i].any_layout) continue; + // (Also arguments whose layout links to a `<>` one.) + if (!specs[i].any_layout and !specs[layout_group[i]].any_layout) continue; const sh = t.shape(a.ty) orelse continue; if (bindings.any_shape == null or sh.count() > bindings.any_shape.?.count()) bindings.any_shape = sh; } - var cost: u32 = 0; + var sum: u32 = 0; + var worst: u32 = 0; const out_params = try sema.arena.alloc(bool, args.len); @memset(out_params, false); const param_types = try sema.arena.alloc(TypeId, args.len); @@ -230,13 +244,17 @@ fn matchOne(sema: anytype, it: *const table.Intrinsic, object: ?TypeId, args: [] param_types[ai] = if (pt == TypeTable.error_type) a.ty else pt; if (pt == TypeTable.error_type) continue; // unconstrained object / unknown class const c = sema.conversionCost(a.ty, pt) orelse return null; - cost += c; + // A `ref` argument (InterlockedAdd's destination) is the storage + // itself: its type must match. + if (s.qual == .ref and c != 0) return null; + sum += c; + worst = @max(worst, c); } // Return type. const ret = try paramType(sema, specs, 0, comp_group, layout_group, group_comp, &bindings, args, obj_elem, explicit) orelse return null; for (args[@min(args.len, it.params.len)..], @min(args.len, it.params.len)..) |a, ai| param_types[ai] = a.ty; // varargs - return .{ .ret = ret, .cost = cost, .out_params = out_params, .params = param_types }; + return .{ .ret = ret, .cost = Scalar.overloadCost(worst, sum), .out_params = out_params, .params = param_types }; } /// The concrete type of spec `i`, or null if the arguments cannot fit. diff --git a/src/sema/sema.zig b/src/sema/sema.zig index 21ebf91..78e1b30 100644 --- a/src/sema/sema.zig +++ b/src/sema/sema.zig @@ -25,6 +25,9 @@ pub const Options = struct { entry: ?[]const u8 = null, spirv: bool = false, enable_16bit: bool = false, + /// HLSL 2016-2018 (below 2021): `&&`, `||` and `?:` work component-wise + /// on vectors and evaluate both operands. + hlsl_version: u16 = 2021, /// Target shader model 6.x (long vectors need 6.9). sm_minor: u8 = 10, /// Library target (`lib_6_x`): exported functions are the roots of @@ -113,13 +116,20 @@ pub const Function = struct { param_vars: []?*Variable = &.{}, /// A function template instance's arguments. template_args: []const Bound = &.{}, + /// A method of a class template instance: its body, checked when the + /// method is first called (as C++ instantiates members). + pending: ?*const PendingBody = null, }; +pub const PendingBody = struct { f: *const ast.FuncDecl, scope: *Scope, strct: ?*types.StructInfo }; + /// A bound template argument. pub const Bound = types.TemplateArg; pub const FuncSet = struct { funcs: std.ArrayList(*Function) = .empty, + /// Function templates of the same name, overloading with `funcs`. + templates: ?*TemplateSet = null, }; pub const Symbol = union(enum) { @@ -309,8 +319,15 @@ pub const Sema = struct { const set = blk: { if (s.scope.syms.get(name)) |sym| switch (sym) { .template => |t| break :blk t, - // Plain functions take precedence over templates. - .functions => return, + // Function templates overload the plain functions. + .functions => |fs| { + if (d.kind != .func) return; + if (fs.templates == null) { + fs.templates = try s.arena.create(TemplateSet); + fs.templates.?.* = .{}; + } + break :blk fs.templates.?; + }, else => {}, }; const set = try s.arena.create(TemplateSet); @@ -740,18 +757,74 @@ pub const Sema = struct { /// A call to a function template: deduce, instantiate (once per /// argument list), then resolve as an ordinary call. fn callTemplate(s: *Sema, e: *ast.Expr, tset: *TemplateSet, explicit: []const ast.TemplateArg, args: []const intrinsics.ArgInfo, callee: *ast.Expr, owner: ?*types.StructInfo) Allocator.Error!TypeId { - // Every overload that deduces contributes its instance. - const all = try s.arena.create(FuncSet); - all.* = .{}; - for (tset.decls.items) |d| { - if (d.kind != .func) continue; - const inst = try s.instantiateCall(d, explicit, args, callee, tset.decls.items.len > 1, owner); - if (inst) |set| try all.funcs.appendSlice(s.arena, set.funcs.items); - } + const all = try s.templateInstances(tset, explicit, args, callee, owner, tset.decls.items.len > 1); if (all.funcs.items.len == 0) { s.err(callee.loc, "this call to a function template is not supported yet", .{}); return TypeTable.error_type; } + return s.resolveInstances(e, all, args, callee); + } + + /// The instances of `tset`'s function templates that deduce for `args`. + fn templateInstances(s: *Sema, tset: *TemplateSet, explicit: []const ast.TemplateArg, args: []const intrinsics.ArgInfo, callee: *ast.Expr, owner: ?*types.StructInfo, quiet: bool) Allocator.Error!*FuncSet { + const all = try s.arena.create(FuncSet); + all.* = .{}; + for (tset.decls.items) |d| { + if (d.kind != .func) continue; + // (Not with too many or too few arguments.) + const ps = d.kind.func.params; + var required: usize = 0; + for (ps) |p| { + if (p.init == null) required += 1; + } + if (args.len > ps.len or args.len < required) continue; + const inst = try s.instantiateCall(d, explicit, args, callee, quiet, owner); + if (inst) |set| try all.funcs.appendSlice(s.arena, set.funcs.items); + } + return all; + } + + /// A call to plain functions and function templates of one name: the + /// templates' instances win only by a lower cost (as in C++, a tie goes + /// to the plain function). + fn callOverloads(s: *Sema, e: *ast.Expr, set: *FuncSet, tset: *TemplateSet, args: []const intrinsics.ArgInfo, callee: *ast.Expr) Allocator.Error!Typed { + const insts = try s.templateInstances(tset, &.{}, args, callee, null, true); + const both = try s.arena.create(FuncSet); + both.* = .{}; + try both.funcs.appendSlice(s.arena, set.funcs.items); + try both.funcs.appendSlice(s.arena, insts.funcs.items); + if (try s.intrinsicFitsBetter(callee, both, args)) return s.intrinsicCall(e, callee, callee.kind.name.parts[0], args, &.{}); + var plain: ?u32 = null; + for (set.funcs.items) |f| { + const cost = s.callCost(f, args) orelse continue; + if (plain == null or cost < plain.?) plain = cost; + } + var templ: ?u32 = null; + for (insts.funcs.items) |f| { + const cost = s.callCost(f, args) orelse continue; + if (templ == null or cost < templ.?) templ = cost; + } + if (templ != null and (plain == null or templ.? < plain.?)) return rvalue(try s.resolveInstances(e, insts, args, callee)); + return rvalue(s.resolveUserCall(e, set, args, callee)); + } + + /// Whether a call by an intrinsic's name to user functions `set` (or + /// template instances) goes to the intrinsic: when it fits better, or + /// when none of them fits (a tie goes to the user function). + fn intrinsicFitsBetter(s: *Sema, callee: *ast.Expr, set: *FuncSet, args: []const intrinsics.ArgInfo) Allocator.Error!bool { + if (callee.kind != .name or callee.kind.name.parts.len != 1) return false; + const name = callee.kind.name.parts[0]; + if (!s.intrinsic_db.has(name, s.opts.spirv)) return false; + var user: ?u32 = null; + for (set.funcs.items) |f| { + const cost = s.callCost(f, args) orelse continue; + if (user == null or cost < user.?) user = cost; + } + const ic = try s.intrinsic_db.bestCost(s, name, args) orelse return user == null; + return user == null or ic < user.?; + } + + fn resolveInstances(s: *Sema, e: *ast.Expr, all: *FuncSet, args: []const intrinsics.ArgInfo, callee: *ast.Expr) Allocator.Error!TypeId { // A template declared, then defined: its definition's instance. var kept: usize = 0; for (all.funcs.items) |a| { @@ -1279,6 +1352,14 @@ pub const Sema = struct { // `S::type` where the instance has no such member (the // parser cannot tell); other unknown names were reported there. if (t.name.parts.len > 1 and t.name.args.len > 0) s.err(t.loc, "no type named '{s}' in this template instance", .{n}); + // `struct S` before any declaration of S: forward-declares it. + if (t.elaborated and t.name.parts.len == 1 and s.global.syms.get(n) == null) { + const info = try s.arena.create(types.StructInfo); + info.* = .{ .name = n, .scopes = &.{} }; + const ty = try s.types.intern(.{ .@"struct" = info }); + try s.global.syms.put(s.arena, n, .{ .type = ty }); + return ty; + } return TypeTable.error_type; } @@ -2300,10 +2381,16 @@ pub const Sema = struct { // Unsized arrays take their size from the initializer. if (v.init) |init_e| if (!is_auto) { if (s.types.get(ty) == .array and s.types.get(ty).array.len == 0 and init_e.kind == .init_list) { + // (Its items typed first: their sizes count.) + _ = try s.checkInitializer(TypeTable.error_type, init_e); const elem = s.types.get(ty).array.elem; const elem_count = s.types.componentCount(elem) orelse 1; const flat = s.flatCount(init_e); ty = try s.types.array(elem, @intCast(@max(1, (flat + elem_count - 1) / @max(1, elem_count)))); + variable.type = ty; + init_e.ty = ty; + if (!s.checkInitCount(ty, init_e)) variable.type = TypeTable.error_type; + return; } variable.type = ty; // Uses of a declaration with a bad initializer are not @@ -2395,15 +2482,17 @@ pub const Sema = struct { // Add to the overload set, matching an earlier prototype if any. const set = blk: { + var templates: ?*TemplateSet = null; if (s.scope.syms.get(name)) |sym| { if (sym == .functions) break :blk sym.functions; if (sym != .template) { s.err(d.loc, "redefinition of '{s}' as a different kind of symbol", .{name}); return; } + if (sym.template.decls.items.len > 0 and sym.template.decls.items[0].kind == .func) templates = sym.template; } const set = try s.arena.create(FuncSet); - set.* = .{}; + set.* = .{ .templates = templates }; try s.declare(name, .{ .functions = set }, d.loc); break :blk set; }; @@ -2525,6 +2614,26 @@ pub const Sema = struct { } fn funcBody(s: *Sema, func: *Function, f: *const ast.FuncDecl) Allocator.Error!void { + if (f.body != null and func.owner != null and s.instance_depth > 0 and s.current_fn == null) { + const p = try s.arena.create(PendingBody); + p.* = .{ .f = f, .scope = s.scope, .strct = s.current_struct }; + func.pending = p; + return; + } + return s.checkBody(func, f); + } + + /// Checks a pending method body (see Function.pending). + fn ensureBody(s: *Sema, func: *Function) Allocator.Error!void { + const p = func.pending orelse return; + func.pending = null; + const ctx = s.enterInstance(p.scope); + defer s.leaveInstance(ctx); + s.current_struct = p.strct; + try s.checkBody(func, p.f); + } + + fn checkBody(s: *Sema, func: *Function, f: *const ast.FuncDecl) Allocator.Error!void { const params = func.params; const body = f.body orelse return; const saved_fn = s.current_fn; @@ -2799,7 +2908,36 @@ pub const Sema = struct { } } + /// Whether `name` is declared in the current function (its parameters + /// and blocks). + fn inFunctionScope(s: *Sema, name: []const u8) bool { + var sc: ?*Scope = s.scope; + while (sc) |c| : (sc = c.parent) { + if (c.kind != .block and c.kind != .function) return false; + if (c.syms.contains(name)) return true; + if (c.kind == .function) return false; + } + return false; + } + + /// A field (or bitfield) of the method's struct named `name`. + fn thisField(s: *Sema, e: *ast.Expr, info: *types.StructInfo, name: []const u8) Allocator.Error!?Typed { + for (info.fields.items, 0..) |f, k| if (std.mem.eql(u8, f.name, name)) { + s.record(e, .{ .this_field = @intCast(k) }); + return .{ .ty = f.type, .lvalue = true }; + }; + if (findBitfield(info, name)) |bf| { + s.record(e, .{ .this_bitfield = bf }); + return .{ .ty = bf.type, .lvalue = true }; + } + return null; + } + fn nameExpr(s: *Sema, e: *ast.Expr, n: ast.Name) Allocator.Error!Typed { + // Inside methods, fields come before names outside the function. + if (n.parts.len == 1 and s.current_struct != null and !s.inFunctionScope(n.parts[0])) { + if (try s.thisField(e, s.current_struct.?, n.parts[0])) |t| return t; + } if (s.lookupName(n)) |sym| switch (sym) { .variable => |v| { s.record(e, .{ .variable = v }); @@ -2827,16 +2965,7 @@ pub const Sema = struct { } // Struct fields and methods used unqualified inside methods. if (s.current_struct) |info| { - if (n.parts.len == 1) { - for (info.fields.items, 0..) |f, k| if (std.mem.eql(u8, f.name, n.parts[0])) { - s.record(e, .{ .this_field = @intCast(k) }); - return .{ .ty = f.type, .lvalue = true }; - }; - if (findBitfield(info, n.parts[0])) |bf| { - s.record(e, .{ .this_bitfield = bf }); - return .{ .ty = bf.type, .lvalue = true }; - } - } + if (n.parts.len == 1) if (try s.thisField(e, info, n.parts[0])) |t| return t; } if (n.parts.len > 1) { for (n.parts[0 .. n.parts.len - 1], 0..) |part, i| { @@ -3027,6 +3156,10 @@ pub const Sema = struct { const ls = s.types.shape(lt) orelse return s.invalidOperands(loc, lt, rt); const rs = s.types.shape(rt) orelse return s.invalidOperands(loc, lt, rt); if (logical) { + if (s.opts.hlsl_version < 2021 and (ls.kind != .scalar or rs.kind != .scalar)) { + const sh = TypeTable.combineDimensions(ls, rs) orelse return s.invalidOperands(loc, lt, rt); + return try s.types.withShape(.bool, sh); + } if (ls.kind != .scalar or rs.kind != .scalar) { s.err(loc, "operands for short-circuiting logical binary operator must be scalar, for non-scalar types use '{s}'", .{if (op == .log_and) "and" else "or"}); return null; @@ -3160,6 +3293,7 @@ pub const Sema = struct { const c = try s.expr(cond); const t = try s.expr(then); const f = try s.expr(else_e); + if (s.opts.hlsl_version < 2021) return s.legacyConditional(e, c, t, f); if (c.ty != TypeTable.error_type) { if (s.types.shape(c.ty)) |sh| { if (sh.kind != .scalar) { @@ -3177,6 +3311,29 @@ pub const Sema = struct { return err_typed; } + /// HLSL 2018's `?:`: a vector condition selects per component, and the + /// result takes the shape of all three operands. + fn legacyConditional(s: *Sema, e: *ast.Expr, c: Typed, t: Typed, f: Typed) Allocator.Error!Typed { + if (c.ty == TypeTable.error_type or t.ty == TypeTable.error_type or f.ty == TypeTable.error_type) return err_typed; + const r = if (t.ty == f.ty) t.ty else if (s.types.isNumeric(t.ty) and s.types.isNumeric(f.ty)) + s.arithmetic(e, t.ty, f.ty) orelse return err_typed + else { + s.err(e.loc, "incompatible operand types ('{s}' and '{s}')", .{ s.typeName(t.ty), s.typeName(f.ty) }); + return err_typed; + }; + const cs = s.types.shape(c.ty) orelse return rvalue(r); + if (cs.kind == .scalar) return rvalue(r); + const rs = s.types.shape(r) orelse { + s.err(e.loc, "incompatible operand types ('{s}' and '{s}')", .{ s.typeName(c.ty), s.typeName(r) }); + return err_typed; + }; + const sh = TypeTable.combineDimensions(cs, rs) orelse { + s.err(e.loc, "incompatible operand types ('{s}' and '{s}')", .{ s.typeName(c.ty), s.typeName(r) }); + return err_typed; + }; + return rvalue(try s.types.withShape(s.types.component(r).?, sh)); + } + /// `sizeof(ty)` plus one, or zero when it has no size: HLSL sizes are /// tightly packed at scalar alignment. A struct that had errors has /// size 1, as in clang. @@ -3520,7 +3677,13 @@ pub const Sema = struct { }; for (arg_types) |a| if (a.ty == TypeTable.error_type) return err_typed; switch (target) { - .functions => |set| return rvalue(s.resolveUserCall(e, set, arg_types, callee)), + .functions => |set| if (set.templates) |tset| { + if (template_args.len > 0) return rvalue(try s.callTemplate(e, tset, template_args, arg_types, callee, null)); + return s.callOverloads(e, set, tset, arg_types, callee); + } else { + if (try s.intrinsicFitsBetter(callee, set, arg_types)) return s.intrinsicCall(e, callee, callee.kind.name.parts[0], arg_types, template_args); + return rvalue(s.resolveUserCall(e, set, arg_types, callee)); + }, .template => |set| { // A member template called unqualified from a method. var owner: ?*types.StructInfo = null; @@ -3530,15 +3693,13 @@ pub const Sema = struct { owner = info; }; }; + if (template_args.len == 0 and owner == null) { + const insts = try s.templateInstances(set, &.{}, arg_types, callee, null, true); + if (try s.intrinsicFitsBetter(callee, insts, arg_types)) return s.intrinsicCall(e, callee, callee.kind.name.parts[0], arg_types, template_args); + } return rvalue(try s.callTemplate(e, set, template_args, arg_types, callee, owner)); }, - .intrinsic => |name| { - var explicit: ?TypeId = null; - if (template_args.len > 0) explicit = try s.typeArg(template_args[0]); - const r = try s.intrinsic_db.resolve(s, e.loc, if (s.opts.spirv and isVkQualified(callee)) "VkIntrinsics" else "Intrinsics", name, null, arg_types, explicit); - if (r.ok) s.record(e, .{ .intrinsic = .{ .index = r.index, .params = r.params } }); - return rvalue(r.ret); - }, + .intrinsic => |name| return s.intrinsicCall(e, callee, name, arg_types, template_args), .method => |m| { switch (s.types.get(m.object)) { .@"struct" => |info| { @@ -3592,33 +3753,44 @@ pub const Sema = struct { return null; } + fn intrinsicCall(s: *Sema, e: *ast.Expr, callee: *ast.Expr, name: []const u8, arg_types: []const intrinsics.ArgInfo, template_args: []const ast.TemplateArg) Allocator.Error!Typed { + var explicit: ?TypeId = null; + if (template_args.len > 0) explicit = try s.typeArg(template_args[0]); + const r = try s.intrinsic_db.resolve(s, e.loc, if (s.opts.spirv and isVkQualified(callee)) "VkIntrinsics" else "Intrinsics", name, null, arg_types, explicit); + if (r.ok) s.record(e, .{ .intrinsic = .{ .index = r.index, .params = r.params } }); + return rvalue(r.ret); + } + + /// The cost of calling `f` with `args`, or null if it cannot take them. + fn callCost(s: *Sema, f: *const Function, args: []const intrinsics.ArgInfo) ?u32 { + if (args.len > f.params.len) return null; + var required: usize = 0; + for (f.params) |p| { + if (!p.has_default) required += 1; + } + if (args.len < required) return null; + var sum: u32 = 0; + var worst: u32 = 0; + for (args, 0..) |a, i| { + const p = f.params[i]; + var c = s.conversionCost(a.ty, p.type) orelse return null; + // groupshared parameters bind only groupshared arguments + // (and are preferred for them). + if (p.groupshared and !a.groupshared) return null; + if (a.groupshared and !p.groupshared) c += 4; + sum += c; + worst = @max(worst, c); + } + return types.Scalar.overloadCost(worst, sum); + } + /// Overload resolution among user functions by conversion cost. fn resolveUserCall(s: *Sema, e: *ast.Expr, set: *FuncSet, args: []const intrinsics.ArgInfo, callee: *ast.Expr) TypeId { var best: ?*Function = null; var best_cost: u32 = std.math.maxInt(u32); var ambiguous = false; for (set.funcs.items) |f| { - if (args.len > f.params.len) continue; - var required: usize = 0; - for (f.params) |p| { - if (!p.has_default) required += 1; - } - if (args.len < required) continue; - var cost: u32 = 0; - var ok = true; - for (args, 0..) |a, i| { - const p = f.params[i]; - const c = s.conversionCost(a.ty, p.type); - // groupshared parameters bind only groupshared arguments - // (and are preferred for them). - if (c == null or (p.groupshared and !a.groupshared)) { - ok = false; - break; - } - cost += c.?; - if (a.groupshared and !p.groupshared) cost += 1; - } - if (!ok) continue; + const cost = s.callCost(f, args) orelse continue; if (cost < best_cost) { best = f; best_cost = cost; @@ -3641,6 +3813,7 @@ pub const Sema = struct { } if (s.current_fn) |caller| caller.callees.append(s.arena, f) catch {}; s.record(e, .{ .function = f }); + s.ensureBody(f) catch {}; return f.ret; } @@ -3658,24 +3831,24 @@ pub const Sema = struct { if (tt == .@"enum" and (tt.@"enum".scoped or ft == .@"enum")) return null; // needs a cast const fs = s.types.shape(from).?; const ts = s.types.shape(to).?; - var cost: u32 = if (fc.? == tc.?) 0 else if (fc.?.isLiteral()) 1 else if (fc.?.isFloat() == tc.?.isFloat() and tc.?.rank() > fc.?.rank()) 2 else 3; + var cost: u32 = fc.?.conversionCost(tc.?); cost += switch (TypeTable.convertDimensions(ts, fs) orelse return null) { .identity => 0, - .scalar => 1, // float1 -> float - .splat => if (ts.count() == 1) 1 else 4, - .conversion => 6, // vector <-> matrix of the same size - .truncation => if (ts.count() == 1) 10 else 8, + .scalar => 4, // float1 -> float + .splat => if (ts.count() == 1) 4 else 16, + .conversion => 24, // vector <-> matrix of the same size + .truncation => if (ts.count() == 1) 40 else 32, }; return cost; } // A descriptor heap element converts to any resource or sampler. if (ft == .dynamic_resource and (tt == .resource or tt == .sampler)) return 0; // Derived structs convert to their bases. - if (ft == .@"struct" and tt == .@"struct" and derivesFrom(ft.@"struct", tt.@"struct")) return 2; + if (ft == .@"struct" and tt == .@"struct" and derivesFrom(ft.@"struct", tt.@"struct")) return 8; // int -> unscoped enum (dxc accepts it). - if (tt == .@"enum" and !tt.@"enum".scoped and s.types.isNumeric(from) and ft != .@"enum") return 3; + if (tt == .@"enum" and !tt.@"enum".scoped and s.types.isNumeric(from) and ft != .@"enum") return 12; // ConstantBuffer / TextureBuffer are usable as an S value. - if (ft == .resource and (ft.resource.kind == .constant_buffer or ft.resource.kind == .texture_buffer) and ft.resource.elem == to) return 1; + if (ft == .resource and (ft.resource.kind == .constant_buffer or ft.resource.kind == .texture_buffer) and ft.resource.elem == to) return 4; return switch (ft) { .array => |fa| switch (tt) { .array => |ta| if ((ta.len == fa.len or ta.len == 0) and s.conversionCost(fa.elem, ta.elem) == 0) 0 else null, @@ -3730,18 +3903,7 @@ pub const Sema = struct { if (item.kind != .init_list) _ = try s.expr(item) else _ = try s.checkInitializer(TypeTable.error_type, item); } e.ty = target; - if (target == TypeTable.error_type) return true; - const want = if (s.types.get(target) == .string) 1 else s.types.componentCount(target) orelse return true; - const have = s.flatCount(e); - if (have != want and have != 0) { - if (have < want) { - s.err(e.loc, "too few elements in vector initialization (expected {d} element{s}, have {d})", .{ want, if (want == 1) "" else "s", have }); - } else { - s.err(e.loc, "too many elements in vector initialization (expected {d} element{s}, have {d})", .{ want, if (want == 1) "" else "s", have }); - } - return false; - } - return true; + return s.checkInitCount(target, e); } const t = try s.expr(e); if (t.callee != null and t.ty == TypeTable.error_type) { @@ -3757,6 +3919,23 @@ pub const Sema = struct { return false; } + /// An initializer list (its items typed) has as many components as + /// `target`. + fn checkInitCount(s: *Sema, target: TypeId, e: *ast.Expr) bool { + if (target == TypeTable.error_type) return true; + const want = if (s.types.get(target) == .string) 1 else s.types.componentCount(target) orelse return true; + const have = s.flatCount(e); + if (have != want and have != 0) { + if (have < want) { + s.err(e.loc, "too few elements in vector initialization (expected {d} element{s}, have {d})", .{ want, if (want == 1) "" else "s", have }); + } else { + s.err(e.loc, "too many elements in vector initialization (expected {d} element{s}, have {d})", .{ want, if (want == 1) "" else "s", have }); + } + return false; + } + return true; + } + /// dxc's err_hlsl_cannot_convert: "implicitly" only when an explicit /// cast would work. fn convertError(s: *Sema, loc: Loc, from: TypeId, to: TypeId) void { diff --git a/src/sema/types.zig b/src/sema/types.zig index 18acfc9..2f9afc3 100644 --- a/src/sema/types.zig +++ b/src/sema/types.zig @@ -97,6 +97,45 @@ pub const Scalar = enum(u8) { }; } + /// The cost of converting a component from `a` to `b` in overload + /// resolution (lower is better), ordered as dxc ranks them: a literal to + /// its own kind, widening within a kind, then a change of sign, then + /// integer to bool, then narrowing or a change of kind, and integer to + /// float last. + pub fn conversionCost(a: Scalar, b: Scalar) u32 { + if (a == b) return 0; + const l = a.props(); + const r = b.props(); + if (a.isLiteral()) { + // (An integer literal takes bool before float.) + if (r.p.floating == l.p.floating and b != .bool) return if (r.p.min_precision) 5 else 4; + return if (b == .bool and !l.p.floating) 6 else 7; + } + if (l.p.floating and r.p.floating) { + if (r.bits < l.bits) return 12; + // `half` (32-bit, partial precision) ranks after float. + return if (r.p.partial_precision) 9 else 8; + } + if (a.isInt() and b.isInt()) { + const same_sign = l.p.unsigned == r.p.unsigned; + if (r.bits < l.bits) return if (same_sign and !l.p.unsigned) 10 else 12; + if (same_sign) return 8; + // A change of sign: to signed best at the same width, to + // unsigned best wider. + return if ((r.bits == l.bits) == l.p.unsigned) 9 else 10; + } + // (From 64 bits, bool ranks with the narrowing to 32.) + if (a.isInt() and b == .bool) return if (l.bits <= 32) 11 else if (l.p.unsigned) 12 else 10; + if (a.isInt() and r.p.floating) return 13; + return 12; + } + + /// An overload candidate's cost from its arguments' conversion costs: + /// dxc ranks candidates by their worst conversion, then by all of them. + pub fn overloadCost(worst: u32, sum: u32) u32 { + return worst << 16 | @min(sum, 0xffff); + } + /// The component type of a binary operation on `a` and `b`: a port of /// dxc's CombineBasicTypes. pub fn combine(a: Scalar, b: Scalar) Scalar { From 72f176084417b6a8b255d887fff93234aa2701e2 Mon Sep 17 00:00:00 2001 From: peterino2 Date: Tue, 3 Nov 2026 00:12:50 -0800 Subject: [PATCH 2/2] Unroll small loops only, and SCCP in reverse postorder The Unreal work unrolled far more than dxc does: the IR unrolled any small constant-count loop, and the DXIL unroller any loop of up to 256 trips. On Glide's GlimmerProbeTrace and GlimmerSHUpdate compiles took 10-17x longer and DXIL grew to 470 KB (dxc: 155 KB), so Glide's replayed compiles took 2.7x as long as with main. - the IR's automatic unrolling is gone again (it did little for Unreal) - DXIL unrolls a loop only when unrolled it stays within 300 instructions, as dxc unrolls only small loops without [unroll] - SCCP visits blocks in reverse postorder, so it settles in a few passes Glide, against main (bb942b0): 24 threads 1.36 s vs 1.25 s, serial sum 13.2 s vs 11.8 s, DXIL 58.1 MB vs 61.4 MB. Unreal's corpus still compiles, validates, and reflects no UAV dxc leaves out. --- src/compile.zig | 1 - src/dxil/sccp.zig | 58 +++++++++++++++++++++++++++++++++++++++++---- src/dxil/unroll.zig | 9 ++++--- src/ir/ir.zig | 3 --- src/ir/opt.zig | 21 ++++------------ 5 files changed, 65 insertions(+), 27 deletions(-) diff --git a/src/compile.zig b/src/compile.zig index 6edca7d..9fbc17a 100644 --- a/src/compile.zig +++ b/src/compile.zig @@ -510,7 +510,6 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void { if (opts.parse or opts.sema) return; if (profile == null) return ctx.fail("missing -T ", .{}); if (module) |*m| { - m.auto_unroll = !opts.spirv and !opts.no_opt and opts.opt_level != .od; try zdxc.ir.opt.run(arena, m); if (opts.spirv) { zdxc.ir.split_resources.run(arena, m, &diags) catch |err| switch (err) { diff --git a/src/dxil/sccp.zig b/src/dxil/sccp.zig index e71c20e..b8dbf0c 100644 --- a/src/dxil/sccp.zig +++ b/src/dxil/sccp.zig @@ -79,6 +79,26 @@ fn isTerminator(inst: Inst) bool { }; } +/// A terminator's successor blocks. +const Succs = struct { + br: [2]u32 = undefined, + sw: ?@FieldType(@FieldType(Inst, "op"), "switch") = null, + len: usize = 0, + + fn get(s: Succs, k: usize) u32 { + if (s.sw) |sw| return if (k == 0) sw.default else sw.cases[k - 1].block; + return s.br[k]; + } +}; + +fn successors(term: Inst) Succs { + return switch (term.op) { + .br => |br| if (br.@"else") |e| .{ .br = .{ br.then, e }, .len = 2 } else .{ .br = .{ br.then, 0 }, .len = 1 }, + .@"switch" => |sw| .{ .sw = sw, .len = 1 + sw.cases.len }, + else => .{}, + }; +} + /// Runs the propagation on `func`; true if it changed anything. pub fn run(a: Allocator, m: *module.Module, func: u32) Allocator.Error!bool { const f = &m.functions.items[func]; @@ -217,15 +237,45 @@ pub fn run(a: Allocator, m: *module.Module, func: u32) Allocator.Error!bool { }; const ev: Eval = .{ .m = m, .f = f, .lat = lat }; - // Iterated to the fixed point in block order (the lattice is three - // levels deep, so this ends quickly). + // Blocks in reverse postorder: definitions before uses except round + // loops, so the fixed point takes a few passes (the lattice is three + // levels deep). + var rpo: std.ArrayList(u32) = .empty; + { + var post: std.ArrayList(u32) = .empty; + const seen = try a.alloc(bool, nb); + @memset(seen, false); + const Fr = struct { b: u32, next: u32 }; + var stack: std.ArrayList(Fr) = .empty; + try stack.append(a, .{ .b = 0, .next = 0 }); + seen[0] = true; + while (stack.items.len > 0) { + const top = &stack.items[stack.items.len - 1]; + const succs = successors(insts[block_start[top.b + 1] - 1]); + if (top.next < succs.len) { + const t = succs.get(top.next); + top.next += 1; + if (!seen[t]) { + seen[t] = true; + try stack.append(a, .{ .b = t, .next = 0 }); + } + } else { + try post.append(a, top.b); + _ = stack.pop(); + } + } + var k = post.items.len; + while (k > 0) { + k -= 1; + try rpo.append(a, post.items[k]); + } + } var changed = true; var rounds: u32 = 0; while (changed) : (rounds += 1) { if (rounds > 1000) return false; changed = false; - for (0..nb) |bb| { - const b: u32 = @intCast(bb); + for (rpo.items) |b| { if (!exec[b]) continue; for (block_start[b]..block_start[b + 1]) |ii| { const i: u32 = @intCast(ii); diff --git a/src/dxil/unroll.zig b/src/dxil/unroll.zig index 7f0a5ba..cc01607 100644 --- a/src/dxil/unroll.zig +++ b/src/dxil/unroll.zig @@ -23,9 +23,12 @@ const Edge = @typeInfo(@FieldType(@FieldType(@FieldType(Inst, "op"), "phi"), "in const none = std.math.maxInt(u32); -/// Most iterations unrolled, and most instructions one function may grow -/// by. +/// Most iterations unrolled, most instructions one loop may grow to +/// unrolled (small loops only, as dxc's full unrolling of loops without +/// [unroll]: larger ones cost compile time and code size for little), and +/// most one function may grow by. const max_trips = 256; +const max_loop_growth = 300; const max_growth = 65536; /// Unrolls the qualifying loops of `func`, innermost first; true if any. @@ -472,7 +475,7 @@ fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried: } const trips = states.items.len; const growth = (trips + 1) * size; - if (growth > budget.*) continue; + if (growth > max_loop_growth or growth > budget.*) continue; budget.* -= growth; try states.append(a, state); // the last pass, up to the exit diff --git a/src/ir/ir.zig b/src/ir/ir.zig index 7a50fdd..019fc35 100644 --- a/src/ir/ir.zig +++ b/src/ir/ir.zig @@ -535,9 +535,6 @@ pub const Module = struct { resource_structs: bool = false, /// -enable-16bit-types: half and 16-bit integers are native types. native_16bit: bool = false, - /// Unroll small loops with a constant trip count too (DXIL with the - /// optimizer on, as dxc's loop unrolling does). - auto_unroll: bool = false, /// -Zpr: matrices that are structured buffer elements themselves /// (not fields, which carry their own orientation) are row_major. /// DXIL only: dxc's SPIR-V keeps those column_major. diff --git a/src/ir/opt.zig b/src/ir/opt.zig index d602e4e..def9e96 100644 --- a/src/ir/opt.zig +++ b/src/ir/opt.zig @@ -19,7 +19,7 @@ const Scalar = types.Scalar; pub fn run(a: Allocator, m: *ir.Module) Allocator.Error!void { for (m.functions.items) |f| { - try unrollLoops(a, m.types, f, m.auto_unroll); + try unrollLoops(a, m.types, f); try fold(a, m.types, f); } } @@ -432,9 +432,6 @@ pub fn fold(a: Allocator, t: *TypeTable, f: *ir.Function) Allocator.Error!void { const unroll_limit = 1024; /// Trip limit for loops unrolled only to make texel offsets constant. const auto_unroll_limit = 64; -/// Instructions a loop may grow to when unrolled for no other reason -/// than its constant trip count (`auto_unroll`). -const auto_unroll_budget = 2048; /// Evaluates scalar `r` with the induction variable `iv` holding `v`. fn eval(t: *TypeTable, f: *ir.Function, r: Ref, iv: Ref, v: ?Constant, depth: u32) ?Constant { @@ -452,7 +449,7 @@ fn eval(t: *TypeTable, f: *ir.Function, r: Ref, iv: Ref, v: ?Constant, depth: u3 }; } -fn unrollLoops(a: Allocator, t: *TypeTable, f: *ir.Function, auto: bool) Allocator.Error!void { +fn unrollLoops(a: Allocator, t: *TypeTable, f: *ir.Function) Allocator.Error!void { var kept: std.AutoHashMapUnmanaged(u32, void) = .empty; while (true) { const live = try reachable(a, f); @@ -473,7 +470,7 @@ fn unrollLoops(a: Allocator, t: *TypeTable, f: *ir.Function, auto: bool) Allocat break; } const h = pick orelse return; - if (!try unrollOne(a, t, f, h, sets.get(h).?, live, auto)) try kept.put(a, h, {}); + if (!try unrollOne(a, t, f, h, sets.get(h).?, live)) try kept.put(a, h, {}); } } @@ -521,7 +518,7 @@ fn hasTexelOffsets(t: *TypeTable, f: *ir.Function, set: []const bool) bool { return false; } -fn unrollOne(a: Allocator, t: *TypeTable, f: *ir.Function, h: u32, set: []const bool, live: []const bool, auto: bool) Allocator.Error!bool { +fn unrollOne(a: Allocator, t: *TypeTable, f: *ir.Function, h: u32, set: []const bool, live: []const bool) Allocator.Error!bool { const hb = f.blocks.items[h]; const lp = hb.merge.loop; if (lp.unroll == .dont) return false; @@ -617,7 +614,7 @@ fn unrollOne(a: Allocator, t: *TypeTable, f: *ir.Function, h: u32, set: []const var v = init orelse return false; const wanted = lp.unroll == .unroll or hasTexelOffsets(t, f, set); - if (!wanted and !auto) return false; + if (!wanted) return false; const limit: usize = if (lp.unroll == .unroll) unroll_limit else auto_unroll_limit; const cond = cb.term.cond_br.cond; var values: std.ArrayList(Constant) = .empty; @@ -628,14 +625,6 @@ fn unrollOne(a: Allocator, t: *TypeTable, f: *ir.Function, h: u32, set: []const try values.append(a, v); v = eval(t, f, step, iv, v, 0) orelse return false; } - // Otherwise only small loops: their size, unrolled, within a budget. - if (!wanted) { - var size: usize = 0; - for (f.blocks.items, 0..) |blk, bi| if (set[bi]) { - size += blk.insts.items.len + 1; - }; - if (values.items.len * size > auto_unroll_budget) return false; - } // The condition block is dropped: nothing else may use its values. {