JFLib

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 Object
    • pos: [f32; 3]
    • scale: f32
    • rot: [f32; 4]
    • color: [f32; 3]
    • radius: f32

impl Object

  • fn bytes(&self) -> Vec<u8>

  • fn from_bytes(b: &[u8]) -> Object one record from 48 bytes

  • fn objects_bytes(objs: &[Object]) -> Vec<u8> the bytes of an Object buffer

  • fn objects_from_bytes(b: &[u8]) -> Vec<Object> an Object buffer read back (len / 48 records)

  • struct Camera

    • view_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 >= 0
    • light_dir: [f32; 3]
    • ambient: f32
  • struct DrawCmd

    • index_count: u32
    • instance_count: u32
    • first_index: u32
    • vertex_offset: i32
    • first_instance: u32

impl DrawCmd

  • fn reset() -> DrawCmd the command cull_reset writes: 36 indices, no instances yet

  • fn bytes(&self) -> Vec<u8>

  • fn from_bytes(b: &[u8]) -> DrawCmd

  • struct Push

    • time: f32 -- seconds since the start
    • count: u32
    • seed: u32
    • extent: f32 -- the scene's radius: orbits between 0.1 and 1.0 times extent
    • object_index: u32 -- vs_single: the object drawn

impl Push

  • fn bytes(&self) -> Vec<u8>

  • fn extent_for(count: u32) -> f32 a good extent for count cubes (about 3 world units between neighbours)

  • struct CubeVertex

    • pos: [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) -> Camera a 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]) -> Camera planes 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.25

  • fn bytes(&self) -> Vec<u8> the 176 bytes of the uniform buffer (std140)

  • fn hash(x: u32) -> u32 PCG hash (Jarkko & Olano, "Hash Functions for GPU Rendering")

  • fn unit(h: u32) -> f32 the top 24 bits as a float in [0, 1) (exact)

  • fn floor(x: f32) -> f32 floor 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 formulas

  • fn move_ref(i: u32, p: &Push) -> Object what move writes for object i

  • fn move_all(p: &Push) -> Vec<Object> move for objects 0 .. p.count

  • fn visible(o: &Object, cam: &Camera) -> bool cull's test: the bounding sphere is not completely outside one of the planes

  • fn 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 Shader the six benchmark shaders

    • Move
    • Cull
    • CullReset
    • VsInstanced
    • VsSingle
    • FsLambert

impl Shader

  • const ALL: [Shader; 6] = [Shader::Move, Shader::Cull, Shader::CullReset, Shader::V ...

  • fn name(self) -> &'static str

  • fn model(self) -> Model

  • fn 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.count

  • fn cull_spv(minor: u32) -> Vec<u32> cull: for gid < pc.count, if visible(objects[gid], camera): visible[atomicAdd( draw.instance_count, 1)] = gid

  • fn 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) -> String a 32-bit float as spirv-dis prints it

  • fn 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 Rule

    • Std140
    • Std430
  • 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 type

  • fn stride(t: &dyn Types, elem: u32, rule: Rule) -> Option<u32> the stride of an array of elem

  • fn 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 Ty a SPIR-V type

    • Void
    • Bool
    • Int { 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 constant
    • RuntimeArray { 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 }
    • Sampler
    • SampledImage { image: Id }
  • trait Types what the layout helper and the validator need to know about ids

    • fn ty(&self, id: u32) -> Option<&Ty>
    • fn const_u32(&self, id: u32) -> Option<u32> the value of a 32-bit integer constant
  • struct Loop the labels of the loop being built (loop_): break = branch(merge), continue = branch(cont)

    • merge: Id
    • cont: Id
  • struct Module

    • generator: 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) -> Module a module for SPIR-V 1.minor (3 ..= 6) with the Shader capability and the logical GLSL450 memory model

  • fn minor(&self) -> u32

  • fn id(&mut self) -> Id a 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) -> Id the GLSL.std.450 import (created on first use)

  • fn type_of(&self, v: Id) -> Id the type of a value id

  • fn ty(&self, t: Id) -> &Ty the description of a type id

  • fn 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 embedded

  • fn 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) -> Id

  • fn ty_bool(&mut self) -> Id

  • fn ty_int(&mut self, width: u32, signed: bool) -> Id an integer type; 8, 16 and 64 bits add Int8 / Int16 / Int64

  • fn ty_u32(&mut self) -> Id

  • fn ty_i32(&mut self) -> Id

  • fn ty_float(&mut self, width: u32) -> Id a float type; 16 and 64 bits add Float16 / Float64

  • fn ty_f32(&mut self) -> Id

  • fn ty_vec(&mut self, elem: Id, n: u32) -> Id

  • fn ty_mat(&mut self, col: Id, cols: u32) -> Id a matrix of cols columns of the vector type col

  • fn ty_array(&mut self, elem: Id, len: u32) -> Id an array of len elements without ArrayStride (Function, Private, Workgroup storage)

  • fn ty_array_id(&mut self, elem: Id, len: Id) -> Id an 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) -> Id an array decorated with ArrayStride (buffers); deduplicated by element, length, stride

  • fn ty_array_layout(&mut self, elem: Id, len: u32, rule: Rule) -> Id an array laid out by rule (ArrayStride from the layout helper)

  • fn ty_runtime_array(&mut self, elem: Id, stride: Option<u32>) -> Id a runtime array; stride Some(s): decorated with ArrayStride s (buffers)

  • fn ty_struct(&mut self, members: &[Id]) -> Id a struct (never deduplicated: two structs may differ in their decorations)

  • fn ty_struct_layout(&mut self, name: &str, members: &[(&str, Id)], rule: Rule) -> Id a named struct laid out by rule: 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) -> Id

  • fn ty_func(&mut self, ret: Id, params: &[Id]) -> Id

  • fn ty_image(&mut self, sampled: Id, dim: Dim, depth: u32, arrayed: u32, ms: u32, usage: u32, format: Fmt) -> Id OpTypeImage; usage 1: sampled, 2: storage image (format needed unless the *WithoutFormat capabilities are declared)

  • fn ty_sampler(&mut self) -> Id

  • fn ty_sampled_image(&mut self, image: Id) -> Id

  • fn bool_like(&mut self, t: Id) -> Id bool (or a bool vector of the same length) for a scalar / vector type

  • fn scalar_of(&self, t: Id) -> Id the component type of a vector (the type itself for a scalar)

  • fn const_scalar(&mut self, ty: Id, words: &[u32]) -> Id OpConstant of an int or float type with its value words (low word first)

  • fn const_u32(&mut self, v: u32) -> Id

  • fn const_i32(&mut self, v: i32) -> Id

  • fn const_f32(&mut self, v: f32) -> Id

  • fn const_bool(&mut self, v: bool) -> Id

  • fn const_composite(&mut self, ty: Id, parts: &[Id]) -> Id

  • fn const_vec_f32(&mut self, v: &[f32]) -> Id a float vector constant

  • fn const_null(&mut self, ty: Id) -> Id

  • fn is_spec(&self, v: Id) -> bool whether v is a specialization constant (OpSpecConstant*, composites of them, results of OpSpecConstantOp)

  • fn spec_scalar(&mut self, ty: Id, spec_id: u32, words: &[u32]) -> Id OpSpecConstant of an int or float type with its default value words (low word first), decorated SpecId spec_id (the pipeline constant's id); never deduplicated

  • fn spec_u32(&mut self, spec_id: u32, default: u32) -> Id

  • fn spec_i32(&mut self, spec_id: u32, default: i32) -> Id

  • fn spec_f32(&mut self, spec_id: u32, default: f32) -> Id

  • fn spec_bool(&mut self, spec_id: u32, default: bool) -> Id OpSpecConstantTrue / OpSpecConstantFalse decorated SpecId spec_id

  • fn spec_composite(&mut self, ty: Id, parts: &[Id]) -> Id OpSpecConstantComposite of constants and specialization constants (deduplicated)

  • fn spec_op(&mut self, ty: Id, opc: u16, ids: &[Id], literals: &[u32]) -> Id OpSpecConstantOp: 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>) -> Id a global OpVariable of pointee in storage class sc

  • fn input(&mut self, ty: Id, location: u32) -> Id

  • fn output(&mut self, ty: Id, location: u32) -> Id

  • fn builtin(&mut self, sc: Sc, ty: Id, b: Bi) -> Id a built-in Input or Output variable; adds the capability some built-ins need

  • fn buffer(&mut self, sc: Sc, block: Id, set: u32, binding: u32) -> Id a uniform (Sc::Uniform) or storage (Sc::StorageBuffer) buffer of a laid-out struct: Block on the struct, DescriptorSet and Binding on the variable

  • fn push_constant(&mut self, block: Id) -> Id the push-constant block (a struct laid out by Rule::Std430)

  • fn workgroup(&mut self, ty: Id) -> Id

  • fn resource(&mut self, ty: Id, set: u32, binding: u32) -> Id an 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]) -> Id the 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) -> Id a new label id (the block starts with begin_block)

  • fn begin_block(&mut self, l: Id)

  • fn block_open(&self) -> bool whether the current block still needs a terminator

  • fn local(&mut self, ty: Id, init: Option<Id>) -> Id a Function-storage variable (placed at the start of the entry block)

  • fn emit(&mut self, opc: u16, ty: Option<Id>, args: &[u32]) -> Id any 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.6

  • fn demote(&mut self) make the invocation a helper (not a terminator); before 1.6 through SPV_EXT_demote_to_helper_invocation

  • fn phi(&mut self, ty: Id, pairs: &[(Id, Id)]) -> Id OpPhi of (value, predecessor label) pairs

  • fn if_then(&mut self, c: Id, then: impl FnOnce(&mut Module)) if (c) { then }: a selection construct

  • fn 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) -> Id

  • fn unary(&mut self, opc: u16, a: Id) -> Id

  • fn fadd(&mut self, a: Id, b: Id) -> Id

  • fn fsub(&mut self, a: Id, b: Id) -> Id

  • fn fmul(&mut self, a: Id, b: Id) -> Id

  • fn fdiv(&mut self, a: Id, b: Id) -> Id

  • fn fmod(&mut self, a: Id, b: Id) -> Id

  • fn fneg(&mut self, a: Id) -> Id

  • fn iadd(&mut self, a: Id, b: Id) -> Id

  • fn isub(&mut self, a: Id, b: Id) -> Id

  • fn imul(&mut self, a: Id, b: Id) -> Id

  • fn udiv(&mut self, a: Id, b: Id) -> Id

  • fn sdiv(&mut self, a: Id, b: Id) -> Id

  • fn umod(&mut self, a: Id, b: Id) -> Id

  • fn srem(&mut self, a: Id, b: Id) -> Id

  • fn ineg(&mut self, a: Id) -> Id

  • fn band(&mut self, a: Id, b: Id) -> Id

  • fn bor(&mut self, a: Id, b: Id) -> Id

  • fn bxor(&mut self, a: Id, b: Id) -> Id

  • fn bnot(&mut self, a: Id) -> Id

  • fn shl(&mut self, a: Id, n: Id) -> Id

  • fn shr(&mut self, a: Id, n: Id) -> Id logical shift right

  • fn sar(&mut self, a: Id, n: Id) -> Id arithmetic shift right

  • fn vec_scale(&mut self, v: Id, s: Id) -> Id vector * scalar

  • fn mat_scale(&mut self, m: Id, s: Id) -> Id matrix * scalar

  • fn mat_vec(&mut self, m: Id, v: Id) -> Id matrix * column vector

  • fn vec_mat(&mut self, v: Id, m: Id) -> Id row vector * matrix

  • fn mat_mat(&mut self, a: Id, b: Id) -> Id

  • fn transpose(&mut self, m: Id) -> Id

  • fn dot(&mut self, a: Id, b: Id) -> Id

  • fn cmp(&mut self, opc: u16, a: Id, b: Id) -> Id a comparison: the result is bool or a bool vector of the operands' length

  • fn feq(&mut self, a: Id, b: Id) -> Id

  • fn fne(&mut self, a: Id, b: Id) -> Id

  • fn flt(&mut self, a: Id, b: Id) -> Id

  • fn fle(&mut self, a: Id, b: Id) -> Id

  • fn fgt(&mut self, a: Id, b: Id) -> Id

  • fn fge(&mut self, a: Id, b: Id) -> Id

  • fn ieq(&mut self, a: Id, b: Id) -> Id

  • fn ine(&mut self, a: Id, b: Id) -> Id

  • fn ult(&mut self, a: Id, b: Id) -> Id

  • fn ule(&mut self, a: Id, b: Id) -> Id

  • fn uge(&mut self, a: Id, b: Id) -> Id

  • fn slt(&mut self, a: Id, b: Id) -> Id

  • fn sge(&mut self, a: Id, b: Id) -> Id

  • fn land(&mut self, a: Id, b: Id) -> Id

  • fn lor(&mut self, a: Id, b: Id) -> Id

  • fn lnot(&mut self, a: Id) -> Id

  • fn any(&mut self, v: Id) -> Id

  • fn all(&mut self, v: Id) -> Id

  • fn select(&mut self, c: Id, a: Id, b: Id) -> Id c ? a : b

  • fn convert(&mut self, opc: u16, ty: Id, a: Id) -> Id a conversion opcode (ConvertFToU, ConvertSToF, Bitcast, FConvert ...) to type ty

  • fn u2f(&mut self, ty: Id, a: Id) -> Id

  • fn s2f(&mut self, ty: Id, a: Id) -> Id

  • fn f2u(&mut self, ty: Id, a: Id) -> Id

  • fn f2s(&mut self, ty: Id, a: Id) -> Id

  • fn bitcast(&mut self, ty: Id, a: Id) -> Id

  • fn access(&mut self, base: Id, idx: &[Id]) -> Id OpAccessChain: the result points at the member / element the indices select (struct indices must be constants)

  • fn access_c(&mut self, base: Id, idx: &[u32]) -> Id access with constant u32 indices

  • fn load(&mut self, ptr: Id) -> Id

  • fn store(&mut self, ptr: Id, v: Id)

  • fn construct(&mut self, ty: Id, parts: &[Id]) -> Id

  • fn extract(&mut self, v: Id, idx: &[u32]) -> Id

  • fn insert(&mut self, v: Id, obj: Id, idx: &[u32]) -> Id

  • fn shuffle(&mut self, a: Id, b: Id, comps: &[u32]) -> Id OpVectorShuffle: components of a (0..) and b (len(a)..)

  • fn extract_dynamic(&mut self, v: Id, i: Id) -> Id

  • fn ext(&mut self, ty: Id, inst: u32, args: &[Id]) -> Id an extended instruction of GLSL.std.450 (spv::glsl::*) with result type ty

  • fn glsl(&mut self, inst: u32, args: &[Id]) -> Id a 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) -> Id GLSL.std.450 Length (the result is the component type)

  • fn atomic(&mut self, opc: u16, ptr: Id, scope: u32, semantics: u32, value: Id) -> Id an atomic read-modify-write (AtomicIAdd, AtomicUMax, AtomicExchange ...) on a 32- or 64-bit integer: scope and semantics become constants

  • fn atomic_load(&mut self, ptr: Id, scope: u32, semantics: u32) -> Id

  • fn 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) -> Id OpAtomicCompareExchange -> the original value

  • fn 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) -> Id

  • fn sample(&mut self, si: Id, coord: Id) -> Id texture(si, coord): implicit LOD (fragment shaders)

  • fn sample_lod(&mut self, si: Id, coord: Id, lod: Id) -> Id textureLod(si, coord, lod)

  • fn fetch(&mut self, image: Id, coord: Id, lod: Id) -> Id texelFetch(image, coord, lod) on an OpImage / sampled-usage image

  • fn image_read(&mut self, image: Id, coord: Id) -> Id imageLoad of a storage image

  • fn image_write(&mut self, image: Id, coord: Id, texel: Id) imageStore of a storage image

  • fn image_size(&mut self, ty: Id, image: Id) -> Id OpImageQuerySize (storage images, no LOD) with result type ty

  • fn image_size_lod(&mut self, ty: Id, image: Id, lod: Id) -> Id OpImageQuerySizeLod (sampled images)

  • fn image_levels(&mut self, ty: Id, image: Id) -> Id OpImageQueryLevels (textureNumLevels of a sampled image) with result type ty

  • fn sample_dref(&mut self, si: Id, coord: Id, dref: Id) -> Id textureSampleCompare: OpImageSampleDrefImplicitLod (fragment shaders) -> the float result

  • fn sample_dref_lod(&mut self, si: Id, coord: Id, dref: Id, lod: Id) -> Id textureSampleCompareLevel: OpImageSampleDrefExplicitLod with Lod lod

  • fn 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) -> Id DPdx, DPdy, Fwidth and their Fine / Coarse forms (those add DerivativeControl)

  • fn dpdx(&mut self, a: Id) -> Id

  • fn dpdy(&mut self, a: Id) -> Id

  • fn fwidth(&mut self, a: Id) -> Id

  • fn call(&mut self, func: Id, args: &[Id]) -> Id OpFunctionCall of a function built (or begun with begin_function_id) in this module

  • fn finish(&self) -> Vec<u32> the module's words

  • fn 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) -> u32 the buffer slot of vertex buffer i (i < VERTEX_BUFFERS_MAX)

  • struct Options<'a> what translate does

    • spec: &'a [(u32, u64)] -- the specialization constants a pipeline sets: (SpecId, value bits) as reflect takes them
    • entry: 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 SlotKind what a slot holds

    • Buffer
    • Texture
    • Sampler
  • struct Slot a resource of an entry point and its index in Metal's argument table

    • set: u32
    • binding: u32
    • kind: SlotKind
    • index: u32
    • table: bool -- a bindless table: an argument buffer in buffer slot index, whatever kind of resource it holds
  • struct Entry an entry point of the translation

    • name: String -- the SPIR-V name
    • function: String -- the MSL function's name
    • model: u32 -- spv::Model as u32
    • workgroup: [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 Msl the result of translate

    • source: String
    • entries: 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: u16
    • ty: u32 -- result type id (0: none)
    • res: u32 -- result id (0: none)
    • ops: &'a [u32] -- the operands after the result type and id
    • at: usize -- the word offset of the instruction in the module
    • info: 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])) -> bool walk 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 Kind the type of a scalar specialization constant

    • Bool
    • Int { width: u32, signed: bool }
    • Float { width: u32 }
  • struct SpecConst a scalar specialization constant with its SpecId (OpSpecConstant / True / False)

    • spec_id: u32
    • id: u32 -- the constant's result id
    • kind: Kind
    • default: u64 -- the default value's bits
  • struct Entry an entry point (OpEntryPoint)

    • model: u32 -- spv::Model as u32
    • name: String
    • func: u32
  • fn entry_points(words: &[u32]) -> Result<Vec<Entry>, String>

  • fn f16_from_f32(x: f32) -> u16 a 32-bit float as the bits of an IEEE half (round to nearest even, overflow to infinity)

  • fn f16_to_f32(h: u16) -> f32 the 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 SpecParams the values of spec_fill's pipeline constants
    • wg: u32 -- workgroup size x (y = z = 1) and the length of the workgroup array
    • mul: u32
    • add: i32
    • scale: f32
    • flip: bool

impl SpecParams

  • const DEFAULT: SpecParams = SpecParams { wg: 64, mul: 3, add: -5, scale: 0.5, flip: f ... the defaults in the module

  • fn 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 Texel the component type of a texture's texels in a shader

    • Float
    • Uint
    • Sint
  • enum SampleDim the dimension of cs_sample's texture

    • D2
    • D2Array
    • Cube
    • CubeArray
  • 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 mip mip (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) -> Texel the texel kind of a storage format

  • fn 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 dropped

  • fn 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) -> u32 what 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) -> u32 the 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 OpInfo

    • op: u16
    • name: &'static str
    • res: u8
    • ops: &'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) table

  • enum Dim image dimensionality (OpTypeImage)

    • D1 = 0
    • D2 = 1
    • D3 = 2
    • Cube = 3
    • Rect = 4
    • Buffer = 5
    • SubpassData = 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 Rule

    • Header
    • Grammar
    • Section
    • IdUnique
    • IdDefined
    • IdKind
    • Type
    • Decoration
    • Storage
    • BlockLayout
    • Cfg
    • Interface
    • ExecMode
    • Capability
    • Version
  • struct Error

    • rule: Rule
    • at: usize -- the word offset of the instruction (0: the module)
    • msg: String
  • struct Options what 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 found

  • fn validate_with(words: &[u32], opt: &Options) -> Result<(), Vec<Error>> validate with device options (a uniform buffer in the storage layout)

Source: docs/API.md in the JFLib repository.