xref: /aosp_15_r20/external/webrtc/modules/audio_processing/agc2/rnn_vad/vector_math_avx2.cc (revision d9f758449e529ab9291ac668be2861e7a55c2422)
1 /*
2  *  Copyright (c) 2020 The WebRTC project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10 
11 #include "modules/audio_processing/agc2/rnn_vad/vector_math.h"
12 
13 #include <immintrin.h>
14 
15 #include "api/array_view.h"
16 #include "rtc_base/checks.h"
17 #include "rtc_base/numerics/safe_conversions.h"
18 
19 namespace webrtc {
20 namespace rnn_vad {
21 
DotProductAvx2(rtc::ArrayView<const float> x,rtc::ArrayView<const float> y) const22 float VectorMath::DotProductAvx2(rtc::ArrayView<const float> x,
23                                  rtc::ArrayView<const float> y) const {
24   RTC_DCHECK(cpu_features_.avx2);
25   RTC_DCHECK_EQ(x.size(), y.size());
26   __m256 accumulator = _mm256_setzero_ps();
27   constexpr int kBlockSizeLog2 = 3;
28   constexpr int kBlockSize = 1 << kBlockSizeLog2;
29   const int incomplete_block_index = (x.size() >> kBlockSizeLog2)
30                                      << kBlockSizeLog2;
31   for (int i = 0; i < incomplete_block_index; i += kBlockSize) {
32     RTC_DCHECK_LE(i + kBlockSize, x.size());
33     const __m256 x_i = _mm256_loadu_ps(&x[i]);
34     const __m256 y_i = _mm256_loadu_ps(&y[i]);
35     accumulator = _mm256_fmadd_ps(x_i, y_i, accumulator);
36   }
37   // Reduce `accumulator` by addition.
38   __m128 high = _mm256_extractf128_ps(accumulator, 1);
39   __m128 low = _mm256_extractf128_ps(accumulator, 0);
40   low = _mm_add_ps(high, low);
41   high = _mm_movehl_ps(high, low);
42   low = _mm_add_ps(high, low);
43   high = _mm_shuffle_ps(low, low, 1);
44   low = _mm_add_ss(high, low);
45   float dot_product = _mm_cvtss_f32(low);
46   // Add the result for the last block if incomplete.
47   for (int i = incomplete_block_index; i < rtc::dchecked_cast<int>(x.size());
48        ++i) {
49     dot_product += x[i] * y[i];
50   }
51   return dot_product;
52 }
53 
54 }  // namespace rnn_vad
55 }  // namespace webrtc
56