hn.today

Making all divisions slower to fix a bug in 0.000000000000000000542% of cases

futhark-lang.org19 points1 comments
Screenshot of Making all divisions slower to fix a bug in 0.000000000000000000542% of cases

Modern two’s-complement integer representation makes the most-negative value asymmetric (e.g., -2^31 has no positive counterpart), so dividing that value by -1 cannot be represented and triggers signed overflow. C treats signed overflow as undefined behavior, but Futhark’s semantics define wrapping arithmetic, so simply emitting straightforward C for signed division can produce undefined behavior in rare inputs. To avoid this, generated C represents integers as unsigned types and performs arithmetic there, but division requires a special-case treatment: the compiler must detect the most-negative/−1 combination and handle it explicitly. That change eliminates undefined behavior but introduces extra checks and branches around divisions.

Benchmarks show the correctness fix is essentially free on CPU code (no measurable difference), but it can significantly slow GPU code: a CUDA test with many repeated divisions roughly doubled runtime because the added branches prevent the GPU from emitting long runs of consecutive div.s32 instructions and from unrolling efficiently; similar but smaller impact appears on AMD hardware. The author accepts the runtime cost as necessary, advises using unsigned division when negatives are impossible, and notes this is the last remembered instance of undefined behavior in generated C, though an implementation-defined bit-shift issue remains.

Read on futhark-lang.org1 comments on Hacker News

Summary generated by AI from the linked article. hn.today is not affiliated with Hacker News or Y Combinator.

More in Programming

OpenCode 2.0

OpenCode 2.0

OpenCode 2.0 introduces a major overhaul with a unified client/server system that runs automatically on users' machines, improving performance and usability. The update includes new features, an improved API, dark mode, and native apps, making the system more flexible and user-friendly. (anoma.ly)

The daily digest

Today's best Hacker News stories, summarized and screenshotted, one email a day.