Compare commits

..

No commits in common. "01a66d456a2b33431a1ea408a923ca9976f4b7ff" and "badcdd85933b3b4d4c89cc76f205eca9925cfc29" have entirely different histories.

14 changed files with 528 additions and 2416 deletions

View File

@ -43,10 +43,8 @@ pub fn build(b: *std.Build) void {
mod.addAnonymousImport("options_table", .{ .root_source_file = options_table }); mod.addAnonymousImport("options_table", .{ .root_source_file = options_table });
mod.addAnonymousImport("intrinsics_table", .{ .root_source_file = intrinsics_table }); mod.addAnonymousImport("intrinsics_table", .{ .root_source_file = intrinsics_table });
// The command line. Its step is "zdxc-cli" so that a dependent's
// artifact("zdxc") names the library; it still installs as bin/zdxc.
const exe = b.addExecutable(.{ const exe = b.addExecutable(.{
.name = "zdxc-cli", .name = "zdxc",
.root_module = b.createModule(.{ .root_module = b.createModule(.{
.root_source_file = b.path("src/main.zig"), .root_source_file = b.path("src/main.zig"),
.target = target, .target = target,
@ -54,50 +52,7 @@ pub fn build(b: *std.Build) void {
.imports = &.{.{ .name = "zdxc", .module = mod }}, .imports = &.{.{ .name = "zdxc", .module = mod }},
}), }),
}); });
const exe_name = if (target.result.os.tag == .windows) "zdxc.exe" else "zdxc"; b.installArtifact(exe);
b.getInstallStep().dependOn(&b.addInstallArtifact(exe, .{ .dest_sub_path = exe_name }).step);
// libzdxc: the C API (include/zdxc.h), static by default.
const linkage = b.option(std.builtin.LinkMode, "linkage", "libzdxc: static (default) or dynamic") orelse .static;
const lib = b.addLibrary(.{
.name = "zdxc",
.linkage = linkage,
.root_module = b.createModule(.{
.root_source_file = b.path("src/capi.zig"),
.target = target,
.optimize = optimize,
.imports = &.{.{ .name = "zdxc", .module = mod }},
}),
});
// A static library carries its own compiler runtime, so C callers
// need nothing else.
lib.bundle_compiler_rt = true;
lib.installHeader(b.path("include/zdxc.h"), "zdxc.h");
b.installArtifact(lib);
// The DXC drop-in: a `dxc` command line and a dxcompiler library with
// DXC's COM entry points (src/dxcapi.zig), for programs that load
// libdxcompiler / dxcompiler.dll themselves.
const dropin_step = b.step("dropin", "Build the DXC drop-in: bin/dxc and the dxcompiler library");
const dxc_name = if (target.result.os.tag == .windows) "dxc.exe" else "dxc";
dropin_step.dependOn(&b.addInstallArtifact(exe, .{ .dest_sub_path = dxc_name }).step);
const dxcompiler = b.addLibrary(.{
.name = "dxcompiler",
.linkage = .dynamic,
.root_module = b.addModule("dxcapi", .{
.root_source_file = b.path("src/dxcapi.zig"),
.target = target,
.optimize = optimize,
// It is loaded into C programs, so it names the libc it uses
// (for TLS, among others) instead of leaving it implied.
.link_libc = target.result.os.tag != .windows,
.imports = &.{.{ .name = "zdxc", .module = mod }},
}),
});
dropin_step.dependOn(&b.addInstallArtifact(dxcompiler, .{}).step);
// (Not installed by default, so a dependent finds it by this name
// rather than with artifact().)
b.addNamedLazyPath("dxcompiler", dxcompiler.getEmittedBin());
const run_step = b.step("run", "Run zdxc"); const run_step = b.step("run", "Run zdxc");
const run_cmd = b.addRunArtifact(exe); const run_cmd = b.addRunArtifact(exe);
@ -110,6 +65,4 @@ pub fn build(b: *std.Build) void {
test_step.dependOn(&b.addRunArtifact(mod_tests).step); test_step.dependOn(&b.addRunArtifact(mod_tests).step);
const exe_tests = b.addTest(.{ .root_module = exe.root_module }); const exe_tests = b.addTest(.{ .root_module = exe.root_module });
test_step.dependOn(&b.addRunArtifact(exe_tests).step); test_step.dependOn(&b.addRunArtifact(exe_tests).step);
const dxcapi_tests = b.addTest(.{ .root_module = dxcompiler.root_module });
test_step.dependOn(&b.addRunArtifact(dxcapi_tests).step);
} }

View File

@ -9,7 +9,6 @@
"build.zig", "build.zig",
"build.zig.zon", "build.zig.zon",
"docs", "docs",
"include",
"src", "src",
"tools", "tools",
"vendor", "vendor",

View File

@ -1,82 +0,0 @@
# The C API: libzdxc
zdxc is also a library with a small C API, [`include/zdxc.h`](../include/zdxc.h).
Unlike dxcompiler, it links statically: there is no DLL to ship or load, no
COM, and nothing to link besides the platform's C library.
```sh
zig build # zig-out/lib/libzdxc.a, zig-out/include/zdxc.h
zig build -Dlinkage=dynamic # libzdxc.so / .dylib / zdxc.dll instead
zig build -Dtarget=x86_64-windows-gnu -Doptimize=ReleaseFast
```
Link `libzdxc.a` like any static library (`cc app.c -Izig-out/include
zig-out/lib/libzdxc.a`). It exports
only the `zdxc_*` functions; the compiler runtime it carries is hidden. For
a macOS binary you ship, give the target a minimum version
(`-Dtarget=aarch64-macos.13.0`), or the linker warns that the library was
built for a newer macOS than the app.
## Compiling
A compilation is a dxc command line, with the outputs returned in memory:
```c
#include <zdxc.h>
const char *args[] = {"-T", "ps_6_0", "-E", "PS", "-D", "SHADOWS=1"};
zdxc_compile_info info = {
.size = sizeof info,
.args = args,
.arg_count = 6,
.source = text,
.source_size = text_size,
.source_name = "mesh.hlsl",
};
zdxc_result *r = zdxc_compile(&info);
if (!r) return OUT_OF_MEMORY;
const char *diags = zdxc_result_output(r, ZDXC_OUTPUT_DIAGNOSTICS, NULL);
if (diags) fputs(diags, stderr); /* errors, or warnings on success */
if (zdxc_result_status(r) == ZDXC_STATUS_OK) {
size_t size;
const void *dxil = zdxc_result_output(r, ZDXC_OUTPUT_OBJECT, &size);
upload(dxil, size);
}
zdxc_result_free(r);
```
- **Options** are exactly the command line's (`-T`, `-E`, `-D`, `-I`,
`-spirv`, `-fvk-*`, `-Zpr`, `-O3`, ...), without the program name.
- **The source** is in memory (`source`, with or without a trailing NUL),
or, when `source` is NULL, the input file named in the options.
- **Files** — the input when given by name, and every `#include` candidate —
are read from disk relative to the current directory, unless you pass a
`read_file` callback. The callback gets each candidate path (the
including file's directory, then each `-I` directory) and returns 0 with
the file's bytes, or nonzero to try the next candidate. Returned memory
only has to last until `zdxc_compile` returns.
- **Status** is `ZDXC_STATUS_OK` (0), `ZDXC_STATUS_FAILED` (1: bad options,
unreadable input) or `ZDXC_STATUS_COMPILE_FAILED` (5: errors in the
source) — the command line's exit codes. `zdxc_compile` returns NULL only
when out of memory.
- **Outputs** are `OBJECT` (a DXIL container or SPIR-V module),
`DIAGNOSTICS`, `PREPROCESSED` (`-P`), `ROOT_SIGNATURE` (`-Frs`) and `TEXT`
(`-help`, `--version`). Each is NUL-terminated for convenience and lives
until `zdxc_result_free`. `zdxc_result_output_name` gives the name an
option assigned (`-Fo`, `-Fi`, `-Frs`); zdxc never writes files.
The output is byte-for-byte what the command line writes for the same
options and files.
## Threads
zdxc has no global state. Any number of threads may call `zdxc_compile` at
once, and a result may be read or freed on any thread.
## Zig
Zig projects can skip the C API: depend on this package and import the
`zdxc` module, whose `compile.compile(arena, request)` is what the C API
wraps.

View File

@ -1,56 +0,0 @@
# The DXC drop-in
Programs that run DXC usually do it in one of two ways: they call the `dxc`
executable, or they load `dxcompiler` (`dxcompiler.dll`,
`libdxcompiler.so`, `libdxcompiler.dylib`) and call `DxcCreateInstance`.
SDL_shadercross, for one, does the second. The `dropin` step builds both on
top of zdxc, so these programs can use zdxc without being changed:
```sh
zig build dropin # zig-out/bin/dxc, zig-out/lib/libdxcompiler.{so,dylib}
zig build dropin -Dtarget=x86_64-windows-gnu -Doptimize=ReleaseFast
# zig-out/bin/dxc.exe, dxcompiler.dll, lib/dxcompiler.lib
```
Put them where the program looks for DXC, in place of DXC's files. There is
no `dxil.dll`: zdxc signs DXIL itself.
- `dxc` is the zdxc command line under DXC's name.
- `dxcompiler` exports `DxcCreateInstance` and `DxcCreateInstance2`, with
`dxcapi.h`'s ABI. On Windows it imports only `kernel32` and `ntdll`. On
other platforms it links the C library and nothing else.
## What the library implements
| Class | Interfaces |
|---|---|
| `CLSID_DxcCompiler` | `IDxcCompiler3` (`Compile`), `IDxcVersionInfo` (reports 1.11) |
| `CLSID_DxcUtils` (also reached as `CLSID_DxcLibrary`) | `IDxcUtils`: blob creation, `LoadFile`, `CreateDefaultIncludeHandler`, `GetBlobAsUtf8` / `GetBlobAsWide`, `GetDxilContainerPart` |
`Compile` takes the same arguments as the command line and follows DXC:
- **Status.** A compile error is a successful call whose status is
`E_FAIL`. A bad option has status `E_INVALIDARG`.
- **Outputs.** The result holds the same outputs DXC's does: the object,
the errors (UTF-8, empty when there are none), the shader hash for DXIL,
the root signature, `-P` text, and the names given with `-Fo`, `-Fi` and
`-Frs`.
- **Includes.** Includes go through the `IDxcIncludeHandler` you pass,
with paths spelled the way DXC spells them (`./inc/common.hlsli`). With no
handler, includes fail, as they do in DXC.
- **Accepted-but-ignored options.** Options that zdxc accepts but does not
act on yet produce no note here. Many clients treat any diagnostic text
as a warning.
Classes and methods that are not implemented return `REGDB_E_CLASSNOTREG`
or `E_NOTIMPL`. These include:
- the legacy `IDxcCompiler` and `IDxcCompiler2` interfaces;
- `Disassemble`;
- `CreateReflection`, `BuildArguments` and `GetPDBContents`;
- the validator, linker, container and PDB classes.
The result has no `DXC_OUT_REFLECTION` output (the reflection container
that `CreateReflection` reads).
Language support is zdxc's own: HLSL 2021, with `-HV 2021` as the only
version.

View File

@ -1,120 +0,0 @@
/*
* zdxc: an HLSL 2021 to DXIL and SPIR-V compiler.
*
* The C API. Link libzdxc statically (zig build -Dlinkage=static, the
* default) or dynamically (-Dlinkage=dynamic); it needs nothing besides
* the platform's C library. See docs/c-api.md.
*
* A compilation takes a dxc command line and returns its outputs in
* memory:
*
* const char *args[] = {"-T", "ps_6_0", "-E", "PS"};
* zdxc_compile_info info = {
* .size = sizeof info,
* .source = text, .source_size = text_size,
* .source_name = "mesh.hlsl",
* .args = args, .arg_count = 4,
* };
* zdxc_result *r = zdxc_compile(&info);
* if (!r) { ... out of memory ... }
* size_t size;
* const char *diags = zdxc_result_output(r, ZDXC_OUTPUT_DIAGNOSTICS, &size);
* if (zdxc_result_status(r) == ZDXC_STATUS_OK) {
* const void *dxil = zdxc_result_output(r, ZDXC_OUTPUT_OBJECT, &size);
* ...
* }
* zdxc_result_free(r);
*
* zdxc never writes files: -Fo, -Fi and -Frs only name the outputs. It
* keeps no global state, so any number of threads may compile at once.
*/
#ifndef ZDXC_H
#define ZDXC_H
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
#define ZDXC_API_VERSION 1
typedef struct zdxc_result zdxc_result;
/* A compilation's outcome. The values are dxc's exit codes. */
typedef enum zdxc_status {
ZDXC_STATUS_OK = 0,
/* Bad options, or an input that cannot be read. */
ZDXC_STATUS_FAILED = 1,
/* Errors in the source. */
ZDXC_STATUS_COMPILE_FAILED = 5
} zdxc_status;
typedef enum zdxc_output {
/* The DXIL container or SPIR-V module. */
ZDXC_OUTPUT_OBJECT = 0,
/* Errors, warnings and notes, as the command line prints them. Present
* after a failure and, with warnings, after a success. */
ZDXC_OUTPUT_DIAGNOSTICS = 1,
/* The preprocessed source (-P). */
ZDXC_OUTPUT_PREPROCESSED = 2,
/* A container holding the root signature (-Frs). */
ZDXC_OUTPUT_ROOT_SIGNATURE = 3,
/* Other text the command line prints (-help, --version). */
ZDXC_OUTPUT_TEXT = 4
} zdxc_output;
/*
* Reads a file: the input when no source text is given, and every
* #include candidate (the including file's directory, then each -I
* directory). On success, set *data and *size and return 0; the memory
* must stay valid until zdxc_compile returns. Return nonzero if the file
* does not exist, and zdxc tries the next candidate.
*/
typedef int (*zdxc_read_file_fn)(void *user, const char *path, const char **data, size_t *size);
typedef struct zdxc_compile_info {
/* sizeof(zdxc_compile_info): lets later versions add fields. */
uint32_t size;
/* dxc command-line options, without the program name. A positional
* argument names the input file. */
const char *const *args;
size_t arg_count;
/* The main file's text (a trailing NUL is allowed), or NULL to read the
* input file named in args with read_file. */
const char *source;
size_t source_size;
/* The main file's name in diagnostics and for #include "...". NULL
* means the input file in args, else "hlsl.hlsl". */
const char *source_name;
/* Reads files; NULL reads them from disk relative to the current
* directory. */
zdxc_read_file_fn read_file;
void *user;
} zdxc_compile_info;
/* Compiles. Returns NULL only when out of memory (or for a NULL or too
* small info); every other failure is in the result. */
zdxc_result *zdxc_compile(const zdxc_compile_info *info);
zdxc_status zdxc_result_status(const zdxc_result *result);
/* One output: its bytes, followed by a NUL that *size does not count, or
* NULL (and *size 0) if the compilation did not produce it. size may be
* NULL. Valid until zdxc_result_free. */
const void *zdxc_result_output(const zdxc_result *result, zdxc_output output, size_t *size);
/* The file name the options give an output (-Fo, -Fi, -Frs), or NULL. */
const char *zdxc_result_output_name(const zdxc_result *result, zdxc_output output);
void zdxc_result_free(zdxc_result *result);
/* zdxc's version, such as "0.1.0". */
const char *zdxc_version(void);
#ifdef __cplusplus
}
#endif
#endif /* ZDXC_H */

View File

@ -1,131 +0,0 @@
//! The C API (include/zdxc.h): `compile`, behind C types. Every result
//! owns an arena; nothing is global.
const std = @import("std");
const zdxc = @import("zdxc");
const compile = zdxc.compile;
const FileSystem = zdxc.front.source.FileSystem;
const ReadFileFn = *const fn (user: ?*anyopaque, path: [*:0]const u8, data: *?[*]const u8, size: *usize) callconv(.c) c_int;
const CompileInfo = extern struct {
size: u32,
args: ?[*]const ?[*:0]const u8,
arg_count: usize,
source: ?[*]const u8,
source_size: usize,
source_name: ?[*:0]const u8,
read_file: ?ReadFileFn,
user: ?*anyopaque,
};
const Output = enum(c_int) { object, diagnostics, preprocessed, root_signature, text, _ };
const Result = struct {
arena: std.heap.ArenaAllocator,
status: compile.Status,
/// Indexed by `Output`; each NUL-terminated.
outputs: [5]?[:0]const u8,
names: [5]?[:0]const u8,
};
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);
const r = compileInto(&arena, i) catch {
arena.deinit();
return null;
};
r.arena = arena;
return r;
}
fn compileInto(arena: *std.heap.ArenaAllocator, 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);
var callback: Callback = undefined;
var threaded: std.Io.Threaded = .init_single_threaded;
var req: compile.Request = .{ .args = args, .io = threaded.io() };
if (i.source) |s| {
// Callers often pass strlen + 1.
req.source = std.mem.trimEnd(u8, s[0..i.source_size], "\x00");
}
if (i.source_name) |n| req.source_name = std.mem.span(n);
if (i.read_file) |f| {
callback = .{ .read_file = f, .user = i.user };
req.fs = callback.fileSystem();
}
const c = try compile.compile(a, req);
const r = try a.create(Result);
r.* = .{
.arena = undefined,
.status = c.status,
.outputs = .{
try dupeZ(a, c.object),
if (c.diagnostics.len > 0) try a.dupeSentinel(u8, c.diagnostics, 0) else null,
try dupeZ(a, c.preprocessed),
try dupeZ(a, c.root_signature),
if (c.text.len > 0) try a.dupeSentinel(u8, c.text, 0) else null,
},
.names = .{
try dupeZ(a, c.object_name),
null,
try dupeZ(a, c.preprocessed_name),
try dupeZ(a, c.root_signature_name),
null,
},
};
return r;
}
fn dupeZ(a: std.mem.Allocator, s: ?[]const u8) !?[:0]const u8 {
return if (s) |t| try a.dupeSentinel(u8, t, 0) else null;
}
/// `zdxc_read_file_fn` as a file system.
const Callback = struct {
read_file: ReadFileFn,
user: ?*anyopaque,
fn fileSystem(c: *Callback) FileSystem {
return .{ .ctx = c, .readFn = read };
}
fn read(ctx: *anyopaque, gpa: std.mem.Allocator, path: []const u8) ?[]const u8 {
const c: *Callback = @ptrCast(@alignCast(ctx));
const z = gpa.dupeSentinel(u8, path, 0) catch return null;
defer gpa.free(z);
var data: ?[*]const u8 = null;
var size: usize = 0;
if (c.read_file(c.user, z, &data, &size) != 0) return null;
const d = data orelse return if (size == 0) gpa.dupe(u8, "") catch null else null;
return gpa.dupe(u8, d[0..size]) catch null;
}
};
export fn zdxc_result_status(r: *const Result) c_int {
return @intFromEnum(r.status);
}
export fn zdxc_result_output(r: *const Result, which: Output, size: ?*usize) ?*const anyopaque {
const o = if (@intFromEnum(which) >= 0 and @intFromEnum(which) < r.outputs.len) r.outputs[@intCast(@intFromEnum(which))] else null;
if (size) |s| s.* = if (o) |b| b.len else 0;
return if (o) |b| b.ptr else null;
}
export fn zdxc_result_output_name(r: *const Result, which: Output) ?[*:0]const u8 {
const n = if (@intFromEnum(which) >= 0 and @intFromEnum(which) < r.names.len) r.names[@intCast(@intFromEnum(which))] else null;
return if (n) |s| s.ptr else null;
}
export fn zdxc_result_free(r: ?*Result) void {
const res = r orelse return;
var arena = res.arena;
arena.deinit();
}
export fn zdxc_version() [*:0]const u8 {
return zdxc.version;
}

View File

@ -1,607 +0,0 @@
//! One compilation, as a library call: a dxc command line in, the outputs
//! and diagnostics out, in memory. The command-line driver and the C API
//! are both built on `compile`; neither the compiler nor this file writes
//! files.
const std = @import("std");
const Io = std.Io;
const zdxc = @import("root.zig");
const shader = zdxc.dxil.shader;
const container = zdxc.dxil.container;
const front = zdxc.front;
const options = zdxc.options;
const FileSystem = front.source.FileSystem;
pub const Request = struct {
/// dxc command-line options, without the program name: "-T", "ps_6_0",
/// "-E", "PS", "shader.hlsl", ...
args: []const []const u8,
/// The main file's text. When null, the input file named in `args` is
/// read through `fs`.
source: ?[]const u8 = null,
/// The main file's name in diagnostics when `source` is given. Defaults
/// to the input file named in `args`, else "hlsl.hlsl" (as in dxc).
source_name: ?[]const u8 = null,
/// Reads the input and included files. Null reads them from disk,
/// relative to the current directory.
fs: ?FileSystem = null,
io: Io,
/// Color diagnostics unless the options say otherwise.
color: bool = false,
/// Fail without -Fo, as the command line does (a library caller takes
/// the object from the result instead).
require_output: bool = false,
/// Note options that are accepted but have no effect yet. (The DXC
/// drop-in leaves them out: its clients read any diagnostic text as a
/// warning.)
compat_notes: bool = true,
};
pub const Status = enum(u8) {
ok = 0,
/// Bad options, or an input that cannot be read (dxc's exit code 1).
failed = 1,
/// Errors in the source (dxc's exit code 5).
compile_failed = 5,
};
pub const Result = struct {
status: Status = .ok,
/// The DXIL container or SPIR-V module, and its -Fo name.
object: ?[]const u8 = null,
object_name: ?[]const u8 = null,
/// The root signature container (-Frs) and its name.
root_signature: ?[]const u8 = null,
root_signature_name: ?[]const u8 = null,
/// Preprocessed source (-P) and its -Fi name.
preprocessed: ?[]const u8 = null,
preprocessed_name: ?[]const u8 = null,
/// Errors, warnings and notes: what the command line prints on stderr.
diagnostics: []const u8 = "",
/// Other text the command line prints on stdout (-help, dumps).
text: []const u8 = "",
};
/// Runs one compilation. Everything in the result is allocated in `arena`.
/// Only running out of memory fails the call; every other failure is in
/// the result's status and diagnostics.
pub fn compile(arena: std.mem.Allocator, req: Request) error{OutOfMemory}!Result {
var result: Result = .{};
var stdout: Io.Writer.Allocating = .init(arena);
var stderr: Io.Writer.Allocating = .init(arena);
var disk: front.source.DiskFs = .{ .io = req.io };
var overlay: Overlay = .{ .base = req.fs orelse disk.fileSystem() };
var r = req;
if (req.source) |text| {
// The main file is the given text, under its name.
var failure: options.Failure = .{};
const inputs = if (options.parse(arena, req.args, &failure)) |p| p.inputs else |_| &.{};
const name = req.source_name orelse if (inputs.len > 0) inputs[inputs.len - 1] else "hlsl.hlsl";
overlay.name = name;
overlay.text = text;
if (inputs.len == 0) {
const args = try arena.alloc([]const u8, req.args.len + 1);
@memcpy(args[0..req.args.len], req.args);
args[req.args.len] = name;
r.args = args;
}
}
var ctx: Ctx = .{
.io = req.io,
.fs = overlay.fileSystem(),
.req = &r,
.result = &result,
.stdout = &stdout.writer,
.stderr = &stderr.writer,
};
run(&ctx, arena) catch |err| switch (err) {
error.Fatal => result.status = .failed,
error.CompileFailed => result.status = .compile_failed,
error.OutOfMemory => return error.OutOfMemory,
else => {
ctx.stderr.print("zdxc: error: {s}\n", .{@errorName(err)}) catch return error.OutOfMemory;
result.status = .failed;
},
};
if (result.status != .ok) {
result.object = null;
result.root_signature = null;
result.preprocessed = null;
}
result.diagnostics = stderr.written();
result.text = stdout.written();
return result;
}
/// The file system, with the in-memory main file in front of it.
const Overlay = struct {
base: FileSystem,
name: ?[]const u8 = null,
text: []const u8 = "",
fn fileSystem(o: *Overlay) FileSystem {
return .{ .ctx = o, .readFn = read };
}
fn read(ctx: *anyopaque, gpa: std.mem.Allocator, path: []const u8) ?[]const u8 {
const o: *Overlay = @ptrCast(@alignCast(ctx));
if (o.name) |n| if (std.mem.eql(u8, n, path)) return gpa.dupe(u8, o.text) catch null;
return o.base.read(gpa, path);
}
};
const Ctx = struct {
io: Io,
fs: FileSystem,
req: *const Request,
result: *Result,
stdout: *Io.Writer,
stderr: *Io.Writer,
fn fail(ctx: *Ctx, comptime fmt: []const u8, args: anytype) error{Fatal} {
ctx.stderr.print("zdxc: error: " ++ fmt ++ "\n", args) catch {};
return error.Fatal;
}
fn read(ctx: *Ctx, arena: std.mem.Allocator, path: []const u8) ![]const u8 {
return ctx.fs.read(arena, path) orelse ctx.fail("cannot open file '{s}'", .{path});
}
/// -Fo is required on the command line.
fn needOutput(ctx: *Ctx, opts: Options) !void {
if (ctx.req.require_output and opts.output == null) return ctx.fail("missing -Fo <file>", .{});
}
};
const Options = struct {
profile: ?[]const u8 = null,
entry: []const u8 = "main",
output: ?[]const u8 = null,
input: ?[]const u8 = null,
spirv: bool = false,
/// -fspv-target-env (vulkan1.0 by default).
target_env: []const u8 = "vulkan1.0",
preprocess: bool = false,
pp_output: ?[]const u8 = null,
enable_16bit: bool = false,
row_major: bool = false,
col_major: bool = false,
/// -force-rootsig-ver, -Qstrip_rootsignature, -rootsig-define, -Frs.
rootsig_ver: ?[]const u8 = null,
strip_rootsig: bool = false,
rootsig_define: ?[]const u8 = null,
rootsig_output: ?[]const u8 = null,
vk: zdxc.ir.ir.VkOptions = .{},
defines: std.ArrayList(front.preproc.Define) = .empty,
include_dirs: std.ArrayList([]const u8) = .empty,
empty: bool = false,
check_hash: bool = false,
lex: bool = false,
warnings_as_errors: bool = false,
no_warnings: bool = false,
disabled_warnings: std.ArrayList([]const u8) = .empty,
diag_format: zdxc.diag.Format = .clang,
color: ?bool = null,
error_limit: u32 = 20,
parse: bool = false,
dump_ast: bool = false,
sema: bool = false,
dump_ir: bool = false,
/// -O0..-O3 / -Od (default -O3, as in dxc).
opt_level: enum { od, o0, o1, o2, o3 } = .o3,
/// Accepted options with no effect yet, reported once each.
ignored: std.ArrayList([]const u8) = .empty,
/// `--job=<file>`: the command-line driver handles it before compiling.
job: ?[]const u8 = null,
};
/// Parse a dxc-style command line. Returns null when the command is
/// complete (`-help`, `--version`).
fn parseArgs(ctx: *Ctx, arena: std.mem.Allocator, args: []const []const u8) !?Options {
var failure: options.Failure = .{};
const parsed = options.parse(arena, args, &failure) catch |e| switch (e) {
error.UnknownArgument => return ctx.fail("unknown argument: '{s}'", .{failure.arg}),
error.MissingArgument => return ctx.fail("argument to '{s}' is missing", .{failure.arg}),
error.OutOfMemory => return error.OutOfMemory,
};
var opts: Options = .{};
for (parsed.args) |a| {
switch (a.which) {
.extra => |x| switch (x) {
.zdxc_empty => opts.empty = true,
.zdxc_check_hash => opts.check_hash = true,
.zdxc_lex => opts.lex = true,
.zdxc_parse => opts.parse = true,
.zdxc_ast => {
opts.parse = true;
opts.dump_ast = true;
},
.zdxc_sema => opts.sema = true,
.zdxc_ir => opts.dump_ir = true,
.job => opts.job = a.value(),
.fcolor_diagnostics => opts.color = true,
.fno_color_diagnostics => opts.color = false,
},
.dxc => |id| {
switch (options.support(id)) {
.implemented => {},
.ignored => {
try opts.ignored.append(arena, a.spelling);
continue;
},
.unsupported => |why| return ctx.fail("'{s}' is not supported: {s}", .{ a.spelling, why }),
}
const v = a.value();
switch (id) {
.target_profile => opts.profile = v,
.entrypoint => opts.entry = v,
.Fo => opts.output = v,
.Fi => opts.pp_output = v,
.D => if (std.mem.indexOfScalar(u8, v, '=')) |eq| {
try opts.defines.append(arena, .{ .name = v[0..eq], .value = v[eq + 1 ..] });
} else try opts.defines.append(arena, .{ .name = v }),
.I => try opts.include_dirs.append(arena, v),
.hlsl_version => if (!std.mem.eql(u8, v, "2021")) {
return ctx.fail("HLSL version {s} is not supported; zdxc implements HLSL 2021 only", .{v});
},
.P => opts.preprocess = true,
.spirv => opts.spirv = true,
.fspv_target_env_EQ => opts.target_env = v,
.enable_16bit_types => opts.enable_16bit = true,
.Zpr => opts.row_major = true,
.Zpc => opts.col_major = true,
.force_rootsig_ver, .force_rootsig_ver_ => opts.rootsig_ver = v,
.Qstrip_rootsignature => opts.strip_rootsig = true,
.rootsig_define => opts.rootsig_define = v,
.Frs => opts.rootsig_output = v,
.fvk_b_shift, .fvk_t_shift, .fvk_s_shift, .fvk_u_shift => {
const k: usize = switch (id) {
.fvk_b_shift => 0,
.fvk_t_shift => 1,
.fvk_s_shift => 2,
else => 3,
};
const shift = std.fmt.parseInt(u32, a.values[0], 10) catch return ctx.fail("invalid {s} shift '{s}'", .{ a.spelling, a.values[0] });
const set: ?u32 = if (std.mem.eql(u8, a.values[1], "all")) null else std.fmt.parseInt(u32, a.values[1], 10) catch return ctx.fail("invalid {s} space '{s}'", .{ a.spelling, a.values[1] });
try opts.vk.shifts[k].append(arena, .{ .shift = shift, .set = set });
},
.fvk_bind_globals => opts.vk.bind_globals = .{
std.fmt.parseInt(u32, a.values[0], 10) catch return ctx.fail("invalid -fvk-bind-globals binding number: {s}", .{a.values[0]}),
std.fmt.parseInt(u32, a.values[1], 10) catch return ctx.fail("invalid -fvk-bind-globals set number: {s}", .{a.values[1]}),
},
.fvk_bind_register, .vkbr => {
const reg = a.values[0];
if (reg.len < 2 or std.mem.indexOfScalar(u8, "btsu", reg[0]) == null) return ctx.fail("invalid -fvk-bind-register register '{s}'", .{reg});
const num = struct {
fn f(c: *Ctx, t: []const u8) !u32 {
return std.fmt.parseInt(u32, t, 10) catch c.fail("invalid -fvk-bind-register number '{s}'", .{t});
}
}.f;
try opts.vk.bind_register.append(arena, .{ .class = reg[0], .index = try num(ctx, reg[1..]), .space = try num(ctx, a.values[1]), .binding = try num(ctx, a.values[2]), .set = try num(ctx, a.values[3]) });
},
.auto_binding_space => opts.vk.auto_binding_space = std.fmt.parseInt(u32, v, 10) catch return ctx.fail("invalid -auto-binding-space '{s}'", .{v}),
.fvk_auto_shift_bindings => opts.vk.auto_shift = true,
.fspv_flatten_resource_arrays => opts.vk.flatten_arrays = true,
.fspv_use_legacy_buffer_matrix_order => opts.vk.legacy_matrix_order = true,
.fspv_use_vulkan_memory_model => opts.vk.vulkan_memory_model = true,
// (zdxc never removes interface variables.)
.fspv_preserve_interface => {},
.fvk_invert_y => opts.vk.invert_y = true,
.fvk_use_gl_layout => opts.vk.layout = .gl,
.fvk_use_dx_layout => opts.vk.layout = .dx,
.fvk_use_scalar_layout => opts.vk.layout = .scalar,
.fspv_entrypoint_name_EQ => opts.vk.entry_name = v,
.fspv_extension_EQ => try opts.vk.extensions.append(arena, v),
.fspv_reflect => opts.vk.reflect = true,
.fspv_enable_maximal_reconvergence => opts.vk.maximal_reconvergence = true,
.fvk_support_nonzero_base_instance => opts.vk.nonzero_base_instance = true,
.fvk_support_nonzero_base_vertex => opts.vk.nonzero_base_vertex = true,
.fspv_use_unknown_image_format => opts.vk.unknown_image_format = true,
.fvk_use_dx_position_w => opts.vk.dx_position_w = true,
.fvk_stage_io_order_EQ => {
if (std.mem.eql(u8, v, "alpha")) opts.vk.alpha_io_order = true else if (!std.mem.eql(u8, v, "decl")) return ctx.fail("unknown -fvk-stage-io-order '{s}'", .{v});
},
._SLASH_WX => opts.warnings_as_errors = true,
.no_warnings => opts.no_warnings = true,
.W_Joined => {
// -Wno-<group>, -Werror; enabling groups is a no-op.
if (std.mem.startsWith(u8, v, "no-")) {
try opts.disabled_warnings.append(arena, v[3..]);
} else if (std.mem.eql(u8, v, "error")) opts.warnings_as_errors = true;
},
.Wno_vk_ignored_features => try opts.disabled_warnings.append(arena, "vk-ignored-features"),
.Wno_vk_emulated_features => try opts.disabled_warnings.append(arena, "vk-emulated-features"),
.fdiagnostics_format_EQ => {
// dxc also accepts msvc-fallback.
const name = if (std.mem.eql(u8, v, "msvc-fallback")) "msvc" else v;
opts.diag_format = std.meta.stringToEnum(zdxc.diag.Format, name) orelse
return ctx.fail("unknown diagnostics format '{s}' (expected clang, msvc or vi)", .{v});
},
.ferror_limit_EQ => opts.error_limit = std.fmt.parseInt(u32, v, 10) catch
return ctx.fail("invalid -ferror-limit value '{s}'", .{v}),
.fdiagnostics_color => opts.color = true,
.fdiagnostics_color_EQ => opts.color = if (std.mem.eql(u8, v, "always"))
true
else if (std.mem.eql(u8, v, "never"))
false
else
null,
.help, ._help_question, ._help_hidden => {
try options.printHelp(ctx.stdout, id == ._help_hidden);
return null;
},
._version => {
try ctx.stdout.print("zdxc {s} (dxc-compatible command line, HLSL 2021)\n", .{zdxc.version});
return null;
},
.O0 => opts.opt_level = .o0,
.O1 => opts.opt_level = .o1,
.O2 => opts.opt_level = .o2,
.O3 => opts.opt_level = .o3,
.Od => opts.opt_level = .od,
else => {}, // implemented as a no-op (e.g. -Vd, -nologo)
}
},
}
}
if (opts.row_major and opts.col_major) return ctx.fail("Cannot specify /Zpr and /Zpc together, use /? to get usage information", .{});
// Like dxc, the last input wins (dxc reads getLastArgValue(OPT_INPUT)).
if (parsed.inputs.len > 0) opts.input = parsed.inputs[parsed.inputs.len - 1];
if (opts.ignored.items.len > 0 and !opts.no_warnings and ctx.req.compat_notes) {
try ctx.stderr.writeAll("zdxc: note: accepted for compatibility, no effect yet:");
for (opts.ignored.items) |sp| try ctx.stderr.print(" {s}", .{sp});
try ctx.stderr.writeByte('\n');
}
return opts;
}
fn run(ctx: *Ctx, arena: std.mem.Allocator) !void {
const opts = try parseArgs(ctx, arena, ctx.req.args) orelse return;
ctx.result.object_name = opts.output;
ctx.result.root_signature_name = opts.rootsig_output;
ctx.result.preprocessed_name = opts.pp_output;
if (opts.job != null) return ctx.fail("--job is a command-line option; it cannot be used inside a job file or the library", .{});
if (opts.check_hash) {
const path = opts.input orelse return ctx.fail("no input file", .{});
const bytes = try ctx.read(arena, path);
const view = container.parse(arena, bytes) catch return ctx.fail("{s}: not a DXIL container", .{path});
if (!container.hashMatches(view.bytes)) return ctx.fail("{s}: hash mismatch", .{path});
try ctx.stdout.print("{s}: hash ok ({d} parts)\n", .{ path, view.parts.items.len });
return;
}
if (opts.lex) {
const path = opts.input orelse return ctx.fail("no input file", .{});
const text = try ctx.read(arena, path);
var lx = front.lexer.Lexer.init(text, 0);
while (true) {
const t = lx.next();
if (t.kind == .eof) break;
if (t.kind == .hash and t.flags.bol) {
const save = lx;
const d = lx.next();
if (d.isIdent("line")) {
lx.skipLine();
continue;
}
lx = save;
}
try ctx.stdout.print("{s}\n", .{t.text});
}
return;
}
// Root signature targets: the root signature in the macro -E names.
if (opts.profile) |p| if (std.mem.eql(u8, p, "rootsig_1_0") or std.mem.eql(u8, p, "rootsig_1_1")) {
const input = opts.input orelse return ctx.fail("no input file", .{});
try ctx.needOutput(opts);
const version: zdxc.dxil.rootsig.Version = if (std.mem.eql(u8, p, "rootsig_1_0")) .v1_0 else .v1_1;
const blob = try compileRootSignatureMacro(ctx, arena, opts, input, opts.entry, version, .none) orelse return error.CompileFailed;
ctx.result.object = try rootSignatureContainer(arena, blob);
return;
};
const profile: ?shader.Profile = if (opts.profile) |p|
shader.Profile.parse(p) orelse return ctx.fail("unknown profile '{s}'", .{p})
else
null;
// The front end: everything except the development modes that work on
// containers or raw tokens.
if (!opts.empty) {
const input = opts.input orelse return ctx.fail("no input file", .{});
var sm = front.source.SourceManager.init(arena, ctx.fs);
var diags = zdxc.Diagnostics.init(arena);
diags.warnings_as_errors = opts.warnings_as_errors;
diags.suppress_warnings = opts.no_warnings;
diags.error_limit = opts.error_limit;
for (opts.disabled_warnings.items) |g| try diags.disableGroup(g);
var pp = front.preproc.Preprocessor.init(arena, &sm, &diags, .{
.defines = opts.defines.items,
.include_dirs = opts.include_dirs.items,
.stage = if (profile) |p| @backingInt(p.kind) else 5,
.major = if (profile) |p| p.major else 6,
.minor = if (profile) |p| p.minor else 0,
.spirv = opts.spirv,
.spirv_minor = if (zdxc.spirv.emit.TargetEnv.parse(opts.target_env)) |t| t.minor else 0,
.enable_16bit = opts.enable_16bit,
});
var out: Io.Writer.Allocating = .init(arena);
var module: ?zdxc.ir.ir.Module = null;
const opened = try pp.enterMainFile(input);
if (opened) {
if (opts.preprocess) {
try front.pp_print.print(&pp, &out.writer);
} else {
var parser = try front.parser.Parser.fromPreprocessor(arena, &diags, &pp);
const tu = try parser.parseTranslationUnit();
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;
var sema = try zdxc.sema.Sema.init(arena, &diags, .{
.entry = if (opts.sema or is_lib) null else opts.entry,
.spirv = opts.spirv,
.enable_16bit = opts.enable_16bit,
.sm_minor = if (profile) |p| p.minor else 10,
.library = is_lib,
.root = opts.entry,
.row_major = opts.row_major,
});
try sema.checkUnit(tu);
if (!opts.sema and !diags.hasErrors() and profile != null) {
const stage: zdxc.ir.ir.Stage = switch (profile.?.kind) {
.vertex => .vertex,
.pixel => .pixel,
.geometry => .geometry,
.hull => .hull,
.domain => .domain,
.compute => .compute,
.mesh => .mesh,
.amplification => .amplification,
else => .library,
};
module = zdxc.ir.lower.lowerUnit(arena, &sema, .{ .entry = opts.entry, .stage = stage }) catch |e| switch (e) {
error.Unsupported => null,
else => |x| return x,
};
if (module) |*mm| {
mm.native_16bit = opts.enable_16bit;
mm.row_major = opts.row_major;
mm.vk = opts.vk;
mm.strip_rootsig = opts.strip_rootsig;
if (opts.rootsig_ver) |rv| {
if (std.mem.eql(u8, rv, "rootsig_1_0")) mm.rootsig_version = .v1_0 else if (!std.mem.eql(u8, rv, "rootsig_1_1")) return ctx.fail("unknown root signature version '{s}'", .{rv});
}
}
}
}
}
}
const color = opts.color orelse ctx.req.color;
try diags.render(&sm, ctx.stderr, .{ .format = opts.diag_format, .color = color });
// An unreadable input is an I/O error, as in dxc.
if (!opened) return error.Fatal;
if (diags.hasErrors()) return error.CompileFailed;
if (opts.preprocess) {
ctx.result.preprocessed = out.written();
return;
}
if (opts.parse or opts.sema) return;
if (profile == null) return ctx.fail("missing -T <profile>", .{});
if (module) |*m| {
try zdxc.ir.opt.run(arena, m);
if (opts.dump_ir) {
try zdxc.ir.ir.dump(m, ctx.stdout);
return;
}
if (opts.spirv) {
zdxc.ir.split_resources.run(arena, m, &diags) catch |err| switch (err) {
error.Unsupported => {
try diags.render(&sm, ctx.stderr, .{ .format = opts.diag_format, .color = false });
return error.CompileFailed;
},
else => |x| return x,
};
const bytes = zdxc.spirv.emit.emit(arena, m, &diags, zdxc.spirv.emit.TargetEnv.parse(opts.target_env) orelse return ctx.fail("unknown SPIR-V target environment '{s}'", .{opts.target_env})) catch |err| switch (err) {
error.Unsupported => {
try diags.render(&sm, ctx.stderr, .{ .format = opts.diag_format, .color = false });
return error.CompileFailed;
},
else => |x| return x,
};
try ctx.needOutput(opts);
ctx.result.object = bytes;
return;
}
// -rootsig-define: the macro's root signature for the entry.
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 bytes = zdxc.dxil.emit.emit(arena, m, profile.?, &diags) catch |err| switch (err) {
error.Unsupported => {
try diags.render(&sm, ctx.stderr, .{ .format = opts.diag_format, .color = false });
return error.CompileFailed;
},
else => |x| return x,
};
try ctx.needOutput(opts);
ctx.result.object = bytes;
if (opts.rootsig_output != null) {
const text = (if (m.entries.items.len == 1) m.entries.items[0].root_signature else null) orelse return ctx.fail("-Frs: the shader has no root signature", .{});
var d: zdxc.dxil.rootsig.Diagnostic = .{};
const blob = try zdxc.dxil.rootsig.compileWithOptions(arena, text, .{ .version = if (m.rootsig_version == .v1_0) .v1_0 else .v1_1, .flags = .global }, &d) orelse return ctx.fail("root signature error - {s}", .{d.message()});
ctx.result.root_signature = try rootSignatureContainer(arena, blob);
}
return;
}
return ctx.fail("code generation is not implemented yet: the input was checked but no output was written (use -zdxc-empty for a placeholder shader)", .{});
}
const prof = profile orelse return ctx.fail("missing -T <profile>", .{});
if (!opts.empty) return ctx.fail("compiling HLSL is not implemented yet (use -P or -zdxc-empty)", .{});
if (prof.kind != .compute) return ctx.fail("-zdxc-empty supports compute profiles only", .{});
const bytes = if (opts.spirv)
try zdxc.spirv.builder.buildEmptyCompute(arena, .{ .entry = opts.entry, .num_threads = .{ 1, 1, 1 } })
else
try shader.buildEmptyCompute(arena, .{ .entry = opts.entry, .profile = prof, .num_threads = .{ 1, 1, 1 } });
try ctx.needOutput(opts);
ctx.result.object = bytes;
}
/// The text of the root signature macro `macro` defines in `input` (its
/// string literals concatenated), or null after reporting an error.
fn rootSignatureMacroText(ctx: *Ctx, arena: std.mem.Allocator, opts: Options, input: []const u8, macro: []const u8) !?[]const u8 {
const text = try ctx.read(arena, input);
var sm = front.source.SourceManager.init(arena, ctx.fs);
var diags = zdxc.Diagnostics.init(arena);
var pp = front.preproc.Preprocessor.init(arena, &sm, &diags, .{
.defines = opts.defines.items,
.include_dirs = opts.include_dirs.items,
.stage = 6,
});
// Expand the macro after a marker at the end of the file.
const marker = "__zdxc_root_signature__";
try pp.enterMainText(input, try std.mem.concat(arena, u8, &.{ text, "\n" ++ marker ++ " ", macro, "\n" }));
var parts: std.ArrayList(u8) = .empty;
var seen = false;
var any = false;
while (true) {
const t = try pp.next();
if (t.kind == .eof) break;
if (!seen) {
seen = t.kind == .identifier and std.mem.eql(u8, t.text, marker);
continue;
}
if (t.kind != .string) {
_ = diags.report(.{ .severity = .@"error", .loc = t.loc }, "root signature macro '{s}' must expand to string literals", .{macro});
break;
}
any = true;
try parts.appendSlice(arena, try zdxc.ir.lower.stringContents(arena, t.text));
}
if (!any and !diags.hasErrors()) _ = diags.report(.{ .severity = .@"error", .loc = .none }, "root signature macro '{s}' is not defined", .{macro});
if (diags.hasErrors()) {
try diags.render(&sm, ctx.stderr, .{ .format = opts.diag_format, .color = false });
return null;
}
return parts.items;
}
fn compileRootSignatureMacro(ctx: *Ctx, arena: std.mem.Allocator, opts: Options, input: []const u8, macro: []const u8, version: zdxc.dxil.rootsig.Version, flags: zdxc.dxil.rootsig.CompilationFlags) !?[]const u8 {
const text = try rootSignatureMacroText(ctx, arena, opts, input, macro) orelse return null;
var d: zdxc.dxil.rootsig.Diagnostic = .{};
return try zdxc.dxil.rootsig.compileWithOptions(arena, text, .{ .version = version, .flags = flags }, &d) orelse {
try ctx.stderr.print("{s}: error: root signature error - {s}\n", .{ input, d.message() });
return null;
};
}
/// A container holding only the root signature (RTS0) part.
fn rootSignatureContainer(arena: std.mem.Allocator, blob: []const u8) ![]u8 {
return zdxc.dxil.container.assemble(arena, &.{.{ .fourcc = zdxc.dxil.container.fourcc("RTS0"), .data = blob }});
}

File diff suppressed because it is too large Load Diff

View File

@ -2000,9 +2000,6 @@ const object_types = [_][]const u8{
"__builtin_LinAlgMatrix", "BuiltInTrianglePositions", "__builtin_LinAlgMatrix", "BuiltInTrianglePositions",
}; };
/// The builtin pseudo-enum typedefs of uint (`const RAY_FLAG f = ...`).
const enum_typedefs = [_][]const u8{ "RAY_FLAG", "RAYQUERY_FLAG", "COMMITTED_STATUS", "CANDIDATE_TYPE", "MEMORY_TYPE_FLAG", "BARRIER_SEMANTIC_FLAG" };
/// Templates among the builtin object types. /// Templates among the builtin object types.
const template_types = [_][]const u8{ const template_types = [_][]const u8{
"vector", "matrix", "Buffer", "vector", "matrix", "Buffer",
@ -2054,7 +2051,7 @@ fn inList(list: []const []const u8, w: []const u8) bool {
/// replaces linear scans of the lists above (a third of parse time). /// replaces linear scans of the lists above (a third of parse time).
const word_map = blk: { const word_map = blk: {
@setEvalBranchQuota(1_000_000); @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 ++ template_types ++ template_funcs);
for (qualifier_words) |q| words = words ++ &[_][]const u8{q[0]}; for (qualifier_words) |q| words = words ++ &[_][]const u8{q[0]};
var kvs: [words.len]struct { []const u8, WordInfo } = undefined; var kvs: [words.len]struct { []const u8, WordInfo } = undefined;
var n: usize = 0; var n: usize = 0;
@ -2065,7 +2062,7 @@ const word_map = blk: {
.contextual = inList(&contextual_words, w), .contextual = inList(&contextual_words, w),
.scalar = inList(&scalar_types, w), .scalar = inList(&scalar_types, w),
.numeric_scalar = inList(&scalar_types, w) and !std.mem.endsWith(u8, w, "_packed"), .numeric_scalar = inList(&scalar_types, w) and !std.mem.endsWith(u8, w, "_packed"),
.object = inList(&object_types, w) or inList(&enum_typedefs, w), .object = inList(&object_types, w),
.template = inList(&template_types, w) or inList(&template_funcs, w), .template = inList(&template_types, w) or inList(&template_funcs, w),
}; };
for (qualifier_words) |q| { for (qualifier_words) |q| {

View File

@ -1693,10 +1693,7 @@ const Lowerer = struct {
const t = l.types(); const t = l.types();
if (l.vars.get(v)) |p| return p; if (l.vars.get(v)) |p| return p;
switch (v.storage) { switch (v.storage) {
.local, .param => return l.fail(e, "this variable"), .local, .param, .local_static => return l.fail(e, "this variable"),
// Not yet in `vars` only inside another static's initializer:
// its global, as for a file-scope static.
.local_static => {},
.global_uniform, .cbuffer => { .global_uniform, .cbuffer => {
if (isObject(&l.s.types, v.type)) { if (isObject(&l.s.types, v.type)) {
l.unsupported(e.loc, "resource '{s}' declared as a uniform is not supported yet", .{v.name}); l.unsupported(e.loc, "resource '{s}' declared as a uniform is not supported yet", .{v.name});

View File

@ -1,67 +1,524 @@
//! The dxc-compatible command line: `compile` from the library, with the
//! outputs written to the files the options name.
const std = @import("std"); const std = @import("std");
const Io = std.Io; const Io = std.Io;
const zdxc = @import("zdxc"); const zdxc = @import("zdxc");
const shader = zdxc.dxil.shader;
const container = zdxc.dxil.container;
const front = zdxc.front;
const options = zdxc.options;
const job = @import("job.zig"); const job = @import("job.zig");
const Options = struct {
profile: ?[]const u8 = null,
entry: []const u8 = "main",
output: ?[]const u8 = null,
input: ?[]const u8 = null,
spirv: bool = false,
/// -fspv-target-env (vulkan1.0 by default).
target_env: []const u8 = "vulkan1.0",
preprocess: bool = false,
pp_output: ?[]const u8 = null,
enable_16bit: bool = false,
row_major: bool = false,
col_major: bool = false,
/// -force-rootsig-ver, -Qstrip_rootsignature, -rootsig-define, -Frs.
rootsig_ver: ?[]const u8 = null,
strip_rootsig: bool = false,
rootsig_define: ?[]const u8 = null,
rootsig_output: ?[]const u8 = null,
vk: zdxc.ir.ir.VkOptions = .{},
defines: std.ArrayList(front.preproc.Define) = .empty,
include_dirs: std.ArrayList([]const u8) = .empty,
empty: bool = false,
check_hash: bool = false,
lex: bool = false,
warnings_as_errors: bool = false,
no_warnings: bool = false,
disabled_warnings: std.ArrayList([]const u8) = .empty,
diag_format: zdxc.diag.Format = .clang,
color: ?bool = null,
error_limit: u32 = 20,
parse: bool = false,
dump_ast: bool = false,
sema: bool = false,
dump_ir: bool = false,
/// -O0..-O3 / -Od (default -O3, as in dxc).
opt_level: enum { od, o0, o1, o2, o3 } = .o3,
/// Accepted options with no effect yet, reported once each.
ignored: std.ArrayList([]const u8) = .empty,
/// `--job=<file>` (handled before run; here only inside a job file).
job: ?[]const u8 = null,
};
const Cli = struct {
io: Io,
stderr: *Io.Writer,
fn fail(cli: Cli, comptime fmt: []const u8, args: anytype) error{Fatal} {
cli.stderr.print("zdxc: error: " ++ fmt ++ "\n", args) catch {};
cli.stderr.flush() catch {};
return error.Fatal;
}
};
pub fn main(init: std.process.Init) !u8 { pub fn main(init: std.process.Init) !u8 {
const arena = init.arena.allocator(); const arena = init.arena.allocator();
const io = init.io; const io = init.io;
// Streaming, not positional: `2>> log` must append.
var stderr_buf: [1024]u8 = undefined; var stderr_buf: [1024]u8 = undefined;
// Streaming, not positional: `2>> log` must append.
var stderr_writer: Io.File.Writer = .initStreaming(.stderr(), io, &stderr_buf); var stderr_writer: Io.File.Writer = .initStreaming(.stderr(), io, &stderr_buf);
var stdout_buf: [4096]u8 = undefined; var stdout_buf: [4096]u8 = undefined;
var stdout_writer: Io.File.Writer = .initStreaming(.stdout(), io, &stdout_buf); var stdout_writer: Io.File.Writer = .initStreaming(.stdout(), io, &stdout_buf);
const cli: Cli = .{ .io = io, .stderr = &stderr_writer.interface };
defer stderr_writer.interface.flush() catch {}; defer stderr_writer.interface.flush() catch {};
const args = try init.minimal.args.toSlice(arena); const args = try init.minimal.args.toSlice(arena);
const code = if (job.find(args)) |at| if (job.find(args)) |at| {
try job.run(io, arena, args, at, runCommandLine, &stdout_writer.interface, &stderr_writer.interface) const code = try job.run(io, arena, args, at, compileJob, &stdout_writer.interface, &stderr_writer.interface);
else try stdout_writer.interface.flush();
runCommandLine(io, arena, args, &stdout_writer.interface, &stderr_writer.interface); return code;
try stdout_writer.interface.flush();
return code;
}
/// Runs one command line (argv[0] first) and returns its exit code, which
/// follows dxc: 1 for command-line and I/O errors, 5 when the compilation
/// reports errors.
fn runCommandLine(io: Io, arena: std.mem.Allocator, argv: []const [:0]const u8, stdout: *Io.Writer, stderr: *Io.Writer) u8 {
return runOrFail(io, arena, argv, stdout, stderr) catch |err| {
stderr.print("zdxc: error: {s}\n", .{@errorName(err)}) catch {};
stderr.flush() catch {};
return 1;
};
}
fn runOrFail(io: Io, arena: std.mem.Allocator, argv: []const [:0]const u8, stdout: *Io.Writer, stderr: *Io.Writer) !u8 {
const args = try arena.alloc([]const u8, argv.len -| 1);
for (args, argv[1..]) |*a, v| a.* = v;
const r = try zdxc.compile.compile(arena, .{
.args = args,
.io = io,
.color = Io.File.stderr().supportsAnsiEscapeCodes(io) catch false,
.require_output = true,
});
try stdout.writeAll(r.text);
try stderr.writeAll(r.diagnostics);
try stderr.flush();
if (r.status != .ok) return @intFromEnum(r.status);
if (r.object) |bytes| try write(io, stderr, r.object_name.?, bytes) orelse return 1;
if (r.root_signature) |bytes| try write(io, stderr, r.root_signature_name.?, bytes) orelse return 1;
if (r.preprocessed) |text| {
if (r.preprocessed_name) |path| try write(io, stderr, path, text) orelse return 1 else try stdout.writeAll(text);
} }
// Exit codes follow dxc: 1 for command-line and I/O errors, 5 when the
// compilation reports errors.
run(cli, arena, args, &stdout_writer.interface) catch |err| switch (err) {
error.Fatal => return 1,
error.CompileFailed => return 5,
else => return err,
};
try stdout_writer.interface.flush();
return 0; return 0;
} }
/// Writes an output file; null (after an error message) if it cannot. /// One job of a `--job` file: `run`, with its exit code.
fn write(io: Io, stderr: *Io.Writer, path: []const u8, bytes: []const u8) !?void { fn compileJob(io: Io, arena: std.mem.Allocator, args: []const [:0]const u8, stdout: *Io.Writer, stderr: *Io.Writer) u8 {
Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = bytes }) catch |err| { const cli: Cli = .{ .io = io, .stderr = stderr };
try stderr.print("zdxc: error: cannot write '{s}': {s}\n", .{ path, @errorName(err) }); run(cli, arena, args, stdout) catch |err| switch (err) {
try stderr.flush(); error.Fatal => return 1,
error.CompileFailed => return 5,
else => {
stderr.print("zdxc: error: {s}\n", .{@errorName(err)}) catch {};
return 1;
},
};
return 0;
}
/// Parse a dxc-style command line. Returns null when the command is
/// complete (`-help`, `--version`).
fn parseArgs(cli: Cli, arena: std.mem.Allocator, argv: []const [:0]const u8, stdout: *Io.Writer) !?Options {
var failure: options.Failure = .{};
const plain = try arena.alloc([]const u8, argv.len -| 1);
for (plain, 0..) |*a, i| a.* = argv[i + 1];
const parsed = options.parse(arena, plain, &failure) catch |e| switch (e) {
error.UnknownArgument => return cli.fail("unknown argument: '{s}'", .{failure.arg}),
error.MissingArgument => return cli.fail("argument to '{s}' is missing", .{failure.arg}),
error.OutOfMemory => return error.OutOfMemory,
};
var opts: Options = .{};
for (parsed.args) |a| {
switch (a.which) {
.extra => |x| switch (x) {
.zdxc_empty => opts.empty = true,
.zdxc_check_hash => opts.check_hash = true,
.zdxc_lex => opts.lex = true,
.zdxc_parse => opts.parse = true,
.zdxc_ast => {
opts.parse = true;
opts.dump_ast = true;
},
.zdxc_sema => opts.sema = true,
.zdxc_ir => opts.dump_ir = true,
.job => opts.job = a.value(),
.fcolor_diagnostics => opts.color = true,
.fno_color_diagnostics => opts.color = false,
},
.dxc => |id| {
switch (options.support(id)) {
.implemented => {},
.ignored => {
try opts.ignored.append(arena, a.spelling);
continue;
},
.unsupported => |why| return cli.fail("'{s}' is not supported: {s}", .{ a.spelling, why }),
}
const v = a.value();
switch (id) {
.target_profile => opts.profile = v,
.entrypoint => opts.entry = v,
.Fo => opts.output = v,
.Fi => opts.pp_output = v,
.D => if (std.mem.indexOfScalar(u8, v, '=')) |eq| {
try opts.defines.append(arena, .{ .name = v[0..eq], .value = v[eq + 1 ..] });
} else try opts.defines.append(arena, .{ .name = v }),
.I => try opts.include_dirs.append(arena, v),
.hlsl_version => if (!std.mem.eql(u8, v, "2021")) {
return cli.fail("HLSL version {s} is not supported; zdxc implements HLSL 2021 only", .{v});
},
.P => opts.preprocess = true,
.spirv => opts.spirv = true,
.fspv_target_env_EQ => opts.target_env = v,
.enable_16bit_types => opts.enable_16bit = true,
.Zpr => opts.row_major = true,
.Zpc => opts.col_major = true,
.force_rootsig_ver, .force_rootsig_ver_ => opts.rootsig_ver = v,
.Qstrip_rootsignature => opts.strip_rootsig = true,
.rootsig_define => opts.rootsig_define = v,
.Frs => opts.rootsig_output = v,
.fvk_b_shift, .fvk_t_shift, .fvk_s_shift, .fvk_u_shift => {
const k: usize = switch (id) {
.fvk_b_shift => 0,
.fvk_t_shift => 1,
.fvk_s_shift => 2,
else => 3,
};
const shift = std.fmt.parseInt(u32, a.values[0], 10) catch return cli.fail("invalid {s} shift '{s}'", .{ a.spelling, a.values[0] });
const set: ?u32 = if (std.mem.eql(u8, a.values[1], "all")) null else std.fmt.parseInt(u32, a.values[1], 10) catch return cli.fail("invalid {s} space '{s}'", .{ a.spelling, a.values[1] });
try opts.vk.shifts[k].append(arena, .{ .shift = shift, .set = set });
},
.fvk_bind_globals => opts.vk.bind_globals = .{
std.fmt.parseInt(u32, a.values[0], 10) catch return cli.fail("invalid -fvk-bind-globals binding number: {s}", .{a.values[0]}),
std.fmt.parseInt(u32, a.values[1], 10) catch return cli.fail("invalid -fvk-bind-globals set number: {s}", .{a.values[1]}),
},
.fvk_bind_register, .vkbr => {
const reg = a.values[0];
if (reg.len < 2 or std.mem.indexOfScalar(u8, "btsu", reg[0]) == null) return cli.fail("invalid -fvk-bind-register register '{s}'", .{reg});
const num = struct {
fn f(c: Cli, t: []const u8) !u32 {
return std.fmt.parseInt(u32, t, 10) catch c.fail("invalid -fvk-bind-register number '{s}'", .{t});
}
}.f;
try opts.vk.bind_register.append(arena, .{ .class = reg[0], .index = try num(cli, reg[1..]), .space = try num(cli, a.values[1]), .binding = try num(cli, a.values[2]), .set = try num(cli, a.values[3]) });
},
.auto_binding_space => opts.vk.auto_binding_space = std.fmt.parseInt(u32, v, 10) catch return cli.fail("invalid -auto-binding-space '{s}'", .{v}),
.fvk_auto_shift_bindings => opts.vk.auto_shift = true,
.fspv_flatten_resource_arrays => opts.vk.flatten_arrays = true,
.fspv_use_legacy_buffer_matrix_order => opts.vk.legacy_matrix_order = true,
.fspv_use_vulkan_memory_model => opts.vk.vulkan_memory_model = true,
// (zdxc never removes interface variables.)
.fspv_preserve_interface => {},
.fvk_invert_y => opts.vk.invert_y = true,
.fvk_use_gl_layout => opts.vk.layout = .gl,
.fvk_use_dx_layout => opts.vk.layout = .dx,
.fvk_use_scalar_layout => opts.vk.layout = .scalar,
.fspv_entrypoint_name_EQ => opts.vk.entry_name = v,
.fspv_extension_EQ => try opts.vk.extensions.append(arena, v),
.fspv_reflect => opts.vk.reflect = true,
.fspv_enable_maximal_reconvergence => opts.vk.maximal_reconvergence = true,
.fvk_support_nonzero_base_instance => opts.vk.nonzero_base_instance = true,
.fvk_support_nonzero_base_vertex => opts.vk.nonzero_base_vertex = true,
.fspv_use_unknown_image_format => opts.vk.unknown_image_format = true,
.fvk_use_dx_position_w => opts.vk.dx_position_w = true,
.fvk_stage_io_order_EQ => {
if (std.mem.eql(u8, v, "alpha")) opts.vk.alpha_io_order = true else if (!std.mem.eql(u8, v, "decl")) return cli.fail("unknown -fvk-stage-io-order '{s}'", .{v});
},
._SLASH_WX => opts.warnings_as_errors = true,
.no_warnings => opts.no_warnings = true,
.W_Joined => {
// -Wno-<group>, -Werror; enabling groups is a no-op.
if (std.mem.startsWith(u8, v, "no-")) {
try opts.disabled_warnings.append(arena, v[3..]);
} else if (std.mem.eql(u8, v, "error")) opts.warnings_as_errors = true;
},
.Wno_vk_ignored_features => try opts.disabled_warnings.append(arena, "vk-ignored-features"),
.Wno_vk_emulated_features => try opts.disabled_warnings.append(arena, "vk-emulated-features"),
.fdiagnostics_format_EQ => {
// dxc also accepts msvc-fallback.
const name = if (std.mem.eql(u8, v, "msvc-fallback")) "msvc" else v;
opts.diag_format = std.meta.stringToEnum(zdxc.diag.Format, name) orelse
return cli.fail("unknown diagnostics format '{s}' (expected clang, msvc or vi)", .{v});
},
.ferror_limit_EQ => opts.error_limit = std.fmt.parseInt(u32, v, 10) catch
return cli.fail("invalid -ferror-limit value '{s}'", .{v}),
.fdiagnostics_color => opts.color = true,
.fdiagnostics_color_EQ => opts.color = if (std.mem.eql(u8, v, "always"))
true
else if (std.mem.eql(u8, v, "never"))
false
else
null,
.help, ._help_question, ._help_hidden => {
try options.printHelp(stdout, id == ._help_hidden);
return null;
},
._version => {
try stdout.print("zdxc {s} (dxc-compatible command line, HLSL 2021)\n", .{zdxc.version});
return null;
},
.O0 => opts.opt_level = .o0,
.O1 => opts.opt_level = .o1,
.O2 => opts.opt_level = .o2,
.O3 => opts.opt_level = .o3,
.Od => opts.opt_level = .od,
else => {}, // implemented as a no-op (e.g. -Vd, -nologo)
}
},
}
}
if (opts.row_major and opts.col_major) return cli.fail("Cannot specify /Zpr and /Zpc together, use /? to get usage information", .{});
// Like dxc, the last input wins (dxc reads getLastArgValue(OPT_INPUT)).
if (parsed.inputs.len > 0) opts.input = parsed.inputs[parsed.inputs.len - 1];
if (opts.ignored.items.len > 0 and !opts.no_warnings) {
try cli.stderr.writeAll("zdxc: note: accepted for compatibility, no effect yet:");
for (opts.ignored.items) |sp| try cli.stderr.print(" {s}", .{sp});
try cli.stderr.writeByte('\n');
}
return opts;
}
fn run(cli: Cli, arena: std.mem.Allocator, args: []const [:0]const u8, stdout: *Io.Writer) !void {
const opts = try parseArgs(cli, arena, args, stdout) orelse return;
if (opts.job != null) return cli.fail("--job cannot be used inside a job file", .{});
if (opts.check_hash) {
const path = opts.input orelse return cli.fail("no input file", .{});
const bytes = try Io.Dir.cwd().readFileAlloc(cli.io, path, arena, .limited(1 << 30));
const view = container.parse(arena, bytes) catch return cli.fail("{s}: not a DXIL container", .{path});
if (!container.hashMatches(view.bytes)) return cli.fail("{s}: hash mismatch", .{path});
try stdout.print("{s}: hash ok ({d} parts)\n", .{ path, view.parts.items.len });
return;
}
if (opts.lex) {
const path = opts.input orelse return cli.fail("no input file", .{});
const text = try Io.Dir.cwd().readFileAlloc(cli.io, path, arena, .limited(256 << 20));
var lx = front.lexer.Lexer.init(text, 0);
while (true) {
const t = lx.next();
if (t.kind == .eof) break;
if (t.kind == .hash and t.flags.bol) {
const save = lx;
const d = lx.next();
if (d.isIdent("line")) {
lx.skipLine();
continue;
}
lx = save;
}
try stdout.print("{s}\n", .{t.text});
}
return;
}
// Root signature targets: the root signature in the macro -E names.
if (opts.profile) |p| if (std.mem.eql(u8, p, "rootsig_1_0") or std.mem.eql(u8, p, "rootsig_1_1")) {
const input = opts.input orelse return cli.fail("no input file", .{});
const out = opts.output orelse return cli.fail("missing -Fo <file>", .{});
const version: zdxc.dxil.rootsig.Version = if (std.mem.eql(u8, p, "rootsig_1_0")) .v1_0 else .v1_1;
const blob = try compileRootSignatureMacro(cli, arena, opts, input, opts.entry, version, .none) orelse return error.CompileFailed;
try Io.Dir.cwd().writeFile(cli.io, .{ .sub_path = out, .data = try rootSignatureContainer(arena, blob) });
return;
};
const profile: ?shader.Profile = if (opts.profile) |p|
shader.Profile.parse(p) orelse return cli.fail("unknown profile '{s}'", .{p})
else
null;
// The front end: everything except the development modes that work on
// containers or raw tokens.
if (!opts.empty) {
const input = opts.input orelse return cli.fail("no input file", .{});
var disk: front.source.DiskFs = .{ .io = cli.io };
var sm = front.source.SourceManager.init(arena, disk.fileSystem());
var diags = zdxc.Diagnostics.init(arena);
diags.warnings_as_errors = opts.warnings_as_errors;
diags.suppress_warnings = opts.no_warnings;
diags.error_limit = opts.error_limit;
for (opts.disabled_warnings.items) |g| try diags.disableGroup(g);
var pp = front.preproc.Preprocessor.init(arena, &sm, &diags, .{
.defines = opts.defines.items,
.include_dirs = opts.include_dirs.items,
.stage = if (profile) |p| @backingInt(p.kind) else 5,
.major = if (profile) |p| p.major else 6,
.minor = if (profile) |p| p.minor else 0,
.spirv = opts.spirv,
.spirv_minor = if (zdxc.spirv.emit.TargetEnv.parse(opts.target_env)) |t| t.minor else 0,
.enable_16bit = opts.enable_16bit,
});
var out: Io.Writer.Allocating = .init(arena);
var module: ?zdxc.ir.ir.Module = null;
const opened = try pp.enterMainFile(input);
if (opened) {
if (opts.preprocess) {
try front.pp_print.print(&pp, &out.writer);
} else {
var parser = try front.parser.Parser.fromPreprocessor(arena, &diags, &pp);
const tu = try parser.parseTranslationUnit();
if (opts.dump_ast) try front.ast_dump.dumpUnit(stdout, tu);
if (!opts.parse) {
const is_lib = if (profile) |p| p.kind == .library else true;
var sema = try zdxc.sema.Sema.init(arena, &diags, .{
.entry = if (opts.sema or is_lib) null else opts.entry,
.spirv = opts.spirv,
.enable_16bit = opts.enable_16bit,
.sm_minor = if (profile) |p| p.minor else 10,
.library = is_lib,
.root = opts.entry,
.row_major = opts.row_major,
});
try sema.checkUnit(tu);
if (!opts.sema and !diags.hasErrors() and profile != null) {
const stage: zdxc.ir.ir.Stage = switch (profile.?.kind) {
.vertex => .vertex,
.pixel => .pixel,
.geometry => .geometry,
.hull => .hull,
.domain => .domain,
.compute => .compute,
.mesh => .mesh,
.amplification => .amplification,
else => .library,
};
module = zdxc.ir.lower.lowerUnit(arena, &sema, .{ .entry = opts.entry, .stage = stage }) catch |e| switch (e) {
error.Unsupported => null,
else => |x| return x,
};
if (module) |*mm| {
mm.native_16bit = opts.enable_16bit;
mm.row_major = opts.row_major;
mm.vk = opts.vk;
mm.strip_rootsig = opts.strip_rootsig;
if (opts.rootsig_ver) |rv| {
if (std.mem.eql(u8, rv, "rootsig_1_0")) mm.rootsig_version = .v1_0 else if (!std.mem.eql(u8, rv, "rootsig_1_1")) return cli.fail("unknown root signature version '{s}'", .{rv});
}
}
}
}
}
}
const color = opts.color orelse (Io.File.stderr().supportsAnsiEscapeCodes(cli.io) catch false);
try diags.render(&sm, cli.stderr, .{ .format = opts.diag_format, .color = color });
try cli.stderr.flush();
// An unreadable input is an I/O error, as in dxc.
if (!opened) return error.Fatal;
if (diags.hasErrors()) return error.CompileFailed;
if (opts.preprocess) {
if (opts.pp_output) |path| {
try Io.Dir.cwd().writeFile(cli.io, .{ .sub_path = path, .data = out.written() });
} else try stdout.writeAll(out.written());
return;
}
if (opts.parse or opts.sema) return;
if (profile == null) return cli.fail("missing -T <profile>", .{});
if (module) |*m| {
try zdxc.ir.opt.run(arena, m);
if (opts.dump_ir) {
try zdxc.ir.ir.dump(m, stdout);
return;
}
if (opts.spirv) {
zdxc.ir.split_resources.run(arena, m, &diags) catch |err| switch (err) {
error.Unsupported => {
try diags.render(&sm, cli.stderr, .{ .format = opts.diag_format, .color = false });
try cli.stderr.flush();
return error.CompileFailed;
},
else => |x| return x,
};
const bytes = zdxc.spirv.emit.emit(arena, m, &diags, zdxc.spirv.emit.TargetEnv.parse(opts.target_env) orelse return cli.fail("unknown SPIR-V target environment '{s}'", .{opts.target_env})) catch |err| switch (err) {
error.Unsupported => {
try diags.render(&sm, cli.stderr, .{ .format = opts.diag_format, .color = false });
try cli.stderr.flush();
return error.CompileFailed;
},
else => |x| return x,
};
const path = opts.output orelse return cli.fail("missing -Fo <file>", .{});
try Io.Dir.cwd().writeFile(cli.io, .{ .sub_path = path, .data = bytes });
return;
}
// -rootsig-define: the macro's root signature for the entry.
if (opts.rootsig_define) |macro| if (m.entries.items.len == 1) {
m.entries.items[0].root_signature = try rootSignatureMacroText(cli, arena, opts, input, macro) orelse return error.CompileFailed;
};
const bytes = zdxc.dxil.emit.emit(arena, m, profile.?, &diags) catch |err| switch (err) {
error.Unsupported => {
try diags.render(&sm, cli.stderr, .{ .format = opts.diag_format, .color = false });
try cli.stderr.flush();
return error.CompileFailed;
},
else => |x| return x,
};
const path = opts.output orelse return cli.fail("missing -Fo <file>", .{});
try Io.Dir.cwd().writeFile(cli.io, .{ .sub_path = path, .data = bytes });
if (opts.rootsig_output) |rs_path| {
const text = (if (m.entries.items.len == 1) m.entries.items[0].root_signature else null) orelse return cli.fail("-Frs: the shader has no root signature", .{});
var d: zdxc.dxil.rootsig.Diagnostic = .{};
const blob = try zdxc.dxil.rootsig.compileWithOptions(arena, text, .{ .version = if (m.rootsig_version == .v1_0) .v1_0 else .v1_1, .flags = .global }, &d) orelse return cli.fail("root signature error - {s}", .{d.message()});
try Io.Dir.cwd().writeFile(cli.io, .{ .sub_path = rs_path, .data = try rootSignatureContainer(arena, blob) });
}
return;
}
return cli.fail("code generation is not implemented yet: the input was checked but no output was written (use -zdxc-empty for a placeholder shader)", .{});
}
const prof = profile orelse return cli.fail("missing -T <profile>", .{});
if (!opts.empty) return cli.fail("compiling HLSL is not implemented yet (use -P or -zdxc-empty)", .{});
if (prof.kind != .compute) return cli.fail("-zdxc-empty supports compute profiles only", .{});
const bytes = if (opts.spirv)
try zdxc.spirv.builder.buildEmptyCompute(arena, .{ .entry = opts.entry, .num_threads = .{ 1, 1, 1 } })
else
try shader.buildEmptyCompute(arena, .{ .entry = opts.entry, .profile = prof, .num_threads = .{ 1, 1, 1 } });
const out = opts.output orelse return cli.fail("missing -Fo <file>", .{});
try Io.Dir.cwd().writeFile(cli.io, .{ .sub_path = out, .data = bytes });
}
/// The text of the root signature macro `macro` defines in `input` (its
/// string literals concatenated), or null after reporting an error.
fn rootSignatureMacroText(cli: Cli, arena: std.mem.Allocator, opts: Options, input: []const u8, macro: []const u8) !?[]const u8 {
const text = try Io.Dir.cwd().readFileAlloc(cli.io, input, arena, .limited(256 << 20));
var disk: front.source.DiskFs = .{ .io = cli.io };
var sm = front.source.SourceManager.init(arena, disk.fileSystem());
var diags = zdxc.Diagnostics.init(arena);
var pp = front.preproc.Preprocessor.init(arena, &sm, &diags, .{
.defines = opts.defines.items,
.include_dirs = opts.include_dirs.items,
.stage = 6,
});
// Expand the macro after a marker at the end of the file.
const marker = "__zdxc_root_signature__";
try pp.enterMainText(input, try std.mem.concat(arena, u8, &.{ text, "\n" ++ marker ++ " ", macro, "\n" }));
var parts: std.ArrayList(u8) = .empty;
var seen = false;
var any = false;
while (true) {
const t = try pp.next();
if (t.kind == .eof) break;
if (!seen) {
seen = t.kind == .identifier and std.mem.eql(u8, t.text, marker);
continue;
}
if (t.kind != .string) {
_ = diags.report(.{ .severity = .@"error", .loc = t.loc }, "root signature macro '{s}' must expand to string literals", .{macro});
break;
}
any = true;
try parts.appendSlice(arena, try zdxc.ir.lower.stringContents(arena, t.text));
}
if (!any and !diags.hasErrors()) _ = diags.report(.{ .severity = .@"error", .loc = .none }, "root signature macro '{s}' is not defined", .{macro});
if (diags.hasErrors()) {
try diags.render(&sm, cli.stderr, .{ .format = opts.diag_format, .color = false });
try cli.stderr.flush();
return null;
}
return parts.items;
}
fn compileRootSignatureMacro(cli: Cli, arena: std.mem.Allocator, opts: Options, input: []const u8, macro: []const u8, version: zdxc.dxil.rootsig.Version, flags: zdxc.dxil.rootsig.CompilationFlags) !?[]const u8 {
const text = try rootSignatureMacroText(cli, arena, opts, input, macro) orelse return null;
var d: zdxc.dxil.rootsig.Diagnostic = .{};
return try zdxc.dxil.rootsig.compileWithOptions(arena, text, .{ .version = version, .flags = flags }, &d) orelse {
try cli.stderr.print("{s}: error: root signature error - {s}\n", .{ input, d.message() });
try cli.stderr.flush();
return null; return null;
}; };
} }
/// A container holding only the root signature (RTS0) part.
fn rootSignatureContainer(arena: std.mem.Allocator, blob: []const u8) ![]u8 {
return zdxc.dxil.container.assemble(arena, &.{.{ .fourcc = zdxc.dxil.container.fourcc("RTS0"), .data = blob }});
}

View File

@ -168,14 +168,10 @@ fn parseOne(arena: Allocator, argv: []const []const u8, index: *usize, failure:
return .{ .which = c.which, .spelling = spelling, .values = vals.items }; return .{ .which = c.which, .spelling = spelling, .values = vals.items };
}, },
.separate, .joined_or_separate => { .separate, .joined_or_separate => {
// dxc also takes "-opt value" passed as one argument: spaces if (rest.len != 0) {
// after the name are skipped, and all-space rest means the if (c.kind == .separate) continue;
// value is the next argument.
const value = std.mem.trimStart(u8, rest, " ");
if (value.len != 0) {
if (c.kind == .separate and value.len == rest.len) continue;
index.* += 1; index.* += 1;
return .{ .which = c.which, .spelling = spelling, .values = try dupeOne(arena, value) }; return .{ .which = c.which, .spelling = spelling, .values = try dupeOne(arena, rest) };
} }
if (index.* + 1 >= argv.len) { if (index.* + 1 >= argv.len) {
failure.arg = spelling; failure.arg = spelling;

View File

@ -2,7 +2,6 @@
pub const diag = @import("diag.zig"); pub const diag = @import("diag.zig");
pub const options = @import("options.zig"); pub const options = @import("options.zig");
pub const compile = @import("compile.zig");
pub const Diagnostics = diag.Diagnostics; pub const Diagnostics = diag.Diagnostics;
pub const front = struct { pub const front = struct {

View File

@ -28,31 +28,6 @@ pub const Error = Allocator.Error || error{Unsupported};
/// Marks a binding that is a recipe (see Emitter.resourceBinding). /// Marks a binding that is a recipe (see Emitter.resourceBinding).
const recipe_tag: u32 = 0x8000_0000; const recipe_tag: u32 = 0x8000_0000;
const Recipe = struct {
var_id: Id,
ptr_ty: Id,
indices: []const Id,
dyn_types: []const Id = &.{},
/// The element is selected non-uniformly (NonUniformResourceIndex).
nonuniform: bool = false,
res_ty: TypeId = 0,
};
/// A resource local assigned different elements of one resource array
/// (`tex = textures[i]` in several branches): a variable per index.
const IndexedLocal = struct {
global: Ref,
index_types: []const TypeId,
vars: []Id = &.{},
nonuniform: bool = false,
};
const IndexedLoad = struct { global: Ref, indices: []const Id, types: []const TypeId, nonuniform: bool };
/// A resource argument: what the callee's parameter is bound to, and the
/// values of its recipe's dynamic indices (passed as extra arguments).
const Binding = struct { id: Id, dyn: []const Id = &.{} };
const StorageClass = enum(u32) { uniform_constant = 0, input = 1, uniform = 2, output = 3, workgroup = 4, private = 6, function = 7, image = 11, storage_buffer = 12, task_payload_workgroup = 5402, callable_data_khr = 5328, incoming_callable_data_khr = 5329, ray_payload_khr = 5338, hit_attribute_khr = 5339, incoming_ray_payload_khr = 5342, shader_record_buffer_khr = 5343, push_constant = 9, physical_storage_buffer = 5349 }; const StorageClass = enum(u32) { uniform_constant = 0, input = 1, uniform = 2, output = 3, workgroup = 4, private = 6, function = 7, image = 11, storage_buffer = 12, task_payload_workgroup = 5402, callable_data_khr = 5328, incoming_callable_data_khr = 5329, ray_payload_khr = 5338, hit_attribute_khr = 5339, incoming_ray_payload_khr = 5342, shader_record_buffer_khr = 5343, push_constant = 9, physical_storage_buffer = 5349 };
const Capability = enum(u32) { const Capability = enum(u32) {
@ -228,19 +203,8 @@ const Emitter = struct {
variants: std.ArrayList(struct { fi: u32, bindings: []const Id, id: Id }) = .empty, variants: std.ArrayList(struct { fi: u32, bindings: []const Id, id: Id }) = .empty,
/// The bindings of the function being emitted (a specialization). /// The bindings of the function being emitted (a specialization).
cur_bindings: []const Id = &.{}, cur_bindings: []const Id = &.{},
/// Per instruction (current function): resource locals assigned /// Resource array elements bound to specialized parameters.
/// elements of one resource array, kept as their indices. recipes: std.ArrayList(struct { var_id: Id, ptr_ty: Id, indices: []const Id }) = .empty,
indexed_locals: std.AutoHashMapUnmanaged(u32, IndexedLocal) = .empty,
/// Per instruction (current function): reads of those locals, with the
/// loaded indices.
indexed_loads: std.AutoHashMapUnmanaged(u32, IndexedLoad) = .empty,
/// The extra parameters of the function being emitted that carry the
/// dynamic indices of its recipe bindings, per parameter.
cur_dyn: []const []const Id = &.{},
/// Resource array elements bound to specialized parameters. A dynamic
/// index is 0 in `indices`; the specialization takes it as an extra
/// parameter of the type in `dyn_types`.
recipes: std.ArrayList(Recipe) = .empty,
payload_global: ?u32 = null, payload_global: ?u32 = null,
/// Per instruction (current function): places in mesh output arrays. /// Per instruction (current function): places in mesh output arrays.
mesh_places: std.AutoHashMapUnmanaged(u32, MeshPlace) = .empty, mesh_places: std.AutoHashMapUnmanaged(u32, MeshPlace) = .empty,
@ -1925,126 +1889,49 @@ const Emitter = struct {
/// What a resource argument binds a specialized callee's parameter /// What a resource argument binds a specialized callee's parameter
/// to: a module variable, or (an element of a resource array) a /// to: a module variable, or (an element of a resource array) a
/// recipe the callee re-creates: `recipe_tag | index` into `recipes`. /// recipe the callee re-creates: `recipe_tag | index` into `recipes`.
fn resourceBinding(e: *Emitter, a: Ref) Error!Binding { fn resourceBinding(e: *Emitter, a: Ref) Error!Id {
const f = e.f; const f = e.f;
var x = a; var x = a;
while (true) switch (f.inst(x).op) { while (true) switch (f.inst(x).op) {
.load => |p| { .load => |p| x = p,
// A read of an indexed local: its element, all indices dynamic.
if (e.indexed_loads.get(x.index())) |il| {
const idx = try e.arena.alloc(Id, il.indices.len);
@memset(idx, 0);
const dyn_types = try e.arena.alloc(Id, il.types.len);
for (dyn_types, il.types) |*d, ty| d.* = try e.typeId(ty);
const p_ = try e.resourcePointee(f.inst(x).ty);
const id = try e.addRecipe(.{ .var_id = e.val(il.global), .ptr_ty = try e.pointerType(p_.sc, p_.ty), .indices = idx, .dyn_types = dyn_types, .nonuniform = il.nonuniform, .res_ty = f.inst(x).ty });
return .{ .id = id, .dyn = il.indices };
}
x = p;
},
// A resource local: what was stored into it. // A resource local: what was stored into it.
.local_var => x = for (f.insts.items) |inst| { .local_var => x = for (f.insts.items) |inst| {
if (inst.op == .store and inst.op.store.ptr == x) break inst.op.store.value; if (inst.op == .store and inst.op.store.ptr == x) break inst.op.store.value;
} else return .{ .id = e.val(x) }, } else return e.val(x),
else => break, else => break,
}; };
switch (f.inst(x).op) { switch (f.inst(x).op) {
.global => return .{ .id = e.val(x) }, .global => return e.val(x),
.heap_resource => |h| { .heap_resource => |h| {
// A heap element at a constant index. // A heap element at a constant index.
if (f.inst(h.index).op != .constant) return e.unsupported("passing a resource from a descriptor heap at a dynamic index to a function is not supported yet", .{}); if (f.inst(h.index).op != .constant) return e.unsupported("passing a resource from a descriptor heap at a dynamic index to a function is not supported yet", .{});
const p = try e.resourcePointee(f.inst(x).ty); const p = try e.resourcePointee(f.inst(x).ty);
const hv = e.heap_vars.get(.{ h.sampler, p.ty }) orelse return e.unsupported("internal: heap variable missing", .{}); const hv = e.heap_vars.get(.{ h.sampler, p.ty }) orelse return e.unsupported("internal: heap variable missing", .{});
return .{ .id = try e.addRecipe(.{ .var_id = hv, .ptr_ty = try e.pointerType(p.sc, p.ty), .indices = try e.arena.dupe(Id, &.{e.val(h.index)}) }) }; return e.addRecipe(hv, try e.pointerType(p.sc, p.ty), try e.arena.dupe(Id, &.{e.val(h.index)}));
},
// A specialized parameter passes on what it is bound to (and
// the dynamic indices it received).
.param => |pi| {
if (pi >= e.cur_bindings.len or e.cur_bindings[pi] == 0) return .{ .id = e.val(x) };
return .{ .id = e.cur_bindings[pi], .dyn = if (pi < e.cur_dyn.len) e.cur_dyn[pi] else &.{} };
}, },
// A specialized parameter passes on what it is bound to.
.param => |pi| return if (pi < e.cur_bindings.len and e.cur_bindings[pi] != 0) e.cur_bindings[pi] else e.val(x),
.access => |acc| { .access => |acc| {
var base = acc.base; var base = acc.base;
while (f.inst(base).op == .load) base = f.inst(base).op.load; while (f.inst(base).op == .load) base = f.inst(base).op.load;
if (f.inst(base).op != .global) return e.unsupported("passing this resource to a function is not supported yet", .{}); if (f.inst(base).op != .global) return e.unsupported("passing this resource to a function is not supported yet", .{});
if (e.flat_vars.contains(f.inst(base).op.global)) {
for (acc.indices) |r| if (f.inst(r).op != .constant) return e.unsupported("passing a dynamically selected resource to a function is not supported yet", .{});
}
// Constant indices are part of the recipe; dynamic ones are
// passed along to the specialization.
const idx = try e.arena.alloc(Id, acc.indices.len); const idx = try e.arena.alloc(Id, acc.indices.len);
var dyn_types: std.ArrayList(Id) = .empty;
var dyn: std.ArrayList(Id) = .empty;
var nonuniform = false;
for (idx, acc.indices) |*d, r| { for (idx, acc.indices) |*d, r| {
if (f.inst(r).op == .constant) { if (f.inst(r).op != .constant) return e.unsupported("passing a dynamically selected resource to a function is not supported yet", .{});
d.* = e.val(r); d.* = e.val(r);
continue;
}
d.* = 0;
try dyn_types.append(e.arena, try e.typeId(f.inst(r).ty));
try dyn.append(e.arena, e.val(r));
if (e.nonuniform_ids.contains(e.val(r))) nonuniform = true;
} }
const p = try e.resourcePointee(f.inst(x).ty); const p = try e.resourcePointee(f.inst(x).ty);
const id = try e.addRecipe(.{ .var_id = e.val(base), .ptr_ty = try e.pointerType(p.sc, p.ty), .indices = idx, .dyn_types = dyn_types.items, .nonuniform = nonuniform, .res_ty = f.inst(x).ty }); return e.addRecipe(e.val(base), try e.pointerType(p.sc, p.ty), idx);
return .{ .id = id, .dyn = dyn.items };
}, },
else => return .{ .id = e.val(x) }, else => return e.val(x),
} }
} }
/// The element access a resource value is (through loads), when it is fn addRecipe(e: *Emitter, var_id: Id, ptr_ty: Id, idx: []const Id) Error!Id {
/// an element of a module-level resource array.
fn resourceElement(e: *Emitter, v: Ref) ?@FieldType(ir.Op, "access") {
const f = e.f;
var x = v;
while (f.inst(x).op == .load) x = f.inst(x).op.load;
if (f.inst(x).op != .access) return null;
const acc = f.inst(x).op.access;
var base = acc.base;
while (f.inst(base).op == .load) base = f.inst(base).op.load;
if (f.inst(base).op != .global) return null;
return .{ .base = base, .indices = acc.indices };
}
/// Finds the resource locals of `f` assigned different elements of
/// one resource array, which keep their indices instead of aliasing
/// one resource.
fn findIndexedLocals(e: *Emitter, f: *const ir.Function) Error!void {
for (f.insts.items, 0..) |inst, li| {
if (inst.op != .local_var or !isResourceType(e.t, inst.ty) or e.t.get(inst.ty) == .array) continue;
const local: Ref = @enumFromInt(li);
var first: ?@FieldType(ir.Op, "access") = null;
var first_value: Ref = .none;
var distinct = false;
const ok = scan: for (f.insts.items) |st| {
if (st.op != .store or st.op.store.ptr != local) continue;
const acc = e.resourceElement(st.op.store.value) orelse break :scan false;
if (first) |fa| {
if (st.op.store.value != first_value) distinct = true;
if (f.inst(fa.base).op.global != f.inst(acc.base).op.global or fa.indices.len != acc.indices.len) break :scan false;
for (fa.indices, acc.indices) |p, q| if (f.inst(p).ty != f.inst(q).ty) break :scan false;
} else {
first = acc;
first_value = st.op.store.value;
}
} else true;
if (!ok or !distinct) continue;
const fa = first.?;
if (e.flat_vars.contains(f.inst(fa.base).op.global)) continue;
const tys = try e.arena.alloc(TypeId, fa.indices.len);
for (tys, fa.indices) |*t, x| t.* = f.inst(x).ty;
try e.indexed_locals.put(e.arena, @intCast(li), .{ .global = fa.base, .index_types = tys });
}
}
fn addRecipe(e: *Emitter, r: Recipe) Error!Id {
for (e.recipes.items, 0..) |rc, k| { for (e.recipes.items, 0..) |rc, k| {
if (rc.var_id == r.var_id and rc.ptr_ty == r.ptr_ty and std.mem.eql(Id, rc.indices, r.indices) and if (rc.var_id == var_id and rc.ptr_ty == ptr_ty and std.mem.eql(Id, rc.indices, idx)) return recipe_tag | @as(Id, @intCast(k));
std.mem.eql(Id, rc.dyn_types, r.dyn_types) and rc.nonuniform == r.nonuniform) return recipe_tag | @as(Id, @intCast(k));
} }
try e.recipes.append(e.arena, r); try e.recipes.append(e.arena, .{ .var_id = var_id, .ptr_ty = ptr_ty, .indices = idx });
return recipe_tag | @as(Id, @intCast(e.recipes.items.len - 1)); return recipe_tag | @as(Id, @intCast(e.recipes.items.len - 1));
} }
@ -2063,9 +1950,6 @@ const Emitter = struct {
e.cur_bindings = bindings; e.cur_bindings = bindings;
e.texel_places = .empty; e.texel_places = .empty;
e.mesh_places = .empty; e.mesh_places = .empty;
e.indexed_locals = .empty;
e.indexed_loads = .empty;
try e.findIndexedLocals(f);
e.vals = try e.arena.alloc(Id, f.insts.items.len); e.vals = try e.arena.alloc(Id, f.insts.items.len);
@memset(e.vals, 0); @memset(e.vals, 0);
e.ptr_layouts = try e.arena.alloc(?PtrLayout, f.insts.items.len); e.ptr_layouts = try e.arena.alloc(?PtrLayout, f.insts.items.len);
@ -2088,9 +1972,6 @@ const Emitter = struct {
} }
try params.append(e.arena, if (p.by_ref) try e.pointerType(if (p.groupshared) .workgroup else .function, t) else t); try params.append(e.arena, if (p.by_ref) try e.pointerType(if (p.groupshared) .workgroup else .function, t) else t);
} }
// The dynamic indices of recipe bindings: extra parameters, last.
const n_plain = params.items.len;
for (bindings) |bd| if (bd & recipe_tag != 0) try params.appendSlice(e.arena, e.recipes.items[bd & ~recipe_tag].dyn_types);
const fn_ty = try e.functionType(ret, params.items); const fn_ty = try e.functionType(ret, params.items);
try e.b.emit(.functions, .function, &.{ ret, fn_id, 0, fn_ty }); try e.b.emit(.functions, .function, &.{ ret, fn_id, 0, fn_ty });
const param_ids = try e.arena.alloc(Id, f.params.len); const param_ids = try e.arena.alloc(Id, f.params.len);
@ -2110,22 +1991,6 @@ const Emitter = struct {
next += 1; next += 1;
try e.b.emitWithString(.debug_names, .name, &.{id.*}, p.name, &.{}); try e.b.emitWithString(.debug_names, .name, &.{id.*}, p.name, &.{});
} }
const cur_dyn = try e.arena.alloc([]const Id, bindings.len);
next = n_plain;
for (bindings, cur_dyn) |bd, *ids| {
ids.* = &.{};
if (bd & recipe_tag == 0) continue;
const rc = e.recipes.items[bd & ~recipe_tag];
const dyn_ids = try e.arena.alloc(Id, rc.dyn_types.len);
for (dyn_ids) |*id| {
id.* = e.b.newId();
try e.b.emit(.functions, .function_parameter, &.{ params.items[next], id.* });
next += 1;
if (rc.nonuniform) try e.nonuniform_ids.put(e.arena, id.*, {});
}
ids.* = dyn_ids;
}
e.cur_dyn = cur_dyn;
const order = try blockOrder(e.arena, f); const order = try blockOrder(e.arena, f);
const labels = try e.arena.alloc(Id, f.blocks.items.len); const labels = try e.arena.alloc(Id, f.blocks.items.len);
@ -2159,29 +2024,12 @@ const Emitter = struct {
e.vals[i] = e.b.newId(); e.vals[i] = e.b.newId();
try e.b.emit(.functions, .variable, &.{ ptr, e.vals[i], @backingInt(StorageClass.function) }); try e.b.emit(.functions, .variable, &.{ ptr, e.vals[i], @backingInt(StorageClass.function) });
}; };
var il_it = e.indexed_locals.valueIterator();
while (il_it.next()) |il| {
il.vars = try e.arena.alloc(Id, il.index_types.len);
for (il.vars, il.index_types) |*v, ty| {
v.* = e.b.newId();
try e.b.emit(.functions, .variable, &.{ try e.pointerType(.function, try e.typeId(ty)), v.*, @backingInt(StorageClass.function) });
}
}
for (bindings, 0..) |bd, k| if (bd & recipe_tag != 0) { for (bindings, 0..) |bd, k| if (bd & recipe_tag != 0) {
const rc = e.recipes.items[bd & ~recipe_tag]; const rc = e.recipes.items[bd & ~recipe_tag];
var ops: std.ArrayList(u32) = .empty; var ops: std.ArrayList(u32) = .empty;
try ops.appendSlice(e.arena, &.{ rc.ptr_ty, param_ids[k], rc.var_id }); try ops.appendSlice(e.arena, &.{ rc.ptr_ty, param_ids[k], rc.var_id });
var d: usize = 0; try ops.appendSlice(e.arena, rc.indices);
for (rc.indices) |x| {
if (x != 0) {
try ops.append(e.arena, x);
continue;
}
try ops.append(e.arena, cur_dyn[k][d]);
d += 1;
}
try e.b.emit(.functions, .access_chain, ops.items); try e.b.emit(.functions, .access_chain, ops.items);
if (rc.nonuniform) try e.markNonUniform(param_ids[k], rc.res_ty);
}; };
} }
const blk = f.blocks.items[bi]; const blk = f.blocks.items[bi];
@ -2382,22 +2230,6 @@ const Emitter = struct {
} }
// Resources stay as their variables (accessed by chains). // Resources stay as their variables (accessed by chains).
if (i.ptr == .none and (e.t.get(i.ty) == .resource or e.t.get(i.ty) == .sampler or (e.t.get(i.ty) == .array and isResourceType(e.t, i.ty)))) { if (i.ptr == .none and (e.t.get(i.ty) == .resource or e.t.get(i.ty) == .sampler or (e.t.get(i.ty) == .array and isResourceType(e.t, i.ty)))) {
if (e.indexed_locals.get(p.index())) |il| {
const idx = try e.arena.alloc(Id, il.vars.len);
for (idx, il.vars, il.index_types) |*d, v, ty| d.* = try e.op1(.load, ty, &.{v});
e.format_override = e.formatFor(il.global);
const pt = try e.resourcePointee(i.ty);
e.format_override = null;
var ops: std.ArrayList(u32) = .empty;
const id = e.b.newId();
try ops.appendSlice(e.arena, &.{ try e.pointerType(pt.sc, pt.ty), id, e.val(il.global) });
try ops.appendSlice(e.arena, idx);
try e.b.emit(.functions, .access_chain, ops.items);
if (il.nonuniform) try e.markNonUniform(id, i.ty);
e.vals[ri] = id;
try e.indexed_loads.put(e.arena, @intCast(ri), .{ .global = il.global, .indices = idx, .types = il.index_types, .nonuniform = il.nonuniform });
return;
}
if (e.val(p) == 0 and f.inst(p).op == .local_var) return e.unsupported("a resource local read before it is assigned", .{}); if (e.val(p) == 0 and f.inst(p).op == .local_var) return e.unsupported("a resource local read before it is assigned", .{});
e.vals[ri] = e.val(p); e.vals[ri] = e.val(p);
return; return;
@ -2427,14 +2259,6 @@ const Emitter = struct {
if (e.val(s.value) == e.val(s.ptr)) return; if (e.val(s.value) == e.val(s.ptr)) return;
return e.unsupported("assigning another resource to a global resource", .{}); return e.unsupported("assigning another resource to a global resource", .{});
} }
if (e.indexed_locals.getPtr(s.ptr.index())) |il| {
const acc = e.resourceElement(s.value).?;
for (il.vars, acc.indices) |v, x| {
if (e.nonuniform_ids.contains(e.val(x))) il.nonuniform = true;
try e.b.emit(.functions, .store, &.{ v, e.val(x) });
}
return;
}
if (target.op == .local_var and isResourceType(e.t, target.ty)) { if (target.op == .local_var and isResourceType(e.t, target.ty)) {
const old = e.vals[s.ptr.index()]; const old = e.vals[s.ptr.index()];
if (old != 0 and old != e.val(s.value)) return e.unsupported("assigning different resources to one variable is not supported yet", .{}); if (old != 0 and old != e.val(s.value)) return e.unsupported("assigning different resources to one variable is not supported yet", .{});
@ -2751,23 +2575,11 @@ const Emitter = struct {
const callee = e.m.functions.items[c.func]; const callee = e.m.functions.items[c.func];
if (e.hasResourceParams(callee)) { if (e.hasResourceParams(callee)) {
const bindings = try e.arena.alloc(Id, c.args.len); const bindings = try e.arena.alloc(Id, c.args.len);
var dyn: std.ArrayList(Id) = .empty; for (callee.params, c.args, bindings) |p, a, *bd| bd.* = if (isResourceType(e.t, p.ty)) try e.resourceBinding(a) else 0;
for (callee.params, c.args, bindings) |p, a, *bd| {
if (!isResourceType(e.t, p.ty)) {
bd.* = 0;
continue;
}
const b = try e.resourceBinding(a);
bd.* = b.id;
try dyn.appendSlice(e.arena, b.dyn);
}
const vid = try e.variantFor(c.func, bindings); const vid = try e.variantFor(c.func, bindings);
try e.recordCall(vid); try e.recordCall(vid);
try ops.append(e.arena, vid); try ops.append(e.arena, vid);
for (callee.params, c.args) |p, a| if (!isResourceType(e.t, p.ty)) try ops.append(e.arena, e.val(a)); for (callee.params, c.args) |p, a| if (!isResourceType(e.t, p.ty)) try ops.append(e.arena, e.val(a));
// The dynamic indices of recipe bindings, after the
// other arguments.
try ops.appendSlice(e.arena, dyn.items);
e.vals[ri] = try e.op1(.function_call, i.ty, ops.items); e.vals[ri] = try e.op1(.function_call, i.ty, ops.items);
return; return;
} }