SuperDex Physics C++ API
Loading...
Searching...
No Matches
simd_inl.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
18
20
21#include <array>
22#include <cmath>
23#include <cstring>
24#include <limits>
25#include <type_traits>
26#include <utility>
27
28// Reverse include for intellisense
29#include "../simd.h"
30
31namespace superdex {
32
33namespace details {
34#if MOCHI_ARCH_X64_SVML
35inline constexpr bool kUseSvml = true;
36#else
37inline constexpr bool kUseSvml = false;
38#endif
39} // namespace details
40
41/***********************************************************************************************
42 Overloaded Operators for Simd<T, N>
43*/
44
45// Defines operators like += for Simd types. The right hand side can be any type as long as
46// the corresponding binary operator (e.g. operator+) exists.
47#define MOCHI_DEFINE_SIMD_OP_EQ(OP_EQ, OP) \
48 template <class T, int N, class RHS> \
49 MOCHI_ANY MOCHI_FORCE_INLINE Simd<T, N>& operator OP_EQ(Simd<T, N>& lhs, RHS rhs) { \
50 lhs = lhs OP rhs; \
51 return lhs; \
52 }
53
54// Defines binary operators between Simd<T, N> and T (either order).
55#define MOCHI_DEFINE_MIXED_SIMD_SCALAR_OP(OP) \
56 template <class T, int N> \
57 MOCHI_ANY MOCHI_FORCE_INLINE auto operator OP(Simd<T, N> lhs, T rhs) { \
58 return lhs OP Simd<T, N>{rhs}; \
59 } \
60 template <class T, int N> \
61 MOCHI_ANY MOCHI_FORCE_INLINE auto operator OP(T lhs, Simd<T, N> rhs) { \
62 return Simd<T, N>{lhs} OP rhs; \
63 }
64
72#undef MOCHI_DEFINE_SIMD_OP_EQ
73
78#undef MOCHI_DEFINE_MIXED_SIMD_SCALAR_OP
79
80namespace details {
81// Returns true if every lane is either all-bits-0 (logical false) or all-bits-1 (logical true).
82template <class T, int N>
83[[nodiscard]] MOCHI_ANY MOCHI_FORCE_INLINE bool IsValidLogicalMask(Simd<T, N> a) {
84 static_assert(sizeof(T) == sizeof(int) || sizeof(T) == sizeof(int64_t));
85 using I = std::conditional_t<sizeof(T) == sizeof(int), int, int64_t>;
86 using IVec = Simd<I, N>;
87 auto const ia = ReinterpretCast<IVec>(a);
88 auto const zero = IVec{};
89 auto const ones = ~zero;
90 // The free AllTrue asserts IsValidLogicalMask, so calling it here would recurse.
91 return IVec::template AllTrue<N>(VEqual(ia, zero) | VEqual(ia, ones));
92}
93} // namespace details
94
95template <class T, int N>
98 superdex::details::IsValidLogicalMask(lhs) && superdex::details::IsValidLogicalMask(rhs),
99 "operator&& requires all lanes to have all-bits-0 or all-bits-1");
100 return lhs & rhs;
101}
102
103template <class T, int N>
106 superdex::details::IsValidLogicalMask(lhs) && superdex::details::IsValidLogicalMask(rhs),
107 "operator|| requires all lanes to have all-bits-0 or all-bits-1");
108 return lhs | rhs;
109}
110
111/***********************************************************************************************
112 Simd Function Definitions
113*/
114
115template <class V, MOCHI_CONCEPT_DEF(IsSimd<V>)>
116MOCHI_ANY MOCHI_FORCE_INLINE V Broadcast(typename V::Scalar a) {
117 return V{a};
118}
119
120// Default implementation for most vector type
121template <class V, MOCHI_CONCEPT_DEF(IsSimd<V>)>
122MOCHI_ANY MOCHI_FORCE_INLINE V Broadcast(typename V::Scalar const* p) {
123 return V::Broadcast(p);
124}
125
126template <int i, class T, int N>
130
131template <class T, int N>
133 // TODO: Other implementations may be faster for specific vector sizes, but this covers the bases.
134 return Simd<T, N>{v[i]};
135}
136
137template <class V, class... MoreBools>
138MOCHI_ANY MOCHI_FORCE_INLINE V SimdMask(bool b0, bool b1, MoreBools... bs) {
139 static_assert(V::kSize == sizeof...(bs) + 2, "Incorrect number of arguments");
140 using I = std::conditional_t<sizeof(typename V::Scalar) == sizeof(int), int, int64_t>;
141 using IVec = Simd<I, V::kSize>;
142 constexpr I kSimdBool[2] = {0, -1}; // false, true
143 return ReinterpretCast<V>(IVec{kSimdBool[b0], kSimdBool[b1], kSimdBool[bs]...});
144}
145
146template <class V>
148 return V::Zero();
149}
150
151template <int i, class V>
153 return V::template SetBasisVector<i>();
154}
155
156template <class V>
158 static_assert(V::kSize == 4, "Unsupported SIMD size");
159 switch (axis) {
160 case 0:
161 return V::template SetBasisVector<0>();
162 case 1:
163 return V::template SetBasisVector<1>();
164 case 2:
165 return V::template SetBasisVector<2>();
166 case 3:
167 return V::template SetBasisVector<3>();
168 default:
169 MOCHI_ASSERT(axis >= 0 && axis <= 3, "Invalid component index");
170 return {};
171 }
172}
173
174template <class V>
176 return V::AsPoint(a);
177}
178
179template <class V>
181 return V::AsDirection(a);
182}
183
184template <class V, MOCHI_CONCEPT_DEF(IsSimd<V>)>
185MOCHI_ANY MOCHI_FORCE_INLINE V Load(typename V::Scalar const* ptr) {
186 return V::template Load<V::kSize>(ptr);
187}
188
189template <int N, class V, MOCHI_CONCEPT_DEF(IsSimd<V>)>
190MOCHI_ANY MOCHI_FORCE_INLINE V Load(typename V::Scalar const* ptr) {
191 return V::template Load<N>(ptr);
192}
193
194template <class V, MOCHI_CONCEPT_DEF(IsSimd<V>)>
195MOCHI_ANY MOCHI_FORCE_INLINE V Load(typename V::Scalar const* ptr, int n) {
196 return V::Load(ptr, n);
197}
198
199template <class V, class I, MOCHI_CONCEPT_DEF(IsSimd<V>)>
201LoadIndexed(typename V::Scalar const* ptr, Simd<I, V::kSize> indices) {
202 static_assert(std::is_integral_v<I>, "Requires integral type");
203 return V::LoadIndexed(ptr, indices);
204}
205
206template <int kTupleCount, class T, int N>
208LoadTransposed(T const* ptr, Simd<T, N>& out0, Simd<T, N>& out1, Simd<T, N>& out2) {
209 constexpr int kTupleCount_ = (kTupleCount == -1) ? N : kTupleCount;
211}
212
213template <class T, int N>
215LoadTransposed(T const* ptr, Simd<T, N>& out0, Simd<T, N>& out1, Simd<T, N>& out2, int count) {
216 Simd<T, N>::LoadTransposed(ptr, out0, out1, out2, count);
217}
218
219template <int COUNT, class T, int N>
221 constexpr int COUNT_ = (COUNT == -1) ? N : COUNT;
223}
224
225template <class T, int N>
226MOCHI_ANY MOCHI_FORCE_INLINE void Store(T* ptr, Simd<T, N> a, int count) {
227 Simd<T, N>::Store(ptr, a, count);
228}
229
230template <class T, int N, class MaskT>
232StoreSelected(T* ptr, Simd<MaskT, N> condition, Simd<T, N> values) {
234 superdex::details::IsValidLogicalMask(condition),
235 "Not a valid logical mask. Each lane must be all-bits-0 or all-bits-1.");
236 if constexpr (sizeof(MaskT) == 8 && sizeof(T) == 4) { // Example: MaskT = double, T = int
237 auto conditionI64 = ReinterpretCast<Simd<int64_t, N>>(condition);
238 auto conditionI32 = StaticCast<Simd<int, N>>(conditionI64);
240 (conditionI32 == StaticCast<Simd<int, N>>(conditionI64 & int64_t(0x00000000FFFFFFFFLL))),
241 "Expected StaticCast from int64_t to int32_t to return the lower 32 bits. This is not guaranteed by the C++ standard for static_cast, "
242 "but it is guaranteed by the x64 and ARM implementations. Your new CPU architecture behaves differenty. Therefore, this code will "
243 "need to perform a masking operation, or use Simd<uint64_t, N> and Simd<uint32_t, N> (not supported at the time of writing).");
244 return Simd<T, N>::StoreSelected(ptr, ReinterpretCast<Simd<T, N>>(conditionI32), values);
245 } else {
246 return Simd<T, N>::StoreSelected(ptr, ReinterpretCast<Simd<T, N>>(condition), values);
247 }
248}
249
250template <int kTupleCount, class T, int N>
253 constexpr int kTupleCount_ = (kTupleCount == -1) ? N : kTupleCount;
255}
256
257template <class T, int N>
259StoreTransposed(T* ptr, Simd<T, N> a, Simd<T, N> b, Simd<T, N> c, int count) {
260 Simd<T, N>::StoreTransposed(ptr, a, b, c, count);
261}
262
263template <class T, int N, class MaskT>
267 superdex::details::IsValidLogicalMask(conditionMask),
268 "Not a valid logical mask. Each lane must be all-bits-0 or all-bits-1.");
269 return Simd<T, N>::Select(ReinterpretCast<Simd<T, N>>(conditionMask), a, b);
270}
271
272template <int kShift, class T, int N>
274 static_assert(
275 Simd<T, N>::kIsSupported && std::is_integral_v<T> && std::is_signed_v<T>,
276 "ShiftRight requires a supported signed integer Simd type");
277 static_assert(kShift >= 0 && kShift < (8 * sizeof(T)), "Shift amount out-of-range");
278 if constexpr (kShift == 0) {
279 return a;
280 } else {
282 }
283}
284
285template <int x, int y, class T>
289
290template <int x, int y, int z, int w, class T>
294
295template <int x, int y, int z, int w, class T>
299
300template <int x, int y, class T, int N>
304
305template <int x, int y, int z, int w, class T, int N>
309
310template <class T, int N>
314
315template <int i, class T, int N>
319
320template <int iHalf, class T, int N>
324
325template <int i, class T, int N>
326[[nodiscard]] Simd<T, N> Set(Simd<T, N> a, T value) {
327 return Simd<T, N>::template Set<i>(a, value);
328}
329
330template <class T, int N>
331[[nodiscard]] MOCHI_ANY MOCHI_FORCE_INLINE Simd<T, N> Set(Simd<T, N> a, int i, T value) {
332 return Simd<T, N>::Set(a, i, value);
333}
334
335template <class V>
337 using T = typename V::Scalar;
338 static_assert(V::kIsSupported && std::is_integral_v<T>, "Must be a supported integral Simd type");
339 if constexpr (V::kIsComposite) {
340 return V::Sequence();
341 } else {
342 alignas(V) T constexpr kSequence[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
343 static_assert(
344 std::size(kSequence) >= V::kSize,
345 "Vector size is too large. Size of kSequence must be increased.");
346 return V::template Load<V::kSize>(kSequence);
347 }
348}
349
350template <bool x, bool y, bool z, bool w, class T, int N>
352 static_assert(
353 std::is_floating_point_v<T> && (N == 4),
354 "This implementation is intended for Vec4f or Vec4d only");
355 return Blend<x, y, z, w>(a, -a);
356}
357
358template <class T, int N>
360 static_assert(std::is_floating_point_v<T>, "Requires float or double");
361 return Simd<T, N>::Sqrt(a);
362}
363
364template <class T, int N>
368
369template <class T, int N>
373
374template <class T, int N>
378
379template <class T, int N>
383
384template <class T, int N>
388
389template <int COUNT, class T, int N>
391 constexpr int COUNT_ = (COUNT == -1) ? N : COUNT;
392 if constexpr (COUNT_ == 1) {
393 return Get0(a);
394 } else {
396 }
397}
398
399template <class T>
403
404template <class T, int N>
407 static_assert(kHasHSumEach<Simd<T, N>>, "Unsupported N");
408 if constexpr (N == 4) {
409 return Simd<T, 4>::HSumEach(a, b, c, d);
410 } else {
411 return HSumEach(
412 GetHalf<0>(a) + GetHalf<1>(a),
413 GetHalf<0>(b) + GetHalf<1>(b),
414 GetHalf<0>(c) + GetHalf<1>(c),
415 GetHalf<0>(d) + GetHalf<1>(d));
416 }
417}
418
419template <int COUNT, class T, int N>
421 constexpr int COUNT_ = (COUNT == -1) ? N : COUNT;
422 if constexpr (COUNT_ == 1) {
423 return Get0(a);
424 } else {
426 }
427}
428
429template <int COUNT, class T, int N>
431 constexpr int COUNT_ = (COUNT == -1) ? N : COUNT;
432 if constexpr (COUNT_ == 1) {
433 return Get0(a);
434 } else {
436 }
437}
438
439template <int COUNT, class T, int N>
441 constexpr int COUNT_ = (COUNT == -1) ? N : COUNT;
442 if constexpr (COUNT_ == 1) {
443 return Get0(a);
444 } else {
446 }
447}
448
449#define MOCHI_SIMD_MEMBERWISE_FALLBACK(T, N, FN, inVec) \
450 ([&]() { \
451 alignas(alignof(Simd<T, N>)) T buf[N]; \
452 Store(buf, inVec); \
453 for (int i = 0; i < N; ++i) { \
454 buf[i] = FN(buf[i]); \
455 } \
456 return Load<Simd<T, N>>(buf); \
457 }())
458
459template <class T, int N>
463
464template <class T, int N>
468
469namespace details {
470// We have a custom SIMD implementation of single-precision sine and cosine. These are computed by
471// summing the first few terms of the Taylor series. The problem is that precision decreases as
472// abs(x) increases. Therefore, the first step is to reduce the range of x. Depending on the
473// quadrant, we may return either the sine or the cosine, and we may need to flip the sign. All of
474// this can be done quickly with branchless SIMD instructions.
475//
476// Some details of this implementation were inspired by code provided by ARM Software:
477// https://github.com/ARM-software/optimized-routines
478//
479template <int N>
481SinCosImpl(Simd<float, N> xf, Simd<float, N>& outSin, Simd<float, N>& outCos, Simd<int, N>& outN) {
482 // Convert to double precision
483 auto x = StaticCast<Simd<double, N>>(xf);
484
485 // Reduce x to [-pi/4, pi/4] in quadrant n
486 auto r = FastRound(x * 0x1.45f306dc9c883p-1); // round(x * (2/pi))
487 outN = StaticCast<Simd<int, N>>(r);
488 x = x - r * 0x1.921fb54442d18p0; // x - n * (pi/2)
489
490 // Compute Taylor series for both sin and cos
491 auto x2 = x * x; // x^2
492 auto x3 = x * x2; // x^3
493 auto x4 = x2 * x2; // x^4
494 auto s1 = 0x1.1107605230bc4p-7 - x2 * 0x1.994eb3774cf24p-13; // 1/5! - (x^2)/7!
495 auto c1 = 1.0 - x2 * 0.5;
496 auto c2 = -0x1.6c087e89a359dp-10 + x2 * 0x1.99343027bf8c3p-16; // -1/6! + (x^2)/8!
497 auto x5 = x3 * x2; // x^5
498 auto x6 = x4 * x2; // x^6
499 auto s0 = x - x3 * 0x1.555545995a603p-3; // x - (x^3)/3!
500 auto c0 = c1 + x4 * 0x1.55553e1068f19p-5; // 1 - (x^2)/2! + (x^4)/4!
501
502 // outSin = x - (x^3)/3! + (x^5)/5! - (x^7)/7!
503 outSin = StaticCast<Simd<float, N>>(s0 + x5 * s1);
504
505 // outCos = 1 - (x^2)/2! + (x^4)/4! - (x^6)/6! + (x^8)/8!
506 outCos = StaticCast<Simd<float, N>>(c0 + x6 * c2);
507}
508
509// Preserve the documented accuracy bound and keep the quadrant index
510// representable by falling back for larger inputs.
511inline constexpr float kMaxFastSinCosInput = 1e6f;
512
513template <int N>
514MOCHI_ANY MOCHI_FORCE_INLINE bool IsFastSinCosInput(Simd<float, N> a) {
515 return AllTrue(Abs(a) <= Simd<float, N>{kMaxFastSinCosInput});
516}
517} // namespace details
518
519template <class T, int N>
521 // TODO: When C++20 syntax in this header is legal, gate based on whether Simd<T, N>::Cos() is
522 // implemented. Same for all other functions with a SIMD memberwise fallback.
523 if constexpr (details::kUseSvml || Simd<T, N>::kIsEmulated) {
524 // There are x64 intrinsics if SVML extension is available
525 return Simd<T, N>::Cos(a);
526 } else if constexpr (std::is_same_v<T, float>) {
527 if (!details::IsFastSinCosInput(a)) MOCHI_UNLIKELY {
528 return MOCHI_SIMD_MEMBERWISE_FALLBACK(T, N, std::cos, a);
529 }
530 // Reduce x to [-pi/4, pi/4) in quadrant n and compute Taylor series
531 Simd<float, N> sin, cos;
532 Simd<int, N> n;
533 details::SinCosImpl(a, sin, cos, n);
534 // Use bitwise ops to select cos for (n == 0) || (n == 2). Else select sin.
535 auto result = Select((n & 1) - 1, cos, sin);
536 // Then flip the sign if (n == 1) || (n == 2).
537 return result ^ ReinterpretCast<Simd<float, N>>((n ^ ShiftRight<1>(n)) << 31);
538 } else {
539 return MOCHI_SIMD_MEMBERWISE_FALLBACK(T, N, std::cos, a); // Fallback
540 }
541}
542
543template <class T, int N>
545 if constexpr (details::kUseSvml || Simd<T, N>::kIsEmulated) {
546 // There are x64 intrinsics if SVML extension is available
547 return Simd<T, N>::Sin(a);
548 } else if constexpr (std::is_same_v<T, float>) {
549 if (!details::IsFastSinCosInput(a)) MOCHI_UNLIKELY {
550 return MOCHI_SIMD_MEMBERWISE_FALLBACK(T, N, std::sin, a);
551 }
552 // Reduce x to [-pi/4, pi/4) in quadrant n and compute Taylor series
553 Simd<T, N> sin, cos;
554 Simd<int, N> n;
555 details::SinCosImpl(a, sin, cos, n);
556 // Use bitwise ops to select sin for (n == 0) || (n == 2). Else select cos.
557 auto result = Select((n & 1) - 1, sin, cos);
558 // Then flip the sign if (n == 2) || (n == 3).
559 return result ^ ReinterpretCast<Simd<T, N>>(ShiftRight<1>(n) << 31);
560 } else {
561 return MOCHI_SIMD_MEMBERWISE_FALLBACK(T, N, std::sin, a);
562 }
563}
564
565template <class T, int N>
566inline std::pair<Simd<T, N>, Simd<T, N>> SinCos(Simd<T, N> a) {
567 // Our custom single-precision implementation can efficiently compute sin and cos at the same
568 // time. However, we still use call Sin and Cos separately when they are implemented with SVML, so
569 // that the results will be exactly the same.
570 if constexpr (!MOCHI_ARCH_X64_SVML && std::is_same_v<T, float>) {
571 if (!details::IsFastSinCosInput(a)) MOCHI_UNLIKELY {
572 return {Sin(a), Cos(a)};
573 }
574 Simd<float, N> sin, cos;
575 Simd<int, N> n;
576 details::SinCosImpl(a, sin, cos, n);
577 auto mask = ReinterpretCast<Simd<float, N>>((n & 1) - 1);
578 auto nr = ShiftRight<1>(n);
579 auto sresult = Select(mask, sin, cos) ^ ReinterpretCast<Simd<float, N>>(nr << 31);
580 auto cresult = Select(mask, cos, sin) ^ ReinterpretCast<Simd<float, N>>((n ^ nr) << 31);
581 return {sresult, cresult};
582 } else {
583 return {Sin(a), Cos(a)};
584 }
585}
586
587template <class T, int N>
589 if constexpr (details::kUseSvml || Simd<T, N>::kIsEmulated) {
590 // Simd<T, N>::Tan only implemented in this case.
591 return Simd<T, N>::Tan(a);
592 } else {
593 return MOCHI_SIMD_MEMBERWISE_FALLBACK(T, N, std::tan, a);
594 }
595}
596
597template <class T, int N>
599 if constexpr (details::kUseSvml || Simd<T, N>::kIsEmulated) {
600 // Simd<T, N>::ACos only implemented in this case.
601 return Simd<T, N>::ACos(a);
602 } else {
603 return MOCHI_SIMD_MEMBERWISE_FALLBACK(T, N, std::acos, a);
604 }
605}
606
607template <class T, int N>
609 if constexpr (details::kUseSvml || Simd<T, N>::kIsEmulated) {
610 // Simd<T, N>::ASin only implemented in this case.
611 return Simd<T, N>::ASin(a);
612 } else {
613 return MOCHI_SIMD_MEMBERWISE_FALLBACK(T, N, std::asin, a);
614 }
615}
616
617template <class T, int N>
619 if constexpr (details::kUseSvml || Simd<T, N>::kIsEmulated) {
620 // Simd<T, N>::ATan only implemented in this case.
621 return Simd<T, N>::ATan(a);
622 } else {
623 return MOCHI_SIMD_MEMBERWISE_FALLBACK(T, N, std::atan, a);
624 }
625}
626
627template <class T, int N>
629 if constexpr (details::kUseSvml || Simd<T, N>::kIsEmulated) {
630 // Simd<T, N>::Exp only implemented in this case.
631 return Simd<T, N>::Exp(a);
632 } else {
633 //
634 // This code is mimicking the following implementations:
635 // Vc (float):
636 // Vc (double): https://github.com/VcDevel/Vc/blob/1.4/Vc/common/math.h
637 // cephes: https://github.com/jeremybarnes/cephes/blob/master/cmath/exp.c
638 // avx_mathfun: https://github.com/reyoung/avx_mathfun/blob/master/avx_mathfun.h
639 // and the references therein.
640 //
641 //--- Treat the case of float and double
642 Simd<T, N> const infinity(std::numeric_limits<T>::infinity());
643 Simd<T, N> const log2_e(T(1.44269504088896341)); // = ln(e) / ln(2)
644 Simd<T, N> const one(T(1.0));
645 Simd<T, N> const half(T(0.5));
646 Simd<T, N> const zero(T(0.0));
647 //
648 auto x = a;
649 auto n = log2_e * x;
650 n += half;
651 n = Floor(n);
652 if constexpr (std::is_same_v<T const, float const>) {
653 Simd<T, N> const C1(T(0.693359375));
654 Simd<T, N> const C2(T(-2.121944400547138e-04));
655 x -= C1 * n;
656 x -= C2 * n;
657 } else {
658 static_assert(std::is_same_v<T const, double const>);
659 Simd<T, N> const C1(T(0.693145751953125));
660 Simd<T, N> const C2(T(1.42860682030941723212e-06));
661 x -= C1 * n;
662 x -= C2 * n;
663 }
664 //--- Polynomial approximation
665 Simd<T, N> y;
666 if constexpr (std::is_same_v<T const, float const>) {
667 float const P[] = {
668 1.9875691500e-04,
669 1.3982999507e-03,
670 8.3334519073e-03,
671 4.1665795894e-02,
672 1.6666665459e-01,
673 5.0000001201e-01};
674 auto z = x * x;
675 y = Simd<T, N>(P[0]);
676 for (int i = 1; i <= 5; ++i) {
677 y *= x;
678 y += Simd<T, N>(P[i]);
679 }
680 y *= z;
681 y += x;
682 y += one;
683 auto imm0 = StaticCast<Simd<int, N>>(n);
684 imm0 += Simd<int, N>(127); // 127 <- 0x7f
685 imm0 = imm0 << 23;
686 x = y * ReinterpretCast<Simd<T, N>>(imm0); // x = y * Exp2(n);
687 //
688 Simd<T, N> const exp_lo(T(-88.37626226647949));
689 auto const underFlow = (a < exp_lo);
690 x = Simd<T, N>::Select(underFlow, zero, x);
691 //
692 Simd<T, N> const exp_hi(T(88.37626226647949));
693 auto const overFlow = (a > exp_hi);
694 x = Simd<T, N>::Select(overFlow, infinity, x);
695 return x;
696 }
697 //
698 // --- Treating the 'double' case
699 //
700 if constexpr (std::is_same_v<T const, double const>) {
701 double const P[] = {
702 1.26177193074810590878E-4,
703 3.02994407707441961300E-2,
704 9.99999999999999999910E-1,
705 };
706 double const Q[] = {
707 3.00198505138664455042E-6,
708 2.52448340349684104192E-3,
709 2.27265548208155028766E-1,
710 2.00000000000000000009E0,
711 };
712 auto z = x * x;
713 Simd<T, N> pz(P[0]);
714 for (int i = 1; i <= 2; ++i) {
715 pz *= z;
716 pz += Simd<T, N>(P[i]);
717 }
718 pz *= x;
719 Simd<T, N> qz(Q[0]);
720 for (int i = 1; i <= 3; ++i) {
721 qz *= z;
722 qz += Simd<T, N>(Q[i]);
723 }
724 y = pz / (qz - pz);
725 y *= Simd<T, N>(T(2.0));
726 y += one;
727 auto jmm = StaticCast<Simd<int64_t, N>>(n);
728 jmm += Simd<int64_t, N>(1023);
729 jmm = jmm << 52;
730 x = y * ReinterpretCast<Simd<T, N>>(jmm);
731 //
732 Simd<T, N> const exp_lo(T(-709.0));
733 auto const underFlow = (a < exp_lo);
734 x = Simd<T, N>::Select(underFlow, zero, x);
735 //
736 Simd<T, N> const exp_hi(T(709.0));
737 auto const overFlow = (a > exp_hi);
738 x = Simd<T, N>::Select(overFlow, infinity, x);
739 return x;
740 }
741 }
742}
743
744template <class T, int N>
746 if constexpr (details::kUseSvml || Simd<T, N>::kIsEmulated) {
747 // Simd<T, N>::Ln only implemented in this case.
748 return Simd<T, N>::Ln(a);
749 } else {
750 return MOCHI_SIMD_MEMBERWISE_FALLBACK(T, N, std::log, a);
751 }
752}
753
754template <class T, int N>
756 if constexpr (details::kUseSvml || Simd<T, N>::kIsEmulated) {
757 // Simd<T, N>::Tanh only implemented in this case.
758 return Simd<T, N>::Tanh(a);
759 } else {
760 return MOCHI_SIMD_MEMBERWISE_FALLBACK(T, N, std::tanh, a);
761 }
762}
763
764#undef MOCHI_SIMD_MEMBERWISE_FALLBACK
765
766template <class V>
768 return V::Equal(a, b);
769}
770
771template <class V>
773 return V::NotEqual(a, b);
774}
775
776template <int COUNT, class T, int N>
778 if constexpr (COUNT == 1) {
779 return Get0(a) == Get0(b);
780 } else {
781 return AllTrue<COUNT>(VEqual(a, b));
782 }
783}
784
785template <int COUNT, class T, int N>
787#if MOCHI_PLATFORM_MACOS && MOCHI_ARCH_X64 && MOCHI_OPTIMIZED
788 // Work-around for a compiler bug in optimized builds on Intel macOS.
789 return !Equal<COUNT>(a, b);
790#else
791 if constexpr (COUNT == 1) {
792 return Get0(a) != Get0(b);
793 } else {
794 return AnyTrue<COUNT>(VNotEqual(a, b));
795 }
796#endif
797}
798
799template <class V>
801 return Abs(a - b) <= epsilon;
802}
803
804template <class V>
806 return Abs(a) <= epsilon;
807}
808
809template <int COUNT, class T, int N>
811 constexpr int COUNT_ = (COUNT == -1) ? N : COUNT; // -1 means "all"
812 // IsValidLogicalMask needs 4- or 8-byte lanes, so Simd<Half, N> masks go unchecked.
813 if constexpr (sizeof(T) == sizeof(int) || sizeof(T) == sizeof(int64_t)) {
815 superdex::details::IsValidLogicalMask(a),
816 "Not a valid logical mask. Each lane must be all-bits-0 or all-bits-1.");
817 }
819}
820
821template <int COUNT, class T, int N>
823 constexpr int COUNT_ = (COUNT == -1) ? N : COUNT; // -1 means "all"
824 // IsValidLogicalMask needs 4- or 8-byte lanes, so Simd<Half, N> masks go unchecked.
825 if constexpr (sizeof(T) == sizeof(int) || sizeof(T) == sizeof(int64_t)) {
827 superdex::details::IsValidLogicalMask(a),
828 "Not a valid logical mask. Each lane must be all-bits-0 or all-bits-1.");
829 }
831}
832
833template <class T, int N>
835 if constexpr (std::is_same_v<T, float>) {
836 constexpr int kMask = 0x7F800000; // These bits set for inf and NaN variants
837 auto mask = Simd<int, N>{kMask};
838 return ReinterpretCast<Simd<T, N>>(VNotEqual(ReinterpretCast<Simd<int, N>>(a) & mask, mask));
839 } else {
840 static_assert(std::is_same_v<T, double>, "VIsFinite only supports float and double.");
841 constexpr int kMask = 0x7FF00000; // These bits set for inf and NaN variants
842 if constexpr (N == 2 && Simd<int, 4>::kIsSupported) {
843 // Use an Int4 mask. Result comes from the 2 that correspond to the high bits of each
844 // double.
845 auto mask = Simd<int, 4>{kMask};
846 auto temp4i32 = VNotEqual(ReinterpretCast<Simd<int, 4>>(a) & mask, mask);
847 auto temp2i64 = Shuffle<1, 1, 3, 3>(temp4i32);
848 return ReinterpretCast<Simd<double, 2>>(temp2i64);
849 } else if constexpr (N == 4 && Simd<int, 8>::kIsSupported) {
850 // Use an int8 mask. Result comes from the 4 that correspond to the high bits of each
851 // double.
852 auto mask = Simd<int, 8>{kMask};
853 auto temp8i32 = VNotEqual(ReinterpretCast<Simd<int, 8>>(a) & mask, mask);
854 auto low2i64 = Shuffle<1, 1, 3, 3>(GetHalf<0>(temp8i32)); // no 8-way shuffle currently
855 auto high2i64 = Shuffle<1, 1, 3, 3>(GetHalf<1>(temp8i32));
856 auto temp4i64 = Simd<int, 8>(low2i64, high2i64);
857 return ReinterpretCast<Simd<double, 4>>(temp4i64);
858 } else if constexpr (N == 8 && Simd<int64_t, 8>::kIsSupported) {
859 auto mask = Simd<int64_t, 8>{INT64_C(0x7FF0000000000000)};
860 auto bits = ReinterpretCast<Simd<int64_t, 8>>(a);
861 return ReinterpretCast<Simd<double, 8>>(VNotEqual(bits & mask, mask));
862 } else if constexpr (Simd<T, N>::kIsComposite) {
863 return Simd<T, N>{VIsFinite(a.first), VIsFinite(a.second)};
864 } else if constexpr (!MOCHI_USE_SIMD) {
865 // Simd Emulated
866 Simd<T, N> result;
867 for (int i = 0; i < N; ++i) {
868 uint64_t isFinite = -static_cast<uint64_t>(IsFinite(a.raw[i])); // true = -1, false = 0
869 memcpy(&result.raw[i], &isFinite, sizeof(T));
870 }
871 return result;
872 } else {
873 static_assert(std::is_void_v<T>, "Unsupported type or size");
874 }
875 }
876}
877
878template <int i, class T, int N>
880 // The bits of mask[i] should be all zeros for "false", or all ones for "true". Therefore we can
881 // test any byte(s) within mask[i]. We never return a floating-point type so that the caller
882 // doesn't have to worry about comparisons with NaN.
883 constexpr int kNumInts{(sizeof(T) * N) / sizeof(int)};
884 constexpr int kStride = kNumInts / N;
885 return Get<i * kStride>(ReinterpretCast<Simd<int, kNumInts>>(mask));
886}
887
888template <class T, int N>
892
893template <class T, int N>
897
898template <class T, int N>
902
903template <class T, int N>
907
908template <int COUNT, class V>
910 constexpr int COUNT_ = (COUNT == -1) ? V::kSize : COUNT;
911 if constexpr (COUNT_ == 1) {
912 return Broadcast<0>(a * b);
913 } else {
914 return V::template Dot<COUNT_>(a, b);
915 }
916}
917
918template <class T, int N>
922
923template <int COUNT, class T, int N>
925 static_assert(COUNT == -1 || COUNT >= 2, "Unsupported COUNT");
926 static_assert(std::is_floating_point_v<T>, "Requires float or double");
927 return VDot<COUNT>(a, a);
928}
929
930template <int COUNT, class T, int N>
934
935template <int COUNT, class T, int N>
939
940template <int COUNT, class T, int N>
944
945template <int COUNT, class T, int N>
947 // By adding the smallest possible scalar we prevent divide-by-zero and get a zero vector result
948 // There is no change in result for any vector longer than.... something very very very small
949 return a / (VNorm<COUNT>(a) + std::numeric_limits<T>::min());
950}
951
952template <class T, int N>
954 // By adding the smallest possible scalar we prevent divide-by-zero and get a zero vector result
955 // There is no change in result for any vector longer than.... something very very very small
956 return a / (Sqrt(normSqr) + std::numeric_limits<T>::min());
957}
958
959template <class T, int N>
961 return Normalize(a, Simd<T, N>{normSqr});
962}
963
964template <class T>
966 static_assert(std::is_floating_point_v<T>, "Requires float or double");
967
968 // Project the coordinate of the minimum absolute value
969 // then build the orthogonal vector in that subspace
970
971 // Compute mask selecting the minimum absolute value(s)
972 auto abs = Abs(a);
973 auto absMin = HMin<3>(abs);
974
975 // Build possible orthogonal vectors and select them according to the mask.
976 a = ToSimdDirection(a);
977 if (absMin == Get<0>(abs)) { // abs(v[0]) was the smallest value (or tied for smallest)
979 } else if (absMin == Get<1>(abs)) { // abs(v[1]) was the smallest value (or tied for smallest)
981 } else { // abs(v[2]) was the smallest value
983 }
984 return a;
985}
986
987namespace details {
988
989/**
990 Determines the smallest supported SIMD size that uses the minimum possible number of native
991 registers for the requested lane count.
992*/
993template <typename T, int kSize, bool kExceedsNativeSize = (kSize > kSimdDefaultSize<T>)>
994struct NextSupportedSimdSizeHelper;
995
996template <typename T, int kSize>
997struct NextSupportedSimdSizeHelper<T, kSize, true> {
998 static_assert(kSize > 0, "SIMD size must be positive.");
999 static_assert(Simd<T>::kIsSupported, "Type T is not supported for any size N.");
1000 static constexpr int value =
1001 kSimdDefaultSize<T> + NextSupportedSimdSizeHelper<T, kSize - kSimdDefaultSize<T>>::value;
1002};
1003
1004template <typename T, int kSize>
1005struct NextSupportedSimdSizeHelper<T, kSize, false> {
1006 static_assert(kSize > 0, "SIMD size must be positive.");
1007 static_assert(Simd<T>::kIsSupported, "Type T is not supported for any size N.");
1008 static constexpr bool kIsSingleRegister =
1010 static constexpr int value = std::conditional_t<
1011 kIsSingleRegister,
1012 std::integral_constant<int, kSize>,
1013 NextSupportedSimdSizeHelper<T, kSize + 1>>::value;
1014};
1015
1016template <typename T, int kSize>
1017inline constexpr int kNextSupportedSimdSize = NextSupportedSimdSizeHelper<T, kSize>::value;
1018
1019} // namespace details
1020
1021} // namespace superdex
1022
1023/************************************************************************************
1024 Reflection support for Simd<T, N>
1025 Serializes like std::array<T, N>.
1026*/
1027#if MOCHI_USE_REFLECTION
1028template <typename T, int N>
1029struct SReflectTypeTraits<superdex::Simd<T, N>> {
1030 static constexpr SReflect::CoreType coreType = SReflect::CoreType::CT_array;
1031 static SReflect::ArrayTypeInfo const& GetTypeInfo() {
1032 static auto* s_typeInfo =
1033 SReflect::MakeFixedArrayTypeInfo<superdex::Simd<T, N>, T, N>("superdex::Simd", true);
1034 return *s_typeInfo;
1035 }
1036};
1037#endif // MOCHI_USE_REFLECTION
NativeType raw
Definition simd.h:174
static constexpr bool kIsComposite
Definition simd.h:98
static constexpr bool kIsEmulated
Definition simd.h:99
static constexpr bool kIsSupported
Definition simd.h:97
#define MOCHI_ASSERT(condition_without_side_effects,...)
Definition debug.h:81
#define MOCHI_ASSERT_VERBOSE(condition_without_side_effects,...)
Definition debug.h:102
#define MOCHI_USE_SIMD
#define MOCHI_UNLIKELY
#define MOCHI_ARCH_X64_SVML
#define MOCHI_FORCE_INLINE
#define MOCHI_ANY
T Dot(Simd< T, N > a, Simd< T, N > b)
Definition simd.h:704
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:834
Simd< T, 2 > Shuffle(Simd< T, 2 > a)
Definition simd_inl.h:286
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:400
V LoadIndexed(typename V::Scalar const *ptr, Simd< I, V::kSize > indices)
Definition simd_inl.h:201
constexpr T const & Min(T const &a, T const &b)
T NormSqr(Simd< T, N > a)
Definition simd_inl.h:936
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:919
constexpr T Sin(T a)
T HSum(Simd< T, N > a)
Definition simd_inl.h:390
constexpr To StaticCast(From const &a)
Definition basic_utils.h:79
V VDot(V a, V b)
Definition simd_inl.h:909
T HMin(Simd< T, N > a)
Definition simd_inl.h:430
T Norm(Simd< T, N > a)
Definition simd_inl.h:941
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:152
Simd< T, N > Tanh(Simd< T, N > a)
Definition simd_inl.h:755
V VEqual(V a, V b)
Definition simd_inl.h:767
V ToSimdDirection(V a)
Definition simd_inl.h:180
Simd< T, N > Set(Simd< T, N > a, T value)
Definition simd_inl.h:326
V Sequence()
Definition simd_inl.h:336
constexpr auto NotEqual(T const &a, T const &b)
constexpr T Exp(T a)
constexpr T Cos(T a)
V VNearEqual(V a, V b, V epsilon)
Definition simd_inl.h:800
V SimdZero()
Definition simd_inl.h:147
T HMax(Simd< T, N > a)
Definition simd_inl.h:440
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:924
int IsTrue(Simd< T, N > mask)
Definition simd_inl.h:879
V Broadcast(typename V::Scalar a)
Definition simd_inl.h:116
constexpr T Abs(T a)
Definition basic_utils.h:50
V VNotEqual(V a, V b)
Definition simd_inl.h:772
constexpr T MulSub(T a, T b, T c)
Simd< T, N > Normalize(Simd< T, N > a)
Definition simd_inl.h:946
Simd< T, N > Blend(Simd< T, N > a, Simd< T, N > b)
Definition simd_inl.h:301
constexpr T Tan(T a)
bool AnyTrue(T const &a)
Definition basic_utils.h:66
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:745
std::pair< Simd< T, N >, Simd< T, N > > SinCos(Simd< T, N > a)
Definition simd_inl.h:566
T Get(Simd< T, N > v)
Definition simd_inl.h:316
constexpr T Floor(T a)
constexpr T ASin(T a)
Simd< T, N > operator||(Simd< T, N > lhs, Simd< T, N > rhs)
Definition simd_inl.h:104
Simd< T, N > operator&&(Simd< T, N > lhs, Simd< T, N > rhs)
Definition simd_inl.h:96
V SimdMask(bool b0, bool b1, MoreBools... bs)
Definition simd_inl.h:138
Simd< T, N/2 > GetHalf(Simd< T, N > a)
Definition simd_inl.h:321
T HProd(Simd< T, N > a)
Definition simd_inl.h:420
Simd< T, 4 > OrthogonalVector3(Simd< T, 4 > a)
T Get0(Simd< T, N > v)
Definition simd_inl.h:311
Simd< T, N > VNorm(Simd< T, N > a)
Definition simd_inl.h:931
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:208
Simd< T, N > FastRound(Simd< T, N > a)
Definition simd_inl.h:465
void StoreTransposed(T *ptr, Simd< T, N > a, Simd< T, N > b, Simd< T, N > c)
Definition simd_inl.h:252
void Store(T *ptr, Simd< T, N > a)
Definition simd_inl.h:220
Simd< T, N > RcpSqrtApprox(Simd< T, N > a)
Definition simd_inl.h:370
constexpr T RcpApprox(T a)
constexpr T MulAdd(T a, T b, T c)
V VNearZero(V a, V epsilon)
Definition simd_inl.h:805
int StoreSelected(T *ptr, Simd< MaskT, N > condition, Simd< T, N > values)
Definition simd_inl.h:232
V Load(typename V::Scalar const *ptr)
Definition simd_inl.h:185
Simd< T, N > Neg(Simd< T, N > a)
Definition simd_inl.h:351
V ToSimdPoint(V a)
Definition simd_inl.h:175
bool IsFinite(TransformRT const &a)
Simd< T, N > ShiftRight(Simd< T, N > a)
Definition simd_inl.h:273
#define MOCHI_SIMD_MEMBERWISE_FALLBACK(T, N, FN, inVec)
Definition simd_inl.h:449
#define MOCHI_DEFINE_MIXED_SIMD_SCALAR_OP(OP)
Definition simd_inl.h:55
#define MOCHI_DEFINE_SIMD_OP_EQ(OP_EQ, OP)
Definition simd_inl.h:47