SuperDex Physics C++ API
Loading...
Searching...
No Matches
simd.h
Go to the documentation of this file.
1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#pragma once
22
23#include <type_traits>
24#include <utility>
25
26namespace superdex {
27
28// Forward declaration for use in composite StaticCast (full definition is in half.h)
29struct Half;
30
31// Number of values of type T that fit in a native SIMD register
32template <class T>
34
35// Type used with enable_if_t that can be used to select a Simd specialization based on type traits
36struct SimdConcept {};
37
38/***********************************************************************************************
39 Simd<T, N>
40
41 A SIMD vector storing N values of type T.
42
43 This generic template must be fully specialized for supported sizes and types.
44 There currently is no reference implementation.
45*/
46template <class T, int N = kSimdDefaultSize<T>, class Concept = SimdConcept>
47class Simd;
48
49// clang-format off
50namespace details {
51template <class T> constexpr bool IsSimdDef = false;
52template <class T, int N> constexpr bool IsSimdDef<Simd<T, N>> = true;
53template <class T> constexpr bool IsSimdSupportedTypeDef = false;
54template <> inline constexpr bool IsSimdSupportedTypeDef<float> = true;
55template <> inline constexpr bool IsSimdSupportedTypeDef<double> = true;
56template <> inline constexpr bool IsSimdSupportedTypeDef<int> = true;
57template <> inline constexpr bool IsSimdSupportedTypeDef<int64_t> = true;
58template <class T> constexpr bool IsHalfDef = false; // Specialized in half.h
59} // namespace details
60// clang-format on
61
62// Compile-time type traits:
63// - IsSimd<T> is true T is an instantiation of the Simd template class.
64// - IsSimdSupportedType<T> is true if Simd<T, N> is supported for some integer N.
65// - IsHalf<T> is true if T is Half (from half.h).
66#if MOCHI_LANGUAGE_CPP20
67template <class T>
68concept IsSimd = details::IsSimdDef<std::decay_t<T>>;
69template <class T>
70concept IsSimdSupportedType = details::IsSimdSupportedTypeDef<T>;
71template <class T>
72concept IsHalf = details::IsHalfDef<std::decay_t<T>>;
73#else
74template <class T>
75inline constexpr bool IsSimd = details::IsSimdDef<std::decay_t<T>>;
76template <class T>
77inline constexpr bool IsSimdSupportedType = details::IsSimdSupportedTypeDef<T>;
78template <class T>
79inline constexpr bool IsHalf = details::IsHalfDef<std::decay_t<T>>;
80#endif
81
82/***********************************************************************************************
83 Simd<T, N>
84
85 A SIMD vector storing N values of type T.
86
87 This generic template must be fully specialized for supported sizes and types.
88 There currently is no reference implementation.
89*/
90template <class T, int N, class Concept>
91class Simd {
92 public:
93 struct NotSupported {};
95 using Scalar = T;
96 static constexpr int kSize = N;
97 static constexpr bool kIsSupported = false; // Can this combination of T and N function
98 static constexpr bool kIsComposite = false; // Is this type a composite of native sizes
99 static constexpr bool kIsEmulated = false; // Whether it emulates SIMD instructions (if true) or
100 // uses actual native SIMD instructions (if false).
101
102 // Check to prevent misuse of Simd<T>::kIsSupported if queried with a const T.
103 static_assert(!std::is_const_v<T>, "Scalar type must not be const");
104
106 static_assert(std::is_same_v<T, void>, "The requested SIMD size or type is not supported");
107 }
108
109 Simd(Simd const& rhs) = default;
110
111 // Implicit conversion from native storage type.
112 Simd(NativeType rhs) : raw(rhs) {};
113
114 // Broadcast scalar
116
117 // Init from 2 or more scalars. Remaining values will be zero.
118 template <class... Ts>
119 Simd(Scalar a, Scalar b, Ts... vals);
120
121 // Lower-case for compatibility with std::size
122 static constexpr size_t size() {
123 return kSize;
124 }
125
126 // Assignment
129
130 // Comparison operators
131 bool operator==(Simd rhs) const;
132 bool operator!=(Simd rhs) const;
133 Simd operator<(Simd rhs) const;
134 Simd operator<=(Simd rhs) const;
135 Simd operator>(Simd rhs) const;
136 Simd operator>=(Simd rhs) const;
137
138 // Math operators
140 Simd operator+(Simd rhs) const;
141 Simd operator-(Simd rhs) const;
142 Simd operator*(Simd rhs) const;
143 Simd operator/(Simd rhs) const;
152
153 // Bitwise operators
155 Simd operator&(Simd rhs) const;
156 Simd operator|(Simd rhs) const;
157 Simd operator^(Simd rhs) const;
161
162 // Logical operators
163 // Each lane must have all-bits-0 (logical false) or all-bits-1 (logical true).
164 Simd operator&&(Simd rhs) const;
165 Simd operator||(Simd rhs) const;
166
167 // Left shift
168 Simd operator<<(int shift) const;
169
170 // Indexing (read only)
171 Scalar operator[](int i) const;
172
173 // Storage type is implementation specific (e.g. __m256)
175};
176
177/// @brief Reinterpret the bits of one Simd type to another of the same binary size.
178/// @note Example: ReinterpretCast<Vec2d>(myVec4i);
179/// @note The generic version of ReinterpretCast is not valid, but specializations
180/// can be provided for specific pairs of types.
181template <class VecTo, class VecFrom, MOCHI_CONCEPT(IsSimd<VecTo>&& IsSimd<VecFrom>)>
182MOCHI_ANY MOCHI_FORCE_INLINE VecTo ReinterpretCast(VecFrom const& a) {
183 static_assert(
184 std::is_same_v<std::decay_t<VecTo>, std::decay_t<VecFrom>>,
185 "ReinterpretCast not supported for these types.");
186 return a;
187}
188
189/// @brief StaticCast from one Simd type to another of the same size.
190/// @note The generic version is a fallback.
191/// Specializations are provided for specific pairs of types.
192template <class VecTo, class VecFrom, MOCHI_CONCEPT(IsSimd<VecTo>&& IsSimd<VecFrom>)>
194
195} // namespace superdex
197namespace superdex {
198
199// Aliases
217
218// clang-format off
219/***********************************************************************************************
220 Native SIMD Function Support Matrix (please keep up-to-date)
221 Functions supporting Simd<T, N> also support composable wider sizes when
222 every native component supports the function.
223
224 For Simd<Half, N> (Vec8h, Vec16h, Vec32h), include half.h.
225
226************************************************************************************************
227
228 | Vec2d | Vec2l | Vec4d | Vec4f | Vec4i | Vec4l | Vec8d | Vec8f | Vec8h | Vec8i | Vec8l | Vec16f | Vec16h | Vec16i | Vec32h |
229 Abs | x | | x | x | | | x | x | | | | x | | | |
230 ACos | x | | x | x | | | x | x | | | | x | | | |
231 AllTrue | x | x | x | x | x | x | x | x | x | x | x | x | x | x | x |
232 AnyTrue | x | | x | x | x | | x | x | x | x | | x | x | x | x |
233 ASin | x | | x | x | | | x | x | | | | x | | | |
234 ATan | x | | x | x | | | x | x | | | | x | | | |
235 Blend | x | x | x | x | x | | | | | | | | | | |
236 Broadcast | x | x | x | x | x | x | x | x | | x | x | x | | x | |
237 Clamp | x | | x | x | | | x | x | | | | x | | | |
238 Cos | x | | x | x | | | x | x | | | | x | | | |
239 Cross3 | | | x | x | | | | | | | | | | | |
240 Dot | x | | x | x | | | x | x | | | | x | | | |
241 (V)Equal | x | x | x | x | x | x | x | x | x | x | x | x | x | x | x |
242 Exp | x | | x | x | | | x | x | | | | x | | | |
243 FastRound | x | | x | x | | | x | x | | | | x | | | |
244 Floor | x | | x | x | | | x | x | | | | x | | | |
245 Get | x | x | x | x | x | x | x | x | x | x | x | x | x | x | x |
246 Get0 | x | x | x | x | x | x | x | x | x | x | x | x | x | x | x |
247 GetHalf | | | x | | | x | x | x | | x | x | x | x | x | x |
248 HMax | x | x | x | x | x | x | x | x | | x | x | x | | x | |
249 HMin | x | x | x | x | x | x | x | x | | x | x | x | | x | |
250 HProd | x | | x | x | | | x | | | | | | | | |
251 HSum | x | x | x | x | x | x | x | x | | x | x | x | | x | |
252 HSumEach | x | x | x | x | x | x | x | x | | x | x | x | | x | |
253 (V)IsFinite | x | | x | x | | | x | x | | | | x | | | |
254 IsTrue | x | x | x | x | x | x | x | x | | x | x | x | | x | |
255 Lerp | x | | x | x | | | x | x | | | | x | | | |
256 Ln | x | | x | x | | | x | x | | | | x | | | |
257 Load | x | x | x | x | x | x | x | x | x | x | x | x | x | x | x |
258 LoadIndexed | x | | x | x | | | x | x | | | | x | | | |
259 LoadTransposed | x | x | x | x | x | x | x | x | | x | x | x | | x | |
260 Max | x | x | x | x | x | x | x | x | | x | x | x | | x | |
261 Min | x | x | x | x | x | x | x | x | | x | x | x | | x | |
262 MulAdd | x | | x | x | | | x | x | | | | x | | | |
263 MulSub | x | | x | x | | | x | x | | | | x | | | |
264 (V)NearEqual | x | | x | x | | | x | x | | | | x | | | |
265 (V)NearZero | x | | x | x | | | x | x | | | | x | | | |
266 Neg (4 bools) | | | x | x | | | | | | | | | | | |
267 NegMulAdd | x | | x | x | | | x | x | | | | x | | | |
268 NegMulSub | x | | x | x | | | x | x | | | | x | | | |
269 (V)Norm | x | | x | x | | | x | x | | | | x | | | |
270 Normalize | x | | x | x | | | x | x | | | | x | | | |
271 NotEqual | x | | x | x | x | | x | x | x | x | | x | x | x | x |
272 VNotEqual | x | x | x | x | x | x | x | x | x | x | x | x | x | x | x |
273 OrthogonalVector3 | | | x | x | | | | | | | | | | | |
274 RcpApprox | x | | x | x | | | x | x | | | | x | | | |
275 RcpSqrtApprox | x | | x | x | | | x | x | | | | x | | | |
276 Select | x | x | x | x | x | x | x | x | | x | x | x | | x | |
277 Set | x | | x | x | x | | x | x | | x | | x | | x | |
278 Sequence | | x | | | x | x | | | | x | x | | | x | |
279 ShiftRight | | x | | | x | x | | | | x | x | | | x | |
280 Shuffle (1 arg) | x | x | x | x | x | x | | | | | | | | | |
281 Shuffle (2 arg) | | | x | x | x | x | | | | | | | | | |
282 Sign | x | | x | x | | | x | x | | | | x | | | |
283 SignedSqrt | x | | x | x | | | x | x | | | | x | | | |
284 SimdBasisVector | | | x | x | | | | | | | | | | | |
285 SimdMask | x | x | x | x | x | x | x | x | | x | x | x | | x | |
286 SimdZero | x | x | x | x | x | x | x | x | x | x | x | x | x | x | x |
287 Sin | x | | x | x | | | x | x | | | | x | | | |
288 SinCos | x | | x | x | | | x | x | | | | x | | | |
289 Sqr | x | x | x | x | x | x | x | x | | x | x | x | | x | |
290 Sqrt | x | | x | x | | | x | x | | | | x | | | |
291 Store | x | x | x | x | x | x | x | x | x | x | x | x | x | x | x |
292 StoreSelected | x | x | x | x | x | x | x | x | | x | x | x | | x | |
293 StoreTransposed | x | x | x | x | x | x | x | x | | x | x | x | | x | |
294 Tan | x | | x | x | | | x | x | | | | x | | | |
295 Tanh | x | | x | x | | | x | x | | | | x | | | |
296 ToSimd | | | x | x | x | x | | | | | | | | | |
297 ToSimdDirection | | | x | x | | | | | | | | | | | |
298 ToSimdPoint | | | x | x | | | | | | | | | | | |
299
300***********************************************************************************************/
301// clang-format on
302
303// Make kDefaultNearEqualEpsilon<T> "just work" when T is a Simd type
304template <class T, int N>
306
307// Broadcast a single value to all elements of the result
308template <class V, MOCHI_CONCEPT(IsSimd<V>)>
309MOCHI_ANY MOCHI_FORCE_INLINE V Broadcast(typename V::Scalar a);
310
311// Broadcast a single value at address ptr to all elements of the result
312template <class V, MOCHI_CONCEPT(IsSimd<V>)>
313MOCHI_ANY MOCHI_FORCE_INLINE V Broadcast(typename V::Scalar const* ptr);
314
315// Broadcast the ith element of a vector to all elements of the result
316template <int i, class T, int N>
317MOCHI_ANY MOCHI_FORCE_INLINE Simd<T, N> Broadcast(Simd<T, N> v);
318
319// Broadcast the ith element of a vector to all elements of the result.
320// Prefer Broadcast<i> if index is known at compile time.
321template <class T, int N>
322MOCHI_ANY MOCHI_FORCE_INLINE Simd<T, N> Broadcast(Simd<T, N> v, int i);
323
324// Return V{b0 ? TRUE : FALSE, b1 ? TRUE : FALSE, ...} where TRUE is represented by all bits set
325// to 1 (e.g. 0xFFFFFFFF) and FALSE is represented by all bits set to 0 (e.g. 0x00000000). This is
326// the same type of mask returned by comparison operators like <, <=, >, and >=. It can be used with
327// functions like AllTrue, AnyTrue, and Select.
328// Example: SimdMask<Vec4r>(true, false, true, false)
329template <class V, class... MoreBools>
330MOCHI_ANY MOCHI_FORCE_INLINE V SimdMask(bool b0, bool b1, MoreBools... bs);
331
332// Return 0 value
333//
334// The function is templated on the return type.
335template <class V = Vec4r>
337
338// Return a vector with a single component set to 1, and the rest to 0.
339template <int i, class V = Vec4r>
341
342// Return a vector with a single component set to 1, and the rest to 0.
343template <class V = Vec4r>
345
346// Return {a[0], a[1], a[2], 1}. Used for positions that can be both rotated & translated.
347template <class V>
349
350// Return {a[0], a[1], a[2], 0}. Used for direction vectors that can only be rotated.
351template <class V>
353
354// Read V::kSize scalars from the specified address into a vector
355template <class V, MOCHI_CONCEPT(IsSimd<V>)>
356MOCHI_ANY MOCHI_FORCE_INLINE V Load(typename V::Scalar const* ptr);
357
358// Read N scalars from the specified address into a vector. Lanes [N, V::kSize) are zero.
359template <int N, class V, MOCHI_CONCEPT(IsSimd<V>)>
360MOCHI_ANY MOCHI_FORCE_INLINE V Load(typename V::Scalar const* ptr);
361
362// Read n scalars from the specified address into a vector. Lanes [n, V::kSize) are zero.
363// Prefer Load<N, V> if the number is a constexpr.
364template <class V, MOCHI_CONCEPT(IsSimd<V>)>
365MOCHI_ANY MOCHI_FORCE_INLINE V Load(typename V::Scalar const* ptr, int n);
366
367// Read V::kSize scalars from an unaligned address offset by Simd<I, kSize>, where I is an integer
368// type.
369template <class V, class I, MOCHI_CONCEPT(IsSimd<V>)>
371LoadIndexed(typename V::Scalar const* ptr, Simd<I, V::kSize> indices);
372
373// Load (kTupleCount * 3) values from memory. Deinterleave into 3 output vectors.
374// By default (kTupleCount == N). Lanes [kTupleCount, N) are zero.
375//
376// If the memory order was:
377// {x0, y0, z0, x1, y1, z1, x2, y2, z2, x3, y3, z3}
378//
379// ...then the output vectors will be:
380// {x0, x1, x2, x3}, {y0, y1, y2, y3}, {z0, z1, z2, z3}
381//
382template <int kTupleCount = -1, class T, int N>
384LoadTransposed(T const* ptr, Simd<T, N>& out0, Simd<T, N>& out1, Simd<T, N>& out2);
385
386// Load (count * 3) values from memory, deinterleaved like LoadTransposed<kTupleCount>, for a
387// runtime count in [0, N]. Lanes [count, N) are zero. Prefer LoadTransposed<kTupleCount> if the
388// count is a constexpr.
389template <class T, int N>
391LoadTransposed(T const* ptr, Simd<T, N>& out0, Simd<T, N>& out1, Simd<T, N>& out2, int count);
392
393// Return the first component of a vector (e.g. a[0])
394template <class T, int N>
395MOCHI_ANY MOCHI_FORCE_INLINE T Get0(Simd<T, N> v);
396
397// Return the ith component of a vector (e.g a[i]), when the index is a constexpr
398template <int i, class T, int N>
399MOCHI_ANY MOCHI_FORCE_INLINE T Get(Simd<T, N> v);
400
401// Return the low or high half of a vector via GetHalf<0>(a) or GetHalf<1>(a)
402template <int iHalf, class T, int N>
403MOCHI_ANY MOCHI_FORCE_INLINE Simd<T, N / 2> GetHalf(Simd<T, N> a);
404
405// Return a copy of the vector with the ith component replaced with a new value.
406template <int i, class T, int N>
407[[nodiscard]] MOCHI_ANY MOCHI_FORCE_INLINE Simd<T, N> Set(Simd<T, N> a, T value);
408
409// Return a copy of the vector with the ith component replaced with a new value.
410template <class T, int N>
411[[nodiscard]] MOCHI_ANY MOCHI_FORCE_INLINE Simd<T, N> Set(Simd<T, N> a, int i, T value);
412
413// Returns a vector with integer values [0, 1, 2, 3, ...].
414// If you want a different starting value, then add an integer to the result.
415// Example: (Sequence<V>() + 1) results in the sequence [1, 2, 3, ...]
416template <class V>
417[[nodiscard]] MOCHI_ANY MOCHI_FORCE_INLINE V Sequence();
418
419// Write COUNT scalars from a vector to the specified address. A COUNT of -1 means "all".
420template <int COUNT = -1, class T, int N>
421MOCHI_ANY MOCHI_FORCE_INLINE void Store(T* ptr, Simd<T, N> a);
422
423// Write count scalars from a vector to the specified address.
424// Prefer Store<N> if the number is a constexpr.
425template <class T, int N>
426MOCHI_ANY MOCHI_FORCE_INLINE void Store(T* ptr, Simd<T, N> a, int count);
427
428// Write each value for which condition[i] is true. It may then write unspecified values for a total
429// of N values written, so the destination buffer must be large enough. Returns the number of
430// values for which condition[i] was true.
431//
432// Example - Store all the positive values (branchless):
433// int count = 0;
434// for (int i = 0; i + N <= isize(src); i += N) {
435// auto values = Load<Simd<T, N>>(&src[i]);
436// count += StoreSelected(&dst[count], values >= 0, values);
437// }
438//
439// Warning: If the condition is somewhat predictable (e.g. many false values in a row), then a
440// traditional branching algorithm may be faster. You should always profile it.
441//
442template <class T, int N, class MaskT>
443MOCHI_ANY MOCHI_FORCE_INLINE int StoreSelected(T* ptr, Simd<MaskT, N> condition, Simd<T, N> values);
444
445// Interleave the values of 3 input vectors. Store those (kTupleCount * 3) values to memory.
446// By default (kTupleCount == N).
447//
448// If the input vectors are:
449// {x0, x1, x2, x3}, {y0, y1, y2, y3}, {z0, z1, z2, z3}
450//
451// ...then the order written to memory will be:
452// {x0, y0, z0, x1, y1, z1, x2, y2, z2, x3, y3, z3}
453//
454template <int kTupleCount = -1, class T, int N>
455MOCHI_ANY MOCHI_FORCE_INLINE void StoreTransposed(T* ptr, Simd<T, N> a, Simd<T, N> b, Simd<T, N> c);
456
457// Store (count * 3) values to memory, interleaved like StoreTransposed<kTupleCount>, for a runtime
458// count in [0, N]. Prefer StoreTransposed<kTupleCount> if the count is a constexpr.
459template <class T, int N>
461StoreTransposed(T* ptr, Simd<T, N> a, Simd<T, N> b, Simd<T, N> c, int count);
462
463// Return result[i] = conditionalMask[i] ? a[i] : b[i]
464// where conditionMask[i] is 0x00000000 (false) or 0xFFFFFFFF (true).
465// Example: Select(a <= b, a, b) is equivalent to Min(a, b)
466template <class T, int N, class MaskT>
468Select(Simd<MaskT, N> conditionMask, Simd<T, N> a, Simd<T, N> b);
469
470// Return a right-shifted integer vector.
471// Signed integer vectors use arithmetic/sign-extending right shift.
472// Unsigned integer vectors are not currently supported.
473template <int kShift, class T, int N>
474MOCHI_ANY MOCHI_FORCE_INLINE Simd<T, N> ShiftRight(Simd<T, N> a);
475
476// Shuffle elements in a vector. Returns: {a[i0], a[i1], ... }
477template <int x = 0, int y = 1, class T>
478MOCHI_ANY MOCHI_FORCE_INLINE Simd<T, 2> Shuffle(Simd<T, 2> a);
479template <int x = 0, int y = 1, int z = 2, int w = 3, class T>
480MOCHI_ANY MOCHI_FORCE_INLINE Simd<T, 4> Shuffle(Simd<T, 4> a);
481
482// Shuffle elements between two vectors. Returns: { a[x], a[y], b[z], b[w] }
483template <int x, int y, int z, int w, class T>
484MOCHI_ANY MOCHI_FORCE_INLINE Simd<T, 4> Shuffle(Simd<T, 4> a, Simd<T, 4> b);
485
486// Blend returns { (x ? b[0] : a[0]), (y ? b[1] : a[1]) }
487template <int x, int y, class T, int N>
488MOCHI_ANY MOCHI_FORCE_INLINE Simd<T, N> Blend(Simd<T, N> a, Simd<T, N> b);
489
490// Blend returns { (x ? b[0] : a[0]), (y ? b[1] : a[1]), (z ? b[2] : a[2]), (w ? b[3] : a[3]) }
491template <int x, int y, int z, int w, class T, int N>
492MOCHI_ANY MOCHI_FORCE_INLINE Simd<T, N> Blend(Simd<T, N> a, Simd<T, N> b);
493
494// Math Operations:
495template <bool x, bool y, bool z, bool w, class T, int N>
497 Simd<T, N> a); // { x ? -a[0] : a[0], y ? -a[1] : a[1], z ? -a[2] : a[2], w ? -a[3] : a[3] }
498template <class T, int N>
499MOCHI_ANY MOCHI_FORCE_INLINE Simd<T, N> Sqrt(Simd<T, N> a); // sqrt(a)
500template <class T, int N>
501MOCHI_ANY MOCHI_FORCE_INLINE Simd<T, N> RcpApprox(Simd<T, N> a); // Fast approximation of 1/a
502template <class T, int N>
504 Simd<T, N> a); // Fast approximation of 1/sqrt(a)
505template <class T, int N>
506MOCHI_ANY MOCHI_FORCE_INLINE Simd<T, N> Abs(Simd<T, N> a); // abs(a)
507
508// NOTE: NaN behavior of Min/Max is undefined (platform-dependent and operand-order-dependent).
509template <class T, int N>
510MOCHI_ANY MOCHI_FORCE_INLINE Simd<T, N> Min(Simd<T, N> a, Simd<T, N> b); // min(a, b)
511template <class T, int N>
512MOCHI_ANY MOCHI_FORCE_INLINE Simd<T, N> Max(Simd<T, N> a, Simd<T, N> b); // max(a, b)
513template <class T, int N>
514MOCHI_ANY MOCHI_FORCE_INLINE Simd<T, N> Floor(Simd<T, N> a); // floor(a)
515
516// Round to the nearest integer. On ARM, exact ties are rounded away from zero, just like with
517// std::round. However, on x64 ties are rounded to the nearest even integer. Use only in situations
518// where this discrepancy is not an issue.
519template <class T, int N>
520MOCHI_ANY MOCHI_FORCE_INLINE Simd<T, N> FastRound(Simd<T, N> a);
521
522// NOT FAST: Horizontal sum of first COUNT elements of a vector. COUNT of -1 means "all".
523template <int COUNT = -1, class T, int N>
524MOCHI_ANY MOCHI_FORCE_INLINE T HSum(Simd<T, N> a);
525
526/// @brief Returns {HSum(a), HSum(b)}. Native SIMD backends compute both sums together, in fewer
527/// instructions than two @ref HSum calls.
528template <class T>
529MOCHI_ANY MOCHI_FORCE_INLINE Simd<T, 2> HSumEach(Simd<T, 2> a, Simd<T, 2> b);
530
531/// @brief True if @ref HSumEach of four vectors of type V is supported.
532template <class V>
533inline constexpr bool kHasHSumEach = false;
534template <class T, int N>
535inline constexpr bool kHasHSumEach<Simd<T, N>> = N >= 4 && IsPowerOfTwo(N);
536
537/// @brief Returns {HSum(a), HSum(b), HSum(c), HSum(d)}. Native SIMD backends compute the four sums
538/// together, in fewer instructions than four @ref HSum calls. Requires @ref kHasHSumEach.
539///
540/// @note Results may not be bitwise equal to @ref HSum for floating-point types: the lanes may be
541/// added in a different order.
542template <class T, int N>
545
546// NOT FAST: Horizontal product of first COUNT elements of a vector. COUNT of -1 means "all".
547template <int COUNT = -1, class T, int N>
549
550// NOT FAST: Horizontal minimum of first COUNT elements of a vector. COUNT of -1 means "all".
551template <int COUNT = -1, class T, int N>
553
554// NOT FAST: Horizontal maximum of first COUNT elements of a vector. COUNT of -1 means "all".
555template <int COUNT = -1, class T, int N>
557
558// We have a custom implementation of cosine for single-precision floats. It matches the precision
559// of std::cos to within than 6.0e-8. Performance is a little slower than a single call to std::cos,
560// but faster than 2 calls, and much faster than N calls. For double-precision, we fall back on SVML
561// intrinsics (no faster than our implementation), or std::cos if SVML is not available.
562template <class T, int N>
564
565// We have a custom implementation of sine for single-precision floats. Performance and precision is
566// nearly identical to Cos (see notes above).
567template <class T, int N>
569
570// If you need both the sine and the cosine of an angle, then this function can compute both at the
571// same time. It is faster than calling std::sin + std::cos for a single float. In that time, it
572// computes sine and cosine for all N vector components. Precision matches the standard library
573// functions to within 6.0e-8 for single-precision floats. For double-precision, we fall back on
574// SVML or scalar functions (more precision, but slower).
575template <class T, int N>
577
578// These trig functions are implemented with intrinsics with the SVML extension is available on x64
579// platforms. Otherwise, these functions are quite slow because they simply call the corresponding
580// std library functions N times.
581template <class T, int N>
583template <class T, int N>
585template <class T, int N>
587template <class T, int N>
589template <class T, int N>
591
592// Exponential. Returns 0 for -inf, inf for inf, and NaN for NaN inputs. Results may overflow to inf
593// up to ln(2)/2 early, and denormal results may flush to 0.
594template <class T, int N>
596
597// Natural logarithm. Returns -inf for +-0, inf for inf, and NaN for negative and NaN inputs.
598template <class T, int N>
600
601// Simd Comparisons:
602// Comparisons are performed for each Simd elements. They return a Simd mask where result[i] has
603// all bits set to 0 to signify "false" or all bits set to 1 to signify "true". This is true for
604// Simd operators <, <=, >, and >= as well as Simd functions with a "V" prefix.
605//
606// Exception:
607// Simd operator== and operator!= return a bool to match typical user expectation. Specifically
608// operator== returns true if all Simd elements are equal, while operator!= returns true if any
609// Simd elements are not equal.
610//
611// Example:
612// auto a = VEqual(Vec4i{1,2,3,4}, Vec4i{1,0,3,0});
613// MOCHI_ASSERT(a == Vec4i{0xFFFFFFFF, 0, 0xFFFFFFFF, 0});
614//
615
616// Return true if ALL of the first COUNT elements are logical true. All N elements must be either
617// all-bits-0 (false) or all-bits-1 (true). COUNT of -1 means "all". Example: AllTrue<2>(a < b)
618// returns true iff ((a[0] < b[0]) && (a[1] < b[1]))
619template <int COUNT = -1, class T, int N>
621
622// Return true if ANY of the first COUNT elements is logical true. All N elements must be either
623// all-bits-0 (false) or all-bits-1 (true). COUNT of -1 means "all". Example: AnyTrue<2>(a < b)
624// returns true iff ((a[0] < b[0]) || (a[1] < b[1]))
625template <int COUNT = -1, class T, int N>
627
628// Returns result[i] = (a[i] == b[i]) ? 0xFFFFFFFF : 0x00000000;
629// See note above regarding Simd comparisons.
630template <class V>
632
633// Return true if (a[i] == b[i]) for ALL of the first COUNT elements. Count of -1 means "all".
634template <int COUNT = -1, class T, int N>
636
637// Returns result[i] = (a[i] != b[i]) ? 0xFFFFFFFF : 0x00000000;
638// See note above regarding Simd comparisons.
639template <class V>
641
642// Return true if (a[i] != b[i]) for ANY of the first COUNT lanes. Count of -1 means "all".
643template <int COUNT = -1, class T, int N>
645
646// Like NearEqual except that it takes a Simd epsilon and returns a Simd bit mask.
647// Returns result[i] = (Abs(a[i] - b[i]) <= epsilon[i]) ? 0xFFFFFFFF : 0x00000000;
648// See note above regarding Simd comparisons.
649template <class V>
650MOCHI_ANY MOCHI_FORCE_INLINE V VNearEqual(V a, V b, V epsilon);
651
652// Return true if (Abs(a[i] - b[i]) <= epsilon) for ALL of the first N lanes.
653// Count of -1 means "all".
654template <int COUNT = -1, class T, int N, class Eps = T>
657 return AllTrue<COUNT>(VNearEqual(a, b, Simd<T, N>{epsilon}));
658}
659
660// Like NearZero except that it takes a Simd epsilon and returns a Simd bit mask.
661// Returns result[i] = (Abs(a[i]) <= epsilon[i]) ? 0xFFFFFFFF : 0x00000000;
662// See note above regarding Simd comparisons.
663template <class V>
664MOCHI_ANY MOCHI_FORCE_INLINE V VNearZero(V a, V epsilon);
665
666// Return true if (Abs(a[i]) <= epsilon) for ALL of the first N lanes. Count of -1 means "all".
667template <int COUNT = -1, class T, int N, class Eps = T>
673
674// Returns result[i] = IsFinite(a[i]) ? 0xFFFFFFFF : 0x00000000;
675template <class T, int N>
676MOCHI_ANY MOCHI_FORCE_INLINE Simd<T, N> VIsFinite(Simd<T, N> a);
677
678// Return true if all elements of the Simd vector are finite (not +inf, -inf, nor NaN).
679template <class T, int N>
683
684// Return a non-zero integer if component i of the vector is considered "true" (see AnyTrue,
685// AllTrue). Example: "if (IsTrue<i>(a < b))" is like writing "if (a[i] < b[i])".
686template <int i, class T, int N>
687MOCHI_ANY MOCHI_FORCE_INLINE int IsTrue(Simd<T, N> mask);
688
689// Fused Math Operations:
690template <class T, int N>
692MulAdd(Simd<T, N> a, Simd<T, N> b, Simd<T, N> c); // (a * b) + c
693template <class T, int N>
695MulSub(Simd<T, N> a, Simd<T, N> b, Simd<T, N> c); // (a * b) - c
696template <class T, int N>
698NegMulAdd(Simd<T, N> a, Simd<T, N> b, Simd<T, N> c); // -(a * b) + c
699template <class T, int N>
701NegMulSub(Simd<T, N> a, Simd<T, N> b, Simd<T, N> c); // -(a * b) - c
702
703// Dot product of the first COUNT elements. Count of -1 means "all". Broadcasts the result to all
704// elements. Use "Dot" (not "VDot") if you want a single scalar result.
705template <int COUNT = -1, class V>
707
708// Dot product of the first COUNT elements. Count of -1 means "all".
709template <int COUNT = -1, class T, int N>
713
714// Cross Product (3 component)
715template <class T, int N>
716MOCHI_ANY MOCHI_FORCE_INLINE Simd<T, N> Cross3(Simd<T, N> a, Simd<T, N> b);
717
718// Compute the square of the norm using the first COUNT elements of a Simd vector. A count of -1
719// means "all". The result will be broadcasted to a new vector. Use NormSqr instead if you want a
720// scalar result.
721template <int COUNT = -1, class T, int N>
722MOCHI_ANY MOCHI_FORCE_INLINE Simd<T, N> VNormSqr(Simd<T, N> a);
723
724// Compute the norm using the first COUNT elements of a Simd vector. A count of -1 means "all". The
725// result will be broadcasted to a new vector. Use Norm instead if you want a scalar result.
726template <int COUNT = -1, class T, int N>
727MOCHI_ANY MOCHI_FORCE_INLINE Simd<T, N> VNorm(Simd<T, N> a);
728
729// Compute the square of the norm using the first COUNT elements of a Simd vector. A count of -1
730// means "all".
731template <int COUNT = -1, class T, int N>
732MOCHI_ANY MOCHI_FORCE_INLINE T NormSqr(Simd<T, N> a);
733
734// Compute the norm using the first COUNT elements of a Simd vector. Count of -1 means "all".
735template <int COUNT = -1, class T, int N>
736MOCHI_ANY MOCHI_FORCE_INLINE T Norm(Simd<T, N> a);
737
738// Normalizes Simd<T, N> elements introducing an epsilon term (to avoid divide-by-zero).
739// Returns (x / (√n₀ + ε), y / (√n₁ + ε), z / (√n₂ + ε), w / (√n₃ + ε))
740template <int COUNT = -1, class T, int N>
741[[nodiscard]] MOCHI_ANY MOCHI_FORCE_INLINE Simd<T, N> Normalize(Simd<T, N> a);
742
743// Use this overload if you have the square of the norm as a Simd vector.
744template <class T, int N>
745[[nodiscard]] MOCHI_ANY MOCHI_FORCE_INLINE Simd<T, N> Normalize(Simd<T, N> a, Simd<T, N> normSqr);
746
747// Use this overload if you have the square of the norm as a scalar.
748template <class T, int N>
749[[nodiscard]] MOCHI_ANY MOCHI_FORCE_INLINE Simd<T, N> Normalize(Simd<T, N> a, T normSqr);
750
751// Builds an arbitrary vector that is orthogonal to the given one.
752template <typename T, int N>
754
755} // namespace superdex
756
757#include "simd/simd_inl.h"
Simd operator-(Simd rhs) const
Simd(NativeType rhs)
Definition simd.h:112
Simd operator&(Simd rhs) const
Simd & operator^=(Simd rhs)
Simd & operator&=(Simd rhs)
Simd & operator/=(T rhs)
bool operator==(Simd rhs) const
Simd operator&&(Simd rhs) const
Simd operator>(Simd rhs) const
Simd operator<<(int shift) const
Simd operator*(Simd rhs) const
Simd & operator-=(T rhs)
Simd operator^(Simd rhs) const
Simd operator-() const
Simd & operator=(Scalar rhs)
Simd & operator-=(Simd rhs)
Simd(Scalar a, Scalar b, Ts... vals)
Simd(Scalar a)
Simd(Simd const &rhs)=default
Simd operator||(Simd rhs) const
Simd operator>=(Simd rhs) const
static constexpr bool kIsComposite
Definition simd.h:98
Simd operator<(Simd rhs) const
Simd & operator*=(T rhs)
Simd & operator|=(Simd rhs)
bool operator!=(Simd rhs) const
Simd & operator*=(Simd rhs)
static constexpr size_t size()
Definition simd.h:122
static constexpr bool kIsEmulated
Definition simd.h:99
Simd & operator=(Simd rhs)
Simd operator|(Simd rhs) const
static constexpr int kSize
Definition simd.h:96
Simd operator+(Simd rhs) const
static constexpr bool kIsSupported
Definition simd.h:97
NotSupported NativeType
Definition simd.h:94
Simd & operator+=(T rhs)
Simd operator~() const
Simd operator/(Simd rhs) const
Simd & operator/=(Simd rhs)
Simd operator<=(Simd rhs) const
Simd & operator+=(Simd rhs)
Scalar operator[](int i) const
#define MOCHI_SIMD_REGISTER_SIZE_BYTES
#define MOCHI_FORCE_INLINE
#define MOCHI_ANY
T Dot(Simd< T, N > a, Simd< T, N > b)
Definition simd.h:710
constexpr T ACos(T a)
constexpr T NegMulAdd(T a, T b, T c)
Simd< T, N > VIsFinite(Simd< T, N > a)
Definition simd_inl.h:862
Simd< T, 2 > Shuffle(Simd< T, 2 > a)
Definition simd_inl.h:287
constexpr int kSimdDefaultSize
Definition simd.h:33
Simd< T, 2 > HSumEach(Simd< T, 2 > a, Simd< T, 2 > b)
Returns {HSum(a), HSum(b)}.
Definition simd_inl.h:401
constexpr bool IsPowerOfTwo(T a)
V LoadIndexed(typename V::Scalar const *ptr, Simd< I, V::kSize > indices)
Definition simd_inl.h:202
constexpr T const & Min(T const &a, T const &b)
Simd< int, 4 > Vec4i
Definition simd.h:204
T NormSqr(Simd< T, N > a)
Definition simd_inl.h:964
constexpr auto Equal(T const &a, T const &b)
Simd< T, N > Cross3(Simd< T, N > a, Simd< T, N > b)
Definition simd_inl.h:947
constexpr T Sin(T a)
T HSum(Simd< T, N > a)
Definition simd_inl.h:391
constexpr To StaticCast(From const &a)
Definition basic_utils.h:79
constexpr T kDefaultNearEqualEpsilon
V VDot(V a, V b)
Definition simd_inl.h:937
T HMin(Simd< T, N > a)
Definition simd_inl.h:451
T Norm(Simd< T, N > a)
Definition simd_inl.h:969
bool AllTrue(T const &a)
Definition basic_utils.h:60
constexpr T NegMulSub(T a, T b, T c)
V SimdBasisVector()
Definition simd_inl.h:153
Simd< real, 16 > Vec16r
Definition simd.h:216
Simd< T, N > Tanh(Simd< T, N > a)
Definition simd_inl.h:783
Simd< int64_t, 2 > Vec2l
Definition simd.h:201
V VEqual(V a, V b)
Definition simd_inl.h:795
V ToSimdDirection(V a)
Definition simd_inl.h:181
Simd< T, N > Set(Simd< T, N > a, T value)
Definition simd_inl.h:327
V Sequence()
Definition simd_inl.h:337
Simd< double, 8 > Vec8d
Definition simd.h:207
constexpr auto NotEqual(T const &a, T const &b)
constexpr T Exp(T a)
Simd< real, 4 > Vec4r
Definition simd.h:206
constexpr T Cos(T a)
V VNearEqual(V a, V b, V epsilon)
Definition simd_inl.h:828
Simd< int, 8 > Vec8i
Definition simd.h:209
V SimdZero()
Definition simd_inl.h:148
T HMax(Simd< T, N > a)
Definition simd_inl.h:461
constexpr bool kHasHSumEach
True if HSumEach of four vectors of type V is supported.
Definition simd.h:533
Simd< T, N > VNormSqr(Simd< T, N > a)
Definition simd_inl.h:952
int IsTrue(Simd< T, N > mask)
Definition simd_inl.h:907
Simd< int64_t, 4 > Vec4l
Definition simd.h:205
V Broadcast(typename V::Scalar a)
Definition simd_inl.h:117
constexpr T Abs(T a)
Definition basic_utils.h:50
V VNotEqual(V a, V b)
Definition simd_inl.h:800
constexpr T MulSub(T a, T b, T c)
Simd< T, N > Normalize(Simd< T, N > a)
Definition simd_inl.h:974
Simd< real, 8 > Vec8r
Definition simd.h:211
Simd< float, 4 > Vec4f
Definition simd.h:203
Simd< T, N > Blend(Simd< T, N > a, Simd< T, N > b)
Definition simd_inl.h:302
constexpr T Tan(T a)
bool AnyTrue(T const &a)
Definition basic_utils.h:66
Simd< double, 4 > Vec4d
Definition simd.h:202
constexpr T Select(bool condition, T a, T b)
constexpr T Sqrt(T a)
constexpr T ATan(T a)
Simd< T, N > Ln(Simd< T, N > a)
Definition simd_inl.h:705
std::pair< Simd< T, N >, Simd< T, N > > SinCos(Simd< T, N > a)
Definition simd_inl.h:587
T Get(Simd< T, N > v)
Definition simd_inl.h:317
Simd< int64_t, 16 > Vec16l
Definition simd.h:215
constexpr T Floor(T a)
constexpr T ASin(T a)
Simd< double, 16 > Vec16d
Definition simd.h:212
V SimdMask(bool b0, bool b1, MoreBools... bs)
Definition simd_inl.h:139
Simd< int, 16 > Vec16i
Definition simd.h:214
Simd< T, N/2 > GetHalf(Simd< T, N > a)
Definition simd_inl.h:322
T HProd(Simd< T, N > a)
Definition simd_inl.h:441
Simd< T, 4 > OrthogonalVector3(Simd< T, 4 > a)
T Get0(Simd< T, N > v)
Definition simd_inl.h:312
Simd< T, N > VNorm(Simd< T, N > a)
Definition simd_inl.h:959
constexpr T const & Max(T const &a, T const &b)
void LoadTransposed(T const *ptr, Simd< T, N > &out0, Simd< T, N > &out1, Simd< T, N > &out2)
Definition simd_inl.h:209
Simd< T, N > FastRound(Simd< T, N > a)
Definition simd_inl.h:486
void StoreTransposed(T *ptr, Simd< T, N > a, Simd< T, N > b, Simd< T, N > c)
Definition simd_inl.h:253
void Store(T *ptr, Simd< T, N > a)
Definition simd_inl.h:221
Simd< T, N > RcpSqrtApprox(Simd< T, N > a)
Definition simd_inl.h:371
Simd< float, 16 > Vec16f
Definition simd.h:213
constexpr T RcpApprox(T a)
Simd< int64_t, 8 > Vec8l
Definition simd.h:210
constexpr T MulAdd(T a, T b, T c)
bool NearEqual(TransformRT const &a, TransformRT const &b, real epsilon=kDefaultNearEqualEpsilon< real >)
V VNearZero(V a, V epsilon)
Definition simd_inl.h:833
int StoreSelected(T *ptr, Simd< MaskT, N > condition, Simd< T, N > values)
Definition simd_inl.h:233
V Load(typename V::Scalar const *ptr)
Definition simd_inl.h:186
Simd< T, N > Neg(Simd< T, N > a)
Definition simd_inl.h:352
Simd< float, 8 > Vec8f
Definition simd.h:208
V ToSimdPoint(V a)
Definition simd_inl.h:176
Simd< double, 2 > Vec2d
Definition simd.h:200
bool IsFinite(TransformRT const &a)
constexpr auto NearZero(T const &a, T epsilon=kDefaultNearEqualEpsilon< T >)
Simd< T, N > ShiftRight(Simd< T, N > a)
Definition simd_inl.h:274