Skip to content

Commit e66e996

Browse files
committed
math: fix ./v -prod -cstrict -cc gcc-11 vlib/math/math_bench_test.v (use unions to implement f64_bits/1 and f64_from_bits/1 for compilers != tcc)
1 parent 4236baf commit e66e996

File tree

2 files changed

+43
-9
lines changed

2 files changed

+43
-9
lines changed

vlib/math/math_bench_test.v

+1-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ module main
33
import math
44
import benchmark
55

6-
const max_iter = 1000
6+
const max_iter = 100_000
77

88
fn test_benchmark_acos() {
99
mut x := 0.0

vlib/math/unsafe.v

+42-8
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,24 @@
33
// that can be found in the LICENSE file.
44
module math
55

6+
union U32_F32 {
7+
u u32
8+
f f32
9+
}
10+
611
// f32_bits returns the IEEE 754 binary representation of f,
712
// with the sign bit of f and the result in the same bit position.
813
// f32_bits(f32_from_bits(x)) == x.
914
@[inline]
1015
pub fn f32_bits(f f32) u32 {
11-
p := *unsafe { &u32(&f) }
12-
return p
16+
$if tinyc {
17+
return *unsafe { &u32(&f) } // this is faster for tcc, but causes `error: dereferencing type-punned pointer will break strict-aliasing rules` on gcc, with -cstrict
18+
}
19+
return unsafe {
20+
U32_F32{
21+
f: f
22+
}.u
23+
}
1324
}
1425

1526
// f32_from_bits returns the floating-point number corresponding
@@ -18,17 +29,34 @@ pub fn f32_bits(f f32) u32 {
1829
// f32_from_bits(f32_bits(x)) == x.
1930
@[inline]
2031
pub fn f32_from_bits(b u32) f32 {
21-
p := *unsafe { &f32(&b) }
22-
return p
32+
$if tinyc {
33+
return *unsafe { &f32(&b) }
34+
}
35+
return unsafe {
36+
U32_F32{
37+
u: b
38+
}.f
39+
}
40+
}
41+
42+
union U64_F64 {
43+
u u64
44+
f f64
2345
}
2446

2547
// f64_bits returns the IEEE 754 binary representation of f,
2648
// with the sign bit of f and the result in the same bit position,
2749
// and f64_bits(f64_from_bits(x)) == x.
2850
@[inline]
2951
pub fn f64_bits(f f64) u64 {
30-
p := *unsafe { &u64(&f) }
31-
return p
52+
$if tinyc {
53+
return *unsafe { &u64(&f) }
54+
}
55+
return unsafe {
56+
U64_F64{
57+
f: f
58+
}.u
59+
}
3260
}
3361

3462
// f64_from_bits returns the floating-point number corresponding
@@ -37,8 +65,14 @@ pub fn f64_bits(f f64) u64 {
3765
// f64_from_bits(f64_bits(x)) == x.
3866
@[inline]
3967
pub fn f64_from_bits(b u64) f64 {
40-
p := *unsafe { &f64(&b) }
41-
return p
68+
$if tinyc {
69+
return *unsafe { &f64(&b) }
70+
}
71+
return unsafe {
72+
U64_F64{
73+
u: b
74+
}.f
75+
}
4276
}
4377

4478
// with_set_low_word sets low word of `f` to `lo`

0 commit comments

Comments
 (0)