native 0.0.1
Vectors, masks and wide register packs for C++26
Loading...
Searching...
No Matches
wide_native_body.h
1// SPDX-FileCopyrightText: 2026 Edward Kmett <ekmett@gmail.com>
2// SPDX-License-Identifier: BSD-2-Clause OR Apache-2.0
3// Repeated in each raw backend's target scope. These ordinary-inline leaves
4// let a generic hint_inline algorithm reach its caller before leaf inlining.
5namespace wide::detail {
6 template<class V> requires requires { V::architecture; } && NATIVE_ARCH_REQUIRES(V::architecture)
7 struct native_ops<V> {
8 template<class T> static inline constexpr V constant(T x) noexcept { return V(x); }
9 // Pattern: [declaration macros](../README.md#declaration-macros).
10#define NATIVE_WIDE_NATIVE_BINARY(name, op) \
11 static inline constexpr auto name(V a, V b) noexcept { \
12 return a op b; \
13 }
14
15 NATIVE_WIDE_NATIVE_BINARY(add, +)
16 NATIVE_WIDE_NATIVE_BINARY(sub, -)
17 NATIVE_WIDE_NATIVE_BINARY(mul, *)
18 NATIVE_WIDE_NATIVE_BINARY(div, /)
19 NATIVE_WIDE_NATIVE_BINARY(bit_and, &)
20 NATIVE_WIDE_NATIVE_BINARY(bit_or, |)
21 NATIVE_WIDE_NATIVE_BINARY(bit_xor, ^)
22 NATIVE_WIDE_NATIVE_BINARY(equal, ==)
23 NATIVE_WIDE_NATIVE_BINARY(unequal, !=)
24 NATIVE_WIDE_NATIVE_BINARY(less, <)
25 NATIVE_WIDE_NATIVE_BINARY(less_equal, <=)
26 NATIVE_WIDE_NATIVE_BINARY(greater, >)
27 NATIVE_WIDE_NATIVE_BINARY(greater_equal, >=)
28#undef NATIVE_WIDE_NATIVE_BINARY
29 static inline constexpr auto negate(V a) noexcept { return -a; }
30 static inline constexpr auto bit_not(V a) noexcept { return ~a; }
31 static inline constexpr auto logical_not(V a) noexcept { return !a; }
32 static inline constexpr auto minimum(V a, V b) noexcept { return select(a < b, a, b); }
33 static inline constexpr auto maximum(V a, V b) noexcept { return select(a > b, a, b); }
34 static inline constexpr auto absolute(V a) noexcept { return abs(a); }
35 static inline constexpr auto root(V a) noexcept { return sqrt(a); }
36 static inline constexpr auto downward(V a) noexcept { return floor(a); }
37 static inline constexpr auto upward(V a) noexcept { return ceil(a); }
38 static inline constexpr auto truncate(V a) noexcept { return trunc(a); }
39 static inline constexpr auto round(V a) noexcept { return round_even(a); }
40 static inline constexpr auto fused(V a, V b, V c) noexcept { return fma(a, b, c); }
41 // SIMD128 has no fused instruction. Keep its polynomial graph explicitly
42 // noncontracting, including in relaxed-SIMD callers; do not weaken fma.
43 static inline constexpr auto polynomial_madd(V a, V b, V c) noexcept {
44#if NATIVE_HAS_WASM_SIMD128
45#pragma clang fp contract(off)
46 return a * b + c;
47#else
48 return fma(a, b, c);
49#endif
50 }
51#if NATIVE_HOST_X86
52 // Exp only needs a normal power-of-two field, or zero. CVTT returns the
53 // signed indefinite integer for NaN/out-of-range inputs; MAX maps it and
54 // negative fields to zero without testing the floating-point input.
55 static inline constexpr V exp_factor(V biased) noexcept {
56 if constexpr(::native::detail::polyfill_operation_shape<typename V::value_type,V::lanes,V::architecture>) {
57 if constexpr(::native::detail::polyfill_chunk_compatible<V,V>)
58 return ::native::detail::polyfill_transform_chunks<V>(biased,[](auto chunk) { return native_ops<decltype(chunk)>::exp_factor(chunk); });
59 else {
60 auto words=::native::detail::float_constant::words(biased);
61 for(auto & word:words) {
62 auto magnitude=word&0x7fffffffu;
63 auto integer=magnitude>=0x4f000000u?INT32_MIN : ::native::detail::float_constant::fcvtzs(word);
64 word=std::uint32_t(integer>0?integer:0)<<23;
65 }
66 return V::load_bits(words.data());
67 }
68 } else {
69 if consteval {
70 auto words=::native::detail::float_constant::words(biased);
71 for(auto & word:words) {
72 auto const magnitude=word & 0x7fffffffu;
73 auto const integer=magnitude>=0x4f000000u ? INT32_MIN :
74 ::native::detail::float_constant::fcvtzs(word);
75 word=std::uint32_t(integer>0 ? integer : 0)<<23;
76 }
77 return V::load_bits(words.data());
78 } else {
79 if constexpr(V::lanes==1) {
80 auto const integer=_mm_cvttss_si32(_mm_set_ss(biased.to_native()));
81 return V::from_bits(std::uint32_t(integer>0 ? integer : 0)<<23);
82 } else if constexpr(V::lanes==2 || V::lanes==3) {
83 // Zero input padding converts to zero and stays zero after the shift.
84 V result;
85 result.value=__builtin_bit_cast(typename V::native_type,
86 native_ops<typename V::storage_type>::exp_factor(biased.to_storage()).to_native());
87 return result;
88 }
89#if NATIVE_HAS_AVX2
90 else if constexpr(V::lanes==4) {
91 auto const integer=_mm_max_epi32(_mm_cvttps_epi32(biased.to_native()),_mm_setzero_si128());
92 return V::from_native(_mm_castsi128_ps(_mm_slli_epi32(integer,23)));
93 } else if constexpr(V::lanes==8) {
94 auto const integer=_mm256_max_epi32(_mm256_cvttps_epi32(biased.to_native()),_mm256_setzero_si256());
95 return V::from_native(_mm256_castsi256_ps(_mm256_slli_epi32(integer,23)));
96 }
97#endif
98 }
99 }
100 }
101#endif
102 // Internal normal power-of-two reconstruction for expm1. Special inputs
103 // have defined integer conversions; the caller selects range endpoints.
104 static inline constexpr V exp_power(V n) noexcept {
105#if NATIVE_HOST_WASM
106 if constexpr(::native::detail::polyfill_operation_shape<typename V::value_type,V::lanes,V::architecture>) {
107 return ::native::detail::polyfill_transform_chunks<V>(n,[](auto chunk) { return native_ops<decltype(chunk)>::exp_power(chunk); });
108 } else
109#endif
110 {
111#if NATIVE_HAS_AVX512F
112 if constexpr (V::lanes == 1 || V::lanes == 16 || (NATIVE_HAS_AVX512VL && V::lanes > 1))
113 return scaleb(V(1.f),n);
114 else
115#endif
116 {
117#if NATIVE_HOST_NEON
118 return V::from_bits(::native::fcvtzu(n + V(127.f)).template left<23>());
119#elif NATIVE_HOST_X86
120 return exp_factor(n + V(127.f));
121#else
122 auto const biased=n + V(127.f);
123 if consteval {
124 auto words=::native::detail::float_constant::words(biased);
125 for(auto & word:words) word=::native::detail::float_constant::fcvtzu(word)<<23;
126 return V::load_bits(words.data());
127 } else {
128 if constexpr(V::lanes==1) {
129 auto const word=std::bit_cast<std::uint32_t>(biased.to_native());
130 return V::from_bits(::native::detail::float_constant::fcvtzu(word)<<23);
131 } else if constexpr(V::lanes==2 || V::lanes==3)
132 return V::from_storage(native_ops<typename V::storage_type>::exp_power(n.to_storage()));
133#if NATIVE_HAS_WASM_SIMD128
134 else return V::from_bits(::native::trunc_sat<std::uint32_t>(biased).template left<23>());
135#endif
136 }
137#endif
138 }
139 }
140 }
141 template<class M>
142 static inline constexpr auto exp_scale(M in_range, V replacement, V y, V n) noexcept {
143#if NATIVE_HAS_AVX512F
144 if constexpr (V::lanes == 1 || V::lanes == 16 || (NATIVE_HAS_AVX512VL && V::lanes > 1))
145 return masked_scaleb(in_range, replacement, y, n);
146 else
147#endif
148 {
149#if NATIVE_HOST_NEON
150 // The biased field is unsigned: FCVTZU maps underflow and NaN to zero
151 // without a compare. NaN y survives the multiply. Range flags stay off
152 // the arithmetic chain and select the completed result below.
153 // A single field cannot encode 2^128. Its two-factor reconstruction
154 // has an exact normal first product, with rounding only in the second.
155 // Keep the established lower-range single-factor behavior unchanged.
156 auto const high = n > V(127.f);
157 auto const biased = ::native::fcvtzu(n + select(high, V(126.f), V(127.f)));
158 auto const first = y * V::from_bits(biased.template left<23>());
159 auto const result = select(high, select(high, first, V(0.f)) * V(2.f), first);
160#elif NATIVE_HOST_X86
161 auto const high = n > V(127.f);
162 auto const first = y * exp_factor(n + select(high, V(126.f), V(127.f)));
163 // Do not consume the lower result again: DAZ alone would erase a
164 // subnormal first product even though output flushing is disabled.
165 auto const result = select(high, select(high, first, V(0.f)) * V(2.f), first);
166#else
167 // This is exp's bounded reconstruction, not a scaling instruction.
168 // Finite n within exp's output range is integral in [-150,128].
169 // Split the biased exponent into two normal powers of two:
170 // the first product is exact and normal; only the second can underflow.
171 // Other scalar backends still use a C++ cast with a finite precondition.
172 n = select(in_range & (n == n), n, V(0.f));
173 auto const biased = trig_integer(n + V(254.f));
174 auto const first = biased.template right<1>();
175 auto const second = biased - first;
176 auto const result = (y * V::from_bits(first.template left<23>())) *
177 V::from_bits(second.template left<23>());
178#endif
179 return select(in_range, result, replacement);
180 }
181 }
182 static inline constexpr auto scale_all(V a,V n) noexcept { return scaleb(a,n); }
183 template<class M>
184 static inline constexpr auto choose(M m,V a,V b) noexcept { return select(m,a,b); }
185 template<class M>
186 static inline constexpr auto scale(M m, V a, V n) noexcept { return masked_scaleb_zero(m, a, n); }
187 template<class M>
188 static inline constexpr auto scale_merge(M m,V prior,V a,V n) noexcept { return masked_scaleb(m,prior,a,n); }
189 static inline constexpr auto encode(V a) noexcept { return a.bits(); }
190 static inline constexpr auto decode(V a) noexcept {
191 using F=typename V::template rebind<float>;
192 return F::from_bits(a);
193 }
194 template<unsigned Shift>
195 static inline constexpr auto left(V a) noexcept { return a.template left<Shift>(); }
196 template<unsigned Shift>
197 static inline constexpr auto right(V a) noexcept { return a.template right<Shift>(); }
198 template<class T>
199 static inline constexpr auto mask_words(V a) noexcept { return ::native::mask_bits<T>(a); }
200
201 // Math reducers retain the signed conversion's bits in unsigned storage
202 // for exponent fields and shifts. ARM uses the defined FCVTZS instruction;
203 // the other scalar/constant paths require a bounded nonnegative input.
204 static inline constexpr auto trig_integer(V a) noexcept {
205 if constexpr(::native::detail::polyfill_operation_shape<typename V::value_type,V::lanes,V::architecture>) {
206 using I=typename V::template rebind<std::uint32_t>;
207 if constexpr(::native::detail::polyfill_chunk_compatible<I,V>)
208 return ::native::detail::polyfill_transform_chunks<I>( a,[](auto chunk) { return native_ops<decltype(chunk)>::trig_integer(chunk); });
209 else {
210 std::array<float,V::lanes> values{}; std::array<std::uint32_t,V::lanes> words{}; a.store(values.data());
211 for(std::size_t i=0;i<V::lanes;++i) words[i]=std::bit_cast<std::uint32_t>(
212 ::native::detail::float_constant::fcvtzs(std::bit_cast<std::uint32_t>(values[i])));
213 return I::load(words.data());
214 }
215 } else {
216 using I=typename V::template rebind<std::uint32_t>;
217#if NATIVE_HOST_NEON
218 return I::from_native(__builtin_bit_cast(typename I::native_type,
219 ::native::fcvtzs(a).to_native()));
220#else
221 if consteval {
222 std::array<float,V::lanes> x{};std::array<std::uint32_t,V::lanes> y{};a.store(x.data());
223 for(std::size_t i=0;i<V::lanes;++i) y[i]=static_cast<std::uint32_t>(x[i]);
224 return I::load(y.data());
225 }
226 if constexpr (V::lanes==1) return I(static_cast<std::uint32_t>(a.value));
227 else if constexpr (V::lanes==2 || V::lanes==3)
228 return I::from_storage(native_ops<typename V::storage_type>::trig_integer(a.to_storage()));
229#if NATIVE_HAS_AVX2
230 else if constexpr (V::lanes==4) return I::from_native(_mm_cvttps_epi32(a.value));
231 else if constexpr (V::lanes==8) return I::from_native(_mm256_cvttps_epi32(a.value));
232#endif
233#if NATIVE_HAS_AVX512F
234 else if constexpr (V::lanes==16) return I::from_native(_mm512_cvttps_epi32(a.value));
235#endif
236#if NATIVE_HAS_WASM_SIMD128
237 else if constexpr (V::lanes==4) return ::native::trunc_sat<std::uint32_t>(a);
238#endif
239#endif
240 }
241 }
242 // Eight coefficient words indexed by lanes in [0,7]. Runtime full vectors
243 // use register tables; scalar indexing is confined to scalar/constant paths.
244 static inline constexpr auto tanh_coefficient(V index,
245 std::array<std::uint32_t,8> const & table) noexcept {
246 if constexpr(::native::detail::polyfill_operation_shape<typename V::value_type,V::lanes,V::architecture>) {
247 using F=typename V::template rebind<float>;
248 if constexpr(::native::detail::polyfill_chunk_compatible<F,V>)
249 return ::native::detail::polyfill_transform_chunks<F>( index,[&](auto chunk) { return native_ops<decltype(chunk)>::tanh_coefficient(chunk,table); });
250 else {
251 std::array<std::uint32_t,V::lanes> indices{},words{}; index.store(indices.data());
252 for(std::size_t i=0;i<V::lanes;++i) words[i]=table[indices[i]];
253 return F::load_bits(words.data());
254 }
255 } else {
256 using F=typename V::template rebind<float>;
257 if consteval {
258 std::array<std::uint32_t,V::lanes> indices{},words{};
259 index.store(indices.data());
260 for(std::size_t i=0;i<V::lanes;++i) words[i]=table[indices[i]];
261 return F::load_bits(words.data());
262 } else {
263 if constexpr(V::lanes==1) return F::from_bits(table[index.to_native()]);
264 else if constexpr(V::lanes==2 || V::lanes==3)
265 return F::from_storage(native_ops<typename V::storage_type>::tanh_coefficient(index.to_storage(),table));
266#if NATIVE_HAS_AVX2
267 else if constexpr(V::lanes<=8) {
268 auto const coefficients=__builtin_bit_cast(__m256i,table);
269 if constexpr(V::lanes==4) {
270 auto const indices=_mm256_zextsi128_si256(index.to_native());
271 return F::from_native(_mm_castsi128_ps(_mm256_castsi256_si128(
272 _mm256_permutevar8x32_epi32(coefficients,indices))));
273 } else return F::from_native(_mm256_castsi256_ps(
274 _mm256_permutevar8x32_epi32(coefficients,index.to_native())));
275 }
276#endif
277#if NATIVE_HAS_AVX512F
278 else if constexpr(V::lanes==16) {
279 auto const coefficients=_mm512_broadcast_i64x4(__builtin_bit_cast(__m256i,table));
280 return F::from_native(_mm512_castsi512_ps(
281 _mm512_permutexvar_epi32(index.to_native(),coefficients)));
282 }
283#endif
284#if NATIVE_HAS_ARM_NEON
285 else if constexpr(V::lanes==4) {
286 uint8x16x2_t const coefficients{{vld1q_u8(reinterpret_cast<std::uint8_t const *>(table.data())),
287 vld1q_u8(reinterpret_cast<std::uint8_t const *>(table.data()+4))}};
288 auto const indices=__builtin_bit_cast(uint32x4_t,index.to_native());
289 // Vector arithmetic avoids importing arm_neon.h's internal-linkage
290 // scalar-broadcast wrappers into both native.simd and native.math.
291 auto const offsets=indices*0x04040404u+0x03020100u;
292 return F::from_native(vreinterpretq_f32_u8(vqtbl2q_u8(coefficients,vreinterpretq_u8_u32(offsets))));
293 }
294#endif
295#if NATIVE_HAS_WASM_SIMD128
296 else if constexpr(V::lanes==4) {
297 auto const offsets=wasm_i32x4_add(wasm_i32x4_mul(index.to_native(),wasm_i32x4_splat(0x04040404)),
298 wasm_i32x4_splat(0x03020100));
299 auto const low=wasm_i8x16_swizzle(wasm_v128_load(table.data()),offsets);
300 auto const high=wasm_i8x16_swizzle(wasm_v128_load(table.data()+4),
301 wasm_i8x16_sub(offsets,wasm_i8x16_splat(16)));
302 return F::from_native(wasm_v128_or(low,high));
303 }
304#endif
305 }
306 }
307 }
308 static inline constexpr auto signed_float(V a) noexcept {
309 if constexpr(::native::detail::polyfill_operation_shape<typename V::value_type,V::lanes,V::architecture>) {
310 using F=typename V::template rebind<float>;
311 if constexpr(::native::detail::polyfill_chunk_compatible<F,V>)
312 return ::native::detail::polyfill_transform_chunks<F>( a,[](auto chunk) { return native_ops<decltype(chunk)>::signed_float(chunk); });
313 else {
314 std::array<std::uint32_t,V::lanes> words{}; std::array<float,V::lanes> values{}; a.store(words.data());
315 for(std::size_t i=0;i<V::lanes;++i) values[i]=static_cast<float>(std::bit_cast<std::int32_t>(words[i]));
316 return F::load(values.data());
317 }
318 } else {
319 using F=typename V::template rebind<float>;
320 if consteval {
321 std::array<std::uint32_t,V::lanes> x{};std::array<float,V::lanes> y{};a.store(x.data());
322 for(std::size_t i=0;i<V::lanes;++i) y[i]=static_cast<float>(std::bit_cast<std::int32_t>(x[i]));
323 return F::load(y.data());
324 }
325 if constexpr (V::lanes==1) return F(static_cast<float>(std::bit_cast<std::int32_t>(a.value)));
326 else if constexpr (V::lanes==2 || V::lanes==3)
327 return F::from_storage(native_ops<typename V::storage_type>::signed_float(a.to_storage()));
328#if NATIVE_HAS_AVX2
329 else if constexpr (V::lanes==4) return F(_mm_cvtepi32_ps(a.value));
330 else if constexpr (V::lanes==8) return F(_mm256_cvtepi32_ps(a.value));
331#endif
332#if NATIVE_HAS_AVX512F
333 else if constexpr (V::lanes==16) return F(_mm512_cvtepi32_ps(a.value));
334#endif
335#if NATIVE_HAS_ARM_NEON
336 else if constexpr (V::lanes==4) return F(vcvtq_f32_s32(vreinterpretq_s32_u8(a.value)));
337#endif
338#if NATIVE_HAS_WASM_SIMD128
339 else if constexpr (V::lanes==4) {
340 using I=typename V::template rebind<std::int32_t>;
341 return ::native::convert<float>(I::from_native(
342 __builtin_bit_cast(typename I::native_type,a.to_native())));
343 }
344#endif
345 }
346 }
347 };
348}
constexpr auto abs(simd< float, N, Arch > a) noexcept
constexpr simd< T, N, A > sqrt(simd< T, N, A > v) noexcept
Compute correctly rounded square roots; negative finite lanes produce NaN.
constexpr simd< T, N, A > round_even(simd< T, N, A > v) noexcept
Round floating lanes to nearest integers, choosing even at ties.
constexpr simd< fp16, 32, Arch > fma(simd< fp16, 32, Arch > a, simd< fp16, 32, Arch > b, simd< fp16, 32, Arch > c) noexcept
constexpr simd< To, 4, A > trunc_sat(simd< From, N, A > a) noexcept
constexpr simd< float, N, A > masked_scaleb(M mask, simd< float, N, A > prior, simd< float, N, A > value, simd< float, N, A > exponent) noexcept
constexpr simd< float, N, A > scaleb(simd< float, N, A > value, simd< float, N, A > exponent) noexcept
Scale every logical lane, preferring each available native scaling register.
constexpr simd< float, N, A > masked_scaleb_zero(M mask, simd< float, N, A > value, simd< float, N, A > exponent) noexcept
Scale active lanes and write positive zero to every inactive lane.