ziglang / zig

General-purpose programming language and toolchain for maintaining robust, optimal, and reusable software.
https://ziglang.org
MIT License
35.13k stars 2.56k forks source link

cmpxchgWeak and cmpxchStrong does not work with float #20562

Open hollinwilkins opened 4 months ago

hollinwilkins commented 4 months ago

Zig Version

0.14.0-dev.208+854e86c56

Steps to Reproduce and Observed Behavior

I am not sure if this is a compiler bug or a documentation bug. The documentation for cmpxchgWeak and cmpxchStrong states that "T must be a pointer, a bool, a float, an integer or an enum." However, when attempting to use either with a float (f32) value, a compiler error is thrown.

The test case is here and seems to go against what the documentation says: https://github.com/ziglang/zig/blob/master/test/cases/compile_errors/cmpxchg_with_float.zig

Documentation links: https://ziglang.org/documentation/master/#cmpxchgWeak and https://ziglang.org/documentation/master/#toc-cmpxchgStrong

export fn entry() void {
    var x: f32 = 0;
    _ = @cmpxchgWeak(f32, &x, 1, 2, .seq_cst, .seq_cst);
}

// error
// backend=stage2
// target=native
//
// :3:22: error: expected bool, integer, enum, or pointer type; found 'f32'

Expected Behavior

Either no compiler error is thrown or the documentation reflects that floats cannot be used with cmpxchgWeak and cmpxchStrong.

EspeuteClement commented 2 weeks ago

I have the same issue in the 0.13.0 release. I found this kinda wonky workaround for this issue where you use bit and pointer casting of your values to the integer with the same size like so :

    var my_var : f64 = 42.0;
    // ...
    _ = @cmpxchgStrong(u64, @as(*u64, @ptrCast(&my_var)), @bitCast(old), @bitCast(new), .monotonic, .monotonic);

Seems to work in my limited testing