Documentation
¶
Overview ¶
Package ir defines the intermediate representation for naga.
The IR is designed to be:
- Shader-agnostic: Not tied to any specific shading language
- Complete: Can represent all features needed for modern shaders
- Efficient: Optimized for analysis and transformation
Structure ¶
The IR is organized around a Module type that contains:
- Types: All type definitions used in the shader
- Constants: Module-scope constant values
- GlobalVariables: Module-scope variables (uniforms, storage, etc.)
- Functions: All function definitions
- EntryPoints: Shader entry points with stage information
Translation Pipeline ¶
The typical translation pipeline is:
Source (WGSL/GLSL) → AST → IR → Target (SPIR-V/GLSL/MSL)
This allows for source-independent analysis and optimization, as well as multi-target compilation from a single IR.
References ¶
This IR design is inspired by:
- naga (Rust): https://github.com/gfx-rs/wgpu/tree/trunk/naga
- SPIR-V specification: https://www.khronos.org/registry/SPIR-V/
Concurrency ¶
Every exported function is safe for concurrent use. Validate and the other functions that take a module never modify it, and Module.Clone shares nothing with its source. Package ir has no pass that rewrites a module: compaction is naga.Compact, which modifies its module in place. A Layouter needs the usual synchronization of a value Update changes.
Package ir defines the intermediate representation for naga.
The IR is a shader-agnostic representation that can be translated from various source languages (WGSL, GLSL) and compiled to various target languages (SPIR-V, GLSL, MSL, HLSL).
Index ¶
- Variables
- type AccelerationStructureType
- type AddressSpace
- type ArraySize
- type ArrayType
- type AtomicAdd
- type AtomicAnd
- type AtomicExchange
- type AtomicExclusiveOr
- type AtomicFunction
- type AtomicInclusiveOr
- type AtomicMax
- type AtomicMin
- type AtomicSubtract
- type AtomicType
- type BarrierFlags
- type BinaryOperator
- type Binding
- type BindingArrayType
- type Block
- type BuiltinBinding
- type BuiltinValue
- type CollectiveOperation
- type ConservativeDepth
- type Constant
- type ConstantHandle
- type DerivativeAxis
- type DerivativeControl
- type EarlyDepthAllow
- type EarlyDepthForce
- type EarlyDepthTest
- type EntryPoint
- type ExprAccess
- type ExprAccessIndex
- type ExprArrayLength
- type ExprAs
- type ExprAtomicResult
- type ExprBinary
- type ExprCallResult
- type ExprCompose
- type ExprConstant
- type ExprDerivative
- type ExprFunctionArgument
- type ExprGlobalVariable
- type ExprImageLoad
- type ExprImageQuery
- type ExprImageSample
- type ExprLoad
- type ExprLocalVariable
- type ExprMath
- type ExprOverride
- type ExprRayQueryGetIntersection
- type ExprRayQueryProceedResult
- type ExprRelational
- type ExprSelect
- type ExprSplat
- type ExprSubgroupBallotResult
- type ExprSubgroupOperationResult
- type ExprSwizzle
- type ExprUnary
- type ExprWorkGroupUniformLoadResult
- type ExprZeroValue
- type Expression
- type ExpressionHandle
- type ExpressionKind
- type Function
- type FunctionArgument
- type FunctionHandle
- type FunctionResult
- type GatherBroadcast
- type GatherBroadcastFirst
- type GatherMode
- type GatherQuadBroadcast
- type GatherQuadSwap
- type GatherShuffle
- type GatherShuffleDown
- type GatherShuffleUp
- type GatherShuffleXor
- type GlobalVariable
- type GlobalVariableHandle
- type ImageClass
- type ImageDimension
- type ImageQuery
- type ImageQueryNumLayers
- type ImageQueryNumLevels
- type ImageQueryNumSamples
- type ImageQuerySize
- type ImageType
- type IndexableLength
- type Interpolation
- type Layouter
- type Literal
- type LiteralAbstractFloat
- type LiteralAbstractInt
- type LiteralBool
- type LiteralF16
- type LiteralF32
- type LiteralF64
- type LiteralI32
- type LiteralI64
- type LiteralU32
- type LiteralU64
- type LiteralValue
- type LocalVariable
- type LocalVariableHandle
- type LocationBinding
- type MathFunction
- type MatrixType
- type MeshOutputTopology
- type MeshStageInfo
- type Module
- type Override
- type OverrideHandle
- type PointerType
- type QuadDirection
- type Range
- type RayQueryConfirmIntersection
- type RayQueryFunction
- type RayQueryGenerateIntersection
- type RayQueryInitialize
- type RayQueryProceed
- type RayQueryTerminate
- type RayQueryType
- type RelationalFunction
- type ResourceBinding
- type SampleLevel
- type SampleLevelAuto
- type SampleLevelBias
- type SampleLevelExact
- type SampleLevelGradient
- type SampleLevelZero
- type SamplerType
- type Sampling
- type ScalarKind
- type ScalarType
- type ShaderStage
- type SourceLocation
- type Span
- type SpecialTypes
- type Statement
- type StatementKind
- type StmtAtomic
- type StmtBlock
- type StmtBreak
- type StmtCall
- type StmtContinue
- type StmtControlBarrier
- type StmtEmit
- type StmtIf
- type StmtImageAtomic
- type StmtImageStore
- type StmtKill
- type StmtLoop
- type StmtMemoryBarrier
- type StmtRayQuery
- type StmtReturn
- type StmtStore
- type StmtSubgroupBallot
- type StmtSubgroupCollectiveOperation
- type StmtSubgroupGather
- type StmtSwitch
- type StmtWorkGroupUniformLoad
- type StorageAccess
- type StorageFormat
- type StructMember
- type StructType
- type SubgroupOperation
- type SwitchCase
- type SwitchValue
- type SwitchValueDefault
- type SwitchValueI32
- type SwitchValueU32
- type SwizzleComponent
- type Type
- type TypeHandle
- type TypeInner
- type TypeLayout
- type TypeResolution
- type UnaryOperator
- type ValuePointerType
- type VectorSize
- type VectorType
Constants ¶
This section is empty.
Variables ¶
var ErrUnresolvedOverride = errors.New("overrides should not be present at this stage")
ErrUnresolvedOverride is the error of a backend given a module that still uses pipeline-overridable constants (Rust naga's backend Error::Override). Run naga.ProcessOverrides first.
Functions ¶
This section is empty.
Types ¶
type AccelerationStructureType ¶ added in v0.15.0
type AccelerationStructureType struct{}
AccelerationStructureType represents an opaque acceleration structure for ray tracing. In SPIR-V, this maps to OpTypeAccelerationStructureKHR.
type AddressSpace ¶
type AddressSpace uint8
AddressSpace represents memory address spaces. Mirrors Rust naga's AddressSpace, in the same order.
const ( SpaceFunction AddressSpace = iota SpacePrivate SpaceWorkGroup SpaceUniform SpaceStorage SpaceHandle // SpaceImmediate is immediate data, WGSL var<immediate> (the WebGPU // immediate-data feature; Vulkan push constants). It was spelled // push_constant before gpuweb renamed it; naga has one space for it, as // Rust naga's AddressSpace::Immediate. SpaceImmediate SpaceTaskPayload )
type ArraySize ¶
type ArraySize struct {
Constant *uint32 // element count
Pending *OverrideHandle // count given by this override's value
}
ArraySize represents array size: a constant count, a count given by an override (Rust ArraySize::Pending; only a workgroup array may have one), or neither for a runtime-sized array.
func (ArraySize) IsRuntimeSized ¶ added in v0.20.1
IsRuntimeSized reports an array whose element count is known only at run time (Rust ArraySize::Dynamic); a pending count is not.
func (ArraySize) Resolve ¶ added in v0.20.1
func (s ArraySize) Resolve(m *Module) (IndexableLength, error)
Resolve returns the element count of s (Rust ArraySize::resolve): for a pending count, the value of the override's initializer, which must be a fully evaluated positive integer, as naga.ProcessOverrides leaves it.
type ArrayType ¶
type ArrayType struct {
Base TypeHandle
Size ArraySize
Stride uint32
}
ArrayType represents array types.
type AtomicExchange ¶
type AtomicExchange struct {
Compare *ExpressionHandle
}
AtomicExchange performs atomic exchange. If Compare is set, performs compare-and-exchange operation.
type AtomicExclusiveOr ¶
type AtomicExclusiveOr struct{}
AtomicExclusiveOr performs atomic bitwise XOR.
type AtomicFunction ¶
type AtomicFunction interface {
// contains filtered or unexported methods
}
AtomicFunction represents atomic operations.
type AtomicInclusiveOr ¶
type AtomicInclusiveOr struct{}
AtomicInclusiveOr performs atomic bitwise OR.
type AtomicType ¶ added in v0.4.0
type AtomicType struct {
Scalar ScalarType
}
AtomicType represents atomic types for thread-safe operations.
type BarrierFlags ¶
type BarrierFlags uint32
BarrierFlags represents memory barrier flags using bitflags pattern.
const ( // BarrierStorage affects all Storage address space accesses. BarrierStorage BarrierFlags = 1 << 0 // BarrierWorkGroup affects all WorkGroup address space accesses. BarrierWorkGroup BarrierFlags = 1 << 1 // BarrierSubGroup synchronizes execution across invocations within a subgroup. BarrierSubGroup BarrierFlags = 1 << 2 // BarrierTexture synchronizes texture memory accesses in a workgroup. BarrierTexture BarrierFlags = 1 << 3 )
type BinaryOperator ¶
type BinaryOperator uint8
BinaryOperator represents binary operations.
const ( // Arithmetic operations BinaryAdd BinaryOperator = iota // Addition BinarySubtract // Subtraction BinaryMultiply // Multiplication BinaryDivide // Division BinaryModulo // Modulo (remainder) // Comparison operations BinaryEqual // Equal (==) BinaryNotEqual // Not equal (!=) BinaryLess // Less than (<) BinaryLessEqual // Less than or equal (<=) BinaryGreater // Greater than (>) BinaryGreaterEqual // Greater than or equal (>=) // Bitwise operations BinaryAnd // Bitwise AND BinaryExclusiveOr // Bitwise XOR BinaryInclusiveOr // Bitwise OR // Logical operations BinaryLogicalAnd // Logical AND (&&) BinaryLogicalOr // Logical OR (||) // Shift operations BinaryShiftLeft // Left shift (<<) BinaryShiftRight // Right shift (>>) - arithmetic for signed, logical for unsigned )
type Binding ¶
type Binding interface {
// contains filtered or unexported methods
}
Binding represents shader bindings.
type BindingArrayType ¶ added in v0.14.0
type BindingArrayType struct {
Base TypeHandle
Size *uint32 // nil for unbounded
}
BindingArrayType represents a binding array type (binding_array<T, N>). In SPIR-V, this maps to an array of uniform resources (textures, samplers).
type Block ¶
type Block []Statement
Block represents a sequence of statements executed in order. This is a simplified version without span tracking (spans will be added later if needed).
type BuiltinBinding ¶
type BuiltinBinding struct {
Builtin BuiltinValue
Invariant bool // only meaningful for Position built-in
}
BuiltinBinding represents a built-in binding.
type BuiltinValue ¶
type BuiltinValue uint8
BuiltinValue represents built-in values.
const ( BuiltinPosition BuiltinValue = iota BuiltinVertexIndex BuiltinInstanceIndex BuiltinFrontFacing BuiltinFragDepth BuiltinSampleIndex BuiltinSampleMask BuiltinLocalInvocationID BuiltinLocalInvocationIndex BuiltinGlobalInvocationID BuiltinWorkGroupID BuiltinNumWorkGroups BuiltinNumSubgroups BuiltinSubgroupID BuiltinSubgroupSize BuiltinSubgroupInvocationID BuiltinBarycentric BuiltinViewIndex BuiltinPrimitiveIndex BuiltinPointSize BuiltinMeshTaskSize BuiltinCullPrimitive BuiltinPointIndex BuiltinLineIndices BuiltinTriangleIndices BuiltinVertexCount BuiltinVertices BuiltinPrimitiveCount BuiltinPrimitives BuiltinClipDistances // BuiltinDrawIndex is the draw index of a multi-draw (WGSL draw_index, // Rust naga's BuiltIn::DrawIndex). BuiltinDrawIndex // BuiltinBarycentricNoPerspective is the barycentric coordinates without // perspective correction (WGSL barycentric_no_perspective, Rust naga's // Barycentric { perspective: false }); BuiltinBarycentric is the // perspective-correct one. BuiltinBarycentricNoPerspective )
type CollectiveOperation ¶ added in v0.15.0
type CollectiveOperation uint8
CollectiveOperation represents how subgroup results are combined.
const ( CollectiveReduce CollectiveOperation = iota // Reduce across all invocations CollectiveInclusiveScan // Inclusive prefix scan CollectiveExclusiveScan // Exclusive prefix scan )
type ConservativeDepth ¶ added in v0.15.0
type ConservativeDepth uint8
ConservativeDepth specifies how the depth value may be modified.
const ( // ConservativeDepthUnchanged means the depth value will not be modified. ConservativeDepthUnchanged ConservativeDepth = iota // ConservativeDepthGreaterEqual means the depth value may be increased. ConservativeDepthGreaterEqual // ConservativeDepthLessEqual means the depth value may be decreased. ConservativeDepthLessEqual )
type Constant ¶
type Constant struct {
// Name is the constant's name; empty for an unnamed constant.
Name string
// Type is the constant's type.
Type TypeHandle
// Init is the constant's value: a handle into Module.GlobalExpressions,
// never into a function's expression arena.
Init ExpressionHandle
}
Constant is a module-scope constant, Rust naga's Constant { name, ty, init }. Its value is its Init expression and nothing else: every reader takes it from Module.GlobalExpressions[Init]. A constant of an abstract type (AbstractInt, AbstractFloat, or a vector, matrix or array of them) comes from a WGSL `const` without a concrete type; compaction removes it before the module reaches a backend.
type DerivativeAxis ¶
type DerivativeAxis uint8
DerivativeAxis specifies the axis for derivative computation.
const ( DerivativeX DerivativeAxis = iota // Partial derivative with respect to X DerivativeY // Partial derivative with respect to Y DerivativeWidth // Sum of absolute derivatives (fwidth) )
type DerivativeControl ¶
type DerivativeControl uint8
DerivativeControl specifies the precision hint for derivative computation.
const ( DerivativeCoarse DerivativeControl = iota // Coarse precision DerivativeFine // Fine precision DerivativeNone // No specific precision )
type EarlyDepthAllow ¶ added in v0.21.0
type EarlyDepthAllow struct {
Conservative ConservativeDepth
}
EarlyDepthAllow allows an additional depth test before fragment shading, and says how the shader may change the depth (SPIR-V DepthGreater, DepthLess, DepthUnchanged; GLSL layout(depth_*) out float gl_FragDepth). WGSL @early_depth_test(greater_equal | less_equal | unchanged).
type EarlyDepthForce ¶ added in v0.21.0
type EarlyDepthForce struct{}
EarlyDepthForce requires the depth and stencil tests before fragment shading (SPIR-V EarlyFragmentTests, GLSL layout(early_fragment_tests)); a discard or a depth write then has no effect. WGSL @early_depth_test(force).
type EarlyDepthTest ¶ added in v0.15.0
type EarlyDepthTest interface {
// contains filtered or unexported methods
}
EarlyDepthTest is Rust naga's EarlyDepthTest: EarlyDepthForce or EarlyDepthAllow. A nil EntryPoint.EarlyDepthTest asks for neither.
type EntryPoint ¶
type EntryPoint struct {
Name string
Stage ShaderStage
Function Function // Inline function (NOT in Module.Functions[])
Workgroup [3]uint32 // For compute/mesh/task shaders
// WorkgroupSizeOverrides holds, per dimension, the global expression of a
// workgroup size given by an override-expression (Rust
// workgroup_size_overrides); nil means the size is Workgroup's. Backends
// need a module processed by naga.ProcessOverrides, where all are nil.
WorkgroupSizeOverrides [3]*ExpressionHandle
EarlyDepthTest EarlyDepthTest // fragment early depth test; nil: none
MeshInfo *MeshStageInfo // For mesh shaders
TaskPayload *GlobalVariableHandle // For mesh/task shaders referencing task payload variable
}
EntryPoint represents a shader entry point. The Function is stored inline (not via FunctionHandle) because Rust naga keeps entry-point functions separate from Module.functions[].
type ExprAccess ¶
type ExprAccess struct {
Base ExpressionHandle
Index ExpressionHandle
}
ExprAccess performs array/vector/matrix access with a computed index. The index operand must be an integer type (signed or unsigned).
type ExprAccessIndex ¶
type ExprAccessIndex struct {
Base ExpressionHandle
Index uint32
}
ExprAccessIndex performs access with a compile-time constant index. Can access arrays, vectors, matrices, and struct fields.
type ExprArrayLength ¶
type ExprArrayLength struct {
Array ExpressionHandle
}
ExprArrayLength gets the length of a runtime-sized array. The expression must resolve to a pointer to an array with dynamic size.
type ExprAs ¶
type ExprAs struct {
Expr ExpressionHandle
Kind ScalarKind
Convert *uint8 // If set, convert to this byte width; otherwise bitcast
}
ExprAs performs a type cast or conversion.
type ExprAtomicResult ¶ added in v0.4.0
type ExprAtomicResult struct {
Ty TypeHandle
Comparison bool
}
ExprAtomicResult represents the result of an atomic operation. This is created by StmtAtomic and holds the previous value. For CompareExchange, Comparison=true and Ty is the result struct type. For other atomics, Comparison=false and Ty is the scalar type.
type ExprBinary ¶
type ExprBinary struct {
Op BinaryOperator
Left ExpressionHandle
Right ExpressionHandle
}
ExprBinary applies a binary operator to two expressions.
type ExprCallResult ¶
type ExprCallResult struct {
Function FunctionHandle
}
ExprCallResult represents the result of a function call.
type ExprCompose ¶
type ExprCompose struct {
Type TypeHandle
Components []ExpressionHandle
}
ExprCompose constructs a composite value (vector, matrix, array, or struct).
type ExprConstant ¶
type ExprConstant struct {
Constant ConstantHandle
}
ExprConstant references a module-scope constant.
type ExprDerivative ¶
type ExprDerivative struct {
Axis DerivativeAxis
Control DerivativeControl
Expr ExpressionHandle
}
ExprDerivative computes the derivative of an expression.
type ExprFunctionArgument ¶
type ExprFunctionArgument struct {
Index uint32
}
ExprFunctionArgument references a function parameter by its index.
type ExprGlobalVariable ¶
type ExprGlobalVariable struct {
Variable GlobalVariableHandle
}
ExprGlobalVariable references a global variable. For handle address space, produces the variable's value directly. For other address spaces, produces a pointer to the variable.
type ExprImageLoad ¶
type ExprImageLoad struct {
Image ExpressionHandle
Coordinate ExpressionHandle
ArrayIndex *ExpressionHandle
Sample *ExpressionHandle // For multisampled images
Level *ExpressionHandle // For mipmapped images
}
ExprImageLoad loads a texel from an image.
type ExprImageQuery ¶
type ExprImageQuery struct {
Image ExpressionHandle
Query ImageQuery
}
ExprImageQuery queries information from an image.
type ExprImageSample ¶
type ExprImageSample struct {
Image ExpressionHandle
Sampler ExpressionHandle
Gather *SwizzleComponent // If set, perform a gather operation
Coordinate ExpressionHandle
ArrayIndex *ExpressionHandle
Offset *ExpressionHandle // Must be a const-expression
Level SampleLevel
DepthRef *ExpressionHandle
ClampToEdge bool // Clamp coordinates to [half_texel, 1 - half_texel]
}
ExprImageSample samples a point from a sampled or depth image.
type ExprLoad ¶
type ExprLoad struct {
Pointer ExpressionHandle
}
ExprLoad loads a value indirectly through a pointer.
type ExprLocalVariable ¶
type ExprLocalVariable struct {
Variable LocalVariableHandle // Index into Function.LocalVars
}
ExprLocalVariable references a local variable. Produces a pointer to the variable's value.
type ExprMath ¶
type ExprMath struct {
Fun MathFunction
Arg ExpressionHandle
Arg1 *ExpressionHandle
Arg2 *ExpressionHandle
Arg3 *ExpressionHandle
}
ExprMath applies a mathematical function.
type ExprOverride ¶ added in v0.15.0
type ExprOverride struct {
// Override is the index into Module.Overrides.
Override OverrideHandle
}
ExprOverride references a pipeline-overridable constant. Used in global_expressions and function expressions for override references. Mirrors Rust naga's Expression::Override(Handle<Override>).
type ExprRayQueryGetIntersection ¶ added in v0.15.0
type ExprRayQueryGetIntersection struct {
Query ExpressionHandle
Committed bool
}
ExprRayQueryGetIntersection returns the intersection found by a ray query. If Committed is true, returns the committed intersection (after Proceed returns false). If Committed is false, returns the candidate intersection (during Proceed).
type ExprRayQueryProceedResult ¶ added in v0.15.0
type ExprRayQueryProceedResult struct{}
ExprRayQueryProceedResult represents the result of a RayQueryProceed statement. The result is a bool indicating whether there are more intersection candidates.
type ExprRelational ¶
type ExprRelational struct {
Fun RelationalFunction
Argument ExpressionHandle
}
ExprRelational applies a relational function.
type ExprSelect ¶
type ExprSelect struct {
Condition ExpressionHandle
Accept ExpressionHandle
Reject ExpressionHandle
}
ExprSelect selects between two values based on a boolean condition. Equivalent to the ternary operator (condition ? accept : reject).
type ExprSplat ¶
type ExprSplat struct {
Size VectorSize
Value ExpressionHandle
}
ExprSplat broadcasts a scalar value to all components of a vector.
type ExprSubgroupBallotResult ¶ added in v0.15.0
type ExprSubgroupBallotResult struct{}
ExprSubgroupBallotResult represents the result of a SubgroupBallot statement. The result type is always vec4<u32>.
type ExprSubgroupOperationResult ¶ added in v0.15.0
type ExprSubgroupOperationResult struct {
Type TypeHandle
}
ExprSubgroupOperationResult represents the result of a SubgroupCollectiveOperation or SubgroupGather statement. The Type field holds the result type.
type ExprSwizzle ¶
type ExprSwizzle struct {
Size VectorSize
Vector ExpressionHandle
Pattern [4]SwizzleComponent
}
ExprSwizzle reorders or duplicates vector components.
type ExprUnary ¶
type ExprUnary struct {
Op UnaryOperator
Expr ExpressionHandle
}
ExprUnary applies a unary operator to an expression.
type ExprWorkGroupUniformLoadResult ¶ added in v0.15.0
type ExprWorkGroupUniformLoadResult struct {
Ty TypeHandle
}
ExprWorkGroupUniformLoadResult represents the result of a workgroup uniform load. Created by StmtWorkGroupUniformLoad, holds the loaded value. Ty is the type of that value: the pointee, or T for an atomic<T> (Rust naga's WorkGroupUniformLoadResult { ty }).
type ExprZeroValue ¶
type ExprZeroValue struct {
Type TypeHandle
}
ExprZeroValue represents a zero-initialized value of a given type.
type Expression ¶
type Expression struct {
Kind ExpressionKind
}
Expression represents an expression in the IR. Expressions follow Single Static Assignment (SSA) form similar to SPIR-V.
func (Expression) NeedsPreEmit ¶ added in v0.21.0
func (e Expression) NeedsPreEmit() bool
NeedsPreEmit reports whether e is evaluated before the function runs and must not be covered by an Emit statement (Rust naga's Expression::needs_pre_emit): a literal, a constant, an override, a zero value, a global or local variable or a function argument.
type ExpressionKind ¶
type ExpressionKind interface {
// contains filtered or unexported methods
}
ExpressionKind represents the different kinds of expressions.
type Function ¶
type Function struct {
Name string
Arguments []FunctionArgument
Result *FunctionResult
LocalVars []LocalVariable
Expressions []Expression
Body Block
// NamedExpressions maps expression handles to user-given names.
// This is used for let bindings and phony assignments (_ = expr).
// Backends use these names when baking (materializing) expressions,
// producing e.g. "float a = ..." instead of "float _e3 = ...".
// Matches Rust naga's Function::named_expressions.
NamedExpressions map[ExpressionHandle]string
}
Function represents a function definition.
type FunctionArgument ¶
type FunctionArgument struct {
Name string
Type TypeHandle
Binding *Binding
}
FunctionArgument represents a function argument.
type FunctionResult ¶
type FunctionResult struct {
Type TypeHandle
Binding *Binding
}
FunctionResult represents a function return type.
type GatherBroadcast ¶ added in v0.15.0
type GatherBroadcast struct {
Index ExpressionHandle
}
GatherBroadcast gathers from the same lane at the given index.
type GatherBroadcastFirst ¶ added in v0.15.0
type GatherBroadcastFirst struct{}
GatherBroadcastFirst gathers from the active lane with the smallest index.
type GatherMode ¶ added in v0.15.0
type GatherMode interface {
// contains filtered or unexported methods
}
GatherMode represents the specific behavior of a SubgroupGather statement.
type GatherQuadBroadcast ¶ added in v0.15.0
type GatherQuadBroadcast struct {
Index ExpressionHandle
}
GatherQuadBroadcast gathers from the same quad lane at the given index.
type GatherQuadSwap ¶ added in v0.15.0
type GatherQuadSwap struct {
Direction QuadDirection
}
GatherQuadSwap gathers from the opposite quad lane along the given direction.
type GatherShuffle ¶ added in v0.15.0
type GatherShuffle struct {
Index ExpressionHandle
}
GatherShuffle gathers from a different lane at the given index.
type GatherShuffleDown ¶ added in v0.15.0
type GatherShuffleDown struct {
Delta ExpressionHandle
}
GatherShuffleDown gathers from the lane plus the given shift.
type GatherShuffleUp ¶ added in v0.15.0
type GatherShuffleUp struct {
Delta ExpressionHandle
}
GatherShuffleUp gathers from the lane minus the given shift.
type GatherShuffleXor ¶ added in v0.15.0
type GatherShuffleXor struct {
Mask ExpressionHandle
}
GatherShuffleXor gathers from the lane xored with the given value.
type GlobalVariable ¶
type GlobalVariable struct {
Name string
Space AddressSpace
Binding *ResourceBinding
Type TypeHandle
Init *ConstantHandle
// InitExpr is an optional handle into Module.GlobalExpressions for the
// init expression. This mirrors Rust naga's GlobalVariable.init field.
// When set, this is the canonical init reference into GlobalExpressions.
InitExpr *ExpressionHandle
// Access is the access of a SpaceStorage variable (Rust naga's
// AddressSpace::Storage { access }): StorageAccessLoad for WGSL read,
// StorageAccessLoad|StorageAccessStore for read_write. The validator
// rejects an empty set on a storage variable and any set on another
// space, where Rust's type has no place for it.
Access StorageAccess
}
GlobalVariable represents a global variable.
type GlobalVariableHandle ¶
type GlobalVariableHandle uint32
Handle types for referencing IR objects
type ImageClass ¶
type ImageClass uint8
ImageClass represents image classification.
const ( ImageClassSampled ImageClass = iota ImageClassDepth ImageClassExternal ImageClassStorage )
type ImageDimension ¶
type ImageDimension uint8
ImageDimension represents image dimensions.
const ( Dim1D ImageDimension = iota Dim2D Dim3D DimCube )
type ImageQuery ¶
type ImageQuery interface {
// contains filtered or unexported methods
}
ImageQuery represents the type of image query.
type ImageQueryNumLayers ¶
type ImageQueryNumLayers struct{}
ImageQueryNumLayers gets the number of array layers.
type ImageQueryNumLevels ¶
type ImageQueryNumLevels struct{}
ImageQueryNumLevels gets the number of mipmap levels.
type ImageQueryNumSamples ¶
type ImageQueryNumSamples struct{}
ImageQueryNumSamples gets the number of samples.
type ImageQuerySize ¶
type ImageQuerySize struct {
Level *ExpressionHandle // If nil, uses base level
}
ImageQuerySize gets the image size at a specified level.
type ImageType ¶
type ImageType struct {
Dim ImageDimension
Arrayed bool
Class ImageClass
Multisampled bool
SampledKind ScalarKind // Kind of values for sampled textures (only valid when Class == ImageClassSampled)
StorageFormat StorageFormat // Format for storage textures (only valid when Class == ImageClassStorage)
StorageAccess StorageAccess // Access mode for storage textures (only valid when Class == ImageClassStorage)
}
ImageType represents image/texture types.
type IndexableLength ¶ added in v0.20.0
type IndexableLength struct {
// Known is the number of elements when it is fixed by the type.
Known uint32
// Dynamic reports a length known only at run time: a runtime-sized
// array or an unbounded binding array.
Dynamic bool
}
IndexableLength is the number of elements of an indexable type, for bounds checks. Mirrors Rust naga's proc::IndexableLength.
type Interpolation ¶
type Interpolation uint8
Interpolation is how a value is interpolated across a primitive: Rust naga's Interpolation, the first word of WGSL's @interpolate.
const ( // InterpolationPerspective is perspective-correct interpolation (WGSL // perspective, GLSL smooth); the default for floats. InterpolationPerspective Interpolation = iota // InterpolationLinear is linear, non-perspective-correct interpolation // (WGSL linear, GLSL noperspective). InterpolationLinear // InterpolationFlat is no interpolation (WGSL flat): the value of one // vertex, chosen by the sampling. InterpolationFlat // InterpolationPerVertex is a fragment input holding the values of the // primitive's three vertices, an array<T, 3> (WGSL per_vertex, which // needs `enable wgpu_per_vertex`). InterpolationPerVertex )
func (Interpolation) String ¶ added in v0.21.0
func (i Interpolation) String() string
String returns Rust's name of the value.
type Layouter ¶ added in v0.21.0
type Layouter struct {
// contains filtered or unexported fields
}
Layouter derives the layout of every type of a module by WGSL's default memory layout rules ("Alignment and Size"), as Rust naga's proc::Layouter. wgpu uses it for the minimum binding size of a buffer binding.
The zero Layouter is ready to use: Update lays out the types of a module and Layout returns the layout of one of them.
func (*Layouter) Layout ¶ added in v0.21.0
func (l *Layouter) Layout(h TypeHandle) TypeLayout
Layout returns the layout of the type h. A handle Update has not laid out has size 0 and alignment 1, as an opaque type.
func (*Layouter) Update ¶ added in v0.21.0
Update lays out the types of m that l has no layout for yet: on the first call all of them, on a later call those m's type arena gained since, as Rust's Layouter::update does for a frontend that keeps adding types. A type laid out before is not computed again, so a module whose types changed in place needs a new Layouter.
Unlike Rust's, it lets a type refer to a later one. It fails for a type that refers to a type outside the arena (Rust's InvalidArrayElementType and InvalidStructMemberType) or, through its members, to itself; l is then left as it was.
type Literal ¶
type Literal struct {
Value LiteralValue
}
Literal represents a literal constant value.
func (Literal) Type ¶ added in v0.21.0
func (lit Literal) Type() (TypeResolution, error)
Type returns the type of the literal, always a scalar value (Rust naga's Literal::ty_inner). It fails only for a LiteralValue of no known kind.
type LiteralAbstractFloat ¶
type LiteralAbstractFloat float64
LiteralAbstractFloat represents an abstract float literal.
type LiteralAbstractInt ¶
type LiteralAbstractInt int64
LiteralAbstractInt represents an abstract integer literal.
type LiteralF16 ¶ added in v0.15.0
type LiteralF16 float32
LiteralF16 represents a 16-bit float literal stored as float32. The value has been rounded to half precision, but is stored as float32 for ease of use. Backends should emit with the appropriate f16 suffix.
type LiteralF32 ¶
type LiteralF32 float32
LiteralF32 represents a 32-bit float literal (may not be NaN or infinity).
type LiteralF64 ¶
type LiteralF64 float64
LiteralF64 represents a 64-bit float literal (may not be NaN or infinity).
type LiteralValue ¶
type LiteralValue interface {
// contains filtered or unexported methods
}
LiteralValue represents the value of a literal.
type LocalVariable ¶
type LocalVariable struct {
Name string
Type TypeHandle
Init *ExpressionHandle
}
LocalVariable represents a function-local variable.
type LocalVariableHandle ¶ added in v0.21.0
type LocalVariableHandle uint32
LocalVariableHandle indexes Function.LocalVars (Rust's Handle<LocalVariable>).
type LocationBinding ¶
type LocationBinding struct {
Location uint32
// Interpolation is Rust's interpolation: Option<Interpolation>; nil is
// None.
Interpolation *Interpolation
// Sampling is Rust's sampling: Option<Sampling>; nil is None, as in
// @interpolate(flat) or @interpolate(linear).
Sampling *Sampling
// BlendSrc is the dual-source blending index (@blend_src attribute).
// Nil when not using dual-source blending.
BlendSrc *uint32
// PerPrimitive is Rust's per_primitive (@per_primitive, mesh shaders):
// the value is per primitive, not interpolated. It is set on a mesh
// shader's primitive outputs and the fragment inputs that read them.
PerPrimitive bool
}
LocationBinding is a user-defined input or output at a @location: Rust naga's Binding::Location.
The WGSL frontend fills Interpolation and Sampling from @interpolate(kind[, sampling]) and gives a float binding without the attribute Perspective and Center (Rust's apply_default_interpolation). An integer binding keeps no interpolation: on a vertex output or a fragment input it must be written @interpolate(flat), which Validate checks.
type MathFunction ¶
type MathFunction uint8
MathFunction represents built-in mathematical functions.
const ( // Comparison functions MathAbs MathFunction = iota // Absolute value MathMin // Minimum MathMax // Maximum MathClamp // Clamp to range MathSaturate // Clamp to [0, 1] // Trigonometric functions MathCos // Cosine MathCosh // Hyperbolic cosine MathSin // Sine MathSinh // Hyperbolic sine MathTan // Tangent MathTanh // Hyperbolic tangent MathAcos // Arc cosine MathAsin // Arc sine MathAtan // Arc tangent MathAtan2 // Two-argument arc tangent MathAsinh // Inverse hyperbolic sine MathAcosh // Inverse hyperbolic cosine MathAtanh // Inverse hyperbolic tangent // Angle conversion MathRadians // Convert degrees to radians MathDegrees // Convert radians to degrees // Decomposition functions MathCeil // Round up to integer MathFloor // Round down to integer MathRound // Round to nearest integer MathFract // Fractional part MathTrunc // Truncate to integer MathModf // Split into integer and fractional parts MathFrexp // Split into mantissa and exponent MathLdexp // Combine mantissa and exponent // Exponential functions MathExp // Natural exponential (e^x) MathExp2 // Base-2 exponential (2^x) MathLog // Natural logarithm MathLog2 // Base-2 logarithm MathPow // Power (x^y) // Geometric functions MathDot // Dot product MathDot4I8Packed // Dot product of packed 4xi8 MathDot4U8Packed // Dot product of packed 4xu8 MathOuter // Outer product MathCross // Cross product MathDistance // Distance between points MathLength // Vector length MathNormalize // Normalize vector MathFaceForward // Orient vector MathReflect // Reflect vector MathRefract // Refract vector // Computational functions MathSign // Sign of value (-1, 0, or 1) MathFma // Fused multiply-add MathMix // Linear interpolation MathStep // Step function MathSmoothStep // Smooth step function MathSqrt // Square root MathInverseSqrt // Inverse square root MathInverse // Matrix inverse MathTranspose // Matrix transpose MathDeterminant // Matrix determinant MathQuantizeToF16 // Round to 16-bit float precision // Bit manipulation functions MathCountTrailingZeros // Count trailing zero bits MathCountLeadingZeros // Count leading zero bits MathCountOneBits // Count one bits MathReverseBits // Reverse bit order MathExtractBits // Extract bit range MathInsertBits // Insert bit range MathFirstTrailingBit // Find first trailing one bit MathFirstLeadingBit // Find first leading one bit // Data packing functions MathPack4x8snorm // Pack 4 normalized signed floats to bytes MathPack4x8unorm // Pack 4 normalized unsigned floats to bytes MathPack2x16snorm // Pack 2 normalized signed floats to shorts MathPack2x16unorm // Pack 2 normalized unsigned floats to shorts MathPack2x16float // Pack 2 floats to half-precision shorts MathPack4xI8 // Pack 4 signed ints to bytes MathPack4xU8 // Pack 4 unsigned ints to bytes MathPack4xI8Clamp // Pack 4 signed ints to bytes with clamping MathPack4xU8Clamp // Pack 4 unsigned ints to bytes with clamping // Data unpacking functions MathUnpack4x8snorm // Unpack bytes to 4 normalized signed floats MathUnpack4x8unorm // Unpack bytes to 4 normalized unsigned floats MathUnpack2x16snorm // Unpack shorts to 2 normalized signed floats MathUnpack2x16unorm // Unpack shorts to 2 normalized unsigned floats MathUnpack2x16float // Unpack half-precision shorts to 2 floats MathUnpack4xI8 // Unpack bytes to 4 signed ints MathUnpack4xU8 // Unpack bytes to 4 unsigned ints )
type MatrixType ¶
type MatrixType struct {
Columns VectorSize
Rows VectorSize
Scalar ScalarType
}
MatrixType represents matrix types.
type MeshOutputTopology ¶ added in v0.15.0
type MeshOutputTopology uint8
MeshOutputTopology specifies the primitive topology for mesh shader output.
const ( MeshTopologyPoints MeshOutputTopology = iota MeshTopologyLines MeshTopologyTriangles )
type MeshStageInfo ¶ added in v0.15.0
type MeshStageInfo struct {
Topology MeshOutputTopology
MaxVertices uint32
MaxVerticesOverride *ExpressionHandle
MaxPrimitives uint32
MaxPrimitivesOverride *ExpressionHandle
VertexOutputType TypeHandle
PrimitiveOutputType TypeHandle
OutputVariable GlobalVariableHandle
}
MeshStageInfo holds information specific to mesh shader entry points.
type Module ¶
type Module struct {
// Types holds all type definitions. Order matches Rust naga's type arena.
Types []Type
// Constants holds module-scope `const` declarations (NOT overrides).
// Rust naga also separates constants from overrides.
Constants []Constant
// GlobalVariables holds module-scope variables (var<storage>, var<uniform>, etc.)
GlobalVariables []GlobalVariable
// GlobalExpressions holds expressions used at module scope:
// Constant.Init, Override.Init, and GlobalVariable.Init reference into this.
// Mirrors Rust naga's Module.global_expressions arena.
GlobalExpressions []Expression
// Functions holds regular (non-entry-point) function definitions.
// Entry point functions are NOT here — they're inline in EntryPoints[].Function.
Functions []Function
// EntryPoints holds shader entry points with inline Function bodies.
// Unlike Rust naga which uses FunctionHandle into functions arena,
// our entry points contain the full Function struct inline.
EntryPoints []EntryPoint
// Overrides holds pipeline-overridable constants (WGSL `override` declarations).
// Separate from Constants — mirrors Rust naga's Module.overrides arena.
Overrides []Override
// SpecialTypes holds handles to compiler-generated types (external textures, etc.)
SpecialTypes SpecialTypes
}
Module represents a shader module in IR form. Module is the IR representation of a shader module. Structurally verified against Rust naga via TestIRReference (18/18 deep match). See docs/dev/research/IR-DEEP-ANALYSIS.md for Go vs Rust comparison.
Key architectural difference from Rust naga: - Entry point functions are inline in EntryPoint.Function (not in Functions[]) - Go slices instead of Rust Arena<T> — cache-friendly, GC-managed - Const array inlining is 1-step (Rust: 3-step create→evaluate→compact)
func (*Module) Clone ¶ added in v0.20.0
Clone returns a deep copy of the module: no slice, map or pointer in the result is shared with m, so the copy can be changed freely without affecting m. It returns nil for a nil module.
Backends that rewrite a module before emitting it (override processing, inlining, the DXIL passes) work on a clone, so a caller can compile one module many times, for different pipelines or backends.
Matches Rust naga's #[derive(Clone)] on Module, which back::pipeline_constants::process_overrides clones before changing it. Like the derive, the copy is complete by construction: it follows the module's types, so a new IR field or statement kind is copied too.
type Override ¶ added in v0.15.0
type Override struct {
// Name is the identifier name of the override.
Name string
// ID is the numeric @id attribute value, if specified.
// In Rust naga this is Option<u16>; we use *uint16 for nil-ability.
ID *uint16
// Ty is the type of this override (handle into Module.Types).
Ty TypeHandle
// Init is an optional handle into Module.GlobalExpressions that holds the
// default value expression. None if the override has no default.
Init *ExpressionHandle
}
Override represents a pipeline-overridable constant. Mirrors Rust naga's Override struct.
type OverrideHandle ¶ added in v0.15.0
type OverrideHandle uint32
Handle types for referencing IR objects
type PointerType ¶
type PointerType struct {
Base TypeHandle
Space AddressSpace
}
PointerType represents pointer types.
type QuadDirection ¶ added in v0.15.0
type QuadDirection uint8
QuadDirection represents the direction for quad swap operations.
const ( QuadDirectionX QuadDirection = iota // Horizontal swap QuadDirectionY // Vertical swap QuadDirectionDiagonal // Diagonal swap )
type Range ¶
type Range struct {
Start ExpressionHandle
End ExpressionHandle // Exclusive
}
Range represents a range of expression handles for Emit statements.
type RayQueryConfirmIntersection ¶ added in v0.15.0
type RayQueryConfirmIntersection struct{}
RayQueryConfirmIntersection confirms the current candidate intersection. Used during candidate intersection processing (triangles).
type RayQueryFunction ¶
type RayQueryFunction interface {
// contains filtered or unexported methods
}
RayQueryFunction represents ray query operations.
type RayQueryGenerateIntersection ¶ added in v0.15.0
type RayQueryGenerateIntersection struct {
HitT ExpressionHandle // f32 intersection distance
}
RayQueryGenerateIntersection generates a new intersection at the given distance. Used during candidate intersection processing (AABB).
type RayQueryInitialize ¶
type RayQueryInitialize struct {
AccelerationStructure ExpressionHandle
Descriptor ExpressionHandle // Ray descriptor struct
}
RayQueryInitialize initializes a RayQuery object.
type RayQueryProceed ¶
type RayQueryProceed struct {
Result ExpressionHandle // RayQueryProceedResult expression
}
RayQueryProceed starts or continues a ray query. After execution, Result is a Bool indicating if there are more intersection candidates.
type RayQueryType ¶ added in v0.15.0
type RayQueryType struct{}
RayQueryType represents an opaque ray query handle for ray tracing. In SPIR-V, this maps to OpTypeRayQueryKHR.
type RelationalFunction ¶
type RelationalFunction uint8
RelationalFunction represents built-in relational test functions.
const ( RelationalAll RelationalFunction = iota // All components are true RelationalAny // Any component is true RelationalIsNan // Test for NaN RelationalIsInf // Test for infinity )
type ResourceBinding ¶
ResourceBinding represents a resource binding.
type SampleLevel ¶
type SampleLevel interface {
// contains filtered or unexported methods
}
SampleLevel controls the level of detail for texture sampling.
type SampleLevelAuto ¶
type SampleLevelAuto struct{}
SampleLevelAuto uses automatic level of detail.
type SampleLevelBias ¶
type SampleLevelBias struct {
Bias ExpressionHandle
}
SampleLevelBias uses automatic level of detail with a bias.
type SampleLevelExact ¶
type SampleLevelExact struct {
Level ExpressionHandle
}
SampleLevelExact uses an explicit level of detail.
type SampleLevelGradient ¶
type SampleLevelGradient struct {
X ExpressionHandle
Y ExpressionHandle
}
SampleLevelGradient uses explicit gradients for level of detail.
type SamplerType ¶
type SamplerType struct {
Comparison bool
}
SamplerType represents sampler types.
type Sampling ¶ added in v0.21.0
type Sampling uint8
Sampling is where in the pixel a value is interpolated, or which vertex a flat value comes from: Rust naga's Sampling, the second word of WGSL's @interpolate.
const ( // SamplingCenter interpolates at the pixel center (WGSL center). SamplingCenter Sampling = iota // SamplingCentroid interpolates at a point inside the primitive's // covered samples (WGSL centroid). SamplingCentroid // SamplingSample interpolates at each sample, running the fragment // shader per sample (WGSL sample). SamplingSample // SamplingFirst takes a flat value from the primitive's first vertex // (WGSL first). SamplingFirst // SamplingEither takes a flat value from the first or the last vertex, // as the implementation chooses (WGSL either). SamplingEither )
type ScalarKind ¶
type ScalarKind uint8
ScalarKind represents scalar type kinds.
const ( ScalarSint ScalarKind = iota // Signed integer ScalarUint // Unsigned integer ScalarFloat // Floating point ScalarBool // Boolean // Abstract types: used during WGSL lowering, removed by compact before backends. // Matches Rust naga: forbidden by validation, never reach backends. ScalarAbstractInt // WGSL abstract integer (unsuffixed int literals) ScalarAbstractFloat // WGSL abstract float (unsuffixed float literals) )
type ScalarType ¶
type ScalarType struct {
Kind ScalarKind
Width uint8 // in bytes
}
ScalarType represents scalar types.
type ShaderStage ¶
type ShaderStage uint8
ShaderStage represents a shader stage.
const ( StageVertex ShaderStage = iota StageTask StageMesh StageFragment StageCompute )
func (ShaderStage) String ¶ added in v0.21.0
func (s ShaderStage) String() string
String returns the stage's name as WGSL writes its attribute: vertex, task, mesh, fragment or compute.
type SourceLocation ¶ added in v0.21.0
type SourceLocation struct {
// Line is the 1-based line of Start.
Line uint32
// Column is the 1-based byte position of Start in its line.
Column uint32
// Offset is Start, the byte offset in the whole source.
Offset uint32
// Length is End - Start in bytes.
Length uint32
}
SourceLocation is a Span's position in a source text, as Rust naga's SourceLocation.
type Span ¶ added in v0.21.0
Span is a byte range [Start, End) of a shader's source text, as Rust naga's Span. The zero Span is undefined: no source position is known. Frontends, error labels and diagnostics share this one type.
func (Span) IsDefined ¶ added in v0.21.0
IsDefined reports whether s names a source position, as Rust's Span::is_defined: the zero Span does not.
func (Span) Location ¶ added in v0.21.0
func (s Span) Location(source string) SourceLocation
Location returns the line and column of s in source, as Rust's Span::location. A Span past the end of source is clamped to it.
type SpecialTypes ¶ added in v0.15.0
type SpecialTypes struct {
// ExternalTextureParams is the handle of the NagaExternalTextureParams struct type.
ExternalTextureParams *TypeHandle
// ExternalTextureTransferFunction is the handle of the NagaExternalTextureTransferFn struct type.
ExternalTextureTransferFunction *TypeHandle
// RayIntersection is the handle of the RayIntersection struct type used by ray query get intersection expressions. Mirrors Rust naga SpecialTypes ray_intersection.
RayIntersection *TypeHandle
}
SpecialTypes holds handles to compiler-generated types used by backends. Mirrors Rust naga's SpecialTypes struct.
type Statement ¶
type Statement struct {
Kind StatementKind
}
Statement represents a statement in the IR. Statements have side effects and structured control flow, but do not produce values. The function body is represented as a tree of statements, with references to expressions.
type StatementKind ¶
type StatementKind interface {
// contains filtered or unexported methods
}
StatementKind represents the different kinds of statements.
type StmtAtomic ¶
type StmtAtomic struct {
Pointer ExpressionHandle
Fun AtomicFunction
Value ExpressionHandle
Result *ExpressionHandle // AtomicResult expression, required for some operations
}
StmtAtomic performs an atomic operation on a value. The pointer must point to an Atomic type with scalar type I32, U32, I64, U64, or F32. Support for I64/U64/F32 depends on enabled capabilities.
type StmtBlock ¶
type StmtBlock struct {
Block Block
}
StmtBlock contains a sequence of statements to be executed in order.
type StmtBreak ¶
type StmtBreak struct{}
StmtBreak exits the innermost enclosing Loop or Switch statement. May not break out of a Loop from within its continuing block.
type StmtCall ¶
type StmtCall struct {
Function FunctionHandle
Arguments []ExpressionHandle
Result *ExpressionHandle
}
StmtCall calls a function. If Result is set, it must be a CallResult expression. The Call statement acts as a barrier for operations on the result expression.
type StmtContinue ¶
type StmtContinue struct{}
StmtContinue skips to the continuing block of the innermost enclosing Loop. May only appear within the body block of a Loop (not in the continuing block).
type StmtControlBarrier ¶ added in v0.21.0
type StmtControlBarrier struct {
Flags BarrierFlags
}
StmtControlBarrier synchronizes invocations within the work group. The Barrier flags control which memory accesses should be synchronized. If empty, this becomes purely an execution barrier.
type StmtEmit ¶
type StmtEmit struct {
Range Range
}
StmtEmit emits a range of expressions, making them visible to all statements that follow. This is used to mark when expressions should be evaluated in SSA form. See module-level IR documentation for details on expression evaluation timing.
type StmtIf ¶
type StmtIf struct {
Condition ExpressionHandle // Must be a bool expression
Accept Block
Reject Block
}
StmtIf conditionally executes one of two blocks based on the condition value. Naga IR does not have phi instructions. To use values computed in accept or reject blocks after the If statement, store them in a LocalVariable.
type StmtImageAtomic ¶ added in v0.15.0
type StmtImageAtomic struct {
Image ExpressionHandle
Coordinate ExpressionHandle
ArrayIndex *ExpressionHandle
Fun AtomicFunction
Value ExpressionHandle
}
StmtImageAtomic performs an atomic operation on a texel in a storage texture. The image must have atomic access. The coordinate type must match the image dimension.
type StmtImageStore ¶
type StmtImageStore struct {
Image ExpressionHandle
Coordinate ExpressionHandle
ArrayIndex *ExpressionHandle
Value ExpressionHandle
}
StmtImageStore stores a texel value to an image. Storing into multisampled images or images with mipmaps is not supported. This acts as a barrier for operations on the image GlobalVariable.
type StmtKill ¶
type StmtKill struct{}
StmtKill aborts the current shader execution (fragment shader discard). Forbidden within the continuing block of a Loop statement.
type StmtLoop ¶
type StmtLoop struct {
Body Block
Continuing Block
BreakIf *ExpressionHandle // Optional break-if expression evaluated after continuing
}
StmtLoop executes a block repeatedly. Each iteration executes the Body block, followed by the Continuing block. The Continuing block is used for loop increment expressions (like C for-loop's third expression). Break, Return, or Kill statements exit the loop. Continue statements in Body jump to the Continuing block.
type StmtMemoryBarrier ¶ added in v0.21.0
type StmtMemoryBarrier struct {
Flags BarrierFlags
}
StmtMemoryBarrier orders the memory accesses Flags names without synchronizing execution (Rust naga's Statement::MemoryBarrier; SPIR-V OpMemoryBarrier). WGSL has no such statement; the SPIR-V and GLSL frontends produce it.
type StmtRayQuery ¶
type StmtRayQuery struct {
Query ExpressionHandle // Must be a RayQuery type
Fun RayQueryFunction
}
StmtRayQuery performs a ray tracing query operation.
type StmtReturn ¶
type StmtReturn struct {
Value *ExpressionHandle
}
StmtReturn returns from the function, possibly with a value. Forbidden within the continuing block of a Loop statement.
type StmtStore ¶
type StmtStore struct {
Pointer ExpressionHandle
Value ExpressionHandle
}
StmtStore stores a value at an address through a pointer. For Atomic types, the value must be a corresponding scalar. For other types behind pointer<T>, the value is T. This acts as a barrier for operations on the underlying variable.
type StmtSubgroupBallot ¶ added in v0.15.0
type StmtSubgroupBallot struct {
Result ExpressionHandle // SubgroupBallotResult expression
Predicate *ExpressionHandle // Optional boolean predicate
}
StmtSubgroupBallot calculates a bitmask using a boolean from each active thread in the subgroup. The result is a vec4<u32> (SubgroupBallotResult expression).
type StmtSubgroupCollectiveOperation ¶ added in v0.15.0
type StmtSubgroupCollectiveOperation struct {
Op SubgroupOperation // What operation to compute
CollectiveOp CollectiveOperation // How to combine the results
Argument ExpressionHandle // The value to compute over
Result ExpressionHandle // SubgroupOperationResult expression
}
StmtSubgroupCollectiveOperation computes a collective operation across active threads.
type StmtSubgroupGather ¶ added in v0.15.0
type StmtSubgroupGather struct {
Mode GatherMode // Specifies which thread to gather from
Argument ExpressionHandle // The value to broadcast over
Result ExpressionHandle // SubgroupOperationResult expression
}
StmtSubgroupGather gathers a value from another active thread in the subgroup.
type StmtSwitch ¶
type StmtSwitch struct {
Selector ExpressionHandle
Cases []SwitchCase
}
StmtSwitch conditionally executes one of multiple blocks based on the selector value. Each case must have a distinct value, and exactly one must be Default. The Default may appear at any position and covers all values not explicitly listed.
type StmtWorkGroupUniformLoad ¶
type StmtWorkGroupUniformLoad struct {
Pointer ExpressionHandle // Must be Pointer in WorkGroup address space
Result ExpressionHandle // WorkGroupUniformLoadResult expression
}
StmtWorkGroupUniformLoad loads uniformly from a uniform pointer in workgroup address space. Corresponds to WGSL workgroupUniformLoad built-in function with barrier semantics.
type StorageAccess ¶ added in v0.10.0
type StorageAccess uint32
StorageAccess is how a storage buffer (GlobalVariable.Access) or a storage image (ImageType.StorageAccess) may be used: Rust naga's StorageAccess bit set, with its values. WGSL read is StorageAccessLoad, write StorageAccessStore, read_write both, atomic all three. The empty set is "unset": the validator rejects it on a storage buffer or image, as it does StorageFormatUndefined (ADR-010 E2).
const ( // StorageAccessLoad: the resource can be read. StorageAccessLoad StorageAccess = 1 << 0 // StorageAccessStore: the resource can be written. StorageAccessStore StorageAccess = 1 << 1 // StorageAccessAtomic: the resource can be the target of atomic // operations (atomic storage textures). StorageAccessAtomic StorageAccess = 1 << 2 )
func (StorageAccess) Contains ¶ added in v0.21.0
func (a StorageAccess) Contains(b StorageAccess) bool
Contains reports whether every bit of b is in a.
type StorageFormat ¶ added in v0.10.0
type StorageFormat uint8
StorageFormat represents storage texture formats. These are the formats that can be used with storage textures in WGSL.
const ( // StorageFormatUndefined is the zero value: no format is set. The // validator rejects it for a storage image, so it never reaches a // backend. Rust naga has no such member (a Rust enum has no zero); it // keeps an ImageType literal without a format from meaning R8Unorm // (ADR-010 R1, the <Enum>Undefined = 0 convention of webgpu.h). StorageFormatUndefined StorageFormat = iota // 8-bit formats StorageFormatR8Unorm StorageFormatR8Snorm StorageFormatR8Uint StorageFormatR8Sint // 16-bit formats StorageFormatR16Uint StorageFormatR16Sint StorageFormatR16Float StorageFormatRg8Unorm StorageFormatRg8Snorm StorageFormatRg8Uint StorageFormatRg8Sint // 32-bit formats StorageFormatR32Uint StorageFormatR32Sint StorageFormatR32Float StorageFormatRg16Uint StorageFormatRg16Sint StorageFormatRg16Float StorageFormatRgba8Unorm StorageFormatRgba8Snorm StorageFormatRgba8Uint StorageFormatRgba8Sint StorageFormatBgra8Unorm // Packed 32-bit formats StorageFormatRgb10a2Uint StorageFormatRgb10a2Unorm StorageFormatRg11b10Ufloat // 64-bit formats StorageFormatRg32Uint StorageFormatRg32Sint StorageFormatRg32Float StorageFormatRgba16Uint StorageFormatRgba16Sint StorageFormatRgba16Float // 128-bit formats StorageFormatRgba32Uint StorageFormatRgba32Sint StorageFormatRgba32Float // Normalized 16-bit per channel formats StorageFormatR16Unorm StorageFormatR16Snorm StorageFormatRg16Unorm StorageFormatRg16Snorm StorageFormatRgba16Unorm StorageFormatRgba16Snorm // 64-bit storage formats (require Metal 3.1 for atomic textures) StorageFormatR64Uint StorageFormatR64Sint )
func (StorageFormat) IsSnorm ¶ added in v0.17.5
func (f StorageFormat) IsSnorm() bool
IsSnorm returns true for storage formats with signed normalized components (e.g., rgba8snorm, r16snorm). DXIL metadata requires distinguishing SNormF32 (component type 13) from plain F32 (9) for typed UAV resources.
func (StorageFormat) IsUnorm ¶ added in v0.17.5
func (f StorageFormat) IsUnorm() bool
IsUnorm returns true for storage formats with unsigned normalized components (e.g., rgba8unorm, rgb10a2unorm). DXIL metadata requires distinguishing UNormF32 (component type 14) from plain F32 (9) for typed UAV resources.
func (StorageFormat) Scalar ¶ added in v0.16.1
func (f StorageFormat) Scalar() ScalarType
Scalar returns the full ScalarType (kind + width) for this storage format. Width is 8 for R64Uint/R64Sint, 4 for all other formats.
func (StorageFormat) ScalarKind ¶ added in v0.15.0
func (f StorageFormat) ScalarKind() ScalarKind
ScalarKind returns the scalar kind associated with this storage format. Unorm/Snorm/Float formats return ScalarFloat, Uint formats return ScalarUint, Sint formats return ScalarSint.
type StructMember ¶
type StructMember struct {
Name string
Type TypeHandle
Binding *Binding // @builtin(position), @location(0), etc.
Offset uint32
}
StructMember represents a struct member.
type StructType ¶
type StructType struct {
Members []StructMember
Span uint32 // Size in bytes
}
StructType represents struct types.
type SubgroupOperation ¶ added in v0.15.0
type SubgroupOperation uint8
SubgroupOperation represents the kind of subgroup collective operation.
const ( SubgroupOperationAll SubgroupOperation = iota SubgroupOperationAny SubgroupOperationAdd SubgroupOperationMul SubgroupOperationMin SubgroupOperationMax SubgroupOperationAnd SubgroupOperationOr SubgroupOperationXor )
type SwitchCase ¶
type SwitchCase struct {
Value SwitchValue
Body Block
FallThrough bool // If true, execution continues to next case
}
SwitchCase represents a case in a switch statement.
type SwitchValue ¶
type SwitchValue interface {
// contains filtered or unexported methods
}
SwitchValue represents the value that triggers a switch case.
type SwitchValueDefault ¶
type SwitchValueDefault struct{}
SwitchValueDefault represents the default case in a switch statement.
type SwitchValueI32 ¶
type SwitchValueI32 int32
SwitchValueI32 represents a signed 32-bit integer switch value.
type SwitchValueU32 ¶
type SwitchValueU32 uint32
SwitchValueU32 represents an unsigned 32-bit integer switch value.
type SwizzleComponent ¶
type SwizzleComponent uint8
SwizzleComponent represents a single component in a vector swizzle.
const ( SwizzleX SwizzleComponent = 0 SwizzleY SwizzleComponent = 1 SwizzleZ SwizzleComponent = 2 SwizzleW SwizzleComponent = 3 )
type TypeInner ¶
type TypeInner interface {
// contains filtered or unexported methods
}
TypeInner represents the inner type kind.
type TypeLayout ¶ added in v0.21.0
type TypeLayout struct {
// Size is the byte size of the type (Rust TypeInner::try_size): a
// runtime-sized array counts one element, an array whose size is an
// override not evaluated yet counts none, and an opaque type (image,
// sampler, pointer, binding array, ...) has size 0, a pointer too (Rust
// gives a pointer 4).
Size uint32
// Alignment is the byte alignment of the type. An opaque type has
// alignment 1; a binding array has the alignment of its element type
// (Rust gives it 1).
Alignment uint32
}
TypeLayout is the size and alignment of a type in memory, in bytes, as Rust naga's proc::TypeLayout.
type TypeResolution ¶ added in v0.2.0
type TypeResolution struct {
Handle *TypeHandle // If set, references a module type
Value TypeInner // If Handle is nil, this is the inline type
}
TypeResolution represents the resolved type of an expression. It can either reference a type in the module's type arena (Handle) or represent an inline/computed type (Value).
func (TypeResolution) Inner ¶ added in v0.21.0
func (r TypeResolution) Inner(types []Type) TypeInner
Inner returns the type r stands for: the inner type of the arena type it refers to, or its own value (Rust naga's TypeResolution::inner_with). types is the module's type arena; a handle outside it panics.
type UnaryOperator ¶
type UnaryOperator uint8
UnaryOperator represents unary operations.
const ( UnaryNegate UnaryOperator = iota // Arithmetic negation UnaryLogicalNot // Logical not (!) UnaryBitwiseNot // Bitwise not (~) )
type ValuePointerType ¶ added in v0.15.0
type ValuePointerType struct {
Size *VectorSize // nil for pointer-to-scalar, non-nil for pointer-to-vector
Scalar ScalarType
Space AddressSpace
}
ValuePointerType represents a pointer to a scalar or vector value. Unlike PointerType (whose Base is a TypeHandle in the arena), ValuePointerType stores the pointee type inline. This exists only in TypeResolution — never in the type arena. Matches Rust naga's TypeInner::ValuePointer.
Produced by the typifier when accessing components through pointers:
- Pointer<Matrix>[i] → ValuePointerType{Size: &rows, Scalar, Space} (pointer to column vector)
- Pointer<Vector>[i] → ValuePointerType{Size: nil, Scalar, Space} (pointer to scalar)
- ValuePointerType{Size: &s}[i] → ValuePointerType{Size: nil, Scalar, Space} (pointer to element)
type VectorSize ¶
type VectorSize uint8
VectorSize represents vector sizes.
const ( Vec2 VectorSize = 2 Vec3 VectorSize = 3 Vec4 VectorSize = 4 )
type VectorType ¶
type VectorType struct {
Size VectorSize
Scalar ScalarType
}
VectorType represents vector types.