Rule 8.22
Chapter 8, Functions and entry points Test
A kernel function is an exported function that is not an entry point, a function declaration, and takes at least one array with no size (array<T>) or one 2D storage texture (texture_storage_2d<F, A>, change 0077), or returns an array with no size that its body makes (Rule 8.23, change 0114, S5); a sampled texture alone does not make one, so an exported helper that reads one stays a helper an entry calls; its candidate loops are the for and for…of statements at the top level of its body, and no other loop is ever a candidate.
out.push(v) is accepted on an array parameter of a kernel function inside a candidate loop, as a statement, with v of the array’s element type (change 0078); a push anywhere else is refused, as every array method surface §63 does not list is.
A parameter of a kernel function may be ECMAScript’s Set<K> or Map<K, V> (change 0080), with K a u32, an i32, an f32 or a key type (Rule 4.1, change 0081) and V a type an array may hold; a Map or a Set anywhere else is refused (TS8002). s.add(k) and m.set(k, v) are statements inside a candidate loop; c.has(k), c.size and m.get(k) read it, m.get(k) only where a m.has(k) of the same m and the same k guards it (the then of an if, after the ? of a conditional, or right of an &&), since a shader value has no undefined; every other member, a local that holds one, and an add or a set outside a loop are refused (TS8099).
A method on the function’s array (Rule 8.18, change 0079) is the loop it is written into: at the top level a candidate loop, with the function handed over as its body, so xs.reduce((a, x) => a + x, 0.) is R3’s reduction form and const s = xs.reduce(…) reduces into s.
Its body is scalar statements, then its loops, then stores into elements of its array parameters and an optional return of scalars (change 0094), or, in a function that makes the array it returns, return of that array on every path (Rule 8.23): after its last loop, a[k] = e, or a compound a[k] op= e, stores into an element of an array parameter a, k and e may read its scalars, what its loops reduced, the length of an array a loop pushes onto (Rule 8.23) and the elements of its arrays, and the stores run in the order written; a store whose index is past the array’s end is dropped on every tier, so the array’s .length after it is still its length; and a function with no loop may be scalar statements and such stores (decision D7).
The statements before a loop, its start and its bound may read the scalar parameters, the elements and the .length of the array parameters, and what an earlier loop of the same call wrote, the length of an array an earlier loop pushes onto included, and no texture (change 0094): a loop whose range reads an element, or such a length, has a range the device holds, which the call computes in a range entry of one invocation and dispatches the loop from (Rule 11.8), and a write that such a loop makes past an array’s end is dropped on every tier, so the array’s .length after it is still its length. A loop over a range the device holds that pushes or reduces, stores into a texture, writes an array through an argument of a parameter that its function writes, or writes an array the statements before it read, and such a range in a function that takes a Map or a Set, run the whole function on the CPU in this version, and the host view says why. A statement before its last loop that writes an array (the array a kernel function makes, Rule 8.23, is not written by its constructor: the constructor is its value at allocation), or a statement that is neither a loop, a scalar statement nor such a store, runs the whole function on the CPU, and so does a loop that reads a variable an earlier loop reduces (“split the function”).
A candidate loop runs as a GPU kernel only when this proof accepts it, on the IR, with no solver and no alias analysis:
- R1: the loop is counted (Rule 7.5) with an additive constant step; a
while, aforthat is not counted and a multiplicative step are refused. - R2: no
returninside it, and nobreakthat belongs to it (one inside a nested loop orswitchbelongs to that). - R3: every write (an assignment, an argument a callee writes through, an atomic, a
textureStore) lands on a name declared in the body; on an outer array ata*i + c(aa nonzero constant, the same at every write to that array, with eachcin[0, |a|)or onec), at one index whose coefficient ofiis loop-invariant, or ati*W + xover a nested loop ofxfrom 0 to< W; on a texture atvec2(i % W, i / W); on a reduction variable written only ass op= e,s = s op e,s = min(s, e)ors = max(s, e)with oneopof+ * & | ^ min maxandenot readings; or on an integer array written only asa[k] op= e, a scatter reduction; or on an array parameter the loop writes only withpush(change 0078), any number of times in an iteration and in any branch; or on aMapor aSetparameter withsetoradd(change 0080), any number of times in an iteration and in any branch. - R4: an array the loop writes is read in the body only at an index it writes, a texture it stores into is loaded only at a coordinate it stores at (its
textureDimensionsis read anywhere), a reduction variable is not read, the value an atomic returns is not read, and an array the loop pushes onto is not read at all, neither an element nor its.length, nor is the valuepushreturns, and aMapor aSetthe loop adds to is not read (has,get,size), since each depends on the iterations before it. - R5: a function the body calls, transitively, writes no module variable and no binding.
- R6: no barrier, no workgroup memory and no
consolecall in the body or in what it calls.
A loop the proof refuses runs on the CPU, and the program is correct either way: the refusal is a warning, TS8070, on the loop, whose first sentence names the line and the author’s own names and whose second gives the remedy, one per loop for the first reason (Rule 12.4).
On WebGPU every invocation of a workgroup that holds an iteration runs to the end of the loop’s entry (change 0096): a workgroup wholly past the trip count returns as one, on a condition every invocation of it shares (its first index, from workgroup_id and num_workgroups, against the trip count), and in the workgroup that holds the last iteration a lane past the trip count runs iteration n − 1, its index clamped to it, with every write of the iteration (a store to an outer array, a texel store, an atomic, a store of a push, a record of a Map or a Set) masked by the lane’s live flag; a loop that reduces gives the tree the operator’s identity for such a lane, and a loop that pushes stores no count and no element for it. Where iteration n − 1’s lane and the clamped lane would race, the clamped lane skips the iteration under the same flag instead: a loop that reads back an element it writes, one that loads a texel it stores, one that writes through an argument of a call that the callee writes, and a fused group with an edge (Rule 11.13). The results of a call do not change on any tier; the WebGL2 program and the CPU tier keep their forms.
A variable an accepted loop reduces is combined in the tree order on every tier (Rule 7.2): each iteration combines into it from the operator’s identity, the iterations’ values are folded 256 at a time by the workgroup tree (at stride 128, then 64, down to 1, slot t becomes slot[t] op slot[t + s], the last block padded with the identity), the partials the same way until one is left, and the variable is combined with that last; a loop that runs no iteration leaves it as it was.
On the WebGPU tier, a reduction whose operator gives one value in every order (an integer operator, or min and max) may fold the lanes of a subgroup with the subgroup function of that operator before the workgroup slots, and a scatter into an integer array may fold the lanes of a subgroup that share a key before one lane adds, as a variant the runtime selects (Rule 11.23, change 0119); the bits such a variant writes are the tree’s and the atomics’, and an f32 sum or product keeps the tree in every variant.
The proof also records how an accepted loop reaches each array parameter, for the planner of typeshade/fuse (Rule 11.13): whether every read of an array the loop does not write, and every write of an array it does, is at exactly the loop’s counter i (the index form a*i + c with a = 1 and c = 0, through casts and the constants the index names); whether the loop only writes the array or also reads back what it wrote; and the first access that is not at i.
These are facts and refuse nothing: a loop accepted without them is accepted with them.
By default, typeshade() and hostFace() write these facts into each lowered kernel function’s face (change 0085). Each face carries them for each loop, with whether the loop reduces, scatters or has a continue of its own, and with the lowered module as portable IR; the first access that is not at i is worded in the author’s names, with its one-based line, as TS8070 words an access (t[i - 1] (line 9)). A kernel function of a module that emulates f64 carries its WGSL under both flavors of the emulated double, 'float' and 'integer' (change 0073), so the owner of a call picks one at run time (Rule 11.8), and a module that emulates none carries one; the loop IR is the module before the fp64 pass, which the planner lowers under the owner’s flavor (Rule 11.13).
The face also names each array parameter whose length the iteration reads (t.length) and the first place it does, since an array that is only measured has no element access among the facts above.
fuse: true retains this default. An explicit fuse: false omits the fusion facts and portable IR.
Facts describe the full layout; their availability does not disable ordinary-call input projection (Rule 8.23).
A kernel function’s workgroup size is the compiler’s choice: in this version 64 for a loop that does not reduce, 256 (the tree, Rule 7.2) for one that reduces, and the group’s size in a fused group (F7, Rule 11.13). The optional attribute @workgroup_size([n]), n one positive whole number or one u32 or i32 module constant in an array literal (read as Rule 8.7 reads @compute), states the size for each accepted loop that does not reduce; on a function with a loop that reduces it is refused (TS8077), and on a function that is neither a kernel function nor an entry it is refused (TS8028), and on an entry it is refused with the message of Rule 6.7; a function takes at most one @workgroup_size([n]), and a second one must be refused (TS8028); an override name is no extent in this version. The size changes the time a loop takes, not the bits it writes, since each element is written from its own index i. A better default, per device or per workload, is compiler work and needs no proposal.
The rule text and the parts under it are the compiler's own English, as the design document writes them.
Rationale
a loop is how a TypeScript developer writes work over an array, and docs/dx.md names dispatches and workgroups as the model the developer should not have to learn first; the proof says which loops are safe to run in any order, predictably, from rules a reader can apply by hand, rather than trusting the author’s assertion (Numba’s prange).
Only a function that takes an array with no size, or a 2D storage texture, is a kernel, so no loop that is per-invocation code today becomes a candidate: #252 measured the 48 loops of the corpus, and none is one; a sampled texture alone makes none, since an exported helper that reads one is a helper entries call (change 0077, Amendment 1).
The proof reads an argument that the callee writes through as a write at its call, which #252’s prototype first missed six times: a method that changes an outer object carries it to the next iteration.
The facts for the planner are written once, at build time, in the author’s names, so that the run time matches them and analyzes no IR (Rule 11.13).
A lane past the trip count runs the last iteration instead of returning early because a workgroup whose idle lanes returned before heavy loops hung the device of docs/hardware-notes.md A1 (NVIDIA Blackwell, D3D12; issue #703), and the clamp-and-mask form completed there; the uniform return of a whole workgroup keeps a reduction’s barriers in uniform control flow (Rule 8.5), and the skipped form keeps a clamped lane from reading what another lane writes in the same dispatch, which WGSL calls a dynamic error.
Derives from
change 0013 in changes/ (roadmap item 15); change 0058 (the facts for the planner); change 0096 (the idle lanes of the last workgroup); change 0094 (the stores after the loops, and a range the device holds); #252; #703; Rule 7.5; docs/dx.md. Change 0119 (the subgroup variant of a reduction and a scatter). Change 0067; change 0130 (D1).
How it is verified
Checked by a test. A test, a gate script or a CI workflow names this rule, and the traceability check fails when a file listed below stops naming it.
Where the rule says the compiler enforces it:
the front end’s decorator reading for @workgroup_size([n]), pinned by src/compiler/ts/stage3.test.ts (the attribute’s emit, TS8077 on a function with a loop that reduces, TS8028 on a function that is neither a kernel function nor an entry), src/compiler/ts/kernel-workgroup.test.ts (a second @workgroup_size([n]) on one function refused at its own attribute in both halves with TS8028, "@workgroup_size([16])" is a second "@workgroup_size" on "scale", after "@workgroup_size([8])": a function takes at most one "@workgroup_size([n])"; delete "@workgroup_size([16])" (Rule 8.22)., the first one setting the size; change 0130, amendment A1) and src/language-service/new-entry-forms.test.ts (the editor lists it as a function); proveKernels in src/core/passes/parallel-loop.ts, whose facts src/compiler/ts/kernel-loops.ts words as TS8070 KERNEL_LOOP_ON_CPU in the author’s names; pinned by src/core/passes/parallel-loop.test.ts, every accepted form and refusal #252 measured, and by src/compiler/ts/kernel-loops.test.ts, each refusal’s text in the compiler and in the language service on the same source, the texel form of R3 and the texture half of R4 among them (change 0077), and a helper that takes only a sampled texture left a helper. parseParams’s caller in src/compiler/ts/lower/function.ts marks the kernel function. The call’s dispatch is lowerKernel in src/core/passes/kernel-lower.ts, which lowers a function whose every loop the proof accepts to one @compute entry per loop, a loop that reduces to a workgroup tree of 256 and an entry that folds its partials, one dispatch per level, with the function’s result from its tail on the CPU tier, and a scatter into an integer array to an atomic on it; callKernel in src/core/host-kernel.ts runs it on WebGPU, and runs the function on the CPU tier where there is none or the function does not lower (a scatter with *, which no atomic does, a refused loop, a bool, a module binding; a function that writes a texture is not callable until change 0077 gives a storage texture parameter its host value), an emulated f64 dispatched as two f32s with the module’s _fp64 guard bound and its reductions folded by the same tree. The tree order is kernelTree in src/core/kernel-tree.ts on the CPU backends. Pinned by src/compiler/ts/host-kernel.test.ts on the CPU tier against the oracle, by src/core/kernel-tree.test.ts for the tree order, and by the import journey, which calls six kernel functions on WebGPU in Chromium, two of them reductions held to the tree bit for bit and one a histogram by atomics. The facts for the planner are LoopRead and LoopStore on each accepted verdict of proveKernels, worded by describeRead in src/compiler/ts/kernel-loops.ts and written into the face by default, unless fuse: false, by fuseRecord and bareArrays in src/compiler/ts/host-face.ts; pinned by the index facts of src/core/passes/parallel-loop.test.ts (every access at the counter, the first that is not, and a loop accepted before still accepted), by describeRead in src/compiler/ts/kernel-loops.test.ts (the author’s names, the line, and the same words TS8070 gives) and by the face’s fuse record in src/compiler/ts/host-kernel.test.ts (the facts, the arrays an iteration measures, and an explicit fuse: false omitting the record). The push form (change 0078) is lowered by lowerCall in src/compiler/ts/lower/expression-call.ts to the builtin push, whose operand src/core/passes/access.ts reads as an append; its R3 and R4 halves are pinned by src/compiler/ts/kernel-loops.test.ts in both halves, and pushEntries in src/core/passes/kernel-lower.ts lowers a loop that pushes to its count, scan and store entries, pushGap saying why one runs on the CPU (change 0078); pinned by src/compiler/ts/host-kernel-push.test.ts (the face, the three entries’ WGSL, each reason) and by the import journey, whose pushAbove and pushPairs run on WebGPU, required, against a sequential run. An array two loops push onto, or whose length the stores after the loops read, has a length word (PushWord in src/core/passes/kernel-lower.ts, change 0094): each scan starts at it and writes the new length into it, and the entry that stores reads it; pinned by src/compiler/ts/host-kernel-push.test.ts (the WGSL of two loops onto one array and of a store of a pushed length, the CPU tier, and the plan on the oracle against the function) and by the generated kernels of src/core/testing/random-kernel-differential.test.ts and scripts/gpu-differential.ts, which push from two loops onto one array and store a pushed length. A method on the function’s array (change 0079) is written into its body by inlineKernelMethods in src/compiler/ts/lower/kernel-methods.ts, from the loop lowerArrayMethod in src/compiler/ts/lower/array-methods.ts makes; pinned by src/compiler/ts/host-kernel-methods.test.ts in both halves, on the face (each loop on the GPU) and on the CPU tier against Array.prototype. The Map and Set forms (change 0080) are mapCollection in src/compiler/ts/type-map.ts, which takes the type only through withCollections around a kernel function’s parameter, and lowerCollectionCall and lowerCollectionSize in src/compiler/ts/lower/collections.ts, which lower the members to the builtins collectionAdd, collectionSet, collectionHas, collectionGet and collectionSize; src/core/passes/access.ts reads the operand of an add or a set as an append. Pinned by src/compiler/ts/host-kernel-collections.test.ts in both halves. The scaffold of a lane past the trip count (change 0096) is laneScaffold, maskWrites and laneSkips in src/core/passes/kernel-lower.ts, with workgroupFirst in src/core/kernel-workgroup.ts, and the same scaffold for a fused group in src/core/fuse-entry.ts; pinned by src/compiler/ts/host-kernel.test.ts (the WGSL of a map’s entry, the four skipped forms, and the plan on the oracle against the function for a partial last workgroup and a grid that spills into y), src/compiler/ts/host-kernel-push.test.ts (the count step) and src/core/fuse-entry.test.ts (the group’s one scaffold, the helper of a group that reduces, and a group with an edge). The stores after the loops (change 0094) are guarded by the array’s length by guardStoresAfterLoops in src/core/passes/kernel-stores.ts, which fillFunctionBody’s kernel step in src/compiler/ts/lower/function.ts applies, so that every tier runs the one guard; the proof and the lowering find them by storeAfterLoops in the same file, and lowerKernel runs them in a finish entry of one invocation, after the loops, which combines what each loop reduced as the tail does; pinned by src/compiler/ts/host-kernel-finish.test.ts (both halves, the face and the entry’s WGSL, the CPU tier, a store past the end and the length after it, a function with no loop, the plan on the oracle against the function, and the forms that still run on the CPU tier), src/compiler/ts/kernel-loops.test.ts and src/core/passes/parallel-loop.test.ts (the shape, in both halves), src/core/passes/determinism.test.ts (a stored result has the rows of a returned one) and the generated kernels of src/core/testing/random-kernel-differential.test.ts and scripts/gpu-differential.ts, which store after their loops, past an array’s end now and then, and have no loop. A range the device holds (change 0094) is deviceRangeLoops in src/core/passes/kernel-stores.ts, whose loops’ writes guardKernelBody in the same file guards by the array’s length, as it guards the stores after the loops, for every tier; lowerKernel writes the range entry of such a loop (rangeEntryFor) and its entry’s reads of the trip buffer, and deviceGap says why one runs on the CPU; pinned by src/compiler/ts/host-kernel-range.test.ts (both halves, the face and the entries’ WGSL, the CPU tier, a write past the end, the plan on the oracle against the function, the workgroup count, and the forms that still run on the CPU tier) and by the generated kernels of src/core/testing/random-kernel-differential.test.ts and scripts/gpu-differential.ts, whose last loop’s range reads an element, past the arrays’ end now and then. The subgroup variant: subgroupFoldable, scattersAtMostOnce, reductionEntries and deferScatters in src/core/passes/kernel-lower.ts, which emit the second module, pinned by src/compiler/ts/host-kernel.test.ts (the two texts of seven functions, and which loops fold) and held to the tree’s bits by journeys/subgroup-folds/ on a device that selects it.
The files that verify it at commit af54ddad5, each at the first line that names the rule:
-
examples/loop-examples.test.ts:2 -
scripts/gpu-differential.ts:1 -
src/compiler/ts/host-face.ts:5 -
src/compiler/ts/host-kernel-collections.test.ts:1 -
src/compiler/ts/host-kernel-finish.test.ts:1 -
src/compiler/ts/host-kernel-growing-open.test.ts:1 -
src/compiler/ts/host-kernel-growing.test.ts:1 -
src/compiler/ts/host-kernel-made.test.ts:2 -
src/compiler/ts/host-kernel-methods.test.ts:1 -
src/compiler/ts/host-kernel-push.test.ts:1 -
src/compiler/ts/host-kernel-range.test.ts:1 -
src/compiler/ts/host-kernel-texture.test.ts:1 -
src/compiler/ts/host-kernel.test.ts:2 -
src/compiler/ts/kernel-corpus.test.ts:1 -
src/compiler/ts/kernel-loops-guards.test.ts:1 -
src/compiler/ts/kernel-loops.test.ts:1 -
src/compiler/ts/kernel-loops.ts:1 -
src/compiler/ts/kernel-scatter.test.ts:1 -
src/compiler/ts/kernel-workgroup.test.ts:1 -
src/compiler/ts/key-types.test.ts:3 -
src/compiler/ts/lower/array-methods.ts:38 -
src/compiler/ts/lower/collections.ts:1 -
src/compiler/ts/lower/expression-call.ts:1 -
src/compiler/ts/lower/function.ts:2521 -
src/compiler/ts/lower/kernel-methods.ts:1 -
src/compiler/ts/made-array-refusals.test.ts:1 -
src/compiler/ts/stage3.test.ts:1 -
src/compiler/ts/static-read-wording.test.ts:1 -
src/compiler/ts/type-map.ts:1129 -
src/core/fuse-entry.test.ts:1 -
src/core/fuse-entry.ts:1 -
src/core/host-kernel.ts:1359 -
src/core/kernel-tree.test.ts:1 -
src/core/kernel-tree.ts:1 -
src/core/kernel-workgroup.ts:1 -
src/core/passes/access.ts:40 -
src/core/passes/determinism.test.ts:220 -
src/core/passes/kernel-lower.ts:23 -
src/core/passes/kernel-stores.ts:1 -
src/core/passes/parallel-loop.test.ts:1 -
src/core/passes/parallel-loop.ts:2 -
src/core/passes/scatter-f32.test.ts:1 -
src/core/testing/random-kernel-differential.test.ts:4 -
src/language-service/new-entry-forms.test.ts:1 -
src/runtime/buffer-scalar.test.ts:2
Explained in
The sections of the surface document that explain this rule, at commit af54ddad5:
Error codes that enforce it
The diagnostic codes the rule names under Enforced by, or whose registry text names the rule:
-
TS8028ATTRIBUTE_NAME - A decorator or an entry form that this surface does not read: an identifier outside the attribute vocabulary (
@vertex,@fragment,@compute,@builtin,@location), such as a misspelled@vertx; a WGSL attribute that the surface writes another way or does not borrow, such as a written@diagnostic(…); a stage written as a call, such asvertex(f); an entry that is written in a form that Rule 8.1 refuses, such asexport default; or a decorator on a declaration or in a place that takes none (Rule 6.7). Without this code the decorated function or field would silently stop being an entry point or an I/O field. -
TS8070KERNEL_LOOP_ON_CPU - A warning on a loop of a kernel function (Rule 8.22) that the independence proof refused: the loop runs on the CPU. The message names the line and the names that stop it, and the remedy. The program is correct either way.
-
TS8077KERNEL_WORKGROUP_REDUCES - A kernel function with
@workgroup_sizethat has a loop which reduces (Rule 8.22). A reduction always runs in the tree of 256, so an attribute that asks for another size cannot be honored. The message names the function and the remedy.
See also
Source
The rule at commit af54ddad5:
docs/language-design.md:1090(the design document)reqs/rules/RULE-0822.md(its traceability item)