Skip to content

core::simd: v.sum() starts at +0.0, so a sum of -0.0 lanes is +0.0, and LLVM keeps an extra add #4566

Done

Description

@hiraditya

v.sum() in core::simd lowers to vector.reduction <add> with no start value. MLIR then starts the LLVM reduction at +0.0. Two problems come from this:

  1. The sign of zero. When all lanes are -0.0, the sum is +0.0. A sum of the lanes in any order gives -0.0, because -0.0 + -0.0 is -0.0.
  2. Speed. x + 0.0 is not always x (it changes -0.0 to +0.0), so LLVM keeps one more add at the end of each sum. LLVM then also does not join four sums into vhaddpd.
import core::simd;

fn main() -> i32 {
  let v : <4 x f64> = splat(-0.0f64);
  println!("{}", 1.0 / v.sum());
  return 0;
}

This prints inf. It should print -inf.

The fix is to start the reduction at -0.0, because x + -0.0 is x for every x. Rust's std::simd reduce_sum also starts at -0.0.

I found this in the SpeedTest n-body program, on PR #4565. It takes 1.55 s with sum() and 1.45 s with a sum that starts at -0.0. The setup: n = 50000000, one CPU of an Intel Xeon 6975P-C, 3 runs each.

Part of #949.

Activity

  1. added a commit that references this issue on Dec 4, 2026
    f70c012
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions