From 92d04754d750983615fb4f072ccf5fa35be676e1 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Wed, 2 Dec 2026 19:40:57 +0000 Subject: [PATCH] GPU: a kernel's read past an array's end gives 0 and is reported, as a write is A kernel that does not wait at a barrier read past an array's end unchecked: whatever GPU memory was there, or a driver fault. Now such a read (an element, a field of one, a typed array's view past its own length) gives 0, the first is recorded in the fault global, and the program stops after the kernel: tslang gpu: the kernel 'k' read past the end of an array: element 4 of 4 (GPU thread 3) The record's flag says which (1 write, 2 read). The CPU still does not check a read past the end; barrier kernels keep giving 0 silently (their threads past n read their tiles). Cost, kept down: the read is always made, of the element or of a block of zeroes (a select), and only the record is branched to, so the array's data pointer and length are loaded once before a loop; the record's call has an alias scope of its own, never an array header. A matrix * vector kernel (2048 x 2048 floats, 200 launches): NVIDIA 37 ms unchecked, 37 ms checked; Intel's iGPU 246 ms -> 405 ms (a branch around the read was 60 ms and 524). Tests: faults/read.ts, read_field.ts, read_typed_array.ts; all 14 fault cases and all 26 programs pass on NVIDIA and Intel, JIT and exe; GPU ctests pass. Co-Authored-By: Claude Opus 5.5 --- docs/gpu.md | 13 +++ .../lib/TypeScriptAsyncRuntime/GpuRuntime.c | 22 ++--- tslang/test/gpu/faults/README.md | 7 +- tslang/test/gpu/faults/read.ts | 13 +++ tslang/test/gpu/faults/read_field.ts | 13 +++ tslang/test/gpu/faults/read_typed_array.ts | 13 +++ tslang/tslang/gpu.cpp | 81 ++++++++++++++++--- 7 files changed, 142 insertions(+), 20 deletions(-) create mode 100644 tslang/test/gpu/faults/read.ts create mode 100644 tslang/test/gpu/faults/read_field.ts create mode 100644 tslang/test/gpu/faults/read_typed_array.ts diff --git a/docs/gpu.md b/docs/gpu.md index ee26f8b3c..be6b90153 100644 --- a/docs/gpu.md +++ b/docs/gpu.md @@ -103,6 +103,19 @@ across launches, and a `GpuArray` lives there for as long as the program keeps i nothing instead, silently (below). A kernel called on the CPU does not grow the array either: the write stops the program (`a kernel called on the CPU wrote past the end of an array`). `tslang/test/gpu/faults/` has a program for each way. +- A read past an array's end (or below 0) gives 0 on the GPU, and stops the program the same way: + + ``` + tslang gpu: the kernel 'k' read past the end of an array: element 4 of 4 (GPU thread 3) + ``` + + A neighbour's element at the last index (`a[i + 1]`), a field of an element, a typed array's view past its own + length: each is a read of no element of the array, which on a GPU reads its memory past the array, whatever is + there, or stops the driver. `a[i] += v` past the end is said as its read, the first thing it does. The CPU does + not check a read past the end (the same kernel called there reads what is in the memory), and in a kernel that + waits at `gpuBarrier` such a read gives 0, silently, as its threads past `n` read their tiles (below). The + check costs nothing measurable on NVIDIA; on Intel's integrated GPU a matrix * vector kernel, two reads and a + multiply each step, takes 1.65 times as long. - `gpuLaunch`, `gpuReduce` and `gpuBatch` need the default memory model (`-mm=gc`). ## The GPU's `Math` library diff --git a/tslang/lib/TypeScriptAsyncRuntime/GpuRuntime.c b/tslang/lib/TypeScriptAsyncRuntime/GpuRuntime.c index 314d9125d..74cac5486 100644 --- a/tslang/lib/TypeScriptAsyncRuntime/GpuRuntime.c +++ b/tslang/lib/TypeScriptAsyncRuntime/GpuRuntime.c @@ -717,21 +717,24 @@ static void gpuAppend(char *text, size_t size, const char *line) snprintf(text + used, size - used, " %s\n", line); } -// ---- a kernel's fault: a write past an array's end +// ---- a kernel's fault: a write or a read past an array's end // -// On the GPU such a write is not made (there is no growing an array there): the kernel records the first one in -// its module's global `__tslang_gpu_fault` (tslang/gpu.cpp's recordKernelFaults) and goes on. After the kernel has -// run, wherever the runtime waits for it, the record is read, and a fault stops the program, as the same write -// past the end does in a kernel called on the CPU. +// On the GPU such a write is not made (there is no growing an array there) and such a read gives 0: the kernel +// records the first one in its module's global `__tslang_gpu_fault` (tslang/gpu.cpp's recordKernelFaults) and goes +// on. After the kernel has run, wherever the runtime waits for it, the record is read, and a fault stops the +// program, as the same write past the end does in a kernel called on the CPU. A read past the end, which the CPU +// does not check, is an error on the GPU too: it reads no array's element. typedef struct { - int32_t flag; // 1: a fault is recorded + int32_t flag; // a fault is recorded: GPU_FAULT_WRITE or GPU_FAULT_READ int32_t thread; // the GPU thread that made it (its x) - int64_t index; // the element written + int64_t index; // the element written or read int64_t length; // the array's length } GpuFault; #define GPU_FAULT_GLOBAL "__tslang_gpu_fault" +#define GPU_FAULT_WRITE 1 +#define GPU_FAULT_READ 2 static struct { @@ -799,8 +802,9 @@ static int gpuFaultReport(GpuDriver *driver, const char *entry) // what the program printed comes first fflush(stdout); - fprintf(stderr, "tslang gpu: %s wrote past the end of an array: element %lld of %lld (GPU thread %d)\n", - which, (long long)fault.index, (long long)fault.length, fault.thread); + fprintf(stderr, "tslang gpu: %s %s past the end of an array: element %lld of %lld (GPU thread %d)\n", + which, fault.flag == GPU_FAULT_READ ? "read" : "wrote", (long long)fault.index, + (long long)fault.length, fault.thread); fflush(stderr); return 1; } diff --git a/tslang/test/gpu/faults/README.md b/tslang/test/gpu/faults/README.md index 73a763c79..4640ddb44 100644 --- a/tslang/test/gpu/faults/README.md +++ b/tslang/test/gpu/faults/README.md @@ -1,9 +1,12 @@ # Kernel faults -Each program here has a kernel write past the end of an array, in one way or another, on the GPU. That write is not -made, and the program stops after the kernel with (on stderr, exit code 1): +Each program here has a kernel write or read past the end of an array, in one way or another, on the GPU. Such a +write is not made, such a read gives 0, and the program stops after the kernel with (on stderr, exit code 1): tslang gpu: the kernel 'k' wrote past the end of an array: element of (GPU thread ) + tslang gpu: the kernel 'k' read past the end of an array: element of (GPU thread ) + +The `read*.ts` ones read; `add_assign.ts` (`a[i] += v`) is said as its read, which comes first. Each prints `before` first, and never `after`. They need a GPU and its driver, so they are not part of the test suite; run each under the JIT and as an executable: diff --git a/tslang/test/gpu/faults/read.ts b/tslang/test/gpu/faults/read.ts new file mode 100644 index 000000000..22054c023 --- /dev/null +++ b/tslang/test/gpu/faults/read.ts @@ -0,0 +1,13 @@ +// a read past the end (a neighbour's element, at the last index): it gives 0 and is reported, as a write is +@kernel +function k(i: int, a: number[], b: number[]) { + b[i] = a[i] + a[i + 1]; +} + +function main() { + const a: number[] = [1, 2, 3, 4]; + const b: number[] = [0, 0, 0, 0]; + print("before"); + gpuLaunch(k, 4, a, b); + print("after"); +} diff --git a/tslang/test/gpu/faults/read_field.ts b/tslang/test/gpu/faults/read_field.ts new file mode 100644 index 000000000..7b6211fcf --- /dev/null +++ b/tslang/test/gpu/faults/read_field.ts @@ -0,0 +1,13 @@ +// a field of an object element read past the end +@kernel +function k(i: int, ps: { x: number, y: number }[], out: number[]) { + out[i] = ps[i + 2].x; +} + +function main() { + const ps: { x: number, y: number }[] = [{ x: 1, y: 0 }, { x: 2, y: 0 }, { x: 3, y: 0 }]; + const out: number[] = [0, 0, 0]; + print("before"); + gpuLaunch(k, 3, ps, out); + print("after"); +} diff --git a/tslang/test/gpu/faults/read_typed_array.ts b/tslang/test/gpu/faults/read_typed_array.ts new file mode 100644 index 000000000..0db42135b --- /dev/null +++ b/tslang/test/gpu/faults/read_typed_array.ts @@ -0,0 +1,13 @@ +// a typed array's view read past its end, inside the buffer: the view's length is the one checked +@kernel +function k(i: int, a: Float32Array, out: Float32Array) { + out[i] = a[i + 1]; +} + +function main() { + const big = new Float32Array(10); + const out = new Float32Array(5); + print("before"); + gpuLaunch(k, 5, big.subarray(0, 5), out); + print("after"); +} diff --git a/tslang/tslang/gpu.cpp b/tslang/tslang/gpu.cpp index 9b60ac367..64600d683 100644 --- a/tslang/tslang/gpu.cpp +++ b/tslang/tslang/gpu.cpp @@ -56,6 +56,7 @@ #include "llvm/MC/TargetRegistry.h" #include "llvm/Support/CommandLine.h" #include "llvm/Analysis/ValueTracking.h" +#include "llvm/IR/MDBuilder.h" #include "llvm/Passes/PassBuilder.h" #include "llvm/Support/Error.h" #include "llvm/Support/FileSystem.h" @@ -148,10 +149,15 @@ constexpr int32_t gpuBlockThreads = 256; // the lanes of an Intel kernel's subgroup (a warp), pinned so that every kernel has the same #define INTEL_SUBGROUP_SIZE 16 #define ACTIVE_ATTR "tslang.gpu_active" -// a kernel's first write past an array's end (recordKernelFaults), which GpuRuntime.c reads after the kernel ran: +// a kernel's first write or read past an array's end (recordKernelFaults), which GpuRuntime.c reads after it ran: // { i32 flag, i32 thread, i64 index, i64 length }; the thread (its x) is the GPU's to say #define FAULT_GLOBAL "__tslang_gpu_fault" #define FAULT_RECORD_FUNCTION "__tslang_gpu_fault_record" +// the record's flag: what the fault was (GpuRuntime.c's GPU_FAULT_WRITE and GPU_FAULT_READ) +#define FAULT_WRITE 1 +#define FAULT_READ 2 +// the zeroes a read past an array's end reads instead (recordKernelFaults): an element of at most this many bytes +#define ZERO_SLOT_BYTES 64 #define FAULT_THREAD_STUB "__tslang_gpu_fault_thread" // 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 @@ -1715,7 +1721,8 @@ llvm::Value *stripIndexCasts(llvm::Value *value) // kernels that do not wait at a barrier (whose guard drops such writes: guardBarrierKernels), and what they call, // each write of an array's element (a store, an Atomics; a field of a tuple element too) is made only inside the // array: past its end it is not made, and the first such write is recorded in FAULT_GLOBAL, which the runtime -// reads after the kernel and stops the program with (GpuRuntime.c's gpuFaultReport). The compiler's own check +// reads after the kernel and stops the program with (GpuRuntime.c's gpuFaultReport). A read of an element is +// guarded the same way: past the end it gives 0 and is recorded (FAULT_READ; the CPU does not check one). The compiler's own check // before such a write (the CPU's grow, or in a @kernel __tslang_gpu_past_end) goes when the write it is for is // guarded here; one whose write is not recognized stays a trap, so that no write past the end is made unseen. void recordKernelFaults(llvm::Module &device, const std::set &kernelNames) @@ -1752,7 +1759,7 @@ void recordKernelFaults(llvm::Module &device, const std::set &kerne auto record = device.getFunction(FAULT_RECORD_FUNCTION); if (!record) { - record = llvm::Function::Create(llvm::FunctionType::get(llvm::Type::getVoidTy(context), {i64, i64}, false), + record = llvm::Function::Create(llvm::FunctionType::get(llvm::Type::getVoidTy(context), {i64, i64, i32}, false), llvm::GlobalValue::InternalLinkage, FAULT_RECORD_FUNCTION, device); record->addFnAttr(llvm::Attribute::Cold); record->addFnAttr(llvm::Attribute::NoInline); @@ -1761,7 +1768,7 @@ void recordKernelFaults(llvm::Module &device, const std::set &kerne auto done = llvm::BasicBlock::Create(context, "done", record); llvm::IRBuilder<> builder(entry); auto exchange = builder.CreateAtomicCmpXchg(builder.CreateStructGEP(faultType, fault, 0), builder.getInt32(0), - builder.getInt32(1), llvm::MaybeAlign(4), + record->getArg(2), llvm::MaybeAlign(4), llvm::AtomicOrdering::Monotonic, llvm::AtomicOrdering::Monotonic); builder.CreateCondBr(builder.CreateExtractValue(exchange, 1), write, done); builder.SetInsertPoint(write); @@ -1774,6 +1781,18 @@ void recordKernelFaults(llvm::Module &device, const std::set &kerne builder.CreateRetVoid(); } + // the record writes FAULT_GLOBAL only, never an array's header: said as an alias scope of its own, so that a + // header's data and length are still read once before a loop, not at each access (to LLVM the record's call in + // the loop could write anything) + llvm::MDBuilder metadata(context); + auto faultScope = metadata.createAnonymousAliasScope(metadata.createAnonymousAliasScopeDomain("tslang.gpu.fault")); + auto faultScopes = llvm::MDNode::get(context, {faultScope}); + llvm::GlobalVariable *zeroSlot = device.getGlobalVariable("__tslang_gpu_zeroes", true); + auto notFault = [&](llvm::Instruction *access) { + access->setMetadata(llvm::LLVMContext::MD_noalias, + llvm::MDNode::concatenate(access->getMetadata(llvm::LLVMContext::MD_noalias), faultScopes)); + }; + for (auto function : reachedFrom(kernels)) { if (function == record || function->getName().starts_with(".array_grow.")) @@ -1782,6 +1801,7 @@ void recordKernelFaults(llvm::Module &device, const std::set &kerne } llvm::SmallVector writes; + llvm::SmallVector reads; llvm::SmallVector checks; for (auto &instruction : llvm::instructions(*function)) { @@ -1789,6 +1809,10 @@ void recordKernelFaults(llvm::Module &device, const std::set &kerne { writes.push_back(&instruction); } + else if (auto load = llvm::dyn_cast(&instruction)) + { + reads.push_back(load); + } else if (auto call = llvm::dyn_cast(&instruction)) { if (auto callee = call->getCalledFunction(); @@ -1801,8 +1825,11 @@ void recordKernelFaults(llvm::Module &device, const std::set &kerne // the indices whose writes are guarded llvm::SmallPtrSet guarded; - for (auto access : writes) + llvm::SmallVector accesses(writes.begin(), writes.end()); + accesses.append(reads.begin(), reads.end()); + for (auto access : accesses) { + auto isRead = llvm::isa(access); auto pointer = llvm::getLoadStorePointerOperand(access); if (!pointer) { @@ -1820,26 +1847,62 @@ void recordKernelFaults(llvm::Module &device, const std::set &kerne auto [header, data, element] = *matched; llvm::IRBuilder<> builder(access); auto length = builder.CreateLoad(i64, builder.CreateStructGEP(headerType, header, 1), "gpu.length"); + notFault(length); + if (data) + { + notFault(data); + } auto index = builder.CreateSExtOrTrunc(*element->idx_begin(), i64); // unsigned: a negative index is past the end too auto inside = builder.CreateICmpULT(index, length, "gpu.inside"); + if (isRead && device.getDataLayout().getTypeStoreSize(access->getType()) <= ZERO_SLOT_BYTES) + { + // a read is made always, of the element or past the end of zeroes, and only the record is + // branched to: the data's load, used on the way the loop always goes, is then made once before + // the loop (in a branch around the read it was made at each one: a matrix * vector kernel ran 1.6 + // times as long on NVIDIA, 2.1 times on Intel) + if (!zeroSlot) + { + auto slotType = llvm::ArrayType::get(llvm::Type::getInt8Ty(context), ZERO_SLOT_BYTES); + zeroSlot = new llvm::GlobalVariable(device, slotType, true, llvm::GlobalValue::InternalLinkage, + llvm::ConstantAggregateZero::get(slotType), "__tslang_gpu_zeroes"); + zeroSlot->setAlignment(llvm::Align(16)); + } + + auto read = llvm::cast(access); + read->setOperand(read->getPointerOperandIndex(), + builder.CreateSelect(inside, pointer, zeroSlot, "gpu.read.from")); + auto recordTerminator = + llvm::SplitBlockAndInsertIfThen(builder.CreateNot(inside), std::next(read->getIterator()), false); + llvm::IRBuilder<> faultBuilder(recordTerminator); + faultBuilder.CreateCall(record, {index, length, faultBuilder.getInt32(FAULT_READ)}) + ->setMetadata(llvm::LLVMContext::MD_alias_scope, faultScopes); + continue; + } + llvm::Instruction *thenTerminator = nullptr; llvm::Instruction *elseTerminator = nullptr; llvm::SplitBlockAndInsertIfThenElse(inside, access->getIterator(), &thenTerminator, &elseTerminator); auto tail = access->getParent(); access->moveBefore(thenTerminator->getIterator()); llvm::IRBuilder<> faultBuilder(elseTerminator); - faultBuilder.CreateCall(record, {index, length}); + auto recorded = + faultBuilder.CreateCall(record, {index, length, builder.getInt32(isRead ? FAULT_READ : FAULT_WRITE)}); + recorded->setMetadata(llvm::LLVMContext::MD_alias_scope, faultScopes); if (!access->getType()->isVoidTy()) { - // what the skipped Atomics gives: 0 - auto phi = llvm::PHINode::Create(access->getType(), 2, "gpu.written", tail->begin()); + // what the skipped read or Atomics gives: 0 + auto phi = llvm::PHINode::Create(access->getType(), 2, isRead ? "gpu.read" : "gpu.written", + tail->begin()); access->replaceAllUsesWith(phi); phi->addIncoming(access, thenTerminator->getParent()); phi->addIncoming(llvm::Constant::getNullValue(access->getType()), elseTerminator->getParent()); } - guarded.insert(stripIndexCasts(*element->idx_begin())); + if (!isRead) + { + guarded.insert(stripIndexCasts(*element->idx_begin())); + } } // the compiler's check before a write: `br (index >= length), check, write`