shader#
SPIR-V: module builder, disassembler, validator, std140 / std430 layouts, the benchmark shaders -- crate root lib/shader/lib.rs
shader -- SPIR-V for JFLib's GPU code: a module builder, a disassembler, a structural
validator, std140 / std430 layouts and the shaders of the GPU benchmark scene. The back
end of the WGSL compiler (step G2), usable directly from Rust. No GPU needed: everything
here produces or reads words (docs/SHADER.md).
Module::new(minor) a SPIR-V 1.minor module (1.3: Vulkan 1.1 "Basis", 1.6: Vulkan
1.3 "Voll"); types, constants, globals, functions, structured
control flow, instructions; finish() -> Vec<u32>
layout Rule::Std140 / Std430: align, size, stride, matrix_stride, offsets
dis::disassemble(words) text close to spirv-dis
val::validate(words) the structural checks (val module comment lists the rules)
bench the benchmark shaders (move, cull, cull_reset, vs_instanced,
vs_single, fs_lambert), their data contract and CPU references
reflect entry points, specialization constants and their values once a
pipeline sets some (OpSpecConstantOp evaluated), workgroup sizes
samples small shaders for the tests: specialization constants, textures
spv opcodes, enums and their names; parse: words -> instructions
msl::translate(words) the module in the Metal Shading Language (lib/gpu on Apple)
to_bytes / from_bytes words <-> the bytes of a .spv file
shader crate root#
/// the SPIR-V minor version of the feature level "Basis" (Vulkan 1.1: SPIR-V 1.3)
BASIS: u32 = 3
/// the SPIR-V minor version of the feature level "Voll" (Vulkan 1.3: SPIR-V 1.6)
VOLL: u32 = 6
shader/bench.rs#
Source: lib/shader/bench.rs
bench -- the GPU benchmark scene: 100 000 to 1 000 000 instanced cubes, moved, culled and
drawn on the GPU (docs/SHADER.md, "Benchmark-Vertrag"). The shaders as SPIR-V words for
SPIR-V 1.3 (Basis) or 1.6 (Voll), their data contract and CPU references.
Shader::{Move, Cull, CullReset, VsInstanced, VsSingle, FsLambert}.build(minor)
move_spv / cull_spv / cull_reset_spv / vs_instanced_spv / vs_single_spv / fs_lambert_spv
Object (48 bytes), Camera (176), DrawCmd (20), CubeVertex (32), Push (20): the buffer
records with bytes() / from_bytes(); offsets in the *_OFF constants
cube_vertices() (24) / cube_indices() (36, u16, counter-clockwise from outside)
Camera::look_at / from_view_proj: lib/gpu's clip space (NDC y up, depth 0..1), planes
hash, unit, floor, sincos_turns, move_ref, move_all, visible, cull_ref: the CPU references
Descriptor set 0 (one layout for every pipeline, stages COMPUTE | VERTEX | FRAGMENT):
binding 0 B_CAMERA uniform buffer Camera (std140) cull, vs_*, fs_lambert
binding 1 B_OBJECTS storage buffer Object[count] (std430) move (writes), cull, vs_*
binding 2 B_VISIBLE storage buffer uint[count] cull (writes), vs_instanced
binding 3 B_DRAW storage buffer DrawCmd, also the INDIRECT buffer cull_reset, cull
binding 4 B_CUBE storage buffer CubeVertex[24] vs_*
Push constants (all stages, offset 0, 20 bytes): Push { time, count, seed, extent,
object_index }. Workgroups: move and cull 256 x 1 x 1 (dispatch ceil(count / 256)),
cull_reset 1 x 1 x 1. Every shader: entry point "main", capability Shader only.
move and cull are exact: only add, sub, mul, floor, conversions of integers below 2^24 and
integer ops, every float result decorated NoContraction (no fused multiply-add), in the
order of the CPU references. Vulkan rounds add / sub / mul correctly, so the GPU results
equal move_ref / cull_ref bit for bit (denormals may flush to zero; the visible list comes
in atomic order: compare it sorted).
SET: u32 = 0
B_CAMERA: u32 = 0
B_OBJECTS: u32 = 1
B_VISIBLE: u32 = 2
B_DRAW: u32 = 3
B_CUBE: u32 = 4
WG_MOVE: u32 = 256
WG_CULL: u32 = 256
CUBE_VERTICES: u32 = 24
CUBE_INDICES: u32 = 36
// Object, std430, stride 48: vec3 pos, float scale, vec4 rot (quaternion x y z w), vec3
// color, float radius (bounding sphere)
OBJECT_SIZE: u32 = 48
OBJECT_OFF: [u32; 5] = [0, 12, 16, 32, 44]
// Camera, std140: mat4 view_proj (column-major, MatrixStride 16), vec4 planes[6] (stride 16),
// vec3 light_dir (towards the light, unit length), float ambient
CAMERA_SIZE: u32 = 176
CAMERA_OFF: [u32; 4] = [0, 64, 160, 172]
// DrawCmd = VkDrawIndexedIndirectCommand, std430
DRAW_SIZE: u32 = 20
DRAW_OFF: [u32; 5] = [0, 4, 8, 12, 16]
// CubeVertex, std430, stride 32: vec4 pos (w = 1), vec4 normal (w = 0)
CUBE_VERTEX_SIZE: u32 = 32
// Push, std430: float time, uint count, uint seed, float extent, uint object_index
PUSH_SIZE: u32 = 20
PUSH_OFF: [u32; 5] = [0, 4, 8, 12, 16]
struct Objectpos: [f32; 3]scale: f32rot: [f32; 4]color: [f32; 3]radius: f32
impl Object
fn bytes(&self) -> Vec<u8>fn from_bytes(b: &[u8]) -> Objectone record from 48 bytesfn objects_bytes(objs: &[Object]) -> Vec<u8>the bytes of an Object bufferfn objects_from_bytes(b: &[u8]) -> Vec<Object>an Object buffer read back (len / 48 records)struct Cameraview_proj: [f32; 16]-- clip = view_proj * vec4(world, 1), column-major (view_proj[col * 4 + row])planes: [[f32; 4]; 6]-- (n, d) with |n| = 1: a point p is inside when dot(n, p) + d >= 0light_dir: [f32; 3]ambient: f32
struct DrawCmdindex_count: u32instance_count: u32first_index: u32vertex_offset: i32first_instance: u32
impl DrawCmd
fn reset() -> DrawCmdthe command cull_reset writes: 36 indices, no instances yetfn bytes(&self) -> Vec<u8>fn from_bytes(b: &[u8]) -> DrawCmdstruct Pushtime: f32-- seconds since the startcount: u32seed: u32extent: f32-- the scene's radius: orbits between 0.1 and 1.0 times extentobject_index: u32-- vs_single: the object drawn
impl Push
fn bytes(&self) -> Vec<u8>fn extent_for(count: u32) -> f32a good extent for count cubes (about 3 world units between neighbours)struct CubeVertexpos: [f32; 4]normal: [f32; 4]
fn cube_vertices() -> Vec<CubeVertex>the 24 vertices of the cube -1 ..= 1 (4 per face, normals per face)fn cube_indices() -> Vec<u16>the 36 indices (two triangles per face)fn cube_bytes() -> Vec<u8>
impl Camera
fn look_at(eye: [f32; 3], target: [f32; 3], fovy: f32, aspect: f32, near: f32, far: f32) -> Cameraa right-handed camera at eye looking at target (+y up), vertical field of view fovy (radians), in lib/gpu's clip space (as WebGPU and Metal): NDC y up (world up is up on screen; the Vulkan backend flips the viewport, the matrix flips nothing), depth 0 (near) to 1 (far). Faces counter-clockwise from outside stay counter-clockwise in NDC: front faces with lib/gpu's default (front_cw false), cull Back.fn from_view_proj(vp: [f32; 16]) -> Cameraplanes of a view-projection matrix (-w <= x, y <= w, 0 <= z <= w: left, right, bottom, top, near, far), normalised; the light comes from above (0.3, 0.8, 0.5), ambient 0.25fn bytes(&self) -> Vec<u8>the 176 bytes of the uniform buffer (std140)fn hash(x: u32) -> u32PCG hash (Jarkko & Olano, "Hash Functions for GPU Rendering")fn unit(h: u32) -> f32the top 24 bits as a float in [0, 1) (exact)fn floor(x: f32) -> f32floor as GLSL.std.450 Floor computes it (exact)fn sincos_turns(u: f32) -> (f32, f32)(sin, cos) of 2 pi u: u reduced to [-0.5, 0.5], sin and cos of pi r by Taylor polynomials, then the double-angle formulasfn move_ref(i: u32, p: &Push) -> Objectwhat move writes for object ifn move_all(p: &Push) -> Vec<Object>move for objects 0 .. p.countfn visible(o: &Object, cam: &Camera) -> boolcull's test: the bounding sphere is not completely outside one of the planesfn cull_ref(objs: &[Object], cam: &Camera) -> Vec<u32>the indices cull appends, ascending (the GPU's list is in atomic order: sort it first)enum Shaderthe six benchmark shadersMoveCullCullResetVsInstancedVsSingleFsLambert
impl Shader
const ALL: [Shader; 6] = [Shader::Move, Shader::Cull, Shader::CullReset, Shader::V ...fn name(self) -> &'static strfn model(self) -> Modelfn build(self, minor: u32) -> Vec<u32>the module for SPIR-V 1.minor (3 or 6)fn move_spv(minor: u32) -> Vec<u32>move: object gid = move_ref(gid, pc) for gid < pc.countfn cull_spv(minor: u32) -> Vec<u32>cull: for gid < pc.count, if visible(objects[gid], camera): visible[atomicAdd( draw.instance_count, 1)] = gidfn cull_reset_spv(minor: u32) -> Vec<u32>cull_reset: draw = DrawCmd::reset() (one invocation; or vkCmdFillBuffer instead)fn vs_instanced_spv(minor: u32) -> Vec<u32>fn vs_single_spv(minor: u32) -> Vec<u32>fn fs_lambert_spv(minor: u32) -> Vec<u32>fs_lambert: colour * (ambient + (1 - ambient) * max(dot(normalize(n), light), 0)), in: Location 0 normal, 1 colour (Flat); out: Location 0 vec4 (alpha 1)
shader/dis.rs#
Source: lib/shader/dis.rs
dis -- SPIR-V words as text in the style of spirv-dis (friendly names, the result column
at 15 characters)
disassemble(words) -> Result<String, String>
fmt_float(f32) -> String a float as spirv-dis prints it (%.9g, hex for inf / NaN)
Names follow spirv-dis' FriendlyNameMapper: OpName first, then generated names for types
(void, uint, v4float, mat4v4float, _arr_float_uint_4, _runtimearr_X, _ptr_Uniform_X,
_struct_N), constants (uint_4, int_n1, float_0_5, true) and built-ins (gl_Position,
gl_GlobalInvocationID ...); a taken name gets _0, _1 ...; everything else (specialization
constants too) is its number. OpSpecConstantOp prints its operation without "Op".
Opcodes shader does not know print as OpUnknown(N) with their words.
fn fmt_float(x: f32) -> Stringa 32-bit float as spirv-dis prints itfn disassemble(words: &[u32]) -> Result<String, String>the module as text
shader/layout.rs#
Source: lib/shader/layout.rs
layout -- std140 / std430 offsets, sizes and strides (Vulkan "Offset and Stride Assignment")
Rule::Std140 uniform buffers: the extended alignment (arrays, structs and matrices
rounded up to 16 bytes)
Rule::Std430 storage buffers and push constants: the base alignment
align / size / stride / matrix_stride / offsets(members) over any Types table (the
builder's Module, the validator's parsed module); matrices are column-major
Base alignment: a scalar of N bytes N; vec2 2N; vec3 and vec4 4N; an array that of its
element; a struct the largest of its members; a column-major matrix that of its column.
A struct's size is rounded up to its alignment, an array's stride is its element's size
rounded up to the array's alignment, a matrix is an array of its columns. Runtime arrays
have no size (the last member of a buffer block); bool, images and pointers have no layout.
enum RuleStd140Std430
fn align(t: &dyn Types, ty: u32, rule: Rule) -> Option<u32>the alignment of a type under rule (None: no layout)fn matrix_stride(t: &dyn Types, mat: u32, rule: Rule) -> Option<u32>the column stride of a column-major matrix typefn stride(t: &dyn Types, elem: u32, rule: Rule) -> Option<u32>the stride of an array of elemfn size(t: &dyn Types, ty: u32, rule: Rule) -> Option<u32>the size in bytes (None for runtime arrays and types without layout; a struct ending in a runtime array: the size without it)fn offsets(t: &dyn Types, members: &[u32], rule: Rule) -> Option<Vec<u32>>the offsets of struct members laid out one after another
shader/module.rs#
Source: lib/shader/module.rs
module -- the SPIR-V module builder: Module collects capabilities, types, constants,
globals and functions in their sections and finish() writes the words.
Module::new(minor) SPIR-V 1.minor (3: Vulkan 1.1 "Basis", 6: Vulkan 1.3 "Voll");
Shader capability, GLSL450 memory model
types ty_void/bool/int/u32/i32/float/f32/vec/mat/array/array_stride/runtime_array/
struct_/struct_layout/ptr/func/image/sampler/sampled_image; deduplicated except
structs and strided arrays (their decorations differ)
constants const_u32/i32/f32/bool/scalar/composite/null (deduplicated)
spec consts spec_u32/i32/f32/bool/scalar (SpecId), spec_composite, spec_op
(OpSpecConstantOp); workgroup sizes from them: local_size_id (LocalSizeId),
workgroup_size_builtin (the WorkgroupSize built-in), workgroup_size (the one
the level allows); ty_array_id (override-sized arrays)
globals global, input, output, builtin, buffer, push_constant, workgroup, resource;
local (Function storage, placed in the entry block)
functions begin_function -> (id, params), end_function, label, begin_block
control flow branch, branch_cond, selection_merge, loop_merge, switch, ret, ret_value,
unreachable, discard (OpKill / OpTerminateInvocation), demote, phi,
if_then, if_else, loop_ (structured helpers)
instructions arithmetic, comparisons, logic, select, conversions, access chains,
load / store, composites, shuffles, dot / matrix products, GLSL.std.450,
atomics, barriers, images, derivatives, calls; emit() for any opcode
finish() the words; entry point interfaces are computed here (1.3: the Input /
Output variables the call tree uses, 1.4+: every global it uses)
Ids are handed out in call order, so the same calls give the same words. Capabilities
and extensions an instruction or type needs are added on the way (Int64 for 64-bit
integers, DerivativeControl for Fine / Coarse derivatives ...). The builder does not check
types beyond what it needs to infer result types: val::validate does.
struct Id(pub u32)enum Tya SPIR-V typeVoidBoolInt { width: u32, signed: bool }Float { width: u32 }Vector { elem: Id, n: u32 }Matrix { col: Id, cols: u32 }Array { elem: Id, len: Id }-- len: the id of an integer constantRuntimeArray { elem: Id }Struct { members: Vec<Id> }Pointer { sc: u32, pointee: Id }Function { ret: Id, params: Vec<Id> }Image { sampled: Id, dim: u32, depth: u32, arrayed: u32, ms: u32, usage: u32, format: u32 }SamplerSampledImage { image: Id }
trait Typeswhat the layout helper and the validator need to know about idsfn ty(&self, id: u32) -> Option<&Ty>fn const_u32(&self, id: u32) -> Option<u32>the value of a 32-bit integer constant
struct Loopthe labels of the loop being built (loop_): break = branch(merge), continue = branch(cont)merge: Idcont: Id
struct Modulegenerator: u32-- the generator word of the header (0: unregistered tool)no_contraction: bool-- decorate every float add, sub, mul, div, rem and product with NoContraction (exact results: no fused multiply-add)
impl Module
fn new(minor: u32) -> Modulea module for SPIR-V 1.minor (3 ..= 6) with the Shader capability and the logical GLSL450 memory modelfn minor(&self) -> u32fn id(&mut self) -> Ida fresh id (for forward references: labels, functions called before they are built)fn capability(&mut self, c: Cap)fn extension(&mut self, name: &str)fn glsl_set(&mut self) -> Idthe GLSL.std.450 import (created on first use)fn type_of(&self, v: Id) -> Idthe type of a value idfn ty(&self, t: Id) -> &Tythe description of a type idfn name(&mut self, id: Id, s: &str)fn member_name(&mut self, ty: Id, member: u32, s: &str)fn source(&mut self, lang: spv::Lang, version: u32)OpSource (e.g. Lang::WGSL, version 100); no text is embeddedfn decorate(&mut self, target: Id, d: Dec, args: &[u32])OpDecorate (the same decoration twice is written once)fn member_decorate(&mut self, ty: Id, member: u32, d: Dec, args: &[u32])fn ty_void(&mut self) -> Idfn ty_bool(&mut self) -> Idfn ty_int(&mut self, width: u32, signed: bool) -> Idan integer type; 8, 16 and 64 bits add Int8 / Int16 / Int64fn ty_u32(&mut self) -> Idfn ty_i32(&mut self) -> Idfn ty_float(&mut self, width: u32) -> Ida float type; 16 and 64 bits add Float16 / Float64fn ty_f32(&mut self) -> Idfn ty_vec(&mut self, elem: Id, n: u32) -> Idfn ty_mat(&mut self, col: Id, cols: u32) -> Ida matrix ofcolscolumns of the vector typecolfn ty_array(&mut self, elem: Id, len: u32) -> Idan array of len elements without ArrayStride (Function, Private, Workgroup storage)fn ty_array_id(&mut self, elem: Id, len: Id) -> Idan array whose length is the id of an integer constant or specialization constant (WGSL: a workgroup array sized by an override expression)fn ty_array_stride(&mut self, elem: Id, len: u32, stride: u32) -> Idan array decorated with ArrayStride (buffers); deduplicated by element, length, stridefn ty_array_layout(&mut self, elem: Id, len: u32, rule: Rule) -> Idan array laid out byrule(ArrayStride from the layout helper)fn ty_runtime_array(&mut self, elem: Id, stride: Option<u32>) -> Ida runtime array; stride Some(s): decorated with ArrayStride s (buffers)fn ty_struct(&mut self, members: &[Id]) -> Ida struct (never deduplicated: two structs may differ in their decorations)fn ty_struct_layout(&mut self, name: &str, members: &[(&str, Id)], rule: Rule) -> Ida named struct laid out byrule: OpName / OpMemberName, Offset on every member, ColMajor and MatrixStride on matrix (and matrix array) members. Array members must be built with ty_array_layout / ty_runtime_array(.., Some(stride)) of the same rule.fn ty_ptr(&mut self, sc: Sc, pointee: Id) -> Idfn ty_func(&mut self, ret: Id, params: &[Id]) -> Idfn ty_image(&mut self, sampled: Id, dim: Dim, depth: u32, arrayed: u32, ms: u32, usage: u32, format: Fmt) -> IdOpTypeImage; usage 1: sampled, 2: storage image (format needed unless the *WithoutFormat capabilities are declared)fn ty_sampler(&mut self) -> Idfn ty_sampled_image(&mut self, image: Id) -> Idfn bool_like(&mut self, t: Id) -> Idbool (or a bool vector of the same length) for a scalar / vector typefn scalar_of(&self, t: Id) -> Idthe component type of a vector (the type itself for a scalar)fn const_scalar(&mut self, ty: Id, words: &[u32]) -> IdOpConstant of an int or float type with its value words (low word first)fn const_u32(&mut self, v: u32) -> Idfn const_i32(&mut self, v: i32) -> Idfn const_f32(&mut self, v: f32) -> Idfn const_bool(&mut self, v: bool) -> Idfn const_composite(&mut self, ty: Id, parts: &[Id]) -> Idfn const_vec_f32(&mut self, v: &[f32]) -> Ida float vector constantfn const_null(&mut self, ty: Id) -> Idfn is_spec(&self, v: Id) -> boolwhether v is a specialization constant (OpSpecConstant*, composites of them, results of OpSpecConstantOp)fn spec_scalar(&mut self, ty: Id, spec_id: u32, words: &[u32]) -> IdOpSpecConstant of an int or float type with its default value words (low word first), decorated SpecId spec_id (the pipeline constant's id); never deduplicatedfn spec_u32(&mut self, spec_id: u32, default: u32) -> Idfn spec_i32(&mut self, spec_id: u32, default: i32) -> Idfn spec_f32(&mut self, spec_id: u32, default: f32) -> Idfn spec_bool(&mut self, spec_id: u32, default: bool) -> IdOpSpecConstantTrue / OpSpecConstantFalse decorated SpecId spec_idfn spec_composite(&mut self, ty: Id, parts: &[Id]) -> IdOpSpecConstantComposite of constants and specialization constants (deduplicated)fn spec_op(&mut self, ty: Id, opc: u16, ids: &[Id], literals: &[u32]) -> IdOpSpecConstantOp: the operation opc on constant ids, then its literals (the indices of CompositeExtract / CompositeInsert, the components of VectorShuffle). SPIR-V allows for Shader: SConvert, UConvert (1.4+), FConvert, QuantizeToF16, SNegate, Not, IAdd, ISub, IMul, UDiv, SDiv, UMod, SRem, SMod, the shifts, BitwiseOr / Xor / And, VectorShuffle, CompositeExtract / Insert, LogicalOr / And / Not / Equal / NotEqual, Select, IEqual, INotEqual and the integer comparisons (val checks it); no float arithmetic.fn global(&mut self, sc: Sc, pointee: Id, init: Option<Id>) -> Ida global OpVariable ofpointeein storage class scfn input(&mut self, ty: Id, location: u32) -> Idfn output(&mut self, ty: Id, location: u32) -> Idfn builtin(&mut self, sc: Sc, ty: Id, b: Bi) -> Ida built-in Input or Output variable; adds the capability some built-ins needfn buffer(&mut self, sc: Sc, block: Id, set: u32, binding: u32) -> Ida uniform (Sc::Uniform) or storage (Sc::StorageBuffer) buffer of a laid-out struct: Block on the struct, DescriptorSet and Binding on the variablefn push_constant(&mut self, block: Id) -> Idthe push-constant block (a struct laid out by Rule::Std430)fn workgroup(&mut self, ty: Id) -> Idfn resource(&mut self, ty: Id, set: u32, binding: u32) -> Idan image, sampler or sampled image (UniformConstant) at set / binding; a runtime array of them (a Bindless table) adds RuntimeDescriptorArray (before 1.5 with SPV_EXT_descriptor_indexing)fn entry_point(&mut self, model: Model, func: Id, name: &str)an entry point; its interface is filled in by finish()fn exec_mode(&mut self, func: Id, mode: Mode, args: &[u32])fn exec_mode_id(&mut self, func: Id, mode: Mode, ids: &[Id])OpExecutionModeId (SPIR-V 1.2+): a mode whose operands are constant ids (LocalSizeId)fn local_size_id(&mut self, func: Id, size: [Id; 3])LocalSizeId x y z: the workgroup size of a GLCompute entry point from 32-bit integer constants or specialization constants. Vulkan needs maintenance4 for it (core and required in Vulkan 1.3, so always there at the level Voll).fn workgroup_size_builtin(&mut self, size: [Id; 3]) -> Idthe WorkgroupSize built-in: a uvec3 composite of size (OpSpecConstantComposite when a part is a specialization constant) decorated BuiltIn WorkgroupSize. It sets the workgroup size of every GLCompute entry point of the module and wins over LocalSize.fn workgroup_size(&mut self, func: Id, size: [Id; 3])a workgroup size of (specialization) constants the way the level allows: LocalSizeId from SPIR-V 1.6 (Voll, Vulkan 1.3), else the WorkgroupSize built-in (then for every compute entry point of the module: one module per entry point, as Basis needs it)fn begin_function(&mut self, ret: Id, params: &[Id]) -> (Id, Vec<Id>)start a function (and its entry block) -> (function id, parameter ids)fn begin_function_id(&mut self, id: Id, ret: Id, params: &[Id]) -> (Id, Vec<Id>)begin_function with an id from id() (a function called before it is built)fn end_function(&mut self)fn label(&mut self) -> Ida new label id (the block starts with begin_block)fn begin_block(&mut self, l: Id)fn block_open(&self) -> boolwhether the current block still needs a terminatorfn local(&mut self, ty: Id, init: Option<Id>) -> Ida Function-storage variable (placed at the start of the entry block)fn emit(&mut self, opc: u16, ty: Option<Id>, args: &[u32]) -> Idany instruction in the current block: ty for opcodes with a result type; the result id is allocated when the opcode has one (Id(0) otherwise)fn branch(&mut self, target: Id)fn branch_cond(&mut self, c: Id, t: Id, f: Id)fn selection_merge(&mut self, merge: Id, ctl: u32)OpSelectionMerge (ctl: spv::SEL_CTL bits, 0 = None)fn loop_merge(&mut self, merge: Id, cont: Id, ctl: u32)OpLoopMerge (ctl: spv::LOOP_CTL bits without arguments, 0 = None)fn switch(&mut self, sel: Id, default: Id, cases: &[(u32, Id)])OpSwitch on a 32-bit selector (the caller writes the OpSelectionMerge first)fn ret(&mut self)fn ret_value(&mut self, v: Id)fn unreachable(&mut self)fn discard(&mut self)discard the fragment: OpKill before SPIR-V 1.6, OpTerminateInvocation from 1.6fn demote(&mut self)make the invocation a helper (not a terminator); before 1.6 through SPV_EXT_demote_to_helper_invocationfn phi(&mut self, ty: Id, pairs: &[(Id, Id)]) -> IdOpPhi of (value, predecessor label) pairsfn if_then(&mut self, c: Id, then: impl FnOnce(&mut Module))if (c) { then }: a selection constructfn if_else(&mut self, c: Id, then: impl FnOnce(&mut Module), els: impl FnOnce(&mut Module))if (c) { then } else { els }fn loop_(&mut self, cond: impl FnOnce(&mut Module) -> Id, body: impl FnOnce(&mut Module, Loop), cont: impl FnOnce(&mut Module))while (cond) { body; cont }: header (OpLoopMerge), condition block, body, continue block, merge block. body gets the labels for break / continue.fn binary(&mut self, opc: u16, a: Id, b: Id) -> Idfn unary(&mut self, opc: u16, a: Id) -> Idfn fadd(&mut self, a: Id, b: Id) -> Idfn fsub(&mut self, a: Id, b: Id) -> Idfn fmul(&mut self, a: Id, b: Id) -> Idfn fdiv(&mut self, a: Id, b: Id) -> Idfn fmod(&mut self, a: Id, b: Id) -> Idfn fneg(&mut self, a: Id) -> Idfn iadd(&mut self, a: Id, b: Id) -> Idfn isub(&mut self, a: Id, b: Id) -> Idfn imul(&mut self, a: Id, b: Id) -> Idfn udiv(&mut self, a: Id, b: Id) -> Idfn sdiv(&mut self, a: Id, b: Id) -> Idfn umod(&mut self, a: Id, b: Id) -> Idfn srem(&mut self, a: Id, b: Id) -> Idfn ineg(&mut self, a: Id) -> Idfn band(&mut self, a: Id, b: Id) -> Idfn bor(&mut self, a: Id, b: Id) -> Idfn bxor(&mut self, a: Id, b: Id) -> Idfn bnot(&mut self, a: Id) -> Idfn shl(&mut self, a: Id, n: Id) -> Idfn shr(&mut self, a: Id, n: Id) -> Idlogical shift rightfn sar(&mut self, a: Id, n: Id) -> Idarithmetic shift rightfn vec_scale(&mut self, v: Id, s: Id) -> Idvector * scalarfn mat_scale(&mut self, m: Id, s: Id) -> Idmatrix * scalarfn mat_vec(&mut self, m: Id, v: Id) -> Idmatrix * column vectorfn vec_mat(&mut self, v: Id, m: Id) -> Idrow vector * matrixfn mat_mat(&mut self, a: Id, b: Id) -> Idfn transpose(&mut self, m: Id) -> Idfn dot(&mut self, a: Id, b: Id) -> Idfn cmp(&mut self, opc: u16, a: Id, b: Id) -> Ida comparison: the result is bool or a bool vector of the operands' lengthfn feq(&mut self, a: Id, b: Id) -> Idfn fne(&mut self, a: Id, b: Id) -> Idfn flt(&mut self, a: Id, b: Id) -> Idfn fle(&mut self, a: Id, b: Id) -> Idfn fgt(&mut self, a: Id, b: Id) -> Idfn fge(&mut self, a: Id, b: Id) -> Idfn ieq(&mut self, a: Id, b: Id) -> Idfn ine(&mut self, a: Id, b: Id) -> Idfn ult(&mut self, a: Id, b: Id) -> Idfn ule(&mut self, a: Id, b: Id) -> Idfn uge(&mut self, a: Id, b: Id) -> Idfn slt(&mut self, a: Id, b: Id) -> Idfn sge(&mut self, a: Id, b: Id) -> Idfn land(&mut self, a: Id, b: Id) -> Idfn lor(&mut self, a: Id, b: Id) -> Idfn lnot(&mut self, a: Id) -> Idfn any(&mut self, v: Id) -> Idfn all(&mut self, v: Id) -> Idfn select(&mut self, c: Id, a: Id, b: Id) -> Idc ? a : bfn convert(&mut self, opc: u16, ty: Id, a: Id) -> Ida conversion opcode (ConvertFToU, ConvertSToF, Bitcast, FConvert ...) to type tyfn u2f(&mut self, ty: Id, a: Id) -> Idfn s2f(&mut self, ty: Id, a: Id) -> Idfn f2u(&mut self, ty: Id, a: Id) -> Idfn f2s(&mut self, ty: Id, a: Id) -> Idfn bitcast(&mut self, ty: Id, a: Id) -> Idfn access(&mut self, base: Id, idx: &[Id]) -> IdOpAccessChain: the result points at the member / element the indices select (struct indices must be constants)fn access_c(&mut self, base: Id, idx: &[u32]) -> Idaccess with constant u32 indicesfn load(&mut self, ptr: Id) -> Idfn store(&mut self, ptr: Id, v: Id)fn construct(&mut self, ty: Id, parts: &[Id]) -> Idfn extract(&mut self, v: Id, idx: &[u32]) -> Idfn insert(&mut self, v: Id, obj: Id, idx: &[u32]) -> Idfn shuffle(&mut self, a: Id, b: Id, comps: &[u32]) -> IdOpVectorShuffle: components of a (0..) and b (len(a)..)fn extract_dynamic(&mut self, v: Id, i: Id) -> Idfn ext(&mut self, ty: Id, inst: u32, args: &[Id]) -> Idan extended instruction of GLSL.std.450 (spv::glsl::*) with result type tyfn glsl(&mut self, inst: u32, args: &[Id]) -> Ida GLSL.std.450 instruction whose result type is its first argument's (Sin, Floor, FMin, FClamp, FMix, Normalize, Cross ...)fn length(&mut self, v: Id) -> IdGLSL.std.450 Length (the result is the component type)fn atomic(&mut self, opc: u16, ptr: Id, scope: u32, semantics: u32, value: Id) -> Idan atomic read-modify-write (AtomicIAdd, AtomicUMax, AtomicExchange ...) on a 32- or 64-bit integer: scope and semantics become constantsfn atomic_load(&mut self, ptr: Id, scope: u32, semantics: u32) -> Idfn atomic_store(&mut self, ptr: Id, scope: u32, semantics: u32, value: Id)fn atomic_cas(&mut self, ptr: Id, scope: u32, eq: u32, neq: u32, value: Id, comparator: Id) -> IdOpAtomicCompareExchange -> the original valuefn control_barrier(&mut self, exec: u32, mem: u32, semantics: u32)OpControlBarrier (barrier() of a workgroup: Workgroup, Workgroup, AcquireRelease | WorkgroupMemory)fn memory_barrier(&mut self, mem: u32, semantics: u32)fn sampled_image(&mut self, image: Id, sampler: Id) -> Idfn sample(&mut self, si: Id, coord: Id) -> Idtexture(si, coord): implicit LOD (fragment shaders)fn sample_lod(&mut self, si: Id, coord: Id, lod: Id) -> IdtextureLod(si, coord, lod)fn fetch(&mut self, image: Id, coord: Id, lod: Id) -> IdtexelFetch(image, coord, lod) on an OpImage / sampled-usage imagefn image_read(&mut self, image: Id, coord: Id) -> IdimageLoad of a storage imagefn image_write(&mut self, image: Id, coord: Id, texel: Id)imageStore of a storage imagefn image_size(&mut self, ty: Id, image: Id) -> IdOpImageQuerySize (storage images, no LOD) with result type tyfn image_size_lod(&mut self, ty: Id, image: Id, lod: Id) -> IdOpImageQuerySizeLod (sampled images)fn image_levels(&mut self, ty: Id, image: Id) -> IdOpImageQueryLevels (textureNumLevels of a sampled image) with result type tyfn sample_dref(&mut self, si: Id, coord: Id, dref: Id) -> IdtextureSampleCompare: OpImageSampleDrefImplicitLod (fragment shaders) -> the float resultfn sample_dref_lod(&mut self, si: Id, coord: Id, dref: Id, lod: Id) -> IdtextureSampleCompareLevel: OpImageSampleDrefExplicitLod with Lod lodfn nonuniform(&mut self, v: Id)decorate v NonUniform (a resource index or the image / sampler loaded with it) and declare ShaderNonUniform (before 1.5 with SPV_EXT_descriptor_indexing)fn deriv(&mut self, opc: u16, a: Id) -> IdDPdx, DPdy, Fwidth and their Fine / Coarse forms (those add DerivativeControl)fn dpdx(&mut self, a: Id) -> Idfn dpdy(&mut self, a: Id) -> Idfn fwidth(&mut self, a: Id) -> Idfn call(&mut self, func: Id, args: &[Id]) -> IdOpFunctionCall of a function built (or begun with begin_function_id) in this modulefn finish(&self) -> Vec<u32>the module's wordsfn to_bytes(words: &[u32]) -> Vec<u8>words as little-endian bytes (a .spv file)fn from_bytes(b: &[u8]) -> Option<Vec<u32>>a .spv file's bytes as words (None: not a multiple of 4 bytes or no SPIR-V magic; a big-endian file is swapped)
shader/msl.rs#
Source: lib/shader/msl.rs
msl -- SPIR-V to the Metal Shading Language (AP6 in docs/APPLE.md): the Metal backend of
lib/gpu translates every module with it, so a module from lib/wgsl or from this crate's
builder runs on Metal as on Vulkan. It reads the SPIR-V those two write: logical
addressing, structured control flow, the opcodes of spv::OPS and GLSL.std.450.
translate(words, &Options) -> Result<Msl, String> MSL source text and, per entry point,
its function name, workgroup size, resource slots, push constants and buffer sizes
Slots (lib/gpu binds by them): per entry point and kind, the resources it uses get buffer,
texture and sampler indices from 0 in (set, binding) order (buffers below
FIRST_VERTEX_SLOT); push constants are a `constant` block at PUSH_SLOT; the byte sizes of
the bound buffer ranges a `constant uint*` at SIZES_SLOT, indexed by a buffer's slot (only
for entry points with arrayLength: Entry::sizes); vertex buffer i is at vertex_slot(i).
DrawIndex (Metal has none) is entry DRAW_INDEX_AT of that buffer, which the backend sets per draw
of a multi-draw (Entry::draw_index).
Bindless tables (an array of images, samplers or storage buffers: lib/gpu's Bindless, level Voll)
are Metal 3 argument buffers in a buffer slot: an array of one-member structs, 8 bytes per image
or sampler (its MTLResourceID), 16 per buffer (its GPU address and its size in bytes, for
arrayLength). The backend writes them; the source needs MSL 3.0.
Specialization constants are substituted (Options::spec, reflect::constant_values): a
pipeline with constants is a translation of its own.
The translation: one MSL struct per SPIR-V struct; one with Offset decorations is padded to
the offsets (3-vectors become packed_ types there), arrays are jf_arr<T, N> (value semantics),
runtime arrays T m[1]. Every SSA value is a function-scope variable assigned where SPIR-V
defines it (dominance holds, C scopes need not); pointers, images and samplers stay
expressions. Structured control flow becomes if / switch / while (true); a branch to a
loop's continue target repeats the continue construct there. Resources, built-ins,
private and workgroup variables are parameters of every function that uses them. Signed
integer arithmetic goes through unsigned (it wraps, as SPIR-V and WGSL define it; MSL would
leave overflow undefined).
/// the buffer slot of the push constants
PUSH_SLOT: u32 = 29
/// the buffer slot of the bound buffer sizes (bytes, `constant uint*`, index = buffer slot)
SIZES_SLOT: u32 = 30
/// resource buffers take the slots below this one, vertex buffers this one and above
FIRST_VERTEX_SLOT: u32 = 21
/// vertex buffer slots a pipeline may use
VERTEX_BUFFERS_MAX: u32 = 8
/// the entry of the sizes buffer (SIZES_SLOT) that holds DrawIndex: the draw's index in a multi-draw
DRAW_INDEX_AT: u32 = FIRST_VERTEX_SLOT
const fn vertex_slot(i: u32) -> u32the buffer slot of vertex buffer i (i < VERTEX_BUFFERS_MAX)struct Options<'a>what translate doesspec: &'a [(u32, u64)]-- the specialization constants a pipeline sets: (SpecId, value bits) as reflect takes thementry: Option<&'a str>-- one entry point (None: all)point_size: bool-- vertex entry points write [[point_size]] = 1 (a point-list pipeline: WGSL points are one pixel, Metal wants the size)
impl Options<'_>
const DEFAULT: Options<'static> = Options { spec: &[], entry: None, point_size: false }enum SlotKindwhat a slot holdsBufferTextureSampler
struct Slota resource of an entry point and its index in Metal's argument tableset: u32binding: u32kind: SlotKindindex: u32table: bool-- a bindless table: an argument buffer in buffer slot index, whatever kind of resource it holds
struct Entryan entry point of the translationname: String-- the SPIR-V namefunction: String-- the MSL function's namemodel: u32-- spv::Model as u32workgroup: [u32; 3]-- compute: the workgroup size with the constants substituted (else 1, 1, 1)slots: Vec<Slot>-- its resources by (set, binding)push_constants: bool-- it reads push constants (PUSH_SLOT)sizes: bool-- it reads the buffer sizes (SIZES_SLOT)draw_index: bool-- it reads DrawIndex (entry DRAW_INDEX_AT of the sizes buffer; sizes is set too)vertex_inputs: Vec<u32>-- vertex: the locations of its inputs ([[attribute(n)]])
struct Mslthe result of translatesource: Stringentries: Vec<Entry>
fn translate(words: &[u32], opt: &Options) -> Result<Msl, String>
shader/parse.rs#
Source: lib/shader/parse.rs
parse -- SPIR-V words into instructions and operands (the grammar of spv::OPS)
parse(words) -> Result<Vec<Inst>, String> the instructions after the 5-word header
operands(inst, f) f(kind, words) per operand, with the masks'
and decorations' arguments as operands of
their own kinds (spv module comment)
ids(inst) -> Vec<u32> every id operand (result type and id excluded)
string(words) -> (String, words used) a literal string
struct Inst<'a>op: u16ty: u32-- result type id (0: none)res: u32-- result id (0: none)ops: &'a [u32]-- the operands after the result type and idat: usize-- the word offset of the instruction in the moduleinfo: Option<&'static OpInfo>
fn parse(words: &[u32]) -> Result<Vec<Inst<'_>>, String>fn string(words: &[u32]) -> (String, usize)a literal string starting at words[0] -> (text, words it takes)fn string_words(s: &str) -> Vec<u32>the words of a literal string (UTF-8, NUL terminated, zero padded)fn operands(inst: &Inst, f: &mut dyn FnMut(char, &[u32])) -> boolwalk the operands: f(kind, words). Kinds as in the spv module comment; the arguments of masks (l, m, I), execution modes (E: n, G: i), decorations (B for BuiltIn, else n) and switch targets (n, i) are reported one by one after their mask / enum; OpSpecConstantOp's opcode as 'o', then its operation's operands. Unknown opcodes: every word as 'n'. Returns false when the words do not fit the grammar.fn ids(inst: &Inst) -> Vec<u32>every id operand of an instruction (result type and result id not included)
shader/reflect.rs#
Source: lib/shader/reflect.rs
reflect -- what a pipeline needs to know of a SPIR-V module: its entry points, its
specialization constants (the pipeline constants: SpecId, type, default), the value every
constant takes once a pipeline sets some of them (composites and OpSpecConstantOp
evaluated), and the workgroup size of a compute entry point. lib/gpu checks pipeline
constants and workgroup limits with it; shadertest's interpreter runs specialized modules.
entry_points(words) -> Result<Vec<Entry>, String> model, name, function id
spec_constants(words) -> Result<Vec<SpecConst>, String> SpecId, result id, Kind, default
constant_values(words, set) -> Result<BTreeMap<u32, Vec<u32>>, String>
the words of every module-level constant (OpConstant*, OpSpecConstant*,
composites, OpSpecConstantOp) once the specialization constants of `set`
((SpecId, value bits) pairs) are replaced; Err for what SPIR-V leaves
undefined (division by 0, a shift by the width or more) and for an
operation SPIR-V does not allow in OpSpecConstantOp under Shader
workgroup_size(words, entry, set) -> Result<Option<[u32; 3]>, String>
of the GLCompute entry point `entry`: the WorkgroupSize built-in (it wins),
else LocalSizeId, else LocalSize (None: no such compute entry point or no
size)
uses_local_size_id(words) -> bool (Vulkan: needs maintenance4)
f16_from_f32 / f16_to_f32 IEEE half conversions
Value words: a scalar of up to 32 bits takes one word (narrower ones in its low bits, signed
ones sign-extended, as SPIR-V literals), a 64-bit one two (low word first), bool one (0 / 1);
a composite is its constituents' words in order. Value bits in `set` and in SpecConst
default: the scalar's bits in the low bits of the u64 (bool 0 / 1).
enum Kindthe type of a scalar specialization constantBoolInt { width: u32, signed: bool }Float { width: u32 }
struct SpecConsta scalar specialization constant with its SpecId (OpSpecConstant / True / False)spec_id: u32id: u32-- the constant's result idkind: Kinddefault: u64-- the default value's bits
struct Entryan entry point (OpEntryPoint)model: u32-- spv::Model as u32name: Stringfunc: u32
fn entry_points(words: &[u32]) -> Result<Vec<Entry>, String>fn f16_from_f32(x: f32) -> u16a 32-bit float as the bits of an IEEE half (round to nearest even, overflow to infinity)fn f16_to_f32(h: u16) -> f32the bits of an IEEE half as a 32-bit float (exact)fn spec_constants(words: &[u32]) -> Result<Vec<SpecConst>, String>fn constant_values(words: &[u32], set: &[(u32, u64)]) -> Result<BTreeMap<u32, Vec<u32>>, String>fn workgroup_size(words: &[u32], entry: &str, set: &[(u32, u64)]) -> Result<Option<[u32; 3]>, String>fn uses_local_size_id(words: &[u32]) -> bool
shader/samples.rs#
Source: lib/shader/samples.rs
samples -- small shaders that exercise what the WGSL compiler will need, built with the
module builder, with CPU references: specialization constants (WGSL override) and textures.
apps/shadertest validates, disassembles and interprets them (spirv-val too when the Vulkan
SDK is there), apps/gputest runs them on the GPU (docs/SHADER.md "Beispiel-Shader").
spec_fill(minor) compute: pipeline constants for values, a derived constant per
OpSpecConstantOp kind used, the workgroup size (SPEC_WG; Basis:
the WorkgroupSize built-in, Voll: LocalSizeId) and a workgroup
array of that size; SpecParams, spec_fill_ref
vs_fullscreen(minor) vertex: one triangle over the whole target (no inputs)
fs_sample(minor) fragment: texture + sampler, explicit LOD or implicit (mip selection)
fs_compare(minor) fragment: depth texture + comparison sampler, explicit or implicit
cs_fetch(minor, k, arrayed, depth) compute: OpImageFetch of every texel of a mip
cs_sample(minor, dim) compute: OpImageSampleExplicitLod at coordinates from a buffer
(2D, 2D array, cube, cube array)
cs_storage_write / cs_storage_read / cs_storage_rw(minor, fmt) compute: storage textures
storage_texel(fmt, x, y) the texel cs_storage_write writes (words as the format stores
them after conversion: unorm bytes, f16 / f32 / int bits)
cs_query(minor) compute: OpImageQuerySizeLod / OpImageQueryLevels / OpImageQuerySize
cs_bindless_sample() compute (SPIR-V 1.6, Voll): textures and samplers indexed
non-uniformly from a Bindless table
Every module: entry point "main", set 0 (the Bindless sample: set 0 = the table, set 1 the
output), push constants as each function's comment says (std430, offset 0).
specialization constants
/// the pipeline-constant ids of spec_fill
SPEC_WG: u32 = 0
SPEC_MUL: u32 = 1
SPEC_ADD: u32 = 2
SPEC_SCALE: u32 = 3
SPEC_FLIP: u32 = 4
struct SpecParamsthe values of spec_fill's pipeline constantswg: u32-- workgroup size x (y = z = 1) and the length of the workgroup arraymul: u32add: i32scale: f32flip: bool
impl SpecParams
const DEFAULT: SpecParams = SpecParams { wg: 64, mul: 3, add: -5, scale: 0.5, flip: f ...the defaults in the modulefn bits(&self) -> Vec<(u32, u64)>(SpecId, value bits) pairs of every constant (reflect::constant_values, the interpreter)fn spec_fill_ref(p: &SpecParams, n: u32) -> Vec<u32>what spec_fill writes for element i (4 words): w0 = the workgroup array's next slot (written by the neighbour invocation: ((i / wg) * wg + (i % wg + 1) % wg) * mul, inverted when flip), w1 = i as i32 + add, w2 = the bits of f32(i) * scale, w3 = flip | (32 < wg) << 1 | (wg * 2) << 8 | wg << 20 (the derived constants)fn spec_fill(minor: u32) -> Vec<u32>compute: set 0 binding 0 buffer { uint v[]; }, push constants { uint n; }; spec constants SPEC_WG .. SPEC_FLIP (SpecParams::DEFAULT); invocation i < n writes spec_fill_ref's words v[4i .. 4i + 4]enum Texelthe component type of a texture's texels in a shaderFloatUintSint
enum SampleDimthe dimension of cs_sample's textureD2D2ArrayCubeCubeArray
fn vs_fullscreen(minor: u32) -> Vec<u32>vertex: gl_Position = (-1, -1), (3, -1), (-1, 3) for vertices 0, 1, 2 (draw 3 vertices)
/// the fragment-shader push constants of fs_sample / fs_compare: uv = frag_coord.xy * scale
/// + bias; value: the LOD (fs_sample) or the depth reference (fs_compare); mode 0: explicit
/// LOD (0 for fs_compare), 1: implicit
FS_PUSH_SIZE: u32 = 24
fn fs_sample(minor: u32) -> Vec<u32>fragment: set 0 binding 0 texture_2d<f32>, binding 1 sampler; push constants (FS_PUSH_SIZE) { vec2 scale; vec2 bias; float lod; uint mode; }; colour 0 = textureSampleLevel(t, s, uv, lod) (mode 0) or textureSample(t, s, uv) (mode 1)fn fs_compare(minor: u32) -> Vec<u32>fragment: set 0 binding 0 texture_depth_2d, binding 1 sampler_comparison; push constants as fs_sample with value = the depth reference; colour 0 = (textureSampleCompareLevel(t, s, uv, dref) (mode 0) or textureSampleCompare(t, s, uv, dref) (mode 1), 0, 0, 1)
/// the push constants of cs_fetch: { uint w, h, layers; int mip; uint base; } (20 bytes)
FETCH_PUSH_SIZE: u32 = 20
fn cs_fetch(minor: u32, k: Texel, arrayed: bool, depth: bool) -> Vec<u32>compute 8 x 8 x 1, one invocation per texel (x, y, layer) of mipmip(w x h x layers): set 0 binding 0 a sampled 2D (array) texture of k (depth: texture_depth_2d), binding 1 buffer { uint v[]; }; v[base + 4 * ((layer * h + y) * w + x) + c] = the bits of component c of textureLoad(t, (x, y[, layer]), mip)fn cs_sample(minor: u32, dim: SampleDim) -> Vec<u32>compute 64 x 1 x 1: set 0 binding 0 a float texture of dim, binding 1 sampler, binding 2 readonly buffer { vec4 at[]; } (two per sample: the coordinate (xy: 2D, xyz: 2D array with the layer in z / cube direction, xyzw: cube array with the cube in w) and (lod, 0, 0, 0)), binding 3 buffer { vec4 v[]; }; push constants { uint count; }: v[i] = textureSampleLevel(t, s, coordinate i, lod i)fn storage_texel_kind(fmt: Fmt) -> Texelthe texel kind of a storage formatfn storage_texel(fmt: Fmt, x: u32, y: u32) -> Vec<u32>what cs_storage_write puts at (x, y) of a texture of fmt, as the texture stores it: for Rgba8 the four unorm bytes in one word (r in the low byte), for Rgba16f two words of two halves (r low), for 32-bit formats one word per channel; channels the format lacks droppedfn storage_read(fmt: Fmt, x: u32, y: u32) -> [u32; 4]what textureLoad gives for storage_texel (four words: float bits, uint or int) -- the format's missing channels as 0, 0, 1 (float) / 0, 0, 1 (integer)fn cs_storage_write(minor: u32, fmt: Fmt) -> Vec<u32>compute 8 x 8 x 1: set 0 binding 0 a write-only storage texture (texture_storage_2d<fmt, write>), push constants { uint w, h; }: textureStore of storage_texel's pattern at every (x, y) < (w, h) (w, h <= 16)fn cs_storage_read(minor: u32, fmt: Fmt) -> Vec<u32>compute 8 x 8 x 1: set 0 binding 0 a read-only storage texture of fmt, binding 1 buffer { uint v[]; }, push constants { uint w, h; }: v[4 (y w + x) + c] = the bits of component c of textureLoad(img, (x, y)); invocation (0, 0) also writes textureDimensions(img) (OpImageQuerySize) to v[4 w h], v[4 w h + 1]fn storage_rw_ref(fmt: Fmt, v: u32) -> u32what cs_storage_rw makes of a texel value v (one channel: r32float, r32uint, r32sint)fn cs_storage_rw(minor: u32, fmt: Fmt) -> Vec<u32>compute 8 x 8 x 1: set 0 binding 0 a read-write storage texture of a one-channel 32-bit fmt, push constants { uint w, h; }: every texel v becomes storage_rw_ref(v) (v * 2 + 1, v * 3 + 1, v - 5)
/// the bindings of cs_query (set 0): 0 texture_2d<f32>, 1 texture_2d_array<f32>, 2
/// texture_cube<f32>, 3 texture_cube_array<f32>, 4 texture_depth_2d, 5 texture_2d<f32> (meant
/// for a view of some mips), 6 texture_storage_2d<r32float, read>; binding 7 the output
QUERY_SAMPLED: u32 = 6
fn cs_query(minor: u32) -> Vec<u32>compute 1 x 1 x 1: for each sampled binding b < QUERY_SAMPLED: v[12 b .. 12 b + 4] = textureDimensions(t, 0) (with the layers of arrays), v[12 b + 4 ..] = at mip 1, v[12 b + 8] = textureNumLevels(t) (the rest of the 12 words 0); v[72 ..] = textureDimensions of the storage texture (OpImageQuerySize); every query as uint components (0 where the result has fewer)fn cs_bindless_sample() -> Vec<u32>compute 64 x 1 x 1, SPIR-V 1.6 (level Voll): set 0 the Bindless table (binding 0 texture_2d<f32> texs[], binding 1 sampler smps[]), set 1 binding 0 buffer { vec4 v[]; }, push constants { uint count; uint ntex; uint nsmp; float u; float v; }: invocation i < count samples texs[i % ntex] with smps[i % nsmp] at (u, v), LOD 0 -- indices that differ between invocations, so the resources are decorated NonUniform
shader/spv.rs#
Source: lib/shader/spv.rs
spv -- the numbers of SPIR-V 1.6 (unified1 grammar) that shader uses, with their names
op::* opcodes (op::FAdd = 129), OPS / op_info(op): name and operand grammar
Cap, Sc (storage class), Dec (decoration), Bi (built-in), Model (execution model),
Mode (execution mode), Dim, Fmt (image format), Lang (source language): typed enums with
name tables (CAPS, SCS, ...) for the disassembler; name(table, v) -> Option<&str>
scope::*, sem::* (memory semantics), mask names (fn_ctl, sel_ctl, loop_ctl, mem_access,
img_ops), glsl::* (GLSL.std.450 instruction numbers, GLSL_NAMES)
Operand grammar (OpInfo::ops), one character per operand, `*` repeats the last kind,
`?` makes the rest optional:
i id n literal word s string v literal number of the result type (OpConstant)
C capability A addressing model Y memory model M execution model
E execution mode + literal args G execution mode + id args d decoration + args
S storage class D dim F image format Q access qualifier k source language
f function control e selection control l loop control (+ args)
m memory access (+ args) I image operands (+ id args) x extended instruction number
w switch targets: (literal, id) pairs
o an opcode (OpSpecConstantOp) followed by the operands of that opcode's grammar
MAGIC: u32 = 0x0723_0203
const fn version(major: u32, minor: u32) -> u32the version word of SPIR-V major.minor
/// result flags of OpInfo::res
R_NONE: u8 = 0
R_ID: u8 = 1 // a result id
R_TY: u8 = 2 // a result type and a result id
struct OpInfoop: u16name: &'static strres: u8ops: &'static str
fn op_info(op: u16) -> Option<&'static OpInfo>the grammar of an opcode (None: unknown to shader)fn name(table: &[(u32, &'static str)], v: u32) -> Option<&'static str>the name of v in a (value, name) tableenum Dimimage dimensionality (OpTypeImage)D1 = 0D2 = 1D3 = 2Cube = 3Rect = 4Buffer = 5SubpassData = 6
DIMS: &[(u32, &str)] = &[(0, "1D"), (1, "2D"), (2, "3D"), (3, "Cube"), (4, "Rect ...
ADDRESSING: &[(u32, &str)] = &[(0, "Logical"), (1, "Physical32"), (2, "Physical64"), ( ...
MEMORY_MODELS: &[(u32, &str)] = &[(0, "Simple"), (1, "GLSL450"), (2, "OpenCL"), (3, "Vulk ...
ACCESS: &[(u32, &str)] = &[(0, "ReadOnly"), (1, "WriteOnly"), (2, "ReadWrite")]
// masks: (bit, name, operand words that follow when the bit is set: 'n' literal, 'i' id)
FN_CTL: &[(u32, &str, &str)] = &[(1, "Inline", ""), (2, "DontInline", ""), (4, "Pure", " ...
SEL_CTL: &[(u32, &str, &str)] = &[(1, "Flatten", ""), (2, "DontFlatten", "")]
LOOP_CTL: &[(u32, &str, &str)] = &[ (1, "Unroll", ""), (2, "DontUnroll", ""), (4, "Depende ...
MEM_ACCESS: &[(u32, &str, &str)] = &[ (1, "Volatile", ""), (2, "Aligned", "n"), (4, "Nontemp ...
IMG_OPS: &[(u32, &str, &str)] = &[ (1, "Bias", "i"), (2, "Lod", "i"), (4, "Grad", "ii"), ...
/// the names of GLSL.std.450 (index = instruction number)
GLSL_NAMES: &[&str] = &[ "", "Round", "RoundEven", "Trunc", "FAbs", "SAbs", "FS ...
mod scope
scopes (the value of a constant id operand)
CrossDevice: u32 = 0
Device: u32 = 1
Workgroup: u32 = 2
Subgroup: u32 = 3
Invocation: u32 = 4
QueueFamily: u32 = 5
mod group_op
the group operation literal of OpGroupNonUniform{IAdd, FAdd ...}
Reduce: u32 = 0
InclusiveScan: u32 = 1
ExclusiveScan: u32 = 2
mod sem
memory semantics bits (the value of a constant id operand)
None: u32 = 0
Acquire: u32 = 0x2
Release: u32 = 0x4
AcquireRelease: u32 = 0x8
SequentiallyConsistent: u32 = 0x10
UniformMemory: u32 = 0x40
SubgroupMemory: u32 = 0x80
WorkgroupMemory: u32 = 0x100
CrossWorkgroupMemory: u32 = 0x200
ImageMemory: u32 = 0x800
mod img
image operand bits (OpImageSample* and friends)
Bias: u32 = 1
Lod: u32 = 2
Grad: u32 = 4
ConstOffset: u32 = 8
Sample: u32 = 0x40
mod glsl
GLSL.std.450 extended instructions
Round: u32 = 1
RoundEven: u32 = 2
Trunc: u32 = 3
FAbs: u32 = 4
SAbs: u32 = 5
FSign: u32 = 6
SSign: u32 = 7
Floor: u32 = 8
Ceil: u32 = 9
Fract: u32 = 10
Sin: u32 = 13
Cos: u32 = 14
Tan: u32 = 15
Atan2: u32 = 25
Pow: u32 = 26
Exp: u32 = 27
Log: u32 = 28
Exp2: u32 = 29
Log2: u32 = 30
Sqrt: u32 = 31
InverseSqrt: u32 = 32
FMin: u32 = 37
UMin: u32 = 38
SMin: u32 = 39
FMax: u32 = 40
UMax: u32 = 41
SMax: u32 = 42
FClamp: u32 = 43
UClamp: u32 = 44
SClamp: u32 = 45
FMix: u32 = 46
Step: u32 = 48
SmoothStep: u32 = 49
Fma: u32 = 50
Length: u32 = 66
Distance: u32 = 67
Cross: u32 = 68
Normalize: u32 = 69
Reflect: u32 = 71
shader/val.rs#
Source: lib/shader/val.rs
val -- a structural validator for SPIR-V modules as Vulkan consumes them. It checks what
a module builder can get wrong; it is not spirv-val (docs/SHADER.md lists what it leaves out).
validate(words) -> Result<(), Vec<Error>> Error { rule, at (word offset), msg }
Rules (Rule::*):
Header magic, version 1.0 ..= 1.6, schema 0, every id below the bound
Grammar known opcodes, operand words that fit the grammar (spv::OPS)
Section the logical layout: capabilities, extensions, imports, one memory model,
entry points, execution modes, debug, annotations, types / constants /
globals, functions; nothing module-level inside a function
IdUnique every result id defined once
IdDefined every used id defined, before its use (except names, decorations, entry
points, execution modes, labels, phis, called functions), function-local ids
only inside their function
IdKind ids of the right kind: result types are types, labels are labels, operands
are values, callees are functions, extended sets are imports
Type types well formed (vector / matrix shapes, array lengths -- constants or
specialization constants --, runtime arrays last) and type agreement of the
instructions shader emits: arithmetic, comparisons, logic, select,
conversions, access chains, load / store, composites, shuffles, products,
GLSL.std.450, atomics, barriers, images (coordinate sizes, Dref, the image
kinds each query takes), derivatives, calls, phis, returns, constants,
specialization constants (OpSpecConstantOp: an operation SPIR-V allows for
Shader, constant operands, its operation's type rules), variables
Decoration decoration targets of the right kind (Offset on struct members, ArrayStride
on arrays, Block on structs, Location on Input / Output, SpecId on scalar
specialization constants and each value once, BuiltIn on a constant only as
a uvec3 WorkgroupSize ...), member indices
Storage variables: storage class of the pointer, Function variables first in the
entry block, Vulkan's resource rules (Block structs in Uniform /
StorageBuffer / PushConstant, DescriptorSet + Binding on resources, Location
on user Input / Output, images in UniformConstant), no stores to read-only
storage, atomics only on buffer / workgroup / image memory
BlockLayout Offset on every block member, offsets aligned per std140 (Uniform) / std430
(StorageBuffer, PushConstant) and not overlapping, ArrayStride / MatrixStride
present, aligned and not smaller than the element, ColMajor / RowMajor on
matrices, push constants at most 128 bytes
Cfg blocks start with OpLabel and end with one terminator, merge instructions
right before the branch they belong to, merge / continue targets in the
function, a merge block per header at most once and after it, conditional
branches without a merge only as break / continue, back edges only to loop
headers, a back edge per loop, the entry block no branch target, phis first in
their block with predecessors as parents
Interface OpEntryPoint: a void function without parameters, the interface lists only
globals, before 1.4 only Input / Output ones, from 1.4 each at most once; it
contains every global the call tree uses (1.4+) or every Input / Output one
ExecMode LocalSize (or LocalSizeId with 32-bit integer constant operands, or the
WorkgroupSize built-in) for GLCompute, id modes only in OpExecutionModeId,
OriginUpperLeft (and no OriginLowerLeft) for
Fragment, modes for the right models, DepthReplacing when FragDepth is
written, fragment-only instructions (discard, demote, derivatives,
implicit-LOD sampling) only under Fragment entry points, Workgroup
variables only under GLCompute
Capability the capabilities types, instructions, built-ins, images and models need
Version instructions and extensions of the module's SPIR-V version (TerminateInvocation
and DemoteToHelperInvocation before 1.6, CopyLogical, composite Select and
UConvert in OpSpecConstantOp before 1.4, OpExecutionModeId before 1.2,
descriptor indexing before 1.5)
enum RuleHeaderGrammarSectionIdUniqueIdDefinedIdKindTypeDecorationStorageBlockLayoutCfgInterfaceExecModeCapabilityVersion
struct Errorrule: Ruleat: usize-- the word offset of the instruction (0: the module)msg: String
struct Optionswhat the device allows beyond Vulkan's defaults (validate_with)uniform_standard_layout: bool-- uniformBufferStandardLayout: uniform blocks laid out like storage blocks (std430)
fn validate(words: &[u32]) -> Result<(), Vec<Error>>check a module (the rules of the module comment) -> Ok or every error foundfn validate_with(words: &[u32], opt: &Options) -> Result<(), Vec<Error>>validate with device options (a uniform buffer in the storage layout)