commit
3ba5acaf75
|
|
@ -0,0 +1,193 @@
|
|||
//! An arena for one thread: what std.heap.ArenaAllocator does, without the
|
||||
//! atomic operations that make that one safe to share between threads (an
|
||||
//! atomic add on every allocation). A compile runs on one thread and
|
||||
//! allocates millions of times.
|
||||
//!
|
||||
//! Memory comes from the child allocator in chunks, each larger than the
|
||||
//! last; freeing or resizing an allocation works in place only for the
|
||||
//! most recent one. reset can keep the chunks for the next use.
|
||||
const BumpArena = @This();
|
||||
|
||||
const std = @import("std");
|
||||
const Allocator = std.mem.Allocator;
|
||||
const Alignment = std.mem.Alignment;
|
||||
|
||||
child: Allocator,
|
||||
/// Chunks in use, newest first; allocations bump `end` in the newest.
|
||||
used: ?*Chunk = null,
|
||||
/// Chunks a reset kept, for reuse.
|
||||
spare: ?*Chunk = null,
|
||||
end: usize = 0,
|
||||
|
||||
const Chunk = struct {
|
||||
next: ?*Chunk,
|
||||
/// Bytes after the header.
|
||||
len: usize,
|
||||
|
||||
fn data(c: *Chunk) [*]u8 {
|
||||
return @as([*]u8, @ptrCast(c)) + @sizeOf(Chunk);
|
||||
}
|
||||
};
|
||||
|
||||
const chunk_align: Alignment = .@"16";
|
||||
const min_chunk = 64 << 10;
|
||||
|
||||
pub fn init(child: Allocator) BumpArena {
|
||||
return .{ .child = child };
|
||||
}
|
||||
|
||||
pub fn deinit(b: *BumpArena) void {
|
||||
freeList(b.child, b.used);
|
||||
freeList(b.child, b.spare);
|
||||
b.* = undefined;
|
||||
}
|
||||
|
||||
fn freeList(child: Allocator, first: ?*Chunk) void {
|
||||
var c = first;
|
||||
while (c) |chunk| {
|
||||
c = chunk.next;
|
||||
const bytes: [*]u8 = @ptrCast(chunk);
|
||||
child.rawFree(bytes[0 .. @sizeOf(Chunk) + chunk.len], chunk_align, @returnAddress());
|
||||
}
|
||||
}
|
||||
|
||||
pub fn allocator(b: *BumpArena) Allocator {
|
||||
return .{ .ptr = b, .vtable = &vtable };
|
||||
}
|
||||
|
||||
const vtable: Allocator.VTable = .{ .alloc = alloc, .resize = resize, .remap = remap, .free = free };
|
||||
|
||||
/// Total bytes of the chunks held (in use and spare).
|
||||
pub fn queryCapacity(b: *const BumpArena) usize {
|
||||
var n: usize = 0;
|
||||
inline for (.{ b.used, b.spare }) |first| {
|
||||
var c = first;
|
||||
while (c) |chunk| : (c = chunk.next) n += chunk.len;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
pub const ResetMode = std.heap.ArenaAllocator.ResetMode;
|
||||
|
||||
/// Frees every allocation. `.retain_capacity` keeps the chunks for reuse;
|
||||
/// `.retain_with_limit` keeps them up to that many bytes (largest first
|
||||
/// kept); `.free_all` gives them back.
|
||||
pub fn reset(b: *BumpArena, mode: ResetMode) bool {
|
||||
const limit: usize = switch (mode) {
|
||||
.free_all => 0,
|
||||
.retain_capacity => std.math.maxInt(usize),
|
||||
.retain_with_limit => |l| l,
|
||||
};
|
||||
// All chunks, then keep the largest that fit under the limit.
|
||||
var all = b.used;
|
||||
if (all) |first| {
|
||||
var last = first;
|
||||
while (last.next) |nx| last = nx;
|
||||
last.next = b.spare;
|
||||
} else all = b.spare;
|
||||
b.used = null;
|
||||
b.spare = null;
|
||||
b.end = 0;
|
||||
var kept: usize = 0;
|
||||
var c = all;
|
||||
while (c) |chunk| {
|
||||
c = chunk.next;
|
||||
if (kept + chunk.len <= limit) {
|
||||
kept += chunk.len;
|
||||
chunk.next = null;
|
||||
b.addSpare(chunk);
|
||||
} else {
|
||||
const bytes: [*]u8 = @ptrCast(chunk);
|
||||
b.child.rawFree(bytes[0 .. @sizeOf(Chunk) + chunk.len], chunk_align, @returnAddress());
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Adds a chunk to the spare list, largest first.
|
||||
fn addSpare(b: *BumpArena, chunk: *Chunk) void {
|
||||
var link = &b.spare;
|
||||
while (link.*) |s| : (link = &s.next) if (s.len < chunk.len) break;
|
||||
chunk.next = link.*;
|
||||
link.* = chunk;
|
||||
}
|
||||
|
||||
fn alloc(ctx: *anyopaque, n: usize, alignment: Alignment, ra: usize) ?[*]u8 {
|
||||
const b: *BumpArena = @ptrCast(@alignCast(ctx));
|
||||
if (b.used) |c| {
|
||||
const base = c.data();
|
||||
const start = alignment.forward(@intFromPtr(base) + b.end) - @intFromPtr(base);
|
||||
if (start + n <= c.len) {
|
||||
b.end = start + n;
|
||||
return base + start;
|
||||
}
|
||||
}
|
||||
return b.allocSlow(n, alignment, ra);
|
||||
}
|
||||
|
||||
fn allocSlow(b: *BumpArena, n: usize, alignment: Alignment, ra: usize) ?[*]u8 {
|
||||
const need = n + alignment.toByteUnits();
|
||||
// A spare chunk big enough (the largest is first), else a new one half
|
||||
// again as large as the current.
|
||||
const chunk: *Chunk = if (b.spare != null and b.spare.?.len >= need) blk: {
|
||||
const s = b.spare.?;
|
||||
b.spare = s.next;
|
||||
break :blk s;
|
||||
} else blk: {
|
||||
const grow = if (b.used) |c| c.len + c.len / 2 else 0;
|
||||
const len = @max(need, grow, min_chunk);
|
||||
const bytes = b.child.rawAlloc(@sizeOf(Chunk) + len, chunk_align, ra) orelse return null;
|
||||
const c: *Chunk = @ptrCast(@alignCast(bytes));
|
||||
c.len = len;
|
||||
break :blk c;
|
||||
};
|
||||
chunk.next = b.used;
|
||||
b.used = chunk;
|
||||
const base = chunk.data();
|
||||
const start = alignment.forward(@intFromPtr(base)) - @intFromPtr(base);
|
||||
b.end = start + n;
|
||||
return base + start;
|
||||
}
|
||||
|
||||
/// Whether `buf` is the newest allocation (the only one that can change
|
||||
/// in place).
|
||||
fn isLast(b: *const BumpArena, buf: []u8) bool {
|
||||
const c = b.used orelse return false;
|
||||
return buf.ptr + buf.len == c.data() + b.end;
|
||||
}
|
||||
|
||||
fn resize(ctx: *anyopaque, buf: []u8, _: Alignment, new_len: usize, _: usize) bool {
|
||||
const b: *BumpArena = @ptrCast(@alignCast(ctx));
|
||||
if (!b.isLast(buf)) return new_len <= buf.len;
|
||||
const c = b.used.?;
|
||||
const start = @intFromPtr(buf.ptr) - @intFromPtr(c.data());
|
||||
if (start + new_len > c.len) return false;
|
||||
b.end = start + new_len;
|
||||
return true;
|
||||
}
|
||||
|
||||
fn remap(ctx: *anyopaque, buf: []u8, alignment: Alignment, new_len: usize, ra: usize) ?[*]u8 {
|
||||
return if (resize(ctx, buf, alignment, new_len, ra)) buf.ptr else null;
|
||||
}
|
||||
|
||||
fn free(ctx: *anyopaque, buf: []u8, _: Alignment, _: usize) void {
|
||||
const b: *BumpArena = @ptrCast(@alignCast(ctx));
|
||||
if (b.isLast(buf)) b.end -= buf.len;
|
||||
}
|
||||
|
||||
test "allocations, growth in place, reset" {
|
||||
var b: BumpArena = .init(std.testing.allocator);
|
||||
defer b.deinit();
|
||||
const a = b.allocator();
|
||||
var list: std.ArrayList(u32) = .empty;
|
||||
for (0..100_000) |k| try list.append(a, @intCast(k));
|
||||
for (list.items, 0..) |x, k| try std.testing.expectEqual(k, x);
|
||||
const big = try a.alignedAlloc(u8, .@"64", 1 << 20);
|
||||
try std.testing.expect(std.mem.isAligned(@intFromPtr(big.ptr), 64));
|
||||
const cap = b.queryCapacity();
|
||||
_ = b.reset(.retain_capacity);
|
||||
try std.testing.expectEqual(cap, b.queryCapacity());
|
||||
_ = try a.alloc(u8, 100);
|
||||
_ = b.reset(.{ .retain_with_limit = 0 });
|
||||
try std.testing.expectEqual(0, b.queryCapacity());
|
||||
}
|
||||
|
|
@ -2,6 +2,7 @@
|
|||
//! owns an arena; nothing is global.
|
||||
|
||||
const std = @import("std");
|
||||
const BumpArena = @import("zdxc").BumpArena;
|
||||
const zdxc = @import("zdxc");
|
||||
const compile = zdxc.compile;
|
||||
const FileSystem = zdxc.front.source.FileSystem;
|
||||
|
|
@ -22,7 +23,7 @@ const CompileInfo = extern struct {
|
|||
const Output = enum(c_int) { object, diagnostics, preprocessed, root_signature, text, _ };
|
||||
|
||||
const Result = struct {
|
||||
arena: std.heap.ArenaAllocator,
|
||||
arena: BumpArena,
|
||||
status: compile.Status,
|
||||
/// Indexed by `Output`; each NUL-terminated.
|
||||
outputs: [5]?[:0]const u8,
|
||||
|
|
@ -32,7 +33,7 @@ const Result = struct {
|
|||
export fn zdxc_compile(info: ?*const CompileInfo) ?*Result {
|
||||
const i = info orelse return null;
|
||||
if (i.size < @sizeOf(CompileInfo)) return null;
|
||||
var arena: std.heap.ArenaAllocator = .init(std.heap.smp_allocator);
|
||||
var arena: BumpArena = .init(std.heap.smp_allocator);
|
||||
const r = compileInto(&arena, i) catch {
|
||||
arena.deinit();
|
||||
return null;
|
||||
|
|
@ -41,7 +42,7 @@ export fn zdxc_compile(info: ?*const CompileInfo) ?*Result {
|
|||
return r;
|
||||
}
|
||||
|
||||
fn compileInto(arena: *std.heap.ArenaAllocator, i: *const CompileInfo) !*Result {
|
||||
fn compileInto(arena: *BumpArena, i: *const CompileInfo) !*Result {
|
||||
const a = arena.allocator();
|
||||
const args = try a.alloc([]const u8, i.arg_count);
|
||||
for (args, 0..) |*d, k| d.* = std.mem.span(i.args.?[k] orelse return error.InvalidArgument);
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ const container = zdxc.dxil.container;
|
|||
const front = zdxc.front;
|
||||
const options = zdxc.options;
|
||||
const FileSystem = front.source.FileSystem;
|
||||
const stats = zdxc.stats;
|
||||
|
||||
pub const Request = struct {
|
||||
/// dxc command-line options, without the program name: "-T", "ps_6_0",
|
||||
|
|
@ -371,7 +372,9 @@ fn parseArgs(ctx: *Ctx, arena: std.mem.Allocator, args: []const []const u8) !?Op
|
|||
}
|
||||
|
||||
fn run(ctx: *Ctx, arena: std.mem.Allocator) !void {
|
||||
const za = stats.begin(.args);
|
||||
const opts = try parseArgs(ctx, arena, ctx.req.args) orelse return;
|
||||
za.end();
|
||||
ctx.result.object_name = opts.output;
|
||||
ctx.result.root_signature_name = opts.rootsig_output;
|
||||
ctx.result.preprocessed_name = opts.pp_output;
|
||||
|
|
@ -445,13 +448,18 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void {
|
|||
});
|
||||
var out: Io.Writer.Allocating = .init(arena);
|
||||
var module: ?zdxc.ir.ir.Module = null;
|
||||
const zp = stats.begin(.preprocess);
|
||||
const opened = try pp.enterMainFile(input);
|
||||
if (opened) {
|
||||
if (opts.preprocess) {
|
||||
try front.pp_print.print(&pp, &out.writer);
|
||||
zp.end();
|
||||
} else {
|
||||
var parser = try front.parser.Parser.fromPreprocessor(arena, &diags, &pp);
|
||||
zp.end();
|
||||
const zparse = stats.begin(.parse);
|
||||
const tu = try parser.parseTranslationUnit();
|
||||
zparse.end();
|
||||
if (opts.dump_ast) try front.ast_dump.dumpUnit(ctx.stdout, tu);
|
||||
if (!opts.parse) {
|
||||
const is_lib = if (profile) |p| p.kind == .library else true;
|
||||
|
|
@ -467,8 +475,10 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void {
|
|||
});
|
||||
// About one resolution per expression: reserve rather
|
||||
// than grow, which leaves every old buffer in the arena.
|
||||
const zs = stats.begin(.sema);
|
||||
try sema.resolutions.ensureTotalCapacity(arena, parser.toks.len);
|
||||
try sema.checkUnit(tu);
|
||||
zs.end();
|
||||
if (!opts.sema and !diags.hasErrors() and profile != null) {
|
||||
const stage: zdxc.ir.ir.Stage = switch (profile.?.kind) {
|
||||
.vertex => .vertex,
|
||||
|
|
@ -481,10 +491,12 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void {
|
|||
.amplification => .amplification,
|
||||
else => .library,
|
||||
};
|
||||
const zl = stats.begin(.lower);
|
||||
module = zdxc.ir.lower.lowerUnit(arena, &sema, .{ .entry = opts.entry, .stage = stage }) catch |e| switch (e) {
|
||||
error.Unsupported => null,
|
||||
else => |x| return x,
|
||||
};
|
||||
zl.end();
|
||||
if (module) |*mm| {
|
||||
mm.native_16bit = opts.enable_16bit;
|
||||
mm.row_major = opts.row_major;
|
||||
|
|
@ -510,7 +522,11 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void {
|
|||
if (opts.parse or opts.sema) return;
|
||||
if (profile == null) return ctx.fail("missing -T <profile>", .{});
|
||||
if (module) |*m| {
|
||||
const zo = stats.begin(.ir_opt);
|
||||
try zdxc.ir.opt.run(arena, m);
|
||||
zo.end();
|
||||
const zv = stats.begin(.spirv);
|
||||
defer if (opts.spirv) zv.end();
|
||||
if (opts.spirv) {
|
||||
zdxc.ir.split_resources.run(arena, m, &diags) catch |err| switch (err) {
|
||||
error.Unsupported => {
|
||||
|
|
@ -546,6 +562,7 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void {
|
|||
if (opts.rootsig_define) |macro| if (m.entries.items.len == 1) {
|
||||
m.entries.items[0].root_signature = try rootSignatureMacroText(ctx, arena, opts, input, macro) orelse return error.CompileFailed;
|
||||
};
|
||||
const zd = stats.begin(.dxil);
|
||||
const dxil_out = zdxc.dxil.emit.emitWithReflection(arena, m, profile.?, &diags, !opts.no_opt and opts.opt_level != .od) catch |err| switch (err) {
|
||||
error.Unsupported => {
|
||||
try diags.render(&sm, ctx.stderr, .{ .format = opts.diag_format, .color = false });
|
||||
|
|
@ -553,6 +570,7 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void {
|
|||
},
|
||||
else => |x| return x,
|
||||
};
|
||||
zd.end();
|
||||
try ctx.needOutput(opts);
|
||||
ctx.result.object = dxil_out.object;
|
||||
ctx.result.reflection = dxil_out.reflection;
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@
|
|||
//! include chains and macro expansion backtraces.
|
||||
|
||||
const std = @import("std");
|
||||
const BumpArena = @import("BumpArena.zig");
|
||||
const Allocator = std.mem.Allocator;
|
||||
const source = @import("front/source.zig");
|
||||
const Loc = source.Loc;
|
||||
|
|
@ -56,7 +57,7 @@ pub const Report = struct {
|
|||
};
|
||||
|
||||
pub const Diagnostics = struct {
|
||||
arena: std.heap.ArenaAllocator,
|
||||
arena: BumpArena,
|
||||
list: std.ArrayList(*Diagnostic) = .empty,
|
||||
error_count: u32 = 0,
|
||||
warning_count: u32 = 0,
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@
|
|||
//! does (test/dropin in the development repo compares the two).
|
||||
|
||||
const std = @import("std");
|
||||
const BumpArena = @import("zdxc").BumpArena;
|
||||
const builtin = @import("builtin");
|
||||
const zdxc = @import("zdxc");
|
||||
const compile = zdxc.compile;
|
||||
|
|
@ -839,7 +840,7 @@ const Compiler = struct {
|
|||
/// gives its blocks back to the OS (smp_allocator maps 64 KiB and up
|
||||
/// directly), and faulting fresh pages in again costs more than the compile
|
||||
/// on many threads. What a thread keeps is capped at `retain_limit`.
|
||||
threadlocal var thread_arena: ?std.heap.ArenaAllocator = null;
|
||||
threadlocal var thread_arena: ?BumpArena = null;
|
||||
const retain_limit = 64 << 20;
|
||||
|
||||
fn run(source: *const Buffer, wargs: []const ?[*:0]const WCHAR, include: ?*anyopaque) error{ OutOfMemory, InvalidArgument }!*Result {
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@
|
|||
//! signed DXIL container.
|
||||
|
||||
const std = @import("std");
|
||||
const BumpArena = @import("../BumpArena.zig");
|
||||
const Allocator = std.mem.Allocator;
|
||||
const ir = @import("../ir/ir.zig");
|
||||
const types = @import("../sema/types.zig");
|
||||
|
|
@ -25,6 +26,7 @@ const reflect = @import("reflect.zig");
|
|||
const rootsig = @import("rootsig.zig");
|
||||
const promote = @import("promote.zig");
|
||||
const unroll = @import("unroll.zig");
|
||||
const stats = @import("../stats.zig");
|
||||
const sccp = @import("sccp.zig");
|
||||
const opt = @import("../ir/opt.zig");
|
||||
|
||||
|
|
@ -51,7 +53,7 @@ pub fn emit(gpa: Allocator, m: *const ir.Module, profile: shader.Profile, diags:
|
|||
pub const Output = struct { object: []u8, reflection: []u8 };
|
||||
|
||||
pub fn emitWithReflection(gpa: Allocator, m: *const ir.Module, profile: shader.Profile, diags: *diag.Diagnostics, optimize: bool) Error!Output {
|
||||
var arena_state = std.heap.ArenaAllocator.init(gpa);
|
||||
var arena_state: BumpArena = .init(gpa);
|
||||
defer arena_state.deinit();
|
||||
var e: Emitter = .{ .arena = arena_state.allocator(), .dm = .init(gpa), .m = m, .t = m.types, .profile = profile, .diags = diags, .optimize = optimize };
|
||||
defer e.dm.deinit();
|
||||
|
|
@ -75,6 +77,10 @@ const Lowered = union(enum) {
|
|||
/// per resource, each an alias of what is stored into it.
|
||||
agg_ptr: struct { data: ?*const Lowered, slots: []const u32, ty: TypeId },
|
||||
ptr: Ptr,
|
||||
/// A by-value parameter's copy that is never written and only indexed
|
||||
/// by constants (Emitter.regsLocals): the argument's components, from
|
||||
/// `offset` on, with no memory behind them.
|
||||
regs: struct { vals: []const Value, offset: u32 = 0 },
|
||||
/// A resource handle (index into Emitter.resources).
|
||||
handle: u32,
|
||||
/// A local holding a resource (index into Emitter.res_locals): an
|
||||
|
|
@ -167,6 +173,8 @@ const Resource = struct {
|
|||
|
||||
const Frame = struct {
|
||||
f: *const ir.Function,
|
||||
/// For inlined calls: Emitter.regsLocals of `f`.
|
||||
regs: []const bool = &.{},
|
||||
vals: []Lowered,
|
||||
params: []const Lowered,
|
||||
blocks: []?u32,
|
||||
|
|
@ -195,7 +203,56 @@ const Frame = struct {
|
|||
arrays: std.ArrayList(struct { ty: TypeId, ptr: Ptr }) = .empty,
|
||||
};
|
||||
|
||||
const PInst = struct { inst: module.Inst, id: u32 };
|
||||
/// Hash maps keyed by a Value (or a Value and an offset). A Value has
|
||||
/// padding, so the automatic context hashes it field by field; this one
|
||||
/// mixes its tag and index into one word.
|
||||
fn ValueMap(comptime V: type) type {
|
||||
return std.HashMapUnmanaged(Value, V, ValueContext, std.hash_map.default_max_load_percentage);
|
||||
}
|
||||
|
||||
const ValueContext = struct {
|
||||
fn word(v: Value) u64 {
|
||||
return @as(u64, @backingInt(v)) << 32 | switch (v) {
|
||||
inline else => |x| x,
|
||||
};
|
||||
}
|
||||
|
||||
fn mix(x: u64) u64 {
|
||||
var z = x;
|
||||
z = (z ^ (z >> 30)) *% 0xbf58476d1ce4e5b9;
|
||||
z = (z ^ (z >> 27)) *% 0x94d049bb133111eb;
|
||||
return z ^ (z >> 31);
|
||||
}
|
||||
|
||||
pub fn hash(_: ValueContext, k: anytype) u64 {
|
||||
return switch (@TypeOf(k)) {
|
||||
Value => mix(word(k)),
|
||||
else => mix(word(k[0]) ^ @as(u64, k[1]) << 40),
|
||||
};
|
||||
}
|
||||
|
||||
pub fn eql(_: ValueContext, a: anytype, b: @TypeOf(a)) bool {
|
||||
return std.meta.eql(a, b);
|
||||
}
|
||||
};
|
||||
|
||||
/// The current function's instructions, by id, in chunks that never move
|
||||
/// (blocks and the prologue list ids).
|
||||
const InstStore = struct {
|
||||
const shift = 10;
|
||||
const chunk_len = 1 << shift;
|
||||
chunks: std.ArrayList(*[chunk_len]module.Inst) = .empty,
|
||||
|
||||
/// Stores instruction `id`, the next one.
|
||||
fn put(s: *InstStore, a: Allocator, id: u32, inst: module.Inst) Allocator.Error!void {
|
||||
if (id >> shift >= s.chunks.items.len) try s.chunks.append(a, try a.create([chunk_len]module.Inst));
|
||||
s.chunks.items[id >> shift][id & (chunk_len - 1)] = inst;
|
||||
}
|
||||
|
||||
fn at(s: *const InstStore, id: u32) *module.Inst {
|
||||
return &s.chunks.items[id >> shift][id & (chunk_len - 1)];
|
||||
}
|
||||
};
|
||||
|
||||
const Emitter = struct {
|
||||
arena: Allocator,
|
||||
|
|
@ -214,8 +271,9 @@ const Emitter = struct {
|
|||
payload_global: ?u32 = null,
|
||||
payload_local: ?struct { func: *const ir.Function, inst: u32 } = null,
|
||||
/// Instructions per block, in creation order, with provisional ids.
|
||||
blocks: std.ArrayList(std.ArrayList(PInst)) = .empty,
|
||||
prologue: std.ArrayList(PInst) = .empty,
|
||||
insts: InstStore = .{},
|
||||
blocks: std.ArrayList(std.ArrayList(u32)) = .empty,
|
||||
prologue: std.ArrayList(u32) = .empty,
|
||||
next_id: u32 = 0,
|
||||
/// Each instruction's type, by id.
|
||||
inst_types: std.ArrayList(DType) = .empty,
|
||||
|
|
@ -227,12 +285,12 @@ const Emitter = struct {
|
|||
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,
|
||||
texel_copies: ValueMap(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,
|
||||
nonuniform: ValueMap(void) = .empty,
|
||||
uses_double: bool = false,
|
||||
uses_int64: bool = false,
|
||||
/// 16-bit min-precision values cross the signature.
|
||||
|
|
@ -265,8 +323,8 @@ const Emitter = struct {
|
|||
last_resret: Value = undefined,
|
||||
/// Status values, forwarded through locals within a block: the
|
||||
/// validator wants CheckAccessFullyMapped's operand to be one.
|
||||
status_vals: std.AutoHashMapUnmanaged(Value, void) = .empty,
|
||||
forwarded: std.AutoHashMapUnmanaged(struct { Value, u32 }, struct { v: Value, block: u32 }) = .empty,
|
||||
status_vals: ValueMap(void) = .empty,
|
||||
forwarded: std.HashMapUnmanaged(struct { Value, u32 }, struct { v: Value, block: u32 }, ValueContext, std.hash_map.default_max_load_percentage) = .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,
|
||||
|
|
@ -279,6 +337,7 @@ const Emitter = struct {
|
|||
writes: u32 = 0,
|
||||
/// paramCopies per IR function.
|
||||
param_copies: std.AutoHashMapUnmanaged(u32, []const u32) = .empty,
|
||||
regs_locals: std.AutoHashMapUnmanaged(u32, []const bool) = .empty,
|
||||
uses_barycentrics: bool = false,
|
||||
uses_sampler_heap: bool = false,
|
||||
/// The shader's reflection (reflect.zig), made with the object; owned
|
||||
|
|
@ -315,6 +374,16 @@ const Emitter = struct {
|
|||
/// Each HLSL struct's module type (struct types are named, and two
|
||||
/// structs may share a name: `A<int>::In`, `A<float>::In`).
|
||||
struct_types: std.AutoHashMapUnmanaged(TypeId, DType) = .empty,
|
||||
/// Per type: see structComps, mixedSizes and mixedStorage.
|
||||
struct_comps: std.AutoHashMapUnmanaged(TypeId, []const TypeId) = .empty,
|
||||
comp_offsets: std.AutoHashMapUnmanaged(struct { TypeId, bool, layout.Rules }, []const u32) = .empty,
|
||||
field_offsets: std.AutoHashMapUnmanaged(struct { *const types.StructInfo, layout.Rules }, []const u32) = .empty,
|
||||
/// elementPtr's last pointer type, and its shared index slices (by the
|
||||
/// index constant).
|
||||
elem_ptr_ty: struct { elem: DType = std.math.maxInt(DType), space: u32 = 0, ty: DType = 0 } = .{},
|
||||
zero_indexed: std.ArrayList([]const Value) = .empty,
|
||||
mixed_sizes: std.AutoHashMapUnmanaged(TypeId, bool) = .empty,
|
||||
mixed_storage: std.AutoHashMapUnmanaged(TypeId, bool) = .empty,
|
||||
/// Prologue instructions dropped again if unused (resource handles).
|
||||
lib_removable: std.AutoHashMapUnmanaged(u32, void) = .empty,
|
||||
|
||||
|
|
@ -342,7 +411,8 @@ const Emitter = struct {
|
|||
},
|
||||
else => {},
|
||||
}
|
||||
try e.blocks.items[e.cur].append(e.arena, .{ .inst = .{ .ty = ty, .op = op }, .id = id });
|
||||
try e.insts.put(e.arena, id, .{ .ty = ty, .op = op });
|
||||
try e.blocks.items[e.cur].append(e.arena, id);
|
||||
return .{ .inst = id };
|
||||
}
|
||||
|
||||
|
|
@ -350,7 +420,8 @@ const Emitter = struct {
|
|||
const id = e.next_id;
|
||||
e.next_id += 1;
|
||||
try e.inst_types.append(e.arena, ty);
|
||||
try e.prologue.append(e.arena, .{ .inst = .{ .ty = ty, .op = op }, .id = id });
|
||||
try e.insts.put(e.arena, id, .{ .ty = ty, .op = op });
|
||||
try e.prologue.append(e.arena, id);
|
||||
return .{ .inst = id };
|
||||
}
|
||||
|
||||
|
|
@ -416,15 +487,58 @@ const Emitter = struct {
|
|||
.vector => |v| v.len,
|
||||
.matrix => |m| @as(u32, m.rows) * m.cols,
|
||||
.array => |a| a.len * try e.flatCount(a.elem),
|
||||
.@"struct" => |s| blk: {
|
||||
var n: u32 = 0;
|
||||
for (s.fields.items) |f| n += try e.flatCount(f.type);
|
||||
break :blk n;
|
||||
},
|
||||
.@"struct" => @intCast((try e.structComps(ty)).len),
|
||||
else => e.unsupported("values of type '{s}' are not supported yet", .{try e.t.format(e.arena, ty)}),
|
||||
};
|
||||
}
|
||||
|
||||
/// Byte offsets of `st`'s fields under `rules`, worked out once per
|
||||
/// struct.
|
||||
fn fieldOffsets(e: *Emitter, st: *const types.StructInfo, rules: layout.Rules) layout.Error![]const u32 {
|
||||
const gop = try e.field_offsets.getOrPut(e.arena, .{ st, rules });
|
||||
if (gop.found_existing) return gop.value_ptr.*;
|
||||
gop.value_ptr.* = layout.fieldOffsets(e.arena, e.t, st, rules) catch |err| {
|
||||
_ = e.field_offsets.remove(.{ st, rules });
|
||||
return err;
|
||||
};
|
||||
return gop.value_ptr.*;
|
||||
}
|
||||
|
||||
/// layout.componentOffset, from a table of `ty`'s components worked out
|
||||
/// once per type.
|
||||
fn componentOffset(e: *Emitter, ty: TypeId, row_major: bool, k: u32, rules: layout.Rules) layout.Error!u32 {
|
||||
const gop = try e.comp_offsets.getOrPut(e.arena, .{ ty, row_major, rules });
|
||||
if (!gop.found_existing) {
|
||||
gop.value_ptr.* = &.{};
|
||||
const n = layout.flatCount(e.t, ty) catch 0;
|
||||
// (Small types: worked out each time, as cheaply.)
|
||||
if (n > 4) {
|
||||
const table = try e.arena.alloc(u32, n);
|
||||
const ok = for (table, 0..) |*o, c| {
|
||||
o.* = layout.componentOffset(e.arena, e.t, ty, row_major, @intCast(c), rules) catch break false;
|
||||
} else true;
|
||||
if (ok) gop.value_ptr.* = table;
|
||||
}
|
||||
}
|
||||
const table = gop.value_ptr.*;
|
||||
if (k < table.len) return table[k];
|
||||
return layout.componentOffset(e.arena, e.t, ty, row_major, k, rules);
|
||||
}
|
||||
|
||||
/// The scalar type of each flattened component of struct `ty`, worked
|
||||
/// out once per type.
|
||||
fn structComps(e: *Emitter, ty: TypeId) Error![]const TypeId {
|
||||
if (e.struct_comps.get(ty)) |c| return c;
|
||||
var out: std.ArrayList(TypeId) = .empty;
|
||||
for (e.t.get(ty).@"struct".fields.items) |f| {
|
||||
const n = try e.flatCount(f.type);
|
||||
try out.ensureUnusedCapacity(e.arena, n);
|
||||
for (0..n) |k| out.appendAssumeCapacity(try e.componentType(f.type, @intCast(k)));
|
||||
}
|
||||
try e.struct_comps.put(e.arena, ty, out.items);
|
||||
return out.items;
|
||||
}
|
||||
|
||||
/// Undefined values for the flattened components of `ty`.
|
||||
fn undefValues(e: *Emitter, ty: TypeId) Error![]const Value {
|
||||
var out: std.ArrayList(Value) = .empty;
|
||||
|
|
@ -511,8 +625,10 @@ const Emitter = struct {
|
|||
try e.buildSignatures(entry);
|
||||
if (entry.stage == .amplification) e.findDispatchPayload();
|
||||
e.cur = try e.newBlock();
|
||||
const zl = stats.begin(.dxil_lower);
|
||||
try e.createHandles();
|
||||
_ = try e.inlineCall(entry.wrapper, &.{});
|
||||
zl.end();
|
||||
try e.finish(e.main_fn);
|
||||
if (entry.patch_wrapper) |pw| {
|
||||
// The patch constant function is a function of its own.
|
||||
|
|
@ -521,6 +637,7 @@ const Emitter = struct {
|
|||
e.call_memo = .empty;
|
||||
e.texel_copies = .empty;
|
||||
e.next_id = 0;
|
||||
e.insts = .{};
|
||||
e.inst_types = .empty;
|
||||
e.private_globals = .empty;
|
||||
e.private_typed = .empty;
|
||||
|
|
@ -536,6 +653,7 @@ const Emitter = struct {
|
|||
|
||||
if (e.optimize) e.inputUsage();
|
||||
if (e.optimize and e.profile.minor >= 6) try e.dropDeadResources();
|
||||
for (e.dm.functions.items) |f| stats.add(.dxil_final, f.insts.items.len);
|
||||
const bitcode = try e.writeModule(entry);
|
||||
defer gpa.free(bitcode);
|
||||
return e.assemble(gpa, entry, bitcode);
|
||||
|
|
@ -709,6 +827,7 @@ const Emitter = struct {
|
|||
e.call_memo = .empty;
|
||||
e.texel_copies = .empty;
|
||||
e.next_id = 0;
|
||||
e.insts = .{};
|
||||
e.inst_types = .empty;
|
||||
e.private_globals = .empty;
|
||||
e.private_typed = .empty;
|
||||
|
|
@ -744,6 +863,7 @@ const Emitter = struct {
|
|||
e.call_memo = .empty;
|
||||
e.texel_copies = .empty;
|
||||
e.next_id = 0;
|
||||
e.insts = .{};
|
||||
e.inst_types = .empty;
|
||||
e.private_globals = .empty;
|
||||
e.private_typed = .empty;
|
||||
|
|
@ -914,6 +1034,7 @@ const Emitter = struct {
|
|||
e.call_memo = .empty;
|
||||
e.texel_copies = .empty;
|
||||
e.next_id = 0;
|
||||
e.insts = .{};
|
||||
e.inst_types = .empty;
|
||||
e.private_globals = .empty;
|
||||
e.private_typed = .empty;
|
||||
|
|
@ -1352,15 +1473,16 @@ const Emitter = struct {
|
|||
/// Assigns final instruction indices: prologue first, then blocks in
|
||||
/// creation order.
|
||||
fn finish(e: *Emitter, func: u32) Error!void {
|
||||
const zf = stats.begin(.dxil_finish);
|
||||
if (e.lib_removable.count() > 0) try e.pruneProlog();
|
||||
const map = try e.arena.alloc(u32, e.next_id);
|
||||
var n: u32 = 0;
|
||||
for (e.prologue.items) |pi| {
|
||||
map[pi.id] = n;
|
||||
for (e.prologue.items) |id| {
|
||||
map[id] = n;
|
||||
n += 1;
|
||||
}
|
||||
for (e.blocks.items) |blk| for (blk.items) |pi| {
|
||||
map[pi.id] = n;
|
||||
for (e.blocks.items) |blk| for (blk.items) |id| {
|
||||
map[id] = n;
|
||||
n += 1;
|
||||
};
|
||||
const f = &e.dm.functions.items[func];
|
||||
|
|
@ -1370,20 +1492,35 @@ const Emitter = struct {
|
|||
return if (x == .inst) .{ .inst = mp[x.inst] } else x;
|
||||
}
|
||||
fn vs(a: Allocator, mp: []const u32, xs: []const Value) Allocator.Error![]const Value {
|
||||
// (Nothing to renumber, as in most getelementptr indices:
|
||||
// the slice is kept; no pass writes operand slices.)
|
||||
for (xs) |x| {
|
||||
if (x == .inst) break;
|
||||
} else return xs;
|
||||
const out = try a.alloc(Value, xs.len);
|
||||
for (xs, out) |x, *o| o.* = v(mp, x);
|
||||
return out;
|
||||
}
|
||||
};
|
||||
stats.add(.dxil_lowered, n);
|
||||
try f.insts.ensureUnusedCapacity(e.dm.allocator(), n);
|
||||
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 (e.blocks.items) |blk| for (blk.items) |pi| try f.insts.append(e.dm.allocator(), try remapInst(e.arena, map, pi.inst, remap));
|
||||
// (Copied into place, then renumbered there.)
|
||||
for (e.prologue.items) |id| {
|
||||
const dst = f.insts.addOneAssumeCapacity();
|
||||
dst.* = e.insts.at(id).*;
|
||||
try remapInst(e.arena, map, dst, remap);
|
||||
}
|
||||
for (e.blocks.items) |blk| for (blk.items) |id| {
|
||||
const dst = f.insts.addOneAssumeCapacity();
|
||||
dst.* = e.insts.at(id).*;
|
||||
try remapInst(e.arena, map, dst, remap);
|
||||
};
|
||||
var ranges: std.AutoHashMapUnmanaged(u32, [2]u32) = .empty;
|
||||
var it = e.dyn_ranges.iterator();
|
||||
while (it.next()) |kv| try ranges.put(e.arena, map[kv.key_ptr.*], kv.value_ptr.*);
|
||||
e.dyn_ranges.clearRetainingCapacity();
|
||||
e.array_pool.clearRetainingCapacity();
|
||||
zf.end();
|
||||
if (e.optimize) {
|
||||
try promote.run(e.arena, &e.dm, func, &ranges);
|
||||
// Values only ever one constant (through loops too), and the
|
||||
|
|
@ -1416,13 +1553,12 @@ const Emitter = struct {
|
|||
while (changed) {
|
||||
changed = false;
|
||||
@memset(used, false);
|
||||
const all = [_][]const PInst{e.prologue.items};
|
||||
for (all) |items| for (items) |pi| markUses(e.arena, pi.inst, used);
|
||||
for (e.blocks.items) |blk| for (blk.items) |pi| markUses(e.arena, pi.inst, used);
|
||||
for (e.prologue.items) |id| markUses(e.arena, e.insts.at(id).*, used);
|
||||
for (e.blocks.items) |blk| for (blk.items) |id| markUses(e.arena, e.insts.at(id).*, used);
|
||||
var k: usize = 0;
|
||||
while (k < e.prologue.items.len) {
|
||||
const pi = e.prologue.items[k];
|
||||
if (e.lib_removable.contains(pi.id) and !used[pi.id]) {
|
||||
const id = e.prologue.items[k];
|
||||
if (e.lib_removable.contains(id) and !used[id]) {
|
||||
_ = e.prologue.orderedRemove(k);
|
||||
changed = true;
|
||||
} else k += 1;
|
||||
|
|
@ -1444,11 +1580,11 @@ const Emitter = struct {
|
|||
}
|
||||
};
|
||||
M.u = used;
|
||||
_ = remapInst(a, &.{}, inst, M) catch {};
|
||||
var copy = inst;
|
||||
remapInst(a, &.{}, ©, M) catch {};
|
||||
}
|
||||
|
||||
fn remapInst(a: Allocator, map: []const u32, inst: module.Inst, comptime R: type) Allocator.Error!module.Inst {
|
||||
var out = inst;
|
||||
fn remapInst(a: Allocator, map: []const u32, out: *module.Inst, comptime R: type) Allocator.Error!void {
|
||||
switch (out.op) {
|
||||
.ret => |*v| if (v.*) |x| {
|
||||
v.* = R.v(map, x);
|
||||
|
|
@ -1508,7 +1644,6 @@ const Emitter = struct {
|
|||
x.index = R.v(map, x.index);
|
||||
},
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
|
|
@ -1546,7 +1681,7 @@ const Emitter = struct {
|
|||
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;
|
||||
b = e.insts.at(br).op.br.then;
|
||||
from = 0;
|
||||
}
|
||||
e.forwarded.clearRetainingCapacity();
|
||||
|
|
@ -1564,11 +1699,11 @@ const Emitter = struct {
|
|||
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) {
|
||||
for (items[from .. items.len - 1]) |id| switch (e.insts.at(id).op) {
|
||||
.br, .@"switch", .ret, .phi => return false,
|
||||
else => {},
|
||||
};
|
||||
const last = items[items.len - 1].inst.op;
|
||||
const last = e.insts.at(items[items.len - 1]).op;
|
||||
if (last != .br or last.br.cond != null or last.br.then < first_new) return false;
|
||||
b = last.br.then;
|
||||
from = 0;
|
||||
|
|
@ -1658,6 +1793,7 @@ const Emitter = struct {
|
|||
@memset(frame.vals, .none);
|
||||
@memset(frame.blocks, null);
|
||||
if (e.optimize and args.len > 0) frame.copies = try e.paramCopies(fi);
|
||||
if (e.optimize) frame.regs = try e.regsLocals(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.
|
||||
|
|
@ -1739,6 +1875,112 @@ const Emitter = struct {
|
|||
return out;
|
||||
}
|
||||
|
||||
/// For each instruction of IR function `fi`: whether it is a local
|
||||
/// that can be the values stored into it (see Lowered.regs), indexed
|
||||
/// only by constants and either a copy of a parameter (paramCopies) or
|
||||
/// stored once, whole, in the entry block before any other use of it
|
||||
/// (and otherwise only read).
|
||||
fn regsLocals(e: *Emitter, fi: u32) Error![]const bool {
|
||||
const gop = try e.regs_locals.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 copies = try e.paramCopies(fi);
|
||||
const n = copies.len;
|
||||
const out = try e.arena.alloc(bool, n);
|
||||
for (out, copies) |*o, c| o.* = c != none;
|
||||
|
||||
// Locals stored once from a value. 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 stores = try e.arena.alloc(u32, n);
|
||||
@memset(stores, 0);
|
||||
const bad = try e.arena.alloc(bool, n);
|
||||
@memset(bad, false);
|
||||
const Use = struct {
|
||||
root: []const u32,
|
||||
bad: []bool,
|
||||
pub fn map(u: @This(), x: Ref) Ref {
|
||||
if (x != .none and u.root[x.index()] != none) u.bad[u.root[x.index()]] = true;
|
||||
return x;
|
||||
}
|
||||
};
|
||||
const use: Use = .{ .root = root, .bad = bad };
|
||||
for (f.insts.items) |inst| switch (inst.op) {
|
||||
.local_var, .load => {},
|
||||
.access => |x| for (x.indices) |ix| {
|
||||
_ = use.map(ix);
|
||||
},
|
||||
.store => |x| {
|
||||
_ = use.map(x.value);
|
||||
const l = root[x.ptr.index()];
|
||||
if (l == none) continue;
|
||||
if (x.ptr.index() != l) bad[l] = true;
|
||||
stores[l] += 1;
|
||||
},
|
||||
else => _ = try opt.mapOp(e.arena, inst.op, use),
|
||||
};
|
||||
// The store: in the entry block (not branched back to), before any
|
||||
// load or access of the local there.
|
||||
var reentered = false;
|
||||
for (f.blocks.items) |blk| switch (blk.term) {
|
||||
.br => |t| reentered = reentered or t.index() == 0,
|
||||
.cond_br => |c| reentered = reentered or c.then.index() == 0 or c.@"else".index() == 0,
|
||||
.@"switch" => |sw| {
|
||||
reentered = reentered or sw.default.index() == 0;
|
||||
for (sw.cases) |cs| reentered = reentered or cs.block.index() == 0;
|
||||
},
|
||||
else => {},
|
||||
};
|
||||
if (!reentered and f.blocks.items.len > 0) {
|
||||
const used = try e.arena.alloc(bool, n);
|
||||
@memset(used, false);
|
||||
for (f.blocks.items[0].insts.items) |r| {
|
||||
const inst = f.inst(r);
|
||||
switch (inst.op) {
|
||||
.load => |p| if (root[p.index()] != none) {
|
||||
used[root[p.index()]] = true;
|
||||
},
|
||||
.access => if (root[r.index()] != none) {
|
||||
used[root[r.index()]] = true;
|
||||
},
|
||||
.store => |x| {
|
||||
const l = root[x.ptr.index()];
|
||||
if (l == none or used[l] or bad[l] or stores[l] != 1 or copies[l] != none) continue;
|
||||
if (f.inst(x.value).op == .param) continue;
|
||||
const ty = f.inst(@fromBackingInt(@intCast(l))).ty;
|
||||
if (isResourceType(e.t, ty) or e.holdsResources(ty) or e.containsLinAlg(ty) or isRayQuery(e.t, ty)) continue;
|
||||
out[l] = true;
|
||||
},
|
||||
else => {},
|
||||
}
|
||||
}
|
||||
}
|
||||
// Only constant indices.
|
||||
for (f.insts.items, 0..) |inst, k| if (inst.op == .access and root[k] != none) {
|
||||
for (inst.op.access.indices) |ix| if (f.inst(ix).op != .constant or f.inst(ix).op.constant != .int) {
|
||||
out[root[k]] = false;
|
||||
};
|
||||
};
|
||||
gop.value_ptr.* = out;
|
||||
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.
|
||||
|
|
@ -2081,6 +2323,15 @@ const Emitter = struct {
|
|||
const k = frame.param_copies[r.index()];
|
||||
if (k != std.math.maxInt(u32)) if (frame.param_srcs[k]) |alias| return alias;
|
||||
}
|
||||
// A copy of a parameter passed as values, or a local stored
|
||||
// once from a value before any use, never written again:
|
||||
// those values (no alloca, no stores, no loads). Its store
|
||||
// sets them.
|
||||
if (frame.regs.len > 0 and frame.regs[r.index()]) {
|
||||
const k = if (frame.copies.len > 0) frame.copies[r.index()] else std.math.maxInt(u32);
|
||||
if (k == std.math.maxInt(u32)) return .{ .regs = .{ .vals = &.{} } };
|
||||
if (frame.params[k] == .scalars) return .{ .regs = .{ .vals = frame.params[k].scalars } };
|
||||
}
|
||||
if (e.payload_local) |pl| if (pl.func == f and pl.inst == r.index()) {
|
||||
const dty = try e.memoryType(i.ty);
|
||||
const base = try e.addPrologue(try e.dm.ptrType(dty), .{ .alloca = .{ .elem = dty, .size = try e.i32Const(1) } });
|
||||
|
|
@ -2121,6 +2372,11 @@ const Emitter = struct {
|
|||
return frame.params[frame.copies[p.index()]];
|
||||
} else switch (frame.vals[p.index()]) {
|
||||
.handle => |h| return .{ .handle = h },
|
||||
.regs => |rg| {
|
||||
const n = try e.flatCount(i.ty);
|
||||
if (rg.offset + n > rg.vals.len) return .{ .scalars = try e.undefValues(i.ty) };
|
||||
return .{ .scalars = rg.vals[rg.offset..][0..n] };
|
||||
},
|
||||
.agg_ptr => |ap| {
|
||||
const vals: []const Value = if (ap.data) |d| switch (d.*) {
|
||||
.ptr => |ptr| (try e.loadPtr(ptr, ap.ty)).scalars,
|
||||
|
|
@ -2188,6 +2444,11 @@ const Emitter = struct {
|
|||
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| {
|
||||
// (The values a local kept as values holds.)
|
||||
if (frame.vals[s.ptr.index()] == .regs) {
|
||||
frame.vals[s.ptr.index()] = .{ .regs = .{ .vals = try e.scalars(frame, s.value) } };
|
||||
return .none;
|
||||
}
|
||||
if (frame.param_copies.len > 0) if (f.inst(s.value).op == .param) {
|
||||
const k = f.inst(s.value).op.param;
|
||||
if (frame.param_copies[s.ptr.index()] == k and frame.param_srcs[k] != null) return .none;
|
||||
|
|
@ -2272,6 +2533,31 @@ const Emitter = struct {
|
|||
return .{ .typed = tp };
|
||||
}
|
||||
if (frame.vals[a.base.index()] == .agg_ptr) return e.aggAccess(frame, frame.vals[a.base.index()].agg_ptr, a.indices);
|
||||
if (frame.vals[a.base.index()] == .regs) {
|
||||
var rg = frame.vals[a.base.index()].regs;
|
||||
var cur = f.inst(a.base).ty;
|
||||
for (a.indices) |x| {
|
||||
const k: u32 = @intCast(@max(f.inst(x).op.constant.int, 0));
|
||||
switch (e.t.get(cur)) {
|
||||
.@"struct" => |st| {
|
||||
if (k >= st.fields.items.len) return e.unsupported("struct member index out of range", .{});
|
||||
for (st.fields.items[0..k]) |fld| rg.offset += try e.flatCount(fld.type);
|
||||
cur = st.fields.items[k].type;
|
||||
},
|
||||
else => {
|
||||
const elem: TypeId = switch (e.t.get(cur)) {
|
||||
.array => |arr| arr.elem,
|
||||
.vector => |v| try e.t.scalar(v.elem),
|
||||
.matrix => |mt| try e.t.vector(mt.elem, mt.cols),
|
||||
else => return e.unsupported("indexing this type is not supported yet", .{}),
|
||||
};
|
||||
rg.offset += k * try e.flatCount(elem);
|
||||
cur = elem;
|
||||
},
|
||||
}
|
||||
}
|
||||
return .{ .regs = rg };
|
||||
}
|
||||
// An element of a local array of resources: of the array
|
||||
// it aliases.
|
||||
if (frame.vals[a.base.index()] == .res_local) {
|
||||
|
|
@ -2745,6 +3031,18 @@ const Emitter = struct {
|
|||
/// memory rather than a flat array).
|
||||
fn mixedSizes(e: *Emitter, ty: TypeId) Error!bool {
|
||||
if (e.t.get(ty) != .@"struct" and e.t.get(ty) != .array) return false;
|
||||
if (e.mixed_sizes.get(ty)) |v| return v;
|
||||
const v = try e.checkMixedSizes(ty);
|
||||
try e.mixed_sizes.put(e.arena, ty, v);
|
||||
return v;
|
||||
}
|
||||
|
||||
fn checkMixedSizes(e: *Emitter, ty: TypeId) Error!bool {
|
||||
// (An array's components repeat its element's.)
|
||||
if (e.t.get(ty) == .array) {
|
||||
const arr = e.t.get(ty).array;
|
||||
return arr.len > 0 and try e.mixedSizes(arr.elem);
|
||||
}
|
||||
const n = try e.flatCount(ty);
|
||||
var size: ?u32 = null;
|
||||
for (0..n) |k| {
|
||||
|
|
@ -2758,6 +3056,17 @@ const Emitter = struct {
|
|||
/// Whether `ty`'s components differ in type (all 32-bit), so storage is
|
||||
/// i32 with bitcasts.
|
||||
fn mixedStorage(e: *Emitter, ty: TypeId) Error!bool {
|
||||
if (e.mixed_storage.get(ty)) |v| return v;
|
||||
const v = try e.checkMixedStorage(ty);
|
||||
try e.mixed_storage.put(e.arena, ty, v);
|
||||
return v;
|
||||
}
|
||||
|
||||
fn checkMixedStorage(e: *Emitter, ty: TypeId) Error!bool {
|
||||
if (e.t.get(ty) == .array) {
|
||||
const arr = e.t.get(ty).array;
|
||||
return arr.len > 0 and try e.mixedStorage(arr.elem);
|
||||
}
|
||||
const n = try e.flatCount(ty);
|
||||
var first: ?Scalar = null;
|
||||
var mixed = false;
|
||||
|
|
@ -2777,7 +3086,7 @@ const Emitter = struct {
|
|||
const n = try e.flatCount(ty);
|
||||
const out = try e.arena.alloc(Value, n);
|
||||
for (out, 0..) |*o, c| {
|
||||
if (ptr.offset_dyn == null) if (e.forwarded.get(.{ ptr.base, ptr.offset_const + @as(u32, @intCast(c)) })) |fw| if (fw.block == e.cur) {
|
||||
if (ptr.offset_dyn == null and e.forwarded.count() > 0) if (e.forwarded.get(.{ ptr.base, ptr.offset_const + @as(u32, @intCast(c)) })) |fw| if (fw.block == e.cur) {
|
||||
o.* = fw.v;
|
||||
continue;
|
||||
};
|
||||
|
|
@ -2800,10 +3109,14 @@ const Emitter = struct {
|
|||
for (vals, 0..) |v, c| {
|
||||
if (ptr.offset_dyn == null) {
|
||||
const key = .{ ptr.base, ptr.offset_const + @as(u32, @intCast(c)) };
|
||||
// (Constants too, in locals: ops such as linear algebra
|
||||
// layouts need immediates passed through parameters.)
|
||||
const forward = e.status_vals.contains(v) or (v == .constant and ptr.addr_space == 0);
|
||||
if (forward) try e.forwarded.put(e.arena, key, .{ .v = v, .block = e.cur }) else _ = e.forwarded.remove(key);
|
||||
// (Every value stored to a local: later loads of it in the
|
||||
// block need no instructions, and constants stay constants,
|
||||
// as ops such as linear algebra layouts need immediates
|
||||
// passed through parameters.)
|
||||
const forward = ptr.addr_space == 0 or (e.status_vals.count() > 0 and e.status_vals.contains(v));
|
||||
if (forward) {
|
||||
try e.forwarded.put(e.arena, key, .{ .v = v, .block = e.cur });
|
||||
} else if (e.forwarded.count() > 0) _ = e.forwarded.remove(key);
|
||||
} else e.forwarded.clearRetainingCapacity();
|
||||
const p = try e.elementPtr(ptr, @intCast(c));
|
||||
const ct = e.compOf(try e.componentType(ty, @intCast(c)));
|
||||
|
|
@ -2829,12 +3142,27 @@ const Emitter = struct {
|
|||
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 } });
|
||||
const pt = try e.dm.getType(.{ .pointer = .{ .elem = ptr.scalar_ty, .addr_space = ptr.addr_space } });
|
||||
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 (e.elem_ptr_ty.elem != ptr.scalar_ty or e.elem_ptr_ty.space != ptr.addr_space) e.elem_ptr_ty = .{
|
||||
.elem = ptr.scalar_ty,
|
||||
.space = ptr.addr_space,
|
||||
.ty = try e.dm.getType(.{ .pointer = .{ .elem = ptr.scalar_ty, .addr_space = ptr.addr_space } }),
|
||||
};
|
||||
const zero = try e.i32Const(0);
|
||||
const gep = try e.add(e.elem_ptr_ty.ty, .{ .gep = .{ .elem = ptr.array_ty, .ptr = ptr.base, .indices = try e.zeroIndexed(zero, idx) } });
|
||||
if (ptr.offset_dyn != null) if (ptr.dyn_range) |r| try e.dyn_ranges.put(e.arena, gep.inst, r);
|
||||
return gep;
|
||||
}
|
||||
|
||||
/// The indices `{ 0, idx }`, shared between getelementptrs with the
|
||||
/// same constant `idx` (no pass writes operand slices).
|
||||
fn zeroIndexed(e: *Emitter, zero: Value, idx: Value) Error![]const Value {
|
||||
if (idx != .constant) return e.arena.dupe(Value, &.{ zero, idx });
|
||||
const k = idx.constant;
|
||||
if (k >= e.zero_indexed.items.len) try e.zero_indexed.appendNTimes(e.arena, &.{}, k + 1 - e.zero_indexed.items.len);
|
||||
if (e.zero_indexed.items[k].len == 0) e.zero_indexed.items[k] = try e.arena.dupe(Value, &.{ zero, idx });
|
||||
return e.zero_indexed.items[k];
|
||||
}
|
||||
|
||||
fn convertScalar(e: *Emitter, v: Value, from: Scalar, to: Scalar) Error!Value {
|
||||
if (from == to) return v;
|
||||
const tt = try e.scalarTy(to);
|
||||
|
|
@ -3675,7 +4003,7 @@ const Emitter = struct {
|
|||
switch (e.t.get(cur)) {
|
||||
.@"struct" => |st| {
|
||||
const k: u32 = @intCast(xi.op.constant.int);
|
||||
const offs = layout.fieldOffsets(e.arena, e.t, st, .dx_legacy) catch return e.unsupported("constant buffer member types", .{});
|
||||
const offs = e.fieldOffsets(st, .dx_legacy) catch return e.unsupported("constant buffer member types", .{});
|
||||
c.offset += offs[k];
|
||||
c.row_major = st.fields.items[k].row_major;
|
||||
cur = st.fields.items[k].type;
|
||||
|
|
@ -3727,7 +4055,7 @@ const Emitter = struct {
|
|||
const mem_c: Scalar = if (c == .bool) .uint else c;
|
||||
// A register holds 16 bytes: 4 32-bit, 2 64-bit or 8 16-bit values.
|
||||
const sz = mem_c.size();
|
||||
const off = offset + (layout.componentOffset(e.arena, e.t, ty, row_major, @intCast(k), .dx_legacy) catch return e.unsupported("constant buffer member types", .{}));
|
||||
const off = offset + (e.componentOffset(ty, row_major, @intCast(k), .dx_legacy) catch return e.unsupported("constant buffer member types", .{}));
|
||||
const reg = off / 16;
|
||||
const st = try e.scalarTy(mem_c);
|
||||
if (res.kind == 15) {
|
||||
|
|
@ -3792,14 +4120,10 @@ const Emitter = struct {
|
|||
.scalar, .@"enum", .linalg => return ty,
|
||||
.vector, .matrix => return e.t.scalar(e.t.component(ty).?),
|
||||
.array => |a| return e.componentType(a.elem, k % try e.flatCount(a.elem)),
|
||||
.@"struct" => |s| {
|
||||
var kk = k;
|
||||
for (s.fields.items) |f| {
|
||||
const n = try e.flatCount(f.type);
|
||||
if (kk < n) return e.componentType(f.type, kk);
|
||||
kk -= n;
|
||||
}
|
||||
return e.unsupported("struct component", .{});
|
||||
.@"struct" => {
|
||||
const comps = try e.structComps(ty);
|
||||
if (k >= comps.len) return e.unsupported("struct component", .{});
|
||||
return comps[k];
|
||||
},
|
||||
else => return e.unsupported("component type", .{}),
|
||||
}
|
||||
|
|
@ -3913,7 +4237,8 @@ const Emitter = struct {
|
|||
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 kind = try e.dm.mdKind("dx.nonuniform");
|
||||
e.insts.at(blk[blk.len - 1]).md = try e.dm.instMd(kind, 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;
|
||||
|
|
@ -4412,7 +4737,7 @@ const Emitter = struct {
|
|||
switch (e.t.get(cur)) {
|
||||
.@"struct" => |st| {
|
||||
const k: u32 = @intCast(xi.op.constant.int);
|
||||
const offs = layout.fieldOffsets(e.arena, e.t, st, .dx_packed) catch return e.unsupported("buffer member types", .{});
|
||||
const offs = e.fieldOffsets(st, .dx_packed) catch return e.unsupported("buffer member types", .{});
|
||||
b.offset += offs[k];
|
||||
b.row_major = st.fields.items[k].row_major;
|
||||
cur = st.fields.items[k].type;
|
||||
|
|
@ -4456,15 +4781,15 @@ const Emitter = struct {
|
|||
const res = e.resources.items[b.res];
|
||||
for (vals, 0..) |v, j| {
|
||||
const c: u32 = mat.col orelse @intCast(j);
|
||||
const off0 = layout.componentOffset(e.arena, e.t, mat.ty, b.row_major, c, .dx_packed) catch return e.unsupported("buffer element types", .{});
|
||||
const off0 = e.componentOffset(mat.ty, b.row_major, c, .dx_packed) catch return e.unsupported("buffer element types", .{});
|
||||
const const_row: ?i64 = if (m.rows == 1) 0 else e.constIntOf(mat.row);
|
||||
if (const_row) |row| {
|
||||
const off = layout.componentOffset(e.arena, e.t, mat.ty, b.row_major, @as(u32, @intCast(row)) * m.cols + c, .dx_packed) catch return e.unsupported("buffer element types", .{});
|
||||
const off = e.componentOffset(mat.ty, b.row_major, @as(u32, @intCast(row)) * m.cols + c, .dx_packed) catch return e.unsupported("buffer element types", .{});
|
||||
try e.structuredStore(res, b.index, b.offset + off, b.dyn, b.row_major, ec, &.{v});
|
||||
continue;
|
||||
}
|
||||
// A dynamic row: rows are a constant byte step apart.
|
||||
const step = (layout.componentOffset(e.arena, e.t, mat.ty, b.row_major, m.cols + c, .dx_packed) catch return e.unsupported("buffer element types", .{})) - off0;
|
||||
const step = (e.componentOffset(mat.ty, b.row_major, m.cols + c, .dx_packed) catch return e.unsupported("buffer element types", .{})) - off0;
|
||||
var dyn = try e.add(i32t, .{ .binop = .{ .op = .mul, .lhs = mat.row, .rhs = try e.i32Const(step) } });
|
||||
if (b.dyn) |d| dyn = try e.add(i32t, .{ .binop = .{ .op = .add, .lhs = d, .rhs = dyn } });
|
||||
try e.structuredStore(res, b.index, b.offset + off0, dyn, b.row_major, ec, &.{v});
|
||||
|
|
@ -4482,12 +4807,12 @@ const Emitter = struct {
|
|||
while (k < n) {
|
||||
const c0 = e.compOf(try e.componentType(ty, k));
|
||||
const mem: Scalar = if (c0 == .bool) .uint else c0;
|
||||
const off0 = layout.componentOffset(e.arena, e.t, ty, row_major, k, .dx_packed) catch return e.unsupported("buffer element types", .{});
|
||||
const off0 = e.componentOffset(ty, row_major, k, .dx_packed) catch return e.unsupported("buffer element types", .{});
|
||||
var count: u32 = 1;
|
||||
while (k + count < n and count < 4) : (count += 1) {
|
||||
const cn = e.compOf(try e.componentType(ty, k + count));
|
||||
const mn: Scalar = if (cn == .bool) .uint else cn;
|
||||
const on = layout.componentOffset(e.arena, e.t, ty, row_major, k + count, .dx_packed) catch break;
|
||||
const on = e.componentOffset(ty, row_major, k + count, .dx_packed) catch break;
|
||||
if (mn != mem or on != off0 + count * mem.size()) break;
|
||||
}
|
||||
const st = try e.scalarTy(mem);
|
||||
|
|
@ -4541,12 +4866,12 @@ const Emitter = struct {
|
|||
while (k < n) {
|
||||
const c0 = e.compOf(try e.componentType(ty, k));
|
||||
const mem: Scalar = if (c0 == .bool) .uint else c0;
|
||||
const off0 = layout.componentOffset(e.arena, e.t, ty, row_major, k, .dx_packed) catch return e.unsupported("buffer element types", .{});
|
||||
const off0 = e.componentOffset(ty, row_major, k, .dx_packed) catch return e.unsupported("buffer element types", .{});
|
||||
var count: u32 = 1;
|
||||
while (k + count < n and count < 4) : (count += 1) {
|
||||
const cn = e.compOf(try e.componentType(ty, k + count));
|
||||
const mn: Scalar = if (cn == .bool) .uint else cn;
|
||||
const on = layout.componentOffset(e.arena, e.t, ty, row_major, k + count, .dx_packed) catch break;
|
||||
const on = e.componentOffset(ty, row_major, k + count, .dx_packed) catch break;
|
||||
if (mn != mem or on != off0 + count * mem.size()) break;
|
||||
}
|
||||
const st = try e.scalarTy(mem);
|
||||
|
|
@ -4659,7 +4984,7 @@ const Emitter = struct {
|
|||
/// (templated Load / Store: natural alignment; dxc's DXIL lays
|
||||
/// matrices out by row here, its SPIR-V by column).
|
||||
fn rawOffset(e: *Emitter, ty: TypeId, k: u32) Error!u32 {
|
||||
return layout.componentOffset(e.arena, e.t, ty, true, k, .dx_packed) catch e.unsupported("byte-address buffer accesses of type '{s}' are not supported yet", .{try e.t.format(e.arena, ty)});
|
||||
return e.componentOffset(ty, true, k, .dx_packed) catch e.unsupported("byte-address buffer accesses of type '{s}' are not supported yet", .{try e.t.format(e.arena, ty)});
|
||||
}
|
||||
|
||||
/// A templated byte-address Load: one raw load per component.
|
||||
|
|
@ -5919,7 +6244,7 @@ const Emitter = struct {
|
|||
if (resources) |r| try dm.addNamedMetadata("dx.resources", &.{r});
|
||||
if (funcs.len > 0) try dm.addNamedMetadata("dx.typeAnnotations", &.{type_annotations});
|
||||
try dm.addNamedMetadata("dx.entryPoints", entries.items);
|
||||
return dm.writeBitcode(dm.arena.child_allocator);
|
||||
return dm.writeBitcode(dm.arena.child);
|
||||
}
|
||||
|
||||
// ---- Reflection (reflect.zig) -----------------------------------------
|
||||
|
|
@ -6200,7 +6525,7 @@ const Emitter = struct {
|
|||
d.rows = 1;
|
||||
d.cols = layout.flatCount(e.t, t) catch 0;
|
||||
d.name = s.name;
|
||||
const offs = layout.fieldOffsets(e.arena, e.t, s, .dx_legacy) catch return e.unsupported("reflection of '{s}'", .{s.name});
|
||||
const offs = e.fieldOffsets(s, .dx_legacy) catch return e.unsupported("reflection of '{s}'", .{s.name});
|
||||
var members: std.ArrayList(reflect.Member) = .empty;
|
||||
for (s.fields.items, offs) |fld, off| {
|
||||
if (fld.bits or layout.isOpaque(e.t, fld.type)) continue;
|
||||
|
|
@ -6363,7 +6688,7 @@ const Emitter = struct {
|
|||
if (g.space == .cbuffer and e.t.get(g.ty) == .@"struct") {
|
||||
// A cbuffer block: its members are the variables.
|
||||
const s = e.t.get(g.ty).@"struct";
|
||||
const offs = layout.fieldOffsets(e.arena, e.t, s, .dx_legacy) catch return e.unsupported("reflection of constant buffer '{s}'", .{g.name});
|
||||
const offs = e.fieldOffsets(s, .dx_legacy) catch return e.unsupported("reflection of constant buffer '{s}'", .{g.name});
|
||||
for (s.fields.items, offs) |fld, off| {
|
||||
if (fld.bits) continue;
|
||||
const fsize = layout.sizeOf(e.t, fld.type, fld.row_major, .dx_legacy) catch 0;
|
||||
|
|
@ -6578,6 +6903,8 @@ const Emitter = struct {
|
|||
}
|
||||
|
||||
fn writeModule(e: *Emitter, entry: ir.Entry) Error![]u8 {
|
||||
const zone = stats.begin(.bitcode);
|
||||
defer zone.end();
|
||||
const dm = &e.dm;
|
||||
const mdI32 = struct {
|
||||
fn f(m: *module.Module, v: i64) !module.MdId {
|
||||
|
|
@ -6618,7 +6945,7 @@ const Emitter = struct {
|
|||
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);
|
||||
return dm.writeBitcode(dm.arena.child);
|
||||
}
|
||||
|
||||
/// `!{id, name, comp, kind, !{indices}, interp, rows, cols, row, col,
|
||||
|
|
@ -6648,6 +6975,8 @@ const Emitter = struct {
|
|||
}
|
||||
|
||||
fn assemble(e: *Emitter, gpa: Allocator, entry: ir.Entry, bitcode: []const u8) Error![]u8 {
|
||||
const zone = stats.begin(.container);
|
||||
defer zone.end();
|
||||
const dxil_part = try shader.programPart(gpa, e.profile, bitcode);
|
||||
defer gpa.free(dxil_part);
|
||||
var binds: std.ArrayList(shader.ResourceBind) = .empty;
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@
|
|||
//! unabbreviated records only.
|
||||
|
||||
const std = @import("std");
|
||||
const BumpArena = @import("../BumpArena.zig");
|
||||
const Allocator = std.mem.Allocator;
|
||||
const bitstream = @import("bitstream.zig");
|
||||
|
||||
|
|
@ -39,6 +40,38 @@ pub const Type = union(enum) {
|
|||
}
|
||||
};
|
||||
|
||||
/// splitmix64's finalizer: a cheap hash of a word, for the type and
|
||||
/// constant pools (a hash map uses both its high and low bits).
|
||||
fn mix(x: u64) u64 {
|
||||
var z = x;
|
||||
z = (z ^ (z >> 30)) *% 0xbf58476d1ce4e5b9;
|
||||
z = (z ^ (z >> 27)) *% 0x94d049bb133111eb;
|
||||
return z ^ (z >> 31);
|
||||
}
|
||||
|
||||
/// Hashes what Type.eql compares.
|
||||
const TypeContext = struct {
|
||||
pub fn hash(_: TypeContext, t: Type) u64 {
|
||||
const tag: u64 = @backingInt(t);
|
||||
return switch (t) {
|
||||
.void, .label, .metadata, .half, .float, .double => mix(tag),
|
||||
.int => |w| mix(tag << 56 | w),
|
||||
.pointer => |p| mix(tag << 56 | @as(u64, p.addr_space) << 32 | p.elem),
|
||||
.function => |f| mix(tag << 56 | f.ret) ^ std.hash.Wyhash.hash(0, std.mem.sliceAsBytes(f.params)),
|
||||
.@"struct" => |st| mix(tag) ^ std.hash.Wyhash.hash(0, st.name),
|
||||
.array => |x| mix(mix(tag << 56 | x.elem) ^ x.len),
|
||||
.vector => |x| mix(tag << 56 | @as(u64, x.len) << 32 | x.elem),
|
||||
};
|
||||
}
|
||||
|
||||
pub fn eql(_: TypeContext, a: Type, b: Type) bool {
|
||||
return a.eql(b);
|
||||
}
|
||||
};
|
||||
|
||||
const no_type = std.math.maxInt(TypeId);
|
||||
const no_const = std.math.maxInt(ConstId);
|
||||
|
||||
pub const Constant = struct {
|
||||
ty: TypeId,
|
||||
kind: union(enum) {
|
||||
|
|
@ -52,6 +85,24 @@ pub const Constant = struct {
|
|||
},
|
||||
};
|
||||
|
||||
/// Constants are equal when their type and kind are (aggregates: the same
|
||||
/// element slice, as std.meta.eql compares slices).
|
||||
const ConstantContext = struct {
|
||||
pub fn hash(_: ConstantContext, c: Constant) u64 {
|
||||
const head = mix(@as(u64, @backingInt(c.kind)) << 32 | c.ty);
|
||||
return switch (c.kind) {
|
||||
.int => |v| mix(head ^ @as(u64, @bitCast(v))),
|
||||
.float_bits => |v| mix(head ^ v),
|
||||
.undef, .null => head,
|
||||
.aggregate => |a| mix(head ^ @intFromPtr(a.ptr) ^ a.len << 48),
|
||||
};
|
||||
}
|
||||
|
||||
pub fn eql(_: ConstantContext, a: Constant, b: Constant) bool {
|
||||
return a.ty == b.ty and std.meta.eql(a.kind, b.kind);
|
||||
}
|
||||
};
|
||||
|
||||
pub const Linkage = enum(u32) { external = 0, internal = 3 };
|
||||
|
||||
/// Attribute group for function declarations (e.g. dx.op functions).
|
||||
|
|
@ -106,11 +157,15 @@ pub const Inst = struct {
|
|||
extractelement: struct { vec: 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,
|
||||
/// An attached metadata node, as `!dx.nonuniform` on a resource
|
||||
/// array's getelementptr (see Module.instMd).
|
||||
md: InstMd = .none,
|
||||
};
|
||||
|
||||
/// An instruction's metadata attachment: an index into Module.inst_mds,
|
||||
/// kept out of line (few instructions have one).
|
||||
pub const InstMd = enum(u32) { none = 0, _ };
|
||||
|
||||
pub const Function = struct {
|
||||
name: []const u8,
|
||||
ty: TypeId,
|
||||
|
|
@ -130,15 +185,24 @@ pub const Metadata = union(enum) {
|
|||
};
|
||||
|
||||
pub const Module = struct {
|
||||
arena: std.heap.ArenaAllocator,
|
||||
arena: BumpArena,
|
||||
triple: []const u8 = "dxil-ms-dx",
|
||||
datalayout: []const u8 = "e-m:e-p:32:32-i1:32-i8:32-i16:32-i32:32-i64:64-f16:32-f32:32-f64:64-n8:16:32:64",
|
||||
types: std.ArrayList(Type) = .empty,
|
||||
/// Index of `types`, for getType to find existing ones.
|
||||
type_ids: std.HashMapUnmanaged(Type, TypeId, TypeContext, std.hash_map.default_max_load_percentage) = .empty,
|
||||
constants: std.ArrayList(Constant) = .empty,
|
||||
/// Index of `constants`, for constant() to find existing ones.
|
||||
constant_ids: std.HashMapUnmanaged(Constant, ConstId, ConstantContext, std.hash_map.default_max_load_percentage) = .empty,
|
||||
functions: std.ArrayList(Function) = .empty,
|
||||
/// intType's and constInt's results for common arguments.
|
||||
int_types: [65]TypeId = @splat(no_type),
|
||||
small_i32: [1024]ConstId = @splat(no_const),
|
||||
globals: std.ArrayList(GlobalVar) = .empty,
|
||||
metadata: std.ArrayList(Metadata) = .empty,
|
||||
named_metadata: std.ArrayList(struct { name: []const u8, nodes: []const MdId }) = .empty,
|
||||
/// Instruction metadata attachments (InstMd), from 1.
|
||||
inst_mds: std.ArrayList(struct { kind: u32, node: MdId }) = .empty,
|
||||
/// Instruction metadata kinds, by id.
|
||||
md_kinds: std.ArrayList([]const u8) = .empty,
|
||||
|
||||
|
|
@ -155,9 +219,7 @@ pub const Module = struct {
|
|||
}
|
||||
|
||||
pub fn getType(m: *Module, t: Type) !TypeId {
|
||||
for (m.types.items, 0..) |existing, i| {
|
||||
if (existing.eql(t)) return @intCast(i);
|
||||
}
|
||||
if (m.type_ids.get(t)) |id| return id;
|
||||
const a = m.allocator();
|
||||
var owned = t;
|
||||
switch (owned) {
|
||||
|
|
@ -168,11 +230,18 @@ pub const Module = struct {
|
|||
},
|
||||
else => {},
|
||||
}
|
||||
const id: TypeId = @intCast(m.types.items.len);
|
||||
try m.type_ids.ensureUnusedCapacity(a, 1);
|
||||
try m.types.append(a, owned);
|
||||
return @intCast(m.types.items.len - 1);
|
||||
m.type_ids.putAssumeCapacity(owned, id);
|
||||
return id;
|
||||
}
|
||||
|
||||
pub fn intType(m: *Module, bits: u32) !TypeId {
|
||||
if (bits < m.int_types.len) {
|
||||
if (m.int_types[bits] == no_type) m.int_types[bits] = try m.getType(.{ .int = bits });
|
||||
return m.int_types[bits];
|
||||
}
|
||||
return m.getType(.{ .int = bits });
|
||||
}
|
||||
|
||||
|
|
@ -200,17 +269,134 @@ pub const Module = struct {
|
|||
}
|
||||
|
||||
pub fn constant(m: *Module, c: Constant) !Value {
|
||||
for (m.constants.items, 0..) |existing, i| {
|
||||
if (existing.ty == c.ty and std.meta.eql(existing.kind, c.kind)) return .{ .constant = @intCast(i) };
|
||||
const gop = try m.constant_ids.getOrPut(m.allocator(), c);
|
||||
if (!gop.found_existing) {
|
||||
gop.value_ptr.* = @intCast(m.constants.items.len);
|
||||
m.constants.append(m.allocator(), c) catch |err| {
|
||||
m.constant_ids.removeByPtr(gop.key_ptr);
|
||||
return err;
|
||||
};
|
||||
}
|
||||
try m.constants.append(m.allocator(), c);
|
||||
return .{ .constant = @intCast(m.constants.items.len - 1) };
|
||||
return .{ .constant = gop.value_ptr.* };
|
||||
}
|
||||
|
||||
pub fn constInt(m: *Module, bits: u32, v: i64) !Value {
|
||||
if (bits == 32 and v >= 0 and v < m.small_i32.len) {
|
||||
const k: usize = @intCast(v);
|
||||
if (m.small_i32[k] == no_const) m.small_i32[k] = (try m.constant(.{ .ty = try m.intType(32), .kind = .{ .int = v } })).constant;
|
||||
return .{ .constant = m.small_i32[k] };
|
||||
}
|
||||
return m.constant(.{ .ty = try m.intType(bits), .kind = .{ .int = v } });
|
||||
}
|
||||
|
||||
/// An attachment of node `node` as metadata kind `kind` (from mdKind).
|
||||
pub fn instMd(m: *Module, kind: u32, node: MdId) !InstMd {
|
||||
try m.inst_mds.append(m.allocator(), .{ .kind = kind, .node = node });
|
||||
return @fromBackingInt(@intCast(m.inst_mds.items.len));
|
||||
}
|
||||
|
||||
/// Drops the constants nothing uses, and numbers the rest in order of
|
||||
/// first use (functions' instructions, then metadata), grouped by type,
|
||||
/// with aggregates last, after their elements. The output then depends
|
||||
/// only on the code that is left, not on code made and removed again or
|
||||
/// on the order constants were first asked for.
|
||||
fn pruneConstants(m: *Module) !void {
|
||||
const a = m.allocator();
|
||||
const n = m.constants.items.len;
|
||||
if (n == 0) return;
|
||||
const Walk = struct {
|
||||
m: *Module,
|
||||
a: Allocator,
|
||||
seen: []bool,
|
||||
order: std.ArrayList(ConstId) = .empty,
|
||||
failed: bool = false,
|
||||
|
||||
fn map(w: *@This(), v: Value) Value {
|
||||
if (v == .constant) w.visit(v.constant) catch {
|
||||
w.failed = true;
|
||||
};
|
||||
return v;
|
||||
}
|
||||
|
||||
fn visit(w: *@This(), c: ConstId) Allocator.Error!void {
|
||||
if (w.seen[c]) return;
|
||||
w.seen[c] = true;
|
||||
switch (w.m.constants.items[c].kind) {
|
||||
.aggregate => |els| for (els) |el| try w.visit(el),
|
||||
else => {},
|
||||
}
|
||||
try w.order.append(w.a, c);
|
||||
}
|
||||
};
|
||||
var walk: Walk = .{ .m = m, .a = a, .seen = try a.alloc(bool, n) };
|
||||
@memset(walk.seen, false);
|
||||
for (m.functions.items) |f| for (f.insts.items) |inst| {
|
||||
var copy = inst;
|
||||
// (Reading only: no slice is copied, nothing changes.)
|
||||
try mapOperands(a, ©, &walk);
|
||||
};
|
||||
for (m.metadata.items) |md| if (md == .value) {
|
||||
_ = walk.map(md.value.val);
|
||||
};
|
||||
if (walk.failed) return error.OutOfMemory;
|
||||
|
||||
// Types in order of first use; scalars by type (stable), then
|
||||
// aggregates in walk order (each after its elements).
|
||||
var rank: std.AutoHashMapUnmanaged(TypeId, u32) = .empty;
|
||||
const Key = struct { rank: u32, id: ConstId };
|
||||
var scalars: std.ArrayList(Key) = .empty;
|
||||
var aggregates: std.ArrayList(ConstId) = .empty;
|
||||
for (walk.order.items) |c| {
|
||||
const k = m.constants.items[c];
|
||||
if (k.kind == .aggregate) {
|
||||
try aggregates.append(a, c);
|
||||
continue;
|
||||
}
|
||||
const gop = try rank.getOrPut(a, k.ty);
|
||||
if (!gop.found_existing) gop.value_ptr.* = rank.count() - 1;
|
||||
try scalars.append(a, .{ .rank = gop.value_ptr.*, .id = c });
|
||||
}
|
||||
std.sort.block(Key, scalars.items, {}, struct {
|
||||
fn lt(_: void, x: Key, y: Key) bool {
|
||||
return x.rank < y.rank;
|
||||
}
|
||||
}.lt);
|
||||
|
||||
const new_id = try a.alloc(ConstId, n);
|
||||
@memset(new_id, no_const);
|
||||
var kept: std.ArrayList(Constant) = .empty;
|
||||
try kept.ensureTotalCapacityPrecise(a, walk.order.items.len);
|
||||
for (scalars.items) |k| {
|
||||
new_id[k.id] = @intCast(kept.items.len);
|
||||
kept.appendAssumeCapacity(m.constants.items[k.id]);
|
||||
}
|
||||
for (aggregates.items) |c| {
|
||||
var k = m.constants.items[c];
|
||||
const els = try a.alloc(ConstId, k.kind.aggregate.len);
|
||||
for (k.kind.aggregate, els) |el, *o| o.* = new_id[el];
|
||||
k.kind = .{ .aggregate = els };
|
||||
new_id[c] = @intCast(kept.items.len);
|
||||
kept.appendAssumeCapacity(k);
|
||||
}
|
||||
|
||||
const Remap = struct {
|
||||
new_id: []const ConstId,
|
||||
fn map(r: @This(), v: Value) Value {
|
||||
return if (v == .constant) .{ .constant = r.new_id[v.constant] } else v;
|
||||
}
|
||||
};
|
||||
const remap: Remap = .{ .new_id = new_id };
|
||||
for (m.functions.items) |*f| for (f.insts.items) |*inst| try mapOperands(a, inst, remap);
|
||||
for (m.metadata.items) |*md| if (md.* == .value) {
|
||||
md.value.val = remap.map(md.value.val);
|
||||
};
|
||||
m.constants = kept;
|
||||
// (Constants made from here on start a new index.)
|
||||
m.constant_ids = .empty;
|
||||
for (m.constants.items, 0..) |c, i| try m.constant_ids.put(a, c, @intCast(i));
|
||||
m.small_i32 = @splat(no_const);
|
||||
}
|
||||
|
||||
pub fn addFunction(m: *Module, f: Function) !u32 {
|
||||
var owned = f;
|
||||
owned.name = try m.allocator().dupe(u8, f.name);
|
||||
|
|
@ -269,12 +455,94 @@ pub const Module = struct {
|
|||
|
||||
/// Encode the module as raw LLVM bitcode (starting with 'BC' 0xC0DE).
|
||||
pub fn writeBitcode(m: *Module, gpa: Allocator) ![]u8 {
|
||||
try m.pruneConstants();
|
||||
var enc: Encoder = .{ .m = m, .w = .init(gpa) };
|
||||
defer enc.w.deinit();
|
||||
return enc.write();
|
||||
}
|
||||
};
|
||||
|
||||
/// Calls `ctx.map(v) Value` on each value operand of `inst` and stores the
|
||||
/// results; operand slices whose values change are copied (slices may be
|
||||
/// shared between instructions).
|
||||
fn mapOperands(a: Allocator, inst: *Inst, ctx: anytype) !void {
|
||||
const S = struct {
|
||||
fn many(al: Allocator, c: anytype, xs: []const Value) ![]const Value {
|
||||
for (xs, 0..) |x, k| {
|
||||
if (std.meta.eql(c.map(x), x)) continue;
|
||||
const out = try al.dupe(Value, xs);
|
||||
for (out[k..]) |*o| o.* = c.map(o.*);
|
||||
return out;
|
||||
}
|
||||
return xs;
|
||||
}
|
||||
};
|
||||
switch (inst.op) {
|
||||
.ret => |*v| if (v.*) |x| {
|
||||
v.* = ctx.map(x);
|
||||
},
|
||||
.br => |*b| if (b.cond) |c| {
|
||||
b.cond = ctx.map(c);
|
||||
},
|
||||
.@"switch" => |*sw| {
|
||||
sw.cond = ctx.map(sw.cond);
|
||||
const cases = try a.dupe(@typeInfo(@TypeOf(sw.cases)).pointer.child, sw.cases);
|
||||
for (cases) |*c| c.val = ctx.map(c.val);
|
||||
sw.cases = cases;
|
||||
},
|
||||
.call => |*c| c.args = try S.many(a, ctx, c.args),
|
||||
.binop => |*b| {
|
||||
b.lhs = ctx.map(b.lhs);
|
||||
b.rhs = ctx.map(b.rhs);
|
||||
},
|
||||
.cast => |*c| c.val = ctx.map(c.val),
|
||||
.cmp => |*c| {
|
||||
c.lhs = ctx.map(c.lhs);
|
||||
c.rhs = ctx.map(c.rhs);
|
||||
},
|
||||
.select => |*x| {
|
||||
x.cond = ctx.map(x.cond);
|
||||
x.t = ctx.map(x.t);
|
||||
x.f = ctx.map(x.f);
|
||||
},
|
||||
.extractvalue => |*x| x.agg = ctx.map(x.agg),
|
||||
.phi => |*p| {
|
||||
const ins = try a.dupe(@typeInfo(@TypeOf(p.incoming)).pointer.child, p.incoming);
|
||||
for (ins) |*in| in.val = ctx.map(in.val);
|
||||
p.incoming = ins;
|
||||
},
|
||||
.alloca => |*x| x.size = ctx.map(x.size),
|
||||
.load => |*x| x.ptr = ctx.map(x.ptr),
|
||||
.store => |*x| {
|
||||
x.ptr = ctx.map(x.ptr);
|
||||
x.val = ctx.map(x.val);
|
||||
},
|
||||
.gep => |*x| {
|
||||
x.ptr = ctx.map(x.ptr);
|
||||
x.indices = try S.many(a, ctx, x.indices);
|
||||
},
|
||||
.atomicrmw => |*x| {
|
||||
x.ptr = ctx.map(x.ptr);
|
||||
x.val = ctx.map(x.val);
|
||||
},
|
||||
.cmpxchg => |*x| {
|
||||
x.ptr = ctx.map(x.ptr);
|
||||
x.cmp = ctx.map(x.cmp);
|
||||
x.new = ctx.map(x.new);
|
||||
},
|
||||
.@"unreachable" => {},
|
||||
.extractelement => |*x| {
|
||||
x.vec = ctx.map(x.vec);
|
||||
x.index = ctx.map(x.index);
|
||||
},
|
||||
.insertelement => |*x| {
|
||||
x.vec = ctx.map(x.vec);
|
||||
x.val = ctx.map(x.val);
|
||||
x.index = ctx.map(x.index);
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
const block_module = 8;
|
||||
const block_paramattr = 9;
|
||||
const block_paramattr_group = 10;
|
||||
|
|
@ -702,10 +970,11 @@ const Encoder = struct {
|
|||
}
|
||||
// METADATA_ATTACHMENT: [instruction index, (kind, node)...]
|
||||
var any_md = false;
|
||||
for (f.insts.items) |inst| any_md = any_md or inst.md != null;
|
||||
for (f.insts.items) |inst| any_md = any_md or inst.md != .none;
|
||||
if (any_md) {
|
||||
try w.enterBlock(block_metadata_attachment, 3);
|
||||
for (f.insts.items, 0..) |inst, k| if (inst.md) |md| {
|
||||
for (f.insts.items, 0..) |inst, k| if (inst.md != .none) {
|
||||
const md = e.m.inst_mds.items[@backingInt(inst.md) - 1];
|
||||
try e.ops.appendSlice(e.gpa(), &.{ k, md.kind, md.node });
|
||||
try e.rec(11);
|
||||
};
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@
|
|||
const std = @import("std");
|
||||
const Allocator = std.mem.Allocator;
|
||||
const module = @import("module.zig");
|
||||
const stats = @import("../stats.zig");
|
||||
|
||||
const Value = module.Value;
|
||||
const Inst = module.Inst;
|
||||
|
|
@ -123,6 +124,9 @@ fn isScalar(m: *const module.Module, ty: TypeId) bool {
|
|||
/// `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 zone = stats.begin(.promote);
|
||||
stats.add(.promote_runs, 1);
|
||||
defer zone.end();
|
||||
const f = &m.functions.items[func];
|
||||
const insts = f.insts.items;
|
||||
const n: u32 = @intCast(insts.len);
|
||||
|
|
@ -133,15 +137,25 @@ pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashM
|
|||
// 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);
|
||||
// The allocas, getelementptrs, and loads and stores, in order: the
|
||||
// passes over just those walk these, not every instruction.
|
||||
var allocas: std.ArrayList(u32) = .empty;
|
||||
var geps: std.ArrayList(u32) = .empty;
|
||||
var mems: std.ArrayList(u32) = .empty;
|
||||
{
|
||||
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);
|
||||
switch (inst.op) {
|
||||
.alloca => try allocas.append(a, @intCast(i)),
|
||||
.gep => try geps.append(a, @intCast(i)),
|
||||
.load, .store => try mems.append(a, @intCast(i)),
|
||||
else => if (isTerminator(inst)) {
|
||||
b += 1;
|
||||
block_start[b] = @intCast(i + 1);
|
||||
},
|
||||
}
|
||||
}
|
||||
if (b != nb) return;
|
||||
|
|
@ -267,8 +281,9 @@ pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashM
|
|||
@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]) {
|
||||
for (allocas.items) |i| {
|
||||
const x = insts[i].op.alloca;
|
||||
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;
|
||||
|
|
@ -279,9 +294,8 @@ pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashM
|
|||
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);
|
||||
|
|
@ -311,8 +325,9 @@ pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashM
|
|||
};
|
||||
// (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) {
|
||||
for (geps.items) |i| if (rpo_index[block_of[i]] != none) {
|
||||
const g = insts[i].op.gep;
|
||||
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;
|
||||
|
|
@ -322,20 +337,20 @@ pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashM
|
|||
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) {
|
||||
} else if (dyn.contains(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, 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, 0..) |inst, i| {
|
||||
for (mems.items) |i| {
|
||||
if (rpo_index[block_of[i]] == none) continue;
|
||||
const inst = insts[i];
|
||||
const ptr, const ty = switch (inst.op) {
|
||||
.load => |x| .{ x.ptr, inst.ty },
|
||||
.store => |x| .{ x.ptr, typeOf(m, f, x.val) },
|
||||
|
|
@ -348,14 +363,16 @@ pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashM
|
|||
|
||||
// Variables.
|
||||
var nv: u32 = 0;
|
||||
for (insts, 0..) |inst, i| {
|
||||
if (inst.op != .alloca or var_base[i] == none) continue;
|
||||
for (allocas.items) |i| {
|
||||
const inst = insts[i];
|
||||
if (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);
|
||||
}
|
||||
const var_ty = try a.alloc(TypeId, nv);
|
||||
for (insts, 0..) |inst, i| {
|
||||
if (inst.op != .alloca or var_base[i] == none) continue;
|
||||
for (allocas.items) |i| {
|
||||
const inst = insts[i];
|
||||
if (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]);
|
||||
}
|
||||
|
|
@ -365,12 +382,12 @@ pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashM
|
|||
@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;
|
||||
for (geps.items) |i| {
|
||||
if (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 r = dyn.get(i).?;
|
||||
const lo = @min(r[0], len);
|
||||
const hi = @min(r[1], len);
|
||||
@memset(pinned[var_base[al] + lo .. var_base[al] + hi], true);
|
||||
|
|
@ -379,11 +396,11 @@ pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashM
|
|||
// 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) {
|
||||
for (mems.items) |i| {
|
||||
const ptr = switch (insts[i].op) {
|
||||
.load => |x| x.ptr,
|
||||
.store => |x| x.ptr,
|
||||
else => continue,
|
||||
else => unreachable,
|
||||
};
|
||||
if (ptr != .inst) continue;
|
||||
const p = ptr.inst;
|
||||
|
|
@ -400,19 +417,19 @@ pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashM
|
|||
@memset(first_block, none);
|
||||
const global = try a.alloc(bool, nv);
|
||||
@memset(global, false);
|
||||
for (insts, 0..) |inst, i| {
|
||||
for (mems.items) |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;
|
||||
if (insts[i].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| {
|
||||
for (mems.items) |i| {
|
||||
const v = access[i];
|
||||
if (v == none or inst.op != .store or !global[v] or rpo_index[block_of[i]] == none) continue;
|
||||
if (v == none or insts[i].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 {
|
||||
|
|
@ -552,8 +569,8 @@ pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashM
|
|||
filled[j] += 1;
|
||||
}
|
||||
}
|
||||
for (insts, 0..) |inst, i| {
|
||||
if (access[i] != none and inst.op == .load and repl[i] == null)
|
||||
for (mems.items) |i| {
|
||||
if (access[i] != none and insts[i].op == .load and repl[i] == null)
|
||||
repl[i] = try Zero.get(a, m, &zeros, var_ty[access[i]]);
|
||||
}
|
||||
|
||||
|
|
@ -608,17 +625,18 @@ pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashM
|
|||
// 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,
|
||||
};
|
||||
@memset(removed, false);
|
||||
for (allocas.items) |i| removed[i] = var_base[i] != none and !keep[i];
|
||||
for (geps.items) |i| removed[i] = 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]];
|
||||
for (mems.items) |i| removed[i] = access[i] != none;
|
||||
|
||||
// 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);
|
||||
// (What has effects, worked out once for every round.)
|
||||
var effects: std.ArrayList(u32) = .empty;
|
||||
for (insts, 0..) |inst, i| if (!removed[i] and hasEffects(m, inst)) try effects.append(a, @intCast(i));
|
||||
while (true) {
|
||||
@memset(live, false);
|
||||
{
|
||||
|
|
@ -643,9 +661,9 @@ pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashM
|
|||
}
|
||||
};
|
||||
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)) {
|
||||
for (effects.items) |i| if (reach[block_of[i]] or i == block_start[block_of[i] + 1] - 1) {
|
||||
live[i] = true;
|
||||
try work.append(a, @intCast(i));
|
||||
try work.append(a, i);
|
||||
};
|
||||
while (work.pop()) |x| {
|
||||
if (x < n) {
|
||||
|
|
@ -805,15 +823,44 @@ fn foldConstantBranches(a: Allocator, m: *module.Module, insts: []Inst, block_st
|
|||
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);
|
||||
/// Whether each entry of `ins` (from `ins[x].block`) is one of the
|
||||
/// edges to `t` there still are: the k-th entry from a block is,
|
||||
/// if the block has more than k edges to `t`. `seen` and `edges_to`
|
||||
/// are per-block scratch (0 and `none`), left as they were.
|
||||
fn keeps(s: @This(), ins: []const Edge, t: u32, seen: []u32, edges_to: []u32, out: []bool) void {
|
||||
for (ins, out) |in, *o| {
|
||||
if (edges_to[in.block] == none) edges_to[in.block] = s.count(in.block, t);
|
||||
o.* = seen[in.block] < edges_to[in.block];
|
||||
seen[in.block] += 1;
|
||||
}
|
||||
for (ins) |in| {
|
||||
seen[in.block] = 0;
|
||||
edges_to[in.block] = none;
|
||||
}
|
||||
}
|
||||
};
|
||||
const edges: Edges = .{ .insts = insts, .block_start = block_start, .reach = reach };
|
||||
const seen = try a.alloc(u32, nb);
|
||||
@memset(seen, 0);
|
||||
const edges_to = try a.alloc(u32, nb);
|
||||
@memset(edges_to, none);
|
||||
var kept: std.ArrayList(bool) = .empty;
|
||||
// Edges into each block from reachable ones. A phi has an entry per
|
||||
// edge, and folding only takes edges away: one with that many entries
|
||||
// lost none.
|
||||
const into = try a.alloc(u32, nb);
|
||||
@memset(into, 0);
|
||||
for (0..nb) |p| if (reach[p]) switch (insts[block_start[p + 1] - 1].op) {
|
||||
.br => |br| {
|
||||
into[br.then] += 1;
|
||||
if (br.@"else") |e| into[e] += 1;
|
||||
},
|
||||
.@"switch" => |sw| {
|
||||
into[sw.default] += 1;
|
||||
for (sw.cases) |cs| into[cs.block] += 1;
|
||||
},
|
||||
else => {},
|
||||
};
|
||||
for (0..nb) |b| {
|
||||
const t: u32 = @intCast(b);
|
||||
const last = block_start[b + 1] - 1;
|
||||
|
|
@ -824,12 +871,15 @@ fn foldConstantBranches(a: Allocator, m: *module.Module, insts: []Inst, block_st
|
|||
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 (old.len == into[b]) continue;
|
||||
kept.clearRetainingCapacity();
|
||||
try kept.resize(a, old.len);
|
||||
edges.keeps(old, t, seen, edges_to, kept.items);
|
||||
const keep = std.mem.count(bool, kept.items, &.{true});
|
||||
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)) {
|
||||
for (old, kept.items) |in, kp| if (kp) {
|
||||
new[k] = in;
|
||||
k += 1;
|
||||
};
|
||||
|
|
@ -838,9 +888,13 @@ fn foldConstantBranches(a: Allocator, m: *module.Module, insts: []Inst, block_st
|
|||
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]);
|
||||
const ins = incoming[j];
|
||||
if (ins.len == into[b]) continue;
|
||||
kept.clearRetainingCapacity();
|
||||
try kept.resize(a, ins.len);
|
||||
edges.keeps(ins, t, seen, edges_to, kept.items);
|
||||
var k: usize = 0;
|
||||
for (orig, 0..) |in, x| if (edges.keeps(orig, x, t)) {
|
||||
for (ins, kept.items) |in, kp| if (kp) {
|
||||
incoming[j][k] = in;
|
||||
k += 1;
|
||||
};
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@
|
|||
//! ZRFL part holding the rest as JSON.
|
||||
|
||||
const std = @import("std");
|
||||
const BumpArena = @import("../BumpArena.zig");
|
||||
const Allocator = std.mem.Allocator;
|
||||
const container = @import("container.zig");
|
||||
|
||||
|
|
@ -194,7 +195,7 @@ test "encode and decode" {
|
|||
};
|
||||
const blob = try encode(a, r, &.{});
|
||||
defer a.free(blob);
|
||||
var arena: std.heap.ArenaAllocator = .init(a);
|
||||
var arena: BumpArena = .init(a);
|
||||
defer arena.deinit();
|
||||
const view = try container.parse(arena.allocator(), blob);
|
||||
const back = try decode(arena.allocator(), view.find(part) orelse return error.TestUnexpectedResult);
|
||||
|
|
|
|||
|
|
@ -18,6 +18,7 @@
|
|||
//! Self-contained: depends on std only.
|
||||
|
||||
const std = @import("std");
|
||||
const BumpArena = @import("../BumpArena.zig");
|
||||
const Allocator = std.mem.Allocator;
|
||||
|
||||
pub const Version = enum(u32) {
|
||||
|
|
@ -66,7 +67,7 @@ pub fn compile(gpa: Allocator, text: []const u8, version: Version, diag: *Diagno
|
|||
}
|
||||
|
||||
pub fn compileWithOptions(gpa: Allocator, text: []const u8, opts: Options, diag: *Diagnostic) Allocator.Error!?[]u8 {
|
||||
var arena_state = std.heap.ArenaAllocator.init(gpa);
|
||||
var arena_state = BumpArena.init(gpa);
|
||||
defer arena_state.deinit();
|
||||
const arena = arena_state.allocator();
|
||||
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@
|
|||
const std = @import("std");
|
||||
const Allocator = std.mem.Allocator;
|
||||
const module = @import("module.zig");
|
||||
const stats = @import("../stats.zig");
|
||||
const unroll = @import("unroll.zig");
|
||||
|
||||
const Value = module.Value;
|
||||
|
|
@ -101,6 +102,8 @@ fn successors(term: Inst) Succs {
|
|||
|
||||
/// Runs the propagation on `func`; true if it changed anything.
|
||||
pub fn run(a: Allocator, m: *module.Module, func: u32) Allocator.Error!bool {
|
||||
const zone = stats.begin(.sccp);
|
||||
defer zone.end();
|
||||
const f = &m.functions.items[func];
|
||||
const insts = f.insts.items;
|
||||
const n: u32 = @intCast(insts.len);
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@
|
|||
const std = @import("std");
|
||||
const Allocator = std.mem.Allocator;
|
||||
const module = @import("module.zig");
|
||||
const stats = @import("../stats.zig");
|
||||
const promote = @import("promote.zig");
|
||||
|
||||
const Value = module.Value;
|
||||
|
|
@ -33,6 +34,8 @@ 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 {
|
||||
const zone = stats.begin(.unroll);
|
||||
defer zone.end();
|
||||
var budget: usize = max_growth;
|
||||
var tried: std.AutoHashMapUnmanaged(u32, void) = .empty;
|
||||
var any = false;
|
||||
|
|
@ -46,16 +49,77 @@ const Cfg = struct {
|
|||
succs: [][]u32,
|
||||
preds: [][]u32,
|
||||
idom: []u32,
|
||||
/// Each reachable block's interval in a depth-first walk of the
|
||||
/// dominator tree (`none` for unreachable blocks): `d` dominates `b`
|
||||
/// when `b`'s interval is inside `d`'s.
|
||||
dom_pre: []u32,
|
||||
dom_post: []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;
|
||||
if (d == b) return true;
|
||||
if (c.dom_pre[d] == none or c.dom_pre[b] == none) return false;
|
||||
return c.dom_pre[d] <= c.dom_pre[b] and c.dom_post[b] <= c.dom_post[d];
|
||||
}
|
||||
};
|
||||
|
||||
/// Numbers the dominator tree's blocks in and out of a depth-first walk.
|
||||
fn domIntervals(a: Allocator, idom: []const u32) Allocator.Error!struct { []u32, []u32 } {
|
||||
const nb = idom.len;
|
||||
// Children lists, packed: block b's are kids[first[b]..first[b + 1]].
|
||||
const first = try a.alloc(u32, nb + 1);
|
||||
@memset(first, 0);
|
||||
for (idom, 0..) |p, b| if (p != none and p != b) {
|
||||
first[p + 1] += 1;
|
||||
};
|
||||
for (1..nb + 1) |k| first[k] += first[k - 1];
|
||||
const fill = try a.dupe(u32, first[0..nb]);
|
||||
const kids = try a.alloc(u32, first[nb]);
|
||||
for (idom, 0..) |p, b| if (p != none and p != b) {
|
||||
kids[fill[p]] = @intCast(b);
|
||||
fill[p] += 1;
|
||||
};
|
||||
const pre = try a.alloc(u32, nb);
|
||||
const post = try a.alloc(u32, nb);
|
||||
@memset(pre, none);
|
||||
@memset(post, none);
|
||||
if (nb == 0) return .{ pre, post };
|
||||
var clock: u32 = 0;
|
||||
// `next` reuses fill: the next child to visit.
|
||||
@memcpy(fill, first[0..nb]);
|
||||
var stack: std.ArrayList(u32) = .empty;
|
||||
try stack.append(a, 0);
|
||||
pre[0] = clock;
|
||||
clock += 1;
|
||||
while (stack.items.len > 0) {
|
||||
const b = stack.items[stack.items.len - 1];
|
||||
if (fill[b] < first[b + 1]) {
|
||||
const k = kids[fill[b]];
|
||||
fill[b] += 1;
|
||||
pre[k] = clock;
|
||||
clock += 1;
|
||||
try stack.append(a, k);
|
||||
} else {
|
||||
post[b] = clock;
|
||||
clock += 1;
|
||||
_ = stack.pop();
|
||||
}
|
||||
}
|
||||
return .{ pre, post };
|
||||
}
|
||||
|
||||
/// A loop's blocks: a bit per block of the function, and the list in
|
||||
/// block order.
|
||||
const Body = struct {
|
||||
bits: []u64,
|
||||
blocks: []const u32,
|
||||
|
||||
fn has(b: Body, x: u32) bool {
|
||||
return b.bits[x >> 6] >> @intCast(x & 63) & 1 != 0;
|
||||
}
|
||||
|
||||
fn add(b: *Body, x: u32) void {
|
||||
b.bits[x >> 6] |= @as(u64, 1) << @intCast(x & 63);
|
||||
}
|
||||
};
|
||||
|
||||
fn isTerminator(inst: Inst) bool {
|
||||
|
|
@ -79,27 +143,43 @@ fn buildCfg(a: Allocator, f: *const module.Function) Allocator.Error!?Cfg {
|
|||
}
|
||||
}
|
||||
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;
|
||||
// Successors (each once) and predecessors, packed: each block's are a
|
||||
// slice of one array.
|
||||
var succ_flat: std.ArrayList(u32) = .empty;
|
||||
try succ_flat.ensureTotalCapacity(a, 2 * nb);
|
||||
const succ_off = try a.alloc(u32, nb + 1);
|
||||
for (0..nb) |bi| {
|
||||
var s: std.ArrayList(u32) = .empty;
|
||||
const start = succ_flat.items.len;
|
||||
succ_off[bi] = @intCast(start);
|
||||
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);
|
||||
try succ_flat.append(a, br.then);
|
||||
if (br.@"else") |e| if (e != br.then) try succ_flat.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);
|
||||
try succ_flat.append(a, sw.default);
|
||||
for (sw.cases) |c| if (std.mem.indexOfScalar(u32, succ_flat.items[start..], c.block) == null) try succ_flat.append(a, c.block);
|
||||
},
|
||||
else => {},
|
||||
}
|
||||
succs[bi] = s.items;
|
||||
for (s.items) |t| try pred_lists[t].append(a, @intCast(bi));
|
||||
}
|
||||
succ_off[nb] = @intCast(succ_flat.items.len);
|
||||
const succs = try a.alloc([]u32, nb);
|
||||
for (succs, 0..) |*sl, bi| sl.* = succ_flat.items[succ_off[bi]..succ_off[bi + 1]];
|
||||
const pred_off = try a.alloc(u32, nb + 1);
|
||||
@memset(pred_off, 0);
|
||||
for (succ_flat.items) |t| pred_off[t + 1] += 1;
|
||||
for (1..nb + 1) |k| pred_off[k] += pred_off[k - 1];
|
||||
const pred_flat = try a.alloc(u32, succ_flat.items.len);
|
||||
{
|
||||
const fill = try a.dupe(u32, pred_off[0..nb]);
|
||||
for (0..nb) |bi| for (succs[bi]) |t| {
|
||||
pred_flat[fill[t]] = @intCast(bi);
|
||||
fill[t] += 1;
|
||||
};
|
||||
}
|
||||
const preds = try a.alloc([]u32, nb);
|
||||
for (preds, pred_lists) |*p, l| p.* = l.items;
|
||||
for (preds, 0..) |*pl, bi| pl.* = pred_flat[pred_off[bi]..pred_off[bi + 1]];
|
||||
|
||||
// Reverse postorder, then Cooper, Harvey and Kennedy's dominators.
|
||||
const order = try a.alloc(u32, nb);
|
||||
|
|
@ -162,7 +242,8 @@ fn buildCfg(a: Allocator, f: *const module.Function) Allocator.Error!?Cfg {
|
|||
}
|
||||
}
|
||||
}
|
||||
return .{ .nb = nb, .block_start = block_start, .succs = succs, .preds = preds, .idom = idom };
|
||||
const pre, const post = try domIntervals(a, idom);
|
||||
return .{ .nb = nb, .block_start = block_start, .succs = succs, .preds = preds, .idom = idom, .dom_pre = pre, .dom_post = post };
|
||||
}
|
||||
|
||||
fn constInt(m: *const module.Module, v: Value) ?i64 {
|
||||
|
|
@ -282,7 +363,7 @@ fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried:
|
|||
|
||||
// Loops: headers with back edges (from blocks they dominate), and
|
||||
// their blocks.
|
||||
const Loop = struct { h: u32, body: []bool, latches: []u32 };
|
||||
const Loop = struct { h: u32, body: Body, latches: []u32 };
|
||||
var loops: std.ArrayList(Loop) = .empty;
|
||||
for (0..nb) |hb| {
|
||||
const h: u32 = @intCast(hb);
|
||||
|
|
@ -290,16 +371,30 @@ fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried:
|
|||
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;
|
||||
const bits = try a.alloc(u64, (nb + 63) / 64);
|
||||
@memset(bits, 0);
|
||||
var body: Body = .{ .bits = bits, .blocks = &.{} };
|
||||
body.add(h);
|
||||
var count: usize = 1;
|
||||
var stack: std.ArrayList(u32) = .empty;
|
||||
try stack.appendSlice(a, latches.items);
|
||||
while (stack.pop()) |x| {
|
||||
if (body[x]) continue;
|
||||
body[x] = true;
|
||||
if (body.has(x)) continue;
|
||||
body.add(x);
|
||||
count += 1;
|
||||
for (cfg.preds[x]) |p| if (cfg.idom[p] != none) try stack.append(a, p);
|
||||
}
|
||||
// The blocks in order, from the bits.
|
||||
const blocks = try a.alloc(u32, count);
|
||||
var k: usize = 0;
|
||||
for (bits, 0..) |word, wi| {
|
||||
var w = word;
|
||||
while (w != 0) : (w &= w - 1) {
|
||||
blocks[k] = @intCast(wi * 64 + @ctz(w));
|
||||
k += 1;
|
||||
}
|
||||
}
|
||||
body.blocks = blocks;
|
||||
try loops.append(a, .{ .h = h, .body = body, .latches = latches.items });
|
||||
}
|
||||
|
||||
|
|
@ -309,10 +404,14 @@ fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried:
|
|||
// 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);
|
||||
@memset(loop_inst, false);
|
||||
// (The loop whose instructions loop_inst marks, cleared for the next.)
|
||||
var marked: ?Body = null;
|
||||
dead: for (loops.items) |lp| {
|
||||
if (marked) |mk| for (mk.blocks) |bb| @memset(loop_inst[cfg.block_start[bb]..cfg.block_start[bb + 1]], false);
|
||||
marked = null;
|
||||
var exit: u32 = none;
|
||||
for (0..nb) |bb| {
|
||||
if (!lp.body[bb]) continue;
|
||||
for (lp.body.blocks) |bb| {
|
||||
for (cfg.block_start[bb]..cfg.block_start[bb + 1]) |i| switch (insts[i].op) {
|
||||
.br, .@"switch" => {},
|
||||
.ret, .@"unreachable", .store, .atomicrmw, .cmpxchg => continue :dead,
|
||||
|
|
@ -322,14 +421,14 @@ fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried:
|
|||
},
|
||||
else => {},
|
||||
};
|
||||
for (cfg.succs[bb]) |s| if (!lp.body[s]) {
|
||||
for (cfg.succs[bb]) |s| if (!lp.body.has(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]) {
|
||||
for (cfg.preds[lp.h]) |p| if (!lp.body.has(p)) {
|
||||
if (pre != none) continue :dead;
|
||||
pre = p;
|
||||
};
|
||||
|
|
@ -338,9 +437,8 @@ fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried:
|
|||
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];
|
||||
};
|
||||
for (lp.body.blocks) |bb| @memset(loop_inst[cfg.block_start[bb]..cfg.block_start[bb + 1]], true);
|
||||
marked = lp.body;
|
||||
// The exit's phis: one value from the loop, from before it.
|
||||
const phi_end = blk: {
|
||||
var i = cfg.block_start[exit];
|
||||
|
|
@ -350,7 +448,7 @@ fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried:
|
|||
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]) {
|
||||
for (insts[i].op.phi.incoming) |in| if (lp.body.has(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;
|
||||
|
|
@ -367,7 +465,7 @@ fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried:
|
|||
};
|
||||
var check: Check = .{ .loop_inst = loop_inst };
|
||||
for (0..nb) |bb| {
|
||||
if (lp.body[bb]) continue;
|
||||
if (lp.body.has(@intCast(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];
|
||||
|
|
@ -379,7 +477,7 @@ fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried:
|
|||
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);
|
||||
for (insts[i].op.phi.incoming) |in| if (!lp.body.has(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;
|
||||
}
|
||||
|
|
@ -387,9 +485,7 @@ fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried:
|
|||
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";
|
||||
};
|
||||
for (lp.body.blocks) |bb| insts[cfg.block_start[bb + 1] - 1].op = .@"unreachable";
|
||||
return true;
|
||||
}
|
||||
|
||||
|
|
@ -397,7 +493,7 @@ fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried:
|
|||
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;
|
||||
for (loops.items) |other| if (other.h != h and lp.body.has(other.h)) continue :candidates;
|
||||
try tried.put(a, h, {});
|
||||
|
||||
// One way out: a conditional branch from one block, to one block.
|
||||
|
|
@ -405,17 +501,16 @@ fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried:
|
|||
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));
|
||||
for (lp.body.blocks) |bb| {
|
||||
try body_blocks.append(a, 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.has(s)) continue :candidates;
|
||||
}
|
||||
for (cfg.succs[bb]) |s| if (!lp.body[s]) {
|
||||
for (cfg.succs[bb]) |s| if (!lp.body.has(s)) {
|
||||
if (exiting != none) continue :candidates;
|
||||
exiting = @intCast(bb);
|
||||
exiting = bb;
|
||||
exit = s;
|
||||
};
|
||||
}
|
||||
|
|
@ -423,11 +518,11 @@ fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried:
|
|||
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;
|
||||
if (!lp.body.has(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]) {
|
||||
for (cfg.preds[h]) |p| if (!lp.body.has(p)) {
|
||||
if (pre != none) continue :candidates;
|
||||
pre = p;
|
||||
};
|
||||
|
|
@ -620,7 +715,7 @@ fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried:
|
|||
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];
|
||||
in_body[i] = lp.body.has(@intCast(bb));
|
||||
};
|
||||
const Outside = struct {
|
||||
last: Mapper,
|
||||
|
|
@ -632,7 +727,7 @@ fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried:
|
|||
};
|
||||
var outside: Outside = .{ .last = last, .in_body = in_body };
|
||||
for (0..nb) |bb| {
|
||||
if (lp.body[bb]) {
|
||||
if (lp.body.has(@intCast(bb))) {
|
||||
// The originals: unreachable now.
|
||||
insts[cfg.block_start[bb + 1] - 1].op = .@"unreachable";
|
||||
continue;
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@
|
|||
//! builtin types are recognized by name.
|
||||
|
||||
const std = @import("std");
|
||||
const BumpArena = @import("../BumpArena.zig");
|
||||
const Allocator = std.mem.Allocator;
|
||||
const ast = @import("ast.zig");
|
||||
const lexer = @import("lexer.zig");
|
||||
|
|
@ -523,7 +524,7 @@ pub const Parser = struct {
|
|||
defer p.last_quals = words.items;
|
||||
while (p.at(.identifier)) {
|
||||
const word = p.tok().text;
|
||||
if (inList(&reserved_declspecs, word)) {
|
||||
if (isReservedDeclspec(word)) {
|
||||
// dxc reports these and parses on as if they were absent.
|
||||
_ = p.reportAt(p.pos, .@"error", "'{s}' is a reserved keyword in HLSL", .{word});
|
||||
_ = p.advance();
|
||||
|
|
@ -1565,7 +1566,7 @@ pub const Parser = struct {
|
|||
if (std.mem.eql(u8, w, "struct") or std.mem.eql(u8, w, "class") or std.mem.eql(u8, w, "typedef") or
|
||||
std.mem.eql(u8, w, "using") or std.mem.eql(u8, w, "enum") or std.mem.eql(u8, w, "_Static_assert"))
|
||||
return true;
|
||||
if (inList(&reserved_declspecs, w)) return true;
|
||||
if (isReservedDeclspec(w)) return true;
|
||||
if (isEffectObjectWord(t) and p.peek(1).kind == .identifier) return true;
|
||||
if (qualifierField(w) != null) {
|
||||
if (!isContextualQualifier(w)) return true;
|
||||
|
|
@ -1939,14 +1940,22 @@ fn isTechniqueWord(t: Token) bool {
|
|||
}
|
||||
|
||||
/// dxc's g_DeprecatedEffectObjectNames.
|
||||
const effect_object_words = [_][]const u8{
|
||||
"texture", "Texture", "pixelshader", "PixelShader", "vertexshader",
|
||||
"VertexShader", "pixelfragment", "vertexfragment", "ComputeShader", "DomainShader",
|
||||
"GeometryShader", "HullShader", "BlendState", "DepthStencilState", "DepthStencilView",
|
||||
"RasterizerState", "RenderTargetView",
|
||||
};
|
||||
|
||||
fn isEffectObjectWord(t: Token) bool {
|
||||
const names = [_][]const u8{
|
||||
"texture", "Texture", "pixelshader", "PixelShader", "vertexshader",
|
||||
"VertexShader", "pixelfragment", "vertexfragment", "ComputeShader", "DomainShader",
|
||||
"GeometryShader", "HullShader", "BlendState", "DepthStencilState", "DepthStencilView",
|
||||
"RasterizerState", "RenderTargetView",
|
||||
};
|
||||
return t.kind == .identifier and inList(&names, t.text);
|
||||
if (t.kind != .identifier) return false;
|
||||
const info = word_map.get(t.text) orelse return false;
|
||||
return info.effect_object;
|
||||
}
|
||||
|
||||
fn isReservedDeclspec(w: []const u8) bool {
|
||||
const info = word_map.get(w) orelse return false;
|
||||
return info.declspec;
|
||||
}
|
||||
|
||||
/// Type attributes that may precede a type: `unorm float`,
|
||||
|
|
@ -2077,6 +2086,8 @@ const WordInfo = struct {
|
|||
numeric_scalar: bool = false,
|
||||
object: bool = false,
|
||||
template: bool = false,
|
||||
declspec: bool = false,
|
||||
effect_object: bool = false,
|
||||
};
|
||||
|
||||
fn inList(list: []const []const u8, w: []const u8) bool {
|
||||
|
|
@ -2088,7 +2099,7 @@ fn inList(list: []const []const u8, w: []const u8) bool {
|
|||
/// replaces linear scans of the lists above (a third of parse time).
|
||||
const word_map = blk: {
|
||||
@setEvalBranchQuota(1_000_000);
|
||||
var words: []const []const u8 = &(reserved_words ++ contextual_words ++ scalar_types ++ object_types ++ enum_typedefs ++ template_types ++ template_funcs);
|
||||
var words: []const []const u8 = &(reserved_words ++ contextual_words ++ scalar_types ++ object_types ++ enum_typedefs ++ template_types ++ template_funcs ++ reserved_declspecs ++ effect_object_words);
|
||||
for (qualifier_words) |q| words = words ++ &[_][]const u8{q[0]};
|
||||
var kvs: [words.len]struct { []const u8, WordInfo } = undefined;
|
||||
var n: usize = 0;
|
||||
|
|
@ -2101,6 +2112,8 @@ const word_map = blk: {
|
|||
.numeric_scalar = inList(&scalar_types, w) and !std.mem.endsWith(u8, w, "_packed"),
|
||||
.object = inList(&object_types, w) or inList(&enum_typedefs, w),
|
||||
.template = inList(&template_types, w) or inList(&template_funcs, w),
|
||||
.declspec = inList(&reserved_declspecs, w),
|
||||
.effect_object = inList(&effect_object_words, w),
|
||||
};
|
||||
for (qualifier_words) |q| {
|
||||
if (std.mem.eql(u8, q[0], w)) info.qualifier = q[1];
|
||||
|
|
@ -2109,9 +2122,66 @@ const word_map = blk: {
|
|||
n += 1;
|
||||
}
|
||||
const final = kvs[0..n].*;
|
||||
break :blk std.StaticStringMap(WordInfo).initComptime(final);
|
||||
break :blk WordMap(WordInfo, final.len).init(final);
|
||||
};
|
||||
|
||||
/// A string map built at compile time: an open-addressing table on a cheap
|
||||
/// hash, comparing a stored hash before any bytes. Most identifiers a
|
||||
/// lookup sees are not in it, and miss after a probe or two (what
|
||||
/// std.StaticStringMap does is compare every key of the same length).
|
||||
fn WordMap(comptime V: type, comptime n: usize) type {
|
||||
return struct {
|
||||
const Self = @This();
|
||||
/// Twice the keys or more, a power of two.
|
||||
const size = std.math.ceilPowerOfTwoAssert(usize, n * 4);
|
||||
const empty = std.math.maxInt(u16);
|
||||
|
||||
keys: [n][]const u8,
|
||||
values: [n]V,
|
||||
hashes: [n]u32,
|
||||
slots: [size]u16,
|
||||
|
||||
fn hash(w: []const u8) u32 {
|
||||
var h: u32 = 2166136261;
|
||||
for (w) |c| h = (h ^ c) *% 16777619;
|
||||
return h;
|
||||
}
|
||||
|
||||
fn init(comptime kvs: anytype) Self {
|
||||
var m: Self = undefined;
|
||||
m.slots = @splat(empty);
|
||||
for (kvs, 0..) |kv, k| {
|
||||
m.keys[k] = kv[0];
|
||||
m.values[k] = kv[1];
|
||||
m.hashes[k] = hash(kv[0]);
|
||||
var i = m.hashes[k] & (size - 1);
|
||||
while (m.slots[i] != empty) i = (i + 1) & (size - 1);
|
||||
m.slots[i] = k;
|
||||
}
|
||||
return m;
|
||||
}
|
||||
|
||||
fn get(m: *const Self, w: []const u8) ?V {
|
||||
const h = hash(w);
|
||||
var i = h & (size - 1);
|
||||
while (true) : (i = (i + 1) & (size - 1)) {
|
||||
const k = m.slots[i];
|
||||
if (k == empty) return null;
|
||||
if (m.hashes[k] == h and std.mem.eql(u8, m.keys[k], w)) return m.values[k];
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
test WordMap {
|
||||
const M = WordMap(u8, 3);
|
||||
const m = comptime M.init(.{ .{ "float", 1 }, .{ "in", 2 }, .{ "inout", 3 } });
|
||||
try std.testing.expectEqual(1, m.get("float").?);
|
||||
try std.testing.expectEqual(3, m.get("inout").?);
|
||||
try std.testing.expectEqual(null, m.get("floa"));
|
||||
try std.testing.expectEqual(null, m.get(""));
|
||||
}
|
||||
|
||||
fn isNumericScalar(w: []const u8) bool {
|
||||
const info = word_map.get(w) orelse return false;
|
||||
return info.numeric_scalar;
|
||||
|
|
@ -2154,7 +2224,7 @@ const TestParse = struct {
|
|||
mfs: source.MemoryFs = .{},
|
||||
sm: source.SourceManager = undefined,
|
||||
diags: Diagnostics = undefined,
|
||||
arena: std.heap.ArenaAllocator = undefined,
|
||||
arena: BumpArena = undefined,
|
||||
out: std.Io.Writer.Allocating = undefined,
|
||||
|
||||
fn run(t: *TestParse, text: []const u8) ![]const u8 {
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@
|
|||
//! disabled macro.
|
||||
|
||||
const std = @import("std");
|
||||
const BumpArena = @import("../BumpArena.zig");
|
||||
const Allocator = std.mem.Allocator;
|
||||
const source = @import("source.zig");
|
||||
const lexer = @import("lexer.zig");
|
||||
|
|
@ -1446,7 +1447,7 @@ const TestPP = struct {
|
|||
mfs: source.MemoryFs = .{},
|
||||
sm: source.SourceManager = undefined,
|
||||
diags: Diagnostics = undefined,
|
||||
arena: std.heap.ArenaAllocator = undefined,
|
||||
arena: BumpArena = undefined,
|
||||
pp: Preprocessor = undefined,
|
||||
|
||||
fn init(t: *TestPP, files: []const [2][]const u8, main: []const u8, opts: Options) !void {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
//! Source files and locations.
|
||||
|
||||
const std = @import("std");
|
||||
const BumpArena = @import("../BumpArena.zig");
|
||||
const Allocator = std.mem.Allocator;
|
||||
const scan = @import("scan.zig");
|
||||
|
||||
|
|
@ -134,7 +135,7 @@ pub const LineOverride = struct {
|
|||
pub const PresumedLoc = struct { file: []const u8, line: u32 };
|
||||
|
||||
pub const SourceManager = struct {
|
||||
arena: std.heap.ArenaAllocator,
|
||||
arena: BumpArena,
|
||||
files: std.ArrayList(File) = .empty,
|
||||
fs: FileSystem,
|
||||
/// path -> contents, or null if the path could not be read.
|
||||
|
|
@ -317,30 +318,46 @@ fn decodeUtf16(a: Allocator, raw: []const u8) !?[]const u8 {
|
|||
}
|
||||
|
||||
fn spliceLines(a: Allocator, raw: []const u8) ![]const u8 {
|
||||
if (std.mem.indexOfScalar(u8, raw, '\\') == null) return raw;
|
||||
var i = std.mem.indexOfScalar(u8, raw, '\\') orelse return raw;
|
||||
var out: std.ArrayList(u8) = .empty;
|
||||
try out.ensureTotalCapacity(a, raw.len);
|
||||
var i: usize = 0;
|
||||
out.appendSliceAssumeCapacity(raw[0..i]);
|
||||
// At a backslash: a splice, or the backslash kept; then the run to the
|
||||
// next backslash, copied whole.
|
||||
while (i < raw.len) {
|
||||
if (raw[i] == '\\') {
|
||||
var j = i + 1;
|
||||
// Clang tolerates whitespace between the backslash and newline.
|
||||
while (j < raw.len and (raw[j] == ' ' or raw[j] == '\t')) j += 1;
|
||||
if (j < raw.len and raw[j] == '\n') {
|
||||
i = j + 1;
|
||||
continue;
|
||||
}
|
||||
if (j + 1 < raw.len and raw[j] == '\r' and raw[j + 1] == '\n') {
|
||||
i = j + 2;
|
||||
continue;
|
||||
}
|
||||
var j = i + 1;
|
||||
// Clang tolerates whitespace between the backslash and newline.
|
||||
while (j < raw.len and (raw[j] == ' ' or raw[j] == '\t')) j += 1;
|
||||
if (j < raw.len and raw[j] == '\n') {
|
||||
i = j + 1;
|
||||
} else if (j + 1 < raw.len and raw[j] == '\r' and raw[j + 1] == '\n') {
|
||||
i = j + 2;
|
||||
} else {
|
||||
out.appendAssumeCapacity('\\');
|
||||
i += 1;
|
||||
}
|
||||
out.appendAssumeCapacity(raw[i]);
|
||||
i += 1;
|
||||
const next = std.mem.indexOfScalarPos(u8, raw, i, '\\') orelse raw.len;
|
||||
out.appendSliceAssumeCapacity(raw[i..next]);
|
||||
i = next;
|
||||
}
|
||||
return out.items;
|
||||
}
|
||||
|
||||
test spliceLines {
|
||||
const cases = [_][2][]const u8{
|
||||
.{ "a\\\nb", "ab" },
|
||||
.{ "a\\ \t\r\nb\\", "ab\\" },
|
||||
.{ "\\x\\\\\ny", "\\x\\y" },
|
||||
.{ "no splice", "no splice" },
|
||||
.{ "#define A 1 \\\n + 2\n", "#define A 1 + 2\n" },
|
||||
};
|
||||
for (cases) |c| {
|
||||
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer arena.deinit();
|
||||
try std.testing.expectEqualStrings(c[1], try spliceLines(arena.allocator(), c[0]));
|
||||
}
|
||||
}
|
||||
|
||||
test "line and column lookup" {
|
||||
var mfs: MemoryFs = .{};
|
||||
var sm = SourceManager.init(std.testing.allocator, mfs.fileSystem());
|
||||
|
|
|
|||
|
|
@ -28,6 +28,7 @@
|
|||
//! and fails its job.
|
||||
|
||||
const std = @import("std");
|
||||
const BumpArena = @import("zdxc").BumpArena;
|
||||
const Io = std.Io;
|
||||
const Allocator = std.mem.Allocator;
|
||||
const FileSystem = @import("zdxc").front.source.FileSystem;
|
||||
|
|
@ -238,7 +239,7 @@ const Batch = struct {
|
|||
/// jobs ahead of the compiles.
|
||||
fn read(b: *Batch) void {
|
||||
const gpa = std.heap.smp_allocator;
|
||||
var arena: std.heap.ArenaAllocator = .init(gpa);
|
||||
var arena: BumpArena = .init(gpa);
|
||||
defer arena.deinit();
|
||||
for (b.jobs, b.sources, 0..) |args, *s, i| {
|
||||
while (true) {
|
||||
|
|
@ -303,7 +304,7 @@ const Batch = struct {
|
|||
|
||||
fn work(b: *Batch) void {
|
||||
const gpa = std.heap.smp_allocator;
|
||||
var arena: std.heap.ArenaAllocator = .init(gpa);
|
||||
var arena: BumpArena = .init(gpa);
|
||||
defer arena.deinit();
|
||||
while (true) {
|
||||
const i = b.next.fetchAdd(1, .monotonic);
|
||||
|
|
|
|||
|
|
@ -3,6 +3,8 @@
|
|||
pub const diag = @import("diag.zig");
|
||||
pub const options = @import("options.zig");
|
||||
pub const compile = @import("compile.zig");
|
||||
pub const stats = @import("stats.zig");
|
||||
pub const BumpArena = @import("BumpArena.zig");
|
||||
pub const Diagnostics = diag.Diagnostics;
|
||||
|
||||
pub const front = struct {
|
||||
|
|
|
|||
|
|
@ -112,6 +112,37 @@ pub const Db = struct {
|
|||
pub const Resolved = struct { ret: TypeId, index: u16 = 0, params: []const TypeId = &.{}, ok: bool = false };
|
||||
|
||||
pub fn resolve(db: *const Db, sema: anytype, loc: source.Loc, ns: []const u8, name: []const u8, object: ?TypeId, args: []const ArgInfo, explicit: ?TypeId) !Resolved {
|
||||
// The same call (name, object, explicit type, argument types and
|
||||
// lvalues) resolves the same way: matched once per compile.
|
||||
var key_buf: [256]u8 = undefined;
|
||||
var key: std.ArrayList(u8) = .initBuffer(&key_buf);
|
||||
const keyed = memoKey(&key, ns, name, object, args, explicit);
|
||||
if (keyed) if (sema.intrinsic_memo.get(key.items)) |r| return r;
|
||||
const reported = sema.diags.list.items.len;
|
||||
const r = try db.resolveUncached(sema, loc, ns, name, object, args, explicit);
|
||||
// (Not one that reported something: a repeat reports it again.)
|
||||
if (keyed and r.ok and sema.diags.list.items.len == reported) try sema.intrinsic_memo.put(sema.arena, try sema.arena.dupe(u8, key.items), r);
|
||||
return r;
|
||||
}
|
||||
|
||||
/// The memo key of a call; false if it does not fit.
|
||||
fn memoKey(key: *std.ArrayList(u8), ns: []const u8, name: []const u8, object: ?TypeId, args: []const ArgInfo, explicit: ?TypeId) bool {
|
||||
const fixed = ns.len + name.len + 2 + 2 * @sizeOf(TypeId) + args.len * (@sizeOf(TypeId) + 1);
|
||||
if (fixed > key.capacity) return false;
|
||||
key.appendSliceAssumeCapacity(ns);
|
||||
key.appendAssumeCapacity(0);
|
||||
key.appendSliceAssumeCapacity(name);
|
||||
key.appendAssumeCapacity(0);
|
||||
key.appendSliceAssumeCapacity(std.mem.asBytes(&@as(TypeId, object orelse std.math.maxInt(TypeId))));
|
||||
key.appendSliceAssumeCapacity(std.mem.asBytes(&@as(TypeId, explicit orelse std.math.maxInt(TypeId))));
|
||||
for (args) |a| {
|
||||
key.appendSliceAssumeCapacity(std.mem.asBytes(&a.ty));
|
||||
key.appendAssumeCapacity(@intFromBool(a.lvalue));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
fn resolveUncached(db: *const Db, sema: anytype, loc: source.Loc, ns: []const u8, name: []const u8, object: ?TypeId, args: []const ArgInfo, explicit: ?TypeId) !Resolved {
|
||||
const cands = try db.candidates(sema.arena, ns, name);
|
||||
if (cands.len == 0) {
|
||||
if (object) |o| {
|
||||
|
|
|
|||
|
|
@ -219,6 +219,8 @@ pub const Sema = struct {
|
|||
loop_depth: u32 = 0,
|
||||
switch_depth: u32 = 0,
|
||||
intrinsic_db: *const intrinsics.Db,
|
||||
/// Intrinsic calls resolved so far (see Db.resolve).
|
||||
intrinsic_memo: std.StringHashMapUnmanaged(intrinsics.Db.Resolved) = .empty,
|
||||
enum_scopes: std.AutoHashMapUnmanaged(*types.EnumInfo, *Scope) = .empty,
|
||||
/// Where each template was declared (its names resolve from there).
|
||||
template_scopes: std.AutoHashMapUnmanaged(*const ast.Decl, *Scope) = .empty,
|
||||
|
|
@ -938,13 +940,26 @@ pub const Sema = struct {
|
|||
}
|
||||
|
||||
fn lookup(s: *Sema, name: []const u8) ?Symbol {
|
||||
// (The name hashed once, for every scope out to the global one.)
|
||||
const key: Prehashed = .{ .h = std.hash_map.hashString(name) };
|
||||
var sc: ?*Scope = s.scope;
|
||||
while (sc) |c| : (sc = c.parent) {
|
||||
if (c.syms.get(name)) |sym| return sym;
|
||||
if (c.syms.getAdapted(name, key)) |sym| return sym;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// A string hash map key context with the hash already worked out.
|
||||
const Prehashed = struct {
|
||||
h: u64,
|
||||
pub fn hash(k: Prehashed, _: []const u8) u64 {
|
||||
return k.h;
|
||||
}
|
||||
pub fn eql(_: Prehashed, a: []const u8, b: []const u8) bool {
|
||||
return std.mem.eql(u8, a, b);
|
||||
}
|
||||
};
|
||||
|
||||
/// Resolve a possibly qualified name.
|
||||
fn lookupName(s: *Sema, n: ast.Name) ?Symbol {
|
||||
return s.lookupNameInst(n) catch null;
|
||||
|
|
|
|||
|
|
@ -357,10 +357,10 @@ pub const ResourceKind = enum(u8) {
|
|||
|
||||
/// vk::SampledTexture* by name.
|
||||
pub const vk_names = [_]struct { []const u8, ResourceKind }{
|
||||
.{ "SampledTexture1D", .sampled_texture1d }, .{ "SampledTexture1DArray", .sampled_texture1d_array },
|
||||
.{ "SampledTexture2D", .sampled_texture2d }, .{ "SampledTexture2DArray", .sampled_texture2d_array },
|
||||
.{ "SampledTexture2DMS", .sampled_texture2dms }, .{ "SampledTexture2DMSArray", .sampled_texture2dms_array },
|
||||
.{ "SampledTexture3D", .sampled_texture3d }, .{ "SampledTextureCUBE", .sampled_texture_cube },
|
||||
.{ "SampledTexture1D", .sampled_texture1d }, .{ "SampledTexture1DArray", .sampled_texture1d_array },
|
||||
.{ "SampledTexture2D", .sampled_texture2d }, .{ "SampledTexture2DArray", .sampled_texture2d_array },
|
||||
.{ "SampledTexture2DMS", .sampled_texture2dms }, .{ "SampledTexture2DMSArray", .sampled_texture2dms_array },
|
||||
.{ "SampledTexture3D", .sampled_texture3d }, .{ "SampledTextureCUBE", .sampled_texture_cube },
|
||||
.{ "SampledTextureCUBEArray", .sampled_texture_cube_array },
|
||||
};
|
||||
|
||||
|
|
@ -535,7 +535,9 @@ pub const LinAlgMatrix = struct { comp: u32, m: u32, n: u32, use: u32, scope: u3
|
|||
pub const TypeTable = struct {
|
||||
gpa: Allocator,
|
||||
types: std.ArrayList(Type) = .empty,
|
||||
map: std.AutoHashMapUnmanaged(Key, TypeId) = .empty,
|
||||
map: std.HashMapUnmanaged(Key, TypeId, KeyContext, std.hash_map.default_max_load_percentage) = .empty,
|
||||
/// scalar's results.
|
||||
scalars: [@typeInfo(Scalar).@"enum".field_names.len]TypeId = @splat(std.math.maxInt(TypeId)),
|
||||
|
||||
pub const error_type: TypeId = 0;
|
||||
pub const void_type: TypeId = 1;
|
||||
|
|
@ -543,6 +545,23 @@ pub const TypeTable = struct {
|
|||
/// Hashable identity of structural types.
|
||||
const Key = struct { tag: u8, a: u64, b: u64 };
|
||||
|
||||
/// Hashes a Key's words (it has padding, which the automatic context
|
||||
/// hashes around field by field).
|
||||
const KeyContext = struct {
|
||||
fn mix(x: u64) u64 {
|
||||
var z = x;
|
||||
z = (z ^ (z >> 30)) *% 0xbf58476d1ce4e5b9;
|
||||
z = (z ^ (z >> 27)) *% 0x94d049bb133111eb;
|
||||
return z ^ (z >> 31);
|
||||
}
|
||||
pub fn hash(_: KeyContext, k: Key) u64 {
|
||||
return mix(k.a ^ mix(k.b ^ @as(u64, k.tag) << 56));
|
||||
}
|
||||
pub fn eql(_: KeyContext, x: Key, y: Key) bool {
|
||||
return x.tag == y.tag and x.a == y.a and x.b == y.b;
|
||||
}
|
||||
};
|
||||
|
||||
pub fn init(gpa: Allocator) !TypeTable {
|
||||
var t: TypeTable = .{ .gpa = gpa };
|
||||
try t.types.append(gpa, .@"error");
|
||||
|
|
@ -591,7 +610,9 @@ pub const TypeTable = struct {
|
|||
}
|
||||
|
||||
pub fn scalar(t: *TypeTable, s: Scalar) !TypeId {
|
||||
return t.intern(.{ .scalar = s });
|
||||
const k = @backingInt(s);
|
||||
if (t.scalars[k] == std.math.maxInt(TypeId)) t.scalars[k] = try t.intern(.{ .scalar = s });
|
||||
return t.scalars[k];
|
||||
}
|
||||
|
||||
/// `len == 1` vectors are kept distinct from scalars (float1 != float).
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@
|
|||
//! (binding = register number, descriptor set = register space).
|
||||
|
||||
const std = @import("std");
|
||||
const BumpArena = @import("../BumpArena.zig");
|
||||
const Allocator = std.mem.Allocator;
|
||||
const ir = @import("../ir/ir.zig");
|
||||
const types = @import("../sema/types.zig");
|
||||
|
|
@ -142,7 +143,7 @@ pub const TargetEnv = struct {
|
|||
};
|
||||
|
||||
pub fn emit(gpa: Allocator, m: *const ir.Module, diags: *diag.Diagnostics, env: TargetEnv) Error![]u8 {
|
||||
var arena_state = std.heap.ArenaAllocator.init(gpa);
|
||||
var arena_state = BumpArena.init(gpa);
|
||||
defer arena_state.deinit();
|
||||
var e: Emitter = .{ .arena = arena_state.allocator(), .b = .init(gpa), .m = m, .t = m.types, .diags = diags, .spv_minor = env.minor, .universal = env.universal, .vk = m.vk };
|
||||
defer e.b.deinit();
|
||||
|
|
|
|||
|
|
@ -0,0 +1,99 @@
|
|||
//! Time and allocations per compilation stage, for benchmarks. A caller
|
||||
//! that wants them points `current` at a `Stats` for the thread's
|
||||
//! compilation; zones anywhere in the compiler then add to it. With no
|
||||
//! `Stats` (the default) a zone costs one thread-local load.
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
pub const Stage = enum {
|
||||
/// Command-line options and setup.
|
||||
args,
|
||||
/// Preprocessing and lexing, up to a token array.
|
||||
preprocess,
|
||||
parse,
|
||||
sema,
|
||||
lower,
|
||||
ir_opt,
|
||||
/// DXIL emission, in all (the zones below are inside it).
|
||||
dxil,
|
||||
/// Lowering the entry's IR to DXIL instructions (inlining every call).
|
||||
dxil_lower,
|
||||
/// Renumbering a function's instructions into its body.
|
||||
dxil_finish,
|
||||
promote,
|
||||
sccp,
|
||||
unroll,
|
||||
bitcode,
|
||||
container,
|
||||
spirv,
|
||||
/// Diagnostics rendering and the rest of `compile`.
|
||||
other,
|
||||
};
|
||||
|
||||
pub const count = @typeInfo(Stage).@"enum".field_names.len;
|
||||
|
||||
/// Sizes of the work, to explain the times.
|
||||
pub const Counter = enum {
|
||||
/// DXIL instructions lowering produced (before any optimization).
|
||||
dxil_lowered,
|
||||
/// DXIL instructions left in the emitted functions.
|
||||
dxil_final,
|
||||
/// Times promotion ran.
|
||||
promote_runs,
|
||||
};
|
||||
|
||||
pub const counter_count = @typeInfo(Counter).@"enum".field_names.len;
|
||||
|
||||
/// What the caller's allocator counters read at a point (the caller's
|
||||
/// `sample` fills it in).
|
||||
pub const Sample = struct { calls: u64 = 0, bytes: u64 = 0 };
|
||||
|
||||
pub const Stats = struct {
|
||||
io: std.Io,
|
||||
ns: [count]u64 = @splat(0),
|
||||
/// Allocation calls and bytes requested in each stage.
|
||||
calls: [count]u64 = @splat(0),
|
||||
bytes: [count]u64 = @splat(0),
|
||||
/// Times each zone was entered.
|
||||
entries: [count]u32 = @splat(0),
|
||||
counters: [counter_count]u64 = @splat(0),
|
||||
sample: ?*const fn (ctx: ?*anyopaque) Sample = null,
|
||||
sample_ctx: ?*anyopaque = null,
|
||||
|
||||
fn read(s: *const Stats) Sample {
|
||||
return if (s.sample) |f| f(s.sample_ctx) else .{};
|
||||
}
|
||||
};
|
||||
|
||||
pub threadlocal var current: ?*Stats = null;
|
||||
|
||||
pub const Zone = struct {
|
||||
stage: Stage,
|
||||
t0: i96 = 0,
|
||||
s0: Sample = .{},
|
||||
on: bool = false,
|
||||
|
||||
/// Ends the zone, adding its time and allocations to its stage
|
||||
/// (inclusive of zones nested in it).
|
||||
pub fn end(z: Zone) void {
|
||||
if (!z.on) return;
|
||||
const s = current orelse return;
|
||||
const t1 = std.Io.Clock.awake.now(s.io).toNanoseconds();
|
||||
const s1 = s.read();
|
||||
const k = @backingInt(z.stage);
|
||||
s.ns[k] += @intCast(t1 - z.t0);
|
||||
s.calls[k] += s1.calls - z.s0.calls;
|
||||
s.bytes[k] += s1.bytes - z.s0.bytes;
|
||||
s.entries[k] += 1;
|
||||
}
|
||||
};
|
||||
|
||||
/// Adds `n` to a counter.
|
||||
pub fn add(c: Counter, n: u64) void {
|
||||
if (current) |s| s.counters[@backingInt(c)] += n;
|
||||
}
|
||||
|
||||
pub fn begin(stage: Stage) Zone {
|
||||
const s = current orelse return .{ .stage = stage };
|
||||
return .{ .stage = stage, .t0 = std.Io.Clock.awake.now(s.io).toNanoseconds(), .s0 = s.read(), .on = true };
|
||||
}
|
||||
Loading…
Reference in New Issue