Compare commits

...

14 Commits

Author SHA1 Message Date
Peterino2 76a41b790b Merge branch 'ue-workgroups' 2026-11-04 08:51:52 -07:00
Peterino2 0ba9de16fa documentation updates 2026-11-04 08:51:40 -07:00
Peter Li 68f9a9d061
Merge pull request #3 from peterino2/ue-workgroups
Ue workgroups
2026-11-04 01:03:32 -07:00
peterino2 eeb5a3fcd1 Merge open-engine-fixes: kajiya and Sascha Willems' samples 2026-11-03 23:01:37 -08:00
peterino2 8d3026b57e Drop-in: IDxcCompiler/IDxcCompiler2; SPIR-V: unassigned resource reads
- dxcapi: the legacy IDxcCompiler and IDxcCompiler2 interfaces (Compile,
  Preprocess, CompileWithDebug) on the compiler object, as hassle-rs and
  other older clients call them: entry point, profile and DxcDefines become
  -E / -T / -D, the source blob is decoded by its encoding, and the result
  is the IDxcResult (an IDxcOperationResult). kajiya's view app now runs on
  zdxc's dxcompiler.dll unchanged.
- SPIR-V: a resource local nothing assigns (a struct copied with a
  resource member left unset, read only behind a flag dxc's legalization
  folds) reads as undefined: copies pass it on without assigning, and a
  real use takes a resource global of the same type (an OpUndef pointer
  would break logical addressing). kajiya's rtdgi/restir_spatial compiles.
- SPIR-V: globalOf gives up after 256 steps through copies between
  resource locals, which can form cycles.

kajiya 77 of 78 compile (dxc 77), Sascha Willems' samples 307 of 308
(dxc 307), every object valid.
2026-11-03 22:59:17 -08:00
peterino2 992307e183 README: Unreal's editor compiles its startup shaders 4.3 times faster 2026-11-03 22:48:05 -08:00
peterino2 24bdbfe7e9 sema: a vector size shared by intrinsic arguments takes the widest
`dot(1, v)` bound dot's `numeric<c>` size from its first argument, a
scalar: c = 1, and v converted to a float (its x). dxc splats the scalar
to v's size instead, and so does zdxc now, for every intrinsic whose
arguments share a symbolic size (dot, distance, reflect, faceforward...).

Unreal decodes every instance's rotation with `dot(1, abs(Oct))`
(HemiOctahedronToUnitVector): StarterMap's beams were drawn rotated, or
not where they belong. 3,666 of Unreal's 11,488 compiles change.
2026-11-03 22:45:45 -08:00
peterino2 886b64da89 Open engine corpora: kajiya and Sascha Willems' samples
Fixes from replaying kajiya's and SaschaWillems/Vulkan's HLSL through the
drop-in against dxc 1.7.2308:

- parser: `const` after the type (`float const x`, `uint const pass`)
  joins the declaration's qualifiers.
- sema: binary integer literals (`0b10u`).
- sema: a function template instance's default argument that does not
  convert to its parameter is an error only at a call that uses it, as
  C++ instantiates defaults on use.
- intrinsics: a dimension several arguments share (`dot`'s `numeric<c>`,
  `mul`'s `<r, c>`) takes the smallest argument's value; longer arguments
  are truncated with dxc's -Wconversion warning at the argument.
  `float4 a = mul(float3x3, float4)` is now rejected, as in dxc.
- SPIR-V: calls of functions returning resources (or structs holding
  them) are inlined before resources are split out of structs, in every
  stage; the splitter skips dead functions and walks blocks in reverse
  postorder.
- SPIR-V: printf as NonSemantic.DebugPrintf with an OpString format.
2026-11-03 22:12:27 -08:00
peterino2 987b2a573c README: Hyperion's numbers at ddefd45, and Unreal's editor 2026-11-03 20:55:41 -08:00
peterino2 ddefd450f7 dxil: smaller code, as dxc's optimizer makes it
Unreal's 11,488 compiles came out 1.7 times dxc's DXIL; now 1.09.

- cfg.zig: blocks that only branch to a block with no other
  predecessor take it in; blocks holding only a branch are bypassed;
  if/else arms with up to two cheap instructions become selects (dxc's
  simplifycfg); a branch or switch going one way everywhere goes there.
- cse.zig: repeated computations over the dominator tree (arithmetic,
  readnone dx.ops, cbuffer loads, handles), as EarlyCSE and GVN.
- promote: floating-point constants folded (arithmetic, FAbs, Saturate,
  rounding, Sqrt, min/max), `zext i1 != 0`, `and` by known-zero bits,
  and compares of selects and phis of constants (`(c ? 2 : 1) == 3`).
- [unroll] loops: their back edge is marked for the unroller, which
  unrolls them up to dxc's 1024 iterations whatever their size.
- -Od promotes locals and removes dead code, as dxc's does: 14 times
  dxc's size before, 0.89 now.

Every compile validates with Unreal's validator 1.8. Compile time
over the corpus: 584 s summed, 539 before.
2026-11-03 19:45:14 -08:00
peterino2 e4cf1caaf2 work graphs: node shaders, as dxc compiles them
[Shader("node")] functions in lib_6_8 libraries: the node input and
output objects (DispatchNodeInputRecord ... GroupNodeOutputRecords) in
sema, lowered as node_io / record accesses, and emitted with dxc's ops
238..253 (handles created and annotated with their I/O flags and record
size, records through getNodeRecordPtr in address space 6), the node
entry properties (launch, ID, dispatch grids, inputs and outputs with
record size, SV_DispatchGrid and alignment), and RDAT's node tables
(NodeID, function and I/O attributes, IONode, NodeShaderInfo).

Also: Barrier on records, GetRemainingRecursionLevels, atomics on record
fields and the *FloatBitwise compares (on the float's bits), node objects
in locals, parameters and return values, the NodeLaunch value check, and
dxc's noduplicate attribute on the SM 6.8 barriers.

DXC's work graph tests (test/workgraph in zdxc-internal): every case DXC
compiles, zdxc compiles too and validator 1.8 accepts, Unreal's node
shader (recording 10056) among them. Other output is unchanged.
2026-11-03 14:13:29 -08:00
peterino2 8a77bb723b dxil: SM 6.8 Barrier(), and one validator version for PSV and RDAT
- Barrier(memory types, semantics) and Barrier(UAV, semantics) lower to
  barrierByMemoryType (244) and barrierByMemoryHandle (245), as dxc does;
  libraries mark a function as needing a group for groupshared memory
  (not via ALL_MEMORY) or group sync / scope semantics, as dxc's
  BarrierRequiresGroup.
- shader.validator is the one validator version zdxc writes for; the
  PSV runtime info (4 from 1.10, else 3) and RDAT's function records
  (FunctionInfo3 from 1.10, else 2) follow it. Building for validator
  1.8 is now changing that constant. (Validator 1.8 rejected the RDAT of
  12 Glide libraries only because their records were 1.10's: built for
  1.8, all of Glide's compiles validate.)
2026-11-03 13:36:18 -08:00
peterino2 285505e36b dxil: write [WaveSize] to the entry, PSV and RDAT
[WaveSize] was checked but not written: the entry properties had no wave
size, so a shader written for one wave size could run with another.
DXC writes tag 11 { size } before SM 6.8 and tag 23 { min, max,
preferred } from 6.8; PSV's and RDAT's expected wave lane counts take
the minimum and the maximum (or the minimum again).

Unreal: 44 of the 2,080 verify compiles use WaveSize and change; all
11,488 validate (validator 1.8).
2026-11-03 13:20:03 -08:00
Peter Li 3ba5acaf75
Merge pull request #2 from peterino2/hillclimb
Hillclimb
2026-11-03 13:31:41 -07:00
30 changed files with 2699 additions and 186 deletions

View File

@ -7,7 +7,7 @@
</p> </p>
<p align="center"> <p align="center">
HLSL 2021 → DXIL / SPIR-V · Written in Zig · No LLVM dependency HLSL 2018 / 2021 → DXIL / SPIR-V · Written in Zig · No LLVM dependency
</p> </p>
<p align="center"> <p align="center">
@ -19,9 +19,9 @@
--- ---
zdxc is an HLSL 2021 compiler written from scratch in Zig. It emits DXIL and zdxc is an HLSL compiler written from scratch in Zig. It supports HLSL 2018
SPIR-V, supports DXC-style command lines, and provides a DXC-compatible COM and 2021, emits DXIL and SPIR-V, supports DXC-style command lines, and
interface for existing engine integrations. provides a DXC-compatible COM interface for existing engine integrations.
Use it as a development drop-in replacement for DXC, link its small C API directly, Use it as a development drop-in replacement for DXC, link its small C API directly,
or import it as a Zig module. The compiler has no package dependencies and or import it as a Zig module. The compiler has no package dependencies and
@ -29,7 +29,7 @@ signs its own DXIL, so there is no separate `dxil.dll` to ship.
| Fast iteration | Small footprint | Easy to embed | | Fast iteration | Small footprint | Easy to embed |
| :--- | :--- | :--- | | :--- | :--- | :--- |
| About **14× faster compilation** in the Hyperion benchmark. | **4.2 MB** Windows drop-in, compared with **19.3 MB** for DXC plus its DXIL library. | A **static library** by default, with a C API and a native Zig module. | | About **15× faster compilation** in the Hyperion benchmark. | **4.2 MB** Windows drop-in, compared with **19.3 MB** for DXC plus its DXIL library. | A **static library** by default, with a C API and a native Zig module. |
## Quick start ## Quick start
@ -70,14 +70,21 @@ Download Windows, Linux, and macOS bundles from a successful run's **Artifacts**
section on [GitHub Actions](https://github.com/peterino2/zdxc/actions). section on [GitHub Actions](https://github.com/peterino2/zdxc/actions).
Each bundle includes the CLI, static C library, header, and DXC drop-in. Each bundle includes the CLI, static C library, header, and DXC drop-in.
See the [Hyperion case study](https://zdxc.org/case-studies.html) for benchmark See the [case studies](https://zdxc.org/case-studies.html) for benchmark
measurements and methodology. In that Windows DXIL workload, zdxc's compile measurements and methodology. In Hyperion's Windows DXIL cook, zdxc's compile
step was **13.9× faster** and the complete shader cook was **2.5× faster**. step was **15.5× faster** and the complete shader cook was **2.5× faster**;
Unreal Engine 5.8's editor compiled its 11,156 startup shaders **4.3× faster**.
## Status ## Status
zdxc is **alpha software**, focused on HLSL 2021 (`-HV 2021`). DXC compatibility zdxc is **alpha software**. HLSL 2021 is the default; use `-HV 2018` for
is still being developed; not every DXC interface or feature is implemented. HLSL 2018 shaders. DXIL supports work graph node shaders in `lib_6_8`
libraries, SM 6.8 `Barrier()`, and `[WaveSize]` metadata. Work graph nodes
are not supported by the SPIR-V backend. See the
[command-line guide](docs/manual/03-command-line.md) for examples.
DXC compatibility is still being developed; not every interface or feature
is implemented.
The [drop-in manual](https://zdxc.org/manual.html#section-dxc-drop-in) documents The [drop-in manual](https://zdxc.org/manual.html#section-dxc-drop-in) documents
the current interface coverage. the current interface coverage.

View File

@ -24,8 +24,10 @@ no `dxil.dll`: zdxc signs DXIL itself.
| Class | Interfaces | | Class | Interfaces |
|---|---| |---|---|
| `CLSID_DxcCompiler` | `IDxcCompiler3` (`Compile`), `IDxcVersionInfo` (reports 1.11) | | `CLSID_DxcCompiler` | `IDxcCompiler3` (`Compile`), `IDxcCompiler` (`Compile`, `Preprocess`), `IDxcCompiler2` (`CompileWithDebug`), `IDxcVersionInfo` (reports 1.11) |
| `CLSID_DxcUtils` (also reached as `CLSID_DxcLibrary`) | `IDxcUtils`: blob creation, `LoadFile`, `CreateDefaultIncludeHandler`, `GetBlobAsUtf8` / `GetBlobAsWide`, `GetDxilContainerPart` | | `CLSID_DxcUtils` (also reached as `CLSID_DxcLibrary`) | `IDxcUtils`: blob creation, `LoadFile`, `CreateDefaultIncludeHandler`, `GetBlobAsUtf8` / `GetBlobAsWide`, `GetDxilContainerPart`, `CreateReflection` |
| `CLSID_DxcContainerReflection` | `IDxcContainerReflection`: load and inspect container parts, `GetPartReflection` |
| `CLSID_DxcContainerBuilder` | `IDxcContainerBuilder`: load, add/remove parts, serialize a signed container |
`Compile` takes the same arguments as the command line and follows DXC: `Compile` takes the same arguments as the command line and follows DXC:
@ -44,13 +46,21 @@ no `dxil.dll`: zdxc signs DXIL itself.
Classes and methods that are not implemented return `REGDB_E_CLASSNOTREG` Classes and methods that are not implemented return `REGDB_E_CLASSNOTREG`
or `E_NOTIMPL`. These include: or `E_NOTIMPL`. These include:
- the legacy `IDxcCompiler` and `IDxcCompiler2` interfaces;
- `Disassemble`; - `Disassemble`;
- `CreateReflection`, `BuildArguments` and `GetPDBContents`; - `BuildArguments` and `GetPDBContents`;
- the validator, linker, container and PDB classes. - the validator, linker, and PDB classes.
The result has no `DXC_OUT_REFLECTION` output (the reflection container DXIL results include `DXC_OUT_REFLECTION`. `CreateReflection` reads zdxc
that `CreateReflection` reads). reflection blobs and exposes `ID3D12ShaderReflection` or
`ID3D12LibraryReflection`. `CompileWithDebug` compiles the shader but returns
no separate debug name or blob; zdxc does not write PDBs.
Language support is zdxc's own: HLSL 2021, with `-HV 2021` as the only Language support is zdxc's own. HLSL 2021 is the default; pass `-HV 2018`
version. for HLSL 2018's component-wise `&&`, `||`, and numeric `?:`, which evaluate
both operands or branches. `-HV 2016` and `-HV 2017` use the same legacy
operator semantics. These options apply to both executable and library calls.
DXIL supports work graph node shaders compiled as `lib_6_8`, including
node input/output records and the `broadcasting`, `coalescing`, and `thread`
launch modes. Work graph nodes are not supported with `-spirv`.

View File

@ -4,7 +4,7 @@ order: 1
title: Introduction title: Introduction
--- ---
zdxc is a from-scratch HLSL 2021 compiler written in Zig. It emits DXIL and zdxc is a from-scratch HLSL compiler written in Zig. It emits DXIL and
SPIR-V and has no package dependencies. The same compiler is available through SPIR-V and has no package dependencies. The same compiler is available through
four interfaces: four interfaces:
@ -15,5 +15,14 @@ four interfaces:
| `zdxc` Zig module | Direct access to the compiler from a Zig build. | | `zdxc` Zig module | Direct access to the compiler from a Zig build. |
| `dxc` / `dxcompiler` | Drop-in names and entry points for existing DXC clients. | | `dxc` / `dxcompiler` | Drop-in names and entry points for existing DXC clients. |
The source language is HLSL 2021; `-HV 2021` is the only language version. HLSL 2021 is the default language version. Select HLSL 2018 with `-HV 2018`;
`-HV 2016` and `-HV 2017` are also accepted with the same legacy operator
semantics. The language version is independent of the target shader model.
Compute shaders support thread groups, `groupshared` storage, and group
barriers. The DXIL backend also supports work graph node shaders in
`lib_6_8` libraries, SM 6.8 `Barrier()`, and `[WaveSize]` metadata. Work graph
nodes are not supported in SPIR-V. See the
[command-line guide](03-command-line.md) for language and work graph examples.
DXIL output is signed by zdxc itself, so no separate `dxil` library is needed. DXIL output is signed by zdxc itself, so no separate `dxil` library is needed.

View File

@ -11,6 +11,7 @@ a file or, through the library interfaces, from memory.
| --- | --- | | --- | --- |
| `-T <profile>` | Target profile, such as `vs_6_0`, `ps_6_0`, or `cs_6_0`. | | `-T <profile>` | Target profile, such as `vs_6_0`, `ps_6_0`, or `cs_6_0`. |
| `-E <name>` | Shader entry point. | | `-E <name>` | Shader entry point. |
| `-HV <version>` | HLSL language version: `2021` (default), `2018`, `2017`, or `2016`. |
| `-D <name[=value]>` | Define a preprocessor macro. | | `-D <name[=value]>` | Define a preprocessor macro. |
| `-I <directory>` | Add an include search directory. | | `-I <directory>` | Add an include search directory. |
| `-Fo <file>` | Write the object to a file. | | `-Fo <file>` | Write the object to a file. |
@ -19,12 +20,75 @@ a file or, through the library interfaces, from memory.
| `-P` | Preprocess instead of compiling. | | `-P` | Preprocess instead of compiling. |
| `-spirv` | Emit SPIR-V instead of DXIL. | | `-spirv` | Emit SPIR-V instead of DXIL. |
| `-Zpr` / `-Zpc` | Select row- or column-major matrix packing. | | `-Zpr` / `-Zpc` | Select row- or column-major matrix packing. |
| `-O0` … `-O3`, `-Od` | Select the optimization level. | | `-O0` … `-O3`, `-Od` | Select the optimization level. `-Od`, as in dxc, still promotes locals to SSA values and removes dead code, but does nothing else. |
| `--job=<file>` | Compile a JSON batch of shaders in one process. | | `--job=<file>` | Compile a JSON batch of shaders in one process. |
DXIL is the default backend. Add `-spirv` for SPIR-V, with the `-fvk-*` and DXIL is the default backend. Add `-spirv` for SPIR-V, with the `-fvk-*` and
`-fspv-*` options controlling Vulkan bindings, layout, and target environment. `-fspv-*` options controlling Vulkan bindings, layout, and target environment.
## HLSL language versions
Use `-HV 2018` when compiling shaders written for HLSL 2018:
```sh
zdxc -HV 2018 -T ps_6_0 -E main shader.hlsl -Fo shader.dxil
zdxc -HV 2018 -spirv -T ps_6_0 -E main shader.hlsl -Fo shader.spv
```
The default is `-HV 2021`. In the legacy modes (`2016`, `2017`, and `2018`),
`&&` and `||` evaluate both operands and operate component-wise on vectors;
numeric `?:` evaluates both branches and permits a vector condition to
select per component. In 2021 mode, logical operands and the conditional
test are scalar, and evaluation short-circuits. Code that relies on an
unevaluated expression to avoid side effects needs particular care when
switching to a legacy mode.
The preprocessor macro `__HLSL_VERSION` reflects the selected version.
`-HV` selects language semantics; `-T` independently selects the shader
stage and shader model. These options also work in batch jobs and through
the C API and DXC drop-in.
## Compute thread groups and work graphs
Compute shaders use `[numthreads(x, y, z)]` to declare their thread group
size, `groupshared` for group-local storage, and intrinsics such as
`GroupMemoryBarrierWithGroupSync()` for synchronization. Compile them with
a compute profile, for example `-T cs_6_0 -E main`, for DXIL or SPIR-V.
For DXIL, `[WaveSize]` is emitted in entry-point and runtime metadata,
including the minimum, maximum, and preferred sizes for SM 6.8 wave-size
ranges. SM 6.8's `Barrier()` supports memory flags, UAVs, and node records.
Work graphs use node shaders in a shader library. Compile with `-T lib_6_8`
and mark each node with `[Shader("node")]` and its `[NodeLaunch]` mode;
there is no single `-E` entry point for the library. The supported launch
modes are `broadcasting`, `coalescing`, and `thread`. Node input/output
records, record allocation and completion, dispatch grids, node IDs, and
`GetRemainingRecursionLevels()` are supported by the DXIL backend.
For example, save this broadcasting node as `node.hlsl`:
```hlsl
RWStructuredBuffer<uint> values : register(u0);
[Shader("node")]
[NodeLaunch("broadcasting")]
[NodeDispatchGrid(1, 1, 1)]
[numthreads(64, 1, 1)]
void Fill(uint3 id : SV_DispatchThreadID)
{
values[id.x] = id.x;
}
```
```sh
zdxc -T lib_6_8 node.hlsl -Fo node.dxil
```
This produces a node shader library for a host application's work graph.
Work graph nodes are DXIL-only; compiling them with `-spirv` reports an
unsupported-feature error.
## Diagnostics and exit status ## Diagnostics and exit status
Diagnostics follow dxc's command-line format. Exit status is 0 for success, Diagnostics follow dxc's command-line format. Exit status is 0 for success,

View File

@ -28,8 +28,10 @@ no `dxil.dll`: zdxc signs DXIL itself.
| Class | Interfaces | | Class | Interfaces |
|---|---| |---|---|
| `CLSID_DxcCompiler` | `IDxcCompiler3` (`Compile`), `IDxcVersionInfo` (reports 1.11) | | `CLSID_DxcCompiler` | `IDxcCompiler3` (`Compile`), `IDxcCompiler` (`Compile`, `Preprocess`), `IDxcCompiler2` (`CompileWithDebug`), `IDxcVersionInfo` (reports 1.11) |
| `CLSID_DxcUtils` (also reached as `CLSID_DxcLibrary`) | `IDxcUtils`: blob creation, `LoadFile`, `CreateDefaultIncludeHandler`, `GetBlobAsUtf8` / `GetBlobAsWide`, `GetDxilContainerPart` | | `CLSID_DxcUtils` (also reached as `CLSID_DxcLibrary`) | `IDxcUtils`: blob creation, `LoadFile`, `CreateDefaultIncludeHandler`, `GetBlobAsUtf8` / `GetBlobAsWide`, `GetDxilContainerPart`, `CreateReflection` |
| `CLSID_DxcContainerReflection` | `IDxcContainerReflection`: load and inspect container parts, `GetPartReflection` |
| `CLSID_DxcContainerBuilder` | `IDxcContainerBuilder`: load, add/remove parts, serialize a signed container |
`Compile` takes the same arguments as the command line and follows DXC: `Compile` takes the same arguments as the command line and follows DXC:
@ -48,13 +50,21 @@ no `dxil.dll`: zdxc signs DXIL itself.
Classes and methods that are not implemented return `REGDB_E_CLASSNOTREG` Classes and methods that are not implemented return `REGDB_E_CLASSNOTREG`
or `E_NOTIMPL`. These include: or `E_NOTIMPL`. These include:
- the legacy `IDxcCompiler` and `IDxcCompiler2` interfaces;
- `Disassemble`; - `Disassemble`;
- `CreateReflection`, `BuildArguments` and `GetPDBContents`; - `BuildArguments` and `GetPDBContents`;
- the validator, linker, container and PDB classes. - the validator, linker, and PDB classes.
The result has no `DXC_OUT_REFLECTION` output (the reflection container DXIL results include `DXC_OUT_REFLECTION`. `CreateReflection` reads zdxc
that `CreateReflection` reads). reflection blobs and exposes `ID3D12ShaderReflection` or
`ID3D12LibraryReflection`. `CompileWithDebug` compiles the shader but returns
no separate debug name or blob; zdxc does not write PDBs.
Language support is zdxc's own: HLSL 2021, with `-HV 2021` as the only Language support is zdxc's own. HLSL 2021 is the default; pass `-HV 2018`
version. for HLSL 2018's component-wise `&&`, `||`, and numeric `?:`, which evaluate
both operands or branches. `-HV 2016` and `-HV 2017` use the same legacy
operator semantics. These options apply to both executable and library calls.
DXIL supports work graph node shaders compiled as `lib_6_8`, including
node input/output records and the `broadcasting`, `coalescing`, and `thread`
launch modes. Work graph nodes are not supported with `-spirv`.

View File

@ -1,5 +1,5 @@
/* /*
* zdxc: an HLSL 2021 to DXIL and SPIR-V compiler. * zdxc: an HLSL 2018 / 2021 to DXIL and SPIR-V compiler.
* *
* The C API. Link libzdxc statically (zig build -Dlinkage=static, the * The C API. Link libzdxc statically (zig build -Dlinkage=static, the
* default) or dynamically (-Dlinkage=dynamic); it needs nothing besides * default) or dynamically (-Dlinkage=dynamic); it needs nothing besides

View File

@ -528,6 +528,7 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void {
const zv = stats.begin(.spirv); const zv = stats.begin(.spirv);
defer if (opts.spirv) zv.end(); defer if (opts.spirv) zv.end();
if (opts.spirv) { if (opts.spirv) {
try zdxc.ir.inline_calls.runResourceReturns(m);
zdxc.ir.split_resources.run(arena, m, &diags) catch |err| switch (err) { zdxc.ir.split_resources.run(arena, m, &diags) catch |err| switch (err) {
error.Unsupported => { error.Unsupported => {
try diags.render(&sm, ctx.stderr, .{ .format = opts.diag_format, .color = false }); try diags.render(&sm, ctx.stderr, .{ .format = opts.diag_format, .color = false });
@ -563,7 +564,7 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void {
m.entries.items[0].root_signature = try rootSignatureMacroText(ctx, arena, opts, input, macro) orelse return error.CompileFailed; m.entries.items[0].root_signature = try rootSignatureMacroText(ctx, arena, opts, input, macro) orelse return error.CompileFailed;
}; };
const zd = stats.begin(.dxil); const zd = stats.begin(.dxil);
const dxil_out = zdxc.dxil.emit.emitWithReflection(arena, m, profile.?, &diags, !opts.no_opt and opts.opt_level != .od) catch |err| switch (err) { const dxil_out = zdxc.dxil.emit.emitWithReflectionAt(arena, m, profile.?, &diags, if (opts.no_opt) .none else if (opts.opt_level == .od) .debug else .full) catch |err| switch (err) {
error.Unsupported => { error.Unsupported => {
try diags.render(&sm, ctx.stderr, .{ .format = opts.diag_format, .color = false }); try diags.render(&sm, ctx.stderr, .{ .format = opts.diag_format, .color = false });
return error.CompileFailed; return error.CompileFailed;

View File

@ -112,6 +112,8 @@ const IID_IDxcIncludeHandler = GUID.parse("7f61fc7d-950d-467f-b3e3-3c02fb49187c"
const IID_IDxcOperationResult = GUID.parse("cedb484a-d4e9-445a-b991-ca21ca157dc2"); const IID_IDxcOperationResult = GUID.parse("cedb484a-d4e9-445a-b991-ca21ca157dc2");
const IID_IDxcResult = GUID.parse("58346cda-dde7-4497-9461-6f87af5e0659"); const IID_IDxcResult = GUID.parse("58346cda-dde7-4497-9461-6f87af5e0659");
const IID_IDxcCompiler3 = GUID.parse("228b4687-5a6a-4730-900c-9702b2203f54"); const IID_IDxcCompiler3 = GUID.parse("228b4687-5a6a-4730-900c-9702b2203f54");
const IID_IDxcCompiler = GUID.parse("8c210bf3-011f-4422-8d70-6f9acb8db617");
const IID_IDxcCompiler2 = GUID.parse("a005a9d9-b8bb-4594-b5c9-0e633bec4d37");
const IID_IDxcUtils = GUID.parse("4605c4cb-2019-492a-ada4-65f20bb7d67f"); const IID_IDxcUtils = GUID.parse("4605c4cb-2019-492a-ada4-65f20bb7d67f");
const IID_IDxcVersionInfo = GUID.parse("b04f5b50-2059-4f12-a8ff-a1e0cde1cc7e"); const IID_IDxcVersionInfo = GUID.parse("b04f5b50-2059-4f12-a8ff-a1e0cde1cc7e");
@ -739,6 +741,18 @@ const Compiler3Vtbl = extern struct {
Disassemble: *const fn (This, ?*const Buffer, *const GUID, ?Out) callconv(cc) HRESULT, Disassemble: *const fn (This, ?*const Buffer, *const GUID, ?Out) callconv(cc) HRESULT,
}; };
const DxcDefine = extern struct { Name: ?[*:0]const WCHAR, Value: ?[*:0]const WCHAR };
/// IDxcCompiler and IDxcCompiler2 (hassle-rs and other older clients):
/// entry point, profile and defines as parameters, the source as a blob.
const Compiler2Vtbl = extern struct {
unknown: UnknownVtbl,
Compile: *const fn (This, ?*anyopaque, ?[*:0]const WCHAR, ?[*:0]const WCHAR, ?[*:0]const WCHAR, ?[*]const ?[*:0]const WCHAR, u32, ?[*]const DxcDefine, u32, ?*anyopaque, ?Out) callconv(cc) HRESULT,
Preprocess: *const fn (This, ?*anyopaque, ?[*:0]const WCHAR, ?[*]const ?[*:0]const WCHAR, u32, ?[*]const DxcDefine, u32, ?*anyopaque, ?Out) callconv(cc) HRESULT,
Disassemble: *const fn (This, ?*anyopaque, ?Out) callconv(cc) HRESULT,
CompileWithDebug: *const fn (This, ?*anyopaque, ?[*:0]const WCHAR, ?[*:0]const WCHAR, ?[*:0]const WCHAR, ?[*]const ?[*:0]const WCHAR, u32, ?[*]const DxcDefine, u32, ?*anyopaque, ?Out, ?*?[*:0]WCHAR, ?Out) callconv(cc) HRESULT,
};
const VersionInfoVtbl = extern struct { const VersionInfoVtbl = extern struct {
unknown: UnknownVtbl, unknown: UnknownVtbl,
GetVersion: *const fn (This, ?*u32, ?*u32) callconv(cc) HRESULT, GetVersion: *const fn (This, ?*u32, ?*u32) callconv(cc) HRESULT,
@ -748,8 +762,17 @@ const VersionInfoVtbl = extern struct {
const Compiler = struct { const Compiler = struct {
compiler: Iface(Compiler3Vtbl) = .{ .vtbl = &compiler_vtbl }, compiler: Iface(Compiler3Vtbl) = .{ .vtbl = &compiler_vtbl },
version: Iface(VersionInfoVtbl) = .{ .vtbl = &version_vtbl }, version: Iface(VersionInfoVtbl) = .{ .vtbl = &version_vtbl },
legacy: Iface(Compiler2Vtbl) = .{ .vtbl = &legacy_vtbl },
rc: RefCount = .{}, rc: RefCount = .{},
const legacy_vtbl: Compiler2Vtbl = .{
.unknown = .{ .QueryInterface = legacyQueryInterface, .AddRef = legacyAddRef, .Release = legacyRelease },
.Compile = legacyCompile,
.Preprocess = legacyPreprocess,
.Disassemble = legacyDisassemble,
.CompileWithDebug = legacyCompileWithDebug,
};
const compiler_vtbl: Compiler3Vtbl = .{ const compiler_vtbl: Compiler3Vtbl = .{
.unknown = .{ .QueryInterface = queryInterface, .AddRef = addRef, .Release = release }, .unknown = .{ .QueryInterface = queryInterface, .AddRef = addRef, .Release = release },
.Compile = compileFn, .Compile = compileFn,
@ -770,6 +793,8 @@ const Compiler = struct {
&c.compiler &c.compiler
else if (iid.eql(IID_IDxcVersionInfo)) else if (iid.eql(IID_IDxcVersionInfo))
&c.version &c.version
else if (iid.eql(IID_IDxcCompiler) or iid.eql(IID_IDxcCompiler2))
&c.legacy
else else
null; null;
if (p == null) { if (p == null) {
@ -834,6 +859,85 @@ const Compiler = struct {
_ = put(out, null); _ = put(out, null);
return E_NOTIMPL; return E_NOTIMPL;
} }
fn legacyOf(this: This) *Compiler {
return parent(Compiler, "legacy", this);
}
fn legacyQueryInterface(this: This, iid: *const GUID, out: ?Out) callconv(cc) HRESULT {
return legacyOf(this).query(iid, out);
}
fn legacyAddRef(this: This) callconv(cc) ULONG {
return legacyOf(this).rc.addRef();
}
fn legacyRelease(this: This) callconv(cc) ULONG {
return release(&legacyOf(this).compiler);
}
fn legacyCompile(_: This, source: ?*anyopaque, name: ?[*:0]const WCHAR, entry: ?[*:0]const WCHAR, profile: ?[*:0]const WCHAR, args: ?[*]const ?[*:0]const WCHAR, count: u32, defines: ?[*]const DxcDefine, define_count: u32, include: ?*anyopaque, out: ?Out) callconv(cc) HRESULT {
const p = profile orelse {
_ = put(out, null);
return E_INVALIDARG;
};
return legacyRun(source, name, .{ .compile = .{ .entry = entry, .profile = p } }, args, count, defines, define_count, include, out);
}
fn legacyCompileWithDebug(this: This, source: ?*anyopaque, name: ?[*:0]const WCHAR, entry: ?[*:0]const WCHAR, profile: ?[*:0]const WCHAR, args: ?[*]const ?[*:0]const WCHAR, count: u32, defines: ?[*]const DxcDefine, define_count: u32, include: ?*anyopaque, out: ?Out, debug_name: ?*?[*:0]WCHAR, debug_blob: ?Out) callconv(cc) HRESULT {
// No separate debug blob (zdxc writes no PDBs).
if (debug_name) |d| d.* = null;
if (debug_blob) |d| d.* = null;
return legacyCompile(this, source, name, entry, profile, args, count, defines, define_count, include, out);
}
fn legacyPreprocess(_: This, source: ?*anyopaque, name: ?[*:0]const WCHAR, args: ?[*]const ?[*:0]const WCHAR, count: u32, defines: ?[*]const DxcDefine, define_count: u32, include: ?*anyopaque, out: ?Out) callconv(cc) HRESULT {
return legacyRun(source, name, .preprocess, args, count, defines, define_count, include, out);
}
fn legacyDisassemble(_: This, _: ?*anyopaque, out: ?Out) callconv(cc) HRESULT {
_ = put(out, null);
return E_NOTIMPL;
}
const LegacyMode = union(enum) {
compile: struct { entry: ?[*:0]const WCHAR, profile: [*:0]const WCHAR },
preprocess,
};
/// The legacy calls as IDxcCompiler3 arguments: `-E entry -T profile`
/// (or `-P`), the arguments, then `-D name=value` per define.
fn legacyRun(source: ?*anyopaque, name: ?[*:0]const WCHAR, mode: LegacyMode, args: ?[*]const ?[*:0]const WCHAR, count: u32, defines: ?[*]const DxcDefine, define_count: u32, include: ?*anyopaque, out: ?Out) HRESULT {
const o = out orelse return E_POINTER;
o.* = null;
const blob = source orelse return E_INVALIDARG;
if ((count > 0 and args == null) or (define_count > 0 and defines == null)) return E_INVALIDARG;
const r = runLegacy(blob, name, mode, if (args) |a| a[0..count] else &.{}, if (defines) |d| d[0..define_count] else &.{}, include) catch |e| return switch (e) {
error.OutOfMemory => E_OUTOFMEMORY,
error.InvalidArgument => E_INVALIDARG,
};
o.* = &r.iface;
return S_OK;
}
fn runLegacy(blob: *anyopaque, name: ?[*:0]const WCHAR, mode: LegacyMode, wargs: []const ?[*:0]const WCHAR, defines: []const DxcDefine, include: ?*anyopaque) error{ OutOfMemory, InvalidArgument }!*Result {
if (thread_arena == null) thread_arena = .init(gpa);
const arena = &thread_arena.?;
defer _ = arena.reset(.{ .retain_with_limit = retain_limit });
const a = arena.allocator();
var args: std.ArrayList([]const u8) = .empty;
switch (mode) {
.compile => |c| {
if (c.entry) |e| try args.appendSlice(a, &.{ "-E", try fromWide(a, e) });
try args.appendSlice(a, &.{ "-T", try fromWide(a, c.profile) });
},
.preprocess => try args.append(a, "-P"),
}
for (wargs) |w| try args.append(a, try fromWide(a, w orelse return error.InvalidArgument));
for (defines) |d| {
const n = try fromWide(a, d.Name orelse continue);
try args.appendSlice(a, &.{ "-D", if (d.Value) |v| try std.fmt.allocPrint(a, "{s}={s}", .{ n, try fromWide(a, v) }) else n });
}
const text = Utils.blobText(a, blob) catch |e| return switch (e) {
error.OutOfMemory => error.OutOfMemory,
else => error.InvalidArgument,
};
return runText(a, args.items, text, if (name) |n| try fromWide(a, n) else null, include);
}
}; };
/// Each thread's compile arena, kept between calls. Freeing it per call /// Each thread's compile arena, kept between calls. Freeing it per call
@ -851,11 +955,17 @@ fn run(source: *const Buffer, wargs: []const ?[*:0]const WCHAR, include: ?*anyop
const args = try a.alloc([]const u8, wargs.len); const args = try a.alloc([]const u8, wargs.len);
for (args, wargs) |*d, w| d.* = try fromWide(a, w orelse return error.InvalidArgument); for (args, wargs) |*d, w| d.* = try fromWide(a, w orelse return error.InvalidArgument);
const bytes: []const u8 = if (source.ptr) |p| p[0..source.size] else &.{}; const bytes: []const u8 = if (source.ptr) |p| p[0..source.size] else &.{};
return runText(a, args, try decodeText(a, bytes, source.encoding), null, include);
}
/// A compile of `text` (in the caller's thread arena).
fn runText(a: std.mem.Allocator, args: []const []const u8, text: []const u8, source_name: ?[]const u8, include: ?*anyopaque) error{ OutOfMemory, InvalidArgument }!*Result {
var client: ClientFs = undefined; var client: ClientFs = undefined;
var threaded: std.Io.Threaded = .init_single_threaded; var threaded: std.Io.Threaded = .init_single_threaded;
var req: compile.Request = .{ var req: compile.Request = .{
.args = args, .args = args,
.source = try decodeText(a, bytes, source.encoding), .source = text,
.source_name = source_name,
.io = threaded.io(), .io = threaded.io(),
.fs = NoFs.fileSystem(), .fs = NoFs.fileSystem(),
.compat_notes = false, .compat_notes = false,

497
src/dxil/cfg.zig Normal file
View File

@ -0,0 +1,497 @@
//! Control-flow cleanup, as dxc's simplifycfg does it: a block that only
//! branches to a block with no other predecessor takes that block in, and
//! a block holding nothing but an unconditional branch is bypassed (its
//! predecessors branch straight to its successor). Lowering gives every
//! statement, scope and inlined call its own blocks, and the optimizer
//! empties many more; without this they stay as chains of branches.
//!
//! Run on a function in SSA form, after promotion (which drops the blocks
//! no path reaches).
const std = @import("std");
const Allocator = std.mem.Allocator;
const module = @import("module.zig");
const promote = @import("promote.zig");
const stats = @import("../stats.zig");
const Value = module.Value;
const Inst = module.Inst;
const none = std.math.maxInt(u32);
const Edge = @typeInfo(@FieldType(@FieldType(@FieldType(Inst, "op"), "phi"), "incoming")).pointer.child;
const Case = @typeInfo(@FieldType(@FieldType(@FieldType(Inst, "op"), "switch"), "cases")).pointer.child;
fn isTerminator(inst: Inst) bool {
return switch (inst.op) {
.ret, .br, .@"switch", .@"unreachable" => true,
else => false,
};
}
/// Most cost of the instructions one arm of an if may hoist above its
/// branch to become a select (LLVM's phi-node-folding-threshold, as in
/// dxc).
const max_arm_cost = 2;
const State = struct {
a: Allocator,
m: *const module.Module,
insts: []Inst,
/// Each block's instructions (old indices), its terminator last.
body: []std.ArrayList(u32),
/// Predecessor edges (a block twice if it branches here twice).
preds: []std.ArrayList(u32),
/// The block that now holds a merged block's terminator: phis naming
/// the merged block mean it.
owner: []u32,
alive: []bool,
/// Phis replaced by their one input.
repl: []?Value,
fn find(s: *State, b: u32) u32 {
var x = b;
while (s.owner[x] != x) x = s.owner[x];
var y = b;
while (s.owner[y] != x) {
const next = s.owner[y];
s.owner[y] = x;
y = next;
}
return x;
}
fn term(s: *State, b: u32) *Inst {
const items = s.body[b].items;
return &s.insts[items[items.len - 1]];
}
fn hasPhis(s: *State, b: u32) bool {
return s.insts[s.body[b].items[0]].op == .phi;
}
fn removePred(s: *State, b: u32, p: u32) void {
const l = &s.preds[b];
for (l.items, 0..) |x, k| if (x == p) {
_ = l.swapRemove(k);
return;
};
}
fn renamePred(s: *State, x: u32, from: u32, to: u32) void {
for (s.preds[x].items) |*p| {
if (p.* == from) p.* = to;
}
}
fn countPred(s: *State, b: u32, p: u32) u32 {
var c: u32 = 0;
for (s.preds[b].items) |x| c += @intFromBool(x == p);
return c;
}
/// `b` (unconditional branch to `c`, `c`'s only predecessor) takes in
/// `c`.
fn merge(s: *State, b: u32, c: u32) Allocator.Error!void {
const cb = s.body[c].items;
var k: usize = 0;
while (k < cb.len and s.insts[cb[k]].op == .phi) : (k += 1) {
s.repl[cb[k]] = s.insts[cb[k]].op.phi.incoming[0].val;
}
const bb = &s.body[b];
_ = bb.pop();
try bb.appendSlice(s.a, cb[k..]);
s.alive[c] = false;
s.owner[c] = b;
// (`c`'s successors now have `b` for a predecessor.)
switch (s.term(b).op) {
.br => |br| {
s.renamePred(br.then, c, b);
if (br.@"else") |e| s.renamePred(e, c, b);
},
.@"switch" => |sw| {
s.renamePred(sw.default, c, b);
for (sw.cases) |x| s.renamePred(x.block, c, b);
},
else => {},
}
}
/// Retargets `p`'s edges to `b` at `c`.
fn retarget(s: *State, p: u32, b: u32, c: u32) Allocator.Error!void {
const t = s.term(p);
switch (t.op) {
.br => |*br| {
if (br.then == b) br.then = c;
if (br.@"else") |*e| if (e.* == b) {
e.* = c;
};
},
.@"switch" => |*sw| {
if (sw.default == b) sw.default = c;
const cs = try s.a.dupe(Case, sw.cases);
for (cs) |*x| if (x.block == b) {
x.block = c;
};
sw.cases = cs;
},
else => unreachable,
}
}
/// True if `b` is cheap instructions safe to run on either path (see
/// cost) and `br m`, and only `p` branches to it.
fn armFrom(s: *State, b: u32, p: u32, m: u32) bool {
if (s.preds[b].items.len != 1 or s.preds[b].items[0] != p) return false;
const t = s.term(b).op;
if (t != .br or t.br.@"else" != null or t.br.then != m) return false;
const items = s.body[b].items;
var total: u32 = 0;
for (items[0 .. items.len - 1]) |i| {
total += s.cost(s.insts[i]) orelse return false;
if (total > max_arm_cost) return false;
}
return true;
}
/// What hoisting `inst` above a branch costs, or null if it cannot
/// be: it has an effect, may trap (integer division), or reads memory.
fn cost(s: *State, inst: Inst) ?u32 {
return switch (inst.op) {
.binop => |b| switch (b.op) {
.udiv, .sdiv, .urem, .srem => if (s.m.types.items[inst.ty] == .int) null else 1,
else => 1,
},
.cast => |c| if (c.op == .bitcast) 0 else 1,
.cmp, .select, .extractvalue, .extractelement, .insertelement => 1,
else => null,
};
}
/// The instructions of `b` before its terminator, moved to the end of
/// `p` (before its terminator).
fn hoist(s: *State, b: u32, p: u32) Allocator.Error!void {
const from = s.body[b].items;
if (from.len < 2) return;
const to = &s.body[p];
const t = to.pop().?;
try to.appendSlice(s.a, from[0 .. from.len - 1]);
try to.append(s.a, t);
from[0] = from[from.len - 1];
s.body[b].shrinkRetainingCapacity(1);
}
/// A branch to one block every way goes there unconditionally; the
/// phis there keep one input from it.
fn collapse(s: *State, b: u32) Allocator.Error!bool {
const t = s.term(b);
const target: u32 = switch (t.op) {
.br => |br| if (br.@"else") |e| (if (e == br.then) e else return false) else return false,
.@"switch" => |sw| blk: {
for (sw.cases) |c| if (c.block != sw.default) return false;
break :blk sw.default;
},
else => return false,
};
t.op = .{ .br = .{ .then = target } };
while (s.countPred(target, b) > 1) s.removePred(target, b);
const cb = s.body[target].items;
var k: usize = 0;
while (k < cb.len and s.insts[cb[k]].op == .phi) : (k += 1) {
const phi = &s.insts[cb[k]].op.phi;
var out: std.ArrayList(Edge) = .empty;
var seen = false;
for (phi.incoming) |in| {
if (s.find(in.block) == b) {
if (seen) continue;
seen = true;
}
try out.append(s.a, in);
}
phi.incoming = out.items;
}
return true;
}
/// `m`'s two predecessors: a conditional branch and a block it
/// branches to (a triangle), or two blocks one conditional
/// branch picks between (a diamond). `m`'s phis become selects on the
/// branch's condition, and the branch goes straight to `m` (dxc's
/// simplifycfg folds two-entry phis so). True if done.
fn ifConvert(s: *State, m: u32) Allocator.Error!bool {
const ps = s.preds[m].items;
if (ps.len != 2 or ps[0] == ps[1]) return false;
// The branching block, and the block each of its arms reaches `m`
// from.
var p: u32 = none;
var via: [2]u32 = undefined;
for (0..2) |k| {
const q = ps[k];
const other = ps[1 - k];
const t = s.term(q).op;
if (q == m or t != .br) continue;
const e = t.br.@"else" orelse continue;
if (t.br.then == m and e == other and s.armFrom(other, q, m)) {
p = q;
via = .{ q, other };
} else if (e == m and t.br.then == other and s.armFrom(other, q, m)) {
p = q;
via = .{ other, q };
}
}
if (p == none) {
// A diamond: both predecessors empty, from one branch.
if (s.preds[ps[0]].items.len != 1) return false;
const q = s.preds[ps[0]].items[0];
if (q == m or !s.armFrom(ps[0], q, m) or !s.armFrom(ps[1], q, m)) return false;
const t = s.term(q).op;
if (t != .br) return false;
const e = t.br.@"else" orelse return false;
if (t.br.then == ps[0] and e == ps[1]) {
via = .{ ps[0], ps[1] };
} else if (t.br.then == ps[1] and e == ps[0]) {
via = .{ ps[1], ps[0] };
} else return false;
p = q;
}
const cond = s.term(p).op.br.cond.?;
const mb = s.body[m].items;
var k: usize = 0;
while (k < mb.len and s.insts[mb[k]].op == .phi) : (k += 1) {
const inst = &s.insts[mb[k]];
var vals: [2]?Value = .{ null, null };
for (inst.op.phi.incoming) |in| {
const from = s.find(in.block);
if (from == via[0]) vals[0] = in.val else if (from == via[1]) vals[1] = in.val;
}
if (vals[0] == null or vals[1] == null) return false;
}
k = 0;
while (k < mb.len and s.insts[mb[k]].op == .phi) : (k += 1) {
const inst = &s.insts[mb[k]];
var vals: [2]Value = undefined;
for (inst.op.phi.incoming) |in| {
const from = s.find(in.block);
if (from == via[0]) vals[0] = in.val else if (from == via[1]) vals[1] = in.val;
}
if (std.meta.eql(vals[0], vals[1])) {
s.repl[mb[k]] = vals[0];
} else inst.op = .{ .select = .{ .cond = cond, .t = vals[0], .f = vals[1] } };
}
// `p` goes to `m`, running what the arms did first; their blocks
// go.
for (via) |v| if (v != p) try s.hoist(v, p);
s.term(p).op = .{ .br = .{ .then = m } };
for (via) |v| if (v != p) {
s.alive[v] = false;
s.preds[v].clearRetainingCapacity();
};
s.preds[m].clearRetainingCapacity();
try s.preds[m].append(s.a, p);
return true;
}
/// Bypasses `b` (only `br c`): its predecessors branch to `c`.
fn bypass(s: *State, b: u32, c: u32) Allocator.Error!void {
const ps = try s.a.dupe(u32, s.preds[b].items);
const phis = s.hasPhis(c);
// `c`'s phis: the input from `b` comes from each of `b`'s
// predecessors instead.
const cb = s.body[c].items;
var k: usize = 0;
while (k < cb.len and s.insts[cb[k]].op == .phi) : (k += 1) {
const phi = &s.insts[cb[k]].op.phi;
var out: std.ArrayList(Edge) = .empty;
try out.ensureTotalCapacity(s.a, phi.incoming.len + ps.len);
for (phi.incoming) |in| {
if (s.find(in.block) == b) {
for (ps) |p| out.appendAssumeCapacity(.{ .val = in.val, .block = p });
} else out.appendAssumeCapacity(in);
}
phi.incoming = out.items;
}
// (Each distinct predecessor once: retarget moves all its edges.)
for (ps, 0..) |p, i| {
if (std.mem.indexOfScalar(u32, ps[0..i], p) != null) continue;
try s.retarget(p, b, c);
}
s.removePred(c, b);
try s.preds[c].appendSlice(s.a, ps);
s.preds[b].clearRetainingCapacity();
s.alive[b] = false;
// A conditional branch now going to `c` both ways goes there
// unconditionally (when `c` has no phis to give two inputs).
if (!phis) for (ps) |p| {
const t = s.term(p);
if (t.op == .br) if (t.op.br.@"else") |e| if (e == t.op.br.then) {
t.op.br = .{ .then = e };
s.removePred(c, p);
};
};
}
};
/// Simplifies `func`'s control flow; true if anything changed.
pub fn run(a: Allocator, m: *module.Module, func: u32) Allocator.Error!bool {
const zone = stats.begin(.cfg);
defer zone.end();
const f = &m.functions.items[func];
const nb = f.num_blocks;
const n: u32 = @intCast(f.insts.items.len);
if (nb < 2) return false;
var s: State = .{
.a = a,
.m = m,
.insts = try a.dupe(Inst, f.insts.items),
.body = try a.alloc(std.ArrayList(u32), nb),
.preds = try a.alloc(std.ArrayList(u32), nb),
.owner = try a.alloc(u32, nb),
.alive = try a.alloc(bool, nb),
.repl = try a.alloc(?Value, n),
};
@memset(s.repl, null);
@memset(s.alive, true);
for (s.owner, 0..) |*o, b| o.* = @intCast(b);
{
var b: u32 = 0;
var start: u32 = 0;
for (s.insts, 0..) |inst, i| {
if (!isTerminator(inst)) continue;
if (b >= nb) return false; // not the block layout expected
s.body[b] = .empty;
try s.body[b].ensureTotalCapacity(a, i + 1 - start);
for (start..i + 1) |k| s.body[b].appendAssumeCapacity(@intCast(k));
start = @intCast(i + 1);
b += 1;
}
if (b != nb or start != n) return false;
}
for (s.preds) |*p| p.* = .empty;
for (0..nb) |b| {
const t = s.term(@intCast(b)).*;
switch (t.op) {
.br => |br| {
try s.preds[br.then].append(a, @intCast(b));
if (br.@"else") |e| try s.preds[e].append(a, @intCast(b));
},
.@"switch" => |sw| {
try s.preds[sw.default].append(a, @intCast(b));
for (sw.cases) |c| try s.preds[c.block].append(a, @intCast(b));
},
else => {},
}
}
var changed = false;
var again = true;
while (again) {
again = false;
for (0..nb) |bi| {
const b: u32 = @intCast(bi);
if (!s.alive[b]) continue;
// Take in the chain of blocks only `b` leads to.
while (true) {
const t = s.term(b).*;
if (t.op != .br or t.op.br.@"else" != null) break;
const c = t.op.br.then;
if (c == b or c == 0 or s.preds[c].items.len != 1) break;
try s.merge(b, c);
changed = true;
again = true;
}
}
for (1..nb) |bi| {
const b: u32 = @intCast(bi);
if (!s.alive[b] or s.body[b].items.len != 1) continue;
const t = s.term(b).*;
if (t.op != .br or t.op.br.@"else" != null) continue;
const c = t.op.br.then;
const ps = s.preds[b].items;
if (c == b or ps.len == 0) continue;
if (std.mem.indexOfScalar(u32, ps, b) != null) continue;
// With phis in `c`, a predecessor already branching there could
// need two values on one edge: left alone.
if (s.hasPhis(c)) {
const clash = for (ps) |p| {
if (s.countPred(c, p) != 0) break true;
} else false;
if (clash) continue;
}
try s.bypass(b, c);
changed = true;
again = true;
}
for (0..nb) |bi| {
const b: u32 = @intCast(bi);
if (!s.alive[b] or !try s.collapse(b)) continue;
changed = true;
again = true;
}
for (1..nb) |bi| {
const b: u32 = @intCast(bi);
if (!s.alive[b] or !try s.ifConvert(b)) continue;
changed = true;
again = true;
}
}
if (!changed) return false;
// Lay the blocks out again, in their old order, and renumber.
const new_block = try a.alloc(u32, nb);
var kept: u32 = 0;
for (0..nb) |b| {
new_block[b] = if (s.alive[b]) kept else none;
if (s.alive[b]) kept += 1;
}
const index = try a.alloc(u32, n);
@memset(index, none);
var count: u32 = 0;
for (0..nb) |b| if (s.alive[b]) for (s.body[b].items) |i| {
if (s.repl[i] != null) continue;
index[i] = count;
count += 1;
};
const Map = struct {
repl: []const ?Value,
index: []const u32,
pub fn visit(ctx: *@This(), v: Value, _: promote.Role) Value {
var x = v;
while (x == .inst) {
const r = ctx.repl[x.inst] orelse break;
x = r;
}
return if (x == .inst) .{ .inst = ctx.index[x.inst] } else x;
}
};
var map: Map = .{ .repl = s.repl, .index = index };
const ma = m.allocator();
var out: std.ArrayList(Inst) = .empty;
try out.ensureTotalCapacityPrecise(ma, count);
for (0..nb) |b| if (s.alive[b]) for (s.body[b].items) |i| {
if (s.repl[i] != null) continue;
var inst = s.insts[i];
try promote.operands(true, ma, &inst, &map);
switch (inst.op) {
.phi => |*p| {
const es: []Edge = @constCast(p.incoming);
for (es) |*e| e.block = new_block[s.find(e.block)];
},
.br => |*br| {
br.then = new_block[br.then];
if (br.@"else") |*e| e.* = new_block[e.*];
},
.@"switch" => |*sw| {
sw.default = new_block[sw.default];
const cs = try ma.alloc(Case, sw.cases.len);
for (sw.cases, cs) |c, *o| o.* = .{ .val = c.val, .block = new_block[c.block] };
sw.cases = cs;
},
else => {},
}
out.appendAssumeCapacity(inst);
};
f.insts = out;
f.num_blocks = kept;
return true;
}

325
src/dxil/cse.zig Normal file
View File

@ -0,0 +1,325 @@
//! Common subexpression elimination over the dominator tree, as dxc's
//! EarlyCSE and GVN do it: an instruction that computes what one in a
//! dominating position already computed (same operation, same operands)
//! is replaced by it. Only instructions without effects and whose result
//! depends on nothing but their operands: arithmetic, comparisons, casts,
//! selects, address computations, readnone dx.op calls, and the readonly
//! ones that read what cannot change during the shader (constant buffer
//! loads, handle creation).
//!
//! Inlining every call and lowering each use of a cbuffer field to its own
//! load leaves many such repeats.
const std = @import("std");
const Allocator = std.mem.Allocator;
const module = @import("module.zig");
const promote = @import("promote.zig");
const stats = @import("../stats.zig");
const Value = module.Value;
const Inst = module.Inst;
const none = std.math.maxInt(u32);
fn isTerminator(inst: Inst) bool {
return switch (inst.op) {
.ret, .br, .@"switch", .@"unreachable" => true,
else => false,
};
}
/// dx.op readonly operations that read only what a dispatch cannot change:
/// CreateHandle, CBufferLoad, CBufferLoadLegacy, CreateHandleForLib,
/// CreateHandleFromBinding, CreateHandleFromHeap.
fn stableReadonly(opcode: i64) bool {
return switch (opcode) {
57, 58, 59, 160, 217, 218 => true,
else => false,
};
}
fn eligible(m: *const module.Module, inst: Inst) bool {
return switch (inst.op) {
.binop, .cast, .cmp, .select, .extractvalue, .gep, .extractelement, .insertelement => true,
.call => |c| {
const callee = m.functions.items[c.callee];
if (callee.num_blocks != 0 or !std.mem.startsWith(u8, callee.name, "dx.op.")) return false;
switch (callee.attrs) {
.nounwind_readnone => return true,
.nounwind_readonly => {
if (c.args.len == 0 or c.args[0] != .constant) return false;
return switch (m.constants.items[c.args[0].constant].kind) {
.int => |k| stableReadonly(k),
else => false,
};
},
else => return false,
}
},
else => false,
};
}
/// An instruction's identity as bytes: its operation, type, the fields
/// that are not operands, and its operands (resolved through replaced
/// instructions).
const Key = struct {
buf: std.ArrayList(u8) = .empty,
a: Allocator,
repl: []const ?Value,
failed: bool = false,
fn resolve(k: *const Key, v: Value) Value {
var x = v;
while (x == .inst) {
const r = k.repl[x.inst] orelse break;
x = r;
}
return x;
}
fn word(k: *Key, w: u64) void {
k.buf.appendSlice(k.a, std.mem.asBytes(&w)) catch {
k.failed = true;
};
}
pub fn visit(k: *Key, v: Value, _: promote.Role) Value {
const x = k.resolve(v);
const tag: u64 = @backingInt(std.meta.activeTag(x));
const id: u64 = switch (x) {
inline else => |i| i,
};
k.word(tag << 32 | id);
return v;
}
fn build(k: *Key, inst: Inst) Allocator.Error![]const u8 {
k.buf.clearRetainingCapacity();
k.word(@backingInt(std.meta.activeTag(inst.op)));
k.word(inst.ty);
switch (inst.op) {
.binop => |b| k.word(@as(u64, @backingInt(b.op)) << 32 | b.flags),
.cast => |c| k.word(@backingInt(c.op)),
.cmp => |c| k.word(c.pred),
.extractvalue => |x| k.word(x.index),
.gep => |g| k.word(g.elem),
.call => |c| k.word(c.callee),
else => {},
}
var copy = inst;
try promote.operands(false, k.a, &copy, k);
if (k.failed) return error.OutOfMemory;
return k.buf.items;
}
};
/// Replaces `func`'s repeated computations; true if any.
pub fn run(a: Allocator, m: *module.Module, func: u32) Allocator.Error!bool {
const zone = stats.begin(.cse);
defer zone.end();
const f = &m.functions.items[func];
const insts = f.insts.items;
const n: u32 = @intCast(insts.len);
const nb = f.num_blocks;
if (n == 0 or nb == 0) return false;
const block_start = try a.alloc(u32, nb + 1);
{
var b: u32 = 0;
block_start[0] = 0;
for (insts, 0..) |inst, i| if (isTerminator(inst)) {
if (b >= nb) return false;
b += 1;
block_start[b] = @intCast(i + 1);
};
if (b != nb or block_start[nb] != n) return false;
}
// Successors, predecessors.
const succ_off = try a.alloc(u32, nb + 1);
var succs: std.ArrayList(u32) = .empty;
for (0..nb) |b| {
succ_off[b] = @intCast(succs.items.len);
switch (insts[block_start[b + 1] - 1].op) {
.br => |br| {
try succs.append(a, br.then);
if (br.@"else") |e| try succs.append(a, e);
},
.@"switch" => |sw| {
try succs.append(a, sw.default);
for (sw.cases) |c| try succs.append(a, c.block);
},
else => {},
}
}
succ_off[nb] = @intCast(succs.items.len);
const pred_off = try a.alloc(u32, nb + 1);
@memset(pred_off, 0);
for (succs.items) |s| pred_off[s + 1] += 1;
for (1..nb + 1) |b| pred_off[b] += pred_off[b - 1];
const preds = try a.alloc(u32, succs.items.len);
{
const fill = try a.dupe(u32, pred_off[0..nb]);
for (0..nb) |b| for (succs.items[succ_off[b]..succ_off[b + 1]]) |s| {
preds[fill[s]] = @intCast(b);
fill[s] += 1;
};
}
// Reverse postorder, then immediate dominators (Cooper, Harvey and
// Kennedy).
const rpo_index = try a.alloc(u32, nb);
@memset(rpo_index, none);
const rpo = try a.alloc(u32, nb);
var nr: u32 = 0;
{
const post = try a.alloc(u32, nb);
var np: u32 = 0;
const seen = try a.alloc(bool, nb);
@memset(seen, false);
const Frame = struct { b: u32, next: u32 };
var stack: std.ArrayList(Frame) = .empty;
try stack.append(a, .{ .b = 0, .next = succ_off[0] });
seen[0] = true;
while (stack.items.len > 0) {
const top = &stack.items[stack.items.len - 1];
if (top.next < succ_off[top.b + 1]) {
const s = succs.items[top.next];
top.next += 1;
if (!seen[s]) {
seen[s] = true;
try stack.append(a, .{ .b = s, .next = succ_off[s] });
}
} else {
post[np] = top.b;
np += 1;
_ = stack.pop();
}
}
for (0..np) |k| {
rpo[k] = post[np - 1 - k];
rpo_index[rpo[k]] = @intCast(k);
}
nr = np;
}
const idom = try a.alloc(u32, nb);
@memset(idom, none);
idom[0] = 0;
{
var changed = true;
while (changed) {
changed = false;
for (rpo[1..nr]) |b| {
var new: u32 = none;
for (preds[pred_off[b]..pred_off[b + 1]]) |p| {
if (idom[p] == none) continue;
if (new == none) {
new = p;
continue;
}
var x = p;
var y = new;
while (x != y) {
while (rpo_index[x] > rpo_index[y]) x = idom[x];
while (rpo_index[y] > rpo_index[x]) y = idom[y];
}
new = x;
}
if (new != idom[b]) {
idom[b] = new;
changed = true;
}
}
}
}
// Dominator tree children, in reverse postorder.
const child_off = try a.alloc(u32, nb + 1);
@memset(child_off, 0);
for (rpo[1..nr]) |b| child_off[idom[b] + 1] += 1;
for (1..nb + 1) |b| child_off[b] += child_off[b - 1];
const children = try a.alloc(u32, if (nr > 0) nr - 1 else 0);
{
const fill = try a.dupe(u32, child_off[0..nb]);
for (rpo[1..nr]) |b| {
children[fill[idom[b]]] = b;
fill[idom[b]] += 1;
}
}
const repl = try a.alloc(?Value, n);
@memset(repl, null);
// The keys of the instructions available (in the dominating blocks),
// to the instruction.
var table: std.StringHashMapUnmanaged(u32) = .empty;
var added: std.ArrayList([]const u8) = .empty;
var key: Key = .{ .a = a, .repl = repl };
var found = false;
const Frame = struct { b: u32, next: u32, mark: usize };
var stack: std.ArrayList(Frame) = .empty;
try stack.append(a, .{ .b = 0, .next = child_off[0], .mark = 0 });
var entered = true;
while (stack.items.len > 0) {
const top = &stack.items[stack.items.len - 1];
if (entered) {
entered = false;
top.mark = added.items.len;
for (block_start[top.b]..block_start[top.b + 1]) |i| {
const inst = insts[i];
if (!eligible(m, inst)) continue;
// (The key is built in one buffer, and kept only if new.)
const gop = try table.getOrPut(a, try key.build(inst));
if (gop.found_existing) {
repl[i] = .{ .inst = gop.value_ptr.* };
found = true;
} else {
gop.key_ptr.* = try a.dupe(u8, key.buf.items);
gop.value_ptr.* = @intCast(i);
try added.append(a, gop.key_ptr.*);
}
}
}
if (top.next < child_off[top.b + 1]) {
const c = children[top.next];
top.next += 1;
try stack.append(a, .{ .b = c, .next = child_off[c], .mark = 0 });
entered = true;
} else {
for (added.items[top.mark..]) |k| _ = table.remove(k);
added.shrinkRetainingCapacity(top.mark);
_ = stack.pop();
}
}
if (!found) return false;
// Renumber without the replaced instructions.
const index = try a.alloc(u32, n);
var count: u32 = 0;
for (0..n) |i| {
index[i] = count;
if (repl[i] == null) count += 1;
}
const Map = struct {
repl: []const ?Value,
index: []const u32,
pub fn visit(ctx: *@This(), v: Value, _: promote.Role) Value {
var x = v;
while (x == .inst) {
const r = ctx.repl[x.inst] orelse break;
x = r;
}
return if (x == .inst) .{ .inst = ctx.index[x.inst] } else x;
}
};
var map: Map = .{ .repl = repl, .index = index };
const ma = m.allocator();
var out: std.ArrayList(Inst) = .empty;
try out.ensureTotalCapacityPrecise(ma, count);
for (insts, 0..) |inst, i| {
if (repl[i] != null) continue;
var copy = inst;
try promote.operands(true, ma, &copy, &map);
out.appendAssumeCapacity(copy);
}
f.insts = out;
return true;
}

View File

@ -28,6 +28,8 @@ const promote = @import("promote.zig");
const unroll = @import("unroll.zig"); const unroll = @import("unroll.zig");
const stats = @import("../stats.zig"); const stats = @import("../stats.zig");
const sccp = @import("sccp.zig"); const sccp = @import("sccp.zig");
const cfg = @import("cfg.zig");
const cse = @import("cse.zig");
const opt = @import("../ir/opt.zig"); const opt = @import("../ir/opt.zig");
const TypeId = types.TypeId; const TypeId = types.TypeId;
@ -53,9 +55,18 @@ pub fn emit(gpa: Allocator, m: *const ir.Module, profile: shader.Profile, diags:
pub const Output = struct { object: []u8, reflection: []u8 }; pub const Output = struct { object: []u8, reflection: []u8 };
pub fn emitWithReflection(gpa: Allocator, m: *const ir.Module, profile: shader.Profile, diags: *diag.Diagnostics, optimize: bool) Error!Output { pub fn emitWithReflection(gpa: Allocator, m: *const ir.Module, profile: shader.Profile, diags: *diag.Diagnostics, optimize: bool) Error!Output {
return emitWithReflectionAt(gpa, m, profile, diags, if (optimize) .full else .none);
}
/// How much `emitWithReflectionAt` optimizes: nothing (-zdxc-no-opt), as
/// dxc's -Od does (locals promoted to SSA values and what that leaves
/// dead removed, nothing else), or fully.
pub const Optimize = enum { none, debug, full };
pub fn emitWithReflectionAt(gpa: Allocator, m: *const ir.Module, profile: shader.Profile, diags: *diag.Diagnostics, level: Optimize) Error!Output {
var arena_state: BumpArena = .init(gpa); var arena_state: BumpArena = .init(gpa);
defer arena_state.deinit(); defer arena_state.deinit();
var e: Emitter = .{ .arena = arena_state.allocator(), .dm = .init(gpa), .m = m, .t = m.types, .profile = profile, .diags = diags, .optimize = optimize }; var e: Emitter = .{ .arena = arena_state.allocator(), .dm = .init(gpa), .m = m, .t = m.types, .profile = profile, .diags = diags, .optimize = level == .full, .promote_only = level == .debug };
defer e.dm.deinit(); defer e.dm.deinit();
// Native 16-bit types are laid out at their own size. // Native 16-bit types are laid out at their own size.
if (m.native_16bit) e.dm.datalayout = "e-m:e-p:32:32-i1:32-i8:8-i16:16-i32:32-i64:64-f16:16-f32:32-f64:64-n8:16:32:64"; if (m.native_16bit) e.dm.datalayout = "e-m:e-p:32:32-i1:32-i8:8-i16:16-i32:32-i64:64-f16:16-f32:32-f64:64-n8:16:32:64";
@ -89,6 +100,8 @@ const Lowered = union(enum) {
/// A local assigned different elements of one resource array (index /// A local assigned different elements of one resource array (index
/// into Emitter.res_index_locals): it holds the element's index. /// into Emitter.res_index_locals): it holds the element's index.
res_index_local: u32, res_index_local: u32,
/// A work graph node input or output, or a node's records.
node: NodeVal,
/// A RayQuery local (index into Emitter.rq_locals) and a query handle. /// A RayQuery local (index into Emitter.rq_locals) and a query handle.
rq_local: u32, rq_local: u32,
ray_query: Value, ray_query: Value,
@ -121,6 +134,11 @@ const Lowered = union(enum) {
}, },
}; };
/// A node object: its handle (%dx.types.NodeHandle for outputs,
/// %dx.types.NodeRecordHandle for records), annotated with `flags`
/// (NodeIOFlags) and the record's size.
const NodeVal = struct { kind: types.NodeKind, handle: Value, record: TypeId, flags: u32, size: u32 };
/// Pointer into a flattened local: alloca `base` of `[n x scalar]`, at /// Pointer into a flattened local: alloca `base` of `[n x scalar]`, at
/// component `offset_const` (+ `offset_dyn` if dynamic). /// component `offset_const` (+ `offset_dyn` if dynamic).
const Ptr = struct { const Ptr = struct {
@ -330,6 +348,8 @@ const Emitter = struct {
dyn_ranges: std.AutoHashMapUnmanaged(u32, [2]u32) = .empty, dyn_ranges: std.AutoHashMapUnmanaged(u32, [2]u32) = .empty,
/// See `emit`. /// See `emit`.
optimize: bool = true, optimize: bool = true,
/// -Od: only promotion runs on the finished functions.
promote_only: bool = false,
/// Arrays of inlined callees that have returned, by type, for later /// Arrays of inlined callees that have returned, by type, for later
/// callees' locals of that type (per function). /// callees' locals of that type (per function).
array_pool: std.AutoHashMapUnmanaged(TypeId, std.ArrayList(Ptr)) = .empty, array_pool: std.AutoHashMapUnmanaged(TypeId, std.ArrayList(Ptr)) = .empty,
@ -727,6 +747,8 @@ const Emitter = struct {
/// Graphics entries: signatures; entry properties of the stage. /// Graphics entries: signatures; entry properties of the stage.
sigs: ?module.MdId = null, sigs: ?module.MdId = null,
stage_props: []const ?module.MdId = &.{}, stage_props: []const ?module.MdId = &.{},
/// Groupshared memory the entry uses (bytes).
groupshared: u32 = 0,
}; };
/// Input qualifier (0 in, 1 out, 2 inout), component type and /// Input qualifier (0 in, 1 out, 2 inout), component type and
@ -750,6 +772,7 @@ const Emitter = struct {
.callable => 12, .callable => 12,
.mesh => 13, .mesh => 13,
.amplification => 14, .amplification => 14,
.node => 15,
}; };
} }
@ -779,7 +802,7 @@ const Emitter = struct {
var units: std.ArrayList(Unit) = .empty; var units: std.ArrayList(Unit) = .empty;
for (m.entries.items, 0..) |entry, k| { for (m.entries.items, 0..) |entry, k| {
switch (entry.stage) { switch (entry.stage) {
.compute, .raygeneration, .intersection, .anyhit, .closesthit, .miss, .callable, .vertex, .pixel, .geometry, .hull, .domain, .mesh, .amplification => {}, .compute, .raygeneration, .intersection, .anyhit, .closesthit, .miss, .callable, .vertex, .pixel, .geometry, .hull, .domain, .mesh, .amplification, .node => {},
else => return e.unsupported("{s} shaders in libraries are not supported yet", .{@tagName(entry.stage)}), else => return e.unsupported("{s} shaders in libraries are not supported yet", .{@tagName(entry.stage)}),
} }
try units.append(e.arena, .{ .order = m.functions.items[entry.func].decl_order, .kind = .entry, .index = @intCast(k) }); try units.append(e.arena, .{ .order = m.functions.items[entry.func].decl_order, .kind = .entry, .index = @intCast(k) });
@ -855,6 +878,7 @@ const Emitter = struct {
try e.libHandles(); try e.libHandles();
_ = try e.inlineCall(entry.wrapper, &.{}); _ = try e.inlineCall(entry.wrapper, &.{});
try e.finish(lf.func); try e.finish(lf.func);
lf.groupshared = e.groupshared_bytes;
var pc_func: ?LibFunc = null; var pc_func: ?LibFunc = null;
if (entry.patch_wrapper) |pw| { if (entry.patch_wrapper) |pw| {
// The patch constant function: a function of its own. // The patch constant function: a function of its own.
@ -1390,7 +1414,7 @@ const Emitter = struct {
switch (e.entry.stage) { switch (e.entry.stage) {
// (Library functions record the use; their callers decide.) // (Library functions record the use; their callers decide.)
.pixel, .library => {}, .pixel, .library => {},
.compute, .mesh, .amplification => if (e.profile.minor < 6) return e.unsupported("derivatives outside pixel shaders need shader model 6.6", .{}), .compute, .mesh, .amplification, .node => if (e.profile.minor < 6) return e.unsupported("derivatives outside pixel shaders need shader model 6.6", .{}),
else => return e.unsupported("derivatives are not available in {s} shaders", .{@tagName(e.entry.stage)}), else => return e.unsupported("derivatives are not available in {s} shaders", .{@tagName(e.entry.stage)}),
} }
if (e.entry.stage == .mesh or e.entry.stage == .amplification) e.uses_mesh_derivatives = true; if (e.entry.stage == .mesh or e.entry.stage == .amplification) e.uses_mesh_derivatives = true;
@ -1542,6 +1566,17 @@ const Emitter = struct {
try promote.run(e.arena, &e.dm, func, &.empty); try promote.run(e.arena, &e.dm, func, &.empty);
if (e.dm.functions.items[func].insts.items.len == before) break; if (e.dm.functions.items[func].insts.items.len == before) break;
} }
// Repeated computations, then blocks that only branch on:
// merged, bypassed, and if-converted.
// (What that leaves dead, or folds, and the blocks that leaves
// empty: again, until nothing changes.)
_ = try cse.run(e.arena, &e.dm, func);
var passes: u32 = 0;
while (passes < 3 and try cfg.run(e.arena, &e.dm, func)) : (passes += 1) {
try promote.run(e.arena, &e.dm, func, &.empty);
}
} else if (e.promote_only) {
try promote.run(e.arena, &e.dm, func, &ranges);
} }
} }
@ -2136,7 +2171,16 @@ const Emitter = struct {
_ = try e.add(void_ty, .{ .br = .{ .then = cont } }); _ = try e.add(void_ty, .{ .br = .{ .then = cont } });
} else _ = try e.add(void_ty, .{ .ret = null }); } else _ = try e.add(void_ty, .{ .ret = null });
}, },
.br => |t| _ = try e.add(void_ty, .{ .br = .{ .then = try e.blockFor(frame, t.index()) } }), .br => |t| {
const br = try e.add(void_ty, .{ .br = .{ .then = try e.blockFor(frame, t.index()) } });
// An `[unroll]` loop's back edge: marked for the unroller.
switch (f.blocks.items[t.index()].merge) {
.loop => |l| if (l.unroll == .unroll and l.@"continue".index() == bi) {
e.insts.at(br.inst).md = .unroll;
},
else => {},
}
},
.cond_br => |c| { .cond_br => |c| {
const cond = (try e.scalars(frame, c.cond))[0]; const cond = (try e.scalars(frame, c.cond))[0];
if (frame.taken.len > 0) if (e.constIntOf(cond)) |k| { if (frame.taken.len > 0) if (e.constIntOf(cond)) |k| {
@ -2233,6 +2277,7 @@ const Emitter = struct {
.constant => |c| return e.list(&.{try e.constant(i.ty, c)}), .constant => |c| return e.list(&.{try e.constant(i.ty, c)}),
.param => |p| return frame.params[p], .param => |p| return frame.params[p],
.spec_constant => return e.unsupported("specialization constants outside SPIR-V", .{}), .spec_constant => return e.unsupported("specialization constants outside SPIR-V", .{}),
.node_io => |x| return e.nodeIo(x),
.spirv_inst => return e.unsupported("inline SPIR-V outside SPIR-V", .{}), .spirv_inst => return e.unsupported("inline SPIR-V outside SPIR-V", .{}),
.ray_incoming => |k| { .ray_incoming => |k| {
// The shader's payload / attribute / parameter argument. // The shader's payload / attribute / parameter argument.
@ -2472,10 +2517,12 @@ const Emitter = struct {
if (frame.vals[s.ptr.index()] == .res_local) { if (frame.vals[s.ptr.index()] == .res_local) {
const slot = &e.res_locals.items[frame.vals[s.ptr.index()].res_local]; const slot = &e.res_locals.items[frame.vals[s.ptr.index()].res_local];
const h = frame.vals[s.value.index()]; const h = frame.vals[s.value.index()];
if (h != .handle and h != .res_array) return e.unsupported("resources not tied to a global are not supported yet", .{}); if (h != .handle and h != .res_array and h != .node) return e.unsupported("resources not tied to a global are not supported yet", .{});
// Selecting between resources at run time has no // Selecting between resources at run time has no
// handle-based lowering here; one assignment is fine. // handle-based lowering here; one assignment is fine.
if (slot.*) |old| if (!std.meta.eql(old, h)) return e.unsupported("assigning different resources to one variable is not supported yet (in '{s}')", .{frame.f.name}); // (Node objects: again, where every assignment is in
// one block.)
if (slot.*) |old| if (!std.meta.eql(old, h) and !(h == .node and storesInOneBlock(f, s.ptr))) return e.unsupported("assigning different resources to one variable is not supported yet (in '{s}')", .{frame.f.name});
slot.* = h; slot.* = h;
return .none; return .none;
} }
@ -2515,6 +2562,17 @@ const Emitter = struct {
}, },
.access => |a| { .access => |a| {
if (frame.vals[a.base.index()] == .mesh) return e.meshAccess(frame, frame.vals[a.base.index()].mesh, a.indices); if (frame.vals[a.base.index()] == .mesh) return e.meshAccess(frame, frame.vals[a.base.index()].mesh, a.indices);
if (frame.vals[a.base.index()] == .node) {
const nv = frame.vals[a.base.index()].node;
const idx = (try e.scalars(frame, a.indices[0]))[0];
if (nv.kind.outputElement()) |k| {
if (a.indices.len > 1) return e.unsupported("indexing a node output", .{});
return .{ .node = try e.nodeIndex(nv, k, idx) };
}
const tp = try e.nodeRecordPtr(nv, idx);
if (a.indices.len == 1) return .{ .typed = tp };
return .{ .typed = try e.typedAccess(frame, tp, a.indices[1..]) };
}
if (frame.vals[a.base.index()] == .typed) { if (frame.vals[a.base.index()] == .typed) {
var tp = frame.vals[a.base.index()].typed; var tp = frame.vals[a.base.index()].typed;
var path: std.ArrayList(Value) = .empty; var path: std.ArrayList(Value) = .empty;
@ -2798,6 +2856,7 @@ const Emitter = struct {
fn resCount(e: *Emitter, ty: TypeId) u32 { fn resCount(e: *Emitter, ty: TypeId) u32 {
return switch (e.t.get(ty)) { return switch (e.t.get(ty)) {
.resource, .sampler => if (isRayQuery(e.t, ty)) 0 else 1, .resource, .sampler => if (isRayQuery(e.t, ty)) 0 else 1,
.node => 1,
.array => |a| a.len * e.resCount(a.elem), .array => |a| a.len * e.resCount(a.elem),
.@"struct" => |st| blk: { .@"struct" => |st| blk: {
var n: u32 = 0; var n: u32 = 0;
@ -2844,7 +2903,7 @@ const Emitter = struct {
return switch (v) { return switch (v) {
.agg => |a| a, .agg => |a| a,
.scalars => |vals| if (e.resCount(ty) == 0) .{ .vals = vals, .res = &.{} } else e.unsupported("this value with resources is not supported yet", .{}), .scalars => |vals| if (e.resCount(ty) == 0) .{ .vals = vals, .res = &.{} } else e.unsupported("this value with resources is not supported yet", .{}),
.handle, .res_array => .{ .vals = &.{}, .res = try e.arena.dupe(Lowered, &.{v}) }, .handle, .res_array, .node => .{ .vals = &.{}, .res = try e.arena.dupe(Lowered, &.{v}) },
.none => .{ .vals = &.{}, .res = &.{} }, .none => .{ .vals = &.{}, .res = &.{} },
else => e.unsupported("this value with resources is not supported yet", .{}), else => e.unsupported("this value with resources is not supported yet", .{}),
}; };
@ -3274,6 +3333,34 @@ const Emitter = struct {
_ = try e.callOp(fn_i, try e.voidTy(), &.{ try e.i32Const(168), (try e.scalars(frame, args[0]))[0], (try e.scalars(frame, args[1]))[0] }); _ = try e.callOp(fn_i, try e.voidTy(), &.{ try e.i32Const(168), (try e.scalars(frame, args[0]))[0], (try e.scalars(frame, args[1]))[0] });
return .none; return .none;
} }
// SM 6.8's Barrier(memory types or a UAV, semantics): the
// arguments as they are (as dxc).
if (eq(u8, name, "GetRemainingRecursionLevels") and args.len == 0) {
const i32t = try e.dm.intType(32);
const fn_i = try e.dxOp("dx.op.getRemainingRecursionLevels", i32t, &.{i32t}, .nounwind_readonly);
return e.list(&.{try e.callOp(fn_i, i32t, &.{try e.i32Const(253)})});
}
if (eq(u8, name, "Barrier") and args.len == 2) {
const i32t = try e.dm.intType(32);
const sem = (try e.scalars(frame, args[1]))[0];
switch (frame.vals[args[0].index()]) {
.handle => |h| {
const fn_i = try e.dxOp("dx.op.barrierByMemoryHandle", try e.voidTy(), &.{ i32t, e.handle_ty, i32t }, .noduplicate_nounwind);
_ = try e.callOp(fn_i, try e.voidTy(), &.{ try e.i32Const(245), e.resources.items[h].handle, sem });
},
.scalars => |m| {
const fn_i = try e.dxOp("dx.op.barrierByMemoryType", try e.voidTy(), &.{ i32t, i32t, i32t }, .noduplicate_nounwind);
_ = try e.callOp(fn_i, try e.voidTy(), &.{ try e.i32Const(244), m[0], sem });
},
.node => |nv| {
const nt = try e.nodeTypes();
const fn_i = try e.dxOp("dx.op.barrierByNodeRecordHandle", try e.voidTy(), &.{ i32t, nt.record_handle, i32t }, .noduplicate_nounwind);
_ = try e.callOp(fn_i, try e.voidTy(), &.{ try e.i32Const(246), nv.handle, sem });
},
else => return e.unsupported("Barrier on this object is not supported yet", .{}),
}
return .none;
}
for (args) |x| if (frame.vals[x.index()] != .scalars) return e.unsupported("intrinsic '{s}' is not supported yet", .{name}); for (args) |x| if (frame.vals[x.index()] != .scalars) return e.unsupported("intrinsic '{s}' is not supported yet", .{name});
var a: [4][]const Value = undefined; var a: [4][]const Value = undefined;
for (args, 0..) |x, k| a[k] = try e.scalars(frame, x); for (args, 0..) |x, k| a[k] = try e.scalars(frame, x);
@ -3638,23 +3725,37 @@ const Emitter = struct {
} }
/// Interlocked*(dest, value(s) [, out original]) on groupshared memory, /// Interlocked*(dest, value(s) [, out original]) on groupshared memory,
/// buffer elements and texels. /// node records, buffer elements and texels. (The *FloatBitwise
/// compares: on the floats' bits.)
fn atomic(e: *Emitter, frame: *Frame, name: []const u8, args: []const Ref) Error!Lowered { fn atomic(e: *Emitter, frame: *Frame, name: []const u8, args: []const Ref) Error!Lowered {
const eq = std.mem.eql; const eq = std.mem.eql;
const op_name = name["Interlocked".len..]; const op_name = name["Interlocked".len..];
const dest_ty = frame.f.inst(args[0]).ty; const dest_ty = frame.f.inst(args[0]).ty;
const dc = e.compOf(dest_ty); const float_bits = std.mem.endsWith(u8, op_name, "FloatBitwise");
const dc: Scalar = if (float_bits and e.compOf(dest_ty) == .float) .uint else e.compOf(dest_ty);
const wide = dc.size() == 8 and !dc.isFloat() and (frame.vals[args[0].index()] == .buf or frame.vals[args[0].index()] == .texel); const wide = dc.size() == 8 and !dc.isFloat() and (frame.vals[args[0].index()] == .buf or frame.vals[args[0].index()] == .texel);
if ((dc.size() != 4 and !wide) or dc.isFloat()) return e.unsupported("'{s}' on '{s}' is not supported yet", .{ name, try e.t.format(e.arena, dest_ty) }); if ((dc.size() != 4 and !wide) or dc.isFloat()) return e.unsupported("'{s}' on '{s}' is not supported yet", .{ name, try e.t.format(e.arena, dest_ty) });
const i32t = try e.dm.intType(32); const i32t = try e.dm.intType(32);
const is_cmp = std.mem.startsWith(u8, op_name, "Compare"); const is_cmp = std.mem.startsWith(u8, op_name, "Compare");
const has_orig = (is_cmp and eq(u8, op_name, "CompareExchange")) or (!is_cmp and args.len == 3); const has_orig = (is_cmp and std.mem.startsWith(u8, op_name, "CompareExchange")) or (!is_cmp and args.len == 3);
const val = (try e.scalars(frame, args[if (is_cmp) 2 else 1]))[0]; const val = try e.atomicOperand(float_bits, (try e.scalars(frame, args[if (is_cmp) 2 else 1]))[0]);
const cmp = if (is_cmp) (try e.scalars(frame, args[1]))[0] else null; const cmp = if (is_cmp) try e.atomicOperand(float_bits, (try e.scalars(frame, args[1]))[0]) else null;
const orig: Value = switch (frame.vals[args[0].index()]) { const orig: Value = switch (frame.vals[args[0].index()]) {
.ptr => |p| blk: { .ptr, .typed => blk: {
const tag = std.meta.activeTag(frame.vals[args[0].index()]);
var ptr = if (tag == .ptr) p: {
const p = frame.vals[args[0].index()].ptr;
if (p.addr_space != 3) return e.unsupported("'{s}' on this variable is not supported yet", .{name}); if (p.addr_space != 3) return e.unsupported("'{s}' on this variable is not supported yet", .{name});
const ptr = try e.elementPtr(p, 0); break :p try e.elementPtr(p, 0);
} else p: {
const tp = frame.vals[args[0].index()].typed;
if (tp.addr_space != 6) return e.unsupported("'{s}' on this variable is not supported yet", .{name});
break :p try e.typedScalarPtr(tp, &.{}, try e.scalarTy(memScalar(e.compOf(dest_ty))));
};
if (float_bits) {
const as: u32 = if (tag == .ptr) 3 else 6;
ptr = try e.add(try e.dm.getType(.{ .pointer = .{ .elem = i32t, .addr_space = as } }), .{ .cast = .{ .op = .bitcast, .val = ptr } });
}
if (cmp) |cv| { if (cmp) |cv| {
const pair = try e.dm.getType(.{ .@"struct" = .{ .name = "", .elems = &.{ i32t, try e.dm.intType(1) } } }); const pair = try e.dm.getType(.{ .@"struct" = .{ .name = "", .elems = &.{ i32t, try e.dm.intType(1) } } });
const r = try e.add(pair, .{ .cmpxchg = .{ .ptr = ptr, .cmp = cv, .new = val } }); const r = try e.add(pair, .{ .cmpxchg = .{ .ptr = ptr, .cmp = cv, .new = val } });
@ -3679,10 +3780,25 @@ const Emitter = struct {
}, },
else => return e.unsupported("'{s}' on this destination is not supported yet", .{name}), else => return e.unsupported("'{s}' on this destination is not supported yet", .{name}),
}; };
if (has_orig) try e.storePtr(try e.outPtr(frame, args[args.len - 1]), &.{orig}, frame.f.inst(args[args.len - 1]).ty); const out_ty = frame.f.inst(args[args.len - 1]).ty;
const orig_val = if (float_bits and e.compOf(out_ty) == .float) try e.add(try e.dm.getType(.float), .{ .cast = .{ .op = .bitcast, .val = orig } }) else orig;
if (has_orig) try e.storePtr(try e.outPtr(frame, args[args.len - 1]), &.{orig_val}, out_ty);
return .none; return .none;
} }
/// An atomic's value: a float's bits for the *FloatBitwise compares
/// (constants folded).
fn atomicOperand(e: *Emitter, float_bits: bool, v: Value) Error!Value {
if (!float_bits) return v;
const i32t = try e.dm.intType(32);
if (v == .constant) switch (e.dm.constants.items[v.constant].kind) {
.float_bits => |b| return e.i32Const(@as(i32, @bitCast(@as(u32, @truncate(b))))),
else => {},
};
if (e.dm.types.items[try e.valueType(v)] != .float) return v;
return e.add(i32t, .{ .cast = .{ .op = .bitcast, .val = v } });
}
/// dx.op.atomicBinOp / atomicCompareExchange at `coords` (padded with /// dx.op.atomicBinOp / atomicCompareExchange at `coords` (padded with
/// undef to three). /// undef to three).
fn resourceAtomic(e: *Emitter, res: Resource, coords: []const Value, op_name: []const u8, dc: Scalar, val: Value, cmp: ?Value) Error!Value { fn resourceAtomic(e: *Emitter, res: Resource, coords: []const Value, op_name: []const u8, dc: Scalar, val: Value, cmp: ?Value) Error!Value {
@ -4385,6 +4501,7 @@ const Emitter = struct {
} }
fn method(e: *Emitter, frame: *Frame, name: []const u8, res_ref: Ref, arg_refs: []const Ref, ty: TypeId) Error!Lowered { fn method(e: *Emitter, frame: *Frame, name: []const u8, res_ref: Ref, arg_refs: []const Ref, ty: TypeId) Error!Lowered {
if (frame.vals[res_ref.index()] == .node) return e.nodeMethod(frame, frame.vals[res_ref.index()].node, name, arg_refs);
if (frame.vals[res_ref.index()] == .ray_query) return e.rayQueryMethod(frame, frame.vals[res_ref.index()].ray_query, name, arg_refs, ty); if (frame.vals[res_ref.index()] == .ray_query) return e.rayQueryMethod(frame, frame.vals[res_ref.index()].ray_query, name, arg_refs, ty);
const res = try e.resourceOf(frame, res_ref); const res = try e.resourceOf(frame, res_ref);
const kind = e.resourceKind(res.*); const kind = e.resourceKind(res.*);
@ -5343,7 +5460,7 @@ const Emitter = struct {
fn inputAt(e: *Emitter, k: u32, ty: TypeId, vertex: ?u32) Error!Lowered { fn inputAt(e: *Emitter, k: u32, ty: TypeId, vertex: ?u32) Error!Lowered {
const entry = e.entry; const entry = e.entry;
if (entry.stage == .compute or entry.stage == .mesh or entry.stage == .amplification) return e.computeInput(k, ty); if (entry.stage == .compute or entry.stage == .mesh or entry.stage == .amplification or entry.stage == .node) return e.computeInput(k, ty);
const el = entry.inputs.items[k]; const el = entry.inputs.items[k];
const se = if (e.in_elem[k]) |ei| &e.sig_in[ei] else return e.systemValueInput(el.semantic, ty); const se = if (e.in_elem[k]) |ei| &e.sig_in[ei] else return e.systemValueInput(el.semantic, ty);
if (se.interpretation == .shadow) return e.systemValueInput(el.semantic, ty); if (se.interpretation == .shadow) return e.systemValueInput(el.semantic, ty);
@ -5783,6 +5900,252 @@ const Emitter = struct {
} }
} }
// ---- Work graph nodes ------------------------------------------------
const NodeTypes = struct { handle: DType, record_handle: DType, info: DType, record_info: DType };
fn nodeTypes(e: *Emitter) Error!NodeTypes {
const i8p = try e.dm.ptrType(try e.dm.intType(8));
const i32t = try e.dm.intType(32);
return .{
.handle = try e.dm.getType(.{ .@"struct" = .{ .name = "dx.types.NodeHandle", .elems = &.{i8p} } }),
.record_handle = try e.dm.getType(.{ .@"struct" = .{ .name = "dx.types.NodeRecordHandle", .elems = &.{i8p} } }),
.info = try e.dm.getType(.{ .@"struct" = .{ .name = "dx.types.NodeInfo", .elems = &.{ i32t, i32t } } }),
.record_info = try e.dm.getType(.{ .@"struct" = .{ .name = "dx.types.NodeRecordInfo", .elems = &.{ i32t, i32t } } }),
};
}
/// A record type's size and alignment (0, 0 for empty inputs and
/// outputs).
fn recordLayout(e: *Emitter, record: TypeId) Error![2]u32 {
if (record == TypeTable.void_type) return .{ 0, 0 };
return e.memLayout(record);
}
/// annotateNodeHandle / annotateNodeRecordHandle of `raw`.
fn annotateNode(e: *Emitter, nv: NodeVal, raw: Value) Error!Value {
const nt = try e.nodeTypes();
const i32t = try e.dm.intType(32);
// (Inputs, empty ones too, and output records: record handles.)
const outputs = !nv.kind.isInput() and !nv.kind.hasRecords();
const info_ty = if (outputs) nt.info else nt.record_info;
const hty = if (outputs) nt.handle else nt.record_handle;
const f0 = try e.dm.constant(.{ .ty = i32t, .kind = .{ .int = nv.flags } });
const f1 = try e.dm.constant(.{ .ty = i32t, .kind = .{ .int = nv.size } });
const props = try e.dm.constant(.{ .ty = info_ty, .kind = .{ .aggregate = try e.arena.dupe(module.ConstId, &.{ f0.constant, f1.constant }) } });
const fn_i = if (outputs)
try e.dxOp("dx.op.annotateNodeHandle", hty, &.{ i32t, hty, info_ty }, .nounwind_readnone)
else
try e.dxOp("dx.op.annotateNodeRecordHandle", hty, &.{ i32t, hty, info_ty }, .nounwind_readnone);
return e.callOp(fn_i, hty, &.{ try e.i32Const(if (outputs) 249 else 251), raw, props });
}
/// The node shader's input or output `x.index`: its handle, created
/// and annotated.
fn nodeIo(e: *Emitter, x: @FieldType(ir.Op, "node_io")) Error!Lowered {
const info = e.entry.node orelse return e.unsupported("node objects outside node shaders", .{});
const io = if (x.output) info.outputs[x.index] else info.inputs[x.index];
const nt = try e.nodeTypes();
const i32t = try e.dm.intType(32);
var nv: NodeVal = .{ .kind = io.kind, .handle = undefined, .record = io.record, .flags = io.kind.ioFlags() | io.extra_flags, .size = (try e.recordLayout(io.record))[0] };
const raw = if (x.output)
try e.callOp(try e.dxOp("dx.op.createNodeOutputHandle", nt.handle, &.{ i32t, i32t }, .nounwind_readnone), nt.handle, &.{ try e.i32Const(247), try e.i32Const(x.index) })
else
try e.callOp(try e.dxOp("dx.op.createNodeInputRecordHandle", nt.record_handle, &.{ i32t, i32t }, .nounwind_readnone), nt.record_handle, &.{ try e.i32Const(250), try e.i32Const(x.index) });
nv.handle = try e.annotateNode(nv, raw);
return .{ .node = nv };
}
/// Output `idx` of an outputs array (annotated as the array).
fn nodeIndex(e: *Emitter, nv: NodeVal, kind: types.NodeKind, idx: Value) Error!NodeVal {
const nt = try e.nodeTypes();
const i32t = try e.dm.intType(32);
const fn_i = try e.dxOp("dx.op.indexNodeHandle", nt.handle, &.{ i32t, nt.handle, i32t }, .nounwind_readnone);
const raw = try e.callOp(fn_i, nt.handle, &.{ try e.i32Const(248), nv.handle, idx });
var out = nv;
out.handle = try e.annotateNode(nv, raw);
out.kind = kind;
return out;
}
/// Record `idx` of a node object, in node record memory.
fn nodeRecordPtr(e: *Emitter, nv: NodeVal, idx: Value) Error!@FieldType(Lowered, "typed") {
if (nv.record == TypeTable.void_type) return e.unsupported("records of an empty node input or output", .{});
const nt = try e.nodeTypes();
const i32t = try e.dm.intType(32);
const dty = try e.memoryType(nv.record);
const sname = switch (e.dm.types.items[dty]) {
.@"struct" => |st| st.name,
else => return e.unsupported("node records of type '{s}'", .{try e.t.format(e.arena, nv.record)}),
};
const pty = try e.dm.getType(.{ .pointer = .{ .elem = dty, .addr_space = 6 } });
const fn_i = try e.dxOp(try std.fmt.allocPrint(e.arena, "dx.op.getNodeRecordPtr.{s}", .{sname}), pty, &.{ i32t, nt.record_handle, i32t }, .nounwind_readnone);
const base = try e.callOp(fn_i, pty, &.{ try e.i32Const(239), nv.handle, idx });
return .{ .base = base, .dty = dty, .addr_space = 6, .ty = nv.record };
}
/// Methods of node objects.
fn nodeMethod(e: *Emitter, frame: *Frame, nv: NodeVal, name: []const u8, arg_refs: []const Ref) Error!Lowered {
const eq = std.mem.eql;
const nt = try e.nodeTypes();
const i32t = try e.dm.intType(32);
const i1t = try e.dm.intType(1);
const void_ty = try e.voidTy();
if (eq(u8, name, "IsValid")) {
const fn_i = try e.dxOp("dx.op.nodeOutputIsValid", i1t, &.{ i32t, nt.handle }, .nounwind_readonly);
return e.list(&.{try e.callOp(fn_i, i1t, &.{ try e.i32Const(252), nv.handle })});
}
if (eq(u8, name, "GetThreadNodeOutputRecords") or eq(u8, name, "GetGroupNodeOutputRecords")) {
const per_thread = eq(u8, name, "GetThreadNodeOutputRecords");
const n = (try e.scalars(frame, arg_refs[0]))[0];
const fn_i = try e.dxOp("dx.op.allocateNodeOutputRecords", nt.record_handle, &.{ i32t, nt.handle, i32t, i1t }, .nounwind);
const pt = try e.dm.constant(.{ .ty = i1t, .kind = .{ .int = @intFromBool(per_thread) } });
const raw = try e.callOp(fn_i, nt.record_handle, &.{ try e.i32Const(238), nv.handle, n, pt });
const kind: types.NodeKind = if (per_thread) .thread_output_records else .group_output_records;
var out: NodeVal = .{ .kind = kind, .handle = undefined, .record = nv.record, .flags = kind.ioFlags(), .size = nv.size };
out.handle = try e.annotateNode(out, raw);
return .{ .node = out };
}
if (eq(u8, name, "GroupIncrementOutputCount") or eq(u8, name, "ThreadIncrementOutputCount")) {
const n = (try e.scalars(frame, arg_refs[0]))[0];
const fn_i = try e.dxOp("dx.op.incrementOutputCount", void_ty, &.{ i32t, nt.handle, i32t, i1t }, .nounwind);
const pt = try e.dm.constant(.{ .ty = i1t, .kind = .{ .int = @intFromBool(eq(u8, name, "ThreadIncrementOutputCount")) } });
_ = try e.callOp(fn_i, void_ty, &.{ try e.i32Const(240), nv.handle, n, pt });
return .none;
}
if (eq(u8, name, "OutputComplete")) {
const fn_i = try e.dxOp("dx.op.outputComplete", void_ty, &.{ i32t, nt.record_handle }, .nounwind);
_ = try e.callOp(fn_i, void_ty, &.{ try e.i32Const(241), nv.handle });
return .none;
}
if (eq(u8, name, "Count")) {
const fn_i = try e.dxOp("dx.op.getInputRecordCount", i32t, &.{ i32t, nt.record_handle }, .nounwind_readonly);
return e.list(&.{try e.callOp(fn_i, i32t, &.{ try e.i32Const(242), nv.handle })});
}
if (eq(u8, name, "FinishedCrossGroupSharing")) {
const fn_i = try e.dxOp("dx.op.finishedCrossGroupSharing", i1t, &.{ i32t, nt.record_handle }, .nounwind);
return e.list(&.{try e.callOp(fn_i, i1t, &.{ try e.i32Const(243), nv.handle })});
}
return e.unsupported("node method '{s}' is not supported yet", .{name});
}
/// A node shader's entry properties (before its thread group size),
/// in dxc's order.
fn nodeProps(e: *Emitter, entry: ir.Entry, n: ir.NodeInfo, props: *std.ArrayList(?module.MdId)) Error!void {
const dm = &e.dm;
const I = struct {
fn f(m: *module.Module, v: i64) !?module.MdId {
return try m.mdI32(v);
}
}.f;
const i1t = try dm.intType(1);
const mdTrue = try dm.mdValue(i1t, try dm.constant(.{ .ty = i1t, .kind = .{ .int = 1 } }));
try props.appendSlice(e.arena, &.{ try I(dm, 13), try I(dm, @backingInt(n.launch)) });
if (entry.wave_size[0] != 0) {
const ws = entry.wave_size;
if (e.profile.minor >= 8) {
try props.appendSlice(e.arena, &.{ try I(dm, 23), try dm.mdNode(&.{ try I(dm, ws[0]), try I(dm, ws[1]), try I(dm, ws[2]) }) });
} else try props.appendSlice(e.arena, &.{ try I(dm, 11), try dm.mdNode(&.{try I(dm, ws[0])}) });
}
if (n.is_program_entry) try props.appendSlice(e.arena, &.{ try I(dm, 14), mdTrue });
try props.appendSlice(e.arena, &.{ try I(dm, 15), try dm.mdNode(&.{ try dm.mdString(n.id.name), try I(dm, n.id.index) }) });
try props.appendSlice(e.arena, &.{ try I(dm, 16), try I(dm, if (n.local_root_arguments_table_index) |x| @as(i64, x) else -1) });
if (n.share_input_of) |s| try props.appendSlice(e.arena, &.{ try I(dm, 17), try dm.mdNode(&.{ try dm.mdString(s.name), try I(dm, s.index) }) });
const grid = struct {
fn f(m: *module.Module, g: ?[3]u32) !?module.MdId {
const v = g orelse return null;
if (v[0] == 0 and v[1] == 0 and v[2] == 0) return null;
return try m.mdNode(&.{ try m.mdI32(v[0]), try m.mdI32(v[1]), try m.mdI32(v[2]) });
}
}.f;
if (try grid(dm, n.dispatch_grid)) |g| try props.appendSlice(e.arena, &.{ try I(dm, 18), g });
if (try grid(dm, n.max_dispatch_grid)) |g| try props.appendSlice(e.arena, &.{ try I(dm, 22), g });
if (n.max_recursion_depth) |d| if (d != 0) try props.appendSlice(e.arena, &.{ try I(dm, 19), try I(dm, d) });
if (n.inputs.len > 0) {
var l: std.ArrayList(?module.MdId) = .empty;
for (n.inputs) |io| try l.append(e.arena, try e.nodeIoProps(io));
try props.appendSlice(e.arena, &.{ try I(dm, 20), try dm.mdNode(l.items) });
}
if (n.outputs.len > 0) {
var l: std.ArrayList(?module.MdId) = .empty;
for (n.outputs) |io| try l.append(e.arena, try e.nodeIoProps(io));
try props.appendSlice(e.arena, &.{ try I(dm, 21), try dm.mdNode(l.items) });
}
}
/// One node input's / output's properties.
fn nodeIoProps(e: *Emitter, io: ir.NodeIo) Error!?module.MdId {
const dm = &e.dm;
var l: std.ArrayList(?module.MdId) = .empty;
try l.appendSlice(e.arena, &.{ try dm.mdI32(1), try dm.mdI32(io.kind.ioFlags() | io.extra_flags) });
const lay = try e.recordLayout(io.record);
if (lay[0] != 0) {
var r: std.ArrayList(?module.MdId) = .empty;
try r.appendSlice(e.arena, &.{ try dm.mdI32(0), try dm.mdI32(lay[0]) });
if (try e.dispatchGridField(io.record, 0)) |g| {
try r.appendSlice(e.arena, &.{ try dm.mdI32(1), try dm.mdNode(&.{ try dm.mdI32(g.offset), try dm.mdI32(g.comp), try dm.mdI32(g.count) }) });
}
try r.appendSlice(e.arena, &.{ try dm.mdI32(2), try dm.mdI32(lay[1]) });
try l.appendSlice(e.arena, &.{ try dm.mdI32(2), try dm.mdNode(r.items) });
}
const i1t = try dm.intType(1);
if (!io.kind.isInput()) {
try l.appendSlice(e.arena, &.{ try dm.mdI32(3), try dm.mdI32(io.max_records orelse 0) });
if (io.array_size) |a| if (a != 0) try l.appendSlice(e.arena, &.{ try dm.mdI32(5), try dm.mdI32(@as(i32, @bitCast(a))) });
if (io.max_records_shared_with) |s| try l.appendSlice(e.arena, &.{ try dm.mdI32(4), try dm.mdI32(s) });
if (io.allow_sparse_nodes) try l.appendSlice(e.arena, &.{ try dm.mdI32(6), try dm.mdValue(i1t, try dm.constant(.{ .ty = i1t, .kind = .{ .int = 1 } })) });
if (io.output_id) |id| try l.appendSlice(e.arena, &.{ try dm.mdI32(0), try dm.mdNode(&.{ try dm.mdString(id.name), try dm.mdI32(id.index) }) });
} else if (io.max_records) |m| if (m != 0) try l.appendSlice(e.arena, &.{ try dm.mdI32(3), try dm.mdI32(m) });
return try dm.mdNode(l.items);
}
/// SV_DispatchGrid in a record: byte offset, component type (U32 5,
/// U16 3) and component count.
const DispatchGrid = struct { offset: u32, comp: u32, count: u32 };
fn dispatchGridField(e: *Emitter, ty: TypeId, base: u32) Error!?DispatchGrid {
const st = switch (e.t.get(ty)) {
.@"struct" => |s| s,
else => return null,
};
var off: u32 = 0;
for (st.fields.items) |fld| {
const fl = try e.memLayout(fld.type);
off = std.mem.alignForward(u32, off, fl[1]);
if (fld.semantic) |sem| if (std.ascii.eqlIgnoreCase(sem, "SV_DispatchGrid")) {
const count: u32 = switch (e.t.get(fld.type)) {
.vector => |v| v.len,
.array => |a| a.len,
else => 1,
};
const scalar_size = fl[0] / count;
return .{ .offset = base + off, .comp = if (scalar_size == 2) 3 else 5, .count = count };
};
if (e.t.get(fld.type) == .@"struct") if (try e.dispatchGridField(fld.type, base + off)) |g| return g;
off += fl[0];
}
return null;
}
/// `tp` indexed by `indices` (struct members by constant index).
fn typedAccess(e: *Emitter, frame: *Frame, start: @FieldType(Lowered, "typed"), indices: []const Ref) Error!@FieldType(Lowered, "typed") {
var tp = start;
var path: std.ArrayList(Value) = .empty;
try path.appendSlice(e.arena, tp.path);
for (indices) |x| {
try path.append(e.arena, (try e.scalars(frame, x))[0]);
tp.ty = switch (e.t.get(tp.ty)) {
.@"struct" => |st| st.fields.items[@intCast(frame.f.inst(x).op.constant.int)].type,
.array => |arr| arr.elem,
.vector => |v| try e.t.scalar(v.elem),
.matrix => |mt| try e.t.vector(mt.elem, mt.cols),
else => return e.unsupported("indexing this member is not supported yet", .{}),
};
}
tp.path = path.items;
return tp;
}
fn typedScalarPtr(e: *Emitter, tp: @FieldType(Lowered, "typed"), sub: []const Value, st: DType) Error!Value { fn typedScalarPtr(e: *Emitter, tp: @FieldType(Lowered, "typed"), sub: []const Value, st: DType) Error!Value {
const idx = try e.arena.alloc(Value, 1 + tp.path.len + sub.len); const idx = try e.arena.alloc(Value, 1 + tp.path.len + sub.len);
idx[0] = try e.i32Const(0); idx[0] = try e.i32Const(0);
@ -6178,7 +6541,7 @@ const Emitter = struct {
}.f; }.f;
const ident = try dm.mdNode(&.{try dm.mdString("zdxc 0.0.0")}); const ident = try dm.mdNode(&.{try dm.mdString("zdxc 0.0.0")});
const version = try dm.mdNode(&.{ try mdI32(dm, 1), try mdI32(dm, e.profile.minor) }); const version = try dm.mdNode(&.{ try mdI32(dm, 1), try mdI32(dm, e.profile.minor) });
const val_ver = try dm.mdNode(&.{ try mdI32(dm, 1), try mdI32(dm, 11) }); const val_ver = try dm.mdNode(&.{ try mdI32(dm, shader.validator[0]), try mdI32(dm, shader.validator[1]) });
const sm = try dm.mdNode(&.{ try dm.mdString("lib"), try mdI32(dm, e.profile.major), try mdI32(dm, e.profile.minor) }); const sm = try dm.mdNode(&.{ try dm.mdString("lib"), try mdI32(dm, e.profile.major), try mdI32(dm, e.profile.minor) });
const resources = try e.resourcesMd(); const resources = try e.resourcesMd();
const analysis = try e.libAnalysis(funcs); const analysis = try e.libAnalysis(funcs);
@ -6713,6 +7076,78 @@ const Emitter = struct {
return @intCast(n); return @intCast(n);
} }
/// A node shader's RDAT NodeShaderInfo (as dxc's AddShaderNodeInfo).
fn rdatNode(e: *Emitter, b: *rdat.Builder, entry: ir.Entry, n: ir.NodeInfo, groupshared: u32) Error!u32 {
const rec = struct {
fn f(bb: *rdat.Builder, t: rdat.Ext, words: []const u32) !u32 {
return bb.record(t, std.mem.sliceAsBytes(words));
}
}.f;
var attrs: std.ArrayList(u32) = .empty;
// NodeFuncAttribKind: ID 1, NumThreads 2, ShareInputOf 3,
// DispatchGrid 4, MaxRecursionDepth 5, LocalRootArgumentsTableIndex
// 6, MaxDispatchGrid 7.
const id = try rec(b, .node_ids, &.{ try b.string(n.id.name), n.id.index });
try attrs.append(e.arena, try rec(b, .node_func_attribs, &.{ 1, id }));
const nt = entry.num_threads;
if (nt[0] != 0 or nt[1] != 0 or nt[2] != 0) try attrs.append(e.arena, try rec(b, .node_func_attribs, &.{ 2, try b.array(&nt) }));
if (n.local_root_arguments_table_index) |x| try attrs.append(e.arena, try rec(b, .node_func_attribs, &.{ 6, x }));
if (n.share_input_of) |s| {
const sid = try rec(b, .node_ids, &.{ try b.string(s.name), s.index });
try attrs.append(e.arena, try rec(b, .node_func_attribs, &.{ 3, sid }));
}
if (n.dispatch_grid) |g| if (g[0] != 0 or g[1] != 0 or g[2] != 0) try attrs.append(e.arena, try rec(b, .node_func_attribs, &.{ 4, try b.array(&g) }));
if (n.max_recursion_depth) |d| if (d != 0) try attrs.append(e.arena, try rec(b, .node_func_attribs, &.{ 5, d }));
if (n.max_dispatch_grid) |g| if (g[0] != 0 or g[1] != 0 or g[2] != 0) try attrs.append(e.arena, try rec(b, .node_func_attribs, &.{ 7, try b.array(&g) }));
const func_attrs = try b.array(attrs.items);
const inputs = try e.rdatIoNodes(b, n.inputs);
const outputs = try e.rdatIoNodes(b, n.outputs);
return rec(b, .node_shaders, &.{ @backingInt(n.launch), groupshared, func_attrs, outputs, inputs });
}
/// The IONode records of node inputs or outputs (an index array).
fn rdatIoNodes(e: *Emitter, b: *rdat.Builder, ios: []const ir.NodeIo) Error!u32 {
const rec = struct {
fn f(bb: *rdat.Builder, t: rdat.Ext, words: []const u32) !u32 {
return bb.record(t, std.mem.sliceAsBytes(words));
}
}.f;
var nodes: std.ArrayList(u32) = .empty;
for (ios) |io| {
// NodeAttribKind: OutputID 1, MaxRecords 2, MaxRecordsSharedWith
// 3, RecordSizeInBytes 4, RecordDispatchGrid 5, OutputArraySize
// 6, AllowSparseNodes 7, RecordAlignmentInBytes 8.
var attrs: std.ArrayList(u32) = .empty;
if (!io.kind.isInput()) {
const oid = io.output_id orelse ir.NodeId{ .name = "" };
const id = try rec(b, .node_ids, &.{ try b.string(oid.name), oid.index });
try attrs.append(e.arena, try rec(b, .node_io_attribs, &.{ 1, id }));
try attrs.append(e.arena, try rec(b, .node_io_attribs, &.{ 6, io.array_size orelse 0 }));
if (io.max_records orelse 0 != 0) {
try attrs.append(e.arena, try rec(b, .node_io_attribs, &.{ 2, io.max_records.? }));
} else if (io.max_records_shared_with) |s| {
try attrs.append(e.arena, try rec(b, .node_io_attribs, &.{ 3, s }));
}
if (io.allow_sparse_nodes) try attrs.append(e.arena, try rec(b, .node_io_attribs, &.{ 7, 1 }));
} else if (io.max_records orelse 0 != 0) {
try attrs.append(e.arena, try rec(b, .node_io_attribs, &.{ 2, io.max_records.? }));
}
const lay = try e.recordLayout(io.record);
if (lay[0] != 0) {
try attrs.append(e.arena, try rec(b, .node_io_attribs, &.{ 4, lay[0] }));
if (try e.dispatchGridField(io.record, 0)) |g| {
// ByteOffset (u16), then components (bits 0..1) and
// component type (from bit 2).
try attrs.append(e.arena, try rec(b, .node_io_attribs, &.{ 5, g.offset | ((g.count & 3) | (g.comp << 2)) << 16 }));
}
if (lay[1] != 0) try attrs.append(e.arena, try rec(b, .node_io_attribs, &.{ 8, lay[1] }));
}
const arr = try b.array(attrs.items);
try nodes.append(e.arena, try rec(b, .io_nodes, &.{ io.kind.ioFlags() | io.extra_flags, arr }));
}
return b.array(nodes.items);
}
/// The library container: feature info, runtime data (RDAT) and the /// The library container: feature info, runtime data (RDAT) and the
/// program. /// program.
fn assembleLibrary(e: *Emitter, gpa: Allocator, funcs: []const LibFunc, bitcode: []const u8) Error![]u8 { fn assembleLibrary(e: *Emitter, gpa: Allocator, funcs: []const LibFunc, bitcode: []const u8) Error![]u8 {
@ -6770,6 +7205,12 @@ const Emitter = struct {
.cbuffers = func_cbuffers.items, .cbuffers = func_cbuffers.items,
}); });
const resources = if (used.items.len > 0) try b.array(used.items) else rdat.null_ref; const resources = if (used.items.len > 0) try b.array(used.items) else rdat.null_ref;
var shader_flags: u16 = 0;
const node_info = if (lf.stage == .node) blk: {
const n = lf.entry.node.?;
if (n.is_program_entry) shader_flags |= 1;
break :blk try e.rdatNode(&b, lf.entry, n, lf.groupshared);
} else rdat.null_ref;
const props = if (e.uses_linalg) try linalg_info.rdatProperties(e.arena, &b, &try linalg_info.functionInfo(e.arena, &e.dm, mats, lf.func)) else rdat.null_ref; const props = if (e.uses_linalg) try linalg_info.rdatProperties(e.arena, &b, &try linalg_info.functionInfo(e.arena, &e.dm, mats, lf.func)) else rdat.null_ref;
const kind = shaderKind(lf.stage); const kind = shaderKind(lf.stage);
try b.addFunction(.{ try b.addFunction(.{
@ -6783,6 +7224,11 @@ const Emitter = struct {
.feature_info2 = @truncate(libinfo.featureInfo(info.flags) >> 32), .feature_info2 = @truncate(libinfo.featureInfo(info.flags) >> 32),
.shader_stage_flag = if (lf.stage == .library) info.mask & 0xffff else info.mask & (@as(u32, 1) << @intCast(kind)), .shader_stage_flag = if (lf.stage == .library) info.mask & 0xffff else info.mask & (@as(u32, 1) << @intCast(kind)),
.min_shader_target = (kind << 16) | (6 << 4) | libinfo.minMinor(info, if (lf.stage == .library) null else kind), .min_shader_target = (kind << 16) | (6 << 4) | libinfo.minMinor(info, if (lf.stage == .library) null else kind),
// (RDAT: 0 where none is specified.)
.min_wave_lanes = @intCast(lf.entry.wave_size[0]),
.max_wave_lanes = @intCast(if (lf.entry.wave_size[1] != 0) lf.entry.wave_size[1] else lf.entry.wave_size[0]),
.shader_flags = shader_flags,
.raw_shader_ref = node_info,
.extended_properties = props, .extended_properties = props,
}); });
} }
@ -6838,6 +7284,14 @@ const Emitter = struct {
}); });
} }
/// The wave lane counts PSV and RDAT give: WaveSize's minimum, and its
/// maximum (a range) or the minimum again; with none, 0 and maxInt.
fn waveLanes(entry: ir.Entry) [2]u32 {
const ws = entry.wave_size;
if (ws[0] == 0) return .{ 0, std.math.maxInt(u32) };
return .{ ws[0], if (ws[1] != 0) ws[1] else ws[0] };
}
/// Entry properties of the stage: thread group size and the GS / HS / /// Entry properties of the stage: thread group size and the GS / HS /
/// DS / MS / AS state. /// DS / MS / AS state.
fn stageProps(e: *Emitter, entry: ir.Entry, props: *std.ArrayList(?module.MdId)) Error!void { fn stageProps(e: *Emitter, entry: ir.Entry, props: *std.ArrayList(?module.MdId)) Error!void {
@ -6848,7 +7302,20 @@ const Emitter = struct {
} }
}.f; }.f;
const threads = try dm.mdNode(&.{ try mdI32(dm, entry.num_threads[0]), try mdI32(dm, entry.num_threads[1]), try mdI32(dm, entry.num_threads[2]) }); const threads = try dm.mdNode(&.{ try mdI32(dm, entry.num_threads[0]), try mdI32(dm, entry.num_threads[1]), try mdI32(dm, entry.num_threads[2]) });
if (entry.node) |n| {
try e.nodeProps(entry, n, props);
try props.appendSlice(e.arena, &.{ try mdI32(dm, 4), threads });
return;
}
if (entry.stage == .compute) try props.appendSlice(e.arena, &.{ try mdI32(dm, 4), threads }); if (entry.stage == .compute) try props.appendSlice(e.arena, &.{ try mdI32(dm, 4), threads });
// WaveSize: a value (tag 11) before SM 6.8, a range with a
// preferred size after (tag 23; zeros where not given).
if (entry.wave_size[0] != 0) {
const ws = entry.wave_size;
if (e.profile.minor >= 8) {
try props.appendSlice(e.arena, &.{ try mdI32(dm, 23), try dm.mdNode(&.{ try mdI32(dm, ws[0]), try mdI32(dm, ws[1]), try mdI32(dm, ws[2]) }) });
} else try props.appendSlice(e.arena, &.{ try mdI32(dm, 11), try dm.mdNode(&.{try mdI32(dm, ws[0])}) });
}
const payload_size: u32 = if (entry.mesh.payload) |p| try e.payloadSize(p) else 0; const payload_size: u32 = if (entry.mesh.payload) |p| try e.payloadSize(p) else 0;
if (entry.stage == .mesh) { if (entry.stage == .mesh) {
// MS state: thread group, max vertices, max primitives, // MS state: thread group, max vertices, max primitives,
@ -6914,7 +7381,7 @@ const Emitter = struct {
const ident = try dm.mdNode(&.{try dm.mdString("zdxc 0.0.0")}); const ident = try dm.mdNode(&.{try dm.mdString("zdxc 0.0.0")});
const version = try dm.mdNode(&.{ try mdI32(dm, 1), try mdI32(dm, e.profile.minor) }); const version = try dm.mdNode(&.{ try mdI32(dm, 1), try mdI32(dm, e.profile.minor) });
const val_ver = try dm.mdNode(&.{ try mdI32(dm, 1), try mdI32(dm, 11) }); const val_ver = try dm.mdNode(&.{ try mdI32(dm, shader.validator[0]), try mdI32(dm, shader.validator[1]) });
const sm = try dm.mdNode(&.{ try dm.mdString(e.profile.kind.profilePrefix()), try mdI32(dm, e.profile.major), try mdI32(dm, e.profile.minor) }); const sm = try dm.mdNode(&.{ try dm.mdString(e.profile.kind.profilePrefix()), try mdI32(dm, e.profile.major), try mdI32(dm, e.profile.minor) });
const resources = try e.resourcesMd(); const resources = try e.resourcesMd();
@ -7064,6 +7531,7 @@ const Emitter = struct {
.entry = entry.name, .entry = entry.name,
.stage_info = stage_info, .stage_info = stage_info,
.num_threads = if (threaded) entry.num_threads else .{ 0, 0, 0 }, .num_threads = if (threaded) entry.num_threads else .{ 0, 0, 0 },
.wave_lanes = waveLanes(entry),
.mesh_topology = if (entry.stage == .mesh) @backingInt(entry.mesh.topology) else 0, .mesh_topology = if (entry.stage == .mesh) @backingInt(entry.mesh.topology) else 0,
.uses_view_id = e.uses_view_id, .uses_view_id = e.uses_view_id,
.resources = binds.items, .resources = binds.items,
@ -7150,15 +7618,29 @@ fn gsTopology(g: ir.GeometryInfo) u32 {
return 1; return 1;
} }
/// Resources, samplers and (handles too) work graph node objects.
fn isResourceType(t: *TypeTable, ty: TypeId) bool { fn isResourceType(t: *TypeTable, ty: TypeId) bool {
return switch (t.get(ty)) { return switch (t.get(ty)) {
.resource, .sampler => true, .resource, .sampler, .node => true,
else => false, else => false,
}; };
} }
const isRayQuery = @import("../ir/lower.zig").isRayQuery; const isRayQuery = @import("../ir/lower.zig").isRayQuery;
/// Whether the stores to local `ptr` are all in one block of `f`.
fn storesInOneBlock(f: *const ir.Function, ptr: Ref) bool {
var found: ?usize = null;
for (f.blocks.items, 0..) |blk, bi| for (blk.insts.items) |r| switch (f.inst(r).op) {
.store => |x| if (x.ptr == ptr) {
if (found) |b| if (b != bi) return false;
found = bi;
},
else => {},
};
return true;
}
fn reachableBlocks(a: Allocator, f: *const ir.Function) Allocator.Error![]bool { fn reachableBlocks(a: Allocator, f: *const ir.Function) Allocator.Error![]bool {
return reachableBlocksTaken(a, f, &.{}); return reachableBlocksTaken(a, f, &.{});
} }

View File

@ -191,6 +191,22 @@ pub fn analyze(m: *const module.Module, f: *const module.Function, o: Options) I
fl |= bit.requires_group; fl |= bit.requires_group;
info.mask &= stage_group; info.mask &= stage_group;
}, },
// Barrier by memory type, UAV or node record: groupshared memory
// (not as part of ALL_MEMORY, which may drop it) or group
// sync / scope semantics need a group (as dxc's
// BarrierRequiresGroup).
244, 245, 246 => if (args.len > 2) {
var needs = false;
if (code == 244) if (constInt(m, args[1])) |mem| {
const kept = if (mem == 0xF) mem & ~@as(i64, 2) else mem;
needs = kept & 2 != 0;
};
if (constInt(m, args[2])) |sem| needs = needs or sem & 3 != 0;
if (needs) {
fl |= bit.requires_group;
info.mask &= stage_group;
}
},
else => {}, else => {},
} }
} }

View File

@ -106,7 +106,7 @@ const ConstantContext = struct {
pub const Linkage = enum(u32) { external = 0, internal = 3 }; pub const Linkage = enum(u32) { external = 0, internal = 3 };
/// Attribute group for function declarations (e.g. dx.op functions). /// Attribute group for function declarations (e.g. dx.op functions).
pub const FnAttrs = enum { none, nounwind, nounwind_readnone, nounwind_readonly, noreturn_nounwind, noinline_nounwind }; pub const FnAttrs = enum { none, nounwind, nounwind_readnone, nounwind_readonly, noreturn_nounwind, noinline_nounwind, noduplicate_nounwind };
pub const Value = union(enum) { pub const Value = union(enum) {
/// Index into Module.globals (a pointer to the variable). /// Index into Module.globals (a pointer to the variable).
@ -164,7 +164,17 @@ pub const Inst = struct {
/// An instruction's metadata attachment: an index into Module.inst_mds, /// An instruction's metadata attachment: an index into Module.inst_mds,
/// kept out of line (few instructions have one). /// kept out of line (few instructions have one).
pub const InstMd = enum(u32) { none = 0, _ }; /// `unroll` is no attachment: it marks the back edge of an `[unroll]` loop
/// for the unroller, and is not written.
pub const InstMd = enum(u32) {
none = 0,
unroll = std.math.maxInt(u32),
_,
pub fn written(md: InstMd) bool {
return md != .none and md != .unroll;
}
};
pub const Function = struct { pub const Function = struct {
name: []const u8, name: []const u8,
@ -671,12 +681,19 @@ const Encoder = struct {
} }
fn writeAttributes(e: *Encoder) !void { fn writeAttributes(e: *Encoder) !void {
// Groups 1..5 match FnAttrs order; each applies to the function (index 0xFFFFFFFF). // Groups 1..6 match FnAttrs order; each applies to the function (index 0xFFFFFFFF).
// Attribute kinds: noinline = 14, noreturn = 17, nounwind = 18, // Attribute kinds: noduplicate = 12, noinline = 14, noreturn = 17,
// readnone = 20, readonly = 21. // nounwind = 18, readnone = 20, readonly = 21.
const w = &e.w; const w = &e.w;
try w.enterBlock(block_paramattr_group, 3); try w.enterBlock(block_paramattr_group, 3);
const groups = [_][]const u64{ &.{18}, &.{ 18, 20 }, &.{ 18, 21 }, &.{ 17, 18 }, &.{ 14, 18 } }; const all = [_][]const u64{ &.{18}, &.{ 18, 20 }, &.{ 18, 21 }, &.{ 17, 18 }, &.{ 14, 18 }, &.{ 12, 18 } };
// noduplicate (the SM 6.8 barriers) only when used: the rest of
// the modules are as they were.
var n: usize = 5;
for (e.m.functions.items) |f| {
if (f.attrs == .noduplicate_nounwind) n = 6;
}
const groups = all[0..n];
for (groups, 1..) |kinds, id| { for (groups, 1..) |kinds, id| {
try e.push(id); try e.push(id);
try e.push(0xFFFFFFFF); try e.push(0xFFFFFFFF);
@ -970,10 +987,10 @@ const Encoder = struct {
} }
// METADATA_ATTACHMENT: [instruction index, (kind, node)...] // METADATA_ATTACHMENT: [instruction index, (kind, node)...]
var any_md = false; var any_md = false;
for (f.insts.items) |inst| any_md = any_md or inst.md != .none; for (f.insts.items) |inst| any_md = any_md or inst.md.written();
if (any_md) { if (any_md) {
try w.enterBlock(block_metadata_attachment, 3); try w.enterBlock(block_metadata_attachment, 3);
for (f.insts.items, 0..) |inst, k| if (inst.md != .none) { for (f.insts.items, 0..) |inst, k| if (inst.md.written()) {
const md = e.m.inst_mds.items[@backingInt(inst.md) - 1]; const md = e.m.inst_mds.items[@backingInt(inst.md) - 1];
try e.ops.appendSlice(e.gpa(), &.{ k, md.kind, md.node }); try e.ops.appendSlice(e.gpa(), &.{ k, md.kind, md.node });
try e.rec(11); try e.rec(11);

View File

@ -23,14 +23,14 @@ const TypeId = module.TypeId;
const none = std.math.maxInt(u32); const none = std.math.maxInt(u32);
const Role = enum { load_ptr, store_ptr, gep_base, other }; pub const Role = enum { load_ptr, store_ptr, gep_base, other };
const Edge = @typeInfo(@FieldType(@FieldType(@FieldType(Inst, "op"), "phi"), "incoming")).pointer.child; const Edge = @typeInfo(@FieldType(@FieldType(@FieldType(Inst, "op"), "phi"), "incoming")).pointer.child;
/// Visits each operand of `inst` (with the way it is used) through /// Visits each operand of `inst` (with the way it is used) through
/// `ctx.visit(value, role) Value`. With `write`, the results replace the /// `ctx.visit(value, role) Value`. With `write`, the results replace the
/// operands, in newly allocated slices where the operands are slices. /// operands, in newly allocated slices where the operands are slices.
fn operands(comptime write: bool, a: Allocator, inst: *Inst, ctx: anytype) Allocator.Error!void { pub fn operands(comptime write: bool, a: Allocator, inst: *Inst, ctx: anytype) Allocator.Error!void {
const S = struct { const S = struct {
fn one(c: anytype, v: *Value, role: Role) void { fn one(c: anytype, v: *Value, role: Role) void {
const r = c.visit(v.*, role); const r = c.visit(v.*, role);
@ -1088,6 +1088,7 @@ fn simplify(m: *module.Module, f: *const module.Function, repl: []const ?Value,
return null; return null;
}, },
.binop => |b| { .binop => |b| {
if (try foldFloat(m, repl, inst)) |v| return v;
const w = S.intWidth(m, inst.ty) orelse return null; const w = S.intWidth(m, inst.ty) orelse return null;
const l = resolve(repl, b.lhs); const l = resolve(repl, b.lhs);
const r = resolve(repl, b.rhs); const r = resolve(repl, b.rhs);
@ -1127,6 +1128,10 @@ fn simplify(m: *module.Module, f: *const module.Function, repl: []const ?Value,
.@"and" => if (S.bits(x, w) == S.bits(-1, w)) return r, .@"and" => if (S.bits(x, w) == S.bits(-1, w)) return r,
else => {}, else => {},
}; };
if (b.op == .@"and" and w <= 64) {
if (rc) |y| return andKnown(m, f, repl, n, l, S.bits(y, w), w, inst.ty);
if (lc) |x| return andKnown(m, f, repl, n, r, S.bits(x, w), w, inst.ty);
}
return null; return null;
}, },
.cmp => |c| { .cmp => |c| {
@ -1159,9 +1164,30 @@ fn simplify(m: *module.Module, f: *const module.Function, repl: []const ?Value,
return try m.constant(.{ .ty = inst.ty, .kind = .{ .int = @intFromBool(t) } }); return try m.constant(.{ .ty = inst.ty, .kind = .{ .int = @intFromBool(t) } });
} }
if (c.pred < 32 or c.pred > 41) return null; // integer predicates if (c.pred < 32 or c.pred > 41) return null; // integer predicates
// A bool widened and compared again: `zext i1 x != 0` and
// `zext i1 x == 1` are x.
if (c.pred == 32 or c.pred == 33) if (l == .inst and l.inst < n) {
const z = f.insts.items[l.inst].op;
if (z == .cast and z.cast.op == .zext) {
const x = resolve(repl, z.cast.val);
if (S.intWidth(m, S.ty(m, f, n, phi_var, var_ty, x)) == 1) {
if (constInt(m, r)) |k| {
if ((c.pred == 33 and k == 0) or (c.pred == 32 and k == 1)) return x;
}
}
}
};
const w = S.intWidth(m, S.ty(m, f, n, phi_var, var_ty, l)) orelse return null; const w = S.intWidth(m, S.ty(m, f, n, phi_var, var_ty, l)) orelse return null;
const x = S.bits(constInt(m, l) orelse return null, w); // Each side's possible values: a constant, or selects and phis
const y = S.bits(constInt(m, r) orelse return null, w); // of constants (`(c ? 2 : 1) == 3` is false, as dxc's
// instcombine finds); the same answer for every pair folds.
var lv: Cands = .{};
var rv: Cands = .{};
if (!lv.add(m, f, repl, n, l, 2) or !rv.add(m, f, repl, n, r, 2)) return null;
var result: ?bool = null;
for (lv.vals[0..lv.len]) |lk| for (rv.vals[0..rv.len]) |rk| {
const x = S.bits(lk, w);
const y = S.bits(rk, w);
const sx = S.stored(x, w); const sx = S.stored(x, w);
const sy = S.stored(y, w); const sy = S.stored(y, w);
const t = switch (c.pred) { const t = switch (c.pred) {
@ -1176,8 +1202,12 @@ fn simplify(m: *module.Module, f: *const module.Function, repl: []const ?Value,
40 => sx < sy, 40 => sx < sy,
else => sx <= sy, else => sx <= sy,
}; };
return try m.constant(.{ .ty = inst.ty, .kind = .{ .int = @intFromBool(t) } }); if (result) |prev| if (prev != t) return null;
result = t;
};
return try m.constant(.{ .ty = inst.ty, .kind = .{ .int = @intFromBool(result orelse return null) } });
}, },
.call => return foldDxOp(m, repl, inst),
.select => |sl| { .select => |sl| {
const t = resolve(repl, sl.t); const t = resolve(repl, sl.t);
const fv = resolve(repl, sl.f); const fv = resolve(repl, sl.f);
@ -1250,6 +1280,240 @@ fn edgePhi(m: *module.Module, insts: []const Inst, block_start: []const u32, rep
return try m.constant(.{ .ty = inst.ty, .kind = .{ .int = same orelse return null } }); return try m.constant(.{ .ty = inst.ty, .kind = .{ .int = same orelse return null } });
} }
/// The integer constants a value can be: itself if constant, or each arm
/// of a select or input of a phi that is (`depth` levels deep).
const Cands = struct {
vals: [8]i64 = undefined,
len: usize = 0,
fn add(c: *Cands, m: *const module.Module, f: *const module.Function, repl: []const ?Value, n: u32, v: Value, depth: u32) bool {
const x = resolve(repl, v);
if (constInt(m, x)) |k| {
for (c.vals[0..c.len]) |e| if (e == k) return true;
if (c.len == c.vals.len) return false;
c.vals[c.len] = k;
c.len += 1;
return true;
}
if (x != .inst or x.inst >= n or depth == 0) return false;
switch (f.insts.items[x.inst].op) {
.select => |sl| return c.add(m, f, repl, n, sl.t, depth - 1) and c.add(m, f, repl, n, sl.f, depth - 1),
.phi => |p| {
for (p.incoming) |in| {
const y = resolve(repl, in.val);
if (y == .inst and y.inst == x.inst) continue;
if (!c.add(m, f, repl, n, y, depth - 1)) return false;
}
return c.len > 0;
},
else => return false,
}
}
};
/// The bits of the `w`-bit integer `v` known to be zero, from what
/// computes it (`depth` levels deep): constants, masks, shifts by
/// constants, widening, and the bitwise operations and selects of such.
fn knownZero(m: *const module.Module, f: *const module.Function, repl: []const ?Value, n: u32, v: Value, w: u32, depth: u32) u64 {
const mask: u64 = if (w >= 64) ~@as(u64, 0) else (@as(u64, 1) << @intCast(w)) - 1;
const x = resolve(repl, v);
if (constInt(m, x)) |k| return ~@as(u64, @bitCast(k)) & mask;
if (x != .inst or x.inst >= n or depth == 0) return 0;
const inst = f.insts.items[x.inst];
const d = depth - 1;
return mask & switch (inst.op) {
.binop => |b| switch (b.op) {
.@"and" => knownZero(m, f, repl, n, b.lhs, w, d) | knownZero(m, f, repl, n, b.rhs, w, d),
.@"or", .xor => knownZero(m, f, repl, n, b.lhs, w, d) & knownZero(m, f, repl, n, b.rhs, w, d),
.shl => blk: {
const k = constInt(m, resolve(repl, b.rhs)) orelse break :blk 0;
if (k < 0 or k >= w) break :blk 0;
const sh: u6 = @intCast(k);
break :blk (knownZero(m, f, repl, n, b.lhs, w, d) << sh) | ((@as(u64, 1) << sh) - 1);
},
.lshr => blk: {
const k = constInt(m, resolve(repl, b.rhs)) orelse break :blk 0;
if (k < 0 or k >= w) break :blk 0;
const sh: u6 = @intCast(k);
break :blk (knownZero(m, f, repl, n, b.lhs, w, d) >> sh) | ~(mask >> sh);
},
else => 0,
},
.cast => |c| switch (c.op) {
.zext => blk: {
// (A phi promotion made has no instruction to read its
// type from yet.)
const src = resolve(repl, c.val);
if (src == .inst and src.inst >= n) break :blk 0;
const from = switch (m.types.items[typeOf(m, f, src)]) {
.int => |iw| iw,
else => break :blk 0,
};
const from_mask: u64 = if (from >= 64) ~@as(u64, 0) else (@as(u64, 1) << @intCast(from)) - 1;
break :blk knownZero(m, f, repl, n, c.val, from, d) | ~from_mask;
},
else => 0,
},
.select => |sl| knownZero(m, f, repl, n, sl.t, w, d) & knownZero(m, f, repl, n, sl.f, w, d),
else => 0,
};
}
/// `x & c` (`w` bits) when known bits decide it, as dxc's instcombine
/// does: 0 if every bit `c` keeps is known zero in `x`; `x` if every bit
/// it clears already is; and through `a | b` where `b` only has bits `c`
/// clears and `a` only bits it keeps, `a`. (Flags packed into one integer
/// with other fields, then tested.)
fn andKnown(m: *module.Module, f: *const module.Function, repl: []const ?Value, n: u32, x: Value, c: u64, w: u32, ty: TypeId) Allocator.Error!?Value {
const mask: u64 = if (w >= 64) ~@as(u64, 0) else (@as(u64, 1) << @intCast(w)) - 1;
const kz = knownZero(m, f, repl, n, x, w, 6);
if (c & ~kz & mask == 0) return try m.constant(.{ .ty = ty, .kind = .{ .int = 0 } });
if (~c & ~kz & mask == 0) return resolve(repl, x);
const xr = resolve(repl, x);
if (xr == .inst and xr.inst < n) {
const inst = f.insts.items[xr.inst];
if (inst.op == .binop and inst.op.binop.op == .@"or") {
const o = inst.op.binop;
const sides = [2][2]Value{ .{ o.lhs, o.rhs }, .{ o.rhs, o.lhs } };
for (sides) |ab| {
const kb = knownZero(m, f, repl, n, ab[1], w, 6);
const ka = knownZero(m, f, repl, n, ab[0], w, 6);
if (c & ~kb & mask == 0 and ~c & ~ka & mask == 0) return resolve(repl, ab[0]);
}
}
}
return null;
}
/// A half, float or double constant of type `ty` with value `x` (rounded
/// to the type).
fn floatConst(m: *module.Module, ty: TypeId, x: f64) Allocator.Error!?Value {
const b: u64 = switch (m.types.items[ty]) {
.half => @as(u16, @bitCast(@as(f16, @floatCast(x)))),
.float => @as(u32, @bitCast(@as(f32, @floatCast(x)))),
.double => @bitCast(x),
else => return null,
};
return try m.constant(.{ .ty = ty, .kind = .{ .float_bits = b } });
}
/// `x op y` in `T`'s precision.
fn floatOp(comptime T: type, op: module.BinOp, x: f64, y: f64) ?f64 {
const a: T = @floatCast(x);
const c: T = @floatCast(y);
return @floatCast(switch (op) {
.add => a + c,
.sub => a - c,
.mul => a * c,
.sdiv => a / c,
.srem => if (c == 0 or std.math.isInf(a) or std.math.isNan(a) or std.math.isNan(c)) std.math.nan(T) else @rem(a, c),
else => return null,
});
}
/// Floating-point arithmetic on two constants, and the identities exact
/// in IEEE arithmetic (`x * 1`, `x / 1`, `x - 0`, `x + -0`), as dxc's
/// constant folding and instcombine fold them.
fn foldFloat(m: *module.Module, repl: []const ?Value, inst: Inst) Allocator.Error!?Value {
const b = inst.op.binop;
const is_float = switch (m.types.items[inst.ty]) {
.half, .float, .double => true,
else => false,
};
if (!is_float) return null;
const l = resolve(repl, b.lhs);
const r = resolve(repl, b.rhs);
const lc = constFloat(m, l);
const rc = constFloat(m, r);
if (lc != null and rc != null) {
const x = switch (m.types.items[inst.ty]) {
.half => floatOp(f16, b.op, lc.?, rc.?),
.float => floatOp(f32, b.op, lc.?, rc.?),
else => floatOp(f64, b.op, lc.?, rc.?),
} orelse return null;
return floatConst(m, inst.ty, x);
}
if (rc) |y| {
const neg_zero = y == 0 and std.math.signbit(y);
switch (b.op) {
.mul, .sdiv => if (y == 1) return l,
.sub => if (y == 0 and !neg_zero) return l,
.add => if (neg_zero) return l,
else => {},
}
}
if (lc) |x| switch (b.op) {
.mul => if (x == 1) return r,
.add => if (x == 0 and std.math.signbit(x)) return r,
else => {},
};
return null;
}
/// A dx.op call on constants, folded as dxc folds them (the operations
/// whose result does not depend on the GPU's precision, and the min / max
/// family).
fn foldDxOp(m: *module.Module, repl: []const ?Value, inst: Inst) Allocator.Error!?Value {
const c = inst.op.call;
if (!std.mem.startsWith(u8, m.functions.items[c.callee].name, "dx.op.")) return null;
if (c.args.len < 2) return null;
const opc = constInt(m, c.args[0]) orelse return null;
switch (opc) {
// FAbs, Saturate, Round_ne, Round_ni, Round_pi, Round_z, Sqrt
6, 7, 24, 26, 27, 28, 29 => {
if (c.args.len != 2) return null;
const x = constFloat(m, resolve(repl, c.args[1])) orelse return null;
if (std.math.isNan(x)) return null;
const y: f64 = switch (opc) {
6 => @abs(x),
7 => @min(@max(x, 0), 1),
24 => if (x < 0) return null else switch (m.types.items[inst.ty]) {
.half => @floatCast(@sqrt(@as(f16, @floatCast(x)))),
.float => @floatCast(@sqrt(@as(f32, @floatCast(x)))),
else => @sqrt(x),
},
// (Halves to even.)
26 => if (@abs(x - @trunc(x)) == 0.5) 2 * @round(x / 2) else @round(x),
27 => @floor(x),
28 => @ceil(x),
else => @trunc(x),
};
return floatConst(m, inst.ty, y);
},
// FMax, FMin
35, 36 => {
if (c.args.len != 3) return null;
const x = constFloat(m, resolve(repl, c.args[1])) orelse return null;
const y = constFloat(m, resolve(repl, c.args[2])) orelse return null;
if (std.math.isNan(x) or std.math.isNan(y)) return null;
return floatConst(m, inst.ty, if (opc == 35) @max(x, y) else @min(x, y));
},
// IMax, IMin, UMax, UMin
37, 38, 39, 40 => {
if (c.args.len != 3) return null;
const w: u32 = switch (m.types.items[inst.ty]) {
.int => |iw| iw,
else => return null,
};
const x = constInt(m, resolve(repl, c.args[1])) orelse return null;
const y = constInt(m, resolve(repl, c.args[2])) orelse return null;
// (Constants hold their value sign-extended: unsigned order is
// that of the w-bit patterns.)
const mask: u64 = if (w >= 64) ~@as(u64, 0) else (@as(u64, 1) << @intCast(w)) - 1;
const ux = @as(u64, @bitCast(x)) & mask;
const uy = @as(u64, @bitCast(y)) & mask;
const pick_x = switch (opc) {
37 => x >= y,
38 => x <= y,
39 => ux >= uy,
else => ux <= uy,
};
return if (pick_x) resolve(repl, c.args[1]) else resolve(repl, c.args[2]);
},
else => return null,
}
}
/// A half, float or double constant's value. /// A half, float or double constant's value.
fn constFloat(m: *const module.Module, v: Value) ?f64 { fn constFloat(m: *const module.Module, v: Value) ?f64 {
if (v != .constant) return null; if (v != .constant) return null;

View File

@ -5,11 +5,13 @@
//! Layout: a header (version, part count), part offsets, then each //! Layout: a header (version, part count), part offsets, then each
//! non-empty part as (type, size) and its 4-byte aligned contents. Parts //! non-empty part as (type, size) and its 4-byte aligned contents. Parts
//! come in the order dxc adds them: strings, resources, functions, index //! come in the order dxc adds them: strings, resources, functions, index
//! arrays, raw bytes, subobjects, then the record tables of the extended //! arrays, raw bytes, subobjects, then the other record tables: work graph
//! function properties (SM 6.10 linear algebra). //! nodes (validator 1.8+) and the extended function properties (SM 6.10
//! linear algebra).
const std = @import("std"); const std = @import("std");
const Allocator = std.mem.Allocator; const Allocator = std.mem.Allocator;
const shader = @import("shader.zig");
pub const null_ref: u32 = 0xffff_ffff; pub const null_ref: u32 = 0xffff_ffff;
@ -24,7 +26,8 @@ pub const Resource = struct {
flags: u32 = 0, flags: u32 = 0,
}; };
/// RuntimeDataFunctionInfo3 (validator 1.10+). /// RuntimeDataFunctionInfo3 (validator 1.10+; before, 2: without the
/// extended properties).
pub const Function = struct { pub const Function = struct {
name: u32, name: u32,
unmangled_name: u32, unmangled_name: u32,
@ -44,9 +47,14 @@ pub const Function = struct {
extended_properties: u32 = null_ref, extended_properties: u32 = null_ref,
}; };
/// The extended function property tables, in part order (part types /// The other record tables, by part type: work graph nodes (7..11) and
/// 13..20). /// the extended function properties (13..20).
pub const Ext = enum(u32) { pub const Ext = enum(u32) {
node_ids = 7,
node_io_attribs,
node_func_attribs,
io_nodes,
node_shaders,
properties = 13, properties = 13,
shapes, shapes,
constructions, constructions,
@ -59,8 +67,10 @@ pub const Ext = enum(u32) {
/// Record size in bytes. /// Record size in bytes.
pub fn stride(t: Ext) usize { pub fn stride(t: Ext) usize {
return switch (t) { return switch (t) {
.node_shaders => 20,
.shapes => 12, .shapes => 12,
.properties, .constructions, .wave_multiplies, .group_multiplies => 8, .properties, .constructions, .wave_multiplies, .group_multiplies => 8,
.node_ids, .node_io_attribs, .node_func_attribs, .io_nodes => 8,
.thread_matvec, .outer_products, .accumulate_stores => 4, .thread_matvec, .outer_products, .accumulate_stores => 4,
}; };
} }
@ -75,7 +85,8 @@ pub const Builder = struct {
functions: std.ArrayList([14]u32) = .empty, functions: std.ArrayList([14]u32) = .empty,
raw: std.ArrayList(u8) = .empty, raw: std.ArrayList(u8) = .empty,
subobjects: std.ArrayList([6]u32) = .empty, subobjects: std.ArrayList([6]u32) = .empty,
ext: [8]std.ArrayList(u8) = @splat(.empty), /// By part type, from 7.
ext: [14]std.ArrayList(u8) = @splat(.empty),
pub fn init(gpa: Allocator) Allocator.Error!Builder { pub fn init(gpa: Allocator) Allocator.Error!Builder {
var b: Builder = .{ .gpa = gpa }; var b: Builder = .{ .gpa = gpa };
@ -132,7 +143,7 @@ pub const Builder = struct {
/// (record deduplication, validator 1.7+). /// (record deduplication, validator 1.7+).
pub fn record(b: *Builder, t: Ext, rec: []const u8) Allocator.Error!u32 { pub fn record(b: *Builder, t: Ext, rec: []const u8) Allocator.Error!u32 {
std.debug.assert(rec.len == t.stride()); std.debug.assert(rec.len == t.stride());
const tab = &b.ext[@intFromEnum(t) - 13]; const tab = &b.ext[@backingInt(t) - 7];
var at: usize = 0; var at: usize = 0;
while (at < tab.items.len) : (at += rec.len) { while (at < tab.items.len) : (at += rec.len) {
if (std.mem.eql(u8, tab.items[at..][0..rec.len], rec)) return @intCast(at / rec.len); if (std.mem.eql(u8, tab.items[at..][0..rec.len], rec)) return @intCast(at / rec.len);
@ -165,7 +176,11 @@ pub const Builder = struct {
try parts.append(b.gpa, .{ .ty = 3, .data = t }); try parts.append(b.gpa, .{ .ty = 3, .data = t });
} }
if (b.functions.items.len > 0) { if (b.functions.items.len > 0) {
const t = try table(b.gpa, 14, std.mem.sliceAsBytes(b.functions.items), b.functions.items.len); const words: usize = if (shader.validatorAtLeast(1, 10)) 14 else 13;
const rows = try b.gpa.alloc(u32, words * b.functions.items.len);
defer b.gpa.free(rows);
for (b.functions.items, 0..) |f, k| @memcpy(rows[k * words ..][0..words], f[0..words]);
const t = try table(b.gpa, words, std.mem.sliceAsBytes(rows), b.functions.items.len);
try tables.append(b.gpa, t); try tables.append(b.gpa, t);
try parts.append(b.gpa, .{ .ty = 4, .data = t }); try parts.append(b.gpa, .{ .ty = 4, .data = t });
} }
@ -176,8 +191,12 @@ pub const Builder = struct {
try tables.append(b.gpa, t); try tables.append(b.gpa, t);
try parts.append(b.gpa, .{ .ty = 6, .data = t }); try parts.append(b.gpa, .{ .ty = 6, .data = t });
} }
for (b.ext, 13..) |rows, ty| if (rows.items.len > 0) { // (dxc's table order: the node function attributes before the
const stride = @as(Ext, @enumFromInt(ty)).stride(); // I/O attributes.)
const order = [_]u32{ 7, 9, 8, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20 };
for (order) |ty| if (b.ext[ty - 7].items.len > 0) {
const rows = b.ext[ty - 7];
const stride = @as(Ext, @fromBackingInt(ty)).stride();
const t = try table(b.gpa, stride / 4, rows.items, rows.items.len / stride); const t = try table(b.gpa, stride / 4, rows.items, rows.items.len / stride);
try tables.append(b.gpa, t); try tables.append(b.gpa, t);
try parts.append(b.gpa, .{ .ty = @intCast(ty), .data = t }); try parts.append(b.gpa, .{ .ty = @intCast(ty), .data = t });

View File

@ -71,8 +71,16 @@ pub const ComputeInfo = struct {
num_threads: [3]u32, num_threads: [3]u32,
}; };
/// Validator version we claim in !dx.valver (matches the oracle dxc). /// The validator version zdxc writes for (!dx.valver; matches the oracle
const valver = .{ 1, 11 }; /// dxc). What its output looks like follows from it: PSVRuntimeInfo4 and
/// RDAT's RuntimeDataFunctionInfo3 from 1.10. Testing with an older
/// validator means changing only this.
pub const validator: [2]u32 = .{ 1, 11 };
/// Whether the validator is at least `major.minor`.
pub fn validatorAtLeast(major: u32, minor: u32) bool {
return validator[0] > major or (validator[0] == major and validator[1] >= minor);
}
pub fn buildEmptyCompute(gpa: Allocator, info: ComputeInfo) ![]u8 { pub fn buildEmptyCompute(gpa: Allocator, info: ComputeInfo) ![]u8 {
var m = Module.init(gpa); var m = Module.init(gpa);
@ -86,7 +94,7 @@ pub fn buildEmptyCompute(gpa: Allocator, info: ComputeInfo) ![]u8 {
// Metadata, in the same shape dxc emits. // Metadata, in the same shape dxc emits.
const ident = try m.mdNode(&.{try m.mdString("zdxc 0.0.0")}); const ident = try m.mdNode(&.{try m.mdString("zdxc 0.0.0")});
const version = try m.mdNode(&.{ try m.mdI32(1), try m.mdI32(info.profile.minor) }); const version = try m.mdNode(&.{ try m.mdI32(1), try m.mdI32(info.profile.minor) });
const val_ver = try m.mdNode(&.{ try m.mdI32(valver[0]), try m.mdI32(valver[1]) }); const val_ver = try m.mdNode(&.{ try m.mdI32(validator[0]), try m.mdI32(validator[1]) });
const sm = try m.mdNode(&.{ try m.mdString(info.profile.kind.profilePrefix()), try m.mdI32(info.profile.major), try m.mdI32(info.profile.minor) }); const sm = try m.mdNode(&.{ try m.mdString(info.profile.kind.profilePrefix()), try m.mdI32(info.profile.major), try m.mdI32(info.profile.minor) });
const threads = try m.mdNode(&.{ try m.mdI32(info.num_threads[0]), try m.mdI32(info.num_threads[1]), try m.mdI32(info.num_threads[2]) }); const threads = try m.mdNode(&.{ try m.mdI32(info.num_threads[0]), try m.mdI32(info.num_threads[1]), try m.mdI32(info.num_threads[2]) });
const props = try m.mdNode(&.{ try m.mdI32(4), threads }); // kDxilNumThreadsTag const props = try m.mdNode(&.{ try m.mdI32(4), threads }); // kDxilNumThreadsTag
@ -143,6 +151,8 @@ pub const PsvInfo = struct {
/// The stage-specific PSVRuntimeInfo0 union. /// The stage-specific PSVRuntimeInfo0 union.
stage_info: [16]u8 = @splat(0), stage_info: [16]u8 = @splat(0),
num_threads: [3]u32 = .{ 0, 0, 0 }, num_threads: [3]u32 = .{ 0, 0, 0 },
/// Minimum and maximum expected wave lane counts (WaveSize).
wave_lanes: [2]u32 = .{ 0, 0xFFFFFFFF },
resources: []const ResourceBind = &.{}, resources: []const ResourceBind = &.{},
inputs: []const signature.Element = &.{}, inputs: []const signature.Element = &.{},
outputs: []const signature.Element = &.{}, outputs: []const signature.Element = &.{},
@ -159,7 +169,7 @@ pub fn psvCompute(gpa: Allocator, entry: []const u8, num_threads: [3]u32, resour
return psv(gpa, .{ .kind = .compute, .entry = entry, .num_threads = num_threads, .resources = resources }); return psv(gpa, .{ .kind = .compute, .entry = entry, .num_threads = num_threads, .resources = resources });
} }
/// PSV0 with PSVRuntimeInfo4 (60 bytes), as produced for validator 1.11. /// PSV0 with PSVRuntimeInfo4 (60 bytes; validator 1.10+) or 3 (52).
pub fn psv(gpa: Allocator, info: PsvInfo) ![]u8 { pub fn psv(gpa: Allocator, info: PsvInfo) ![]u8 {
var buf: std.ArrayList(u8) = .empty; var buf: std.ArrayList(u8) = .empty;
errdefer buf.deinit(gpa); errdefer buf.deinit(gpa);
@ -169,11 +179,12 @@ pub fn psv(gpa: Allocator, info: PsvInfo) ![]u8 {
for (&out_vectors, 0..) |*v, s| v.* = signature.vectorsUsed(info.outputs, @intCast(s)); for (&out_vectors, 0..) |*v, s| v.* = signature.vectorsUsed(info.outputs, @intCast(s));
const pc_vectors = signature.vectorsUsed(info.patch_constants, 0); const pc_vectors = signature.vectorsUsed(info.patch_constants, 0);
try w(&buf, gpa, 60); // sizeof(PSVRuntimeInfo4) const info4 = validatorAtLeast(1, 10);
try w(&buf, gpa, if (info4) 60 else 52); // sizeof(PSVRuntimeInfo4 / 3)
// PSVRuntimeInfo0 // PSVRuntimeInfo0
try buf.appendSlice(gpa, &info.stage_info); try buf.appendSlice(gpa, &info.stage_info);
try w(&buf, gpa, 0); // MinimumExpectedWaveLaneCount try w(&buf, gpa, info.wave_lanes[0]); // MinimumExpectedWaveLaneCount
try w(&buf, gpa, 0xFFFFFFFF); // MaximumExpectedWaveLaneCount try w(&buf, gpa, info.wave_lanes[1]); // MaximumExpectedWaveLaneCount
// PSVRuntimeInfo1: stage, UsesViewID, MaxVertexCount, element counts, // PSVRuntimeInfo1: stage, UsesViewID, MaxVertexCount, element counts,
// vector counts. // vector counts.
// (The MaxVertexCount union holds SigPatchConstOrPrimVectors for hull // (The MaxVertexCount union holds SigPatchConstOrPrimVectors for hull
@ -221,7 +232,7 @@ pub fn psv(gpa: Allocator, info: PsvInfo) ![]u8 {
try w(&records, gpa, idx_off); try w(&records, gpa, idx_off);
var cols_and_start: u8 = @intCast(e.cols); var cols_and_start: u8 = @intCast(e.cols);
if (e.start_row != null) cols_and_start |= 0x40 | @as(u8, @intCast(e.start_col << 4)); if (e.start_row != null) cols_and_start |= 0x40 | @as(u8, @intCast(e.start_col << 4));
try records.appendSlice(gpa, &.{ @intCast(e.rows), @intCast(e.start_row orelse 0), cols_and_start, @intFromEnum(e.kind), @intCast(e.comp.sigCompType()), @intFromEnum(e.interp), @intCast((e.stream & 3) << 4), 0 }); try records.appendSlice(gpa, &.{ @intCast(e.rows), @intCast(e.start_row orelse 0), cols_and_start, @backingInt(e.kind), @intCast(e.comp.sigCompType()), @backingInt(e.interp), @intCast((e.stream & 3) << 4), 0 });
}; };
const entry_off: u32 = @intCast(strings.items.len); const entry_off: u32 = @intCast(strings.items.len);
try strings.appendSlice(gpa, info.entry); try strings.appendSlice(gpa, info.entry);
@ -230,9 +241,11 @@ pub fn psv(gpa: Allocator, info: PsvInfo) ![]u8 {
// PSVRuntimeInfo3: EntryFunctionName // PSVRuntimeInfo3: EntryFunctionName
try w(&buf, gpa, entry_off); try w(&buf, gpa, entry_off);
if (info4) {
// PSVRuntimeInfo4 // PSVRuntimeInfo4
try w(&buf, gpa, info.groupshared_bytes); // NumBytesGroupSharedMemory try w(&buf, gpa, info.groupshared_bytes); // NumBytesGroupSharedMemory
try w(&buf, gpa, @intFromBool(linalg != null)); // Flags: LinAlgRuntimeInfoPresent try w(&buf, gpa, @intFromBool(linalg != null)); // Flags: LinAlgRuntimeInfoPresent
}
try w(&buf, gpa, @intCast(info.resources.len)); try w(&buf, gpa, @intCast(info.resources.len));
if (info.resources.len > 0) { if (info.resources.len > 0) {

View File

@ -31,6 +31,9 @@ const none = std.math.maxInt(u32);
const max_trips = 256; const max_trips = 256;
const max_loop_growth = 300; const max_loop_growth = 300;
const max_growth = 65536; const max_growth = 65536;
/// For `[unroll]` loops: dxc's limit on their iterations (its
/// DxilLoopUnroll), and no limit on their size but the function's.
const max_marked_trips = 1024;
/// Unrolls the qualifying loops of `func`, innermost first; true if any. /// Unrolls the qualifying loops of `func`, innermost first; true if any.
pub fn run(a: Allocator, m: *module.Module, func: u32) Allocator.Error!bool { pub fn run(a: Allocator, m: *module.Module, func: u32) Allocator.Error!bool {
@ -495,6 +498,10 @@ fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried:
// Innermost: no other loop's header inside. // Innermost: no other loop's header inside.
for (loops.items) |other| if (other.h != h and lp.body.has(other.h)) continue :candidates; for (loops.items) |other| if (other.h != h and lp.body.has(other.h)) continue :candidates;
try tried.put(a, h, {}); try tried.put(a, h, {});
// `[unroll]` (its back edge marked by the emitter).
const marked_loop = for (lp.latches) |l| {
if (insts[cfg.block_start[l + 1] - 1].md == .unroll) break true;
} else false;
// One way out: a conditional branch from one block, to one block. // One way out: a conditional branch from one block, to one block.
var exiting: u32 = none; var exiting: u32 = none;
@ -547,7 +554,7 @@ fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried:
while (true) { while (true) {
const c = eval(m, f, &state, xcond, 0) orelse continue :candidates; const c = eval(m, f, &state, xcond, 0) orelse continue :candidates;
if ((c & 1) != stay_on) break; if ((c & 1) != stay_on) break;
if (states.items.len >= max_trips) continue :candidates; if (states.items.len >= @as(usize, if (marked_loop) max_marked_trips else max_trips)) continue :candidates;
try states.append(a, try state.clone(a)); try states.append(a, try state.clone(a));
// Next values: what every latch passes back (the same). // Next values: what every latch passes back (the same).
var next: std.AutoHashMapUnmanaged(u32, i64) = .empty; var next: std.AutoHashMapUnmanaged(u32, i64) = .empty;
@ -570,7 +577,7 @@ fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried:
} }
const trips = states.items.len; const trips = states.items.len;
const growth = (trips + 1) * size; const growth = (trips + 1) * size;
if (growth > max_loop_growth or growth > budget.*) continue; if ((!marked_loop and growth > max_loop_growth) or growth > budget.*) continue;
budget.* -= growth; budget.* -= growth;
try states.append(a, state); // the last pass, up to the exit try states.append(a, state); // the last pass, up to the exit

View File

@ -41,6 +41,8 @@ pub const Parser = struct {
/// Name of the struct most recently parsed by parseStructDeclInto /// Name of the struct most recently parsed by parseStructDeclInto
/// (synthesized for anonymous structs), for `typedef struct ...`. /// (synthesized for anonymous structs), for `typedef struct ...`.
last_struct_name: []const u8 = "", last_struct_name: []const u8 = "",
/// The last parseType read `const` after the type (`float const x`).
type_const: bool = false,
/// The qualifier words read by the last parseQualifiers call. /// The qualifier words read by the last parseQualifiers call.
last_quals: []const ast.QualWord = &.{}, last_quals: []const ast.QualWord = &.{},
/// Qualifier words for the next parseDeclaratorsInto call. /// Qualifier words for the next parseDeclaratorsInto call.
@ -410,6 +412,8 @@ pub const Parser = struct {
fn skipTypeAttrs(p: *const Parser, start: usize) usize { fn skipTypeAttrs(p: *const Parser, start: usize) usize {
var i = start; var i = start;
// `T const`: a type qualifier written after the type.
while (p.toks[i].isIdent("const")) i += 1;
if (!(p.toks[i].kind == .l_square and p.toks[i + 1].kind == .l_square)) return i; if (!(p.toks[i].kind == .l_square and p.toks[i + 1].kind == .l_square)) return i;
var depth: u32 = 0; var depth: u32 = 0;
while (true) : (i += 1) { while (true) : (i += 1) {
@ -565,10 +569,19 @@ pub const Parser = struct {
t.pack_matrix = p.packMatrixAt(type_pos); t.pack_matrix = p.packMatrixAt(type_pos);
if (norm != .none) t.norm = norm; if (norm != .none) t.norm = norm;
if (words.items.len > 0) t.attr_words = words.items; if (words.items.len > 0) t.attr_words = words.items;
p.type_const = false;
while (p.eatIdent("const")) p.type_const = true;
if (p.at(.l_square) and p.peek(1).kind == .l_square) t.attrs = try p.parseAttributes(); if (p.at(.l_square) and p.peek(1).kind == .l_square) t.attrs = try p.parseAttributes();
return t; return t;
} }
/// parseType for a declaration: `const` after the type joins `quals`.
fn parseDeclType(p: *Parser, quals: *ast.Qualifiers) Error!*ast.TypeRef {
const t = try p.parseType();
if (p.type_const) quals.@"const" = true;
return t;
}
fn parseTypeInner(p: *Parser) Error!*ast.TypeRef { fn parseTypeInner(p: *Parser) Error!*ast.TypeRef {
// An elaborated type: `struct S` names S (declaring it if needed). // An elaborated type: `struct S` names S (declaring it if needed).
const elaborated = (p.atIdent("struct") or p.atIdent("class")) and p.peek(1).kind == .identifier and p.peek(2).kind != .l_brace and p.peek(2).kind != .colon; const elaborated = (p.atIdent("struct") or p.atIdent("class")) and p.peek(1).kind == .identifier and p.peek(2).kind != .l_brace and p.peek(2).kind != .colon;
@ -835,9 +848,9 @@ pub const Parser = struct {
return out.append(p.arena, d); return out.append(p.arena, d);
} }
const quals = p.parseQualifiers(); var quals = p.parseQualifiers();
const words = p.last_quals; const words = p.last_quals;
const ty = try p.parseType(); const ty = try p.parseDeclType(&quals);
p.decl_quals = words; p.decl_quals = words;
const first = out.items.len; const first = out.items.len;
try p.parseDeclaratorsInto(out, attrs, quals, template_params, ty, ctx); try p.parseDeclaratorsInto(out, attrs, quals, template_params, ty, ctx);
@ -1299,9 +1312,9 @@ pub const Parser = struct {
if (p.atIdent("void") and p.peek(1).kind == .r_paren) _ = p.advance(); if (p.atIdent("void") and p.peek(1).kind == .r_paren) _ = p.advance();
while (!p.at(.r_paren)) { while (!p.at(.r_paren)) {
const pattrs = try p.parseAttributes(); const pattrs = try p.parseAttributes();
const pquals = p.parseQualifiers(); var pquals = p.parseQualifiers();
const pwords = p.last_quals; const pwords = p.last_quals;
const pty = try p.parseType(); const pty = try p.parseDeclType(&pquals);
var pname: []const u8 = ""; var pname: []const u8 = "";
var pname_loc = p.tok().loc; var pname_loc = p.tok().loc;
if (p.at(.identifier) and !isReserved(p.tok().text)) { if (p.at(.identifier) and !isReserved(p.tok().text)) {
@ -1507,8 +1520,8 @@ pub const Parser = struct {
/// `expr`, or `T name = init` (C++ condition declaration). /// `expr`, or `T name = init` (C++ condition declaration).
fn parseCondition(p: *Parser) Error!struct { decl: ?*ast.Decl, cond: *ast.Expr } { fn parseCondition(p: *Parser) Error!struct { decl: ?*ast.Decl, cond: *ast.Expr } {
if (!p.startsLocalDecl()) return .{ .decl = null, .cond = try p.parseExpr() }; if (!p.startsLocalDecl()) return .{ .decl = null, .cond = try p.parseExpr() };
const quals = p.parseQualifiers(); var quals = p.parseQualifiers();
const ty = try p.parseType(); const ty = try p.parseDeclType(&quals);
const name = try p.expectIdent("variable name"); const name = try p.expectIdent("variable name");
_ = try p.expect(.equal, "'='"); _ = try p.expect(.equal, "'='");
const init_expr = try p.parseAssign(); const init_expr = try p.parseAssign();

View File

@ -20,6 +20,7 @@ const Allocator = std.mem.Allocator;
const ir = @import("ir.zig"); const ir = @import("ir.zig");
const types = @import("../sema/types.zig"); const types = @import("../sema/types.zig");
const opt = @import("opt.zig"); const opt = @import("opt.zig");
const split_resources = @import("split_resources.zig");
const Ref = ir.Ref; const Ref = ir.Ref;
const BlockId = ir.BlockId; const BlockId = ir.BlockId;
@ -73,6 +74,41 @@ pub fn run(m: *ir.Module) Error!void {
try markDead(m); try markDead(m);
} }
/// Inlines only the calls of functions that return a resource or a struct
/// holding one, in every kind of module (ray-tracing libraries included),
/// before resources are split out of structs: what such a function
/// returns can be an element of a resource array picked by an index it
/// computes (`bindless[NonUniformResourceIndex(i)]`), which no function
/// signature can pass back. dxc's legalization inlines everything.
pub fn runResourceReturns(m: *ir.Module) Error!void {
const a = m.arena;
const n = m.functions.items.len;
const shapes = try a.alloc(?Shape, n);
var any = false;
for (m.functions.items, shapes) |f, *sh| {
sh.* = .keep;
if (!isResource(m.types, f.ret) and !split_resources.holdsResources(m.types, f.ret)) continue;
const shape = try shapeOf(a, m, f);
sh.* = shape;
if (shape != .keep) any = true;
}
if (!any) return;
const done = try a.alloc(bool, n);
@memset(done, false);
var work: std.ArrayList(u32) = .empty;
for (m.entries.items) |e| {
try work.append(a, e.wrapper);
if (e.patch_wrapper) |pw| try work.append(a, pw);
}
try work.appendSlice(a, m.exports.items);
while (work.pop()) |fi| {
if (done[fi]) continue;
done[fi] = true;
try inlineCalls(m, m.functions.items[fi], shapes, &work);
}
try markDead(m);
}
/// How a function returns, for inlining it. /// How a function returns, for inlining it.
const Shape = union(enum) { const Shape = union(enum) {
/// Not inlinable. /// Not inlinable.

View File

@ -38,7 +38,8 @@ pub const BlockId = enum(u32) {
}; };
/// Where a pointer points. /// Where a pointer points.
pub const Space = enum { none, function, private, groupshared, resource, input, output, cbuffer, mesh, ray }; /// (`node`: a work graph node record.)
pub const Space = enum { none, function, private, groupshared, resource, input, output, cbuffer, mesh, ray, node };
/// Ray tracing shader storage an entry receives: the incoming payload, /// Ray tracing shader storage an entry receives: the incoming payload,
/// the hit attributes and the incoming callable data. /// the hit attributes and the incoming callable data.
@ -72,6 +73,9 @@ pub const Constant = union(enum) {
pub const Op = union(enum) { pub const Op = union(enum) {
/// A scalar constant (or a vector of one constant, splatted). /// A scalar constant (or a vector of one constant, splatted).
constant: Constant, constant: Constant,
/// A node shader's input (`output` false) or its output `index`: the
/// node object (Entry.node's inputs / outputs).
node_io: struct { output: bool, index: u32 },
/// The function's `n`th parameter (a pointer for out / inout). /// The function's `n`th parameter (a pointer for out / inout).
param: u32, param: u32,
/// Pointer to a module global (resource, groupshared, static). /// Pointer to a module global (resource, groupshared, static).
@ -356,6 +360,8 @@ pub const Stage = enum {
mesh, mesh,
amplification, amplification,
library, library,
/// Work graph nodes (SM 6.8 libraries).
node,
raygeneration, raygeneration,
intersection, intersection,
anyhit, anyhit,
@ -409,6 +415,45 @@ pub const OutputTopology = enum(u8) { point = 1, line = 2, triangle_cw = 3, tria
pub const MeshOutput = enum { vertices, primitives, indices }; pub const MeshOutput = enum { vertices, primitives, indices };
/// A node shader's properties (`[Shader("node")]`), from its attributes.
pub const NodeInfo = struct {
launch: Launch = .broadcasting,
is_program_entry: bool = false,
/// `[NodeID("name", index)]`; by default the function's name, 0.
id: NodeId,
local_root_arguments_table_index: ?u32 = null,
share_input_of: ?NodeId = null,
dispatch_grid: ?[3]u32 = null,
max_dispatch_grid: ?[3]u32 = null,
max_recursion_depth: ?u32 = null,
inputs: []const NodeIo = &.{},
outputs: []const NodeIo = &.{},
/// NodeLaunchType.
pub const Launch = enum(u32) { broadcasting = 1, coalescing = 2, thread = 3 };
};
pub const NodeId = struct { name: []const u8, index: u32 = 0 };
/// One node input or output: a parameter of a node object type.
pub const NodeIo = struct {
kind: types.NodeKind,
/// The record type (void for empty inputs / outputs).
record: TypeId,
/// I/O flags beyond the kind: TrackRWInputSharing 0x100,
/// GloballyCoherent 0x200.
extra_flags: u32 = 0,
/// Outputs: `[NodeID]`, by default the parameter's name, 0.
output_id: ?NodeId = null,
max_records: ?u32 = null,
/// Outputs: the index of the output whose records these share.
max_records_shared_with: ?u32 = null,
/// Output arrays: `[NodeArraySize(n)]`, or maxInt for
/// `[UnboundedSparseNodes]`.
array_size: ?u32 = null,
allow_sparse_nodes: bool = false,
};
pub const MeshInfo = struct { pub const MeshInfo = struct {
max_vertices: u32 = 0, max_vertices: u32 = 0,
max_primitives: u32 = 0, max_primitives: u32 = 0,
@ -436,9 +481,14 @@ pub const Entry = struct {
name: []const u8, name: []const u8,
stage: Stage, stage: Stage,
num_threads: [3]u32 = .{ 1, 1, 1 }, num_threads: [3]u32 = .{ 1, 1, 1 },
/// `[WaveSize(min[, max[, preferred]])]`: zeros where not given (no
/// attribute: min 0).
wave_size: [3]u32 = .{ 0, 0, 0 },
geometry: GeometryInfo = .{}, geometry: GeometryInfo = .{},
tess: TessInfo = .{}, tess: TessInfo = .{},
mesh: MeshInfo = .{}, mesh: MeshInfo = .{},
/// Node shaders.
node: ?NodeInfo = null,
inputs: std.ArrayList(SigElement) = .empty, inputs: std.ArrayList(SigElement) = .empty,
outputs: std.ArrayList(SigElement) = .empty, outputs: std.ArrayList(SigElement) = .empty,
/// Patch constants: written by the hull shader's patch constant /// Patch constants: written by the hull shader's patch constant
@ -483,8 +533,9 @@ pub const SpirvExt = struct {
pub const SpirvInst = struct { pub const SpirvInst = struct {
opcode: u32, opcode: u32,
set: ?[]const u8 = null, set: ?[]const u8 = null,
/// Values, pointers (`[[vk::ext_reference]]`) or literal words. /// Values, pointers (`[[vk::ext_reference]]`), literal words, types,
operands: []const union(enum) { value: Ref, literal: u32, type: TypeId }, /// or the id of an OpString (printf's format).
operands: []const union(enum) { value: Ref, literal: u32, type: TypeId, string: []const u8 },
capabilities: []const u32 = &.{}, capabilities: []const u32 = &.{},
extensions: []const []const u8 = &.{}, extensions: []const []const u8 = &.{},
}; };
@ -658,6 +709,7 @@ fn dumpInst(m: *const Module, f: *const Function, r: Ref, w: *std.Io.Writer) !vo
.float => |v| try w.print("const {d}", .{v}), .float => |v| try w.print("const {d}", .{v}),
}, },
.param => |p| try w.print("param {d}", .{p}), .param => |p| try w.print("param {d}", .{p}),
.node_io => |x| try w.print("node_{s} {d}", .{ if (x.output) "output" else "input", x.index }),
.global => |g| try w.print("global @{d}", .{g}), .global => |g| try w.print("global @{d}", .{g}),
.local_var => try w.writeAll("local_var"), .local_var => try w.writeAll("local_var"),
.load => |p| try w.print("load %{d}", .{p.index()}), .load => |p| try w.print("load %{d}", .{p.index()}),

View File

@ -73,11 +73,21 @@ pub fn lowerUnit(arena: Allocator, s: *Sema, opts: Options) Error!ir.Module {
/// The stage a `[shader("...")]` attribute names. /// The stage a `[shader("...")]` attribute names.
fn stageNamed(name: []const u8) ?ir.Stage { fn stageNamed(name: []const u8) ?ir.Stage {
const names = [_]struct { []const u8, ir.Stage }{ const names = [_]struct { []const u8, ir.Stage }{
.{ "vertex", .vertex }, .{ "pixel", .pixel }, .{ "geometry", .geometry }, .{ "node", .node },
.{ "hull", .hull }, .{ "domain", .domain }, .{ "compute", .compute }, .{ "vertex", .vertex },
.{ "mesh", .mesh }, .{ "amplification", .amplification }, .{ "raygeneration", .raygeneration }, .{ "pixel", .pixel },
.{ "intersection", .intersection }, .{ "anyhit", .anyhit }, .{ "closesthit", .closesthit }, .{ "geometry", .geometry },
.{ "miss", .miss }, .{ "callable", .callable }, .{ "hull", .hull },
.{ "domain", .domain },
.{ "compute", .compute },
.{ "mesh", .mesh },
.{ "amplification", .amplification },
.{ "raygeneration", .raygeneration },
.{ "intersection", .intersection },
.{ "anyhit", .anyhit },
.{ "closesthit", .closesthit },
.{ "miss", .miss },
.{ "callable", .callable },
}; };
for (names) |t| if (std.ascii.eqlIgnoreCase(name, t[0])) return t[1]; for (names) |t| if (std.ascii.eqlIgnoreCase(name, t[0])) return t[1];
return null; return null;
@ -1070,6 +1080,13 @@ const Lowerer = struct {
const idx = try l.indexValue(x.index, bt.resource.kind.indexDims()); const idx = try l.indexValue(x.index, bt.resource.kind.indexDims());
return l.b.add(.{ .op = .{ .res_load = .{ .res = res, .index = idx } }, .ty = try l.concrete(e.ty) }); return l.b.add(.{ .op = .{ .res_load = .{ .res = res, .index = idx } }, .ty = try l.concrete(e.ty) });
} }
if (bt == .node) {
if (bt.node.kind.isArray()) return l.b.load(try l.nodeRecordPtr(e));
// An output of an outputs array: the node object.
const obj = try l.rvalue(x.base);
const idx = try l.converted(x.index, try t.scalar(.uint));
return l.b.add(.{ .op = .{ .access = .{ .base = obj, .indices = try l.arena.dupe(Ref, &.{idx}) } }, .ty = e.ty });
}
if (isAddressable(l.s, x.base)) return l.b.load(try l.lvalue(e)); if (isAddressable(l.s, x.base)) return l.b.load(try l.lvalue(e));
const base = try l.rvalue(x.base); const base = try l.rvalue(x.base);
if (l.s.evalInt(x.index)) |k| return l.b.add(.{ .op = .{ .extract = .{ .agg = base, .index = @intCast(k) } }, .ty = try l.concrete(e.ty) }); if (l.s.evalInt(x.index)) |k| return l.b.add(.{ .op = .{ .extract = .{ .agg = base, .index = @intCast(k) } }, .ty = try l.concrete(e.ty) });
@ -1377,6 +1394,7 @@ const Lowerer = struct {
fn call(l: *Lowerer, e: *ast.Expr, callee: *ast.Expr, args: []const *ast.Expr) Error!Ref { fn call(l: *Lowerer, e: *ast.Expr, callee: *ast.Expr, args: []const *ast.Expr) Error!Ref {
const r = l.s.resolution(e) orelse return l.fail(e, "this call"); const r = l.s.resolution(e) orelse return l.fail(e, "this call");
const ret_ty = try l.concrete(e.ty); const ret_ty = try l.concrete(e.ty);
if (r == .node_record) return l.b.load(try l.nodeRecordPtr(e));
switch (r) { switch (r) {
.function => |f| { .function => |f| {
if (!f.defined and hasAttr(f.decl.attrs, "vk::ext_instruction")) return l.spirvInstCall(e, f, args, ret_ty); if (!f.defined and hasAttr(f.decl.attrs, "vk::ext_instruction")) return l.spirvInstCall(e, f, args, ret_ty);
@ -1547,6 +1565,16 @@ const Lowerer = struct {
}; };
return result; return result;
} }
// printf: NonSemantic.DebugPrintf's DebugPrintf (opcode 1)
// with the format as an OpString (SPIR-V only).
if (std.mem.eql(u8, name, "printf") and l.s.opts.spirv and args.len >= 1 and args[0].kind == .string_lit) {
const p = try l.arena.create(ir.SpirvInst);
const ops = try l.arena.alloc(@typeInfo(@TypeOf(p.operands)).pointer.child, args.len);
ops[0] = .{ .string = try stringContents(l.arena, args[0].kind.string_lit) };
for (ops[1..], args[1..]) |*o, a| o.* = .{ .value = try l.converted(a, try l.concrete(a.ty)) };
p.* = .{ .opcode = 1, .set = "NonSemantic.DebugPrintf", .operands = ops, .extensions = try l.arena.dupe([]const u8, &.{"SPV_KHR_non_semantic_info"}) };
return l.b.add(.{ .op = .{ .spirv_inst = p }, .ty = TypeTable.void_type });
}
if (std.mem.eql(u8, name, "DispatchMesh") and args.len == 4) { if (std.mem.eql(u8, name, "DispatchMesh") and args.len == 4) {
// The payload goes by reference (a groupshared // The payload goes by reference (a groupshared
// variable). // variable).
@ -1754,7 +1782,22 @@ const Lowerer = struct {
return l.b.add(.{ .op = .{ .global = g }, .ty = glob.ty, .ptr = glob.space }); return l.b.add(.{ .op = .{ .global = g }, .ty = glob.ty, .ptr = glob.space });
} }
/// A node record: `obj.Get()`, `obj.Get(i)` or `obj[i]` (an element
/// of the node object, in node record memory).
fn nodeRecordPtr(l: *Lowerer, e: *ast.Expr) Error!Ref {
const t = l.types();
const obj_expr, const index: ?*ast.Expr = switch (e.kind) {
.call => |c| .{ c.callee.kind.member.base, if (c.args.len > 0) c.args[0] else null },
.index => |x| .{ x.base, x.index },
else => return l.fail(e, "this node record"),
};
const obj = try l.rvalue(obj_expr);
const idx = if (index) |i| try l.converted(i, try t.scalar(.uint)) else try l.b.constInt(try t.scalar(.uint), 0);
return l.b.add(.{ .op = .{ .access = .{ .base = obj, .indices = try l.arena.dupe(Ref, &.{idx}) } }, .ty = e.ty, .ptr = .node });
}
fn lvalue(l: *Lowerer, e: *ast.Expr) Error!Ref { fn lvalue(l: *Lowerer, e: *ast.Expr) Error!Ref {
if (l.s.resolution(e)) |r| if (r == .node_record) return l.nodeRecordPtr(e);
const t = l.types(); const t = l.types();
// A resource inside a global struct: its own global. // A resource inside a global struct: its own global.
if (e.kind == .member or e.kind == .index) if (l.uniformPath(e)) |up| if (layout.isOpaque(t, e.ty)) return l.leafGlobal(up.v, up.path, e.ty); if (e.kind == .member or e.kind == .index) if (l.uniformPath(e)) |up| if (layout.isOpaque(t, e.ty)) return l.leafGlobal(up.v, up.path, e.ty);
@ -2421,6 +2464,97 @@ const Lowerer = struct {
entry.patch_wrapper = wrapper; entry.patch_wrapper = wrapper;
} }
/// A node shader's properties: its attributes and its node object
/// parameters (inputs, then outputs, in parameter order).
fn nodeInfo(l: *Lowerer, f: *const semamod.Function) Error!ir.NodeInfo {
const eqi = std.ascii.eqlIgnoreCase;
var info: ir.NodeInfo = .{ .id = .{ .name = f.name } };
for (f.decl.attrs) |a| {
if (eqi(a.name, "nodelaunch") and a.args.len == 1 and a.args[0].kind == .string_lit) {
const v = try stringContents(l.arena, a.args[0].kind.string_lit);
if (eqi(v, "coalescing")) info.launch = .coalescing else if (eqi(v, "thread")) info.launch = .thread else info.launch = .broadcasting;
} else if (eqi(a.name, "nodeisprogramentry")) {
info.is_program_entry = true;
} else if (eqi(a.name, "nodeid")) {
if (try l.nodeId(a)) |id| info.id = id;
} else if (eqi(a.name, "nodelocalrootargumentstableindex") and a.args.len == 1) {
info.local_root_arguments_table_index = l.attrUint(a.args[0]);
} else if (eqi(a.name, "nodeshareinputof")) {
info.share_input_of = try l.nodeId(a);
} else if (eqi(a.name, "nodedispatchgrid") and a.args.len == 3) {
info.dispatch_grid = .{ l.attrUint(a.args[0]), l.attrUint(a.args[1]), l.attrUint(a.args[2]) };
} else if (eqi(a.name, "nodemaxdispatchgrid") and a.args.len == 3) {
info.max_dispatch_grid = .{ l.attrUint(a.args[0]), l.attrUint(a.args[1]), l.attrUint(a.args[2]) };
} else if (eqi(a.name, "nodemaxrecursiondepth") and a.args.len == 1) {
info.max_recursion_depth = l.attrUint(a.args[0]);
}
}
var inputs: std.ArrayList(ir.NodeIo) = .empty;
var outputs: std.ArrayList(ir.NodeIo) = .empty;
var out_names: std.ArrayList([]const u8) = .empty;
// MaxRecordsSharedWith names a later output too: resolved after.
var shared: std.ArrayList(struct { out: usize, name: []const u8 }) = .empty;
for (f.decl.params, f.params) |pd, p| {
const nt = switch (l.s.types.get(p.type)) {
.node => |x| x,
else => continue,
};
var io: ir.NodeIo = .{ .kind = nt.kind, .record = nt.elem };
if (pd.quals.globallycoherent) io.extra_flags |= 0x200;
if (nt.elem != TypeTable.void_type and l.trackRwInputSharing(nt.elem)) io.extra_flags |= 0x100;
if (!nt.kind.isInput()) io.output_id = .{ .name = pd.name };
for (pd.attrs) |a| {
if (eqi(a.name, "maxrecords") and a.args.len == 1) {
io.max_records = l.attrUint(a.args[0]);
} else if (eqi(a.name, "nodeid")) {
if (try l.nodeId(a)) |id| io.output_id = id;
} else if (eqi(a.name, "nodearraysize") and a.args.len == 1) {
io.array_size = l.attrUint(a.args[0]);
} else if (eqi(a.name, "unboundedsparsenodes")) {
io.array_size = std.math.maxInt(u32);
io.allow_sparse_nodes = true;
} else if (eqi(a.name, "allowsparsenodes")) {
io.allow_sparse_nodes = true;
} else if (eqi(a.name, "maxrecordssharedwith") and a.args.len == 1 and a.args[0].kind == .name) {
try shared.append(l.arena, .{ .out = outputs.items.len, .name = a.args[0].kind.name.last() });
}
}
if (nt.kind.isInput()) {
try inputs.append(l.arena, io);
} else {
try outputs.append(l.arena, io);
try out_names.append(l.arena, pd.name);
}
}
for (shared.items) |sh| {
for (out_names.items, 0..) |n, k| if (std.mem.eql(u8, n, sh.name)) {
outputs.items[sh.out].max_records_shared_with = @intCast(k);
};
}
info.inputs = inputs.items;
info.outputs = outputs.items;
return info;
}
/// `[NodeID("name"[, index])]`, `[NodeShareInputOf(...)]`.
fn nodeId(l: *Lowerer, a: ast.Attribute) Error!?ir.NodeId {
if (a.args.len < 1 or a.args[0].kind != .string_lit) return null;
return .{ .name = try stringContents(l.arena, a.args[0].kind.string_lit), .index = if (a.args.len > 1) l.attrUint(a.args[1]) else 0 };
}
fn attrUint(l: *Lowerer, e: *const ast.Expr) u32 {
return @intCast(std.math.clamp(l.s.evalInt(e) orelse 0, 0, std.math.maxInt(u32)));
}
/// A record struct declared `[NodeTrackRWInputSharing]`.
fn trackRwInputSharing(l: *Lowerer, record: TypeId) bool {
const info = switch (l.s.types.get(record)) {
.@"struct" => |s| s,
else => return false,
};
return l.s.structHasAttr(info, "nodetrackrwinputsharing");
}
fn buildEntry(l: *Lowerer, f: *const semamod.Function, main: u32, opts: Options) Error!void { fn buildEntry(l: *Lowerer, f: *const semamod.Function, main: u32, opts: Options) Error!void {
const inits = try l.staticInits(); const inits = try l.staticInits();
var entry: ir.Entry = .{ .func = main, .name = opts.entry, .stage = opts.stage, .ext = try l.spirvExt(f.decl.attrs) }; var entry: ir.Entry = .{ .func = main, .name = opts.entry, .stage = opts.stage, .ext = try l.spirvExt(f.decl.attrs) };
@ -2429,6 +2563,9 @@ const Lowerer = struct {
if (std.ascii.eqlIgnoreCase(a.name, "numthreads") and a.args.len == 3) { if (std.ascii.eqlIgnoreCase(a.name, "numthreads") and a.args.len == 3) {
for (a.args, 0..) |arg, i| entry.num_threads[i] = @intCast(@max(1, l.s.evalInt(arg) orelse 1)); for (a.args, 0..) |arg, i| entry.num_threads[i] = @intCast(@max(1, l.s.evalInt(arg) orelse 1));
} }
if (std.ascii.eqlIgnoreCase(a.name, "wavesize") and a.args.len >= 1 and a.args.len <= 3) {
for (a.args, 0..) |arg, i| entry.wave_size[i] = @intCast(@max(0, l.s.evalInt(arg) orelse 0));
}
if (std.ascii.eqlIgnoreCase(a.name, "maxvertexcount") and a.args.len == 1) entry.geometry.max_vertex_count = @intCast(@max(1, l.s.evalInt(a.args[0]) orelse 1)); if (std.ascii.eqlIgnoreCase(a.name, "maxvertexcount") and a.args.len == 1) entry.geometry.max_vertex_count = @intCast(@max(1, l.s.evalInt(a.args[0]) orelse 1));
if (std.ascii.eqlIgnoreCase(a.name, "instance") and a.args.len == 1) entry.geometry.instance_count = @intCast(@max(1, l.s.evalInt(a.args[0]) orelse 1)); if (std.ascii.eqlIgnoreCase(a.name, "instance") and a.args.len == 1) entry.geometry.instance_count = @intCast(@max(1, l.s.evalInt(a.args[0]) orelse 1));
if (std.ascii.eqlIgnoreCase(a.name, "RootSignature") and a.args.len == 1 and a.args[0].kind == .string_lit) entry.root_signature = try stringContents(l.arena, a.args[0].kind.string_lit); if (std.ascii.eqlIgnoreCase(a.name, "RootSignature") and a.args.len == 1 and a.args[0].kind == .string_lit) entry.root_signature = try stringContents(l.arena, a.args[0].kind.string_lit);
@ -2458,14 +2595,25 @@ const Lowerer = struct {
} }
}; };
if (opts.stage == .amplification) entry.mesh.payload = l.mesh_payload; if (opts.stage == .amplification) entry.mesh.payload = l.mesh_payload;
if (opts.stage == .node) entry.node = try l.nodeInfo(f);
const tess = opts.stage == .hull or opts.stage == .domain; const tess = opts.stage == .hull or opts.stage == .domain;
if (tess) l.tessAttributes(f, &entry); if (tess) l.tessAttributes(f, &entry);
// Hull shaders: where the control point inputs start. // Hull shaders: where the control point inputs start.
var cp_first: ?u32 = null; var cp_first: ?u32 = null;
var node_in: u32 = 0;
var node_out: u32 = 0;
for (f.decl.params, f.params, 0..) |pd, p, i| { for (f.decl.params, f.params, 0..) |pd, p, i| {
if (l.s.types.get(p.type) == .stream) continue; if (l.s.types.get(p.type) == .stream) continue;
n_args += 1; n_args += 1;
const q = pd.quals; const q = pd.quals;
if (l.s.types.get(p.type) == .node) {
const output = !l.s.types.get(p.type).node.kind.isInput();
const index = if (output) node_out else node_in;
if (output) node_out += 1 else node_in += 1;
args[i] = try l.b.add(.{ .op = .{ .node_io = .{ .output = output, .index = index } }, .ty = p.type });
locals[i] = args[i];
continue;
}
if (opts.stage == .mesh and (q.vertices or q.indices or q.primitives) and l.s.types.get(p.type) == .array) { if (opts.stage == .mesh and (q.vertices or q.indices or q.primitives) and l.s.types.get(p.type) == .array) {
// Output arrays: stores through them write the outputs. // Output arrays: stores through them write the outputs.
const arr = l.s.types.get(p.type).array; const arr = l.s.types.get(p.type).array;
@ -2748,7 +2896,6 @@ pub fn isObject(t: *TypeTable, ty: TypeId) bool {
}; };
} }
fn semanticOf(sems: []const ast.Semantic) ?[]const u8 { fn semanticOf(sems: []const ast.Semantic) ?[]const u8 {
for (sems) |sem| if (sem.kind == .semantic) return sem.values[0]; for (sems) |sem| if (sem.kind == .semantic) return sem.values[0];
return null; return null;
@ -2842,6 +2989,7 @@ fn signExtend(v: u64, bits: u8) i64 {
/// Whether `e` designates storage (a variable, or a part of one) rather /// Whether `e` designates storage (a variable, or a part of one) rather
/// than a temporary such as an operator call's result. /// than a temporary such as an operator call's result.
fn isAddressable(s: *const Sema, e: *const ast.Expr) bool { fn isAddressable(s: *const Sema, e: *const ast.Expr) bool {
if (s.resolution(e)) |r| if (r == .node_record) return true;
return switch (e.kind) { return switch (e.kind) {
.name, .this => true, .name, .this => true,
.member => |m| isAddressable(s, m.base), .member => |m| isAddressable(s, m.base),

View File

@ -181,7 +181,7 @@ fn mapRefs(a: Allocator, xs: []const Ref, ctx: anytype) Allocator.Error![]const
/// `op` with every operand passed through `ctx.map`. /// `op` with every operand passed through `ctx.map`.
pub fn mapOp(a: Allocator, op: Op, ctx: anytype) Allocator.Error!Op { pub fn mapOp(a: Allocator, op: Op, ctx: anytype) Allocator.Error!Op {
return switch (op) { return switch (op) {
.constant, .param, .global, .local_var, .input, .input_vertex, .emit, .cut, .patch_input, .output_vertex, .mesh_output, .mesh_payload, .ray_incoming, .spec_constant, .undef => op, .constant, .param, .global, .local_var, .input, .input_vertex, .emit, .cut, .patch_input, .output_vertex, .mesh_output, .mesh_payload, .ray_incoming, .spec_constant, .undef, .node_io => op,
.load => |p| .{ .load = ctx.map(p) }, .load => |p| .{ .load = ctx.map(p) },
.store => |x| .{ .store = .{ .ptr = ctx.map(x.ptr), .value = ctx.map(x.value) } }, .store => |x| .{ .store = .{ .ptr = ctx.map(x.ptr), .value = ctx.map(x.value) } },
.access => |x| .{ .access = .{ .base = ctx.map(x.base), .indices = try mapRefs(a, x.indices, ctx) } }, .access => |x| .{ .access = .{ .base = ctx.map(x.base), .indices = try mapRefs(a, x.indices, ctx) } },
@ -207,7 +207,7 @@ pub fn mapOp(a: Allocator, op: Op, ctx: anytype) Allocator.Error!Op {
const ops = try a.dupe(@typeInfo(@TypeOf(x.operands)).pointer.child, x.operands); const ops = try a.dupe(@typeInfo(@TypeOf(x.operands)).pointer.child, x.operands);
for (ops) |*o| switch (o.*) { for (ops) |*o| switch (o.*) {
.value => |*v| v.* = ctx.map(v.*), .value => |*v| v.* = ctx.map(v.*),
.literal, .type => {}, .literal, .type, .string => {},
}; };
const n = try a.create(ir.SpirvInst); const n = try a.create(ir.SpirvInst);
n.* = x.*; n.* = x.*;
@ -227,7 +227,7 @@ pub fn mapOp(a: Allocator, op: Op, ctx: anytype) Allocator.Error!Op {
/// allocating. /// allocating.
pub fn eachOperand(op: Op, ctx: anytype) void { pub fn eachOperand(op: Op, ctx: anytype) void {
switch (op) { switch (op) {
.constant, .param, .global, .local_var, .input, .input_vertex, .emit, .cut, .patch_input, .output_vertex, .mesh_output, .mesh_payload, .ray_incoming, .spec_constant, .undef => {}, .constant, .param, .global, .local_var, .input, .input_vertex, .emit, .cut, .patch_input, .output_vertex, .mesh_output, .mesh_payload, .ray_incoming, .spec_constant, .undef, .node_io => {},
.load => |p| ctx.use(p), .load => |p| ctx.use(p),
.store => |x| { .store => |x| {
ctx.use(x.ptr); ctx.use(x.ptr);
@ -278,7 +278,7 @@ pub fn eachOperand(op: Op, ctx: anytype) void {
.heap_resource => |h| ctx.use(h.index), .heap_resource => |h| ctx.use(h.index),
.spirv_inst => |x| for (x.operands) |o| switch (o) { .spirv_inst => |x| for (x.operands) |o| switch (o) {
.value => |v| ctx.use(v), .value => |v| ctx.use(v),
.literal, .type => {}, .literal, .type, .string => {},
}, },
.patch_output => |x| ctx.use(x.value), .patch_output => |x| ctx.use(x.value),
.phi => |ps| for (ps) |pp| ctx.use(pp.value), .phi => |ps| for (ps) |pp| ctx.use(pp.value),

View File

@ -189,6 +189,8 @@ const Pass = struct {
if (info.done) return; if (info.done) return;
info.done = true; info.done = true;
const f = p.m.functions.items[fi]; const f = p.m.functions.items[fi];
// (Inlined everywhere: not emitted.)
if (f.dead) return;
// Callees first: their returns may be resources. // Callees first: their returns may be resources.
for (f.insts.items) |inst| if (inst.op == .call) try p.function(inst.op.call.func); for (f.insts.items) |inst| if (inst.op == .call) try p.function(inst.op.call.func);
@ -209,7 +211,10 @@ const Pass = struct {
const n_old = f.insts.items.len; const n_old = f.insts.items.len;
const ret_holds = holdsResources(p.t, f.ret) or isOpaque(p.t, f.ret); const ret_holds = holdsResources(p.t, f.ret) or isOpaque(p.t, f.ret);
for (f.blocks.items, 0..) |*blk, bi| { // Definitions before uses: inlining leaves a call's continuation
// ahead of the callee's blocks.
for (try reversePostorder(p.a, f)) |bi| {
const blk = &f.blocks.items[bi];
var out: std.ArrayList(Ref) = .empty; var out: std.ArrayList(Ref) = .empty;
for (blk.insts.items) |r| { for (blk.insts.items) |r| {
const old = f.insts.items[r.index()]; const old = f.insts.items[r.index()];
@ -421,7 +426,6 @@ const Pass = struct {
.@"switch" => |sw| blk.term = .{ .@"switch" = .{ .value = mp.map(sw.value), .default = sw.default, .cases = sw.cases } }, .@"switch" => |sw| blk.term = .{ .@"switch" = .{ .value = mp.map(sw.value), .default = sw.default, .cases = sw.cases } },
else => {}, else => {},
} }
_ = bi;
} }
_ = n_old; _ = n_old;
// What each out / inout resource holds when the function returns: // What each out / inout resource holds when the function returns:
@ -480,6 +484,42 @@ const Pass = struct {
} }
}; };
/// `f`'s blocks in reverse postorder from the entry (each block after its
/// dominators), then any unreachable ones in list order.
fn reversePostorder(a: Allocator, f: *const ir.Function) Allocator.Error![]const u32 {
const n = f.blocks.items.len;
const seen = try a.alloc(bool, n);
@memset(seen, false);
var post: std.ArrayList(u32) = try .initCapacity(a, n);
// (block, whether its successors were pushed)
var stack: std.ArrayList(struct { b: u32, expanded: bool }) = .empty;
if (n > 0) try stack.append(a, .{ .b = 0, .expanded = false });
while (stack.pop()) |it| {
if (it.expanded) {
post.appendAssumeCapacity(it.b);
continue;
}
if (seen[it.b]) continue;
seen[it.b] = true;
try stack.append(a, .{ .b = it.b, .expanded = true });
const succs: []const ir.BlockId = switch (f.blocks.items[it.b].term) {
.br => |t| &.{t},
.cond_br => |c| &.{ c.@"else", c.then },
.@"switch" => |sw| blk: {
const out = try a.alloc(ir.BlockId, sw.cases.len + 1);
for (sw.cases, 0..) |c, i| out[sw.cases.len - 1 - i] = c.block;
out[sw.cases.len] = sw.default;
break :blk out;
},
else => &.{},
};
for (succs) |sb| if (sb != .none and !seen[sb.index()]) try stack.append(a, .{ .b = @intCast(sb.index()), .expanded = false });
}
std.mem.reverse(u32, post.items);
for (0..n) |bi| if (!seen[bi]) post.appendAssumeCapacity(@intCast(bi));
return post.items;
}
/// Splits every function's resource-holding aggregates (SPIR-V only). /// Splits every function's resource-holding aggregates (SPIR-V only).
pub fn run(a: Allocator, m: *ir.Module, diags: *diag.Diagnostics) Error!void { pub fn run(a: Allocator, m: *ir.Module, diags: *diag.Diagnostics) Error!void {
var any = false; var any = false;

View File

@ -1,4 +1,4 @@
//! zdxc: an HLSL 2021 compiler targeting DXIL and SPIR-V. //! zdxc: an HLSL 2018 / 2021 compiler targeting DXIL and SPIR-V.
pub const diag = @import("diag.zig"); pub const diag = @import("diag.zig");
pub const options = @import("options.zig"); pub const options = @import("options.zig");

View File

@ -197,6 +197,16 @@ const Bindings = struct {
return null; return null;
} }
/// Bind `name` to `v` unless it is bound to a smaller value.
fn lower(b: *Bindings, name: []const u8, v: u16) void {
if (std.fmt.parseInt(u16, name, 10)) |_| return else |_| {}
for (b.names[0..b.n], b.values[0..b.n]) |k, *old| if (std.mem.eql(u8, k, name)) {
old.* = @min(old.*, v);
return;
};
_ = b.bind(name, v);
}
/// Bind or check; false on conflict. /// Bind or check; false on conflict.
fn bind(b: *Bindings, name: []const u8, v: u16) bool { fn bind(b: *Bindings, name: []const u8, v: u16) bool {
if (b.get(name)) |old| return old == v; if (b.get(name)) |old| return old == v;
@ -221,6 +231,7 @@ fn matchOne(sema: anytype, it: *const table.Intrinsic, object: ?TypeId, args: []
.resource => |r| r.elem, .resource => |r| r.elem,
.stream => |s| s.elem, .stream => |s| s.elem,
.patch => |p| p.elem, .patch => |p| p.elem,
.node => |x| x.elem,
else => TypeTable.error_type, else => TypeTable.error_type,
} else TypeTable.error_type; } else TypeTable.error_type;
@ -253,12 +264,66 @@ fn matchOne(sema: anytype, it: *const table.Intrinsic, object: ?TypeId, args: []
} }
var bindings: Bindings = .{}; var bindings: Bindings = .{};
// A vector size (`c` of `numeric<c>`) shared by several arguments takes
// the widest of them, scalars splatting to it, as in dxc: `dot(1, v)`
// is a dot product of v's size, not v truncated to a scalar.
{
var syms: [8][]const u8 = undefined;
var widest: [8]u16 = undefined;
var ok: [8]bool = undefined;
var ns: usize = 0;
for (args[0..it.params.len], 1..) |a, i| {
const ls = if (specs[i].dims.len > 0) specs[i] else specs[layout_group[i]];
if (ls.any_layout or ls.dims.len != 1) continue;
const sym = ls.dims[0];
if (std.fmt.parseInt(u16, sym, 10)) |_| continue else |_| {}
const sh = t.shape(a.ty) orelse continue;
const len: u16 = switch (sh.kind) {
.scalar => 1,
.vector => sh.cols,
else => continue,
};
const k = for (syms[0..ns], 0..) |s, j| {
if (std.mem.eql(u8, s, sym)) break j;
} else blk: {
if (ns == syms.len) break :blk null;
syms[ns] = sym;
widest[ns] = len;
ok[ns] = true;
ns += 1;
break :blk ns - 1;
} orelse continue;
// (Vectors of two different sizes: left to the usual binding,
// which converts to the first.)
if (len != 1 and widest[k] != 1 and len != widest[k]) ok[k] = false;
widest[k] = @max(widest[k], len);
}
for (syms[0..ns], widest[0..ns], ok[0..ns]) |s, w, good| if (good and w > 1) {
_ = bindings.bind(s, w);
};
}
for (args[0..it.params.len], 1..) |a, i| { for (args[0..it.params.len], 1..) |a, i| {
// (Also arguments whose layout links to a `<>` one.) // (Also arguments whose layout links to a `<>` one.)
if (!specs[i].any_layout and !specs[layout_group[i]].any_layout) continue; if (!specs[i].any_layout and !specs[layout_group[i]].any_layout) continue;
const sh = t.shape(a.ty) orelse continue; const sh = t.shape(a.ty) orelse continue;
if (bindings.any_shape == null or sh.count() > bindings.any_shape.?.count()) bindings.any_shape = sh; if (bindings.any_shape == null or sh.count() > bindings.any_shape.?.count()) bindings.any_shape = sh;
} }
// A dimension shared by several arguments (`dot(numeric<c>,
// numeric<c>)`, mul's `numeric<r, c>` and `numeric<c>`) is the
// smallest one: dxc truncates the larger arguments (with a warning).
// Scalars splat and do not bind it.
for (args[0..it.params.len], 1..) |a, i| {
const ls = if (specs[i].dims.len > 0) specs[i] else specs[layout_group[i]];
const sh = t.shape(a.ty) orelse continue;
switch (ls.dims.len) {
1 => if (sh.kind == .vector) bindings.lower(ls.dims[0], sh.cols),
2 => if (sh.kind == .matrix) {
bindings.lower(ls.dims[0], sh.rows);
bindings.lower(ls.dims[1], sh.cols);
},
else => {},
}
}
var sum: u32 = 0; var sum: u32 = 0;
var worst: u32 = 0; var worst: u32 = 0;
const out_params = try sema.arena.alloc(bool, args.len); const out_params = try sema.arena.alloc(bool, args.len);
@ -321,6 +386,12 @@ fn paramType(
// Non-numeric classes. // Non-numeric classes.
const base = if (cs.special == .none) cs.base else s.base; const base = if (cs.special == .none) cs.base else s.base;
// NodeOutput's Get{Thread,Group}NodeOutputRecords: records of the
// output's record type.
if (i == 0 and obj_elem != TypeTable.error_type) {
const records: ?types.NodeKind = if (std.mem.eql(u8, base, "ThreadNodeOutputRecords")) .thread_output_records else if (std.mem.eql(u8, base, "GroupNodeOutputRecords")) .group_output_records else null;
if (records) |k| return try t.intern(.{ .node = .{ .kind = k, .elem = obj_elem } });
}
if (!std.mem.eql(u8, base, "void") and !isNumericClass(base)) { if (!std.mem.eql(u8, base, "void") and !isNumericClass(base)) {
// Objects (samplers are checked) and classes zdxc does not model // Objects (samplers are checked) and classes zdxc does not model
// (HitObject, node records, LinAlg...): unconstrained. // (HitObject, node records, LinAlg...): unconstrained.

View File

@ -89,6 +89,9 @@ pub const Resolution = union(enum) {
/// A bitfield member (`this_bitfield`: named without `this.`). /// A bitfield member (`this_bitfield`: named without `this.`).
bitfield: types.Bitfield, bitfield: types.Bitfield,
this_bitfield: types.Bitfield, this_bitfield: types.Bitfield,
/// A node object's record: `Get()`, `Get(i)` or `[i]` (lowered as an
/// element of the object).
node_record,
}; };
pub const Param = struct { pub const Param = struct {
@ -96,6 +99,10 @@ pub const Param = struct {
type: TypeId, type: TypeId,
dir: enum { in, out, inout }, dir: enum { in, out, inout },
has_default: bool, has_default: bool,
/// A template instance's default argument that does not convert to
/// the parameter's type: an error only where a call uses it (C++
/// instantiates default arguments on use).
bad_default: bool = false,
/// `groupshared` parameter (SM 6.8 groupshared arguments). /// `groupshared` parameter (SM 6.8 groupshared arguments).
groupshared: bool = false, groupshared: bool = false,
}; };
@ -1352,6 +1359,18 @@ pub const Sema = struct {
// Any other builtin object (RayQuery, node records, vk:: types...). // Any other builtin object (RayQuery, node records, vk:: types...).
// vk::ext_result_id<T>: a T (an inline instruction's result). // vk::ext_result_id<T>: a T (an inline instruction's result).
if (eql(n, "ext_result_id") and args.len == 1) return try s.typeArg(args[0]) orelse TypeTable.error_type; if (eql(n, "ext_result_id") and args.len == 1) return try s.typeArg(args[0]) orelse TypeTable.error_type;
// Work graph node objects: their record type.
if (types.NodeKind.named(n)) |kind| {
var elem: TypeId = TypeTable.void_type;
if (kind.templated()) {
if (args.len == 0) {
s.err(t.loc, "'{s}' requires a record type template argument", .{n});
return TypeTable.error_type;
}
elem = try s.typeArg(args[0]) orelse return TypeTable.error_type;
}
return s.types.intern(.{ .node = .{ .kind = kind, .elem = elem } });
}
if (isOtherBuiltinObject(n)) { if (isOtherBuiltinObject(n)) {
var elem: TypeId = TypeTable.void_type; var elem: TypeId = TypeTable.void_type;
if (eql(n, "RayQuery")) { if (eql(n, "RayQuery")) {
@ -1548,6 +1567,15 @@ pub const Sema = struct {
// ------------------------------------------------------------------ // ------------------------------------------------------------------
// Constant evaluation (array sizes, case labels, template arguments) // Constant evaluation (array sizes, case labels, template arguments)
/// Whether struct `info` was declared with attribute `name` (any case).
pub fn structHasAttr(s: *const Sema, info: *const types.StructInfo, name: []const u8) bool {
_ = s;
const ss: *const StructSema = @ptrCast(@alignCast(info.sema orelse return false));
if (ss.decl.kind != .@"struct") return false;
for (ss.decl.kind.@"struct".attrs) |a| if (std.ascii.eqlIgnoreCase(a.name, name)) return true;
return false;
}
pub fn evalInt(s: *Sema, e: *const ast.Expr) ?i64 { pub fn evalInt(s: *Sema, e: *const ast.Expr) ?i64 {
return switch (s.evalConst(e) orelse return null) { return switch (s.evalConst(e) orelse return null) {
.int => |v| v, .int => |v| v,
@ -2166,6 +2194,13 @@ pub const Sema = struct {
if (last_shader) |kept| { if (last_shader) |kept| {
if (!eql(kept, stage)) s.err(a.loc, "shader attribute type '{s}' conflicts with shader attribute type '{s}'", .{ stage, kept }); if (!eql(kept, stage)) s.err(a.loc, "shader attribute type '{s}' conflicts with shader attribute type '{s}'", .{ stage, kept });
} else last_shader = stage; } else last_shader = stage;
} else if (std.ascii.eqlIgnoreCase(a.name, "nodelaunch") and a.args.len == 1 and a.args[0].kind == .string_lit) {
// (Exactly these: dxc compares case-sensitively.)
const lit = a.args[0].kind.string_lit;
const v = if (lit.len >= 2) lit[1 .. lit.len - 1] else lit;
if (!eql(v, "broadcasting") and !eql(v, "coalescing") and !eql(v, "thread")) {
s.err(a.args[0].loc, "attribute 'NodeLaunch' must have one of these values: broadcasting,coalescing,thread", .{});
}
} else if (std.ascii.eqlIgnoreCase(a.name, "wavesize")) { } else if (std.ascii.eqlIgnoreCase(a.name, "wavesize")) {
if (last_wavesize) |kept| { if (last_wavesize) |kept| {
var same = kept.args.len == a.args.len; var same = kept.args.len == a.args.len;
@ -2490,7 +2525,16 @@ pub const Sema = struct {
.has_default = p.init != null, .has_default = p.init != null,
.groupshared = p.quals.groupshared, .groupshared = p.quals.groupshared,
}; };
if (p.init) |init_e| _ = try s.checkInitializer(pt, init_e); if (p.init) |init_e| {
if (s.instance_depth > 0) {
const m = s.diags.mark();
_ = try s.checkInitializer(pt, init_e);
if (s.diags.error_count != m.errors) {
s.diags.rollback(m);
out.bad_default = true;
}
} else _ = try s.checkInitializer(pt, init_e);
}
} }
const func = try s.arena.create(Function); const func = try s.arena.create(Function);
func.* = .{ .name = name, .decl = f, .loc = d.loc, .ret = ret, .params = params, .defined = f.body != null, .owner = owner }; func.* = .{ .name = name, .decl = f, .loc = d.loc, .ret = ret, .params = params, .defined = f.body != null, .owner = owner };
@ -3554,6 +3598,17 @@ pub const Sema = struct {
return .{ .ty = TypeTable.error_type, .callee = .{ .method = .{ .object = b.ty, .name = name, .object_lvalue = b.lvalue } } }; return .{ .ty = TypeTable.error_type, .callee = .{ .method = .{ .object = b.ty, .name = name, .object_lvalue = b.lvalue } } };
}, },
.stream, .patch => return .{ .ty = TypeTable.error_type, .callee = .{ .method = .{ .object = b.ty, .name = name, .object_lvalue = b.lvalue } } }, .stream, .patch => return .{ .ty = TypeTable.error_type, .callee = .{ .method = .{ .object = b.ty, .name = name, .object_lvalue = b.lvalue } } },
.node => |x| {
// Get: the record (records objects); the rest from the
// intrinsics table.
const known = (eql(name, "Get") and x.kind.hasRecords()) or
if (methodNamespace(s.types.get(b.ty))) |ns| s.intrinsic_db.hasMethod(ns, name) else false;
if (!known) {
s.err(name_loc, "no member named '{s}' in '{s}'", .{ name, s.typeName(b.ty) });
return err_typed;
}
return .{ .ty = TypeTable.error_type, .callee = .{ .method = .{ .object = b.ty, .name = name, .object_lvalue = b.lvalue } } };
},
else => { else => {
s.err(name_loc, "member reference base type '{s}' is not a structure", .{s.typeName(b.ty)}); s.err(name_loc, "member reference base type '{s}' is not a structure", .{s.typeName(b.ty)});
return err_typed; return err_typed;
@ -3597,6 +3652,16 @@ pub const Sema = struct {
}; };
return .{ .ty = try s.types.vector(m.elem, m.cols), .lvalue = b.lvalue, .read_only = b.read_only }; return .{ .ty = try s.types.vector(m.elem, m.cols), .lvalue = b.lvalue, .read_only = b.read_only };
}, },
.node => |x| {
// Records of a records array; an output of an outputs array.
if (x.kind.isArray()) {
s.record(e, .node_record);
return .{ .ty = x.elem, .lvalue = true, .read_only = !x.kind.writable() };
}
if (x.kind.outputElement()) |k| return rvalue(try s.types.intern(.{ .node = .{ .kind = k, .elem = x.elem } }));
s.err(e.loc, "type '{s}' does not provide a subscript operator", .{s.typeName(b.ty)});
return err_typed;
},
.resource => |r| { .resource => |r| {
if (r.kind.indexDims() == 0 or r.elem == TypeTable.void_type) { if (r.kind.indexDims() == 0 or r.elem == TypeTable.void_type) {
if (r.kind == .other) return err_typed; if (r.kind == .other) return err_typed;
@ -3724,6 +3789,25 @@ pub const Sema = struct {
if (sym != .functions) return err_typed; if (sym != .functions) return err_typed;
return rvalue(s.resolveUserCall(e, sym.functions, arg_types, callee)); return rvalue(s.resolveUserCall(e, sym.functions, arg_types, callee));
}, },
.node => |x| if (eql(m.name, "Get")) {
// The record (`Get(i)`: of several).
const most: usize = if (x.kind.isArray()) 1 else 0;
if (arg_types.len > most) {
s.err(e.loc, "too many arguments to function call, expected at most {d}, have {d}", .{ most, arg_types.len });
return err_typed;
}
if (arg_types.len == 1 and s.conversionCost(arg_types[0].ty, try s.types.scalar(.uint)) == null) {
s.err(e.loc, "no matching member function for call to 'Get'", .{});
return err_typed;
}
s.record(e, .node_record);
return .{ .ty = x.elem, .lvalue = true, .read_only = !x.kind.writable() };
} else {
const ns = methodNamespace(s.types.get(m.object)) orelse return err_typed;
const r = try s.intrinsic_db.resolve(s, e.loc, ns, m.name, m.object, arg_types, null);
if (r.ok) s.record(e, .{ .intrinsic = .{ .index = r.index, .params = r.params, .object = m.object } });
return rvalue(r.ret);
},
else => { else => {
var explicit: ?TypeId = null; var explicit: ?TypeId = null;
if (template_args.len > 0) explicit = try s.typeArg(template_args[0]); if (template_args.len > 0) explicit = try s.typeArg(template_args[0]);
@ -3772,7 +3856,17 @@ pub const Sema = struct {
var explicit: ?TypeId = null; var explicit: ?TypeId = null;
if (template_args.len > 0) explicit = try s.typeArg(template_args[0]); if (template_args.len > 0) explicit = try s.typeArg(template_args[0]);
const r = try s.intrinsic_db.resolve(s, e.loc, if (s.opts.spirv and isVkQualified(callee)) "VkIntrinsics" else "Intrinsics", name, null, arg_types, explicit); const r = try s.intrinsic_db.resolve(s, e.loc, if (s.opts.spirv and isVkQualified(callee)) "VkIntrinsics" else "Intrinsics", name, null, arg_types, explicit);
if (r.ok) s.record(e, .{ .intrinsic = .{ .index = r.index, .params = r.params } }); if (r.ok) {
s.record(e, .{ .intrinsic = .{ .index = r.index, .params = r.params } });
// `dot(float4, float3)`: the longer argument is truncated.
for (arg_types, r.params[0..@min(arg_types.len, r.params.len)], 0..) |a, pt, i| {
const as = s.types.shape(a.ty) orelse continue;
const ps = s.types.shape(pt) orelse continue;
if (as.kind == .scalar or ps.kind == .scalar or (ps.rows >= as.rows and ps.cols >= as.cols)) continue;
const loc = if (e.kind == .call and i < e.kind.call.args.len) startLoc(e.kind.call.args[i]) else a.loc;
s.warn(loc, "conversion", "implicit truncation of vector type", .{});
}
}
return rvalue(r.ret); return rvalue(r.ret);
} }
@ -3826,6 +3920,10 @@ pub const Sema = struct {
s.err(a.loc, "cannot bind non-lvalue argument to {s} parameter", .{if (f.params[i].dir == .out) "out" else "inout"}); s.err(a.loc, "cannot bind non-lvalue argument to {s} parameter", .{if (f.params[i].dir == .out) "out" else "inout"});
} }
} }
for (f.params[@min(args.len, f.params.len)..]) |p| if (p.bad_default) {
s.err(callee.loc, "cannot initialize a parameter of type '{s}' with its default argument", .{s.typeName(p.type)});
return TypeTable.error_type;
};
if (s.current_fn) |caller| caller.callees.append(s.arena, f) catch {}; if (s.current_fn) |caller| caller.callees.append(s.arena, f) catch {};
s.record(e, .{ .function = f }); s.record(e, .{ .function = f });
s.ensureBody(f) catch {}; s.ensureBody(f) catch {};
@ -4067,6 +4165,9 @@ pub fn parseIntLiteral(text: []const u8) ?i64 {
if (digits.len > 2 and digits[0] == '0' and (digits[1] == 'x' or digits[1] == 'X')) { if (digits.len > 2 and digits[0] == '0' and (digits[1] == 'x' or digits[1] == 'X')) {
base = 16; base = 16;
body = digits[2..]; body = digits[2..];
} else if (isBinaryLiteral(digits)) {
base = 2;
body = digits[2..];
} else if (digits.len > 1 and digits[0] == '0') { } else if (digits.len > 1 and digits[0] == '0') {
base = 8; base = 8;
body = digits[1..]; body = digits[1..];
@ -4086,6 +4187,11 @@ pub fn parseFloatLiteral(text: []const u8) ?f64 {
/// dxc's `.#INF`): where the suffix starts and whether it is floating. /// dxc's `.#INF`): where the suffix starts and whether it is floating.
fn scanLiteral(text: []const u8) struct { end: usize, float: bool, inf: bool = false } { fn scanLiteral(text: []const u8) struct { end: usize, float: bool, inf: bool = false } {
var i: usize = 0; var i: usize = 0;
if (isBinaryLiteral(text)) {
i = 2;
while (i < text.len and (text[i] == '0' or text[i] == '1')) i += 1;
return .{ .end = i, .float = false };
}
const hex = text.len > 1 and text[0] == '0' and (text[1] == 'x' or text[1] == 'X'); const hex = text.len > 1 and text[0] == '0' and (text[1] == 'x' or text[1] == 'X');
if (hex) i = 2; if (hex) i = 2;
const isDigit = struct { const isDigit = struct {
@ -4114,6 +4220,24 @@ fn scanLiteral(text: []const u8) struct { end: usize, float: bool, inf: bool = f
return .{ .end = i, .float = float }; return .{ .end = i, .float = float };
} }
/// `0b101`: a binary integer literal (clang accepts them in HLSL).
/// Where an expression's text starts (clang's getBeginLoc): `i` in `i.T`.
fn startLoc(e: *const ast.Expr) Loc {
return switch (e.kind) {
.member => |m| startLoc(m.base),
.index => |x| startLoc(x.base),
.binary => |b| startLoc(b.lhs),
.assign => |b| startLoc(b.lhs),
.conditional => |c| startLoc(c.cond),
.call => |c| startLoc(c.callee),
else => e.loc,
};
}
fn isBinaryLiteral(text: []const u8) bool {
return text.len > 2 and text[0] == '0' and (text[1] == 'b' or text[1] == 'B') and (text[2] == '0' or text[2] == '1');
}
/// `f16` / `f32` / `f64` (any case) at the end of a float literal. /// `f16` / `f32` / `f64` (any case) at the end of a float literal.
fn fixedFloatSuffix(text: []const u8) ?[]const u8 { fn fixedFloatSuffix(text: []const u8) ?[]const u8 {
if (text.len < 4) return null; if (text.len < 4) return null;
@ -4328,6 +4452,15 @@ fn methodNamespace(t: types.Type) ?[]const u8 {
.constant_buffer, .texture_buffer, .raytracing_acceleration_structure => null, .constant_buffer, .texture_buffer, .raytracing_acceleration_structure => null,
.other => if (std.mem.eql(u8, r.name, "RayQuery")) "RayQueryMethods" else if (std.mem.eql(u8, r.name, "SubpassInput")) "VkSubpassInputMethods" else if (std.mem.eql(u8, r.name, "SubpassInputMS")) "VkSubpassInputMSMethods" else null, .other => if (std.mem.eql(u8, r.name, "RayQuery")) "RayQueryMethods" else if (std.mem.eql(u8, r.name, "SubpassInput")) "VkSubpassInputMethods" else if (std.mem.eql(u8, r.name, "SubpassInputMS")) "VkSubpassInputMSMethods" else null,
}, },
.node => |x| switch (x.kind) {
.empty_input => "EmptyNodeInputMethods",
.rw_dispatch_input => "RWDispatchNodeInputRecordMethods",
.group_input, .rw_group_input => "GroupNodeInputRecordsMethods",
.output => "NodeOutputMethods",
.empty_output => "EmptyNodeOutputMethods",
.thread_output_records, .group_output_records => "GroupOrThreadNodeOutputRecordsMethods",
else => null,
},
else => null, else => null,
}; };
} }

View File

@ -527,6 +527,110 @@ pub const Type = union(enum) {
/// `__builtin_LinAlgMatrix [[__LinAlgMatrix_Attributes(c, m, n, use, /// `__builtin_LinAlgMatrix [[__LinAlgMatrix_Attributes(c, m, n, use,
/// scope)]]` (SM 6.10): an opaque matrix handle. /// scope)]]` (SM 6.10): an opaque matrix handle.
linalg: LinAlgMatrix, linalg: LinAlgMatrix,
/// A work graph node input, output or output record object
/// (`DispatchNodeInputRecord<T>`, `NodeOutput<T>`, ...): `elem` is the
/// record type (void for the empty ones).
node: struct { kind: NodeKind, elem: TypeId },
};
/// Work graph node object types, as DXC's NodeIOKind.
pub const NodeKind = enum {
dispatch_input,
rw_dispatch_input,
group_input,
rw_group_input,
thread_input,
rw_thread_input,
empty_input,
output,
output_array,
empty_output,
empty_output_array,
thread_output_records,
group_output_records,
pub const names = [_]struct { []const u8, NodeKind }{
.{ "DispatchNodeInputRecord", .dispatch_input }, .{ "RWDispatchNodeInputRecord", .rw_dispatch_input },
.{ "GroupNodeInputRecords", .group_input }, .{ "RWGroupNodeInputRecords", .rw_group_input },
.{ "ThreadNodeInputRecord", .thread_input }, .{ "RWThreadNodeInputRecord", .rw_thread_input },
.{ "EmptyNodeInput", .empty_input }, .{ "NodeOutput", .output },
.{ "NodeOutputArray", .output_array }, .{ "EmptyNodeOutput", .empty_output },
.{ "EmptyNodeOutputArray", .empty_output_array }, .{ "ThreadNodeOutputRecords", .thread_output_records },
.{ "GroupNodeOutputRecords", .group_output_records },
};
pub fn named(n: []const u8) ?NodeKind {
for (names) |e| if (std.mem.eql(u8, e[0], n)) return e[1];
return null;
}
pub fn name(k: NodeKind) []const u8 {
for (names) |e| if (e[1] == k) return e[0];
unreachable;
}
/// NodeIOFlags: input 0x1, output 0x2, read-write 0x4, empty 0x8,
/// array 0x10; record granularity thread 0x20, group 0x40, dispatch
/// 0x60.
pub fn ioFlags(k: NodeKind) u32 {
return switch (k) {
.dispatch_input => 0x61,
.rw_dispatch_input => 0x65,
.group_input => 0x41,
.rw_group_input => 0x45,
.thread_input => 0x21,
.rw_thread_input => 0x25,
.empty_input => 0x9,
.output => 0x6,
.output_array => 0x16,
.empty_output => 0xA,
.empty_output_array => 0x1A,
.thread_output_records => 0x26,
.group_output_records => 0x46,
};
}
pub fn isInput(k: NodeKind) bool {
return k.ioFlags() & 1 != 0;
}
/// Objects holding records (Get and, for the group ones, indexing).
pub fn hasRecords(k: NodeKind) bool {
return switch (k) {
.dispatch_input, .rw_dispatch_input, .group_input, .rw_group_input, .thread_input, .rw_thread_input, .thread_output_records, .group_output_records => true,
else => false,
};
}
/// Several records: `Get(i)` and `[i]` (dxc's IsArray).
pub fn isArray(k: NodeKind) bool {
return switch (k) {
.group_input, .rw_group_input, .thread_output_records, .group_output_records => true,
else => false,
};
}
/// An array of outputs: `[i]` is one.
pub fn outputElement(k: NodeKind) ?NodeKind {
return switch (k) {
.output_array => .output,
.empty_output_array => .empty_output,
else => null,
};
}
/// Records that may be written.
pub fn writable(k: NodeKind) bool {
return k.ioFlags() & 4 != 0 and k.hasRecords();
}
/// Whether the type takes a record type argument.
pub fn templated(k: NodeKind) bool {
return switch (k) {
.empty_input, .empty_output, .empty_output_array => false,
else => true,
};
}
}; };
pub const LinAlgMatrix = struct { comp: u32, m: u32, n: u32, use: u32, scope: u32 }; pub const LinAlgMatrix = struct { comp: u32, m: u32, n: u32, use: u32, scope: u32 };
@ -597,6 +701,7 @@ pub const TypeTable = struct {
.texture_view => |v| .{ .tag = 14, .a = v.texture, .b = @backingInt(v.kind) }, .texture_view => |v| .{ .tag = 14, .a = v.texture, .b = @backingInt(v.kind) },
.linalg => |x| .{ .tag = 16, .a = (@as(u64, x.comp) << 32) | x.m, .b = (@as(u64, x.n) << 32) | (@as(u64, x.use) << 16) | x.scope }, .linalg => |x| .{ .tag = 16, .a = (@as(u64, x.comp) << 32) | x.m, .b = (@as(u64, x.n) << 32) | (@as(u64, x.use) << 16) | x.scope },
.spirv => |x| .{ .tag = 15, .a = (@as(u64, x.opcode) << 32) | x.size, .b = std.hash.Wyhash.hash(x.alignment, std.mem.sliceAsBytes(x.operands)) }, .spirv => |x| .{ .tag = 15, .a = (@as(u64, x.opcode) << 32) | x.size, .b = std.hash.Wyhash.hash(x.alignment, std.mem.sliceAsBytes(x.operands)) },
.node => |x| .{ .tag = 17, .a = @backingInt(x.kind), .b = x.elem },
}; };
} }
@ -778,6 +883,7 @@ pub const TypeTable = struct {
.triangle => "TriangleStream", .triangle => "TriangleStream",
}, try t.format(gpa, s.elem), ""), }, try t.format(gpa, s.elem), ""),
.patch => |p| templateName(gpa, if (p.output) "OutputPatch" else "InputPatch", try t.format(gpa, p.elem), try std.fmt.allocPrint(gpa, ", {d}", .{p.count})), .patch => |p| templateName(gpa, if (p.output) "OutputPatch" else "InputPatch", try t.format(gpa, p.elem), try std.fmt.allocPrint(gpa, ", {d}", .{p.count})),
.node => |x| if (x.kind.templated()) templateName(gpa, x.kind.name(), try t.format(gpa, x.elem), "") else x.kind.name(),
.descriptor_heap => |h| if (h.sampler) "SamplerDescriptorHeap" else "ResourceDescriptorHeap", .descriptor_heap => |h| if (h.sampler) "SamplerDescriptorHeap" else "ResourceDescriptorHeap",
.dynamic_resource => "<dynamic resource>", .dynamic_resource => "<dynamic resource>",
.texture_view => |v| std.fmt.allocPrint(gpa, "{s}::{s}", .{ try t.format(gpa, v.texture), switch (v.kind) { .texture_view => |v| std.fmt.allocPrint(gpa, "{s}::{s}", .{ try t.format(gpa, v.texture), switch (v.kind) {

View File

@ -10,6 +10,7 @@ pub const Id = u32;
pub const Op = enum(u16) { pub const Op = enum(u16) {
undef = 1, undef = 1,
source = 3, source = 3,
string = 7,
name = 5, name = 5,
member_name = 6, member_name = 6,
extension = 10, extension = 10,
@ -259,6 +260,8 @@ pub const Section = enum {
memory_model, memory_model,
entry_points, entry_points,
execution_modes, execution_modes,
/// OpString (before OpSource and the names).
debug_strings,
debug_names, debug_names,
annotations, annotations,
types_globals, types_globals,

View File

@ -202,6 +202,10 @@ const Emitter = struct {
used_bindings: std.AutoHashMapUnmanaged(struct { u32, u32 }, void) = .empty, used_bindings: std.AutoHashMapUnmanaged(struct { u32, u32 }, void) = .empty,
spec_ids: std.AutoHashMapUnmanaged(u32, Id) = .empty, spec_ids: std.AutoHashMapUnmanaged(u32, Id) = .empty,
ext_imports: std.StringHashMapUnmanaged(Id) = .empty, ext_imports: std.StringHashMapUnmanaged(Id) = .empty,
string_ids: std.StringHashMapUnmanaged(Id) = .empty,
/// Reads of resource locals nothing assigns: the resource of the same
/// type each stands in with where it is used.
undef_resources: std.AutoHashMapUnmanaged(u32, Id) = .empty,
/// Flattened resource arrays: a variable per element. /// Flattened resource arrays: a variable per element.
flat_vars: std.AutoHashMapUnmanaged(u32, []const Id) = .empty, flat_vars: std.AutoHashMapUnmanaged(u32, []const Id) = .empty,
flat_iface: std.ArrayList(Id) = .empty, flat_iface: std.ArrayList(Id) = .empty,
@ -837,12 +841,30 @@ const Emitter = struct {
.value => |r| e.val(r), .value => |r| e.val(r),
.literal => |w| w, .literal => |w| w,
.type => |t| try e.typeId(t), .type => |t| try e.typeId(t),
.string => |str| try e.stringId(str),
}); });
const op: Op = if (x.set != null) .ext_inst else @enumFromInt(@as(u16, @intCast(x.opcode))); const op: Op = if (x.set != null) .ext_inst else @enumFromInt(@as(u16, @intCast(x.opcode)));
try e.b.emit(.functions, op, words.items); try e.b.emit(.functions, op, words.items);
return id; return id;
} }
/// A declared resource global of type `ty`.
fn anyGlobalOf(e: *Emitter, ty: TypeId) ?u32 {
for (e.m.globals.items, 0..) |g, gi| {
if (g.ty == ty and g.space == .resource and e.global_vars[gi] != 0) return @intCast(gi);
}
return null;
}
/// An OpString of `str` (made once).
fn stringId(e: *Emitter, str: []const u8) Error!Id {
if (e.string_ids.get(str)) |id| return id;
const id = e.b.newId();
try e.b.emitWithString(.debug_strings, .string, &.{id}, str, &.{});
try e.string_ids.put(e.arena, str, id);
return id;
}
/// An OpExtInstImport of `name` (made once). /// An OpExtInstImport of `name` (made once).
fn extInstImport(e: *Emitter, name: []const u8) Error!Id { fn extInstImport(e: *Emitter, name: []const u8) Error!Id {
if (std.mem.eql(u8, name, "GLSL.std.450")) { if (std.mem.eql(u8, name, "GLSL.std.450")) {
@ -1089,6 +1111,7 @@ const Emitter = struct {
.miss => 5317, .miss => 5317,
.callable => 5318, .callable => 5318,
.library => return e.unsupported("library targets are not supported", .{}), .library => return e.unsupported("library targets are not supported", .{}),
.node => return e.unsupported("work graph nodes are not supported in SPIR-V", .{}),
}; };
const wrapper = e.func_ids[entry.wrapper]; const wrapper = e.func_ids[entry.wrapper];
const name = if (e.m.entries.items.len == 1) e.vk.entry_name orelse entry.name else entry.name; const name = if (e.m.entries.items.len == 1) e.vk.entry_name orelse entry.name else entry.name;
@ -2372,7 +2395,9 @@ const Emitter = struct {
} }
fn val(e: *Emitter, r: Ref) Id { fn val(e: *Emitter, r: Ref) Id {
return e.vals[r.index()]; const v = e.vals[r.index()];
if (v == 0) if (e.undef_resources.get(r.index())) |stand_in| return stand_in;
return v;
} }
fn compOf(e: *Emitter, ty: TypeId) Scalar { fn compOf(e: *Emitter, ty: TypeId) Scalar {
@ -2385,6 +2410,7 @@ const Emitter = struct {
const ri = r.index(); const ri = r.index();
switch (i.op) { switch (i.op) {
.constant, .param, .local_var => {}, .constant, .param, .local_var => {},
.node_io => return e.unsupported("work graph nodes are not supported in SPIR-V", .{}),
.spec_constant => |k| e.vals[ri] = try e.specConstant(k), .spec_constant => |k| e.vals[ri] = try e.specConstant(k),
.spirv_inst => |x| e.vals[ri] = try e.spirvInst(x, i.ty), .spirv_inst => |x| e.vals[ri] = try e.spirvInst(x, i.ty),
.ray_incoming => |k| e.vals[ri] = try e.rayVar(switch (k) { .ray_incoming => |k| e.vals[ri] = try e.rayVar(switch (k) {
@ -2436,7 +2462,28 @@ const Emitter = struct {
try e.indexed_loads.put(e.arena, @intCast(ri), .{ .global = il.global, .indices = idx, .types = il.index_types, .nonuniform = il.nonuniform }); try e.indexed_loads.put(e.arena, @intCast(ri), .{ .global = il.global, .indices = idx, .types = il.index_types, .nonuniform = il.nonuniform });
return; 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) {
// A resource local nothing assigns (a struct copied
// with a resource member left unset, read where dxc's
// legalization folds the read away): its value is
// undefined, so any resource of its type will do.
// An OpUndef pointer would break logical addressing.
// Copies (`res = this`) pass the undefined value on
// without assigning it; the first real use takes the
// stand-in.
const only_copies = for (f.insts.items) |x| {
if (x.op != .store or x.op.store.ptr != p) continue;
const v = f.inst(x.op.store.value);
if (v.op != .load or f.inst(v.op.load).op != .local_var) break false;
} else true;
if (only_copies) if (e.anyGlobalOf(i.ty)) |g| {
if (e.spv_minor >= 4) try e.useVar(e.global_vars[g]);
e.vals[ri] = 0;
try e.undef_resources.put(e.arena, @intCast(ri), e.global_vars[g]);
return;
};
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;
} }
@ -2473,6 +2520,8 @@ const Emitter = struct {
} }
return; return;
} }
// Copying an undefined resource assigns nothing.
if (target.op == .local_var and e.undef_resources.contains(s.value.index())) 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", .{});
@ -4276,12 +4325,20 @@ const Emitter = struct {
} }
fn globalOf(e: *Emitter, r: Ref) ?u32 { fn globalOf(e: *Emitter, r: Ref) ?u32 {
return e.globalOfDepth(r, 0);
}
/// (Copies between resource locals can form cycles: give up after
/// `max_depth` steps.)
fn globalOfDepth(e: *Emitter, r: Ref, depth: u32) ?u32 {
const max_depth = 256;
if (depth > max_depth) return null;
const i = e.f.inst(r); const i = e.f.inst(r);
return switch (i.op) { return switch (i.op) {
.global => |g| g, .global => |g| g,
.load => |p| e.globalOf(p), .load => |p| e.globalOfDepth(p, depth + 1),
.local_var => for (e.f.insts.items) |inst| { .local_var => for (e.f.insts.items) |inst| {
if (inst.op == .store and inst.op.store.ptr == r) break e.globalOf(inst.op.store.value); if (inst.op == .store and inst.op.store.ptr == r) break e.globalOfDepth(inst.op.store.value, depth + 1);
} else null, } else null,
// A specialized parameter: the global it is bound to. // A specialized parameter: the global it is bound to.
.param => |pi| blk: { .param => |pi| blk: {

View File

@ -23,6 +23,9 @@ pub const Stage = enum {
promote, promote,
sccp, sccp,
unroll, unroll,
cse,
/// Block merging, bypassing and if-conversion (dxil/cfg.zig).
cfg,
bitcode, bitcode,
container, container,
spirv, spirv,