MLIR spirv Dialect (MLIR / C++)
MLIR's one-to-one model of SPIR-V as a compiler IR — structured selection and loop regions, availability-driven capability inference and binary (de)serialization — together with the revived effort to give LDC an MLIR path, the one route by which D statements could reach SPIR-V without a heuristic structurizer.
| Field | Value |
|---|---|
| Language | C++ with ODS/TableGen op definitions |
| License | Apache-2.0 WITH LLVM-exception |
| Repository | llvm/llvm-project — mlir/include/mlir/Dialect/SPIRV/, mlir/lib/Dialect/SPIRV/, mlir/lib/Target/SPIRV/, mlir/lib/Conversion/*ToSPIRV/ |
| Documentation | mlir/docs/Dialects/SPIR-V.md · mlir.llvm.org SPIR-V dialect |
| Category | Toolchain — compiler IR and SPIR-V serializer |
| Latest version | LLVM main at 27ba493781 (2026-09-19); MLIR has no separate releases |
| Targets | SPIR-V binary only (Vulkan "Shader" and OpenCL "Kernel" environments); convert-spirv-to-llvm lowers per-invocation SPIR-V back to the LLVM dialect |
| Main users | IREE (Vulkan compute), Arm ML/graph extensions; graphics support driven by Imagination's research tooling (no production graphics user visible) |
| D connection | LDC MLIR revival ldc-developers/ldc#5300 (merged 2026-10-16), inline MLIR #5307 (open), SAoC 2026 "MLIR Support for LDC" (proposal) |
NOTE
MLIR paths are relative to mlir/ in llvm-project at upstream 27ba493781, the same revision as the LLVM SPIR-V backend deep-dive. The LDC side is read from PR metadata, LDC upstream at ac0e420a and the SAoC repository asindarov/mlir-support-for-D at 79cec3a1.
Overview
What it solves
LLVM IR cannot carry SPIR-V's structured control flow, typed pointers or capability requirements, so the LLVM backend reconstructs all three after the fact. The spirv dialect keeps them in the IR from the start: a spirv.module declares its version/capabilities/extensions (VCE) triple, selections and loops are regions with explicit merge and continue blocks, every op carries availability metadata, and the serializer writes the binary almost one instruction per op. Producers lower into it from higher dialects (scf, arith, math, memref, vector, gpu), and a front end that emits scf from source statements gets structured SPIR-V without ever building a CFG.
Design philosophy
The design document (docs/Dialects/SPIR-V.md) states the dialect's level precisely:
"The main objective of the SPIR-V dialect is to be a proper intermediate representation (IR) to facilitate compiler transformations. While we still aim to support serializing to and deserializing from the binary format for various good reasons, the binary format and its concerns play less a role in the design of the SPIR-V dialect: when there is a trade-off to be made between favoring IR and supporting binary format, we lean towards the former."
and, in its principles, "Stay as the same semantic level as the SPIR-V specification by having one-to-one mapping for most concepts and entities." The dialect is therefore not a shading language and not a higher abstraction: anything above SPIR-V (layout, resource binding, stages-as-functions) belongs to other dialects or the producer.
How it works
Structured control flow as regions
spirv.mlir.selection and spirv.mlir.loop (SPIRVControlFlowOps.td) replace OpSelectionMerge/OpLoopMerge with regions:
"Instead of having a
spirv.SelectionMergeop to directly model selection merge instruction for indicating the merge target, we use regions to delimit the boundary of the selection: the merge target is the next op following thespirv.mlir.selectionop."
spirv.mlir.selection {
spirv.BranchConditional %cond, ^then, ^merge
^then:
spirv.Return // early return: legal, Return is InFunctionScope
^merge:
spirv.mlir.merge
}The serializer (SerializeOps.cpp) emits the merge instructions from the region boundaries; the deserializer (Deserializer.cpp) has its own ControlFlowStructurizer to rebuild regions from a binary's merge annotations. Construct nesting is a property of the IR's shape, so a well-formed spirv.module cannot express the "construct escapes its parent" failure that the LLVM backend's heuristic produces.
Capabilities derived from availability
Each op, type and enum case carries min_version/max_version, extension and capability requirements (SPIRVAvailability.td, generated into QueryMinVersionInterface, QueryCapabilityInterface, …). The spirv-update-vce pass (Passes.td, UpdateVCEPass.cpp):
"For each spirv.module op, this pass requires a
spirv.target_envattribute on it or an enclosing module-like op to drive the deduction. …spirv.target_envgives the hard limit as for what the target environment can support; this pass deduces what are actually needed for a specific spirv.module op."
This inverts the LLVM backend's model: a target is a declared environment (version, capabilities, extensions, client API, device limits), and the module's requirements are the minimal set its ops need within it. A target that cannot provide an op is a conversion failure for that op, with a location, not a whole-module abort.
Conversions into spirv
| Pass / pattern set | What it does |
|---|---|
SCFToSPIRV (SCFToSPIRV.cpp) | scf.for, scf.if, scf.index_switch, scf.while → spirv.mlir.loop/selection; "we explicitly create a selection header block … and a merge block" |
ControlFlowToSPIRV (ControlFlowToSPIRV.cpp) | cf.cond_br → plain spirv.BranchConditional, no merge — valid only for Kernel |
lift-cf-to-scf (CFGToSCF.cpp) | Lifts any single-entry CFG, irreducible ones included, to scf.while + scf.index_switch (Bahmann et al. 2015, Perfect Reconstructability of Control Flow) |
ArithToSPIRV, MathToSPIRV, VectorToSPIRV, MemRefToSPIRV, FuncToSPIRV, GPUToSPIRV | Scalar/vector arithmetic, GLSL.std.450/OpenCL.std math, memory, functions, kernel launch ABI |
spirv-lower-abi-attrs (LowerABIAttributesPass.cpp) | Turns ABI attributes into interface variables and LocalSize — compute only |
convert-spirv-to-llvm (SPIRVToLLVM.cpp) | SPIR-V → LLVM dialect, per invocation; group ops become OpenCL builtin calls (_Z27__spirv_GroupNonUniformIAddii) |
Execution model and stages
The dialect knows every stage: SPIRV_ExecutionModelAttr (SPIRVBase.td) lists Vertex, TessellationControl, TessellationEvaluation, Geometry, Fragment, GLCompute, Kernel, the six …KHR ray-tracing stages and TaskEXT/MeshEXT; spirv.EntryPoint and spirv.ExecutionMode (SPIRVStructureOps.td) take any of them and every execution mode (OriginUpperLeft, EarlyFragmentTests, DepthReplacing, primitive and output-vertex modes, …). Geometry primitives (spirv.EmitVertex, spirv.EndPrimitive, SPIRVPrimitiveOps.td) and SPV_EXT_mesh_shader ops (SPIRVMeshOps.td) exist.
The conversion layer is compute-only. spirv::getExecutionModel (TargetAndABI.cpp) maps a Shader capability to GLCompute and nothing else, and the ABI pass emits only LocalSize. A graphics producer builds Input/Output spirv.GlobalVariables, spirv.EntryPoint and spirv.ExecutionMode itself — exactly the work ldc-vulkan already does in LLVM IR attributes and metadata.
Type system and generic programming
The type system is SPIR-V's: scalars, vector, matrix (with MatrixTimesVector, Transpose, … in SPIRVMatrixOps.td — which the LLVM backend never emits), arrays with stride, runtime arrays, structs with member offsets and decorations, typed !spirv.ptr with a storage class, images, samplers, sampled images, cooperative matrices. Integers carry signedness in the type, so the "every int is uint" problem of the LLVM backend does not arise. There are no generics; MLIR's genericity lives in the producer dialects (vector of any width before VectorToSPIRV legalises to four components).
Resources, interfaces and memory layout
Descriptor bindings are spirv.GlobalVariables with bind(set, binding); push constants, storage/uniform buffers and PhysicalStorageBuffer pointers are storage classes on !spirv.ptr. Layout is explicit in the type (Offset, ArrayStride), so a producer states std140/std430/scalar offsets rather than inheriting a DataLayout's. The decorate-spirv-composite-type-layout pass (Passes.td, Utils/LayoutUtils.cpp) attaches layout to composites in StorageBuffer, PhysicalStorageBuffer, Uniform and PushConstant — "Right now this pass only supports Vulkan layout rules." A separate spirv-webgpu-prepare pass expands ops WebGPU cannot take.
The serializer's decoration support is the binding constraint for fragment interfaces (Serializer.cpp): Binding, DescriptorSet, Location, Index, Offset, XfbBuffer/XfbStride, BuiltIn, Flat, NoPerspective, NonReadable/NonWritable, RelaxedPrecision, Restrict, Block, Invariant, Patch, Coherent, Volatile and a few others are handled; any other decoration reaches the "unhandled decoration " error. Centroid, Sample and Component are not in the list, so centroid or per-sample interpolation and packed varyings fail to serialize.
Built-in library and intrinsics
About 405 SPIRV_*Op definitions span the IR files at this revision: arithmetic, bit, logical, composite, atomics, barriers, GLSL.std.450 (SPIRVGLOps.td), OpenCL.std, group/non-uniform ops (ballot, elect, shuffle, arithmetic, QuadSwap), integer dot product, cooperative matrix and Arm graph/TOSA extensions. Image ops are partial (SPIRVImageOps.td): SampledImage, ImageDrefGather, ImageQuerySize, ImageRead, ImageWrite, Image, ImageSampleExplicitLod, ImageSampleImplicitLod, ImageSampleProjDrefImplicitLod, ImageFetch.
Missing at 27ba493781, each of which a fragment shader uses:
- Derivatives — no
OpDPdx/OpDPdy/OpFwidthor Fine/Coarse ops anywhere undermlir/includeormlir/lib. - Discard —
spirv.Killexists, described as "Deprecated (use OpTerminateInvocation or OpDemoteToHelperInvocation)", but neither replacement is an op;DemoteToHelperInvocationexists only as a capability enum case. - Sampling — no
ImageGather, no Dref implicit/explicit-LOD sampling, no non-Dref projective sampling, noImageQueryLod/QuerySizeLod/QueryLevels. - Subgroups / ray tracing — no
GroupNonUniformQuadBroadcast; noOpTraceRayKHR, ray query or hit-reporting ops, although the stages exist.
Control flow, memory model and restrictions
Structured control flow is enforced by construction (see How it works). The cost moves to the producer: func.return is HasParent<"FuncOp"> (FuncOps.td) and scf has no break/continue, so a front end lowering D's early return, break and continue into scf must turn them into flags or yielded values, or emit cf locally and run lift-cf-to-scf. Either way the lowering defines where invocations reconverge — a choice the LLVM path leaves to SimplifyCFG and the structurizer, and one that matters to derivatives and subgroup operations. ControlFlowToSPIRV is not an alternative for shaders: unstructured branches are only valid in Kernel modules.
The memory model, addressing model and pointer storage classes are explicit on spirv.module and !spirv.ptr; spirv-update-vce adds VulkanMemoryModel or PhysicalStorageBufferAddresses when ops need them. Validation is MLIR's op verifiers plus availability; it is not spirv-val, so Vulkan-environment rules (non-opaque UniformConstant, recursion) still need the external validator.
Compilation pipeline and targets
producer dialects (scf, arith, math, vector, memref, gpu)
→ *-to-spirv conversions (SPIRVConversionTarget built from spirv.target_env)
→ spirv.module → spirv-update-vce → canonicalisation, spirv-unify-aliased-resource, …
→ mlir-translate --serialize-spirv → SPIR-V binaryOutput is SPIR-V only. GLSL, MSL, HLSL and WGSL still need SPIRV-Cross, naga or Tint; MLIR has no DXIL path (no dxil or directx under mlir/include or mlir/lib), so DirectX would go MLIR → LLVM dialect → LLVM IR → LLVM's DirectX backend, the LLVM-IR route again (Clang HLSL).
The D/LDC MLIR effort
| When | What |
|---|---|
| 2019–2020 | SAoC 2019, Roberto Rosmaninho: a custom "D" dialect and MLIRGen in an LDC fork (D-Dialect-for-MLIR, 2019-08-26 to 2020-01-23; Robertorosmaninho/ldc). Only scaffolding was upstreamed — FindMLIR and -output-mlir (#3313), merged 2020-05-22. The emitted samples were flat std.cond_br CFGs, i.e. unstructured. |
| 2022-03-31 | LDC acc306a4 "Hack: Disable MLIR support with LLVM 14+ for now" (Martin Kinkelin); LDC upstream ac0e420a still gates MLIR on LLVM_VERSION_MAJOR LESS 14 in CMakeLists.txt. |
| 2026-09 | SAoC 2026 "MLIR Support for LDC", Asadbek Sindarov, mentor Nicholas Wilson (dcompute's author). Milestones (saoc-mislestones.md): M1 MLIR build + LDC_inline_mlir; M2 an AST visitor emitting func/arith for the BetterC subset; M3 if/else → scf.if, loops → scf.for/scf.while, then scf→cf→llvm; stretch: DCompute kernels. |
| 2026-10-16 | #5300 merged ("Revive MLIR support in the build"): LDC_WITH_MLIR AUTO/ON/OFF, find_package(MLIR CONFIG), OwningOpRef<ModuleOp>; "there's still no MLIR codegen, so -output-mlir writes an empty module". |
| 2026-10-16 | #5307 opened: __mlir!(code, R, P...) in ldc.llvmasm, wrapped in func.func, lowered scf → cf, arith/cf/func → llvm, linked in alwaysinline; dialects func, arith, cf, scf, llvm. |
The proposal (saoc-proposal.md) is explicit about direction: "I intend to keep extending MLIR support in LDC, including a DCompute target, beyond SAOC", names memref as "a good fit for DCompute's global/local/private address spaces", and puts a D dialect out of scope.
IMPORTANT
As planned, M3 lowers scf to cf and on to LLVM IR — which discards the structure before any SPIR-V back end sees it. For shaders, the useful artifact is the D-statement → scf visitor itself, with an scf → spirv exit kept open alongside scf → cf → llvm.
Host integration and CPU execution
MLIR offers no host runtime for SPIR-V at this revision (mlir/tools/ has mlir-runner; the former Vulkan and SPIR-V CPU runners are gone). convert-spirv-to-llvm gives a per-invocation CPU lowering, not SPMD: group operations become calls to OpenCL builtins, and nothing models quads, helper invocations or derivatives. The vector dialect has masking, shuffles and reductions, but no pass takes a scalar per-invocation function and lanes it out. Structured scf input is nevertheless the natural substrate for an ISPC-style masking pass (scf.if → both arms under a mask; scf.while → loop while any(mask)), because it is already the linearised form whole-function vectorisers such as ISPC have to reconstruct.
Lessons for sparkles:shaders
- Adopt: declared target environments. Model a target as a D value — SPIR-V version, capabilities, extensions, client API — and derive a module's requirements from what the vocabulary used, as
spirv-update-vcedoes, instead of a backend's fixed whitelist. Each vocabulary item then carries its availability (a UDA such as@requires(Capability.DerivativeControl)). - Match: structure from statements. If
sparkles:shadersever owns its SPIR-V emission, emit structure from D'sif/while/switchdirectly; earlyreturn,breakandcontinuelower to explicit flags whose placement defines reconvergence, and the CPU simulator must use the same lowering. - Adopt: one structured IR for GPU and CPU. The scalar CPU reference and a later SPMD-on-SIMD simulator both want structured regions; MLIR's
scfis the evidence that the same form serves SPIR-V serialization and lane masking. - Avoid: migrating now. Derivatives, terminate/demote, gather and Dref sampling and the
Centroid/Sample/Componentdecorations are missing; a fragment shader cannot ship without them, and LDC builds with MLIR do not exist outside a source build yet. - Adopt: contribute requirements to SAoC M3. Offer the shader control-flow corpus (early return in nested
if,else if (a && b),break/continuein nested loops,switch) as M3 acceptance tests with a--convert-scf-to-spirv+spirv-valcheck, and ask that thescfstage stay exposed rather than lowered straight tocf. - Match: explicit layout in types. The dialect has no DataLayout; offsets and strides are in the types.
sparkles:shadersshould compute them in D the same way, whichever back end serializes them.
Strengths
- Structured control flow by construction; early return inside a selection is legal, and construct nesting cannot be violated.
- Capability, extension and version requirements are derived per op against a declared target environment.
- Full stage and execution-mode enumeration, matrix types, signed integer types, explicit layout.
lift-cf-to-scfis a correct-by-construction structurizer for arbitrary (even irreducible) CFGs.- Upstream is receptive to graphics additions (geometry and mesh ops landed in 2025).
Weaknesses
- Graphics op coverage is thin: no derivatives, no terminate/demote, partial image sampling, no ray-tracing instructions.
- The serializer rejects common interpolation decorations (
Centroid,Sample,Component). - All conversion layers above the dialect target compute only.
- SPIR-V binary is the only output; no DXIL, no shading-language emitters.
- No visible production graphics user; LDC's MLIR support is days old and BetterC-scoped.
Key design decisions and trade-offs
| Decision | Rationale | Trade-off |
|---|---|---|
| One-to-one with the SPIR-V spec | Straightforward (de)serialization; no invented semantics | Every graphics instruction must be added op by op; no higher-level shader abstraction |
| Merge/continue as regions, not instructions | Nesting is structural; region-based transforms are easy | Producers must lower unstructured exits themselves; deserializing needs its own structurizer |
Availability on every op + spirv-update-vce | Minimal requirements per module; precise errors per op | Every op definition carries availability metadata to maintain |
Target environment as an attribute (spirv.target_env) | Conversions can legalise per device/API | The producer must know and state the target; there is no default "Vulkan" profile to fall into |
cf → spirv without merges | Kernel modules need no structure | Unusable for shaders; a shader producer must go through scf or lift-cf-to-scf |
Compute-first conversions (gpu, ABI lowering) | IREE and ML workloads drove the work | Graphics producers write entry points, interfaces and execution modes by hand |
Sources
- llvm/llvm-project at
27ba493781—mlir/ mlir/docs/Dialects/SPIR-V.md— design document · published versionSPIRVBase.td— execution models, modes, capabilities ·SPIRVControlFlowOps.td·SPIRVStructureOps.td·SPIRVImageOps.td·SPIRVMatrixOps.td·SPIRVPrimitiveOps.td·SPIRVMeshOps.tdPasses.td·UpdateVCEPass.cpp·TargetAndABI.cpp·LowerABIAttributesPass.cppSCFToSPIRV.cpp·ControlFlowToSPIRV.cpp·CFGToSCF.cpp·SPIRVToLLVM.cppSerializer.cpp·SerializeOps.cpp·Deserializer.cpp·FuncOps.td- ldc-developers/ldc#5300 — Revive MLIR support in the build · #5307 —
LDC_inline_mlir· #3313 —-output-mlir· LDCCMakeLists.txtatac0e420a - asindarov/mlir-support-for-D — SAoC 2026 proposal and milestones
- Robertorosmaninho/D-Dialect-for-MLIR (SAoC 2019) · Robertorosmaninho/ldc
- Related: LLVM SPIR-V backend · Clang HLSL · SPIRV-Cross · naga · Tint · dcompute · Vcc/Shady · ISPC · Concepts · Comparison · Index ·
sparkles:shadersSPEC