Skip to content

fix(mir-lower): trap on assert failure so opt cannot delete bounds checks - #405

Merged
nihalpasham merged 2 commits into
NVIDIA:mainfrom
SomeB1oody:fix/issue396-assert-bounds-check
Jul 22, 2026
Merged

nihalpasham merged 2 commits into
NVIDIA:mainfrom
SomeB1oody:fix/issue396-assert-bounds-check

Conversation

@SomeB1oody

@SomeB1oody SomeB1oody commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fix #396. Checked slice indexing inside kernels (src[j]) lost its bounds check. An out-of-bounds Rust index triggers a MIR Assert terminator. mir-lower incorrectly translated the assert's failure branch into a block containing only LLVM unreachable (unreachable means "control flow can never reach this point", not "stop when control flow reaches here"). Based on that semantics, opt -O2 (SimplifyCFG) folds the entire check into llvm.assume(j < len). The branch disappears and the optimizer treats the condition as always true. So an out-of-bounds index still executes, which is the Invalid __global__ read reported by compute-sanitizer.

Changes

  • crates/mir-lower/src/convert/ops/control_flow.rs: convert_assert now declares @llvm.trap and inserts a direct call to it at the head of the abort block, ahead of llvm.unreachable.
  • crates/dialect-mir/src/ops/control_flow.rs: MirAssertOp docs updated: assert failure aborts the kernel via trap. The failure path must stay observable or the optimizer deletes the check.
  • Unit test convert_assert_creates_abort_block_with_trap asserts the abort block is exactly [call @llvm_trap, llvm.unreachable] and that the trap intrinsic is declared in the module.
  • New example crate slice_index_bounds_check: Regression test. A gather kernel indexes with runtime data. The in-range pass must produce correct values. An out-of-range index must trap (or skip the access) without the load reaching memory (CUDA_ERROR_ILLEGAL_ADDRESS fails the test).

Testing

cargo oxide run slice_index_bounds_check (sm_120a):

=== Checked Slice Indexing Bounds Check Test (issue #396) ===
in_bounds_gather: PASS
out_of_bounds_gather: PASS (kernel trapped: DriverError(719, "unspecified launch failure"))
SUCCESS
  • PTX inspection: the gather kernel regains both setp bounds guard. The abort path is a PTX trap.

  • compute-sanitizer --tool memcheck on the issue reproducer: 0 memory violation (previously 6 invalid __global__ reads of size 4).

  • cargo oxide run <example> passes

  • cargo test --workspace passes

  • New example added (if applicable)

Checklist

  • All commits signed off (git commit -s)
  • SPDX headers on new source files

…ecks

Fixes NVIDIA#396

Problem: `mir-lower` incorrectly translated the assert's failure branch into a block containing only LLVM `unreachable`. SimplifyCFG rewrites a block containing`unreachable` into `llvm.assume(cond)`, which causes every checked slice index in a kernel lose its bounds check

Fix: Emit call @llvm.trap() ahead of the unreachable in the abort block. Add the slice_index_bounds_check example. An in-range gather must produce correct values. An out-of-range index must trap (or skip the access) without the load.

Verified on sm_120a.

Signed-off-by: SomeB1oody <[email protected]>
@midiareshadi

Copy link
Copy Markdown

Verified on sm_89 (NVIDIA L4, driver 580.159.03, CUDA 12.8) using the original repro from #396 (indices[0] = 1_000_000 into a 1024-element src).

The fix works. Backend 5fbf122, clean rebuild:

PTX (gather kernel):

before (29396b7) after (5fbf122)
trap 0 2
setp 1 3
total instr 37 45

Both bounds guards are back, and each abort path carries a trap.

Runtime under compute-sanitizer --tool memcheck:

  • No Invalid __global__ read — the out-of-bounds read is gone (previously 6 of them).
  • The kernel traps as intended: Trace/breakpoint trap at gather+0x1d0, by thread (0,0,0) in block (0,0,0).

One small note on the "0 errors" claim: on sm_89 the sanitizer still prints ERROR SUMMARY: 6 errors, but they are not memory violations — 1 is the Trace/breakpoint trap itself, and 5 are CUDA_ERROR_LAUNCH_FAILED (719) on post-trap cleanup calls (cuMemcpyDtoHAsync_v2, cuModuleUnload, 3x cuMemFree_v2), since the context is poisoned after the trap. So the memory-safety result is clean; the summary count just reflects the cascade. Might differ from sm_120a depending on how the host tears down after the trap.

@SomeB1oody

Copy link
Copy Markdown
Contributor Author

Thanks for the verification. Your reading of the error summary is exactly right.

I can reproduce the same breakdown on sm_120a:

  • 0 Invalid __global__ read
  • 1 Trace/breakpoint trap entry
  • a cascade of sticky-error entries on the post-trap cleanup calls (cuMemcpyDtoHAsync_v2, cuMemFree_v2 from Rust Drop, cuModuleUnload)
  • ERROR SUMMARY: 10 errors: the count differing from your 6 only because the two host programs issue a different number of CUDA calls after the trap, not because of the architecture.

That cascade is inherent to trap semantics, not bug. A device-side trap poisons the context and the error is sticky, so every subsequent driver call on that context returns 719.

I will change my PR's claim from "0 error" to "0 memory violations".

The comment above convert_assert_creates_abort_block_with_trap ended in
"llvm.unreachable=" instead of "llvm.unreachable.".

Signed-off-by: nihalp <[email protected]>
@nihalpasham nihalpasham added bug Something isn't working miscompile Produces incorrect PTX/IR (wrong generated code) safety Memory safety, soundness, or undefined behavior IR-lowering Lowering between dialects (dialect-mir to LLVM dialect) codegen Device code-generation pipeline (Rust MIR to IR to PTX) labels Jul 22, 2026
@nihalpasham

Copy link
Copy Markdown
Collaborator

Thanks for the PR. LGTM.

  • convert_assert now emits call void @llvm.trap() before unreachable on the assert-failure edge, so opt -O2 can no longer delete bounds checks — previously a bare unreachable told LLVM the failure edge was impossible and the whole check folded away, letting out-of-bounds indexing silently touch wild memory.
  • Kernels are panic=abort, so a device trap (sticky error 719) is the correct device analog of the panic, matching nvcc's device assert.
  • The new slice_index_bounds_check example pins the behavior end to end. I pushed a trivial maintainer follow-up fixing a test comment typo.

For example:

let j = idx[i] as usize;
*out_elem = src[j];        // j >= src.len() must panic

before: opt deletes the check; OOB reads wild memory
after:  PTX keeps the check; OOB traps, host observes error 719

Reviewer note: mir-lower tests pass; the example exits 0 with SUCCESS on an RTX 5090 after the deliberate trap; the NVVM-IR path accepts llvm.trap; the PTX failure edge contains trap. Kernels that previously "passed" only because a failing assert was deleted will now visibly trap — correct, and may surface latent bugs. Merge together with companion #408, which closes the same bug class at the mir-importer site. All hosted CI checks passed on the final head.

This closes #396.

@nihalpasham
nihalpasham merged commit ab99b5a into NVIDIA:main Jul 22, 2026
33 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working codegen Device code-generation pipeline (Rust MIR to IR to PTX) IR-lowering Lowering between dialects (dialect-mir to LLVM dialect) miscompile Produces incorrect PTX/IR (wrong generated code) safety Memory safety, soundness, or undefined behavior

Projects

None yet

Development

Successfully merging this pull request may close these issues.

kernel reads out of bounds: checked &[T] indexing (src[j]) no longer emits a bounds check (regressed since v0.2.0)

3 participants