From ebe977a1d0c68b2901dc1c6423c8217b9394bc82 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Wed, 2 Dec 2026 12:23:46 +0000 Subject: [PATCH 1/4] A warp's builtins: gpuLaneIndex, gpuWarpSize, gpuShuffle/Down/Up/Xor, gpuBallot, gpuAll, gpuAny Stubs lowered per GPU: NVIDIA shfl.sync/vote.sync over activemask, AMD ds_bpermute and ballot (wave32 from gfx10; gpuBallot refused on wave64), Intel OpSubgroupShuffleINTEL (SPV_INTEL_subgroups, given to the SPIR-V backend through its -spirv-ext option) and sub-group reduce/all/any. A kernel that uses them runs as a barrier kernel (every thread; writes past n dropped); its votes leave out the threads past n. Its block must be whole warps (a multiple of 32), gpuReduce refuses it, and a CPU call is an error. gpu_warp.ts and gpu_scan.ts (a prefix sum of shuffles and shared memory) pass on the RTX 5080, JIT and exe. Co-Authored-By: Claude Opus 5.5 --- .../TypeScript/MLIRLogic/MLIRCodeLogic.h | 4 +- tslang/lib/TypeScript/MLIRGenAccessCall.cpp | 104 ++++++ tslang/lib/TypeScript/MLIRGenImpl.h | 3 + tslang/test/gpu/CMakeLists.txt | 51 +++ tslang/test/gpu/compile/warp.ts | 21 ++ tslang/test/gpu/compile/warp_block.ts | 10 + tslang/test/gpu/compile/warp_cpu_call.ts | 10 + tslang/test/gpu/compile/warp_reduce.ts | 10 + tslang/test/gpu/compile/warp_value.ts | 10 + tslang/test/gpu/gpu_scan.ts | 67 ++++ tslang/test/gpu/gpu_warp.ts | 141 ++++++++ tslang/tslang/gpu.cpp | 328 +++++++++++++++++- 12 files changed, 744 insertions(+), 15 deletions(-) create mode 100644 tslang/test/gpu/compile/warp.ts create mode 100644 tslang/test/gpu/compile/warp_block.ts create mode 100644 tslang/test/gpu/compile/warp_cpu_call.ts create mode 100644 tslang/test/gpu/compile/warp_reduce.ts create mode 100644 tslang/test/gpu/compile/warp_value.ts create mode 100644 tslang/test/gpu/gpu_scan.ts create mode 100644 tslang/test/gpu/gpu_warp.ts diff --git a/tslang/include/TypeScript/MLIRLogic/MLIRCodeLogic.h b/tslang/include/TypeScript/MLIRLogic/MLIRCodeLogic.h index 114fe8c97..618a64ec4 100644 --- a/tslang/include/TypeScript/MLIRLogic/MLIRCodeLogic.h +++ b/tslang/include/TypeScript/MLIRLogic/MLIRCodeLogic.h @@ -420,7 +420,7 @@ class MLIRCustomMethods static std::map m { {"print", true}, {"convertf", true}, {"assert", true}, {"parseInt", true}, {"parseFloat", true}, {"isNaN", true}, {"sizeof", true}, {GENERATOR_SWITCHSTATE, true}, {"LoadLibraryPermanently", true}, { "SearchForAddressOfSymbol", true }, { "LoadReference", true }, { "ReferenceOf", true }, { "Deref", true }, { "Ref", true }, - {"atomicrmw", true}, {"cmpxchg", true}, {"atomicload", true}, {"atomicstore", true}, {"fence", true}, {"inline_asm", true}, {"call_intrinsic", true}, {"linker_options", true}, {"gpuLaunch", true}, {"gpuReduce", true}, {"gpuBatch", true}, {"gpuThreadIndex", true}, {"gpuBlockIndex", true}, {"gpuBlockSize", true}, {"gpuBarrier", true}, {"gpuShared", true}, {"gpuArray", true}, {"gpuRead", true}, {"gpuWrite", true}, {"gpuFree", true} + {"atomicrmw", true}, {"cmpxchg", true}, {"atomicload", true}, {"atomicstore", true}, {"fence", true}, {"inline_asm", true}, {"call_intrinsic", true}, {"linker_options", true}, {"gpuLaunch", true}, {"gpuReduce", true}, {"gpuBatch", true}, {"gpuThreadIndex", true}, {"gpuBlockIndex", true}, {"gpuBlockSize", true}, {"gpuBarrier", true}, {"gpuShared", true}, {"gpuArray", true}, {"gpuRead", true}, {"gpuWrite", true}, {"gpuFree", true}, {"gpuLaneIndex", true}, {"gpuWarpSize", true}, {"gpuShuffle", true}, {"gpuShuffleDown", true}, {"gpuShuffleUp", true}, {"gpuShuffleXor", true}, {"gpuBallot", true}, {"gpuAll", true}, {"gpuAny", true} }; return m[functionName.str()]; } @@ -430,7 +430,7 @@ class MLIRCustomMethods static std::map m { {"print", true}, {"convertf", true}, {"assert", true}, {"sizeof", true}, {GENERATOR_SWITCHSTATE, true}, {"LoadLibraryPermanently", true}, { "SearchForAddressOfSymbol", true }, { "LoadReference", true }, { "ReferenceOf", true }, { "Deref", true }, { "Ref", true }, - {"atomicrmw", true}, {"cmpxchg", true}, {"atomicload", true}, {"atomicstore", true}, {"fence", true}, {"inline_asm", true}, {"call_intrinsic", true}, {"linker_options", true}, {"gpuLaunch", true}, {"gpuReduce", true}, {"gpuBatch", true}, {"gpuThreadIndex", true}, {"gpuBlockIndex", true}, {"gpuBlockSize", true}, {"gpuBarrier", true}, {"gpuShared", true}, {"gpuArray", true}, {"gpuRead", true}, {"gpuWrite", true}, {"gpuFree", true} + {"atomicrmw", true}, {"cmpxchg", true}, {"atomicload", true}, {"atomicstore", true}, {"fence", true}, {"inline_asm", true}, {"call_intrinsic", true}, {"linker_options", true}, {"gpuLaunch", true}, {"gpuReduce", true}, {"gpuBatch", true}, {"gpuThreadIndex", true}, {"gpuBlockIndex", true}, {"gpuBlockSize", true}, {"gpuBarrier", true}, {"gpuShared", true}, {"gpuArray", true}, {"gpuRead", true}, {"gpuWrite", true}, {"gpuFree", true}, {"gpuLaneIndex", true}, {"gpuWarpSize", true}, {"gpuShuffle", true}, {"gpuShuffleDown", true}, {"gpuShuffleUp", true}, {"gpuShuffleXor", true}, {"gpuBallot", true}, {"gpuAll", true}, {"gpuAny", true} }; return m[functionName.str()]; } diff --git a/tslang/lib/TypeScript/MLIRGenAccessCall.cpp b/tslang/lib/TypeScript/MLIRGenAccessCall.cpp index 927a5535d..2852c208f 100644 --- a/tslang/lib/TypeScript/MLIRGenAccessCall.cpp +++ b/tslang/lib/TypeScript/MLIRGenAccessCall.cpp @@ -2343,6 +2343,14 @@ namespace mlirgen return mlirGenGpuBlockBuiltin(location, functionName, typeArguments, operands, genContext); } + if (functionName == "gpuLaneIndex" || functionName == "gpuWarpSize" || functionName == "gpuShuffle" || + functionName == "gpuShuffleDown" || functionName == "gpuShuffleUp" || functionName == "gpuShuffleXor" || + functionName == "gpuBallot" || + functionName == "gpuAll" || functionName == "gpuAny") + { + return mlirGenGpuWarpBuiltin(location, functionName, operands, genContext); + } + // `print(x)` prints x as console.log does (`[ 1, 'a' ]`), not as String() makes it if (functionName == "print") { @@ -3245,6 +3253,102 @@ namespace mlirgen return V(callOp.getResult(0)); } + // What a warp's threads share (docs/gpu.md): the GPU runs a block's threads in warps (NVIDIA's 32, AMD's + // wavefronts, Intel's sub-groups), whose lanes run together and can see each other's values. gpuLaneIndex() (the + // thread's lane), gpuWarpSize(), gpuShuffle(v, lane) (v of the warp's lane `lane`), gpuShuffleDown(v, d) (of the + // lane d above, a thread's own past the warp's end), gpuShuffleUp(v, d) (of the lane d below, a thread's own + // below lane 0), gpuShuffleXor(v, m) (of lane ^ m), gpuBallot(p) (an int, a + // bit per lane p is true for), gpuAll(p) and gpuAny(p). Each is a call of a declared stub, + // `__tslang_gpu_warp_`, as gpuBarrier's (tslang/gpu.cpp lowers them per GPU); a shuffle's is + // `__tslang_gpu_warp_shuffle..`, so that each type has a stub of its own. + ValueOrLogicalResult MLIRGenImpl::mlirGenGpuWarpBuiltin(mlir::Location location, StringRef functionName, + SmallVector &operands, + const GenContext &genContext) + { + auto call = [&](StringRef name, mlir::Type result, mlir::ValueRange args) -> ValueOrLogicalResult { + auto funcOp = theModule.lookupSymbol(name); + if (!funcOp) + { + SmallVector inputs; + for (auto arg : args) + { + inputs.push_back(arg.getType()); + } + + auto funcType = mlir_ts::FunctionType::get(builder.getContext(), inputs, {result}, false); + mlir::OpBuilder::InsertionGuard guard(builder); + builder.setInsertionPointToStart(theModule.getBody()); + funcOp = mlir_ts::FuncOp::create(stripMetadata(location), name, funcType); + funcOp.setPrivate(); + pushFunction(funcOp); + } + + auto callOp = builder.create(location, funcOp, args); + return V(callOp.getResult(0)); + }; + + auto intType = builder.getIntegerType(32, true); + if (functionName == "gpuLaneIndex" || functionName == "gpuWarpSize") + { + if (!operands.empty()) + { + emitError(location) << functionName << "() takes no arguments"; + return mlir::failure(); + } + + return call(functionName == "gpuLaneIndex" ? "__tslang_gpu_warp_lane" : "__tslang_gpu_warp_size", intType, + {}); + } + + if (functionName == "gpuBallot" || functionName == "gpuAll" || functionName == "gpuAny") + { + if (operands.size() != 1) + { + emitError(location) << functionName << "(p) takes one argument, whether it is true for the thread"; + return mlir::failure(); + } + + CAST_A(predicate, location, getBooleanType(), operands[0], genContext); + auto name = functionName == "gpuBallot" ? "__tslang_gpu_warp_ballot" + : functionName == "gpuAll" ? "__tslang_gpu_warp_all" + : "__tslang_gpu_warp_any"; + mlir::Type result = functionName == "gpuBallot" ? mlir::Type(intType) : mlir::Type(getBooleanType()); + return call(name, result, {predicate}); + } + + // gpuShuffle(v, lane), gpuShuffleDown(v, delta), gpuShuffleXor(v, mask): v a number of 4 or 8 bytes + if (operands.size() != 2) + { + emitError(location) << functionName << "(v, " + << (functionName == "gpuShuffle" ? "lane" : functionName == "gpuShuffleXor" ? "mask" : "delta") + << ") takes the value and an int"; + return mlir::failure(); + } + + auto valueType = mth.wideStorageType(mth.stripLiteralType(operands[0].getType())); + std::string typeName; + if (isa(valueType)) + typeName = "number"; + else if (auto floatType = dyn_cast(valueType); floatType && (floatType.getWidth() == 32 || floatType.getWidth() == 64)) + typeName = "f" + std::to_string(floatType.getWidth()); + else if (auto integerType = dyn_cast(valueType); integerType && (integerType.getWidth() == 32 || integerType.getWidth() == 64)) + typeName = (integerType.isUnsigned() ? "u" : integerType.isSigned() ? "s" : "i") + std::to_string(integerType.getWidth()); + if (typeName.empty()) + { + emitError(location) << functionName << "'s value is a number of 4 or 8 bytes (number, float, int, ...), not '" + << to_print(operands[0].getType()) << "'"; + return mlir::failure(); + } + + CAST_A(value, location, valueType, operands[0], genContext); + CAST_A(lane, location, intType, operands[1], genContext); + auto mode = functionName == "gpuShuffle" ? "idx" + : functionName == "gpuShuffleDown" ? "down" + : functionName == "gpuShuffleUp" ? "up" + : "xor"; + return call((llvm::Twine("__tslang_gpu_warp_shuffle.") + mode + "." + typeName).str(), valueType, {value, lane}); + } + // Math.min, Math.max and Math.hypot of two or three numbers (number, an integer, float), compiled as they are: // the default library's take their arguments as an array, made on the heap for each call, which a GPU kernel // cannot make (docs/gpu.md), and which is slow on the CPU too. Their results are JavaScript's: a NaN makes min diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index 98252164b..422fc88e9 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -14864,6 +14864,9 @@ class MLIRGenImpl NodeArray typeArguments, SmallVector &operands, const GenContext &genContext); + ValueOrLogicalResult mlirGenGpuWarpBuiltin(mlir::Location location, StringRef functionName, + SmallVector &operands, const GenContext &genContext); + ValueOrLogicalResult mlirGenMathMinMaxHypot(mlir::Location location, CallExpression callExpression, StringRef name, const GenContext &genContext); diff --git a/tslang/test/gpu/CMakeLists.txt b/tslang/test/gpu/CMakeLists.txt index 24a79bb71..c6ed63187 100644 --- a/tslang/test/gpu/CMakeLists.txt +++ b/tslang/test/gpu/CMakeLists.txt @@ -405,6 +405,57 @@ if (gpu_any_backend) FAIL_REGULAR_EXPRESSION "Stack dump|Assertion failed" TIMEOUT 120) endforeach() + # a warp's builtins, for every GPU this tslang has a backend for: NVIDIA's shuffles and votes, Intel's SPIR-V + # (SPV_INTEL_subgroups) valid, AMD's linked when an ld.lld is there + set(gpu_warp_pass "call void @__tslang_gpu_run") + if ("NVPTX" IN_LIST LLVM_TARGETS_TO_BUILD) + set(gpu_warp_pass "shfl\\.sync\\.idx\\.b32.*vote\\.sync\\.ballot\\.b32") + endif() + add_test(NAME test-gpu-compile-warp + COMMAND $ --emit=llvm --no-default-lib "${gpu_compile_dir}/warp.ts" -o -) + set_tests_properties(test-gpu-compile-warp PROPERTIES + PASS_REGULAR_EXPRESSION "${gpu_warp_pass}" + FAIL_REGULAR_EXPRESSION "${gpu_fail_pattern}|LLVM ERROR" + TIMEOUT 120) + set(gpu_warp_environment "") + if (TSLANG_GPU_LLD AND gpu_lld_result EQUAL 0) + list(APPEND gpu_warp_environment "TSLANG_LLD=${TSLANG_GPU_LLD}") + endif() + if (TSLANG_SPIRV_VAL) + list(APPEND gpu_warp_environment "TSLANG_GPU_DUMP=${CMAKE_CURRENT_BINARY_DIR}/warp") + set_tests_properties(test-gpu-compile-warp PROPERTIES FIXTURES_SETUP gpu-intel-warp) + add_test(NAME test-gpu-spirv-val-warp + COMMAND "${TSLANG_SPIRV_VAL}" --target-env opencl2.2 "${CMAKE_CURRENT_BINARY_DIR}/warp.intel") + set_tests_properties(test-gpu-spirv-val-warp PROPERTIES FIXTURES_REQUIRED gpu-intel-warp TIMEOUT 60) + endif() + if (gpu_warp_environment) + set_tests_properties(test-gpu-compile-warp PROPERTIES ENVIRONMENT "${gpu_warp_environment}") + endif() + foreach(gpu_warp_error + "warp_block|'k' uses gpuShuffleDown\\(\\), so its block is of whole warps, a multiple of 32 threads: not 100" + "warp_reduce|gpuReduce cannot add up 'k': it waits at gpuBarrier or uses a warp's builtins" + "warp_cpu_call|'main' calls 'k' on the CPU, which uses gpuBallot\\(\\)" + "warp_value|gpuShuffle's value is a number of 4 or 8 bytes") + string(FIND "${gpu_warp_error}" "|" gpu_warp_sep) + string(SUBSTRING "${gpu_warp_error}" 0 ${gpu_warp_sep} gpu_warp_name) + math(EXPR gpu_warp_sep "${gpu_warp_sep} + 1") + string(SUBSTRING "${gpu_warp_error}" ${gpu_warp_sep} -1 gpu_warp_message) + string(REPLACE "_" "-" gpu_warp_test "${gpu_warp_name}") + add_test(NAME test-gpu-error-${gpu_warp_test} + COMMAND $ --emit=llvm --no-default-lib "${gpu_compile_dir}/${gpu_warp_name}.ts" -o -) + set_tests_properties(test-gpu-error-${gpu_warp_test} PROPERTIES + PASS_REGULAR_EXPRESSION "${gpu_warp_message}" + FAIL_REGULAR_EXPRESSION "Stack dump|Assertion failed" TIMEOUT 120) + endforeach() + # AMD's GPUs before gfx10 have wavefronts of 64, more lanes than gpuBallot's int has bits + if ("AMDGPU" IN_LIST LLVM_TARGETS_TO_BUILD) + add_test(NAME test-gpu-error-warp-ballot-wave64 + COMMAND $ --emit=llvm --no-default-lib --gpu-arch=gfx906 "${gpu_compile_dir}/warp.ts" -o -) + set_tests_properties(test-gpu-error-warp-ballot-wave64 PROPERTIES + PASS_REGULAR_EXPRESSION "gpuBallot\\(\\) is a mask of 32 lanes, and gfx906's wavefronts have 64" + FAIL_REGULAR_EXPRESSION "Stack dump|Assertion failed" TIMEOUT 120) + endif() + # typed arrays: a launch gives a kernel the typed array's view, copied for that launch alone (4 | 0x20000, a # float's), and a call on the CPU gives it the view too; a typed array of other elements is an error add_test(NAME test-gpu-compile-typed-arrays diff --git a/tslang/test/gpu/compile/warp.ts b/tslang/test/gpu/compile/warp.ts new file mode 100644 index 000000000..206d3e622 --- /dev/null +++ b/tslang/test/gpu/compile/warp.ts @@ -0,0 +1,21 @@ +// A warp's builtins (docs/gpu.md), each for every GPU: lanes, shuffles of 4- and 8-byte values, votes +@kernel +function warps(i: int, a: number[], f: float[], ints: int[], masks: int[]) { + const lane = gpuLaneIndex(); + const size = gpuWarpSize(); + let sum = a[i]; + for (let d = size >> 1; d > 0; d = d >> 1) sum += gpuShuffleDown(sum, d); + a[i] = sum + gpuShuffle(a[i], 0) + gpuShuffleXor(a[i], 1); + f[i] = gpuShuffle(f[i], lane + 1) + gpuShuffleXor(f[i], 2); + ints[i] = gpuShuffleDown(ints[i], 3) + gpuShuffleUp(ints[i], 2) + gpuShuffle(7, 0); + const mask = gpuBallot(a[i] > 0); + if (gpuAll(ints[i] > 0) || gpuAny(f[i] < 0)) masks[i] = mask; +} + +function main() { + const a: number[] = [1, 2, 3]; + const f: float[] = [1, 2, 3]; + const ints: int[] = [1, 2, 3]; + const masks: int[] = [0, 0, 0]; + gpuLaunch(warps, 3, a, f, ints, masks); +} diff --git a/tslang/test/gpu/compile/warp_block.ts b/tslang/test/gpu/compile/warp_block.ts new file mode 100644 index 000000000..5487c2cfd --- /dev/null +++ b/tslang/test/gpu/compile/warp_block.ts @@ -0,0 +1,10 @@ +// a kernel that uses a warp's builtins has blocks of whole warps: 100 threads is not +@kernel({ block: 100 }) +function k(i: int, a: number[]) { + a[i] = gpuShuffleDown(a[i], 1); +} + +function main() { + const a: number[] = [1, 2, 3]; + gpuLaunch(k, 3, a); +} diff --git a/tslang/test/gpu/compile/warp_cpu_call.ts b/tslang/test/gpu/compile/warp_cpu_call.ts new file mode 100644 index 000000000..a7817d54b --- /dev/null +++ b/tslang/test/gpu/compile/warp_cpu_call.ts @@ -0,0 +1,10 @@ +// a warp is a GPU's: a kernel that uses its builtins, called on the CPU, is an error +@kernel +function k(i: int, a: int[]) { + a[i] = gpuBallot(a[i] > 0); +} + +function main() { + const a: int[] = [1, 2, 3]; + k(0, a); +} diff --git a/tslang/test/gpu/compile/warp_reduce.ts b/tslang/test/gpu/compile/warp_reduce.ts new file mode 100644 index 000000000..9e968714c --- /dev/null +++ b/tslang/test/gpu/compile/warp_reduce.ts @@ -0,0 +1,10 @@ +// gpuReduce's threads each add up a different number of indices: a kernel that uses a warp's builtins is not one +@kernel +function k(i: int, a: number[]): number { + return gpuShuffle(a[i], 0); +} + +function main() { + const a: number[] = [1, 2, 3]; + print(gpuReduce(k, 3, a)); +} diff --git a/tslang/test/gpu/compile/warp_value.ts b/tslang/test/gpu/compile/warp_value.ts new file mode 100644 index 000000000..2955ae074 --- /dev/null +++ b/tslang/test/gpu/compile/warp_value.ts @@ -0,0 +1,10 @@ +// a shuffle's value is a number of 4 or 8 bytes +@kernel +function k(i: int, a: boolean[]) { + a[i] = gpuShuffle(a[i], 0); +} + +function main() { + const a: boolean[] = [true]; + gpuLaunch(k, 1, a); +} diff --git a/tslang/test/gpu/gpu_scan.ts b/tslang/test/gpu/gpu_scan.ts new file mode 100644 index 000000000..076f04777 --- /dev/null +++ b/tslang/test/gpu/gpu_scan.ts @@ -0,0 +1,67 @@ +// A prefix sum (an inclusive scan) of a warp's builtins and a block's (docs/gpu.md): each warp scans its values +// with gpuShuffleUp, the block adds each warp's total before it (in shared memory), and a second launch adds each +// block's total before it. Needs a GPU and its driver, so it is not part of the test suite. +// +// tslang --emit=exe gpu_scan.ts -o gpu_scan.exe (or tslang --emit=jit gpu_scan.ts) + +// out[i] = a[0] + ... + a[i] within the block; totals[b] = block b's sum +@kernel +function blockScan(i: int, n: int, a: int[], out: int[], totals: int[]) { + const warps = gpuShared(256); // a warp's total each: at most 256 warps of one thread + const lane = gpuLaneIndex(); + const w = gpuWarpSize(); + const t = gpuThreadIndex(); + const warp = (t / w) as int; + + let v = i < n ? a[i] : 0; + for (let d = 1; d < w; d = d << 1) { + const below = gpuShuffleUp(v, d); + if (lane >= d) v += below; + } + + if (lane == w - 1) warps[warp] = v; + gpuBarrier(); + if (t == 0) { + // the warps' totals, each the sum of those before it and its own + const count = (gpuBlockSize() / w) as int; + for (let k = 1; k < count; k++) warps[k] = warps[k] + warps[k - 1]; + } + gpuBarrier(); + + if (warp > 0) v += warps[warp - 1]; + out[i] = v; + if (t == gpuBlockSize() - 1) totals[gpuBlockIndex()] = v; +} + +// each block's values, plus the blocks' before it +@kernel +function addBefore(i: int, out: int[], before: int[]) { + out[i] = out[i] + before[(i / 256) as int]; +} + +function main() { + const n = 100000; // 391 blocks, the last of 160 values + const a: int[] = []; + for (let i = 0; i < n; i++) a.push((i * 7) % 13 - 6); + const out: int[] = []; + for (let i = 0; i < n; i++) out.push(0); + const blocks = Math.ceil(n / 256) as int; + const totals: int[] = []; + for (let b = 0; b < blocks; b++) totals.push(0); + + gpuLaunch(blockScan, n, n, a, out, totals); + // the blocks' totals before each block: few, so on the CPU + const before: int[] = [0]; + for (let b = 1; b < blocks; b++) before.push(before[b - 1] + totals[b - 1]); + gpuLaunch(addBefore, n, out, before); + + let sum = 0; + let wrong = 0; + for (let i = 0; i < n; i++) { + sum += a[i]; + if (out[i] != sum) wrong++; + } + print("scan of", n, ": out[n-1] =", out[n - 1], "expected", sum, "wrong =", wrong); + assert(wrong == 0); + print("scan: ok"); +} diff --git a/tslang/test/gpu/gpu_warp.ts b/tslang/test/gpu/gpu_warp.ts new file mode 100644 index 000000000..0c0aa361d --- /dev/null +++ b/tslang/test/gpu/gpu_warp.ts @@ -0,0 +1,141 @@ +// A warp's builtins (docs/gpu.md): gpuLaneIndex, gpuWarpSize, gpuShuffle, gpuShuffleDown, gpuShuffleXor, +// gpuBallot, gpuAll, gpuAny. A kernel that uses them runs on every thread of its blocks, as a barrier kernel: the +// arrays here are longer than n, and past n a thread's writes are dropped and it is in no vote. Its shuffled values +// are its own to give, so the kernels give 0 past n. Needs a GPU and its driver, so it is not part of the test +// suite (test/gpu/CMakeLists.txt compiles kernels on these). +// +// tslang --emit=exe gpu_warp.ts -o gpu_warp.exe (or tslang --emit=jit gpu_warp.ts) + +// each warp's sum, by halving: lane 0 has it; the warp's first index is i - lane +@kernel +function warpSums(i: int, n: int, a: number[], sums: number[]) { + let v = i < n ? a[i] : 0; + for (let d = gpuWarpSize() >> 1; d > 0; d = d >> 1) v += gpuShuffleDown(v, d); + if (gpuLaneIndex() == 0) sums[i] = v; +} + +// lanes and sizes as the block's threads give them (blocks of 256, warps a power of two) +@kernel +function lanes(i: int, lane: int[], size: int[]) { + lane[i] = gpuLaneIndex(); + size[i] = gpuWarpSize(); +} + +// shuffles of each kind and size: the warp's first value, a neighbour's, and floats and ints +@kernel +function shuffles(i: int, first: number[], swapped: number[], floats: float[], ints: int[]) { + first[i] = gpuShuffle(i * 1.5, 0); + swapped[i] = gpuShuffleXor(i * 1.0, 1); + floats[i] = gpuShuffle(i * 0.5 as float, gpuLaneIndex() + 1); + ints[i] = gpuShuffleDown(i * 2, 1); +} + +// votes, of the threads below n: the lanes whose value is odd, whether all are below 990, whether any is 995 +@kernel +function votes(i: int, a: int[], odd: int[], allBelow: int[], anyIs: int[]) { + const v = a[i]; + const mask = gpuBallot(v % 2 == 1); + const all = gpuAll(v < 990); + const any = gpuAny(v == 995); + odd[i] = mask; + allBelow[i] = all ? 1 : 0; + anyIs[i] = any ? 1 : 0; +} + +// a shuffle within lanes that run here: the even lanes swap with the even lane two away (lane ^ 2) +@kernel +function evenSwap(i: int, out: int[]) { + out[i] = -1; + if (gpuLaneIndex() % 2 == 0) out[i] = gpuShuffleXor(i, 2); +} + +function filled(length: int, below: int, value: int): int[] { + const a: int[] = []; + for (let i = 0; i < length; i++) a.push(i < below ? value : -7); + return a; +} + +function main() { + const n = 1000; // the last warp of 32 has 8 threads below n + const a: number[] = []; + for (let i = 0; i < n + 300; i++) a.push(i < n ? i : 1000000); + const sums: number[] = []; + for (let i = 0; i < n + 300; i++) sums.push(-7); + gpuLaunch(warpSums, n, n, a, sums); + + const lane = filled(n + 300, n, 0); + const size = filled(n + 300, n, 0); + gpuLaunch(lanes, n, lane, size); + const w = size[0]; + let wrong = 0; + for (let i = 0; i < n; i++) if (size[i] != w || lane[i] != i % w) wrong++; + for (let i = n; i < n + 300; i++) if (lane[i] != -7 || size[i] != -7) wrong++; + print("warp size", w, "lanes wrong =", wrong); + assert(wrong == 0 && (w == 8 || w == 16 || w == 32 || w == 64)); + + // a warp's sum: of its indices below n + wrong = 0; + for (let first = 0; first < n; first += w) { + let expected = 0; + for (let k = first; k < first + w && k < n; k++) expected += k; + if (sums[first] != expected) wrong++; + } + for (let i = n; i < n + 300; i++) if (sums[i] != -7) wrong++; + print("warp sums wrong =", wrong, "last =", sums[n - n % w]); + assert(wrong == 0); + + const first: number[] = []; + const swapped: number[] = []; + const floats: float[] = []; + const ints: int[] = []; + for (let i = 0; i < n; i++) { first.push(0); swapped.push(0); floats.push(0); ints.push(0); } + gpuLaunch(shuffles, n, first, swapped, floats, ints); + wrong = 0; + for (let i = 0; i < n; i++) { + const l = i % w; + if (first[i] != (i - l) * 1.5) wrong++; + if (swapped[i] != (i ^ 1)) wrong++; + // lane + 1 modulo the warp's size; a thread past n (in the last warp) gives its own value too + const source = i - l + (l + 1) % w; + if (floats[i] != source * 0.5) wrong++; + // lane + 1, a thread's own at the warp's end + if (ints[i] != (l == w - 1 ? i : i + 1) * 2) wrong++; + } + print("shuffles wrong =", wrong, "floats[31] =", floats[31]); + assert(wrong == 0); + + // the values: their index, 990..999 in the last warps; past n 1001 (odd, not below 990), which no vote sees + const values = filled(n + 300, n, 0); + for (let i = 0; i < n + 300; i++) values[i] = i < n ? i : 1001; + const odd = filled(n + 300, n, 0); + const allBelow = filled(n + 300, n, 0); + const anyIs = filled(n + 300, n, 0); + gpuLaunch(votes, n, values, odd, allBelow, anyIs); + wrong = 0; + for (let i = 0; i < n; i++) { + const start = i - i % w; + let mask = 0; + let all = 1; + let any = 0; + for (let k = start; k < start + w && k < n; k++) { + if (k % 2 == 1) mask = mask | (1 << (k - start)); + if (!(k < 990)) all = 0; + if (k == 995) any = 1; + } + if (odd[i] != mask || allBelow[i] != all || anyIs[i] != any) wrong++; + } + for (let i = n; i < n + 300; i++) if (odd[i] != -7) wrong++; + print("votes wrong =", wrong, "odd[0] =", odd[0], "anyIs[999] =", anyIs[999]); + assert(wrong == 0); + + const even = filled(n + 300, n, 0); + gpuLaunch(evenSwap, n, even); + wrong = 0; + for (let i = 0; i < n; i++) { + if (even[i] != (i % 2 == 0 ? i ^ 2 : -1)) wrong++; + } + print("even swap wrong =", wrong); + assert(wrong == 0); + + print("warp: ok"); +} diff --git a/tslang/tslang/gpu.cpp b/tslang/tslang/gpu.cpp index d84cb7822..fe92b393f 100644 --- a/tslang/tslang/gpu.cpp +++ b/tslang/tslang/gpu.cpp @@ -52,7 +52,9 @@ #include "llvm/IR/Module.h" #include "llvm/IR/Verifier.h" #include "llvm/Linker/Linker.h" +#include "llvm/MC/MCSubtargetInfo.h" #include "llvm/MC/TargetRegistry.h" +#include "llvm/Support/CommandLine.h" #include "llvm/Passes/PassBuilder.h" #include "llvm/Support/Error.h" #include "llvm/Support/FileSystem.h" @@ -75,6 +77,7 @@ #include #include +#include #include // gpumathIr: the GPU's Math library as LLVM IR text, NUL-terminated (gpumath/, embedded by gpumath/embed.cmake) @@ -142,6 +145,41 @@ constexpr int32_t gpuBlockThreads = 256; // barrier kernel's mark, whose last parameter is whether the thread runs for an index below n #define IS_SHARED_STUB "__tslang_gpu_is_shared" #define ACTIVE_ATTR "tslang.gpu_active" +// What a warp's threads share (MLIRGenImpl::mlirGenGpuWarpBuiltin; docs/gpu.md): its lanes run together, and a +// kernel that uses these runs like a barrier kernel, on every thread of its blocks (reachesBarrier), so that no +// lane of a warp is left out by the `i < n` check. gpuShuffle's stubs are +// `__tslang_gpu_warp_shuffle..`, the value's type only to keep each stub's own signature. +#define WARP_STUB_PREFIX "__tslang_gpu_warp_" +#define WARP_LANE_STUB "__tslang_gpu_warp_lane" +#define WARP_SIZE_STUB "__tslang_gpu_warp_size" +#define WARP_BALLOT_STUB "__tslang_gpu_warp_ballot" +#define WARP_ALL_STUB "__tslang_gpu_warp_all" +#define WARP_ANY_STUB "__tslang_gpu_warp_any" +#define WARP_SHUFFLE_PREFIX "__tslang_gpu_warp_shuffle." + +// a warp builtin's name in the program, for messages +std::string warpBuiltinWhat(llvm::StringRef name) +{ + if (name == WARP_LANE_STUB) + return "gpuLaneIndex()"; + if (name == WARP_SIZE_STUB) + return "gpuWarpSize()"; + if (name == WARP_BALLOT_STUB) + return "gpuBallot()"; + if (name == WARP_ALL_STUB) + return "gpuAll()"; + if (name == WARP_ANY_STUB) + return "gpuAny()"; + if (name.starts_with(WARP_SHUFFLE_PREFIX "down")) + return "gpuShuffleDown()"; + if (name.starts_with(WARP_SHUFFLE_PREFIX "up")) + return "gpuShuffleUp()"; + if (name.starts_with(WARP_SHUFFLE_PREFIX "xor")) + return "gpuShuffleXor()"; + if (name.starts_with(WARP_SHUFFLE_PREFIX)) + return "gpuShuffle()"; + return ""; +} // gpuThreadIndex(d), gpuBlockIndex(d), gpuBlockSize(d): the stub of x is THREAD_INDEX_STUB (and the others), of y // `|1`, of z `|2`. The stub without the dimension, and the dimension. @@ -166,7 +204,7 @@ bool isBlockBuiltin(llvm::StringRef name) { auto stub = blockBuiltinOf(name).first; return stub == THREAD_INDEX_STUB || stub == BLOCK_INDEX_STUB || stub == BLOCK_SIZE_STUB || name == BARRIER_STUB || - name.starts_with(SHARED_STUB_PREFIX) || name == IS_SHARED_STUB; + name.starts_with(SHARED_STUB_PREFIX) || name == IS_SHARED_STUB || name.starts_with(WARP_STUB_PREFIX); } BlockShape kernelBlock(const llvm::Function *kernel) @@ -191,7 +229,8 @@ BlockShape kernelBlock(const llvm::Function *kernel) return shape; } -// whether a function waits at gpuBarrier, itself or through what it calls +// whether a function waits at gpuBarrier or uses a warp's builtins, itself or through what it calls: either needs +// every thread of its block (a barrier kernel) bool reachesBarrier(llvm::Function *function) { llvm::SmallVector work{function}; @@ -204,7 +243,7 @@ bool reachesBarrier(llvm::Function *function) continue; } - if (current->getName() == BARRIER_STUB) + if (current->getName() == BARRIER_STUB || current->getName().starts_with(WARP_STUB_PREFIX)) { return true; } @@ -1417,6 +1456,33 @@ void guardBarrierKernels(llvm::Module &device, const std::set &kern } } + // a warp's vote counts the threads that run for an index below n only: a thread past n is in no ballot, is + // no gpuAny's true, and no gpuAll's false + for (auto [function, clone] : guarded) + { + auto active = clone->getArg(clone->arg_size() - 1); + for (auto &instruction : llvm::instructions(*clone)) + { + auto call = llvm::dyn_cast(&instruction); + auto callee = call ? call->getCalledFunction() : nullptr; + if (!callee || call->arg_size() != 1) + { + continue; + } + + auto name = callee->getName(); + llvm::IRBuilder<> builder(call); + if (name == WARP_BALLOT_STUB || name == WARP_ANY_STUB) + { + call->setArgOperand(0, builder.CreateAnd(call->getArgOperand(0), active)); + } + else if (name == WARP_ALL_STUB) + { + call->setArgOperand(0, builder.CreateOr(call->getArgOperand(0), builder.CreateNot(active))); + } + } + } + // the barrier kernels are their clones now, under their names for (auto kernel : barrierKernels) { @@ -1677,10 +1743,138 @@ llvm::Expected> prepareDeviceModule(llvm::Module & return std::move(device); } +// An OpenCL sub-group function of Intel's GPUs: convergent, so that nothing moves it to where fewer of the +// sub-group's work items reach it +llvm::Value *subGroupCall(llvm::IRBuilder<> &builder, llvm::StringRef name, llvm::Type *result, + llvm::ArrayRef args) +{ + auto call = llvm::cast(openClCall(builder, name, result, args)); + call->getCalledFunction()->addFnAttr(llvm::Attribute::Convergent); + call->addFnAttr(llvm::Attribute::Convergent); + return call; +} + +// the thread's lane in its warp (an i32) +llvm::Value *warpLane(llvm::IRBuilder<> &builder, const GpuTarget &target) +{ + if (target.intel()) + { + return subGroupCall(builder, "_Z22get_sub_group_local_idv", builder.getInt32Ty(), {}); + } + + if (target.amd()) + { + // HIP's __lane_id(): the lanes below this one, of all of them + auto all = builder.getInt32(-1); + auto low = builder.CreateIntrinsic(llvm::Intrinsic::amdgcn_mbcnt_lo, {all, builder.getInt32(0)}); + return builder.CreateIntrinsic(llvm::Intrinsic::amdgcn_mbcnt_hi, {all, low}); + } + + return builder.CreateIntrinsic(llvm::Intrinsic::nvvm_read_ptx_sreg_laneid, {}); +} + +// the warp's size (an i32): NVIDIA's 32, AMD's wavefront (32 on the GPUs from gfx10 on, 64 before), Intel's +// sub-group, which its driver picks per kernel (8, 16 or 32; the block's last can be smaller) +llvm::Value *warpSize(llvm::IRBuilder<> &builder, const GpuTarget &target, unsigned waveSize) +{ + if (target.intel()) + { + return subGroupCall(builder, "_Z18get_sub_group_sizev", builder.getInt32Ty(), {}); + } + + return builder.getInt32(target.amd() ? waveSize : 32); +} + +// the 32 bits of `value` of the warp's lane `source` (an i32 below the warp's size) +llvm::Value *shuffle32(llvm::IRBuilder<> &builder, const GpuTarget &target, llvm::Value *value, llvm::Value *source) +{ + if (target.intel()) + { + // SPV_INTEL_subgroups' OpSubgroupShuffleINTEL + return subGroupCall(builder, "_Z23intel_sub_group_shufflejj", builder.getInt32Ty(), {value, source}); + } + + if (target.amd()) + { + // the lanes' values by address, 4 bytes a lane + return builder.CreateIntrinsic(llvm::Intrinsic::amdgcn_ds_bpermute, + {builder.CreateShl(source, 2), value}); + } + + // of the lanes that run here, as CUDA's __shfl_sync(__activemask(), ...) + auto mask = builder.CreateIntrinsic(llvm::Intrinsic::nvvm_activemask, {}); + return builder.CreateIntrinsic(llvm::Intrinsic::nvvm_shfl_sync_idx_i32, + {mask, value, source, builder.getInt32(0x1f)}); +} + +// a number (4 or 8 bytes: an int, float, number, a 64-bit integer) of the warp's lane `source` +llvm::Value *shuffleValue(llvm::IRBuilder<> &builder, const GpuTarget &target, llvm::Value *value, llvm::Value *source) +{ + auto type = value->getType(); + auto bits = type->getPrimitiveSizeInBits().getFixedValue(); + auto i32 = builder.getInt32Ty(); + if (bits == 32) + { + return builder.CreateBitCast(shuffle32(builder, target, builder.CreateBitCast(value, i32), source), type); + } + + // 64 bits: each half + auto i64 = builder.getInt64Ty(); + auto whole = builder.CreateBitCast(value, i64); + auto low = shuffle32(builder, target, builder.CreateTrunc(whole, i32), source); + auto high = shuffle32(builder, target, builder.CreateTrunc(builder.CreateLShr(whole, 32), i32), source); + auto joined = builder.CreateOr(builder.CreateZExt(low, i64), builder.CreateShl(builder.CreateZExt(high, i64), 32)); + return builder.CreateBitCast(joined, type); +} + +// the lanes for which `predicate` is true, a bit each (lane 0 the lowest), of the warp's lanes that run here +llvm::Value *warpBallot(llvm::IRBuilder<> &builder, const GpuTarget &target, llvm::Value *predicate, unsigned waveSize) +{ + if (target.intel()) + { + // the sub-group's sum of each work item's own bit (SPIR-V 1.2 has no ballot without an extension) + auto bit = builder.CreateShl(builder.CreateZExt(predicate, builder.getInt32Ty()), warpLane(builder, target)); + return subGroupCall(builder, "_Z20sub_group_reduce_addj", builder.getInt32Ty(), {bit}); + } + + if (target.amd()) + { + auto waveType = builder.getIntNTy(waveSize); + return builder.CreateIntrinsic(llvm::Intrinsic::amdgcn_ballot, {waveType}, {predicate}); + } + + auto mask = builder.CreateIntrinsic(llvm::Intrinsic::nvvm_activemask, {}); + return builder.CreateIntrinsic(llvm::Intrinsic::nvvm_vote_ballot_sync, {mask, predicate}); +} + +// whether `predicate` is true for all (or any) of the warp's lanes that run here +llvm::Value *warpVote(llvm::IRBuilder<> &builder, const GpuTarget &target, llvm::Value *predicate, bool all, + unsigned waveSize) +{ + if (target.intel()) + { + auto vote = subGroupCall(builder, all ? "_Z13sub_group_alli" : "_Z13sub_group_anyi", builder.getInt32Ty(), + {builder.CreateZExt(predicate, builder.getInt32Ty())}); + return builder.CreateIsNotNull(vote); + } + + if (target.amd()) + { + auto ballot = warpBallot(builder, target, predicate, waveSize); + // all: the lanes it is true for are the lanes that run here (exec, the ballot of true) + return all ? builder.CreateICmpEQ(ballot, warpBallot(builder, target, builder.getTrue(), waveSize)) + : builder.CreateIsNotNull(ballot); + } + + auto mask = builder.CreateIntrinsic(llvm::Intrinsic::nvvm_activemask, {}); + return builder.CreateIntrinsic(all ? llvm::Intrinsic::nvvm_vote_all_sync : llvm::Intrinsic::nvvm_vote_any_sync, + {mask, predicate}); +} + // The block's builtins as the GPU has them: its thread and block ids, its barrier, and for each gpuShared stub an // array in the block's shared memory (address space 3 on every GPU here), whose header is a local of the function // that asks for it. After the address-space work, so that what is made here stays where it is put. -void lowerBlockBuiltins(llvm::Module &device, const GpuTarget &target) +llvm::Error lowerBlockBuiltins(llvm::Module &device, const GpuTarget &target, unsigned waveSize) { auto &context = device.getContext(); auto i64 = llvm::Type::getInt64Ty(context); @@ -1772,6 +1966,52 @@ void lowerBlockBuiltins(llvm::Module &device, const GpuTarget &target) builder.CreateIntrinsic(llvm::Intrinsic::nvvm_barrier_cta_sync_all, {builder.getInt32(0)}); } } + else if (name == WARP_LANE_STUB) + { + result = warpLane(builder, target); + } + else if (name == WARP_SIZE_STUB) + { + result = warpSize(builder, target, waveSize); + } + else if (name == WARP_BALLOT_STUB) + { + if (target.amd() && waveSize > 32) + { + return makeError("gpuBallot() is a mask of 32 lanes, and " + target.arch + + "'s wavefronts have 64 (an AMD GPU from gfx10 on has 32)"); + } + + result = warpBallot(builder, target, call->getArgOperand(0), waveSize); + } + else if (name == WARP_ALL_STUB || name == WARP_ANY_STUB) + { + result = warpVote(builder, target, call->getArgOperand(0), name == WARP_ALL_STUB, waveSize); + } + else if (name.starts_with(WARP_SHUFFLE_PREFIX)) + { + // the lane to read: gpuShuffle(v, lane) the lane modulo the warp's size, as CUDA's __shfl_sync; + // gpuShuffleDown(v, d) lane + d, gpuShuffleUp(v, d) lane - d and gpuShuffleXor(v, m) lane ^ m, a + // thread's own beyond the warp (lane - d below 0 is a large unsigned, so beyond it too) + auto value = call->getArgOperand(0); + auto argument = builder.CreateZExtOrTrunc(call->getArgOperand(1), builder.getInt32Ty()); + auto size = warpSize(builder, target, waveSize); + llvm::Value *source; + if (name.starts_with(WARP_SHUFFLE_PREFIX "idx")) + { + source = builder.CreateURem(argument, size); + } + else + { + auto lane = warpLane(builder, target); + auto wanted = name.starts_with(WARP_SHUFFLE_PREFIX "down") ? builder.CreateAdd(lane, argument) + : name.starts_with(WARP_SHUFFLE_PREFIX "up") ? builder.CreateSub(lane, argument) + : builder.CreateXor(lane, argument); + source = builder.CreateSelect(builder.CreateICmpULT(wanted, size), wanted, lane); + } + + result = shuffleValue(builder, target, value, source); + } else if (name == IS_SHARED_STUB) { auto pointer = call->getArgOperand(0); @@ -1824,7 +2064,9 @@ void lowerBlockBuiltins(llvm::Module &device, const GpuTarget &target) if (result && !call->getType()->isVoidTy()) { - call->replaceAllUsesWith(builder.CreateZExtOrTrunc(result, call->getType())); + call->replaceAllUsesWith(result->getType() == call->getType() + ? result + : builder.CreateZExtOrTrunc(result, call->getType())); } call->eraseFromParent(); @@ -1832,6 +2074,8 @@ void lowerBlockBuiltins(llvm::Module &device, const GpuTarget &target) stub->eraseFromParent(); } + + return llvm::Error::success(); } // the prepared device module compiled for one GPU @@ -1862,6 +2106,20 @@ llvm::Expected compileForTarget(const llvm::Module &prepared, } llvm::TargetOptions options; + if (target.intel()) + { + // gpuShuffle's OpSubgroupShuffleINTEL is SPV_INTEL_subgroups' (Level Zero's drivers have it): the backend + // takes the extensions it may use from its option only, `-spirv-ext`, so it is given that + static std::once_flag extensionsSet; + std::call_once(extensionsSet, [] { + auto ®istered = llvm::cl::getRegisteredOptions(); + if (auto found = registered.find("spirv-ext"); found != registered.end()) + { + found->second->addOccurrence(0, "spirv-ext", "+SPV_INTEL_subgroups"); + } + }); + } + // Intel: the IR is optimized (O3, below) and the driver compiles the SPIR-V for its GPU; the backend's own // optimizations moved blocks before the blocks that dominate them, which SPIR-V does not allow (the Math // library's loops), so it runs without them @@ -1911,7 +2169,17 @@ llvm::Expected compileForTarget(const llvm::Module &prepared, device = toGenericPointers(*device); } - lowerBlockBuiltins(*device, target); + // AMD's wavefront: 32 lanes on the GPUs from gfx10 on (LLVM's default there), 64 before + unsigned waveSize = 32; + if (target.amd() && machine->getMCSubtargetInfo().checkFeatures("+wavefrontsize64")) + { + waveSize = 64; + } + + if (auto error = lowerBlockBuiltins(*device, target, waveSize)) + { + return std::move(error); + } // a kernel's entry is the GPU's kind of function auto makeEntry = [&](llvm::Function *entry, unsigned threads) { @@ -2264,7 +2532,7 @@ static llvm::Error refuseBlockBuiltinsOnCpu(llvm::Module &module) : name == BLOCK_INDEX_STUB ? "gpuBlockIndex()" : name == BARRIER_STUB ? "gpuBarrier()" : name.starts_with(SHARED_STUB_PREFIX) ? "gpuShared()" - : ""; + : warpBuiltinWhat(name); reached[function] = what; return what; } @@ -2355,11 +2623,12 @@ static void stopBlockBuiltinsOnCpu(llvm::Module &module) for (auto stub : stubs) { auto [name, dimension] = blockBuiltinOf(stub->getName()); - auto what = name == THREAD_INDEX_STUB ? "gpuThreadIndex()" - : name == BLOCK_INDEX_STUB ? "gpuBlockIndex()" - : name == BARRIER_STUB ? "gpuBarrier()" - : name == BLOCK_SIZE_STUB ? "gpuBlockSize()" - : "gpuShared()"; + std::string what = name == THREAD_INDEX_STUB ? "gpuThreadIndex()" + : name == BLOCK_INDEX_STUB ? "gpuBlockIndex()" + : name == BARRIER_STUB ? "gpuBarrier()" + : name == BLOCK_SIZE_STUB ? "gpuBlockSize()" + : name.starts_with(SHARED_STUB_PREFIX) ? "gpuShared()" + : warpBuiltinWhat(name); for (auto user : llvm::make_early_inc_range(stub->users())) { auto call = llvm::dyn_cast(user); @@ -2796,7 +3065,40 @@ llvm::Error outlineGpuKernels(llvm::Module &module, const std::vectorgetFunction(kernelName))) { return makeError("gpuReduce cannot add up '" + kernelName + - "': it waits at gpuBarrier, which every thread of a block has to reach (gpuLaunch it)"); + "': it waits at gpuBarrier or uses a warp's builtins (gpuShuffle, gpuBallot, ...), " + "which every thread of a block has to reach (gpuLaunch it)"); + } + } + + // a kernel that uses a warp's builtins has blocks of whole warps: of a block of 100, the last warp would be 4 + // threads, which a GPU runs as a warp of 32 with 28 lanes missing + for (auto &[kernelName, dimensionsLaunched] : launchKernels) + { + auto kernel = (*prepared)->getFunction(kernelName); + if (!kernel) + { + continue; + } + + auto threads = kernelBlock(kernel).threads(); + if (threads % 32 == 0) + { + continue; + } + + for (auto function : reachedFrom({kernel})) + { + for (auto &instruction : llvm::instructions(*function)) + { + auto call = llvm::dyn_cast(&instruction); + auto callee = call ? call->getCalledFunction() : nullptr; + if (callee && callee->getName().starts_with(WARP_STUB_PREFIX)) + { + return makeError("'" + kernelName + "' uses " + warpBuiltinWhat(callee->getName()) + + ", so its block is of whole warps, a multiple of 32 threads: not " + + llvm::Twine(threads)); + } + } } } From 1bf19d56f2b60a04adaedb1a9c397e3a9406ab87 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Wed, 2 Dec 2026 12:28:26 +0000 Subject: [PATCH 2/4] docs/gpu.md: a warp's builtins; every running GPU test passes on Linux (WSL) too Co-Authored-By: Claude Opus 5.5 --- docs/gpu.md | 45 ++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 42 insertions(+), 3 deletions(-) diff --git a/docs/gpu.md b/docs/gpu.md index 9a9f2fed1..6b3b479c9 100644 --- a/docs/gpu.md +++ b/docs/gpu.md @@ -247,6 +247,46 @@ gpuLaunch(matmul, [p, m], a, b, c, m, k, p); - `tslang/test/gpu/gpu_blocks.ts` checks a block sum in blocks of 128, a 70 x 90 tiled matrix product (not a multiple of 16), a 4 x 4 x 4 block, and blocks of 64 and 512 sharing a function, against the CPU. +## Threads that run together: warps + +The GPU runs a block's threads in warps, groups whose lanes run each step together and can read each other's +values directly, without shared memory or a barrier: a warp's sum, a vote, a prefix sum. + +- `gpuWarpSize()`: the warp's lanes. 32 on NVIDIA's GPUs and on AMD's from gfx10 on (RDNA; 64 on the ones before, + as gfx906); on Intel's the driver picks 8, 16 or 32 for each kernel. Use it rather than a number. +- `gpuLaneIndex()`: the thread's lane, 0 to `gpuWarpSize() - 1`. In a block of one dimension the warps are the + block's threads in order: lane `gpuThreadIndex() % gpuWarpSize()`. +- `gpuShuffle(v, lane)`: `v` of the warp's lane `lane` (modulo the warp's size). `gpuShuffleDown(v, d)`: of the lane + `d` above, `gpuShuffleUp(v, d)` of the lane `d` below, `gpuShuffleXor(v, m)` of lane `^ m`; a thread whose lane + would be outside the warp gets its own `v`. `v` is a number of 4 or 8 bytes (`number`, `float`, `int`, ...), + as CUDA's `__shfl_sync`, `__shfl_down_sync`, `__shfl_up_sync`, `__shfl_xor_sync`. +- `gpuBallot(p)`: an `int` with a bit for each lane `p` is true for (lane 0 the lowest). `gpuAll(p)`, `gpuAny(p)`: + whether `p` is true for all, or any, of the warp's lanes. + +```ts +// each warp's sum, which its lane 0 writes +@kernel +function warpSums(i: int, n: int, a: number[], sums: number[]) { + let v = i < n ? a[i] : 0; + for (let d = gpuWarpSize() >> 1; d > 0; d = d >> 1) v += gpuShuffleDown(v, d); + if (gpuLaneIndex() == 0) sums[i] = v; +} +``` + +- The lanes have to run together, so a kernel that uses these runs as one that waits at `gpuBarrier` does (above): + on every thread of its blocks, past `n` too, with its array accesses guarded. A thread past `n` is in no vote + (it is no bit of a ballot, no `gpuAny`'s true, no `gpuAll`'s false), but what it gives a shuffle is its own + `v`: so `warpSums` gives 0 past `n` itself (`i < n ? a[i] : 0`). +- A shuffle reads the lanes that run with it: in an `if` only some lanes take, a lane that does not is not there + to read (on NVIDIA its value is undefined). `gpuShuffleXor(v, 2)` among the even lanes is fine; reading an odd + lane from there is not. +- Its block is of whole warps, a multiple of 32 threads (`@kernel({ block: 100 })` is an error); `gpuReduce` does + not take it, and a call of it on the CPU is an error, as for a barrier kernel. On AMD's GPUs before gfx10 + `gpuBallot` is an error: their 64 lanes do not fit in an `int`. +- `tslang/test/gpu/gpu_warp.ts` checks each of them on 1000 threads (the last warp partly past `n`), with arrays + longer than that; `gpu_scan.ts` is a prefix sum of 100000 values: each warp's of `gpuShuffleUp`, each block's of + its warps' totals in shared memory, then the blocks' (on the RTX 5080: warps of 32). + ## Combining what the threads find: `Atomics` Threads that write the same element would overwrite each other. `Atomics.add(a, i, v)` and the rest, given a @@ -497,13 +537,12 @@ Arithmetic on `number`s brings 64-bit floats back: `Math.sqrt(v) + 1` is a `numb ## What has been run The NVIDIA path runs on an RTX 5080, as executables and under the JIT, on Windows and on Linux (Ubuntu under WSL2, -whose CUDA driver is the Windows one's: the running tests below up to `gpu_call.ts` pass there too; those after it -have been run on Windows only so far). The AMD and Intel ones are checked as +whose CUDA driver is the Windows one's: the running tests below pass there too). The AMD and Intel ones are checked as far as their compiled code goes (the AMD code object's kernel table, the SPIR-V by `spirv-val`): neither has been run on its GPU yet. The test suite compiles a kernel for every GPU there is a backend for, and checks the errors (`tslang/test/gpu`). Running ones, which need a GPU: `tslang/test/gpu/gpu_add_arrays.ts`, `gpu_saxpy_table.ts`, `gpu_add_ints.ts`, `gpu_math.ts`, `gpu_copy_back.ts`, `gpu_batch.ts`, `gpu_float.ts`, -`gpu_atomics.ts`, `gpu_reduce.ts`, `gpu_batch_temporaries.ts`, `gpu_math_library.ts`, `gpu_shared.ts`, `gpu_grid.ts`, `gpu_call.ts`, `gpu_min_max.ts`, `gpu_array.ts`, `gpu_array_collect.ts`, `gpu_async.ts`, `gpu_barrier_guard.ts`, `gpu_blocks.ts`, `gpu_typed_arrays.ts`. +`gpu_atomics.ts`, `gpu_reduce.ts`, `gpu_batch_temporaries.ts`, `gpu_math_library.ts`, `gpu_shared.ts`, `gpu_grid.ts`, `gpu_call.ts`, `gpu_min_max.ts`, `gpu_array.ts`, `gpu_array_collect.ts`, `gpu_async.ts`, `gpu_barrier_guard.ts`, `gpu_blocks.ts`, `gpu_typed_arrays.ts`, `gpu_warp.ts`, `gpu_scan.ts`. ## Not yet From 515708e0aff78ed4a1a271190e24eba6693c95c4 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Wed, 2 Dec 2026 12:39:25 +0000 Subject: [PATCH 3/4] Arrays of tuples and object types as kernel arguments: { x: number, y: number }[], [number, int][] Their elements are structs held by value, one after another, laid out alike on the CPU and every GPU: the launch passes each element's size (gpuElementSize: numbers, integers, floats, booleans and nested tuples, each at its alignment), and gpuReduce, GpuArray and gpuBatch take them as they take numbers. A barrier kernel's guard sees through a field's GEP to the element. A tuple with a string, an array or a class in it is refused. gpu_structs.ts (particles, padded fields, nested, whole elements, GpuArray, gpuReduce, a barrier kernel past n) passes on the RTX 5080, JIT and exe. Co-Authored-By: Claude Opus 5.5 --- tslang/lib/TypeScript/MLIRGenAccessCall.cpp | 82 +++++++----- tslang/lib/TypeScript/MLIRGenImpl.h | 2 + tslang/test/gpu/CMakeLists.txt | 28 ++++ tslang/test/gpu/compile/struct_element.ts | 10 ++ tslang/test/gpu/compile/structs.ts | 28 ++++ tslang/test/gpu/gpu_structs.ts | 140 ++++++++++++++++++++ tslang/tslang/gpu.cpp | 14 ++ 7 files changed, 274 insertions(+), 30 deletions(-) create mode 100644 tslang/test/gpu/compile/struct_element.ts create mode 100644 tslang/test/gpu/compile/structs.ts create mode 100644 tslang/test/gpu/gpu_structs.ts diff --git a/tslang/lib/TypeScript/MLIRGenAccessCall.cpp b/tslang/lib/TypeScript/MLIRGenAccessCall.cpp index 2852c208f..61dbf363d 100644 --- a/tslang/lib/TypeScript/MLIRGenAccessCall.cpp +++ b/tslang/lib/TypeScript/MLIRGenAccessCall.cpp @@ -2514,15 +2514,7 @@ namespace mlirgen return mlir::failure(); } - auto byteSize = [&](mlir::Type type) -> int { - if (isa(type)) - return 8; - if (auto intType = dyn_cast(type)) - return intType.getWidth() / 8; - if (auto floatType = dyn_cast(type)) - return floatType.getWidth() / 8; - return 0; - }; + auto byteSize = [&](mlir::Type type) -> int { return gpuElementSize(type); }; std::string kinds; // the kernel itself first: it keeps the kernel in the module (under the JIT a program's functions are @@ -2613,7 +2605,9 @@ namespace mlirgen if (kind == 1 || (isa(type) && kind == 0)) { - emitError(location, "a @kernel parameter is an array of numbers or a number: ") << type; + emitError(location, "a @kernel parameter is a number, or an array of numbers or of tuples and object " + "types of numbers: ") + << type; return mlir::failure(); } @@ -2762,13 +2756,7 @@ namespace mlirgen mlir_ts::FuncOp MLIRGenImpl::gpuArrayStub(mlir::Location location, StringRef what, mlir::Type elementType, ArrayRef inputs, mlir::Type result) { - auto elementSize = 0u; - if (isa(elementType)) - elementSize = 8; - else if (auto floatType = dyn_cast(elementType)) - elementSize = floatType.getWidth() / 8; - else if (auto integerType = dyn_cast(elementType)) - elementSize = integerType.getWidth() / 8; + auto elementSize = gpuElementSize(elementType); std::string typeName; llvm::raw_string_ostream typeStream(typeName); @@ -2921,25 +2909,15 @@ namespace mlirgen return mlir::failure(); } - auto elementSizeOf = [](mlir::Type elementType) { - if (isa(elementType)) - return 8u; - if (auto floatType = dyn_cast(elementType)) - return floatType.getWidth() / 8; - if (auto integerType = dyn_cast(elementType)) - return integerType.getWidth() / 8; - return 0u; - }; - auto stub = [&](StringRef what, mlir::Type elementType, ArrayRef inputs, mlir::Type result) { return gpuArrayStub(location, what, elementType, inputs, result); }; auto elementCheck = [&](mlir::Type elementType) { - auto size = elementSizeOf(elementType); - if (size != 1 && size != 2 && size != 4 && size != 8) + if (!gpuElementSize(elementType)) { - emitError(location, "a GpuArray's elements are numbers (number, float, int, ...), not '") + emitError(location, "a GpuArray's elements are numbers (number, float, int, ...) or tuples and " + "object types of those, not '") << to_print(elementType) << "'"; return false; } @@ -3253,6 +3231,50 @@ namespace mlirgen return V(callOp.getResult(0)); } + // The bytes of a value a kernel's array holds, as LLVM lays it out on the CPU and on every GPU alike (all are + // 64-bit, each type aligned to its size): a number, an integer, a float, and a tuple or object literal type + // (`[number, int]`, `{ x: number, y: number }`, held by value) of those and of booleans (a byte), its fields in + // order, each at its alignment, the whole a multiple of its largest. 0 for anything else (a string, an array, + // a class: a pointer, which is the CPU's). + int MLIRGenImpl::gpuElementSize(mlir::Type type, int *alignment) + { + int size = 0; + int align = 0; + if (isa(type)) + size = align = 8; + else if (isa(type)) + size = align = 1; + else if (auto intType = dyn_cast(type); + intType && (intType.getWidth() == 8 || intType.getWidth() == 16 || intType.getWidth() == 32 || + intType.getWidth() == 64)) + size = align = intType.getWidth() / 8; + else if (auto floatType = dyn_cast(type); + floatType && (floatType.getWidth() == 16 || floatType.getWidth() == 32 || floatType.getWidth() == 64)) + size = align = floatType.getWidth() / 8; + else if (auto tupleType = dyn_cast(type)) + { + align = 1; + for (auto field : tupleType.getFields()) + { + int fieldAlign = 0; + auto fieldSize = gpuElementSize(field.type, &fieldAlign); + if (!fieldSize) + return 0; + size = (size + fieldAlign - 1) / fieldAlign * fieldAlign + fieldSize; + align = std::max(align, fieldAlign); + } + + if (!size) + return 0; + size = (size + align - 1) / align * align; + } + + if (alignment) + *alignment = align; + // GpuRuntime.c's kinds keep an element's size in 16 bits + return size < 0x10000 ? size : 0; + } + // What a warp's threads share (docs/gpu.md): the GPU runs a block's threads in warps (NVIDIA's 32, AMD's // wavefronts, Intel's sub-groups), whose lanes run together and can see each other's values. gpuLaneIndex() (the // thread's lane), gpuWarpSize(), gpuShuffle(v, lane) (v of the warp's lane `lane`), gpuShuffleDown(v, d) (of the diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index 422fc88e9..85cbe0850 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -14864,6 +14864,8 @@ class MLIRGenImpl NodeArray typeArguments, SmallVector &operands, const GenContext &genContext); + int gpuElementSize(mlir::Type type, int *alignment = nullptr); + ValueOrLogicalResult mlirGenGpuWarpBuiltin(mlir::Location location, StringRef functionName, SmallVector &operands, const GenContext &genContext); diff --git a/tslang/test/gpu/CMakeLists.txt b/tslang/test/gpu/CMakeLists.txt index c6ed63187..62774cfd7 100644 --- a/tslang/test/gpu/CMakeLists.txt +++ b/tslang/test/gpu/CMakeLists.txt @@ -456,6 +456,34 @@ if (gpu_any_backend) FAIL_REGULAR_EXPRESSION "Stack dump|Assertion failed" TIMEOUT 120) endif() + # arrays of tuples and object types: each element's bytes as LLVM lays them out (Mixed 32 with its padding, + # [number, int] 16 and only read, 0x10000), for every GPU; Intel's SPIR-V valid + add_test(NAME test-gpu-compile-structs + COMMAND $ --emit=llvm --no-default-lib "${gpu_compile_dir}/structs.ts" -o -) + set_tests_properties(test-gpu-compile-structs PROPERTIES + PASS_REGULAR_EXPRESSION "\\[2 x i32\\] \\[i32 32, i32 65552\\].*\\[1 x i32\\] \\[i32 24\\]|\\[1 x i32\\] \\[i32 24\\].*\\[2 x i32\\] \\[i32 32, i32 65552\\]" + FAIL_REGULAR_EXPRESSION "${gpu_fail_pattern}|LLVM ERROR" + TIMEOUT 120) + set(gpu_structs_environment "") + if (TSLANG_GPU_LLD AND gpu_lld_result EQUAL 0) + list(APPEND gpu_structs_environment "TSLANG_LLD=${TSLANG_GPU_LLD}") + endif() + if (TSLANG_SPIRV_VAL) + list(APPEND gpu_structs_environment "TSLANG_GPU_DUMP=${CMAKE_CURRENT_BINARY_DIR}/structs") + set_tests_properties(test-gpu-compile-structs PROPERTIES FIXTURES_SETUP gpu-intel-structs) + add_test(NAME test-gpu-spirv-val-structs + COMMAND "${TSLANG_SPIRV_VAL}" --target-env opencl2.2 "${CMAKE_CURRENT_BINARY_DIR}/structs.intel") + set_tests_properties(test-gpu-spirv-val-structs PROPERTIES FIXTURES_REQUIRED gpu-intel-structs TIMEOUT 60) + endif() + if (gpu_structs_environment) + set_tests_properties(test-gpu-compile-structs PROPERTIES ENVIRONMENT "${gpu_structs_environment}") + endif() + add_test(NAME test-gpu-error-struct-element + COMMAND $ --emit=llvm --no-default-lib "${gpu_compile_dir}/struct_element.ts" -o -) + set_tests_properties(test-gpu-error-struct-element PROPERTIES + PASS_REGULAR_EXPRESSION "a @kernel parameter is a number, or an array of numbers or of tuples and object types of numbers" + FAIL_REGULAR_EXPRESSION "Stack dump|Assertion failed" TIMEOUT 120) + # typed arrays: a launch gives a kernel the typed array's view, copied for that launch alone (4 | 0x20000, a # float's), and a call on the CPU gives it the view too; a typed array of other elements is an error add_test(NAME test-gpu-compile-typed-arrays diff --git a/tslang/test/gpu/compile/struct_element.ts b/tslang/test/gpu/compile/struct_element.ts new file mode 100644 index 000000000..a5219f5bc --- /dev/null +++ b/tslang/test/gpu/compile/struct_element.ts @@ -0,0 +1,10 @@ +// a tuple with a string in it is the CPU's: not for a kernel +@kernel +function k(i: int, ps: { x: number, name: string }[]) { + ps[i].x = i; +} + +function main() { + const ps: { x: number, name: string }[] = [{ x: 1, name: "a" }]; + gpuLaunch(k, 1, ps); +} diff --git a/tslang/test/gpu/compile/structs.ts b/tslang/test/gpu/compile/structs.ts new file mode 100644 index 000000000..b0a2ab0cc --- /dev/null +++ b/tslang/test/gpu/compile/structs.ts @@ -0,0 +1,28 @@ +// arrays of tuples and object types, for every GPU: fields of each size (padding between them), nested, a whole +// element written, in a barrier kernel too; their element sizes in the launch's kinds (32, 16 | 0x10000 read only) +type Mixed = { a: byte, b: number, c: float, d: boolean, e: int }; + +@kernel +function mix(i: int, ms: Mixed[], ts: [number, int][]) { + ms[i].a = ms[i].a + 1; + ms[i].b = ms[i].b * ts[i][0]; + ms[i].d = !ms[i].d; + ms[i].e = ts[i][1]; +} + +@kernel +function shifted(i: int, ps: { pos: { x: number, y: number }, m: number }[]) { + const tile = gpuShared(256); + tile[gpuThreadIndex()] = ps[i].pos.x; + gpuBarrier(); + ps[i].pos.y = tile[0]; + ps[i] = { pos: { x: 1, y: 2 }, m: ps[i].m }; +} + +function main() { + const ms: Mixed[] = [{ a: 1, b: 2, c: 3, d: true, e: 5 }]; + const ts: [number, int][] = [[1, 2]]; + gpuLaunch(mix, 1, ms, ts); + const ps: { pos: { x: number, y: number }, m: number }[] = [{ pos: { x: 1, y: 2 }, m: 3 }]; + gpuLaunch(shifted, 1, ps); +} diff --git a/tslang/test/gpu/gpu_structs.ts b/tslang/test/gpu/gpu_structs.ts new file mode 100644 index 000000000..76ffa1a0b --- /dev/null +++ b/tslang/test/gpu/gpu_structs.ts @@ -0,0 +1,140 @@ +// Arrays of tuples and object types as kernel arguments (docs/gpu.md): `{ x: number, y: number }[]` and +// `[number, int][]` hold their elements by value, one after another, as the GPU has them too. A launch, gpuReduce, +// a GpuArray, a barrier kernel and a call on the CPU each take them. Needs a GPU and its driver, so it is not part +// of the test suite (test/gpu/CMakeLists.txt compiles kernels on these). +// +// tslang --emit=exe gpu_structs.ts -o gpu_structs.exe (or tslang --emit=jit gpu_structs.ts) + +type Particle = { x: number, y: number, vx: number, vy: number }; + +// fields of every size, with the padding between them +type Mixed = { a: byte, b: number, c: float, d: boolean, e: int, f: short }; + +type Body = { pos: { x: number, y: number }, mass: number }; + +@kernel +function step(i: int, ps: Particle[], dt: number) { + ps[i].vy = ps[i].vy - 9.8 * dt; + ps[i].x = ps[i].x + ps[i].vx * dt; + ps[i].y = ps[i].y + ps[i].vy * dt; +} + +@kernel +function mix(i: int, ms: Mixed[]) { + ms[i].a = ms[i].a + 1; + ms[i].b = ms[i].b * 2; + ms[i].c = ms[i].c + 0.5; + ms[i].d = !ms[i].d; + ms[i].e = ms[i].e - i; + ms[i].f = ms[i].f + 3; +} + +@kernel +function pairs(i: int, ts: [number, int][]) { + ts[i][0] = ts[i][0] * ts[i][1]; + ts[i][1] = i; +} + +// a whole element written +@kernel +function place(i: int, ps: { x: number, y: number }[]) { + ps[i] = { x: i * 2, y: -i }; +} + +@kernel +function heavier(i: int, bodies: Body[]) { + bodies[i].mass = bodies[i].mass + bodies[i].pos.x; +} + +@kernel +function mass(i: int, bodies: Body[]): number { + return bodies[i].mass; +} + +// a barrier kernel: its threads past n write nothing, so the elements past n keep theirs +@kernel +function shifted(i: int, ps: Particle[]) { + const tile = gpuShared(256); + const t = gpuThreadIndex(); + tile[t] = ps[i].x; + gpuBarrier(); + ps[i].y = t < 255 ? tile[t + 1] : -1; +} + +function particles(count: int): Particle[] { + const ps: Particle[] = []; + for (let i = 0; i < count; i++) ps.push({ x: i, y: 100, vx: 1, vy: 0 }); + return ps; +} + +function main() { + const n = 10000; + const ps = particles(n); + const cpu = particles(n); + for (let s = 0; s < 3; s++) { + gpuLaunch(step, n, ps, 0.1); + for (let i = 0; i < n; i++) step(i, cpu, 0.1); // the same kernel on the CPU + } + let wrong = 0; + for (let i = 0; i < n; i++) + if (ps[i].x != cpu[i].x || ps[i].y != cpu[i].y || ps[i].vy != cpu[i].vy) wrong++; + print("particles: ps[7] =", ps[7].x, ps[7].y, ps[7].vy, "wrong =", wrong); + assert(wrong == 0 && ps[7].x == cpu[7].x); + + const ms: Mixed[] = []; + for (let i = 0; i < 100; i++) ms.push({ a: i, b: i + 0.25, c: i, d: i % 3 == 0, e: 1000, f: -i }); + gpuLaunch(mix, 100, ms); + wrong = 0; + for (let i = 0; i < 100; i++) { + const m = ms[i]; + if (m.a != i + 1 || m.b != (i + 0.25) * 2 || m.c != i + 0.5 || m.d != (i % 3 != 0) || m.e != 1000 - i || + m.f != -i + 3) wrong++; + } + print("mixed: ms[5] =", ms[5].a, ms[5].b, ms[5].c, ms[5].d, ms[5].e, ms[5].f, "wrong =", wrong); + assert(wrong == 0); + + const ts: [number, int][] = []; + for (let i = 0; i < 50; i++) ts.push([i + 0.5, 3]); + gpuLaunch(pairs, 50, ts); + wrong = 0; + for (let i = 0; i < 50; i++) if (ts[i][0] != (i + 0.5) * 3 || ts[i][1] != i) wrong++; + print("tuples: ts[4] =", ts[4][0], ts[4][1], "wrong =", wrong); + assert(wrong == 0); + + const points: { x: number, y: number }[] = []; + for (let i = 0; i < 40; i++) points.push({ x: 0, y: 0 }); + gpuLaunch(place, 40, points); + assert(points[39].x == 78 && points[39].y == -39 && points[0].y == 0); + + const bodies: Body[] = []; + for (let i = 0; i < 64; i++) bodies.push({ pos: { x: i, y: 1 }, mass: 10 }); + gpuLaunch(heavier, 64, bodies); + assert(bodies[3].mass == 13 && bodies[63].mass == 73 && bodies[3].pos.x == 3); + const total = gpuReduce(mass, 64, bodies); + print("bodies: total mass", total); + assert(total == 64 * 10 + 63 * 64 / 2); + + // on the GPU across launches + const onGpu = gpuArray(ps); + for (let s = 0; s < 2; s++) gpuLaunch(step, n, onGpu, 0.1); + gpuRead(onGpu, ps); + for (let s = 0; s < 2; s++) for (let i = 0; i < n; i++) step(i, cpu, 0.1); + wrong = 0; + for (let i = 0; i < n; i++) if (ps[i].x != cpu[i].x || ps[i].y != cpu[i].y) wrong++; + print("GpuArray: wrong =", wrong, "length", onGpu.length); + assert(wrong == 0 && onGpu.length == n); + gpuFree(onGpu); + + // 1000 threads of a barrier kernel, on 1300 particles: the last 300 keep y = 100 + const many = particles(1300); + gpuLaunch(shifted, 1000, many); + wrong = 0; + for (let i = 0; i < 1300; i++) { + const expected = i >= 1000 ? 100 : i % 256 == 255 ? -1 : i + 1; + if (many[i].y != expected) wrong++; + } + print("barrier: many[999].y =", many[999].y, "wrong =", wrong); + assert(wrong == 0); + + print("structs: ok"); +} diff --git a/tslang/tslang/gpu.cpp b/tslang/tslang/gpu.cpp index fe92b393f..8f440b9eb 100644 --- a/tslang/tslang/gpu.cpp +++ b/tslang/tslang/gpu.cpp @@ -1539,6 +1539,20 @@ void guardBarrierKernels(llvm::Module &device, const std::set &kern : llvm::cast(access)->getPointerOperand(); } + // a field of a tuple element (`ps[i].x`): gep S, element, 0, field (fields of fields too) + while (auto field = llvm::dyn_cast(pointer)) + { + auto first = field->getNumIndices() >= 2 ? llvm::dyn_cast(*field->idx_begin()) + : nullptr; + if (!first || !first->isZero() || !field->getSourceElementType()->isStructTy() || + isHeader(field->getSourceElementType())) + { + break; + } + + pointer = field->getPointerOperand(); + } + // gep T, data, index; data = load (gep { ptr, i64, i64 }, header, 0, 0) auto element = llvm::dyn_cast(pointer); if (!element || element->getNumIndices() != 1) From 46023401fb4bea6147a7a8c545274c6dc6c80f9a Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Wed, 2 Dec 2026 12:51:48 +0000 Subject: [PATCH 4/4] Kernel arrays of 1-byte elements (boolean[], byte[]): the scalar check no longer refuses them; docs for struct arrays Co-Authored-By: Claude Opus 5.5 --- docs/gpu.md | 15 ++++++++++++--- tslang/lib/TypeScript/MLIRGenAccessCall.cpp | 3 ++- tslang/test/gpu/gpu_structs.ts | 16 ++++++++++++++++ 3 files changed, 30 insertions(+), 4 deletions(-) diff --git a/docs/gpu.md b/docs/gpu.md index 6b3b479c9..3f2d19806 100644 --- a/docs/gpu.md +++ b/docs/gpu.md @@ -28,8 +28,17 @@ across launches, and a `GpuArray` lives there for as long as the program keeps i - It is a function marked `@kernel`, whose first parameter is the thread's index (`int`). It returns nothing, or, for `gpuReduce`, the number to add up. -- Its other parameters are arrays of numbers (`number[]`, `float[]`, `int[]`), typed arrays (below) or plain - numbers (`number`, `float`, `int`). +- Its other parameters are arrays of numbers (`number[]`, `float[]`, `int[]`, `boolean[]`), arrays of tuples and + object types of numbers (below), typed arrays (below) or plain numbers (`number`, `float`, `int`). +- An array of a tuple or an object type, `[number, int][]` or `{ x: number, y: number }[]`, holds its elements by + value, one after another, and the GPU has them so too: a kernel reads and writes their fields (`ps[i].x`, + `ts[i][0]`), a nested object's (`bodies[i].pos.x`), or a whole element (`ps[i] = { x: 0, y: 1 }`). Their fields + are numbers, integers, floats, booleans and such tuples. A launch, `gpuReduce`, `gpuBatch` and a `GpuArray` + take them as they take arrays of numbers. A field that is a string, an array or a class's object is a pointer + into the CPU's memory, so such an element is an error (`a @kernel parameter is a number, or an array of + numbers or of tuples and object types of numbers`). A class's objects are not taken either: an array of them + is of pointers. `tslang/test/gpu/gpu_structs.ts` steps 10000 particles on the GPU and on the CPU alike, and + checks fields of every size with the padding between them. - A typed array (`Float32Array`, `Float64Array`, `Int8Array` to `Int32Array`, `Uint8Array` to `Uint32Array`, `BigInt64Array`, `BigUint64Array`) is given where the kernel takes it, `a: Float32Array`, or takes the array of its elements, `a: float[]` (a `Float64Array` for a `number[]` too). In the kernel it is that array: `a[i]`, @@ -542,7 +551,7 @@ far as their compiled code goes (the AMD code object's kernel table, the SPIR-V been run on its GPU yet. The test suite compiles a kernel for every GPU there is a backend for, and checks the errors (`tslang/test/gpu`). Running ones, which need a GPU: `tslang/test/gpu/gpu_add_arrays.ts`, `gpu_saxpy_table.ts`, `gpu_add_ints.ts`, `gpu_math.ts`, `gpu_copy_back.ts`, `gpu_batch.ts`, `gpu_float.ts`, -`gpu_atomics.ts`, `gpu_reduce.ts`, `gpu_batch_temporaries.ts`, `gpu_math_library.ts`, `gpu_shared.ts`, `gpu_grid.ts`, `gpu_call.ts`, `gpu_min_max.ts`, `gpu_array.ts`, `gpu_array_collect.ts`, `gpu_async.ts`, `gpu_barrier_guard.ts`, `gpu_blocks.ts`, `gpu_typed_arrays.ts`, `gpu_warp.ts`, `gpu_scan.ts`. +`gpu_atomics.ts`, `gpu_reduce.ts`, `gpu_batch_temporaries.ts`, `gpu_math_library.ts`, `gpu_shared.ts`, `gpu_grid.ts`, `gpu_call.ts`, `gpu_min_max.ts`, `gpu_array.ts`, `gpu_array_collect.ts`, `gpu_async.ts`, `gpu_barrier_guard.ts`, `gpu_blocks.ts`, `gpu_typed_arrays.ts`, `gpu_warp.ts`, `gpu_scan.ts`, `gpu_structs.ts`. ## Not yet diff --git a/tslang/lib/TypeScript/MLIRGenAccessCall.cpp b/tslang/lib/TypeScript/MLIRGenAccessCall.cpp index 61dbf363d..17727d424 100644 --- a/tslang/lib/TypeScript/MLIRGenAccessCall.cpp +++ b/tslang/lib/TypeScript/MLIRGenAccessCall.cpp @@ -2603,7 +2603,8 @@ namespace mlirgen kind = size == 4 ? 0 : size == 8 && !isa(type) ? -2 : 1; } - if (kind == 1 || (isa(type) && kind == 0)) + // a scalar that is none of those is 1; an array's kind is its element's size (1 for a byte's) + if (isa(type) ? kind == 0 : kind == 1) { emitError(location, "a @kernel parameter is a number, or an array of numbers or of tuples and object " "types of numbers: ") diff --git a/tslang/test/gpu/gpu_structs.ts b/tslang/test/gpu/gpu_structs.ts index 76ffa1a0b..1a43149e6 100644 --- a/tslang/test/gpu/gpu_structs.ts +++ b/tslang/test/gpu/gpu_structs.ts @@ -61,6 +61,13 @@ function shifted(i: int, ps: Particle[]) { ps[i].y = t < 255 ? tile[t + 1] : -1; } +// arrays of 1-byte elements: booleans and bytes +@kernel +function flags(i: int, b: boolean[], bytes: byte[]) { + b[i] = !b[i]; + bytes[i] = bytes[i] + 2; +} + function particles(count: int): Particle[] { const ps: Particle[] = []; for (let i = 0; i < count; i++) ps.push({ x: i, y: 100, vx: 1, vy: 0 }); @@ -136,5 +143,14 @@ function main() { print("barrier: many[999].y =", many[999].y, "wrong =", wrong); assert(wrong == 0); + const b: boolean[] = []; + const bytes: byte[] = []; + for (let i = 0; i < 1000; i++) { b.push(i % 3 == 0); bytes.push(i % 100); } + gpuLaunch(flags, 1000, b, bytes); + wrong = 0; + for (let i = 0; i < 1000; i++) if (b[i] != (i % 3 != 0) || bytes[i] != i % 100 + 2) wrong++; + print("booleans and bytes: wrong =", wrong); + assert(wrong == 0); + print("structs: ok"); }