diff --git a/build.zig b/build.zig index 73d2843..8803a64 100644 --- a/build.zig +++ b/build.zig @@ -43,8 +43,10 @@ pub fn build(b: *std.Build) void { mod.addAnonymousImport("options_table", .{ .root_source_file = options_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(.{ - .name = "zdxc", + .name = "zdxc-cli", .root_module = b.createModule(.{ .root_source_file = b.path("src/main.zig"), .target = target, @@ -52,7 +54,26 @@ pub fn build(b: *std.Build) void { .imports = &.{.{ .name = "zdxc", .module = mod }}, }), }); - b.installArtifact(exe); + const exe_name = if (target.result.os.tag == .windows) "zdxc.exe" else "zdxc"; + 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); const run_step = b.step("run", "Run zdxc"); const run_cmd = b.addRunArtifact(exe); diff --git a/build.zig.zon b/build.zig.zon index 9ef2d76..4e8700d 100644 --- a/build.zig.zon +++ b/build.zig.zon @@ -9,6 +9,7 @@ "build.zig", "build.zig.zon", "docs", + "include", "src", "tools", "vendor", diff --git a/docs/c-api.md b/docs/c-api.md new file mode 100644 index 0000000..3e27619 --- /dev/null +++ b/docs/c-api.md @@ -0,0 +1,82 @@ +# 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 + +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. diff --git a/include/zdxc.h b/include/zdxc.h new file mode 100644 index 0000000..0d9e00d --- /dev/null +++ b/include/zdxc.h @@ -0,0 +1,120 @@ +/* + * 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 +#include + +#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 */ diff --git a/src/capi.zig b/src/capi.zig new file mode 100644 index 0000000..0fb2bd8 --- /dev/null +++ b/src/capi.zig @@ -0,0 +1,131 @@ +//! 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; +} diff --git a/src/compile.zig b/src/compile.zig new file mode 100644 index 0000000..95a1c03 --- /dev/null +++ b/src/compile.zig @@ -0,0 +1,603 @@ +//! 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, +}; + +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 ", .{}); + } +}; + +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=`: 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-, -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) { + 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 ", .{}); + 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 ", .{}); + 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 }}); +} \ No newline at end of file diff --git a/src/main.zig b/src/main.zig index c4fdad2..6cf52ee 100644 --- a/src/main.zig +++ b/src/main.zig @@ -1,524 +1,67 @@ +//! The dxc-compatible command line: `compile` from the library, with the +//! outputs written to the files the options name. + const std = @import("std"); const Io = std.Io; 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 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=` (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 { const arena = init.arena.allocator(); const io = init.io; - var stderr_buf: [1024]u8 = undefined; // Streaming, not positional: `2>> log` must append. + var stderr_buf: [1024]u8 = undefined; var stderr_writer: Io.File.Writer = .initStreaming(.stderr(), io, &stderr_buf); var stdout_buf: [4096]u8 = undefined; 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 {}; const args = try init.minimal.args.toSlice(arena); - if (job.find(args)) |at| { - const code = try job.run(io, arena, args, at, compileJob, &stdout_writer.interface, &stderr_writer.interface); - try stdout_writer.interface.flush(); - return code; - } - // 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, - }; + const code = if (job.find(args)) |at| + try job.run(io, arena, args, at, runCommandLine, &stdout_writer.interface, &stderr_writer.interface) + else + runCommandLine(io, arena, args, &stdout_writer.interface, &stderr_writer.interface); try stdout_writer.interface.flush(); - return 0; + return code; } -/// One job of a `--job` file: `run`, with its exit code. -fn compileJob(io: Io, arena: std.mem.Allocator, args: []const [:0]const u8, stdout: *Io.Writer, stderr: *Io.Writer) u8 { - const cli: Cli = .{ .io = io, .stderr = stderr }; - run(cli, arena, args, stdout) catch |err| switch (err) { - error.Fatal => return 1, - error.CompileFailed => return 5, - else => { - stderr.print("zdxc: error: {s}\n", .{@errorName(err)}) catch {}; - return 1; - }, +/// 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; }; - 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-, -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 ", .{}); - 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 ", .{}); - 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 ", .{}); - 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 ", .{}); - 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 ", .{}); - 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 ", .{}); - 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, +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, }); - // 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)); + 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); } - 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; + return 0; } -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(); +/// Writes an output file; null (after an error message) if it cannot. +fn write(io: Io, stderr: *Io.Writer, path: []const u8, bytes: []const u8) !?void { + Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = bytes }) catch |err| { + try stderr.print("zdxc: error: cannot write '{s}': {s}\n", .{ path, @errorName(err) }); + try stderr.flush(); 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 }}); -} diff --git a/src/root.zig b/src/root.zig index 98c1c28..efd87d2 100644 --- a/src/root.zig +++ b/src/root.zig @@ -2,6 +2,7 @@ pub const diag = @import("diag.zig"); pub const options = @import("options.zig"); +pub const compile = @import("compile.zig"); pub const Diagnostics = diag.Diagnostics; pub const front = struct {