Commit Graph

142 Commits

Author SHA1 Message Date
Peter Li 5ac8c1254a Add structured buffers of matrices
SPIR-V: MatrixStride / RowMajor on the block's array member (std430
strides, as dxc). DXIL: rows and row components read through the whole
matrix (a column-major row is not contiguous).
2026-10-31 12:58:48 -07:00
Peter Li c32f29c596 Add templated byte-address Load/Store
Load<T> / Store<T> of any numeric, struct or array type: one access
per component at natural-alignment offsets (matrices by row in DXIL,
by column in SPIR-V, as dxc). DXIL uses 64-bit raw buffer overloads
from SM 6.3 and two words (makeDouble / splitDouble) before; SPIR-V
assembles 64-bit values from word pairs and 16-bit ones from halves.

DXIL locals and statics whose components have several sizes live in
struct-typed memory; 16-bit values set the low-precision shader flag.
Test files may give extra compiler flags with // FLAGS:.
2026-10-31 12:55:12 -07:00
Peter Li cd878468da Add ConstantBuffer<T> and descriptor heaps
ConstantBuffer<S>: members (and bitfields, methods, whole-struct reads)
through the buffer, arrays of them, as function arguments. DXIL: cbuffer
resources from the handle; SPIR-V: a Block struct of its own per S.

ResourceDescriptorHeap / SamplerDescriptorHeap (SM 6.6): DXIL
createHandleFromHeap + annotateHandle (with the heap shader flags);
SPIR-V runtime arrays per element type on the next free bindings of set
0, as dxc.

SPIR-V specializations now take elements of resource arrays (and heap
elements at constant indices): the callee re-creates the access chain
instead of using the caller's id.
2026-10-31 12:44:45 -07:00
Peter Li f6be1447c5 Add mesh and amplification shaders
Output arrays (vertices, primitives, indices) are a pointer space of
their own: stores through it become storeVertexOutput /
storePrimitiveOutput / emitIndices in DXIL and per-attribute output
arrays in SPIR-V (SPV_EXT_mesh_shader, SPIR-V 1.4+). Payloads are
struct-typed memory accessed by GEP in DXIL (getMeshPayload, a
groupshared or local variable for dispatchMesh) and TaskPayloadWorkgroupEXT
storage in SPIR-V. MS/AS state metadata, PSV info and PSG1. PSV now
reports UsesViewID with its (empty) masks.

The codegen oracle passes each test's -fspv-target-env (spirv-val
spells vulkan1.1spirv1.4 as vulkan1.1spv1.4).
2026-10-31 12:29:20 -07:00
Peter Li 5c582cddca Add hull and domain shaders
Both backends: control points in and out, patch constants, the patch
constant function (a function of its own in DXIL, called once after a
barrier in SPIR-V), SV_TessFactor / SV_InsideTessFactor (TessLevelOuter
/ TessLevelInner), SV_DomainLocation, SV_OutputControlPointID. DXIL:
PSG1, HS/DS state metadata and PSV info, the full SigPoint table.
SPIR-V: hull outputs and domain inputs located by semantic as dxc.
Also fixes geometry shader per-vertex inputs taking a location per
vertex.
2026-10-31 12:12:06 -07:00
Peter Li 45e79f04fa Add bitfields
Consecutive bitfields pack into hidden storage fields as dxc lays them
out (DXIL by type size, SPIR-V by exact type); member reads shift and
mask, writes read-modify-write. Also: dxc's bitfield diagnostics, sizeof
evaluation, SPIR-V base-class layout as a nested struct, operator[]
results are not addressable, and the codegen oracle reports crashes.
2026-10-31 11:50:22 -07:00
Peter Li 40292bfced Allow out-of-line operator definitions 2026-10-31 11:33:41 -07:00
Peter Li 06bfbe2a06 Match dxc's operator overloading rules
Operators dxc forbids (=, compound assignments, ++, --, ->, new/delete,
non-member operators) are errors at the declaration; unary operators and
compound assignment on structs are 'scalar, vector, or matrix expected',
as in dxc. test/dxil/check.sh now fails when dxc rejects a test instead
of comparing with stale output.
2026-10-31 11:32:26 -07:00
Peter Li 392df21a12 Operator overloading (M0.2, part 2)
Member operator functions are ordinary methods; binary, unary, [], ()
and compound-assignment expressions on struct operands resolve to them
(op= falls back to op plus assignment) and lower as method calls on the
first operand.
2026-10-31 11:30:02 -07:00
Peter Li eeff789393 Templates and member functions (M0.2, part 1)
Function, class, typedef and variable templates: each instance checks a
deep copy of the template's AST (src/front/ast_clone.zig) with the
parameters bound in a scope under the declaring scope, so lowering sees
ordinary functions and structs. Explicit arguments, defaults, deduction
from T, vector<T, N>, matrix<T, R, C>, arrays and class-template
instances; overload sets of function templates; partial and explicit
specializations (struct and variable templates); forward-declared class
templates completed by their definition; nested typedefs in instances.

Member functions now lower: a hidden this parameter, unqualified fields
and methods inside methods, this, and calls through copies for base
methods on derived objects and non-local objects (as Vulkan requires).
Template uses zdxc cannot model (dx/linalg.h metaprogramming) report
'not supported yet'.
2026-10-31 11:26:03 -07:00
Peter Li e8e77a172f Geometry shaders on both backends
Lowering: per-vertex inputs (point/line/triangle/lineadj/triangleadj
arrays), stream outputs registered per stream parameter in order, and
Append/RestartStrip from any function (streams are compile-time only and
drop out of IR signatures). [maxvertexcount] and [instance].

DXIL: GSVIn/GSIn/GSOut signatures (SV_PrimitiveID as a shadow element,
SV_GSInstanceID by intrinsic), vertex-indexed loadInput, emitStream /
cutStream, GS state metadata, PSV0 geometry info, MaxVertexCount and
per-stream dependency tables. SPIR-V: the Geometry execution model and
modes, arrayed per-vertex inputs, OpEmitVertex / OpEndPrimitive (stream
variants for several streams), and the PrimitiveId, InvocationId, Layer,
ViewportIndex and SampleId builtins (Flat on integer fragment builtins).
2026-10-31 11:11:28 -07:00
Peter Li ae1fb98cad SPIR-V target environments and wave intrinsics
-fspv-target-env picks the SPIR-V version (vulkan1.1: 1.3, vulkan1.2:
1.5, vulkan1.3: 1.6, ...). From SPIR-V 1.4 storage buffers use the
StorageBuffer class with Block and the entry interface lists all
globals. Wave/quad intrinsics become GroupNonUniform operations and
subgroup builtins (Vulkan 1.1+). The codegen oracle validates each test
in its own target environment.
2026-10-31 11:03:51 -07:00
Peter Li 45c7746c7f Static locals; DXIL wave and quad intrinsics
Static locals are private globals initialized on entry with the other
statics. DXIL wave/quad intrinsics (lane queries, votes, ballot, reads,
active and prefix reductions, quad reads and votes) match dxc's calls,
with the wave-ops shader flag.
2026-10-31 10:58:41 -07:00
Peter Li d3532368ae switch statements on both backends
Lowering builds one block per case label (consecutive labels fall
through), with break leaving the switch and continue reaching the
enclosing loop. DXIL gains the LLVM switch instruction.
2026-10-31 10:56:48 -07:00
Peter Li 52266c6fc6 Groupshared memory, atomics, counters and byte-address buffers
DXIL: groupshared variables are address-space-3 module globals (the
bitcode writer gains global variables, atomicrmw and cmpxchg), with the
PSV0 groupshared byte count. Interlocked* on groupshared memory,
structured and byte-address buffers, typed buffers and texels
(atomicBinOp / atomicCompareExchange). ByteAddressBuffer Load/Store
(2..4) and atomic methods; IncrementCounter / DecrementCounter, Append
and Consume buffers with the counter flag in metadata, PSV0 and SM 6.6
handle properties. Also fixes void intrinsics (barriers) in DXIL.

SPIR-V: the same atomics (OpImageTexelPointer for texels, Workgroup or
Device scope, Int64Atomics), byte-address buffer methods, and dxc's
separate counter buffers for counters and Append/Consume. Typed-buffer
elements reached through assignments read and write as images.
2026-10-31 10:51:26 -07:00
Peter Li 7a74e55fc7 Intrinsics with out parameters; 64-bit DXIL cbuffer members
Lowering passes `out` arguments of intrinsics through temporaries and
`ref` arguments (atomic destinations) as the storage itself. sincos,
modf, frexp (dxc's bit-level lowering on DXIL; ModfStruct/FrexpStruct
per row on SPIR-V, so matrices work) and asuint(double, out lo, out hi).
DXIL constant buffers now load 64-bit and 16-bit members, and SPIR-V
64-bit fragment inputs are Flat.
2026-10-31 10:40:10 -07:00
Peter Li 99f1ff38d5 Arrays of resources on both backends
Arrays of textures, buffers and samplers (sized, multi-dimensional and
unsized) are register ranges: DXIL creates each element's handle where
it is used (lower bound + flattened index, folded when constant) and
records the range in metadata and PSV0; SPIR-V uses array-typed
variables and access chains (runtime arrays need descriptor indexing).
NonUniformResourceIndex sets the non-uniform handle flag on DXIL and
decorates the index, access chain, load and sampled image NonUniform on
SPIR-V, with dxc's capabilities.
2026-10-31 10:35:47 -07:00
Peter Li ef77796cd9 Loop unrolling and constant folding
A shared IR pass (src/ir/opt.zig) runs before both backends:

- Full unrolling of loops with a constant trip count: [unroll] loops, and
  loops whose texture calls take texel offsets, which DXIL and Vulkan need
  as constants (dxc gets them from its unroller). The induction variable
  is a local only loaded and stored, initialized before the loop and
  stepped once in the continue block; each copy reads it as a constant.
  Innermost loops go first, so nests unroll fully. [loop] loops, loops
  with break or continue (their jumps would leave SPIR-V's structured
  regions), non-constant bounds and trips over the limit stay loops.
- Constant folding of scalar and vector arithmetic, comparisons,
  conversions, splats, extracts and shuffles, wrapping integers to their
  width.

Integer `static const` scalars now lower to constants (loop bounds such
as `x < KERNEL_END`). Also fixes negative int16_t SPIR-V constants, which
were written zero-extended.
2026-10-31 10:20:57 -07:00
Peter Li 5ab73ed89c Resources as function parameters and locals
DXIL: a resource local aliases the one handle stored into it (assigning
two different resources to one variable is reported, not miscompiled).
SPIR-V: functions with resource parameters are specialized per distinct
set of resource arguments, since Vulkan cannot pass buffer pointers to
functions; buffer block types are shared per HLSL type, and access chains
into buffers reached through parameters stay in Uniform std430 storage.
2026-10-31 10:08:53 -07:00
Peter Li ead0a0b9a6 Textures and samplers on both backends
Texture1D/2D/3D/Cube (and arrays), Texture2DMS, RWTexture*, Buffer and
RWBuffer, SamplerState and SamplerComparisonState. Methods: Sample,
SampleBias, SampleLevel, SampleGrad, SampleCmp, SampleCmpLevelZero,
SampleCmpLevel/Bias/Grad (DXIL 6.7/6.8), Load, operator[] reads and
writes, Gather and GatherCmp (per channel, one offset),
CalculateLevelOfDetail(Unclamped), GetDimensions (textures and buffers)
and, on DXIL, GetSamplePosition. Argument roles come from one shared
decoder (src/ir/texture.zig); out parameters of methods go through
temporaries.

DXIL follows dxc's argument layout (undef padding, zero offsets),
resource metadata and properties, replicated typed stores and the typed
UAV load flag. SPIR-V follows dxc's image types (unknown depth, inferred
formats for typed buffers and RW textures), capabilities and image
operands.

Also: SPIR-V interpolation decorations on pixel inputs and vertex
outputs (as dxc), a crash on array pixel inputs, and a miscompile on both
backends where swizzle components lived in a 16-entry static buffer, so
a function with more than 16 swizzles could silently read the wrong
components. test/spirv/check.sh (part of `zig build oracle`) checks
SPIR-V disassembly like test/dxil/check.sh does for DXIL.

Not yet: status (sparse feedback) arguments, Gather with four offsets,
and texel offsets that need loop unrolling to become constants.
2026-10-31 10:00:06 -07:00
Peter Li 7cac477a99 DXIL math intrinsics
atan2, fmod, isnan/isinf/isfinite, sign, step, smoothstep, degrees,
radians, ldexp, distance, reflect, refract, faceforward, cross and
determinant, lowered as dxc's HLOperationLower does (including its NaN
behavior for step and its atan2 quadrant fixups).
2026-10-31 07:42:59 -07:00
Peter Li ca171b5776 DXIL vertex and pixel shaders
Signatures follow dxc: semantic interpretation per signature point, a port
of the prefix-stable signature packer (registers and masks match dxc, so
stages link with dxc-compiled ones), canonical system-value names,
SV_Target arrays split per render target, ISG1/OSG1, PSV0 signature
elements and dependency tables, and signature metadata. Inputs and
outputs go through loadInput/storeOutput; shadow and not-in-signature
system values use their intrinsics. Adds discard, clip, derivatives and
fwidth, and signature-driven shader flags.

Also fixes two miscompiles found along the way: static global
initializers were dropped (both backends; they now run on entry in
declaration order, and DXIL keeps static globals in allocas), and DXIL
float constants were written as f64 bit patterns, so every float literal
read back as 0.0.

test/dxil/check.sh (part of `zig build oracle`) compares signatures with
dxc and checks the disassembly, since dxv does not catch wrong values.
2026-10-31 07:40:06 -07:00
Peter Li 8a9b5552aa Matrices and structs in codegen
SPIR-V:
- Float matrices are OpTypeMatrix with HLSL rows as columns (as dxc);
  integer / bool matrices are arrays of row vectors; 1xN / Nx1 are
  vectors. Arithmetic, comparisons, selects and component-wise
  intrinsics go row by row; mul maps to OpMatrixTimesVector /
  OpVectorTimesMatrix / OpMatrixTimesMatrix / OpDot with dxc's operand
  order (manual expansion for integers and vector-shaped matrices);
  transpose, matrix swizzles.
- Structs as OpTypeStruct. Buffer contents use laid-out type variants:
  std430 (structured buffers) and relaxed std140 (cbuffers), with member
  offsets, array strides, MatrixStride and RowMajor / ColMajor matching
  dxc; whole values convert between laid-out and plain types; access
  chains into structured buffer elements (buf[i].field).

Both backends:
- src/ir/layout.zig gains std430 and DXIL's packed structured-buffer
  layout and per-field row_major (recorded by Sema on fields and
  variables).
- Lowering: matrix-aware conversions (truncation, vector <-> matrix),
  constructors and initializer lists for structs and arrays, aggregate
  casts, derived-to-base conversion and stores through base casts.
- Entry points take and return structs: fields become signature
  elements, and a semantic on a struct numbers its fields.
- DXIL: structured buffers of structs (packed offsets, runs merged into
  4-wide loads / stores), buffer element access chains, mixed 32-bit
  struct locals, mul / transpose, cbuffer matrices by orientation.

oracle-codegen: SPIR-V 528 valid (was 313), DXIL 13 valid, 0 invalid.
2026-10-31 05:37:25 -07:00
Peter Li 8e5c318327 Constant buffers on both backends; default arguments
- Sema records each variable's cbuffer and the $Globals members in
  order; lowering turns a cbuffer (all members, since layout depends on
  every one) into a global of a synthetic struct type in a new .cbuffer
  space.
- src/ir/layout.zig: DX legacy cbuffer packing (DXIL) and dxc's relaxed
  std140 (SPIR-V), with field offsets, array strides and per-component
  offsets (column-major matrices).
- DXIL: cbufferLoadLegacy by register plus extractvalue, cbuffer handles
  and metadata records (size in bytes), $Globals first on the next free
  b register, CBV entries in PSV0.
- SPIR-V: Block structs with Offset / ArrayStride decorations matching
  dxc's bindings; bools stored as uints in externally visible storage.
- Calls fill missing trailing arguments from the parameters' defaults.

oracle-codegen: SPIR-V 313 valid, DXIL 6 valid (compute only), 0 invalid.
2026-10-31 05:15:15 -07:00
Peter Li 01bc248563 DXIL backend for compute shaders
src/dxil/emit.zig lowers IR to DXIL: calls are inlined while emitting
(returns merge through phis), values are scalarized, locals become
flattened [N x scalar] allocas, and resources become handles created on
entry (createHandle before SM 6.6, createHandleFromBinding plus
annotateHandle from 6.6). Structured, byte-address and typed buffer
reads and writes use bufferLoad/Store or rawBufferLoad/Store by shader
model; math intrinsics map to dx.op unary / binary / tertiary / dot
operations; compute system values to threadId and friends. The module
carries dx.resources, entry properties (shader flags, numthreads) and a
PSV0 part with resource bindings; dxv accepts the output.

The bitcode writer gains alloca, load, store, getelementptr, unreachable
and aggregate constants. Float-to-int constant folding saturates instead
of panicking on out-of-range values.

zig build oracle-codegen: SPIR-V 281 valid, DXIL 2 valid (compute only so
far), 0 invalid on either backend.
2026-10-31 05:05:51 -07:00
Peter Li c9b458a3b4 IR, AST lowering and a SPIR-V backend
- src/ir/ir.zig: typed values in a structured CFG (selection / loop
  headers name their merge and continue blocks), memory-form locals,
  functions kept, plus a text dump (-zdxc-ir).
- src/ir/lower.zig: lowers the entry point and everything it reaches
  from the AST and Sema's new resolutions (variables, call targets,
  intrinsic overloads, struct fields): statements, structured loops and
  selections, short-circuit operators, implicit conversions, copy-in /
  copy-out arguments, swizzle stores, resource reads and writes, and a
  parameterless entry wrapper over the stage inputs and outputs.
- src/spirv/emit.zig: IR -> SPIR-V with dxc's conventions (BufferBlock
  structured buffers with std430 strides, default register bindings,
  stage builtins, GLSL.std.450 intrinsics, structured merges).
- test/oracle/codegen.sh: compiles every dxc-valid corpus file and
  validates the output: 281 files produce SPIR-V spirv-val accepts, 0
  invalid; the rest report the construct not supported yet.
2026-10-31 04:54:45 -07:00
Peter Li d5d6b3578a Sema: unit tests for operator, register, indexing and recursion checks 2026-10-31 04:37:21 -07:00
Peter Li a234fc24c3 Sema/parser: fewer false errors on legacy and edge-case code
- Legacy effect syntax (technique blocks, effect object declarations,
  sampler_state assignments, local state blocks) is skipped with dxc's
  deprecation warnings.
- f16 / f32 / f64 float suffixes are accepted with dxc's 202x-extension
  warning (f16 needs -enable-16bit-types).
- Casts of lvalues that keep the component type are lvalues.
- No error for const locals without an initializer (dxc accepts them).
- 'using namespace dx' is accepted in every shader model.

oracle-verify: 85% of expected error lines caught, 12 false (was 51).
2026-10-31 04:27:44 -07:00
Peter Li b6552b8a67 Sema: more of dxc's declaration, type and TU checks
- Type attributes (row_major / column_major / unorm / snorm) are tracked
  as sugar through template arguments and typedefs, with dxc's conflict
  and applicability errors.
- Reserved C/C++ keywords (volatile, signed, long, ...) are rejected by
  the parser as in dxc.
- Typed resource element and template-argument count checks; vector /
  matrix size ranges (long vectors need SM 6.9) and scalar elements;
  constant out-of-bounds vector / matrix indices; `unsigned` on
  non-integer types; mixed matrix swizzle forms.
- packoffset syntax and placement, conflicting register semantics,
  string placement rules, conflicting [shader] / [WaveSize] attributes,
  builtin base classes, unsized inner array dimensions.
- Call graph and dxc's no-recursion check over exported / entry
  functions (run only on an otherwise valid unit).
- Typedef redeclaration with the same type is accepted.

oracle-verify: 85% of expected error lines caught (was 79%), 51 false.
2026-10-31 04:18:43 -07:00
Peter Li 77fbd26412 Sema: port dxc's operator, conversion and register checks
- Binary, compound-assignment and unary operators follow dxc's
  CheckBinOpForHLSL / CheckUnaryOpForHLSL: operand requirements, bool
  lvalues, objects / structs / arrays, min-precision division, double
  modulo.
- Shape conversions use a port of ConvertDimensions / CombineDimensions
  for implicit and explicit conversions and binary operands; assignment
  errors use dxc's "cannot [implicitly] convert" wording, and a
  declaration with a bad initializer no longer cascades errors.
- register(...) syntax and per-type register class validation.
- Resource subscripts check index dimensions; `.mips` / `.sample` views;
  unknown members of resource types are reported.
- Uses of operators on structs that declare overloads stay silent
  (milestone 0.2, reported at the declaration).

oracle-verify: 79% of expected error lines caught (was 53%), 66 false.
oracle-sema: still no false errors on the dxc-valid corpus.
2026-10-31 03:59:16 -07:00
Peter Li f81c049912 Add semantic analysis (Sema) with dxc-derived oracles
Sema type-checks a parsed translation unit: an interned type table, scopes
and symbols, declarations, statements and expressions, implicit and explicit
conversions, user-function overload resolution, and intrinsic / builtin
method matching driven by dxc's gen_intrin_main.txt (vendored, turned into a
Zig table at build time by tools/gen_intrinsics.zig).

Rules ported from dxc where it matters for exact agreement:
- operator result types (CombineBasicTypes, shift and bool rules)
- literal suffix types and diagnostics, including `1.#INF`
- declaration modifier validity and conflicts (DiagnoseHLSLDecl) and
  row_major / column_major checks, using source-ordered qualifier words
- constant folding of asuint / max / min
- `_Static_assert`, `__decltype` and `std::is_same` builtins
  (`static_assert` is an ordinary identifier in HLSL 2021)

Templates, operator overloading and bitfields report "not supported yet
(planned for milestone 0.2)".

Oracles:
- zig build oracle-sema: no false errors on the 1604 dxc-valid corpus
  files (1537 clean, 67 need milestone 0.2 features)
- zig build oracle-verify: error-line agreement with dxc's SemaHLSL
  -verify tests under HLSL 2021 (53% of expected error lines caught,
  80 false error lines)

Also fixes the provenance commit of gen_intrin_main.txt (55a61aa79).
2026-10-31 03:17:40 -07:00
Peter Li 88fe78bb3d dxc-compatible command line
zdxc now accepts dxc's command line as-is, so it can replace dxc in build
scripts.

- vendor/dxc/HLSLOptions.td (dxc's option definitions) is turned into a
  Zig table at build time by tools/gen_options.zig (no tablegen/Python).
- src/options.zig parses with LLVM OptTable's rules, as dxc does: `-`,
  `/` and `--` prefixes; flags, joined, separate, joined-or-separate,
  multi-arg and comma-joined options; longest spelling first; aliases;
  case-sensitive; `/`-prefixed non-options are input paths; the last input
  wins. `-T cs_6_0`, `/T cs_6_0` and `-Tcs_6_0` are all accepted.
- Every dxc option has a support level:
  - implemented (-T -E -Fo -D -I -P -Fi -HV -spirv -enable-16bit-types
    -WX -no-warnings -W[no-]x -fdiagnostics-format= -ferror-limit=
    -fdiagnostics-color[=] -O0..3 -Od -Vd -help --version -nologo ...),
  - accepted with a one-line note, no effect yet (-Zpr, -Gis, -Qstrip_*,
    -Fh, -fvk-*, -fspv-target-env=, ... ),
  - rejected with a reason: dropped features (-Zi/-Fd debug info,
    -Fc/-dumpbin disassembly, -recompile, -link, -verify, -ast-dump, LLVM
    internals) or "not supported by zdxc yet".
- Errors match dxc's: "unknown argument: '-x'", "argument to '-T' is
  missing"; exit codes 1 (command line / I/O) and 5 (compile errors).
- -help lists dxc's groups and help text for what zdxc accepts.
- zdxc-only options (-zdxc-*, -f[no-]color-diagnostics) use names dxc
  does not define.
- `zig build oracle-cli`: all 5873 `RUN: %dxc` command lines in the DXC
  test corpus parse; 3392 are accepted and 2481 rejected only for
  deliberately unsupported features, with 0 unknown/missing arguments.
2026-10-31 02:27:52 -07:00
Peter Li a87482931b Proper error reporting: macro backtraces, include chains, clang/msvc output
Diagnostics now match dxc's layout on the cases compared (nested macros,
include chains, #line, bracket matching, missing ';', fatal errors), with
range underlines and fix-it hints on top.

Locations:
- Macro-expanded tokens get clang-style macro locations: an expansion
  record (spelling, expansion point, macro name, argument or body).
  Errors print at the expansion site with "expanded from macro" notes,
  outermost first; argument tokens report at their own position.
- Files remember the #include that entered them ("In file included from").
- #line remapping moved into the source manager so diagnostics use
  presumed locations.
- UTF-16 sources with a BOM are decoded, as dxc does.

Engine (src/diag.zig):
- Diagnostics carry a range, notes, fix-it text and a warning group.
- Rendered in source order: the preprocessor runs ahead of the parser, so
  diagnostics are sorted by token position; a fatal error hides only what
  follows it.
- -fdiagnostics-format=clang|msvc|vi, colors when stderr is a terminal
  (-f[no-]color-diagnostics), -WX, -no-warnings, -Wno-<group>,
  -ferror-limit=N (default 20, applied in source order).

Messages:
- Missing ';' is reported after the previous token with a ';' fix-it and
  context ("at end of declaration", "after expression", ...); parsing
  continues when the next token starts a new line.
- Missing ')' / ']' / '}' get "note: to match this '('".
- "expected ';' after struct", "unknown type name 'X'", macro redefinition
  with "previous definition is here" [-Wmacro-redefined], #warning
  [-W#warnings], carets on the directive name / file name.
- Errors at end of file point just past the last token.
- Empty read()/write() payload qualifiers and static_assert (HLSL 202x)
  are rejected, matching dxc under -HV 2021.
2026-10-31 01:50:47 -07:00
Peter Li 8ecbe1719a Parser performance: keyword map and cheaper isIdent
pp_bench gains a `parse` mode (preprocess + parse). On the 4764-file,
13.1 MB DXC test corpus (ReleaseFast, interleaved A/B):
  parse  130.9 -> 78.2 ms (-40%); the parser's own share 92 -> 39 ms.

- A third of parse time was mem.eql in linear scans over keyword and
  builtin-type lists. All of them now go through one comptime
  std.StaticStringMap of per-word flags (reserved, qualifier, contextual,
  scalar, object, template): -38%.
- Token.isIdent compares lengths inline before calling mem.eql: -3%.
2026-10-31 01:29:58 -07:00
Peter Li 9089c5ea56 M0.1: HLSL 2021 parser and syntax tree
- src/front/ast.zig: purely syntactic tree (declarations, statements,
  expressions, types as written, attributes, semantics/registers).
- src/front/parser.zig: recursive descent over the preprocessed tokens,
  with a scoped type-name table to tell declarations from expressions,
  casts from parenthesized expressions and template arguments from
  comparisons. Covers the M0.1 language plus the syntax M0.2 needs
  (templates incl. partial specialization and variable templates, operator
  overloading, bitfields, methods, namespaces, enums, typedef/using) and
  dxc-isms seen in the corpus: payload access qualifiers, typed
  [[attributes]], legacy annotations / state blocks, `.template` calls,
  condition declarations, functions returning arrays.
- Error recovery at declaration and statement boundaries.
- src/front/ast_dump.zig and -zdxc-ast / -zdxc-parse dev flags.
- `zig build oracle-parse`: all 1604 corpus files that dxc compiles under
  -HV 2021 parse without errors; no crashes over all 4764 test files.
2026-10-31 01:20:46 -07:00
Peter Li c80747e6f4 Preprocessor performance, round 2: inline the lexer into lexRaw
- Lexer.next is force-inlined into the preprocessor's raw token loop and
  the _Pragma check no longer runs a string compare on every identifier
  (pp: -3%).
- pp_bench gains a `load` mode (source manager only).

Overall vs 74979f0 (before any tuning), 4764-file DXC test corpus,
ReleaseFast, interleaved A/B:
  lex    13.28 -> 10.34 ms  (-22%)
  load    6.89 ->  3.96 ms  (-43%)
  pp     50.11 -> 38.74 ms  (-23%)
  print  70.78 -> 48.99 ms  (-31%)

Tried and dropped in this round (no gain): a single-space fast path in
Lexer.next, and vector blank skipping limited to runs of 4+ spaces.
2026-10-31 00:50:49 -07:00
Peter Li 05f0a965be Preprocessor performance, round 1: benchmark + vector scans
Adds `zig build bench` (bench/pp_bench.zig): lexes / preprocesses / prints
a file list in-process, best of N, files served from memory.

On the 4764-file, 13.1 MB DXC test corpus (Apple M-series, ReleaseFast,
interleaved A/B against the previous commit):
  lex    13.3 -> 11.2 ms  (-16%)
  pp     49.7 -> 40.1 ms  (-19%)
  print  68.6 -> 53.2 ms  (-22%)

Kept:
- src/front/scan.zig: portable @Vector scans (width from
  std.simd.suggestVectorLength). Comment bodies are skipped with vector
  searches; line-start tables are built from per-block newline bitmasks.
- An identifier character table for the (short) identifier scans.
- A line cursor for -P printing: O(1) per token instead of a binary search.
- A 1024-bit filter over macro names so most identifiers skip hashing;
  the macro table is presized.

Tried and dropped (no gain): vector skipping of blank runs (2% slower;
gaps between tokens are mostly a single space) and fusing splice detection
into the newline scan.
2026-10-31 00:45:52 -07:00
Peter Li 74979f0548 Preprocessor: close the remaining review gaps
- '#' not followed by a parameter in a function-like macro is an error
  (object-like macros keep '#' literally), as in dxc.
- _Pragma("...") is destringized and handled like a #pragma line;
  "#pragma once in main file" now warns instead of registering.
- GNU line markers (`# 40 "file" 1 3`, `#40`) work like #line.
- Macro-argument pre-expansion and #if parentheses are limited to 512
  levels of nesting with a diagnostic, instead of overflowing the stack
  (dxc segfaults at a few thousand levels).
2026-10-31 00:35:58 -07:00
Peter Li d9e2130f87 Preprocessor review fixes: include search order, #if short-circuit, caching
- Quoted includes now search the directory of every file on the include
  stack (innermost first) before -I, and angled includes search only -I
  and the compiled-in headers, matching dxc. Angled lookups that only a
  quoted include would find get dxc's "use quotes" diagnostic.
- #if evaluation short-circuits &&, || and ?:; division by zero in an
  unevaluated operand is no longer an error (dxc accepts these).
- File contents are read once per path (with negative caching); each
  inclusion still gets its own FileId so #line state stays per inclusion.
- Include-guarded files (#ifndef X / #if !defined(X) wrapping the whole
  file) are not re-entered once X is defined. 2000 guarded includes:
  65 ms -> 2 ms per run (dxc: 3 ms).
- Skipped lines are now skipped token by token, so "/*" inside a string
  in an #if 0 block no longer swallows the #endif.
2026-10-31 00:29:29 -07:00
Peter Li fb322f24a7 M0.1: HLSL preprocessor matching dxc -P across the DXC test corpus
- Source manager (line splicing, UTF-8 BOM) and clang-style diagnostics.
- Lexer producing preprocessing tokens.
- Preprocessor modelled on clang's: object and function-like macros, #/##,
  variadics with GNU comma elision, painted recursion blocking, nested
  argument pre-expansion, #if/#elif expressions, #include with -I and
  #pragma once, #line, #error/#warning, pass-through #pragma, and dxc's
  predefined macros (__HLSL_VERSION, __SHADER_TARGET_*, __spirv__, ...).
- dxc's compiled-in HLSL headers (<dx/linalg.h>, <vk/spirv.h>, ...) are
  vendored as data and used as the fallback for angled includes.
- -P/-Fi/-D/-I/-HV 2021/-enable-16bit-types options; profiles now cover
  lib_, ms_, as_ and SM 6.0-6.11.
- `zig build oracle-pp`: token-for-token comparison with dxc -P. 2060 of
  2060 corpus files dxc accepts match.
2026-10-31 00:16:50 -07:00
Peter Li de2e3da34a M0.0: DXIL container, hash, bitcode writer and SPIR-V builder
- Port of DXC's container hash (ComputeHashRetail); matches dxc-signed
  containers on both padding paths.
- DXIL container reader/writer that signs its output.
- LLVM bitstream writer and a minimal LLVM 3.7 IR model that encodes types,
  constants, functions, core instructions and metadata as bitcode.
- An empty compute shader that dxv accepts for SM 6.0 through 6.9.
- SPIR-V builder; the empty compute module passes spirv-val (Vulkan 1.0).
- `zig build oracle` runs these checks against the DXC build.
2026-10-31 00:01:46 -07:00
Peter Li 8e38009a69 git package 2026-10-30 23:52:41 -07:00