Each loop's block list was sorted after the walk that found its blocks,
for every loop on each of unrollOne's calls (230 calls of about 200
loops on 00828). The body's bitset already holds them in order: they
are read out of its words.
The hill-climbing set: -8.1% (A/B); output unchanged on the verify
corpus.
Values stored to locals were forwarded to later loads in the same block
only when constants (or status values); every value now is. Such loads
need no getelementptr, load or conversion back from i32 storage.
- The hill-climbing set: -2.4% (A/B).
- Output: 1,349 of 19,624 verify compiles change (loads from locals that
stay in memory, such as arrays also indexed at run time, read the
stored value directly).
- Validator 1.8: 11,488 Unreal compiles, 0 invalid; Glide's the same 12
invalid as before.
The same as a parameter's copy: a local stored once, whole, in the entry
block before any other use of it (the entry not branched back to),
otherwise only read and only indexed by constants, is now the stored
values (Unreal: `ViewState View = GetPrimaryView();` and the like). Its
store sets them; there is no alloca, store or load.
- The hill-climbing set: 781 ms to 718 ms (-8.1%).
- Output: 10,789 of 19,624 verify compiles change. Samples of 25 Unreal
and 25 Glide ones: Glide's differ only in the type table; Unreal's
lose zext / icmp ne / bitcast round trips through i32 storage, and
nothing else (no instruction added).
- Validator 1.8: 11,488 Unreal compiles, 0 invalid; Glide's the same 12
invalid as before.
An inlined function's by-value parameter is copied into a local, and a
struct parameter copied whole: every component a getelementptr and a
store (and a bitcast or zext where storage mixes types), then a load per
read, all of which promotion deletes again. Unreal passes its view state
(thousands of components) by value: 00195 inlined a 6-instruction
function 256 times and lowered 3.3 million instructions for it.
A copy that is never written and only indexed by constants
(regsLocals) is now the argument's values themselves: no alloca, stores
or loads; reads take the components at their offset.
- The hill-climbing set: 1,095 ms to 773 ms (-29%); 00195 -59%, Unreal's
other shaders 10-28%, Glide's 1-4.5%.
- Output: 2,853 of the 19,624 verify compiles change. Those checked
differ only in the type table, or lose zext / icmp ne round trips of
bools through i32 storage (the same code, smaller).
- Validator 1.8: 11,488 Unreal compiles, 0 invalid; Glide's 8,772 the
same 12 invalid as before this change.
unrollOne handles one loop and is called again until none is left (230
times on Unreal's slowest shader to unroll, 00828, with about 200 loops
in 13,000 blocks). Each call gave every loop an nb-byte body array and
scanned all nb blocks to visit it, rewrote a flag per instruction for
each loop it considered deleting, and built per-block successor and
predecessor lists. Bodies are now bitsets with sorted block lists,
deletion marks only the loop's own instructions (cleared after), and the
CFG's lists are slices of two packed arrays.
00828: unrolling 256 ms to 176 ms; the hill-climbing set -1.0% (A/B);
output unchanged on the verify corpus.
TypeTable's key (tag, a, b) has padding, so the automatic context hashed
it field by field through Wyhash's streaming interface on every vector,
matrix and array type looked up. KeyContext mixes its words.
Glide's shaders in the hill-climbing set: -1.1% (A/B); output unchanged
on the verify corpus.
finish passed each instruction to remapInst by value, got it back by
value and appended that: three copies of 48 bytes per instruction
lowered. It now copies each once, into its place, and renumbers there.
The hill-climbing set: -3.8% (A/B); output unchanged on the verify
corpus.
A Value has padding, so the emitter's maps keyed by one (the forwarding
map, status values, nonuniform values, texel copies) hashed it field by
field with Wyhash's streaming interface. ValueContext mixes its tag and
index into one word.
The hill-climbing set: -2.8% (A/B); output unchanged on the verify
corpus.
The type and constant pools hashed their small keys with Wyhash's
streaming interface (init, update per field, final). A splitmix64
finalizer over the fields does (slices still go through Wyhash).
The hill-climbing set: -1.1% (A/B); output unchanged on the verify
corpus.
Each stored component looked itself up in the status values and removed
its key from the forwarding map, both hash operations, though the first
is usually empty and the second often. Both are now skipped when empty.
The hill-climbing set: -0.8% (A/B, near noise); output unchanged on the
verify corpus.
Every liveness round re-examined every phi's entries. A phi has an entry
per edge, and folding only takes edges away, so a phi with as many
entries as its block has edges in from reachable blocks lost none; one
pass over the terminators counts those.
The hill-climbing set: -4.2% (A/B); output unchanged on the verify
corpus.
Dropping the entries of edges a folded branch removed checked each entry
against every earlier one, and counted its block's edges again: quadratic
in a phi's entries, every liveness round. Per-block counters (reset
after each phi) make it one pass.
ue-ps-q75: -2.5% (A/B); output unchanged on the verify corpus.
A file with any backslash (most headers: macro continuations) was copied
a byte at a time. The runs between backslashes are now found with
indexOfScalarPos (vectorized) and copied whole.
The hill-climbing set: preprocessing -5 to -8%; output unchanged on the
verify corpus.
std.StaticStringMap compares a word against every key of the same
length, and most identifiers the parser asks about are not keywords.
The word table is now an open-addressing table on an FNV hash, built at
compile time, comparing a stored hash before any bytes. The reserved
declaration specifiers and effect object names, scanned linearly per
identifier, are flags in it too.
Glide's small pixel shaders: -1.8% (A/B); output unchanged on the
verify corpus.
Sema.lookup hashed the name again in every scope out to the global one;
it now hashes once and probes each scope with that hash. TypeTable.scalar
interned its key through the type map on every call; it now keeps the
result per scalar.
Glide's shaders in the hill-climbing set: -3.1% (A/B); output unchanged
on the verify corpus.
Zig 0.17's ArenaAllocator is safe to share between threads: every
allocation is an atomic add, and some a compare-exchange. A compile
allocates millions of times on one thread. BumpArena does what it does
(chunks from a child allocator, growth and freeing in place for the
newest allocation, reset keeping capacity) without the atomics, and now
backs every arena that belongs to one compile: the DXIL emitter's and
module's, the front end's, rootsig, reflection, SPIR-V, the C API, the
job runner's workers and the DXC drop-in's per-thread arena. (The
drop-in's result objects keep std's: a caller may share them.)
The hill-climbing set: -5.4% (A/B), Glide's shaders -6.3%; output
unchanged on the verify corpus.
The constants block held every constant ever made, in the order they
were first asked for, including those only code that optimization later
removed used. Output bytes therefore depended on how much throwaway code
lowering made. writeBitcode now drops unused constants and numbers the
rest by first use (grouped by type, aggregates after their elements),
remapping every reference.
- Output: -7% on the hill-climbing set; Unreal shaders up to -59%
(ue-vs-2021: 10.2 KB to 4.2 KB).
- Cost: about 1.2 ms for the set (bitcode stage +18%, 0.25% of the total).
- Validator 1.8: 11,488 Unreal compiles, 0 invalid (10056, a work graph
node shader, fails to compile as before).
Of promotion's 16 passes over every instruction, 11 look only at
allocas, getelementptrs or loads and stores. The first pass now lists
those, and the others walk the lists.
The hill-climbing set: -2.1% (A/B); output unchanged on the verify
corpus.
Resolving an intrinsic call matches every overload, comparing class names
as strings, and the same calls (mul, dot, saturate, ...) recur with the
same argument types. Resolutions are memoized by name, object type,
explicit type and the arguments' types and lvalues (not those that
reported a diagnostic).
The hill-climbing set: sema -5.7%, its allocation calls -25%; output
unchanged on the verify corpus.
Few instructions carry metadata (!dx.nonuniform), but each had room for
an optional (kind, node) pair. It is now an index into Module.inst_mds,
and every pass moves 14% less memory.
The hill-climbing set: -2.1%; output unchanged on the verify corpus.
Liveness runs again each time an empty branch folds (up to 10 rounds on
the largest functions), and each round scanned every instruction for the
ones with effects. That list does not change between rounds.
The hill-climbing set: promotion -16%; output unchanged on the verify
corpus.
The emitter kept each block's instructions (56 bytes, with their id) in a
growing list per block, copied whenever one grew. Instructions now go to
fixed chunks by id that never move, and blocks and the prologue list
4-byte ids.
The hill-climbing set: -5.5% (lowering -12%, finish -12%); output
unchanged on the verify corpus.
Every constant and structured buffer access laid out its whole struct
again (layout.fieldOffsets), and loading a struct component by component
did so for each component (layout.componentOffset). Both are now cached
per struct or type and layout rules.
The hill-climbing set: -2.8% (lowering -9.5%); output unchanged on the
verify corpus.
Each element access allocated its { 0, k } index pair and looked its
pointer type up; constant pairs are now shared (by the index constant)
and the last pointer type kept. loadPtr also skips the forwarding lookup
when nothing is forwarded.
The hill-climbing set: -7.8% (lowering -12.7%, its allocation calls
halved); output unchanged on the verify corpus.
DXIL emission spent most of its time on three lookups that grew with the
shader:
- componentType and flatCount recursed through a struct's fields for
every component, so loading or storing a struct of n components was
O(n^2). Each struct's component types are now worked out once
(structComps), and mixedSizes / mixedStorage are cached per type.
- Module.constant and Module.getType searched every existing constant or
type; they are now hash-indexed with the same equality. intType and
small i32 constants also have direct caches.
- unroll's dominates walked the immediate-dominator chain; it is now an
interval check on the dominator tree's depth-first numbering.
finish also keeps operand slices with nothing to renumber instead of
copying them.
Output is unchanged on the hill-climbing set, every Glide recording and
2,080 Unreal ones. The hill-climbing set compiles in 638 ms instead of
2,130 (-70%); DXIL lowering is 86% faster and unrolling 84%.
A caller that wants them points stats.current at a Stats for the thread;
zones in compile (options, preprocess, parse, sema, lower, ir_opt, DXIL,
SPIR-V) and in DXIL emission (lowering, finish, promote, sccp, unroll,
bitcode, container) add their time and the caller's allocation counts,
and counters record DXIL instructions lowered and kept. Without a Stats a
zone costs one thread-local load.
The Unreal work unrolled far more than dxc does: the IR unrolled any
small constant-count loop, and the DXIL unroller any loop of up to 256
trips. On Glide's GlimmerProbeTrace and GlimmerSHUpdate compiles took
10-17x longer and DXIL grew to 470 KB (dxc: 155 KB), so Glide's
replayed compiles took 2.7x as long as with main.
- the IR's automatic unrolling is gone again (it did little for Unreal)
- DXIL unrolls a loop only when unrolled it stays within 300
instructions, as dxc unrolls only small loops without [unroll]
- SCCP visits blocks in reverse postorder, so it settles in a few passes
Glide, against main (bb942b0): 24 threads 1.36 s vs 1.25 s, serial sum
13.2 s vs 11.8 s, DXIL 58.1 MB vs 61.4 MB. Unreal's corpus still
compiles, validates, and reflects no UAV dxc leaves out.
Every shader the editor compiles (11,488 recorded Compile calls) now
compiles, passes DXC 1.8's validator, and reflects bindings the engine
accepts; the editor runs with the D3D debug layer clean.
Front end and semantics:
- -HV 2016..2018 and 2021, with HLSL 2018's component-wise &&, || and ?:
- overload ranking with DXC's conversion costs (worst, then sum), where
intrinsics compete with user functions and templates; ref parameters
of intrinsics (Interlocked* destinations) match exactly
- template class methods checked on use; elaborated struct declarations;
struct fields before globals in methods
- layout of structs over 256 fields
DXIL backend:
- loops with a constant trip count unrolled after promotion (unroll.zig)
- sparse conditional constant propagation (sccp.zig)
- loops with no effects deleted; constant switches folded; float compares
of constants folded; phis read on the edge their branch's condition
decides; empty branches folded through chains of empty blocks
- unreachable blocks, unused groupshared, and resources no code uses any
more dropped; shader flags, PSV and handle properties from what is left
- 64-bit typed resources and atomics
Unreal Engine's D3D12 shader compiler needs DXC_OUT_REFLECTION and reads
every shader's parameters through ID3D12ShaderReflection; it also strips
parts with IDxcContainerBuilder and blobs through IDxcLibrary.
- The DXIL emitter builds the reflection with the object (dxil/reflect.zig):
bound resources, constant buffers with their variables and types, and
per-function data for libraries. A variable is marked used from the
optimized code, by the cbuffer components actually loaded, as DXC marks
them. Input signature usage is likewise taken from the optimized code.
- The drop-in returns it as DXC_OUT_REFLECTION, and IDxcUtils::
CreateReflection serves ID3D12ShaderReflection and
ID3D12LibraryReflection over it.
- New classes: DxcContainerBuilder and DxcContainerReflection; the utils
object also answers IDxcLibrary.
On the 65 test/dxil shaders, reflection printed through the D3D12
interfaces matches DXC 1.8's on 46; the rest differ in details clients do
not read (bitfield members, -Zpr matrix classes, resource order).
Windows (here, with Defender's on-access scanning) serializes opening
files: creating the corpus's 8,772 outputs takes about 1.8 s whatever
the thread count. The compile threads blocked on it, so --job barely
gained past 8 threads.
- A reading thread reads each job's input ahead of the compiles (at
most 256 jobs ahead), and a writing thread writes the outputs, in job
order, after them. An output that cannot be written is reported after
every job's output and fails its job.
- Files the jobs read through the compiler (headers) are cached for the
whole run, with misses remembered, so each is opened once instead of
once per job and include directory searched.
On the Glide corpus: compiles only, 13.6 -> 12.1 s on 1 thread and
2.75 -> 2.6 s on 24; preprocess and compile, 36.2 -> 17.1 s on 1 thread
and 7.3 -> 5.9 s on 24, which is about the time it takes to create its
17,544 output files. Outputs and diagnostics are identical to 0622292
on all 17,544 calls.
Every compile ran in an arena, where a growing list leaves each old
buffer behind, and a few sites dominated: the Glide corpus's 8,772
compiles allocated 38 GB. Now 24 GB:
- intrinsics: build the Db once per process and share it read-only
(it was rebuilt from the static table on every compile, 3.5 GB);
- parser: reserve the token list from the source size (5.2 GB of
regrowth), and collect name parts on the stack (25M allocations);
- dxil emit: reserve the function's instruction list in finish (5.0 GB);
- sema: reserve resolutions from the token count (1.0 GB).
zdxc --job on the corpus: 15.4 -> 14.3 s on 1 thread, 3.0 -> 2.65 s on
24. Output is byte-identical on a 1,462-compile subset.
valueType searched the prologue and every block for the instruction,
so lowering was quadratic in function size. On the Glide corpus it was
half of all samples in zdxc --job; with a type per id the corpus's
8,772 compiles take 15.4 s on 1 thread (was 21.6 s) and 3.0 s on 24
(was 7.4 s). Output is byte-identical on a 1,462-compile subset.
Freeing the arena after every Compile gave its blocks back to the OS
(smp_allocator maps 64 KiB and up directly), so each call faulted about
4 MB of fresh pages in again. On the Glide corpus's 8,770 compiles that
was 9.06M page faults and up to 28 s of kernel time; with the arena kept
(reset to at most 64 MiB) it is 0.4-1.0M, and the replay is 25% faster
on 1 thread, 30% on 8 and 16% on 24. Output is byte-identical.
GlimmerProbeTrace (Glide) still came out at 374 KB of DXIL against
dxc's 155 KB, with 130 allocas against 40. Most of the remainder:
by-value struct parameters copied out of the constant buffer at every
call (GlimmerGroundParams and GlimmerSpanParams, 32 i32s each), then
indexed dynamically, which pinned each copy in memory.
- Arguments loaded from a constant buffer are passed as the constant
buffer place itself, structs as well as arrays (not with matrices,
whose constant buffer access is narrower than a local's). Locals still
alias only within a block with no write since. The alias now comes
first in local_var lowering, so the skipped parameter store always
matches.
- Peepholes on promoted values: bitcast round trips (int/float mixing
locals store i32s), constant integer arithmetic and comparisons,
identities, selects on a constant. A constant out-of-bounds array
index this exposes (on a path that cannot run) becomes 0, since the
validator rejects it.
- Inlined callees' array locals return to a per-type pool on return,
for later callees to reuse.
- -Od and -zdxc-no-opt skip promotion, aliasing and reuse, as they skip
the SPIR-V IR passes.
GlimmerProbeTrace: 374 KB to 191 KB, 21 allocas, 282 bitcasts (from
7198). Its pipeline builds in 3.6 s on an RX 9070 XT (was 5.1 s). All
of Glide's 400 DXIL compiles: 5.91 MB (dxc: 6.11 MB), 7.1x faster than
dxc. All pass dxc 1.8.2505's validator, and Glide renders.
Locals were left as allocas, so every access was a store or a reload.
Glide's GlimmerProbeTrace came out as 2.3 MB of DXIL (DXC: 155 KB) that
AMD's driver took over ten minutes to build into a pipeline, and the game
stalled on a black screen.
- promote.zig: SROA + mem2reg over the finished function. An alloca whose
accesses are loads and stores through constant indices becomes one SSA
variable per element, with phis at the iterated dominance frontiers.
Trivial phis fold away, and dead instructions go. Locals read before
they are written read zero, since the validator rejects reads of undef.
- Dynamically indexed locals pin only what the index can reach. The
emitter records each dynamic getelementptr's range (the indexed array's
extent), and the rest of the local is still promoted.
- A by-value array parameter that the callee only reads aliases the
caller's storage when the argument was loaded from a local in the same
block with no write since. This drops the per-call copies.
- Declarations that lose their last call are pruned before writing, since
the validator rejects unused external functions.
On Glide's 400 DXIL compiles, total output goes from 34.5 MB to 6.8 MB
(DXC: 6.1 MB), and GlimmerProbeTrace from 2.3 MB to 374 KB. Its
pipeline now builds in about 5 s. All 400 objects pass DXC 1.8.2505's
validator (checked with a copy built to claim validator 1.8), and Glide
renders on zdxc.
- A constant buffer vector indexed at run time loads the whole vector and
selects the component.
- Resource arrays in libraries: globals of class arrays, mangled as
pointers to their element (as dxc); each access loads its element for
createHandleForLib. NonUniform indices put !dx.nonuniform on the
getelementptr, so the bitcode writer now writes metadata kinds and
instruction attachments.
- Array types in mangled names count their dimensions as dxc does.
- A resource local assigned different elements of one resource array keeps
the element's index and makes the handle where it is read.
markUses kept the array it marks in a static, which concurrent library
compiles under --job shared: one could mark into another's array, or index
past its own. Make it thread-local.