Compare commits
3 Commits
4666275a0b
...
7d7a456d63
| Author | SHA1 | Date |
|---|---|---|
|
|
7d7a456d63 | |
|
|
83f2298773 | |
|
|
5792d653b5 |
|
|
@ -1,8 +1,9 @@
|
||||||
//! IR -> DXIL. Everything is inlined into the entry function while
|
//! IR -> DXIL. Everything is inlined into the entry function while
|
||||||
//! emitting (each call instantiates its callee); values are scalarized
|
//! emitting (each call instantiates its callee); values are scalarized
|
||||||
//! (DXIL has no vectors); locals become flattened `[N x scalar]` allocas;
|
//! (DXIL has no vectors); locals become flattened `[N x scalar]` allocas,
|
||||||
//! resources become handles created on entry. The result is a signed DXIL
|
//! which promote.zig turns into SSA values where they are not indexed
|
||||||
//! container.
|
//! dynamically; resources become handles created on entry. The result is a
|
||||||
|
//! signed DXIL container.
|
||||||
|
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
const Allocator = std.mem.Allocator;
|
const Allocator = std.mem.Allocator;
|
||||||
|
|
@ -21,6 +22,8 @@ const rdat = @import("rdat.zig");
|
||||||
const linalg_info = @import("linalg_info.zig");
|
const linalg_info = @import("linalg_info.zig");
|
||||||
const libinfo = @import("libinfo.zig");
|
const libinfo = @import("libinfo.zig");
|
||||||
const rootsig = @import("rootsig.zig");
|
const rootsig = @import("rootsig.zig");
|
||||||
|
const promote = @import("promote.zig");
|
||||||
|
const opt = @import("../ir/opt.zig");
|
||||||
|
|
||||||
const TypeId = types.TypeId;
|
const TypeId = types.TypeId;
|
||||||
const TypeTable = types.TypeTable;
|
const TypeTable = types.TypeTable;
|
||||||
|
|
@ -59,6 +62,9 @@ const Lowered = union(enum) {
|
||||||
/// A local holding a resource (index into Emitter.res_locals): an
|
/// A local holding a resource (index into Emitter.res_locals): an
|
||||||
/// alias of the one resource stored into it.
|
/// alias of the one resource stored into it.
|
||||||
res_local: u32,
|
res_local: u32,
|
||||||
|
/// A local assigned different elements of one resource array (index
|
||||||
|
/// into Emitter.res_index_locals): it holds the element's index.
|
||||||
|
res_index_local: u32,
|
||||||
/// A RayQuery local (index into Emitter.rq_locals) and a query handle.
|
/// A RayQuery local (index into Emitter.rq_locals) and a query handle.
|
||||||
rq_local: u32,
|
rq_local: u32,
|
||||||
ray_query: Value,
|
ray_query: Value,
|
||||||
|
|
@ -68,8 +74,9 @@ const Lowered = union(enum) {
|
||||||
/// far.
|
/// far.
|
||||||
res_array: struct { res: u32, index: ?Value = null, ty: TypeId },
|
res_array: struct { res: u32, index: ?Value = null, ty: TypeId },
|
||||||
/// A place in a constant buffer: byte offset plus a dynamic register
|
/// A place in a constant buffer: byte offset plus a dynamic register
|
||||||
/// offset.
|
/// offset; with `dyn_comp`, the component of the `vec` vector at
|
||||||
cbuf: struct { res: u32, offset: u32 = 0, dyn_regs: ?Value = null, row_major: bool = false },
|
/// `offset` that index picks at run time.
|
||||||
|
cbuf: struct { res: u32, offset: u32 = 0, dyn_regs: ?Value = null, row_major: bool = false, dyn_comp: ?Value = null, vec: TypeId = 0 },
|
||||||
/// A place in a mesh shader output array: the vertex / primitive index
|
/// A place in a mesh shader output array: the vertex / primitive index
|
||||||
/// and a flattened component offset within it.
|
/// and a flattened component offset within it.
|
||||||
mesh: struct { kind: ir.MeshOutput, index: ?Value = null, offset: u32 = 0, ty: TypeId },
|
mesh: struct { kind: ir.MeshOutput, index: ?Value = null, offset: u32 = 0, ty: TypeId },
|
||||||
|
|
@ -98,6 +105,9 @@ const Ptr = struct {
|
||||||
scalar_ty: DType,
|
scalar_ty: DType,
|
||||||
offset_const: u32 = 0,
|
offset_const: u32 = 0,
|
||||||
offset_dyn: ?Value = null,
|
offset_dyn: ?Value = null,
|
||||||
|
/// The components `offset_dyn` can reach: the extent of the array (or
|
||||||
|
/// vector or matrix) it indexes. Null when not known.
|
||||||
|
dyn_range: ?[2]u32 = null,
|
||||||
/// bools are stored as i32.
|
/// bools are stored as i32.
|
||||||
bool_storage: bool = false,
|
bool_storage: bool = false,
|
||||||
/// Mixed 32-bit component types share i32 storage (floats bitcast).
|
/// Mixed 32-bit component types share i32 storage (floats bitcast).
|
||||||
|
|
@ -145,6 +155,13 @@ const Frame = struct {
|
||||||
rets: std.ArrayList(struct { block: u32, vals: []const Value }) = .empty,
|
rets: std.ArrayList(struct { block: u32, vals: []const Value }) = .empty,
|
||||||
/// The resources a function returns (every return the same ones).
|
/// The resources a function returns (every return the same ones).
|
||||||
ret_res: ?[]const Lowered = null,
|
ret_res: ?[]const Lowered = null,
|
||||||
|
/// Loads of locals: where from, and the block and write count when
|
||||||
|
/// read, so a call right after can pass the local itself.
|
||||||
|
load_srcs: std.AutoHashMapUnmanaged(u32, struct { ptr: Ptr, block: u32, writes: u32 }) = .empty,
|
||||||
|
/// By-value parameters passed as the caller's storage (see paramCopies).
|
||||||
|
param_ptrs: []const ?Ptr = &.{},
|
||||||
|
/// paramCopies of the function, when some parameter is aliased.
|
||||||
|
param_copies: []const u32 = &.{},
|
||||||
};
|
};
|
||||||
|
|
||||||
const PInst = struct { inst: module.Inst, id: u32 };
|
const PInst = struct { inst: module.Inst, id: u32 };
|
||||||
|
|
@ -201,12 +218,22 @@ const Emitter = struct {
|
||||||
/// RayQuery locals: the query handle (allocated in the prologue on
|
/// RayQuery locals: the query handle (allocated in the prologue on
|
||||||
/// first use, or a copy of another query) and the query type.
|
/// first use, or a copy of another query) and the query type.
|
||||||
rq_locals: std.ArrayList(struct { h: ?Value, ty: TypeId }) = .empty,
|
rq_locals: std.ArrayList(struct { h: ?Value, ty: TypeId }) = .empty,
|
||||||
|
/// Resource locals holding an element index of resource array `res`:
|
||||||
|
/// the index's storage, and whether any index stored is NonUniform.
|
||||||
|
res_index_locals: std.ArrayList(struct { ptr: Ptr, res: u32, nonuniform: bool = false }) = .empty,
|
||||||
/// The ResRet of the last texture operation (for status arguments).
|
/// The ResRet of the last texture operation (for status arguments).
|
||||||
last_resret: Value = undefined,
|
last_resret: Value = undefined,
|
||||||
/// Status values, forwarded through locals within a block: the
|
/// Status values, forwarded through locals within a block: the
|
||||||
/// validator wants CheckAccessFullyMapped's operand to be one.
|
/// validator wants CheckAccessFullyMapped's operand to be one.
|
||||||
status_vals: std.AutoHashMapUnmanaged(Value, void) = .empty,
|
status_vals: std.AutoHashMapUnmanaged(Value, void) = .empty,
|
||||||
forwarded: std.AutoHashMapUnmanaged(struct { Value, u32 }, struct { v: Value, block: u32 }) = .empty,
|
forwarded: std.AutoHashMapUnmanaged(struct { Value, u32 }, struct { v: Value, block: u32 }) = .empty,
|
||||||
|
/// Dynamically indexed getelementptrs into locals (by id) and the
|
||||||
|
/// components they can reach, for promote.run.
|
||||||
|
dyn_ranges: std.AutoHashMapUnmanaged(u32, [2]u32) = .empty,
|
||||||
|
/// Instructions emitted so far that may write memory.
|
||||||
|
writes: u32 = 0,
|
||||||
|
/// paramCopies per IR function.
|
||||||
|
param_copies: std.AutoHashMapUnmanaged(u32, []const u32) = .empty,
|
||||||
uses_barycentrics: bool = false,
|
uses_barycentrics: bool = false,
|
||||||
uses_sampler_heap: bool = false,
|
uses_sampler_heap: bool = false,
|
||||||
|
|
||||||
|
|
@ -255,6 +282,13 @@ const Emitter = struct {
|
||||||
fn add(e: *Emitter, ty: DType, op: @FieldType(module.Inst, "op")) Error!Value {
|
fn add(e: *Emitter, ty: DType, op: @FieldType(module.Inst, "op")) Error!Value {
|
||||||
const id = e.next_id;
|
const id = e.next_id;
|
||||||
e.next_id += 1;
|
e.next_id += 1;
|
||||||
|
switch (op) {
|
||||||
|
.store, .atomicrmw, .cmpxchg => e.writes += 1,
|
||||||
|
.call => |c| if (!std.mem.startsWith(u8, e.dm.functions.items[c.callee].name, "dx.op.")) {
|
||||||
|
e.writes += 1;
|
||||||
|
},
|
||||||
|
else => {},
|
||||||
|
}
|
||||||
try e.blocks.items[e.cur].append(e.arena, .{ .inst = .{ .ty = ty, .op = op }, .id = id });
|
try e.blocks.items[e.cur].append(e.arena, .{ .inst = .{ .ty = ty, .op = op }, .id = id });
|
||||||
return .{ .inst = id };
|
return .{ .inst = id };
|
||||||
}
|
}
|
||||||
|
|
@ -510,8 +544,8 @@ const Emitter = struct {
|
||||||
// A global per resource, named as dxc mangles it.
|
// A global per resource, named as dxc mangles it.
|
||||||
for (e.resources.items) |*r| {
|
for (e.resources.items) |*r| {
|
||||||
if (r.view) continue;
|
if (r.view) continue;
|
||||||
if (r.count != 1) return e.unsupported("resource arrays in libraries are not supported yet", .{});
|
|
||||||
const g = m.globals.items[r.global];
|
const g = m.globals.items[r.global];
|
||||||
|
// (Arrays: of the class, all dimensions flattened.)
|
||||||
const ty = try e.classType(r.*);
|
const ty = try e.classType(r.*);
|
||||||
const name = if (g.space == .resource) try mangle.global(e.arena, e.t, g.name, g.ty) else g.name;
|
const name = if (g.space == .resource) try mangle.global(e.arena, e.t, g.name, g.ty) else g.name;
|
||||||
const v = try e.dm.addGlobal(name, ty, 0);
|
const v = try e.dm.addGlobal(name, ty, 0);
|
||||||
|
|
@ -574,6 +608,7 @@ const Emitter = struct {
|
||||||
e.nonuniform = .empty;
|
e.nonuniform = .empty;
|
||||||
e.res_locals = .empty;
|
e.res_locals = .empty;
|
||||||
e.rq_locals = .empty;
|
e.rq_locals = .empty;
|
||||||
|
e.res_index_locals = .empty;
|
||||||
e.forwarded = .empty;
|
e.forwarded = .empty;
|
||||||
e.status_vals = .empty;
|
e.status_vals = .empty;
|
||||||
e.payload_global = null;
|
e.payload_global = null;
|
||||||
|
|
@ -626,6 +661,9 @@ const Emitter = struct {
|
||||||
return x.func < y.func;
|
return x.func < y.func;
|
||||||
}
|
}
|
||||||
}.lt);
|
}.lt);
|
||||||
|
if (try promote.pruneDeclarations(e.arena, &e.dm)) |index| for (funcs.items) |*lf| {
|
||||||
|
lf.func = index[lf.func];
|
||||||
|
};
|
||||||
const bitcode = try e.writeLibraryModule(funcs.items);
|
const bitcode = try e.writeLibraryModule(funcs.items);
|
||||||
defer gpa.free(bitcode);
|
defer gpa.free(bitcode);
|
||||||
return e.assembleLibrary(gpa, funcs.items, bitcode);
|
return e.assembleLibrary(gpa, funcs.items, bitcode);
|
||||||
|
|
@ -766,6 +804,7 @@ const Emitter = struct {
|
||||||
e.nonuniform = .empty;
|
e.nonuniform = .empty;
|
||||||
e.res_locals = .empty;
|
e.res_locals = .empty;
|
||||||
e.rq_locals = .empty;
|
e.rq_locals = .empty;
|
||||||
|
e.res_index_locals = .empty;
|
||||||
e.forwarded = .empty;
|
e.forwarded = .empty;
|
||||||
e.status_vals = .empty;
|
e.status_vals = .empty;
|
||||||
e.lib_args = &.{};
|
e.lib_args = &.{};
|
||||||
|
|
@ -828,6 +867,8 @@ const Emitter = struct {
|
||||||
const i32t = try e.dm.intType(32);
|
const i32t = try e.dm.intType(32);
|
||||||
for (e.resources.items) |*res| {
|
for (e.resources.items) |*res| {
|
||||||
const lg = res.lib_global orelse continue;
|
const lg = res.lib_global orelse continue;
|
||||||
|
// (Arrays: a handle per element access, in arrayElement.)
|
||||||
|
if (res.count != 1) continue;
|
||||||
const gty = e.dm.globals.items[lg].ty;
|
const gty = e.dm.globals.items[lg].ty;
|
||||||
const loaded = try e.addPrologue(gty, .{ .load = .{ .ptr = .{ .global = lg }, .@"align" = 4 } });
|
const loaded = try e.addPrologue(gty, .{ .load = .{ .ptr = .{ .global = lg }, .@"align" = 4 } });
|
||||||
try e.lib_removable.put(e.arena, loaded.inst, {});
|
try e.lib_removable.put(e.arena, loaded.inst, {});
|
||||||
|
|
@ -1210,6 +1251,11 @@ const Emitter = struct {
|
||||||
const all = [_][]const PInst{e.prologue.items};
|
const all = [_][]const PInst{e.prologue.items};
|
||||||
for (all) |items| for (items) |pi| try f.insts.append(e.dm.allocator(), try remapInst(e.arena, map, pi.inst, remap));
|
for (all) |items| for (items) |pi| try f.insts.append(e.dm.allocator(), try remapInst(e.arena, map, pi.inst, remap));
|
||||||
for (e.blocks.items) |blk| for (blk.items) |pi| try f.insts.append(e.dm.allocator(), try remapInst(e.arena, map, pi.inst, remap));
|
for (e.blocks.items) |blk| for (blk.items) |pi| try f.insts.append(e.dm.allocator(), try remapInst(e.arena, map, pi.inst, remap));
|
||||||
|
var ranges: std.AutoHashMapUnmanaged(u32, [2]u32) = .empty;
|
||||||
|
var it = e.dyn_ranges.iterator();
|
||||||
|
while (it.next()) |kv| try ranges.put(e.arena, map[kv.key_ptr.*], kv.value_ptr.*);
|
||||||
|
e.dyn_ranges.clearRetainingCapacity();
|
||||||
|
try promote.run(e.arena, &e.dm, func, &ranges);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Drops removable prologue instructions nothing uses (repeatedly: a
|
/// Drops removable prologue instructions nothing uses (repeatedly: a
|
||||||
|
|
@ -1237,7 +1283,7 @@ const Emitter = struct {
|
||||||
|
|
||||||
fn markUses(a: Allocator, inst: module.Inst, used: []bool) void {
|
fn markUses(a: Allocator, inst: module.Inst, used: []bool) void {
|
||||||
const M = struct {
|
const M = struct {
|
||||||
var u: []bool = &.{};
|
threadlocal var u: []bool = &.{};
|
||||||
fn v(_: []const u32, x: Value) Value {
|
fn v(_: []const u32, x: Value) Value {
|
||||||
if (x == .inst) u[x.inst] = true;
|
if (x == .inst) u[x.inst] = true;
|
||||||
return x;
|
return x;
|
||||||
|
|
@ -1321,6 +1367,12 @@ const Emitter = struct {
|
||||||
/// Emits function `fi` inline at the current block with `args`; returns
|
/// Emits function `fi` inline at the current block with `args`; returns
|
||||||
/// its result components and leaves the current block after the call.
|
/// its result components and leaves the current block after the call.
|
||||||
fn inlineCall(e: *Emitter, fi: u32, args: []const Lowered) Error![]const Value {
|
fn inlineCall(e: *Emitter, fi: u32, args: []const Lowered) Error![]const Value {
|
||||||
|
return e.inlineCallAliased(fi, args, &.{});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `aliases[k]`, when set, is caller storage holding by-value argument
|
||||||
|
/// `k`, which the callee may read in place of a copy (see argAliases).
|
||||||
|
fn inlineCallAliased(e: *Emitter, fi: u32, args: []const Lowered, aliases: []const ?Ptr) Error![]const Value {
|
||||||
const f = e.m.functions.items[fi];
|
const f = e.m.functions.items[fi];
|
||||||
var frame: Frame = .{
|
var frame: Frame = .{
|
||||||
.f = f,
|
.f = f,
|
||||||
|
|
@ -1328,6 +1380,11 @@ const Emitter = struct {
|
||||||
.params = args,
|
.params = args,
|
||||||
.blocks = try e.arena.alloc(?u32, f.blocks.items.len),
|
.blocks = try e.arena.alloc(?u32, f.blocks.items.len),
|
||||||
};
|
};
|
||||||
|
for (aliases) |al| if (al != null) {
|
||||||
|
frame.param_ptrs = aliases;
|
||||||
|
frame.param_copies = try e.paramCopies(fi);
|
||||||
|
break;
|
||||||
|
};
|
||||||
@memset(frame.vals, .none);
|
@memset(frame.vals, .none);
|
||||||
@memset(frame.blocks, null);
|
@memset(frame.blocks, null);
|
||||||
const is_entry = e.cur == 0 and e.blocks.items[0].items.len == 0 and (fi == e.entry.wrapper or fi == e.entry.patch_wrapper);
|
const is_entry = e.cur == 0 and e.blocks.items[0].items.len == 0 and (fi == e.entry.wrapper or fi == e.entry.patch_wrapper);
|
||||||
|
|
@ -1357,6 +1414,87 @@ const Emitter = struct {
|
||||||
return &.{};
|
return &.{};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Caller storage the by-value arguments of a call to `fi` can be read
|
||||||
|
/// from: an argument loaded from a local in the same block, with no
|
||||||
|
/// write since. Calls with out / inout arguments get none (the callee
|
||||||
|
/// could write the local through one while reading it through another).
|
||||||
|
fn argAliases(e: *Emitter, frame: *const Frame, fi: u32, refs: []const Ref) Error![]const ?Ptr {
|
||||||
|
const params = e.m.functions.items[fi].params;
|
||||||
|
for (params) |p| if (p.by_ref) return &.{};
|
||||||
|
const out = try e.arena.alloc(?Ptr, refs.len);
|
||||||
|
for (refs, params, out) |r, p, *o| {
|
||||||
|
o.* = null;
|
||||||
|
if (e.t.get(p.ty) != .array) continue;
|
||||||
|
const src = frame.load_srcs.get(r.index()) orelse continue;
|
||||||
|
if (src.block == e.cur and src.writes == e.writes) o.* = src.ptr;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// For each instruction of IR function `fi`: the parameter a
|
||||||
|
/// `local_var` only ever holds a copy of (stored once, from that
|
||||||
|
/// by-value parameter, and otherwise only read), else maxInt.
|
||||||
|
fn paramCopies(e: *Emitter, fi: u32) Error![]const u32 {
|
||||||
|
const gop = try e.param_copies.getOrPut(e.arena, fi);
|
||||||
|
if (gop.found_existing) return gop.value_ptr.*;
|
||||||
|
const none = std.math.maxInt(u32);
|
||||||
|
const f = e.m.functions.items[fi];
|
||||||
|
const n = f.insts.items.len;
|
||||||
|
// The local each pointer is into.
|
||||||
|
const root = try e.arena.alloc(u32, n);
|
||||||
|
@memset(root, none);
|
||||||
|
var changed = true;
|
||||||
|
while (changed) {
|
||||||
|
changed = false;
|
||||||
|
for (f.insts.items, 0..) |inst, k| {
|
||||||
|
const want: u32 = switch (inst.op) {
|
||||||
|
.local_var => @intCast(k),
|
||||||
|
.access => |x| root[x.base.index()],
|
||||||
|
else => none,
|
||||||
|
};
|
||||||
|
if (want != root[k]) {
|
||||||
|
root[k] = want;
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const out = try e.arena.alloc(u32, n);
|
||||||
|
@memset(out, none);
|
||||||
|
const ok = try e.arena.alloc(bool, n);
|
||||||
|
@memset(ok, true);
|
||||||
|
const Use = struct {
|
||||||
|
root: []const u32,
|
||||||
|
ok: []bool,
|
||||||
|
pub fn map(s: @This(), x: Ref) Ref {
|
||||||
|
if (x != .none and s.root[x.index()] != none) s.ok[s.root[x.index()]] = false;
|
||||||
|
return x;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
for (f.insts.items) |inst| switch (inst.op) {
|
||||||
|
.local_var => {},
|
||||||
|
.load => {},
|
||||||
|
.access => |x| for (x.indices) |ix| {
|
||||||
|
_ = (Use{ .root = root, .ok = ok }).map(ix);
|
||||||
|
},
|
||||||
|
.store => |x| {
|
||||||
|
_ = (Use{ .root = root, .ok = ok }).map(x.value);
|
||||||
|
const l = root[x.ptr.index()];
|
||||||
|
if (l == none) continue;
|
||||||
|
const v = f.inst(x.value).op;
|
||||||
|
if (x.ptr.index() == l and v == .param and !f.params[v.param].by_ref and out[l] == none) {
|
||||||
|
out[l] = v.param;
|
||||||
|
} else ok[l] = false;
|
||||||
|
},
|
||||||
|
else => _ = try opt.mapOp(e.arena, inst.op, Use{ .root = root, .ok = ok }),
|
||||||
|
};
|
||||||
|
// Terminators returning pointers do not occur.
|
||||||
|
for (out, ok) |*o, good| if (!good) {
|
||||||
|
o.* = none;
|
||||||
|
};
|
||||||
|
gop.value_ptr.* = out;
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
/// A call of `[noinline]` function `fi` (module function `func`), as
|
/// A call of `[noinline]` function `fi` (module function `func`), as
|
||||||
/// exportSignature passes values: out / inout values and structs
|
/// exportSignature passes values: out / inout values and structs
|
||||||
/// through temporaries.
|
/// through temporaries.
|
||||||
|
|
@ -1612,6 +1750,10 @@ const Emitter = struct {
|
||||||
try e.rq_locals.append(e.arena, .{ .h = null, .ty = i.ty });
|
try e.rq_locals.append(e.arena, .{ .h = null, .ty = i.ty });
|
||||||
return .{ .rq_local = @intCast(e.rq_locals.items.len - 1) };
|
return .{ .rq_local = @intCast(e.rq_locals.items.len - 1) };
|
||||||
}
|
}
|
||||||
|
if (isResourceType(e.t, i.ty) and e.t.get(i.ty) != .array) if (e.indexedLocal(f, r)) |ri| {
|
||||||
|
try e.res_index_locals.append(e.arena, .{ .ptr = try e.alloca(try e.t.scalar(.uint)), .res = ri });
|
||||||
|
return .{ .res_index_local = @intCast(e.res_index_locals.items.len - 1) };
|
||||||
|
};
|
||||||
// (An array of resources is one alias too: of an array.)
|
// (An array of resources is one alias too: of an array.)
|
||||||
if (isResourceType(e.t, i.ty) or e.isResourceArray(i.ty)) {
|
if (isResourceType(e.t, i.ty) or e.isResourceArray(i.ty)) {
|
||||||
try e.res_locals.append(e.arena, null);
|
try e.res_locals.append(e.arena, null);
|
||||||
|
|
@ -1625,6 +1767,10 @@ const Emitter = struct {
|
||||||
const base = try e.addPrologue(try e.dm.ptrType(dty), .{ .alloca = .{ .elem = dty, .size = try e.i32Const(1) } });
|
const base = try e.addPrologue(try e.dm.ptrType(dty), .{ .alloca = .{ .elem = dty, .size = try e.i32Const(1) } });
|
||||||
return .{ .typed = .{ .base = base, .dty = dty, .addr_space = 0, .ty = i.ty } };
|
return .{ .typed = .{ .base = base, .dty = dty, .addr_space = 0, .ty = i.ty } };
|
||||||
}
|
}
|
||||||
|
if (frame.param_copies.len > 0) {
|
||||||
|
const k = frame.param_copies[r.index()];
|
||||||
|
if (k != std.math.maxInt(u32)) if (frame.param_ptrs[k]) |alias| return .{ .ptr = alias };
|
||||||
|
}
|
||||||
return .{ .ptr = try e.alloca(i.ty) };
|
return .{ .ptr = try e.alloca(i.ty) };
|
||||||
},
|
},
|
||||||
.load => |p| switch (frame.vals[p.index()]) {
|
.load => |p| switch (frame.vals[p.index()]) {
|
||||||
|
|
@ -1641,6 +1787,12 @@ const Emitter = struct {
|
||||||
},
|
},
|
||||||
.rq_local => |k| return .{ .ray_query = try e.rqHandle(k) },
|
.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.unsupported("a resource local read before it is assigned", .{}),
|
||||||
|
.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];
|
||||||
|
if (il.nonuniform) try e.nonuniform.put(e.arena, idx, {});
|
||||||
|
return e.elementHandle(il.res, idx, il.nonuniform);
|
||||||
|
},
|
||||||
.res_array => |ra| return .{ .res_array = ra },
|
.res_array => |ra| return .{ .res_array = ra },
|
||||||
.texel => |tx| {
|
.texel => |tx| {
|
||||||
const res = e.resources.items[tx.res];
|
const res = e.resources.items[tx.res];
|
||||||
|
|
@ -1648,7 +1800,11 @@ const Emitter = struct {
|
||||||
if (res.kind == 10) return .{ .scalars = try e.typedBufferLoad(res, tx.coords[0], i.ty) };
|
if (res.kind == 10) return .{ .scalars = try e.typedBufferLoad(res, tx.coords[0], i.ty) };
|
||||||
return .{ .scalars = try e.textureLoad(res, mip, tx.coords, null, i.ty) };
|
return .{ .scalars = try e.textureLoad(res, mip, tx.coords, null, i.ty) };
|
||||||
},
|
},
|
||||||
.cbuf => |c| return e.cbufferLoad(c.res, c.offset, c.dyn_regs, c.row_major, i.ty),
|
.cbuf => |c| {
|
||||||
|
const dc = c.dyn_comp orelse return e.cbufferLoad(c.res, c.offset, c.dyn_regs, c.row_major, i.ty);
|
||||||
|
const whole = (try e.cbufferLoad(c.res, c.offset, c.dyn_regs, c.row_major, c.vec)).scalars;
|
||||||
|
return .{ .scalars = try e.arena.dupe(Value, &.{try e.pickComponent(whole, dc, i.ty)}) };
|
||||||
|
},
|
||||||
.buf => |b| {
|
.buf => |b| {
|
||||||
const mat = b.mat orelse return .{ .scalars = try e.structuredLoad(e.resources.items[b.res], b.index, b.offset, b.dyn, b.row_major, i.ty) };
|
const mat = b.mat orelse return .{ .scalars = try e.structuredLoad(e.resources.items[b.res], b.index, b.offset, b.dyn, b.row_major, i.ty) };
|
||||||
const m = e.t.get(mat.ty).matrix;
|
const m = e.t.get(mat.ty).matrix;
|
||||||
|
|
@ -1674,12 +1830,19 @@ const Emitter = struct {
|
||||||
}
|
}
|
||||||
return .{ .scalars = out };
|
return .{ .scalars = out };
|
||||||
},
|
},
|
||||||
.ptr => |ptr| return e.loadPtr(ptr, i.ty),
|
.ptr => |ptr| {
|
||||||
|
if (ptr.addr_space == 0 and localRoot(f, p)) try frame.load_srcs.put(e.arena, r.index(), .{ .ptr = ptr, .block = e.cur, .writes = e.writes });
|
||||||
|
return e.loadPtr(ptr, i.ty);
|
||||||
|
},
|
||||||
.typed => |tp| return e.typedLoad(tp, i.ty),
|
.typed => |tp| return e.typedLoad(tp, i.ty),
|
||||||
.mesh => return e.unsupported("reading mesh shader outputs is not supported", .{}),
|
.mesh => return e.unsupported("reading mesh shader outputs is not supported", .{}),
|
||||||
else => return e.unsupported("internal: load from a non-pointer", .{}),
|
else => return e.unsupported("internal: load from a non-pointer", .{}),
|
||||||
},
|
},
|
||||||
.store => |s| {
|
.store => |s| {
|
||||||
|
if (frame.param_copies.len > 0) if (f.inst(s.value).op == .param) {
|
||||||
|
const k = f.inst(s.value).op.param;
|
||||||
|
if (frame.param_copies[s.ptr.index()] == k and frame.param_ptrs[k] != null) return .none;
|
||||||
|
};
|
||||||
if (frame.vals[s.ptr.index()] == .rq_local) {
|
if (frame.vals[s.ptr.index()] == .rq_local) {
|
||||||
// A copy of a query is the same query.
|
// A copy of a query is the same query.
|
||||||
const v = frame.vals[s.value.index()];
|
const v = frame.vals[s.value.index()];
|
||||||
|
|
@ -1687,6 +1850,15 @@ const Emitter = struct {
|
||||||
e.rq_locals.items[frame.vals[s.ptr.index()].rq_local].h = v.ray_query;
|
e.rq_locals.items[frame.vals[s.ptr.index()].rq_local].h = v.ray_query;
|
||||||
return .none;
|
return .none;
|
||||||
}
|
}
|
||||||
|
if (frame.vals[s.ptr.index()] == .res_index_local) {
|
||||||
|
const il = &e.res_index_locals.items[frame.vals[s.ptr.index()].res_index_local];
|
||||||
|
const acc = resourceElement(f, s.value).?;
|
||||||
|
const g = f.inst(acc.base).op.global;
|
||||||
|
const elem = try e.arrayIndex(frame, .{ .res = il.res, .ty = e.m.globals.items[g].ty }, acc.indices);
|
||||||
|
if (elem.nonuniform) il.nonuniform = true;
|
||||||
|
try e.storePtr(il.ptr, &.{elem.ra.index orelse try e.i32Const(0)}, try e.t.scalar(.uint));
|
||||||
|
return .none;
|
||||||
|
}
|
||||||
if (frame.vals[s.ptr.index()] == .res_local) {
|
if (frame.vals[s.ptr.index()] == .res_local) {
|
||||||
const slot = &e.res_locals.items[frame.vals[s.ptr.index()].res_local];
|
const slot = &e.res_locals.items[frame.vals[s.ptr.index()].res_local];
|
||||||
const h = frame.vals[s.value.index()];
|
const h = frame.vals[s.value.index()];
|
||||||
|
|
@ -1796,6 +1968,7 @@ const Emitter = struct {
|
||||||
} else {
|
} else {
|
||||||
const idx = (try e.scalars(frame, x))[0];
|
const idx = (try e.scalars(frame, x))[0];
|
||||||
const scaled = if (s == 1) idx else try e.add(try e.dm.intType(32), .{ .binop = .{ .op = .mul, .lhs = idx, .rhs = try e.i32Const(s) } });
|
const scaled = if (s == 1) idx else try e.add(try e.dm.intType(32), .{ .binop = .{ .op = .mul, .lhs = idx, .rhs = try e.i32Const(s) } });
|
||||||
|
if (ptr.offset_dyn == null) ptr.dyn_range = .{ ptr.offset_const, ptr.offset_const + try e.flatCount(cur) };
|
||||||
ptr.offset_dyn = if (ptr.offset_dyn) |d| try e.add(try e.dm.intType(32), .{ .binop = .{ .op = .add, .lhs = d, .rhs = scaled } }) else scaled;
|
ptr.offset_dyn = if (ptr.offset_dyn) |d| try e.add(try e.dm.intType(32), .{ .binop = .{ .op = .add, .lhs = d, .rhs = scaled } }) else scaled;
|
||||||
}
|
}
|
||||||
cur = elem;
|
cur = elem;
|
||||||
|
|
@ -1930,7 +2103,7 @@ const Emitter = struct {
|
||||||
if (e.lib_calls.get(c.func)) |func| return e.libCall(frame, c.func, func, c.args);
|
if (e.lib_calls.get(c.func)) |func| return e.libCall(frame, c.func, func, c.args);
|
||||||
const args = try e.arena.alloc(Lowered, c.args.len);
|
const args = try e.arena.alloc(Lowered, c.args.len);
|
||||||
for (c.args, args) |a, *o| o.* = frame.vals[a.index()];
|
for (c.args, args) |a, *o| o.* = frame.vals[a.index()];
|
||||||
const res = try e.inlineCall(c.func, args);
|
const res = try e.inlineCallAliased(c.func, args, try e.argAliases(frame, c.func, c.args));
|
||||||
// Functions returning resources (or structs of them).
|
// Functions returning resources (or structs of them).
|
||||||
if (isResourceType(e.t, i.ty) and !isRayQuery(e.t, i.ty)) {
|
if (isResourceType(e.t, i.ty) and !isRayQuery(e.t, i.ty)) {
|
||||||
const rr = e.last_ret_res orelse return e.unsupported("a function returning a resource with no return value", .{});
|
const rr = e.last_ret_res orelse return e.unsupported("a function returning a resource with no return value", .{});
|
||||||
|
|
@ -2059,6 +2232,7 @@ const Emitter = struct {
|
||||||
const konst: ?u32 = if (xi.op == .constant) @intCast(xi.op.constant.int) else null;
|
const konst: ?u32 = if (xi.op == .constant) @intCast(xi.op.constant.int) else null;
|
||||||
var data_off: u32 = 0;
|
var data_off: u32 = 0;
|
||||||
var data_dyn: ?Value = null;
|
var data_dyn: ?Value = null;
|
||||||
|
var data_extent: u32 = 0;
|
||||||
switch (e.t.get(cur)) {
|
switch (e.t.get(cur)) {
|
||||||
.@"struct" => |st| {
|
.@"struct" => |st| {
|
||||||
const k = konst.?;
|
const k = konst.?;
|
||||||
|
|
@ -2079,6 +2253,7 @@ const Emitter = struct {
|
||||||
const idx = (try e.scalars(frame, x))[0];
|
const idx = (try e.scalars(frame, x))[0];
|
||||||
const n = try e.flatCount(arr.elem);
|
const n = try e.flatCount(arr.elem);
|
||||||
data_dyn = if (n == 1) idx else try e.add(try e.dm.intType(32), .{ .binop = .{ .op = .mul, .lhs = idx, .rhs = try e.i32Const(n) } });
|
data_dyn = if (n == 1) idx else try e.add(try e.dm.intType(32), .{ .binop = .{ .op = .mul, .lhs = idx, .rhs = try e.i32Const(n) } });
|
||||||
|
data_extent = try e.flatCount(cur);
|
||||||
}
|
}
|
||||||
cur = arr.elem;
|
cur = arr.elem;
|
||||||
},
|
},
|
||||||
|
|
@ -2087,7 +2262,10 @@ const Emitter = struct {
|
||||||
if (data) |*d| switch (d.*) {
|
if (data) |*d| switch (d.*) {
|
||||||
.ptr => |*ptr| {
|
.ptr => |*ptr| {
|
||||||
ptr.offset_const += data_off;
|
ptr.offset_const += data_off;
|
||||||
if (data_dyn) |dd| ptr.offset_dyn = if (ptr.offset_dyn) |old| try e.add(try e.dm.intType(32), .{ .binop = .{ .op = .add, .lhs = old, .rhs = dd } }) else dd;
|
if (data_dyn) |dd| {
|
||||||
|
if (ptr.offset_dyn == null) ptr.dyn_range = .{ ptr.offset_const, ptr.offset_const + data_extent };
|
||||||
|
ptr.offset_dyn = if (ptr.offset_dyn) |old| try e.add(try e.dm.intType(32), .{ .binop = .{ .op = .add, .lhs = old, .rhs = dd } }) else dd;
|
||||||
|
}
|
||||||
},
|
},
|
||||||
.typed => try path.append(e.arena, (try e.scalars(frame, x))[0]),
|
.typed => try path.append(e.arena, (try e.scalars(frame, x))[0]),
|
||||||
else => {},
|
else => {},
|
||||||
|
|
@ -2265,7 +2443,9 @@ const Emitter = struct {
|
||||||
var idx = try e.i32Const(ptr.offset_const + c);
|
var idx = try e.i32Const(ptr.offset_const + c);
|
||||||
if (ptr.offset_dyn) |d| idx = try e.add(try e.dm.intType(32), .{ .binop = .{ .op = .add, .lhs = d, .rhs = idx } });
|
if (ptr.offset_dyn) |d| idx = try e.add(try e.dm.intType(32), .{ .binop = .{ .op = .add, .lhs = d, .rhs = idx } });
|
||||||
const pt = try e.dm.getType(.{ .pointer = .{ .elem = ptr.scalar_ty, .addr_space = ptr.addr_space } });
|
const pt = try e.dm.getType(.{ .pointer = .{ .elem = ptr.scalar_ty, .addr_space = ptr.addr_space } });
|
||||||
return e.add(pt, .{ .gep = .{ .elem = ptr.array_ty, .ptr = ptr.base, .indices = try e.arena.dupe(Value, &.{ try e.i32Const(0), idx }) } });
|
const gep = try e.add(pt, .{ .gep = .{ .elem = ptr.array_ty, .ptr = ptr.base, .indices = try e.arena.dupe(Value, &.{ try e.i32Const(0), idx }) } });
|
||||||
|
if (ptr.offset_dyn != null) if (ptr.dyn_range) |r| try e.dyn_ranges.put(e.arena, gep.inst, r);
|
||||||
|
return gep;
|
||||||
}
|
}
|
||||||
|
|
||||||
fn convertScalar(e: *Emitter, v: Value, from: Scalar, to: Scalar) Error!Value {
|
fn convertScalar(e: *Emitter, v: Value, from: Scalar, to: Scalar) Error!Value {
|
||||||
|
|
@ -3115,9 +3295,13 @@ const Emitter = struct {
|
||||||
cur = arr.elem;
|
cur = arr.elem;
|
||||||
},
|
},
|
||||||
.vector => |v| {
|
.vector => |v| {
|
||||||
if (xi.op != .constant) return e.unsupported("dynamic indexing of constant buffer vectors", .{});
|
|
||||||
c.offset += @as(u32, @intCast(xi.op.constant.int)) * storageScalar(v.elem).size();
|
|
||||||
cur = try e.t.scalar(v.elem);
|
cur = try e.t.scalar(v.elem);
|
||||||
|
if (xi.op != .constant) {
|
||||||
|
c.dyn_comp = (try e.scalars(frame, x))[0];
|
||||||
|
c.vec = try e.t.vector(v.elem, v.len);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
c.offset += @as(u32, @intCast(xi.op.constant.int)) * storageScalar(v.elem).size();
|
||||||
},
|
},
|
||||||
.matrix => |mt| {
|
.matrix => |mt| {
|
||||||
if (xi.op != .constant) return e.unsupported("dynamic indexing of constant buffer matrices", .{});
|
if (xi.op != .constant) return e.unsupported("dynamic indexing of constant buffer matrices", .{});
|
||||||
|
|
@ -3192,6 +3376,18 @@ const Emitter = struct {
|
||||||
return .{ .scalars = out };
|
return .{ .scalars = out };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Component `idx` (a dynamic index) of `vals`: a chain of selects.
|
||||||
|
fn pickComponent(e: *Emitter, vals: []const Value, idx: Value, ty: TypeId) Error!Value {
|
||||||
|
const i1t = try e.dm.intType(1);
|
||||||
|
const dty = try e.scalarTy(e.compOf(ty));
|
||||||
|
var acc = vals[0];
|
||||||
|
for (vals[1..], 1..) |v, k| {
|
||||||
|
const is_k = try e.add(i1t, .{ .cmp = .{ .pred = 32, .lhs = idx, .rhs = try e.i32Const(@intCast(k)) } });
|
||||||
|
acc = try e.select(is_k, v, acc, dty);
|
||||||
|
}
|
||||||
|
return acc;
|
||||||
|
}
|
||||||
|
|
||||||
/// The scalar type of flattened component `k` of `ty`.
|
/// The scalar type of flattened component `k` of `ty`.
|
||||||
fn componentType(e: *Emitter, ty: TypeId, k: u32) Error!TypeId {
|
fn componentType(e: *Emitter, ty: TypeId, k: u32) Error!TypeId {
|
||||||
switch (e.t.get(ty)) {
|
switch (e.t.get(ty)) {
|
||||||
|
|
@ -3217,6 +3413,59 @@ const Emitter = struct {
|
||||||
/// `array[i]...` on a resource array: a sub-array, or the element's
|
/// `array[i]...` on a resource array: a sub-array, or the element's
|
||||||
/// handle (created here, at register lower bound + flattened index).
|
/// handle (created here, at register lower bound + flattened index).
|
||||||
fn arrayElement(e: *Emitter, frame: *Frame, start: @FieldType(Lowered, "res_array"), indices: []const Ref) Error!Lowered {
|
fn arrayElement(e: *Emitter, frame: *Frame, start: @FieldType(Lowered, "res_array"), indices: []const Ref) Error!Lowered {
|
||||||
|
const elem = try e.arrayIndex(frame, start, indices);
|
||||||
|
if (e.t.get(elem.ra.ty) == .array) return .{ .res_array = elem.ra };
|
||||||
|
return e.elementHandle(elem.ra.res, elem.ra.index orelse try e.i32Const(0), elem.nonuniform);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The resource array global behind `v`, an element of it (possibly
|
||||||
|
/// loaded), and the indices; null for anything else.
|
||||||
|
fn resourceElement(f: *const ir.Function, v: Ref) ?@FieldType(ir.Op, "access") {
|
||||||
|
var x = v;
|
||||||
|
while (f.inst(x).op == .load) x = f.inst(x).op.load;
|
||||||
|
if (f.inst(x).op != .access) return null;
|
||||||
|
const acc = f.inst(x).op.access;
|
||||||
|
var base = acc.base;
|
||||||
|
while (f.inst(base).op == .load) base = f.inst(base).op.load;
|
||||||
|
if (f.inst(base).op != .global) return null;
|
||||||
|
return .{ .base = base, .indices = acc.indices };
|
||||||
|
}
|
||||||
|
|
||||||
|
/// For a resource local of `f`, the resource array whose elements are
|
||||||
|
/// all that is stored into it, when they are different ones (as in a
|
||||||
|
/// switch picking a texture): such a local holds the element's index.
|
||||||
|
fn indexedLocal(e: *Emitter, f: *const ir.Function, local: Ref) ?u32 {
|
||||||
|
var first: ?@FieldType(ir.Op, "access") = null;
|
||||||
|
var first_value: Ref = .none;
|
||||||
|
var distinct = false;
|
||||||
|
for (f.insts.items) |st| {
|
||||||
|
if (st.op != .store or st.op.store.ptr != local) continue;
|
||||||
|
const acc = resourceElement(f, st.op.store.value) orelse return null;
|
||||||
|
if (first) |fa| {
|
||||||
|
if (st.op.store.value != first_value) distinct = true;
|
||||||
|
if (f.inst(fa.base).op.global != f.inst(acc.base).op.global or fa.indices.len != acc.indices.len) return null;
|
||||||
|
} else {
|
||||||
|
first = acc;
|
||||||
|
first_value = st.op.store.value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const fa = first orelse return null;
|
||||||
|
if (!distinct) return null;
|
||||||
|
const g = f.inst(fa.base).op.global;
|
||||||
|
const ri = e.resource_of_global.get(g) orelse return null;
|
||||||
|
if (e.resources.items[ri].count == 1) return null;
|
||||||
|
// Indexed down to single resources.
|
||||||
|
var ty = e.m.globals.items[g].ty;
|
||||||
|
for (fa.indices) |_| {
|
||||||
|
if (e.t.get(ty) != .array) return null;
|
||||||
|
ty = e.t.get(ty).array.elem;
|
||||||
|
}
|
||||||
|
if (e.t.get(ty) == .array) return null;
|
||||||
|
return ri;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The flattened index of an element of a resource array.
|
||||||
|
fn arrayIndex(e: *Emitter, frame: *Frame, start: @FieldType(Lowered, "res_array"), indices: []const Ref) Error!struct { ra: @FieldType(Lowered, "res_array"), nonuniform: bool } {
|
||||||
var ra = start;
|
var ra = start;
|
||||||
const i32t = try e.dm.intType(32);
|
const i32t = try e.dm.intType(32);
|
||||||
var nonuniform = false;
|
var nonuniform = false;
|
||||||
|
|
@ -3235,10 +3484,21 @@ const Emitter = struct {
|
||||||
ra.ty = arr.elem;
|
ra.ty = arr.elem;
|
||||||
}
|
}
|
||||||
_ = i32t;
|
_ = i32t;
|
||||||
if (e.t.get(ra.ty) == .array) return .{ .res_array = ra };
|
return .{ .ra = ra, .nonuniform = nonuniform };
|
||||||
const res = e.resources.items[ra.res];
|
}
|
||||||
|
|
||||||
|
/// A handle for element `index` (flattened) of resource array `ri`.
|
||||||
|
fn elementHandle(e: *Emitter, ri: u32, index: Value, nonuniform: bool) Error!Lowered {
|
||||||
|
const res = e.resources.items[ri];
|
||||||
|
if (res.lib_global) |lg| {
|
||||||
|
var view = res;
|
||||||
|
view.view = true;
|
||||||
|
view.handle = try e.libArrayHandle(res, lg, index, nonuniform);
|
||||||
|
try e.resources.append(e.arena, view);
|
||||||
|
return .{ .handle = @intCast(e.resources.items.len - 1) };
|
||||||
|
}
|
||||||
const lb = e.binding(res).index;
|
const lb = e.binding(res).index;
|
||||||
const idx = try e.intArith(.add, ra.index orelse try e.i32Const(0), try e.i32Const(lb));
|
const idx = try e.intArith(.add, index, try e.i32Const(lb));
|
||||||
var view = res;
|
var view = res;
|
||||||
view.view = true;
|
view.view = true;
|
||||||
view.handle = try e.makeHandle(res, idx, nonuniform, false);
|
view.handle = try e.makeHandle(res, idx, nonuniform, false);
|
||||||
|
|
@ -3246,6 +3506,27 @@ const Emitter = struct {
|
||||||
return .{ .handle = @intCast(e.resources.items.len - 1) };
|
return .{ .handle = @intCast(e.resources.items.len - 1) };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A library's handle for element `index` of a resource array: of the
|
||||||
|
/// element loaded from the array's global.
|
||||||
|
fn libArrayHandle(e: *Emitter, res: Resource, lg: u32, index: Value, nonuniform: bool) Error!Value {
|
||||||
|
const i32t = try e.dm.intType(32);
|
||||||
|
const arr_ty = e.dm.globals.items[lg].ty;
|
||||||
|
const class_ty = e.dm.types.items[arr_ty].array.elem;
|
||||||
|
const ptr = try e.add(try e.dm.ptrType(class_ty), .{ .gep = .{ .elem = arr_ty, .ptr = .{ .global = lg }, .indices = try e.arena.dupe(Value, &.{ try e.i32Const(0), index }) } });
|
||||||
|
if (nonuniform) {
|
||||||
|
const blk = e.blocks.items[e.cur].items;
|
||||||
|
blk[blk.len - 1].inst.md = .{ .kind = try e.dm.mdKind("dx.nonuniform"), .node = try e.dm.mdNode(&.{try e.dm.mdI32(1)}) };
|
||||||
|
}
|
||||||
|
const loaded = try e.add(class_ty, .{ .load = .{ .ptr = ptr, .@"align" = 4 } });
|
||||||
|
const struct_name = e.dm.types.items[class_ty].@"struct".name;
|
||||||
|
const create = try e.dxOp(try std.fmt.allocPrint(e.arena, "dx.op.createHandleForLib.{s}", .{struct_name}), e.handle_ty, &.{ i32t, class_ty }, .nounwind_readonly);
|
||||||
|
const h = try e.callOp(create, e.handle_ty, &.{ try e.i32Const(160), loaded });
|
||||||
|
if (!e.self_sm66()) return h;
|
||||||
|
const props_ty = try e.dm.getType(.{ .@"struct" = .{ .name = "dx.types.ResourceProperties", .elems = &.{ i32t, i32t } } });
|
||||||
|
const annotate = try e.dxOp("dx.op.annotateHandle", e.handle_ty, &.{ i32t, e.handle_ty, props_ty }, .nounwind_readnone);
|
||||||
|
return e.callOp(annotate, e.handle_ty, &.{ try e.i32Const(216), h, try e.propertiesConst(res) });
|
||||||
|
}
|
||||||
|
|
||||||
fn constIntOf(e: *Emitter, v: Value) ?i64 {
|
fn constIntOf(e: *Emitter, v: Value) ?i64 {
|
||||||
if (v != .constant) return null;
|
if (v != .constant) return null;
|
||||||
return switch (e.dm.constants.items[v.constant].kind) {
|
return switch (e.dm.constants.items[v.constant].kind) {
|
||||||
|
|
@ -5196,13 +5477,20 @@ const Emitter = struct {
|
||||||
const f = &e.dm.functions.items[lf.func];
|
const f = &e.dm.functions.items[lf.func];
|
||||||
const name = try b.string(lf.name);
|
const name = try b.string(lf.name);
|
||||||
const unmangled = try b.string(lf.unmangled);
|
const unmangled = try b.string(lf.unmangled);
|
||||||
// Resources whose globals the function loads, in table order.
|
// Resources whose globals the function loads (or indexes, for
|
||||||
|
// arrays), in table order.
|
||||||
var used: std.ArrayList(u32) = .empty;
|
var used: std.ArrayList(u32) = .empty;
|
||||||
for (f.insts.items) |inst| if (inst.op == .load and inst.op.load.ptr == .global) {
|
for (f.insts.items) |inst| {
|
||||||
if (res_index.get(inst.op.load.ptr.global)) |ri| {
|
const ptr = switch (inst.op) {
|
||||||
|
.load => |l| l.ptr,
|
||||||
|
.gep => |g| g.ptr,
|
||||||
|
else => continue,
|
||||||
|
};
|
||||||
|
if (ptr != .global) continue;
|
||||||
|
if (res_index.get(ptr.global)) |ri| {
|
||||||
if (std.mem.indexOfScalar(u32, used.items, ri) == null) try used.append(e.arena, ri);
|
if (std.mem.indexOfScalar(u32, used.items, ri) == null) try used.append(e.arena, ri);
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
std.mem.sort(u32, used.items, {}, std.sort.asc(u32));
|
std.mem.sort(u32, used.items, {}, std.sort.asc(u32));
|
||||||
const resources = if (used.items.len > 0) try b.array(used.items) else rdat.null_ref;
|
const resources = if (used.items.len > 0) try b.array(used.items) else rdat.null_ref;
|
||||||
const props = if (e.uses_linalg) try linalg_info.rdatProperties(e.arena, &b, &try linalg_info.functionInfo(e.arena, &e.dm, mats, lf.func)) else rdat.null_ref;
|
const props = if (e.uses_linalg) try linalg_info.rdatProperties(e.arena, &b, &try linalg_info.functionInfo(e.arena, &e.dm, mats, lf.func)) else rdat.null_ref;
|
||||||
|
|
@ -5358,6 +5646,7 @@ const Emitter = struct {
|
||||||
try dm.addNamedMetadata("dx.shaderModel", &.{sm});
|
try dm.addNamedMetadata("dx.shaderModel", &.{sm});
|
||||||
if (resources) |r| try dm.addNamedMetadata("dx.resources", &.{r});
|
if (resources) |r| try dm.addNamedMetadata("dx.resources", &.{r});
|
||||||
try dm.addNamedMetadata("dx.entryPoints", &.{entry_md});
|
try dm.addNamedMetadata("dx.entryPoints", &.{entry_md});
|
||||||
|
_ = try promote.pruneDeclarations(e.arena, dm);
|
||||||
return dm.writeBitcode(dm.arena.child_allocator);
|
return dm.writeBitcode(dm.arena.child_allocator);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -5557,3 +5846,11 @@ fn reachableBlocks(a: Allocator, f: *const ir.Function) Allocator.Error![]bool {
|
||||||
}
|
}
|
||||||
return seen;
|
return seen;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Whether pointer `p` is into a function's own local (not a global or a
|
||||||
|
/// parameter's storage).
|
||||||
|
fn localRoot(f: *const ir.Function, p: Ref) bool {
|
||||||
|
var x = p;
|
||||||
|
while (f.inst(x).op == .access) x = f.inst(x).op.access.base;
|
||||||
|
return f.inst(x).op == .local_var;
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -306,6 +306,11 @@ fn handleRes(m: *const module.Module, f: *const module.Function, o: Options, h:
|
||||||
},
|
},
|
||||||
.load => |l| {
|
.load => |l| {
|
||||||
if (l.ptr == .global) return o.globals[l.ptr.global];
|
if (l.ptr == .global) return o.globals[l.ptr.global];
|
||||||
|
// An element of a resource array global.
|
||||||
|
if (l.ptr == .inst) switch (f.insts.items[l.ptr.inst].op) {
|
||||||
|
.gep => |g| if (g.ptr == .global) return o.globals[g.ptr.global],
|
||||||
|
else => {},
|
||||||
|
};
|
||||||
return null;
|
return null;
|
||||||
},
|
},
|
||||||
else => return null,
|
else => return null,
|
||||||
|
|
|
||||||
|
|
@ -69,7 +69,11 @@ pub fn global(a: Allocator, t: *TypeTable, name: []const u8, ty: TypeId) Allocat
|
||||||
var names: Names = .{};
|
var names: Names = .{};
|
||||||
try names.add(a, name);
|
try names.add(a, name);
|
||||||
try out.print(a, "\x01?{s}@@3", .{name});
|
try out.print(a, "\x01?{s}@@3", .{name});
|
||||||
try typeCode(a, t, ty, &out, &names);
|
// An array global: a pointer to its element.
|
||||||
|
if (t.get(ty) == .array) {
|
||||||
|
try out.appendSlice(a, "PA");
|
||||||
|
try typeCode(a, t, t.get(ty).array.elem, &out, &names);
|
||||||
|
} else try typeCode(a, t, ty, &out, &names);
|
||||||
try out.append(a, 'A');
|
try out.append(a, 'A');
|
||||||
return out.items;
|
return out.items;
|
||||||
}
|
}
|
||||||
|
|
@ -137,7 +141,7 @@ fn typeCode(a: Allocator, t: *TypeTable, ty: TypeId, out: *std.ArrayList(u8), na
|
||||||
var et = ty;
|
var et = ty;
|
||||||
while (t.get(et) == .array) : (et = t.get(et).array.elem) try dims.append(a, t.get(et).array.len);
|
while (t.get(et) == .array) : (et = t.get(et).array.elem) try dims.append(a, t.get(et).array.len);
|
||||||
try out.append(a, 'Y');
|
try out.append(a, 'Y');
|
||||||
try number(a, dims.items.len - 1, out);
|
try number(a, dims.items.len, out);
|
||||||
for (dims.items) |d| try number(a, d, out);
|
for (dims.items) |d| try number(a, d, out);
|
||||||
try typeCode(a, t, et, out, names);
|
try typeCode(a, t, et, out, names);
|
||||||
},
|
},
|
||||||
|
|
|
||||||
|
|
@ -106,6 +106,9 @@ pub const Inst = struct {
|
||||||
extractelement: struct { vec: Value, index: Value },
|
extractelement: struct { vec: Value, index: Value },
|
||||||
insertelement: struct { vec: Value, val: Value, index: Value },
|
insertelement: struct { vec: Value, val: Value, index: Value },
|
||||||
},
|
},
|
||||||
|
/// An attached metadata node (`kind` from Module.mdKind), as
|
||||||
|
/// `!dx.nonuniform` on a resource array's getelementptr.
|
||||||
|
md: ?struct { kind: u32, node: MdId } = null,
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const Function = struct {
|
pub const Function = struct {
|
||||||
|
|
@ -136,6 +139,8 @@ pub const Module = struct {
|
||||||
globals: std.ArrayList(GlobalVar) = .empty,
|
globals: std.ArrayList(GlobalVar) = .empty,
|
||||||
metadata: std.ArrayList(Metadata) = .empty,
|
metadata: std.ArrayList(Metadata) = .empty,
|
||||||
named_metadata: std.ArrayList(struct { name: []const u8, nodes: []const MdId }) = .empty,
|
named_metadata: std.ArrayList(struct { name: []const u8, nodes: []const MdId }) = .empty,
|
||||||
|
/// Instruction metadata kinds, by id.
|
||||||
|
md_kinds: std.ArrayList([]const u8) = .empty,
|
||||||
|
|
||||||
pub fn init(gpa: Allocator) Module {
|
pub fn init(gpa: Allocator) Module {
|
||||||
return .{ .arena = .init(gpa) };
|
return .{ .arena = .init(gpa) };
|
||||||
|
|
@ -250,6 +255,13 @@ pub const Module = struct {
|
||||||
return @intCast(m.metadata.items.len - 1);
|
return @intCast(m.metadata.items.len - 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The id of an instruction metadata kind.
|
||||||
|
pub fn mdKind(m: *Module, name: []const u8) !u32 {
|
||||||
|
for (m.md_kinds.items, 0..) |k, i| if (std.mem.eql(u8, k, name)) return @intCast(i);
|
||||||
|
try m.md_kinds.append(m.allocator(), try m.allocator().dupe(u8, name));
|
||||||
|
return @intCast(m.md_kinds.items.len - 1);
|
||||||
|
}
|
||||||
|
|
||||||
pub fn addNamedMetadata(m: *Module, name: []const u8, nodes: []const MdId) !void {
|
pub fn addNamedMetadata(m: *Module, name: []const u8, nodes: []const MdId) !void {
|
||||||
const a = m.allocator();
|
const a = m.allocator();
|
||||||
try m.named_metadata.append(a, .{ .name = try a.dupe(u8, name), .nodes = try a.dupe(MdId, nodes) });
|
try m.named_metadata.append(a, .{ .name = try a.dupe(u8, name), .nodes = try a.dupe(MdId, nodes) });
|
||||||
|
|
@ -270,6 +282,7 @@ const block_constants = 11;
|
||||||
const block_function = 12;
|
const block_function = 12;
|
||||||
const block_value_symtab = 14;
|
const block_value_symtab = 14;
|
||||||
const block_metadata = 15;
|
const block_metadata = 15;
|
||||||
|
const block_metadata_attachment = 16;
|
||||||
const block_type = 17;
|
const block_type = 17;
|
||||||
|
|
||||||
const Encoder = struct {
|
const Encoder = struct {
|
||||||
|
|
@ -371,6 +384,12 @@ const Encoder = struct {
|
||||||
}
|
}
|
||||||
try e.writeConstants();
|
try e.writeConstants();
|
||||||
try e.writeMetadata();
|
try e.writeMetadata();
|
||||||
|
if (e.m.md_kinds.items.len != 0) {
|
||||||
|
// METADATA_KIND: [id, name...]
|
||||||
|
try w.enterBlock(block_metadata, 3);
|
||||||
|
for (e.m.md_kinds.items, 0..) |k, id| try w.recordString(6, &.{id}, k);
|
||||||
|
try w.endBlock();
|
||||||
|
}
|
||||||
try e.writeSymtab();
|
try e.writeSymtab();
|
||||||
for (e.m.functions.items) |*f| {
|
for (e.m.functions.items) |*f| {
|
||||||
if (f.num_blocks != 0) try e.writeFunction(f);
|
if (f.num_blocks != 0) try e.writeFunction(f);
|
||||||
|
|
@ -681,6 +700,17 @@ const Encoder = struct {
|
||||||
}
|
}
|
||||||
if (e.m.types.items[inst.ty] != .void) inst_id += 1;
|
if (e.m.types.items[inst.ty] != .void) inst_id += 1;
|
||||||
}
|
}
|
||||||
|
// METADATA_ATTACHMENT: [instruction index, (kind, node)...]
|
||||||
|
var any_md = false;
|
||||||
|
for (f.insts.items) |inst| any_md = any_md or inst.md != null;
|
||||||
|
if (any_md) {
|
||||||
|
try w.enterBlock(block_metadata_attachment, 3);
|
||||||
|
for (f.insts.items, 0..) |inst, k| if (inst.md) |md| {
|
||||||
|
try e.ops.appendSlice(e.gpa(), &.{ k, md.kind, md.node });
|
||||||
|
try e.rec(11);
|
||||||
|
};
|
||||||
|
try w.endBlock();
|
||||||
|
}
|
||||||
try w.endBlock();
|
try w.endBlock();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,796 @@
|
||||||
|
//! Promotes locals from memory to SSA values, as LLVM's SROA and mem2reg do
|
||||||
|
//! for dxc. The emitter gives every local a flattened `[N x scalar]` alloca
|
||||||
|
//! (or a scalar one); an alloca whose every access is a load or store,
|
||||||
|
//! directly or through a getelementptr with constant indices, becomes one
|
||||||
|
//! SSA variable per element, with phis where control flow merges. Locals
|
||||||
|
//! indexed dynamically stay in memory, but only the components the dynamic
|
||||||
|
//! index can reach (`dyn`, from the emitter: the indexed array's extent);
|
||||||
|
//! the rest of such a local is still promoted. Locals used any other way
|
||||||
|
//! stay in memory.
|
||||||
|
//!
|
||||||
|
//! The phis go at the iterated dominance frontiers of the stores (Cytron et
|
||||||
|
//! al.), dominators by Cooper, Harvey and Kennedy's iteration. Phis whose
|
||||||
|
//! inputs are all one value, and phis nothing reads, are removed again.
|
||||||
|
|
||||||
|
const std = @import("std");
|
||||||
|
const Allocator = std.mem.Allocator;
|
||||||
|
const module = @import("module.zig");
|
||||||
|
|
||||||
|
const Value = module.Value;
|
||||||
|
const Inst = module.Inst;
|
||||||
|
const TypeId = module.TypeId;
|
||||||
|
|
||||||
|
const none = std.math.maxInt(u32);
|
||||||
|
|
||||||
|
const Role = enum { load_ptr, store_ptr, gep_base, other };
|
||||||
|
|
||||||
|
const Edge = @typeInfo(@FieldType(@FieldType(@FieldType(Inst, "op"), "phi"), "incoming")).pointer.child;
|
||||||
|
|
||||||
|
/// Visits each operand of `inst` (with the way it is used) through
|
||||||
|
/// `ctx.visit(value, role) Value`. With `write`, the results replace the
|
||||||
|
/// operands, in newly allocated slices where the operands are slices.
|
||||||
|
fn operands(comptime write: bool, a: Allocator, inst: *Inst, ctx: anytype) Allocator.Error!void {
|
||||||
|
const S = struct {
|
||||||
|
fn one(c: anytype, v: *Value, role: Role) void {
|
||||||
|
const r = c.visit(v.*, role);
|
||||||
|
if (write) v.* = r;
|
||||||
|
}
|
||||||
|
fn many(al: Allocator, c: anytype, vs: *[]const Value) Allocator.Error!void {
|
||||||
|
if (!write) {
|
||||||
|
for (vs.*) |v| _ = c.visit(v, .other);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const out = try al.alloc(Value, vs.len);
|
||||||
|
for (vs.*, out) |v, *o| o.* = c.visit(v, .other);
|
||||||
|
vs.* = out;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
switch (inst.op) {
|
||||||
|
.ret => |*v| if (v.*) |*x| S.one(ctx, x, .other),
|
||||||
|
.br => |*b| if (b.cond) |*c| S.one(ctx, c, .other),
|
||||||
|
.@"switch" => |*sw| S.one(ctx, &sw.cond, .other),
|
||||||
|
.call => |*c| try S.many(a, ctx, &c.args),
|
||||||
|
.binop => |*b| {
|
||||||
|
S.one(ctx, &b.lhs, .other);
|
||||||
|
S.one(ctx, &b.rhs, .other);
|
||||||
|
},
|
||||||
|
.cast => |*c| S.one(ctx, &c.val, .other),
|
||||||
|
.cmp => |*c| {
|
||||||
|
S.one(ctx, &c.lhs, .other);
|
||||||
|
S.one(ctx, &c.rhs, .other);
|
||||||
|
},
|
||||||
|
.select => |*s| {
|
||||||
|
S.one(ctx, &s.cond, .other);
|
||||||
|
S.one(ctx, &s.t, .other);
|
||||||
|
S.one(ctx, &s.f, .other);
|
||||||
|
},
|
||||||
|
.extractvalue => |*x| S.one(ctx, &x.agg, .other),
|
||||||
|
.phi => |*p| {
|
||||||
|
if (!write) {
|
||||||
|
for (p.incoming) |in| _ = ctx.visit(in.val, .other);
|
||||||
|
} else {
|
||||||
|
const out = try a.alloc(Edge, p.incoming.len);
|
||||||
|
for (p.incoming, out) |in, *o| o.* = .{ .val = ctx.visit(in.val, .other), .block = in.block };
|
||||||
|
p.incoming = out;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
.alloca => |*x| S.one(ctx, &x.size, .other),
|
||||||
|
.load => |*x| S.one(ctx, &x.ptr, .load_ptr),
|
||||||
|
.store => |*x| {
|
||||||
|
S.one(ctx, &x.ptr, .store_ptr);
|
||||||
|
S.one(ctx, &x.val, .other);
|
||||||
|
},
|
||||||
|
.gep => |*x| {
|
||||||
|
S.one(ctx, &x.ptr, .gep_base);
|
||||||
|
try S.many(a, ctx, &x.indices);
|
||||||
|
},
|
||||||
|
.atomicrmw => |*x| {
|
||||||
|
S.one(ctx, &x.ptr, .other);
|
||||||
|
S.one(ctx, &x.val, .other);
|
||||||
|
},
|
||||||
|
.cmpxchg => |*x| {
|
||||||
|
S.one(ctx, &x.ptr, .other);
|
||||||
|
S.one(ctx, &x.cmp, .other);
|
||||||
|
S.one(ctx, &x.new, .other);
|
||||||
|
},
|
||||||
|
.@"unreachable" => {},
|
||||||
|
.extractelement => |*x| {
|
||||||
|
S.one(ctx, &x.vec, .other);
|
||||||
|
S.one(ctx, &x.index, .other);
|
||||||
|
},
|
||||||
|
.insertelement => |*x| {
|
||||||
|
S.one(ctx, &x.vec, .other);
|
||||||
|
S.one(ctx, &x.val, .other);
|
||||||
|
S.one(ctx, &x.index, .other);
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn isTerminator(inst: Inst) bool {
|
||||||
|
return switch (inst.op) {
|
||||||
|
.ret, .br, .@"switch", .@"unreachable" => true,
|
||||||
|
else => false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
fn isScalar(m: *const module.Module, ty: TypeId) bool {
|
||||||
|
return switch (m.types.items[ty]) {
|
||||||
|
.half, .float, .double, .int => true,
|
||||||
|
else => false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `dyn` maps the dynamically indexed getelementptrs into locals to the
|
||||||
|
/// components [lo, hi) they can reach; one missing from it can reach all.
|
||||||
|
pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashMapUnmanaged(u32, [2]u32)) Allocator.Error!void {
|
||||||
|
const f = &m.functions.items[func];
|
||||||
|
const insts = f.insts.items;
|
||||||
|
const n: u32 = @intCast(insts.len);
|
||||||
|
const nb = f.num_blocks;
|
||||||
|
if (n == 0 or nb == 0) return;
|
||||||
|
|
||||||
|
// Blocks: instruction ranges, successors and predecessors (one entry
|
||||||
|
// per edge, so a switch's repeated target counts once per case).
|
||||||
|
const block_start = try a.alloc(u32, nb + 1);
|
||||||
|
const block_of = try a.alloc(u32, n);
|
||||||
|
{
|
||||||
|
var b: u32 = 0;
|
||||||
|
block_start[0] = 0;
|
||||||
|
for (insts, 0..) |inst, i| {
|
||||||
|
if (b >= nb) return; // not the block layout this pass expects
|
||||||
|
block_of[i] = b;
|
||||||
|
if (isTerminator(inst)) {
|
||||||
|
b += 1;
|
||||||
|
block_start[b] = @intCast(i + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (b != nb) return;
|
||||||
|
}
|
||||||
|
const succ_off = try a.alloc(u32, nb + 1);
|
||||||
|
var succs: std.ArrayList(u32) = .empty;
|
||||||
|
for (0..nb) |b| {
|
||||||
|
succ_off[b] = @intCast(succs.items.len);
|
||||||
|
switch (insts[block_start[b + 1] - 1].op) {
|
||||||
|
.br => |br| {
|
||||||
|
try succs.append(a, br.then);
|
||||||
|
if (br.@"else") |e| try succs.append(a, e);
|
||||||
|
},
|
||||||
|
.@"switch" => |sw| {
|
||||||
|
try succs.append(a, sw.default);
|
||||||
|
for (sw.cases) |c| try succs.append(a, c.block);
|
||||||
|
},
|
||||||
|
else => {},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
succ_off[nb] = @intCast(succs.items.len);
|
||||||
|
const pred_off = try a.alloc(u32, nb + 1);
|
||||||
|
@memset(pred_off, 0);
|
||||||
|
for (succs.items) |s| pred_off[s + 1] += 1;
|
||||||
|
for (1..nb + 1) |b| pred_off[b] += pred_off[b - 1];
|
||||||
|
const preds = try a.alloc(u32, succs.items.len);
|
||||||
|
{
|
||||||
|
const fill = try a.dupe(u32, pred_off[0..nb]);
|
||||||
|
for (0..nb) |b| for (succs.items[succ_off[b]..succ_off[b + 1]]) |s| {
|
||||||
|
preds[fill[s]] = @intCast(b);
|
||||||
|
fill[s] += 1;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reverse postorder from the entry; unreachable blocks stay `none`.
|
||||||
|
const rpo_index = try a.alloc(u32, nb);
|
||||||
|
@memset(rpo_index, none);
|
||||||
|
const rpo = try a.alloc(u32, nb);
|
||||||
|
var nr: u32 = 0;
|
||||||
|
{
|
||||||
|
const post = try a.alloc(u32, nb);
|
||||||
|
var np: u32 = 0;
|
||||||
|
const seen = try a.alloc(bool, nb);
|
||||||
|
@memset(seen, false);
|
||||||
|
const Frame = struct { b: u32, next: u32 };
|
||||||
|
var stack: std.ArrayList(Frame) = .empty;
|
||||||
|
try stack.append(a, .{ .b = 0, .next = succ_off[0] });
|
||||||
|
seen[0] = true;
|
||||||
|
while (stack.items.len > 0) {
|
||||||
|
const top = &stack.items[stack.items.len - 1];
|
||||||
|
if (top.next < succ_off[top.b + 1]) {
|
||||||
|
const s = succs.items[top.next];
|
||||||
|
top.next += 1;
|
||||||
|
if (!seen[s]) {
|
||||||
|
seen[s] = true;
|
||||||
|
try stack.append(a, .{ .b = s, .next = succ_off[s] });
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
post[np] = top.b;
|
||||||
|
np += 1;
|
||||||
|
_ = stack.pop();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (0..np) |k| {
|
||||||
|
rpo[k] = post[np - 1 - k];
|
||||||
|
rpo_index[rpo[k]] = @intCast(k);
|
||||||
|
}
|
||||||
|
nr = np;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Immediate dominators.
|
||||||
|
const idom = try a.alloc(u32, nb);
|
||||||
|
@memset(idom, none);
|
||||||
|
idom[0] = 0;
|
||||||
|
{
|
||||||
|
var changed = true;
|
||||||
|
while (changed) {
|
||||||
|
changed = false;
|
||||||
|
for (rpo[1..nr]) |b| {
|
||||||
|
var new: u32 = none;
|
||||||
|
for (preds[pred_off[b]..pred_off[b + 1]]) |p| {
|
||||||
|
if (idom[p] == none) continue;
|
||||||
|
if (new == none) {
|
||||||
|
new = p;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
var x = p;
|
||||||
|
var y = new;
|
||||||
|
while (x != y) {
|
||||||
|
while (rpo_index[x] > rpo_index[y]) x = idom[x];
|
||||||
|
while (rpo_index[y] > rpo_index[x]) y = idom[y];
|
||||||
|
}
|
||||||
|
new = x;
|
||||||
|
}
|
||||||
|
if (new != idom[b]) {
|
||||||
|
idom[b] = new;
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Dominance frontiers.
|
||||||
|
const df = try a.alloc(std.ArrayList(u32), nb);
|
||||||
|
@memset(df, .empty);
|
||||||
|
for (rpo[0..nr]) |b| {
|
||||||
|
const ps = preds[pred_off[b]..pred_off[b + 1]];
|
||||||
|
if (ps.len < 2) continue;
|
||||||
|
for (ps) |p| {
|
||||||
|
if (rpo_index[p] == none) continue;
|
||||||
|
var r = p;
|
||||||
|
while (r != idom[b]) {
|
||||||
|
const l = &df[r];
|
||||||
|
if (l.items.len == 0 or l.items[l.items.len - 1] != b) try l.append(a, b);
|
||||||
|
r = idom[r];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Candidate allocas: arrays of scalars and scalars. `var_base[i]` is
|
||||||
|
// the variable of an alloca's element 0, `none` if it stays in memory.
|
||||||
|
const var_base = try a.alloc(u32, n);
|
||||||
|
@memset(var_base, none);
|
||||||
|
const elem_ty = try a.alloc(TypeId, n);
|
||||||
|
const direct = try a.alloc(bool, n);
|
||||||
|
for (insts, 0..) |inst, i| switch (inst.op) {
|
||||||
|
.alloca => |x| switch (m.types.items[x.elem]) {
|
||||||
|
.array => |arr| if (isScalar(m, arr.elem) and arr.len > 0) {
|
||||||
|
var_base[i] = 0;
|
||||||
|
elem_ty[i] = arr.elem;
|
||||||
|
direct[i] = false;
|
||||||
|
},
|
||||||
|
else => if (isScalar(m, x.elem)) {
|
||||||
|
var_base[i] = 0;
|
||||||
|
elem_ty[i] = x.elem;
|
||||||
|
direct[i] = true;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
else => {},
|
||||||
|
};
|
||||||
|
// getelementptrs of candidates: the alloca and the element they
|
||||||
|
// address (`none` for a dynamic index, which pins its range).
|
||||||
|
const gep_alloca = try a.alloc(u32, n);
|
||||||
|
@memset(gep_alloca, none);
|
||||||
|
const gep_k = try a.alloc(u32, n);
|
||||||
|
const Scan = struct {
|
||||||
|
insts: []const Inst,
|
||||||
|
var_base: []u32,
|
||||||
|
direct: []const bool,
|
||||||
|
gep_alloca: []const u32,
|
||||||
|
|
||||||
|
fn visit(s: *@This(), v: Value, role: Role) Value {
|
||||||
|
if (v != .inst) return v;
|
||||||
|
const i = v.inst;
|
||||||
|
if (s.var_base[i] != none and s.insts[i].op == .alloca) {
|
||||||
|
const ok = switch (role) {
|
||||||
|
.gep_base => !s.direct[i],
|
||||||
|
.load_ptr, .store_ptr => s.direct[i],
|
||||||
|
.other => false,
|
||||||
|
};
|
||||||
|
if (!ok) s.var_base[i] = none;
|
||||||
|
} else if (s.gep_alloca[i] != none and role != .load_ptr and role != .store_ptr) {
|
||||||
|
s.var_base[s.gep_alloca[i]] = none;
|
||||||
|
}
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
for (insts, 0..) |inst, i| switch (inst.op) {
|
||||||
|
.gep => |g| if (g.ptr == .inst and var_base[g.ptr.inst] != none and insts[g.ptr.inst].op == .alloca) {
|
||||||
|
const al = g.ptr.inst;
|
||||||
|
if (direct[al]) {
|
||||||
|
var_base[al] = none;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const k = constIndex(m, g.indices, m.types.items[insts[al].op.alloca.elem].array.len);
|
||||||
|
if (k) |kk| {
|
||||||
|
gep_alloca[i] = al;
|
||||||
|
gep_k[i] = kk;
|
||||||
|
} else if (dyn.contains(@intCast(i)) and g.indices.len == 2 and constInt(m, g.indices[0]) == 0) {
|
||||||
|
gep_alloca[i] = al;
|
||||||
|
gep_k[i] = none;
|
||||||
|
} else var_base[al] = none;
|
||||||
|
},
|
||||||
|
else => {},
|
||||||
|
};
|
||||||
|
{
|
||||||
|
var scan: Scan = .{ .insts = insts, .var_base = var_base, .direct = direct, .gep_alloca = gep_alloca };
|
||||||
|
for (insts) |*inst| try operands(false, a, inst, &scan);
|
||||||
|
}
|
||||||
|
// Loads and stores must move whole elements of the element type.
|
||||||
|
for (insts) |inst| {
|
||||||
|
const ptr, const ty = switch (inst.op) {
|
||||||
|
.load => |x| .{ x.ptr, inst.ty },
|
||||||
|
.store => |x| .{ x.ptr, typeOf(m, f, x.val) },
|
||||||
|
else => continue,
|
||||||
|
};
|
||||||
|
if (ptr != .inst) continue;
|
||||||
|
const al = if (gep_alloca[ptr.inst] != none) gep_alloca[ptr.inst] else ptr.inst;
|
||||||
|
if (var_base[al] != none and insts[al].op == .alloca and ty != elem_ty[al]) var_base[al] = none;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Variables.
|
||||||
|
var nv: u32 = 0;
|
||||||
|
for (insts, 0..) |inst, i| {
|
||||||
|
if (inst.op != .alloca or var_base[i] == none) continue;
|
||||||
|
var_base[i] = nv;
|
||||||
|
nv += if (direct[i]) 1 else @intCast(m.types.items[inst.op.alloca.elem].array.len);
|
||||||
|
}
|
||||||
|
if (nv == 0) return;
|
||||||
|
const var_ty = try a.alloc(TypeId, nv);
|
||||||
|
for (insts, 0..) |inst, i| {
|
||||||
|
if (inst.op != .alloca or var_base[i] == none) continue;
|
||||||
|
const len: u32 = if (direct[i]) 1 else @intCast(m.types.items[inst.op.alloca.elem].array.len);
|
||||||
|
@memset(var_ty[var_base[i]..][0..len], elem_ty[i]);
|
||||||
|
}
|
||||||
|
// Components a dynamic index can reach stay in memory, and so does
|
||||||
|
// their alloca.
|
||||||
|
const pinned = try a.alloc(bool, nv);
|
||||||
|
@memset(pinned, false);
|
||||||
|
const keep = try a.alloc(bool, n);
|
||||||
|
@memset(keep, false);
|
||||||
|
for (insts, 0..) |inst, i| {
|
||||||
|
if (inst.op != .gep or gep_alloca[i] == none or gep_k[i] != none) continue;
|
||||||
|
const al = gep_alloca[i];
|
||||||
|
if (var_base[al] == none) continue;
|
||||||
|
const len: u32 = @intCast(m.types.items[insts[al].op.alloca.elem].array.len);
|
||||||
|
const r = dyn.get(@intCast(i)).?;
|
||||||
|
const lo = @min(r[0], len);
|
||||||
|
const hi = @min(r[1], len);
|
||||||
|
@memset(pinned[var_base[al] + lo .. var_base[al] + hi], true);
|
||||||
|
keep[al] = true;
|
||||||
|
}
|
||||||
|
// The variable an instruction loads or stores, or `none`.
|
||||||
|
const access = try a.alloc(u32, n);
|
||||||
|
@memset(access, none);
|
||||||
|
for (insts, 0..) |inst, i| {
|
||||||
|
const ptr = switch (inst.op) {
|
||||||
|
.load => |x| x.ptr,
|
||||||
|
.store => |x| x.ptr,
|
||||||
|
else => continue,
|
||||||
|
};
|
||||||
|
if (ptr != .inst) continue;
|
||||||
|
const p = ptr.inst;
|
||||||
|
if (gep_alloca[p] != none and var_base[gep_alloca[p]] != none) {
|
||||||
|
if (gep_k[p] != none and !pinned[var_base[gep_alloca[p]] + gep_k[p]]) access[i] = var_base[gep_alloca[p]] + gep_k[p];
|
||||||
|
} else if (insts[p].op == .alloca and var_base[p] != none) {
|
||||||
|
access[i] = var_base[p];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A variable needs phis unless all its accesses are in one block and
|
||||||
|
// the first is a store. Collect the blocks that store the others.
|
||||||
|
const first_block = try a.alloc(u32, nv);
|
||||||
|
@memset(first_block, none);
|
||||||
|
const global = try a.alloc(bool, nv);
|
||||||
|
@memset(global, false);
|
||||||
|
for (insts, 0..) |inst, i| {
|
||||||
|
const v = access[i];
|
||||||
|
if (v == none) continue;
|
||||||
|
if (first_block[v] == none) {
|
||||||
|
first_block[v] = block_of[i];
|
||||||
|
if (inst.op == .load) global[v] = true;
|
||||||
|
} else if (first_block[v] != block_of[i]) global[v] = true;
|
||||||
|
}
|
||||||
|
const Def = struct { v: u32, b: u32 };
|
||||||
|
var defs: std.ArrayList(Def) = .empty;
|
||||||
|
for (insts, 0..) |inst, i| {
|
||||||
|
const v = access[i];
|
||||||
|
if (v == none or inst.op != .store or !global[v] or rpo_index[block_of[i]] == none) continue;
|
||||||
|
try defs.append(a, .{ .v = v, .b = block_of[i] });
|
||||||
|
}
|
||||||
|
std.sort.pdq(Def, defs.items, {}, struct {
|
||||||
|
fn lt(_: void, x: Def, y: Def) bool {
|
||||||
|
return if (x.v != y.v) x.v < y.v else x.b < y.b;
|
||||||
|
}
|
||||||
|
}.lt);
|
||||||
|
|
||||||
|
// Phis at the iterated dominance frontiers.
|
||||||
|
var phi_var: std.ArrayList(u32) = .empty;
|
||||||
|
var phi_block: std.ArrayList(u32) = .empty;
|
||||||
|
{
|
||||||
|
const has_phi = try a.alloc(u32, nb);
|
||||||
|
@memset(has_phi, none);
|
||||||
|
const queued = try a.alloc(u32, nb);
|
||||||
|
@memset(queued, none);
|
||||||
|
var work: std.ArrayList(u32) = .empty;
|
||||||
|
var k: usize = 0;
|
||||||
|
while (k < defs.items.len) {
|
||||||
|
const v = defs.items[k].v;
|
||||||
|
work.clearRetainingCapacity();
|
||||||
|
while (k < defs.items.len and defs.items[k].v == v) : (k += 1) {
|
||||||
|
const b = defs.items[k].b;
|
||||||
|
if (queued[b] != v) {
|
||||||
|
queued[b] = v;
|
||||||
|
try work.append(a, b);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
while (work.pop()) |b| for (df[b].items) |y| {
|
||||||
|
if (has_phi[y] == v) continue;
|
||||||
|
has_phi[y] = v;
|
||||||
|
try phi_var.append(a, v);
|
||||||
|
try phi_block.append(a, y);
|
||||||
|
if (queued[y] != v) {
|
||||||
|
queued[y] = v;
|
||||||
|
try work.append(a, y);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const np: u32 = @intCast(phi_var.items.len);
|
||||||
|
// Phis per block, and their incoming edges (filled while renaming).
|
||||||
|
const bphi_off = try a.alloc(u32, nb + 1);
|
||||||
|
@memset(bphi_off, 0);
|
||||||
|
for (phi_block.items) |b| bphi_off[b + 1] += 1;
|
||||||
|
for (1..nb + 1) |b| bphi_off[b] += bphi_off[b - 1];
|
||||||
|
const bphis = try a.alloc(u32, np);
|
||||||
|
{
|
||||||
|
const fill = try a.dupe(u32, bphi_off[0..nb]);
|
||||||
|
for (phi_block.items, 0..) |b, j| {
|
||||||
|
bphis[fill[b]] = @intCast(j);
|
||||||
|
fill[b] += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const incoming = try a.alloc([]Edge, np);
|
||||||
|
const filled = try a.alloc(u32, np);
|
||||||
|
@memset(filled, 0);
|
||||||
|
for (incoming, phi_block.items) |*in, b| in.* = try a.alloc(Edge, pred_off[b + 1] - pred_off[b]);
|
||||||
|
|
||||||
|
// Renaming, over the dominator tree. A load's replacement goes to
|
||||||
|
// `repl`; phi `j` is the value `.{ .inst = n + j }` until rebuilt.
|
||||||
|
// A local read before any store reads zero: the validator rejects
|
||||||
|
// instructions that read undef.
|
||||||
|
var zeros: std.AutoHashMapUnmanaged(TypeId, Value) = .empty;
|
||||||
|
const Zero = struct {
|
||||||
|
fn get(al: Allocator, mm: *module.Module, cache: *std.AutoHashMapUnmanaged(TypeId, Value), ty: TypeId) Allocator.Error!Value {
|
||||||
|
const gop = try cache.getOrPut(al, ty);
|
||||||
|
if (!gop.found_existing) gop.value_ptr.* = try mm.constant(.{ .ty = ty, .kind = switch (mm.types.items[ty]) {
|
||||||
|
.int => .{ .int = 0 },
|
||||||
|
else => .{ .float_bits = 0 },
|
||||||
|
} });
|
||||||
|
return gop.value_ptr.*;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const repl = try a.alloc(?Value, n + np);
|
||||||
|
@memset(repl, null);
|
||||||
|
const cur = try a.alloc(Value, nv);
|
||||||
|
for (cur, var_ty) |*c, t| c.* = try Zero.get(a, m, &zeros, t);
|
||||||
|
{
|
||||||
|
const child_off = try a.alloc(u32, nb + 1);
|
||||||
|
@memset(child_off, 0);
|
||||||
|
for (rpo[1..nr]) |b| child_off[idom[b] + 1] += 1;
|
||||||
|
for (1..nb + 1) |b| child_off[b] += child_off[b - 1];
|
||||||
|
const children = try a.alloc(u32, nr);
|
||||||
|
{
|
||||||
|
const fill = try a.dupe(u32, child_off[0..nb]);
|
||||||
|
for (rpo[1..nr]) |b| {
|
||||||
|
children[fill[idom[b]]] = b;
|
||||||
|
fill[idom[b]] += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const Undo = struct { v: u32, old: Value };
|
||||||
|
var log: std.ArrayList(Undo) = .empty;
|
||||||
|
const Visit = struct { b: u32, mark: u32, enter: bool };
|
||||||
|
var stack: std.ArrayList(Visit) = .empty;
|
||||||
|
try stack.append(a, .{ .b = 0, .mark = 0, .enter = true });
|
||||||
|
while (stack.pop()) |top| {
|
||||||
|
if (!top.enter) {
|
||||||
|
while (log.items.len > top.mark) {
|
||||||
|
const u = log.pop().?;
|
||||||
|
cur[u.v] = u.old;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const b = top.b;
|
||||||
|
try stack.append(a, .{ .b = b, .mark = @intCast(log.items.len), .enter = false });
|
||||||
|
for (bphis[bphi_off[b]..bphi_off[b + 1]]) |j| {
|
||||||
|
const v = phi_var.items[j];
|
||||||
|
try log.append(a, .{ .v = v, .old = cur[v] });
|
||||||
|
cur[v] = .{ .inst = n + j };
|
||||||
|
}
|
||||||
|
for (block_start[b]..block_start[b + 1]) |i| {
|
||||||
|
const v = access[i];
|
||||||
|
if (v == none) continue;
|
||||||
|
switch (insts[i].op) {
|
||||||
|
.load => repl[i] = cur[v],
|
||||||
|
.store => |x| {
|
||||||
|
try log.append(a, .{ .v = v, .old = cur[v] });
|
||||||
|
cur[v] = resolve(repl, x.val);
|
||||||
|
},
|
||||||
|
else => unreachable,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (succs.items[succ_off[b]..succ_off[b + 1]]) |s| for (bphis[bphi_off[s]..bphi_off[s + 1]]) |j| {
|
||||||
|
incoming[j][filled[j]] = .{ .val = cur[phi_var.items[j]], .block = b };
|
||||||
|
filled[j] += 1;
|
||||||
|
};
|
||||||
|
for (children[child_off[b]..child_off[b + 1]]) |c| try stack.append(a, .{ .b = c, .mark = 0, .enter = true });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Edges from unreachable blocks bring zero; loads there read zero.
|
||||||
|
for (0..np) |j| {
|
||||||
|
const b = phi_block.items[j];
|
||||||
|
for (preds[pred_off[b]..pred_off[b + 1]]) |p| {
|
||||||
|
if (rpo_index[p] != none) continue;
|
||||||
|
incoming[j][filled[j]] = .{ .val = try Zero.get(a, m, &zeros, var_ty[phi_var.items[j]]), .block = p };
|
||||||
|
filled[j] += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (insts, 0..) |inst, i| {
|
||||||
|
if (access[i] != none and inst.op == .load and repl[i] == null)
|
||||||
|
repl[i] = try Zero.get(a, m, &zeros, var_ty[access[i]]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Phis whose inputs (besides themselves) are one value become it.
|
||||||
|
const removed_phi = try a.alloc(bool, np);
|
||||||
|
@memset(removed_phi, false);
|
||||||
|
{
|
||||||
|
var changed = true;
|
||||||
|
while (changed) {
|
||||||
|
changed = false;
|
||||||
|
for (0..np) |j| {
|
||||||
|
if (removed_phi[j]) continue;
|
||||||
|
const self: Value = .{ .inst = n + @as(u32, @intCast(j)) };
|
||||||
|
var same: ?Value = null;
|
||||||
|
var trivial = true;
|
||||||
|
for (incoming[j]) |in| {
|
||||||
|
const x = resolve(repl, in.val);
|
||||||
|
if (std.meta.eql(x, self)) continue;
|
||||||
|
if (same) |s| {
|
||||||
|
if (!std.meta.eql(s, x)) {
|
||||||
|
trivial = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
} else same = x;
|
||||||
|
}
|
||||||
|
if (!trivial) continue;
|
||||||
|
repl[n + j] = same orelse try Zero.get(a, m, &zeros, var_ty[phi_var.items[j]]);
|
||||||
|
removed_phi[j] = true;
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The instructions that go: promoted allocas, their getelementptrs,
|
||||||
|
// loads and stores.
|
||||||
|
const removed = try a.alloc(bool, n);
|
||||||
|
for (insts, 0..) |inst, i| removed[i] = switch (inst.op) {
|
||||||
|
.alloca => var_base[i] != none and !keep[i],
|
||||||
|
.gep => gep_alloca[i] != none and var_base[gep_alloca[i]] != none and gep_k[i] != none and !pinned[var_base[gep_alloca[i]] + gep_k[i]],
|
||||||
|
.load, .store => access[i] != none,
|
||||||
|
else => false,
|
||||||
|
};
|
||||||
|
|
||||||
|
// What stays: instructions with effects, and what they read,
|
||||||
|
// transitively; new phis likewise. (The loads promotion leaves dead,
|
||||||
|
// such as copies of arguments never read, go too.)
|
||||||
|
const live = try a.alloc(bool, n + np);
|
||||||
|
@memset(live, false);
|
||||||
|
{
|
||||||
|
var work: std.ArrayList(u32) = .empty;
|
||||||
|
const Mark = struct {
|
||||||
|
repl: []const ?Value,
|
||||||
|
live: []bool,
|
||||||
|
removed: []const bool,
|
||||||
|
work: *std.ArrayList(u32),
|
||||||
|
a: Allocator,
|
||||||
|
failed: bool = false,
|
||||||
|
|
||||||
|
fn visit(s: *@This(), v: Value, _: Role) Value {
|
||||||
|
const x = resolve(s.repl, v);
|
||||||
|
if (x == .inst and !s.live[x.inst] and !(x.inst < s.removed.len and s.removed[x.inst])) {
|
||||||
|
s.live[x.inst] = true;
|
||||||
|
s.work.append(s.a, x.inst) catch {
|
||||||
|
s.failed = true;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var mark: Mark = .{ .repl = repl, .live = live, .removed = removed, .work = &work, .a = a };
|
||||||
|
for (insts, 0..) |inst, i| if (!removed[i] and hasEffects(m, inst)) {
|
||||||
|
live[i] = true;
|
||||||
|
try work.append(a, @intCast(i));
|
||||||
|
};
|
||||||
|
while (work.pop()) |x| {
|
||||||
|
if (x < n) {
|
||||||
|
var inst = insts[x];
|
||||||
|
try operands(false, a, &inst, &mark);
|
||||||
|
} else for (incoming[x - n]) |in| {
|
||||||
|
_ = mark.visit(in.val, .other);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (mark.failed) return error.OutOfMemory;
|
||||||
|
}
|
||||||
|
|
||||||
|
// New indices: in each block the existing phis, then the new ones,
|
||||||
|
// then the rest.
|
||||||
|
const index = try a.alloc(u32, n + np);
|
||||||
|
@memset(index, none);
|
||||||
|
var count: u32 = 0;
|
||||||
|
for (0..nb) |b| {
|
||||||
|
var i = block_start[b];
|
||||||
|
while (i < block_start[b + 1] and insts[i].op == .phi) : (i += 1) if (live[i]) {
|
||||||
|
index[i] = count;
|
||||||
|
count += 1;
|
||||||
|
};
|
||||||
|
for (bphis[bphi_off[b]..bphi_off[b + 1]]) |j| if (live[n + j]) {
|
||||||
|
index[n + j] = count;
|
||||||
|
count += 1;
|
||||||
|
};
|
||||||
|
while (i < block_start[b + 1]) : (i += 1) if (live[i]) {
|
||||||
|
index[i] = count;
|
||||||
|
count += 1;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const Map = struct {
|
||||||
|
repl: []const ?Value,
|
||||||
|
index: []const u32,
|
||||||
|
fn visit(s: *@This(), v: Value, _: Role) Value {
|
||||||
|
const x = resolve(s.repl, v);
|
||||||
|
return if (x == .inst) .{ .inst = s.index[x.inst] } else x;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var map: Map = .{ .repl = repl, .index = index };
|
||||||
|
const ma = m.allocator();
|
||||||
|
var out: std.ArrayList(Inst) = .empty;
|
||||||
|
try out.ensureTotalCapacityPrecise(ma, count);
|
||||||
|
for (0..nb) |b| {
|
||||||
|
var i = block_start[b];
|
||||||
|
while (i < block_start[b + 1] and insts[i].op == .phi) : (i += 1) if (live[i]) {
|
||||||
|
var inst = insts[i];
|
||||||
|
try operands(true, ma, &inst, &map);
|
||||||
|
out.appendAssumeCapacity(inst);
|
||||||
|
};
|
||||||
|
for (bphis[bphi_off[b]..bphi_off[b + 1]]) |j| if (live[n + j]) {
|
||||||
|
const edges = try ma.alloc(Edge, incoming[j].len);
|
||||||
|
for (incoming[j], edges) |in, *e| e.* = .{ .val = map.visit(in.val, .other), .block = in.block };
|
||||||
|
out.appendAssumeCapacity(.{ .ty = var_ty[phi_var.items[j]], .op = .{ .phi = .{ .incoming = edges } } });
|
||||||
|
};
|
||||||
|
while (i < block_start[b + 1]) : (i += 1) if (live[i]) {
|
||||||
|
var inst = insts[i];
|
||||||
|
try operands(true, ma, &inst, &map);
|
||||||
|
out.appendAssumeCapacity(inst);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
f.insts = out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Instructions that must stay even when nothing reads their result.
|
||||||
|
fn hasEffects(m: *const module.Module, inst: Inst) bool {
|
||||||
|
return switch (inst.op) {
|
||||||
|
.ret, .br, .@"switch", .@"unreachable", .store, .atomicrmw, .cmpxchg => true,
|
||||||
|
.call => |c| switch (m.functions.items[c.callee].attrs) {
|
||||||
|
.nounwind_readnone, .nounwind_readonly => false,
|
||||||
|
else => true,
|
||||||
|
},
|
||||||
|
else => false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `v` with replaced loads and phis followed to their final value.
|
||||||
|
fn resolve(repl: []const ?Value, v: Value) Value {
|
||||||
|
var x = v;
|
||||||
|
while (x == .inst) {
|
||||||
|
const r = repl[x.inst] orelse break;
|
||||||
|
x = r;
|
||||||
|
}
|
||||||
|
return x;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Element `k` of `getelementptr [len x T], %a, 0, k`, or null.
|
||||||
|
fn constIndex(m: *const module.Module, indices: []const Value, len: u64) ?u32 {
|
||||||
|
if (indices.len != 2) return null;
|
||||||
|
const first = constInt(m, indices[0]) orelse return null;
|
||||||
|
const k = constInt(m, indices[1]) orelse return null;
|
||||||
|
if (first != 0 or k < 0 or k >= len) return null;
|
||||||
|
return @intCast(k);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn constInt(m: *const module.Module, v: Value) ?i64 {
|
||||||
|
if (v != .constant) return null;
|
||||||
|
return switch (m.constants.items[v.constant].kind) {
|
||||||
|
.int => |x| x,
|
||||||
|
else => null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
fn typeOf(m: *const module.Module, f: *const module.Function, v: Value) TypeId {
|
||||||
|
return switch (v) {
|
||||||
|
.inst => |i| f.insts.items[i].ty,
|
||||||
|
.constant => |c| m.constants.items[c].ty,
|
||||||
|
.arg => |k| m.types.items[f.ty].function.params[k],
|
||||||
|
.global => |g| m.globals.items[g].ptr_ty,
|
||||||
|
.function => none,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Drops the function declarations nothing calls or refers to any more
|
||||||
|
/// (dead code removal can take a dx.op's last call, and the validator
|
||||||
|
/// rejects unused external functions), renumbering the other functions.
|
||||||
|
/// Run last: indices the emitter holds go stale. Returns the new index of
|
||||||
|
/// each old function (`none` for dropped ones), or null if none went.
|
||||||
|
pub fn pruneDeclarations(a: Allocator, m: *module.Module) Allocator.Error!?[]const u32 {
|
||||||
|
const funcs = m.functions.items;
|
||||||
|
const used = try a.alloc(bool, funcs.len);
|
||||||
|
for (funcs, used) |f, *u| u.* = f.num_blocks > 0;
|
||||||
|
const Use = struct {
|
||||||
|
used: []bool,
|
||||||
|
fn visit(s: *@This(), v: Value, _: Role) Value {
|
||||||
|
if (v == .function) s.used[v.function] = true;
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var use: Use = .{ .used = used };
|
||||||
|
for (funcs) |f| for (f.insts.items) |*inst| {
|
||||||
|
if (inst.op == .call) used[inst.op.call.callee] = true;
|
||||||
|
try operands(false, a, inst, &use);
|
||||||
|
};
|
||||||
|
for (m.metadata.items) |md| if (md == .value and md.value.val == .function) {
|
||||||
|
used[md.value.val.function] = true;
|
||||||
|
};
|
||||||
|
if (std.mem.indexOfScalar(bool, used, false) == null) return null;
|
||||||
|
|
||||||
|
const index = try a.alloc(u32, funcs.len);
|
||||||
|
var count: u32 = 0;
|
||||||
|
for (used, index) |u, *x| {
|
||||||
|
x.* = if (u) count else none;
|
||||||
|
if (u) count += 1;
|
||||||
|
}
|
||||||
|
const Map = struct {
|
||||||
|
index: []const u32,
|
||||||
|
fn visit(s: *@This(), v: Value, _: Role) Value {
|
||||||
|
return if (v == .function) .{ .function = s.index[v.function] } else v;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var map: Map = .{ .index = index };
|
||||||
|
const ma = m.allocator();
|
||||||
|
for (funcs) |*f| for (f.insts.items) |*inst| {
|
||||||
|
try operands(true, ma, inst, &map);
|
||||||
|
if (inst.op == .call) inst.op.call.callee = index[inst.op.call.callee];
|
||||||
|
};
|
||||||
|
for (m.metadata.items) |*md| if (md.* == .value and md.value.val == .function) {
|
||||||
|
md.value.val = .{ .function = index[md.value.val.function] };
|
||||||
|
};
|
||||||
|
var k: usize = 0;
|
||||||
|
for (funcs, used) |f, u| if (u) {
|
||||||
|
funcs[k] = f;
|
||||||
|
k += 1;
|
||||||
|
};
|
||||||
|
m.functions.shrinkRetainingCapacity(k);
|
||||||
|
return index;
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue