Repository navigation
CrossTL 3.6.0
This page lists every breaking change, addition and improvement in 3.6.0 and 142 of its 184 fixes; GitHub limits release notes to 125,000 characters. The complete list of all 238 entries is in CHANGELOG.md.
Breaking Changes
- WGSL output refuses a function-local array whose size is a constant computed from a specialization constant that CrossGL declares as a module-scope variable, such as
float tmp[doubled];withconstant int count @constant_id(3) = 4;andconstant int doubled = count * 2;, which is how the Metal importer writes an MSL[[function_constant]], withSpecializationConstantError(project.translate.specialization-constant-unsupported), because WGSL takes an override expression as an element count only for avar<workgroup>array. It used to size the array by the constant's default, ignoring the value the host specializes. - The CrossGL parser refuses a token it cannot place with a
SyntaxErrorthat names the token and the construct, at program, shader, stage, structure, member, enumeration, trait andswitchscope and where an expression is expected:struct S { float a junk; float b; };,float v = ;and a structure cut off at the end of the input are refused. It used to skip such tokens one at a time, soSlostb,vtook the value;and the cut-off structure vanished from every target's output, and it truncated a program of more than 10,000 top-level declarations with a printed warning. Empty declarations (;) andstruct S;forward declarations are still accepted. The Rust importer now writestype Name = T;astypedef T Name;, which the parser used to skip, and the Slang importer refusesextern static constandStructuredBuffer<T*>withSlangImportRefused(project.translate.slang-import-unsupported). - The CrossGL parser refuses a malformed
generic<...>structure, enumeration, function or trait declaration, one without its<, cut off at the end of the input or with no declaration after its parameters, withSyntaxError. It used to skip the whole declaration, so it vanished from the program and from every target's output. - The Metal, HLSL and Vulkan GLSL importers refuse a statement or expression they have no CrossGL form for, with
MetalImportRefused(project.translate.metal-import-unsupported),DirectXImportRefused(project.translate.directx-import-unsupported) andSpirvStatementUnsupportedError(project.translate.spirv-statement-unsupportedorproject.translate.spirv-expression-unsupported). They used to write// Unhandled statement type: ...or/* Unhandled expression */in its place, which dropped the statement from every target's output, and the Vulkan GLSL importer's expression fallback printed the Python form of the node. - CrossGL reads
static_assert(condition)andstatic_assert(condition, "message")at shader, stage and structure scope and as a statement, and checks it for every target aftersizeofis folded: a true condition is removed, a false one is refused withStaticAssertionFailedError(project.translate.static-assertion-failed), and one the translator cannot evaluate is refused withStaticAssertionUnresolvedError(project.translate.static-assertion-unresolved). A condition may use integer literals, integerconstdeclarations, enumerators, foldedsizeof, arithmetic, bitwise, shift, comparison and logical operators,!,?:and integer andboolconversions, on values from 0 to 2^31 - 1. A shader-scope assertion used to be skipped unchecked, so a program its source compiler rejects translated, and one in a function body became a call to an undeclaredstatic_assertfunction. - HLSL and Slang input import
SV_VertexIDas the CrossGL built-ingl_RelativeVertexID, which, like Direct3D's value, leaves out the draw's base vertex. HLSL and Slang output write it back asSV_VertexID; GLSL, SPIR-V and Metal output, whose vertex index includes the base vertex, read it asgl_VertexIndex - gl_BaseVertex, and the entry point takes the base vertex as a parameter, reusing one that already carries it. OpenGL'sgl_BaseVertexis zero forglDrawArrays, so GLSL output still readsfirstmore in a non-indexed draw that starts at vertexfirst. WGSL and WebGL output, which cannot read the base vertex, refuse it withRelativeVertexIdUnsupportedError(project.translate.relative-vertex-id-unsupported), and so does every target for a member of a nested structure that carries it.source_options={"zero_base_vertex": True}keeps the old import for a shader whose draws all have a zero base vertex.SV_VertexIDused to import asgl_VertexID, so GLSL, SPIR-V and Metal output read the vertexBaseVertexpositions further on in a draw with a non-zero base vertex, and WGSL and WebGL output translated it the same way (#3894). - HLSL output refuses a
volatileresource, such as a GLSLvolatile buffer, a SPIR-VVolatileblock or a Metalvolatile device T*buffer, and a resource coherent at system scope, such as Metal'scoherent(system), withDirectXLoweringRefused(project.translate.directx-lowering-unsupported); SPIR-V output refusescoherent(system)andcoherent(host)withSpirvLoweringRefused(project.translate.vulkan-lowering-unsupported). HLSL has no volatile resource (DXC rejectsvolatileon a global) andgloballycoherentneither reaches past the device nor stops DXC from merging repeated accesses, and Vulkan'sCoherentreaches the device at most. Both used to drop the qualifier and declare an ordinary resource, so a spin-wait on a flag could compile to an infinite loop (#3902). - HLSL output refuses a call that passes two private pointer views of one local array, at least one of them writable, such as
two(x, x + 1)for a Metalvoid two(thread float* a, thread float* b), withDirectXPrivatePointerParameterError(project.translate.directx-private-pointer-unsupported, reasonaliased-view-backing), as GLSL output already does. Views rooted at one caller parameter are refused the same way, and a call whose views of one array are all read-only still translates. HLSL output passes each view as aninoutcopy of the array, so it used to emit two independent copies, which DXC accepts: the copy written back last overwrote the other view's writes, and a read-only view did not see writes made through the other (#3827). - Output refuses a specialization constant it cannot keep specializable, where it used to freeze the constant at its default value. WGSL output refuses, with
SpecializationConstantError(project.translate.specialization-constant-unsupported), a specialization constant that is not abool,i32,u32,f32orf16scalar, an id above 65535, an array sized by one other than avar<workgroup>array, and aswitchcase selector that reads one; Slang output refuses, with the same error, an array sized by a dependent constant it declares as a static global and a case label that reads one; both refuse two constants with one id and a malformed id. Metal output refuses a specialization constant whose type has no function constant form, such as adouble, withMetalLoweringRefused; it used to lower adoubleone tofloat. HLSL output refuses a compute workgroup size set throughlocal_size_x_id,local_size_y_idorlocal_size_z_idwithSpecializedWorkgroupSizeError(project.translate.workgroup-size-specialization-unsupported), sincenumthreadstakes literals and Direct3D has no specialization constants; it used to write the default size (#3776, #3778, #3795, #3835).
Added
- HLSL output of a compute, mesh or amplification entry whose result depends on a threadgroup size that the source's host chooses at dispatch time, such as a Metal kernel with
threadgroupmemory and nothreadgroup_sizesource option, reads the size from theCROSSGL_WORKGROUP_SIZE_X,_Yand_Zmacros, which the host defines when it compiles the shader (dxc -D CROSSGL_WORKGROUP_SIZE_X=64 ...), as GLSL output does without SPIR-V specialization:[numthreads(CROSSGL_WORKGROUP_SIZE_X, CROSSGL_WORKGROUP_SIZE_Y, CROSSGL_WORKGROUP_SIZE_Z)], behind an#errorthat names the macros when they are missing.gl_WorkGroupSizeand[[threads_per_threadgroup]]read the same macros, and host reflection reports the entry'shost_workgroup_sizewith the macros and no size. Such an entry used to be refused withHostDefinedWorkgroupSizeError, which Slang output still raises. - A CrossGL function marked
@explicit_specialization(primary, types), such asuint8 bump_u8(uint8 x) @explicit_specialization(bump, uint8) { return x + 2; }, replaces the body of the genericbumpforT = uint8, as a C++template <> uint8_t bump<uint8_t>(uint8_t)does. HLSL, GLSL, Metal, SPIR-V, CUDA, HIP, Slang, Mojo and WGSL output call it for every matching instantiation, including one reached only through another generic function and a call on a narrow storage load such asbump(buffer_load(p, id))for aRWStructuredBuffer<uint8> p. Rust output, which keeps native generics, refuses such a program withRustLoweringRefused, and a malformed attribute is aSyntaxError. The Metal importer marks each explicit specialization it imports for the CrossGL and Metal targets this way, soapply<T>callingtwice(x)runs thetwice<float>specialization. Metal output, and every target given the imported CrossGL, used to call a copy of the primary template's body, such astwice_float, instead. - HLSL output reads a specialization constant that has no default, such as an MSL
[[function_constant]]declared without a value, from aCROSSGL_SPECIALIZE_<name>macro that the host defines when it compiles the shader (dxc -D CROSSGL_SPECIALIZE_forward=1), the macro GLSL output already uses:static const bool forward = (bool)(CROSSGL_SPECIALIZE_forward);, after an#errorthat stops compilation when the macro is missing. Host reflection lists such a constant inspecializationConstantswithkind: preprocessor-macro,required: trueand its macro. HLSL output used to refuse it withDirectXSpecializationConstantError(missing-required-value). - Slang output of a compute, mesh or amplification entry whose threadgroup size the source's host chooses at dispatch time, such as a Metal kernel with
threadgroupmemory and nothreadgroup_sizesource option, writes[numthreads(CROSSGL_WORKGROUP_SIZE_X, CROSSGL_WORKGROUP_SIZE_Y, CROSSGL_WORKGROUP_SIZE_Z)]when the host defines those macros (slangc -D CROSSGL_WORKGROUP_SIZE_X=64 ...), as HLSL output does, and otherwise names three[vk::constant_id(N)]constants with the ids GLSL and SPIR-V output use, so a SPIR-V pipeline sets the size throughLocalSizeId. Agl_WorkGroupSizeentry parameter readsWorkgroupSize(). Slang output used to refuse such an entry withHostDefinedWorkgroupSizeError(project.translate.workgroup-size-host-defined). Specialized workgroup sizes are declared once per module; a module with two such entries used to declare the constants twice, which slangc rejects as an ambiguous reference. - SPIR-V, GLSL and WGSL output translate a compute, mesh or task entry whose threadgroup size the host chooses at dispatch time, such as a Metal kernel that reads
threads_per_threadgroupor sizes athreadgrouptile by it. SPIR-V output declares the size as three specialization constants whose ids no other specialization constant of the program uses; GLSL output declareslayout(local_size_x_id = N, ...)underGL_SPIRVorVULKANand otherwise reads theCROSSGL_WORKGROUP_SIZE_X,_Yand_Zmacros, as HLSL output does; WGSL output declares@id(N) override crossgl_workgroup_size_x: u32;and its_yand_zcompanions. They used to refuse such entries withproject.translate.workgroup-size-host-defined. SPIR-V output also gives each entry point of a module its own workgroup size, withLocalSize, orLocalSizeIdwhen the size is specialized, and refuses a helper that readsgl_WorkGroupSizeand is shared by entries of different sizes. - SPIR-V output translates
++,--and+=on a buffer element, a structure member, a vector component or a shared array element, and in a loop condition, through the wrapping step helpers the other targets use, so the result wraps atINT_MAXandINT_MIN. SPIR-V output used to refuse these programs. - GLSL and Metal output lower
RWByteAddressBuffer.InterlockedMinandInterlockedMaxwith anintvalue, which compare as signed integers, to a compare-exchange loop on the buffer'suintword: a word that already holds the value is left unchanged, and the original value converts into anint,uintorfloatreceiver as the signed overload'sout intdoes. The call must be a statement, an assignment statement or a declaration directly in a block; one inside a larger expression, including aforinitializer, and a value that is neitherintnoruintare refused. - The HLSL, Metal, CUDA, HIP, OpenCL and Slang preprocessors define Clang's
__COUNTER__,__INCLUDE_LEVEL__,__BASE_FILE__and, except for HLSL,__FILE_NAME__, count built-in macros as defined for#ifdefanddefined, evaluate__has_includeand__has_include_nextin#ifand#elif, turn_Pragma("...")into a#pragmaline, accept the null directive and%:for#, and read a function-like macro invocation whose arguments continue on later lines or whose(starts the next line, and a block comment spanning lines.__LINE__is the line where the outermost invocation ends, counting backslash-spliced lines, as in Clang.__DATE__,__TIME__and__TIMESTAMP__are refused withPreprocessorError(project.translate.preprocessor-unsupported-builtin), because they would make the output depend on the time of the build. - A
static_assertin a generic structure whose condition depends on the structure's type parameters, such asstatic_assert(sizeof(in_T) <= 16)in a Metal template structure, is not evaluated against the template itself: it is dropped when no live code names the template, checked with the arguments substituted in each specialization the Metal importer writes, and refused withStaticAssertionUnresolvedError(project.translate.static-assertion-unresolved) when live code names the CrossGL generic structure. A condition that names none of the parameters is still evaluated. - GLSL and Metal output lower HLSL
ByteAddressBufferandRWByteAddressBuffertouintstorage buffers: every load, store, size query andInterlocked*member indexes 32-bit words ataddress >> 2, and the HLSL importer readsLoad<T>andStore<T>as bit-cast word accesses. Rasterizer-ordered byte-address buffers, a byte-address buffer inside a structure and a multi-word operand with side effects are refused with a typed diagnostic. Both outputs used to copyRWByteAddressBufferand the importer'sbuffer_load*andbuffer_storecalls, which neither compiler accepts; the importer also dropped the template argument ofLoad<T>andStore<T>, and byte-address atomics were rewritten as if their value were the original-value argument. - SPIR-V output lowers CrossGL
atomicLoadandatomicStoreto relaxedOpAtomicLoadandOpAtomicStore, atDevicescope on storage buffers andWorkgroupscope on workgroup memory, and HLSL output lowersatomicLoadof a byte-address buffer member. SPIR-V output used to refuse both calls as neither a declared function nor a built-in with a SPIR-V lowering, and HLSL output refused the byte-address load. - The GLSL importer reads
GL_KHR_memory_scope_semanticsatomics, such asatomicAdd(mem, data, gl_ScopeDevice, gl_StorageSemanticsBuffer, gl_SemanticsRelaxed),atomicCompSwapwith its two semantics pairs,atomicLoad,atomicStoreandimageAtomic*, as CrossGL's relaxed atomics when every semantics operand isgl_SemanticsRelaxedand the scope is no wider thangl_ScopeDevice. Acquire, release and acquire-release semantics,MakeAvailable,MakeVisible,Volatile,gl_ScopeCrossDevice, non-constant operands,imageAtomicLoadandimageAtomicStoreare refused withScopedAtomicUnsupportedError(project.translate.opengl-import-scoped-atomic-unsupported), and Metal output refuses a buffer-block atomic with extra operands. The operands used to be passed through: OpenGL and HLSL output refused the call's argument count, SPIR-V output reportedgl_ScopeDeviceas an unknown variable and Metal output dropped them. - Metal output accepts an array sized by a specialization constant, directly or through other constants. A uniform or storage block member is laid out from the constant's default size, as
GL_KHR_vulkan_glsllays out such a block, and any other array, such as asharedarray, takes its size from aCROSSGL_SPECIALIZATION_CONSTANT_ID_<id>macro that defaults to the declared value and that the host sets throughMTLCompileOptions.preprocessorMacrosor-D. Metal host reflection lists such a constant with kindpreprocessor-macro, its id, macro name and default. On every target, thelength()of an array sized by constants is its size expression,int(N), so it follows a specialized value; where a local, parameter or member hides a name of that expression at the call, it is refused withArrayLengthUnresolvedError. Metal output used to refuse these arrays; 3.5.0 froze the constant at its default. - A geometry stage that writes several vertex streams translates between GLSL, HLSL and SPIR-V. HLSL input numbers its
PointStreamparameters in order, as DXC does, and GLSL output declares streamk's outputslayout(stream = k)and writesAppend()andRestartStrip()on it asEmitStreamVertex(k)andEndStreamPrimitive(k), with the built-in outputs and the locations the next stage reads on stream 0. HLSL output gives each GLSL streamN, from@stream(N)outputs orEmitStreamVertex(N), its ownGeometryOutputNstructure andinout PointStream<GeometryOutputN> streamNparameter, withEmitVertex()andEndPrimitive()on stream 0. SPIR-V output writesOpEmitStreamVertexandOpEndStreamPrimitivewith theGeometryStreamscapability and aStreamdecoration on every output, and SPIR-V input imports them with@stream(N). Several streams whose output primitive is not points, a built-in output on a stream other than 0, more than four streams and a stream number that is not a constant are refused, withGeometryStreamUnsupportedErrorin GLSL output andHlslGeometryStreamUnsupportedError(project.translate.hlsl-geometry-stream-unsupported) in HLSL output. HLSL output used to refuse a second stream withHlslGeometryStreamUnsupportedError, GLSL output refused severalPointStreamparameters, and SPIR-V output and input refusedEmitStreamVertex. GLSL input also puts an output declared afterlayout(stream = N) out;on streamN; it used to put it on stream 0 (#3853). - A compute stage's
local_size_x_id,local_size_y_idandlocal_size_z_id, as inlayout(local_size_x_id = 0, local_size_x = 64) in;, make that workgroup dimension a specialization constant in SPIR-V, GLSL, Slang and WGSL output: SPIR-V output buildsBuiltIn WorkgroupSizeas anOpSpecConstantCompositeofSpecId-decorated dimensions, GLSL output keeps the ids under its SPIR-V guard, Slang output sizesnumthreadswithvk::constant_idconstants and readsgl_WorkGroupSizeasWorkgroupSize(), and WGSL output sizes the entry point withoverridedeclarations. A duplicate, non-literal or out-of-range id is refused withSpecializedWorkgroupSizeError(project.translate.workgroup-size-specialization-unsupported). The ids used to be dropped, so every target fixed the size at its default and the pipeline's specialization never reached the dispatch (#3835, #3793, #3788, #3791). - CrossGL has
cooperative_matrix_diagonal(value), a cooperative matrix withvalueon its diagonal and zero elsewhere, whose shape comes from the declaration, assignment or return it initializes, as for a fill; a one-argumentCooperativeMatrix<...>(value)constructor means the same, asmat3(s)does, and another number of arguments is aSyntaxError. Metal input readssimdgroup_matrix<T, Cols, Rows>(value)and thesimdgroup_float8x8(value)style spellings as it and Metal output writes it back; GLSL and HLSL output lower it for a registered lane mapping, evaluatingvalueonce, and SPIR-V and the other targets refuse it with their cooperative-matrix errors. Metal input used to turn the constructor into a call to an undefined function, and a one-argumentCooperativeMatrix<...>(value)was copied unchanged into the output. - A cooperative matrix multiply-accumulate takes independent component types for A, B and the accumulator, as Metal's
simdgroup_multiply_accumulate(d, a, b, c)and SPIR-V'sOpCooperativeMatrixMulAddKHRdo, so a kernel withhalfinputs and afloataccumulator translates; the result takes the accumulator's component type, or the destination's when there is one. A plain multiply still needs one component type. The type checker used to refuse such a kernel on every target, Metal to Metal included. - Metal input gives a
simdgroup_matrixthat a kernel only loads, fills, multiplies and stores, with nothread_elements()view, the lane mapping the caller configures for the 32-lane SIMD-group, so GLSL and HLSL output lower the kernel. Such a matrix used to keep an unspecified lane contract, and GLSL and HLSL output refused the kernel even with a mapping configured. A matrix whose contract comes from a view keeps it, and symbolic or unregistered shapes are still refused.
Improved
- WGSL output passes an array element, a structure member, a vector component or swizzle, a storage buffer element or a module-scope variable to an
inoutoroutparameter by copying it into a function-scope temporary before the call and storing it back after the call in parameter order, as GLSL does. An earlier argument that calls a function is bound to aletfirst, an index the call could change is evaluated once, and awhileorforcondition with such a call becomes a loop guard. A call in the right operand of&&or||, a ternary branch, aforupdate or ado-whilecondition, where that order cannot be kept, is refused, and so is a uniform, constant or constant-buffer member passed this way, which WGSL cannot store to. These arguments used to be refused, because a WGSLptr<function, T>parameter can only point at a whole variable. - The Metal importer evaluates
is_scalar,is_vectorandis_arithmeticand their_vforms in a constraint, directly or through a variable template such as PyTorch'sis_scalar_integral_v<T> = is_integral_v<T> && is_scalar_v<T>, asmetal_type_traitsdefines them, and expands a namespace-scope alias template in a type-trait operand, sometal::is_same_v<StrY, Int<1>>withtemplate <int val> using Int = integral_constant<int, val>;is decided. The first used to be refused as an unrecognized SFINAE constraint and the second withMetalTypeTraitError. - The Metal importer ranks an enabled constrained template whose substituted parameters are exactly the argument types above a competing non-template overload that needs a conversion, as C++ does: PyTorch's
simd_sum(T)besidefloat2 simd_sum(float2), called with afloat, calls the template. Such a call used to be refused because the competing overload had unproven precedence. - The Metal importer decides more
static_assertconditions: ones over qualified namespace constants such as::c10::metal::simdgroup_size, integralstatic_cast<T>(v)andT(v)casts,constexpr autolocals and structure members declared in one list such asuint32_t m, n, k;, and, for the Metal and CrossGL targets as for the others, ones over constexpr aggregates such asstatic_assert((complex_t<half>{1.0h, 2.0h} * complex_t<half>{3.0h, 4.0h}).real == -5.0h)in MLX'scomplex.h. A condition that holds is removed and one that fails is refused withMetalStaticAssertionError(assertion-failed). They used to be refused as unresolved, so every Metal or CrossGL translation of a kernel that includescomplex.hfailed withStaticAssertionUnresolvedError. A structure head withalignas(...),[[...]]or__attribute__((...))is read as the structure it declares; it used to be scanned as a structure namedalignas. - The Metal importer types each subscript of a multidimensional array local or parameter, so
shmem[0][tid.x]ofT shmem[N][M]is aT, and types themetal::and::metal::spellings of the SIMD-group built-ins as it types the unqualified ones. A constrained call with such an argument, such asOP::finalize(shmem[0][tid.x], param), used to be refused, becauseshmem[0]was typed as aTandshmem[0][tid.x]was left untyped. - The Metal importer binds a constrained call in an
inlinehelper that no kernel calls to the template C++ selects, and binds a constrained call whose argument types are known only once another call is bound, as inauto a = larger(x, 1.0f); halve(a);. The first used to be left to code generation, whose only remaining candidate could be an explicit specialization for another type, and the second was refused. - The Metal importer inlines more structure members that return a reference into the structure's storage: an accessor beside an overload that takes an extra tag argument, such as
T& frag_at(short i, short j)besidetemplate <bool B> T& frag_at(short i, short j, metal::bool_constant<B>), a member template called with integer constants, such asfrag_at<0, 1>(), and an accessor that forwards to another, such asthread T& at_t(short i, short j) thread { return at(j, i); }, through chains up to eight deep. They used to be refused withMetalStructMethodError(reference-return-identity-unsupported). - The Metal importer declares each concrete
metal::bool_constant<B>,metal::integral_constant<T, v>,metal::true_typeandmetal::false_typethat a source uses as a type as a structure with the samestatic constexpr value, such asmetal_integral_constant_bool_true, sopick(src, metal::bool_constant<true>{})fortemplate <bool B> float pick(..., metal::bool_constant<B>)translates, and gives aconst autoorconstexpr autolocal its initializer's type. Such a tag used to become the undeclared typebool_constant<true_>, which every target refused. - The Metal importer resolves a member type named through an alias of its owner structure, such as
kern::acc_typeortypename kern::acc_typewithusing kern = KH;, in a declaration, in a type-trait operand of a lowered structure method such asmetal::is_same_v<scalar_T, float>, and in a materialized helper, wheretypename IOTraits_float2_float2::scalar_T(0)names the alias's target. It used to write the bare, undeclaredacc_type, refuse the trait withMetalTypeTraitError(operand-unresolved), and keep a functional cast that the Metal parser rejects. - Metal output writes a conditional array extent, such as
threadgroup float scratch[size == 0 ? 1 : size];, as HLSL and GLSL output do. It used to print the expression's AST node and refuse the program withGeneratedAstTextError. - The Metal importer deduces the template arguments that an explicit argument list leaves out from the call's arguments before applying defaults, as C++ does, for the Metal and CrossGL targets as for the others:
offset<false>(ptr, n)fortemplate <bool scaled, typename T> void offset(const device T*& p, int n)bindsTfromptr. Two arguments that deduce different types are refused withMetalTemplateArgumentResolutionError. Such a call used to be refused becauseTwas not supplied. - Project translation of a Metal source for HLSL, GLSL and the other targets without templates deduces the template arguments of a call in a materialized template through a unary sign, a predefined Metal constant or a one-argument math function, as in
erf(-x),exp(-x)andx * M_SQRT1_2_F, and no longer splitsx * -yat the sign. Such programs, such as candle'sunary.metal, used to be refused for a missing template argument. - The Metal importer reads a function template whose result type is a
decltypeof its parameters, written directly, as a trailing return type such asauto f(T a) -> decltype(a + a), or through an alias template such astemplate <class T> using sum_t = decltype(T{} + T{});, and types each call, and anautolocal initialized from one, from the concrete operand types with the usual promotions. Such a definition used to be dropped, leaving calls to an undefined function, andauto b = f(x)was declared asdecltype(x + x). A CrossGL generic function whose result type is still adecltypewhen it is specialized is refused withGenericResultTypeError(project.translate.generic-result-type-unresolved). - The Metal importer binds a call to a user function template named like a Metal SIMD-group or quad function, such as a
simd_shuffle_down(IndexValPair<U>, ...)overload in MLX'sarg_reduce.metal, to the instantiation C++ selects, and refuses a call whose scalar or vector arguments the built-in also accepts, which the Metal compiler reports as ambiguous. Such a template used to shadow the built-in, so its own call to the built-in recursed into itself and was refused withRecursionUnsupportedError. - The Metal importer drops a family of
enable_if-constrained function templates that no call, address-of or explicit specialization names, such aspow(T, U)overloads selected byis_complex_v<T>. It used to import them as duplicate generic CrossGL functions with one signature, which no target accepts and which stopped the typing of the functions after them, so MLX'sgated_delta_update_vjp.metalwas refused withMetalAddressProvenanceError. - The Metal importer keeps a subscript of a value whose type is a template parameter, such as
reg[i]forthread T& reg,m[i / 4][i % 4]orx4[i][k]fordevice const T04* x4, in the generic CrossGL function, and each target types it onceTis substituted. It used to refuse it as an aggregate subscript, as it still does when the structure declares its ownoperator[]. - Metal output proves the address space of a storage pointer view taken of another view, such as
(device const T*)((device const char*)src + off), follows a view's constness through pointer arithmetic, and writes a view that removesconstfrom read-only storage as aconstview when every use only reads through it. Such views used to be refused withPointerReinterpretationError, as in seven ggml kernels. - Slang output lowers
WaveShuffleDown,WaveShuffleUp,WaveShuffleXorandWaveShuffleAndFillUp, which Metalsimd_shuffle_down,simd_shuffle_up,simd_shuffle_xorandsimd_shuffle_and_fill_upimport as, to one helper per operation and type that readsWaveReadLaneAtonce with every lane active; a source lane outside the SIMD-group reads the calling lane, as MSL documents.@gl_SubgroupInvocationIDand@gl_SubgroupSizeentry parameters, from MSLthread_index_in_simdgroupandthreads_per_simdgroup, are read fromWaveGetLaneIndex()andWaveGetLaneCount(). Both used to be refused, which stopped every Metal kernel whose headers define shuffle overloads, such as MLX'sutils.h. - The Metal importer types more arguments of a call to a constrained function template or overload set, so it selects the overload instead of refusing the call because
one or more call argument types could not be inferred: a swizzle of a subscript, call, member access or parenthesized expression, as inmax(m, partials[i].x),load(p).yzor(a * b).w; a call of a source function whose declarations all state one concrete return type, as incast_to<float>(linspace_value(i, v, p[0])); a conditional, as incast_to<float>(u < p ? 1u : 0u); a unary-or+, as inmax(0, -padL); and arithmetic on two different scalar or vector types, typed as the Metal compiler types it, sohalf4 * floatishalf4andint + 1.0isfloat. It used to typehalf * 1.5ashalfwhere Metal givesfloat, which could select the wrong overload. - The Metal importer selects a function template by an
enable_if_t<B, T>ortypename enable_if<B, T>::typereturn type, with or withoutmetal::, as it does by anenable_if_ttemplate parameter, takes a namespace-scopetemplate<>specialization as the body of its template instead of a competing overload, and writes an enabler left in concrete code as the type it names, soenable_if_t<true, float>isfloat. An enabler whose condition is false or not constant is refused withMetalTypeTraitError(project.translate.metal-type-trait-unresolved). A source that declares its ownenable_ifkeeps its meaning. Calls that chose between such overloads used to stop the import. - Metal import of sources with many template instantiations or many reopened namespace blocks is faster: the importer finds the declaration a
receiver.method(...)call sees with one sweep over the call sites instead of a scan per call, and computes a refused call's source location only when it refuses it. A large reduction kernel from the Metal corpus imports in 386 s instead of 461 s, and PyTorch MPSBinaryKernel.metal, which reopensc10::metalabout 500 times, in 62 s instead of 71.5 s. - The Metal importer reads more of the template-heavy MSL in MLX, PyTorch and ggml kernels: adjacent string literals join into one, as in
static_assert(c, "a" "b"); function-pointer template parameters, such asvoid (*load)(device const T *, short, thread U &), bind by name, so explicit template arguments no longer shift by one; matrix types and structures declared throughtypedef struct { ... } name;are operands ofis_sameand the other folded traits; a free operator used in astatic_assertoutside a template is instantiated; a math built-in applied to a member of a value whose type is a template parameter, as inmetal::abs(y.x), takes a dependent result type;auto,auto*andconst auto*locals initialized fromreinterpret_cast<P>(e)or(P)egive template argument deduction the pointer typeP; auniondeclared in a function body is hoisted with the layout metadata of a program-scope union; an unnamed structure or union with declarators, such asunion { uint i; half t[2]; } val;, is named__crossgl_unnamed_<kind>_<n>; integralconstexpr autolocals can size arrays;sizeofof a concrete structure, alias or class template specialization folds; andS a, b, c;declares three variables. Such sources used to stop withMetalParserError(Expected RPAREN, got STRING,Expected union name),MetalTemplateSpecializationError,MetalSourceOverloadResolutionError,MetalBuiltinResultTypeResolutionErrororMetalSourceMaterializationError(missing T). - Translating large Metal sources is faster: AST walks classify values from a per-type table and use an explicit stack, the Metal preprocessor finds a name's declaration by bisection and a local integral constant's binding with one sweep, free-operator candidates come from a cached list, and template materialization looks up structure specializations by their normalized template-id. MLX's
unary.metalto GLSL takes 81 s of CPU instead of 102 s, andsteel_conv.metalto HLSL 199 s instead of 234 s. - Refusals that depend only on a program's entry stages or workgroup sizes come earlier. For a program with more than one entry and no selected
entry_point, HLSL, Slang, GLSL, SPIR-V and WGSL output refuse a kernel whose workgroup size only the host chooses withHostDefinedWorkgroupSizeError(project.translate.workgroup-size-host-defined) right after the CrossGL parse, before the semantics passes and the other kernels' code, and WebGL output refuses a source with no vertex or fragment entry withStageUnsupportedErrorbefore importing it, so before the Metal importer materializes templates. candle'sgemv.metalto HLSL is refused after 19.9 s of CPU instead of 71.1 s, and MLX'ssteel_conv.metalto WebGL after 0.69 s instead of more than 90 s. - OpenGL output proves more storage subscripts in range: a guarded subscript through a rebased storage pointer whose base may lie before the buffer, as in a helper passed
in + size - offset - N, is bounded from the helper's guards, and a subscript such asin[y * stride + i]is bounded through affine relations between locals, as afteruint c = y; y = uint(n - 1 - y);with a guard onc. Such subscripts, as in MLX's reverse scans, used to be refused withproject.translate.opengl-index-type-unsupported(composed pointer index range unproven). - HLSL and GLSL output lower dynamically indexed
bfloatandboollane arrays that share a 32-bit union word, such as MLX'suint_or_packed<T>atomic helpers for bfloat16 and bool scatter, as they lower 8- and 16-bit integer andhalflanes. HLSL output keeps abfloatlane's 16-bit pattern; GLSL output holds it as afloat, so a store rounds to nearest even and quiets a NaN, keeping its sign. Aboollane stores one byte, 0 or 1, and reads back as!= 0. They used to be refused. - Importing large template-heavy Metal modules is faster: struct-scoped alias rules reuse cached regular expressions and are built only for the aliases the source spells, the built-in input and mesh payload passes index each function body once instead of once per entry point, a comparison such as
i < nno longer sends the template-argument search to the end of the module, and fragment and whole-module source analyses are cached apart. A sort module that took 452 s to import takes 94 s, and materializing a constrained partial structure for 8 specializations in a 17 KB module takes 0.40 s instead of 1.21 s. Output is unchanged.
Fixed
- WGSL output types
buffer_load(b, i)andb.Load(i)asb[i], so a generic call such asbump(buffer_load(b, i))is specialized, converts the value thatbuffer_storeand.Storewrite to the buffer's element type, as an assignment does, and declares an 8- or 16-bit integer storage element, as inRWStructuredBuffer<uint8>or Metaldevice uchar*, as one 32-bit word,array<u32>, as SPIR-V output does. A generic function instantiated for an 8- or 16-bit type argument without an explicit specialization is refused withNarrowIntegerUnsupportedError(project.translate.wgsl-narrow-integer-unsupported). The generic call used to be refused because its type argument could not be inferred, and WGSL output stored ani32into anarray<u32>, declared the buffer asarray<uint8>and wrotefn bump_uint8(x: uint8), which naga rejects. - HLSL, GLSL and SPIR-V output of a Metal source select an explicit specialization by type, whichever spelling of an integer scalar the specialization and the call use:
bump(x)for auchar xrunstemplate <> uint8_t bump<uint8_t>(uint8_t), andushortanduint16_t, anduintanduint32_t, match the same way. They used to give the call a helper with a copy of the primary template's body, which computed a different result. - GLSL output writes a 64-bit integer literal that initializes a 32-bit integer, such as
2654435761inuint[3](1, 2654435761, 805459861)oruint x = 3674653429;from a C or Metal source, with the type it initializes when the value fits:2654435761u. It used to write2654435761l, which glslang rejects because GLSL has no implicitint64_ttouintconversion. A literal inside a larger expression, or one that initializes a 64-bit integer, keeps its type. - Metal output passes an argument to a
device,threadgrouporconstantreference parameter, such as a Metaldevice float& vor CrossGLinout device float v, in place. It used to copy the argument into a thread temporary and store it back after the call, which the Metal compiler rejects withcannot bind reference in default address space to object in address space 'device'. - The Metal importer declares
const auto p = data + i;for adevice float* dataasdevice float* p, because theconstqualifies the local pointer, not the storage it points to, so a store throughptranslates. It used to declareconst device float* p, so Metal output refused the store as one through a const-qualified local alias and other compilers rejected it. Aconst auto*local and a pointer intoconstorconstantstorage keep theirconst. - The Metal importer calls a Metal library function where C++ overload resolution selects it over a source function of the same name: after
using metal::max;beside a sourcebfloat max(bfloat, bfloat),max(h0, h1)onhalfvalues calls the librarymax, and afterusing namespace metal;an exact library overload is preferred to an enabled user template, somax(x, 1.0f)on afloat xcallsmetal::maxbeside a float-onlymaxtemplate. It used to bind the source function in both cases, which on every target converted thehalfoperands tobfloatin the first and ran the template's body in the second. A constrained call in the body of an unconstrained template is bound when that template is instantiated, a call whose constrained candidates are all disabled and whose library function lookup cannot see is refused instead of calling the library function, andreturn ::max(...)is no longer written asreturn::max(...). - Metal output places the
[[id(n)]]of an argument buffer's array member after the member's name, as indevice float* params [[id(0)]][4];. It used to writedevice float* params[4] [[id(0)]];, which the Metal compiler rejects with'id' attribute cannot be applied to types. - HLSL output types a predefined Metal constant that no local shadows, such as
M_SQRT1_2_F, as its own scalar type, sox * M_SQRT1_2_Ffor afloat16 xis afloatproduct. It used to give the product the type ofxand pass it through the binary16 widening helper, which DXC rejects. - HLSL, GLSL and the other targets without templates drop an explicit specialization of a Metal function template, such as
template <> void f<float>(...), that nothing names once project translation has made a concrete copy of every call and removed the primary template. It used to stay in the output as a separate function, such asf_u3cfloat_u3e, whose body called the removed generic helpers by their template names, which DXC rejects, as in MLX'sgated_delta_update_vjp.metal. - The Metal importer applies a structure's converting constructor wherever C++ copy-initializes an object of that structure from a value of another type, not only in a declaration or a
return: in an assignment such asc = vor*p = v, a stored buffer element such asout[i] = vorout[i] = inv ? float2(x, -y) : v, and a value orconstreference argument of a user function, structure method or overloaded operator, and a call whose only candidate needs such a conversion binds to it. The value used to reach every target unconverted, so, for example, DXC rejected MLX'sfft.metal. An assignment that would run the structure's ownoperator=instead is refused withMetalAssignmentOperatorError(project.translate.metal-assignment-operator-unrepresentable). - The Metal importer resolves a member alias of a structure template through the most specialized matching partial specialization, so
typename tr<device half*>::typeusestemplate <typename T> struct tr<device T*>. It used to read the primary template's alias, such asfloatfor a primaryusing type = float;, on every target. A choice it cannot decide where the type is named, such as a partial specialization constrained withenable_if_tor two matches neither of which is more specialized, is refused withMetalStructAliasResolutionError. - The Metal importer binds a
device const T*buffer that a function stores through after castingconstaway as a writable buffer, aRWStructuredBufferin HLSL output, converts the result of an atomic such asatomic_fetch_add_expliciton anatomic_intwhen it initializes or is stored into another integer type, as inuint x = atomic_fetch_add_explicit(...), and imports a C compound literal such as(float4x4){c0, c1, c2, c3}or(Pair){1.5f, 2}as a braced initialization. It used to bind such a buffer as a read-onlyStructuredBuffer, to refuse the atomic result with an untypedValueError, and to write the compound literal as a constructor call with an initializer-list argument that no generator can lower. HLSL output keeps a buffer's view through a pointer cast that only removesconst, and refuses a storage pointer alias it cannot lower withDirectXResourcePointerAliasError(project.translate.directx-resource-pointer-alias-unsupported) instead of an untypedValueError. - HLSL output samples at level 0 in a compute stage: an implicit-LOD sample that a compute entry reaches, directly or through a helper, is written as
t.SampleLevel(s, uv, 0.0), as SPIR-V output already samples the base level there. It used to writet.Sample(s, uv), which DXC accepts in a compute shader only for Shader Model 6.6 with a derivative-capable thread-group shape. - The Metal importer reads a
static constexprdata member through a plain object, such ast.value,h.inner.count,h.many[1].countorp->count, as the member's constant, as it readsT::value. It used to read it as a field, which HLSL output then read from a structure that keeps no storage for static members. An object expression with side effects, such astags[count++].bias, keeps its lowering. - Slang output writes CrossGL
as_type<T>(x)asbit_cast<T>(x)and a Metalconstant T& x [[buffer(n)]]entry argument asConstantBuffer<T> x, and refuses any other reference entry parameter withSlangLoweringRefused. It used to copyas_type<T>(x)unchanged and write the argument asT &x, which slangc rejects. A wave result whose type has the shape its use expects is converted, as inbool(WaveReadLaneAt(uint(b), lane)). - Slang output refuses
bfloat16, its vectors and the MSLbfloatandbfloatNspellings withSlangLoweringRefused, naming each type, because Slang has no bfloat16 type andhalforfloatwould change its range, precision and size. It used to copy the type names, as inRWStructuredBuffer<bfloat16>, which slangc rejects as undefined identifiers. - Slang output declares a function-local
threadgrouparray of a Metal kernel or helper asstatic groupshared, writesbuffer_storeto aRWStructuredBufferasbuf[i] = v, and accepts scalar anduint2SV_GroupThreadIDandSV_GroupIDentry parameters, as it acceptsSV_DispatchThreadID. It used to write the local asgroupshared, which slangc rejects (E31201), and the store asbuf.Store(i, v), which slangc rejects because structured buffers have noStoremethod (E30027). A groupshared local with an initializer and a threadgroup pointer local, which used to be written asgroupshared float* p, are refused withSlangLoweringRefused. - Slang and WGSL output keep a specialization constant that CrossGL declares as a module-scope variable, such as
constant bool x @function_constant(N);, which is how the Metal importer writes an MSL[[function_constant(N)]], specializable:[vk::constant_id(N)] const bool x;in Slang output and@id(N) override x: bool;in WGSL output, with the default when there is one. A module-scope constant computed from one, such asconstant int span = tile * stride + 1;, is declared as one computed from aconst T name @constant_id(N)constant already is. Slang output used to writestatic const bool x;, which slangc rejects (E31225), WGSL outputvar<private> x: bool;, which is always false, and both dropped the id of a constant with a default, as inconst b: f32 = 0.25;, and froze a constant computed from one at its default or wrote a WGSLconstthat reads an override, which naga rejects. - The Metal importer types a call to a built-in SIMD-group function whose arguments match no user overload of that name as the built-in's result: beside MLX's
bfloat simd_prefix_inclusive_sum(bfloat),before + simd_prefix_inclusive_sum(n)forintvalues stays integer arithmetic. It used to take the user overload'sbfloattype and convertbeforetobfloat, which on every target rounded values above 256 and left row tiles unwritten in MLX's sortedgather_mm_rhsandgather_qmm_rhskernels. - The HLSL importer keeps an expression statement whose root is a conditional, an element or member access or a cast, such as
c ? bump() : bump();ordata[i++];, asexpr;, and drops a literal statement such as1;. It used to write// Unhandled statement type: TernaryOpNodein place of such a statement, so its calls and side effects were lost. - The Metal importer writes the
halfandbfloatpredefined constants,HALF_MAX,HALF_MIN,HALF_EPSILON,MAXHALF, theM_*_Hconstants,BFLT_MAX,BFLT_MIN,BFLT_EPSILONand theM_*_BFconstants, as conversions of their exact values, such asfloat16(3.140625f)forM_PI_H, and the integer limits such asHALF_DIGandBFLT_MAX_EXPasintliterals. It used to keep the names, which HLSL and GLSL output left undeclared. Predefined constants,FLT_MINandM_PI_Fincluded, also type the arguments of constrained calls, somax(result, FLT_MIN)is no longer refused. - Metal output stores back a buffer element, threadgroup value or vector component passed to an
inoutoroutparameter before areturnand before the rest of the statement reads it:return f(tile[i]);becomes a local, the store back and areturnof the local, and intile[l] = bump(tile[l]);,v.y = bump(v.y) + 1;orivec2(bump(v.y), v.y)the call is evaluated into a local whose store back runs before the statement reads it. It used to refuse such a return, writereturn bump(tmp); tile[i] = tmp;for a tail expression, losing the write, and run the assignment before the store back or read the stale value. A wrapping compound assignment lowered tot = asint(asuint(t) + asuint(v))evaluatesvfirst whenvmay writet, as inv.y += bump(v.y), as glslang, Mesa and DXC do; it used to readtfirst, so Metal, HLSL and SPIR-V output gave different results. - WGSL output declares a storage buffer element, structure member or workgroup variable that the program uses atomically, and a CrossGL
atomic<T>oratomic_uint, asatomic<i32>oratomic<u32>, passes it to the atomic built-ins by pointer, as inatomicAdd(&data[i], v), and writes plain reads and stores of it,++and--included, asatomicLoadandatomicStore. It used to writeatomicAdd(data[i], v)on a plainarray<i32>, which naga rejects.atomicCompSwapandatomicCompareExchangebecome a retry loop aroundatomicCompareExchangeWeak, which may fail spuriously. A float atomic, an atomic on read-only or uniform storage, a copy of a structure that holds atomics, an atomic local, an atomicinoutargument and a compare-exchange inside a conditional,&&,||, ado-whilecondition or aforupdate are refused withWGSLAtomicLoweringError. - WGSL output declares an entry point's function-scope
threadgroup,workgroup,sharedorgroupsharedvariable, such as a Metalthreadgroup float tile[256];, as a module-scopevar<workgroup>and renames the entry's uses if the name is taken. It used to declare it as a functionvar, so every invocation worked on its own copy of the tile. Such a variable in a helper, with an initializer, or whose type names a value the entry declares is refused withWGSLWorkgroupLocalError(project.translate.wgsl-workgroup-local-...). - WGSL output writes a conditional whose arms have side effects, such as
int x = c ? bump() : 7;, as anif/elsewhen it is a whole initializer, assigned value, return value or expression statement, nested conditionals included. It used to writeselect(7, bump(), c), which evaluates both arms, sobump()ran even whencwas false. Such a conditional anywhere else, as in1 + (c ? bump() : 0), is refused with aValueError. An expression statement that is not a call or an update, such asdata[0];, is written as the phony assignment_ = data[0];; it used to be written bare, which naga rejects. - The Vulkan GLSL importer keeps an expression statement whose root is a conditional, a member access, an index or a literal, such as
(a > 0) ? bump() : reset();orvalues[0];. It used to write// Unhandled statement type: TernaryOpNodein its place, so both calls were lost. - WGSL output lowers
isnan,isinf,isfiniteandsignbitof anf32scalar or vector to bit tests, component by component:isnan(x)becomes((bitcast<u32>(x) & 0x7fffffffu) > 0x7f800000u). An operand that is notf32, or whose type is unknown, is refused withWGSLFloatClassificationError(project.translate.wgsl-float-classification-unsupported). It used to copy the calls, which naga rejects because WGSL has none of these built-ins. - Output for every target other than Metal lowers Metal's
isordered,isunorderedandisnormal:isunordered(x, y)becomesisnan(x) || isnan(y),isordered(x, y)its negation, andisnormal(x)becomesisfinite(x) && abs(x) >=the smallest normal value, 2^-126 forfloatand 2^-14 forhalf, component by component for a vector, with operands that have side effects evaluated once and in order. A vector operand with side effects, an operand of unknown type and a 64-bit operand are refused withFloatRelationUnsupportedError(project.translate.<target>-metal-relational-function-unsupported). GLSL and HLSL output used to copy the calls, which glslang and DXC reject, and SPIR-V output refused them. - A call of a program function that returns
void, used as a value, as infloat y = f() + 1.0;forvoid f(), is refused on every target withVoidValueError(project.translate.<target>-void-value); SPIR-V output used to emit an instruction on avoidoperand, which spirv-val rejects. A cast tovoid, CrossGLvoid(e)or HLSL(void)e;, is written as the statemente;, or dropped whenehas no side effects, avoidconditional statement as anif/else, and a cast in aforheader or a non-last comma operand loses the cast; one left anywhere else is refused withVoidCastError(project.translate.<target>-void-cast) except on Metal. GLSL output used to writevoid(x);, which glslang rejects, HLSL and WGSL output were invalid, SPIR-V output refused the call, and the HLSL importer dropped(void)bump();together with its side effect. SPIR-V output also refuses an operator operand, aswitchselector or afor-inbound it cannot generate; it used to write0,0.0orfalsein its place. - SPIR-V output passes a swizzle of several components, such as
v.xz, as anoutorinoutargument by copying the components into a temporary before the inlined call and storing each one back after it. It used to refuse the call or bind the wrong storage. A storage buffer argument with a side-effecting subscript, such asinc(outBuf.vecs[j++].z), evaluates the subscript once; SPIR-V output used to runj++once per overload candidate it checked and write the wrong element. - Metal output declares a CrossGL stage-block
sharedvariable or an HLSL program-scopegroupsharedvariable that a helper reaches, directly or through other calls, in the entry point and passes it to the helper as athreadgroupreference parameter. The helper used to name an undeclared variable, or the variable was declared at program scope, which the Metal compiler rejects. A call that copies aninoutoroutargument in and out through a temporary, as Metal output does for threadgroup, device and vector-component arguments, evaluates the side effects of earlier arguments before the copy and an index the call can change once, and anif,else if,while,fororswitchheader that holds such a call gets a statement of its own so the copy runs at every evaluation; such a call in ado-whilecondition or aforupdate is refused with aValueError. Headers with such calls used to produce MSL that the compiler rejected withno matching function. - Metal output writes an
inoutoroutargument that is an element of a GLSL buffer block held as bytes back through the block's store form, and a component write to an element of an array of vectors, such asblock.v[i].y = x, as a store of that component. It used to write both through the block'sconst deviceload, which the Metal compiler rejects as not assignable. Such a write to a read-only block is refused. - A
forheader that declares or assigns several variables, or updates several, such asfor (int i = 0, n = 4; i < n; i++, n--)orfor (k = 0, m = 3; k < m; k++), translates from CrossGL and GLSL input with every element of each list, evaluated in order. The CrossGL and GLSL parsers used to fail on these lists or keep only their first element, and SPIR-V output dropped every update but the first. WGSL output writes a list update or one with side effects, and ado-whileloop, as aloopwith acontinuingblock, socontinuestill runs the update or the condition, and ends a value-returning function after such a loop with areturnof a zero value, which WGSL's behaviour analysis requires. - The CrossGL parser reads a braced constructor of a generic type:
vec<T, 2>{x, y}is the constructor callvec<T, 2>(x, y), andPair<float>{1.0, 2.0}an aggregate of typePair<float>. The Metal importer writes the first form for a defaulted template such astemplate <typename IdxT = int> vec<IdxT, 2> f(...), which used to be refused withExpected binding name, got NUMBER, andPair<float>{1.0, 2.0}used to be read asPair < float, which Metal output wrote asint(Pair < float)>{1.0, 2.0}. - CUDA and HIP output keep a module-scope
staticvariable or a stage-private variable per thread: each kernel that reaches it declares it as a local, zero-initialized when it has no initializer, and passes it by reference to the helpers on the way. A private variable that is a resource or a pointer is refused withDevicePrivateGlobalUnsupportedError(project.translate.device-private-global-unsupported). They used to declare it as a host global, which nvcc rejects as undefined in device code. - The Metal importer gives free functions of one name declared in several namespaces, such as
a::fandb::f, distinct program-scope names and binds each call by C++ name lookup, using-directives included. Identical parameter lists used to become duplicate definitions, which every target compiler rejects, and different ones a single overload set, so a call could bind to a better-matching global overload instead of the namespace member C++ selects. User overloads of a Metal library function, such asmetal::simd_shuffle_down(bfloat, ushort)or theldexp(bfloat, int)that MLX'sbf16_math.hdeclares inmetal,metal::fastandmetal::precise, still extend the library function, soldexp(float, int)keeps calling it. - The Metal importer writes a comma-operator statement, such as
a = x, b = y;, as one parenthesized CrossGL comma expression, and resolves array designators,[i] = vand the GNU range form[a ... b] = v, to positional initializer lists, zero-filling the elements left out and sizing an unsized array by its largest index. It used to writea = x , b = y;and copy the designators, neither of which the CrossGL parser reads. A duplicate or out-of-range index, a non-constant index, a range with side effects and a designator chain are refused withMetalImportRefused(project.translate.metal-import-unsupported). - A shader-scope helper that names a stage's declaration, directly or through the functions it calls, is copied into each stage that calls it, and each copy reads its own stage's input structure. The SPIR-V importer writes helpers at shader scope beside the stages' interface variables, so HLSL and Metal output used to print
input.inUVin a helper without aninputparameter, which DXC rejects as an undeclared identifier, SPIR-V output refused the program withUnknown variable inUV, and two stages with same-named helpers both readFragmentInput. - CUDA, HIP, HLSL, Metal, GLSL, GLSL ES, Rust, Slang and WGSL output refuse generated code that contains the printed form of a CrossTL AST node, such as
ConstructorNode(constructor_type=NamedType(...), arguments=2), or a default Python object representation, withGeneratedAstTextError(project.translate.<target>-ast-node-unlowered), which names the node. An emitter with no rule for a node used to print it into the code it returned. - The SPIR-V importer names a geometry stage's
Inputvariable decoratedBuiltIn PrimitiveIdgl_PrimitiveIDInand keepsgl_PrimitiveIDfor theOutputone. Both used to import asgl_PrimitiveID, sogl_PrimitiveID = gl_PrimitiveIDIn;came back asgl_PrimitiveID = gl_PrimitiveID;, which GLSL and SPIR-V output compiled to copy the stage's own output. HLSL output lowers geometry built-ins declared as stage variables, as the SPIR-V importer writes them, toSV_GSInstanceID,SV_PrimitiveIDand output structure members, as it lowers undeclared ones, instead of refusing them as non-array per-vertex inputs, and refuses a geometry or tessellation entry without the HLSL attributes its stage needs withDirectXStageAttributesMissingError(project.translate.directx-stage-attributes-missing) instead of an untypedValueError. - A program-scope constant or a
static_assertwhose initializer calls a function of the program, as MSL and HLSL allow, is evaluated at translation time with the source's rules, the usual arithmetic conversions, modular unsigned and narrowing conversions and binary32 rounding, and the call is replaced by a literal of its return type. GLSL, WGSL and SPIR-V output used to refuse such a constant, and Metal, Slang and CUDA output wrote the call ahead of the function it names, which their compilers reject. A call the evaluator does not run, such as one that overflows a signed integer, divides by zero or callssin, is left for the generators to refuse. - GLSL and WebGL output declare a stage-level vertex
@outputvariable whose type is or holds an integerflat, as they already did for members of stage output structures. The SPIR-V importer writes vertex outputs this way, and they used to be writtenout int cgl_location_0;, which glslang rejects for GLSL ES because an integer vertex output must beflat. - The SPIR-V importer writes a lookup through
OpSampledImageof a separate image and sampler as CrossGL's separate-sampler call, such astexture(image, sampler, uv), also fortextureLod,textureGrad,textureOffset,textureGatherand the comparison lookups, as the HLSL importer writes them, and takes the image back out of the combination fortexelFetchandtextureSize. It used to writetexture(sampler2D(image, sampler), uv), which only Vulkan GLSL reads, so GLSL, HLSL and Metal output failed and SPIR-V output refused the shadow lookups. Every module DXC writes uses separate samplers. - The SPIR-V importer declares a
Privatestorage-class variable as astaticmodule-scope variable, one copy per invocation. It used to declare a plain module-scope variable, which HLSL output treated as read-only (DXC:read-only variable is not assignable), GLSL output as auniformand Metal output as a constant, so a shader that wrote it did not compile. - The SPIR-V importer imports storage images and texel buffers with CrossGL's image types, such as
uimage2D x @r32ui,imageBufferandsamplerBuffer, and anOpAtomic*throughOpImageTexelPointerasimageAtomicAdd,imageAtomicMin,imageAtomicMax,imageAtomicAnd,imageAtomicOr,imageAtomicXor,imageAtomicExchangeorimageAtomicCompSwap, a subtraction, increment or decrement beingimageAtomicAddof the negated value. It used to write HLSL'sRWTexture2D<uint>,RWBufferandBuffer, which Metal and WGSL output do not read, so every SPIR-V storage image failed on those targets. - A call of a reserved SPIR-V operation name that the program does not declare, such as
spirvImageSparseSampleorspirvSparseTexel, which the SPIR-V importer writes for an operation CrossGL cannot express, is refused on every target other than CrossGL withSpirvOperationUnsupportedError(project.translate.<target>-spirv-operation-unsupported), and WGSL output, since WGSL has no texture atomics, refusesimageAtomic*calls withWGSLImageAtomicUnsupportedError(project.translate.wgsl-image-atomic-unsupported). The generators used to copy these calls into their output. - A stage-scope constant,
const,static constor MSLconstantwith an initializer, is declared as a constant on every target. GLSL and HLSL output used to drop the declaration, so DXC rejected its uses as undeclared identifiers, and Slang output declared it as a uniform. One whose initializer reads run-time values becomes a private variable that the entry point assigns first. Slang output writesconstandconstantglobals asstatic const, CUDA and HIP output an initializedconstantasconstand a constant array as__device__ const, and WGSL output aconstglobal asconst; WGSL output used to write avar<private>whose initializer naga rejected when it read another module variable. - The GLSL importer applies a default block layout,
layout(...) uniform;orlayout(...) buffer;, to the blocks declared after it, with later defaults and a block's own qualifiers taking precedence, and passes a block-levelrow_majororcolumn_majorto the block's matrix members and to structure members that name no order of their own. It used to ignore the defaults, so the blocks afterlayout(std140) buffer;were laid out as std430 and a block-levelrow_majorwas lost. A qualifier that cannot be a block default is refused withSyntaxError. - The binding-index, array-extent,
sizeofandstatic_assertevaluators convert to a narrow integer type modulo its width, as MSL and HLSL do, souint8_t(300)is 44, and evaluate constants, conversions andsizeofoperands that name a program-scope type alias through the alias. They used to evaluateuint8_t(300)as 300, so astatic_assertthat overlooked the wrap passed and a binding index written as a narrow conversion bound the wrong slot, and they refused operands that named an alias. A negative result of a signed narrow conversion used as a binding index stays unresolved. - The Metal importer finds a constant declared in one block of a namespace from every later block of the same namespace, as C++ lookup does, and reads multi-word integer types such as
unsigned int,unsigned short intandlong intin namespace-scope constants and static data members. Astatic_assertin a reopened block used to be refused withMetalStaticAssertionErrorbecause it found no value for the constant. - The Metal importer binds namespace-scope variables by C++ name lookup: a qualified reference such as
outer::inner::COUNT,::outer::inner::COUNTor one through a namespace alias names the variable, a variable declared in several namespaces gets a distinct program-scope name built from its namespace path while a global one keeps its name, and an unqualified use is looked up through blocks, enclosing namespaces and using-directives. A qualified reference used to be written as an identifier nothing declared, such asouter_u3a_u3ainner_u3a_u3aCOUNT, and same-named variables of different namespaces were all written asN. An unqualified use that lookup cannot bind to one declaration is refused withMetalNamespaceLookupError(project.translate.metal-namespace-lookup). - The Metal importer gives a program-scope
constant autoorconstant constexpr autoits initializer's type, as it does for a block-scopeauto. It used to writeconstant auto name, which GLSL output refused withOpenGLCompileTimeGlobalErrorand the other generators could not declare. - Metal output parenthesizes a conditional that is the condition of another conditional, so
(a ? b : 0) ? 5 : 6stays as written. It used to be writtena ? b : 0 ? 5 : 6, which groups asa ? b : (0 ? 5 : 6)and gives a different result. Metal output also keeps the parentheses that clang's-Wparentheseswarnings ask for, around&&inside||,&and^inside|,&inside^and a comparison inside&,|or^, so the output compiles under-Werror -Wall(#4048). - The Metal importer keeps a structure's
alignasspecifier, an integral constant oralignas(T), as@metal_alignas(N);sizeofhonours it and a buffer of such structures takes@buffer_layout(metal), sostruct alignas(16) Rec { float a; float b; }has a 16-byte stride in Metal, GLSL, HLSL and SPIR-V output, as in MSL. The importer used to drop the specifier, which gave an 8-byte stride. A specialization of a generic structure that carries an attribute is refused withGenericStructAttributeError(project.translate.generic-struct-attribute) instead of losing the attribute. - HLSL output writes CrossGL's byte-address buffer atomics,
atomicAdd,atomicMin,atomicMax,atomicAnd,atomicOr,atomicXorandatomicExchange(buffer, offset, value)andatomicCompareExchange(buffer, offset, compare, value), as theRWByteAddressBuffer.Interlocked*method when the call is a statement, asInterlockedCompareStorefor a compare-exchange whose result is unused, and through a__crossgl_bab_atomic_<op>_<uint|int>helper that returns the original value when the result is used; anintvalue selects the signedInterlockedMinandInterlockedMax. It used to copy the calls, as inprev = InterlockedAdd(dst, 0, 1), which DXC rejects. SPIR-V output writes them asOpAtomic*on the word atoffset / 4, withOpAtomicSMinandOpAtomicSMaxfor anintvalue, also for theInterlockedMinandInterlockedMaxmethods; it used to refuse the CrossGL forms and compare the methods' values as unsigned. A form that cannot be lowered is refused withByteAddressAtomicUnsupportedError(project.translate.byte-address-atomic-unsupported). - The CrossGL parser keeps every qualifier of a declaration whose
layout(...)follows another qualifier, as GLSL 4.20 allows, at program, shader and stage scope:uniform layout(rgba16f) imageCube img;stays a uniform with thergba16flayout. The qualifier list used to end atlayout, so the declaration lostuniform. - A generic function's specialization takes a name the program does not already declare: with
float pick_float(float a, float b)besidegeneric<T> T pick(T a, T b), thefloatspecialization ispick_float_2. HLSL, GLSL, Metal, CUDA, HIP, Slang, Mojo and SPIR-V output used to emit twopick_floatdefinitions, which their compilers reject. An implicit template call of a Metal source that project translation materializes takes a free name the same way. - HLSL output applies the offset of a buffer pointer alias, such as
device float* first = data + 4;, only to accesses through that alias. It used to look the offset up by the name of the root buffer, sodata[tid]beside the alias readdata.Load(first_offset + tid)and wrotedata[first_offset + tid], and an access through one of two aliases of the same buffer could take the other's offset; DXC compiled the wrong indices without complaint. - Project translation of a Metal source types the arguments of an implicit template call as the Metal compiler does before choosing the template arguments:
g(u + l)foruint uandlong lspecializesgforlongandg(v4 * f)forfloat4. It used to typea + basa, sog(u + l)becameg_uint(uint(int64_t(u) + l)), which truncates, typed a call of an overloaded function by its last definition, sog(f(x))withfloat f(float)andhalf f(half)becameg_half(...), and could take an undeducedautoas a template argument, as inmin<uint, auto>. A call whose argument has no sound type, such asg(f(x))with that overloadedf, is refused withMetalSourceMaterializationError. - GLSL, Slang and HLSL output declare a block marked
@push_constant, such as an HLSL[[vk::push_constant]]cbufferorConstantBuffer<T>, as Vulkan push constants. GLSL output writeslayout(push_constant) uniformwith each member'slayout(offset = N)under#ifdef VULKANand keeps its OpenGL uniform block in the#elsebranch; Slang output writes[[vk::push_constant]] cbufferorConstantBuffer<T>with[[vk::offset(N)]]members and no binding; HLSL output writes[[vk::push_constant]] ConstantBuffer<T>with std430[[vk::offset]]members under#ifdef __spirv__, reading blocks whose arrays or matrices DXC cannot place as 32-bit words, and keeps a constant buffer at the same offsets for Direct3D. A second push-constant block in a stage, an array of blocks, an offset on a structure member and a layout the target cannot express are refused withPushConstantBlockError. All three used to declare an ordinary uniform buffer at binding 0 or a register, which the host never binds, so the program read its constants from an unbound descriptor. The Slang importer reads[[vk::offset(N)]]on acbuffermember as@offset(N). - HLSL output refuses a uniform or push-constant block whose layout its declarations cannot reproduce, such as one with a 16-bit member, with
DirectXBufferLayoutError(project.translate.directx-buffer-layout-unsupported). It used to raise an untypedValueError. - HLSL output moves
halfvalues held ingroupsharedarrays, function-local arrays and the pointer and array parameters into them as bits: such arrays are declared withuint16_telements, a read isasfloat16(element), a write iselement = asuint16(value)and a selection between stored elements selects the bits, so a copy keeps a NaN's bit pattern. Arithmetic and comparisons stay infloat16_t, and a program whose binary16 workgroup and private memory cannot all be rewritten keeps all of it typed. The arrays used to befloat16_t, and the D3D11.3 specification lets every typed 16-bit load, store and selection change a NaN's bits, which WARP does. - HLSL output runs an atomic in the condition of an
if,else if,while,for,do-whileorswitchon agroupsharedvalue or a typed buffer element, such asif (atomicAdd(g, 1u) == 0u)or a spin lock onatomicCompSwap, as anInterlocked*statement before the test, once per evaluation: anelse ifatomic runs only after the earlier conditions fail, and a loop condition's atomic runs on every iteration, including one acontinuestarts. It used to write the atomic inside the condition, which DXC rejects becauseInterlocked*returns the original value through anoutargument. - HLSL output writes
atomicLoad,atomicStore, anatomicExchangewhose result is unused and anatomicAddnested in an expression on agroupsharedvalue asInterlocked*calls, and stores an atomic's result into a GLSL buffer block member through a temporary and aStore. It used to print thegroupsharedcalls under their CrossGL names, and to writeb.Load(...)as the assignment target or theoutargument, which DXC rejects as not assignable. - Metal, HLSL, CUDA and HIP output compute an 8- or 16-bit integer operation of a GLSL or HLSL source at its own width, as GLSL with
GL_EXT_shader_explicit_arithmetic_typesand HLSL with-enable-16bit-typesdo: foruint16_t a, b,a * bis computed asuint16_t(uint(a) * uint(b)), souint((a * b) >> 8)drops the bits above 16 and(a + b) < ais true on overflow. They used to compute in 32 bits, as CrossGL's promotion tointdoes, and HLSL output wroteint(a) * int(b). SPIR-V and WGSL output keep a shift's left operand type, sov << 12for auint16_t vwraps at 16 bits, and SPIR-V output no longer fails on aforheader that declares several 8- or 16-bit variables, such asfor (short i = 0, step = 3; ...). Metal sources keep C promotion. - DirectX, Slang and Metal output read and write the 8- and 16-bit integer and
float16_tmembers of a GLSLbufferoruniformblock at their own size and alignment, asGL_EXT_shader_8bit_storageandGL_EXT_shader_16bit_storagelay them out: afteruint16_t words[2];,words[1]is at byte 2 and the next 4-byte member at byte 4. They used to give each such member 4 bytes, sowords[1]was at byte 4 and the next member at byte 8. DirectX and Slang output load and store 16- and 64-bit components withLoad<T>andStore<T>; a 64-bit integer used to go through the 32-bitLoadandStore, which dropped its high word. Metal output spellsfloat16_t(x)ashalf(x), and a block Slang output cannot lay out is refused withBufferBlockUnsupportedErrorinstead of being written as a comment with a placeholder. - CUDA and HIP output map the named 8- and 16-bit integer vectors that GLSL input imports,
i8vec2tou16vec4, tochar2toushort4, withmake_char2-style constructors and arithmetic helpers, as they mapvec2<i8>, and type a swizzle of a narrow vector by its element, sovec4<i16> t = s.wzyxis ashort4. They used to copyi8vec2unchanged and type the swizzle as anintvector, as inshort4 t = make_int4(...), which nvcc and hipcc reject. - The HLSL and Slang importers keep a storage image's format and texel type: HLSL
[[vk::image_format(F)]]and Slang[format(F)]import as@format(F), and a typed UAV without a format whose texel is not the four-component default, such asRWTexture2D<uint>, imports with the new@texelattribute, asuimage2D @format(unknown) @texel(uint), from which HLSL and Slang output declare the texel type again. An unknown format, and@texelbeside an explicit format, are refused. GLSL output used to declarergba32ffor a[[vk::image_format("rgba8")]]image, an HLSL round trip returnedRWTexture2D<unorm float4>andRWTexture2D<uint>asRWTexture2D<float4>andRWTexture2D<uint4>, and the Slang importer readRWTexture2D<uint>as a floatimage2D. A helper's storage-image parameter takes the type of the images passed to it, so DXC finds its overload; passing images of different texel types to one parameter is refused. - The Slang importer reads a storage texture subscript as an image operation: a read is
imageLoadnarrowed to the element type, a write, compound write, increment or component write isimageStoreof the widened texel, andInterlocked*on a texel isimageAtomic*. Writes CrossGL cannot express are refused. The subscripts used to stay in CrossGL, so GLSL and SPIR-V output refused them and Metal output wrote invalid subscripts. Slang output writes CrossGL atomics ongroupsharedvalues asInterlocked*calls; it used to copy them. - The HLSL, Metal, GLSL, CUDA, HIP, OpenCL and Slang importers expand macros as the C preprocessor does: arguments are replaced before substitution, so
F(F(1))is fully expanded andCAT(v, N)through#define CAT_I(a, b) a##bpastes the replacedN; a function-like name at the end of a replacement is rescanned with the(that follows the invocation; a self-referential macro in an argument is replaced once; and#ifgroups nested in a skipped group are not evaluated. A malformed invocation, such as one with the wrong argument count, an unterminated argument list or an invalid paste, is refused with the shared preprocessor'sMacroErrororPreprocessorError. They used to substitute text, which leftF(F(1))partly unexpanded and pasted the unreplacedN. - A call to a generic function deduces its type parameters from a buffer or array element, a structure member, a typed constant, a shader-scope or stage-scope variable and the result of another generic call on GLSL, HLSL, Metal and SPIR-V output, and a
T*parameter deducesTfrom a buffer argument such asRWStructuredBuffer<X>, keeping the pointer and its address space. Metal and HLSL output used to specialize the caller of a nested generic call with the unsubstituted parameter, as inT twice_T, Metal output called undeclared specializations such astwice_floatfor a global argument, and GLSL and SPIR-V output refused these calls. Metal, HLSL and GLSL output refuse a call to a specialization they did not emit withGenericSpecializationOrderError(project.translate.generic-specialization-uncollected), and the Metal importer accepts atomic load and compare-exchange targets typed by an open generic parameter. - A call that only a built-in accepts goes to the built-in when the source also declares a function of that name and argument count: beside a user
float dot(float x, float y),dot(v, float4(1.0f))stays the librarydot, because a vector argument whose width differs from every user overload's parameter cannot convert. Metal output used to send every two-argumentdotto the renamed user function, as indot_fn(v.x, ...), which the Metal compiler rejects or, with matching widths, truncates to the x component. - A Metal source's vector-scalar arithmetic keeps MSL's types on every target: a scalar that ranks above the vector's component type converts to it, so
h * ffor ahalf3 hand afloat fis ahalf3computed inhalf, andv / ufor anint3 vand auint uis a signed division. The Metal importer writes the conversion into its CrossGL output, as inh * half(f). CrossGL used to apply GLSL's common type, computingfloat3(h) * fand an unsigned division, sohalf3 h = saturate(fmod(f3, x))did not compile in Metal output.fmodand%onhalfvalues use an exactcgl_half_fmodon SPIR-V and WGSL output instead of being refused, and WGSL output writesfmodas%, the truncated remainder; it used to write an undeclaredfmodcall. - The Metal importer spells MSL's names for one scalar type, such as
uint,uint32_tandunsigned int, orulong,uint64_tandsize_t, the same inside template names, somax_value<uint>()reaches the explicit specializationmax_value<uint32_t>; it used to call an undeclaredmax_value_u3cuint_u3e. Metal output passes 8- and 16-bit scalar arguments ofmin,maxandclampin their 32-bit register type, which used to match no overload beside aucharbuffer element. - The Metal importer refuses a type trait, such as
is_same_v<T, U>, that it cannot evaluate in code outside a template withMetalTypeTraitError(project.translate.metal-type-trait-unresolved) for every target. Unless the project pipeline checked static assertions for a target without templates, it used to reach the output as a mangled name, such asis_same_u3csampler_u2c..., that nothing declares. - The Metal importer reads
i < MAX(a, b), whose expansion holds a>inside parentheses, as a comparison: the scan that decides whethername <opens a template argument list skips<and>inside parentheses and brackets. It used to read a template argument list that swallowed the rest of the function. Explicit specializations whose names would collide, such aspick<(N > 2)>andpick<(N < 2)>, ortwice<int>beside a functiontwice_int, take a numbered suffix; they used to share one name. - Metal output tracks read-only locals by block, so a writable local that reuses the name of a
constlocal from an earlier block or loop body can be written. Every store to it used to be refused. - The Metal importer prefers a non-template member function over a member template when the conversions of the parameters they share tie, as C++ does: with both declaring a
uintparameter,scaler.apply(values, lane)for aushort lanecalls the non-templateapply. It used to call the template unless every argument matched the non-template exactly. - The Metal importer resolves an owner's static constant members in a template-id inside a member function unless a parameter, local or member template parameter hides them, keeps the method calls of a member function whose only receivers are its own structure-typed locals, and drops pointee
constfrom a cast toconst threadgroup T*when the destination is notconst. It used to write unresolved names such asTile_float_TM, drop those method calls, and writethreadgroup float* p = (const threadgroup float*)..., which the Metal compiler rejects. - The Metal importer writes a kernel template only through its instantiations; the uninstantiated template used to become an entry point with unbound template parameters. In a project source, a comment before a nested block no longer hides the block's first declaration from template argument deduction, and a generic function's specialization keeps a parameter type that names no type parameter as declared, so a pointer parameter is no longer redeclared as a reference to a pointer.
- The Metal importer declares the specialization of a namespaced function template in that namespace and calls it by its qualified name, such as
::lib::detail::combine_float, so a type alias, alias template or constant declared beside the template is visible in it. It used to declare the specialization at global scope, where Metal output keptreal_torcommon_t<float, float>undeclared. - The Metal importer translates a member of a class template specialization only when the program uses it, as C++ instantiates member definitions. An unused member whose body is ill-formed for the specialization's arguments, such as
scan_implcallingsimd_prefix_inclusive_sumon a structure, used to be translated, so HLSL output refused a valid source withWavePrefixInclusiveSum ... got cplx. - The Metal importer calls a non-template free operator that the source defines at namespace scope, such as
cplx operator+(cplx a, cplx b), wherevera + b, a unary or compound form or a direct call such asoperator>(a, b)selects it. Every target used to apply the built-in operator, silently dropping the definition. - Metal output keeps the index of a
threadgrouporthreadgroup_imageblockentry parameter as[[threadgroup(n)]], which the host passes tosetThreadgroupMemoryLength:atIndex:. It used to drop it, so the compiler numbered the slots in declaration order and slots 0 and 2 became 0 and 1. An index that is not one non-negative integer literal is refused withMetalLoweringRefused. - Metal output converts the value of a texel write to the texture's element type, so a GLSL
imageStoreof anf16vec4to a float image passes afloat4totexture2d<float>::write. It used to pass thehalf4, which the Metal compiler rejects withno matching member function for call to 'write'. - Metal output names the entry parameter of a uniform block whose name is an MSL keyword once lowercased, such as a block
Kernel,kernel_. It used to name itkernel, which the Metal compiler reads as a keyword. - OpenGL output finishes a helper that declares one storage-pointer name in two scopes from different offsets of a parameter; translation used to never finish, as for Apple's
hash_encoder_kernel.metal. A pointer that still refers to itself after a fixed number of passes is givenread_writeaccess. - HLSL and Slang output keep a storage image's texel format. HLSL output declares an 8- or 16-bit normalized format with a
unormorsnormtexel type, so anrgba8image isRWTexture2D<unorm float4>and anrg8_snormoneRWTexture2D<snorm float2>, on globals and on parameters, and adds[[vk::image_format("rgba8")]]under#ifdef __spirv__for every format DXC cannot derive from the texel type; Slang output writes[format("rgba8")]for every explicit format. Both used to declare every float storage image asRWTexture2D<float4>, so anrgba8image lost its normalization and DXC and slangc gave it the SPIR-V formatRgba32f(#3929). - GLSL output keeps the Vulkan descriptor set of a resource whose set is not 0: its layout binding is
CROSSGL_BINDING(set, Vulkan binding, OpenGL binding), a macro defined after the#versionand#extensionlines that expands toset = S, binding = Bwhen glslang compiles for Vulkan and definesVULKAN, and to the planned OpenGLbinding = Notherwise. A set-0 resource keepsbinding = B. GLSL output used to write only the OpenGL binding, soglslang -Vput every resource in set 0 (#3898). - CrossGL input reads a pointer buffer followed by an attribute, such as
buffer float* data @binding(2);, at program or stage scope as a declaration. It used to skip it, so every target read an undeclared buffer. - Metal output declares
struct BuiltInTriangleIntersectionAttributes { float2 barycentrics; }when an HLSL or Slang closest-hit or any-hit stage, a helper or a structure member uses DXR's triangle attributes and the program does not declare them, and the stage's[[visible]]function takes it as an ordinary argument. It used to write the HLSL type name undeclared, which the Metal compiler rejects as an unknown type name (#3917). - Metal input reads a mesh function's output parameter spelled
mesh<V, P, NV, NP, topology::triangle>withoutmetal::, underusing namespace metal, as it reads the qualified spelling. It used to refuse the function withMetalParserError(Expected type, got MESH) (#3885). - Metal output of a vertex stage that reads
gl_InstanceIDcomputes it as[[instance_id]]less[[base_instance]], so it counts from zero as in OpenGL and Direct3D, whilegl_InstanceIndexkeeps[[instance_id]], and Metal input reads[[instance_id]]asgl_InstanceIndex. Slang output readsgl_InstanceIndexasint(gl_InstanceID + gl_BaseInstance), written withSV_InstanceIDandSV_StartInstanceLocation, andgl_VertexIndexasgl_VertexID, in reads and in entry parameters. Metal output used to readgl_InstanceIDfrom[[instance_id]], which includes the draw's base instance, and Slang output copiedgl_InstanceIndexandgl_VertexIndexunchanged, which slangc rejects as undeclared identifiers, and refused an entry parameter carrying either (#3893). - HLSL and Metal output read GLSL's
gl_VertexID,gl_InstanceID,gl_BaseVertexandgl_BaseInstancewherever a vertex stage reads them by name, in the entry point or a helper: the entry point takes the system value as a parameter, reusing an input that already carries it, passes it to the helpers that read it and converts theuintvalue to GLSL'sintonce at its start. HLSL output also reuses an input that already carriesSV_VertexID,SV_InstanceIDorSV_ViewIDinstead of declaring a second one. Both used to copy the reads unchanged, which DXC and the Metal compiler reject as undeclared identifiers (#3891). - HLSL and Slang input read
SV_StartVertexLocation,SV_StartInstanceLocationandSV_DrawIndexas the draw parametersgl_BaseVertex,gl_BaseInstanceandgl_DrawID. HLSL output writesgl_BaseVertexandgl_BaseInstanceas those Shader Model 6.8 system values and refuses them for thedx10anddx11profiles, Slang output writesgl_DrawIDasSV_DrawIndex, and Metal output, which has no draw-index attribute, refuses a vertex input carrying a built-in it cannot spell, such asuint draw @ gl_DrawID, withMetalLoweringRefused. The three semantics used to import as user vertex attributes, so GLSL output declaredlayout(location = n) ininputs, SPIR-V output gave them aLocationand Metal output an[[attribute(n)]], which no vertex fetch fills (#3840, #3545). - SPIR-V output decorates a vertex input carrying
@gl_BaseVertex,@gl_BaseInstanceor@gl_DrawID, theirARBspellings, or HLSL'sSV_StartVertexLocationorSV_StartInstanceLocationasBuiltIn BaseVertex,BaseInstanceandDrawIndex, with theDrawParameterscapability and theSPV_KHR_shader_draw_parametersextension. It used to give the input a userLocation, which no vertex fetch fills (#3794, #3800, #3807). - Metal output accepts an
intentry parameter or stage structure member carrying one of GLSL'sintbuilt-ins,gl_VertexID,gl_InstanceID,gl_BaseVertex,gl_BaseInstance,gl_PrimitiveID,gl_Layer,gl_ViewportIndex,gl_SampleID,gl_ViewIndexorgl_FragStencilRefARB, and reads it through theuintattribute Metal declares: a parameter takes the attribute under a fresh name and initializes anintlocal, and a member is declareduint, converted tointwhere it is read and touintwhere it is written, with/=,%=and>>=keeping their signed meaning.gl_BaseVertexandgl_BaseInstancemap to[[base_vertex]]and[[base_instance]], and HLSL output declares anintSV_StencilRefmember asuint, which DXIL requires. Metal output used to refuse every suchintdeclaration with an untypedValueErrorand to declaregl_BaseVertexandgl_BaseInstancemembers as vertex attributes (#3777, #3780, #3781). - Slang input keeps the stage roles of mesh, task and ray tracing entry points, as HLSL input does: a miss, hit or callable entry's payload, hit attributes and callable data become
@ payload,@ hit_attributeand@ callable_data, a mesh entry'sout vertices,out indices,out primitivesandin payloadparameters become@ vertices out,@ indices out,@ primitives outand@ mesh_payload in, mesh and task entries keep[numthreads]and[outputtopology], andstruct [raypayload] Payloadparses. Slang input used to drop the roles and readpayloadas the parameter's type, and refusedstruct [raypayload]withSyntaxError: Expected IDENTIFIER, got LBRACKET(#3880, #3887, #2597). - SPIR-V input declares a task or mesh stage's
TaskPayloadWorkgroupEXTvariable asPayload payload @taskPayloadSharedEXT, as GLSL input does, and SPIR-V output passes the stage's payload variable toOpEmitMeshTasksEXT, refusing a stage where the choice is ambiguous. SPIR-V input used to drop the declaration and keep its uses, so no target took the import, and SPIR-V output wroteOpEmitMeshTasksEXTwithout its payload operand, which spirv-val accepts, so the mesh stage read no payload (#3879, #3909). - SPIR-V output passes the
rayPayloadEXTorcallableDataEXTvariable at the location thatTraceRay(..., 0)orCallShader(index, 0)names toOpTraceRayKHRandOpExecuteCallableKHR; GLSL and SPIR-V input writetraceRayEXTandexecuteCallableEXTin this form. A location that no variable, or more than one, occupies is still refused. SPIR-V output used to refuse the location as not an addressable value, so no GLSL or SPIR-V shader that traced a ray or called a callable shader reached SPIR-V (#3888). - Every target carries a mesh primitive's cull flag, CrossGL
gl_CullPrimitiveEXT, which HLSL and Slang input readSV_CullPrimitiveas: GLSL output writesgl_MeshPrimitivesEXT[i].gl_CullPrimitiveEXT, SPIR-V outputBuiltIn CullPrimitiveEXTwithPerPrimitiveEXT, HLSL and Slang outputSV_CullPrimitive, and Metal output a[[primitive_culled]]member of the primitive structure, and every generator accepts either spelling. GLSL output used to write anSV_CullPrimitivemember as a userperprimitiveEXT out bool, which glslang rejects ('out' : cannot be bool), SPIR-V and Metal output refused it, and HLSL and Slang output refusedgl_CullPrimitiveEXT. Slang output also writes GLSL-style mesh and task stages, which it used to copy withgl_MeshVerticesEXTand the index arrays unchanged, and translates a task stage without a mesh stage, which it refused withDispatchMesh payload argument requires a mesh stage(#3878, #3906). - GLSL output of a mesh or task stage that enables
GL_NV_mesh_shaderkeeps only that extension. It used to add#extension GL_EXT_mesh_shader : requireabove it, which glslang rejects (GL_EXT_mesh_shader is already turned on, and not allowed with GL_NV_mesh_shader) (#3842). - Slang input keeps
globallycoherenton a UAV as@globallycoherent, as HLSL input does, and Metal output writes agloballycoherentbuffer ascoherent(device). Slang input used to drop the qualifier, and Metal output declared the buffer as an ordinarydevice T*, so its writes were not made visible across the device (#3861). - Metal output keeps
restrict,volatileandcoherenton abuffer T*storage pointer, andrestricton a structured buffer, asdevice T* __restrict,volatile device T*andcoherent device T*, on entry points and on the helpers the buffers pass through, and Metal input reads__restrictand__restrict__on a buffer argument asrestrict. SPIR-V and HLSL output read Metal's device- and threadgroup-scopedcoherentascoherent, writingCoherentandgloballycoherent, and GLSL output acceptsvolatileandcoherenton abuffer T*pointer. Metal input and output used to drop these qualifiers, SPIR-V and HLSL output droppedcoherent(device), and GLSL output refused the pointer qualifiers as representable only on shader-storage buffers (#3838, #3851, #3852, #3858). - SPIR-V input imports a storage block's
CoherentandVolatiledecorations, on the variable, the structure or any member, and itsRestrict,NonWritableandNonReadabledecorations, when the variable, the structure or every member carries them, as@coherent,@volatile,@restrict, a read-onlyStructuredBufferand@writeonly. It used to drop all but aNonWritableon the variable, so a block whose members alone were non-writable, as CrossTL's own SPIR-V output decorates them, imported writable and HLSL output gave it auregister. GLSL output accepts a plain store into awriteonlystorage buffer; it used to refuse it as requiring read-write storage (#3833, #3839, #3844, #3845). - HLSL, GLSL and Slang output declare a stage-scope variable whose type is a plain type alias, such as
real scratch;fortypedef float real;, as a private variable of the aliased type, also for an alias used as a vector element type or reached through a structure member. HLSL and GLSL output used to drop the declaration, so the body read an undeclared name, and Slang output declared it as a uniform (#3818). - A stage that names a
gl_built-in variable GLSL does not declare for that stage, such asgl_VertexIDorgl_DrawIDin a fragment stage, in its entry point or in a function it calls, and that the program does not declare itself, is refused withBuiltinValueUnsupportedError(project.translate.builtin-value-unsupported), as the same name as a member semantic already is. It used to be copied into GLSL, HLSL, Metal and Slang output, whose compilers reject it as an undeclared identifier (#3841). - SPIR-V input keeps the primitive, spacing, vertex-order and
PointModeexecution modes of aTessellationControlentry point, where DXC writes a hull shader's modes, as the@domain,@partitioningand@outputtopologyattributes of the CrossGLtessellation_controlstage, and SPIR-V output of a control stage without@domainwrites the spacing, winding and point mode the stage declares. SPIR-V input used to keep onlyOutputVertices, so a round trip lost the modes (#3871). - GLSL and SPIR-V output of a tessellation stage, and the tessellation factors in HLSL output, read a bare identifier attribute argument such as
@domain(tri)or@patchconstantfunc(Constants)by its name, as they read@domain("tri"). They used to compare it as a value, so the stage was refused or a triangle domain kept four outer factors (#3868). - SPIR-V output resolves a call to an overloaded function whose overloads are declared after the caller. It used to emit the caller first and refuse the call as neither a declared function nor a built-in (#3870).
- Metal, WGSL and Slang output keep a specialization constant such as
const int scale @constant_id(0) = 3;specializable with its id: Metal output declares a[[function_constant(0)]]and definesscalethroughis_function_constant_defined, falling back to the default, WGSL output writes@id(0) override scale: i32 = 3;, and Slang output[vk::constant_id(0)] const int scale = 3;. Constants computed from one follow the specialized value: WGSL output makes a dependent scalar anoverrideand a dependent aggregate avar<private>, and Slang output keeps a foldable dependentintorboolconstantstatic const. All three used to write an ordinary constant, which froze the default value and dropped the id (#3776, #3778, #3795). - Slang input imports
[vk::constant_id(N)]and[SpecializationConstant]as@constant_id(N), giving each automatic constant the lowest id the explicit ones leave free, in declaration order, as slangc does. A misstated id, astaticor non-constspecialization constant, and anumthreadsdimension that depends on one are refused withSlangImportRefused. Slang input used to drop both attributes, so every target fixed the constant at its default and lost its SpecId (#3792). - GLSL output raises
#versionto430 core, or310 esfor GLSL ES, for a program with an array of arrays, such asfloat a[2][3], in a declaration, parameter, structure member, block instance or constructor, and keeps the version of a 4.20 program that enablesGL_ARB_arrays_of_arrays; WebGL output, fixed at GLSL ES 3.00, refuses it withWebGLLoweringRefused(project.translate.webgl-lowering-unsupported). GLSL output used to keep a lower version such as#version 300 es, which glslang rejects (#3810). - Metal input lowers a scalar conversion of a structure,
T(v),T{v},static_cast<T>(v)or(T)v, through the structure's conversion operator also in a function template first instantiated from a member of a structure template, choosing the operator whose result type isTor else the only one, whose result it converts; an ambiguous or missing conversion is refused withMetalSourceOverloadResolutionError. It folds an argument-less call to aconstexprfunction template whose template parameters are all defaulted, such asget_bytes_per_pack(), in a static data member or constructor member initializer, and defines a helper reached from both a kernel and a template member once. It used to write a scalar constructor of the structure value, as infloat(fp8{...}), to leave the call to the removed template in place and to define the helper twice, so the MLX block-scaled (mxfp4, mxfp8, nvfp4) matrix loaders compiled on no target (#2690). - Metal input folds
__builtin_ctz,__builtin_clzand__builtin_popcount, and theirlandllforms, on a constant operand, as inconstexpr short logN = __builtin_ctz(N);after template materialization, and leaves a zero operand toctzorclzunfolded, as Clang does; such a specialization used to be refused withMetalTemplateSpecializationError. HLSL and GLSL output pass a rowx[r]of a localfloat x[R][C]to athread float*parameter as that row with offset 0 and extentC, and a view into the row, such as&x[1][0], with its offset; they used to refuse both withDirectXPrivatePointerParameterErrorandOpenGLPrivatePointerParameterError(reasonmissing-view-backing), because only a whole local array could back a view. - SPIR-V input types a bare
OpTypeImageas Vulkan GLSL's separate texture type, such astexture2D,itexture2Dortexture2DMS, read through a constructor such assampler2D(tex, samp)at anOpSampledImage, and anOpTypeSampledImageas the combined sampler type, such assampler2D,samplerCubeorsampler2DShadow. It used to name bothTexture2D, which is neither CrossGL type, so Metal output refused every texture operation as requiring a declared texture or image resource argument. - HLSL output records binary16 storage for any number of buffers that fits the 64 KiB limit of its resource-storage header, so a module with many entry points, such as 300 kernels with one
halfbuffer each, translates, and a header over the limit is refused withDirectXHalfStorageError(project.translate.directx-half-storage-unsupported, reasonresource-storage-contract-limit). It used to refuse a module with more than 256 such buffers with an untypedValueErrorafter generating the whole program. - CUDA, HIP, Slang, Rust, Mojo and WGSL output refuse a program that uses a cooperative matrix with
CooperativeMatrixLoweringUnsupportedError(project.translate.cooperative-matrix-unsupported), which names every cooperative-matrix type and operation it uses. They have no lowering for one and used to write the CrossGL type, or the Python representation of the type or operation, into the program. - GLSL output pads a short array constructor whose size is a compile-time integer constant, as it pads a literal size:
float[N](x)withconst int N = 3;becomesfloat[N](x, 0.0, 0.0), andfloat[N][2](float[2](x, 1.0))withN = 2becomesfloat[N][2](float[2](x, 1.0), float[2](0.0, 0.0)). It used to copy the constructor with one argument, which glslang rejects witharray constructor needs one argument per array element(#3811). A size set by a specialization constant is left as written. - GLSL output refuses an array constructor with more arguments than elements, such as
a = float[1](x, 1.0);, in an assignment, a return, a call argument or a structure constructor, withOpenGLAggregateInitializerError(project.translate.opengl-aggregate-initializer-invalid), as it already did in a declaration. It used to copy it, which glslang rejects (#3710). - Metal output refuses the
length()of aStructuredBuffer<T>orRWStructuredBuffer<T>, such asvalues.length()forStructuredBuffer<float> values, in an entry point or a helper, withBufferLengthUnsupportedError(project.translate.metal-buffer-length-unsupported), as it already does for abuffer float*view: a Metal buffer argument is a pointer and carries no size. It used to copyvalues.length()unchanged onto the device pointer, which the Metal compiler rejects as not a structure or union. - GLSL and HLSL output write the
length()of an element of a structured buffer array, such asbufs[1].length()forStructuredBuffer<float> bufs[2], asbufs[1].data.length()andint(cgl_buffer_count(bufs[1])), as they do for a singleStructuredBuffer<T>. They used to copybufs[1].length()unchanged, which glslang rejects becauselengthdoes not operate on a block and DXC rejects becauseStructuredBuffer<float>has no member namedlength(#3641). - Metal output refuses the
length()of anAppendStructuredBuffer<T>orConsumeStructuredBuffer<T>, and of an element of a structured buffer array such asbufs[1].length()forStructuredBuffer<float> bufs[2], withBufferLengthUnsupportedError(project.translate.metal-buffer-length-unsupported), as it does for aStructuredBuffer<T>. It used to copy the call unchanged onto the device pointer, which the Metal compiler rejects as not a structure or union. - GLSL output writes
GetDimensions(count, stride)on aStructuredBuffer<T>orRWStructuredBuffer<T>, such asvalues.GetDimensions(n, s), asn = uint(values.length()), s = 4u: the element count, read as the buffer'slength()is, less the element offset in a helper that takes the buffer, and the element's std430 array stride, 16 for avec3. An element type whose std430 stride GLSL output does not know, such as a structure, is refused withOpenGLLoweringRefused. It used to copy the call unchanged, which glslang rejects with'.' : cannot apply to an array: GetDimensions, and wrotevalues[v_offset].GetDimensions(n, s)in a helper ('GetDimensions' : vector swizzle too long) (#3755). - GLSL output writes the
length()of aStructuredBuffer<T>orRWStructuredBuffer<T>helper parameter, such asv.length()inint count(StructuredBuffer<float> v), as the length of the buffer the specialized helper reads less the element offset it is called with,(values.length() - int(v_offset)), and does the same for abuffer float*parameter or local view, socount(data + 2)counts the elements fromdata[2]on. It used to writevalues[v_offset].length(), thelength()of one element, which glslang rejects (#3640). - HLSL output writes the
length()of abuffer T*helper parameter, such asv.length()inint count(buffer float* v), as the element count of the buffer the helper receives less the element offset it is called with,(int(cgl_buffer_count(v)) - int(v_offset)), as GLSL output does, and does the same for a local view such asbuffer float* p = data + 2;. It used to copyv.length()unchanged, which DXC rejects withno member named 'length' in 'RWStructuredBuffer<float>', and wrotep.length()for the local view, whosepHLSL output does not declare (#3759). - WGSL output writes the
length()of an HLSL-styleStructuredBuffer<T>orRWStructuredBuffer<T>, such asvalues.length()forStructuredBuffer<float> values, asi32(arrayLength(&values)). It used to copyvalues.length()unchanged, which naga rejects (#3582). - WGSL output writes the four-argument
texture()with an explicit sampler and a bias,texture(t, s, uv, 0.5), which HLSLt.SampleBias(s, uv, 0.5)and Metalt.sample(s, uv, bias(0.5))import as, astextureSampleBias(t, s, uv, 0.5), passing the layer of a 2D array or cube array texture as its own argument and converting an integer bias withf32(), as it does fortexture(t, uv, bias). It refuses a bias in a vertex or compute stage withImplicitLodStageUnsupportedError(project.translate.wgsl-implicit-lod-stage-unsupported), and a bias on a 1D or depth texture, through a comparison sampler, on an element of a sampled texture array selected at run time or that is not a scalar, and a four-argument call whose second argument is not a sampler, withWGSLTextureBiasUnsupportedError(project.translate.wgsl-texture-bias-unsupported). It used to refuse every such call withValueError: WGSL target supports texture() calls with texture/coords or texture/sampler/coords arguments(#3584). - WGSL output converts the
length()of abuffer T*storage buffer or aStructuredBuffer<T>tou32where auintis expected, as a variable's value, an argument or a return value, souint n = values.length();becomesvar n: u32 = u32(i32(arrayLength(&values)));. It used to writevar n: u32 = i32(arrayLength(&values));, which naga rejects (#3617). - WGSL output converts a negative integer literal to
u32as ani32:uint u = -1;,uint(-1),uvec2(-1, 2)and auintmember's value inU(-1, x)orU s = {-1, x};are writtenu32(-1i), 4294967295 as in GLSL output. They used to be writtenu32(-1), which naga rejects because the abstract integer-1has nou32value (#3686). - WGSL output writes a scalar element of a matrix array constructor or initializer as the matrix with that scalar on its diagonal, as it writes
mat3(s):mat4 n[3] = mat4[3](1.0);becomesarray<mat4x4<f32>, 3>(mat4x4<f32>(vec4<f32>(1.0, 0.0, 0.0, 0.0), ...), mat4x4<f32>(), mat4x4<f32>()), the identity followed by zero matrices. It used to keep the scalar, as inarray<mat4x4<f32>, 3>(1.0, mat4x4<f32>(), mat4x4<f32>())orarray(x, 1.0)format2 m[2] = mat2[2](x, 1.0);, which naga rejects (#3635). - WGSL output lowers a plain enumeration, whose variants carry no data, to one
i32constant per variant, as GLSL and Metal output writeintconstants:enum Mode { First, Second = 5, Third }becomesconst Mode_First: i32 = 0;,const Mode_Second: i32 = 5;andconst Mode_Third: i32 = 6;, aModevalue is ani32, andMode::SecondisMode_Second. An enumeration whose variants carry data is refused withWGSLEnumUnsupportedError(project.translate.wgsl-enum-unsupported). Every program with a shader-scope enumeration used to fail withAttributeError: 'EnumNode' object has no attribute 'members'(#3687). - WGSL output writes a structure's brace initializer, such as
Pair p = {x, 2.0};, as the structure's value constructor,var p: Pair = Pair(x, 2.0);, in a declaration, an assignment, a return value, a call argument, a shader-scope constant or variable, a nested member and an array of structures. Each value is converted to its member's type, as inQ(u32(1), i32(x)), and the members left out are set to zero as GLSL output does. An initializer with more values than members, or one for a structure that holds an atomic or a resource, is refused withWGSLStructInitializerError(project.translate.wgsl-struct-initializer-unsupported). It used to writearray(x, 2.0), which naga rejects because the declared type isPair(#3653). - WGSL output writes a vector's or a matrix's brace initializer as the type's value constructor:
vec3 v = {x, 1.0, 2.0};becomesvar v: vec3<f32> = vec3<f32>(x, 1.0, 2.0);, andmat2 m = {vec2(1.0, 0.0), vec2(0.0, x)};or{{1.0, 0.0}, {0.0, x}}becomesmat2x2<f32>(vec2<f32>(1.0, 0.0), vec2<f32>(0.0, x)), in the same places as a structure's, including a structure member, as inV(vec3<f32>(x, 1.0, 2.0), 3.0), and an array of vectors. A matrix takes one vector per column or one scalar per component. Each value is converted to the component or column type, as invec3<f32>(f32(k), 1.0, 2.0), and the components a vector list leaves out are set to zero as GLSL output does. A list with more values than the vector has components, a non-scalar vector component, and a matrix list that is neither one vector per column nor one scalar per component are refused withWGSLVectorInitializerError(project.translate.wgsl-vector-initializer-unsupported). It used to writearray(x, 1.0, 2.0), which naga rejects because the declared type isvec3<f32>(#3684). - An empty brace initializer of a scalar variable or constant, such as
float one = {};,int n = {};,short s = {};orreal_t one = {};fortypedef float real_t;, which CUDA and HIP input import asvar one: f32 = {};, is the scalar's zero on every target, as if the zero were written:float one = 0.0;in HLSL, GLSL and Metal output andvar one: f32 = 0.0;in WGSL output. HLSL output used to copy{}, which DXC rejects, WGSL output to writearray(), which naga rejects, and GLSL output to refuse the program withOpenGLAggregateInitializerError; SPIR-V output refused ahalfor 16-bit one, and Metal output wrote an 8- or 16-bit one asint(short({})), which the Metal compiler rejects (#3735). - A one-value brace initializer of a scalar variable or constant, such as
float g = {1.0};,int n = {x};orreal_t g = {1.0};fortypedef float real_t;, at shader scope or in a function, is its value converted to the declared type on every target, as iffloat g = 1.0;orint n = int(x);were written, and so is a nested list such as{{1.0}}. A scalar's brace list with more than one value, such asfloat g = {1.0, 2.0};, is refused withScalarBraceInitializerError(project.translate.scalar-brace-initializer-invalid). WGSL output used to writevar<private> g: f32 = array(1.0);, which naga rejects, SPIR-V output anOpConstantCompositeoffloat, which spirv-val rejects, Rust output[1.0], which rustc rejects, and GLSL output refused the program withOpenGLAggregateInitializerError; Metal, CUDA and HIP output copied the braces, which their compilers reject when the value narrows, as inuint u = {x};forint x, and HLSL output dropped a longer list's values, writingfloat g;(#3760). - An empty brace initializer of a variable or constant of a plain enumeration, one whose variants carry no data, such as
Mode m = {};, which CUDA and HIP input import asvar m: Mode = {};, is zero:int m = 0;in HLSL, GLSL, Metal, Slang and HIP output andvar m: i32 = 0;in WGSL output, also for an enumeration that names its type, such asenum Mode : uint, whose variables these generators write asint. HLSL output used to copyint m = {};, which DXC rejects, WGSL output to writevar m: i32 = array();, which naga rejects, and GLSL output to refuse the program withOpenGLAggregateInitializerError. CUDA output keepsMode m = {};, which C++ value-initializes to zero (#3752). - Rust output writes an empty brace initializer of a plain enumeration, such as
Mode m = {};forenum Mode { First, Second }, as the variant whose discriminant is 0:let m: Mode = Mode::First;. An enumeration with no zero-valued variant, such asenum Mode { First = 3, Second = 5 }, is refused withRustEnumEmptyBraceError(project.translate.rust-enum-empty-brace-unsupported), as is one whose variants carry data, such asenum MaybeInt { Value(int), Missing }. It used to writelet m: Mode = [];, which rustc rejects (#3820). - WGSL output writes a declared array whose initializer gives fewer elements than the array has, such as
float a[3] = float[3](0.0);or{x, 1.0}, asarray<f32, 3>(0.0, f32(), f32()), with the elements left out set to zero as GLSL output does. It used to writearray(0.0), a one-element array that naga rejects. - WGSL output zero-fills a short array constructor outside a declaration as well, in an assignment, a call argument, an index or a return value:
a = float[3](1.0);becomesa = array<f32, 3>(1.0, f32(), f32());, andvec3[2](vec3(x))becomesarray<vec3<f32>, 2>(vec3<f32>(x), vec3<f32>()), as in a declaration. A constructor with more arguments than its size, and an empty one, are refused withWGSLAggregateInitializerError(project.translate.wgsl-aggregate-initializer-invalid). All three used to raise an untypedValueError(#3638). - WGSL output refuses an array initializer with more elements than its declared array, such as
float a[1] = {x, 1.0};orfloat a[1] = float[1](x, 1.0);, withWGSLAggregateInitializerError(project.translate.wgsl-aggregate-initializer-invalid), which names the array type and both counts, as GLSL and HLSL output refuse it. This covers a declaration, an assignment, a return value, a call argument, a shader-scope constant, a structure member and an array of structures, and an array whose size is a constant, as infloat a[COUNT]. It used to writevar a: array<f32, 1> = array(x, 1.0);, which naga rejects (#3685). - WGSL output gives a shader-scope array variable's brace list its declared type, as it does for a local or a shader-scope constant:
float g[3] = float[3](1.0);orfloat g[3] = {1.0};becomesvar<private> g: array<f32, 3> = array<f32, 3>(1.0, f32(), f32());, and a list longer than its array, such asfloat g[3] = {1.0, 2.0, 3.0, 4.0};, is refused withWGSLAggregateInitializerError(project.translate.wgsl-aggregate-initializer-invalid), as in a local declaration. It used to writearray(1.0), a one-element array, and copy a long list asarray(1.0, 2.0, 3.0, 4.0); naga rejects both because the declared type isarray<f32, 3>(#3676).
The other 42 fixes are listed in CHANGELOG.md.