hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
48.5k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
44c0d08c30036ed7bfff7d18d81cf9471f75ae34
| 1,009
|
cpp
|
C++
|
Emaject/examples/single/main.cpp
|
tyanmahou/Emaject
|
f0fcac3a251ce5be7cde3330fe23a40d68155e56
|
[
"MIT"
] | 7
|
2020-12-14T13:41:22.000Z
|
2021-03-02T05:45:57.000Z
|
Emaject/examples/single/main.cpp
|
tyanmahou/Emaject
|
f0fcac3a251ce5be7cde3330fe23a40d68155e56
|
[
"MIT"
] | null | null | null |
Emaject/examples/single/main.cpp
|
tyanmahou/Emaject
|
f0fcac3a251ce5be7cde3330fe23a40d68155e56
|
[
"MIT"
] | null | null | null |
#include <Emaject.hpp>
#include <iostream>
#include <string_view>
using emaject::Container;
using emaject::IInstaller;
using emaject::Injector;
class ICounter
{
public:
virtual int countUp() = 0;
};
class Counter : public ICounter
{
int m_count;
public:
int countUp() override
{
return ++m_count;
}
};
struct CounterInstaller : IInstaller
{
void onBinding(Container* c) const
{
c->bind<ICounter>()
.to<Counter>()
.asSingle();
// compile error "don't use ID"
//c->bind<ICounter, 1>()
// .to<Counter>()
// .asSingle();
}
};
int main()
{
Injector injector;
injector.install<CounterInstaller>();
{
auto counter = injector.resolve<ICounter, 0>(); // new instance
std::cout << counter->countUp() << std::endl; // 1
}
{
auto counter = injector.resolve<ICounter, 1>(); // used cache
std::cout << counter->countUp() << std::endl; // 2
}
}
| 18.685185
| 71
| 0.561943
|
tyanmahou
|
44c841f626c8c0b3ddfd101beedf7b32824828d1
| 41,862
|
cpp
|
C++
|
src/core/NEON/kernels/NEFFTRadixStageKernel.cpp
|
wql15/ComputeLibrary
|
11eac125873e91c828e318224db45701e2f32b39
|
[
"MIT"
] | 2,313
|
2017-03-24T16:25:28.000Z
|
2022-03-31T03:00:30.000Z
|
src/core/NEON/kernels/NEFFTRadixStageKernel.cpp
|
wql15/ComputeLibrary
|
11eac125873e91c828e318224db45701e2f32b39
|
[
"MIT"
] | 952
|
2017-03-28T07:05:58.000Z
|
2022-03-30T09:54:02.000Z
|
src/core/NEON/kernels/NEFFTRadixStageKernel.cpp
|
wql15/ComputeLibrary
|
11eac125873e91c828e318224db45701e2f32b39
|
[
"MIT"
] | 714
|
2017-03-24T22:21:51.000Z
|
2022-03-18T19:49:57.000Z
|
/*
* Copyright (c) 2019-2021 Arm Limited.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "src/core/NEON/kernels/NEFFTRadixStageKernel.h"
#include "arm_compute/core/ITensor.h"
#include "arm_compute/core/TensorInfo.h"
#include "arm_compute/core/Types.h"
#include "arm_compute/core/Utils.h"
#include "arm_compute/core/Window.h"
#include "src/core/NEON/wrapper/traits.h"
#include "src/core/NEON/wrapper/wrapper.h"
#include "src/core/helpers/AutoConfiguration.h"
#include "src/core/helpers/WindowHelpers.h"
#include "support/ToolchainSupport.h"
#include <arm_neon.h>
#include <cmath>
#include <complex>
#include <map>
namespace arm_compute
{
namespace
{
// PI constant (from cmath)
constexpr float kPi = float(M_PI);
// Constant used in the fft_3 kernel
constexpr float kSqrt3Div2 = 0.866025403784438;
// Constants used in the fft_5 kernel
constexpr float kW5_0 = 0.30901699437494f;
constexpr float kW5_1 = 0.95105651629515f;
constexpr float kW5_2 = 0.80901699437494f;
constexpr float kW5_3 = 0.58778525229247f;
// Constants used in the fft_7 kernel
constexpr float kW7_0 = 0.62348980185873f;
constexpr float kW7_1 = 0.78183148246802f;
constexpr float kW7_2 = 0.22252093395631f;
constexpr float kW7_3 = 0.97492791218182f;
constexpr float kW7_4 = 0.90096886790241f;
constexpr float kW7_5 = 0.43388373911755f;
// Constant used in the fft_8 kernel
constexpr float kSqrt2Div2 = 0.707106781186548;
float32x2_t c_mul_neon(float32x2_t a, float32x2_t b)
{
using ExactTagType = typename wrapper::traits::neon_vector<float, 2>::tag_type;
const float32x2_t mask = { -1.0, 1.0 };
const float32x2_t tmp0 = wrapper::vdup_n(wrapper::vgetlane(a, 0), ExactTagType{});
const float32x2_t tmp1 = wrapper::vdup_n(wrapper::vgetlane(a, 1), ExactTagType{});
float32x2_t res = wrapper::vmul(tmp0, b);
b = wrapper::vrev64(b);
b = wrapper::vmul(b, mask);
res = wrapper::vmla(res, tmp1, b);
return res;
}
float32x2_t c_mul_neon_img(float32x2_t a, float img_constant)
{
const float a_r = wrapper::vgetlane(a, 0);
const float a_i = wrapper::vgetlane(a, 1);
const auto out = wrapper::vmul(float32x2_t{ -a_i, a_r }, float32x2_t{ img_constant, img_constant });
return out;
}
float32x2_t reduce_sum_5(float32x2_t a, float32x2_t b, float32x2_t c, float32x2_t d, float32x2_t e)
{
const auto t0 = wrapper::vadd(a, b);
const auto t1 = wrapper::vadd(c, d);
const auto t2 = wrapper::vadd(t0, t1);
return wrapper::vadd(t2, e);
}
float32x2_t reduce_sum_7(float32x2_t x1, float32x2_t x2, float32x2_t x3, float32x2_t x4, float32x2_t x5, float32x2_t x6, float32x2_t x7)
{
const auto t0 = wrapper::vadd(x1, x2);
const auto t1 = wrapper::vadd(x3, x4);
const auto t2 = wrapper::vadd(x5, x6);
const auto t00 = wrapper::vadd(t0, t1);
const auto t01 = wrapper::vadd(t2, x7);
return wrapper::vadd(t00, t01);
}
float32x2_t reduce_sum_8(float32x2_t x1, float32x2_t x2, float32x2_t x3, float32x2_t x4, float32x2_t x5, float32x2_t x6, float32x2_t x7, float32x2_t x8)
{
const auto t0 = wrapper::vadd(x1, x2);
const auto t1 = wrapper::vadd(x3, x4);
const auto t2 = wrapper::vadd(x5, x6);
const auto t3 = wrapper::vadd(x7, x8);
const auto t00 = wrapper::vadd(t0, t1);
const auto t01 = wrapper::vadd(t2, t3);
return wrapper::vadd(t00, t01);
}
void fft_2(float32x2_t &x, float32x2_t &y, float32x2_t &w)
{
float32x2_t a = x;
float32x2_t b = c_mul_neon(w, y);
x = wrapper::vadd(a, b);
y = wrapper::vsub(a, b);
}
void fft_3(float32x2_t &x, float32x2_t &y, float32x2_t &z, const float32x2_t &w, const float32x2_t &w2)
{
float32x2_t a = x;
float32x2_t b = c_mul_neon(w, y);
float32x2_t c = c_mul_neon(w2, z);
x = wrapper::vadd(a, b);
x = wrapper::vadd(x, c);
const auto v1 = wrapper::vmul(float32x2_t{ 0.5f, 0.5 }, wrapper::vadd(b, c));
const auto v2 = c_mul_neon(float32x2_t{ 0.f, -kSqrt3Div2 }, wrapper::vsub(b, c));
y = z = wrapper::vsub(a, v1);
y = wrapper::vadd(y, v2);
z = wrapper::vsub(z, v2);
}
void fft_4(float32x2_t &x1, float32x2_t &x2, float32x2_t &x3, float32x2_t &x4, const float32x2_t &w, const float32x2_t &w2, const float32x2_t &w3)
{
float32x2_t a = x1;
float32x2_t b = c_mul_neon(w, x2);
float32x2_t c = c_mul_neon(w2, x3);
float32x2_t d = c_mul_neon(w3, x4);
const auto x11 = wrapper::vadd(a, b);
const auto x12 = wrapper::vadd(c, d);
x1 = wrapper::vadd(x11, x12);
const auto x21 = wrapper::vadd(a, c_mul_neon_img(b, -1));
const auto x22 = wrapper::vadd(wrapper::vneg(c), c_mul_neon_img(d, 1.f));
x2 = wrapper::vadd(x21, x22);
const auto x31 = wrapper::vadd(a, wrapper::vneg(b));
const auto x32 = wrapper::vadd(c, wrapper::vneg(d));
x3 = wrapper::vadd(x31, x32);
const auto x41 = wrapper::vadd(a, c_mul_neon_img(b, 1));
const auto x42 = wrapper::vadd(wrapper::vneg(c), c_mul_neon_img(d, -1));
x4 = wrapper::vadd(x41, x42);
}
void fft_5(float32x2_t &x1, float32x2_t &x2, float32x2_t &x3, float32x2_t &x4, float32x2_t &x5, const float32x2_t &w, const float32x2_t &w2, const float32x2_t &w3, const float32x2_t &w4)
{
const auto a = x1;
const auto b = c_mul_neon(w, x2);
const auto c = c_mul_neon(w2, x3);
const auto d = c_mul_neon(w3, x4);
const auto e = c_mul_neon(w4, x5);
const auto b0 = c_mul_neon(float32x2_t{ kW5_0, -kW5_1 }, b);
const auto b1 = c_mul_neon(float32x2_t{ -kW5_2, -kW5_3 }, b);
const auto b2 = c_mul_neon(float32x2_t{ -kW5_2, kW5_3 }, b);
const auto b3 = c_mul_neon(float32x2_t{ kW5_0, kW5_1 }, b);
const auto c0 = c_mul_neon(float32x2_t{ -kW5_2, -kW5_3 }, c);
const auto c1 = c_mul_neon(float32x2_t{ kW5_0, kW5_1 }, c);
const auto c2 = c_mul_neon(float32x2_t{ kW5_0, -kW5_1 }, c);
const auto c3 = c_mul_neon(float32x2_t{ -kW5_2, kW5_3 }, c);
const auto d0 = c_mul_neon(float32x2_t{ -kW5_2, kW5_3 }, d);
const auto d1 = c_mul_neon(float32x2_t{ kW5_0, -kW5_1 }, d);
const auto d2 = c_mul_neon(float32x2_t{ kW5_0, kW5_1 }, d);
const auto d3 = c_mul_neon(float32x2_t{ -kW5_2, -kW5_3 }, d);
const auto e0 = c_mul_neon(float32x2_t{ kW5_0, kW5_1 }, e);
const auto e1 = c_mul_neon(float32x2_t{ -kW5_2, kW5_3 }, e);
const auto e2 = c_mul_neon(float32x2_t{ -kW5_2, -kW5_3 }, e);
const auto e3 = c_mul_neon(float32x2_t{ kW5_0, -kW5_1 }, e);
x1 = reduce_sum_5(a, b, c, d, e);
x2 = reduce_sum_5(a, b0, c0, d0, e0);
x3 = reduce_sum_5(a, b1, c1, d1, e1);
x4 = reduce_sum_5(a, b2, c2, d2, e2);
x5 = reduce_sum_5(a, b3, c3, d3, e3);
}
void fft_7(float32x2_t &x1, float32x2_t &x2, float32x2_t &x3, float32x2_t &x4, float32x2_t &x5, float32x2_t &x6, float32x2_t &x7, const float32x2_t &w, const float32x2_t &w2, const float32x2_t &w3,
const float32x2_t &w4,
const float32x2_t &w5, const float32x2_t &w6)
{
const auto a = x1;
const auto b = c_mul_neon(w, x2);
const auto c = c_mul_neon(w2, x3);
const auto d = c_mul_neon(w3, x4);
const auto e = c_mul_neon(w4, x5);
const auto f = c_mul_neon(w5, x6);
const auto g = c_mul_neon(w6, x7);
const auto b0 = c_mul_neon(float32x2_t{ kW7_0, -kW7_1 }, b);
const auto b1 = c_mul_neon(float32x2_t{ -kW7_2, -kW7_3 }, b);
const auto b2 = c_mul_neon(float32x2_t{ -kW7_4, -kW7_5 }, b);
const auto b3 = c_mul_neon(float32x2_t{ -kW7_4, kW7_5 }, b);
const auto b4 = c_mul_neon(float32x2_t{ -kW7_2, kW7_3 }, b);
const auto b5 = c_mul_neon(float32x2_t{ kW7_0, kW7_1 }, b);
const auto c0 = c_mul_neon(float32x2_t{ -kW7_2, -kW7_3 }, c);
const auto c1 = c_mul_neon(float32x2_t{ -kW7_4, kW7_5 }, c);
const auto c2 = c_mul_neon(float32x2_t{ kW7_0, kW7_1 }, c);
const auto c3 = c_mul_neon(float32x2_t{ kW7_0, -kW7_1 }, c);
const auto c4 = c_mul_neon(float32x2_t{ -kW7_4, -kW7_5 }, c);
const auto c5 = c_mul_neon(float32x2_t{ -kW7_2, kW7_3 }, c);
const auto d0 = c_mul_neon(float32x2_t{ -kW7_4, -kW7_5 }, d);
const auto d1 = c_mul_neon(float32x2_t{ kW7_0, kW7_1 }, d);
const auto d2 = c_mul_neon(float32x2_t{ -kW7_2, -kW7_3 }, d);
const auto d3 = c_mul_neon(float32x2_t{ -kW7_2, +kW7_3 }, d);
const auto d4 = c_mul_neon(float32x2_t{ kW7_0, -kW7_1 }, d);
const auto d5 = c_mul_neon(float32x2_t{ -kW7_4, kW7_5 }, d);
const auto e0 = c_mul_neon(float32x2_t{ -kW7_4, kW7_5 }, e);
const auto e1 = c_mul_neon(float32x2_t{ kW7_0, -kW7_1 }, e);
const auto e2 = c_mul_neon(float32x2_t{ -kW7_2, kW7_3 }, e);
const auto e3 = c_mul_neon(float32x2_t{ -kW7_2, -kW7_3 }, e);
const auto e4 = c_mul_neon(float32x2_t{ kW7_0, kW7_1 }, e);
const auto e5 = c_mul_neon(float32x2_t{ -kW7_4, -kW7_5 }, e);
const auto f0 = c_mul_neon(float32x2_t{ -kW7_2, kW7_3 }, f);
const auto f1 = c_mul_neon(float32x2_t{ -kW7_4, -kW7_5 }, f);
const auto f2 = c_mul_neon(float32x2_t{ kW7_0, -kW7_1 }, f);
const auto f3 = c_mul_neon(float32x2_t{ kW7_0, kW7_1 }, f);
const auto f4 = c_mul_neon(float32x2_t{ -kW7_4, kW7_5 }, f);
const auto f5 = c_mul_neon(float32x2_t{ -kW7_2, -kW7_3 }, f);
const auto g0 = c_mul_neon(float32x2_t{ kW7_0, kW7_1 }, g);
const auto g1 = c_mul_neon(float32x2_t{ -kW7_2, kW7_3 }, g);
const auto g2 = c_mul_neon(float32x2_t{ -kW7_4, kW7_5 }, g);
const auto g3 = c_mul_neon(float32x2_t{ -kW7_4, -kW7_5 }, g);
const auto g4 = c_mul_neon(float32x2_t{ -kW7_2, -kW7_3 }, g);
const auto g5 = c_mul_neon(float32x2_t{ kW7_0, -kW7_1 }, g);
x1 = reduce_sum_7(a, b, c, d, e, f, g);
x2 = reduce_sum_7(a, b0, c0, d0, e0, f0, g0);
x3 = reduce_sum_7(a, b1, c1, d1, e1, f1, g1);
x4 = reduce_sum_7(a, b2, c2, d2, e2, f2, g2);
x5 = reduce_sum_7(a, b3, c3, d3, e3, f3, g3);
x6 = reduce_sum_7(a, b4, c4, d4, e4, f4, g4);
x7 = reduce_sum_7(a, b5, c5, d5, e5, f5, g5);
}
void fft_8(float32x2_t &x1, float32x2_t &x2, float32x2_t &x3, float32x2_t &x4, float32x2_t &x5, float32x2_t &x6, float32x2_t &x7, float32x2_t &x8, const float32x2_t &w, const float32x2_t &w2,
const float32x2_t &w3,
const float32x2_t &w4, const float32x2_t &w5, const float32x2_t &w6,
const float32x2_t &w7)
{
const auto a = x1;
const auto b = c_mul_neon(w, x2);
const auto c = c_mul_neon(w2, x3);
const auto d = c_mul_neon(w3, x4);
const auto e = c_mul_neon(w4, x5);
const auto f = c_mul_neon(w5, x6);
const auto g = c_mul_neon(w6, x7);
const auto h = c_mul_neon(w7, x8);
const auto b0 = c_mul_neon(float32x2_t{ kSqrt2Div2, -kSqrt2Div2 }, b);
const auto b1 = c_mul_neon(float32x2_t{ 0, -1 }, b);
const auto b2 = c_mul_neon(float32x2_t{ -kSqrt2Div2, -kSqrt2Div2 }, b);
const auto b3 = c_mul_neon(float32x2_t{ -1, 0 }, b);
const auto b4 = c_mul_neon(float32x2_t{ -kSqrt2Div2, kSqrt2Div2 }, b);
const auto b5 = c_mul_neon(float32x2_t{ 0, 1 }, b);
const auto b6 = c_mul_neon(float32x2_t{ kSqrt2Div2, kSqrt2Div2 }, b);
const auto c0 = c_mul_neon(float32x2_t{ 0, -1 }, c);
const auto c1 = c_mul_neon(float32x2_t{ -1, 0 }, c);
const auto c2 = c_mul_neon(float32x2_t{ 0, 1 }, c);
const auto c3 = c_mul_neon(float32x2_t{ 1, 0 }, c);
const auto c4 = c_mul_neon(float32x2_t{ 0, -1 }, c);
const auto c5 = c_mul_neon(float32x2_t{ -1, 0 }, c);
const auto c6 = c_mul_neon(float32x2_t{ 0, 1 }, c);
const auto d0 = c_mul_neon(float32x2_t{ -kSqrt2Div2, -kSqrt2Div2 }, d);
const auto d1 = c_mul_neon(float32x2_t{ 0, 1 }, d);
const auto d2 = c_mul_neon(float32x2_t{ kSqrt2Div2, -kSqrt2Div2 }, d);
const auto d3 = c_mul_neon(float32x2_t{ -1, 0 }, d);
const auto d4 = c_mul_neon(float32x2_t{ kSqrt2Div2, kSqrt2Div2 }, d);
const auto d5 = c_mul_neon(float32x2_t{ 0, -1 }, d);
const auto d6 = c_mul_neon(float32x2_t{ -kSqrt2Div2, kSqrt2Div2 }, d);
const auto e0 = c_mul_neon(float32x2_t{ -1, 0 }, e);
const auto e1 = c_mul_neon(float32x2_t{ 1, 0 }, e);
const auto e2 = c_mul_neon(float32x2_t{ -1, 0 }, e);
const auto e3 = c_mul_neon(float32x2_t{ 1, 0 }, e);
const auto e4 = c_mul_neon(float32x2_t{ -1, 0 }, e);
const auto e5 = c_mul_neon(float32x2_t{ 1, 0 }, e);
const auto e6 = c_mul_neon(float32x2_t{ -1, 0 }, e);
const auto f0 = c_mul_neon(float32x2_t{ -kSqrt2Div2, kSqrt2Div2 }, f);
const auto f1 = c_mul_neon(float32x2_t{ 0, -1 }, f);
const auto f2 = c_mul_neon(float32x2_t{ kSqrt2Div2, kSqrt2Div2 }, f);
const auto f3 = c_mul_neon(float32x2_t{ -1, 0 }, f);
const auto f4 = c_mul_neon(float32x2_t{ kSqrt2Div2, -kSqrt2Div2 }, f);
const auto f5 = c_mul_neon(float32x2_t{ 0, 1 }, f);
const auto f6 = c_mul_neon(float32x2_t{ -kSqrt2Div2, -kSqrt2Div2 }, f);
const auto g0 = c_mul_neon(float32x2_t{ 0, 1 }, g);
const auto g1 = c_mul_neon(float32x2_t{ -1, 0 }, g);
const auto g2 = c_mul_neon(float32x2_t{ 0, -1 }, g);
const auto g3 = c_mul_neon(float32x2_t{ 1, 0 }, g);
const auto g4 = c_mul_neon(float32x2_t{ 0, 1 }, g);
const auto g5 = c_mul_neon(float32x2_t{ -1, 0 }, g);
const auto g6 = c_mul_neon(float32x2_t{ 0, -1 }, g);
const auto h0 = c_mul_neon(float32x2_t{ kSqrt2Div2, kSqrt2Div2 }, h);
const auto h1 = c_mul_neon(float32x2_t{ 0, 1 }, h);
const auto h2 = c_mul_neon(float32x2_t{ -kSqrt2Div2, kSqrt2Div2 }, h);
const auto h3 = c_mul_neon(float32x2_t{ -1, 0 }, h);
const auto h4 = c_mul_neon(float32x2_t{ -kSqrt2Div2, -kSqrt2Div2 }, h);
const auto h5 = c_mul_neon(float32x2_t{ 0, -1 }, h);
const auto h6 = c_mul_neon(float32x2_t{ kSqrt2Div2, -kSqrt2Div2 }, h);
x1 = reduce_sum_8(a, b, c, d, e, f, g, h);
x2 = reduce_sum_8(a, b0, c0, d0, e0, f0, g0, h0);
x3 = reduce_sum_8(a, b1, c1, d1, e1, f1, g1, h1);
x4 = reduce_sum_8(a, b2, c2, d2, e2, f2, g2, h2);
x5 = reduce_sum_8(a, b3, c3, d3, e3, f3, g3, h3);
x6 = reduce_sum_8(a, b4, c4, d4, e4, f4, g4, h4);
x7 = reduce_sum_8(a, b5, c5, d5, e5, f5, g5, h5);
x8 = reduce_sum_8(a, b6, c6, d6, e6, f6, g6, h6);
}
template <bool first_stage>
void fft_radix_2_axes_0(float *out, float *in, unsigned int Nx, unsigned int NxRadix, const float32x2_t &w_m, unsigned int N)
{
float32x2_t w{ 1.0f, 0.0f };
for(unsigned int j = 0; j < Nx; j++)
{
for(unsigned int k = 2 * j; k < 2 * N; k += 2 * NxRadix)
{
auto a = float32x2_t{ 0, 0 };
auto b = float32x2_t{ 0, 0 };
// Load inputs
if(first_stage)
{
const auto ab = wrapper::vloadq(in + k);
a = wrapper::vgetlow(ab);
b = wrapper::vgethigh(ab);
}
else
{
a = wrapper::vload(in + k);
b = wrapper::vload(in + k + 2 * Nx);
}
// Base-case prime transform
fft_2(a, b, w);
// Write outputs
if(first_stage)
{
wrapper::vstore(out + k, wrapper::vcombine(a, b));
}
else
{
wrapper::vstore(out + k, a);
wrapper::vstore(out + k + 2 * Nx, b);
}
}
w = c_mul_neon(w, w_m);
}
}
void fft_radix_2_axes_1(float *out, float *in, unsigned int Nx, unsigned int NxRadix, const float32x2_t &w_m, unsigned int N, unsigned int M, unsigned int in_pad_x, unsigned int out_pad_x)
{
float32x2_t w{ 1.0f, 0.0f };
for(unsigned int j = 0; j < Nx; j++)
{
for(unsigned int k = 2 * j; k < 2 * M; k += 2 * NxRadix)
{
// Load inputs
float32x2_t a = wrapper::vload(in + (N + in_pad_x) * k);
float32x2_t b = wrapper::vload(in + (N + in_pad_x) * (k + 2 * Nx));
// Base-case prime transform
fft_2(a, b, w);
// Write outputs
wrapper::vstore(out + (N + out_pad_x) * k, a);
wrapper::vstore(out + (N + out_pad_x) * (k + 2 * Nx), b);
}
w = c_mul_neon(w, w_m);
}
}
template <bool first_stage>
void fft_radix_3_axes_0(float *out, float *in, unsigned int Nx, unsigned int NxRadix, const float32x2_t &w_m, unsigned int N)
{
float32x2_t w{ 1.0f, 0.0f };
for(unsigned int j = 0; j < Nx; j++)
{
const auto w2 = c_mul_neon(w, w);
for(unsigned int k = 2 * j; k < 2 * N; k += 2 * NxRadix)
{
// Load inputs
float32x2_t a = { 0, 0 };
float32x2_t b = { 0, 0 };
float32x2_t c = { 0, 0 };
if(first_stage)
{
const auto ab = wrapper::vloadq(in + k);
a = wrapper::vgetlow(ab);
b = wrapper::vgethigh(ab);
}
else
{
a = wrapper::vload(in + k);
b = wrapper::vload(in + k + 2 * Nx);
}
c = wrapper::vload(in + k + 4 * Nx);
// Base-case prime transform
fft_3(a, b, c, w, w2);
if(first_stage)
{
wrapper::vstore(out + k, wrapper::vcombine(a, b));
}
else
{
wrapper::vstore(out + k, a);
wrapper::vstore(out + k + 2 * Nx, b);
}
wrapper::vstore(out + k + 4 * Nx, c);
}
w = c_mul_neon(w, w_m);
}
}
void fft_radix_3_axes_1(float *out, float *in, unsigned int Nx, unsigned int NxRadix, const float32x2_t &w_m, unsigned int N, unsigned int M, unsigned int in_pad_x, unsigned int out_pad_x)
{
float32x2_t w{ 1.0f, 0.0f };
for(unsigned int j = 0; j < Nx; j++)
{
const auto w2 = c_mul_neon(w, w);
for(unsigned int k = 2 * j; k < 2 * M; k += 2 * NxRadix)
{
// Load inputs
float32x2_t a = wrapper::vload(in + (N + in_pad_x) * k);
float32x2_t b = wrapper::vload(in + (N + in_pad_x) * (k + 2 * Nx));
float32x2_t c = wrapper::vload(in + (N + in_pad_x) * (k + 4 * Nx));
// Base-case prime transform
fft_3(a, b, c, w, w2);
// Store the output
wrapper::vstore(out + (N + out_pad_x) * k, a);
wrapper::vstore(out + (N + out_pad_x) * (k + 2 * Nx), b);
wrapper::vstore(out + (N + out_pad_x) * (k + 4 * Nx), c);
}
w = c_mul_neon(w, w_m);
}
}
template <bool first_stage>
void fft_radix_4_axes_0(float *out, float *in, unsigned int Nx, unsigned int NxRadix, const float32x2_t &w_m, unsigned int N)
{
float32x2_t w{ 1.0f, 0.0f };
for(unsigned int j = 0; j < Nx; j++)
{
const auto w2 = c_mul_neon(w, w);
const auto w3 = c_mul_neon(w2, w);
for(unsigned int k = 2 * j; k < 2 * N; k += 2 * NxRadix)
{
float32x2_t a = { 0, 0 };
float32x2_t b = { 0, 0 };
float32x2_t c = { 0, 0 };
float32x2_t d = { 0, 0 };
if(first_stage)
{
const auto ab = wrapper::vloadq(in + k);
const auto cd = wrapper::vloadq(in + k + 4 * Nx);
a = wrapper::vgetlow(ab);
b = wrapper::vgethigh(ab);
c = wrapper::vgetlow(cd);
d = wrapper::vgethigh(cd);
}
else
{
// Load inputs
a = wrapper::vload(in + k);
b = wrapper::vload(in + k + 2 * Nx);
c = wrapper::vload(in + k + 4 * Nx);
d = wrapper::vload(in + k + 6 * Nx);
}
// Base-case prime transform
fft_4(a, b, c, d, w, w2, w3);
if(first_stage)
{
wrapper::vstore(out + k, wrapper::vcombine(a, b));
wrapper::vstore(out + k + 4 * Nx, wrapper::vcombine(c, d));
}
else
{
wrapper::vstore(out + k, a);
wrapper::vstore(out + k + 2 * Nx, b);
wrapper::vstore(out + k + 4 * Nx, c);
wrapper::vstore(out + k + 6 * Nx, d);
}
}
w = c_mul_neon(w, w_m);
}
}
void fft_radix_4_axes_1(float *out, float *in, unsigned int Nx, unsigned int NxRadix, const float32x2_t &w_m, unsigned int N, unsigned int M, unsigned int in_pad_x, unsigned int out_pad_x)
{
float32x2_t w{ 1.0f, 0.0f };
for(unsigned int j = 0; j < Nx; j++)
{
const auto w2 = c_mul_neon(w, w);
const auto w3 = c_mul_neon(w2, w);
for(unsigned int k = 2 * j; k < 2 * M; k += 2 * NxRadix)
{
// Load inputs
float32x2_t a = wrapper::vload(in + (N + in_pad_x) * k);
float32x2_t b = wrapper::vload(in + (N + in_pad_x) * (k + 2 * Nx));
float32x2_t c = wrapper::vload(in + (N + in_pad_x) * (k + 4 * Nx));
float32x2_t d = wrapper::vload(in + (N + in_pad_x) * (k + 6 * Nx));
// Base-case prime transform
fft_4(a, b, c, d, w, w2, w3);
wrapper::vstore(out + (N + out_pad_x) * k, a);
wrapper::vstore(out + (N + out_pad_x) * (k + 2 * Nx), b);
wrapper::vstore(out + (N + out_pad_x) * (k + 4 * Nx), c);
wrapper::vstore(out + (N + out_pad_x) * (k + 6 * Nx), d);
}
w = c_mul_neon(w, w_m);
}
}
template <bool first_stage>
void fft_radix_5_axes_0(float *out, float *in, unsigned int Nx, unsigned int NxRadix, const float32x2_t &w_m, unsigned int N)
{
float32x2_t w{ 1.0f, 0.0f };
for(unsigned int j = 0; j < Nx; j++)
{
const float32x2_t w2 = c_mul_neon(w, w);
const float32x2_t w3 = c_mul_neon(w2, w);
const float32x2_t w4 = c_mul_neon(w3, w);
for(unsigned int k = 2 * j; k < 2 * N; k += 2 * NxRadix)
{
float32x2_t a = { 0, 0 };
float32x2_t b = { 0, 0 };
float32x2_t c = { 0, 0 };
float32x2_t d = { 0, 0 };
float32x2_t e = { 0, 0 };
// Load inputs
if(first_stage)
{
const auto ab = wrapper::vloadq(in + k);
const auto cd = wrapper::vloadq(in + k + 4 * Nx);
a = wrapper::vgetlow(ab);
b = wrapper::vgethigh(ab);
c = wrapper::vgetlow(cd);
d = wrapper::vgethigh(cd);
}
else
{
a = wrapper::vload(in + k);
b = wrapper::vload(in + k + 2 * Nx);
c = wrapper::vload(in + k + 4 * Nx);
d = wrapper::vload(in + k + 6 * Nx);
}
e = wrapper::vload(in + k + 8 * Nx);
// Base-case prime transform
fft_5(a, b, c, d, e, w, w2, w3, w4);
// Store outputs
if(first_stage)
{
wrapper::vstore(out + k, wrapper::vcombine(a, b));
wrapper::vstore(out + k + 4 * Nx, wrapper::vcombine(c, d));
}
else
{
wrapper::vstore(out + k, a);
wrapper::vstore(out + k + 2 * Nx, b);
wrapper::vstore(out + k + 4 * Nx, c);
wrapper::vstore(out + k + 6 * Nx, d);
}
wrapper::vstore(out + k + 8 * Nx, e);
}
w = c_mul_neon(w, w_m);
}
}
void fft_radix_5_axes_1(float *out, float *in, unsigned int Nx, unsigned int NxRadix, const float32x2_t &w_m, unsigned int N, unsigned int M, unsigned int in_pad_x, unsigned int out_pad_x)
{
float32x2_t w{ 1.0f, 0.0f };
for(unsigned int j = 0; j < Nx; j++)
{
const float32x2_t w2 = c_mul_neon(w, w);
const float32x2_t w3 = c_mul_neon(w2, w);
const float32x2_t w4 = c_mul_neon(w3, w);
for(unsigned int k = 2 * j; k < 2 * M; k += 2 * NxRadix)
{
// Load inputs
float32x2_t a = wrapper::vload(in + (N + in_pad_x) * k);
float32x2_t b = wrapper::vload(in + (N + in_pad_x) * (k + 2 * Nx));
float32x2_t c = wrapper::vload(in + (N + in_pad_x) * (k + 4 * Nx));
float32x2_t d = wrapper::vload(in + (N + in_pad_x) * (k + 6 * Nx));
float32x2_t e = wrapper::vload(in + (N + in_pad_x) * (k + 8 * Nx));
// Base-case prime transform
fft_5(a, b, c, d, e, w, w2, w3, w4);
// Store outputs
wrapper::vstore(out + (N + out_pad_x) * k, a);
wrapper::vstore(out + (N + out_pad_x) * (k + 2 * Nx), b);
wrapper::vstore(out + (N + out_pad_x) * (k + 4 * Nx), c);
wrapper::vstore(out + (N + out_pad_x) * (k + 6 * Nx), d);
wrapper::vstore(out + (N + out_pad_x) * (k + 8 * Nx), e);
}
w = c_mul_neon(w, w_m);
}
}
template <bool first_stage>
void fft_radix_7_axes_0(float *out, float *in, unsigned int Nx, unsigned int NxRadix, const float32x2_t &w_m, unsigned int N)
{
float32x2_t w{ 1.0f, 0.0f };
for(unsigned int j = 0; j < Nx; j++)
{
const float32x2_t w2 = c_mul_neon(w, w);
const float32x2_t w3 = c_mul_neon(w2, w);
const float32x2_t w4 = c_mul_neon(w3, w);
const float32x2_t w5 = c_mul_neon(w4, w);
const float32x2_t w6 = c_mul_neon(w5, w);
for(unsigned int k = 2 * j; k < 2 * N; k += 2 * NxRadix)
{
float32x2_t a = { 0, 0 };
float32x2_t b = { 0, 0 };
float32x2_t c = { 0, 0 };
float32x2_t d = { 0, 0 };
float32x2_t e = { 0, 0 };
float32x2_t f = { 0, 0 };
float32x2_t g = { 0, 0 };
// Load inputs
if(first_stage)
{
const auto ab = wrapper::vloadq(in + k);
const auto cd = wrapper::vloadq(in + k + 4 * Nx);
const auto ef = wrapper::vloadq(in + k + 8 * Nx);
a = wrapper::vgetlow(ab);
b = wrapper::vgethigh(ab);
c = wrapper::vgetlow(cd);
d = wrapper::vgethigh(cd);
e = wrapper::vgetlow(ef);
f = wrapper::vgethigh(ef);
}
else
{
a = wrapper::vload(in + k);
b = wrapper::vload(in + k + 2 * Nx);
c = wrapper::vload(in + k + 4 * Nx);
d = wrapper::vload(in + k + 6 * Nx);
e = wrapper::vload(in + k + 8 * Nx);
f = wrapper::vload(in + k + 10 * Nx);
}
g = wrapper::vload(in + k + 12 * Nx);
// Base-case prime transform
fft_7(a, b, c, d, e, f, g, w, w2, w3, w4, w5, w6);
if(first_stage)
{
wrapper::vstore(out + k, wrapper::vcombine(a, b));
wrapper::vstore(out + k + 4 * Nx, wrapper::vcombine(c, d));
wrapper::vstore(out + k + 8 * Nx, wrapper::vcombine(e, f));
}
else
{
wrapper::vstore(out + k, a);
wrapper::vstore(out + k + 2 * Nx, b);
wrapper::vstore(out + k + 4 * Nx, c);
wrapper::vstore(out + k + 6 * Nx, d);
wrapper::vstore(out + k + 8 * Nx, e);
wrapper::vstore(out + k + 10 * Nx, f);
}
wrapper::vstore(out + k + 12 * Nx, g);
}
w = c_mul_neon(w, w_m);
}
}
void fft_radix_7_axes_1(float *out, float *in, unsigned int Nx, unsigned int NxRadix, const float32x2_t &w_m, unsigned int N, unsigned int M, unsigned int in_pad_x, unsigned int out_pad_x)
{
float32x2_t w{ 1.0f, 0.0f };
for(unsigned int j = 0; j < Nx; j++)
{
const float32x2_t w2 = c_mul_neon(w, w);
const float32x2_t w3 = c_mul_neon(w2, w);
const float32x2_t w4 = c_mul_neon(w3, w);
const float32x2_t w5 = c_mul_neon(w4, w);
const float32x2_t w6 = c_mul_neon(w5, w);
for(unsigned int k = 2 * j; k < 2 * M; k += 2 * NxRadix)
{
// Load inputs
float32x2_t a = wrapper::vload(in + (N + in_pad_x) * k);
float32x2_t b = wrapper::vload(in + (N + in_pad_x) * (k + 2 * Nx));
float32x2_t c = wrapper::vload(in + (N + in_pad_x) * (k + 4 * Nx));
float32x2_t d = wrapper::vload(in + (N + in_pad_x) * (k + 6 * Nx));
float32x2_t e = wrapper::vload(in + (N + in_pad_x) * (k + 8 * Nx));
float32x2_t f = wrapper::vload(in + (N + in_pad_x) * (k + 10 * Nx));
float32x2_t g = wrapper::vload(in + (N + in_pad_x) * (k + 12 * Nx));
// Base-case prime transform
fft_7(a, b, c, d, e, f, g, w, w2, w3, w4, w5, w6);
// Store outputs
wrapper::vstore(out + (N + out_pad_x) * k, a);
wrapper::vstore(out + (N + out_pad_x) * (k + 2 * Nx), b);
wrapper::vstore(out + (N + out_pad_x) * (k + 4 * Nx), c);
wrapper::vstore(out + (N + out_pad_x) * (k + 6 * Nx), d);
wrapper::vstore(out + (N + out_pad_x) * (k + 8 * Nx), e);
wrapper::vstore(out + (N + out_pad_x) * (k + 10 * Nx), f);
wrapper::vstore(out + (N + out_pad_x) * (k + 12 * Nx), g);
}
w = c_mul_neon(w, w_m);
}
}
template <bool first_stage>
void fft_radix_8_axes_0(float *out, float *in, unsigned int Nx, unsigned int NxRadix, const float32x2_t &w_m, unsigned int N)
{
float32x2_t w{ 1.0f, 0.0f };
for(unsigned int j = 0; j < Nx; j++)
{
const float32x2_t w2 = c_mul_neon(w, w);
const float32x2_t w3 = c_mul_neon(w2, w);
const float32x2_t w4 = c_mul_neon(w3, w);
const float32x2_t w5 = c_mul_neon(w4, w);
const float32x2_t w6 = c_mul_neon(w5, w);
const float32x2_t w7 = c_mul_neon(w6, w);
for(unsigned int k = 2 * j; k < 2 * N; k += 2 * NxRadix)
{
// Load inputs
float32x2_t a = { 0, 0 };
float32x2_t b = { 0, 0 };
float32x2_t c = { 0, 0 };
float32x2_t d = { 0, 0 };
float32x2_t e = { 0, 0 };
float32x2_t f = { 0, 0 };
float32x2_t g = { 0, 0 };
float32x2_t h = { 0, 0 };
// Base-case prime transform
if(first_stage)
{
const auto ab = wrapper::vloadq(in + k);
const auto cd = wrapper::vloadq(in + k + 4 * Nx);
const auto ef = wrapper::vloadq(in + k + 8 * Nx);
const auto gh = wrapper::vloadq(in + k + 12 * Nx);
a = wrapper::vgetlow(ab);
b = wrapper::vgethigh(ab);
c = wrapper::vgetlow(cd);
d = wrapper::vgethigh(cd);
e = wrapper::vgetlow(ef);
f = wrapper::vgethigh(ef);
g = wrapper::vgetlow(gh);
h = wrapper::vgethigh(gh);
}
else
{
a = wrapper::vload(in + k);
b = wrapper::vload(in + k + 2 * Nx);
c = wrapper::vload(in + k + 4 * Nx);
d = wrapper::vload(in + k + 6 * Nx);
e = wrapper::vload(in + k + 8 * Nx);
f = wrapper::vload(in + k + 10 * Nx);
g = wrapper::vload(in + k + 12 * Nx);
h = wrapper::vload(in + k + 14 * Nx);
}
// Apply twiddle factors
fft_8(a, b, c, d, e, f, g, h, w, w2, w3, w4, w5, w6, w7);
// Store outputs
if(first_stage)
{
wrapper::vstore(out + k, wrapper::vcombine(a, b));
wrapper::vstore(out + k + 4 * Nx, wrapper::vcombine(c, d));
wrapper::vstore(out + k + 8 * Nx, wrapper::vcombine(e, f));
wrapper::vstore(out + k + 12 * Nx, wrapper::vcombine(g, h));
}
else
{
wrapper::vstore(out + k, a);
wrapper::vstore(out + k + 2 * Nx, b);
wrapper::vstore(out + k + 4 * Nx, c);
wrapper::vstore(out + k + 6 * Nx, d);
wrapper::vstore(out + k + 8 * Nx, e);
wrapper::vstore(out + k + 10 * Nx, f);
wrapper::vstore(out + k + 12 * Nx, g);
wrapper::vstore(out + k + 14 * Nx, h);
}
}
w = c_mul_neon(w, w_m);
}
}
void fft_radix_8_axes_1(float *out, float *in, unsigned int Nx, unsigned int NxRadix, const float32x2_t &w_m, unsigned int N, unsigned int M, unsigned int in_pad_x, unsigned int out_pad_x)
{
float32x2_t w{ 1.0f, 0.0f };
for(unsigned int j = 0; j < Nx; j++)
{
const float32x2_t w2 = c_mul_neon(w, w);
const float32x2_t w3 = c_mul_neon(w2, w);
const float32x2_t w4 = c_mul_neon(w3, w);
const float32x2_t w5 = c_mul_neon(w4, w);
const float32x2_t w6 = c_mul_neon(w5, w);
const float32x2_t w7 = c_mul_neon(w6, w);
for(unsigned int k = 2 * j; k < 2 * M; k += 2 * NxRadix)
{
// Load inputs
float32x2_t a = wrapper::vload(in + (N + in_pad_x) * k);
float32x2_t b = wrapper::vload(in + (N + in_pad_x) * (k + 2 * Nx));
float32x2_t c = wrapper::vload(in + (N + in_pad_x) * (k + 4 * Nx));
float32x2_t d = wrapper::vload(in + (N + in_pad_x) * (k + 6 * Nx));
float32x2_t e = wrapper::vload(in + (N + in_pad_x) * (k + 8 * Nx));
float32x2_t f = wrapper::vload(in + (N + in_pad_x) * (k + 10 * Nx));
float32x2_t g = wrapper::vload(in + (N + in_pad_x) * (k + 12 * Nx));
float32x2_t h = wrapper::vload(in + (N + in_pad_x) * (k + 14 * Nx));
// Base-case prime transform
fft_8(a, b, c, d, e, f, g, h, w, w2, w3, w4, w5, w6, w7);
// Store outputs
wrapper::vstore(out + (N + out_pad_x) * k, a);
wrapper::vstore(out + (N + out_pad_x) * (k + 2 * Nx), b);
wrapper::vstore(out + (N + out_pad_x) * (k + 4 * Nx), c);
wrapper::vstore(out + (N + out_pad_x) * (k + 6 * Nx), d);
wrapper::vstore(out + (N + out_pad_x) * (k + 8 * Nx), e);
wrapper::vstore(out + (N + out_pad_x) * (k + 10 * Nx), f);
wrapper::vstore(out + (N + out_pad_x) * (k + 12 * Nx), g);
wrapper::vstore(out + (N + out_pad_x) * (k + 14 * Nx), h);
}
w = c_mul_neon(w, w_m);
}
}
Status validate_arguments(const ITensorInfo *input, const ITensorInfo *output, const FFTRadixStageKernelInfo &config)
{
ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(input, 2, DataType::F32);
ARM_COMPUTE_RETURN_ERROR_ON(config.axis > 1);
ARM_COMPUTE_RETURN_ERROR_ON(NEFFTRadixStageKernel::supported_radix().count(config.radix) == 0);
ARM_COMPUTE_UNUSED(config);
// Checks performed when output is configured
if((output != nullptr) && (output->total_size() != 0))
{
ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_SHAPES(input, output);
ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(input, output);
}
return Status{};
}
std::pair<Status, Window> validate_and_configure_window(ITensorInfo *input, ITensorInfo *output, const FFTRadixStageKernelInfo &config)
{
ARM_COMPUTE_UNUSED(config);
if(output != nullptr)
{
auto_init_if_empty(*output, *input);
}
Window win = calculate_max_window(*input, Steps());
return std::make_pair(Status{}, win);
}
} // namespace
NEFFTRadixStageKernel::NEFFTRadixStageKernel()
: _input(nullptr), _output(nullptr), _Nx(0), _axis(0), _radix(0), _func_0(), _func_1()
{
}
void NEFFTRadixStageKernel::set_radix_stage_axis0(const FFTRadixStageKernelInfo &config)
{
// FFT table axis 0: [radix, first_stage]
static std::map<unsigned int, std::map<bool, FFTFunctionPointerAxis0>> fft_table_axis0;
if(fft_table_axis0.empty())
{
fft_table_axis0[2][false] = &fft_radix_2_axes_0<false>;
fft_table_axis0[3][false] = &fft_radix_3_axes_0<false>;
fft_table_axis0[4][false] = &fft_radix_4_axes_0<false>;
fft_table_axis0[5][false] = &fft_radix_5_axes_0<false>;
fft_table_axis0[7][false] = &fft_radix_7_axes_0<false>;
fft_table_axis0[8][false] = &fft_radix_8_axes_0<false>;
fft_table_axis0[2][true] = &fft_radix_2_axes_0<true>;
fft_table_axis0[3][true] = &fft_radix_3_axes_0<true>;
fft_table_axis0[4][true] = &fft_radix_4_axes_0<true>;
fft_table_axis0[5][true] = &fft_radix_5_axes_0<true>;
fft_table_axis0[7][true] = &fft_radix_7_axes_0<true>;
fft_table_axis0[8][true] = &fft_radix_8_axes_0<true>;
}
_func_0 = fft_table_axis0[config.radix][config.is_first_stage];
}
void NEFFTRadixStageKernel::set_radix_stage_axis1(const FFTRadixStageKernelInfo &config)
{
// FFT table axis 1: [radix, first_stage]
static std::map<unsigned int, FFTFunctionPointerAxis1> fft_table_axis1;
if(fft_table_axis1.empty())
{
fft_table_axis1[2] = &fft_radix_2_axes_1;
fft_table_axis1[3] = &fft_radix_3_axes_1;
fft_table_axis1[4] = &fft_radix_4_axes_1;
fft_table_axis1[5] = &fft_radix_5_axes_1;
fft_table_axis1[7] = &fft_radix_7_axes_1;
fft_table_axis1[8] = &fft_radix_8_axes_1;
}
_func_1 = fft_table_axis1[config.radix];
}
void NEFFTRadixStageKernel::configure(ITensor *input, ITensor *output, const FFTRadixStageKernelInfo &config)
{
ARM_COMPUTE_ERROR_ON_NULLPTR(input);
// Output auto inizialitation if not yet initialized
if(output != nullptr)
{
auto_init_if_empty(*output->info(), *input->info()->clone());
}
ARM_COMPUTE_ERROR_THROW_ON(validate_arguments(input->info(), (output != nullptr) ? output->info() : nullptr, config));
_input = input;
_output = (output == nullptr) ? input : output;
_Nx = config.Nx;
_axis = config.axis;
_radix = config.radix;
switch(config.axis)
{
case 0:
set_radix_stage_axis0(config);
break;
case 1:
set_radix_stage_axis1(config);
break;
default:
ARM_COMPUTE_ERROR("Axis not supported");
break;
}
// Configure kernel window
auto win_config = validate_and_configure_window(input->info(), (output != nullptr) ? output->info() : nullptr, config);
ARM_COMPUTE_ERROR_THROW_ON(win_config.first);
INEKernel::configure(win_config.second);
}
Status NEFFTRadixStageKernel::validate(const ITensorInfo *input, const ITensorInfo *output, const FFTRadixStageKernelInfo &config)
{
const bool run_in_place = (output == nullptr) || (output == input);
ARM_COMPUTE_RETURN_ON_ERROR(validate_arguments(input, output, config));
ARM_COMPUTE_RETURN_ON_ERROR(validate_and_configure_window(input->clone().get(),
(run_in_place) ? nullptr : output->clone().get(),
config)
.first);
return Status{};
}
std::set<unsigned int> NEFFTRadixStageKernel::supported_radix()
{
return std::set<unsigned int> { 2, 3, 4, 5, 7, 8 };
}
void NEFFTRadixStageKernel::run(const Window &window, const ThreadInfo &info)
{
ARM_COMPUTE_ERROR_ON_UNCONFIGURED_KERNEL(this);
ARM_COMPUTE_ERROR_ON_INVALID_SUBWINDOW(INEKernel::window(), window);
ARM_COMPUTE_UNUSED(info);
Window input_window = window;
input_window.set(_axis, 0);
Iterator in(_input, input_window);
Iterator out(_output, input_window);
// Precompute FFT constants
const unsigned int NxRadix = _radix * _Nx;
const float alpha = 2.0f * kPi / float(NxRadix);
const float32x2_t w_m{ cosf(alpha), -sinf(alpha) };
if(_axis == 0)
{
const unsigned int N = _input->info()->dimension(0);
execute_window_loop(input_window, [&](const Coordinates &)
{
_func_0(reinterpret_cast<float *>(out.ptr()), reinterpret_cast<float *>(in.ptr()), _Nx, NxRadix, w_m, N);
},
in, out);
}
else
{
const unsigned int N = _input->info()->dimension(0);
const unsigned int M = _input->info()->dimension(1);
execute_window_loop(input_window, [&](const Coordinates &)
{
_func_1(reinterpret_cast<float *>(out.ptr()), reinterpret_cast<float *>(in.ptr()), _Nx, NxRadix, w_m, N, M,
_input->info()->padding().right + _input->info()->padding().left,
_output->info()->padding().right + _output->info()->padding().left);
},
in, out);
}
ARM_COMPUTE_ERROR_ON_UNCONFIGURED_KERNEL(this);
ARM_COMPUTE_ERROR_ON_INVALID_SUBWINDOW(INEKernel::window(), window);
}
} // namespace arm_compute
| 38.761111
| 197
| 0.563877
|
wql15
|
44cec18bafefb76b4fee8356792c761ff7605922
| 14,594
|
cpp
|
C++
|
tests/helics/core/TcpSSCore-tests.cpp
|
manoj1511/HELICS
|
5b085bb4331f943d3fa98eb40056c3e10a1b882d
|
[
"BSD-3-Clause"
] | null | null | null |
tests/helics/core/TcpSSCore-tests.cpp
|
manoj1511/HELICS
|
5b085bb4331f943d3fa98eb40056c3e10a1b882d
|
[
"BSD-3-Clause"
] | null | null | null |
tests/helics/core/TcpSSCore-tests.cpp
|
manoj1511/HELICS
|
5b085bb4331f943d3fa98eb40056c3e10a1b882d
|
[
"BSD-3-Clause"
] | null | null | null |
/*
Copyright (c) 2017-2019,
Battelle Memorial Institute; Lawrence Livermore National Security, LLC; Alliance for Sustainable Energy, LLC. See
the top-level NOTICE for additional details. All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
*/
#include "gtest/gtest.h"
#include "helics/common/AsioContextManager.h"
#include "helics/common/GuardedTypes.hpp"
#include "helics/core/ActionMessage.hpp"
#include "helics/core/BrokerFactory.hpp"
#include "helics/core/Core.hpp"
#include "helics/core/CoreFactory.hpp"
#include "helics/core/core-types.hpp"
#include "helics/core/networkDefaults.hpp"
#include "helics/core/tcp/TcpBroker.h"
#include "helics/core/tcp/TcpCommsSS.h"
#include "helics/core/tcp/TcpCore.h"
#include "helics/core/tcp/TcpHelperClasses.h"
#include <numeric>
#include <future>
using namespace std::literals::chrono_literals;
using asio::ip::tcp;
using helics::Core;
#define TCP_BROKER_PORT_STRING "33133"
#define TCP_BROKER_PORT_ALT 33134
#define TCP_BROKER_PORT_ALT_STRING "33134"
TEST (TcpSSCore_tests, tcpSSComms_broker_test)
{
std::atomic<int> counter{0};
std::string host = "localhost";
helics::tcp::TcpCommsSS comm;
comm.loadTargetInfo (host, host);
auto srv = AsioContextManager::getContextPointer ();
auto server = helics::tcp::TcpServer::create (srv->getBaseContext (), DEFAULT_TCPSS_PORT);
auto contextLoop = srv->startContextLoop ();
std::vector<char> data (1024);
server->setDataCall ([&counter] (helics::tcp::TcpConnection::pointer, const char *, size_t data_avail) {
++counter;
return data_avail;
});
server->start ();
comm.setCallback ([&counter] (helics::ActionMessage /*m*/) { ++counter; });
comm.setBrokerPort (DEFAULT_TCPSS_PORT);
comm.setName ("tests");
comm.setTimeout (1000ms);
comm.setServerMode (false);
auto confut = std::async (std::launch::async, [&comm] () { return comm.connect (); });
std::this_thread::sleep_for (100ms);
int cnt = 0;
while (counter < 1)
{
std::this_thread::sleep_for (100ms);
++cnt;
if (cnt > 30)
{
break;
}
}
EXPECT_EQ (counter, 1);
server->close ();
comm.disconnect ();
std::this_thread::sleep_for (100ms);
}
TEST (TcpSSCore_tests, tcpSSComms_broker_test_transmit)
{
std::this_thread::sleep_for (400ms);
std::atomic<int> counter{0};
std::atomic<size_t> len{0};
std::string host = "localhost";
helics::tcp::TcpCommsSS comm;
comm.loadTargetInfo (host, host);
auto srv = AsioContextManager::getContextPointer ();
auto contextLoop = srv->startContextLoop ();
auto server = helics::tcp::TcpServer::create (srv->getBaseContext (), host, DEFAULT_TCPSS_PORT);
std::vector<char> data (1024);
server->setDataCall (
[&data, &counter, &len] (helics::tcp::TcpConnection::pointer, const char *data_rec, size_t data_Size) {
std::copy (data_rec, data_rec + data_Size, data.begin ());
len = data_Size;
++counter;
return data_Size;
});
ASSERT_TRUE (server->isReady ());
auto res = server->start ();
EXPECT_TRUE (res);
std::this_thread::sleep_for (100ms);
comm.setCallback ([] (helics::ActionMessage /*m*/) {});
comm.setBrokerPort (DEFAULT_TCPSS_PORT);
comm.setName ("tests");
comm.setServerMode (false);
bool connected = comm.connect ();
ASSERT_TRUE (connected);
comm.transmit (helics::parent_route_id, helics::CMD_IGNORE);
asio::error_code error;
int cnt = 0;
while (counter < 2)
{
if (len > 130)
{
break;
}
std::this_thread::sleep_for (100ms);
++cnt;
if (cnt > 30)
{
break;
}
}
EXPECT_GE (counter, 1);
EXPECT_GT (len.load (), 50u);
helics::ActionMessage rM;
auto loc = rM.depacketize (data.data (), len);
if ((counter == 1) && (loc < static_cast<int> (len.load ())))
{
rM.depacketize (data.data () + loc, static_cast<int> (len.load () - loc));
}
EXPECT_TRUE (rM.action () == helics::action_message_def::action_t::cmd_ignore);
server->close ();
comm.disconnect ();
std::this_thread::sleep_for (100ms);
}
TEST (TcpSSCore_tests, tcpSSComms_rx_test)
{
std::this_thread::sleep_for (400ms);
// std::atomic<int> ServerCounter{0};
std::atomic<int> CommCounter{0};
// std::atomic<size_t> len{0};
helics::ActionMessage act;
std::string host = "127.0.0.1";
helics::tcp::TcpCommsSS comm;
comm.loadTargetInfo (host, "");
std::mutex actguard;
auto srv = AsioContextManager::getContextPointer ();
auto contextLoop = srv->startContextLoop ();
comm.setCallback ([&CommCounter, &act, &actguard] (helics::ActionMessage m) {
++CommCounter;
std::lock_guard<std::mutex> lock (actguard);
act = m;
});
comm.setBrokerPort (DEFAULT_TCPSS_PORT);
comm.setName ("tests");
comm.setServerMode (true);
bool connected = comm.connect ();
ASSERT_TRUE (connected);
auto txconn = helics::tcp::TcpConnection::create (srv->getBaseContext (), host, TCP_BROKER_PORT_STRING, 1024);
auto res = txconn->waitUntilConnected (1000ms);
ASSERT_EQ (res, true);
ASSERT_TRUE (txconn->isConnected ());
helics::ActionMessage cmd (helics::CMD_ACK);
std::string buffer = cmd.packetize ();
txconn->send (buffer);
std::this_thread::sleep_for (200ms);
EXPECT_EQ (CommCounter, 1);
std::lock_guard<std::mutex> lock (actguard);
EXPECT_TRUE (act.action () == helics::action_message_def::action_t::cmd_ack);
txconn->close ();
comm.disconnect ();
std::this_thread::sleep_for (100ms);
}
TEST (TcpSSCore_tests, tcpSSComm_transmit_through)
{
std::this_thread::sleep_for (400ms);
std::atomic<int> counter{0};
std::atomic<int> counter2{0};
guarded<helics::ActionMessage> act;
guarded<helics::ActionMessage> act2;
auto srv = AsioContextManager::getContextPointer ();
auto contextLoop = srv->startContextLoop ();
std::string host = "localhost";
helics::tcp::TcpCommsSS comm;
helics::tcp::TcpCommsSS comm2;
comm.loadTargetInfo (host, host);
// comm2 is the broker
comm2.loadTargetInfo (host, std::string ());
comm.setBrokerPort (DEFAULT_TCPSS_PORT);
comm.setName ("tests");
comm.setServerMode (false);
comm2.setName ("test2");
comm2.setPortNumber (DEFAULT_TCPSS_PORT);
comm2.setServerMode (true);
comm.setCallback ([&counter, &act] (helics::ActionMessage m) {
++counter;
act = m;
});
comm2.setCallback ([&counter2, &act2] (helics::ActionMessage m) {
++counter2;
act2 = m;
});
// need to launch the connection commands at the same time since they depend on each other in this case
auto connected_fut = std::async (std::launch::async, [&comm] { return comm.connect (); });
bool connected1 = comm2.connect ();
ASSERT_TRUE (connected1);
bool connected2 = connected_fut.get ();
if (!connected2)
{ // lets just try again if it is not connected
connected2 = comm.connect ();
}
ASSERT_TRUE (connected2);
comm.transmit (helics::parent_route_id, helics::CMD_ACK);
std::this_thread::sleep_for (250ms);
if (counter2 != 1)
{
std::this_thread::sleep_for (500ms);
}
ASSERT_EQ (counter2, 1);
EXPECT_TRUE (act2.lock ()->action () == helics::action_message_def::action_t::cmd_ack);
comm2.disconnect ();
EXPECT_TRUE (!comm2.isConnected ());
comm.disconnect ();
EXPECT_TRUE (!comm.isConnected ());
std::this_thread::sleep_for (100ms);
}
TEST (TcpSSCore_tests, tcpSSComm_transmit_add_route)
{
std::this_thread::sleep_for (500ms);
std::atomic<int> counter{0};
std::atomic<int> counter2{0};
std::atomic<int> counter3{0};
std::string host = "localhost";
helics::tcp::TcpCommsSS comm, comm2, comm3;
auto srv = AsioContextManager::getContextPointer ();
auto contextLoop = srv->startContextLoop ();
comm.loadTargetInfo (host, host);
comm2.loadTargetInfo (host, std::string ());
comm3.loadTargetInfo (host, host);
comm.setBrokerPort (DEFAULT_TCPSS_PORT);
comm.setName ("tests");
comm.setServerMode (false);
comm2.setName ("broker");
comm2.setServerMode (true);
comm3.setName ("test3");
comm3.setServerMode (false);
comm3.setBrokerPort (DEFAULT_TCPSS_PORT);
comm2.setPortNumber (DEFAULT_TCPSS_PORT);
guarded<helics::ActionMessage> act;
guarded<helics::ActionMessage> act2;
guarded<helics::ActionMessage> act3;
comm.setCallback ([&counter, &act] (helics::ActionMessage m) {
++counter;
act = m;
});
comm2.setCallback ([&counter2, &act2] (helics::ActionMessage m) {
++counter2;
act2 = m;
});
comm3.setCallback ([&counter3, &act3] (helics::ActionMessage m) {
++counter3;
act3 = m;
});
// need to launch the connection commands at the same time since they depend on eachother in this case
// auto connected_fut = std::async(std::launch::async, [&comm] {return comm.connect(); });
bool connected = comm2.connect ();
ASSERT_TRUE (connected);
// connected = connected_fut.get();
connected = comm.connect ();
ASSERT_TRUE (connected);
connected = comm3.connect ();
ASSERT_TRUE (connected);
comm.transmit (helics::route_id (0), helics::CMD_ACK);
std::this_thread::sleep_for (250ms);
ASSERT_EQ (counter2, 1);
EXPECT_TRUE (act2.lock ()->action () == helics::action_message_def::action_t::cmd_ack);
comm3.transmit (helics::route_id (0), helics::CMD_ACK);
std::this_thread::sleep_for (250ms);
ASSERT_EQ (counter2, 2);
EXPECT_TRUE (act2.lock ()->action () == helics::action_message_def::action_t::cmd_ack);
comm2.addRoute (helics::route_id (3), comm3.getAddress ());
comm2.transmit (helics::route_id (3), helics::CMD_ACK);
std::this_thread::sleep_for (250ms);
if (counter3 != 1)
{
std::this_thread::sleep_for (250ms);
}
ASSERT_EQ (counter3, 1);
EXPECT_TRUE (act3.lock ()->action () == helics::action_message_def::action_t::cmd_ack);
comm2.addRoute (helics::route_id (4), comm.getAddress ());
comm2.transmit (helics::route_id (4), helics::CMD_ACK);
std::this_thread::sleep_for (250ms);
ASSERT_EQ (counter, 1);
EXPECT_TRUE (act.lock ()->action () == helics::action_message_def::action_t::cmd_ack);
comm.disconnect ();
comm3.disconnect ();
comm2.disconnect ();
std::this_thread::sleep_for (100ms);
}
TEST (TcpSSCore_tests, tcpSSCore_initialization_test)
{
std::this_thread::sleep_for (400ms);
std::atomic<int> counter{0};
std::string initializationString = "-f 1 --name=core1";
auto core = helics::CoreFactory::create (helics::core_type::TCP_SS, initializationString);
ASSERT_TRUE (core);
EXPECT_TRUE (core->isConfigured ());
auto srv = AsioContextManager::getContextPointer ();
auto contextLoop = srv->startContextLoop ();
auto server = helics::tcp::TcpServer::create (srv->getBaseContext (), "localhost", DEFAULT_TCPSS_PORT);
std::vector<char> data (1024);
std::atomic<size_t> len{0};
server->setDataCall (
[&data, &counter, &len] (helics::tcp::TcpConnection::pointer, const char *data_rec, size_t data_Size) {
std::copy (data_rec, data_rec + data_Size, data.begin () + len);
len += data_Size;
++counter;
return len.load ();
});
auto started = server->start ();
EXPECT_TRUE (started);
std::this_thread::sleep_for (100ms);
bool connected = core->connect ();
EXPECT_TRUE (connected);
if (connected)
{
int cnt = 0;
while (counter == 0)
{
std::this_thread::sleep_for (100ms);
++cnt;
if (cnt > 30)
{
break;
}
}
EXPECT_GE (counter, 1);
EXPECT_GT (len, 32u);
helics::ActionMessage rM;
helics::ActionMessage rM2;
auto used = rM.depacketize (data.data (), static_cast<int> (len.load ()));
if (used < static_cast<int> (len.load ()))
{
auto use2 = rM2.depacketize (data.data () + used, static_cast<int> (len.load () - used));
if (use2 == 0)
{
while (counter != 2)
{
std::this_thread::sleep_for (100ms);
++cnt;
if (cnt > 30)
{
break;
}
}
}
rM2.depacketize (data.data () + used, static_cast<int> (len.load () - used));
}
else
{
while (counter != 2)
{
std::this_thread::sleep_for (100ms);
++cnt;
if (cnt > 30)
{
break;
}
}
rM2.depacketize (data.data () + used, static_cast<int> (len.load () - used));
}
EXPECT_EQ (rM.name, "core1");
EXPECT_TRUE (rM.action () == helics::action_message_def::action_t::cmd_protocol);
EXPECT_EQ (rM2.name, "core1");
EXPECT_TRUE (rM2.action () == helics::action_message_def::action_t::cmd_reg_broker);
}
core->disconnect ();
server->close ();
core = nullptr;
helics::CoreFactory::cleanUpCores (100ms);
}
/** test case checks default values and makes sure they all mesh together
also tests the automatic port determination for cores
*/
TEST (TcpSSCore_tests, tcpSSCore_core_broker_default_test)
{
std::this_thread::sleep_for (std::chrono::milliseconds (400));
std::string initializationString = "-f 1";
auto broker = helics::BrokerFactory::create (helics::core_type::TCP_SS, initializationString);
ASSERT_TRUE (broker);
auto core = helics::CoreFactory::create (helics::core_type::TCP_SS, initializationString);
ASSERT_TRUE (core);
bool connected = broker->isConnected ();
EXPECT_TRUE (connected);
connected = core->connect ();
EXPECT_TRUE (connected);
auto ccore = static_cast<helics::tcp::TcpCoreSS *> (core.get ());
// this will test the automatic port allocation
EXPECT_EQ (ccore->getAddress (), ccore->getIdentifier ());
core->disconnect ();
broker->disconnect ();
core = nullptr;
broker = nullptr;
helics::CoreFactory::cleanUpCores (100ms);
helics::BrokerFactory::cleanUpBrokers (100ms);
}
| 32.004386
| 114
| 0.627313
|
manoj1511
|
44cf291f2500924fecf9f707a3323aff6cdc6e68
| 965
|
cpp
|
C++
|
AtCoder/abc222/c/main.cpp
|
H-Tatsuhiro/Com_Pro-Cpp
|
fd79f7821a76b11f4a6f83bbb26a034db577a877
|
[
"MIT"
] | null | null | null |
AtCoder/abc222/c/main.cpp
|
H-Tatsuhiro/Com_Pro-Cpp
|
fd79f7821a76b11f4a6f83bbb26a034db577a877
|
[
"MIT"
] | 1
|
2021-10-19T08:47:23.000Z
|
2022-03-07T05:23:56.000Z
|
AtCoder/abc222/c/main.cpp
|
H-Tatsuhiro/Com_Pro-Cpp
|
fd79f7821a76b11f4a6f83bbb26a034db577a877
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <cmath>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
int n, m; cin >> n >> m;
vector<vector<char>> a(2 * n, vector<char>(m, '.'));
for (int i = 0; i < 2 * n; i++) for (int j = 0; j < m; j++) cin >> a[i][j];
vector<pair<int, int>> v(2 * n, make_pair(0, 0));
for (int i = 0; i < 2 * n; i++) v[i].second = i;
function<int(char, char)> judge = [](char x, char y){
if (x == y) return -1;
if (x == 'G' && y == 'P') return 1;
if (x =='C' && y == 'G') return 1;
if (x == 'P' && y == 'C') return 1;
return 0;
};
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
int p = v[2 * j].second, q = v[2 * j + 1].second;
int res = judge(a[p][i], a[q][i]);
if (res != -1) v[2 * j + res].first--;
}
sort(v.begin(), v.end());
}
for (auto vv : v) cout << vv.second + 1 << endl;
}
| 33.275862
| 79
| 0.426943
|
H-Tatsuhiro
|
44cfd4e7ce4d2e5e386c5d9f9bbba81b4557ed24
| 1,340
|
cpp
|
C++
|
SimTest/MaterialElementTest.cpp
|
doplusplus/Physics_Simulator
|
f562b07fe7c3e245c0ebc9d5618fe0c09114126c
|
[
"MIT"
] | null | null | null |
SimTest/MaterialElementTest.cpp
|
doplusplus/Physics_Simulator
|
f562b07fe7c3e245c0ebc9d5618fe0c09114126c
|
[
"MIT"
] | 1
|
2015-09-03T08:03:12.000Z
|
2015-10-06T20:11:48.000Z
|
SimTest/MaterialElementTest.cpp
|
doplusplus/PointSimulator
|
f562b07fe7c3e245c0ebc9d5618fe0c09114126c
|
[
"MIT"
] | null | null | null |
#include "stdafx.h"
#include "CppUnitTest.h"
#include "..\SimModule\MaterialElement.h"
#include "..\SimModule\MechanicalAction.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace UnitTesting
{
TEST_CLASS(MaterialPointTest)
{
public:
TEST_METHOD(blankMatPointConstruction)
{
MaterialPoint A;
MaterialPoint B(0.0, 0.0);
MaterialPoint C(0.0, 0.0, {});
Assert::IsTrue(A == B&&B == C);
}
TEST_METHOD(MatPointConstruction_WithSwapedActions)
{
auto a2 = std::make_shared<ActionOnPoint>
(ActionOnPoint(Vect(0, 0, 0), Vect(0, 0, 0), Vect(0, 0, 0), Vect::linear, Vect::Vconstant));
auto a3 = std::make_shared<ActionOnPoint>
(ActionOnPoint(Vect(0, 0, 0), Vect(0, 0, 0), Vect(0, 0, 0), Vect::constant, Vect::Vlinear));
MaterialPoint A(0.0, 0.0, { a2,a3 });
MaterialPoint B(0.0, 0.0, { a3,a2 });
Assert::IsTrue(A == B);
}
TEST_METHOD(MatPointConstruction_unequal)
{
auto a2 = std::make_shared<ActionOnPoint>
(ActionOnPoint(Vect(0, 0, 0), Vect(0, 0, 0), Vect(0, 0, 0), Vect::linear, Vect::Vlinear));
auto a3 = std::make_shared<ActionOnPoint>
(ActionOnPoint(Vect(0, 0, 0), Vect(0, 0, 0), Vect(0, 0, 0), Vect::Quadratic, Vect::Vlinear));
MaterialPoint A(0.0, 0.0, { a2 });
MaterialPoint B(0.0, 0.0, { a3 });
Assert::IsFalse(A == B);
}
};
}
| 25.769231
| 97
| 0.647761
|
doplusplus
|
44d00fc1ec492aaf1d3ae338ca53775e5285ffe3
| 1,393
|
cpp
|
C++
|
src/xray/xrLC/xrHierrarhy.cpp
|
OLR-xray/OLR-3.0
|
b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611
|
[
"Apache-2.0"
] | 8
|
2016-01-25T20:18:51.000Z
|
2019-03-06T07:00:04.000Z
|
code/utils/xrLC/xrHierrarhy.cpp
|
ipl-adm/xray-oxygen
|
3ae4d4911f5b000e93bdf108eb68db25315b2fc6
|
[
"Apache-2.0"
] | null | null | null |
code/utils/xrLC/xrHierrarhy.cpp
|
ipl-adm/xray-oxygen
|
3ae4d4911f5b000e93bdf108eb68db25315b2fc6
|
[
"Apache-2.0"
] | 3
|
2016-02-14T01:20:43.000Z
|
2021-02-03T11:19:11.000Z
|
#include "stdafx.h"
#include "build.h"
#include "OGF_Face.h"
void CBuild::BuildHierrarhy()
{
Fvector scene_size;
float delimiter;
scene_bb.getsize(scene_size);
delimiter = _MAX(scene_size.x,_MAX(scene_size.y,scene_size.z));
delimiter *= 2;
int iLevel = 1;
float SizeLimit = g_params.m_maxsize/8;
if (SizeLimit<4.f) SizeLimit=4.f;
for (; SizeLimit<=delimiter; SizeLimit*=2)
{
int iSize = g_tree.size();
Status("Level #%d",iLevel);
for (int I=0; I<iSize; I++)
{
if (g_tree[I]->bConnected) continue;
OGF_Node* pNode = xr_new<OGF_Node> (iLevel);
pNode->AddChield(I);
// Find best object to connect with
for (int J=0; J<iSize; J++)
{
OGF_Base* candidate = g_tree[J];
if ( candidate->bConnected) continue;
Fbox bb;
Fvector size;
bb.set (pNode->bbox);
bb.merge (candidate->bbox);
bb.getsize (size);
if (size.x>SizeLimit || size.y>SizeLimit || size.z>SizeLimit) continue;
pNode->AddChield(J);
}
if (pNode->chields.size()>1) {
pNode->CalcBounds();
g_tree.push_back(pNode);
} else {
g_tree[I]->bConnected = false;
xr_delete pNode;
}
Progress(float(I)/float(iSize));
}
clMsg("#%2d [%3.1f]: %d nodes",iLevel,SizeLimit,g_tree.size()-iSize);
if (iSize != g_tree.size()) iLevel++;
}
g_TREE_ROOT = g_tree.back();
clMsg("* TREE levels %d, TREE size %d",iLevel,g_tree.size());
}
| 23.610169
| 75
| 0.632448
|
OLR-xray
|
44d2f00ef7111469bb8aca0db3686b9f951d7d70
| 107,793
|
cpp
|
C++
|
src/Chain/libraries/glua/lauxlib.cpp
|
WillAchain/Achain
|
4118a8fc7a18e356e5a865d39d21bba3100664c9
|
[
"MIT"
] | 226
|
2017-09-07T13:13:08.000Z
|
2022-02-26T09:07:10.000Z
|
src/Chain/libraries/glua/lauxlib.cpp
|
WillAchain/Achain
|
4118a8fc7a18e356e5a865d39d21bba3100664c9
|
[
"MIT"
] | 22
|
2017-09-26T03:36:21.000Z
|
2020-08-23T19:59:40.000Z
|
src/Chain/libraries/glua/lauxlib.cpp
|
WillAchain/Achain
|
4118a8fc7a18e356e5a865d39d21bba3100664c9
|
[
"MIT"
] | 79
|
2017-09-08T02:57:08.000Z
|
2022-02-02T12:46:31.000Z
|
/*
** $Id: lauxlib.c,v 1.284 2015/11/19 19:16:22 roberto Exp $
** Auxiliary functions for building Lua libraries
** See Copyright Notice in lua.h
*/
#define lauxlib_cpp
#include <glua/lprefix.h>
#include <errno.h>
#include <stdarg.h>
#include <cstdint>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <cstdint>
#include <string>
#include <sstream>
#include <iostream>
#include <functional>
#include <vector>
#include <stack>
#include <algorithm>
/* This file uses only the official API of Lua.
** Any function declared here could be written as an application function.
*/
#include <glua/lua.h>
#include <glua/lauxlib.h>
#include <glua/lobject.h>
#include <glua/lapi.h>
#include <glua/thinkyoung_lua_api.h>
#include <glua/thinkyoung_lua_lib.h>
#include <glua/glua_lutil.h>
#include <glua/exceptions.h>
using thinkyoung::lua::api::global_glua_chain_api;
/*
** {======================================================
** Traceback
** =======================================================
*/
#define LEVELS1 10 /* size of the first part of the stack */
#define LEVELS2 11 /* size of the second part of the stack */
/*
** search for 'objidx' in table at index -1.
** return 1 + string at top if find a good name.
*/
static int findfield(lua_State *L, int objidx, int level) {
if (level == 0 || !lua_istable(L, -1))
return 0; /* not found */
lua_pushnil(L); /* start 'next' loop */
while (lua_next(L, -2)) { /* for each pair in table */
if (lua_type(L, -2) == LUA_TSTRING) { /* ignore non-string keys */
if (lua_rawequal(L, objidx, -1)) { /* found object? */
lua_pop(L, 1); /* remove value (but keep name) */
return 1;
}
else if (findfield(L, objidx, level - 1)) { /* try recursively */
lua_remove(L, -2); /* remove table (but keep name) */
lua_pushliteral(L, ".");
lua_insert(L, -2); /* place '.' between the two names */
lua_concat(L, 3);
return 1;
}
}
lua_pop(L, 1); /* remove value */
}
return 0; /* not found */
}
/*
** Search for a name for a function in all loaded modules
** (registry._LOADED).
*/
static int pushglobalfuncname(lua_State *L, lua_Debug *ar) {
int top = lua_gettop(L);
lua_getinfo(L, "f", ar); /* push function */
lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
if (findfield(L, top + 1, 2)) {
const char *name = lua_tostring(L, -1);
if (strncmp(name, "_G.", 3) == 0) { /* name start with '_G.'? */
lua_pushstring(L, name + 3); /* push name without prefix */
lua_remove(L, -2); /* remove original name */
}
lua_copy(L, -1, top + 1); /* move name to proper place */
lua_pop(L, 2); /* remove pushed values */
return 1;
}
else {
lua_settop(L, top); /* remove function and global table */
return 0;
}
}
static void pushfuncname(lua_State *L, lua_Debug *ar) {
if (pushglobalfuncname(L, ar)) { /* try first a global name */
lua_pushfstring(L, "function '%s'", lua_tostring(L, -1));
lua_remove(L, -2); /* remove name */
}
else if (*ar->namewhat != '\0') /* is there a name from code? */
lua_pushfstring(L, "%s '%s'", ar->namewhat, ar->name); /* use it */
else if (*ar->what == 'm') /* main? */
lua_pushliteral(L, "main chunk");
else if (*ar->what != 'C') /* for Lua functions, use <file:line> */
lua_pushfstring(L, "function <%s:%d>", ar->short_src, ar->linedefined);
else /* nothing left... */
lua_pushliteral(L, "?");
}
static int lastlevel(lua_State *L) {
lua_Debug ar;
int li = 1, le = 1;
/* find an upper bound */
while (lua_getstack(L, le, &ar)) { li = le; le *= 2; }
/* do a binary search */
while (li < le) {
int m = (li + le) / 2;
if (lua_getstack(L, m, &ar)) li = m + 1;
else le = m;
}
return le - 1;
}
LUALIB_API void luaL_traceback(lua_State *L, lua_State *L1,
const char *msg, int level) {
lua_Debug ar;
int top = lua_gettop(L);
int last = lastlevel(L1);
int n1 = (last - level > LEVELS1 + LEVELS2) ? LEVELS1 : -1;
if (msg)
lua_pushfstring(L, "%s\n", msg);
luaL_checkstack(L, 10, nullptr);
lua_pushliteral(L, "stack traceback:");
while (lua_getstack(L1, level++, &ar)) {
if (n1-- == 0) { /* too many levels? */
lua_pushliteral(L, "\n\t..."); /* add a '...' */
level = last - LEVELS2 + 1; /* and skip to last ones */
}
else {
lua_getinfo(L1, "Slnt", &ar);
lua_pushfstring(L, "\n\t%s:", ar.short_src);
if (ar.currentline > 0)
lua_pushfstring(L, "%d:", ar.currentline);
lua_pushliteral(L, " in ");
pushfuncname(L, &ar);
if (ar.istailcall)
lua_pushliteral(L, "\n\t(...tail calls...)");
lua_concat(L, lua_gettop(L) - top);
}
}
lua_concat(L, lua_gettop(L) - top);
}
/* }====================================================== */
/*
** {======================================================
** Error-report functions
** =======================================================
*/
LUALIB_API int luaL_argerror(lua_State *L, int arg, const char *extramsg) {
lua_Debug ar;
if (!lua_getstack(L, 0, &ar)) /* no stack frame? */
return luaL_error(L, "bad argument #%d (%s)", arg, extramsg);
lua_getinfo(L, "n", &ar);
if (strcmp(ar.namewhat, "method") == 0) {
arg--; /* do not count 'self' */
if (arg == 0) /* error is in the self argument itself? */
return luaL_error(L, "calling '%s' on bad self (%s)",
ar.name, extramsg);
}
if (ar.name == nullptr)
ar.name = (pushglobalfuncname(L, &ar)) ? lua_tostring(L, -1) : "?";
return luaL_error(L, "bad argument #%d to '%s' (%s)",
arg, ar.name, extramsg);
}
static int typeerror(lua_State *L, int arg, const char *tname) {
const char *msg;
const char *typearg; /* name for the type of the actual argument */
if (luaL_getmetafield(L, arg, "__name") == LUA_TSTRING)
typearg = lua_tostring(L, -1); /* use the given type name */
else if (lua_type(L, arg) == LUA_TLIGHTUSERDATA)
typearg = "light userdata"; /* special name for messages */
else
typearg = luaL_typename(L, arg); /* standard name */
msg = lua_pushfstring(L, "%s expected, got %s", tname, typearg);
global_glua_chain_api->throw_exception(L, THINKYOUNG_API_SIMPLE_ERROR, msg);
return luaL_argerror(L, arg, msg);
}
static void tag_error(lua_State *L, int arg, int tag) {
typeerror(L, arg, lua_typename(L, tag));
}
LUALIB_API void luaL_where(lua_State *L, int level) {
lua_Debug ar;
if (lua_getstack(L, level, &ar)) { /* check function at level */
lua_getinfo(L, "Sl", &ar); /* get info about it */
if (ar.currentline > 0) { /* is there info? */
lua_pushfstring(L, "%s:%d: ", ar.short_src, ar.currentline);
return;
}
}
lua_pushliteral(L, ""); /* else, no information available... */
}
LUALIB_API int luaL_error(lua_State *L, const char *fmt, ...) {
va_list argp;
va_start(argp, fmt);
luaL_where(L, 1);
lua_pushvfstring(L, fmt, argp);
va_end(argp);
lua_concat(L, 2);
return lua_error(L);
}
LUALIB_API int luaL_fileresult(lua_State *L, int stat, const char *fname) {
int en = errno; /* calls to Lua API may change this value */
if (stat) {
lua_pushboolean(L, 1);
return 1;
}
else {
lua_pushnil(L);
if (fname)
lua_pushfstring(L, "%s: %s", fname, strerror(en));
else
lua_pushstring(L, strerror(en));
lua_pushinteger(L, en);
return 3;
}
}
#if !defined(l_inspectstat) /* { */
#if defined(LUA_USE_POSIX)
#include <sys/wait.h>
/*
** use appropriate macros to interpret 'pclose' return status
*/
#define l_inspectstat(stat,what) \
if (WIFEXITED(stat)) { stat = WEXITSTATUS(stat); } \
else if (WIFSIGNALED(stat)) { stat = WTERMSIG(stat); what = "signal"; }
#else
#define l_inspectstat(stat,what) /* no op */
#endif
#endif /* } */
LUALIB_API int luaL_execresult(lua_State *L, int stat) {
const char *what = "exit"; /* type of termination */
if (stat == -1) /* error? */
return luaL_fileresult(L, 0, nullptr);
else {
l_inspectstat(stat, what); /* interpret result */
if (*what == 'e' && stat == 0) /* successful termination? */
lua_pushboolean(L, 1);
else
lua_pushnil(L);
lua_pushstring(L, what);
lua_pushinteger(L, stat);
return 3; /* return true/nil,what,code */
}
}
/* }====================================================== */
/*
** {======================================================
** Userdata's metatable manipulation
** =======================================================
*/
LUALIB_API int luaL_newmetatable(lua_State *L, const char *tname) {
if (luaL_getmetatable(L, tname) != LUA_TNIL) /* name already in use? */
return 0; /* leave previous value on top, but return 0 */
lua_pop(L, 1);
lua_createtable(L, 0, 2); /* create metatable */
lua_pushstring(L, tname);
lua_setfield(L, -2, "__name"); /* metatable.__name = tname */
lua_pushvalue(L, -1);
lua_setfield(L, LUA_REGISTRYINDEX, tname); /* registry.name = metatable */
return 1;
}
LUALIB_API void luaL_setmetatable(lua_State *L, const char *tname) {
luaL_getmetatable(L, tname);
lua_setmetatable(L, -2);
}
LUALIB_API void *luaL_testudata(lua_State *L, int ud, const char *tname) {
void *p = lua_touserdata(L, ud);
if (p != nullptr) { /* value is a userdata? */
if (lua_getmetatable(L, ud)) { /* does it have a metatable? */
luaL_getmetatable(L, tname); /* get correct metatable */
if (!lua_rawequal(L, -1, -2)) /* not the same? */
p = nullptr; /* value is a userdata with wrong metatable */
lua_pop(L, 2); /* remove both metatables */
return p;
}
}
return nullptr; /* value is not a userdata with a metatable */
}
LUALIB_API void *luaL_checkudata(lua_State *L, int ud, const char *tname) {
void *p = luaL_testudata(L, ud, tname);
if (p == nullptr) typeerror(L, ud, tname);
return p;
}
/* }====================================================== */
/*
** {======================================================
** Argument check functions
** =======================================================
*/
LUALIB_API int luaL_checkoption(lua_State *L, int arg, const char *def,
const char *const lst[]) {
const char *name = (def) ? luaL_optstring(L, arg, def) :
luaL_checkstring(L, arg);
int i;
for (i = 0; lst[i]; i++)
if (strcmp(lst[i], name) == 0)
return i;
return luaL_argerror(L, arg,
lua_pushfstring(L, "invalid option '%s'", name));
}
LUALIB_API void luaL_checkstack(lua_State *L, int space, const char *msg) {
/* keep some extra space to run error routines, if needed */
const int extra = LUA_MINSTACK;
if (!lua_checkstack(L, space + extra)) {
if (msg)
luaL_error(L, "stack overflow (%s)", msg);
else
luaL_error(L, "stack overflow");
}
}
LUALIB_API void luaL_checktype(lua_State *L, int arg, int t) {
if (lua_type(L, arg) != t)
tag_error(L, arg, t);
}
LUALIB_API void luaL_checkany(lua_State *L, int arg) {
if (lua_type(L, arg) == LUA_TNONE)
luaL_argerror(L, arg, "value expected");
}
LUALIB_API const char *luaL_checklstring(lua_State *L, int arg, size_t *len) {
const char *s = lua_tolstring(L, arg, len);
if (!s) tag_error(L, arg, LUA_TSTRING);
return s;
}
LUALIB_API const char *luaL_optlstring(lua_State *L, int arg,
const char *def, size_t *len) {
if (lua_isnoneornil(L, arg)) {
if (len)
*len = (def ? strlen(def) : 0);
return def;
}
else return luaL_checklstring(L, arg, len);
}
LUALIB_API lua_Number luaL_checknumber(lua_State *L, int arg) {
int isnum;
lua_Number d = lua_tonumberx(L, arg, &isnum);
if (!isnum)
tag_error(L, arg, LUA_TNUMBER);
return d;
}
LUALIB_API lua_Number luaL_optnumber(lua_State *L, int arg, lua_Number def) {
return luaL_opt(L, luaL_checknumber, arg, def);
}
static void interror(lua_State *L, int arg) {
if (lua_isnumber(L, arg))
luaL_argerror(L, arg, "number has no integer representation");
else
tag_error(L, arg, LUA_TNUMBER);
}
LUALIB_API lua_Integer luaL_checkinteger(lua_State *L, int arg) {
int isnum;
lua_Integer d = lua_tointegerx(L, arg, &isnum);
if (!isnum) {
interror(L, arg);
}
return d;
}
LUALIB_API lua_Integer luaL_optinteger(lua_State *L, int arg,
lua_Integer def) {
return luaL_opt(L, luaL_checkinteger, arg, def);
}
/* }====================================================== */
/*
** {======================================================
** Generic Buffer manipulation
** =======================================================
*/
/* userdata to box arbitrary data */
typedef struct UBox {
void *box;
size_t bsize;
} UBox;
static void *resizebox(lua_State *L, int idx, size_t newsize) {
void *ud;
lua_Alloc allocf = lua_getallocf(L, &ud);
UBox *box = (UBox *)lua_touserdata(L, idx);
void *temp = allocf(ud, box->box, box->bsize, newsize);
if (temp == nullptr && newsize > 0) { /* allocation error? */
resizebox(L, idx, 0); /* free buffer */
luaL_error(L, "not enough memory for buffer allocation");
}
box->box = temp;
box->bsize = newsize;
return temp;
}
static int boxgc(lua_State *L) {
resizebox(L, 1, 0);
return 0;
}
static void *newbox(lua_State *L, size_t newsize) {
UBox *box = (UBox *)lua_newuserdata(L, sizeof(UBox));
box->box = nullptr;
box->bsize = 0;
if (luaL_newmetatable(L, "LUABOX")) { /* creating metatable? */
lua_pushcfunction(L, boxgc);
lua_setfield(L, -2, "__gc"); /* metatable.__gc = boxgc */
}
lua_setmetatable(L, -2);
return resizebox(L, -1, newsize);
}
/*
** check whether buffer is using a userdata on the stack as a temporary
** buffer
*/
#define buffonstack(B) ((B)->b != (B)->initb)
/*
** returns a pointer to a free area with at least 'sz' bytes
*/
LUALIB_API char *luaL_prepbuffsize(luaL_Buffer *B, size_t sz) {
lua_State *L = B->L;
if (B->size - B->n < sz) { /* not enough space? */
char *newbuff;
size_t newsize = B->size * 2; /* double buffer size */
if (newsize - B->n < sz) /* not big enough? */
newsize = B->n + sz;
if (newsize < B->n || newsize - B->n < sz)
luaL_error(L, "buffer too large");
/* create larger buffer */
if (buffonstack(B))
newbuff = (char *)resizebox(L, -1, newsize);
else { /* no buffer yet */
newbuff = (char *)newbox(L, newsize);
memcpy(newbuff, B->b, B->n * sizeof(char)); /* copy original content */
}
B->b = newbuff;
B->size = newsize;
}
return &B->b[B->n];
}
LUALIB_API void luaL_addlstring(luaL_Buffer *B, const char *s, size_t l) {
if (l > 0) { /* avoid 'memcpy' when 's' can be nullptr */
char *b = luaL_prepbuffsize(B, l);
memcpy(b, s, l * sizeof(char));
luaL_addsize(B, l);
}
}
LUALIB_API void luaL_addstring(luaL_Buffer *B, const char *s) {
luaL_addlstring(B, s, strlen(s));
}
LUALIB_API void luaL_pushresult(luaL_Buffer *B) {
lua_State *L = B->L;
lua_pushlstring(L, B->b, B->n);
if (buffonstack(B)) {
resizebox(L, -2, 0); /* delete old buffer */
lua_remove(L, -2); /* remove its header from the stack */
}
}
LUALIB_API void luaL_pushresultsize(luaL_Buffer *B, size_t sz) {
luaL_addsize(B, sz);
luaL_pushresult(B);
}
LUALIB_API void luaL_addvalue(luaL_Buffer *B) {
lua_State *L = B->L;
size_t l;
const char *s = lua_tolstring(L, -1, &l);
if (buffonstack(B))
lua_insert(L, -2); /* put value below buffer */
luaL_addlstring(B, s, l);
lua_remove(L, (buffonstack(B)) ? -2 : -1); /* remove value */
}
LUALIB_API void luaL_buffinit(lua_State *L, luaL_Buffer *B) {
B->L = L;
B->b = B->initb;
B->n = 0;
B->size = LUAL_BUFFERSIZE;
}
LUALIB_API char *luaL_buffinitsize(lua_State *L, luaL_Buffer *B, size_t sz) {
luaL_buffinit(L, B);
return luaL_prepbuffsize(B, sz);
}
/* }====================================================== */
/*
** {======================================================
** Reference system
** =======================================================
*/
/* index of free-list header */
#define freelist 0
LUALIB_API int luaL_ref(lua_State *L, int t) {
int ref;
if (lua_isnil(L, -1)) {
lua_pop(L, 1); /* remove from stack */
return LUA_REFNIL; /* 'nil' has a unique fixed reference */
}
t = lua_absindex(L, t);
lua_rawgeti(L, t, freelist); /* get first free element */
ref = (int)lua_tointeger(L, -1); /* ref = t[freelist] */
lua_pop(L, 1); /* remove it from stack */
if (ref != 0) { /* any free element? */
lua_rawgeti(L, t, ref); /* remove it from list */
lua_rawseti(L, t, freelist); /* (t[freelist] = t[ref]) */
}
else /* no free elements */
ref = (int)lua_rawlen(L, t) + 1; /* get a new reference */
lua_rawseti(L, t, ref);
return ref;
}
LUALIB_API void luaL_unref(lua_State *L, int t, int ref) {
if (ref >= 0) {
t = lua_absindex(L, t);
lua_rawgeti(L, t, freelist);
lua_rawseti(L, t, ref); /* t[ref] = t[freelist] */
lua_pushinteger(L, ref);
lua_rawseti(L, t, freelist); /* t[freelist] = ref */
}
}
/* }====================================================== */
/*
** {======================================================
** Load functions
** =======================================================
*/
typedef struct LoadF {
int n; /* number of pre-read characters */
FILE *f; /* file being read */
char buff[BUFSIZ]; /* area for reading file */
} LoadF;
static const char *getF(lua_State *L, void *ud, size_t *size) {
LoadF *lf = (LoadF *)ud;
(void)L; /* not used */
if (lf->n > 0) { /* are there pre-read characters to be read? */
*size = lf->n; /* return them (chars already in buffer) */
lf->n = 0; /* no more pre-read characters */
}
else { /* read a block from file */
/* 'fread' can return > 0 *and* set the EOF flag. If next call to
'getF' called 'fread', it might still wait for user input.
The next check avoids this problem. */
if (feof(lf->f)) return nullptr;
*size = fread(lf->buff, 1, sizeof(lf->buff), lf->f); /* read block */
}
return lf->buff;
}
static int errfile(lua_State *L, const char *what, int fnameindex) {
const char *serr = strerror(errno);
const char *filename = lua_tostring(L, fnameindex) + 1;
lua_pushfstring(L, "cannot %s %s: %s", what, filename, serr);
global_glua_chain_api->throw_exception(L, THINKYOUNG_API_SIMPLE_ERROR, luaL_checkstring(L, -1));
lua_remove(L, fnameindex);
return LUA_ERRFILE;
}
static int skipBOM(LoadF *lf) {
const char *p = "\xEF\xBB\xBF"; /* UTF-8 BOM mark */
int c;
lf->n = 0;
do {
c = getc(lf->f);
if (c == EOF || c != *(const unsigned char *)p++) return c;
lf->buff[lf->n++] = c; /* to be read by the parser */
} while (*p != '\0');
lf->n = 0; /* prefix matched; discard it */
return getc(lf->f); /* return next character */
}
/*
** reads the first character of file 'f' and skips an optional BOM mark
** in its beginning plus its first line if it starts with '#'. Returns
** true if it skipped the first line. In any case, '*cp' has the
** first "valid" character of the file (after the optional BOM and
** a first-line comment).
*/
static int skipcomment(LoadF *lf, int *cp) {
int c = *cp = skipBOM(lf);
if (c == '#') { /* first line is a comment (Unix exec. file)? */
do { /* skip first line */
c = getc(lf->f);
} while (c != EOF && c != '\n');
*cp = getc(lf->f); /* skip end-of-line, if present */
return 1; /* there was a comment */
}
else return 0; /* no comment */
}
static lua_State *globalL = nullptr;
static const char *progname = "thinkyoung_lua";
/*
** Prints an error message, adding the program name in front of it
** (if present)
*/
static void l_message(const char *pname, const char *msg) {
if (pname) lua_writestringerror("%s: ", pname);
lua_writestringerror("%s\n", msg);
}
/*
** Hook set by signal function to stop the interpreter.
*/
static void lstop(lua_State *L, lua_Debug *ar) {
(void)ar; /* unused arg. */
lua_sethook(L, nullptr, 0, 0); /* reset hook */
luaL_error(L, "interrupted!");
}
/*
** Function to be called at a C signal. Because a C signal cannot
** just change a Lua state (as there is no proper synchronization),
** this function only sets a hook that, when called, will stop the
** interpreter.
*/
static void laction(int i) {
signal(i, SIG_DFL); /* if another SIGINT happens, terminate process */
lua_sethook(globalL, lstop, LUA_MASKCALL | LUA_MASKRET | LUA_MASKCOUNT, 1);
}
/*
** Message handler used to run all chunks
*/
static int msghandler(lua_State *L) {
const char *msg = lua_tostring(L, 1);
if (msg == nullptr) { /* is error object not a string? */
if (luaL_callmeta(L, 1, "__tostring") && /* does it have a metamethod */
lua_type(L, -1) == LUA_TSTRING) /* that produces a string? */
return 1; /* that is the message */
else
msg = lua_pushfstring(L, "(error object is a %s value)",
luaL_typename(L, 1));
}
luaL_traceback(L, L, msg, 1); /* append a standard traceback */
return 1; /* return the traceback */
}
/*
** Interface to 'lua_pcall', which sets appropriate message function
** and C-signal handler. Used to run all chunks.
*/
static int docall(lua_State *L, int narg, int nres) {
int status;
int base = lua_gettop(L) - narg; /* function index */
lua_pushcfunction(L, msghandler); /* push message handler */
lua_insert(L, base); /* put it under function and args */
globalL = L; /* to be available to 'laction' */
signal(SIGINT, laction); /* set C-signal handler */
status = lua_pcall(L, narg, nres, base);
signal(SIGINT, SIG_DFL); /* reset C-signal handler */
if (lua_gettop(L) > 0)
lua_remove(L, base); /* remove message handler from the stack */
return status;
}
/*
** Check whether 'status' is not OK and, if so, prints the error
** message on the top of the stack. It assumes that the error object
** is a string, as it was either generated by Lua or by 'msghandler'.
*/
static int report(lua_State *L, int status) {
if (status != LUA_OK) {
const char *msg = lua_tostring(L, -1);
l_message(progname, msg);
lua_pop(L, 1); /* remove message */
}
return status;
}
static int dochunk(lua_State *L, int status) {
if (status == LUA_OK) status = docall(L, 0, 0);
return report(L, status);
}
static int dofile(lua_State *L, const char *name) {
return dochunk(L, luaL_loadfile(L, name));
}
static int dostring(lua_State *L, const char *s, const char *name) {
return dochunk(L, luaL_loadbuffer(L, s, strlen(s), name));
}
/*
** Calls 'require(name)' and stores the result in a global variable
** with the given name.
*/
static int dolibrary(lua_State *L, const char *name) {
int status;
lua_getglobal(L, "require");
lua_pushstring(L, name);
status = docall(L, 1, 1); /* call 'require(name)' */
if (status == LUA_OK)
lua_setglobal(L, name); /* global[name] = require return */
return report(L, status);
}
/*
** Push on the stack the contents of table 'arg' from 1 to #arg
*/
static int pushargs(lua_State *L) {
int i, n;
if (lua_getglobal(L, "arg") != LUA_TTABLE)
luaL_error(L, "'arg' is not a table");
n = (int)luaL_len(L, -1);
luaL_checkstack(L, n + 3, "too many arguments to script");
for (i = 1; i <= n; i++)
lua_rawgeti(L, -i, i);
lua_remove(L, -i); /* remove table from the stack */
return n;
}
static int handle_script(lua_State *L, char **argv) {
// READ THIS
int status;
const char *fname = argv[0];
if (strcmp(fname, "-") == 0 && strcmp(argv[-1], "--") != 0)
fname = nullptr; /* stdin */
status = luaL_loadfile(L, fname);
if (status == LUA_OK) {
int n = pushargs(L); /* push arguments to script */
status = docall(L, n, LUA_MULTRET);
}
return report(L, status);
}
/* bits of various argument indicators in 'args' */
#define has_error 1 /* bad option */
#define has_i 2 /* -i */
#define has_v 4 /* -v */
#define has_e 8 /* -e */
#define has_E 16 /* -E */
#if !defined(LUA_PROMPT)
#define LUA_PROMPT "> "
#define LUA_PROMPT2 ">> "
#endif
#if !defined(LUA_PROGNAME)
#define LUA_PROGNAME "lua"
#endif
#if !defined(LUA_MAXINPUT)
#define LUA_MAXINPUT 512
#endif
#if !defined(LUA_INIT_VAR)
#define LUA_INIT_VAR "LUA_INIT"
#endif
#define LUA_INITVARVERSION \
LUA_INIT_VAR "_" LUA_VERSION_MAJOR "_" LUA_VERSION_MINOR
/*
** Traverses all arguments from 'argv', returning a mask with those
** needed before running any Lua code (or an error code if it finds
** any invalid argument). 'first' returns the first not-handled argument
** (either the script name or a bad argument in case of error).
*/
static int collectargs(char **argv, int *first) {
int args = 0;
int i;
for (i = 1; argv[i] != nullptr; i++) {
*first = i;
if (argv[i][0] != '-') /* not an option? */
return args; /* stop handling options */
switch (argv[i][1]) { /* else check option */
case '-': /* '--' */
if (argv[i][2] != '\0') /* extra characters after '--'? */
return has_error; /* invalid option */
*first = i + 1;
return args;
case '\0': /* '-' */
return args; /* script "name" is '-' */
case 'E':
if (argv[i][2] != '\0') /* extra characters after 1st? */
return has_error; /* invalid option */
args |= has_E;
break;
case 'i':
args |= has_i; /* (-i implies -v) *//* FALLTHROUGH */
case 'v':
if (argv[i][2] != '\0') /* extra characters after 1st? */
return has_error; /* invalid option */
args |= has_v;
break;
case 'e':
args |= has_e; /* FALLTHROUGH */
case 'l': /* both options need an argument */
if (argv[i][2] == '\0') { /* no concatenated argument? */
i++; /* try next 'argv' */
if (argv[i] == nullptr || argv[i][0] == '-')
return has_error; /* no next argument or it is another option */
}
break;
default: /* invalid option */
return has_error;
}
}
*first = i; /* no script name */
return args;
}
/*
** Processes options 'e' and 'l', which involve running Lua code.
** Returns 0 if some code raises an error.
*/
static int runargs(lua_State *L, char **argv, int n) {
int i;
for (i = 1; i < n; i++) {
int option = argv[i][1];
lua_assert(argv[i][0] == '-'); /* already checked */
if (option == 'e' || option == 'l') {
int status;
const char *extra = argv[i] + 2; /* both options need an argument */
if (*extra == '\0') extra = argv[++i];
lua_assert(extra != nullptr);
status = (option == 'e')
? dostring(L, extra, "=(command line)")
: dolibrary(L, extra);
if (status != LUA_OK) return 0;
}
}
return 1;
}
/*
** Create the 'arg' table, which stores all arguments from the
** command line ('argv'). It should be aligned so that, at index 0,
** it has 'argv[script]', which is the script name. The arguments
** to the script (everything after 'script') go to positive indices;
** other arguments (before the script name) go to negative indices.
** If there is no script name, assume interpreter's name as base.
*/
static void createargtable(lua_State *L, char **argv, int argc, int script) {
int i, narg;
if (script == argc) script = 0; /* no script name? */
narg = argc - (script + 1); /* number of positive indices */
lua_createtable(L, narg, script + 1);
for (i = 0; i < argc; i++) {
lua_pushstring(L, argv[i]);
lua_rawseti(L, -2, i - script);
}
lua_setglobal(L, "arg");
}
static int handle_luainit(lua_State *L) {
const char *name = "=" LUA_INITVARVERSION;
const char *init = getenv(name + 1);
if (init == nullptr) {
name = "=" LUA_INIT_VAR;
init = getenv(name + 1); /* try alternative name */
}
if (init == nullptr) return LUA_OK;
else if (init[0] == '@')
return dofile(L, init + 1);
else
return dostring(L, init, name);
}
static int pmain_of_run_compiled_file(lua_State *L)
{
int argc = (int)lua_tointeger(L, 1);
char **argv = (char **)lua_touserdata(L, 2);
int script;
int args = collectargs(argv, &script);
luaL_checkversion(L); /* check that interpreter has correct version */
if (argv[0] && argv[0][0]) progname = argv[0];
createargtable(L, argv, argc, script); /* create table 'arg' */
if (!(args & has_E)) { /* no option '-E'? */
if (handle_luainit(L) != LUA_OK) /* run LUA_INIT */
return 0; /* error running LUA_INIT */
}
if (!runargs(L, argv, script)) /* execute arguments -e and -l */
return 0; /* something failed */
if (script < argc && /* execute main script (if there is one) */
handle_script(L, argv + script) != LUA_OK)
return 0;
lua_pushboolean(L, 1); /* signal no errors */
return 1;
}
LUA_API int lua_docompiledfile(lua_State *L, const char *filename)
{
try
{
if (luaL_loadfile(L, filename))
{
printf("error\n");
return LUA_ERRRUN;
}
lua_pcall(L, 0, 0, 0);
return LUA_OK;
}
catch(const std::exception &e)
{
global_glua_chain_api->throw_exception(L, THINKYOUNG_API_SIMPLE_ERROR, "error in load bytecode file, %s", e.what());
return LUA_ERRRUN;
}
}
LUA_API int lua_docompiled_bytestream(lua_State *L, void *stream_addr)
{
GluaModuleByteStreamP stream = (GluaModuleByteStreamP) stream_addr;
if (luaL_loadbufferx(L, stream->buff.data(), stream->buff.size(), "compiled_chunk", "binary"))
{
printf("error\n");
return LUA_ERRRUN;
}
lua_pcall(L, 0, 0, 0);
return LUA_OK;
}
static bool findloader_for_import_stream(lua_State *L, const char *name) {
int i;
luaL_Buffer msg; /* to build error message */
luaL_buffinit(L, &msg);
lua_getglobal(L, "package");
/* push 'package.searchers' to index 4 in the stack */
if (lua_getfield(L, -1, "searchers") != LUA_TTABLE)
luaL_error(L, "'package.searchers' must be a table");
lua_remove(L, 3);
/* iterate over available searchers to find a loader */
for (i = 1;; i++) {
if (lua_rawgeti(L, 3, i) == LUA_TNIL) { /* no more searchers? */
lua_pop(L, 1); /* remove nil */
luaL_pushresult(&msg); /* create error message */
luaL_error(L, "module '%s' not found:%s", name, lua_tostring(L, -1));
}
lua_pushstring(L, name);
lua_call(L, 1, 2); /* call it */
if (lua_isfunction(L, -2)) /* did it find a loader? */
return true; /* module loader found */
else if (lua_isstring(L, -2)) { /* searcher returned error message? */
lua_pop(L, 1); /* remove extra return */
luaL_addvalue(&msg); /* concatenate error message */
if (global_glua_chain_api->has_exception(L))
{
return false;
}
}
else
lua_pop(L, 2); /* remove both returns */
}
return false;
}
static bool findloader(lua_State *L, const char *name) {
return findloader_for_import_stream(L, name);
}
static bool findloader_for_import_contract(lua_State *L, const char *name) {
return findloader_for_import_stream(L, name);
}
int luaL_require_module(lua_State *L)
{
if (lua_gettop(L) < 1)
{
global_glua_chain_api->throw_exception(L, THINKYOUNG_API_SIMPLE_ERROR, "require need 1 argument of contract name");
return 0;
}
const char *name = luaL_checkstring(L, 1);
lua_settop(L, 1); /* _LOADED table will be at index 2 */
lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
lua_getfield(L, 2, name); /* _LOADED[name] */
if (lua_toboolean(L, -1)) /* is it there? */
return 1; /* package is already loaded */
/* else must load package */
lua_pop(L, 1); /* remove 'getfield' result */
bool loaderfound = findloader(L, name);
lua_pushstring(L, name); /* pass name as argument to module loader */
lua_insert(L, -2); /* name is 1st argument (before search data) */
lua_call(L, 2, 1); /* run loader to load module */
if (!lua_isnil(L, -1)) /* non-nil return? */
lua_setfield(L, 2, name); /* _LOADED[name] = returned value */
if (lua_getfield(L, 2, name) == LUA_TNIL) { /* module set no value? */
lua_pushboolean(L, 1); /* use true as result */
lua_pushvalue(L, -1); /* extra copy to be returned */
lua_setfield(L, 2, name); /* _LOADED[name] = true */
}
return 1;
}
struct GluaStorageValue;
struct GluaStorageValue lua_type_to_storage_value_type(lua_State *L, int index, size_t len);
// 包装后的合约的api函数
static int contract_api_wrapper_func(lua_State *L)
{
int api_func_index = lua_upvalueindex(1); // api func
const char *contract_id = lua_tostring(L, lua_upvalueindex(2));
// contract_id压栈
auto contract_id_stack = thinkyoung::lua::lib::get_using_contract_id_stack(L, true);
if (!contract_id_stack)
return 0;
contract_id_stack->push(contract_id);
lua_pushvalue(L, api_func_index);
auto args_count = lua_gettop(L) - 1;
for(int i=0;i<args_count;++i)
{
lua_pushvalue(L, 1 + i);
}
auto nresults = 1; // FIXME: 是否有返回值,1 or 0
lua_call(L, args_count, nresults);
// contract_id出栈
if (contract_id_stack->size() > 0)
contract_id_stack->pop();
return nresults;
}
// 包装合约的api函数
// args: apiFunc, contract_id, ret: wrapedApiFunc
static int contract_api_wrapper(lua_State *L)
{
// 获取合约id,加入upval/关联到这个closure
const char *contract_id = luaL_checkstring(L, 2);
lua_pushvalue(L, 1); // 压函数本身入栈
lua_pushstring(L, contract_id);
lua_pushcclosure(L, &contract_api_wrapper_func, 2);
return 1;
}
static bool contract_table_traverser_to_wrap_api(lua_State *L, void *ud)
{
if (!lua_isfunction(L, -1))
return true;
int contract_table_index = *((int*)ud);
const char *key = lua_tostring(L, -2);
lua_getfield(L, contract_table_index, "id");
const char *contract_id = lua_tostring(L, -1);
lua_pop(L, 1);
lua_pushcfunction(L, contract_api_wrapper);
lua_pushvalue(L, -2);
lua_pushstring(L, contract_id);
lua_call(L, 2, 1);
lua_setfield(L, contract_table_index, key);
return true;
}
static bool lua_get_contract_apis_direct(lua_State *L, GluaModuleByteStream *stream, char *error)
{
int *stopped_pointer = thinkyoung::lua::lib::get_lua_state_value(L, LUA_STATE_STOP_TO_RUN_IN_LVM_STATE_MAP_KEY).int_pointer_value;
if (nullptr != stopped_pointer && (*stopped_pointer) > 0)
return false;
intptr_t stream_p = (intptr_t)stream;
std::string name = std::string(STREAM_CONTRACT_PREFIX) + std::to_string(stream_p);
const char *contract_name = name.c_str();
lua_pushstring(L, name.c_str());
const char *filename = name.c_str();
lua_settop(L, 1); /* _LOADED table will be at index 2 */
lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
lua_getfield(L, 2, filename); /* _LOADED[name] */
/* else must load package */
lua_pop(L, 1); /* remove 'getfield' result */
if (!findloader_for_import_stream(L, filename))
return false;
lua_pushstring(L, filename); /* pass name as argument to module loader */
lua_insert(L, -2); /* name is 1st argument (before search data) */
lua_call(L, 2, 1); /* run loader to load module */
if (nullptr != stopped_pointer && (*stopped_pointer) > 0)
return false;
if (!lua_isnil(L, -1)) /* non-nil return? */
{
if (lua_istable(L, -1)) {
int it = lua_gettop(L);
lua_pushnil(L);
int apis_count = 0;
char *contract_apis[THINKYOUNG_CONTRACT_APIS_LIMIT];
memset(contract_apis, 0x0, sizeof(contract_apis));
std::set<std::string> contract_apis_set; // 用来记录有序的contract_apis集合
std::set<std::string> offline_contract_apis_set; // 用来记录有序的offline_contract_apis集合
while (lua_next(L, it))
{
if (!lua_isstring(L, -2))
continue;
char *key = (char *)lua_tostring(L, -2);
if (strcmp(key, "locals") == 0)
{
// save locals to LuaModuleStream
if (lua_istable(L, -1))
{
if (stream->offline_apis.size() > 0)
{
stream->offline_apis.clear();
}
size_t offline_apis_count;
try{
lua_len(L, -1);
offline_apis_count = (size_t)lua_tointegerx(L, -1, nullptr);
lua_pop(L, 1);
for (size_t i = 0; i < offline_apis_count; ++i)
{
lua_geti(L, -1, i + 1);
if (!lua_isstring(L, -1))
{
lua_pop(L, 1);
continue;
}
const char *api_name = luaL_checkstring(L, -1);
offline_contract_apis_set.insert(api_name);
lua_pop(L, 1);
}
stream->offline_apis.clear();
for(const auto &item : offline_contract_apis_set)
{
if (stream->offline_apis.size() >= CONTRACT_MAX_OFFLINE_API_COUNT)
break;
stream->offline_apis.push_back(item);
}
}
catch (...)
{
}
}
lua_pop(L, 1);
continue;
}
lua_pop(L, 1);
// store module info into thinkyoung, limit not too many apis
if (strlen(key) > THINKYOUNG_CONTRACT_API_NAME_MAX_LENGTH) {
global_glua_chain_api->throw_exception(L, THINKYOUNG_API_SIMPLE_ERROR, "contract module api name must be less than 1024 characters\n");
return false;
}
contract_apis_set.insert(key);
}
for(const auto &item : contract_apis_set)
{
contract_apis[apis_count] = (char*)malloc((item.length() + 1) * sizeof(char));
memset(contract_apis[apis_count], 0x0, (item.length() + 1) * sizeof(char));
memcpy(contract_apis[apis_count], item.c_str(), sizeof(char) * (item.length() + 1));
contract_apis[apis_count][item.length()] = '\0';
apis_count += 1;
}
// if the contract info stored in thinkyoung before, fetch and check whether the apis are the same. if not the same, error
/*char *stored_contract_apis[THINKYOUNG_CONTRACT_APIS_LIMIT];
int stored_contract_apis_count;*/
stream->contract_apis.clear();
for (auto i = 0; i < apis_count; ++i)
{
stream->contract_apis.push_back(contract_apis[i]);
}
// for (int i = 0; i < apis_count; ++i)
// {
// free(contract_apis[i]); // need free in all return statement
// }
// lua_pop(L, 1); // this line code will pop the module return result from stack
}
else {
const char *msg = "this thinkyoung contract not return a table";
lua_set_compile_error(L, msg);
global_glua_chain_api->throw_exception(L, THINKYOUNG_API_SIMPLE_ERROR, msg);
return false;
}
lua_fill_contract_info_for_use(L);
// set name of contract to contract module table
bool use_self_name = glua::util::starts_with(name, std::string(ADDRESS_CONTRACT_PREFIX)) || glua::util::starts_with(name, std::string(STREAM_CONTRACT_PREFIX));
lua_pushstring(L, use_self_name ? CURRENT_CONTRACT_NAME : name.c_str());
lua_setfield(L, -2, "name");
char contract_id[CONTRACT_ID_MAX_LENGTH] = "\0";
size_t contract_id_size = 0;
global_glua_chain_api->get_contract_address_by_name(L, thinkyoung::lua::lib::unwrap_any_contract_name(name.c_str()).c_str(), contract_id, &contract_id_size);
contract_id[CONTRACT_ID_MAX_LENGTH - 1] = '\0';
// lua_pushstring(L, CURRENT_CONTRACT_NAME);
lua_pushstring(L, contract_id);
lua_setfield(L, -2, "id");
// lua_setfield(L, 2, filename); /* _LOADED[name] = returned value */
}
else
{
const char *msg = "this thinkyoung contract not return a table";
lua_set_compile_error(L, msg);
global_glua_chain_api->throw_exception(L, THINKYOUNG_API_SIMPLE_ERROR, msg);
return false;
}
if (lua_getfield(L, 2, filename) == LUA_TNIL) { /* module set no value? */
lua_pushboolean(L, 1); /* use true as result */
lua_pushvalue(L, -1); /* extra copy to be returned */
lua_setfield(L, 2, filename); /* _LOADED[name] = true */
}
return true;
}
static int lua_get_contract_apis_cfunction(lua_State *L)
{
if (lua_gettop(L) < 1)
{
lua_pushboolean(L, false);
return 1;
}
GluaModuleByteStream *stream = (GluaModuleByteStream*)lua_touserdata(L, 1);
char *error = lua_gettop(L) > 1 ? (char *)lua_touserdata(L, 2) : nullptr;
auto result = lua_get_contract_apis_direct(L, stream, error);
lua_pushboolean(L, result);
return 1;
}
/**
* get contract apis in stream
*/
bool luaL_get_contract_apis(lua_State *L, GluaModuleByteStream *stream, char *error)
{
lua_pushcfunction(L, lua_get_contract_apis_cfunction);
lua_pushlightuserdata(L, stream);
if (nullptr != error)
lua_pushlightuserdata(L, error);
int args_count = nullptr != error ? 2 : 1;
lua_pcall(L, args_count, 1, 0);
if (lua_gettop(L) > 1)
{
auto result = lua_toboolean(L, -1);
lua_pop(L, 2);
return result > 0 ? true : false;
}
else
{
lua_pop(L, 1);
return false;
}
}
void lua_fill_contract_info_for_use(lua_State *L)
{
lua_newtable(L);
lua_setfield(L, -2, "_data");
lua_getglobal(L, "contract_mt");
lua_setmetatable(L, -2); // 设置contract的metatable为contract_mt
// contract.storage = {....}
lua_newtable(L); // {}
lua_setfield(L, -2, "storage"); //
lua_getfield(L, -1, "storage"); // {}
lua_pushvalue(L, -2); // {}, contract
lua_setfield(L, -2, "contract"); // {}
lua_getglobal(L, "thinkyoung"); // {}, thinkyoung
lua_pushvalue(L, -2); // {}, thinkyoung, {}
lua_getfield(L, -2, "storage_mt"); // {}, thinkyoung, {}, storage_mt
lua_setmetatable(L, -2); // {}, thinkyoung, {} 设置storage的metatable为storage_mt
lua_pop(L, 3);
}
static std::string unwrap_get_contract_address(std::string namestr)
{
std::string address;
std::stringstream ss(namestr.substr(strlen(ADDRESS_CONTRACT_PREFIX)));
ss >> address;
return address;
}
static GluaModuleByteStream *unwrap_get_contract_stream(std::string namestr)
{
intptr_t stream_p;
std::stringstream ss(namestr.substr(strlen(STREAM_CONTRACT_PREFIX)));
ss >> stream_p;
GluaModuleByteStream *stream = (GluaModuleByteStream*)stream_p;
return stream;
}
static std::string get_contract_name_using_in_lua(std::string namestr)
{
bool use_self_name = glua::util::starts_with(namestr, ADDRESS_CONTRACT_PREFIX)
|| glua::util::starts_with(namestr, STREAM_CONTRACT_PREFIX);
return use_self_name ? CURRENT_CONTRACT_NAME : thinkyoung::lua::lib::unwrap_any_contract_name(namestr.c_str());
}
static std::string get_contract_id_using_in_lua(lua_State *L, std::string namestr, bool is_pointer, bool is_stream)
{
if (is_pointer)
{
std::string address;
std::stringstream(namestr.substr(strlen(ADDRESS_CONTRACT_PREFIX))) >> address;
return address;
}
else if (!is_pointer && !is_stream)
{
char address[CONTRACT_ID_MAX_LENGTH];
memset(address, 0x0, sizeof(char) * CONTRACT_ID_MAX_LENGTH);
size_t address_len = 0;
global_glua_chain_api->get_contract_address_by_name(L, thinkyoung::lua::lib::unwrap_any_contract_name(namestr.c_str()).c_str(), address, &address_len);
address[CONTRACT_ID_MAX_LENGTH-1] = '\0';
return address;
}
else
{
auto name = thinkyoung::lua::lib::unwrap_any_contract_name(namestr.c_str());
char address[CONTRACT_ID_MAX_LENGTH];
memset(address, 0x0, sizeof(char) * CONTRACT_ID_MAX_LENGTH);
size_t address_len = 0;
global_glua_chain_api->get_contract_address_by_name(L, thinkyoung::lua::lib::unwrap_any_contract_name(name.c_str()).c_str(), address, &address_len);
address[CONTRACT_ID_MAX_LENGTH - 1] = '\0';
return address;
// return CURRENT_CONTRACT_NAME;
}
}
/************************************************************************/
/* FIXME import contract by contract id, need copy code from luaL_import_contract_module */
/************************************************************************/
int luaL_import_contract_module_from_address(lua_State *L)
{
if (lua_gettop(L) < 1)
{
global_glua_chain_api->throw_exception(L, THINKYOUNG_API_SIMPLE_ERROR, "import_contract_from_address need 1 argument of contract name");
return 0;
}
const char *contract_id = luaL_checkstring(L, 1);
if (!contract_id)
return 0;
const char *name = contract_id;
if (glua::util::ends_with(std::string(name), std::string(".lua"))
|| glua::util::ends_with(std::string(name), std::string(GLUA_SOURCE_FILE_EXTENTION_NAME))) {
global_glua_chain_api->throw_exception(L, THINKYOUNG_API_SIMPLE_ERROR, "this contract byte stream not matched with the info stored in thinkyoung api");
return 0;
}
std::string name_str;
name_str = std::string(ADDRESS_CONTRACT_PREFIX) + thinkyoung::lua::lib::unwrap_any_contract_name(contract_id);
name = name_str.c_str();
auto unwrap_name = thinkyoung::lua::lib::unwrap_any_contract_name(contract_id);
const char *filename = name;
lua_settop(L, 1); /* _LOADED table will be at index 2 */
lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
lua_getfield(L, 2, filename); /* _LOADED[name] */
if (lua_toboolean(L, -1)) /* is it there? */
return 1; /* package is already loaded */
/* else must load package */
lua_pop(L, 1); /* remove 'getfield' result */
size_t global_size_before = luaL_count_global_variables(L);
std::list<std::string> global_vars_before;
luaL_get_global_variables(L, &global_vars_before);
// check whether the contract existed
bool exists;
std::string namestr(name);
exists = global_glua_chain_api->check_contract_exist_by_address(L, contract_id);
if (!exists)
{
global_glua_chain_api->throw_exception(L, THINKYOUNG_API_SIMPLE_ERROR, "this contract not found");
return 0;
}
findloader_for_import_contract(L, name);
lua_pushstring(L, filename); /* pass name as argument to module loader */
lua_insert(L, -2); /* name is 1st argument (before search data) */
auto update_loaded_func = [&]() {
if (lua_getfield(L, 2, filename) == LUA_TNIL) { /* module set no value? */
lua_pushboolean(L, 1); /* use true as result */
lua_pushvalue(L, -1); /* extra copy to be returned */
lua_setfield(L, 2, filename); /* _LOADED[name] = true */
}
};
struct exit_scope_of_update_loaded
{
std::function<void(void)> _update_loaded_func;
exit_scope_of_update_loaded(std::function<void(void)> func) : _update_loaded_func(func) {}
~exit_scope_of_update_loaded(){
_update_loaded_func();
}
} exit_scope1(update_loaded_func);
lua_call(L, 2, 1); /* run loader to load module */
if (!lua_isnil(L, -1)) /* non-nil return? */
{
if (lua_istable(L, -1)) {
int it = lua_gettop(L);
lua_pushnil(L);
int apis_count = 0;
char *contract_apis[THINKYOUNG_CONTRACT_APIS_LIMIT];
memset(contract_apis, 0x0, THINKYOUNG_CONTRACT_APIS_LIMIT*sizeof(char*));
while (lua_next(L, it))
{
if (apis_count >= THINKYOUNG_CONTRACT_APIS_LIMIT)
{
lua_pop(L, 1);
break;
}
if (!lua_isstring(L, -2))
{
lua_pop(L, 1);
continue;
}
char *key = (char *)lua_tostring(L, -2);
lua_pop(L, 1);
// store module info into thinkyoung, limit not too many apis
if (strlen(key) > THINKYOUNG_CONTRACT_API_NAME_MAX_LENGTH) {
global_glua_chain_api->throw_exception(L, THINKYOUNG_API_SIMPLE_ERROR, "contract module api name must be less than %d characters", THINKYOUNG_CONTRACT_API_NAME_MAX_LENGTH);
thinkyoung::lua::lib::notify_lua_state_stop(L);
return 0;
}
if (strcmp(key, "locals") == 0)
continue;
contract_apis[apis_count] = (char*)malloc((strlen(key) + 1) * sizeof(char));
memset(contract_apis[apis_count], 0x0, (strlen(key) + 1) * sizeof(char));
if (!contract_apis[apis_count])
{
lmalloc_error(L);
thinkyoung::lua::lib::notify_lua_state_stop(L);
return 0;
}
memcpy(contract_apis[apis_count], key, sizeof(char) * (strlen(key) + 1));
contract_apis[apis_count][strlen(key)] = '\0';
apis_count += 1;
}
// if the contract info stored in thinkyoung before, fetch and check whether the apis are the same. if not the same, error
auto clear_stored_contract_info = [&]() {
// global_glua_chain_api->free_contract_info(L, unwrap_name.c_str(), stored_contract_apis, &stored_contract_apis_count);
};
std::string address = contract_id;
auto stored_contract_info = std::make_shared<GluaContractInfo>();
if (global_glua_chain_api->get_stored_contract_info_by_address(L, address.c_str(), stored_contract_info))
{
struct exit_scope_of_stored_contract_info
{
std::function<void(void)> _clear_stored_contract_info;
exit_scope_of_stored_contract_info(std::function<void(void)> clear_stored_contract_info)
: _clear_stored_contract_info(clear_stored_contract_info) {}
~exit_scope_of_stored_contract_info(){
_clear_stored_contract_info();
}
} exit_scope1(clear_stored_contract_info);
// found this contract stored in the thinkyoung api before
if (stored_contract_info->contract_apis.size() != apis_count)
{
char error_msg[LUA_COMPILE_ERROR_MAX_LENGTH];
snprintf(error_msg, LUA_COMPILE_ERROR_MAX_LENGTH - 1, "this contract byte stream not matched with the info stored in thinkyoung api, need %d apis but only found %d", stored_contract_info->contract_apis.size(), apis_count);
if (strlen(L->compile_error) < 1)
memcpy(L->compile_error, error_msg, LUA_COMPILE_ERROR_MAX_LENGTH);
global_glua_chain_api->throw_exception(L, THINKYOUNG_API_SIMPLE_ERROR, error_msg);
thinkyoung::lua::lib::notify_lua_state_stop(L);
return 0;
}
for (auto i = 0; i < apis_count; ++i)
{
auto a = stored_contract_info->contract_apis[i].c_str();
int matched = 0;
for (int j = 0; j < stored_contract_info->contract_apis.size(); ++j)
{
char *b = contract_apis[j];
if (!a || !b)
{
char error_msg[LUA_COMPILE_ERROR_MAX_LENGTH];
snprintf(error_msg, LUA_COMPILE_ERROR_MAX_LENGTH - 1, "empty contract api name");
if (strlen(L->compile_error) < 1)
memcpy(L->compile_error, error_msg, LUA_COMPILE_ERROR_MAX_LENGTH);
global_glua_chain_api->throw_exception(L, THINKYOUNG_API_SIMPLE_ERROR, error_msg);
return 0;
}
if (strcmp(a, b) == 0)
{
matched = 1;
break;
}
}
if (!matched)
{
char error_msg[LUA_COMPILE_ERROR_MAX_LENGTH];
snprintf(error_msg, LUA_COMPILE_ERROR_MAX_LENGTH - 1, "the contract api not match info stored in thinkyoung");
if (strlen(L->compile_error) < 1)
memcpy(L->compile_error, error_msg, LUA_COMPILE_ERROR_MAX_LENGTH);
global_glua_chain_api->throw_exception(L, THINKYOUNG_API_SIMPLE_ERROR, error_msg);
thinkyoung::lua::lib::notify_lua_state_stop(L);
return 0;
}
}
// check _G size whether change
size_t global_size_after = luaL_count_global_variables(L);
std::list<std::string> global_vars_after;
luaL_get_global_variables(L, &global_vars_after);
if (global_size_before != global_size_after || !glua::util::compare_string_list(global_vars_before, global_vars_after))
{
// check all global variables not changed, don't call code eg. ```_G['abc'] = nil; abc = 1;```
char error_msg[LUA_COMPILE_ERROR_MAX_LENGTH] = "\0";
/*
snprintf(error_msg, LUA_COMPILE_ERROR_MAX_LENGTH - 1, "contract can't use global variables");
if (strlen(L->compile_error) < 1)
memcpy(L->compile_error, error_msg, LUA_COMPILE_ERROR_MAX_LENGTH);
global_glua_chain_api->throw_exception(L, THINKYOUNG_API_SIMPLE_ERROR, error_msg);
*/
lcompile_error_set(L, error_msg, "contract can't use global variables");
thinkyoung::lua::lib::notify_lua_state_stop(L);
return 0;
}
}
else
{
char error_msg[LUA_COMPILE_ERROR_MAX_LENGTH] = "\0";
/*
snprintf(error_msg, LUA_COMPILE_ERROR_MAX_LENGTH - 1, "contract info not stored before");
if (strlen(L->compile_error) < 1)
memcpy(L->compile_error, error_msg, LUA_COMPILE_ERROR_MAX_LENGTH);
global_glua_chain_api->throw_exception(L, THINKYOUNG_API_SIMPLE_ERROR, error_msg);
*/
lcompile_error_set(L, error_msg, "contract info not stored before");
thinkyoung::lua::lib::notify_lua_state_stop(L);
return 0;
}
}
else {
char error_msg[LUA_COMPILE_ERROR_MAX_LENGTH] = "\0";
/*
snprintf(error_msg, LUA_COMPILE_ERROR_MAX_LENGTH - 1, "this thinkyoung contract not return a table");
if (strlen(L->compile_error) < 1)
memcpy(L->compile_error, error_msg, LUA_COMPILE_ERROR_MAX_LENGTH);
global_glua_chain_api->throw_exception(L, THINKYOUNG_API_SIMPLE_ERROR, error_msg);
*/
lcompile_error_set(L, error_msg, "this thinkyoung contract not return a table");
return 0;
}
lua_fill_contract_info_for_use(L);
// set name of contract to contract module table
lua_pushstring(L, get_contract_name_using_in_lua(namestr).c_str());
lua_setfield(L, -2, "name");
lua_pushstring(L, contract_id);
lua_setfield(L, -2, "id");
auto starting_contract_address = thinkyoung::lua::lib::get_starting_contract_address(L);
bool is_starting_contract = false;
if (starting_contract_address.length()>0)
{
if (strcmp(contract_id, starting_contract_address.c_str()) == 0)
is_starting_contract = true;
}
// 给合约中各api加上proxy,做pre/post操作,其中压栈合约ID
auto contract_table_index = lua_gettop(L);
luaL_traverse_table(L, contract_table_index, contract_table_traverser_to_wrap_api, &contract_table_index);
if (!is_starting_contract)
{
for(const auto &special_api_name : thinkyoung::lua::lib::contract_special_api_names)
{
lua_pushnil(L);
lua_setfield(L, -2, special_api_name.c_str());
}
}
lua_setfield(L, 2, filename); /* _LOADED[name] = returned value */
}
else
{
global_glua_chain_api->throw_exception(L, THINKYOUNG_API_SIMPLE_ERROR, "this thinkyoung contract not return a table");
return 0;
}
/*
if (lua_getfield(L, 2, filename) == LUA_TNIL) { // module set no value?
lua_pushboolean(L, 1); // use true as result
lua_pushvalue(L, -1); // extra copy to be returned
lua_setfield(L, 2, filename); // _LOADED[name] = true
}
*/
return 1;
}
/**
* import_contract function
* restrain name must be pure file name, with no '.lua' extension. And can load bytestream from thinkyoung api.
* try load bytestream first, then try write bytes to tmp file and then load the new file
*/
int luaL_import_contract_module(lua_State *L)
{
if (lua_gettop(L) < 1 || !lua_isstring(L, 1))
{
global_glua_chain_api->throw_exception(L, THINKYOUNG_API_SIMPLE_ERROR, "import_contract need 1 string argument of contract name");
return 0;
}
const char *origin_contract_name = luaL_checkstring(L, -1);
const char *name = origin_contract_name;
if (glua::util::ends_with(name, ".lua"), glua::util::ends_with(name, GLUA_SOURCE_FILE_EXTENTION_NAME)) {
global_glua_chain_api->throw_exception(L, THINKYOUNG_API_SIMPLE_ERROR, "this contract byte stream not matched with the info stored in thinkyoung api");
return 0;
}
bool is_pointer = glua::util::starts_with(name, ADDRESS_CONTRACT_PREFIX);
bool is_stream = glua::util::starts_with(name, STREAM_CONTRACT_PREFIX);
std::string name_str;
if (!is_pointer && !is_stream)
{
name_str = thinkyoung::lua::lib::wrap_contract_name(origin_contract_name);
name = name_str.c_str();
}
auto unwrap_name = thinkyoung::lua::lib::unwrap_any_contract_name(origin_contract_name);
const char *filename = name;
lua_settop(L, 1); /* _LOADED table will be at index 2 */
lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
lua_getfield(L, 2, filename); /* _LOADED[name] */
if (lua_toboolean(L, -1)) /* is it there? */
return 1; /* package is already loaded */
/* else must load package */
lua_pop(L, 1); /* remove 'getfield' result */
size_t global_size_before = luaL_count_global_variables(L);
std::list<std::string> global_vars_before;
luaL_get_global_variables(L, &global_vars_before);
// check whether the contract existed
bool exists;
std::string namestr(name);
if (is_pointer)
{
std::string address = unwrap_get_contract_address(namestr);
exists = global_glua_chain_api->check_contract_exist_by_address(L, address.c_str());
}
else if (is_stream)
{
GluaModuleByteStream *stream = unwrap_get_contract_stream(namestr);
exists = true;
}
else
{
exists = global_glua_chain_api->check_contract_exist(L, origin_contract_name);
}
if (!exists)
{
global_glua_chain_api->throw_exception(L, THINKYOUNG_API_SIMPLE_ERROR, "this contract not found");
return 0;
}
if (!is_stream)
findloader_for_import_contract(L, name);
else
findloader_for_import_stream(L, filename);
lua_pushstring(L, filename); /* pass name as argument to module loader */
lua_insert(L, -2); /* name is 1st argument (before search data) */
auto update_loaded_func = [&]() {
if (lua_getfield(L, 2, filename) == LUA_TNIL) { /* module set no value? */
lua_pushboolean(L, 1); /* use true as result */
lua_pushvalue(L, -1); /* extra copy to be returned */
lua_setfield(L, 2, filename); /* _LOADED[name] = true */
}
};
struct exit_scope_of_update_loaded
{
std::function<void(void)> _update_loaded_func;
exit_scope_of_update_loaded(std::function<void(void)> func) : _update_loaded_func(func) {}
~exit_scope_of_update_loaded(){
_update_loaded_func();
}
} exit_scope1(update_loaded_func);
lua_call(L, 2, 1); /* run loader to load module */
if (!lua_isnil(L, -1)) /* non-nil return? */
{
if (lua_istable(L, -1)) {
int it = lua_gettop(L);
lua_pushnil(L);
int apis_count = 0;
char *contract_apis[THINKYOUNG_CONTRACT_APIS_LIMIT];
while (lua_next(L, it))
{
if (apis_count >= THINKYOUNG_CONTRACT_APIS_LIMIT)
{
lua_pop(L, 1);
break;
}
if (!lua_isstring(L, -2))
{
lua_pop(L, 1);
continue;
}
char *key = (char *)lua_tostring(L, -2);
if (strcmp(key, "locals") == 0)
{
lua_pop(L, 1);
continue;
}
lua_pop(L, 1);
// store module info into thinkyoung, limit not too many apis
if (strlen(key) > THINKYOUNG_CONTRACT_API_NAME_MAX_LENGTH) {
global_glua_chain_api->throw_exception(L, THINKYOUNG_API_SIMPLE_ERROR, "contract module api name must be less than 1024 characters\n");
thinkyoung::lua::lib::notify_lua_state_stop(L);
return 0;
}
contract_apis[apis_count] = (char*)malloc((strlen(key) + 1) * sizeof(char));
memset(contract_apis[apis_count], 0x0, (strlen(key) + 1) * sizeof(char));
memcpy(contract_apis[apis_count], key, sizeof(char) * (strlen(key) + 1));
contract_apis[apis_count][strlen(key)] = '\0';
apis_count += 1;
}
// if the contract info stored in thinkyoung before, fetch and check whether the apis are the same. if not the same, error
auto stored_contract_info = std::make_shared<GluaContractInfo>();
auto clear_stored_contract_info = [&]() {
//if (!is_stream)
// global_glua_chain_api->free_contract_info(L, unwrap_name.c_str(), stored_contract_apis, &stored_contract_apis_count);
};
std::string address = unwrap_name;
if (!is_pointer && !is_stream)
{
char address_chars[50];
size_t address_len = 0;
global_glua_chain_api->get_contract_address_by_name(L, unwrap_name.c_str(), address_chars, &address_len);
if (address_len > 0)
address = std::string(address_chars);
}
if (global_glua_chain_api->get_stored_contract_info_by_address(L, address.c_str(), stored_contract_info))
{
struct exit_scope_of_stored_contract_info
{
std::function<void(void)> _clear_stored_contract_info;
exit_scope_of_stored_contract_info(std::function<void(void)> clear_stored_contract_info)
: _clear_stored_contract_info(clear_stored_contract_info) {}
~exit_scope_of_stored_contract_info(){
_clear_stored_contract_info();
}
} exit_scope1(clear_stored_contract_info);
// found this contract stored in the thinkyoung api before
if (stored_contract_info->contract_apis.size() != apis_count)
{
global_glua_chain_api->throw_exception(L, THINKYOUNG_API_SIMPLE_ERROR, "this contract byte stream not matched with the info stored in thinkyoung api");
thinkyoung::lua::lib::notify_lua_state_stop(L);
return 0;
}
for (auto i = 0; i < apis_count; ++i)
{
auto a = stored_contract_info->contract_apis[i].c_str();
int matched = 0;
for (int j = 0; j < stored_contract_info->contract_apis.size(); ++j)
{
char *b = contract_apis[j];
if (nullptr == a || nullptr == b)
{
global_glua_chain_api->throw_exception(L, THINKYOUNG_API_SIMPLE_ERROR, "empty contract api name");
return 0;
}
if (strcmp(a, b) == 0)
{
matched = 1;
break;
}
}
if (!matched)
{
global_glua_chain_api->throw_exception(L, THINKYOUNG_API_SIMPLE_ERROR, "the contract api not match info stored in thinkyoung");
thinkyoung::lua::lib::notify_lua_state_stop(L);
return 0;
}
}
// check _G size whether change
size_t global_size_after = luaL_count_global_variables(L);
std::list<std::string> global_vars_after;
luaL_get_global_variables(L, &global_vars_after);
if (global_size_before != global_size_after || !glua::util::compare_string_list(global_vars_before, global_vars_after))
{
// check all global variables not changed, don't call code eg. ```_G['abc'] = nil; abc = 1;```
global_glua_chain_api->throw_exception(L, THINKYOUNG_API_SIMPLE_ERROR, "contract can't use global variables");
thinkyoung::lua::lib::notify_lua_state_stop(L);
return 0;
}
}
else
{
global_glua_chain_api->throw_exception(L, THINKYOUNG_API_SIMPLE_ERROR, "contract info not stored before");
thinkyoung::lua::lib::notify_lua_state_stop(L);
return 0;
}
}
else {
global_glua_chain_api->throw_exception(L, THINKYOUNG_API_SIMPLE_ERROR, "this thinkyoung contract not return a table");
return 0;
}
lua_fill_contract_info_for_use(L);
// set name of contract to contract module table
lua_pushstring(L, get_contract_name_using_in_lua(namestr).c_str());
lua_setfield(L, -2, "name");
auto contract_id = get_contract_id_using_in_lua(L, namestr, is_pointer, is_stream);
lua_pushstring(L, contract_id.c_str());
lua_setfield(L, -2, "id");
// 只有源头合约保留合约的特殊API方法,引用其他合约不能调用这几个函数,import时去除
auto starting_contract_address = thinkyoung::lua::lib::get_starting_contract_address(L);
bool is_starting_contract = false;
if (starting_contract_address.length() > 0)
{
if (strcmp(get_contract_id_using_in_lua(L, namestr, is_pointer, is_stream).c_str(),
starting_contract_address.c_str()) == 0)
is_starting_contract = true;
}
if (!is_starting_contract)
{
for(const auto &api_name : thinkyoung::lua::lib::contract_special_api_names)
{
lua_pushnil(L);
lua_setfield(L, -2, api_name.c_str());
lua_pushstring(L, api_name.c_str());
lua_pushnil(L);
lua_rawset(L, -3);
}
}
// 给合约中各api加上proxy,做pre/post操作,其中压栈合约ID
auto contract_table_index = lua_gettop(L);
luaL_traverse_table(L, contract_table_index, contract_table_traverser_to_wrap_api, &contract_table_index);
lua_setfield(L, 2, filename); /* _LOADED[name] = returned value */
}
else
{
global_glua_chain_api->throw_exception(L, THINKYOUNG_API_SIMPLE_ERROR, "this thinkyoung contract not return a table");
return 0;
}
/*
if (lua_getfield(L, 2, filename) == LUA_TNIL) { // module set no value?
lua_pushboolean(L, 1); // use true as result
lua_pushvalue(L, -1); // extra copy to be returned
lua_setfield(L, 2, filename); // _LOADED[name] = true
}
*/
return 1;
}
static int lua_real_execute_contract_api(lua_State *L
, const char *contract_name, const char *api_name, const char *arg1
)
{
/*
if (lua_gettop(L) < 2)
return 0;
const char *contract_name = luaL_checkstring(L, 1);
const char *api_name = luaL_checkstring(L, 2);
const char *arg1 = lua_gettop(L)>2 && lua_isstring(L, 3) ? luaL_checkstring(L, 3) : nullptr;
*/
std::string arg1_str = arg1 ? std::string(arg1) : ""; // 这里单独保存一份是因为arg1,可能栈上数据哪里被pop了
// FIXME
if (!(glua::util::starts_with(contract_name, STREAM_CONTRACT_PREFIX)
|| glua::util::starts_with(contract_name, ADDRESS_CONTRACT_PREFIX))
&& !global_glua_chain_api->check_contract_exist(L, contract_name))
{
global_glua_chain_api->throw_exception(L, THINKYOUNG_API_SIMPLE_ERROR, "can't find this contract");
lua_pushinteger(L, LUA_ERRRUN);
return 1;
}
bool is_address = glua::util::starts_with(contract_name, ADDRESS_CONTRACT_PREFIX);
char address[CONTRACT_ID_MAX_LENGTH + 1] = "\0";
size_t address_size = 0;
std::string wrapper_contract_name_str = thinkyoung::lua::lib::wrap_contract_name(contract_name);
std::string unwrapper_name = thinkyoung::lua::lib::unwrap_any_contract_name(contract_name);
if (!is_address)
global_glua_chain_api->get_contract_address_by_name(L, unwrapper_name.c_str(), address, &address_size);
else
{
strncpy(address, unwrapper_name.c_str(), CONTRACT_ID_MAX_LENGTH);
address_size = unwrapper_name.length();
address[address_size] = '\0';
}
// std::stringstream codess;
// codess << "import_contract '" << contract_name << "'";
// luaL_dostring(L, codess.str().c_str());
auto saved_out = L->out;
auto saved_err = L->err;
L->out = nullptr;
L->err = nullptr;
lua_pushstring(L, contract_name);
std::string api_name_str(api_name);
luaL_import_contract_module(L); // FIXME: searcher_Lua添加了时, 这里好像内存越界,改动了api_name, pushnexttemplate这个函数好像有问题
lua_settop(L, 1); /* _LOADED table will be at index 2 */
lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
lua_getfield(L, 2, wrapper_contract_name_str.c_str()); /* _LOADED[name] */
L->out = saved_out;
L->err = saved_err;
if (!lua_toboolean(L, -1)) /* is it there? */
{
global_glua_chain_api->throw_exception(L, THINKYOUNG_API_SIMPLE_ERROR, "need load contract before execute contract api");
lua_pushinteger(L, LUA_ERRRUN);
return 1;
}
if (!lua_istable(L, -1))
{
lua_pushinteger(L, LUA_ERRRUN);
return 1;
}
bool is_self = glua::util::starts_with(contract_name, STREAM_CONTRACT_PREFIX)
|| glua::util::starts_with(contract_name, ADDRESS_CONTRACT_PREFIX);
lua_fill_contract_info_for_use(L);
lua_pushstring(L, is_self ? CURRENT_CONTRACT_NAME : contract_name);
lua_setfield(L, -2, "name");
lua_pushstring(L, address);
lua_setfield(L, -2, "id");
for (const auto &special_api_name : thinkyoung::lua::lib::contract_special_api_names)
{
if (special_api_name != api_name_str)
{
lua_pushnil(L);
lua_setfield(L, -2, special_api_name.c_str());
}
}
lua_getfield(L, -1, api_name_str.c_str());
if (lua_isfunction(L, -1))
{
lua_pushvalue(L, -2); // push self
//if (nullptr != arg1)
// lua_pushstring(L, arg1);
if (glua::util::vector_contains(thinkyoung::lua::lib::contract_int_argument_special_api_names, api_name_str))
{
std::stringstream arg_ss;
arg_ss << arg1_str;
lua_Integer arg1_int = 0;
arg_ss >> arg1_int;
lua_pushinteger(L, arg1_int);
}
else
{
lua_pushstring(L, arg1_str.c_str());
}
// lua_pcall(L, nullptr != arg1 ? 2 : 1, 1, 0);
lua_pcall(L, 2, 1, 0);
//if (nullptr != arg1)
// lua_pop(L, 1);
lua_pop(L, 1);
lua_pop(L, 1); // pop self
} else
{
global_glua_chain_api->throw_exception(L, THINKYOUNG_API_SIMPLE_ERROR, "Can't find api %s in this contract", api_name_str.c_str());
lua_pop(L, 1);
return 0;
}
lua_pop(L, 1);
lua_pushinteger(L, LUA_OK);
return 1;
}
LUA_API int lua_execute_contract_api(lua_State *L, const char *contract_name,
const char *api_name, const char *arg1, std::string *result_json_string)
{
auto contract_address = thinkyoung::lua::lib::malloc_managed_string(L, CONTRACT_ID_MAX_LENGTH + 1);
memset(contract_address, 0x0, CONTRACT_ID_MAX_LENGTH + 1);
size_t address_size = 0;
global_glua_chain_api->get_contract_address_by_name(L, contract_name, contract_address, &address_size);
if (address_size > 0)
{
GluaStateValue value;
value.string_value = contract_address;
thinkyoung::lua::lib::set_lua_state_value(L, STARTING_CONTRACT_ADDRESS, value, LUA_STATE_VALUE_STRING);
}
lua_createtable(L, 0, 0);
lua_setglobal(L, "last_return");
/*
lua_pushcfunction(L, lua_real_execute_contract_api);
lua_pushstring(L, contract_name);
lua_pushstring(L, api_name);
if (nullptr != arg1)
lua_pushstring(L, arg1);
// FIXME: 这里看能不能不需要这样调用而是直接调用
int status = lua_pcall(L, nullptr != arg1 ? 3 : 2, 1, 0);
*/
int status = lua_real_execute_contract_api(L, contract_name, api_name, arg1);
if (lua_gettop(L) < 1)
return LUA_ERRRUN;
int result = lua_toboolean(L, -1);
if (result>0 && result_json_string)
{
// FIXME
lua_getglobal(L, "last_return");
auto last_return_value_json = luaL_tojsonstring(L, -1, nullptr);
auto last_return_value_json_string = std::string(last_return_value_json);
lua_pop(L, 1);
*result_json_string = last_return_value_json_string;
}
if(result)
result = luaL_commit_storage_changes(L);
return result > 0 ? LUA_OK : LUA_ERRRUN;
}
LUA_API int lua_execute_contract_api_by_address(lua_State *L, const char *address,
const char *api_name, const char *arg1, std::string *result_json_string)
{
std::string name = std::string(ADDRESS_CONTRACT_PREFIX) + std::string(address);
return lua_execute_contract_api(L, name.c_str(), api_name, arg1, result_json_string);
}
LUA_API int lua_execute_contract_api_by_stream(lua_State *L, GluaModuleByteStream *stream,
const char *api_name, const char *arg1, std::string *result_json_string)
{
intptr_t stream_p = (intptr_t)stream;
std::string name = std::string(STREAM_CONTRACT_PREFIX) + std::to_string(stream_p);
return lua_execute_contract_api(L, name.c_str(), api_name, arg1, result_json_string);
}
std::shared_ptr<GluaModuleByteStream> lua_common_open_contract(lua_State *L, const char *name, char *error)
{
std::string namestr(name);
if (glua::util::starts_with(namestr, ADDRESS_CONTRACT_PREFIX))
{
std::string pointer_str = namestr.substr(strlen(ADDRESS_CONTRACT_PREFIX), namestr.length() - strlen(ADDRESS_CONTRACT_PREFIX));
std::string address;
std::stringstream(pointer_str) >> address;
auto stream = global_glua_chain_api->open_contract_by_address(L, address.c_str());
if (stream && stream->contract_level != CONTRACT_LEVEL_FOREVER && (stream->contract_name.length() < 1 || stream->contract_state == CONTRACT_STATE_DELETED))
{
auto start_contract_address = thinkyoung::lua::lib::get_starting_contract_address(L);
if (start_contract_address.length()>0 && stream->contract_name.length() < 1 && std::string(address) == start_contract_address)
{
return stream;
}
lerror_set(L, error, "only active and upgraded contract %s can be imported by others", namestr.c_str());
return nullptr;
}
else
return stream;
}
else if (glua::util::starts_with(namestr, STREAM_CONTRACT_PREFIX))
{
std::string p_str = namestr.substr(strlen(STREAM_CONTRACT_PREFIX), namestr.length() - strlen(STREAM_CONTRACT_PREFIX));
intptr_t p;
std::stringstream(p_str) >> p;
auto stream = std::make_shared<GluaModuleByteStream>(*(GluaModuleByteStream*)p);
return stream;
}
else
{
return global_glua_chain_api->open_contract(L, name);
}
}
LUALIB_API bool luaL_is_bytecode_file(lua_State *L, const char *filename)
{
LoadF lf;
int c;
bool result = false;
if (filename == nullptr) {
lua_pushliteral(L, "=stdin");
lf.f = stdin;
}
else {
lf.f = fopen(filename, "r");
if (lf.f == nullptr) return false;
}
if (skipcomment(&lf, &c)) /* read initial portion */
lf.buff[lf.n++] = '\n'; /* add line to correct line numbers */
if (c == LUA_SIGNATURE[0] && filename) { /* binary file? */
result = true;
}
if (filename)
fclose(lf.f);
return result;
}
LUALIB_API int luaL_loadfilex(lua_State *L, const char *filename,
const char *mode) {
LoadF lf;
int status, readstatus;
int c;
int fnameindex = lua_gettop(L) + 1; /* index of filename on the stack */
if (filename == nullptr) {
lua_pushliteral(L, "=stdin");
lf.f = stdin;
}
else {
lua_pushfstring(L, "@%s", filename);
lf.f = fopen(filename, "r");
if (lf.f == nullptr) return errfile(L, "open", fnameindex);
}
if (skipcomment(&lf, &c)) /* read initial portion */
lf.buff[lf.n++] = '\n'; /* add line to correct line numbers */
if (c == LUA_SIGNATURE[0] && filename) { /* binary file? */
lf.f = freopen(filename, "rb", lf.f); /* reopen in binary mode */
if (lf.f == nullptr) return errfile(L, "reopen", fnameindex);
skipcomment(&lf, &c); /* re-read initial portion */
}
if (c != EOF)
lf.buff[lf.n++] = c; /* 'c' is the first character of the stream */
status = lua_load(L, getF, &lf, lua_tostring(L, -1), mode);
readstatus = ferror(lf.f);
if (filename) fclose(lf.f); /* close file (even in case of errors) */
if (readstatus) {
lua_settop(L, fnameindex); /* ignore results from 'lua_load' */
return errfile(L, "read", fnameindex);
}
lua_remove(L, fnameindex);
return status;
}
static int writer(lua_State* L, const void* p, size_t size, void* u)
{
UNUSED(L);
int status = (fwrite(p, size, 1, (FILE*)u) != 1) && (size != 0);
return status;
}
static int writer_to_stream(lua_State *L, const void *p, size_t size, void *u)
{
UNUSED(L);
GluaModuleByteStreamP stream = (GluaModuleByteStreamP) u;
if (!stream)
return 1;
auto old_buff_size = stream->buff.size();
stream->buff.resize(old_buff_size + size);
memcpy(stream->buff.data() + old_buff_size, p, size);
return 0;
}
static int lua_compilefile_preload(lua_State *L, LoadF &lf, const char *filename, char *error,
struct LuaCompileFilePreloadResult *result, bool use_type_check = false, GluaModuleByteStreamP stream = nullptr, bool is_contract = false)
{
int status, readstatus;
int c;
int fnameindex = lua_gettop(L) + 1;
auto using_filename = filename;
global_glua_chain_api->clear_exceptions(L);
auto code = thinkyoung::lua::lib::pre_modify_lua_source_code(L, filename, error, nullptr, use_type_check, stream, is_contract);
if (global_glua_chain_api->has_exception(L))
{
lcompile_error_set(L, error, "compile error");
return LUA_ERRRUN;
}
auto tf = std::tmpfile();
if (!tf)
{
lerror_set(L, error, "can't create tmpfile");
return LUA_ERRRUN;
}
fwrite(code.c_str(), sizeof(char), code.length(), tf);
// using_filename = using_filename_str.c_str();
lua_pushfstring(L, "@%s", filename);
// lf.f = fopen(using_filename, "r");
fseek(tf, 0, SEEK_SET);
lf.f = tf;
if (lf.f == nullptr)
{
lcompile_error_set(L, error, "Can't open file %s", using_filename);
return errfile(L, "open", 1);
}
if (skipcomment(&lf, &c)) // read initial portion
lf.buff[lf.n++] = '\n'; // add line to correct line numbers
if (c == LUA_SIGNATURE[0] && using_filename) { // binary file?
lf.f = freopen(using_filename, "rb", lf.f); // reopen in binary mode
if (lf.f == nullptr) return errfile(L, "reopen", 1);
skipcomment(&lf, &c); // re-read initial portion
}
if (c != EOF)
lf.buff[lf.n++] = c; // 'c' is the first character of the stream
const char *chunk_name = lua_tostring(L, -1);
result->chunk_name = chunk_name;
auto saved_out = L->out;
auto saved_err = L->err;
L->out = nullptr;
L->err = nullptr;
status = lua_load(L, getF, &lf, chunk_name, nullptr);
L->out = saved_out;
L->err = saved_err;
if (status != 0)
{
// if (using_filename) fclose(lf.f);
if (lf.f) fclose(lf.f);
const char *error_str = "parse thinkyoung lua code error";
if (strlen(L->compile_error) > 0)
error_str = L->compile_error;
if (error)
strncpy(error, error_str, LUA_COMPILE_ERROR_MAX_LENGTH);
global_glua_chain_api->throw_exception(L, THINKYOUNG_API_PARSER_ERROR, error_str);
// lcompile_error_set(L, error, "parse thinkyoung lua code error");
return LUA_ERRFILE;
}
readstatus = ferror(lf.f);
// if (using_filename) fclose(lf.f); /* close file (even in case of errors) */
if (lf.f) fclose(lf.f);
if (readstatus) {
lua_settop(L, fnameindex); /* ignore results from 'lua_load' */
int errresult = errfile(L, "read", fnameindex);
return errresult;
}
lua_remove(L, fnameindex);
return LUA_OK;
}
LUA_API int luaL_compilefilex(const char *filename, FILE *out_file, char *error, bool is_contract)
{
thinkyoung::lua::lib::GluaStateScope scope;
lua_State* L = scope.L();
LoadF lf;
struct LuaCompileFilePreloadResult pre_result;
int preload_status = lua_compilefile_preload(L, lf, filename, error, &pre_result, false, nullptr, is_contract);
if (preload_status != LUA_OK)
return preload_status;
int result_status = lua_compile(L, getF, &lf, pre_result.chunk_name, "text", writer, out_file);
return result_status;
}
/**
* copied code from luaL_compilefilex
*/
LUA_API int luaL_compilefile(const char *filename, const char *out_filename, char *error, bool use_type_check, bool is_contract)
{
thinkyoung::lua::lib::GluaStateScope scope;
lua_State* L = scope.L();
LoadF lf;
struct LuaCompileFilePreloadResult pre_result;
int preload_status = lua_compilefile_preload(L, lf, filename, error, &pre_result, use_type_check, nullptr, is_contract);
if (preload_status != LUA_OK)
return preload_status;
int result_status = lua_compilex(L, getF, &lf, pre_result.chunk_name, "text", writer, out_filename);
lcompile_error_get(L, error);
return result_status;
}
LUA_API int luaL_compilefile_to_stream(lua_State *L, const char *filename,
GluaModuleByteStreamP stream, char *error, bool use_type_check, bool is_contract)
{
LoadF lf;
struct LuaCompileFilePreloadResult pre_result;
int preload_status = lua_compilefile_preload(L, lf, filename, error, &pre_result, use_type_check, stream, is_contract);
if (preload_status != LUA_OK)
return preload_status;
if (global_glua_chain_api->has_exception(L))
{
return LUA_ERRRUN;
}
int status = lua_compile_to_stream(L, getF, &lf, pre_result.chunk_name, "text", writer_to_stream, stream);
stream->is_bytes = true;
lcompile_error_get(L, error);
return status;
}
typedef struct LoadS {
const char *s;
size_t size;
} LoadS;
static const char *getS(lua_State *L, void *ud, size_t *size) {
LoadS *ls = (LoadS *)ud;
(void)L; /* not used */
if (ls->size == 0) return nullptr;
*size = ls->size;
ls->size = 0;
return ls->s;
}
LUALIB_API int luaL_loadbufferx(lua_State *L, const char *buff, size_t size,
const char *name, const char *mode) {
LoadS ls;
ls.s = buff;
ls.size = size;
return lua_load(L, getS, &ls, name, mode);
}
LUALIB_API int luaL_loadbufferx_with_check(lua_State *L, const char *buff, size_t size,
const char *name, const char *mode, const int check_type) {
LoadS ls;
ls.s = buff;
ls.size = size;
return lua_load_with_check(L, getS, &ls, name, mode, check_type);
}
LUALIB_API int luaL_loadstring(lua_State *L, const char *s) {
return luaL_loadbuffer(L, s, strlen(s), s);
}
/* }====================================================== */
LUALIB_API int luaL_getmetafield(lua_State *L, int obj, const char *event) {
if (!lua_getmetatable(L, obj)) /* no metatable? */
return LUA_TNIL;
else {
int tt;
lua_pushstring(L, event);
tt = lua_rawget(L, -2);
if (tt == LUA_TNIL) /* is metafield nil? */
lua_pop(L, 2); /* remove metatable and metafield */
else
lua_remove(L, -2); /* remove only metatable */
return tt; /* return metafield type */
}
}
LUALIB_API int luaL_callmeta(lua_State *L, int obj, const char *event) {
obj = lua_absindex(L, obj);
if (luaL_getmetafield(L, obj, event) == LUA_TNIL) /* no metafield? */
return 0;
lua_pushvalue(L, obj);
lua_call(L, 1, 1);
return 1;
}
LUALIB_API lua_Integer luaL_len(lua_State *L, int idx) {
lua_Integer l;
int isnum;
lua_len(L, idx);
l = lua_tointegerx(L, -1, &isnum);
if (!isnum)
luaL_error(L, "object length is not an integer");
lua_pop(L, 1); /* remove object */
return l;
}
LUALIB_API const char *luaL_tolstring(lua_State *L, int idx, size_t *len) {
if (!luaL_callmeta(L, idx, "__tostring")) { /* no metafield? */
switch (lua_type(L, idx)) {
case LUA_TNUMBER: {
if (lua_isinteger(L, idx))
{
auto value = lua_tointeger(L, idx);
std::string s = std::to_string(value);
lua_pushfstring(L, "%s", s.c_str());
}
else {
auto value = lua_tonumber(L, idx);
std::string s = std::to_string(value);
lua_pushfstring(L, "%s", s.c_str());
}
break;
}
case LUA_TSTRING:
lua_pushvalue(L, idx);
break;
case LUA_TBOOLEAN:
lua_pushstring(L, (lua_toboolean(L, idx) ? "true" : "false"));
break;
case LUA_TNIL:
lua_pushliteral(L, "nil");
break;
default:
auto value_typename = luaL_typename(L, idx);
lua_pushfstring(L, "%s: %d", value_typename,
0);
//lua_pushfstring(L, "%s: %p", luaL_typename(L, idx),
// lua_topointer(L, idx));
break;
}
}
return lua_tolstring(L, -1, len);
}
void free_lua_table_map(lua_State *L, GluaTableMapP map)
{
// map->~GluaTableMap();
// lua_free(L, map);
// delete map; // TODO: free recur
}
GluaTableMapP luaL_create_lua_table_map_in_memory_pool(lua_State *L)
{
auto lua_table_map_list_p = thinkyoung::lua::lib::get_lua_state_value(L, LUA_TABLE_MAP_LIST_STATE_MAP_KEY).pointer_value;
if (nullptr == lua_table_map_list_p)
{
lua_table_map_list_p = (void*)new std::list<GluaTableMapP>();
if (nullptr == lua_table_map_list_p)
{
exit(1);
}
GluaStateValue value;
value.pointer_value = lua_table_map_list_p;
thinkyoung::lua::lib::set_lua_state_value(L, LUA_TABLE_MAP_LIST_STATE_MAP_KEY, value, LUA_STATE_VALUE_POINTER);
}
//auto p = (GluaTableMapP)lua_malloc(L, sizeof(GluaTableMap));
auto p = new GluaTableMap();
if (nullptr == p)
{
global_glua_chain_api->throw_exception(L, THINKYOUNG_API_SIMPLE_ERROR, "out of memory");
thinkyoung::lua::lib::notify_lua_state_stop(L);
return nullptr;
}
// new(p)GluaTableMap();
auto list_p = (std::list<GluaTableMapP>*)lua_table_map_list_p;
list_p->push_back(p);
return p;
}
/**
* read lua table to hashmap
*/
GluaTableMapP lua_table_to_map_with_nested(lua_State *L, int index, std::list<const void*> &jsons, size_t recur_depth)
{
if (index > lua_gettop(L))
return nullptr;
if (!lua_istable(L, index))
return nullptr;
GluaTableMapP map = luaL_create_lua_table_map_in_memory_pool(L);
luaL_traverse_table_with_nested(L, index, lua_table_to_map_traverser_with_nested, map, jsons, recur_depth);
return map;
}
struct GluaStorageValue lua_type_to_storage_value_type_with_nested(lua_State *L, int index, size_t len, std::list<const void *> &jsons, size_t recur_depth)
{
struct GluaStorageValue storage_value;
if (index > lua_gettop(L))
{
storage_value.type = thinkyoung::blockchain::StorageValueTypes::storage_value_not_support;
storage_value.value.int_value = 0;
return storage_value;
}
if(recur_depth>LUA_MAP_TRAVERSER_MAX_DEPTH)
{
storage_value.type = thinkyoung::blockchain::StorageValueTypes::storage_value_null;
storage_value.value.int_value = 0;
return storage_value;
}
switch (lua_type(L, index))
{
case LUA_TNIL:
storage_value.type = thinkyoung::blockchain::StorageValueTypes::storage_value_null;
storage_value.value.int_value = 0;
return storage_value;
case LUA_TBOOLEAN:
storage_value.type = thinkyoung::blockchain::StorageValueTypes::storage_value_bool;
storage_value.value.bool_value = BOOL_VAL(lua_toboolean(L, index));
return storage_value;
case LUA_TNUMBER:
if (lua_isinteger(L, index))
{
storage_value.type = thinkyoung::blockchain::StorageValueTypes::storage_value_int;
storage_value.value.int_value = (lua_Integer)lua_tointeger(L, index);
return storage_value;
}
storage_value.type = thinkyoung::blockchain::StorageValueTypes::storage_value_number;
storage_value.value.number_value = lua_tonumber(L, index);
return storage_value;
case LUA_TSTRING:
storage_value.type = thinkyoung::blockchain::StorageValueTypes::storage_value_string;
storage_value.value.string_value = const_cast<char*>(lua_tostring(L, index));
return storage_value;
case LUA_TTABLE:
try{
lua_len(L, index);
}
catch (...)
{
storage_value.type = thinkyoung::blockchain::StorageValueTypes::storage_value_null;
storage_value.value.int_value = 0;
return storage_value;
}
len = (size_t)lua_tointegerx(L, -1, nullptr);
lua_pop(L, 1);
if(len < 0 || len > INT32_MAX)
{
// too big table
storage_value.type = thinkyoung::blockchain::StorageValueTypes::storage_value_null;
storage_value.value.int_value = 0;
return storage_value;
}
// FIXME: 根据子项类型修改
storage_value.type = thinkyoung::blockchain::StorageValueTypes::storage_value_unknown_table;
if (len > 0)
storage_value.type = thinkyoung::blockchain::StorageValueTypes::storage_value_unknown_array;
storage_value.value.table_value = lua_table_to_map_with_nested(L, index, jsons, recur_depth+1);
return storage_value;
case LUA_TUSERDATA:
// 如果是Stream,转成stream类型
{
auto addr = lua_touserdata(L, index);
if (global_glua_chain_api->is_object_in_pool(L, (intptr_t)addr, GluaOutsideObjectTypes::OUTSIDE_STREAM_STORAGE_TYPE))
{
storage_value.type = thinkyoung::blockchain::StorageValueTypes::storage_value_stream;
storage_value.value.userdata_value = addr;
}
else
{
storage_value.type = thinkyoung::blockchain::StorageValueTypes::storage_value_userdata;
storage_value.value.userdata_value = (void *)0; // lua_touserdata(L, index);
}
return storage_value;
}
case LUA_TFUNCTION:
storage_value.type = thinkyoung::blockchain::StorageValueTypes::storage_value_not_support;
storage_value.value.pointer_value = (void *)0; // (void*)lua_tocfunction(L, index); // 这里用0是为了让不同节点执行结果一致,用内存地址可能会每次执行结果不一样
return storage_value;
default:
storage_value.type = thinkyoung::blockchain::StorageValueTypes::storage_value_not_support;
storage_value.value.int_value = 0;
return storage_value;
}
}
struct GluaStorageValue lua_type_to_storage_value_type(lua_State *L, int index, size_t len)
{
std::list<const void*> jsons;
return lua_type_to_storage_value_type_with_nested(L, index, len, jsons, 0);
}
// TODO: 递归层次限制
bool lua_table_to_map_traverser_with_nested(lua_State *L, void *ud, size_t len, std::list<const void*> &jsons, size_t recur_depth)
{
GluaTableMapP map = (GluaTableMapP) ud;
if (lua_gettop(L) < 2)
return false;
if (!lua_isstring(L, -2) && !lua_isinteger(L, -1)) // now only support integer and string as table key, when using by thinkyoung
return false;
std::string key;
auto key_type = lua_type(L, -2);
if (key_type == LUA_TBOOLEAN)
key = std::to_string(lua_toboolean(L, -2));
else if (lua_isinteger(L, -2))
key = std::to_string(lua_tointeger(L, -2));
else if (key_type == LUA_TNUMFLT || key_type == LUA_TNUMINT || key_type == LUA_TNUMBER)
key = std::to_string(lua_tonumber(L, -2));
else if (key_type == LUA_TSTRING)
key = std::string(lua_tostring(L, -2));
else
return false;
if (key == "package") // FIXME: _G中package模块内容有嵌套递归,暂时全部排除掉避免报错
return true;
auto addr = lua_topointer(L, -1);
GluaStorageValue value;
bool json_found=false;
auto jit=jsons.begin();
while(jit!=jsons.end())
{
if(*jit==addr)
{
json_found=true;
break;
}
++jit;
}
if (nullptr != addr && lua_istable(L, -1) && json_found)
{
value.type = thinkyoung::blockchain::StorageValueTypes::storage_value_string;
std::string addr_str = std::to_string((intptr_t) addr);
addr_str = "address";
char *addr_s = (char*)lua_malloc(L, (1 + addr_str.length()) * sizeof(char));
memcpy(addr_s, addr_str.c_str(), (1 + addr_str.length()) * sizeof(char));
value.value.string_value = addr_s;
}
else
value = lua_type_to_storage_value_type_with_nested(L, -1, len, jsons, recur_depth);
(*map)[key] = value;
return true;
}
/**
* 把map转成json写入字符串流
* @param map 源map
* @param ss 要写入的字符串流
* @param is_array 是否作为一个array来进行json转换(因为lua的table中可能包含array和hashmap两部分)
*/
static void luatablemap_to_json_stream(GluaTableMapP map, std::stringstream &ss, bool is_array=false)
{
if(!is_array)
{
// 检查是否是数组
std::vector<int> all_int_keys;
bool has_wrong_array_format = false;
for(const auto &p : *map)
{
std::string key(p.first);
if(key.length()<1)
{
has_wrong_array_format = true;
break;
}
int int_key = 0;
if(key=="0")
{
int_key = 0;
}
else
{
try
{
int_key = std::stoi(key);
if (int_key == 0)
{
has_wrong_array_format = true;
break;
}
}catch(std::exception e)
{
has_wrong_array_format = true;
break;
}
}
all_int_keys.push_back(int_key);
}
if(!has_wrong_array_format)
{
std::sort(all_int_keys.begin(), all_int_keys.end());
for (int i = 1; i <= all_int_keys.size(); ++i)
{
if (i != all_int_keys[i-1])
{
has_wrong_array_format = true;
break;
}
}
if (!has_wrong_array_format)
{
is_array = true;
}
}
}
if (is_array)
ss << "[";
else
ss << "{";
for (auto it = map->begin(); it != map->end(); ++it)
{
if (it != map->begin())
ss << ",";
struct GluaStorageValue value = it->second;
if (!is_array)
{
std::string key(it->first);
ss << "\"" << glua::util::escape_string(key) << "\":";
}
switch (value.type)
{
case thinkyoung::blockchain::StorageValueTypes::storage_value_null:
ss << "null";
break;
case thinkyoung::blockchain::StorageValueTypes::storage_value_bool:
ss << (value.value.bool_value ? "true" : "false");
break;
case thinkyoung::blockchain::StorageValueTypes::storage_value_int:
ss << value.value.int_value;
break;
case thinkyoung::blockchain::StorageValueTypes::storage_value_number:
ss << value.value.number_value;
break;
case thinkyoung::blockchain::StorageValueTypes::storage_value_string:
{
auto str=std::string(value.value.string_value);
ss << "\"" << glua::util::escape_string(str) << "\"";
break;
}
case thinkyoung::blockchain::StorageValueTypes::storage_value_userdata:
ss << "\"userdata\"";
default:
{
if (thinkyoung::blockchain::is_any_table_storage_value_type(value.type)
|| thinkyoung::blockchain::is_any_array_storage_value_type(value.type))
{
luatablemap_to_json_stream(value.value.table_value, ss);
break;
}
ss << "\"userdata\"";
}
}
}
if (is_array)
ss << "]";
else
ss << "}";
}
static const char *tojsonstring_with_nested(lua_State *L, int idx, size_t *len, std::list<const void*> &jsons)
{
const void *addr = lua_topointer(L, idx);
if (nullptr != addr && glua::util::find(jsons.begin(), jsons.end(), addr))
{
lua_pushfstring(L, "%p", addr);
return lua_tolstring(L, -1, len);
}
if (!luaL_callmeta(L, idx, "__tojsonstring")) { /* no metafield? */
switch (lua_type(L, idx)) {
case LUA_TNUMBER: {
if (lua_isinteger(L, idx))
lua_pushfstring(L, "%I", lua_tointeger(L, idx));
else
lua_pushfstring(L, "%f", lua_tonumber(L, idx));
break;
}
case LUA_TSTRING:
lua_pushvalue(L, idx);
break;
case LUA_TBOOLEAN:
lua_pushstring(L, (lua_toboolean(L, idx) ? "true" : "false"));
break;
case LUA_TNIL:
lua_pushliteral(L, "nil");
break;
case LUA_TTABLE:
{
jsons.push_back(addr);
GluaTableMapP map = luaL_create_lua_table_map_in_memory_pool(L);
luaL_traverse_table_with_nested(L, idx, lua_table_to_map_traverser_with_nested, map, jsons, 0);
std::stringstream ss;
luatablemap_to_json_stream(map, ss);
if (len)
*len = ss.str().size();
lua_pushlstring(L, ss.str().c_str(), ss.str().size());
}
break;
default:
lua_pushfstring(L, "%s: %p", luaL_typename(L, idx),
(intptr_t) 0);
//lua_pushfstring(L, "%s: %p", luaL_typename(L, idx),
// lua_topointer(L, idx));
break;
}
}
return lua_tolstring(L, -1, len);
}
LUALIB_API const char *(luaL_tojsonstring)(lua_State *L, int idx, size_t *len)
{
std::list<const void*> jsons;
return tojsonstring_with_nested(L, idx, len, jsons);
}
/*
** {======================================================
** Compatibility with 5.1 module functions
** =======================================================
*/
#if defined(LUA_COMPAT_MODULE)
static const char *luaL_findtable(lua_State *L, int idx,
const char *fname, int szhint) {
const char *e;
if (idx) lua_pushvalue(L, idx);
do {
e = strchr(fname, '.');
if (e == nullptr) e = fname + strlen(fname);
lua_pushlstring(L, fname, e - fname);
if (lua_rawget(L, -2) == LUA_TNIL) { /* no such field? */
lua_pop(L, 1); /* remove this nil */
lua_createtable(L, 0, (*e == '.' ? 1 : szhint)); /* new table for field */
lua_pushlstring(L, fname, e - fname);
lua_pushvalue(L, -2);
lua_settable(L, -4); /* set new table into field */
}
else if (!lua_istable(L, -1)) { /* field has a non-table value? */
lua_pop(L, 2); /* remove table and value */
return fname; /* return problematic part of the name */
}
lua_remove(L, -2); /* remove previous table */
fname = e + 1;
} while (*e == '.');
return nullptr;
}
/*
** Count number of elements in a luaL_Reg list.
*/
static int libsize(const luaL_Reg *l) {
int size = 0;
for (; l && l->name; l++) size++;
return size;
}
/*
** Find or create a module table with a given name. The function
** first looks at the _LOADED table and, if that fails, try a
** global variable with that name. In any case, leaves on the stack
** the module table.
*/
LUALIB_API void luaL_pushmodule(lua_State *L, const char *modname,
int sizehint) {
luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED", 1); /* get _LOADED table */
if (lua_getfield(L, -1, modname) != LUA_TTABLE) { /* no _LOADED[modname]? */
lua_pop(L, 1); /* remove previous result */
/* try global variable (and create one if it does not exist) */
lua_pushglobaltable(L);
if (luaL_findtable(L, 0, modname, sizehint) != nullptr)
luaL_error(L, "name conflict for module '%s'", modname);
lua_pushvalue(L, -1);
lua_setfield(L, -3, modname); /* _LOADED[modname] = new table */
}
lua_remove(L, -2); /* remove _LOADED table */
}
LUALIB_API void luaL_openlib(lua_State *L, const char *libname,
const luaL_Reg *l, int nup) {
luaL_checkversion(L);
if (libname) {
luaL_pushmodule(L, libname, libsize(l)); /* get/create library table */
lua_insert(L, -(nup + 1)); /* move library table to below upvalues */
}
if (l)
luaL_setfuncs(L, l, nup);
else
lua_pop(L, nup); /* remove upvalues */
}
#endif
/* }====================================================== */
/*
** set functions from list 'l' into table at top - 'nup'; each
** function gets the 'nup' elements at the top as upvalues.
** Returns with only the table at the stack.
*/
LUALIB_API void luaL_setfuncs(lua_State *L, const luaL_Reg *l, int nup) {
luaL_checkstack(L, nup, "too many upvalues");
for (; l->name != nullptr; l++) { /* fill the table with given functions */
int i;
for (i = 0; i < nup; i++) /* copy upvalues to the top */
lua_pushvalue(L, -nup);
lua_pushcclosure(L, l->func, nup); /* closure with those upvalues */
lua_setfield(L, -(nup + 2), l->name);
}
lua_pop(L, nup); /* remove upvalues */
}
/*
** ensure that stack[idx][fname] has a table and push that table
** into the stack
*/
LUALIB_API int luaL_getsubtable(lua_State *L, int idx, const char *fname) {
if (lua_getfield(L, idx, fname) == LUA_TTABLE)
return 1; /* table already there */
else {
lua_pop(L, 1); /* remove previous result */
idx = lua_absindex(L, idx);
lua_newtable(L);
lua_pushvalue(L, -1); /* copy to be left at top */
lua_setfield(L, idx, fname); /* assign new table to field */
return 0; /* false, because did not find table there */
}
}
/*
** Stripped-down 'require': After checking "loaded" table, calls 'openf'
** to open a module, registers the result in 'package.loaded' table and,
** if 'glb' is true, also registers the result in the global table.
** Leaves resulting module on the top.
*/
LUALIB_API void luaL_requiref(lua_State *L, const char *modname,
lua_CFunction openf, int glb) {
luaL_getsubtable(L, LUA_REGISTRYINDEX, "_LOADED");
lua_getfield(L, -1, modname); /* _LOADED[modname] */
if (!lua_toboolean(L, -1)) { /* package not already loaded? */
lua_pop(L, 1); /* remove field */
lua_pushcfunction(L, openf);
lua_pushstring(L, modname); /* argument to open function */
lua_call(L, 1, 1); /* call 'openf' to open module */
lua_pushvalue(L, -1); /* make copy of module (call result) */
lua_setfield(L, -3, modname); /* _LOADED[modname] = module */
}
lua_remove(L, -2); /* remove _LOADED table */
if (glb) {
lua_pushvalue(L, -1); /* copy of module */
lua_setglobal(L, modname); /* _G[modname] = module */
}
}
LUALIB_API const char *luaL_gsub(lua_State *L, const char *s, const char *p,
const char *r) {
const char *wild;
size_t l = strlen(p);
luaL_Buffer b;
luaL_buffinit(L, &b);
while ((wild = strstr(s, p)) != nullptr) {
luaL_addlstring(&b, s, wild - s); /* push prefix */
luaL_addstring(&b, r); /* push replacement in place of pattern */
s = wild + l; /* continue after 'p' */
}
luaL_addstring(&b, s); /* push last suffix */
luaL_pushresult(&b);
return lua_tostring(L, -1);
}
static void *l_alloc(void *ud, void *ptr, size_t osize, size_t nsize) {
(void)ud; (void)osize; /* not used */
if (nsize == 0) {
free(ptr);
return nullptr;
}
else
return realloc(ptr, nsize);
}
static int panic(lua_State *L) {
lua_writestringerror("PANIC: unprotected error in call to Lua API (%s)\n",
lua_tostring(L, -1));
return 0; /* return to Lua to abort */
}
LUALIB_API lua_State *luaL_newstate(void) {
lua_State *L = lua_newstate(l_alloc, nullptr);
if (L) lua_atpanic(L, &panic);
return L;
}
LUALIB_API void luaL_checkversion_(lua_State *L, lua_Number ver, size_t sz) {
const lua_Number *v = lua_version(L);
if (sz != LUAL_NUMSIZES) /* check numeric types */
luaL_error(L, "core and library have incompatible numeric types");
if (v != lua_version(nullptr))
luaL_error(L, "multiple Lua VMs detected");
else if (*v != ver)
luaL_error(L, "version mismatch: app. needs %f, Lua core provides %f",
ver, *v);
}
| 35.388378
| 242
| 0.596931
|
WillAchain
|
44d4f86af1df765eb59f67783b5fc33ec26b160f
| 1,752
|
cpp
|
C++
|
button_maps.cpp
|
laparca/deconz-rest-plugin
|
d1298938484538f858428b12632269ffddb31484
|
[
"BSD-3-Clause"
] | 1,765
|
2015-06-09T08:10:44.000Z
|
2022-03-29T16:20:41.000Z
|
button_maps.cpp
|
laparca/deconz-rest-plugin
|
d1298938484538f858428b12632269ffddb31484
|
[
"BSD-3-Clause"
] | 5,354
|
2015-01-09T21:18:14.000Z
|
2022-03-31T21:41:56.000Z
|
button_maps.cpp
|
laparca/deconz-rest-plugin
|
d1298938484538f858428b12632269ffddb31484
|
[
"BSD-3-Clause"
] | 506
|
2015-04-15T14:08:41.000Z
|
2022-03-28T09:23:35.000Z
|
/*
* Copyright (c) 2021 dresden elektronik ingenieurtechnik gmbh.
* All rights reserved.
*
* The software in this package is published under the terms of the BSD
* style license a copy of which has been included with this distribution in
* the LICENSE.txt file.
*
*/
#include "button_maps.h"
ButtonMapRef BM_ButtonMapRefForHash(uint32_t buttonMapNameHash, const std::vector<ButtonMap> &buttonMaps)
{
const auto bm = std::find_if(buttonMaps.cbegin(), buttonMaps.cend(),
[buttonMapNameHash](const auto &bm) { return bm.buttonMapRef.hash == buttonMapNameHash; });
if (bm != buttonMaps.cend())
{
return bm->buttonMapRef;
}
return {};
}
const ButtonMap *BM_ButtonMapForRef(ButtonMapRef ref, const std::vector<ButtonMap> &buttonMaps)
{
if (isValid(ref) && ref.index < buttonMaps.size())
{
const ButtonMap &bm = buttonMaps[ref.index];
if (bm.buttonMapRef.hash == ref.hash)
{
return &bm;
}
}
return nullptr;
}
const ButtonMap *BM_ButtonMapForProduct(ProductIdHash productHash, const std::vector<ButtonMap> &buttonMaps,
const std::vector<ButtonProduct> &buttonProductMap)
{
ButtonMapRef buttonMapHash{};
{
const auto mapping = std::find_if(buttonProductMap.cbegin(), buttonProductMap.cend(),
[productHash](const auto &i) { return i.productHash == productHash; });
if (mapping != buttonProductMap.cend())
{
buttonMapHash = mapping->buttonMapRef;
}
}
if (isValid(buttonMapHash))
{
return BM_ButtonMapForRef(buttonMapHash, buttonMaps);
}
return nullptr;
}
| 29.2
| 124
| 0.625
|
laparca
|
44d87228414d19518d2172db0707da54cd025a12
| 4,489
|
cpp
|
C++
|
Group3_FinalProject/GLTextWriter.cpp
|
BrandonLittell/PinballGL
|
d2678f0e916cdb8b8a234243feeda03a196e5bc8
|
[
"MIT"
] | 1
|
2016-12-17T12:28:42.000Z
|
2016-12-17T12:28:42.000Z
|
Group3_FinalProject/GLTextWriter.cpp
|
BrandonLittell/PinballGL
|
d2678f0e916cdb8b8a234243feeda03a196e5bc8
|
[
"MIT"
] | null | null | null |
Group3_FinalProject/GLTextWriter.cpp
|
BrandonLittell/PinballGL
|
d2678f0e916cdb8b8a234243feeda03a196e5bc8
|
[
"MIT"
] | null | null | null |
// see
// http://nehe.gamedev.net/tutorial/bitmap_fonts/17002/
//
#include "GLTextWriter.h"
GLTextWriter::GLTextWriter( HDC& ahDC, HGLRC& ahRC ) : hDC( ahDC ), hRC( ahRC )
{
GLuint PixelFormat;
static PIXELFORMATDESCRIPTOR pfd= // pfd Tells Windows How We Want Things To Be
{
sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor
1, // Version Number
PFD_DRAW_TO_WINDOW | // Format Must Support Window
PFD_SUPPORT_OPENGL | // Format Must Support OpenGL
PFD_DOUBLEBUFFER, // Must Support Double Buffering
PFD_TYPE_RGBA, // Request An RGBA Format
16, // Select Our Color Depth
0, 0, 0, 0, 0, 0, // Color Bits Ignored
0, // No Alpha Buffer
0, // Shift Bit Ignored
0, // No Accumulation Buffer
0, 0, 0, 0, // Accumulation Bits Ignored
16, // 16Bit Z-Buffer (Depth Buffer)
0, // No Stencil Buffer
0, // No Auxiliary Buffer
PFD_MAIN_PLANE, // Main Drawing Layer
0, // Reserved
0, 0, 0 // Layer Masks Ignored
};
PixelFormat=ChoosePixelFormat(hDC,&pfd);
SetPixelFormat(hDC,PixelFormat,&pfd);
BuildFont();
GetCharABCWidths( hDC, 0, 255, &glyphInfo[0] );
}
GLTextWriter::~GLTextWriter( )
{
KillFont();
}
void GLTextWriter::print( GLfloat x, GLfloat y, string text, vec3 color )
{
// version 4.2.X on our personal computers vs 4.3.0 on the lab machines requires slightly different rasters
static const GLubyte* ver = glGetString(GL_VERSION);
const string verStr(reinterpret_cast<const char*>(ver));
const string shortVerStr = verStr.substr(0,3);
/*
* http://www.mesa3d.org/brianp/sig97/gotchas.htm Yay for Gotchas!
*/
glPushAttrib( GL_TRANSFORM_BIT | GL_VIEWPORT_BIT );
/* Setup projection parameters */
glMatrixMode( GL_PROJECTION );
glPushMatrix();
glLoadIdentity();
//gluOrtho2D( 0, WINDOW_WIDTH, 0, WINDOW_HEIGHT);
glMatrixMode( GL_MODELVIEW );
glPushMatrix();
glLoadIdentity();
// http://stackoverflow.com/questions/6595772/painting-text-above-opengl-context-in-mfc
stringWidth=0; // pixels
for(int j=0; j < text.length(); ++j )
stringWidth += glyphInfo[ text.c_str()[j] ].abcA + glyphInfo[ text.c_str()[j] ].abcB + glyphInfo[ text.c_str()[j] ].abcC;
glColor3f( color.x, color.y, color.z );
/* set the raster (window) position */
xPos = x - stringWidth/2.0f;
glViewport( (int) xPos - 1, (int) y - 1, 2, 2 );
if( !strcmp(shortVerStr.c_str(), "4.3") )
{
glRasterPos2f( xPos , y );
}
else
{ // 4.2.X
glRasterPos2f( -1.0f + x/(WINDOW_WIDTH/2), -1.0f + y/(WINDOW_HEIGHT/2) );
}
glPrint( text.c_str() );
/* restore matrices, viewport and matrix mode */
glPopMatrix();
glMatrixMode( GL_PROJECTION );
glViewport( 0, 0, WINDOW_WIDTH, WINDOW_HEIGHT );
glPopMatrix();
glPopAttrib();
}
GLvoid GLTextWriter::BuildFont( GLvoid )
{
HFONT font;
HFONT oldfont;
base = glGenLists(96);
font = CreateFont( -24, // Height Of Font
0, // Width Of Font
0, // Angle Of Escapement
0, // Orientation Angle
FW_BOLD, // Font Weight
FALSE, // Italic
FALSE, // Underline
FALSE, // Strikeout
ANSI_CHARSET, // Character Set Identifier
OUT_TT_PRECIS, // Output Precision
CLIP_DEFAULT_PRECIS, // Clipping Precision
ANTIALIASED_QUALITY, // Output Quality
FF_DONTCARE|DEFAULT_PITCH, // Family And Pitch
"Courier New"); // Font Name
oldfont = (HFONT)SelectObject( hDC, font );
wglUseFontBitmaps( hDC, 32, 96, base );
SelectObject( hDC, font );
DeleteObject(font);
}
GLvoid GLTextWriter::KillFont(GLvoid) // Delete The Font
{
glDeleteLists(base, 96);
}
GLvoid GLTextWriter::glPrint( const char *fmt ) // Custom GL "Print" Routine
{
char text[256]; // Holds Our String
va_list ap; // Pointer To List Of Arguments
if (fmt == NULL) // If There's No Text
return; // Do Nothing
va_start(ap, fmt); // Parses The String For Variables
vsprintf(text, fmt, ap); // And Converts Symbols To Actual Numbers
va_end(ap); // Results Are Stored In Text
glPushAttrib(GL_LIST_BIT); // Pushes The Display List Bits
glListBase(base - 32); // Sets The Base Character to 32
glCallLists(strlen(text), GL_UNSIGNED_BYTE, text); // Draws The Display List Text
glPopAttrib(); // Pops The Display List Bits
}
| 31.173611
| 123
| 0.637336
|
BrandonLittell
|
44d910c679948cd17474fba10a0939a90cb697b1
| 6,719
|
cpp
|
C++
|
src/client/udpclient.cpp
|
Jamol/udptest
|
c053ccfb8cb1af6bd85647421487117392328451
|
[
"MIT"
] | null | null | null |
src/client/udpclient.cpp
|
Jamol/udptest
|
c053ccfb8cb1af6bd85647421487117392328451
|
[
"MIT"
] | null | null | null |
src/client/udpclient.cpp
|
Jamol/udptest
|
c053ccfb8cb1af6bd85647421487117392328451
|
[
"MIT"
] | null | null | null |
//
// udptest.cpp
// udptest
//
// Created by Jamol Bao on 7/8/14.
// Copyright (c) 2014. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
#include <thread>
#include <string>
#include <chrono>
#include "util.h"
using namespace std::chrono;
#define now_tick_ms() duration_cast<milliseconds>(steady_clock::now().time_since_epoch())
static std::thread s_thread;
static bool s_stop = false;
extern "C" void startTest(const char* bind_addr, uint16_t bind_port, const char* peer_addr,
uint16_t peer_port, uint32_t bw, uint32_t slice_ms, uint32_t burst_bytes)
{
std::string str_bind_addr = bind_addr;
std::string str_peer_addr = peer_addr;
try
{
s_thread = std::thread ([=] () mutable {
my_printf("bind_addr=%s, bind_port=%d, peer_addr=%s, peer_port=%d, bw=%u, slice=%u, burst_bytes=%u\n",
str_bind_addr.c_str(), bind_port, str_peer_addr.c_str(), peer_port, bw, slice_ms,
burst_bytes);
int sfd = create_udp_fd(str_bind_addr.c_str(), bind_port);
if(sfd < 0){
return;
}
int buf_size = 64*1024;
//setsockopt(sfd, SOL_SOCKET, SO_RCVBUF, (char*)&buf_size, sizeof(buf_size));
setsockopt(sfd, SOL_SOCKET, SO_SNDBUF, (char*)&buf_size, sizeof(buf_size));
sockaddr_storage ss_addr = {0};
socklen_t addr_len = sizeof(ss_addr);
if(getsockname(sfd, (struct sockaddr*)&ss_addr, &addr_len) == 0){
char bind_addr[64] = {0};
unsigned short bind_port = 0;
km_get_sock_addr((struct sockaddr*)&ss_addr, addr_len, bind_addr, sizeof(bind_addr), &bind_port);
my_printf("bind to %s:%d\n", bind_addr, bind_port);
}
struct addrinfo hints = {0};
addr_len = sizeof(ss_addr);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_flags = AI_ADDRCONFIG;
km_set_sock_addr(str_peer_addr.c_str(), peer_port, &hints, (struct sockaddr *)&ss_addr, addr_len);
if(AF_INET == ss_addr.ss_family) {
addr_len = sizeof(sockaddr_in);
} else {
addr_len = sizeof(sockaddr_in6);
}
unsigned char buf[65535];
// construct RTP header
buf[0] = 2 << 6;
buf[1] = 0x80|101; // marker & payload type
*(uint32_t*)(buf + 4) = 0; // timestamp
*(uint32_t*)(buf + 8) = htonl(12345678); // ssrc
my_printf("start to send data...\n");
unsigned short sequence = 0;
unsigned short* p_seq = (unsigned short*)(buf + 2);
uint32_t loop_count = 1000/slice_ms;
uint32_t average_bytes_per_slice = bw/loop_count;
uint32_t bytes_sent_in_this_second = 0;
milliseconds start_tick = now_tick_ms();
uint32_t cur_send_bytes = 0;
if(burst_bytes < average_bytes_per_slice){
burst_bytes = average_bytes_per_slice;
}
srand((unsigned int)time(NULL));
while (!s_stop) {
milliseconds second_start_tick = now_tick_ms();
bytes_sent_in_this_second = 0;
for (uint32_t i=0; i<loop_count; ++i) {// this second
milliseconds slice_start_tick = now_tick_ms();
uint32_t cur_slice_bytes_to_send = average_bytes_per_slice;
uint32_t left_bytes_in_this_second = bw - bytes_sent_in_this_second;
if(left_bytes_in_this_second < burst_bytes){
cur_slice_bytes_to_send = left_bytes_in_this_second;
}
//int r = rand();
uint32_t slice_loop_count = cur_slice_bytes_to_send/1024;
if(cur_slice_bytes_to_send%1024 != 0){
++slice_loop_count;
}
uint32_t bytes_sent_in_this_slice = 0;
uint32_t cur_bytes_to_send = cur_slice_bytes_to_send/slice_loop_count;
for (uint32_t j=0; j<slice_loop_count; ++j) {
//*(unsigned int*)buf = htonl(++sequence);
*p_seq = htons(++sequence);
long ret = sendto(sfd, (const char*)buf, cur_bytes_to_send, 0, (struct sockaddr*)&ss_addr, addr_len);
if(ret < 0){
my_printf("failed to call sendto, ret=%ld, err=%d\n", ret, errno);
closesocket(sfd);
return ;
}
if(ret != cur_bytes_to_send){
my_printf("+++ ret=%ld, cur_bytes_to_send=%d\n", ret, cur_bytes_to_send);
}
cur_send_bytes += ret;
bytes_sent_in_this_slice += cur_bytes_to_send;
}
bytes_sent_in_this_second += bytes_sent_in_this_slice;
milliseconds slice_end_tick = now_tick_ms();
milliseconds diff = slice_end_tick - slice_start_tick;
if(diff.count() < slice_ms - 1){
std::this_thread::sleep_for(milliseconds(slice_ms-diff.count()-1));
}
if(bytes_sent_in_this_second >= bw){
break;
}
}
milliseconds end_tick = now_tick_ms();
milliseconds diff = end_tick - second_start_tick;
if(diff.count() < 999){
std::this_thread::sleep_for(milliseconds(1000 - diff.count()));
end_tick += milliseconds(1000-diff.count());
}
diff = end_tick - start_tick;
if(diff.count() > 5000){
uint32_t send_rate = cur_send_bytes*1000/diff.count();
my_printf("sequence=%u, send_bytes=%u, diff=%lld, send_rate=%u\n",
sequence, cur_send_bytes, diff.count(), send_rate);
cur_send_bytes = 0;
start_tick = end_tick;
}
}
closesocket(sfd);
});
}
catch(...)
{
}
}
extern "C" void stopTest()
{
my_printf("stopTest ...\n");
s_stop = true;
}
extern "C" void waitTest()
{
try
{
s_thread.join();
}
catch(...)
{
}
}
| 39.523529
| 125
| 0.51466
|
Jamol
|
44da3abdbe428ae12f3a00c31009289fc4ee97b5
| 469
|
hpp
|
C++
|
include/glm/gtc/vec1.hpp
|
anonreclaimer/glWebKit
|
7c64ba02a734f2a97e023ad6e5dc9eebd7fadb6c
|
[
"MIT"
] | 1,726
|
2017-06-15T14:58:55.000Z
|
2022-03-22T02:02:15.000Z
|
glm/gtc/vec1.hpp
|
mortennobel/SimpleVRCpp
|
7a4f07c591413e805c9a3a24b21bc2650119b354
|
[
"MIT"
] | 135
|
2018-09-09T06:46:04.000Z
|
2022-01-29T19:33:12.000Z
|
glm/gtc/vec1.hpp
|
mortennobel/SimpleVRCpp
|
7a4f07c591413e805c9a3a24b21bc2650119b354
|
[
"MIT"
] | 107
|
2017-11-16T02:17:07.000Z
|
2022-03-16T16:33:13.000Z
|
/// @ref gtc_vec1
/// @file glm/gtc/vec1.hpp
///
/// @see core (dependence)
///
/// @defgroup gtc_vec1 GLM_GTC_vec1
/// @ingroup gtc
///
/// Include <glm/gtc/vec1.hpp> to use the features of this extension.
///
/// Add vec1, ivec1, uvec1 and bvec1 types.
#pragma once
// Dependency:
#include "../ext/vec1.hpp"
#if GLM_MESSAGES == GLM_MESSAGES_ENABLED && !defined(GLM_EXT_INCLUDED)
# pragma message("GLM: GLM_GTC_vec1 extension included")
#endif
#include "vec1.inl"
| 20.391304
| 70
| 0.686567
|
anonreclaimer
|
44dbe86663dded8f98a276203200cbe293697a0e
| 635
|
hpp
|
C++
|
EDMUtils/interface/TFileUtils.hpp
|
NTUHEP-Tstar/ManagerUtils
|
2536174671e537f210c330fe739f4cf0615e735e
|
[
"MIT"
] | null | null | null |
EDMUtils/interface/TFileUtils.hpp
|
NTUHEP-Tstar/ManagerUtils
|
2536174671e537f210c330fe739f4cf0615e735e
|
[
"MIT"
] | null | null | null |
EDMUtils/interface/TFileUtils.hpp
|
NTUHEP-Tstar/ManagerUtils
|
2536174671e537f210c330fe739f4cf0615e735e
|
[
"MIT"
] | null | null | null |
/*******************************************************************************
*
* Filename : TFileUtils.hpp
* Description : Helper functions for interacting with TFiles for EDM Plugins
* Author : Yi-Mu "Enoch" Chen [ ensc@hep1.phys.ntu.edu.tw ]
*
*******************************************************************************/
#ifndef MANAGERUTILS_EDMUTILS_TFILEUTILS_HPP
#define MANAGERUTILS_EDMUTILS_TFILEUTILS_HPP
#include "TObject.h"
#include <string>
extern TObject* GetCloneFromFile( const std::string& filename, const std::string& obj );
#endif/* end of include guard: MANAGERUTILS_EDMUTILS_TFILEUTILS_HPP */
| 35.277778
| 88
| 0.568504
|
NTUHEP-Tstar
|
44e3eb6788881c36c808f4dad8cd56e18633b465
| 13,038
|
cpp
|
C++
|
src/camera_capture_flea3/Fla3Camera.cpp
|
neemoh/ART
|
3f990b9d3c4b58558adf97866faf4eea553ba71b
|
[
"Unlicense"
] | 11
|
2018-06-29T19:08:08.000Z
|
2021-12-30T07:13:00.000Z
|
src/camera_capture_flea3/Fla3Camera.cpp
|
liuxia-zju/ATAR
|
3f990b9d3c4b58558adf97866faf4eea553ba71b
|
[
"Unlicense"
] | 1
|
2020-05-09T23:44:55.000Z
|
2020-05-09T23:44:55.000Z
|
src/camera_capture_flea3/Fla3Camera.cpp
|
liuxia-zju/ATAR
|
3f990b9d3c4b58558adf97866faf4eea553ba71b
|
[
"Unlicense"
] | 6
|
2017-11-28T14:26:18.000Z
|
2019-11-29T01:57:14.000Z
|
#include "Fla3Camera.h"
#include <sensor_msgs/fill_image.h>
#include <cv_bridge/cv_bridge.h>
//#include <stdexcept>
// ============================================================================
// ----------------------------------------------------------------------------
Fla3Camera::Fla3Camera()
{
}
// ----------------------------------------------------------------------------
Fla3Camera::~Fla3Camera()
{
delete[] p_osaFlea3CameraConnect;
delete[] capture_running;
delete[] p_PGIdentity;
delete[] cameras;
}
// ----------------------------------------------------------------------------
void Fla3Camera::Init()
{
num_cams = DetermineNumberOfCameras();
printf("Number of cameras is %d\n", num_cams);
// Initialize the variable that keep track of camera connect and start
p_osaFlea3CameraConnect = new bool[num_cams];
capture_running = new bool[num_cams];
p_PGIdentity = new PGRGuid[num_cams];
cameras = new Camera[num_cams];
for (int i = 0 ; i < num_cams; i++)
{
p_osaFlea3CameraConnect[i] = false;
capture_running[i] = false;
}
}
// ----------------------------------------------------------------------------
uint Fla3Camera::GetNumberOfCameras()
{
return num_cams;
}
// ----------------------------------------------------------------------------
void Fla3Camera::ConnectCamera(uint a_cameraNum)
{
if ((a_cameraNum +1) > num_cams)
throw std::runtime_error("Trying to connect to an invalid camera!");
if (!p_osaFlea3CameraConnect[a_cameraNum])
{
Error t_error;
t_error = bus_manager.GetCameraFromIndex(a_cameraNum, &(p_PGIdentity[a_cameraNum]));
if (t_error != PGRERROR_OK)
{
throw std::runtime_error("Error: Fla3Camera::ConnectCamera::GetCameraFromIndex");
}
else
{
// Connect to a camera
t_error = cameras[a_cameraNum].Connect(&(p_PGIdentity[a_cameraNum]));
if (t_error != PGRERROR_OK)
{
throw std::runtime_error("Error: Fla3Camera::ConnectCamera::Connect");
}
else
{
// Set the camera to be connected
p_osaFlea3CameraConnect[a_cameraNum] = true;
printf("camera_intrinsics %d connected!\n", a_cameraNum);
}
}
}
FlyCapture2::PixelFormat a;
}
// ----------------------------------------------------------------------------
void Fla3Camera::DisconnectCamera(uint a_cameraNum)
{
// Disconnect the camera
Error t_error;
t_error = cameras[a_cameraNum].Disconnect();
if (t_error != PGRERROR_OK)
throw std::runtime_error("Error: Fla3Camera::DisconnectCamera");
else// Set the camera to be disconnected
p_osaFlea3CameraConnect[a_cameraNum] = false;
std::cout << "camera_intrinsics " << a_cameraNum << " disconnected." << std::endl;
}
// ----------------------------------------------------------------------------
uint Fla3Camera::DetermineNumberOfCameras()
{
uint t_numCameras;
Error t_error = bus_manager.GetNumOfCameras(&t_numCameras);
if (t_error != PGRERROR_OK)
throw std::runtime_error("Error: Fla3Camera::DetermineNumberOfCameras");
return t_numCameras;
}
// ----------------------------------------------------------------------------
void Fla3Camera::StartCameraCapture(uint a_cameraNum)
{
Error t_error;
if ((a_cameraNum+1) > num_cams)
throw std::runtime_error("Trying to start an invalid camera!");
else if (!p_osaFlea3CameraConnect[a_cameraNum])
throw std::runtime_error("Trying to start a camera that is not connected!");
// Start capturing images
t_error = cameras[a_cameraNum].StartCapture();
if (t_error != PGRERROR_OK)
throw std::runtime_error("Error: Fla3Camera::StartCameraCapture");
else
{
capture_running[a_cameraNum] = true;
printf("camera_intrinsics %d started!\n", a_cameraNum);
}
}
// ----------------------------------------------------------------------------
void Fla3Camera::StopCameraCapture(uint a_cameraNum)
{
Error error;
if ((a_cameraNum+1) > num_cams)
throw std::runtime_error("Trying to stop an invalid camera!");
else if (!p_osaFlea3CameraConnect[a_cameraNum])
throw std::runtime_error("Trying to stop a camera that is not connected!");
// Stop capturing images
error = cameras[a_cameraNum].StopCapture();
HandleError("Fla3Camera::StopCameraCapture Failed to stop capturing", error);
capture_running[a_cameraNum] = false;
std::cout << "camera_intrinsics " << a_cameraNum << " stopped." << std::endl;
}
// ----------------------------------------------------------------------------
//void Fla3Camera::GetImageFromCamera(int a_cameraNum, unsigned char** a_data, int *a_rowSize, int *a_colSize)
void Fla3Camera::GetImageFromCamera(uint a_cameraNum, cv::Mat &image_out, int *a_rowSize, int *a_colSize)
{
if ((a_cameraNum+1) > num_cams)
throw std::runtime_error("Trying to get the image from an invalid camera!");
else if (!p_osaFlea3CameraConnect[a_cameraNum])
throw std::runtime_error("Trying to get the image from a camera that is not connected!");
else if (!capture_running[a_cameraNum])
throw std::runtime_error("Trying to get the image from a camera that is not started!");
FlyCapture2::Error t_error;
FlyCapture2::Image t_rawImage;
// Retrieve an image
t_error = cameras[a_cameraNum].RetrieveBuffer( &t_rawImage );
if (t_error != PGRERROR_OK)
{
throw std::runtime_error("Error: Unable to get image from camera");
}
// Get the raw image dimensions
PixelFormat pixFormat;
unsigned int rows, cols, stride;
t_rawImage.GetDimensions( &rows, &cols, &stride, &pixFormat );
// Create a converted image
FlyCapture2::Image rgbImage;
// Convert the raw image
t_error = t_rawImage.Convert( FlyCapture2::PIXEL_FORMAT_BGR, &rgbImage );
if (t_error != PGRERROR_OK)
{
throw std::runtime_error("Error: Unable to convert image from camera");
}
// Copy the image from to the data buffer
// unsigned char *t_data = t_convertedImage.GetData();
// rgbImage.GetDataSize();
// Copy FlyCapture2 image into OpenCV struct
// if ((*a_data) == NULL){
// *a_data = new unsigned char[rgbImage.GetDataSize()];
// std::cout << "(*a_data) == NULL " << std::endl;
//
// }
// memcpy( *a_data,
// rgbImage.GetData(),
// rgbImage.GetDataSize());
// convert to OpenCV Mat
unsigned int rowBytes = rgbImage.GetReceivedDataSize()/rgbImage.GetRows();
// cv::Mat image_temp = cv::Mat(rgbImage.GetRows(), rgbImage.GetCols(), CV_8UC3, rgbImage.GetData(),rowBytes);
cv::Mat image_temp = cv::Mat(rgbImage.GetRows(), rgbImage.GetCols(), CV_8UC3, rgbImage.GetData(),rowBytes);
cv::imshow("Aruco extrinsic", image_temp);
cv::waitKey(1);
*a_rowSize = (int)rows;
*a_colSize = (int)cols;
}
// ----------------------------------------------------------------------------
void Fla3Camera::GetAndSaveImageFromCamera(int a_cameraNum, char* a_filename)
{
if ((a_cameraNum+1) > num_cams)
{
throw std::runtime_error("Trying to get the image from an invalid camera!");
}
else if (!p_osaFlea3CameraConnect[a_cameraNum] )
{
throw std::runtime_error("Trying to get the image from a camera that is not connected!");
}
else if (!capture_running[a_cameraNum])
{
throw std::runtime_error("Trying to get the image from a camera that is not started!");
}
Error t_error;
FlyCapture2::Image t_rawImage;
// Retrieve an image
t_error = cameras[a_cameraNum].RetrieveBuffer( &t_rawImage );
if (t_error != PGRERROR_OK)
{
throw std::runtime_error("Error: Unable to get image from camera");
}
// Get the raw image dimensions
PixelFormat pixFormat;
unsigned int rows, cols, stride;
t_rawImage.GetDimensions( &rows, &cols, &stride, &pixFormat );
// Create a converted image
FlyCapture2::Image t_convertedImage;
// Convert the raw image
t_error = t_rawImage.Convert( PIXEL_FORMAT_RGB8, &t_convertedImage );
if (t_error != PGRERROR_OK)
throw std::runtime_error("Error: Unable to convert image from camera");
// Save the image. If a file format is not passed in, then the file
// extension is parsed to attempt to determine the file format.
t_error = t_convertedImage.Save(a_filename);
if (t_error != PGRERROR_OK)
{
throw std::runtime_error("Error: Unable to save image from camera");
}
}
// ----------------------------------------------------------------------------
void Fla3Camera::SetCameraProperty(int a_cameraNum, char* a_configFile)
{
}
// ----------------------------------------------------------------------------
double Fla3Camera::GetFrameRate(int a_cameraNum)
{
Error t_error;
if ((a_cameraNum+1) > num_cams)
{
throw std::runtime_error("Trying to grab the frame rate of an invalid camera!");
}
else if (!p_osaFlea3CameraConnect[a_cameraNum])
{
throw std::runtime_error("Trying to grab the frame rate of a camera that is not connected!");
}
else if (!capture_running[a_cameraNum])
{
throw std::runtime_error("Trying to grab the frame rate of a camera that is not started!");
}
// Retrieve frame rate property
Property t_frmRate;
t_frmRate.type = FRAME_RATE;
t_error = cameras[a_cameraNum].GetProperty( &t_frmRate );
if (t_error != PGRERROR_OK)
{
throw std::runtime_error("Error: Fla3Camera::GetFrameRate");
}
else
{
return (double)t_frmRate.absValue;
}
}
// ----------------------------------------------------------------------------
void Fla3Camera::grabImage(uint cam_num, sensor_msgs::Image &image)
{
boost::mutex::scoped_lock scopedLock(mutex_);
if(cameras[cam_num].IsConnected() && capture_running[cam_num])
{
// Make a FlyCapture2::image to hold the buffer returned by the camera.
Image rawImage;
// Retrieve an image
Error error = cameras[cam_num].RetrieveBuffer(&rawImage);
HandleError("PointGreyCamera::grabImage Failed to retrieve buffer", error);
// Set header timestamp as embedded for now
TimeStamp embeddedTime = rawImage.GetTimeStamp();
image.header.stamp.sec = embeddedTime.seconds;
image.header.stamp.nsec = 1000 * embeddedTime.microSeconds;
// Check the bits per pixel.
auto bitsPerPixel = rawImage.GetBitsPerPixel();
// Set the image encoding
std::string imageEncoding = sensor_msgs::image_encodings::BAYER_RGGB8;
fillImage(image, imageEncoding, rawImage.GetRows(), rawImage.GetCols(), rawImage.GetStride(), rawImage.GetData());
// image.header.frame_id = frame_id;
}
else if(cameras[cam_num].IsConnected())
{
throw std::runtime_error("PointGreyCamera::grabImage: camera_intrinsics is currently not running. Please start the capture.");
}
else
{
throw std::runtime_error("PointGreyCamera::grabImage not connected!");
}
}
void Fla3Camera::HandleError(const std::string &prefix, const FlyCapture2::Error &error)
{
if(error == PGRERROR_TIMEOUT)
{
throw std::runtime_error("PointGreyCamera: Failed to retrieve buffer within timeout.");
}
else if(error != PGRERROR_OK) // If there is actually an error (PGRERROR_OK means the function worked as intended...)
{
std::string start(" | FlyCapture2::ErrorType ");
std::stringstream out;
out << error.GetType();
std::string desc(error.GetDescription());
throw std::runtime_error(prefix + start + out.str() + " " + desc);
}
}
std::vector<uint32_t> Fla3Camera::getAttachedCameras()
{
std::vector<uint32_t> serials;
Error error = bus_manager.GetNumOfCameras(&num_cams);
HandleError("PFla3Camera::getAttachedCameras: Could not get number of cameras", error);
for(unsigned int i = 0; i < num_cams; i++)
{
unsigned int this_serial;
error = bus_manager.GetCameraSerialNumberFromIndex(i, &this_serial);
HandleError("PointGreyCamera::getAttachedCameras: Could not get get serial number from index", error);
serials.push_back(this_serial);
std::cout << "Found camera " << i << " with serial number: "<< this_serial<< std::endl;
}
return serials;
}
sensor_msgs::ImagePtr Fla3Camera::ResizeImage(
const sensor_msgs::Image &image_in) {
cv_bridge::CvImagePtr cv_ptr_in;
cv_ptr_in = cv_bridge::toCvCopy(image_in, sensor_msgs::image_encodings::BGR8);
cv::Mat image_out;
cv::resize(cv_ptr_in->image, image_out, cv::Size(), 0.5, 0.5, CV_INTER_AREA);
sensor_msgs::ImagePtr msg = cv_bridge::CvImage(std_msgs::Header(), "bgr8", image_out).toImageMsg();
return msg;
}
| 33.864935
| 135
| 0.604617
|
neemoh
|
44e475be2679c252799eca51c927e6a68fc702f9
| 249
|
cpp
|
C++
|
ACT.cpp
|
Marethyu12/SPOJ-solutions
|
10fb3352e0b8818be40f7df2285b0d30a0fdc09c
|
[
"Unlicense"
] | null | null | null |
ACT.cpp
|
Marethyu12/SPOJ-solutions
|
10fb3352e0b8818be40f7df2285b0d30a0fdc09c
|
[
"Unlicense"
] | null | null | null |
ACT.cpp
|
Marethyu12/SPOJ-solutions
|
10fb3352e0b8818be40f7df2285b0d30a0fdc09c
|
[
"Unlicense"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int T;
int n;
string s;
cin >> T;
while (T--)
{
cin >> n >> s;
cout << s[s.length() - 1] << "\n";
}
return 0;
}
| 9.96
| 36
| 0.518072
|
Marethyu12
|
44e4d22bc36c080b39d17cccafdcce9edcb923fa
| 8,192
|
hpp
|
C++
|
Common_3/ThirdParty/OpenSource/ModifiedSonyMath/sse/boolinvec.hpp
|
Mercesa/The-Forge
|
13d7604bde91f90188c9dcb480ea6e97f60f1645
|
[
"Apache-2.0"
] | 3,058
|
2017-10-03T01:33:22.000Z
|
2022-03-30T22:04:23.000Z
|
Common_3/ThirdParty/OpenSource/ModifiedSonyMath/sse/boolinvec.hpp
|
juteman/The-Forge
|
e882fbc000b2915b52c98fe3a8c791930490dd3c
|
[
"Apache-2.0"
] | 157
|
2018-01-26T10:18:33.000Z
|
2022-03-06T10:59:23.000Z
|
Common_3/ThirdParty/OpenSource/ModifiedSonyMath/sse/boolinvec.hpp
|
juteman/The-Forge
|
e882fbc000b2915b52c98fe3a8c791930490dd3c
|
[
"Apache-2.0"
] | 388
|
2017-12-21T10:52:32.000Z
|
2022-03-31T18:25:49.000Z
|
/*
Copyright (C) 2006, 2007 Sony Computer Entertainment Inc.
All rights reserved.
Redistribution and use in source and binary forms,
with or without modification, are permitted provided that the
following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Sony Computer Entertainment Inc nor the names
of its contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef VECTORMATH_SSE_BOOLINVEC_HPP
#define VECTORMATH_SSE_BOOLINVEC_HPP
namespace Vectormath
{
namespace SSE
{
class FloatInVec;
typedef __m128i Vector4Int;
// ========================================================
// BoolInVec
// ========================================================
// Vectorized boolean value.
VECTORMATH_ALIGNED_TYPE_PRE class BoolInVec
{
__m128 mData;
inline BoolInVec(__m128 vec);
public:
// Default constructor; does no initialization
//
inline BoolInVec() { } //-V730
// matches standard type conversions
//
inline BoolInVec(const FloatInVec & vec);
// explicit cast from bool
//
explicit inline BoolInVec(bool scalar);
#ifdef VECTORMATH_NO_SCALAR_CAST
// explicit cast to bool
inline bool getAsBool() const;
#else // !VECTORMATH_NO_SCALAR_CAST
// implicit cast to bool
inline operator bool() const;
#endif // VECTORMATH_NO_SCALAR_CAST
// get vector data
// bool value is splatted across all word slots of vector as 0 (false) or -1 (true)
//
inline __m128 get128() const;
// operators
//
inline const BoolInVec operator ! () const;
inline BoolInVec & operator = (const BoolInVec & vec);
inline BoolInVec & operator &= (const BoolInVec & vec);
inline BoolInVec & operator ^= (const BoolInVec & vec);
inline BoolInVec & operator |= (const BoolInVec & vec);
// friend functions
//
friend inline const BoolInVec operator == (const BoolInVec & vec0, const BoolInVec & vec1);
friend inline const BoolInVec operator != (const BoolInVec & vec0, const BoolInVec & vec1);
friend inline const BoolInVec operator < (const FloatInVec & vec0, const FloatInVec & vec1);
friend inline const BoolInVec operator <= (const FloatInVec & vec0, const FloatInVec & vec1);
friend inline const BoolInVec operator > (const FloatInVec & vec0, const FloatInVec & vec1);
friend inline const BoolInVec operator >= (const FloatInVec & vec0, const FloatInVec & vec1);
friend inline const BoolInVec operator == (const FloatInVec & vec0, const FloatInVec & vec1);
friend inline const BoolInVec operator != (const FloatInVec & vec0, const FloatInVec & vec1);
friend inline const BoolInVec operator & (const BoolInVec & vec0, const BoolInVec & vec1);
friend inline const Vector4Int operator & (const BoolInVec & vec0, const Vector4Int & vec1);
friend inline const BoolInVec operator ^ (const BoolInVec & vec0, const BoolInVec & vec1);
friend inline const BoolInVec operator | (const BoolInVec & vec0, const BoolInVec & vec1);
friend inline const BoolInVec select(const BoolInVec & vec0, const BoolInVec & vec1, const BoolInVec & select_vec1);
} VECTORMATH_ALIGNED_TYPE_POST;
// ========================================================
// BoolInVec functions
// ========================================================
// operators
//
inline const BoolInVec operator == (const BoolInVec & vec0, const BoolInVec & vec1);
inline const BoolInVec operator != (const BoolInVec & vec0, const BoolInVec & vec1);
inline const BoolInVec operator & (const BoolInVec & vec0, const BoolInVec & vec1);
inline const Vector4Int operator & (const BoolInVec & vec0, const Vector4Int& vec1);
inline const BoolInVec operator ^ (const BoolInVec & vec0, const BoolInVec & vec1);
inline const BoolInVec operator | (const BoolInVec & vec0, const BoolInVec & vec1);
// select between vec0 and vec1 using BoolInVec.
// false selects vec0, true selects vec1
//
inline const BoolInVec select(const BoolInVec & vec0, const BoolInVec & vec1, const BoolInVec & select_vec1);
} // namespace SSE
} // namespace Vectormath
// ========================================================
// BoolInVec implementation
// ========================================================
#include "floatinvec.hpp"
namespace Vectormath
{
namespace SSE
{
inline BoolInVec::BoolInVec(__m128 vec)
{
mData = vec;
}
inline BoolInVec::BoolInVec(const FloatInVec & vec)
{
*this = (vec != FloatInVec(0.0f));
}
inline BoolInVec::BoolInVec(bool scalar)
{
union
{
unsigned int mask;
float f;
} tmp;
tmp.mask = -(int)scalar;
mData = _mm_set1_ps(tmp.f);
}
#ifdef VECTORMATH_NO_SCALAR_CAST
inline bool BoolInVec::getAsBool() const
#else
inline BoolInVec::operator bool() const
#endif
{
// cast to unsigned char* instead of bool*
// mData of type __m128 stores either 0xffffffff or 0x0 to reflect a boolean value
// 0xffffffff as seen as a float is NaN, which would cause the cast to bool* to trigger an
// undefined behavior error because it assumes NaN to be uninitialized.
return *(unsigned char*)&mData;
}
inline __m128 BoolInVec::get128() const
{
return mData;
}
inline const BoolInVec BoolInVec::operator ! () const
{
return BoolInVec(_mm_andnot_ps(mData, _mm_cmpneq_ps(_mm_setzero_ps(), _mm_setzero_ps())));
}
inline BoolInVec & BoolInVec::operator = (const BoolInVec & vec)
{
mData = vec.mData;
return *this;
}
inline BoolInVec & BoolInVec::operator &= (const BoolInVec & vec)
{
*this = *this & vec;
return *this;
}
inline BoolInVec & BoolInVec::operator ^= (const BoolInVec & vec)
{
*this = *this ^ vec;
return *this;
}
inline BoolInVec & BoolInVec::operator |= (const BoolInVec & vec)
{
*this = *this | vec;
return *this;
}
inline const BoolInVec operator == (const BoolInVec & vec0, const BoolInVec & vec1)
{
return BoolInVec(_mm_cmpeq_ps(vec0.get128(), vec1.get128()));
}
inline const BoolInVec operator != (const BoolInVec & vec0, const BoolInVec & vec1)
{
return BoolInVec(_mm_cmpneq_ps(vec0.get128(), vec1.get128()));
}
inline const BoolInVec operator & (const BoolInVec & vec0, const BoolInVec & vec1)
{
return BoolInVec(_mm_and_ps(vec0.get128(), vec1.get128()));
}
inline const Vector4Int operator & (const BoolInVec& vec0, const Vector4Int& vec1)
{
return _mm_and_si128(_mm_castps_si128(vec0.get128()), vec1);
}
inline const BoolInVec operator | (const BoolInVec & vec0, const BoolInVec & vec1)
{
return BoolInVec(_mm_or_ps(vec0.get128(), vec1.get128()));
}
inline const BoolInVec operator ^ (const BoolInVec & vec0, const BoolInVec & vec1)
{
return BoolInVec(_mm_xor_ps(vec0.get128(), vec1.get128()));
}
inline const BoolInVec select(const BoolInVec & vec0, const BoolInVec & vec1, const BoolInVec & select_vec1)
{
return BoolInVec(sseSelect(vec0.get128(), vec1.get128(), select_vec1.get128()));
}
} // namespace SSE
} // namespace Vectormath
#endif // VECTORMATH_SSE_BOOLINVEC_HPP
| 33.436735
| 120
| 0.692017
|
Mercesa
|
44e718badd567bd6de06d2da5e64b9d10526c15f
| 1,159
|
hpp
|
C++
|
include/uneuro/network.hpp
|
AdamsPL/uneuro
|
9f4c74051b1accf05cbc7fb22a834c96bb5c100f
|
[
"MIT"
] | null | null | null |
include/uneuro/network.hpp
|
AdamsPL/uneuro
|
9f4c74051b1accf05cbc7fb22a834c96bb5c100f
|
[
"MIT"
] | null | null | null |
include/uneuro/network.hpp
|
AdamsPL/uneuro
|
9f4c74051b1accf05cbc7fb22a834c96bb5c100f
|
[
"MIT"
] | null | null | null |
#pragma once
#include <cstdlib>
#include <tuple>
#include "backprop.hpp"
#include "utils.hpp"
template <typename... Layers>
class Network
{
public:
constexpr Network(Layers&&... layers)
: layers(layers...)
{
}
template <size_t N>
constexpr auto &get()
{
return std::get<N>(layers);
}
template<size_t N = 0>
constexpr void init()
{
if constexpr (N < std::tuple_size_v<decltype(layers)>) {
std::get<N>(layers).init();
init<N+1>();
}
}
template<size_t N = 0>
constexpr void print() const
{
if constexpr (N < std::tuple_size_v<decltype(layers)>) {
std::get<N>(layers).print();
print<N+1>();
}
}
template <size_t N = 0, typename InputType>
constexpr auto forward(const InputType &input) const
{
if constexpr (N == std::tuple_size_v<decltype(layers)>) {
return input;
} else {
return forward<N+1>(std::get<N>(layers).forward(input));
}
}
template <template <typename> class Algorithm>
std::tuple<Algorithm<Layers>...> wrapLayers()
{
return std::tuple<Algorithm<Layers>...>();
}
private:
std::tuple<Layers...> layers;
};
template <typename... Layers>
Network(Layers...) -> Network<Layers...>;
| 17.830769
| 59
| 0.646247
|
AdamsPL
|
44ea13fc52be2863e61e12a14ed144548672075b
| 1,387
|
cpp
|
C++
|
Shoot-Game-Ver.1/Project3/MapLoader.cpp
|
Piorosen/Yore-Program
|
939e4633648db0f5b2e24fe7b639a232f5518a16
|
[
"MIT"
] | null | null | null |
Shoot-Game-Ver.1/Project3/MapLoader.cpp
|
Piorosen/Yore-Program
|
939e4633648db0f5b2e24fe7b639a232f5518a16
|
[
"MIT"
] | null | null | null |
Shoot-Game-Ver.1/Project3/MapLoader.cpp
|
Piorosen/Yore-Program
|
939e4633648db0f5b2e24fe7b639a232f5518a16
|
[
"MIT"
] | null | null | null |
#include "MapLoader.h"
MapLoader::MapLoader()
{
m_mapdata = 0;
path.operator=('\0');
}
void MapLoader::Initialize(unsigned int width, unsigned int height, const char * path)
{
m_mapdata = new MapData*[height];
for (int i = 0; i < height; i++) {
m_mapdata[i] = new MapData[width];
}
m_width = width;
m_height = height;
this->path = path;
}
void MapLoader::Shutdown()
{
for (int i = 0; i < m_height; i++) {
delete m_mapdata[i];
}
delete m_mapdata;
}
void MapLoader::Load(const char *name, MapData** &returndata)
{
if (!m_mapdata)
return;
path += name;
std::ifstream file(path);
char data[100];
for (int i = 0; i < m_width * m_height; i++) {
char token = '/';
file >> data;
auto var = split(data, token);
m_mapdata[i / m_width][i % m_width].Filed = atoi(var[0].c_str());
m_mapdata[i / m_width][i % m_width].Move = atoi(var[1].c_str()) == 0 ? false : true;
m_mapdata[i / m_width][i % m_width].TextureID = atoi(var[2].c_str());
m_mapdata[i / m_width][i % m_width].Alpha = atof(var[3].c_str());
m_mapdata[i / m_width][i % m_width].Red = atof(var[4].c_str());
m_mapdata[i / m_width][i % m_width].Green = atof(var[5].c_str());
m_mapdata[i / m_width][i % m_width].Blue = atof(var[6].c_str());
}
returndata = m_mapdata;
file.close();
}
MapData** MapLoader::GetMapData() const
{
return m_mapdata;
}
MapLoader::~MapLoader()
{
}
| 19.263889
| 86
| 0.626532
|
Piorosen
|
44ee86a5c2a3b775b131400ba00384e0a1f9005e
| 5,714
|
hpp
|
C++
|
general/src/Utils.hpp
|
mrpPhys/Isis
|
0322a660e75f13605b0e6fc9688b0ca99b72999d
|
[
"MIT"
] | null | null | null |
general/src/Utils.hpp
|
mrpPhys/Isis
|
0322a660e75f13605b0e6fc9688b0ca99b72999d
|
[
"MIT"
] | null | null | null |
general/src/Utils.hpp
|
mrpPhys/Isis
|
0322a660e75f13605b0e6fc9688b0ca99b72999d
|
[
"MIT"
] | null | null | null |
///////////////////////////////////////////////////////////
//
// General package
//
// --------------------------------------------------------
//
// AUTHOR: Miguel Ramos Pernas
// e-mail: miguel.ramos.pernas@cern.ch
//
// Last update: 18/09/2017
//
// --------------------------------------------------------
//
// Description:
//
// Template file that contains some utils to work with
// c++ classes.
//
// --------------------------------------------------------
///////////////////////////////////////////////////////////
#ifndef UTILS_H
#define UTILS_H
#include "Definitions.hpp"
#include "Exceptions.hpp"
#include "Messenger.hpp"
#include <cmath>
#include <iostream>
#include <string>
#include <sstream>
//_______________________________________________________________________________
namespace isis {
// Calculates the length ( number of numbers ) for a given interger
size_t calcIntLength( long int integer );
// This function allows to center a string in a place with width equal to
// < size >. In case of working with odd sizes the right hand will always be
// greater.
std::string centerString( const std::string &str,
const size_t &size,
const char &ch = ' ' );
// Checks the current expression to see if it can be pased. If a list of strings
// is given, a check is made to see if all the names in the current expression
// are contained in such list.
void checkParseOpts( const std::string &str, const Strings &lst = {} );
// This function replaces all the substrings of the strings storaged in a vector
// with another
void replaceNames( Strings &vector, std::string istr, std::string ostr );
// Splits a given string < str > taking into account the expression < expr > that
// appears on it. The output is appended to the given vector.
void splitString( Strings &output,
const std::string &str,
const std::string &expr );
// Filters the entries in the given vector following the rules imposed by the
// input variable < regex >. The strings that pass the filter are attached to the
// output vector.
void stringVectorFilter( Strings &output,
const Strings &input,
const std::string ®ex );
// Trims the given string using < trexpr >. All the elements that match this
// expression in the front and back of < str > will be removed.
void trimString( std::string &str, const std::string &trexpr = " " );
//_______________________________________________________________________________
// This function checks if the given string can be converted to a variable of the
// type specified
template <typename type>
bool checkStringType( const std::string &input ) {
std::istringstream iss( input );
type value;
iss >> std::noskipws >> value;
return iss.eof() && !iss.fail();
}
//_______________________________________________________________________________
// Integer power function
template<typename type>
type ipow( const type &value, size_t pw ) {
type res = 1;
while ( pw-- )
res *= value;
return res;
}
//_______________________________________________________________________________
// This function sets < value > to the assignement given in the expression
// < opts > for the name < var >. The format of the string has to be like:
// expr = "var1=2.3 : var2=4e5 : var3=S : var4 : var5=1"
// Note:
// The whitespaces surrounding the < : > symbols can be removed (recommendable).
// Whitespaces can be written surrounding < = > symbols too.
// No whitespaces can be present between characters in the expression to assign.
template<typename type>
void parseOpt( std::string opts, const std::string &var, type &value ) {
size_t endpos, pos, varpos = opts.find(var);
// If the variable is not found an error is displayed
if ( varpos == std::string::npos ) {
IWarning << "Could not parse option \"" << var <<
"\". Key not found." << IEndMsg;
return;
}
// Looks for the end of the current expression
if ( varpos == std::string::npos )
endpos = opts.size();
else
endpos = opts.find(':', varpos);
// If no < = > symbol is found, it is considered that the variable is boolean. The
// static_cast call is needed to allow taking strings as values at compilation time.
pos = opts.find( '=', varpos );
if ( pos >= endpos ) {
bool res = true;
if ( varpos )
while ( opts.at( --varpos ) == '!' ) {
opts.erase( varpos );
res = !res;
}
void *auxptr = &res;
value = *static_cast<type*>( auxptr );
return;
}
++pos;
// Gets the string to parse removing the initial and final whitespaces
opts = opts.substr( pos, endpos - pos );
trimString( opts );
// If the string to be parsed has whitespaces, an error is sent
if ( opts.find( ' ' ) != std::string::npos )
throw BaseException("The value to assign to \"" + var +
"\" has whitespaces; remove them.");
// The string is converted to a stream and the value for the given variable
// is set to its result
std::stringstream ss( opts );
ss >> value;
}
//_______________________________________________________________________________
// Returns a given container as a string
template<template <class ...> class cont, class type>
std::string contToString( const cont<type> &container ) {
std::stringstream ss;
if ( container.size() ) {
ss << '[' << container[ 0 ];
for ( auto it = std::begin(container) + 1; it != std::end(container); ++it )
ss << ", " << *it;
ss << ']';
}
else
ss << "[]";
return ss.str();
}
}
#endif
| 32.83908
| 88
| 0.623031
|
mrpPhys
|
60245a8a5d41bd7df2563e3f78c36f5cc70b0dcc
| 2,989
|
cpp
|
C++
|
Source/Tests/LinuxSyscalls/x64/Memory.cpp
|
Azkali/FEX
|
264ec44276e5e04ba96a559e1407527bbc2135d6
|
[
"MIT"
] | null | null | null |
Source/Tests/LinuxSyscalls/x64/Memory.cpp
|
Azkali/FEX
|
264ec44276e5e04ba96a559e1407527bbc2135d6
|
[
"MIT"
] | null | null | null |
Source/Tests/LinuxSyscalls/x64/Memory.cpp
|
Azkali/FEX
|
264ec44276e5e04ba96a559e1407527bbc2135d6
|
[
"MIT"
] | null | null | null |
#include "Tests/LinuxSyscalls/Syscalls.h"
#include "Tests/LinuxSyscalls/x64/Syscalls.h"
#include <FEXCore/Core/Context.h>
#include <FEXCore/Debug/InternalThreadState.h>
#include <sys/mman.h>
#include <sys/shm.h>
#include <map>
#include <unistd.h>
#include <FEXCore/Core/Context.h>
#include <FEXCore/Config/Config.h>
#include <fstream>
#include <filesystem>
static std::string get_fdpath(int fd)
{
std::error_code ec;
return std::filesystem::canonical(std::filesystem::path("/proc/self/fd") / std::to_string(fd), ec).string();
}
namespace FEX::HLE::x64 {
void RegisterMemory() {
REGISTER_SYSCALL_IMPL_X64(munmap, [](FEXCore::Core::CpuStateFrame *Frame, void *addr, size_t length) -> uint64_t {
uint64_t Result = ::munmap(addr, length);
auto Thread = Frame->Thread;
if (Result != -1) {
FEXCore::Context::RemoveNamedRegion(Thread->CTX, (uintptr_t)addr, length);
FEXCore::Context::FlushCodeRange(Thread, (uintptr_t)addr, length);
}
SYSCALL_ERRNO();
});
REGISTER_SYSCALL_IMPL_X64(mmap, [](FEXCore::Core::CpuStateFrame *Frame, void *addr, size_t length, int prot, int flags, int fd, off_t offset) -> uint64_t {
static FEX_CONFIG_OPT(AOTIRLoad, AOTIR_LOAD);
uint64_t Result = reinterpret_cast<uint64_t>(::mmap(addr, length, prot, flags, fd, offset));
auto Thread = Frame->Thread;
if (Result != -1) {
if (!(flags & MAP_ANONYMOUS)) {
auto filename = get_fdpath(fd);
FEXCore::Context::AddNamedRegion(Thread->CTX, Result, length, offset, filename);
}
FEXCore::Context::FlushCodeRange(Thread, (uintptr_t)Result, length);
}
SYSCALL_ERRNO();
});
REGISTER_SYSCALL_IMPL_X64(mremap, [](FEXCore::Core::CpuStateFrame *Frame, void *old_address, size_t old_size, size_t new_size, int flags, void *new_address) -> uint64_t {
uint64_t Result = reinterpret_cast<uint64_t>(::mremap(old_address, old_size, new_size, flags, new_address));
SYSCALL_ERRNO();
});
REGISTER_SYSCALL_IMPL_X64(mprotect, [](FEXCore::Core::CpuStateFrame *Frame, void *addr, size_t len, int prot) -> uint64_t {
uint64_t Result = ::mprotect(addr, len, prot);
auto Thread = Frame->Thread;
if (Result != -1 && prot & PROT_EXEC) {
FEXCore::Context::FlushCodeRange(Thread, (uintptr_t)addr, len);
}
SYSCALL_ERRNO();
});
REGISTER_SYSCALL_IMPL_X64(mlockall, [](FEXCore::Core::CpuStateFrame *Frame, int flags) -> uint64_t {
uint64_t Result = ::mlockall(flags);
SYSCALL_ERRNO();
});
REGISTER_SYSCALL_IMPL_X64(munlockall, [](FEXCore::Core::CpuStateFrame *Frame) -> uint64_t {
uint64_t Result = ::munlockall();
SYSCALL_ERRNO();
});
REGISTER_SYSCALL_IMPL_X64(shmat, [](FEXCore::Core::CpuStateFrame *Frame, int shmid, const void *shmaddr, int shmflg) -> uint64_t {
uint64_t Result = reinterpret_cast<uint64_t>(shmat(shmid, shmaddr, shmflg));
SYSCALL_ERRNO();
});
}
}
| 36.45122
| 174
| 0.669789
|
Azkali
|
602612c100826058d95f8390572915e5460a5eeb
| 2,575
|
cxx
|
C++
|
debs/com.maxleiter.FLTK/usr/local/share/doc/fltk/examples/resizebox.cxx
|
MaxLeiter/Cydia
|
eb5ac542926523d55c7732c2077162daf5f3e0ef
|
[
"MIT"
] | 4
|
2020-05-15T03:43:53.000Z
|
2021-06-05T16:21:31.000Z
|
debs/com.maxleiter.FLTK/usr/local/share/doc/fltk/examples/resizebox.cxx
|
MaxLeiter/Cydia
|
eb5ac542926523d55c7732c2077162daf5f3e0ef
|
[
"MIT"
] | 1
|
2021-04-19T19:48:04.000Z
|
2021-04-19T19:48:04.000Z
|
debs/com.maxleiter.FLTK/usr/local/share/doc/fltk/examples/resizebox.cxx
|
MaxLeiter/Cydia
|
eb5ac542926523d55c7732c2077162daf5f3e0ef
|
[
"MIT"
] | 11
|
2020-03-28T19:24:12.000Z
|
2021-10-18T00:20:45.000Z
|
//
// "$Id$"
//
// Resize box test program for the Fast Light Tool Kit (FLTK).
//
// Copyright 1998-2010 by Bill Spitzak and others.
//
// This library is free software. Distribution and use rights are outlined in
// the file "COPYING" which should have been included with this file. If this
// file is missing or damaged, see the license at:
//
// http://www.fltk.org/COPYING.php
//
// Please report all bugs and problems on the following page:
//
// http://www.fltk.org/str.php
//
#define W1 (big ? 60 : 40)
#define B 0
#define W3 (5*W1+6*B)
#include <FL/Fl.H>
#include <FL/Fl_Double_Window.H>
#include <FL/Fl_Box.H>
#include <FL/Fl_Radio_Button.H>
#include <FL/fl_draw.H>
#include <FL/fl_message.H>
Fl_Double_Window *window;
Fl_Box *box;
int big = 0;
void b_cb(Fl_Widget *,long w) {
if (window->w() != W3 || window->h() != W3) {
fl_message("Put window back to minimum size before changing");
return;
}
window->init_sizes();
switch (w) {
case 0: box->hide(); window->box(FL_FLAT_BOX); window->resizable(0); return;
case 8: box->resize(W1+B,W1,2*W1,B); break;
case 2: box->resize(W1+B,W1+B+2*W1,2*W1,B); break;
case 4: box->resize(W1+B,W1,B,2*W1); break;
case 6: box->resize(W1+B+2*W1,W1+B,B,2*W1); break;
}
window->box(FL_NO_BOX);
if (w == 6 || w == 4)
box->label("re\nsiz\nab\nle");
else box->label("resizable");
box->show();
window->resizable(box);
window->redraw();
}
int main(int argc, char **argv) {
window = new Fl_Double_Window(W3,W3);
window->box(FL_NO_BOX);
Fl_Box *n;
for (int x = 0; x<4; x++) for (int y = 0; y<4; y++) {
if ((x==1 || x==2) && (y==1 || y==2)) continue;
n = new Fl_Box(FL_FRAME_BOX,x*(B+W1)+B,y*(B+W1)+B,W1,W1,0);
n->color(x+y+8);
}
n = new Fl_Box(FL_FRAME_BOX,B,4*W1+5*B,4*W1+3*B,W1,0);
n->color(12);
n = new Fl_Box(FL_FRAME_BOX,4*W1+5*B,B,W1,5*W1+4*B,0);
n->color(13);
n = new Fl_Box(FL_FRAME_BOX,W1+B+B,W1+B+B,2*W1+B,2*W1+B,0);
n->color(8);
Fl_Button *b = new Fl_Radio_Button(W1+B+50,W1+B+30,20,20,"@6>");
b->callback(b_cb,6);
(new Fl_Radio_Button(W1+B+30,W1+B+10,20,20,"@8>"))->callback(b_cb,8);
(new Fl_Radio_Button(W1+B+10,W1+B+30,20,20,"@4>"))->callback(b_cb,4);
(new Fl_Radio_Button(W1+B+30,W1+B+50,20,20,"@2>"))->callback(b_cb,2);
(new Fl_Radio_Button(W1+B+30,W1+B+30,20,20,"off"))->callback(b_cb,0);
box = new Fl_Box(FL_FLAT_BOX,0,0,0,0,"resizable");
box->color(FL_DARK2);
b->set();
b->do_callback();
window->end();
window->size_range(W3,W3);
window->show(argc,argv);
return Fl::run();
}
//
// End of "$Id$".
//
| 27.393617
| 78
| 0.619806
|
MaxLeiter
|
602693d9ff5efc9b5a235803ebb8e2378f9914e2
| 7,299
|
cpp
|
C++
|
helloTriangle/Model.cpp
|
JonnyKelso/learnOpenGL
|
3cda765dba002268792cc890cc72dc70ffec5bbc
|
[
"MIT"
] | null | null | null |
helloTriangle/Model.cpp
|
JonnyKelso/learnOpenGL
|
3cda765dba002268792cc890cc72dc70ffec5bbc
|
[
"MIT"
] | null | null | null |
helloTriangle/Model.cpp
|
JonnyKelso/learnOpenGL
|
3cda765dba002268792cc890cc72dc70ffec5bbc
|
[
"MIT"
] | null | null | null |
#include "Model.h"
namespace Graphics
{
unsigned int TextureFromFile(const std::filesystem::path& filename, bool gamma = false)
{
unsigned int textureID;
glGenTextures(1, &textureID);
int width{}, height{}, nrComponents{};
if (auto data { stbi_load(filename.generic_string().c_str(), &width, &height, &nrComponents, 0) })
{
GLenum format{};
if (nrComponents == 1)
format = GL_RED;
else if (nrComponents == 3)
format = GL_RGB;
else if (nrComponents == 4)
format = GL_RGBA;
glBindTexture(GL_TEXTURE_2D, textureID);
glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
stbi_image_free(data);
}
else
{
std::cout << "Texture failed to load at path: " << filename << std::endl;
}
return textureID;
}
void Model::Draw(Graphics::ShaderProgram &shader)
{
for(auto& mesh : m_Meshes)
mesh.Draw(shader);
}
void Model::loadModel(const std::filesystem::path& path)
{
Assimp::Importer import;
const aiScene *scene = import.ReadFile(path, aiProcess_Triangulate | aiProcess_GenSmoothNormals | aiProcess_FlipUVs | aiProcess_CalcTangentSpace);
if(!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode)
{
std::cout << "ERROR::ASSIMP::" << import.GetErrorString() << std::endl;
return;
}
m_Directory = path.parent_path();
processNode(scene->mRootNode, scene);
}
void Model::processNode(aiNode *node, const aiScene *scene)
{
// process all the node's meshes (if any)
for(unsigned int i = 0; i < node->mNumMeshes; i++)
{
aiMesh *mesh = scene->mMeshes[node->mMeshes[i]];
m_Meshes.push_back(processMesh(mesh, scene));
}
// then do the same for each of its children
for(unsigned int i = 0; i < node->mNumChildren; i++)
{
processNode(node->mChildren[i], scene);
}
}
Mesh Model::processMesh(aiMesh *mesh, const aiScene *scene)
{
std::vector<Vertex> vertices;
std::vector<unsigned int> indices;
std::vector<Texture> textures;
for(unsigned int i = 0; i < mesh->mNumVertices; i++)
{
Vertex vertex;
// process vertex positions, normals and texture coordinates
glm::vec3 v3;
v3.x = mesh->mVertices[i].x;
v3.y = mesh->mVertices[i].y;
v3.z = mesh->mVertices[i].z;
vertex.Position = v3;
// normals
if(mesh->HasNormals())
{
v3.x = mesh->mNormals[i].x;
v3.y = mesh->mNormals[i].y;
v3.z = mesh->mNormals[i].z;
vertex.Normal = v3;
}
if(mesh->mTextureCoords[0]) // does the mesh contain texture coordinates?
{
glm::vec2 v2;
v2.x = mesh->mTextureCoords[0][i].x;
v2.y = mesh->mTextureCoords[0][i].y;
vertex.TexCoords = v2;
// tangent
v3.x = mesh->mTangents[i].x;
v3.y = mesh->mTangents[i].y;
v3.z = mesh->mTangents[i].z;
vertex.Tangent = v3;
// bitangent
v3.x = mesh->mBitangents[i].x;
v3.y = mesh->mBitangents[i].y;
v3.z = mesh->mBitangents[i].z;
vertex.Bitangent = v3;
}
else
{
vertex.TexCoords = glm::vec2(0.0f, 0.0f);
}
vertices.push_back(vertex);
}
// process indices
for(unsigned int i = 0; i < mesh->mNumFaces; i++)
{
aiFace face = mesh->mFaces[i];
for(unsigned int j = 0; j < face.mNumIndices; j++)
indices.push_back(face.mIndices[j]);
}
// process materials
aiMaterial* material = scene->mMaterials[mesh->mMaterialIndex];
// we assume a convention for sampler names in the shaders. Each diffuse texture should be named
// as 'texture_diffuseN' where N is a sequential number ranging from 1 to MAX_SAMPLER_NUMBER.
// Same applies to other texture as the following list summarizes:
// diffuse: texture_diffuseN
// specular: texture_specularN
// normal: texture_normalN
// 1. diffuse maps
std::vector<Texture> diffuseMaps = loadMaterialTextures(material, aiTextureType_DIFFUSE, "texture_diffuse");
textures.insert(textures.end(), diffuseMaps.begin(), diffuseMaps.end());
// 2. specular maps
std::vector<Texture> specularMaps = loadMaterialTextures(material, aiTextureType_SPECULAR, "texture_specular");
textures.insert(textures.end(), specularMaps.begin(), specularMaps.end());
// 3. normal maps
std::vector<Texture> normalMaps = loadMaterialTextures(material, aiTextureType_HEIGHT, "texture_normal");
textures.insert(textures.end(), normalMaps.begin(), normalMaps.end());
// 4. height maps
std::vector<Texture> heightMaps = loadMaterialTextures(material, aiTextureType_AMBIENT, "texture_height");
textures.insert(textures.end(), heightMaps.begin(), heightMaps.end());
return Mesh(vertices, indices, textures);
}
std::vector<Texture> Model::loadMaterialTextures(aiMaterial *mat, aiTextureType type, std::string typeName)
{
namespace fs = std::filesystem;
std::vector<Texture> textures;
for (unsigned int i = 0; i < mat->GetTextureCount(type); i++)
{
aiString str;
mat->GetTexture(type, i, &str);
const fs::path file{ m_Directory / str.C_Str() };
auto skip = [&file,&textures, &loaded{m_LoadedTextures}]() {
for (auto& tex : loaded)
{
if (tex.file == file)
{
textures.push_back(tex);
return true;
}
}
return false;
}();
if (!skip)
{
Texture texture;
if (!fs::exists(file))
throw std::runtime_error{ file.generic_string().append(" not found") };
texture.id = TextureFromFile(file);
texture.type = typeName;
texture.file = file;
textures.push_back(texture);
m_LoadedTextures.push_back(texture);
}
}
return textures;
}
}
| 36.495
| 154
| 0.538978
|
JonnyKelso
|
6026b0faa1d4acae44baf94a0b30c7ffbddc9b66
| 1,669
|
cpp
|
C++
|
source/Factories/Meadow.cpp
|
badbrainz/pme
|
1c8e6f3d154cc59613f5ef3f2f8293f488c64b28
|
[
"WTFPL"
] | null | null | null |
source/Factories/Meadow.cpp
|
badbrainz/pme
|
1c8e6f3d154cc59613f5ef3f2f8293f488c64b28
|
[
"WTFPL"
] | null | null | null |
source/Factories/Meadow.cpp
|
badbrainz/pme
|
1c8e6f3d154cc59613f5ef3f2f8293f488c64b28
|
[
"WTFPL"
] | null | null | null |
#include "Meadow.h"
Meadow::Meadow(const char* strname) : NamedObject(strname)
{
}
void Meadow::addPatch(GrassPatch* patch)
{
patchesList.append(patch);
//updateBounds();
}
void Meadow::setBounds(const Tuple4i& bounds)
{
boundary = bounds;
}
Tuple4i Meadow::getBounds()
{
return boundary;
}
GrassPatch* Meadow::getPatch(unsigned int index)
{
return patchesList(index);
}
unsigned int Meadow::getPatchCount()
{
return patchesList.length();
}
void Meadow::updateBounds()
{
if (patchesList.isEmpty())
return;
Tuple4i bounds(1000, 1000, -1000, -1000);
GrassPatch* patch;
bounds.x = patchesList(0)->position.x;
bounds.y = patchesList(0)->position.y;
bounds.z = bounds.x;
bounds.w = bounds.y;
for (unsigned int i = 0; i < patchesList.length(); i++)
{
patch = patchesList(i);
bounds.x = bounds.x < patch->position.x ? bounds.x : patch->position.x;
bounds.y = bounds.y < patch->position.y ? bounds.y : patch->position.y;
bounds.z = bounds.z > patch->position.x ? bounds.z : patch->position.x;
bounds.w = bounds.w > patch->position.y ? bounds.w : patch->position.y;
}
bounds.z = 1 + bounds.z - bounds.x;
bounds.w = 1 + bounds.w - bounds.y;
boundary = bounds;
}
void Meadow::addTileIndex(unsigned int index)
{
tileIdentifierList.append(index);
}
bool Meadow::containsTileIndex(unsigned int index)
{
return tileIdentifierList.contains(index);
}
void Meadow::clearPatches()
{
patchesList.clearAndDestroy();
tileIdentifierList.clear();
}
Meadow::~Meadow()
{
patchesList.clearAndDestroy();
tileIdentifierList.clear();
}
| 20.8625
| 76
| 0.653086
|
badbrainz
|
602c7f1f9f8e3a59e6b95bc2a44b377c8b1e324e
| 12,499
|
cpp
|
C++
|
src/src/pngimg.cpp
|
qiwenwang/imgpp
|
40c27a1c6fa66fbc569e10cf2f1e8aa86e1b7097
|
[
"MIT"
] | null | null | null |
src/src/pngimg.cpp
|
qiwenwang/imgpp
|
40c27a1c6fa66fbc569e10cf2f1e8aa86e1b7097
|
[
"MIT"
] | null | null | null |
src/src/pngimg.cpp
|
qiwenwang/imgpp
|
40c27a1c6fa66fbc569e10cf2f1e8aa86e1b7097
|
[
"MIT"
] | null | null | null |
#include <imgpp/loaders.hpp>
#include <png.h>
#include <imgpp/imgpp.hpp>
namespace imgpp {
bool PNGAbort(const char * s) {
printf("%s\n", s);
return false;
}
bool LoadPNG(const char *fn, Img &img, bool flip_y) {
if (nullptr == fn || 0 == strlen(fn)) {
return false;
}
png_structp png_ptr;
png_infop info_ptr;
int number_of_passes = 0;
png_bytep *row_pointers = nullptr;
char header[8]; // 8 is the maximum size that can be checked
/* open file and test for it being a png */
FILE *fp = fopen(fn, "rb");
if (!fp) {
return PNGAbort("imgpp: file could not be opened for reading!");
}
auto count = fread(header, 1, 8, fp);
if (count < 8 || png_sig_cmp((unsigned char*)header, 0, 8)) {
fclose(fp);
return PNGAbort("imgpp: file is not recognized as a PNG file!");
}
/* initialize stuff */
png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
if (!png_ptr) {
fclose(fp);
return PNGAbort("imgpp: png_create_read_struct failed!");
}
info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr) {
png_destroy_read_struct(&png_ptr, nullptr, nullptr);
fclose(fp);
return PNGAbort("imgpp: png_create_info_struct failed!");
}
if (setjmp(png_jmpbuf(png_ptr))) {
png_destroy_read_struct(&png_ptr, &info_ptr, nullptr);
fclose(fp);
return PNGAbort("imgpp: error setting up libpng!");
}
png_init_io(png_ptr, fp);
png_set_sig_bytes(png_ptr, 8);
png_read_info(png_ptr, info_ptr);
int width = png_get_image_width(png_ptr, info_ptr);
int height = png_get_image_height(png_ptr, info_ptr);
png_byte bit_depth = png_get_bit_depth(png_ptr, info_ptr);
png_byte color_type = png_get_color_type(png_ptr, info_ptr);
png_byte filter_method = png_get_filter_type(png_ptr, info_ptr);
png_byte compression_type = png_get_compression_type(png_ptr, info_ptr);
png_byte interlace_type = png_get_interlace_type(png_ptr, info_ptr);
/* read file */
row_pointers = new png_bytep[height];
int num_channel = 0;
if (color_type == PNG_COLOR_TYPE_GRAY) {
if (bit_depth < 8) {
png_set_expand_gray_1_2_4_to_8(png_ptr);
}
num_channel = 1;
} else if (color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
num_channel = 2;
} else if (color_type == PNG_COLOR_TYPE_PALETTE) {
png_set_palette_to_rgb(png_ptr);
num_channel = 3;
} else if (color_type == PNG_COLOR_TYPE_RGB) {
num_channel = 3;
} else if (color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
num_channel = 4;
}
img.SetSize(width, height, 1, num_channel, bit_depth);
if (flip_y){
for (int y = 0; y < height; y++) {
row_pointers[y] = (unsigned char*)img.ROI().PtrAt(0, height - y - 1, 0);
}
} else {
for (int y = 0; y < height; y++) {
row_pointers[y] = (unsigned char*)img.ROI().PtrAt(0, y, 0);
}
}
number_of_passes = png_set_interlace_handling(png_ptr);
png_read_update_info(png_ptr, info_ptr);
png_read_image(png_ptr, row_pointers);
png_destroy_read_struct(&png_ptr, &info_ptr, nullptr);
fclose(fp);
delete []row_pointers;
return true;
}
bool WritePNG(const char *fn, const ImgROI &roi, bool flip_y) {
if (nullptr == fn || 0 == strlen(fn))
return false;
/* create file */
FILE *fp = fopen(fn, "wb");
if (!fp) {
return PNGAbort("imgpp: file could not be opened for writing!");
}
/* initialize stuff */
png_structp png_ptr;
png_infop info_ptr;
png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
if (!png_ptr) {
png_destroy_write_struct(&png_ptr, nullptr);
return PNGAbort("imgpp: png_create_write_struct failed!");
}
info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr) {
png_destroy_write_struct(&png_ptr, &info_ptr);
return PNGAbort("imgpp: png_create_info_struct failed!");
}
if (setjmp(png_jmpbuf(png_ptr))) {
png_destroy_write_struct(&png_ptr, &info_ptr);
return PNGAbort("imgpp: Error during init_io!");
}
png_init_io(png_ptr, fp);
/* write header */
if (setjmp(png_jmpbuf(png_ptr))) {
png_destroy_write_struct(&png_ptr, &info_ptr);
return PNGAbort("imgpp: error writing header!");
}
png_byte color_type;
if (1 == roi.Channel()) {
color_type = PNG_COLOR_TYPE_GRAY;
} else if (2 == roi.Channel()) {
color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
} else if (3 == roi.Channel()) {
color_type = PNG_COLOR_TYPE_RGB;
} else if (4 == roi.Channel()) {
color_type = PNG_COLOR_TYPE_RGB_ALPHA;
} else {
png_destroy_write_struct(&png_ptr, &info_ptr);
return PNGAbort("imgpp: error determining color type!");
}
png_set_IHDR(png_ptr, info_ptr, roi.Width(), roi.Height(),
roi.BPC(), color_type, PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
png_write_info(png_ptr, info_ptr);
/* write bytes */
if (setjmp(png_jmpbuf(png_ptr))) {
return PNGAbort("imgpp: error during writing bytes!");
}
png_bytep * row_pointers = new png_bytep[roi.Height()];
if (flip_y) {
for (uint32_t y = 0; y < roi.Height(); ++y) {
row_pointers[y] = (unsigned char *)roi.PtrAt(0, roi.Height() - y - 1, 0);
}
} else {
for (uint32_t y = 0; y < roi.Height(); ++y) {
row_pointers[y] = (unsigned char *)roi.PtrAt(0, y, 0);
}
}
png_write_image(png_ptr, row_pointers);
/* end write */
if (setjmp(png_jmpbuf(png_ptr))) {
return PNGAbort("imgpp: error during end of write!");
}
png_write_end(png_ptr, nullptr);
png_destroy_write_struct(&png_ptr, &info_ptr);
/* cleanup heap allocation */
delete []row_pointers;
fclose(fp);
return true;
}
struct png_io_t {
void *buffer;
size_t length_left;
};
void png_copy_from_buffer(png_structp png_ptr, png_bytep data, png_size_t length) {
png_io_t *png_io = (png_io_t*)png_get_io_ptr(png_ptr);
if (!png_io->buffer || png_io->length_left < length) {
png_error(png_ptr, "EOF");
return;
}
memcpy(data, png_io->buffer, length);
png_io->buffer = (png_bytep)png_io->buffer + length;
png_io->length_left -= length;
}
void png_copy_to_buffer(png_structp png_ptr, png_bytep data, png_size_t length) {
png_io_t *png_io = (png_io_t*)png_get_io_ptr(png_ptr);
if (!png_io->buffer || png_io->length_left < length) {
png_io->buffer = nullptr;
return;
}
memcpy(png_io->buffer, data, length);
png_io->buffer = (png_bytep)png_io->buffer + length;
png_io->length_left -= length;
}
void png_flush_buffer(png_structp) {}
size_t CompressPNG(const ImgROI& roi, void *dst, size_t length) {
/* initialize stuff */
png_structp png_ptr;
png_infop info_ptr;
png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
if (!png_ptr) {
png_destroy_write_struct(&png_ptr, nullptr);
return PNGAbort("imgpp: png_create_write_struct failed!");
}
info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr) {
png_destroy_write_struct(&png_ptr, &info_ptr);
return PNGAbort("imgpp: png_create_info_struct failed!");
}
if (setjmp(png_jmpbuf(png_ptr))) {
png_destroy_write_struct(&png_ptr, &info_ptr);
return PNGAbort("imgpp: error during set_write_fn!");
}
png_io_t png_io;
png_io.buffer = dst;
png_io.length_left = length;
png_set_write_fn(png_ptr, &png_io, png_copy_to_buffer, png_flush_buffer);
/* write header */
if (setjmp(png_jmpbuf(png_ptr))) {
png_destroy_write_struct(&png_ptr, &info_ptr);
return PNGAbort("imgpp: error during writing header!");
}
png_byte color_type;
if (1 == roi.Channel()) {
color_type = PNG_COLOR_TYPE_GRAY;
} else if (2 == roi.Channel()) {
color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
} else if (3 == roi.Channel()) {
color_type = PNG_COLOR_TYPE_RGB;
} else if (4 == roi.Channel()) {
color_type = PNG_COLOR_TYPE_RGB_ALPHA;
} else {
png_destroy_write_struct(&png_ptr, &info_ptr);
return PNGAbort("imgpp: error determining color type!");
}
png_set_IHDR(png_ptr, info_ptr, roi.Width(), roi.Height(),
roi.BPC(), color_type, PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
png_write_info(png_ptr, info_ptr);
/* write bytes */
if (setjmp(png_jmpbuf(png_ptr))) {
png_destroy_write_struct(&png_ptr, &info_ptr);
return PNGAbort("imgpp: error during writing bytes!");
}
png_bytep *row_pointers = new png_bytep[roi.Height()];
if (row_pointers == nullptr) {
png_destroy_write_struct(&png_ptr, &info_ptr);
return PNGAbort("imgpp: failed to allocate memory!");
}
for (uint32_t y = 0; y < roi.Height(); ++y) {
row_pointers[y] = (unsigned char *)roi.PtrAt(0, y, 0);
}
png_write_image(png_ptr, row_pointers);
/* end write */
if (setjmp(png_jmpbuf(png_ptr))) {
png_destroy_write_struct(&png_ptr, &info_ptr);
return PNGAbort("imgpp: error during end of write!");
}
png_write_end(png_ptr, nullptr);
png_destroy_write_struct(&png_ptr, &info_ptr);
/* cleanup heap allocation */
delete[]row_pointers;
return (png_io.buffer != nullptr) ? (length - png_io.length_left) : 0;
}
bool LoadPNG(void *src, uint32_t length, Img &img, bool flip_y) {
if (src == nullptr || length == 0) {
return false;
}
png_structp png_ptr;
png_infop info_ptr;
int number_of_passes = 0;
png_bytep *row_pointers = nullptr;
uint8_t header[8];
memcpy(header, src, 8);
if (png_sig_cmp(header, 0, 8)) {
return PNGAbort("imgpp: file is not recognized as a PNG file!");
}
/* initialize stuff */
png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
if (!png_ptr) {
png_destroy_read_struct(&png_ptr, nullptr, nullptr);
return PNGAbort("imgpp: png_create_read_struct failed!");
}
info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr) {
png_destroy_read_struct(&png_ptr, &info_ptr, nullptr);
return PNGAbort("imgpp: png_create_info_struct failed!");
}
if (setjmp(png_jmpbuf(png_ptr))) {
png_destroy_read_struct(&png_ptr, &info_ptr, nullptr);
return PNGAbort("imgpp: error during init_io!");
}
png_io_t png_io;
png_io.buffer = src;
png_io.length_left = length;
png_set_read_fn(png_ptr, &png_io, png_copy_from_buffer);
png_set_sig_bytes(png_ptr, 0);
png_read_info(png_ptr, info_ptr);
int width = png_get_image_width(png_ptr, info_ptr);
int height = png_get_image_height(png_ptr, info_ptr);
png_byte bit_depth = png_get_bit_depth(png_ptr, info_ptr);
png_byte color_type = png_get_color_type(png_ptr, info_ptr);
png_byte filter_method = png_get_filter_type(png_ptr, info_ptr);
png_byte compression_type = png_get_compression_type(png_ptr, info_ptr);
png_byte interlace_type = png_get_interlace_type(png_ptr, info_ptr);
row_pointers = new png_bytep[height];
int num_channel = 0;
if (color_type == PNG_COLOR_TYPE_GRAY) {
if (bit_depth < 8) {
png_set_expand_gray_1_2_4_to_8(png_ptr);
}
num_channel = 1;
} else if (color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
num_channel = 2;
} else if (color_type == PNG_COLOR_TYPE_PALETTE) {
png_set_palette_to_rgb(png_ptr);
num_channel = 3;
} else if (color_type == PNG_COLOR_TYPE_RGB) {
num_channel = 3;
} else if (color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
num_channel = 4;
}
img.SetSize(width, height, 1, num_channel, bit_depth);
if (flip_y) {
for (int y = 0; y < height; y++) {
row_pointers[y] = (unsigned char*)img.ROI().PtrAt(0, height - y - 1, 0);
}
} else {
for (int y = 0; y < height; y++) {
row_pointers[y] = (unsigned char*)img.ROI().PtrAt(0, y, 0);
}
}
number_of_passes = png_set_interlace_handling(png_ptr);
png_read_update_info(png_ptr, info_ptr);
png_read_image(png_ptr, row_pointers);
png_destroy_read_struct(&png_ptr, &info_ptr, nullptr);
delete []row_pointers;
return true;
}
} //end namespace
| 29.759524
| 88
| 0.651732
|
qiwenwang
|
602d994110f585e8a679121b9570dbd47b80c319
| 14,225
|
cpp
|
C++
|
src/ast/ast.cpp
|
bjorn3/mrustc
|
01f73e7894119405ab3f92b6191f044e491c9062
|
[
"MIT"
] | null | null | null |
src/ast/ast.cpp
|
bjorn3/mrustc
|
01f73e7894119405ab3f92b6191f044e491c9062
|
[
"MIT"
] | null | null | null |
src/ast/ast.cpp
|
bjorn3/mrustc
|
01f73e7894119405ab3f92b6191f044e491c9062
|
[
"MIT"
] | null | null | null |
/*
* MRustC - Rust Compiler
* - By John Hodge (Mutabah/thePowersGang)
*
* ast/ast.cpp
* - Implementation of the various AST classes
*/
#include "ast.hpp"
#include "crate.hpp"
#include "types.hpp"
#include "expr.hpp"
#include "../common.hpp"
#include <iostream>
#include "../parse/parseerror.hpp"
#include <algorithm>
namespace AST {
namespace {
::std::vector<Attribute> clone_mivec(const ::std::vector<Attribute>& v) {
::std::vector<Attribute> ri;
ri.reserve(v.size());
for(const auto& i : v)
ri.push_back( i.clone() );
return ri;
}
}
AttributeList AttributeList::clone() const
{
return AttributeList( clone_mivec(m_items) );
}
void AttributeList::push_back(Attribute i)
{
m_items.push_back( ::std::move(i) );
}
const Attribute* AttributeList::get(const char *name) const
{
for( auto& i : m_items ) {
if(i.name() == name) {
//i.mark_used();
return &i;
}
}
return 0;
}
::std::ostream& operator<<(::std::ostream& os, const AttributeList& x) {
for(const auto& i : x.m_items) {
os << "#[" << i << "]";
}
return os;
}
::std::ostream& operator<<(::std::ostream& os, const AttributeName& x) {
if(x.elems.empty())
{
os << "''";
}
else
{
for(const auto& i : x.elems)
{
if(&i != &x.elems.front())
os << "::";
os << i;
}
}
return os;
}
Attribute::Attribute(const Attribute& x):
m_span(x.m_span),
m_name(x.m_name),
m_is_used(x.m_is_used)
{
struct H {
static AttributeData clone_ad(const AttributeData& ad) {
TU_MATCH_HDRA( (ad), {)
TU_ARMA(None, e)
return AttributeData::make_None({});
TU_ARMA(ValueUnexpanded, e)
return AttributeData::make_ValueUnexpanded( e->clone() );
TU_ARMA(String, e)
return AttributeData::make_String({ e.val });
TU_ARMA(List, e)
return AttributeData::make_List({ clone_mivec(e.sub_items) });
}
throw ::std::runtime_error("Attribute::clone - Fell off end");
}
};
m_data = H::clone_ad(x.m_data);
}
Attribute Attribute::clone() const
{
return Attribute(*this);
}
void Attribute::fmt(std::ostream& os) const
{
os << m_name;
TU_MATCH_HDRA( (m_data), {)
TU_ARMA(None, e) {
}
TU_ARMA(ValueUnexpanded, e) {
os << "=\"" << *e << "\"";
}
TU_ARMA(String, e) {
os << "=\"" << e.val << "\"";
}
TU_ARMA(List, e) {
os << "(" << e.sub_items << ")";
}
}
}
StructItem StructItem::clone() const
{
return StructItem(m_attrs.clone(), m_is_public, m_name, m_type.clone());
}
TupleItem TupleItem::clone() const
{
return TupleItem(m_attrs.clone(), m_is_public, m_type.clone());
}
TypeAlias TypeAlias::clone() const
{
return TypeAlias( m_params.clone(), m_type.clone() );
}
Static Static::clone() const
{
return Static( m_class, m_type.clone(), m_value.is_valid() ? AST::Expr( m_value.node().clone() ) : AST::Expr() );
}
Function::Function(Span sp, GenericParams params, ::std::string abi, bool is_unsafe, bool is_const, bool is_variadic, TypeRef ret_type, Arglist args):
m_span(sp),
m_params( move(params) ),
m_rettype( move(ret_type) ),
m_args( move(args) ),
m_abi( mv$(abi) ),
m_is_const(is_const),
m_is_unsafe(is_unsafe),
m_is_variadic(is_variadic)
{
}
Function Function::clone() const
{
decltype(m_args) new_args;
for(const auto& arg : m_args)
new_args.push_back( ::std::make_pair( arg.first.clone(), arg.second.clone() ) );
auto rv = Function( m_span, m_params.clone(), m_abi, m_is_unsafe, m_is_const, m_is_variadic, m_rettype.clone(), mv$(new_args) );
if( m_code.is_valid() )
{
rv.m_code = AST::Expr( m_code.node().clone() );
}
return rv;
}
void Trait::add_type(Span sp, RcString name, AttributeList attrs, TypeRef type) {
m_items.push_back( Named<Item>(sp, mv$(attrs), true, mv$(name), Item::make_Type({TypeAlias(GenericParams(), mv$(type))})) );
}
void Trait::add_function(Span sp, RcString name, AttributeList attrs, Function fcn) {
DEBUG("trait fn " << name);
m_items.push_back( Named<Item>(sp, mv$(attrs), true, mv$(name), Item::make_Function({mv$(fcn)})) );
}
void Trait::add_static(Span sp, RcString name, AttributeList attrs, Static v) {
m_items.push_back( Named<Item>(sp, mv$(attrs), true, mv$(name), Item::make_Static({mv$(v)})) );
}
void Trait::set_is_marker() {
m_is_marker = true;
}
bool Trait::is_marker() const {
return m_is_marker;
}
bool Trait::has_named_item(const RcString& name, bool& out_is_fcn) const
{
for( const auto& i : m_items )
{
if( i.name == name ) {
out_is_fcn = i.data.is_Function();
return true;
}
}
return false;
}
Trait Trait::clone() const
{
auto rv = Trait(m_params.clone(), m_supertraits);
for(const auto& item : m_items)
{
rv.m_items.push_back( Named<Item> { item.span, item.attrs.clone(), item.is_pub, item.name, item.data.clone() } );
}
return rv;
}
Enum Enum::clone() const
{
decltype(m_variants) new_variants;
for(const auto& var : m_variants)
{
TU_MATCHA( (var.m_data), (e),
(Value,
new_variants.push_back( EnumVariant(var.m_attrs.clone(), var.m_name, e.m_value.clone()) );
),
(Tuple,
decltype(e.m_sub_types) new_st;
for(const auto& f : e.m_sub_types)
new_st.push_back( f.clone() );
new_variants.push_back( EnumVariant(var.m_attrs.clone(), var.m_name, mv$(new_st)) );
),
(Struct,
decltype(e.m_fields) new_fields;
for(const auto& f : e.m_fields)
new_fields.push_back( f.clone() );
new_variants.push_back( EnumVariant(var.m_attrs.clone(), var.m_name, mv$(new_fields)) );
)
)
}
return Enum(m_params.clone(), mv$(new_variants));
}
Struct Struct::clone() const
{
TU_MATCHA( (m_data), (e),
(Unit,
return Struct(m_params.clone());
),
(Tuple,
decltype(e.ents) new_fields;
for(const auto& f : e.ents)
new_fields.push_back( f.clone() );
return Struct(m_params.clone(), mv$(new_fields));
),
(Struct,
decltype(e.ents) new_fields;
for(const auto& f : e.ents)
new_fields.push_back( f.clone() );
return Struct(m_params.clone(), mv$(new_fields));
)
)
throw "";
}
Union Union::clone() const
{
decltype(m_variants) new_vars;
for(const auto& f : m_variants)
new_vars.push_back( f.clone() );
return Union(m_params.clone(), mv$(new_vars));
}
::std::ostream& operator<<(::std::ostream& os, const ImplDef& impl)
{
return os << "impl<" << impl.m_params << "> " << impl.m_trait.ent << " for " << impl.m_type << "";
}
void Impl::add_function(Span sp, AttributeList attrs, bool is_public, bool is_specialisable, RcString name, Function fcn)
{
DEBUG("impl fn " << name);
m_items.push_back( ImplItem { sp, mv$(attrs), is_public, is_specialisable, mv$(name), box$( Item::make_Function(mv$(fcn)) ) } );
}
void Impl::add_type(Span sp, AttributeList attrs, bool is_public, bool is_specialisable, RcString name, TypeRef type)
{
m_items.push_back( ImplItem { sp, mv$(attrs), is_public, is_specialisable, mv$(name), box$( Item::make_Type(TypeAlias(GenericParams(), mv$(type))) ) } );
}
void Impl::add_static(Span sp, AttributeList attrs, bool is_public, bool is_specialisable, RcString name, Static v)
{
m_items.push_back( ImplItem { sp, mv$(attrs), is_public, is_specialisable, mv$(name), box$( Item::make_Static(mv$(v)) ) } );
}
void Impl::add_macro_invocation(MacroInvocation item) {
m_items.push_back( ImplItem { item.span(), {}, false, false, "", box$( Item::make_MacroInv(mv$(item)) ) } );
}
bool Impl::has_named_item(const RcString& name) const
{
for( const auto& it : this->items() )
{
if( it.name == name ) {
return true;
}
}
return false;
}
::std::ostream& operator<<(::std::ostream& os, const Impl& impl)
{
return os << impl.m_def;
}
::std::ostream& operator<<(::std::ostream& os, const UseItem::Ent& x)
{
return os << x.name << "=" << x.path;
}
MacroInvocation MacroInvocation::clone() const
{
return MacroInvocation(m_span, AST::Path(m_macro_path), m_ident, m_input.clone());
}
UseItem UseItem::clone() const
{
decltype(this->entries) entries;
for(const auto& e : this->entries)
{
entries.push_back({ e.sp, e.path, e.name });
}
return UseItem {
this->sp,
mv$(entries)
};
}
void ExternBlock::add_item(Named<Item> named_item)
{
ASSERT_BUG(named_item.span, named_item.data.is_Function() || named_item.data.is_Static() || named_item.data.is_Type(), "Incorrect item type for ExternBlock - " << named_item.data.tag_str());
m_items.push_back( mv$(named_item) );
}
ExternBlock ExternBlock::clone() const
{
TODO(Span(), "Clone an extern block");
}
::std::shared_ptr<AST::Module> Module::add_anon() {
auto rv = ::std::shared_ptr<AST::Module>( new Module(m_my_path + RcString::new_interned(FMT("#" << m_anon_modules.size()))) );
DEBUG("New anon " << rv->m_my_path);
rv->m_file_info = m_file_info;
m_anon_modules.push_back( rv );
return rv;
}
void Module::add_item( Named<Item> named_item ) {
m_items.push_back( box$(named_item) );
const auto& i = m_items.back();
if( i->name == "" ) {
}
else {
DEBUG(m_my_path << "::" << i->name << " = " << i->data.tag_str() << ", attrs = " << i->attrs);
}
}
void Module::add_item(Span sp, bool is_pub, RcString name, Item it, AttributeList attrs) {
add_item( Named<Item>( mv$(sp), mv$(attrs), is_pub, mv$(name), mv$(it) ) );
}
void Module::add_ext_crate(Span sp, bool is_pub, RcString ext_name, RcString imp_name, AttributeList attrs) {
this->add_item( mv$(sp), is_pub, imp_name, Item::make_Crate({mv$(ext_name)}), mv$(attrs) );
}
void Module::add_macro_invocation(MacroInvocation item) {
this->add_item( item.span(), false, "", Item( mv$(item) ), ::AST::AttributeList {} );
}
void Module::add_macro(bool is_exported, RcString name, MacroRulesPtr macro) {
m_macros.push_back( Named<MacroRulesPtr>( Span(), {}, /*is_pub=*/is_exported, mv$(name), mv$(macro) ) );
}
Item Item::clone() const
{
TU_MATCHA( (*this), (e),
(None,
return Item(e);
),
(MacroInv,
TODO(Span(), "Clone on Item::MacroInv");
),
(Macro,
TODO(Span(), "Clone on Item::Macro");
),
(Use,
return Item(e.clone());
),
(ExternBlock,
TODO(Span(), "Clone on Item::" << this->tag_str());
),
(Impl,
TODO(Span(), "Clone on Item::" << this->tag_str());
),
(NegImpl,
TODO(Span(), "Clone on Item::" << this->tag_str());
),
(Module,
TODO(Span(), "Clone on Item::" << this->tag_str());
),
(Crate,
return Item(e);
),
(Type,
return AST::Item(e.clone());
),
(Struct,
return AST::Item(e.clone());
),
(Enum,
return AST::Item(e.clone());
),
(Union,
return AST::Item(e.clone());
),
(Trait,
return AST::Item(e.clone());
),
(TraitAlias,
return AST::Item(e.clone());
),
(Function,
return AST::Item(e.clone());
),
(Static,
return AST::Item(e.clone());
)
)
throw "";
}
::std::ostream& operator<<(::std::ostream& os, const TypeParam& tp)
{
//os << "TypeParam(";
os << tp.m_name;
os << " = ";
os << tp.m_default;
//os << ")";
return os;
}
::std::ostream& operator<<(::std::ostream& os, const LifetimeParam& p)
{
os << "'" << p.m_name;
return os;
}
::std::ostream& operator<<(::std::ostream& os, const ValueParam& p)
{
os << "const " << p.m_name << ": " << p.m_type;
return os;
}
::std::ostream& operator<<(::std::ostream& os, const HigherRankedBounds& x)
{
if( !x.empty() )
{
os << "for<";
for(const auto& l : x.m_lifetimes)
os << "'" << l << ",";
os << "> ";
}
return os;
}
GenericParam GenericParam::clone() const
{
TU_MATCH_HDRA( (*this), {)
TU_ARMA(None, e)
return e;
TU_ARMA(Lifetime, e)
return LifetimeParam(e);
TU_ARMA(Type, e)
return TypeParam(e);
TU_ARMA(Value, e)
return ValueParam(e);
}
throw "";
}
std::ostream& operator<<(std::ostream& os, const GenericParam& x)
{
TU_MATCH_HDRA( (x), {)
TU_ARMA(None, e)
os << "/*-*/";
TU_ARMA(Lifetime, e)
os << e;
TU_ARMA(Type, e)
os << e;
TU_ARMA(Value, e)
os << e;
}
return os;
}
::std::ostream& operator<<(::std::ostream& os, const GenericBound& x)
{
TU_MATCH_HDRA( (x), {)
TU_ARMA(None, ent) {
os << "/*-*/";
}
TU_ARMA(Lifetime, ent) {
os << "'" << ent.test << ": '" << ent.bound;
}
TU_ARMA(TypeLifetime, ent) {
os << ent.type << ": '" << ent.bound;
}
TU_ARMA(IsTrait, ent) {
os << ent.outer_hrbs << ent.type << ": " << ent.inner_hrbs << ent.trait;
}
TU_ARMA(MaybeTrait, ent) {
os << ent.type << ": ?" << ent.trait;
}
TU_ARMA(NotTrait, ent) {
os << ent.type << ": !" << ent.trait;
}
TU_ARMA(Equality, ent) {
os << ent.type << " = " << ent.replacement;
}
}
return os;
}
//int GenericParams::find_name(const char* name) const
//{
// for( unsigned int i = 0; i < m_type_params.size(); i ++ )
// {
// if( m_type_params[i].name() == name )
// return i;
// }
// DEBUG("Type param '" << name << "' not in list");
// return -1;
//}
::std::ostream& operator<<(::std::ostream& os, const GenericParams& tps)
{
return os << "<" << tps.m_params << "> where {" << tps.m_bounds << "}";
}
} // namespace AST
| 26.99241
| 194
| 0.56717
|
bjorn3
|
602e30b8fa104bc24388b755a999413c6a922877
| 22,654
|
cpp
|
C++
|
system/jlib/junicode.cpp
|
rpastrana/HPCC-Platform
|
489454bd326ed6a39228c81f5d837c276724c022
|
[
"Apache-2.0"
] | 1
|
2021-01-23T18:54:19.000Z
|
2021-01-23T18:54:19.000Z
|
system/jlib/junicode.cpp
|
RoySRobinson/HPCC-Platform
|
338c890a0bf1f6ca55d7b20c791131e4c060579d
|
[
"Apache-2.0"
] | 1
|
2016-04-06T16:41:58.000Z
|
2016-04-06T16:41:58.000Z
|
system/jlib/junicode.cpp
|
cloLN/HPCC-Platform
|
42ffb763a1cdcf611d3900831973d0a68e722bbe
|
[
"Apache-2.0"
] | 1
|
2019-10-26T22:05:26.000Z
|
2019-10-26T22:05:26.000Z
|
/*##############################################################################
HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
############################################################################## */
#include "platform.h"
#include "jliball.hpp"
#include "jerror.hpp"
#include "junicode.hpp"
/* Based on code extracted from the following source... Changed quite signficantly */
/*
* Copyright 2001 Unicode, Inc.
*
* Disclaimer
*
* This source code is provided as is by Unicode, Inc. No claims are
* made as to fitness for any particular purpose. No warranties of any
* kind are expressed or implied. The recipient agrees to determine
* applicability of information provided. If this file has been
* purchased on magnetic or optical media from Unicode, Inc., the
* sole remedy for any claim will be exchange of defective media
* within 90 days of receipt.
*
* Limitations on Rights to Redistribute This Code
*
* Unicode, Inc. hereby grants the right to freely use the information
* supplied in this file in the creation of products supporting the
* Unicode Standard, and to make copies of this file in any form
* for internal or external distribution as long as this notice
* remains attached.
*/
//----------------------------------------------------------------------------
static const int halfShift = 10; /* used for shifting by 10 bits */
static const UTF32 halfBase = 0x0010000UL;
static const UTF32 halfMask = 0x3FFUL;
#define UNI_REPLACEMENT_CHAR (UTF32)0x0000FFFD
#define UNI_MAX_BMP (UTF32)0x0000FFFF
#define UNI_MAX_UTF16 (UTF32)0x0010FFFF
#define UNI_MAX_UTF32 (UTF32)0x7FFFFFFF
#define UNI_SUR_HIGH_START (UTF32)0xD800
#define UNI_SUR_HIGH_END (UTF32)0xDBFF
#define UNI_SUR_LOW_START (UTF32)0xDC00
#define UNI_SUR_LOW_END (UTF32)0xDFFF
UTF32 UtfReader::next()
{
switch (type)
{
case Utf8: return next8();
case Utf16le: return next16le();
case Utf16be: return next16be();
case Utf32le: return next32le();
case Utf32be: return next32be();
}
UNIMPLEMENTED;
}
size32_t UtfReader::getLegalLength()
{
const byte * saved = cur;
while (next() < errorLowerLimit)
{
}
size32_t ret = (size32_t)(cur-saved);
cur = saved;
return ret;
}
//---------------------------------------------------------------------------
UTF32 UtfReader::next32le()
{
if (end - cur < 4) return sourceExhausted;
UTF32 ch = *(UTF32 *)cur;
if (strictConversion && ((ch >= UNI_SUR_HIGH_START) && (ch <= UNI_SUR_LOW_END)))
return sourceIllegal;
cur += sizeof(UTF32);
return ch;
}
//---------------------------------------------------------------------------
UTF32 UtfReader::next32be()
{
if (end - cur < 4) return sourceExhausted;
UTF32 ch;
_cpyrev4(&ch, cur);
if (strictConversion && ((ch >= UNI_SUR_HIGH_START) && (ch <= UNI_SUR_LOW_END)))
return sourceIllegal;
cur += sizeof(UTF32);
return ch;
}
//---------------------------------------------------------------------------
UTF32 UtfReader::next16le()
{
if (end - cur < 2) return sourceExhausted;
const byte * source = cur;
UTF32 ch = source[0] | (source[1] << 8);
source += 2;
if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_HIGH_END)
{
if (end - cur < 2)
return sourceExhausted;
UTF32 ch2 = source[0] | (source[1] << 8);
source += 2;
if (ch2 >= UNI_SUR_LOW_START && ch2 <= UNI_SUR_LOW_END)
{
ch = ((ch - UNI_SUR_HIGH_START) << halfShift)
+ (ch2 - UNI_SUR_LOW_START) + halfBase;
}
else if (strictConversion) /* it's an unpaired high surrogate */
return sourceIllegal;
}
else if ((strictConversion) && (ch >= UNI_SUR_LOW_START && ch <= UNI_SUR_LOW_END))
return sourceIllegal;
cur = (const byte *)source;
return ch;
}
//---------------------------------------------------------------------------
UTF32 UtfReader::next16be()
{
if (end - cur < 2) return sourceExhausted;
const byte * source = cur;
UTF32 ch = (source[0] << 8) | source[1];
source += 2;
if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_HIGH_END)
{
if (end - cur < 2)
return sourceExhausted;
UTF32 ch2 = (source[0] << 8) | source[1];
source += 2;
if (ch2 >= UNI_SUR_LOW_START && ch2 <= UNI_SUR_LOW_END)
{
ch = ((ch - UNI_SUR_HIGH_START) << halfShift)
+ (ch2 - UNI_SUR_LOW_START) + halfBase;
}
else if (strictConversion) /* it's an unpaired high surrogate */
return sourceIllegal;
}
else if ((strictConversion) && (ch >= UNI_SUR_LOW_START && ch <= UNI_SUR_LOW_END))
return sourceIllegal;
cur = source;
return ch;
}
//---------------------------------------------------------------------------
//This is probably faster than a table lookup on modern processors since it would avoid a cache hit.
//Especially because first branch is the most common.
inline unsigned getTrailingBytesForUTF8(byte value)
{
if (value < 0xc0)
return 0;
if (value < 0xe0)
return 1;
if (value < 0xf0)
return 2;
if (value < 0xf8)
return 3;
if (value < 0xfc)
return 4;
return 5;
}
/*
* Magic values subtracted from a buffer value during UTF8 conversion.
* This table contains as many values as there might be trailing bytes
* in a UTF-8 sequence.
*/
static const UTF32 offsetsFromUTF8[6] = { 0x00000000UL, 0x00003080UL, 0x000E2080UL,
0x03C82080UL, 0xFA082080UL, 0x82082080UL };
/*
* Utility routine to tell whether a sequence of bytes is legal UTF-8.
* This must be called with the length pre-determined by the first byte.
* If not calling this from ConvertUTF8to*, then the length can be set by:
* length = trailingBytesForUTF8[*source]+1;
* and the sequence is illegal right away if there aren't that many bytes
* available.
* If presented with a length > 4, this returns false. The Unicode
* definition of UTF-8 goes up to 4-byte sequences.
*/
unsigned readUtf8Size(const void * _data)
{
const byte * ptr = (const byte *)_data;
return getTrailingBytesForUTF8(*ptr)+1;
}
UTF32 readUtf8Char(const void * _data)
{
const byte * ptr = (const byte *)_data;
unsigned short extraBytesToRead = getTrailingBytesForUTF8(*ptr);
UTF32 ch = 0;
switch (extraBytesToRead) {
case 3: ch += *ptr++; ch <<= 6; // fallthrough
case 2: ch += *ptr++; ch <<= 6; // fallthrough
case 1: ch += *ptr++; ch <<= 6; // fallthrough
case 0: ch += *ptr++;
}
return ch - offsetsFromUTF8[extraBytesToRead];
}
inline bool isLegalUTF8(const UTF8 *source, unsigned length)
{
UTF8 a;
const UTF8 *srcptr = source+length;
switch (length)
{
default: return false;
/* Everything else falls through when "true"... */
case 4:
if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return false;
// fallthrough
case 3:
if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return false;
// fallthrough
case 2: if ((a = (*--srcptr)) > 0xBF) return false;
switch (*source)
{
/* no fall-through in this inner switch */
case 0xE0: if (a < 0xA0) return false; break;
case 0xF0: if (a < 0x90) return false; break;
case 0xF4: if (a > 0x8F) return false; break;
default: if (a < 0x80) return false;
}
// fallthrough
case 1:
if (*source >= 0x80 && *source < 0xC2) return false;
if (*source > 0xF4) return false;
}
return true;
}
/* --------------------------------------------------------------------- */
UTF32 UtfReader::next8()
{
const UTF8* source = (const UTF8*)cur;
if (source >= end) return sourceExhausted;
unsigned short extraBytesToRead = getTrailingBytesForUTF8(*source);
if (source + extraBytesToRead >= end)
return sourceExhausted;
/* Do this check whether lenient or strict */
if (! isLegalUTF8(source, extraBytesToRead+1))
return sourceIllegal;
/*
* The cases all fall through. See "Note A" below.
*/
UTF32 ch = 0;
switch (extraBytesToRead) {
case 3: ch += *source++; ch <<= 6; // fallthrough
case 2: ch += *source++; ch <<= 6; // fallthrough
case 1: ch += *source++; ch <<= 6; // fallthrough
case 0: ch += *source++;
}
cur = (const byte *)source;
return ch - offsetsFromUTF8[extraBytesToRead];
}
//---------------------------------------------------------------------------
UTF32 readUtf8Character(unsigned len, const byte * & cur)
{
const UTF8* source = (const UTF8*)cur;
if (len == 0) return sourceExhausted;
unsigned short extraBytesToRead = getTrailingBytesForUTF8(*source);
if (extraBytesToRead >= len)
return sourceExhausted;
/* Do this check whether lenient or strict */
if (! isLegalUTF8(source, extraBytesToRead+1))
return sourceIllegal;
/*
* The cases all fall through. See "Note A" below.
*/
UTF32 ch = 0;
switch (extraBytesToRead) {
case 3: ch += *source++; ch <<= 6; // fallthrough
case 2: ch += *source++; ch <<= 6; // fallthrough
case 1: ch += *source++; ch <<= 6; // fallthrough
case 0: ch += *source++;
}
cur = (const byte *)source;
return ch - offsetsFromUTF8[extraBytesToRead];
}
/*
* Once the bits are split out into bytes of UTF-8, this is a mask OR-ed
* into the first byte, depending on how many bytes follow. There are
* as many entries in this table as there are UTF-8 sequence types.
* (I.e., one byte sequence, two byte... six byte sequence.)
*/
static const UTF8 firstByteMark[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC };
static const UTF32 byteMask = 0xBF;
static const UTF32 byteMark = 0x80;
unsigned writeUtf8(void * vtarget, unsigned maxLength, UTF32 ch)
{
unsigned short bytesToWrite;
/* Figure out how many bytes the result will require */
if (ch < (UTF32)0x80)
bytesToWrite = 1;
else if (ch < (UTF32)0x800)
bytesToWrite = 2;
else if (ch < (UTF32)0x10000)
bytesToWrite = 3;
else if (ch < (UTF32)0x200000)
bytesToWrite = 4;
else {
bytesToWrite = 2;
ch = UNI_REPLACEMENT_CHAR;
}
if (bytesToWrite > maxLength)
return 0;
UTF8 * target = (UTF8 *)vtarget + bytesToWrite;
switch (bytesToWrite) { /* note: everything falls through. */
case 4: *--target = (ch | byteMark) & byteMask; ch >>= 6; // fallthrough
case 3: *--target = (ch | byteMark) & byteMask; ch >>= 6; // fallthrough
case 2: *--target = (ch | byteMark) & byteMask; ch >>= 6; // fallthrough
case 1: *--target = ch | firstByteMark[bytesToWrite];
}
return bytesToWrite;
}
unsigned writeUtf16le(void * vtarget, unsigned maxLength, UTF32 ch)
{
if (maxLength < 2)
return 0;
UTF16 * target = (UTF16 *)vtarget;
if (ch <= UNI_MAX_BMP)
{
/* Target is a character <= 0xFFFF */
if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END)
ch = UNI_REPLACEMENT_CHAR;
*target = ch; /* normal case */
return 2;
}
if (ch > UNI_MAX_UTF16)
{
*target = UNI_REPLACEMENT_CHAR;
return 2;
}
/* target is a character in range 0xFFFF - 0x10FFFF. */
if (maxLength < 4)
return 0;
ch -= halfBase;
target[0] = (ch >> halfShift) + UNI_SUR_HIGH_START;
target[1] = (ch & halfMask) + UNI_SUR_LOW_START;
return 4;
}
unsigned writeUtf16be(void * vtarget, unsigned maxLength, UTF32 ch)
{
if (maxLength < 2)
return 0;
UTF16 * target = (UTF16 *)vtarget;
UTF16 temp;
if (ch <= UNI_MAX_BMP)
{
/* Target is a character <= 0xFFFF */
if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END)
ch = UNI_REPLACEMENT_CHAR;
temp = ch;
_cpyrev2(target, &temp); /* normal case */
return 2;
}
if (ch > UNI_MAX_UTF16)
{
temp = UNI_REPLACEMENT_CHAR;
_cpyrev2(target, &temp);
return 2;
}
/* target is a character in range 0xFFFF - 0x10FFFF. */
if (maxLength < 4)
return 0;
ch -= halfBase;
temp = (ch >> halfShift) + UNI_SUR_HIGH_START;
_cpyrev2(target, &temp);
temp = (ch & halfMask) + UNI_SUR_LOW_START;
_cpyrev2(target+1, &temp);
return 4;
}
unsigned writeUtf32le(void * vtarget, unsigned maxLength, UTF32 ch)
{
if (maxLength < 4) return 0;
*(UTF32 *)vtarget = ch;
return 4;
}
unsigned writeUtf32be(void * vtarget, unsigned maxLength, UTF32 ch)
{
if (maxLength < 4) return 0;
_cpyrev4(vtarget, &ch);
return 4;
}
//---------------------------------------------------------------------------
MemoryBuffer & appendUtf8(MemoryBuffer & out, UTF32 value)
{
char temp[4];
return out.append(writeUtf8(temp, sizeof(temp), value), temp);
}
MemoryBuffer & appendUtf16le(MemoryBuffer & out, UTF32 value)
{
char temp[4];
return out.append(writeUtf16le(temp, sizeof(temp), value), temp);
}
MemoryBuffer & appendUtf16be(MemoryBuffer & out, UTF32 value)
{
char temp[4];
return out.append(writeUtf16be(temp, sizeof(temp), value), temp);
}
MemoryBuffer & appendUtf32le(MemoryBuffer & out, UTF32 value)
{
char temp[4];
return out.append(writeUtf32le(temp, sizeof(temp), value), temp);
}
MemoryBuffer & appendUtf32be(MemoryBuffer & out, UTF32 value)
{
char temp[4];
return out.append(writeUtf32be(temp, sizeof(temp), value), temp);
}
MemoryBuffer & appendUtf(MemoryBuffer & out, UtfReader::UtfFormat targetType, UTF32 value)
{
switch (targetType)
{
case UtfReader::Utf8: appendUtf8(out, value); break;
case UtfReader::Utf16le: appendUtf16le(out, value); break;
case UtfReader::Utf16be: appendUtf16be(out, value); break;
case UtfReader::Utf32le: appendUtf32le(out, value); break;
case UtfReader::Utf32be: appendUtf32be(out, value); break;
}
return out;
}
/* ---------------------------------------------------------------------
Note A.
The fall-through switches in UTF-8 reading code save a
temp variable, some decrements & conditionals. The switches
are equivalent to the following loop:
{
int tmpBytesToRead = extraBytesToRead+1;
do {
ch += *source++;
--tmpBytesToRead;
if (tmpBytesToRead) ch <<= 6;
} while (tmpBytesToRead > 0);
}
In UTF-8 writing code, the switches on "bytesToWrite" are
similarly unrolled loops.
--------------------------------------------------------------------- */
bool convertUtf(MemoryBuffer & target, UtfReader::UtfFormat targetType, unsigned sourceLength, const void * source, UtfReader::UtfFormat sourceType)
{
UtfReader input(sourceType, false);
input.set(sourceLength, source);
unsigned originalLength = target.length();
for (;;)
{
UTF32 next = input.next();
if (next == sourceExhausted)
return true;
if (next == sourceIllegal)
{
target.setLength(originalLength);
return false;
}
appendUtf(target, targetType, next);
}
}
bool convertToUtf8(MemoryBuffer & target, unsigned sourceLength, const void * source)
{
if (sourceLength < 2)
return false;
const byte * text = (const byte *)source;
//check for leading BOM of 0xfeff in the appropriate encoding
if ((text[0] == 0xfe) && (text[1] == 0xff))
return convertUtf(target, UtfReader::Utf8, sourceLength-2, text+2, UtfReader::Utf16be);
if ((text[0] == 0xff) && (text[1] == 0xfe))
{
if (sourceLength >= 4 && (text[2] == 0) && (text[3] == 0))
return convertUtf(target, UtfReader::Utf8, sourceLength-4, text+4, UtfReader::Utf32le);
return convertUtf(target, UtfReader::Utf8, sourceLength-2, text+2, UtfReader::Utf16le);
}
if (sourceLength > 4 && (text[0] == 0) && (text[1] == 0) && (text[2] == 0xfe) && (text[3] == 0xff))
return convertUtf(target, UtfReader::Utf8, sourceLength-4, text+4, UtfReader::Utf32be);
//Try and guess the format
if (text[0] && !text[1])
{
if (text[2])
{
if (convertUtf(target, UtfReader::Utf8, sourceLength, source, UtfReader::Utf16le))
return true;
}
else
{
if (convertUtf(target, UtfReader::Utf8, sourceLength, source, UtfReader::Utf32le))
return true;
}
}
else if (!text[0])
{
if (text[1])
{
if (convertUtf(target, UtfReader::Utf8, sourceLength, source, UtfReader::Utf16be))
return true;
}
else
{
if (convertUtf(target, UtfReader::Utf8, sourceLength, source, UtfReader::Utf32be))
return true;
}
}
//No idea first one that matches wins!
return
convertUtf(target, UtfReader::Utf8, sourceLength, source, UtfReader::Utf16le) ||
convertUtf(target, UtfReader::Utf8, sourceLength, source, UtfReader::Utf16be) ||
convertUtf(target, UtfReader::Utf8, sourceLength, source, UtfReader::Utf32le) ||
convertUtf(target, UtfReader::Utf8, sourceLength, source, UtfReader::Utf32be);
}
//---------------------------------------------------------------------------
void addUtfActionList(StringMatcher & matcher, const char * text, unsigned action, unsigned * maxElementLength, UtfReader::UtfFormat utfFormat)
{
if (!text)
return;
unsigned idx=0;
while (*text)
{
StringBuffer str;
while (*text)
{
char next = *text++;
if (next == ',')
break;
if (next == '\\' && *text)
{
next = *text++;
switch (next)
{
case 'r': next = '\r'; break;
case 'n': next = '\n'; break;
case 't': next = '\t'; break;
case 'x':
//hex constant - at least we can define spaces then...
if (text[0] && text[1])
{
next = (hex2num(*text) << 4) | hex2num(text[1]);
text+=2;
}
break;
default:
break; //otherwise \ just quotes the character e.g. \,
}
}
str.append(next);
}
if (str.length())
{
MemoryBuffer converted;
if (!convertUtf(converted, utfFormat, str.length(), str.str(), UtfReader::Utf8))
throwError(JLIBERR_BadUtf8InArguments);
matcher.queryAddEntry(converted.length(), converted.toByteArray(), action+(idx++<<8));
if (maxElementLength && (converted.length() > *maxElementLength))
*maxElementLength = converted.length();
}
}
}
extern jlib_decl bool replaceUtf(utfReplacementFunc func, MemoryBuffer & target, UtfReader::UtfFormat type, unsigned sourceLength, const void * source)
{
UtfReader input(type, false);
input.set(sourceLength, source);
unsigned originalLength = target.length();
for (;;)
{
const byte * cur = input.cur;
UTF32 next = input.next();
if (next == sourceExhausted)
return true;
if (next == sourceIllegal)
{
target.setLength(originalLength);
return false;
}
func(target, next, type, cur, input.cur-cur, cur==source);
}
}
struct utf32ValidXmlCharRange
{
UTF32 min;
UTF32 max;
bool start;
};
utf32ValidXmlCharRange utf32ValidXmlCharRanges[] = {
{'0', '9', false},
{'A', 'Z', true},
{'a', 'z', true},
{0xC0, 0xD6, true},
{0xD8, 0xF6, true},
{0xF8, 0x2FF, true},
{0x300, 0x36F, false},
{0x370, 0x37D, true},
{0x37F, 0x1FFF, true},
{0x200C, 0x200D, true},
{0x203F, 0x2040, false},
{0x2070, 0x218F, true},
{0x2C00, 0x2FEF, true},
{0x3001, 0xD7FF, true},
{0xF900, 0xFDCF, true},
{0xFDF0, 0xFFFD, true},
{0x10000, 0xEFFFF, true},
{0, 0, false}
};
inline bool replaceBelowRange(UTF32 match, UTF32 replace, int id, MemoryBuffer & target, UtfReader::UtfFormat type, const void * source, int len, bool start)
{
utf32ValidXmlCharRange &r = utf32ValidXmlCharRanges[id];
if (r.min==0)
return true;
if (match>r.max)
return false;
if (match<r.min)
{
appendUtf(target, type, replace);
return true;
}
if (!r.start && start)
appendUtf(target, type, replace);
else
target.append(len, source); //src and target are same, no need to reconvert
return true;
}
MemoryBuffer & utfXmlNameReplacementFunc(MemoryBuffer & target, UTF32 match, UtfReader::UtfFormat type, const void * source, int len, bool start)
{
if (match==':' || match=='_' || (!start && (match=='-' || match=='.' || match==0xB7)))
return target.append(len, source);
for (int i=0; !replaceBelowRange(match, '_', i, target, type, source, len, start); i++);
return target;
}
extern jlib_decl bool appendUtfXmlName(MemoryBuffer & target, UtfReader::UtfFormat type, unsigned sourceLength, const void * source)
{
return replaceUtf(utfXmlNameReplacementFunc, target, type, sourceLength, source);
}
extern jlib_decl bool containsOnlyAscii(const char * source)
{
for (;;)
{
byte next = *source++;
if (!next)
return true;
if (next >= 128)
return false;
}
}
extern jlib_decl bool containsOnlyAscii(size_t sourceLength, const char * source)
{
for (size_t i=0; i < sourceLength; i++)
{
byte next = source[i];
if (next >= 128)
return false;
}
return true;
}
| 30.654939
| 157
| 0.573983
|
rpastrana
|
602e3a2eb0a7e79d64284c89b2c1c2cc37a71234
| 908
|
hpp
|
C++
|
archive/cmdstan/src/cmdstan/print_helper.hpp
|
alashworth/stan-monorepo
|
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
|
[
"BSD-3-Clause"
] | 1
|
2019-09-06T15:53:17.000Z
|
2019-09-06T15:53:17.000Z
|
archive/cmdstan/src/cmdstan/print_helper.hpp
|
alashworth/stan-monorepo
|
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
|
[
"BSD-3-Clause"
] | 8
|
2019-01-17T18:51:16.000Z
|
2019-01-17T18:51:39.000Z
|
archive/cmdstan/src/cmdstan/print_helper.hpp
|
alashworth/stan-monorepo
|
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
|
[
"BSD-3-Clause"
] | null | null | null |
#ifndef CMDSTAN_PRINT_HELPER_HPP
#define CMDSTAN_PRINT_HELPER_HPP
#include <iostream>
void print_deprecated() {
std::cout << std::endl << std::endl;
std::cout << "*** print is deprecated and will be removed in v3.0;"
<< std::endl
<< "*** use stansummary instead"
<< std::endl
<< std::endl;
}
void print_usage() {
std::cout << "USAGE: print <filename 1> [<filename 2> ... <filename N>]"
<< std::endl
<< std::endl;
std::cout << "OPTIONS:" << std::endl << std::endl;
std::cout << " --autocorr=<chain_index>\tAppend the autocorrelations "
<< "for the given chain"
<< std::endl
<< std::endl;
std::cout << " --sig_figs=<int>\tSet significant figures of output "
<< "(Defaults to 2)"
<< std::endl
<< std::endl;
}
#endif
| 28.375
| 76
| 0.511013
|
alashworth
|
602e89c57e1cd0ab83d1136216d5be23b2b04770
| 63,702
|
cpp
|
C++
|
dali/base/dasess.cpp
|
fnisswandt/HPCC-Platform
|
9ae8317441d279d9670e807e8535e74ee7f937ca
|
[
"Apache-2.0"
] | null | null | null |
dali/base/dasess.cpp
|
fnisswandt/HPCC-Platform
|
9ae8317441d279d9670e807e8535e74ee7f937ca
|
[
"Apache-2.0"
] | null | null | null |
dali/base/dasess.cpp
|
fnisswandt/HPCC-Platform
|
9ae8317441d279d9670e807e8535e74ee7f937ca
|
[
"Apache-2.0"
] | null | null | null |
/*##############################################################################
HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
############################################################################## */
#define da_decl DECL_EXPORT
#include "platform.h"
#include "jlib.hpp"
#include "jfile.hpp"
#include "jsuperhash.hpp"
#include "jmisc.hpp"
#include "jencrypt.hpp"
#include "dacoven.hpp"
#include "mpbuff.hpp"
#include "mpcomm.hpp"
#include "mputil.hpp"
#include "daserver.hpp"
#include "dasubs.ipp"
#include "dasds.hpp"
#include "daclient.hpp"
#include "daldap.hpp"
#include "seclib.hpp"
#include "dasess.hpp"
#ifdef _MSC_VER
#pragma warning (disable : 4355)
#endif
const char *queryRoleName(DaliClientRole role)
{
switch (role) {
case DCR_Private: return "Private";
case DCR_Diagnostic: return "Diagnostic";
case DCR_ThorSlave: return "ThorSlave";
case DCR_ThorMaster: return "ThorMaster";
case DCR_EclCCServer: return "EclCCServer";
case DCR_EclCC: return "eclcc";
case DCR_EclServer: return "EclServer";
case DCR_EclScheduler: return "EclScheduler";
case DCR_EclAgent: return "EclAgent";
case DCR_AgentExec: return "AgentExec";
case DCR_DaliServer:return "DaliServer";
case DCR_SashaServer: return "SashaServer";
case DCR_Util: return "Util";
case DCR_Dfu: return "Dfu";
case DCR_DfuServer: return "DfuServer";
case DCR_EspServer: return "EspServer";
case DCR_WuClient: return "WuClient";
case DCR_Config: return "Config";
case DCR_Scheduler: return "Scheduler";
case DCR_RoxyMaster: return "RoxieMaster";
case DCR_RoxySlave: return "RoxieSlave";
case DCR_BackupGen: return "BackupGen";
case DCR_Other: return "Other";
}
return "Unknown";
}
interface ISessionManagerServer: implements IConnectionMonitor
{
virtual SessionId registerSession(SecurityToken tok,SessionId parentid) = 0;
virtual SessionId registerClientProcess(INode *node,IGroup *&grp, DaliClientRole role) = 0;
virtual void addProcessSession(SessionId id, INode *node, DaliClientRole role) = 0;
virtual void addSession(SessionId id) = 0;
virtual SessionId lookupProcessSession(INode *node) = 0;
virtual INode *getProcessSessionNode(SessionId id) =0;
virtual SecAccessFlags getPermissionsLDAP(const char *key,const char *obj,IUserDescriptor *udesc,unsigned flags, int *err)=0;
virtual bool clearPermissionsCache(IUserDescriptor *udesc) = 0;
virtual void stopSession(SessionId sessid,bool failed) = 0;
virtual void setClientAuth(IDaliClientAuthConnection *authconn) = 0;
virtual void setLDAPconnection(IDaliLdapConnection *_ldapconn) = 0;
virtual bool authorizeConnection(int role,bool revoke) = 0;
virtual void start() = 0;
virtual void ready() = 0;
virtual void stop() = 0;
virtual bool queryScopeScansEnabled(IUserDescriptor *udesc, int * err, StringBuffer &retMsg) = 0;
virtual bool enableScopeScans(IUserDescriptor *udesc, bool enable, int * err, StringBuffer &retMsg) = 0;
};
static SessionId mySessionId=0;
static ISessionManager *SessionManager=NULL;
static ISessionManagerServer *SessionManagerServer=NULL;
static CriticalSection sessionCrit;
#define SESSIONREPLYTIMEOUT (3*60*1000)
#define CLDAPE_getpermtimeout (-1)
#define CLDAPE_ldapfailure (-2)
class DECL_EXCEPTION CDaliLDAP_Exception: implements IException, public CInterface
{
int errcode;
public:
CDaliLDAP_Exception(int _errcode)
{
errcode = _errcode;
}
int errorCode() const { return errcode; }
StringBuffer & errorMessage(StringBuffer &str) const
{
if (errcode==0)
return str;
str.appendf("LDAP Exception(%d): ",errcode);
if (errcode==CLDAPE_getpermtimeout)
return str.append("getPermissionsLDAP - timeout to LDAP server");
if (errcode==CLDAPE_ldapfailure)
return str.append("getPermissionsLDAP - LDAP server failure");
return str.append("Unknown Exception");
}
MessageAudience errorAudience() const { return MSGAUD_user; }
IMPLEMENT_IINTERFACE;
};
class CdelayedTerminate: public Thread // slightly obfuscated stop code
{
byte err;
int run()
{
while (getRandom()%711!=0) getRandom(); // look busy
ERRLOG("Server fault %d",(int)err);
while (getRandom()%7!=0) Sleep(1);
exit(0);
}
public:
CdelayedTerminate(byte _err)
{
err = _err;
start();
Release();
Sleep(100);
}
};
class CSessionState: public CInterface
{
protected: friend class CSessionStateTable;
SessionId id;
public:
CSessionState(SessionId _id)
{
id = _id;
}
SessionId getId() const
{
return id;
}
};
class CSessionStateTable: private SuperHashTableOf<CSessionState,SessionId>
{
CheckedCriticalSection sessstatesect;
void onAdd(void *) {}
void onRemove(void *e)
{
CSessionState &elem=*(CSessionState *)e;
elem.Release();
}
unsigned getHashFromElement(const void *e) const
{
const CSessionState &elem=*(const CSessionState *)e;
SessionId id=elem.id;
return low(id)^(unsigned)high(id);
}
unsigned getHashFromFindParam(const void *fp) const
{
SessionId id = *(const SessionId *)fp;
return low(id)^(unsigned)high(id);
}
const void * getFindParam(const void *p) const
{
const CSessionState &elem=*(const CSessionState *)p;
return (void *)&elem.id;
}
bool matchesFindParam(const void * et, const void *fp, unsigned) const
{
return ((CSessionState *)et)->id==*(SessionId *)fp;
}
IMPLEMENT_SUPERHASHTABLEOF_REF_FIND(CSessionState,SessionId);
public:
CSessionStateTable()
{
}
~CSessionStateTable() {
CHECKEDCRITICALBLOCK(sessstatesect,60000);
_releaseAll();
}
bool add(CSessionState *e) // takes ownership
{
CHECKEDCRITICALBLOCK(sessstatesect,60000);
if (SuperHashTableOf<CSessionState,SessionId>::find(&e->id))
return false;
SuperHashTableOf<CSessionState,SessionId>::add(*e);
return true;
}
CSessionState *query(SessionId id)
{
CHECKEDCRITICALBLOCK(sessstatesect,60000);
return SuperHashTableOf<CSessionState,SessionId>::find(&id);
}
void remove(SessionId id)
{
CHECKEDCRITICALBLOCK(sessstatesect,60000);
SuperHashTableOf<CSessionState,SessionId>::remove(&id);
}
};
class CProcessSessionState: public CSessionState
{
INode *node;
DaliClientRole role;
UInt64Array previousSessionIds;
public:
CProcessSessionState(SessionId id,INode *_node,DaliClientRole _role)
: CSessionState(id)
{
node = _node;
node->Link();
role = _role;
}
~CProcessSessionState()
{
node->Release();
}
INode &queryNode() const
{
return *node;
}
DaliClientRole queryRole() const
{
return role;
}
StringBuffer &getDetails(StringBuffer &buf)
{
StringBuffer ep;
return buf.appendf("%16" I64F "X: %s, role=%s",CSessionState::id,node->endpoint().getUrlStr(ep).str(),queryRoleName(role));
}
void addSessionIds(CProcessSessionState &other, bool prevOnly)
{
for (;;)
{
SessionId id = other.dequeuePreviousSessionId();
if (!id)
break;
previousSessionIds.append(id);
}
if (!prevOnly)
previousSessionIds.append(other.getId());
}
SessionId dequeuePreviousSessionId()
{
if (!previousSessionIds.ordinality())
return 0;
return previousSessionIds.popGet();
}
unsigned previousSessionIdCount() const
{
return previousSessionIds.ordinality();
}
void removeOldSessionId(SessionId id)
{
if (previousSessionIds.zap(id))
PROGLOG("Removed old sessionId (%" I64F "x) from current process state", id);
}
};
class CMapProcessToSession: private SuperHashTableOf<CProcessSessionState,INode>
{
CheckedCriticalSection mapprocesssect;
void onAdd(void *) {}
void onRemove(void *e) {} // do nothing
unsigned getHashFromElement(const void *e) const
{
const CProcessSessionState &elem=*(const CProcessSessionState *)e;
return elem.queryNode().getHash();
}
unsigned getHashFromFindParam(const void *fp) const
{
return ((INode *)fp)->getHash();
}
const void * getFindParam(const void *p) const
{
const CProcessSessionState &elem=*(const CProcessSessionState *)p;
return (void *)&elem.queryNode();
}
bool matchesFindParam(const void * et, const void *fp, unsigned) const
{
return ((CProcessSessionState *)et)->queryNode().equals((INode *)fp);
}
IMPLEMENT_SUPERHASHTABLEOF_REF_FIND(CProcessSessionState,INode);
public:
CMapProcessToSession()
{
}
~CMapProcessToSession()
{
CHECKEDCRITICALBLOCK(mapprocesssect,60000);
_releaseAll();
}
bool add(CProcessSessionState *e)
{
CHECKEDCRITICALBLOCK(mapprocesssect,60000);
if (SuperHashTableOf<CProcessSessionState,INode>::find(&e->queryNode()))
return false;
SuperHashTableOf<CProcessSessionState,INode>::add(*e);
return true;
}
void replace(CProcessSessionState *e)
{
CHECKEDCRITICALBLOCK(mapprocesssect,60000);
SuperHashTableOf<CProcessSessionState,INode>::replace(*e);
}
CProcessSessionState *query(INode *n)
{
CHECKEDCRITICALBLOCK(mapprocesssect,60000);
return SuperHashTableOf<CProcessSessionState,INode>::find(n);
}
bool remove(const CProcessSessionState *state, ISessionManagerServer *manager)
{
CHECKEDCRITICALBLOCK(mapprocesssect,60000);
if (SuperHashTableOf<CProcessSessionState,INode>::removeExact((CProcessSessionState *)state))
{
if (manager)
manager->authorizeConnection(state->queryRole(), true);
return true;
}
return false;
}
unsigned count()
{
CHECKEDCRITICALBLOCK(mapprocesssect,60000);
return SuperHashTableOf<CProcessSessionState,INode>::count();
}
CProcessSessionState *next(const CProcessSessionState *s)
{
CHECKEDCRITICALBLOCK(mapprocesssect,60000);
return (CProcessSessionState *)SuperHashTableOf<CProcessSessionState,INode>::next(s);
}
};
enum MSessionRequestKind {
MSR_REGISTER_PROCESS_SESSION,
MSR_SECONDARY_REGISTER_PROCESS_SESSION,
MSR_REGISTER_SESSION,
MSR_SECONDARY_REGISTER_SESSION,
MSR_LOOKUP_PROCESS_SESSION,
MSR_STOP_SESSION,
MSR_IMPORT_CAPABILITIES,
MSR_LOOKUP_LDAP_PERMISSIONS,
MSR_CLEAR_PERMISSIONS_CACHE,
MSR_EXIT, // TBD
MSR_QUERY_SCOPE_SCANS_ENABLED,
MSR_ENABLE_SCOPE_SCANS
};
class CQueryScopeScansEnabledReq : implements IMessageWrapper
{
public:
bool enabled;
Linked<IUserDescriptor> udesc;
CQueryScopeScansEnabledReq(IUserDescriptor *_udesc) : udesc(_udesc) {}
CQueryScopeScansEnabledReq() {}
void serializeReq(CMessageBuffer &mb)
{
mb.append(MSR_QUERY_SCOPE_SCANS_ENABLED);
udesc->serialize(mb);
}
void deserializeReq(CMessageBuffer &mb)
{
udesc.setown(createUserDescriptor(mb));
}
};
class CEnableScopeScansReq : implements IMessageWrapper
{
public:
bool doEnable;
Linked<IUserDescriptor> udesc;
CEnableScopeScansReq(IUserDescriptor *_udesc, bool _doEnable) : udesc(_udesc), doEnable(_doEnable) {}
CEnableScopeScansReq() {}
void serializeReq(CMessageBuffer &mb)
{
mb.append(MSR_ENABLE_SCOPE_SCANS);
udesc->serialize(mb);
mb.append(doEnable);
}
void deserializeReq(CMessageBuffer &mb)
{
udesc.setown(createUserDescriptor(mb));
mb.read(doEnable);
}
};
class CSessionRequestServer: public Thread
{
bool stopped;
ISessionManagerServer &manager;
Semaphore acceptConnections;
public:
CSessionRequestServer(ISessionManagerServer &_manager)
: Thread("Session Manager, CSessionRequestServer"), manager(_manager)
{
stopped = true;
}
int run()
{
ICoven &coven=queryCoven();
CMessageHandler<CSessionRequestServer> handler("CSessionRequestServer",this,&CSessionRequestServer::processMessage);
stopped = false;
CMessageBuffer mb;
while (!stopped) {
try {
mb.clear();
if (coven.recv(mb,RANK_ALL,MPTAG_DALI_SESSION_REQUEST,NULL))
handler.handleMessage(mb);
else
stopped = true;
}
catch (IException *e)
{
EXCLOG(e, "CDaliPublisherServer");
e->Release();
}
}
return 0;
}
void processMessage(CMessageBuffer &mb)
{
ICoven &coven=queryCoven();
SessionId id;
int fn;
mb.read(fn);
switch (fn) {
case MSR_REGISTER_PROCESS_SESSION: {
acceptConnections.wait();
acceptConnections.signal();
Owned<INode> node(deserializeINode(mb));
Owned<INode> servernode(deserializeINode(mb)); // hopefully me, but not if forwarded
int role=0;
if (mb.length()-mb.getPos()>=sizeof(role)) { // a capability block present
mb.read(role);
if (!manager.authorizeConnection(role,false)) {
SocketEndpoint sender = mb.getSender();
mb.clear();
coven.reply(mb);
MilliSleep(100+getRandom()%1000); // Causes client to 'work' for a short time.
Owned<INode> node = createINode(sender);
coven.disconnect(node);
break;
}
#ifdef _DEBUG
StringBuffer eps;
PROGLOG("Connection to %s at %s authorized",queryRoleName((DaliClientRole)role),mb.getSender().getUrlStr(eps).str());
#endif
}
IGroup *covengrp;
id = manager.registerClientProcess(node.get(),covengrp,(DaliClientRole)role);
mb.clear().append(id);
if (covengrp->rank(servernode)==RANK_NULL) { // must have been redirected
covengrp->Release(); // no good, so just use one we know about (may use something more sophisticated later)
INode *na = servernode.get();
covengrp = createIGroup(1, &na);
}
covengrp->serialize(mb);
covengrp->Release();
coven.reply(mb);
}
break;
case MSR_SECONDARY_REGISTER_PROCESS_SESSION: {
mb.read(id);
Owned<INode> node (deserializeINode(mb));
int role;
mb.read(role);
manager.addProcessSession(id,node.get(),(DaliClientRole)role);
mb.clear();
coven.reply(mb);
}
break;
case MSR_REGISTER_SESSION: {
SecurityToken tok;
SessionId parentid;
mb.read(tok).read(parentid);
SessionId id = manager.registerSession(tok,parentid);
mb.clear().append(id);
coven.reply(mb);
}
break;
case MSR_SECONDARY_REGISTER_SESSION: {
mb.read(id);
manager.addSession(id);
mb.clear();
coven.reply(mb);
}
break;
case MSR_LOOKUP_PROCESS_SESSION: {
// looks up from node or from id
Owned<INode> node (deserializeINode(mb));
if (node->endpoint().isNull()&&(mb.length()-mb.getPos()>=sizeof(id))) {
mb.read(id);
INode *n = manager.getProcessSessionNode(id);
if (n)
node.setown(n);
node->serialize(mb.clear());
}
else {
id = manager.lookupProcessSession(node.get());
mb.clear().append(id);
}
coven.reply(mb);
}
break;
case MSR_STOP_SESSION: {
SessionId sessid;
bool failed;
mb.read(sessid).read(failed);
manager.stopSession(sessid,failed);
mb.clear();
coven.reply(mb);
}
break;
case MSR_LOOKUP_LDAP_PERMISSIONS: {
StringAttr key;
StringAttr obj;
Owned<IUserDescriptor> udesc=createUserDescriptor();
mb.read(key).read(obj);
udesc->deserialize(mb);
#ifdef NULL_DALIUSER_STACKTRACE
//following debug code to be removed
StringBuffer sb;
udesc->getUserName(sb);
if (0==sb.length())
{
DBGLOG("UNEXPECTED USER (NULL) in dasess.cpp CSessionRequestServer::processMessage() line %d", __LINE__);
}
#endif
unsigned auditflags = 0;
if (mb.length()-mb.getPos()>=sizeof(auditflags))
mb.read(auditflags);
udesc->deserializeExtra(mb);//deserialize sessionToken and user signature if present (hpcc ver 7.0.0 and newer)
int err = 0;
SecAccessFlags perms = manager.getPermissionsLDAP(key,obj,udesc,auditflags,&err);
mb.clear().append((int)perms);
if (err)
mb.append(err);
coven.reply(mb);
}
break;
case MSR_CLEAR_PERMISSIONS_CACHE: {
Owned<IUserDescriptor> udesc=createUserDescriptor();
udesc->deserialize(mb);
bool ok = manager.clearPermissionsCache(udesc);
mb.append(ok);
coven.reply(mb);
}
break;
case MSR_QUERY_SCOPE_SCANS_ENABLED:{
CQueryScopeScansEnabledReq req;
req.deserializeReq(mb);
int err;
StringBuffer retMsg;
bool enabled = manager.queryScopeScansEnabled(req.udesc, &err, retMsg);
mb.clear().append(err);
mb.append(enabled);
mb.append(retMsg.str());
if (err != 0 || retMsg.length())
{
StringBuffer user;
req.udesc->getUserName(user);
DBGLOG("Error %d querying scope scan status for %s : %s", err, user.str(), retMsg.str());
}
coven.reply(mb);
}
break;
case MSR_ENABLE_SCOPE_SCANS:{
CEnableScopeScansReq req;
req.deserializeReq(mb);
int err;
StringBuffer retMsg;
bool ok = manager.enableScopeScans(req.udesc, req.doEnable, &err, retMsg);
mb.clear().append(err);
mb.append(retMsg.str());
if (err != 0 || retMsg.length())
{
StringBuffer user;
req.udesc->getUserName(user);
DBGLOG("Error %d %sing Scope Scan Status for %s: %s", err, req.doEnable?"Enabl":"Disabl", user.str(), retMsg.str());
}
coven.reply(mb);
}
break;
}
}
void ready()
{
acceptConnections.signal();
}
void stop()
{
if (!stopped) {
stopped = true;
queryCoven().cancel(RANK_ALL, MPTAG_DALI_SESSION_REQUEST);
}
join();
}
};
class CSessionManagerBase: implements ISessionManager, public CInterface
{
protected:
CheckedCriticalSection sessmanagersect;
public:
IMPLEMENT_IINTERFACE;
CSessionManagerBase()
{
servernotifys.kill();
}
virtual ~CSessionManagerBase()
{
}
class CSessionSubscriptionProxy: implements ISubscription, public CInterface
{
ISessionNotify *sub;
SubscriptionId id;
MemoryAttr ma;
SessionId sessid;
public:
IMPLEMENT_IINTERFACE;
CSessionSubscriptionProxy(ISessionNotify *_sub,SessionId _sessid)
{
sub = LINK(_sub);
sessid = _sessid;
MemoryBuffer mb;
mb.append(sessid);
ma.set(mb.length(),mb.toByteArray());
id = queryCoven().getUniqueId();
}
~CSessionSubscriptionProxy()
{
sub->Release();
}
ISessionNotify *queryNotify()
{
return sub;
}
const MemoryAttr &queryData()
{
return ma;
}
SubscriptionId getId()
{
return id;
}
void doNotify(bool aborted)
{
if (aborted)
sub->aborted(sessid);
else
sub->closed(sessid);
}
void notify(MemoryBuffer &mb)
{
bool aborted;
mb.read(aborted);
doNotify(aborted);
}
void abort()
{
//NH: TBD
}
bool aborted()
{
return false;
}
};
CIArrayOf<CSessionSubscriptionProxy>servernotifys;
SubscriptionId subscribeSession(SessionId sessid, ISessionNotify *inotify)
{
CSessionSubscriptionProxy *proxy;
SubscriptionId id;
{
CHECKEDCRITICALBLOCK(sessmanagersect,60000);
proxy = new CSessionSubscriptionProxy(inotify,sessid);
id = proxy->getId();
if (sessid==SESSID_DALI_SERVER) {
servernotifys.append(*proxy);
return id;
}
}
querySubscriptionManager(SESSION_PUBLISHER)->add(proxy,id);
return id;
}
void unsubscribeSession(SubscriptionId id)
{
{
CHECKEDCRITICALBLOCK(sessmanagersect,60000);
// check not a server subscription
ForEachItemIn(i,servernotifys) {
if (servernotifys.item(i).getId()==id) {
servernotifys.remove(i);
return;
}
}
}
querySubscriptionManager(SESSION_PUBLISHER)->remove(id);
}
class cNotify: implements ISessionNotify, public CInterface
{
public:
IMPLEMENT_IINTERFACE;
Semaphore sem;
void closed(SessionId id)
{
//PROGLOG("Session closed %" I64F "x",id);
sem.signal();
}
void aborted(SessionId id)
{
//PROGLOG("Session aborted %" I64F "x",id);
sem.signal();
}
};
bool sessionStopped(SessionId id, unsigned timeout)
{
Owned<INode> node = getProcessSessionNode(id);
if (node.get()==NULL)
return true;
if (timeout==0)
return false;
Owned<cNotify> cnotify = new cNotify;
querySessionManager().subscribeSession(id,cnotify);
if (cnotify->sem.wait(timeout))
return false;
node.setown(getProcessSessionNode(id));
return node.get()==NULL;
}
void notifyServerStopped(bool aborted)
{
CHECKEDCRITICALBLOCK(sessmanagersect,60000);
// check not a server subscription
ForEachItemIn(i,servernotifys) {
servernotifys.item(i).doNotify(aborted);
}
}
};
class CClientSessionManager: public CSessionManagerBase, implements IConnectionMonitor
{
bool securitydisabled;
public:
IMPLEMENT_IINTERFACE;
CClientSessionManager()
{
securitydisabled = false;
}
virtual ~CClientSessionManager()
{
stop();
}
SessionId lookupProcessSession(INode *node)
{
if (!node)
return mySessionId;
CMessageBuffer mb;
mb.append((int)MSR_LOOKUP_PROCESS_SESSION);
node->serialize(mb);
if (!queryCoven().sendRecv(mb,RANK_RANDOM,MPTAG_DALI_SESSION_REQUEST,SESSIONREPLYTIMEOUT))
return 0;
SessionId ret;
mb.read(ret);
return ret;
}
virtual INode *getProcessSessionNode(SessionId id)
{
if (!id)
return NULL;
CMessageBuffer mb;
mb.append((int)MSR_LOOKUP_PROCESS_SESSION);
queryNullNode()->serialize(mb);
mb.append(id);
if (!queryCoven().sendRecv(mb,RANK_RANDOM,MPTAG_DALI_SESSION_REQUEST,SESSIONREPLYTIMEOUT))
return NULL;
Owned<INode> node = deserializeINode(mb);
if (node->endpoint().isNull())
return NULL;
return node.getClear();
}
SecAccessFlags getPermissionsLDAP(const char *key,const char *obj,IUserDescriptor *udesc,unsigned auditflags,int *err)
{
if (err)
*err = 0;
if (securitydisabled)
return SecAccess_Unavailable;
if (queryDaliServerVersion().compare("1.8") < 0) {
securitydisabled = true;
return SecAccess_Unavailable;
}
CMessageBuffer mb;
mb.append((int)MSR_LOOKUP_LDAP_PERMISSIONS);
mb.append(key).append(obj);
#ifdef NULL_DALIUSER_STACKTRACE
//following debug code to be removed
StringBuffer sb;
if (udesc)
udesc->getUserName(sb);
if (0==sb.length())
{
DBGLOG("UNEXPECTED USER (NULL) in dasess.cpp getPermissionsLDAP() line %d",__LINE__);
PrintStackReport();
}
#endif
udesc->serialize(mb);
mb.append(auditflags);
udesc->serializeExtra(mb);//serialize sessionToken and user signature if Dali version
if (!queryCoven().sendRecv(mb,RANK_RANDOM,MPTAG_DALI_SESSION_REQUEST,SESSIONREPLYTIMEOUT))
return SecAccess_None;
SecAccessFlags perms = SecAccess_Unavailable;
if (mb.remaining()>=sizeof(perms)) {
mb.read((int &)perms);
if (mb.remaining()>=sizeof(int)) {
int e = 0;
mb.read(e);
if (err)
*err = e;
else if (e)
throw new CDaliLDAP_Exception(e);
}
}
if (perms == SecAccess_Unavailable)
securitydisabled = true;
return perms;
}
bool clearPermissionsCache(IUserDescriptor *udesc)
{
if (securitydisabled)
return true;
if (queryDaliServerVersion().compare("1.8") < 0) {
securitydisabled = true;
return true;
}
CMessageBuffer mb;
mb.append((int)MSR_CLEAR_PERMISSIONS_CACHE);
udesc->serialize(mb);
return queryCoven().sendRecv(mb,RANK_RANDOM,MPTAG_DALI_SESSION_REQUEST,SESSIONREPLYTIMEOUT);
}
bool queryScopeScansEnabled(IUserDescriptor *udesc, int * err, StringBuffer &retMsg)
{
if (queryDaliServerVersion().compare("3.10") < 0)
{
*err = -1;
StringBuffer ver;
queryDaliServerVersion().toString(ver);
retMsg.appendf("Scope Scan status feature requires Dali V3.10 or newer, current Dali version %s",ver.str());
return false;
}
if (securitydisabled)
{
*err = -1;
retMsg.append("Security not enabled");
return false;
}
if (queryDaliServerVersion().compare("1.8") < 0) {
*err = -1;
retMsg.append("Security not enabled");
securitydisabled = true;
return false;
}
CMessageBuffer mb;
CQueryScopeScansEnabledReq req(udesc);
req.serializeReq(mb);
if (!queryCoven().sendRecv(mb,RANK_RANDOM,MPTAG_DALI_SESSION_REQUEST,SESSIONREPLYTIMEOUT))
{
*err = -1;
retMsg.append("DALI Send/Recv error");
return false;
}
int rc;
bool enabled;
mb.read(rc).read(enabled).read(retMsg);
*err = rc;
return enabled;
}
bool enableScopeScans(IUserDescriptor *udesc, bool enable, int * err, StringBuffer &retMsg)
{
if (queryDaliServerVersion().compare("3.10") < 0)
{
*err = -1;
StringBuffer ver;
queryDaliServerVersion().toString(ver);
retMsg.appendf("Scope Scan enable/disable feature requires Dali V3.10 or newer, current Dali version %s",ver.str());
return false;
}
if (securitydisabled)
{
*err = -1;
retMsg.append("Security not enabled");
return false;
}
if (queryDaliServerVersion().compare("1.8") < 0) {
*err = -1;
retMsg.append("Security not enabled");
securitydisabled = true;
return false;
}
CMessageBuffer mb;
CEnableScopeScansReq req(udesc,enable);
req.serializeReq(mb);
if (!queryCoven().sendRecv(mb,RANK_RANDOM,MPTAG_DALI_SESSION_REQUEST,SESSIONREPLYTIMEOUT))
{
*err = -1;
retMsg.append("DALI Send/Recv error");
return false;
}
int rc;
mb.read(rc).read(retMsg);
*err = rc;
if (rc == 0)
{
StringBuffer user;
udesc->getUserName(user);
DBGLOG("Scope Scans %sabled by %s",enable ? "En" : "Dis", user.str());
}
return rc == 0;
}
bool checkScopeScansLDAP()
{
assertex(!"checkScopeScansLDAP called on client");
return true; // actually only used server size
}
unsigned getLDAPflags()
{
assertex(!"getLdapFlags called on client");
return 0;
}
void setLDAPflags(unsigned)
{
assertex(!"setLdapFlags called on client");
}
bool authorizeConnection(DaliClientRole,bool)
{
return true;
}
SessionId startSession(SecurityToken tok, SessionId parentid)
{
CMessageBuffer mb;
mb.append((int)MSR_REGISTER_SESSION).append(tok).append(parentid);
if (!queryCoven().sendRecv(mb,RANK_RANDOM,MPTAG_DALI_SESSION_REQUEST,SESSIONREPLYTIMEOUT))
return 0;
SessionId ret;
mb.read(ret);
return ret;
}
void stopSession(SessionId sessid, bool failed)
{
if (sessid==SESSID_DALI_SERVER) {
notifyServerStopped(failed);
return;
}
CMessageBuffer mb;
mb.append((int)MSR_STOP_SESSION).append(sessid).append(failed);
queryCoven().sendRecv(mb,RANK_RANDOM,MPTAG_DALI_SESSION_REQUEST,SESSIONREPLYTIMEOUT);
}
void onClose(SocketEndpoint &ep)
{
CHECKEDCRITICALBLOCK(sessmanagersect,60000);
Owned<INode> node = createINode(ep);
if (queryCoven().inCoven(node)) {
StringBuffer str;
PROGLOG("Coven Session Stopping (%s)",ep.getUrlStr(str).str());
if (queryCoven().size()==1)
notifyServerStopped(true);
}
}
void start()
{
addMPConnectionMonitor(this);
}
void stop()
{
}
void ready()
{
removeMPConnectionMonitor(this);
}
StringBuffer &getClientProcessList(StringBuffer &buf)
{
// dummy
return buf;
}
StringBuffer &getClientProcessEndpoint(SessionId,StringBuffer &buf)
{
// dummy
return buf;
}
unsigned queryClientCount()
{
// dummy
return 0;
}
void importCapabilities(MemoryBuffer &mb)
{
CMessageBuffer msg;
msg.append((int)MSR_IMPORT_CAPABILITIES);
msg.append(mb.length(), mb.toByteArray());
queryCoven().sendRecv(msg,RANK_RANDOM,MPTAG_DALI_SESSION_REQUEST,SESSIONREPLYTIMEOUT);
}
};
class CLdapWorkItem : public Thread
{
StringAttr key;
StringAttr obj;
Linked<IUserDescriptor> udesc;
Linked<IDaliLdapConnection> ldapconn;
unsigned flags;
bool running;
Semaphore contsem;
Semaphore ready;
Semaphore &threaddone;
int ret;
public:
CLdapWorkItem(IDaliLdapConnection *_ldapconn,Semaphore &_threaddone)
: ldapconn(_ldapconn), threaddone(_threaddone)
{
running = false;
}
void start(const char *_key,const char *_obj,IUserDescriptor *_udesc,unsigned _flags)
{
key.set(_key);
obj.set(_obj);
#ifdef NULL_DALIUSER_STACKTRACE
StringBuffer sb;
if (_udesc)
_udesc->getUserName(sb);
if (sb.length()==0)
{
DBGLOG("UNEXPECTED USER (NULL) in dasess.cpp CLdapWorkItem::start() line %d",__LINE__);
PrintStackReport();
}
#endif
udesc.set(_udesc);
flags = _flags;
ret = CLDAPE_ldapfailure;
if (!running) {
running = true;
Thread::start();
}
contsem.signal();
}
int run()
{
for (;;) {
contsem.wait();
if (!running)
break;
try {
ret = ldapconn->getPermissions(key,obj,udesc,flags);
}
catch(IException *e) {
LOG(MCoperatorError, unknownJob, e, "CLdapWorkItem");
e->Release();
}
ready.signal();
}
threaddone.signal();
return 0;
}
bool wait(unsigned timeout, int &_ret)
{
if (ready.wait(timeout)) {
_ret = ret;
return true;
}
_ret = 0;
return false;
}
void stop()
{
running = false;
contsem.signal();
}
static CLdapWorkItem *get(IDaliLdapConnection *_ldapconn,Semaphore &_threaddone)
{
if (!_threaddone.wait(1000*60*5)) {
ERRLOG("Too many stalled LDAP threads");
return NULL;
}
return new CLdapWorkItem(_ldapconn,_threaddone);
}
};
class CCovenSessionManager: public CSessionManagerBase, implements ISessionManagerServer, implements ISubscriptionManager
{
CSessionRequestServer sessionrequestserver;
CSessionStateTable sessionstates;
CMapProcessToSession processlookup;
Owned<IDaliLdapConnection> ldapconn;
Owned<CLdapWorkItem> ldapworker;
Semaphore ldapsig;
atomic_t ldapwaiting;
Semaphore workthreadsem;
bool stopping;
void remoteAddProcessSession(rank_t dst,SessionId id,INode *node, DaliClientRole role)
{
CMessageBuffer mb;
mb.append((int)MSR_SECONDARY_REGISTER_PROCESS_SESSION).append(id);
node->serialize(mb);
int r = (int)role;
mb.append(role);
queryCoven().sendRecv(mb,dst,MPTAG_DALI_SESSION_REQUEST);
// no fail currently
}
void remoteAddSession(rank_t dst,SessionId id)
{
CMessageBuffer mb;
mb.append((int)MSR_SECONDARY_REGISTER_SESSION).append(id);
queryCoven().sendRecv(mb,dst,MPTAG_DALI_SESSION_REQUEST);
// no fail currently
}
public:
IMPLEMENT_IINTERFACE;
CCovenSessionManager()
: sessionrequestserver(*this)
{
mySessionId = queryCoven().getUniqueId(); // tell others in coven TBD
registerSubscriptionManager(SESSION_PUBLISHER,this);
atomic_set(&ldapwaiting,0);
workthreadsem.signal(10);
stopping = false;
ldapsig.signal();
}
~CCovenSessionManager()
{
stubTable.kill();
}
void start()
{
sessionrequestserver.start();
}
void stop()
{
stopping = true;
if (!ldapsig.wait(60*1000))
WARNLOG("LDAP stalled(1)");
if (ldapworker) {
ldapworker->stop();
if (!ldapworker->join(1000))
WARNLOG("LDAP stalled(2)");
ldapworker.clear();
}
ldapconn.clear();
removeMPConnectionMonitor(this);
sessionrequestserver.stop();
}
void ready()
{
addMPConnectionMonitor(this);
sessionrequestserver.ready();
}
void setLDAPconnection(IDaliLdapConnection *_ldapconn)
{
if (_ldapconn&&(_ldapconn->getLDAPflags()&DLF_ENABLED))
ldapconn.setown(_ldapconn);
else {
ldapconn.clear();
::Release(_ldapconn);
}
}
void setClientAuth(IDaliClientAuthConnection *_authconn)
{
}
void addProcessSession(SessionId id,INode *client,DaliClientRole role)
{
StringBuffer str;
PROGLOG("Session starting %" I64F "x (%s) : role=%s",id,client->endpoint().getUrlStr(str).str(),queryRoleName(role));
CHECKEDCRITICALBLOCK(sessmanagersect,60000);
CProcessSessionState *s = new CProcessSessionState(id,client,role);
while (!sessionstates.add(s)) // takes ownership
{
WARNLOG("Dali session manager: session already registered");
sessionstates.remove(id);
}
while (!processlookup.add(s))
{
/* There's existing ip:port match (client) in process table..
* Old may be in process of closing or about to, but new has beaten the onClose() to it..
* Track old sessions in new CProcessSessionState instance, so that in-process or upcoming onClose()/stopSession() can find them
*/
CProcessSessionState *previousState = processlookup.query(client);
dbgassertex(previousState); // Must be there, it's reason add() failed
SessionId oldSessionId = previousState->getId();
s->addSessionIds(*previousState, false); // merges sessions from previous process state into new one that replaces it
WARNLOG("Dali session manager: registerClient process session already registered, old (%" I64F "x) replaced", oldSessionId);
processlookup.remove(previousState, this);
}
}
void addSession(SessionId id)
{
CHECKEDCRITICALBLOCK(sessmanagersect,60000);
CSessionState *s = new CSessionState(id);
while (!sessionstates.add(s)) { // takes ownership
WARNLOG("Dali session manager: session already registered (2)");
sessionstates.remove(id);
}
}
SessionId registerSession(SecurityToken, SessionId parent)
{
// this is where security token should be checked
// not in critical block (otherwise possibility of deadlock)
ICoven &coven=queryCoven();
SessionId id = coven.getUniqueId();
rank_t myrank = coven.getServerRank();
rank_t ownerrank = coven.chooseServer(id);
// first do local
if (myrank==ownerrank)
addSession(id);
else
remoteAddSession(ownerrank,id);
ForEachOtherNodeInGroup(r,coven.queryGroup()) {
if (r!=ownerrank)
remoteAddSession(r,id);
}
return id;
}
SessionId registerClientProcess(INode *client, IGroup *& retcoven, DaliClientRole role)
{
// not in critical block (otherwise possibility of deadlock)
retcoven = NULL;
ICoven &coven=queryCoven();
SessionId id = coven.getUniqueId();
rank_t myrank = coven.getServerRank();
rank_t ownerrank = coven.chooseServer(id);
// first do local
if (myrank==ownerrank)
addProcessSession(id,client,role);
else
remoteAddProcessSession(ownerrank,id,client,role);
ForEachOtherNodeInGroup(r,coven.queryGroup()) {
if (r!=ownerrank)
remoteAddProcessSession(r,id,client,role);
}
retcoven = coven.getGroup();
return id;
}
SessionId lookupProcessSession(INode *node)
{
if (!node)
return mySessionId;
CHECKEDCRITICALBLOCK(sessmanagersect,60000);
CProcessSessionState *s= processlookup.query(node);
return s?s->getId():0;
}
INode *getProcessSessionNode(SessionId id)
{
StringBuffer eps;
if (SessionManager->getClientProcessEndpoint(id,eps).length()!=0)
return createINode(eps.str());
return NULL;
}
virtual SecAccessFlags getPermissionsLDAP(const char *key,const char *obj,IUserDescriptor *udesc,unsigned flags, int *err)
{
if (err)
*err = 0;
if (!ldapconn)
return SecAccess_Unavailable;
#ifdef _NO_LDAP
return SecAccess_Unavailable;
#else
#ifdef NULL_DALIUSER_STACKTRACE
StringBuffer sb;
if (udesc)
udesc->getUserName(sb);
if (sb.length()==0)
{
DBGLOG("UNEXPECTED USER (NULL) in dasess.cpp CCovenSessionManager::getPermissionsLDAP() line %d",__LINE__);
PrintStackReport();
}
#endif
if ((ldapconn->getLDAPflags()&(DLF_SAFE|DLF_ENABLED))!=(DLF_SAFE|DLF_ENABLED))
return ldapconn->getPermissions(key,obj,udesc,flags);
atomic_inc(&ldapwaiting);
unsigned retries = 0;
while (!stopping) {
if (ldapsig.wait(1000)) {
atomic_dec(&ldapwaiting);
if (!ldapworker)
ldapworker.setown(CLdapWorkItem::get(ldapconn,workthreadsem));
if (ldapworker) {
ldapworker->start(key,obj,udesc,flags);
for (unsigned i=0;i<10;i++) {
if (i)
WARNLOG("LDAP stalled(%d) - retrying",i);
SecAccessFlags ret;
if (ldapworker->wait(1000*20,(int&)ret)) {
if (ret==CLDAPE_ldapfailure) {
LOG(MCoperatorError, unknownJob, "LDAP - failure (returning no access for %s)",obj);
ldapsig.signal();
if (err)
*err = CLDAPE_ldapfailure;
return SecAccess_None;
}
else {
ldapsig.signal();
return ret;
}
}
if (atomic_read(&ldapwaiting)>10) // give up quicker if piling up
break;
if (i==5) { // one retry
ldapworker->stop(); // abandon thread
ldapworker.clear();
ldapworker.setown(CLdapWorkItem::get(ldapconn,workthreadsem));
if (ldapworker)
ldapworker->start(key,obj,udesc,flags);
}
}
if (ldapworker)
ldapworker->stop();
ldapworker.clear(); // abandon thread
}
LOG(MCoperatorError, unknownJob, "LDAP stalled - aborting (returning no access for %s)",obj);
ldapsig.signal();
if (err)
*err = CLDAPE_getpermtimeout;
return SecAccess_None;
}
else {
unsigned waiting = atomic_read(&ldapwaiting);
static unsigned last=0;
static unsigned lasttick=0;
static unsigned first50=0;
if ((waiting!=last)&&(msTick()-lasttick>1000)) {
WARNLOG("%d threads waiting for ldap",waiting);
last = waiting;
lasttick = msTick();
}
if (waiting>50) {
if (first50==0)
first50 = msTick();
else if (msTick()-first50>60*1000) {
LOG(MCoperatorError, unknownJob, "LDAP stalled - aborting (returning 0 for %s)", obj);
if (err)
*err = CLDAPE_getpermtimeout;
break;
}
}
else
first50 = 0;
}
}
atomic_dec(&ldapwaiting);
return SecAccess_None;
#endif
}
virtual bool clearPermissionsCache(IUserDescriptor *udesc)
{
#ifdef _NO_LDAP
bool ok = true;
#else
bool ok = true;
if (ldapconn && ldapconn->getLDAPflags() & DLF_ENABLED)
ok = ldapconn->clearPermissionsCache(udesc);
#endif
return ok;
}
virtual bool queryScopeScansEnabled(IUserDescriptor *udesc, int * err, StringBuffer &retMsg)
{
#ifdef _NO_LDAP
*err = -1;
retMsg.append("LDAP not enabled");
return false;
#else
*err = 0;
return checkScopeScansLDAP();
#endif
}
virtual bool enableScopeScans(IUserDescriptor *udesc, bool enable, int * err, StringBuffer &retMsg)
{
#ifdef _NO_LDAP
*err = -1;
retMsg.append("LDAP not supporteded");
return false;
#else
if (!ldapconn)
{
*err = -1;
retMsg.append("LDAP not connected");
return false;
}
return ldapconn->enableScopeScans(udesc, enable, err);
#endif
}
virtual bool checkScopeScansLDAP()
{
#ifdef _NO_LDAP
return false;
#else
return ldapconn?ldapconn->checkScopeScans():false;
#endif
}
virtual unsigned getLDAPflags()
{
#ifdef _NO_LDAP
return 0;
#else
return ldapconn?ldapconn->getLDAPflags():0;
#endif
}
void setLDAPflags(unsigned flags)
{
#ifndef _NO_LDAP
if (ldapconn)
ldapconn->setLDAPflags(flags);
#endif
}
bool authorizeConnection(int role,bool revoke)
{
return true;
}
SessionId startSession(SecurityToken tok, SessionId parentid)
{
return registerSession(tok,parentid);
}
void setSessionDependancy(SessionId id , SessionId dependsonid )
{
UNIMPLEMENTED; // TBD
}
void clearSessionDependancy(SessionId id , SessionId dependsonid )
{
UNIMPLEMENTED; // TBD
}
protected:
class CSessionSubscriptionStub: public CInterface
{
ISubscription *subs;
SubscriptionId id;
SessionId sessid;
public:
CSessionSubscriptionStub(ISubscription *_subs,SubscriptionId _id) // takes ownership
{
subs = _subs;
id = _id;
const MemoryAttr &ma = subs->queryData();
MemoryBuffer mb(ma.length(),ma.get());
mb.read(sessid);
}
~CSessionSubscriptionStub()
{
subs->Release();
}
SubscriptionId getId() { return id; }
SessionId getSessionId() { return sessid; }
void notify(bool abort)
{
MemoryBuffer mb;
mb.append(abort);
subs->notify(mb);
}
const void *queryFindParam() const { return &id; }
};
OwningSimpleHashTableOf<CSessionSubscriptionStub, SubscriptionId> stubTable;
void add(ISubscription *subs,SubscriptionId id)
{
CSessionSubscriptionStub *nstub;
{
CHECKEDCRITICALBLOCK(sessmanagersect,60000);
nstub = new CSessionSubscriptionStub(subs,id);
if (sessionstates.query(nstub->getSessionId())||(nstub->getSessionId()==mySessionId))
{
stubTable.replace(*nstub);
return;
}
}
// see if session known
MemoryBuffer mb;
bool abort=true;
mb.append(abort);
ERRLOG("Session Manager - adding unknown session ID %" I64F "x", nstub->getSessionId());
subs->notify(mb);
delete nstub;
return;
}
void remove(SubscriptionId id)
{
CHECKEDCRITICALBLOCK(sessmanagersect,60000);
stubTable.remove(&id);
}
void stopSession(SessionId id, bool abort)
{
PROGLOG("Session stopping %" I64F "x %s",id,abort?"aborted":"ok");
CHECKEDCRITICALBLOCK(sessmanagersect,60000);
// do in multiple stages as may remove one or more sub sessions
for (;;)
{
CIArrayOf<CSessionSubscriptionStub> tonotify;
SuperHashIteratorOf<CSessionSubscriptionStub> iter(stubTable);
ForEach(iter)
{
CSessionSubscriptionStub &stub = iter.query();
if (stub.getSessionId()==id)
tonotify.append(*LINK(&stub));
}
if (tonotify.ordinality()==0)
break;
ForEachItemIn(j,tonotify)
{
CSessionSubscriptionStub &stub = tonotify.item(j);
stubTable.removeExact(&stub);
}
CHECKEDCRITICALUNBLOCK(sessmanagersect,60000);
ForEachItemIn(j2,tonotify)
{
CSessionSubscriptionStub &stub = tonotify.item(j2);
try { stub.notify(abort); }
catch (IException *e) { e->Release(); } // subscriber session may abort during stopSession
}
tonotify.kill(); // clear whilst sessmanagersect unblocked, as subs may query session manager.
}
const CSessionState *state = sessionstates.query(id);
if (state)
{
const CProcessSessionState *pState = QUERYINTERFACE(state, const CProcessSessionState);
if (pState)
{
CProcessSessionState *cState = processlookup.query(&pState->queryNode()); // get current
if (pState == cState) // so is current one.
{
/* This is reinstating a previous CProcessSessionState for this node (if there is one),
* that has not yet stopped, and adding any other pending process states to the CProcessSessionState
* being reinstated.
*/
SessionId prevId = cState->dequeuePreviousSessionId();
if (prevId)
{
PROGLOG("Session (%" I64F "x) in stopSession, detected %d pending previous states, reinstating session (%" I64F "x) as current", id, cState->previousSessionIdCount(), prevId);
CSessionState *prevSessionState = sessionstates.query(prevId);
dbgassertex(prevSessionState); // must be there
CProcessSessionState *prevProcessState = QUERYINTERFACE(prevSessionState, CProcessSessionState);
dbgassertex(prevProcessState);
/* NB: prevProcessState's have 0 entries in their previousSessionIds, since they were merged at replacement time
* in addProcessSession()
*/
/* add in any remaining to-be-stopped process sessions from current that's stopping into this previous state
* that's being reinstated, so will be picked up on next onClose()/stopSession()
*/
prevProcessState->addSessionIds(*cState, true);
processlookup.replace(prevProcessState);
}
else
processlookup.remove(pState, this);
}
else // Here because in stopSession for an previous process state, that has been replaced (in addProcessSession)
{
if (processlookup.remove(pState, this))
{
// Don't think possible to be here, if not current must have replaced afaics
PROGLOG("Session (%" I64F "x) in stopSession, old process session removed", id);
}
else
PROGLOG("Session (%" I64F "x) in stopSession, old process session was already removed", id); // because replaced
if (cState)
{
PROGLOG("Session (%" I64F "x) was replaced, ensuring removed from new process state", id);
cState->removeOldSessionId(id); // If already replaced, then must ensure no longer tracked by new
}
}
}
sessionstates.remove(id);
}
}
void onClose(SocketEndpoint &ep)
{
StringBuffer clientStr;
PROGLOG("Client closed (%s)", ep.getUrlStr(clientStr).str());
SessionId idtostop;
{
CHECKEDCRITICALBLOCK(sessmanagersect,60000);
Owned<INode> node = createINode(ep);
if (queryCoven().inCoven(node))
{
PROGLOG("Coven Session Stopping (%s)", clientStr.str());
// more TBD here
return;
}
CProcessSessionState *s = processlookup.query(node);
if (!s)
return;
idtostop = s->dequeuePreviousSessionId();
if (idtostop)
{
PROGLOG("Previous sessionId (%" I64F "x) for %s was replaced by (%" I64F "x), stopping old session now", idtostop, clientStr.str(), s->getId());
unsigned c = s->previousSessionIdCount();
if (c) // very unlikely, but could be >1, trace for info.
PROGLOG("%d old sessions pending closure", c);
}
else
idtostop = s->getId();
}
stopSession(idtostop,true);
}
StringBuffer &getClientProcessList(StringBuffer &buf)
{
CHECKEDCRITICALBLOCK(sessmanagersect,60000);
unsigned n = processlookup.count();
CProcessSessionState *s=NULL;
for (unsigned i=0;i<n;i++) {
s=processlookup.next(s);
if (!s)
break;
s->getDetails(buf).append('\n');
}
return buf;
}
StringBuffer &getClientProcessEndpoint(SessionId id,StringBuffer &buf)
{
CHECKEDCRITICALBLOCK(sessmanagersect,60000);
const CSessionState *state = sessionstates.query(id);
if (state) {
const CProcessSessionState *pstate = QUERYINTERFACE(state,const CProcessSessionState);
if (pstate)
return pstate->queryNode().endpoint().getUrlStr(buf);
}
return buf;
}
unsigned queryClientCount()
{
CHECKEDCRITICALBLOCK(sessmanagersect,60000);
return processlookup.count();
}
};
ISessionManager &querySessionManager()
{
CriticalBlock block(sessionCrit);
if (!SessionManager) {
assertex(!isCovenActive()||!queryCoven().inCoven()); // Check not Coven server (if occurs - not initialized correctly;
// If !coven someone is checking for dali so allow
SessionManager = new CClientSessionManager();
}
return *SessionManager;
}
class CDaliSessionServer: public IDaliServer, public CInterface
{
public:
IMPLEMENT_IINTERFACE;
CDaliSessionServer()
{
}
void start()
{
CriticalBlock block(sessionCrit);
assertex(queryCoven().inCoven()); // must be member of coven
CCovenSessionManager *serv = new CCovenSessionManager();
SessionManagerServer = serv;
SessionManager = serv;
SessionManagerServer->start();
}
void suspend()
{
}
void stop()
{
CriticalBlock block(sessionCrit);
SessionManagerServer->stop();
SessionManagerServer->Release();
SessionManagerServer = NULL;
SessionManager = NULL;
}
void ready()
{
SessionManagerServer->ready();
}
void nodeDown(rank_t rank)
{
assertex(!"TBD");
}
};
IDaliServer *createDaliSessionServer()
{
return new CDaliSessionServer();
}
void setLDAPconnection(IDaliLdapConnection *ldapconn)
{
if (SessionManagerServer)
SessionManagerServer->setLDAPconnection(ldapconn);
}
void setClientAuth(IDaliClientAuthConnection *authconn)
{
if (SessionManagerServer)
SessionManagerServer->setClientAuth(authconn);
}
#define REG_SLEEP 5000
bool registerClientProcess(ICommunicator *comm, IGroup *& retcoven,unsigned timeout,DaliClientRole role)
{
// NB doesn't use coven as not yet set up
if (comm->queryGroup().ordinality()==0)
return false;
CTimeMon tm(timeout);
retcoven = NULL;
unsigned nextLog = 0, lastNextLog = 0;
unsigned t=REG_SLEEP;
unsigned remaining;
rank_t r;
while (!tm.timedout(&remaining)) {
if (remaining>t)
remaining = t;
r = getRandom()%comm->queryGroup().ordinality();
bool ok = false;
if (remaining>10000) // MP protocol has a minimum time of 10s so if remaining < 10s use a detachable thread
ok = comm->verifyConnection(r,remaining);
else {
struct cThread: public Thread
{
Semaphore sem;
Linked<ICommunicator> comm;
bool ok;
Owned<IException> exc;
unsigned remaining;
rank_t r;
cThread(ICommunicator *_comm,rank_t _r,unsigned _remaining)
: Thread ("dasess.registerClientProcess"), comm(_comm)
{
r = _r;
remaining = _remaining;
ok = false;
}
int run()
{
try {
if (comm->verifyConnection(r,remaining))
ok = true;
}
catch (IException *e)
{
exc.setown(e);
}
sem.signal();
return 0;
}
} *t = new cThread(comm,r,remaining);
t->start();
t->sem.wait(remaining);
ok = t->ok;
if (t->exc.get()) {
IException *e = t->exc.getClear();
t->Release();
throw e;
}
t->Release();
}
if (ok) {
CMessageBuffer mb;
mb.append((int)MSR_REGISTER_PROCESS_SESSION);
queryMyNode()->serialize(mb);
comm->queryGroup().queryNode(r).serialize(mb);
mb.append((int)role);
if (comm->sendRecv(mb,r,MPTAG_DALI_SESSION_REQUEST,SESSIONREPLYTIMEOUT)) {
if (!mb.length())
{
// failed system capability match,
retcoven = comm->getGroup(); // continue as if - will fail later more obscurely.
return true;
}
mb.read(mySessionId);
retcoven = deserializeIGroup(mb);
return true;
}
}
StringBuffer str;
PROGLOG("Failed to connect to Dali Server %s.", comm->queryGroup().queryNode(r).endpoint().getUrlStr(str).str());
if (tm.timedout())
{
PROGLOG("%s", str.append(" Timed out.").str());
break;
}
else if (0 == nextLog)
{
PROGLOG("%s", str.append(" Retrying...").str());
if ((lastNextLog * REG_SLEEP) >= 60000) // limit to a minute between logging
nextLog = 60000 / REG_SLEEP;
else
nextLog = lastNextLog + 2; // wait +2 REG_SLEEP pauses before next logging
lastNextLog = nextLog;
}
else
--nextLog;
Sleep(REG_SLEEP);
}
return false;
}
extern void stopClientProcess()
{
CriticalBlock block(sessionCrit);
if (mySessionId&&SessionManager) {
try {
querySessionManager().stopSession(mySessionId,false);
}
catch (IDaliClient_Exception *e) {
if (e->errorCode()!=DCERR_server_closed)
throw;
e->Release();
}
mySessionId = 0;
}
}
class CProcessSessionWatchdog
{
};
class CUserDescriptor: implements IUserDescriptor, public CInterface
{
StringAttr username;
StringAttr passwordenc;
MemoryBuffer sessionToken;//ESP session token
MemoryBuffer signature;//user's digital Signature
public:
IMPLEMENT_IINTERFACE;
StringBuffer &getUserName(StringBuffer &buf)
{
return buf.append(username);
}
StringBuffer &getPassword(StringBuffer &buf)
{
decrypt(buf,passwordenc);
return buf;
}
const MemoryBuffer *querySessionToken()
{
return &sessionToken;
}
const MemoryBuffer *querySignature()
{
return &signature;
}
virtual void set(const char *name,const char *password)
{
username.set(name);
StringBuffer buf;
encrypt(buf,password);
passwordenc.set(buf.str());
}
void set(const char *_name, const char *_password, const MemoryBuffer *_sessionToken, const MemoryBuffer *_signature)
{
set(_name, _password);
sessionToken.clear().append(_sessionToken);
signature.clear().append(_signature);
}
virtual void clear()
{
username.clear();
passwordenc.clear();
sessionToken.clear();
signature.clear();
}
void serialize(MemoryBuffer &mb)
{
mb.append(username).append(passwordenc);
}
void serializeExtra(MemoryBuffer &mb)
{
if (queryDaliServerVersion().compare("3.14") >= 0)
mb.append(sessionToken.length()).append(sessionToken).append(signature.length()).append(signature);
}
void deserialize(MemoryBuffer &mb)
{
mb.read(username).read(passwordenc);
}
void deserializeExtra(MemoryBuffer &mb)
{
if (mb.remaining() > 0)
{
size32_t len = 0;
mb.read(len);
if (len)
sessionToken.append(len, mb.readDirect(len));
if (mb.remaining() > 0)
{
mb.read(len);
if (len)
signature.append(len, mb.readDirect(len));
}
}
}
};
IUserDescriptor *createUserDescriptor()
{
return new CUserDescriptor;
}
IUserDescriptor *createUserDescriptor(MemoryBuffer &mb)
{
IUserDescriptor * udesc = createUserDescriptor();
udesc->deserialize(mb);
return udesc;
}
MODULE_INIT(INIT_PRIORITY_DALI_DASESS)
{
return true;
}
MODULE_EXIT()
{
::Release(SessionManager);
SessionManager = NULL;
}
| 30.219165
| 199
| 0.56543
|
fnisswandt
|
6030f5c2ed095e8407aa421820c61abfa79b6f8b
| 1,488
|
cpp
|
C++
|
source/Async/After.cpp
|
kurocha/async
|
48d3c9e8e2631077c2c623902078eb8791cc3b17
|
[
"Unlicense",
"MIT"
] | 19
|
2017-08-20T18:52:08.000Z
|
2021-08-16T12:20:35.000Z
|
source/Async/After.cpp
|
kurocha/async
|
48d3c9e8e2631077c2c623902078eb8791cc3b17
|
[
"Unlicense",
"MIT"
] | null | null | null |
source/Async/After.cpp
|
kurocha/async
|
48d3c9e8e2631077c2c623902078eb8791cc3b17
|
[
"Unlicense",
"MIT"
] | 3
|
2017-07-01T15:29:46.000Z
|
2020-05-05T11:12:32.000Z
|
//
// After.cpp
// File file is part of the "Async" project and released under the MIT License.
//
// Created by Samuel Williams on 29/6/2017.
// Copyright, 2017, by Samuel Williams. All rights reserved.
//
#include "After.hpp"
#include <Concurrent/Fiber.hpp>
#include <cassert>
#if defined(ASYNC_EPOLL)
#include <sys/timerfd.h>
#endif
namespace Async
{
using namespace Concurrent;
After::After(Interval duration, Reactor & reactor) : _duration(duration), _reactor(reactor)
{
}
After::~After()
{
}
void After::wait()
{
assert(Fiber::current);
#if defined(ASYNC_KQUEUE)
_reactor.append({
reinterpret_cast<uintptr_t>(this),
EVFILT_TIMER,
EV_ADD | EV_ONESHOT,
// TODO this may overflow
NOTE_USECONDS,
static_cast<intptr_t>(static_cast<double>(_duration) * 1000 * 1000),
Fiber::current
});
try {
Fiber::current->yield();
} catch (...) {
_reactor.append({
reinterpret_cast<uintptr_t>(this),
EVFILT_TIMER,
EV_ADD | EV_ONESHOT,
0,
0,
nullptr
}, false);
throw;
}
#elif defined(ASYNC_EPOLL)
// TODO cache the timer handle:
Handle timer_handle = ::timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK|TFD_CLOEXEC);
_reactor.append(EPOLL_CTL_ADD, timer_handle, EPOLLIN|EPOLLET, (void*)Fiber::current);
struct itimerspec value;
value.it_value = _duration.value();
value.it_interval = {0, 0};
::timerfd_settime(timer_handle, 0, &value, nullptr);
Fiber::current->yield();
#endif
}
}
| 19.84
| 92
| 0.678763
|
kurocha
|
60395623d39da0c95da1ef0f2bbcef28513b2452
| 754
|
cpp
|
C++
|
example.cpp
|
mersinvald/DynamicCaller
|
56314492e423393488c702a4f2e733f610bc2e13
|
[
"MIT"
] | null | null | null |
example.cpp
|
mersinvald/DynamicCaller
|
56314492e423393488c702a4f2e733f610bc2e13
|
[
"MIT"
] | null | null | null |
example.cpp
|
mersinvald/DynamicCaller
|
56314492e423393488c702a4f2e733f610bc2e13
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include "dynamiccaller.hpp"
int plus(int a, int b) {
return a+b;
}
int minus(int a, int b) {
return a-b;
}
int multiply(int a, int b) {
return a*b;
}
int divide(int a, int b) {
return a/b;
}
#define AddDynFunc(DC, function) \
DC.PutFunction(function, #function);
int main() {
DynamicCaller<string, int(int, int)> DC;
AddDynFunc(DC, plus);
AddDynFunc(DC, minus);
AddDynFunc(DC, multiply);
AddDynFunc(DC, divide);
std::string func;
int a, b;
while(1) {
std::cin >> func >> a >> b;
try {
std::cout << DC.CallFunction(func, a, b) << std::endl;
} catch(std::exception& e) {
std::cerr << e.what() << std::endl;
}
}
}
| 17.136364
| 66
| 0.543767
|
mersinvald
|
603da7c3cfa969d26775cdf876a327d8a3d25e27
| 3,268
|
cpp
|
C++
|
src/libv/gl/load_image_soil.cpp
|
cpplibv/libv
|
293e382f459f0acbc540de8ef6283782b38d2e63
|
[
"Zlib"
] | 2
|
2018-04-11T03:07:03.000Z
|
2019-03-29T15:24:12.000Z
|
src/libv/gl/load_image_soil.cpp
|
cpplibv/libv
|
293e382f459f0acbc540de8ef6283782b38d2e63
|
[
"Zlib"
] | null | null | null |
src/libv/gl/load_image_soil.cpp
|
cpplibv/libv
|
293e382f459f0acbc540de8ef6283782b38d2e63
|
[
"Zlib"
] | 1
|
2021-06-13T06:39:06.000Z
|
2021-06-13T06:39:06.000Z
|
// Project: libv.gl, File: src/libv/gl/load_image_soil.cpp, Author: Császár Mátyás [Vader]
// hpp
#include <libv/gl/image.hpp>
// ext
#include <SOIL2/SOIL2.h>
// libv
#include <libv/container/dynarray.hpp>
// std
#include <cstring>
// pro
#include <libv/gl/check.hpp>
#include <libv/gl/texture_object.hpp>
namespace libv {
namespace gl {
// -------------------------------------------------------------------------------------------------
class ImageSOIL : public detail::ImageImplementation {
libv::vec2i size_;
int32_t channels;
std::unique_ptr<uint8_t, decltype(&SOIL_free_image_data)> storage;
public:
ImageSOIL(libv::vec2i size_, int32_t channels, std::unique_ptr<uint8_t, decltype(&SOIL_free_image_data)>&& storage) :
size_(size_), channels(channels), storage(std::move(storage)) { }
[[nodiscard]] virtual libv::vec2i size() const noexcept override;
[[nodiscard]] virtual Texture createTexture() const noexcept override;
virtual ~ImageSOIL() noexcept override = default;
};
std::optional<Image> load_image_SOIL(const std::string_view data) noexcept {
int32_t channels;
libv::vec2i size;
std::unique_ptr<uint8_t, decltype(&SOIL_free_image_data)> storage{nullptr, SOIL_free_image_data};
storage.reset(
SOIL_load_image_from_memory(
reinterpret_cast<const unsigned char*>(data.data()),
static_cast<int>(data.size()),
&size.x, &size.y, &channels,
SOIL_LOAD_AUTO));
if (storage == nullptr)
return std::nullopt;
else
return std::optional<Image>{std::make_shared<ImageSOIL>(size, channels, std::move(storage))};
}
// -------------------------------------------------------------------------------------------------
libv::vec2i ImageSOIL::size() const noexcept {
return size_;
}
Texture ImageSOIL::createTexture() const noexcept {
// NOTE: SOIL_create_OGL_texture Fails in OpenGL 3.3 core profile
// SOIL_create_OGL_texture(storage.get(), size_.x, size_.y, channels, SOIL_CREATE_NEW_ID, SOIL_FLAG_INVERT_Y);
// TODO P3: Would be nice to have on the fly compression requests
{
// Flip Y axis
const auto row_size = size_.x * channels;
auto row_tmp = libv::dynarray<uint8_t>{static_cast<size_t>(row_size)};
for (int32_t y = 0; y < size_.y / 2; ++y) {
auto* const tmp = row_tmp.data();
auto* const front = storage.get() + row_size * y;
auto* const back = storage.get() + row_size * (size_.y - 1 - y);
std::memcpy(tmp, front, row_size);
std::memcpy(front, back, row_size);
std::memcpy(back, tmp, row_size);
}
}
// Upload texture image
GLuint textureID = 0;
GLenum target = GL_TEXTURE_2D;
GLenum externalType = GL_UNSIGNED_BYTE;
GLenum externalFormat =
channels == 4 ? GL_RGBA :
channels == 3 ? GL_RGB :
channels == 2 ? GL_RG :
channels == 1 ? GL_R : 0;
GLenum Format = externalFormat;
glGenTextures(1, &textureID);
glBindTexture(target, textureID);
glTexParameteri(target, GL_TEXTURE_BASE_LEVEL, 0);
glTexParameteri(target, GL_TEXTURE_MAX_LEVEL, 0);
glTexImage2D(target, 0, Format, size_.x, size_.y, 0, externalFormat, externalType, storage.get());
libv::gl::checkGL();
return {textureID, TextureTarget{target}};
}
// -------------------------------------------------------------------------------------------------
} // namespace gl
} // namespace libv
| 31.12381
| 118
| 0.649327
|
cpplibv
|
60410d24844343dde7aedf4bda5b8157ebd9d8f1
| 215,735
|
cc
|
C++
|
src/xenia/cpu/backend/x64/x64_sequences.cc
|
Parovozik/Xenia_UI
|
3f12becc1845a8fc264ae74d25e28e543f61b5b4
|
[
"BSD-3-Clause"
] | null | null | null |
src/xenia/cpu/backend/x64/x64_sequences.cc
|
Parovozik/Xenia_UI
|
3f12becc1845a8fc264ae74d25e28e543f61b5b4
|
[
"BSD-3-Clause"
] | null | null | null |
src/xenia/cpu/backend/x64/x64_sequences.cc
|
Parovozik/Xenia_UI
|
3f12becc1845a8fc264ae74d25e28e543f61b5b4
|
[
"BSD-3-Clause"
] | 1
|
2018-10-16T16:45:27.000Z
|
2018-10-16T16:45:27.000Z
|
/**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2014 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
// A note about vectors:
// Xenia represents vectors as xyzw pairs, with indices 0123.
// XMM registers are xyzw pairs with indices 3210, making them more like wzyx.
// This makes things somewhat confusing. It'd be nice to just shuffle the
// registers around on load/store, however certain operations require that
// data be in the right offset.
// Basically, this identity must hold:
// shuffle(vec, b00011011) -> {x,y,z,w} => {x,y,z,w}
// All indices and operations must respect that.
//
// Memory (big endian):
// [00 01 02 03] [04 05 06 07] [08 09 0A 0B] [0C 0D 0E 0F] (x, y, z, w)
// load into xmm register:
// [0F 0E 0D 0C] [0B 0A 09 08] [07 06 05 04] [03 02 01 00] (w, z, y, x)
#include "xenia/cpu/backend/x64/x64_sequences.h"
#include "xenia/base/assert.h"
#include "xenia/base/logging.h"
#include "xenia/base/threading.h"
#include "xenia/cpu/backend/x64/x64_emitter.h"
#include "xenia/cpu/backend/x64/x64_tracers.h"
#include "xenia/cpu/hir/hir_builder.h"
#include "xenia/cpu/processor.h"
namespace xe {
namespace cpu {
namespace backend {
namespace x64 {
using namespace Xbyak;
// TODO(benvanik): direct usings.
using namespace xe::cpu::hir;
using namespace xe::cpu;
typedef bool (*SequenceSelectFn)(X64Emitter&, const Instr*, const Instr**);
std::unordered_multimap<uint32_t, SequenceSelectFn> sequence_table;
// Utilities/types used only in this file:
#include "xenia/cpu/backend/x64/x64_sequence.inl"
// Selects the right byte/word/etc from a vector. We need to flip logical
// indices (0,1,2,3,4,5,6,7,...) = (3,2,1,0,7,6,5,4,...)
#define VEC128_B(n) ((n) ^ 0x3)
#define VEC128_W(n) ((n) ^ 0x1)
#define VEC128_D(n) (n)
#define VEC128_F(n) (n)
// ============================================================================
// OPCODE_COMMENT
// ============================================================================
EMITTER(COMMENT, MATCH(I<OPCODE_COMMENT, VoidOp, OffsetOp>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
if (IsTracingInstr()) {
auto str = reinterpret_cast<const char*>(i.src1.value);
// TODO(benvanik): pass through.
// TODO(benvanik): don't just leak this memory.
auto str_copy = strdup(str);
e.mov(e.rdx, reinterpret_cast<uint64_t>(str_copy));
e.CallNative(reinterpret_cast<void*>(TraceString));
}
}
};
EMITTER_OPCODE_TABLE(
OPCODE_COMMENT,
COMMENT);
// ============================================================================
// OPCODE_NOP
// ============================================================================
EMITTER(NOP, MATCH(I<OPCODE_NOP, VoidOp>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.nop();
}
};
EMITTER_OPCODE_TABLE(
OPCODE_NOP,
NOP);
// ============================================================================
// OPCODE_SOURCE_OFFSET
// ============================================================================
EMITTER(SOURCE_OFFSET, MATCH(I<OPCODE_SOURCE_OFFSET, VoidOp, OffsetOp>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.MarkSourceOffset(i.instr);
}
};
EMITTER_OPCODE_TABLE(
OPCODE_SOURCE_OFFSET,
SOURCE_OFFSET);
// ============================================================================
// OPCODE_DEBUG_BREAK
// ============================================================================
EMITTER(DEBUG_BREAK, MATCH(I<OPCODE_DEBUG_BREAK, VoidOp>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.DebugBreak();
}
};
EMITTER_OPCODE_TABLE(
OPCODE_DEBUG_BREAK,
DEBUG_BREAK);
// ============================================================================
// OPCODE_DEBUG_BREAK_TRUE
// ============================================================================
EMITTER(DEBUG_BREAK_TRUE_I8, MATCH(I<OPCODE_DEBUG_BREAK_TRUE, VoidOp, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.test(i.src1, i.src1);
Xbyak::Label skip;
e.jz(skip);
e.DebugBreak();
e.L(skip);
}
};
EMITTER(DEBUG_BREAK_TRUE_I16, MATCH(I<OPCODE_DEBUG_BREAK_TRUE, VoidOp, I16<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.test(i.src1, i.src1);
Xbyak::Label skip;
e.jz(skip);
e.DebugBreak();
e.L(skip);
}
};
EMITTER(DEBUG_BREAK_TRUE_I32, MATCH(I<OPCODE_DEBUG_BREAK_TRUE, VoidOp, I32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.test(i.src1, i.src1);
Xbyak::Label skip;
e.jz(skip);
e.DebugBreak();
e.L(skip);
}
};
EMITTER(DEBUG_BREAK_TRUE_I64, MATCH(I<OPCODE_DEBUG_BREAK_TRUE, VoidOp, I64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.test(i.src1, i.src1);
Xbyak::Label skip;
e.jz(skip);
e.DebugBreak();
e.L(skip);
}
};
EMITTER(DEBUG_BREAK_TRUE_F32, MATCH(I<OPCODE_DEBUG_BREAK_TRUE, VoidOp, F32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.vptest(i.src1, i.src1);
Xbyak::Label skip;
e.jz(skip);
e.DebugBreak();
e.L(skip);
}
};
EMITTER(DEBUG_BREAK_TRUE_F64, MATCH(I<OPCODE_DEBUG_BREAK_TRUE, VoidOp, F64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.vptest(i.src1, i.src1);
Xbyak::Label skip;
e.jz(skip);
e.DebugBreak();
e.L(skip);
}
};
EMITTER_OPCODE_TABLE(
OPCODE_DEBUG_BREAK_TRUE,
DEBUG_BREAK_TRUE_I8,
DEBUG_BREAK_TRUE_I16,
DEBUG_BREAK_TRUE_I32,
DEBUG_BREAK_TRUE_I64,
DEBUG_BREAK_TRUE_F32,
DEBUG_BREAK_TRUE_F64);
// ============================================================================
// OPCODE_TRAP
// ============================================================================
EMITTER(TRAP, MATCH(I<OPCODE_TRAP, VoidOp>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.Trap(i.instr->flags);
}
};
EMITTER_OPCODE_TABLE(
OPCODE_TRAP,
TRAP);
// ============================================================================
// OPCODE_TRAP_TRUE
// ============================================================================
EMITTER(TRAP_TRUE_I8, MATCH(I<OPCODE_TRAP_TRUE, VoidOp, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.test(i.src1, i.src1);
Xbyak::Label skip;
e.jz(skip);
e.Trap(i.instr->flags);
e.L(skip);
}
};
EMITTER(TRAP_TRUE_I16, MATCH(I<OPCODE_TRAP_TRUE, VoidOp, I16<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.test(i.src1, i.src1);
Xbyak::Label skip;
e.jz(skip);
e.Trap(i.instr->flags);
e.L(skip);
}
};
EMITTER(TRAP_TRUE_I32, MATCH(I<OPCODE_TRAP_TRUE, VoidOp, I32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.test(i.src1, i.src1);
Xbyak::Label skip;
e.jz(skip);
e.Trap(i.instr->flags);
e.L(skip);
}
};
EMITTER(TRAP_TRUE_I64, MATCH(I<OPCODE_TRAP_TRUE, VoidOp, I64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.test(i.src1, i.src1);
Xbyak::Label skip;
e.jz(skip);
e.Trap(i.instr->flags);
e.L(skip);
}
};
EMITTER(TRAP_TRUE_F32, MATCH(I<OPCODE_TRAP_TRUE, VoidOp, F32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.vptest(i.src1, i.src1);
Xbyak::Label skip;
e.jz(skip);
e.Trap(i.instr->flags);
e.L(skip);
}
};
EMITTER(TRAP_TRUE_F64, MATCH(I<OPCODE_TRAP_TRUE, VoidOp, F64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.vptest(i.src1, i.src1);
Xbyak::Label skip;
e.jz(skip);
e.Trap(i.instr->flags);
e.L(skip);
}
};
EMITTER_OPCODE_TABLE(
OPCODE_TRAP_TRUE,
TRAP_TRUE_I8,
TRAP_TRUE_I16,
TRAP_TRUE_I32,
TRAP_TRUE_I64,
TRAP_TRUE_F32,
TRAP_TRUE_F64);
// ============================================================================
// OPCODE_CALL
// ============================================================================
EMITTER(CALL, MATCH(I<OPCODE_CALL, VoidOp, SymbolOp>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.Call(i.instr, i.src1.value);
}
};
EMITTER_OPCODE_TABLE(
OPCODE_CALL,
CALL);
// ============================================================================
// OPCODE_CALL_TRUE
// ============================================================================
EMITTER(CALL_TRUE_I8, MATCH(I<OPCODE_CALL_TRUE, VoidOp, I8<>, SymbolOp>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.test(i.src1, i.src1);
Xbyak::Label skip;
e.jz(skip);
e.Call(i.instr, i.src2.value);
e.L(skip);
}
};
EMITTER(CALL_TRUE_I16, MATCH(I<OPCODE_CALL_TRUE, VoidOp, I16<>, SymbolOp>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.test(i.src1, i.src1);
Xbyak::Label skip;
e.jz(skip);
e.Call(i.instr, i.src2.value);
e.L(skip);
}
};
EMITTER(CALL_TRUE_I32, MATCH(I<OPCODE_CALL_TRUE, VoidOp, I32<>, SymbolOp>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.test(i.src1, i.src1);
Xbyak::Label skip;
e.jz(skip);
e.Call(i.instr, i.src2.value);
e.L(skip);
}
};
EMITTER(CALL_TRUE_I64, MATCH(I<OPCODE_CALL_TRUE, VoidOp, I64<>, SymbolOp>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.test(i.src1, i.src1);
Xbyak::Label skip;
e.jz(skip);
e.Call(i.instr, i.src2.value);
e.L(skip);
}
};
EMITTER(CALL_TRUE_F32, MATCH(I<OPCODE_CALL_TRUE, VoidOp, F32<>, SymbolOp>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.vptest(i.src1, i.src1);
Xbyak::Label skip;
e.jz(skip);
e.Call(i.instr, i.src2.value);
e.L(skip);
}
};
EMITTER(CALL_TRUE_F64, MATCH(I<OPCODE_CALL_TRUE, VoidOp, F64<>, SymbolOp>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.vptest(i.src1, i.src1);
Xbyak::Label skip;
e.jz(skip);
e.Call(i.instr, i.src2.value);
e.L(skip);
}
};
EMITTER_OPCODE_TABLE(
OPCODE_CALL_TRUE,
CALL_TRUE_I8,
CALL_TRUE_I16,
CALL_TRUE_I32,
CALL_TRUE_I64,
CALL_TRUE_F32,
CALL_TRUE_F64);
// ============================================================================
// OPCODE_CALL_INDIRECT
// ============================================================================
EMITTER(CALL_INDIRECT, MATCH(I<OPCODE_CALL_INDIRECT, VoidOp, I64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.CallIndirect(i.instr, i.src1);
}
};
EMITTER_OPCODE_TABLE(
OPCODE_CALL_INDIRECT,
CALL_INDIRECT);
// ============================================================================
// OPCODE_CALL_INDIRECT_TRUE
// ============================================================================
EMITTER(CALL_INDIRECT_TRUE_I8, MATCH(I<OPCODE_CALL_INDIRECT_TRUE, VoidOp, I8<>, I64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.test(i.src1, i.src1);
Xbyak::Label skip;
e.jz(skip, CodeGenerator::T_NEAR);
e.CallIndirect(i.instr, i.src2);
e.L(skip);
}
};
EMITTER(CALL_INDIRECT_TRUE_I16, MATCH(I<OPCODE_CALL_INDIRECT_TRUE, VoidOp, I16<>, I64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.test(i.src1, i.src1);
Xbyak::Label skip;
e.jz(skip, CodeGenerator::T_NEAR);
e.CallIndirect(i.instr, i.src2);
e.L(skip);
}
};
EMITTER(CALL_INDIRECT_TRUE_I32, MATCH(I<OPCODE_CALL_INDIRECT_TRUE, VoidOp, I32<>, I64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.test(i.src1, i.src1);
Xbyak::Label skip;
e.jz(skip, CodeGenerator::T_NEAR);
e.CallIndirect(i.instr, i.src2);
e.L(skip);
}
};
EMITTER(CALL_INDIRECT_TRUE_I64, MATCH(I<OPCODE_CALL_INDIRECT_TRUE, VoidOp, I64<>, I64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.test(i.src1, i.src1);
Xbyak::Label skip;
e.jz(skip, CodeGenerator::T_NEAR);
e.CallIndirect(i.instr, i.src2);
e.L(skip);
}
};
EMITTER(CALL_INDIRECT_TRUE_F32, MATCH(I<OPCODE_CALL_INDIRECT_TRUE, VoidOp, F32<>, I64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.vptest(i.src1, i.src1);
Xbyak::Label skip;
e.jz(skip, CodeGenerator::T_NEAR);
e.CallIndirect(i.instr, i.src2);
e.L(skip);
}
};
EMITTER(CALL_INDIRECT_TRUE_F64, MATCH(I<OPCODE_CALL_INDIRECT_TRUE, VoidOp, F64<>, I64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.vptest(i.src1, i.src1);
Xbyak::Label skip;
e.jz(skip, CodeGenerator::T_NEAR);
e.CallIndirect(i.instr, i.src2);
e.L(skip);
}
};
EMITTER_OPCODE_TABLE(
OPCODE_CALL_INDIRECT_TRUE,
CALL_INDIRECT_TRUE_I8,
CALL_INDIRECT_TRUE_I16,
CALL_INDIRECT_TRUE_I32,
CALL_INDIRECT_TRUE_I64,
CALL_INDIRECT_TRUE_F32,
CALL_INDIRECT_TRUE_F64);
// ============================================================================
// OPCODE_CALL_EXTERN
// ============================================================================
EMITTER(CALL_EXTERN, MATCH(I<OPCODE_CALL_EXTERN, VoidOp, SymbolOp>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.CallExtern(i.instr, i.src1.value);
}
};
EMITTER_OPCODE_TABLE(
OPCODE_CALL_EXTERN,
CALL_EXTERN);
// ============================================================================
// OPCODE_RETURN
// ============================================================================
EMITTER(RETURN, MATCH(I<OPCODE_RETURN, VoidOp>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
// If this is the last instruction in the last block, just let us
// fall through.
if (i.instr->next || i.instr->block->next) {
e.jmp("epilog", CodeGenerator::T_NEAR);
}
}
};
EMITTER_OPCODE_TABLE(
OPCODE_RETURN,
RETURN);
// ============================================================================
// OPCODE_RETURN_TRUE
// ============================================================================
EMITTER(RETURN_TRUE_I8, MATCH(I<OPCODE_RETURN_TRUE, VoidOp, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.test(i.src1, i.src1);
e.jnz("epilog", CodeGenerator::T_NEAR);
}
};
EMITTER(RETURN_TRUE_I16, MATCH(I<OPCODE_RETURN_TRUE, VoidOp, I16<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.test(i.src1, i.src1);
e.jnz("epilog", CodeGenerator::T_NEAR);
}
};
EMITTER(RETURN_TRUE_I32, MATCH(I<OPCODE_RETURN_TRUE, VoidOp, I32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.test(i.src1, i.src1);
e.jnz("epilog", CodeGenerator::T_NEAR);
}
};
EMITTER(RETURN_TRUE_I64, MATCH(I<OPCODE_RETURN_TRUE, VoidOp, I64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.test(i.src1, i.src1);
e.jnz("epilog", CodeGenerator::T_NEAR);
}
};
EMITTER(RETURN_TRUE_F32, MATCH(I<OPCODE_RETURN_TRUE, VoidOp, F32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.vptest(i.src1, i.src1);
e.jnz("epilog", CodeGenerator::T_NEAR);
}
};
EMITTER(RETURN_TRUE_F64, MATCH(I<OPCODE_RETURN_TRUE, VoidOp, F64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.vptest(i.src1, i.src1);
e.jnz("epilog", CodeGenerator::T_NEAR);
}
};
EMITTER_OPCODE_TABLE(
OPCODE_RETURN_TRUE,
RETURN_TRUE_I8,
RETURN_TRUE_I16,
RETURN_TRUE_I32,
RETURN_TRUE_I64,
RETURN_TRUE_F32,
RETURN_TRUE_F64);
// ============================================================================
// OPCODE_SET_RETURN_ADDRESS
// ============================================================================
EMITTER(SET_RETURN_ADDRESS, MATCH(I<OPCODE_SET_RETURN_ADDRESS, VoidOp, I64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.SetReturnAddress(i.src1.constant());
}
};
EMITTER_OPCODE_TABLE(
OPCODE_SET_RETURN_ADDRESS,
SET_RETURN_ADDRESS);
// ============================================================================
// OPCODE_BRANCH
// ============================================================================
EMITTER(BRANCH, MATCH(I<OPCODE_BRANCH, VoidOp, LabelOp>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.jmp(i.src1.value->name, e.T_NEAR);
}
};
EMITTER_OPCODE_TABLE(
OPCODE_BRANCH,
BRANCH);
// ============================================================================
// OPCODE_BRANCH_TRUE
// ============================================================================
EMITTER(BRANCH_TRUE_I8, MATCH(I<OPCODE_BRANCH_TRUE, VoidOp, I8<>, LabelOp>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.test(i.src1, i.src1);
e.jnz(i.src2.value->name, e.T_NEAR);
}
};
EMITTER(BRANCH_TRUE_I16, MATCH(I<OPCODE_BRANCH_TRUE, VoidOp, I16<>, LabelOp>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.test(i.src1, i.src1);
e.jnz(i.src2.value->name, e.T_NEAR);
}
};
EMITTER(BRANCH_TRUE_I32, MATCH(I<OPCODE_BRANCH_TRUE, VoidOp, I32<>, LabelOp>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.test(i.src1, i.src1);
e.jnz(i.src2.value->name, e.T_NEAR);
}
};
EMITTER(BRANCH_TRUE_I64, MATCH(I<OPCODE_BRANCH_TRUE, VoidOp, I64<>, LabelOp>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.test(i.src1, i.src1);
e.jnz(i.src2.value->name, e.T_NEAR);
}
};
EMITTER(BRANCH_TRUE_F32, MATCH(I<OPCODE_BRANCH_TRUE, VoidOp, F32<>, LabelOp>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.vptest(i.src1, i.src1);
e.jnz(i.src2.value->name, e.T_NEAR);
}
};
EMITTER(BRANCH_TRUE_F64, MATCH(I<OPCODE_BRANCH_TRUE, VoidOp, F64<>, LabelOp>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.vptest(i.src1, i.src1);
e.jnz(i.src2.value->name, e.T_NEAR);
}
};
EMITTER_OPCODE_TABLE(
OPCODE_BRANCH_TRUE,
BRANCH_TRUE_I8,
BRANCH_TRUE_I16,
BRANCH_TRUE_I32,
BRANCH_TRUE_I64,
BRANCH_TRUE_F32,
BRANCH_TRUE_F64);
// ============================================================================
// OPCODE_BRANCH_FALSE
// ============================================================================
EMITTER(BRANCH_FALSE_I8, MATCH(I<OPCODE_BRANCH_FALSE, VoidOp, I8<>, LabelOp>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.test(i.src1, i.src1);
e.jz(i.src2.value->name, e.T_NEAR);
}
};
EMITTER(BRANCH_FALSE_I16, MATCH(I<OPCODE_BRANCH_FALSE, VoidOp, I16<>, LabelOp>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.test(i.src1, i.src1);
e.jz(i.src2.value->name, e.T_NEAR);
}
};
EMITTER(BRANCH_FALSE_I32, MATCH(I<OPCODE_BRANCH_FALSE, VoidOp, I32<>, LabelOp>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.test(i.src1, i.src1);
e.jz(i.src2.value->name, e.T_NEAR);
}
};
EMITTER(BRANCH_FALSE_I64, MATCH(I<OPCODE_BRANCH_FALSE, VoidOp, I64<>, LabelOp>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.test(i.src1, i.src1);
e.jz(i.src2.value->name, e.T_NEAR);
}
};
EMITTER(BRANCH_FALSE_F32, MATCH(I<OPCODE_BRANCH_FALSE, VoidOp, F32<>, LabelOp>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.vptest(i.src1, i.src1);
e.jz(i.src2.value->name, e.T_NEAR);
}
};
EMITTER(BRANCH_FALSE_F64, MATCH(I<OPCODE_BRANCH_FALSE, VoidOp, F64<>, LabelOp>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.vptest(i.src1, i.src1);
e.jz(i.src2.value->name, e.T_NEAR);
}
};
EMITTER_OPCODE_TABLE(
OPCODE_BRANCH_FALSE,
BRANCH_FALSE_I8,
BRANCH_FALSE_I16,
BRANCH_FALSE_I32,
BRANCH_FALSE_I64,
BRANCH_FALSE_F32,
BRANCH_FALSE_F64);
// ============================================================================
// OPCODE_ASSIGN
// ============================================================================
EMITTER(ASSIGN_I8, MATCH(I<OPCODE_ASSIGN, I8<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.mov(i.dest, i.src1);
}
};
EMITTER(ASSIGN_I16, MATCH(I<OPCODE_ASSIGN, I16<>, I16<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.mov(i.dest, i.src1);
}
};
EMITTER(ASSIGN_I32, MATCH(I<OPCODE_ASSIGN, I32<>, I32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.mov(i.dest, i.src1);
}
};
EMITTER(ASSIGN_I64, MATCH(I<OPCODE_ASSIGN, I64<>, I64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.mov(i.dest, i.src1);
}
};
EMITTER(ASSIGN_F32, MATCH(I<OPCODE_ASSIGN, F32<>, F32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.vmovaps(i.dest, i.src1);
}
};
EMITTER(ASSIGN_F64, MATCH(I<OPCODE_ASSIGN, F64<>, F64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.vmovaps(i.dest, i.src1);
}
};
EMITTER(ASSIGN_V128, MATCH(I<OPCODE_ASSIGN, V128<>, V128<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.vmovaps(i.dest, i.src1);
}
};
EMITTER_OPCODE_TABLE(
OPCODE_ASSIGN,
ASSIGN_I8,
ASSIGN_I16,
ASSIGN_I32,
ASSIGN_I64,
ASSIGN_F32,
ASSIGN_F64,
ASSIGN_V128);
// ============================================================================
// OPCODE_CAST
// ============================================================================
EMITTER(CAST_I32_F32, MATCH(I<OPCODE_CAST, I32<>, F32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.vmovd(i.dest, i.src1);
}
};
EMITTER(CAST_I64_F64, MATCH(I<OPCODE_CAST, I64<>, F64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.vmovq(i.dest, i.src1);
}
};
EMITTER(CAST_F32_I32, MATCH(I<OPCODE_CAST, F32<>, I32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.vmovd(i.dest, i.src1);
}
};
EMITTER(CAST_F64_I64, MATCH(I<OPCODE_CAST, F64<>, I64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.vmovq(i.dest, i.src1);
}
};
EMITTER_OPCODE_TABLE(
OPCODE_CAST,
CAST_I32_F32,
CAST_I64_F64,
CAST_F32_I32,
CAST_F64_I64);
// ============================================================================
// OPCODE_ZERO_EXTEND
// ============================================================================
EMITTER(ZERO_EXTEND_I16_I8, MATCH(I<OPCODE_ZERO_EXTEND, I16<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.movzx(i.dest, i.src1);
}
};
EMITTER(ZERO_EXTEND_I32_I8, MATCH(I<OPCODE_ZERO_EXTEND, I32<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.movzx(i.dest, i.src1);
}
};
EMITTER(ZERO_EXTEND_I64_I8, MATCH(I<OPCODE_ZERO_EXTEND, I64<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.movzx(i.dest, i.src1);
}
};
EMITTER(ZERO_EXTEND_I32_I16, MATCH(I<OPCODE_ZERO_EXTEND, I32<>, I16<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.movzx(i.dest, i.src1);
}
};
EMITTER(ZERO_EXTEND_I64_I16, MATCH(I<OPCODE_ZERO_EXTEND, I64<>, I16<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.movzx(i.dest, i.src1);
}
};
EMITTER(ZERO_EXTEND_I64_I32, MATCH(I<OPCODE_ZERO_EXTEND, I64<>, I32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.mov(i.dest.reg().cvt32(), i.src1);
}
};
EMITTER_OPCODE_TABLE(
OPCODE_ZERO_EXTEND,
ZERO_EXTEND_I16_I8,
ZERO_EXTEND_I32_I8,
ZERO_EXTEND_I64_I8,
ZERO_EXTEND_I32_I16,
ZERO_EXTEND_I64_I16,
ZERO_EXTEND_I64_I32);
// ============================================================================
// OPCODE_SIGN_EXTEND
// ============================================================================
EMITTER(SIGN_EXTEND_I16_I8, MATCH(I<OPCODE_SIGN_EXTEND, I16<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.movsx(i.dest, i.src1);
}
};
EMITTER(SIGN_EXTEND_I32_I8, MATCH(I<OPCODE_SIGN_EXTEND, I32<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.movsx(i.dest, i.src1);
}
};
EMITTER(SIGN_EXTEND_I64_I8, MATCH(I<OPCODE_SIGN_EXTEND, I64<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.movsx(i.dest, i.src1);
}
};
EMITTER(SIGN_EXTEND_I32_I16, MATCH(I<OPCODE_SIGN_EXTEND, I32<>, I16<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.movsx(i.dest, i.src1);
}
};
EMITTER(SIGN_EXTEND_I64_I16, MATCH(I<OPCODE_SIGN_EXTEND, I64<>, I16<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.movsx(i.dest, i.src1);
}
};
EMITTER(SIGN_EXTEND_I64_I32, MATCH(I<OPCODE_SIGN_EXTEND, I64<>, I32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.movsxd(i.dest, i.src1);
}
};
EMITTER_OPCODE_TABLE(
OPCODE_SIGN_EXTEND,
SIGN_EXTEND_I16_I8,
SIGN_EXTEND_I32_I8,
SIGN_EXTEND_I64_I8,
SIGN_EXTEND_I32_I16,
SIGN_EXTEND_I64_I16,
SIGN_EXTEND_I64_I32);
// ============================================================================
// OPCODE_TRUNCATE
// ============================================================================
EMITTER(TRUNCATE_I8_I16, MATCH(I<OPCODE_TRUNCATE, I8<>, I16<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.movzx(i.dest.reg().cvt32(), i.src1.reg().cvt8());
}
};
EMITTER(TRUNCATE_I8_I32, MATCH(I<OPCODE_TRUNCATE, I8<>, I32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.movzx(i.dest.reg().cvt32(), i.src1.reg().cvt8());
}
};
EMITTER(TRUNCATE_I8_I64, MATCH(I<OPCODE_TRUNCATE, I8<>, I64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.movzx(i.dest.reg().cvt32(), i.src1.reg().cvt8());
}
};
EMITTER(TRUNCATE_I16_I32, MATCH(I<OPCODE_TRUNCATE, I16<>, I32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.movzx(i.dest.reg().cvt32(), i.src1.reg().cvt16());
}
};
EMITTER(TRUNCATE_I16_I64, MATCH(I<OPCODE_TRUNCATE, I16<>, I64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.movzx(i.dest.reg().cvt32(), i.src1.reg().cvt16());
}
};
EMITTER(TRUNCATE_I32_I64, MATCH(I<OPCODE_TRUNCATE, I32<>, I64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.mov(i.dest, i.src1.reg().cvt32());
}
};
EMITTER_OPCODE_TABLE(
OPCODE_TRUNCATE,
TRUNCATE_I8_I16,
TRUNCATE_I8_I32,
TRUNCATE_I8_I64,
TRUNCATE_I16_I32,
TRUNCATE_I16_I64,
TRUNCATE_I32_I64);
// ============================================================================
// OPCODE_CONVERT
// ============================================================================
EMITTER(CONVERT_I32_F32, MATCH(I<OPCODE_CONVERT, I32<>, F32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
// TODO(benvanik): saturation check? cvtt* (trunc?)
e.vcvtss2si(i.dest, i.src1);
}
};
EMITTER(CONVERT_I32_F64, MATCH(I<OPCODE_CONVERT, I32<>, F64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
// TODO(benvanik): saturation check? cvtt* (trunc?)
e.vcvttsd2si(i.dest, i.src1);
}
};
EMITTER(CONVERT_I64_F64, MATCH(I<OPCODE_CONVERT, I64<>, F64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
// TODO(benvanik): saturation check? cvtt* (trunc?)
e.vcvttsd2si(i.dest, i.src1);
}
};
EMITTER(CONVERT_F32_I32, MATCH(I<OPCODE_CONVERT, F32<>, I32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
// TODO(benvanik): saturation check? cvtt* (trunc?)
e.vcvtsi2ss(i.dest, i.src1);
}
};
EMITTER(CONVERT_F32_F64, MATCH(I<OPCODE_CONVERT, F32<>, F64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
// TODO(benvanik): saturation check? cvtt* (trunc?)
e.vcvtsd2ss(i.dest, i.src1);
}
};
EMITTER(CONVERT_F64_I64, MATCH(I<OPCODE_CONVERT, F64<>, I64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
// TODO(benvanik): saturation check? cvtt* (trunc?)
e.vcvtsi2sd(i.dest, i.src1);
}
};
EMITTER(CONVERT_F64_F32, MATCH(I<OPCODE_CONVERT, F64<>, F32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.vcvtss2sd(i.dest, i.src1);
}
};
EMITTER_OPCODE_TABLE(
OPCODE_CONVERT,
CONVERT_I32_F32,
CONVERT_I32_F64,
CONVERT_I64_F64,
CONVERT_F32_I32,
CONVERT_F32_F64,
CONVERT_F64_I64,
CONVERT_F64_F32);
// ============================================================================
// OPCODE_ROUND
// ============================================================================
EMITTER(ROUND_F32, MATCH(I<OPCODE_ROUND, F32<>, F32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
switch (i.instr->flags) {
case ROUND_TO_ZERO:
e.vroundss(i.dest, i.src1, B00000011);
break;
case ROUND_TO_NEAREST:
e.vroundss(i.dest, i.src1, B00000000);
break;
case ROUND_TO_MINUS_INFINITY:
e.vroundss(i.dest, i.src1, B00000001);
break;
case ROUND_TO_POSITIVE_INFINITY:
e.vroundss(i.dest, i.src1, B00000010);
break;
}
}
};
EMITTER(ROUND_F64, MATCH(I<OPCODE_ROUND, F64<>, F64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
switch (i.instr->flags) {
case ROUND_TO_ZERO:
e.vroundsd(i.dest, i.src1, B00000011);
break;
case ROUND_TO_NEAREST:
e.vroundsd(i.dest, i.src1, B00000000);
break;
case ROUND_TO_MINUS_INFINITY:
e.vroundsd(i.dest, i.src1, B00000001);
break;
case ROUND_TO_POSITIVE_INFINITY:
e.vroundsd(i.dest, i.src1, B00000010);
break;
}
}
};
EMITTER(ROUND_V128, MATCH(I<OPCODE_ROUND, V128<>, V128<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
switch (i.instr->flags) {
case ROUND_TO_ZERO:
e.vroundps(i.dest, i.src1, B00000011);
break;
case ROUND_TO_NEAREST:
e.vroundps(i.dest, i.src1, B00000000);
break;
case ROUND_TO_MINUS_INFINITY:
e.vroundps(i.dest, i.src1, B00000001);
break;
case ROUND_TO_POSITIVE_INFINITY:
e.vroundps(i.dest, i.src1, B00000010);
break;
}
}
};
EMITTER_OPCODE_TABLE(
OPCODE_ROUND,
ROUND_F32,
ROUND_F64,
ROUND_V128);
// ============================================================================
// OPCODE_VECTOR_CONVERT_I2F
// ============================================================================
EMITTER(VECTOR_CONVERT_I2F, MATCH(I<OPCODE_VECTOR_CONVERT_I2F, V128<>, V128<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
// flags = ARITHMETIC_UNSIGNED
// TODO(benvanik): are these really the same? VC++ thinks so.
e.vcvtdq2ps(i.dest, i.src1);
}
};
EMITTER_OPCODE_TABLE(
OPCODE_VECTOR_CONVERT_I2F,
VECTOR_CONVERT_I2F);
// ============================================================================
// OPCODE_VECTOR_CONVERT_F2I
// ============================================================================
EMITTER(VECTOR_CONVERT_F2I, MATCH(I<OPCODE_VECTOR_CONVERT_F2I, V128<>, V128<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
// flags = ARITHMETIC_UNSIGNED | ARITHMETIC_UNSIGNED
// TODO(benvanik): are these really the same? VC++ thinks so.
e.vcvttps2dq(i.dest, i.src1);
if (i.instr->flags & ARITHMETIC_SATURATE) {
// TODO(benvanik): check saturation.
// In theory cvt throws if it saturates.
}
}
};
EMITTER_OPCODE_TABLE(
OPCODE_VECTOR_CONVERT_F2I,
VECTOR_CONVERT_F2I);
// ============================================================================
// OPCODE_LOAD_VECTOR_SHL
// ============================================================================
static const vec128_t lvsl_table[16] = {
vec128b(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15),
vec128b(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16),
vec128b(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17),
vec128b(3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18),
vec128b(4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19),
vec128b(5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20),
vec128b(6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21),
vec128b(7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22),
vec128b(8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23),
vec128b(9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24),
vec128b(10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25),
vec128b(11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26),
vec128b(12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27),
vec128b(13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28),
vec128b(14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29),
vec128b(15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30),
};
EMITTER(LOAD_VECTOR_SHL_I8, MATCH(I<OPCODE_LOAD_VECTOR_SHL, V128<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
if (i.src1.is_constant) {
auto sh = i.src1.constant();
assert_true(sh < xe::countof(lvsl_table));
e.mov(e.rax, (uintptr_t)&lvsl_table[sh]);
e.vmovaps(i.dest, e.ptr[e.rax]);
} else {
// TODO(benvanik): find a cheaper way of doing this.
e.movzx(e.rdx, i.src1);
e.and(e.dx, 0xF);
e.shl(e.dx, 4);
e.mov(e.rax, (uintptr_t)lvsl_table);
e.vmovaps(i.dest, e.ptr[e.rax + e.rdx]);
e.ReloadEDX();
}
}
};
EMITTER_OPCODE_TABLE(
OPCODE_LOAD_VECTOR_SHL,
LOAD_VECTOR_SHL_I8);
// ============================================================================
// OPCODE_LOAD_VECTOR_SHR
// ============================================================================
static const vec128_t lvsr_table[16] = {
vec128b(16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31),
vec128b(15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30),
vec128b(14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29),
vec128b(13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28),
vec128b(12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27),
vec128b(11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26),
vec128b(10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25),
vec128b(9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24),
vec128b(8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23),
vec128b(7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22),
vec128b(6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21),
vec128b(5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20),
vec128b(4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19),
vec128b(3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18),
vec128b(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17),
vec128b(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16),
};
EMITTER(LOAD_VECTOR_SHR_I8, MATCH(I<OPCODE_LOAD_VECTOR_SHR, V128<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
if (i.src1.is_constant) {
auto sh = i.src1.constant();
assert_true(sh < xe::countof(lvsr_table));
e.mov(e.rax, (uintptr_t)&lvsr_table[sh]);
e.vmovaps(i.dest, e.ptr[e.rax]);
} else {
// TODO(benvanik): find a cheaper way of doing this.
e.movzx(e.rdx, i.src1);
e.and(e.dx, 0xF);
e.shl(e.dx, 4);
e.mov(e.rax, (uintptr_t)lvsr_table);
e.vmovaps(i.dest, e.ptr[e.rax + e.rdx]);
e.ReloadEDX();
}
}
};
EMITTER_OPCODE_TABLE(
OPCODE_LOAD_VECTOR_SHR,
LOAD_VECTOR_SHR_I8);
// ============================================================================
// OPCODE_LOAD_CLOCK
// ============================================================================
EMITTER(LOAD_CLOCK, MATCH(I<OPCODE_LOAD_CLOCK, I64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
// It'd be cool to call QueryPerformanceCounter directly, but w/e.
e.CallNative(LoadClock);
e.mov(i.dest, e.rax);
}
static uint64_t LoadClock(void* raw_context) {
return xe::threading::ticks();
}
};
EMITTER_OPCODE_TABLE(
OPCODE_LOAD_CLOCK,
LOAD_CLOCK);
// ============================================================================
// OPCODE_LOAD_LOCAL
// ============================================================================
// Note: all types are always aligned on the stack.
EMITTER(LOAD_LOCAL_I8, MATCH(I<OPCODE_LOAD_LOCAL, I8<>, I32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.mov(i.dest, e.byte[e.rsp + i.src1.constant()]);
//e.TraceLoadI8(DATA_LOCAL, i.src1.constant, i.dest);
}
};
EMITTER(LOAD_LOCAL_I16, MATCH(I<OPCODE_LOAD_LOCAL, I16<>, I32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.mov(i.dest, e.word[e.rsp + i.src1.constant()]);
//e.TraceLoadI16(DATA_LOCAL, i.src1.constant, i.dest);
}
};
EMITTER(LOAD_LOCAL_I32, MATCH(I<OPCODE_LOAD_LOCAL, I32<>, I32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.mov(i.dest, e.dword[e.rsp + i.src1.constant()]);
//e.TraceLoadI32(DATA_LOCAL, i.src1.constant, i.dest);
}
};
EMITTER(LOAD_LOCAL_I64, MATCH(I<OPCODE_LOAD_LOCAL, I64<>, I32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.mov(i.dest, e.qword[e.rsp + i.src1.constant()]);
//e.TraceLoadI64(DATA_LOCAL, i.src1.constant, i.dest);
}
};
EMITTER(LOAD_LOCAL_F32, MATCH(I<OPCODE_LOAD_LOCAL, F32<>, I32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.vmovss(i.dest, e.dword[e.rsp + i.src1.constant()]);
//e.TraceLoadF32(DATA_LOCAL, i.src1.constant, i.dest);
}
};
EMITTER(LOAD_LOCAL_F64, MATCH(I<OPCODE_LOAD_LOCAL, F64<>, I32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.vmovsd(i.dest, e.qword[e.rsp + i.src1.constant()]);
//e.TraceLoadF64(DATA_LOCAL, i.src1.constant, i.dest);
}
};
EMITTER(LOAD_LOCAL_V128, MATCH(I<OPCODE_LOAD_LOCAL, V128<>, I32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.vmovaps(i.dest, e.ptr[e.rsp + i.src1.constant()]);
//e.TraceLoadV128(DATA_LOCAL, i.src1.constant, i.dest);
}
};
EMITTER_OPCODE_TABLE(
OPCODE_LOAD_LOCAL,
LOAD_LOCAL_I8,
LOAD_LOCAL_I16,
LOAD_LOCAL_I32,
LOAD_LOCAL_I64,
LOAD_LOCAL_F32,
LOAD_LOCAL_F64,
LOAD_LOCAL_V128);
// ============================================================================
// OPCODE_STORE_LOCAL
// ============================================================================
// Note: all types are always aligned on the stack.
EMITTER(STORE_LOCAL_I8, MATCH(I<OPCODE_STORE_LOCAL, VoidOp, I32<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
//e.TraceStoreI8(DATA_LOCAL, i.src1.constant, i.src2);
e.mov(e.byte[e.rsp + i.src1.constant()], i.src2);
}
};
EMITTER(STORE_LOCAL_I16, MATCH(I<OPCODE_STORE_LOCAL, VoidOp, I32<>, I16<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
//e.TraceStoreI16(DATA_LOCAL, i.src1.constant, i.src2);
e.mov(e.word[e.rsp + i.src1.constant()], i.src2);
}
};
EMITTER(STORE_LOCAL_I32, MATCH(I<OPCODE_STORE_LOCAL, VoidOp, I32<>, I32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
//e.TraceStoreI32(DATA_LOCAL, i.src1.constant, i.src2);
e.mov(e.dword[e.rsp + i.src1.constant()], i.src2);
}
};
EMITTER(STORE_LOCAL_I64, MATCH(I<OPCODE_STORE_LOCAL, VoidOp, I32<>, I64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
//e.TraceStoreI64(DATA_LOCAL, i.src1.constant, i.src2);
e.mov(e.qword[e.rsp + i.src1.constant()], i.src2);
}
};
EMITTER(STORE_LOCAL_F32, MATCH(I<OPCODE_STORE_LOCAL, VoidOp, I32<>, F32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
//e.TraceStoreF32(DATA_LOCAL, i.src1.constant, i.src2);
e.vmovss(e.dword[e.rsp + i.src1.constant()], i.src2);
}
};
EMITTER(STORE_LOCAL_F64, MATCH(I<OPCODE_STORE_LOCAL, VoidOp, I32<>, F64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
//e.TraceStoreF64(DATA_LOCAL, i.src1.constant, i.src2);
e.vmovsd(e.qword[e.rsp + i.src1.constant()], i.src2);
}
};
EMITTER(STORE_LOCAL_V128, MATCH(I<OPCODE_STORE_LOCAL, VoidOp, I32<>, V128<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
//e.TraceStoreV128(DATA_LOCAL, i.src1.constant, i.src2);
e.vmovaps(e.ptr[e.rsp + i.src1.constant()], i.src2);
}
};
EMITTER_OPCODE_TABLE(
OPCODE_STORE_LOCAL,
STORE_LOCAL_I8,
STORE_LOCAL_I16,
STORE_LOCAL_I32,
STORE_LOCAL_I64,
STORE_LOCAL_F32,
STORE_LOCAL_F64,
STORE_LOCAL_V128);
// ============================================================================
// OPCODE_LOAD_CONTEXT
// ============================================================================
// Note: all types are always aligned in the context.
RegExp ComputeContextAddress(X64Emitter& e, const OffsetOp& offset) {
return e.rcx + offset.value;
}
EMITTER(LOAD_CONTEXT_I8, MATCH(I<OPCODE_LOAD_CONTEXT, I8<>, OffsetOp>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
auto addr = ComputeContextAddress(e, i.src1);
e.mov(i.dest, e.byte[addr]);
if (IsTracingData()) {
e.mov(e.r8, e.byte[addr]);
e.mov(e.rdx, i.src1.value);
e.CallNative(reinterpret_cast<void*>(TraceContextLoadI8));
}
}
};
EMITTER(LOAD_CONTEXT_I16, MATCH(I<OPCODE_LOAD_CONTEXT, I16<>, OffsetOp>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
auto addr = ComputeContextAddress(e, i.src1);
e.mov(i.dest, e.word[addr]);
if (IsTracingData()) {
e.mov(e.r8, e.word[addr]);
e.mov(e.rdx, i.src1.value);
e.CallNative(reinterpret_cast<void*>(TraceContextLoadI16));
}
}
};
EMITTER(LOAD_CONTEXT_I32, MATCH(I<OPCODE_LOAD_CONTEXT, I32<>, OffsetOp>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
auto addr = ComputeContextAddress(e, i.src1);
e.mov(i.dest, e.dword[addr]);
if (IsTracingData()) {
e.mov(e.r8, e.dword[addr]);
e.mov(e.rdx, i.src1.value);
e.CallNative(reinterpret_cast<void*>(TraceContextLoadI32));
}
}
};
EMITTER(LOAD_CONTEXT_I64, MATCH(I<OPCODE_LOAD_CONTEXT, I64<>, OffsetOp>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
auto addr = ComputeContextAddress(e, i.src1);
e.mov(i.dest, e.qword[addr]);
if (IsTracingData()) {
e.mov(e.r8, e.qword[addr]);
e.mov(e.rdx, i.src1.value);
e.CallNative(reinterpret_cast<void*>(TraceContextLoadI64));
}
}
};
EMITTER(LOAD_CONTEXT_F32, MATCH(I<OPCODE_LOAD_CONTEXT, F32<>, OffsetOp>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
auto addr = ComputeContextAddress(e, i.src1);
e.vmovss(i.dest, e.dword[addr]);
if (IsTracingData()) {
e.lea(e.r8, e.dword[addr]);
e.mov(e.rdx, i.src1.value);
e.CallNative(reinterpret_cast<void*>(TraceContextLoadF32));
}
}
};
EMITTER(LOAD_CONTEXT_F64, MATCH(I<OPCODE_LOAD_CONTEXT, F64<>, OffsetOp>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
auto addr = ComputeContextAddress(e, i.src1);
e.vmovsd(i.dest, e.qword[addr]);
if (IsTracingData()) {
e.lea(e.r8, e.qword[addr]);
e.mov(e.rdx, i.src1.value);
e.CallNative(reinterpret_cast<void*>(TraceContextLoadF64));
}
}
};
EMITTER(LOAD_CONTEXT_V128, MATCH(I<OPCODE_LOAD_CONTEXT, V128<>, OffsetOp>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
auto addr = ComputeContextAddress(e, i.src1);
e.vmovaps(i.dest, e.ptr[addr]);
if (IsTracingData()) {
e.lea(e.r8, e.ptr[addr]);
e.mov(e.rdx, i.src1.value);
e.CallNative(reinterpret_cast<void*>(TraceContextLoadV128));
}
}
};
EMITTER_OPCODE_TABLE(
OPCODE_LOAD_CONTEXT,
LOAD_CONTEXT_I8,
LOAD_CONTEXT_I16,
LOAD_CONTEXT_I32,
LOAD_CONTEXT_I64,
LOAD_CONTEXT_F32,
LOAD_CONTEXT_F64,
LOAD_CONTEXT_V128);
// ============================================================================
// OPCODE_STORE_CONTEXT
// ============================================================================
// Note: all types are always aligned on the stack.
EMITTER(STORE_CONTEXT_I8, MATCH(I<OPCODE_STORE_CONTEXT, VoidOp, OffsetOp, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
auto addr = ComputeContextAddress(e, i.src1);
if (i.src2.is_constant) {
e.mov(e.byte[addr], i.src2.constant());
} else {
e.mov(e.byte[addr], i.src2);
}
if (IsTracingData()) {
e.mov(e.r8, e.byte[addr]);
e.mov(e.rdx, i.src1.value);
e.CallNative(reinterpret_cast<void*>(TraceContextStoreI8));
}
}
};
EMITTER(STORE_CONTEXT_I16, MATCH(I<OPCODE_STORE_CONTEXT, VoidOp, OffsetOp, I16<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
auto addr = ComputeContextAddress(e, i.src1);
if (i.src2.is_constant) {
e.mov(e.word[addr], i.src2.constant());
} else {
e.mov(e.word[addr], i.src2);
}
if (IsTracingData()) {
e.mov(e.r8, e.word[addr]);
e.mov(e.rdx, i.src1.value);
e.CallNative(reinterpret_cast<void*>(TraceContextStoreI16));
}
}
};
EMITTER(STORE_CONTEXT_I32, MATCH(I<OPCODE_STORE_CONTEXT, VoidOp, OffsetOp, I32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
auto addr = ComputeContextAddress(e, i.src1);
if (i.src2.is_constant) {
e.mov(e.dword[addr], i.src2.constant());
} else {
e.mov(e.dword[addr], i.src2);
}
if (IsTracingData()) {
e.mov(e.r8, e.dword[addr]);
e.mov(e.rdx, i.src1.value);
e.CallNative(reinterpret_cast<void*>(TraceContextStoreI32));
}
}
};
EMITTER(STORE_CONTEXT_I64, MATCH(I<OPCODE_STORE_CONTEXT, VoidOp, OffsetOp, I64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
auto addr = ComputeContextAddress(e, i.src1);
if (i.src2.is_constant) {
e.MovMem64(addr, i.src2.constant());
} else {
e.mov(e.qword[addr], i.src2);
}
if (IsTracingData()) {
e.mov(e.r8, e.qword[addr]);
e.mov(e.rdx, i.src1.value);
e.CallNative(reinterpret_cast<void*>(TraceContextStoreI64));
}
}
};
EMITTER(STORE_CONTEXT_F32, MATCH(I<OPCODE_STORE_CONTEXT, VoidOp, OffsetOp, F32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
auto addr = ComputeContextAddress(e, i.src1);
if (i.src2.is_constant) {
e.mov(e.dword[addr], i.src2.value->constant.i32);
} else {
e.vmovss(e.dword[addr], i.src2);
}
if (IsTracingData()) {
e.lea(e.r8, e.dword[addr]);
e.mov(e.rdx, i.src1.value);
e.CallNative(reinterpret_cast<void*>(TraceContextStoreF32));
}
}
};
EMITTER(STORE_CONTEXT_F64, MATCH(I<OPCODE_STORE_CONTEXT, VoidOp, OffsetOp, F64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
auto addr = ComputeContextAddress(e, i.src1);
if (i.src2.is_constant) {
e.MovMem64(addr, i.src2.value->constant.i64);
} else {
e.vmovsd(e.qword[addr], i.src2);
}
if (IsTracingData()) {
e.lea(e.r8, e.qword[addr]);
e.mov(e.rdx, i.src1.value);
e.CallNative(reinterpret_cast<void*>(TraceContextStoreF64));
}
}
};
EMITTER(STORE_CONTEXT_V128, MATCH(I<OPCODE_STORE_CONTEXT, VoidOp, OffsetOp, V128<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
auto addr = ComputeContextAddress(e, i.src1);
if (i.src2.is_constant) {
e.LoadConstantXmm(e.xmm0, i.src2.constant());
e.vmovaps(e.ptr[addr], e.xmm0);
} else {
e.vmovaps(e.ptr[addr], i.src2);
}
if (IsTracingData()) {
e.lea(e.r8, e.ptr[addr]);
e.mov(e.rdx, i.src1.value);
e.CallNative(reinterpret_cast<void*>(TraceContextStoreV128));
}
}
};
EMITTER_OPCODE_TABLE(
OPCODE_STORE_CONTEXT,
STORE_CONTEXT_I8,
STORE_CONTEXT_I16,
STORE_CONTEXT_I32,
STORE_CONTEXT_I64,
STORE_CONTEXT_F32,
STORE_CONTEXT_F64,
STORE_CONTEXT_V128);
// ============================================================================
// OPCODE_LOAD
// ============================================================================
// Note: most *should* be aligned, but needs to be checked!
template <typename T>
RegExp ComputeMemoryAddress(X64Emitter& e, const T& guest) {
if (guest.is_constant) {
// TODO(benvanik): figure out how to do this without a temp.
// Since the constant is often 0x8... if we tried to use that as a
// displacement it would be sign extended and mess things up.
e.mov(e.eax, static_cast<uint32_t>(guest.constant()));
return e.rdx + e.rax;
} else {
// Clear the top 32 bits, as they are likely garbage.
// TODO(benvanik): find a way to avoid doing this.
e.mov(e.eax, guest.reg().cvt32());
return e.rdx + e.rax;
}
}
EMITTER(LOAD_I8, MATCH(I<OPCODE_LOAD, I8<>, I64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
auto addr = ComputeMemoryAddress(e, i.src1);
e.mov(i.dest, e.byte[addr]);
if (IsTracingData()) {
e.mov(e.r8b, i.dest);
e.lea(e.rdx, e.ptr[addr]);
e.CallNative(reinterpret_cast<void*>(TraceMemoryLoadI8));
}
}
};
EMITTER(LOAD_I16, MATCH(I<OPCODE_LOAD, I16<>, I64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
auto addr = ComputeMemoryAddress(e, i.src1);
e.mov(i.dest, e.word[addr]);
if (IsTracingData()) {
e.mov(e.r8w, i.dest);
e.lea(e.rdx, e.ptr[addr]);
e.CallNative(reinterpret_cast<void*>(TraceMemoryLoadI16));
}
}
};
EMITTER(LOAD_I32, MATCH(I<OPCODE_LOAD, I32<>, I64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
auto addr = ComputeMemoryAddress(e, i.src1);
e.mov(i.dest, e.dword[addr]);
if (IsTracingData()) {
e.mov(e.r8d, i.dest);
e.lea(e.rdx, e.ptr[addr]);
e.CallNative(reinterpret_cast<void*>(TraceMemoryLoadI32));
}
}
};
EMITTER(LOAD_I64, MATCH(I<OPCODE_LOAD, I64<>, I64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
auto addr = ComputeMemoryAddress(e, i.src1);
e.mov(i.dest, e.qword[addr]);
if (IsTracingData()) {
e.mov(e.r8, i.dest);
e.lea(e.rdx, e.ptr[addr]);
e.CallNative(reinterpret_cast<void*>(TraceMemoryLoadI64));
}
}
};
EMITTER(LOAD_F32, MATCH(I<OPCODE_LOAD, F32<>, I64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
auto addr = ComputeMemoryAddress(e, i.src1);
e.vmovss(i.dest, e.dword[addr]);
if (IsTracingData()) {
e.lea(e.r8, e.dword[addr]);
e.lea(e.rdx, e.ptr[addr]);
e.CallNative(reinterpret_cast<void*>(TraceMemoryLoadF32));
}
}
};
EMITTER(LOAD_F64, MATCH(I<OPCODE_LOAD, F64<>, I64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
auto addr = ComputeMemoryAddress(e, i.src1);
e.vmovsd(i.dest, e.qword[addr]);
if (IsTracingData()) {
e.lea(e.r8, e.qword[addr]);
e.lea(e.rdx, e.ptr[addr]);
e.CallNative(reinterpret_cast<void*>(TraceMemoryLoadF64));
}
}
};
EMITTER(LOAD_V128, MATCH(I<OPCODE_LOAD, V128<>, I64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
auto addr = ComputeMemoryAddress(e, i.src1);
// TODO(benvanik): we should try to stick to movaps if possible.
e.vmovups(i.dest, e.ptr[addr]);
if (IsTracingData()) {
e.lea(e.r8, e.ptr[addr]);
e.lea(e.rdx, e.ptr[addr]);
e.CallNative(reinterpret_cast<void*>(TraceMemoryLoadV128));
}
}
};
EMITTER_OPCODE_TABLE(
OPCODE_LOAD,
LOAD_I8,
LOAD_I16,
LOAD_I32,
LOAD_I64,
LOAD_F32,
LOAD_F64,
LOAD_V128);
// ============================================================================
// OPCODE_STORE
// ============================================================================
// Note: most *should* be aligned, but needs to be checked!
EMITTER(STORE_I8, MATCH(I<OPCODE_STORE, VoidOp, I64<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
auto addr = ComputeMemoryAddress(e, i.src1);
if (i.src2.is_constant) {
e.mov(e.byte[addr], i.src2.constant());
} else {
e.mov(e.byte[addr], i.src2);
}
if (IsTracingData()) {
addr = ComputeMemoryAddress(e, i.src1);
e.mov(e.r8b, e.byte[addr]);
e.lea(e.rdx, e.ptr[addr]);
e.CallNative(reinterpret_cast<void*>(TraceMemoryStoreI8));
}
}
};
EMITTER(STORE_I16, MATCH(I<OPCODE_STORE, VoidOp, I64<>, I16<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
auto addr = ComputeMemoryAddress(e, i.src1);
if (i.src2.is_constant) {
e.mov(e.word[addr], i.src2.constant());
} else {
e.mov(e.word[addr], i.src2);
}
if (IsTracingData()) {
addr = ComputeMemoryAddress(e, i.src1);
e.mov(e.r8w, e.word[addr]);
e.lea(e.rdx, e.ptr[addr]);
e.CallNative(reinterpret_cast<void*>(TraceMemoryStoreI16));
}
}
};
EMITTER(STORE_I32, MATCH(I<OPCODE_STORE, VoidOp, I64<>, I32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
auto addr = ComputeMemoryAddress(e, i.src1);
if (i.src2.is_constant) {
e.mov(e.dword[addr], i.src2.constant());
} else {
e.mov(e.dword[addr], i.src2);
}
if (IsTracingData()) {
addr = ComputeMemoryAddress(e, i.src1);
e.mov(e.r8d, e.dword[addr]);
e.lea(e.rdx, e.ptr[addr]);
e.CallNative(reinterpret_cast<void*>(TraceMemoryStoreI32));
}
}
};
EMITTER(STORE_I64, MATCH(I<OPCODE_STORE, VoidOp, I64<>, I64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
auto addr = ComputeMemoryAddress(e, i.src1);
if (i.src2.is_constant) {
e.MovMem64(addr, i.src2.constant());
} else {
e.mov(e.qword[addr], i.src2);
}
if (IsTracingData()) {
addr = ComputeMemoryAddress(e, i.src1);
e.mov(e.r8, e.qword[addr]);
e.lea(e.rdx, e.ptr[addr]);
e.CallNative(reinterpret_cast<void*>(TraceMemoryStoreI64));
}
}
};
EMITTER(STORE_F32, MATCH(I<OPCODE_STORE, VoidOp, I64<>, F32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
auto addr = ComputeMemoryAddress(e, i.src1);
if (i.src2.is_constant) {
e.mov(e.dword[addr], i.src2.value->constant.i32);
} else {
e.vmovss(e.dword[addr], i.src2);
}
if (IsTracingData()) {
addr = ComputeMemoryAddress(e, i.src1);
e.lea(e.r8, e.ptr[addr]);
e.lea(e.rdx, e.ptr[addr]);
e.CallNative(reinterpret_cast<void*>(TraceMemoryStoreF32));
}
}
};
EMITTER(STORE_F64, MATCH(I<OPCODE_STORE, VoidOp, I64<>, F64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
auto addr = ComputeMemoryAddress(e, i.src1);
if (i.src2.is_constant) {
e.MovMem64(addr, i.src2.value->constant.i64);
} else {
e.vmovsd(e.qword[addr], i.src2);
}
if (IsTracingData()) {
addr = ComputeMemoryAddress(e, i.src1);
e.lea(e.r8, e.ptr[addr]);
e.lea(e.rdx, e.ptr[addr]);
e.CallNative(reinterpret_cast<void*>(TraceMemoryStoreF64));
}
}
};
EMITTER(STORE_V128, MATCH(I<OPCODE_STORE, VoidOp, I64<>, V128<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
auto addr = ComputeMemoryAddress(e, i.src1);
if (i.src2.is_constant) {
e.LoadConstantXmm(e.xmm0, i.src2.constant());
e.vmovaps(e.ptr[addr], e.xmm0);
} else {
e.vmovaps(e.ptr[addr], i.src2);
}
if (IsTracingData()) {
addr = ComputeMemoryAddress(e, i.src1);
e.lea(e.r8, e.ptr[addr]);
e.lea(e.rdx, e.ptr[addr]);
e.CallNative(reinterpret_cast<void*>(TraceMemoryStoreV128));
}
}
};
EMITTER_OPCODE_TABLE(
OPCODE_STORE,
STORE_I8,
STORE_I16,
STORE_I32,
STORE_I64,
STORE_F32,
STORE_F64,
STORE_V128);
// ============================================================================
// OPCODE_PREFETCH
// ============================================================================
EMITTER(PREFETCH, MATCH(I<OPCODE_PREFETCH, VoidOp, I64<>, OffsetOp>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
// TODO(benvanik): prefetch addr -> length.
}
};
EMITTER_OPCODE_TABLE(
OPCODE_PREFETCH,
PREFETCH);
// ============================================================================
// OPCODE_MEMSET
// ============================================================================
EMITTER(MEMSET_I64_I8_I64, MATCH(I<OPCODE_MEMSET, VoidOp, I64<>, I8<>, I64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
assert_true(i.src2.is_constant);
assert_true(i.src3.is_constant);
assert_true(i.src2.constant() == 0);
e.vpxor(e.xmm0, e.xmm0);
auto addr = ComputeMemoryAddress(e, i.src1);
switch (i.src3.constant()) {
case 32:
e.vmovaps(e.ptr[addr + 0 * 16], e.xmm0);
e.vmovaps(e.ptr[addr + 1 * 16], e.xmm0);
break;
case 128:
e.vmovaps(e.ptr[addr + 0 * 16], e.xmm0);
e.vmovaps(e.ptr[addr + 1 * 16], e.xmm0);
e.vmovaps(e.ptr[addr + 2 * 16], e.xmm0);
e.vmovaps(e.ptr[addr + 3 * 16], e.xmm0);
e.vmovaps(e.ptr[addr + 4 * 16], e.xmm0);
e.vmovaps(e.ptr[addr + 5 * 16], e.xmm0);
e.vmovaps(e.ptr[addr + 6 * 16], e.xmm0);
e.vmovaps(e.ptr[addr + 7 * 16], e.xmm0);
break;
default:
assert_unhandled_case(i.src3.constant());
break;
}
if (IsTracingData()) {
addr = ComputeMemoryAddress(e, i.src1);
e.mov(e.r9, i.src3.constant());
e.mov(e.r8, i.src2.constant());
e.lea(e.rdx, e.ptr[addr]);
e.CallNative(reinterpret_cast<void*>(TraceMemset));
}
}
};
EMITTER_OPCODE_TABLE(
OPCODE_MEMSET,
MEMSET_I64_I8_I64);
// ============================================================================
// OPCODE_MAX
// ============================================================================
EMITTER(MAX_F32, MATCH(I<OPCODE_MAX, F32<>, F32<>, F32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitCommutativeBinaryXmmOp(e, i,
[](X64Emitter& e, Xmm dest, Xmm src1, Xmm src2) {
e.vmaxss(dest, src1, src2);
});
}
};
EMITTER(MAX_F64, MATCH(I<OPCODE_MAX, F64<>, F64<>, F64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitCommutativeBinaryXmmOp(e, i,
[](X64Emitter& e, Xmm dest, Xmm src1, Xmm src2) {
e.vmaxsd(dest, src1, src2);
});
}
};
EMITTER(MAX_V128, MATCH(I<OPCODE_MAX, V128<>, V128<>, V128<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitCommutativeBinaryXmmOp(e, i,
[](X64Emitter& e, Xmm dest, Xmm src1, Xmm src2) {
e.vmaxps(dest, src1, src2);
});
}
};
EMITTER_OPCODE_TABLE(
OPCODE_MAX,
MAX_F32,
MAX_F64,
MAX_V128);
// ============================================================================
// OPCODE_VECTOR_MAX
// ============================================================================
EMITTER(VECTOR_MAX, MATCH(I<OPCODE_VECTOR_MAX, V128<>, V128<>, V128<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitCommutativeBinaryXmmOp(e, i,
[&i](X64Emitter& e, Xmm dest, Xmm src1, Xmm src2) {
uint32_t part_type = i.instr->flags >> 8;
if (i.instr->flags & ARITHMETIC_UNSIGNED) {
switch (part_type) {
case INT8_TYPE:
e.vpmaxub(dest, src1, src2);
break;
case INT16_TYPE:
e.vpmaxuw(dest, src1, src2);
break;
case INT32_TYPE:
e.vpmaxud(dest, src1, src2);
break;
default:
assert_unhandled_case(part_type);
break;
}
} else {
switch (part_type) {
case INT8_TYPE:
e.vpmaxsb(dest, src1, src2);
break;
case INT16_TYPE:
e.vpmaxsw(dest, src1, src2);
break;
case INT32_TYPE:
e.vpmaxsd(dest, src1, src2);
break;
default:
assert_unhandled_case(part_type);
break;
}
}
});
}
};
EMITTER_OPCODE_TABLE(
OPCODE_VECTOR_MAX,
VECTOR_MAX);
// ============================================================================
// OPCODE_MIN
// ============================================================================
EMITTER(MIN_I8, MATCH(I<OPCODE_MIN, I8<>, I8<>, I8<>>)) {
static void Emit(X64Emitter & e, const EmitArgType& i) {
EmitCommutativeBinaryOp(e, i,
[](X64Emitter& e, const Reg8& dest_src, const Reg8& src) {
e.cmp(dest_src, src);
e.cmovg(dest_src.cvt32(), src.cvt32());
},
[](X64Emitter& e, const Reg8& dest_src, int32_t constant) {
e.mov(e.al, constant);
e.cmp(dest_src, e.al);
e.cmovg(dest_src.cvt32(), e.eax);
});
}
};
EMITTER(MIN_I16, MATCH(I<OPCODE_MIN, I16<>, I16<>, I16<>>)) {
static void Emit(X64Emitter & e, const EmitArgType& i) {
EmitCommutativeBinaryOp(e, i,
[](X64Emitter& e, const Reg16& dest_src, const Reg16& src) {
e.cmp(dest_src, src);
e.cmovg(dest_src.cvt32(), src.cvt32());
},
[](X64Emitter& e, const Reg16& dest_src, int32_t constant) {
e.mov(e.ax, constant);
e.cmp(dest_src, e.ax);
e.cmovg(dest_src.cvt32(), e.eax);
});
}
};
EMITTER(MIN_I32, MATCH(I<OPCODE_MIN, I32<>, I32<>, I32<>>)) {
static void Emit(X64Emitter & e, const EmitArgType& i) {
EmitCommutativeBinaryOp(e, i,
[](X64Emitter& e, const Reg32& dest_src, const Reg32& src) {
e.cmp(dest_src, src);
e.cmovg(dest_src, src);
},
[](X64Emitter& e, const Reg32& dest_src, int32_t constant) {
e.mov(e.eax, constant);
e.cmp(dest_src, e.eax);
e.cmovg(dest_src, e.eax);
});
}
};
EMITTER(MIN_I64, MATCH(I<OPCODE_MIN, I64<>, I64<>, I64<>>)) {
static void Emit(X64Emitter & e, const EmitArgType& i) {
EmitCommutativeBinaryOp(e, i,
[](X64Emitter& e, const Reg64& dest_src, const Reg64& src) {
e.cmp(dest_src, src);
e.cmovg(dest_src, src);
},
[](X64Emitter& e, const Reg64& dest_src, int64_t constant) {
e.mov(e.rax, constant);
e.cmp(dest_src, e.rax);
e.cmovg(dest_src, e.rax);
});
}
};
EMITTER(MIN_F32, MATCH(I<OPCODE_MIN, F32<>, F32<>, F32<>>)) {
static void Emit(X64Emitter & e, const EmitArgType& i) {
EmitCommutativeBinaryXmmOp(e, i,
[](X64Emitter& e, Xmm dest, Xmm src1, Xmm src2) {
e.vminss(dest, src1, src2);
});
}
};
EMITTER(MIN_F64, MATCH(I<OPCODE_MIN, F64<>, F64<>, F64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitCommutativeBinaryXmmOp(e, i,
[](X64Emitter& e, Xmm dest, Xmm src1, Xmm src2) {
e.vminsd(dest, src1, src2);
});
}
};
EMITTER(MIN_V128, MATCH(I<OPCODE_MIN, V128<>, V128<>, V128<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitCommutativeBinaryXmmOp(e, i,
[](X64Emitter& e, Xmm dest, Xmm src1, Xmm src2) {
e.vminps(dest, src1, src2);
});
}
};
EMITTER_OPCODE_TABLE(
OPCODE_MIN,
MIN_I8,
MIN_I16,
MIN_I32,
MIN_I64,
MIN_F32,
MIN_F64,
MIN_V128);
// ============================================================================
// OPCODE_VECTOR_MIN
// ============================================================================
EMITTER(VECTOR_MIN, MATCH(I<OPCODE_VECTOR_MIN, V128<>, V128<>, V128<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitCommutativeBinaryXmmOp(e, i,
[&i](X64Emitter& e, Xmm dest, Xmm src1, Xmm src2) {
uint32_t part_type = i.instr->flags >> 8;
if (i.instr->flags & ARITHMETIC_UNSIGNED) {
switch (part_type) {
case INT8_TYPE:
e.vpminub(dest, src1, src2);
break;
case INT16_TYPE:
e.vpminuw(dest, src1, src2);
break;
case INT32_TYPE:
e.vpminud(dest, src1, src2);
break;
default:
assert_unhandled_case(part_type);
break;
}
} else {
switch (part_type) {
case INT8_TYPE:
e.vpminsb(dest, src1, src2);
break;
case INT16_TYPE:
e.vpminsw(dest, src1, src2);
break;
case INT32_TYPE:
e.vpminsd(dest, src1, src2);
break;
default:
assert_unhandled_case(part_type);
break;
}
}
});
}
};
EMITTER_OPCODE_TABLE(
OPCODE_VECTOR_MIN,
VECTOR_MIN);
// ============================================================================
// OPCODE_SELECT
// ============================================================================
// dest = src1 ? src2 : src3
// TODO(benvanik): match compare + select sequences, as often it's something
// like SELECT(VECTOR_COMPARE_SGE(a, b), a, b)
EMITTER(SELECT_I8, MATCH(I<OPCODE_SELECT, I8<>, I8<>, I8<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
Reg8 src2;
if (i.src2.is_constant) {
src2 = e.al;
e.mov(src2, i.src2.constant());
} else {
src2 = i.src2;
}
e.test(i.src1, i.src1);
e.cmovnz(i.dest.reg().cvt32(), src2.cvt32());
e.cmovz(i.dest.reg().cvt32(), i.src3.reg().cvt32());
}
};
EMITTER(SELECT_I16, MATCH(I<OPCODE_SELECT, I16<>, I8<>, I16<>, I16<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
Reg16 src2;
if (i.src2.is_constant) {
src2 = e.ax;
e.mov(src2, i.src2.constant());
} else {
src2 = i.src2;
}
e.test(i.src1, i.src1);
e.cmovnz(i.dest.reg().cvt32(), src2.cvt32());
e.cmovz(i.dest.reg().cvt32(), i.src3.reg().cvt32());
}
};
EMITTER(SELECT_I32, MATCH(I<OPCODE_SELECT, I32<>, I8<>, I32<>, I32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
Reg32 src2;
if (i.src2.is_constant) {
src2 = e.eax;
e.mov(src2, i.src2.constant());
} else {
src2 = i.src2;
}
e.test(i.src1, i.src1);
e.cmovnz(i.dest, src2);
e.cmovz(i.dest, i.src3);
}
};
EMITTER(SELECT_I64, MATCH(I<OPCODE_SELECT, I64<>, I8<>, I64<>, I64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
Reg64 src2;
if (i.src2.is_constant) {
src2 = e.rax;
e.mov(src2, i.src2.constant());
} else {
src2 = i.src2;
}
e.test(i.src1, i.src1);
e.cmovnz(i.dest, src2);
e.cmovz(i.dest, i.src3);
}
};
EMITTER(SELECT_F32, MATCH(I<OPCODE_SELECT, F32<>, I8<>, F32<>, F32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
// TODO(benvanik): find a shorter sequence.
// xmm0 = src1 != 0 ? 1111... : 0000....
e.movzx(e.eax, i.src1);
e.vmovd(e.xmm1, e.eax);
e.vxorps(e.xmm0, e.xmm0);
e.vcmpneqss(e.xmm0, e.xmm1);
e.vpand(e.xmm1, e.xmm0, i.src2);
e.vpandn(i.dest, e.xmm0, i.src3);
e.vpor(i.dest, e.xmm1);
}
};
EMITTER(SELECT_F64, MATCH(I<OPCODE_SELECT, F64<>, I8<>, F64<>, F64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
// xmm0 = src1 != 0 ? 1111... : 0000....
e.movzx(e.eax, i.src1);
e.vmovd(e.xmm1, e.eax);
e.vxorpd(e.xmm0, e.xmm0);
e.vcmpneqsd(e.xmm0, e.xmm1);
e.vpand(e.xmm1, e.xmm0, i.src2);
e.vpandn(i.dest, e.xmm0, i.src3);
e.vpor(i.dest, e.xmm1);
}
};
EMITTER(SELECT_V128_I8, MATCH(I<OPCODE_SELECT, V128<>, I8<>, V128<>, V128<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
// TODO(benvanik): find a shorter sequence.
// xmm0 = src1 != 0 ? 1111... : 0000....
e.movzx(e.eax, i.src1);
e.vmovd(e.xmm1, e.eax);
e.vpbroadcastd(e.xmm1, e.xmm1);
e.vxorps(e.xmm0, e.xmm0);
e.vcmpneqps(e.xmm0, e.xmm1);
e.vpand(e.xmm1, e.xmm0, i.src2);
e.vpandn(i.dest, e.xmm0, i.src3);
e.vpor(i.dest, e.xmm1);
}
};
EMITTER(SELECT_V128_V128, MATCH(I<OPCODE_SELECT, V128<>, V128<>, V128<>, V128<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
// TODO(benvanik): could be made shorter when consts involved.
if (i.src2.is_constant) {
if (i.src2.value->IsConstantZero()) {
e.vpxor(e.xmm1, e.xmm1);
} else {
assert_always();
}
} else {
e.vpandn(e.xmm1, i.src1, i.src2);
}
if (i.src3.is_constant) {
if (i.src3.value->IsConstantZero()) {
e.vpxor(i.dest, i.dest);
} else {
assert_always();
}
} else {
e.vpand(i.dest, i.src1, i.src3);
}
e.vpor(i.dest, e.xmm1);
}
};
EMITTER_OPCODE_TABLE(
OPCODE_SELECT,
SELECT_I8,
SELECT_I16,
SELECT_I32,
SELECT_I64,
SELECT_F32,
SELECT_F64,
SELECT_V128_I8,
SELECT_V128_V128);
// ============================================================================
// OPCODE_IS_TRUE
// ============================================================================
EMITTER(IS_TRUE_I8, MATCH(I<OPCODE_IS_TRUE, I8<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.test(i.src1, i.src1);
e.setnz(i.dest);
}
};
EMITTER(IS_TRUE_I16, MATCH(I<OPCODE_IS_TRUE, I8<>, I16<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.test(i.src1, i.src1);
e.setnz(i.dest);
}
};
EMITTER(IS_TRUE_I32, MATCH(I<OPCODE_IS_TRUE, I8<>, I32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.test(i.src1, i.src1);
e.setnz(i.dest);
}
};
EMITTER(IS_TRUE_I64, MATCH(I<OPCODE_IS_TRUE, I8<>, I64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.test(i.src1, i.src1);
e.setnz(i.dest);
}
};
EMITTER(IS_TRUE_F32, MATCH(I<OPCODE_IS_TRUE, I8<>, F32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.vptest(i.src1, i.src1);
e.setnz(i.dest);
}
};
EMITTER(IS_TRUE_F64, MATCH(I<OPCODE_IS_TRUE, I8<>, F64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.vptest(i.src1, i.src1);
e.setnz(i.dest);
}
};
EMITTER(IS_TRUE_V128, MATCH(I<OPCODE_IS_TRUE, I8<>, V128<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.vptest(i.src1, i.src1);
e.setnz(i.dest);
}
};
EMITTER_OPCODE_TABLE(
OPCODE_IS_TRUE,
IS_TRUE_I8,
IS_TRUE_I16,
IS_TRUE_I32,
IS_TRUE_I64,
IS_TRUE_F32,
IS_TRUE_F64,
IS_TRUE_V128);
// ============================================================================
// OPCODE_IS_FALSE
// ============================================================================
EMITTER(IS_FALSE_I8, MATCH(I<OPCODE_IS_FALSE, I8<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.test(i.src1, i.src1);
e.setz(i.dest);
}
};
EMITTER(IS_FALSE_I16, MATCH(I<OPCODE_IS_FALSE, I8<>, I16<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.test(i.src1, i.src1);
e.setz(i.dest);
}
};
EMITTER(IS_FALSE_I32, MATCH(I<OPCODE_IS_FALSE, I8<>, I32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.test(i.src1, i.src1);
e.setz(i.dest);
}
};
EMITTER(IS_FALSE_I64, MATCH(I<OPCODE_IS_FALSE, I8<>, I64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.test(i.src1, i.src1);
e.setz(i.dest);
}
};
EMITTER(IS_FALSE_F32, MATCH(I<OPCODE_IS_FALSE, I8<>, F32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.vptest(i.src1, i.src1);
e.setz(i.dest);
}
};
EMITTER(IS_FALSE_F64, MATCH(I<OPCODE_IS_FALSE, I8<>, F64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.vptest(i.src1, i.src1);
e.setz(i.dest);
}
};
EMITTER(IS_FALSE_V128, MATCH(I<OPCODE_IS_FALSE, I8<>, V128<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.vptest(i.src1, i.src1);
e.setz(i.dest);
}
};
EMITTER_OPCODE_TABLE(
OPCODE_IS_FALSE,
IS_FALSE_I8,
IS_FALSE_I16,
IS_FALSE_I32,
IS_FALSE_I64,
IS_FALSE_F32,
IS_FALSE_F64,
IS_FALSE_V128);
// ============================================================================
// OPCODE_COMPARE_EQ
// ============================================================================
EMITTER(COMPARE_EQ_I8, MATCH(I<OPCODE_COMPARE_EQ, I8<>, I8<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitCommutativeCompareOp(
e, i,
[](X64Emitter& e, const Reg8& src1, const Reg8& src2) { e.cmp(src1, src2); },
[](X64Emitter& e, const Reg8& src1, int32_t constant) { e.cmp(src1, constant); });
e.sete(i.dest);
}
};
EMITTER(COMPARE_EQ_I16, MATCH(I<OPCODE_COMPARE_EQ, I8<>, I16<>, I16<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitCommutativeCompareOp(
e, i,
[](X64Emitter& e, const Reg16& src1, const Reg16& src2) { e.cmp(src1, src2); },
[](X64Emitter& e, const Reg16& src1, int32_t constant) { e.cmp(src1, constant); });
e.sete(i.dest);
}
};
EMITTER(COMPARE_EQ_I32, MATCH(I<OPCODE_COMPARE_EQ, I8<>, I32<>, I32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitCommutativeCompareOp(
e, i,
[](X64Emitter& e, const Reg32& src1, const Reg32& src2) { e.cmp(src1, src2); },
[](X64Emitter& e, const Reg32& src1, int32_t constant) { e.cmp(src1, constant); });
e.sete(i.dest);
}
};
EMITTER(COMPARE_EQ_I64, MATCH(I<OPCODE_COMPARE_EQ, I8<>, I64<>, I64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitCommutativeCompareOp(
e, i,
[](X64Emitter& e, const Reg64& src1, const Reg64& src2) { e.cmp(src1, src2); },
[](X64Emitter& e, const Reg64& src1, int32_t constant) { e.cmp(src1, constant); });
e.sete(i.dest);
}
};
EMITTER(COMPARE_EQ_F32, MATCH(I<OPCODE_COMPARE_EQ, I8<>, F32<>, F32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.vcomiss(i.src1, i.src2);
e.sete(i.dest);
}
};
EMITTER(COMPARE_EQ_F64, MATCH(I<OPCODE_COMPARE_EQ, I8<>, F64<>, F64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.vcomisd(i.src1, i.src2);
e.sete(i.dest);
}
};
EMITTER_OPCODE_TABLE(
OPCODE_COMPARE_EQ,
COMPARE_EQ_I8,
COMPARE_EQ_I16,
COMPARE_EQ_I32,
COMPARE_EQ_I64,
COMPARE_EQ_F32,
COMPARE_EQ_F64);
// ============================================================================
// OPCODE_COMPARE_NE
// ============================================================================
EMITTER(COMPARE_NE_I8, MATCH(I<OPCODE_COMPARE_NE, I8<>, I8<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitCommutativeCompareOp(
e, i,
[](X64Emitter& e, const Reg8& src1, const Reg8& src2) { e.cmp(src1, src2); },
[](X64Emitter& e, const Reg8& src1, int32_t constant) { e.cmp(src1, constant); });
e.setne(i.dest);
}
};
EMITTER(COMPARE_NE_I16, MATCH(I<OPCODE_COMPARE_NE, I8<>, I16<>, I16<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitCommutativeCompareOp(
e, i,
[](X64Emitter& e, const Reg16& src1, const Reg16& src2) { e.cmp(src1, src2); },
[](X64Emitter& e, const Reg16& src1, int32_t constant) { e.cmp(src1, constant); });
e.setne(i.dest);
}
};
EMITTER(COMPARE_NE_I32, MATCH(I<OPCODE_COMPARE_NE, I8<>, I32<>, I32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitCommutativeCompareOp(
e, i,
[](X64Emitter& e, const Reg32& src1, const Reg32& src2) { e.cmp(src1, src2); },
[](X64Emitter& e, const Reg32& src1, int32_t constant) { e.cmp(src1, constant); });
e.setne(i.dest);
}
};
EMITTER(COMPARE_NE_I64, MATCH(I<OPCODE_COMPARE_NE, I8<>, I64<>, I64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitCommutativeCompareOp(
e, i,
[](X64Emitter& e, const Reg64& src1, const Reg64& src2) { e.cmp(src1, src2); },
[](X64Emitter& e, const Reg64& src1, int32_t constant) { e.cmp(src1, constant); });
e.setne(i.dest);
}
};
EMITTER(COMPARE_NE_F32, MATCH(I<OPCODE_COMPARE_NE, I8<>, F32<>, F32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.vcomiss(i.src1, i.src2);
e.setne(i.dest);
}
};
EMITTER(COMPARE_NE_F64, MATCH(I<OPCODE_COMPARE_NE, I8<>, F64<>, F64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.vcomisd(i.src1, i.src2);
e.setne(i.dest);
}
};
EMITTER_OPCODE_TABLE(
OPCODE_COMPARE_NE,
COMPARE_NE_I8,
COMPARE_NE_I16,
COMPARE_NE_I32,
COMPARE_NE_I64,
COMPARE_NE_F32,
COMPARE_NE_F64);
// ============================================================================
// OPCODE_COMPARE_*
// ============================================================================
#define EMITTER_ASSOCIATIVE_COMPARE_INT(op, instr, inverse_instr, type, reg_type) \
EMITTER(COMPARE_##op##_##type, MATCH(I<OPCODE_COMPARE_##op, I8<>, type<>, type<>>)) { \
static void Emit(X64Emitter& e, const EmitArgType& i) { \
EmitAssociativeCompareOp( \
e, i, \
[](X64Emitter& e, const Reg8& dest, const reg_type& src1, const reg_type& src2, bool inverse) { \
e.cmp(src1, src2); \
if (!inverse) { e.instr(dest); } else { e.inverse_instr(dest); } \
}, \
[](X64Emitter& e, const Reg8& dest, const reg_type& src1, int32_t constant, bool inverse) { \
e.cmp(src1, constant); \
if (!inverse) { e.instr(dest); } else { e.inverse_instr(dest); } \
}); \
} \
};
#define EMITTER_ASSOCIATIVE_COMPARE_XX(op, instr, inverse_instr) \
EMITTER_ASSOCIATIVE_COMPARE_INT(op, instr, inverse_instr, I8, Reg8); \
EMITTER_ASSOCIATIVE_COMPARE_INT(op, instr, inverse_instr, I16, Reg16); \
EMITTER_ASSOCIATIVE_COMPARE_INT(op, instr, inverse_instr, I32, Reg32); \
EMITTER_ASSOCIATIVE_COMPARE_INT(op, instr, inverse_instr, I64, Reg64); \
EMITTER_OPCODE_TABLE( \
OPCODE_COMPARE_##op, \
COMPARE_##op##_I8, \
COMPARE_##op##_I16, \
COMPARE_##op##_I32, \
COMPARE_##op##_I64);
EMITTER_ASSOCIATIVE_COMPARE_XX(SLT, setl, setge);
EMITTER_ASSOCIATIVE_COMPARE_XX(SLE, setle, setg);
EMITTER_ASSOCIATIVE_COMPARE_XX(SGT, setg, setle);
EMITTER_ASSOCIATIVE_COMPARE_XX(SGE, setge, setl);
EMITTER_ASSOCIATIVE_COMPARE_XX(ULT, setb, setae);
EMITTER_ASSOCIATIVE_COMPARE_XX(ULE, setbe, seta);
EMITTER_ASSOCIATIVE_COMPARE_XX(UGT, seta, setbe);
EMITTER_ASSOCIATIVE_COMPARE_XX(UGE, setae, setb);
// http://x86.renejeschke.de/html/file_module_x86_id_288.html
#define EMITTER_ASSOCIATIVE_COMPARE_FLT_XX(op, instr) \
EMITTER(COMPARE_##op##_F32, MATCH(I<OPCODE_COMPARE_##op, I8<>, F32<>, F32<>>)) { \
static void Emit(X64Emitter& e, const EmitArgType& i) { \
e.vcomiss(i.src1, i.src2); \
e.instr(i.dest); \
} \
}; \
EMITTER(COMPARE_##op##_F64, MATCH(I<OPCODE_COMPARE_##op, I8<>, F64<>, F64<>>)) { \
static void Emit(X64Emitter& e, const EmitArgType& i) { \
if (i.src1.is_constant) { \
e.LoadConstantXmm(e.xmm0, i.src1.constant()); \
e.vcomisd(e.xmm0, i.src2); \
} else if (i.src2.is_constant) { \
e.LoadConstantXmm(e.xmm0, i.src2.constant()); \
e.vcomisd(i.src1, e.xmm0); \
} else { \
e.vcomisd(i.src1, i.src2); \
} \
e.instr(i.dest); \
} \
}; \
EMITTER_OPCODE_TABLE( \
OPCODE_COMPARE_##op##_FLT, \
COMPARE_##op##_F32, \
COMPARE_##op##_F64);
EMITTER_ASSOCIATIVE_COMPARE_FLT_XX(SLT, setb);
EMITTER_ASSOCIATIVE_COMPARE_FLT_XX(SLE, setbe);
EMITTER_ASSOCIATIVE_COMPARE_FLT_XX(SGT, seta);
EMITTER_ASSOCIATIVE_COMPARE_FLT_XX(SGE, setae);
EMITTER_ASSOCIATIVE_COMPARE_FLT_XX(ULT, setb);
EMITTER_ASSOCIATIVE_COMPARE_FLT_XX(ULE, setbe);
EMITTER_ASSOCIATIVE_COMPARE_FLT_XX(UGT, seta);
EMITTER_ASSOCIATIVE_COMPARE_FLT_XX(UGE, setae);
// ============================================================================
// OPCODE_DID_CARRY
// ============================================================================
// TODO(benvanik): salc/setalc
// https://code.google.com/p/corkami/wiki/x86oddities
EMITTER(DID_CARRY_I8, MATCH(I<OPCODE_DID_CARRY, I8<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
assert_true(!i.src1.is_constant);
e.LoadEflags();
e.setc(i.dest);
}
};
EMITTER(DID_CARRY_I16, MATCH(I<OPCODE_DID_CARRY, I8<>, I16<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
assert_true(!i.src1.is_constant);
e.LoadEflags();
e.setc(i.dest);
}
};
EMITTER(DID_CARRY_I32, MATCH(I<OPCODE_DID_CARRY, I8<>, I32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
assert_true(!i.src1.is_constant);
e.LoadEflags();
e.setc(i.dest);
}
};
EMITTER(DID_CARRY_I64, MATCH(I<OPCODE_DID_CARRY, I8<>, I64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
assert_true(!i.src1.is_constant);
e.LoadEflags();
e.setc(i.dest);
}
};
EMITTER_OPCODE_TABLE(
OPCODE_DID_CARRY,
DID_CARRY_I8,
DID_CARRY_I16,
DID_CARRY_I32,
DID_CARRY_I64);
// ============================================================================
// OPCODE_DID_OVERFLOW
// ============================================================================
EMITTER(DID_OVERFLOW, MATCH(I<OPCODE_DID_OVERFLOW, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.LoadEflags();
e.seto(i.dest);
}
};
EMITTER_OPCODE_TABLE(
OPCODE_DID_OVERFLOW,
DID_OVERFLOW);
// ============================================================================
// OPCODE_DID_SATURATE
// ============================================================================
EMITTER(DID_SATURATE, MATCH(I<OPCODE_DID_SATURATE, I8<>, V128<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
// TODO(benvanik): implement saturation check (VECTOR_ADD, etc).
e.xor(i.dest, i.dest);
}
};
EMITTER_OPCODE_TABLE(OPCODE_DID_SATURATE,
DID_SATURATE);
// ============================================================================
// OPCODE_VECTOR_COMPARE_EQ
// ============================================================================
EMITTER(VECTOR_COMPARE_EQ_V128, MATCH(I<OPCODE_VECTOR_COMPARE_EQ, V128<>, V128<>, V128<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitCommutativeBinaryXmmOp(e, i,
[&i](X64Emitter& e, Xmm dest, Xmm src1, Xmm src2) {
switch (i.instr->flags) {
case INT8_TYPE:
e.vpcmpeqb(dest, src1, src2);
break;
case INT16_TYPE:
e.vpcmpeqw(dest, src1, src2);
break;
case INT32_TYPE:
e.vpcmpeqd(dest, src1, src2);
break;
case FLOAT32_TYPE:
e.vcmpeqps(dest, src1, src2);
break;
}
});
}
};
EMITTER_OPCODE_TABLE(
OPCODE_VECTOR_COMPARE_EQ,
VECTOR_COMPARE_EQ_V128);
// ============================================================================
// OPCODE_VECTOR_COMPARE_SGT
// ============================================================================
EMITTER(VECTOR_COMPARE_SGT_V128, MATCH(I<OPCODE_VECTOR_COMPARE_SGT, V128<>, V128<>, V128<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitAssociativeBinaryXmmOp(e, i,
[&i](X64Emitter& e, Xmm dest, Xmm src1, Xmm src2) {
switch (i.instr->flags) {
case INT8_TYPE:
e.vpcmpgtb(dest, src1, src2);
break;
case INT16_TYPE:
e.vpcmpgtw(dest, src1, src2);
break;
case INT32_TYPE:
e.vpcmpgtd(dest, src1, src2);
break;
case FLOAT32_TYPE:
e.vcmpgtps(dest, src1, src2);
break;
}
});
}
};
EMITTER_OPCODE_TABLE(
OPCODE_VECTOR_COMPARE_SGT,
VECTOR_COMPARE_SGT_V128);
// ============================================================================
// OPCODE_VECTOR_COMPARE_SGE
// ============================================================================
EMITTER(VECTOR_COMPARE_SGE_V128, MATCH(I<OPCODE_VECTOR_COMPARE_SGE, V128<>, V128<>, V128<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitAssociativeBinaryXmmOp(e, i,
[&i](X64Emitter& e, Xmm dest, Xmm src1, Xmm src2) {
switch (i.instr->flags) {
case INT8_TYPE:
e.vpcmpeqb(e.xmm0, src1, src2);
e.vpcmpgtb(dest, src1, src2);
e.vpor(dest, e.xmm0);
break;
case INT16_TYPE:
e.vpcmpeqw(e.xmm0, src1, src2);
e.vpcmpgtw(dest, src1, src2);
e.vpor(dest, e.xmm0);
break;
case INT32_TYPE:
e.vpcmpeqd(e.xmm0, src1, src2);
e.vpcmpgtd(dest, src1, src2);
e.vpor(dest, e.xmm0);
break;
case FLOAT32_TYPE:
e.vcmpgeps(dest, src1, src2);
break;
}
});
}
};
EMITTER_OPCODE_TABLE(
OPCODE_VECTOR_COMPARE_SGE,
VECTOR_COMPARE_SGE_V128);
// ============================================================================
// OPCODE_VECTOR_COMPARE_UGT
// ============================================================================
EMITTER(VECTOR_COMPARE_UGT_V128, MATCH(I<OPCODE_VECTOR_COMPARE_UGT, V128<>, V128<>, V128<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
Xbyak::Address sign_addr = e.ptr[e.rax]; // dummy
switch (i.instr->flags) {
case INT8_TYPE:
sign_addr = e.GetXmmConstPtr(XMMSignMaskI8);
break;
case INT16_TYPE:
sign_addr = e.GetXmmConstPtr(XMMSignMaskI16);
break;
case INT32_TYPE:
sign_addr = e.GetXmmConstPtr(XMMSignMaskI32);
break;
case FLOAT32_TYPE:
sign_addr = e.GetXmmConstPtr(XMMSignMaskF32);
break;
}
if (i.src1.is_constant) {
// TODO(benvanik): make this constant.
e.LoadConstantXmm(e.xmm0, i.src1.constant());
e.vpxor(e.xmm0, sign_addr);
} else {
e.vpxor(e.xmm0, i.src1, sign_addr);
}
if (i.src2.is_constant) {
// TODO(benvanik): make this constant.
e.LoadConstantXmm(e.xmm1, i.src1.constant());
e.vpxor(e.xmm1, sign_addr);
} else {
e.vpxor(e.xmm1, i.src2, sign_addr);
}
switch (i.instr->flags) {
case INT8_TYPE:
e.vpcmpgtb(i.dest, e.xmm0, e.xmm1);
break;
case INT16_TYPE:
e.vpcmpgtw(i.dest, e.xmm0, e.xmm1);
break;
case INT32_TYPE:
e.vpcmpgtd(i.dest, e.xmm0, e.xmm1);
break;
case FLOAT32_TYPE:
e.vcmpgtps(i.dest, e.xmm0, e.xmm1);
break;
}
}
};
EMITTER_OPCODE_TABLE(
OPCODE_VECTOR_COMPARE_UGT,
VECTOR_COMPARE_UGT_V128);
// ============================================================================
// OPCODE_VECTOR_COMPARE_UGE
// ============================================================================
EMITTER(VECTOR_COMPARE_UGE_V128, MATCH(I<OPCODE_VECTOR_COMPARE_UGE, V128<>, V128<>, V128<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
Xbyak::Address sign_addr = e.ptr[e.rax]; // dummy
switch (i.instr->flags) {
case INT8_TYPE:
sign_addr = e.GetXmmConstPtr(XMMSignMaskI8);
break;
case INT16_TYPE:
sign_addr = e.GetXmmConstPtr(XMMSignMaskI16);
break;
case INT32_TYPE:
sign_addr = e.GetXmmConstPtr(XMMSignMaskI32);
break;
case FLOAT32_TYPE:
sign_addr = e.GetXmmConstPtr(XMMSignMaskF32);
break;
}
if (i.src1.is_constant) {
// TODO(benvanik): make this constant.
e.LoadConstantXmm(e.xmm0, i.src1.constant());
e.vpxor(e.xmm0, sign_addr);
} else {
e.vpxor(e.xmm0, i.src1, sign_addr);
}
if (i.src2.is_constant) {
// TODO(benvanik): make this constant.
e.LoadConstantXmm(e.xmm1, i.src1.constant());
e.vpxor(e.xmm1, sign_addr);
} else {
e.vpxor(e.xmm1, i.src2, sign_addr);
}
switch (i.instr->flags) {
case INT8_TYPE:
e.vpcmpeqb(e.xmm2, e.xmm0, e.xmm1);
e.vpcmpgtb(i.dest, e.xmm0, e.xmm1);
e.vpor(i.dest, e.xmm2);
break;
case INT16_TYPE:
e.vpcmpeqw(e.xmm2, e.xmm0, e.xmm1);
e.vpcmpgtw(i.dest, e.xmm0, e.xmm1);
e.vpor(i.dest, e.xmm2);
break;
case INT32_TYPE:
e.vpcmpeqd(e.xmm2, e.xmm0, e.xmm1);
e.vpcmpgtd(i.dest, e.xmm0, e.xmm1);
e.vpor(i.dest, e.xmm2);
break;
case FLOAT32_TYPE:
e.vcmpgeps(i.dest, e.xmm0, e.xmm1);
break;
}
}
};
EMITTER_OPCODE_TABLE(
OPCODE_VECTOR_COMPARE_UGE,
VECTOR_COMPARE_UGE_V128);
// ============================================================================
// OPCODE_ADD
// ============================================================================
// TODO(benvanik): put dest/src1|2 together.
template <typename SEQ, typename REG, typename ARGS>
void EmitAddXX(X64Emitter& e, const ARGS& i) {
SEQ::EmitCommutativeBinaryOp(
e, i,
[](X64Emitter& e, const REG& dest_src, const REG& src) { e.add(dest_src, src); },
[](X64Emitter& e, const REG& dest_src, int32_t constant) { e.add(dest_src, constant); });
if (i.instr->flags & ARITHMETIC_SET_CARRY) {
// CF is set if carried.
e.StoreEflags();
}
}
EMITTER(ADD_I8, MATCH(I<OPCODE_ADD, I8<>, I8<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitAddXX<ADD_I8, Reg8>(e, i);
}
};
EMITTER(ADD_I16, MATCH(I<OPCODE_ADD, I16<>, I16<>, I16<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitAddXX<ADD_I16, Reg16>(e, i);
}
};
EMITTER(ADD_I32, MATCH(I<OPCODE_ADD, I32<>, I32<>, I32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitAddXX<ADD_I32, Reg32>(e, i);
}
};
EMITTER(ADD_I64, MATCH(I<OPCODE_ADD, I64<>, I64<>, I64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitAddXX<ADD_I64, Reg64>(e, i);
}
};
EMITTER(ADD_F32, MATCH(I<OPCODE_ADD, F32<>, F32<>, F32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitCommutativeBinaryXmmOp(e, i,
[](X64Emitter& e, Xmm dest, Xmm src1, Xmm src2) {
e.vaddss(dest, src1, src2);
});
}
};
EMITTER(ADD_F64, MATCH(I<OPCODE_ADD, F64<>, F64<>, F64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitCommutativeBinaryXmmOp(e, i,
[](X64Emitter& e, Xmm dest, Xmm src1, Xmm src2) {
e.vaddsd(dest, src1, src2);
});
}
};
EMITTER_OPCODE_TABLE(
OPCODE_ADD,
ADD_I8,
ADD_I16,
ADD_I32,
ADD_I64,
ADD_F32,
ADD_F64);
// ============================================================================
// OPCODE_ADD_CARRY
// ============================================================================
// TODO(benvanik): put dest/src1|2 together.
template <typename SEQ, typename REG, typename ARGS>
void EmitAddCarryXX(X64Emitter& e, const ARGS& i) {
// TODO(benvanik): faster setting? we could probably do some fun math tricks
// here to get the carry flag set.
if (i.src3.is_constant) {
if (i.src3.constant()) {
e.stc();
} else {
e.clc();
}
} else {
if (i.src3.reg().getIdx() <= 4) {
// Can move from A/B/C/DX to AH.
e.mov(e.ah, i.src3.reg().cvt8());
} else {
e.mov(e.al, i.src3);
e.mov(e.ah, e.al);
}
e.sahf();
}
SEQ::EmitCommutativeBinaryOp(
e, i, [](X64Emitter& e, const REG& dest_src, const REG& src) {
e.adc(dest_src, src);
}, [](X64Emitter& e, const REG& dest_src, int32_t constant) {
e.adc(dest_src, constant);
});
if (i.instr->flags & ARITHMETIC_SET_CARRY) {
// CF is set if carried.
e.StoreEflags();
}
}
EMITTER(ADD_CARRY_I8, MATCH(I<OPCODE_ADD_CARRY, I8<>, I8<>, I8<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitAddCarryXX<ADD_CARRY_I8, Reg8>(e, i);
}
};
EMITTER(ADD_CARRY_I16, MATCH(I<OPCODE_ADD_CARRY, I16<>, I16<>, I16<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitAddCarryXX<ADD_CARRY_I16, Reg16>(e, i);
}
};
EMITTER(ADD_CARRY_I32, MATCH(I<OPCODE_ADD_CARRY, I32<>, I32<>, I32<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitAddCarryXX<ADD_CARRY_I32, Reg32>(e, i);
}
};
EMITTER(ADD_CARRY_I64, MATCH(I<OPCODE_ADD_CARRY, I64<>, I64<>, I64<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitAddCarryXX<ADD_CARRY_I64, Reg64>(e, i);
}
};
EMITTER_OPCODE_TABLE(
OPCODE_ADD_CARRY,
ADD_CARRY_I8,
ADD_CARRY_I16,
ADD_CARRY_I32,
ADD_CARRY_I64);
// ============================================================================
// OPCODE_VECTOR_ADD
// ============================================================================
EMITTER(VECTOR_ADD, MATCH(I<OPCODE_VECTOR_ADD, V128<>, V128<>, V128<>>)){
static __m128i EmulateVectorAddUnsignedSatI32(void*, __m128i src1,
__m128i src2){
alignas(16) uint32_t a[4];
alignas(16) uint32_t b[4];
_mm_store_si128(reinterpret_cast<__m128i*>(a), src1);
_mm_store_si128(reinterpret_cast<__m128i*>(b), src2);
for (size_t i = 0; i < 4; ++i) {
uint64_t v = (uint64_t)a[i] + (uint64_t)b[i];
if (v > 0xFFFFFFFF) {
a[i] = 0xFFFFFFFF;
} else {
a[i] = (uint32_t)v;
}
}
return _mm_load_si128(reinterpret_cast<__m128i*>(a));
}
static __m128i EmulateVectorAddSignedSatI32(void*, __m128i src1,
__m128i src2){
alignas(16) int32_t a[4];
alignas(16) int32_t b[4];
_mm_store_si128(reinterpret_cast<__m128i*>(a), src1);
_mm_store_si128(reinterpret_cast<__m128i*>(b), src2);
for (size_t i = 0; i < 4; ++i) {
int64_t v = (int64_t)a[i] + (int64_t)b[i];
if (v > 0x7FFFFFFF) {
a[i] = 0x7FFFFFFF;
} else if (v < -0x80000000ll) {
a[i] = 0x80000000;
} else {
a[i] = (uint32_t)v;
}
}
return _mm_load_si128(reinterpret_cast<__m128i*>(a));
}
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitCommutativeBinaryXmmOp(e, i,
[&i](X64Emitter& e, const Xmm& dest, const Xmm& src1, const Xmm& src2) {
const TypeName part_type = static_cast<TypeName>(i.instr->flags & 0xFF);
const uint32_t arithmetic_flags = i.instr->flags >> 8;
bool is_unsigned = !!(arithmetic_flags & ARITHMETIC_UNSIGNED);
bool saturate = !!(arithmetic_flags & ARITHMETIC_SATURATE);
switch (part_type) {
case INT8_TYPE:
if (saturate) {
// TODO(benvanik): trace DID_SATURATE
if (is_unsigned) {
e.vpaddusb(dest, src1, src2);
} else {
e.vpaddsb(dest, src1, src2);
}
} else {
e.vpaddb(dest, src1, src2);
}
break;
case INT16_TYPE:
if (saturate) {
// TODO(benvanik): trace DID_SATURATE
if (is_unsigned) {
e.vpaddusw(dest, src1, src2);
} else {
e.vpaddsw(dest, src1, src2);
}
} else {
e.vpaddw(dest, src1, src2);
}
break;
case INT32_TYPE:
if (saturate) {
if (is_unsigned) {
// TODO(benvanik): broken with UINT32MAX+1
//// We reuse all these temps...
//assert_true(src1 != e.xmm0 && src1 != e.xmm1 && src1 != e.xmm2);
//assert_true(src2 != e.xmm0 && src2 != e.xmm1 && src2 != e.xmm2);
//// Clamp to 0xFFFFFFFF.
//// Wish there was a vpaddusd...
//// | A | B | C | D |
//// | B | D |
//e.vpsllq(e.xmm0, src1, 32);
//e.vpsllq(e.xmm1, src2, 32);
//e.vpsrlq(e.xmm0, 32);
//e.vpsrlq(e.xmm1, 32);
//e.vpaddq(e.xmm0, e.xmm1);
//e.vpcmpgtq(e.xmm0, e.GetXmmConstPtr(XMMUnsignedDwordMax));
//e.vpsllq(e.xmm0, 32);
//e.vpsrlq(e.xmm0, 32);
//// | A | C |
//e.vpsrlq(e.xmm1, src1, 32);
//e.vpsrlq(e.xmm2, src2, 32);
//e.vpaddq(e.xmm1, e.xmm2);
//e.vpcmpgtq(e.xmm1, e.GetXmmConstPtr(XMMUnsignedDwordMax));
//e.vpsllq(e.xmm1, 32);
//// xmm0 = mask for with saturated dwords == 111...
//e.vpor(e.xmm0, e.xmm1);
//e.vpaddd(dest, src1, src2);
//// dest.f[n] = xmm1.f[n] ? xmm1.f[n] : dest.f[n];
//e.vblendvps(dest, dest, e.xmm1, e.xmm1);
if (i.src2.is_constant) {
e.LoadConstantXmm(e.xmm0, i.src2.constant());
e.lea(e.r9, e.StashXmm(1, e.xmm0));
} else {
e.lea(e.r9, e.StashXmm(1, i.src2));
}
e.lea(e.r8, e.StashXmm(0, i.src1));
e.CallNativeSafe(
reinterpret_cast<void*>(EmulateVectorAddUnsignedSatI32));
e.vmovaps(i.dest, e.xmm0);
} else {
// https://software.intel.com/en-us/forums/topic/285219
// TODO(benvanik): this is broken with INTMAX+1.
// We reuse all these temps...
//assert_true(src1 != e.xmm0 && src1 != e.xmm1 && src1 != e.xmm2);
//assert_true(src2 != e.xmm0 && src2 != e.xmm1 && src2 != e.xmm2);
//e.vpaddd(e.xmm0, src1, src2); // res
//e.vpand(e.xmm1, src1, src2); // sign_and
//e.vpandn(e.xmm2, e.xmm0, e.xmm1); // min_sat_mask
//e.vblendvps(dest, e.xmm0, e.GetXmmConstPtr(XMMSignMaskPS), e.xmm2);
//e.vpor(e.xmm1, src1, src2); // sign_or
//e.vpandn(e.xmm1, e.xmm0); // max_sat_mask
//e.vblendvps(dest, e.GetXmmConstPtr(XMMAbsMaskPS), e.xmm1);
if (i.src2.is_constant) {
e.LoadConstantXmm(e.xmm0, i.src2.constant());
e.lea(e.r9, e.StashXmm(1, e.xmm0));
} else {
e.lea(e.r9, e.StashXmm(1, i.src2));
}
e.lea(e.r8, e.StashXmm(0, i.src1));
e.CallNativeSafe(
reinterpret_cast<void*>(EmulateVectorAddSignedSatI32));
e.vmovaps(i.dest, e.xmm0);
}
} else {
e.vpaddd(dest, src1, src2);
}
break;
case FLOAT32_TYPE:
assert_false(is_unsigned);
assert_false(saturate);
e.vaddps(dest, src1, src2);
break;
default: assert_unhandled_case(part_type); break;
}
});
}
};
EMITTER_OPCODE_TABLE(
OPCODE_VECTOR_ADD,
VECTOR_ADD);
// ============================================================================
// OPCODE_SUB
// ============================================================================
// TODO(benvanik): put dest/src1|2 together.
template <typename SEQ, typename REG, typename ARGS>
void EmitSubXX(X64Emitter& e, const ARGS& i) {
if (i.instr->flags & ARITHMETIC_SET_CARRY) {
// TODO(benvanik): faster way of doing sub with CF set?
SEQ::EmitAssociativeBinaryOp(
e, i,
[](X64Emitter& e, const REG& dest_src, const REG& src) {
auto temp = GetTempReg<REG>(e);
e.mov(temp, src);
e.not(temp);
e.stc();
e.adc(dest_src, temp);
},
[](X64Emitter& e, const REG& dest_src, int32_t constant) {
auto temp = GetTempReg<REG>(e);
e.mov(temp, constant);
e.not(temp);
e.stc();
e.adc(dest_src, temp);
});
e.StoreEflags();
} else {
SEQ::EmitAssociativeBinaryOp(
e, i,
[](X64Emitter& e, const REG& dest_src, const REG& src) { e.sub(dest_src, src); },
[](X64Emitter& e, const REG& dest_src, int32_t constant) { e.sub(dest_src, constant); });
}
}
EMITTER(SUB_I8, MATCH(I<OPCODE_SUB, I8<>, I8<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitSubXX<SUB_I8, Reg8>(e, i);
}
};
EMITTER(SUB_I16, MATCH(I<OPCODE_SUB, I16<>, I16<>, I16<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitSubXX<SUB_I16, Reg16>(e, i);
}
};
EMITTER(SUB_I32, MATCH(I<OPCODE_SUB, I32<>, I32<>, I32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitSubXX<SUB_I32, Reg32>(e, i);
}
};
EMITTER(SUB_I64, MATCH(I<OPCODE_SUB, I64<>, I64<>, I64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitSubXX<SUB_I64, Reg64>(e, i);
}
};
EMITTER(SUB_F32, MATCH(I<OPCODE_SUB, F32<>, F32<>, F32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
assert_true(!i.instr->flags);
EmitAssociativeBinaryXmmOp(e, i,
[](X64Emitter& e, Xmm dest, Xmm src1, Xmm src2) {
e.vsubss(dest, src1, src2);
});
}
};
EMITTER(SUB_F64, MATCH(I<OPCODE_SUB, F64<>, F64<>, F64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
assert_true(!i.instr->flags);
EmitAssociativeBinaryXmmOp(e, i,
[](X64Emitter& e, Xmm dest, Xmm src1, Xmm src2) {
e.vsubsd(dest, src1, src2);
});
}
};
EMITTER_OPCODE_TABLE(
OPCODE_SUB,
SUB_I8,
SUB_I16,
SUB_I32,
SUB_I64,
SUB_F32,
SUB_F64);
// ============================================================================
// OPCODE_VECTOR_SUB
// ============================================================================
EMITTER(VECTOR_SUB, MATCH(I<OPCODE_VECTOR_SUB, V128<>, V128<>, V128<>>)) {
static __m128i EmulateVectorSubSignedSatI32(void*, __m128i src1, __m128i src2) {
alignas(16) int32_t src1v[4];
alignas(16) int32_t src2v[4];
alignas(16) int32_t value[4];
_mm_store_si128(reinterpret_cast<__m128i*>(src1v), src1);
_mm_store_si128(reinterpret_cast<__m128i*>(src2v), src2);
for (size_t i = 0; i < 4; ++i) {
auto t = int64_t(src1v[i]) - int64_t(src2v[i]);
value[i] = t < INT_MIN ? INT_MIN : (t > INT_MAX ? INT_MAX : int32_t(t));
}
return _mm_load_si128(reinterpret_cast<__m128i*>(value));
}
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitCommutativeBinaryXmmOp(e, i,
[&i](X64Emitter& e, const Xmm& dest, const Xmm& src1, const Xmm& src2) {
const TypeName part_type = static_cast<TypeName>(i.instr->flags & 0xFF);
const uint32_t arithmetic_flags = i.instr->flags >> 8;
bool is_unsigned = !!(arithmetic_flags & ARITHMETIC_UNSIGNED);
bool saturate = !!(arithmetic_flags & ARITHMETIC_SATURATE);
switch (part_type) {
case INT8_TYPE:
if (saturate) {
// TODO(benvanik): trace DID_SATURATE
if (is_unsigned) {
e.vpsubusb(dest, src1, src2);
} else {
e.vpsubsb(dest, src1, src2);
}
} else {
e.vpsubb(dest, src1, src2);
}
break;
case INT16_TYPE:
if (saturate) {
// TODO(benvanik): trace DID_SATURATE
if (is_unsigned) {
e.vpsubusw(dest, src1, src2);
} else {
e.vpsubsw(dest, src1, src2);
}
} else {
e.vpsubw(dest, src1, src2);
}
break;
case INT32_TYPE:
if (saturate) {
if (is_unsigned) {
assert_always();
} else {
e.lea(e.r8, e.StashXmm(0, i.src1));
e.lea(e.r9, e.StashXmm(1, i.src2));
e.CallNativeSafe(
reinterpret_cast<void*>(EmulateVectorSubSignedSatI32));
e.vmovaps(i.dest, e.xmm0);
}
} else {
e.vpsubd(dest, src1, src2);
}
break;
case FLOAT32_TYPE:
e.vsubps(dest, src1, src2);
break;
default: assert_unhandled_case(part_type); break;
}
});
}
};
EMITTER_OPCODE_TABLE(
OPCODE_VECTOR_SUB,
VECTOR_SUB);
// ============================================================================
// OPCODE_MUL
// ============================================================================
// Sign doesn't matter here, as we don't use the high bits.
// We exploit mulx here to avoid creating too much register pressure.
EMITTER(MUL_I8, MATCH(I<OPCODE_MUL, I8<>, I8<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
if (e.IsFeatureEnabled(kX64EmitBMI2)) {
// mulx: $1:$2 = EDX * $3
// TODO(benvanik): place src2 in edx?
if (i.src1.is_constant) {
assert_true(!i.src2.is_constant);
e.movzx(e.edx, i.src2);
e.mov(e.eax, static_cast<uint8_t>(i.src1.constant()));
e.mulx(e.edx, i.dest.reg().cvt32(), e.eax);
} else if (i.src2.is_constant) {
e.movzx(e.edx, i.src1);
e.mov(e.eax, static_cast<uint8_t>(i.src2.constant()));
e.mulx(e.edx, i.dest.reg().cvt32(), e.eax);
} else {
e.movzx(e.edx, i.src2);
e.mulx(e.edx, i.dest.reg().cvt32(), i.src1.reg().cvt32());
}
} else {
// x86 mul instruction
// AH:AL = AL * $1;
if (i.src1.is_constant) {
assert_true(!i.src2.is_constant);
e.mov(e.al, i.src1.constant());
e.mul(i.src2);
e.mov(i.dest, e.al);
} else if (i.src2.is_constant) {
assert_true(!i.src1.is_constant);
e.mov(e.al, i.src2.constant());
e.mul(i.src1);
e.mov(i.dest, e.al);
} else {
e.movzx(e.al, i.src1);
e.mul(i.src2);
e.mov(i.dest, e.al);
}
}
e.ReloadEDX();
}
};
EMITTER(MUL_I16, MATCH(I<OPCODE_MUL, I16<>, I16<>, I16<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
if (e.IsFeatureEnabled(kX64EmitBMI2)) {
// mulx: $1:$2 = EDX * $3
// TODO(benvanik): place src2 in edx?
if (i.src1.is_constant) {
assert_true(!i.src2.is_constant);
e.movzx(e.edx, i.src2);
e.mov(e.ax, static_cast<uint16_t>(i.src1.constant()));
e.mulx(e.edx, i.dest.reg().cvt32(), e.eax);
} else if (i.src2.is_constant) {
e.movzx(e.edx, i.src1);
e.mov(e.ax, static_cast<uint16_t>(i.src2.constant()));
e.mulx(e.edx, i.dest.reg().cvt32(), e.eax);
} else {
e.movzx(e.edx, i.src2);
e.mulx(e.edx, i.dest.reg().cvt32(), i.src1.reg().cvt32());
}
} else {
// x86 mul instruction
// DX:AX = AX * $1;
if (i.src1.is_constant) {
assert_true(!i.src2.is_constant);
e.mov(e.ax, i.src1.constant());
e.mul(i.src2);
e.movzx(i.dest, e.ax);
} else if (i.src2.is_constant) {
assert_true(!i.src1.is_constant);
e.mov(e.ax, i.src2.constant());
e.mul(i.src1);
e.movzx(i.dest, e.ax);
} else {
e.movzx(e.ax, i.src1);
e.mul(i.src2);
e.movzx(i.dest, e.ax);
}
}
e.ReloadEDX();
}
};
EMITTER(MUL_I32, MATCH(I<OPCODE_MUL, I32<>, I32<>, I32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
if (e.IsFeatureEnabled(kX64EmitBMI2)) {
// mulx: $1:$2 = EDX * $3
// TODO(benvanik): place src2 in edx?
if (i.src1.is_constant) {
assert_true(!i.src2.is_constant);
e.mov(e.edx, i.src2);
e.mov(e.eax, i.src1.constant());
e.mulx(e.edx, i.dest, e.eax);
} else if (i.src2.is_constant) {
e.mov(e.edx, i.src1);
e.mov(e.eax, i.src2.constant());
e.mulx(e.edx, i.dest, e.eax);
} else {
e.mov(e.edx, i.src2);
e.mulx(e.edx, i.dest, i.src1);
}
} else {
// x86 mul instruction
// EDX:EAX = EAX * $1;
// is_constant AKA not a register
if (i.src1.is_constant) {
assert_true(!i.src2.is_constant); // can't multiply 2 constants
e.mov(e.eax, i.src1.constant());
e.mul(i.src2);
e.mov(i.dest, e.eax);
} else if (i.src2.is_constant) {
assert_true(!i.src1.is_constant); // can't multiply 2 constants
e.mov(e.eax, i.src2.constant());
e.mul(i.src1);
e.mov(i.dest, e.eax);
} else {
e.mov(e.eax, i.src1);
e.mul(i.src2);
e.mov(i.dest, e.eax);
}
}
e.ReloadEDX();
}
};
EMITTER(MUL_I64, MATCH(I<OPCODE_MUL, I64<>, I64<>, I64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
if (e.IsFeatureEnabled(kX64EmitBMI2)) {
// mulx: $1:$2 = RDX * $3
// TODO(benvanik): place src2 in edx?
if (i.src1.is_constant) {
assert_true(!i.src2.is_constant);
e.mov(e.rdx, i.src2);
e.mov(e.rax, i.src1.constant());
e.mulx(e.rdx, i.dest, e.rax);
} else if (i.src2.is_constant) {
e.mov(e.rdx, i.src1);
e.mov(e.rax, i.src2.constant());
e.mulx(e.rdx, i.dest, e.rax);
} else {
e.mov(e.rdx, i.src2);
e.mulx(e.rdx, i.dest, i.src1);
}
} else {
// x86 mul instruction
// RDX:RAX = RAX * $1;
if (i.src1.is_constant) {
assert_true(!i.src2.is_constant); // can't multiply 2 constants
e.mov(e.rax, i.src1.constant());
e.mul(i.src2);
e.mov(i.dest, e.rax);
} else if (i.src2.is_constant) {
assert_true(!i.src1.is_constant); // can't multiply 2 constants
e.mov(e.rax, i.src2.constant());
e.mul(i.src1);
e.mov(i.dest, e.rax);
} else {
e.mov(e.rax, i.src1);
e.mul(i.src2);
e.mov(i.dest, e.rax);
}
}
e.ReloadEDX();
}
};
EMITTER(MUL_F32, MATCH(I<OPCODE_MUL, F32<>, F32<>, F32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
assert_true(!i.instr->flags);
EmitCommutativeBinaryXmmOp(e, i,
[](X64Emitter& e, Xmm dest, Xmm src1, Xmm src2) {
e.vmulss(dest, src1, src2);
});
}
};
EMITTER(MUL_F64, MATCH(I<OPCODE_MUL, F64<>, F64<>, F64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
assert_true(!i.instr->flags);
EmitCommutativeBinaryXmmOp(e, i,
[](X64Emitter& e, Xmm dest, Xmm src1, Xmm src2) {
e.vmulsd(dest, src1, src2);
});
}
};
EMITTER(MUL_V128, MATCH(I<OPCODE_MUL, V128<>, V128<>, V128<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
assert_true(!i.instr->flags);
EmitCommutativeBinaryXmmOp(e, i,
[](X64Emitter& e, Xmm dest, Xmm src1, Xmm src2) {
e.vmulps(dest, src1, src2);
});
}
};
EMITTER_OPCODE_TABLE(
OPCODE_MUL,
MUL_I8,
MUL_I16,
MUL_I32,
MUL_I64,
MUL_F32,
MUL_F64,
MUL_V128);
// ============================================================================
// OPCODE_MUL_HI
// ============================================================================
EMITTER(MUL_HI_I8, MATCH(I<OPCODE_MUL_HI, I8<>, I8<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
if (i.instr->flags & ARITHMETIC_UNSIGNED) {
// mulx: $1:$2 = EDX * $3
// TODO(justin): Find a way to shorten this has call
if (e.IsFeatureEnabled(kX64EmitBMI2)) {
// TODO(benvanik): place src1 in eax? still need to sign extend
e.movzx(e.edx, i.src1);
e.mulx(i.dest.reg().cvt32(), e.eax, i.src2.reg().cvt32());
} else {
// x86 mul instruction
// AH:AL = AL * $1;
if (i.src1.is_constant) {
assert_true(!i.src2.is_constant); // can't multiply 2 constants
e.mov(e.al, i.src1.constant());
e.mul(i.src2);
e.mov(i.dest, e.ah);
} else if (i.src2.is_constant) {
assert_true(!i.src1.is_constant); // can't multiply 2 constants
e.mov(e.al, i.src2.constant());
e.mul(i.src1);
e.mov(i.dest, e.ah);
} else {
e.mov(e.al, i.src1);
e.mul(i.src2);
e.mov(i.dest, e.ah);
}
}
} else {
if (i.src1.is_constant) {
e.mov(e.al, i.src1.constant());
} else {
e.mov(e.al, i.src1);
}
if (i.src2.is_constant) {
e.mov(e.al, i.src2.constant());
e.imul(e.al);
} else {
e.imul(i.src2);
}
e.mov(i.dest, e.ah);
}
e.ReloadEDX();
}
};
EMITTER(MUL_HI_I16, MATCH(I<OPCODE_MUL_HI, I16<>, I16<>, I16<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
if (i.instr->flags & ARITHMETIC_UNSIGNED) {
// TODO(justin): Find a way to shorten this has call
if (e.IsFeatureEnabled(kX64EmitBMI2)) {
// TODO(benvanik): place src1 in eax? still need to sign extend
e.movzx(e.edx, i.src1);
e.mulx(i.dest.reg().cvt32(), e.eax, i.src2.reg().cvt32());
} else {
// x86 mul instruction
// DX:AX = AX * $1;
if (i.src1.is_constant) {
assert_true(!i.src2.is_constant); // can't multiply 2 constants
e.mov(e.ax, i.src1.constant());
e.mul(i.src2);
e.mov(i.dest, e.dx);
} else if (i.src2.is_constant) {
assert_true(!i.src1.is_constant); // can't multiply 2 constants
e.mov(e.ax, i.src2.constant());
e.mul(i.src1);
e.mov(i.dest, e.dx);
} else {
e.mov(e.ax, i.src1);
e.mul(i.src2);
e.mov(i.dest, e.dx);
}
}
} else {
if (i.src1.is_constant) {
e.mov(e.ax, i.src1.constant());
} else {
e.mov(e.ax, i.src1);
}
if (i.src2.is_constant) {
e.mov(e.dx, i.src2.constant());
e.imul(e.dx);
} else {
e.imul(i.src2);
}
e.mov(i.dest, e.dx);
}
e.ReloadEDX();
}
};
EMITTER(MUL_HI_I32, MATCH(I<OPCODE_MUL_HI, I32<>, I32<>, I32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
if (i.instr->flags & ARITHMETIC_UNSIGNED) {
// TODO(justin): Find a way to shorten this has call
if (e.IsFeatureEnabled(kX64EmitBMI2)) {
// TODO(benvanik): place src1 in eax? still need to sign extend
e.mov(e.edx, i.src1);
if (i.src2.is_constant) {
e.mov(e.eax, i.src2.constant());
e.mulx(i.dest, e.edx, e.eax);
} else {
e.mulx(i.dest, e.edx, i.src2);
}
} else {
// x86 mul instruction
// EDX:EAX = EAX * $1;
if (i.src1.is_constant) {
assert_true(!i.src2.is_constant); // can't multiply 2 constants
e.mov(e.eax, i.src1.constant());
e.mul(i.src2);
e.mov(i.dest, e.edx);
} else if (i.src2.is_constant) {
assert_true(!i.src1.is_constant); // can't multiply 2 constants
e.mov(e.eax, i.src2.constant());
e.mul(i.src1);
e.mov(i.dest, e.edx);
} else {
e.mov(e.eax, i.src1);
e.mul(i.src2);
e.mov(i.dest, e.edx);
}
}
} else {
if (i.src1.is_constant) {
e.mov(e.eax, i.src1.constant());
} else {
e.mov(e.eax, i.src1);
}
if (i.src2.is_constant) {
e.mov(e.edx, i.src2.constant());
e.imul(e.edx);
} else {
e.imul(i.src2);
}
e.mov(i.dest, e.edx);
}
e.ReloadEDX();
}
};
EMITTER(MUL_HI_I64, MATCH(I<OPCODE_MUL_HI, I64<>, I64<>, I64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
if (i.instr->flags & ARITHMETIC_UNSIGNED) {
// TODO(justin): Find a way to shorten this has call
if (e.IsFeatureEnabled(kX64EmitBMI2)) {
// TODO(benvanik): place src1 in eax? still need to sign extend
e.mov(e.rdx, i.src1);
if (i.src2.is_constant) {
e.mov(e.rax, i.src2.constant());
e.mulx(i.dest, e.rdx, e.rax);
} else {
e.mulx(i.dest, e.rax, i.src2);
}
} else {
// x86 mul instruction
// RDX:RAX < RAX * REG(op1);
if (i.src1.is_constant) {
assert_true(!i.src2.is_constant); // can't multiply 2 constants
e.mov(e.rax, i.src1.constant());
e.mul(i.src2);
e.mov(i.dest, e.rdx);
} else if (i.src2.is_constant) {
assert_true(!i.src1.is_constant); // can't multiply 2 constants
e.mov(e.rax, i.src2.constant());
e.mul(i.src1);
e.mov(i.dest, e.rdx);
} else {
e.mov(e.rax, i.src1);
e.mul(i.src2);
e.mov(i.dest, e.rdx);
}
}
} else {
if (i.src1.is_constant) {
e.mov(e.rax, i.src1.constant());
} else {
e.mov(e.rax, i.src1);
}
if (i.src2.is_constant) {
e.mov(e.rdx, i.src2.constant());
e.imul(e.rdx);
} else {
e.imul(i.src2);
}
e.mov(i.dest, e.rdx);
}
e.ReloadEDX();
}
};
EMITTER_OPCODE_TABLE(
OPCODE_MUL_HI,
MUL_HI_I8,
MUL_HI_I16,
MUL_HI_I32,
MUL_HI_I64);
// ============================================================================
// OPCODE_DIV
// ============================================================================
// TODO(benvanik): optimize common constant cases.
// TODO(benvanik): simplify code!
EMITTER(DIV_I8, MATCH(I<OPCODE_DIV, I8<>, I8<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
Xbyak::Label skip;
e.inLocalLabel();
// NOTE: RDX clobbered.
bool clobbered_rcx = false;
if (i.src2.is_constant) {
assert_true(!i.src1.is_constant);
clobbered_rcx = true;
e.mov(e.cl, i.src2.constant());
if (i.instr->flags & ARITHMETIC_UNSIGNED) {
e.movzx(e.ax, i.src1);
e.div(e.cl);
} else {
e.movsx(e.ax, i.src1);
e.idiv(e.cl);
}
} else {
// Skip if src2 is zero.
e.test(i.src2, i.src2);
e.jz(skip, CodeGenerator::T_SHORT);
if (i.instr->flags & ARITHMETIC_UNSIGNED) {
if (i.src1.is_constant) {
e.mov(e.ax, static_cast<int16_t>(i.src1.constant()));
} else {
e.movzx(e.ax, i.src1);
}
e.div(i.src2);
} else {
if (i.src1.is_constant) {
e.mov(e.ax, static_cast<int16_t>(i.src1.constant()));
} else {
e.movsx(e.ax, i.src1);
}
e.idiv(i.src2);
}
}
e.L(skip);
e.outLocalLabel();
e.mov(i.dest, e.al);
if (clobbered_rcx) {
e.ReloadECX();
}
e.ReloadEDX();
}
};
EMITTER(DIV_I16, MATCH(I<OPCODE_DIV, I16<>, I16<>, I16<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
Xbyak::Label skip;
e.inLocalLabel();
// NOTE: RDX clobbered.
bool clobbered_rcx = false;
if (i.src2.is_constant) {
assert_true(!i.src1.is_constant);
clobbered_rcx = true;
e.mov(e.cx, i.src2.constant());
if (i.instr->flags & ARITHMETIC_UNSIGNED) {
e.mov(e.ax, i.src1);
// Zero upper bits.
e.xor(e.dx, e.dx);
e.div(e.cx);
} else {
e.mov(e.ax, i.src1);
// Set dx to sign bit of src1 (dx:ax = dx:ax / src).
e.mov(e.dx, e.ax);
e.sar(e.dx, 15);
e.idiv(e.cx);
}
} else {
// Skip if src2 is zero.
e.test(i.src2, i.src2);
e.jz(skip, CodeGenerator::T_SHORT);
if (i.instr->flags & ARITHMETIC_UNSIGNED) {
if (i.src1.is_constant) {
e.mov(e.ax, i.src1.constant());
} else {
e.mov(e.ax, i.src1);
}
// Zero upper bits.
e.xor(e.dx, e.dx);
e.div(i.src2);
} else {
if (i.src1.is_constant) {
e.mov(e.ax, i.src1.constant());
} else {
e.mov(e.ax, i.src1);
}
// Set dx to sign bit of src1 (dx:ax = dx:ax / src).
e.mov(e.dx, e.ax);
e.sar(e.dx, 15);
e.idiv(i.src2);
}
}
e.L(skip);
e.outLocalLabel();
e.mov(i.dest, e.ax);
if (clobbered_rcx) {
e.ReloadECX();
}
e.ReloadEDX();
}
};
EMITTER(DIV_I32, MATCH(I<OPCODE_DIV, I32<>, I32<>, I32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
Xbyak::Label skip;
e.inLocalLabel();
// NOTE: RDX clobbered.
bool clobbered_rcx = false;
if (i.src2.is_constant) {
assert_true(!i.src1.is_constant);
clobbered_rcx = true;
e.mov(e.ecx, i.src2.constant());
if (i.instr->flags & ARITHMETIC_UNSIGNED) {
e.mov(e.eax, i.src1);
// Zero upper bits.
e.xor(e.edx, e.edx);
e.div(e.ecx);
} else {
e.mov(e.eax, i.src1);
// Set dx to sign bit of src1 (dx:ax = dx:ax / src).
e.mov(e.edx, e.eax);
e.sar(e.edx, 31);
e.idiv(e.ecx);
}
} else {
// Skip if src2 is zero.
e.test(i.src2, i.src2);
e.jz(skip, CodeGenerator::T_SHORT);
if (i.instr->flags & ARITHMETIC_UNSIGNED) {
if (i.src1.is_constant) {
e.mov(e.eax, i.src1.constant());
} else {
e.mov(e.eax, i.src1);
}
// Zero upper bits.
e.xor(e.edx, e.edx);
e.div(i.src2);
} else {
if (i.src1.is_constant) {
e.mov(e.eax, i.src1.constant());
} else {
e.mov(e.eax, i.src1);
}
// Set dx to sign bit of src1 (dx:ax = dx:ax / src).
e.mov(e.edx, e.eax);
e.sar(e.edx, 31);
e.idiv(i.src2);
}
}
e.L(skip);
e.outLocalLabel();
e.mov(i.dest, e.eax);
if (clobbered_rcx) {
e.ReloadECX();
}
e.ReloadEDX();
}
};
EMITTER(DIV_I64, MATCH(I<OPCODE_DIV, I64<>, I64<>, I64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
Xbyak::Label skip;
e.inLocalLabel();
// NOTE: RDX clobbered.
bool clobbered_rcx = false;
if (i.src2.is_constant) {
assert_true(!i.src1.is_constant);
clobbered_rcx = true;
e.mov(e.rcx, i.src2.constant());
if (i.instr->flags & ARITHMETIC_UNSIGNED) {
e.mov(e.rax, i.src1);
// Zero upper bits.
e.xor(e.rdx, e.rdx);
e.div(e.rcx);
} else {
e.mov(e.rax, i.src1);
// Set dx to sign bit of src1 (dx:ax = dx:ax / src).
e.mov(e.rdx, e.rax);
e.sar(e.rdx, 63);
e.idiv(e.rcx);
}
} else {
// Skip if src2 is zero.
e.test(i.src2, i.src2);
e.jz(skip, CodeGenerator::T_SHORT);
if (i.instr->flags & ARITHMETIC_UNSIGNED) {
if (i.src1.is_constant) {
e.mov(e.rax, i.src1.constant());
} else {
e.mov(e.rax, i.src1);
}
// Zero upper bits.
e.xor(e.rdx, e.rdx);
e.div(i.src2);
} else {
if (i.src1.is_constant) {
e.mov(e.rax, i.src1.constant());
} else {
e.mov(e.rax, i.src1);
}
// Set dx to sign bit of src1 (dx:ax = dx:ax / src).
e.mov(e.rdx, e.rax);
e.sar(e.rdx, 63);
e.idiv(i.src2);
}
}
e.L(skip);
e.outLocalLabel();
e.mov(i.dest, e.rax);
if (clobbered_rcx) {
e.ReloadECX();
}
e.ReloadEDX();
}
};
EMITTER(DIV_F32, MATCH(I<OPCODE_DIV, F32<>, F32<>, F32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
assert_true(!i.instr->flags);
EmitAssociativeBinaryXmmOp(e, i,
[](X64Emitter& e, Xmm dest, Xmm src1, Xmm src2) {
e.vdivss(dest, src1, src2);
});
}
};
EMITTER(DIV_F64, MATCH(I<OPCODE_DIV, F64<>, F64<>, F64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
assert_true(!i.instr->flags);
EmitAssociativeBinaryXmmOp(e, i,
[](X64Emitter& e, Xmm dest, Xmm src1, Xmm src2) {
e.vdivsd(dest, src1, src2);
});
}
};
EMITTER(DIV_V128, MATCH(I<OPCODE_DIV, V128<>, V128<>, V128<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
assert_true(!i.instr->flags);
EmitAssociativeBinaryXmmOp(e, i,
[](X64Emitter& e, Xmm dest, Xmm src1, Xmm src2) {
e.vdivps(dest, src1, src2);
});
}
};
EMITTER_OPCODE_TABLE(
OPCODE_DIV,
DIV_I8,
DIV_I16,
DIV_I32,
DIV_I64,
DIV_F32,
DIV_F64,
DIV_V128);
// ============================================================================
// OPCODE_MUL_ADD
// ============================================================================
// d = 1 * 2 + 3
// $0 = $1x$0 + $2
// TODO(benvanik): use other forms (132/213/etc) to avoid register shuffling.
// dest could be src2 or src3 - need to ensure it's not before overwriting dest
// perhaps use other 132/213/etc
// Forms:
// - 132 -> $1 = $1 * $3 + $2
// - 213 -> $1 = $2 * $1 + $3
// - 231 -> $1 = $2 * $3 + $1
EMITTER(MUL_ADD_F32, MATCH(I<OPCODE_MUL_ADD, F32<>, F32<>, F32<>, F32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
// FMA extension
if (e.IsFeatureEnabled(kX64EmitFMA)) {
if (i.dest == i.src1) {
e.vfmadd213ss(i.dest, i.src2, i.src3);
} else if (i.dest == i.src2) {
e.vfmadd213ss(i.dest, i.src1, i.src3);
} else if (i.dest == i.src3) {
e.vfmadd231ss(i.dest, i.src1, i.src2);
} else {
// Dest not equal to anything
e.vmovss(i.dest, i.src1);
e.vfmadd213ss(i.dest, i.src2, i.src3);
}
} else {
// If i.dest == i.src3, back up i.src3 so we don't overwrite it.
Xmm src3 = i.src3;
if (i.dest == i.src3) {
e.vmovss(e.xmm0, i.src3);
src3 = e.xmm0;
}
e.vmulss(i.dest, i.src1, i.src2); // $0 = $1 * $2
e.vaddss(i.dest, i.dest, src3); // $0 = $1 + $2
}
}
};
EMITTER(MUL_ADD_F64, MATCH(I<OPCODE_MUL_ADD, F64<>, F64<>, F64<>, F64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
// FMA extension
if (e.IsFeatureEnabled(kX64EmitFMA)) {
if (i.dest == i.src1) {
e.vfmadd213sd(i.dest, i.src2, i.src3);
} else if (i.dest == i.src2) {
e.vfmadd213sd(i.dest, i.src1, i.src3);
} else if (i.dest == i.src3) {
e.vfmadd231sd(i.dest, i.src1, i.src2);
} else {
// Dest not equal to anything
e.vmovsd(i.dest, i.src1);
e.vfmadd213sd(i.dest, i.src2, i.src3);
}
} else {
// If i.dest == i.src3, back up i.src3 so we don't overwrite it.
Xmm src3 = i.src3;
if (i.dest == i.src3) {
e.vmovsd(e.xmm0, i.src3);
src3 = e.xmm0;
}
e.vmulsd(i.dest, i.src1, i.src2); // $0 = $1 * $2
e.vaddsd(i.dest, i.dest, src3); // $0 = $1 + $2
}
}
};
EMITTER(MUL_ADD_V128, MATCH(I<OPCODE_MUL_ADD, V128<>, V128<>, V128<>, V128<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
// FMA extension
if (e.IsFeatureEnabled(kX64EmitFMA)) {
if (i.dest == i.src1) {
e.vfmadd213ps(i.dest, i.src2, i.src3);
} else if (i.dest == i.src2) {
e.vfmadd213ps(i.dest, i.src1, i.src3);
} else if (i.dest == i.src3) {
e.vfmadd231ps(i.dest, i.src1, i.src2);
} else {
// Dest not equal to anything
e.vmovdqa(i.dest, i.src1);
e.vfmadd213ps(i.dest, i.src2, i.src3);
}
} else {
// If i.dest == i.src3, back up i.src3 so we don't overwrite it.
Xmm src3 = i.src3;
if (i.dest == i.src3) {
e.vmovdqa(e.xmm0, i.src3);
src3 = e.xmm0;
}
e.vmulps(i.dest, i.src1, i.src2); // $0 = $1 * $2
e.vaddps(i.dest, i.dest, src3); // $0 = $1 + $2
}
}
};
EMITTER_OPCODE_TABLE(
OPCODE_MUL_ADD,
MUL_ADD_F32,
MUL_ADD_F64,
MUL_ADD_V128);
// ============================================================================
// OPCODE_MUL_SUB
// ============================================================================
// d = 1 * 2 - 3
// $0 = $2x$0 - $3
// TODO(benvanik): use other forms (132/213/etc) to avoid register shuffling.
// dest could be src2 or src3 - need to ensure it's not before overwriting dest
// perhaps use other 132/213/etc
// Forms:
// - 132 -> $1 = $1 * $3 - $2
// - 213 -> $1 = $2 * $1 - $3
// - 231 -> $1 = $2 * $3 - $1
EMITTER(MUL_SUB_F32, MATCH(I<OPCODE_MUL_SUB, F32<>, F32<>, F32<>, F32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
// FMA extension
if (e.IsFeatureEnabled(kX64EmitFMA)) {
if (i.dest == i.src1) {
e.vfmsub213ss(i.dest, i.src2, i.src3);
} else if (i.dest == i.src2) {
e.vfmsub213ss(i.dest, i.src1, i.src3);
} else if (i.dest == i.src3) {
e.vfmsub231ss(i.dest, i.src1, i.src2);
} else {
// Dest not equal to anything
e.vmovss(i.dest, i.src1);
e.vfmsub213ss(i.dest, i.src2, i.src3);
}
} else {
// If i.dest == i.src3, back up i.src3 so we don't overwrite it.
Xmm src3 = i.src3;
if (i.dest == i.src3) {
e.vmovss(e.xmm0, i.src3);
src3 = e.xmm0;
}
e.vmulss(i.dest, i.src1, i.src2); // $0 = $1 * $2
e.vsubss(i.dest, i.dest, src3); // $0 = $1 - $2
}
}
};
EMITTER(MUL_SUB_F64, MATCH(I<OPCODE_MUL_SUB, F64<>, F64<>, F64<>, F64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
// FMA extension
if (e.IsFeatureEnabled(kX64EmitFMA)) {
if (i.dest == i.src1) {
e.vfmsub213sd(i.dest, i.src2, i.src3);
} else if (i.dest == i.src2) {
e.vfmsub213sd(i.dest, i.src1, i.src3);
} else if (i.dest == i.src3) {
e.vfmsub231sd(i.dest, i.src1, i.src2);
} else {
// Dest not equal to anything
e.vmovsd(i.dest, i.src1);
e.vfmsub213sd(i.dest, i.src2, i.src3);
}
} else {
// If i.dest == i.src3, back up i.src3 so we don't overwrite it.
Xmm src3 = i.src3;
if (i.dest == i.src3) {
e.vmovsd(e.xmm0, i.src3);
src3 = e.xmm0;
}
e.vmulsd(i.dest, i.src1, i.src2); // $0 = $1 * $2
e.vsubsd(i.dest, i.dest, src3); // $0 = $1 - $2
}
}
};
EMITTER(MUL_SUB_V128, MATCH(I<OPCODE_MUL_SUB, V128<>, V128<>, V128<>, V128<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
// FMA extension
if (e.IsFeatureEnabled(kX64EmitFMA)) {
if (i.dest == i.src1) {
e.vfmsub213ps(i.dest, i.src2, i.src3);
} else if (i.dest == i.src2) {
e.vfmsub213ps(i.dest, i.src1, i.src3);
} else if (i.dest == i.src3) {
e.vfmsub231ps(i.dest, i.src1, i.src2);
} else {
// Dest not equal to anything
e.vmovdqa(i.dest, i.src1);
e.vfmsub213ps(i.dest, i.src2, i.src3);
}
} else {
// If i.dest == i.src3, back up i.src3 so we don't overwrite it.
Xmm src3 = i.src3;
if (i.dest == i.src3) {
e.vmovdqa(e.xmm0, i.src3);
src3 = e.xmm0;
}
e.vmulps(i.dest, i.src1, i.src2); // $0 = $1 * $2
e.vsubps(i.dest, i.dest, src3); // $0 = $1 - $2
}
}
};
EMITTER_OPCODE_TABLE(
OPCODE_MUL_SUB,
MUL_SUB_F32,
MUL_SUB_F64,
MUL_SUB_V128);
// ============================================================================
// OPCODE_NEG
// ============================================================================
// TODO(benvanik): put dest/src1 together.
template <typename SEQ, typename REG, typename ARGS>
void EmitNegXX(X64Emitter& e, const ARGS& i) {
SEQ::EmitUnaryOp(
e, i,
[](X64Emitter& e, const REG& dest_src) { e.neg(dest_src); });
}
EMITTER(NEG_I8, MATCH(I<OPCODE_NEG, I8<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitNegXX<NEG_I8, Reg8>(e, i);
}
};
EMITTER(NEG_I16, MATCH(I<OPCODE_NEG, I16<>, I16<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitNegXX<NEG_I16, Reg16>(e, i);
}
};
EMITTER(NEG_I32, MATCH(I<OPCODE_NEG, I32<>, I32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitNegXX<NEG_I32, Reg32>(e, i);
}
};
EMITTER(NEG_I64, MATCH(I<OPCODE_NEG, I64<>, I64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitNegXX<NEG_I64, Reg64>(e, i);
}
};
EMITTER(NEG_F32, MATCH(I<OPCODE_NEG, F32<>, F32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.vxorps(i.dest, i.src1, e.GetXmmConstPtr(XMMSignMaskPS));
}
};
EMITTER(NEG_F64, MATCH(I<OPCODE_NEG, F64<>, F64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.vxorpd(i.dest, i.src1, e.GetXmmConstPtr(XMMSignMaskPD));
}
};
EMITTER(NEG_V128, MATCH(I<OPCODE_NEG, V128<>, V128<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
assert_true(!i.instr->flags);
e.vxorps(i.dest, i.src1, e.GetXmmConstPtr(XMMSignMaskPS));
}
};
EMITTER_OPCODE_TABLE(
OPCODE_NEG,
NEG_I8,
NEG_I16,
NEG_I32,
NEG_I64,
NEG_F32,
NEG_F64,
NEG_V128);
// ============================================================================
// OPCODE_ABS
// ============================================================================
EMITTER(ABS_F32, MATCH(I<OPCODE_ABS, F32<>, F32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.vpand(i.dest, i.src1, e.GetXmmConstPtr(XMMAbsMaskPS));
}
};
EMITTER(ABS_F64, MATCH(I<OPCODE_ABS, F64<>, F64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.vpand(i.dest, i.src1, e.GetXmmConstPtr(XMMAbsMaskPD));
}
};
EMITTER(ABS_V128, MATCH(I<OPCODE_ABS, V128<>, V128<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.vpand(i.dest, i.src1, e.GetXmmConstPtr(XMMAbsMaskPS));
}
};
EMITTER_OPCODE_TABLE(
OPCODE_ABS,
ABS_F32,
ABS_F64,
ABS_V128);
// ============================================================================
// OPCODE_SQRT
// ============================================================================
EMITTER(SQRT_F32, MATCH(I<OPCODE_SQRT, F32<>, F32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.vsqrtss(i.dest, i.src1);
}
};
EMITTER(SQRT_F64, MATCH(I<OPCODE_SQRT, F64<>, F64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.vsqrtsd(i.dest, i.src1);
}
};
EMITTER(SQRT_V128, MATCH(I<OPCODE_SQRT, V128<>, V128<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.vsqrtps(i.dest, i.src1);
}
};
EMITTER_OPCODE_TABLE(
OPCODE_SQRT,
SQRT_F32,
SQRT_F64,
SQRT_V128);
// ============================================================================
// OPCODE_RSQRT
// ============================================================================
EMITTER(RSQRT_F32, MATCH(I<OPCODE_RSQRT, F32<>, F32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.vrsqrtss(i.dest, i.src1);
}
};
EMITTER(RSQRT_F64, MATCH(I<OPCODE_RSQRT, F64<>, F64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.vcvtsd2ss(i.dest, i.src1);
e.vrsqrtss(i.dest, i.dest);
e.vcvtss2sd(i.dest, i.dest);
}
};
EMITTER(RSQRT_V128, MATCH(I<OPCODE_RSQRT, V128<>, V128<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.vrsqrtps(i.dest, i.src1);
}
};
EMITTER_OPCODE_TABLE(
OPCODE_RSQRT,
RSQRT_F32,
RSQRT_F64,
RSQRT_V128);
// ============================================================================
// OPCODE_POW2
// ============================================================================
// TODO(benvanik): use approx here:
// http://jrfonseca.blogspot.com/2008/09/fast-sse2-pow-tables-or-polynomials.html
EMITTER(POW2_F32, MATCH(I<OPCODE_POW2, F32<>, F32<>>)) {
static __m128 EmulatePow2(void*, __m128 src) {
float src_value;
_mm_store_ss(&src_value, src);
float result = std::exp2(src_value);
return _mm_load_ss(&result);
}
static void Emit(X64Emitter& e, const EmitArgType& i) {
assert_always();
e.lea(e.r8, e.StashXmm(0, i.src1));
e.CallNativeSafe(reinterpret_cast<void*>(EmulatePow2));
e.vmovaps(i.dest, e.xmm0);
}
};
EMITTER(POW2_F64, MATCH(I<OPCODE_POW2, F64<>, F64<>>)) {
static __m128d EmulatePow2(void*, __m128d src) {
double src_value;
_mm_store_sd(&src_value, src);
double result = std::exp2(src_value);
return _mm_load_sd(&result);
}
static void Emit(X64Emitter& e, const EmitArgType& i) {
assert_always();
e.lea(e.r8, e.StashXmm(0, i.src1));
e.CallNativeSafe(reinterpret_cast<void*>(EmulatePow2));
e.vmovaps(i.dest, e.xmm0);
}
};
EMITTER(POW2_V128, MATCH(I<OPCODE_POW2, V128<>, V128<>>)) {
static __m128 EmulatePow2(void*, __m128 src) {
alignas(16) float values[4];
_mm_store_ps(values, src);
for (size_t i = 0; i < 4; ++i) {
values[i] = std::exp2(values[i]);
}
return _mm_load_ps(values);
}
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.lea(e.r8, e.StashXmm(0, i.src1));
e.CallNativeSafe(reinterpret_cast<void*>(EmulatePow2));
e.vmovaps(i.dest, e.xmm0);
}
};
EMITTER_OPCODE_TABLE(
OPCODE_POW2,
POW2_F32,
POW2_F64,
POW2_V128);
// ============================================================================
// OPCODE_LOG2
// ============================================================================
// TODO(benvanik): use approx here:
// http://jrfonseca.blogspot.com/2008/09/fast-sse2-pow-tables-or-polynomials.html
// TODO(benvanik): this emulated fn destroys all xmm registers! don't do it!
EMITTER(LOG2_F32, MATCH(I<OPCODE_LOG2, F32<>, F32<>>)) {
static __m128 EmulateLog2(void*, __m128 src) {
float src_value;
_mm_store_ss(&src_value, src);
float result = std::log2(src_value);
return _mm_load_ss(&result);
}
static void Emit(X64Emitter& e, const EmitArgType& i) {
assert_always();
e.lea(e.r8, e.StashXmm(0, i.src1));
e.CallNativeSafe(reinterpret_cast<void*>(EmulateLog2));
e.vmovaps(i.dest, e.xmm0);
}
};
EMITTER(LOG2_F64, MATCH(I<OPCODE_LOG2, F64<>, F64<>>)) {
static __m128d EmulateLog2(void*, __m128d src) {
double src_value;
_mm_store_sd(&src_value, src);
double result = std::log2(src_value);
return _mm_load_sd(&result);
}
static void Emit(X64Emitter& e, const EmitArgType& i) {
assert_always();
e.lea(e.r8, e.StashXmm(0, i.src1));
e.CallNativeSafe(reinterpret_cast<void*>(EmulateLog2));
e.vmovaps(i.dest, e.xmm0);
}
};
EMITTER(LOG2_V128, MATCH(I<OPCODE_LOG2, V128<>, V128<>>)) {
static __m128 EmulateLog2(void*, __m128 src) {
alignas(16) float values[4];
_mm_store_ps(values, src);
for (size_t i = 0; i < 4; ++i) {
values[i] = std::log2(values[i]);
}
return _mm_load_ps(values);
}
static void Emit(X64Emitter& e, const EmitArgType& i) {
e.lea(e.r8, e.StashXmm(0, i.src1));
e.CallNativeSafe(reinterpret_cast<void*>(EmulateLog2));
e.vmovaps(i.dest, e.xmm0);
}
};
EMITTER_OPCODE_TABLE(
OPCODE_LOG2,
LOG2_F32,
LOG2_F64,
LOG2_V128);
// ============================================================================
// OPCODE_DOT_PRODUCT_3
// ============================================================================
EMITTER(DOT_PRODUCT_3_V128, MATCH(I<OPCODE_DOT_PRODUCT_3, F32<>, V128<>, V128<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
// http://msdn.microsoft.com/en-us/library/bb514054(v=vs.90).aspx
EmitCommutativeBinaryXmmOp(e, i,
[](X64Emitter& e, Xmm dest, Xmm src1, Xmm src2) {
// TODO(benvanik): apparently this is very slow - find alternative?
e.vdpps(dest, src1, src2, B01110001);
});
}
};
EMITTER_OPCODE_TABLE(
OPCODE_DOT_PRODUCT_3,
DOT_PRODUCT_3_V128);
// ============================================================================
// OPCODE_DOT_PRODUCT_4
// ============================================================================
EMITTER(DOT_PRODUCT_4_V128, MATCH(I<OPCODE_DOT_PRODUCT_4, F32<>, V128<>, V128<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
// http://msdn.microsoft.com/en-us/library/bb514054(v=vs.90).aspx
EmitCommutativeBinaryXmmOp(e, i,
[](X64Emitter& e, Xmm dest, Xmm src1, Xmm src2) {
// TODO(benvanik): apparently this is very slow - find alternative?
e.vdpps(dest, src1, src2, B11110001);
});
}
};
EMITTER_OPCODE_TABLE(
OPCODE_DOT_PRODUCT_4,
DOT_PRODUCT_4_V128);
// ============================================================================
// OPCODE_AND
// ============================================================================
// TODO(benvanik): put dest/src1|2 together.
template <typename SEQ, typename REG, typename ARGS>
void EmitAndXX(X64Emitter& e, const ARGS& i) {
SEQ::EmitCommutativeBinaryOp(
e, i,
[](X64Emitter& e, const REG& dest_src, const REG& src) { e.and(dest_src, src); },
[](X64Emitter& e, const REG& dest_src, int32_t constant) { e.and(dest_src, constant); });
}
EMITTER(AND_I8, MATCH(I<OPCODE_AND, I8<>, I8<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitAndXX<AND_I8, Reg8>(e, i);
}
};
EMITTER(AND_I16, MATCH(I<OPCODE_AND, I16<>, I16<>, I16<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitAndXX<AND_I16, Reg16>(e, i);
}
};
EMITTER(AND_I32, MATCH(I<OPCODE_AND, I32<>, I32<>, I32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitAndXX<AND_I32, Reg32>(e, i);
}
};
EMITTER(AND_I64, MATCH(I<OPCODE_AND, I64<>, I64<>, I64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitAndXX<AND_I64, Reg64>(e, i);
}
};
EMITTER(AND_V128, MATCH(I<OPCODE_AND, V128<>, V128<>, V128<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitCommutativeBinaryXmmOp(e, i,
[](X64Emitter& e, Xmm dest, Xmm src1, Xmm src2) {
e.vpand(dest, src1, src2);
});
}
};
EMITTER_OPCODE_TABLE(
OPCODE_AND,
AND_I8,
AND_I16,
AND_I32,
AND_I64,
AND_V128);
// ============================================================================
// OPCODE_OR
// ============================================================================
// TODO(benvanik): put dest/src1|2 together.
template <typename SEQ, typename REG, typename ARGS>
void EmitOrXX(X64Emitter& e, const ARGS& i) {
SEQ::EmitCommutativeBinaryOp(
e, i,
[](X64Emitter& e, const REG& dest_src, const REG& src) { e.or(dest_src, src); },
[](X64Emitter& e, const REG& dest_src, int32_t constant) { e.or(dest_src, constant); });
}
EMITTER(OR_I8, MATCH(I<OPCODE_OR, I8<>, I8<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitOrXX<OR_I8, Reg8>(e, i);
}
};
EMITTER(OR_I16, MATCH(I<OPCODE_OR, I16<>, I16<>, I16<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitOrXX<OR_I16, Reg16>(e, i);
}
};
EMITTER(OR_I32, MATCH(I<OPCODE_OR, I32<>, I32<>, I32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitOrXX<OR_I32, Reg32>(e, i);
}
};
EMITTER(OR_I64, MATCH(I<OPCODE_OR, I64<>, I64<>, I64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitOrXX<OR_I64, Reg64>(e, i);
}
};
EMITTER(OR_V128, MATCH(I<OPCODE_OR, V128<>, V128<>, V128<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitCommutativeBinaryXmmOp(e, i,
[](X64Emitter& e, Xmm dest, Xmm src1, Xmm src2) {
e.vpor(dest, src1, src2);
});
}
};
EMITTER_OPCODE_TABLE(
OPCODE_OR,
OR_I8,
OR_I16,
OR_I32,
OR_I64,
OR_V128);
// ============================================================================
// OPCODE_XOR
// ============================================================================
// TODO(benvanik): put dest/src1|2 together.
template <typename SEQ, typename REG, typename ARGS>
void EmitXorXX(X64Emitter& e, const ARGS& i) {
SEQ::EmitCommutativeBinaryOp(
e, i,
[](X64Emitter& e, const REG& dest_src, const REG& src) { e.xor(dest_src, src); },
[](X64Emitter& e, const REG& dest_src, int32_t constant) { e.xor(dest_src, constant); });
}
EMITTER(XOR_I8, MATCH(I<OPCODE_XOR, I8<>, I8<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitXorXX<XOR_I8, Reg8>(e, i);
}
};
EMITTER(XOR_I16, MATCH(I<OPCODE_XOR, I16<>, I16<>, I16<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitXorXX<XOR_I16, Reg16>(e, i);
}
};
EMITTER(XOR_I32, MATCH(I<OPCODE_XOR, I32<>, I32<>, I32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitXorXX<XOR_I32, Reg32>(e, i);
}
};
EMITTER(XOR_I64, MATCH(I<OPCODE_XOR, I64<>, I64<>, I64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitXorXX<XOR_I64, Reg64>(e, i);
}
};
EMITTER(XOR_V128, MATCH(I<OPCODE_XOR, V128<>, V128<>, V128<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitCommutativeBinaryXmmOp(e, i,
[](X64Emitter& e, Xmm dest, Xmm src1, Xmm src2) {
e.vpxor(dest, src1, src2);
});
}
};
EMITTER_OPCODE_TABLE(
OPCODE_XOR,
XOR_I8,
XOR_I16,
XOR_I32,
XOR_I64,
XOR_V128);
// ============================================================================
// OPCODE_NOT
// ============================================================================
// TODO(benvanik): put dest/src1 together.
template <typename SEQ, typename REG, typename ARGS>
void EmitNotXX(X64Emitter& e, const ARGS& i) {
SEQ::EmitUnaryOp(
e, i,
[](X64Emitter& e, const REG& dest_src) { e.not(dest_src); });
}
EMITTER(NOT_I8, MATCH(I<OPCODE_NOT, I8<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitNotXX<NOT_I8, Reg8>(e, i);
}
};
EMITTER(NOT_I16, MATCH(I<OPCODE_NOT, I16<>, I16<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitNotXX<NOT_I16, Reg16>(e, i);
}
};
EMITTER(NOT_I32, MATCH(I<OPCODE_NOT, I32<>, I32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitNotXX<NOT_I32, Reg32>(e, i);
}
};
EMITTER(NOT_I64, MATCH(I<OPCODE_NOT, I64<>, I64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitNotXX<NOT_I64, Reg64>(e, i);
}
};
EMITTER(NOT_V128, MATCH(I<OPCODE_NOT, V128<>, V128<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
// dest = src ^ 0xFFFF...
e.vpxor(i.dest, i.src1, e.GetXmmConstPtr(XMMFFFF /* FF... */));
}
};
EMITTER_OPCODE_TABLE(
OPCODE_NOT,
NOT_I8,
NOT_I16,
NOT_I32,
NOT_I64,
NOT_V128);
// ============================================================================
// OPCODE_SHL
// ============================================================================
// TODO(benvanik): optimize common shifts.
template <typename SEQ, typename REG, typename ARGS>
void EmitShlXX(X64Emitter& e, const ARGS& i) {
SEQ::EmitAssociativeBinaryOp(
e, i,
[](X64Emitter& e, const REG& dest_src, const Reg8& src) {
// shlx: $1 = $2 << $3
// shl: $1 = $1 << $2
if (e.IsFeatureEnabled(kX64EmitBMI2)) {
if (dest_src.getBit() == 64) {
e.shlx(dest_src.cvt64(), dest_src.cvt64(), src.cvt64());
} else {
e.shlx(dest_src.cvt32(), dest_src.cvt32(), src.cvt32());
}
} else {
e.mov(e.cl, src);
e.shl(dest_src, e.cl);
e.ReloadECX();
}
}, [](X64Emitter& e, const REG& dest_src, int8_t constant) {
e.shl(dest_src, constant);
});
}
EMITTER(SHL_I8, MATCH(I<OPCODE_SHL, I8<>, I8<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitShlXX<SHL_I8, Reg8>(e, i);
}
};
EMITTER(SHL_I16, MATCH(I<OPCODE_SHL, I16<>, I16<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitShlXX<SHL_I16, Reg16>(e, i);
}
};
EMITTER(SHL_I32, MATCH(I<OPCODE_SHL, I32<>, I32<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitShlXX<SHL_I32, Reg32>(e, i);
}
};
EMITTER(SHL_I64, MATCH(I<OPCODE_SHL, I64<>, I64<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitShlXX<SHL_I64, Reg64>(e, i);
}
};
EMITTER_OPCODE_TABLE(
OPCODE_SHL,
SHL_I8,
SHL_I16,
SHL_I32,
SHL_I64);
// ============================================================================
// OPCODE_SHR
// ============================================================================
// TODO(benvanik): optimize common shifts.
template <typename SEQ, typename REG, typename ARGS>
void EmitShrXX(X64Emitter& e, const ARGS& i) {
SEQ::EmitAssociativeBinaryOp(
e, i,
[](X64Emitter& e, const REG& dest_src, const Reg8& src) {
// shrx: op1 dest, op2 src, op3 count
// shr: op1 src/dest, op2 count
if (e.IsFeatureEnabled(kX64EmitBMI2)) {
if (dest_src.getBit() == 64) {
e.shrx(dest_src.cvt64(), dest_src.cvt64(), src.cvt64());
} else if (dest_src.getBit() == 32) {
e.shrx(dest_src.cvt32(), dest_src.cvt32(), src.cvt32());
} else {
e.movzx(dest_src.cvt32(), dest_src);
e.shrx(dest_src.cvt32(), dest_src.cvt32(), src.cvt32());
}
} else {
e.mov(e.cl, src);
e.shr(dest_src, e.cl);
e.ReloadECX();
}
}, [](X64Emitter& e, const REG& dest_src, int8_t constant) {
e.shr(dest_src, constant);
});
}
EMITTER(SHR_I8, MATCH(I<OPCODE_SHR, I8<>, I8<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitShrXX<SHR_I8, Reg8>(e, i);
}
};
EMITTER(SHR_I16, MATCH(I<OPCODE_SHR, I16<>, I16<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitShrXX<SHR_I16, Reg16>(e, i);
}
};
EMITTER(SHR_I32, MATCH(I<OPCODE_SHR, I32<>, I32<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitShrXX<SHR_I32, Reg32>(e, i);
}
};
EMITTER(SHR_I64, MATCH(I<OPCODE_SHR, I64<>, I64<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitShrXX<SHR_I64, Reg64>(e, i);
}
};
EMITTER(SHR_V128, MATCH(I<OPCODE_SHR, V128<>, V128<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
// TODO(benvanik): native version (with shift magic).
if (i.src2.is_constant) {
e.mov(e.r9, i.src2.constant());
} else {
e.mov(e.r9, i.src2);
}
e.lea(e.r8, e.StashXmm(0, i.src1));
e.CallNativeSafe(reinterpret_cast<void*>(EmulateShrV128));
e.vmovaps(i.dest, e.xmm0);
}
static __m128i EmulateShrV128(void*, __m128i src1, uint8_t src2) {
// Almost all instances are shamt = 1, but non-constant.
// shamt is [0,7]
uint8_t shamt = src2 & 0x7;
alignas(16) vec128_t value;
_mm_store_si128(reinterpret_cast<__m128i*>(&value), src1);
value.u8[0 ^ 0x3] = value.u8[0 ^ 0x3] >> shamt;
for (int i = 15; i > 0; --i) {
value.u8[i ^ 0x3] = (value.u8[i ^ 0x3] >> shamt) |
(value.u8[(i - 1) ^ 0x3] << (8 - shamt));
}
return _mm_load_si128(reinterpret_cast<__m128i*>(&value));
}
};
EMITTER_OPCODE_TABLE(
OPCODE_SHR,
SHR_I8,
SHR_I16,
SHR_I32,
SHR_I64,
SHR_V128);
// ============================================================================
// OPCODE_SHA
// ============================================================================
// TODO(benvanik): optimize common shifts.
template <typename SEQ, typename REG, typename ARGS>
void EmitSarXX(X64Emitter& e, const ARGS& i) {
SEQ::EmitAssociativeBinaryOp(
e, i,
[](X64Emitter& e, const REG& dest_src, const Reg8& src) {
if (e.IsFeatureEnabled(kX64EmitBMI2)) {
if (dest_src.getBit() == 64) {
e.sarx(dest_src.cvt64(), dest_src.cvt64(), src.cvt64());
} else if (dest_src.getBit() == 32) {
e.sarx(dest_src.cvt32(), dest_src.cvt32(), src.cvt32());
} else {
e.movsx(dest_src.cvt32(), dest_src);
e.sarx(dest_src.cvt32(), dest_src.cvt32(), src.cvt32());
}
} else {
e.mov(e.cl, src);
e.sar(dest_src, e.cl);
e.ReloadECX();
}
}, [](X64Emitter& e, const REG& dest_src, int8_t constant) {
e.sar(dest_src, constant);
});
}
EMITTER(SHA_I8, MATCH(I<OPCODE_SHA, I8<>, I8<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitSarXX<SHA_I8, Reg8>(e, i);
}
};
EMITTER(SHA_I16, MATCH(I<OPCODE_SHA, I16<>, I16<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitSarXX<SHA_I16, Reg16>(e, i);
}
};
EMITTER(SHA_I32, MATCH(I<OPCODE_SHA, I32<>, I32<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitSarXX<SHA_I32, Reg32>(e, i);
}
};
EMITTER(SHA_I64, MATCH(I<OPCODE_SHA, I64<>, I64<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitSarXX<SHA_I64, Reg64>(e, i);
}
};
EMITTER_OPCODE_TABLE(
OPCODE_SHA,
SHA_I8,
SHA_I16,
SHA_I32,
SHA_I64);
// ============================================================================
// OPCODE_VECTOR_SHL
// ============================================================================
EMITTER(VECTOR_SHL_V128, MATCH(I<OPCODE_VECTOR_SHL, V128<>, V128<>, V128<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
switch (i.instr->flags) {
case INT8_TYPE:
EmitInt8(e, i);
break;
case INT16_TYPE:
EmitInt16(e, i);
break;
case INT32_TYPE:
EmitInt32(e, i);
break;
default:
assert_always();
break;
}
}
static __m128i EmulateVectorShlI8(void*, __m128i src1, __m128i src2) {
alignas(16) uint8_t value[16];
alignas(16) uint8_t shamt[16];
_mm_store_si128(reinterpret_cast<__m128i*>(value), src1);
_mm_store_si128(reinterpret_cast<__m128i*>(shamt), src2);
for (size_t i = 0; i < 16; ++i) {
value[i] = value[i] << (shamt[i] & 0x7);
}
return _mm_load_si128(reinterpret_cast<__m128i*>(value));
}
static void EmitInt8(X64Emitter& e, const EmitArgType& i) {
// TODO(benvanik): native version (with shift magic).
if (i.src2.is_constant) {
e.LoadConstantXmm(e.xmm0, i.src2.constant());
e.lea(e.r9, e.StashXmm(1, e.xmm0));
} else {
e.lea(e.r9, e.StashXmm(1, i.src2));
}
e.lea(e.r8, e.StashXmm(0, i.src1));
e.CallNativeSafe(reinterpret_cast<void*>(EmulateVectorShlI8));
e.vmovaps(i.dest, e.xmm0);
}
static __m128i EmulateVectorShlI16(void*, __m128i src1, __m128i src2) {
alignas(16) uint16_t value[8];
alignas(16) uint16_t shamt[8];
_mm_store_si128(reinterpret_cast<__m128i*>(value), src1);
_mm_store_si128(reinterpret_cast<__m128i*>(shamt), src2);
for (size_t i = 0; i < 8; ++i) {
value[i] = value[i] << (shamt[i] & 0xF);
}
return _mm_load_si128(reinterpret_cast<__m128i*>(value));
}
static void EmitInt16(X64Emitter& e, const EmitArgType& i) {
if (i.src2.is_constant) {
const auto& shamt = i.src2.constant();
bool all_same = true;
for (size_t n = 0; n < 8 - n; ++n) {
if (shamt.u16[n] != shamt.u16[n + 1]) {
all_same = false;
break;
}
}
if (all_same) {
// Every count is the same, so we can use vpsllw.
e.vpsllw(i.dest, i.src1, shamt.u16[0] & 0xF);
return;
}
}
// TODO(benvanik): native version (with shift magic).
if (i.src2.is_constant) {
e.LoadConstantXmm(e.xmm0, i.src2.constant());
e.lea(e.r9, e.StashXmm(1, e.xmm0));
} else {
e.lea(e.r9, e.StashXmm(1, i.src2));
}
e.lea(e.r8, e.StashXmm(0, i.src1));
e.CallNativeSafe(reinterpret_cast<void*>(EmulateVectorShlI16));
e.vmovaps(i.dest, e.xmm0);
}
static __m128i EmulateVectorShlI32(void*, __m128i src1, __m128i src2) {
alignas(16) uint32_t value[4];
alignas(16) uint32_t shamt[4];
_mm_store_si128(reinterpret_cast<__m128i*>(value), src1);
_mm_store_si128(reinterpret_cast<__m128i*>(shamt), src2);
for (size_t i = 0; i < 4; ++i) {
value[i] = value[i] << (shamt[i] & 0x1F);
}
return _mm_load_si128(reinterpret_cast<__m128i*>(value));
}
static void EmitInt32(X64Emitter& e, const EmitArgType& i) {
if (e.IsFeatureEnabled(kX64EmitAVX2)) {
if (i.src2.is_constant) {
const auto& shamt = i.src2.constant();
bool all_same = true;
for (size_t n = 0; n < 4 - n; ++n) {
if (shamt.u32[n] != shamt.u32[n + 1]) {
all_same = false;
break;
}
}
if (all_same) {
// Every count is the same, so we can use vpslld.
e.vpslld(i.dest, i.src1, shamt.u8[0] & 0x1F);
} else {
// Counts differ, so pre-mask and load constant.
vec128_t masked = i.src2.constant();
for (size_t n = 0; n < 4; ++n) {
masked.u32[n] &= 0x1F;
}
e.LoadConstantXmm(e.xmm0, masked);
e.vpsllvd(i.dest, i.src1, e.xmm0);
}
} else {
// Fully variable shift.
// src shift mask may have values >31, and x86 sets to zero when
// that happens so we mask.
e.vandps(e.xmm0, i.src2, e.GetXmmConstPtr(XMMShiftMaskPS));
e.vpsllvd(i.dest, i.src1, e.xmm0);
}
} else {
// TODO(benvanik): native version (with shift magic).
if (i.src2.is_constant) {
e.LoadConstantXmm(e.xmm0, i.src2.constant());
e.lea(e.r9, e.StashXmm(1, e.xmm0));
} else {
e.lea(e.r9, e.StashXmm(1, i.src2));
}
e.lea(e.r8, e.StashXmm(0, i.src1));
e.CallNativeSafe(reinterpret_cast<void*>(EmulateVectorShlI32));
e.vmovaps(i.dest, e.xmm0);
}
}
};
EMITTER_OPCODE_TABLE(
OPCODE_VECTOR_SHL,
VECTOR_SHL_V128);
// ============================================================================
// OPCODE_VECTOR_SHR
// ============================================================================
EMITTER(VECTOR_SHR_V128, MATCH(I<OPCODE_VECTOR_SHR, V128<>, V128<>, V128<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
switch (i.instr->flags) {
case INT8_TYPE:
EmitInt8(e, i);
break;
case INT16_TYPE:
EmitInt16(e, i);
break;
case INT32_TYPE:
EmitInt32(e, i);
break;
default:
assert_always();
break;
}
}
static __m128i EmulateVectorShrI8(void*, __m128i src1, __m128i src2) {
alignas(16) uint8_t value[16];
alignas(16) uint8_t shamt[16];
_mm_store_si128(reinterpret_cast<__m128i*>(value), src1);
_mm_store_si128(reinterpret_cast<__m128i*>(shamt), src2);
for (size_t i = 0; i < 16; ++i) {
value[i] = value[i] >> (shamt[i] & 0x7);
}
return _mm_load_si128(reinterpret_cast<__m128i*>(value));
}
static void EmitInt8(X64Emitter& e, const EmitArgType& i) {
// TODO(benvanik): native version (with shift magic).
if (i.src2.is_constant) {
e.LoadConstantXmm(e.xmm0, i.src2.constant());
e.lea(e.r9, e.StashXmm(1, e.xmm0));
} else {
e.lea(e.r9, e.StashXmm(1, i.src2));
}
e.lea(e.r8, e.StashXmm(0, i.src1));
e.CallNativeSafe(reinterpret_cast<void*>(EmulateVectorShrI8));
e.vmovaps(i.dest, e.xmm0);
}
static __m128i EmulateVectorShrI16(void*, __m128i src1, __m128i src2) {
alignas(16) uint16_t value[8];
alignas(16) uint16_t shamt[8];
_mm_store_si128(reinterpret_cast<__m128i*>(value), src1);
_mm_store_si128(reinterpret_cast<__m128i*>(shamt), src2);
for (size_t i = 0; i < 8; ++i) {
value[i] = value[i] >> (shamt[i] & 0xF);
}
return _mm_load_si128(reinterpret_cast<__m128i*>(value));
}
static void EmitInt16(X64Emitter& e, const EmitArgType& i) {
if (i.src2.is_constant) {
const auto& shamt = i.src2.constant();
bool all_same = true;
for (size_t n = 0; n < 8 - n; ++n) {
if (shamt.u16[n] != shamt.u16[n + 1]) {
all_same = false;
break;
}
}
if (all_same) {
// Every count is the same, so we can use vpsllw.
e.vpsrlw(i.dest, i.src1, shamt.u16[0] & 0xF);
return;
}
}
// TODO(benvanik): native version (with shift magic).
if (i.src2.is_constant) {
e.LoadConstantXmm(e.xmm0, i.src2.constant());
e.lea(e.r9, e.StashXmm(1, e.xmm0));
} else {
e.lea(e.r9, e.StashXmm(1, i.src2));
}
e.lea(e.r8, e.StashXmm(0, i.src1));
e.CallNativeSafe(reinterpret_cast<void*>(EmulateVectorShrI16));
e.vmovaps(i.dest, e.xmm0);
}
static __m128i EmulateVectorShrI32(void*, __m128i src1, __m128i src2) {
alignas(16) uint32_t value[4];
alignas(16) uint32_t shamt[4];
_mm_store_si128(reinterpret_cast<__m128i*>(value), src1);
_mm_store_si128(reinterpret_cast<__m128i*>(shamt), src2);
for (size_t i = 0; i < 4; ++i) {
value[i] = value[i] >> (shamt[i] & 0x1F);
}
return _mm_load_si128(reinterpret_cast<__m128i*>(value));
}
static void EmitInt32(X64Emitter& e, const EmitArgType& i) {
if (i.src2.is_constant) {
const auto& shamt = i.src2.constant();
bool all_same = true;
for (size_t n = 0; n < 4 - n; ++n) {
if (shamt.u32[n] != shamt.u32[n + 1]) {
all_same = false;
break;
}
}
if (all_same) {
// Every count is the same, so we can use vpslld.
e.vpsrld(i.dest, i.src1, shamt.u8[0] & 0x1F);
return;
} else {
if (e.IsFeatureEnabled(kX64EmitAVX2)) {
// Counts differ, so pre-mask and load constant.
vec128_t masked = i.src2.constant();
for (size_t n = 0; n < 4; ++n) {
masked.u32[n] &= 0x1F;
}
e.LoadConstantXmm(e.xmm0, masked);
e.vpsrlvd(i.dest, i.src1, e.xmm0);
return;
}
}
} else {
if (e.IsFeatureEnabled(kX64EmitAVX2)) {
// Fully variable shift.
// src shift mask may have values >31, and x86 sets to zero when
// that happens so we mask.
e.vandps(e.xmm0, i.src2, e.GetXmmConstPtr(XMMShiftMaskPS));
e.vpsrlvd(i.dest, i.src1, e.xmm0);
return;
}
}
// We've reached here if we don't have AVX2 and it's a variable shift
// TODO: native version
if (i.src2.is_constant) {
e.LoadConstantXmm(e.xmm0, i.src2.constant());
e.lea(e.r9, e.StashXmm(1, e.xmm0));
} else {
e.lea(e.r9, e.StashXmm(1, i.src2));
}
e.lea(e.r8, e.StashXmm(0, i.src1));
e.CallNativeSafe(reinterpret_cast<void*>(EmulateVectorShrI32));
e.vmovaps(i.dest, e.xmm0);
}
};
EMITTER_OPCODE_TABLE(
OPCODE_VECTOR_SHR,
VECTOR_SHR_V128);
// ============================================================================
// OPCODE_VECTOR_SHA
// ============================================================================
EMITTER(VECTOR_SHA_V128, MATCH(I<OPCODE_VECTOR_SHA, V128<>, V128<>, V128<>>)) {
static __m128i EmulateVectorShaI8(void*, __m128i src1, __m128i src2) {
alignas(16) int8_t value[16];
alignas(16) int8_t shamt[16];
_mm_store_si128(reinterpret_cast<__m128i*>(value), src1);
_mm_store_si128(reinterpret_cast<__m128i*>(shamt), src2);
for (size_t i = 0; i < 16; ++i) {
value[i] = value[i] >> (shamt[i] & 0x7);
}
return _mm_load_si128(reinterpret_cast<__m128i*>(value));
}
static __m128i EmulateVectorShaI16(void*, __m128i src1, __m128i src2) {
alignas(16) int16_t value[8];
alignas(16) int16_t shamt[8];
_mm_store_si128(reinterpret_cast<__m128i*>(value), src1);
_mm_store_si128(reinterpret_cast<__m128i*>(shamt), src2);
for (size_t i = 0; i < 8; ++i) {
value[i] = value[i] >> (shamt[i] & 0xF);
}
return _mm_load_si128(reinterpret_cast<__m128i*>(value));
}
static __m128i EmulateVectorShaI32(void*, __m128i src1, __m128i src2) {
alignas(16) int32_t value[4];
alignas(16) int32_t shamt[4];
_mm_store_si128(reinterpret_cast<__m128i*>(value), src1);
_mm_store_si128(reinterpret_cast<__m128i*>(shamt), src2);
for (size_t i = 0; i < 4; ++i) {
value[i] = value[i] >> (shamt[i] & 0x1F);
}
return _mm_load_si128(reinterpret_cast<__m128i*>(value));
}
static void Emit(X64Emitter& e, const EmitArgType& i) {
switch (i.instr->flags) {
case INT8_TYPE:
// TODO(benvanik): native version (with shift magic).
if (i.src2.is_constant) {
e.LoadConstantXmm(e.xmm0, i.src2.constant());
e.lea(e.r9, e.StashXmm(1, e.xmm0));
} else {
e.lea(e.r9, e.StashXmm(1, i.src2));
}
e.lea(e.r8, e.StashXmm(0, i.src1));
e.CallNativeSafe(reinterpret_cast<void*>(EmulateVectorShaI8));
e.vmovaps(i.dest, e.xmm0);
break;
case INT16_TYPE:
// TODO(benvanik): native version (with shift magic).
if (i.src2.is_constant) {
e.LoadConstantXmm(e.xmm0, i.src2.constant());
e.lea(e.r9, e.StashXmm(1, e.xmm0));
} else {
e.lea(e.r9, e.StashXmm(1, i.src2));
}
e.lea(e.r8, e.StashXmm(0, i.src1));
e.CallNativeSafe(reinterpret_cast<void*>(EmulateVectorShaI16));
e.vmovaps(i.dest, e.xmm0);
break;
case INT32_TYPE:
if (e.IsFeatureEnabled(kX64EmitAVX2)) {
// src shift mask may have values >31, and x86 sets to zero when
// that happens so we mask.
if (i.src2.is_constant) {
e.LoadConstantXmm(e.xmm0, i.src2.constant());
e.vandps(e.xmm0, e.GetXmmConstPtr(XMMShiftMaskPS));
} else {
e.vandps(e.xmm0, i.src2, e.GetXmmConstPtr(XMMShiftMaskPS));
}
e.vpsravd(i.dest, i.src1, e.xmm0);
} else {
// Emulated for now...
// TODO: Native version
if (i.src2.is_constant) {
e.LoadConstantXmm(e.xmm0, i.src2.constant());
e.lea(e.r9, e.StashXmm(1, e.xmm0));
} else {
e.lea(e.r9, e.StashXmm(1, i.src2));
}
e.lea(e.r8, e.StashXmm(0, i.src1));
e.CallNativeSafe(reinterpret_cast<void*>(EmulateVectorShaI32));
e.vmovaps(i.dest, e.xmm0);
}
break;
default:
assert_always();
break;
}
}
};
EMITTER_OPCODE_TABLE(
OPCODE_VECTOR_SHA,
VECTOR_SHA_V128);
// ============================================================================
// OPCODE_ROTATE_LEFT
// ============================================================================
// TODO(benvanik): put dest/src1 together, src2 in cl.
template <typename SEQ, typename REG, typename ARGS>
void EmitRotateLeftXX(X64Emitter& e, const ARGS& i) {
if (i.src2.is_constant) {
// Constant rotate.
if (i.dest != i.src1) {
if (i.src1.is_constant) {
e.mov(i.dest, i.src1.constant());
} else {
e.mov(i.dest, i.src1);
}
}
e.rol(i.dest, i.src2.constant());
} else {
// Variable rotate.
if (i.src2.reg().getIdx() != e.cl.getIdx()) {
e.mov(e.cl, i.src2);
}
if (i.dest != i.src1) {
if (i.src1.is_constant) {
e.mov(i.dest, i.src1.constant());
} else {
e.mov(i.dest, i.src1);
}
}
e.rol(i.dest, e.cl);
e.ReloadECX();
}
}
EMITTER(ROTATE_LEFT_I8, MATCH(I<OPCODE_ROTATE_LEFT, I8<>, I8<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitRotateLeftXX<ROTATE_LEFT_I8, Reg8>(e, i);
}
};
EMITTER(ROTATE_LEFT_I16, MATCH(I<OPCODE_ROTATE_LEFT, I16<>, I16<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitRotateLeftXX<ROTATE_LEFT_I16, Reg16>(e, i);
}
};
EMITTER(ROTATE_LEFT_I32, MATCH(I<OPCODE_ROTATE_LEFT, I32<>, I32<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitRotateLeftXX<ROTATE_LEFT_I32, Reg32>(e, i);
}
};
EMITTER(ROTATE_LEFT_I64, MATCH(I<OPCODE_ROTATE_LEFT, I64<>, I64<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitRotateLeftXX<ROTATE_LEFT_I64, Reg64>(e, i);
}
};
EMITTER_OPCODE_TABLE(
OPCODE_ROTATE_LEFT,
ROTATE_LEFT_I8,
ROTATE_LEFT_I16,
ROTATE_LEFT_I32,
ROTATE_LEFT_I64);
// ============================================================================
// OPCODE_VECTOR_ROTATE_LEFT
// ============================================================================
// TODO(benvanik): AVX512 has a native variable rotate (rolv).
EMITTER(VECTOR_ROTATE_LEFT_V128, MATCH(I<OPCODE_VECTOR_ROTATE_LEFT, V128<>, V128<>, V128<>>)) {
static __m128i EmulateVectorRotateLeftI8(void*, __m128i src1, __m128i src2) {
alignas(16) uint8_t value[16];
alignas(16) uint8_t shamt[16];
_mm_store_si128(reinterpret_cast<__m128i*>(value), src1);
_mm_store_si128(reinterpret_cast<__m128i*>(shamt), src2);
for (size_t i = 0; i < 16; ++i) {
value[i] = xe::rotate_left<uint8_t>(value[i], shamt[i] & 0x7);
}
return _mm_load_si128(reinterpret_cast<__m128i*>(value));
}
static __m128i EmulateVectorRotateLeftI16(void*, __m128i src1, __m128i src2) {
alignas(16) uint16_t value[8];
alignas(16) uint16_t shamt[8];
_mm_store_si128(reinterpret_cast<__m128i*>(value), src1);
_mm_store_si128(reinterpret_cast<__m128i*>(shamt), src2);
for (size_t i = 0; i < 8; ++i) {
value[i] = xe::rotate_left<uint16_t>(value[i], shamt[i] & 0xF);
}
return _mm_load_si128(reinterpret_cast<__m128i*>(value));
}
static __m128i EmulateVectorRotateLeftI32(void*, __m128i src1, __m128i src2) {
alignas(16) uint32_t value[4];
alignas(16) uint32_t shamt[4];
_mm_store_si128(reinterpret_cast<__m128i*>(value), src1);
_mm_store_si128(reinterpret_cast<__m128i*>(shamt), src2);
for (size_t i = 0; i < 4; ++i) {
value[i] = xe::rotate_left<uint32_t>(value[i], shamt[i] & 0x1F);
}
return _mm_load_si128(reinterpret_cast<__m128i*>(value));
}
static void Emit(X64Emitter& e, const EmitArgType& i) {
switch (i.instr->flags) {
case INT8_TYPE:
// TODO(benvanik): native version (with shift magic).
e.lea(e.r8, e.StashXmm(0, i.src1));
e.lea(e.r9, e.StashXmm(1, i.src2));
e.CallNativeSafe(reinterpret_cast<void*>(EmulateVectorRotateLeftI8));
e.vmovaps(i.dest, e.xmm0);
break;
case INT16_TYPE:
// TODO(benvanik): native version (with shift magic).
e.lea(e.r8, e.StashXmm(0, i.src1));
e.lea(e.r9, e.StashXmm(1, i.src2));
e.CallNativeSafe(reinterpret_cast<void*>(EmulateVectorRotateLeftI16));
e.vmovaps(i.dest, e.xmm0);
break;
case INT32_TYPE: {
if (e.IsFeatureEnabled(kX64EmitAVX2)) {
Xmm temp = i.dest;
if (i.dest == i.src1 || i.dest == i.src2) {
temp = e.xmm2;
}
// Shift left (to get high bits):
e.vpand(e.xmm0, i.src2, e.GetXmmConstPtr(XMMShiftMaskPS));
e.vpsllvd(e.xmm1, i.src1, e.xmm0);
// Shift right (to get low bits):
e.vmovaps(temp, e.GetXmmConstPtr(XMMPI32));
e.vpsubd(temp, e.xmm0);
e.vpsrlvd(i.dest, i.src1, temp);
// Merge:
e.vpor(i.dest, e.xmm1);
} else {
// TODO: Non-AVX2 native version
e.lea(e.r8, e.StashXmm(0, i.src1));
e.lea(e.r9, e.StashXmm(1, i.src2));
e.CallNativeSafe(reinterpret_cast<void*>(EmulateVectorRotateLeftI32));
e.vmovaps(i.dest, e.xmm0);
}
break;
}
default:
assert_always();
break;
}
}
};
EMITTER_OPCODE_TABLE(
OPCODE_VECTOR_ROTATE_LEFT,
VECTOR_ROTATE_LEFT_V128);
// ============================================================================
// OPCODE_VECTOR_AVERAGE
// ============================================================================
EMITTER(VECTOR_AVERAGE, MATCH(I<OPCODE_VECTOR_AVERAGE, V128<>, V128<>, V128<>>)) {
static __m128i EmulateVectorAverageUnsignedI32(void*, __m128i src1, __m128i src2) {
alignas(16) uint32_t src1v[4];
alignas(16) uint32_t src2v[4];
alignas(16) uint32_t value[4];
_mm_store_si128(reinterpret_cast<__m128i*>(src1v), src1);
_mm_store_si128(reinterpret_cast<__m128i*>(src2v), src2);
for (size_t i = 0; i < 4; ++i) {
auto t = (uint64_t(src1v[i]) + uint64_t(src2v[i]) + 1) >> 1;
value[i] = uint32_t(t);
}
return _mm_load_si128(reinterpret_cast<__m128i*>(value));
}
static __m128i EmulateVectorAverageSignedI32(void*, __m128i src1, __m128i src2) {
alignas(16) int32_t src1v[4];
alignas(16) int32_t src2v[4];
alignas(16) int32_t value[4];
_mm_store_si128(reinterpret_cast<__m128i*>(src1v), src1);
_mm_store_si128(reinterpret_cast<__m128i*>(src2v), src2);
for (size_t i = 0; i < 4; ++i) {
auto t = (int64_t(src1v[i]) + int64_t(src2v[i]) + 1) >> 1;
value[i] = int32_t(t);
}
return _mm_load_si128(reinterpret_cast<__m128i*>(value));
}
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitCommutativeBinaryXmmOp(e, i, [&i](X64Emitter& e, const Xmm& dest,
const Xmm& src1, const Xmm& src2) {
const TypeName part_type = static_cast<TypeName>(i.instr->flags & 0xFF);
const uint32_t arithmetic_flags = i.instr->flags >> 8;
bool is_unsigned = !!(arithmetic_flags & ARITHMETIC_UNSIGNED);
switch (part_type) {
case INT8_TYPE:
if (is_unsigned) {
e.vpavgb(dest, src1, src2);
} else {
assert_always();
}
break;
case INT16_TYPE:
if (is_unsigned) {
e.vpavgw(dest, src1, src2);
} else {
assert_always();
}
break;
case INT32_TYPE:
// No 32bit averages in AVX.
if (is_unsigned) {
e.lea(e.r8, e.StashXmm(0, i.src1));
e.lea(e.r9, e.StashXmm(1, i.src2));
e.CallNativeSafe(
reinterpret_cast<void*>(EmulateVectorAverageUnsignedI32));
e.vmovaps(i.dest, e.xmm0);
} else {
e.lea(e.r8, e.StashXmm(0, i.src1));
e.lea(e.r9, e.StashXmm(1, i.src2));
e.CallNativeSafe(
reinterpret_cast<void*>(EmulateVectorAverageSignedI32));
e.vmovaps(i.dest, e.xmm0);
}
break;
default:
assert_unhandled_case(part_type);
break;
}
});
}
};
EMITTER_OPCODE_TABLE(
OPCODE_VECTOR_AVERAGE,
VECTOR_AVERAGE);
// ============================================================================
// OPCODE_BYTE_SWAP
// ============================================================================
// TODO(benvanik): put dest/src1 together.
EMITTER(BYTE_SWAP_I16, MATCH(I<OPCODE_BYTE_SWAP, I16<>, I16<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitUnaryOp(
e, i,
[](X64Emitter& e, const Reg16& dest_src) { e.ror(dest_src, 8); });
}
};
EMITTER(BYTE_SWAP_I32, MATCH(I<OPCODE_BYTE_SWAP, I32<>, I32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitUnaryOp(
e, i,
[](X64Emitter& e, const Reg32& dest_src) { e.bswap(dest_src); });
}
};
EMITTER(BYTE_SWAP_I64, MATCH(I<OPCODE_BYTE_SWAP, I64<>, I64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitUnaryOp(
e, i,
[](X64Emitter& e, const Reg64& dest_src) { e.bswap(dest_src); });
}
};
EMITTER(BYTE_SWAP_V128, MATCH(I<OPCODE_BYTE_SWAP, V128<>, V128<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
// TODO(benvanik): find a way to do this without the memory load.
e.vpshufb(i.dest, i.src1, e.GetXmmConstPtr(XMMByteSwapMask));
}
};
EMITTER_OPCODE_TABLE(
OPCODE_BYTE_SWAP,
BYTE_SWAP_I16,
BYTE_SWAP_I32,
BYTE_SWAP_I64,
BYTE_SWAP_V128);
// ============================================================================
// OPCODE_CNTLZ
// Count leading zeroes
// ============================================================================
EMITTER(CNTLZ_I8, MATCH(I<OPCODE_CNTLZ, I8<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
if (e.IsFeatureEnabled(kX64EmitLZCNT)) {
// No 8bit lzcnt, so do 16 and sub 8.
e.movzx(i.dest.reg().cvt16(), i.src1);
e.lzcnt(i.dest.reg().cvt16(), i.dest.reg().cvt16());
e.sub(i.dest, 8);
} else {
Xbyak::Label jz, jend;
e.inLocalLabel();
// BSR: searches $2 until MSB 1 found, stores idx (from bit 0) in $1
// if input is 0, results are undefined (and ZF is set)
e.bsr(i.dest, i.src1);
e.jz(jz); // Jump if zero
// sub: $1 = $1 - $2
// Invert the result (7 - i.dest)
e.mov(e.eax, 7);
e.sub(e.eax, i.dest);
e.mov(i.dest, e.eax);
e.jmp(jend); // Jmp to end
// src1 was zero, so write 8 to the dest reg
e.L(jz);
e.mov(i.dest, 8);
e.L(jend);
e.outLocalLabel();
}
}
};
EMITTER(CNTLZ_I16, MATCH(I<OPCODE_CNTLZ, I8<>, I16<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
if (e.IsFeatureEnabled(kX64EmitLZCNT)) {
// LZCNT: searches $2 until MSB 1 found, stores idx (from last bit) in $1
e.lzcnt(i.dest.reg().cvt32(), i.src1);
} else {
Xbyak::Label jz, jend;
e.inLocalLabel();
// BSR: searches $2 until MSB 1 found, stores idx (from bit 0) in $1
// if input is 0, results are undefined (and ZF is set)
e.bsr(i.dest, i.src1);
e.jz(jz); // Jump if zero
// sub: $1 = $1 - $2
// Invert the result (15 - i.dest)
e.mov(e.eax, 15);
e.sub(e.eax, i.dest);
e.mov(i.dest, e.eax);
e.jmp(jend); // Jmp to end
// src1 was zero, so write 16 to the dest reg
e.L(jz);
e.mov(i.dest, 16);
e.L(jend);
e.outLocalLabel();
}
}
};
EMITTER(CNTLZ_I32, MATCH(I<OPCODE_CNTLZ, I8<>, I32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
if (e.IsFeatureEnabled(kX64EmitLZCNT)) {
e.lzcnt(i.dest.reg().cvt32(), i.src1);
} else {
Xbyak::Label jz, jend;
e.inLocalLabel();
// BSR: searches $2 until MSB 1 found, stores idx (from bit 0) in $1
// if input is 0, results are undefined (and ZF is set)
e.bsr(i.dest, i.src1);
e.jz(jz); // Jump if zero
// sub: $1 = $1 - $2
// Invert the result (31 - i.dest)
e.mov(e.eax, 31);
e.sub(e.eax, i.dest);
e.mov(i.dest, e.eax);
e.jmp(jend); // Jmp to end
// src1 was zero, so write 32 to the dest reg
e.L(jz);
e.mov(i.dest, 32);
e.L(jend);
e.outLocalLabel();
}
}
};
EMITTER(CNTLZ_I64, MATCH(I<OPCODE_CNTLZ, I8<>, I64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
if (e.IsFeatureEnabled(kX64EmitLZCNT)) {
e.lzcnt(i.dest.reg().cvt64(), i.src1);
} else {
Xbyak::Label jz, jend;
e.inLocalLabel();
// BSR: searches $2 until MSB 1 found, stores idx (from bit 0) in $1
// if input is 0, results are undefined (and ZF is set)
e.bsr(i.dest, i.src1);
e.jz(jz); // Jump if zero
// sub: $1 = $1 - $2
// Invert the result (63 - i.dest)
e.mov(e.rax, 63);
e.sub(e.rax, i.dest);
e.mov(i.dest, e.rax);
e.jmp(jend); // Jmp to end
// src1 was zero, so write 64 to the dest reg
e.L(jz);
e.mov(i.dest, 64);
e.L(jend);
e.outLocalLabel();
}
}
};
EMITTER_OPCODE_TABLE(
OPCODE_CNTLZ,
CNTLZ_I8,
CNTLZ_I16,
CNTLZ_I32,
CNTLZ_I64);
// ============================================================================
// OPCODE_INSERT
// ============================================================================
EMITTER(INSERT_I8, MATCH(I<OPCODE_INSERT, V128<>, V128<>, I8<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
assert_true(i.src2.is_constant);
e.vpinsrb(i.dest, i.src3.reg().cvt32(), i.src2.constant() ^ 0x3);
}
};
EMITTER(INSERT_I16, MATCH(I<OPCODE_INSERT, V128<>, V128<>, I8<>, I16<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
assert_true(i.src2.is_constant);
e.vpinsrw(i.dest, i.src3.reg().cvt32(), i.src2.constant() ^ 0x1);
}
};
EMITTER(INSERT_I32, MATCH(I<OPCODE_INSERT, V128<>, V128<>, I8<>, I32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
assert_true(i.src2.is_constant);
e.vpinsrd(i.dest, i.src3, i.src2.constant());
}
};
EMITTER_OPCODE_TABLE(
OPCODE_INSERT,
INSERT_I8,
INSERT_I16,
INSERT_I32);
// ============================================================================
// OPCODE_EXTRACT
// ============================================================================
// TODO(benvanik): sequence extract/splat:
// v0.i32 = extract v0.v128, 0
// v0.v128 = splat v0.i32
// This can be a single broadcast.
EMITTER(EXTRACT_I8, MATCH(I<OPCODE_EXTRACT, I8<>, V128<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
if (i.src2.is_constant) {
e.vpextrb(i.dest.reg().cvt32(), i.src1, VEC128_B(i.src2.constant()));
} else {
e.mov(e.eax, 0x00000003);
e.xor(e.al, i.src2);
e.and(e.al, 0x1F);
e.vmovd(e.xmm0, e.eax);
e.vpshufb(e.xmm0, i.src1, e.xmm0);
e.vmovd(i.dest.reg().cvt32(), e.xmm0);
e.and(i.dest, uint8_t(0xFF));
}
}
};
EMITTER(EXTRACT_I16, MATCH(I<OPCODE_EXTRACT, I16<>, V128<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
if (i.src2.is_constant) {
e.vpextrw(i.dest.reg().cvt32(), i.src1, VEC128_W(i.src2.constant()));
} else {
e.mov(e.al, i.src2);
e.xor(e.al, 0x01);
e.shl(e.al, 1);
e.mov(e.ah, e.al);
e.add(e.ah, 1);
e.vmovd(e.xmm0, e.eax);
e.vpshufb(e.xmm0, i.src1, e.xmm0);
e.vmovd(i.dest.reg().cvt32(), e.xmm0);
e.and(i.dest.reg().cvt32(), 0xFFFFu);
}
}
};
EMITTER(EXTRACT_I32, MATCH(I<OPCODE_EXTRACT, I32<>, V128<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
static const vec128_t extract_table_32[4] = {
vec128b( 3, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
vec128b( 7, 6, 5, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
vec128b(11, 10, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
vec128b(15, 14, 13, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
};
if (i.src2.is_constant) {
if (i.src2.constant() == 0) {
e.vmovd(i.dest, i.src1);
} else {
e.vpextrd(i.dest, i.src1, VEC128_D(i.src2.constant()));
}
} else {
// TODO(benvanik): try out hlide's version:
// e.mov(e.eax, 3);
// e.and(e.al, i.src2); // eax = [(i&3), 0, 0, 0]
// e.imul(e.eax, 0x04040404); // [(i&3)*4, (i&3)*4, (i&3)*4, (i&3)*4]
// e.add(e.eax, 0x00010203); // [((i&3)*4)+3, ((i&3)*4)+2, ((i&3)*4)+1, ((i&3)*4)+0]
// e.vmovd(e.xmm0, e.eax);
// e.vpshufb(e.xmm0, i.src1, e.xmm0);
// e.vmovd(i.dest.reg().cvt32(), e.xmm0);
// Get the desired word in xmm0, then extract that.
e.xor(e.rax, e.rax);
e.mov(e.al, i.src2);
e.and(e.al, 0x03);
e.shl(e.al, 4);
e.mov(e.rdx, reinterpret_cast<uint64_t>(extract_table_32));
e.vmovaps(e.xmm0, e.ptr[e.rdx + e.rax]);
e.vpshufb(e.xmm0, i.src1, e.xmm0);
e.vpextrd(i.dest, e.xmm0, 0);
e.ReloadEDX();
}
}
};
EMITTER_OPCODE_TABLE(
OPCODE_EXTRACT,
EXTRACT_I8,
EXTRACT_I16,
EXTRACT_I32);
// ============================================================================
// OPCODE_SPLAT
// ============================================================================
// Copy a value into all elements of a vector
EMITTER(SPLAT_I8, MATCH(I<OPCODE_SPLAT, V128<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
if (e.IsFeatureEnabled(kX64EmitAVX2)) {
if (i.src1.is_constant) {
// TODO(benvanik): faster constant splats.
e.mov(e.al, i.src1.constant());
e.vmovd(e.xmm0, e.eax);
e.vpbroadcastb(i.dest, e.xmm0);
} else {
e.vmovd(e.xmm0, i.src1.reg().cvt32());
e.vpbroadcastb(i.dest, e.xmm0);
}
} else {
if (i.src1.is_constant) {
e.mov(e.eax, i.src1.constant());
e.movd(e.xmm0, e.eax);
} else {
e.movd(e.xmm0, i.src1.reg().cvt32());
}
// Credits: VC++ compiler (i love you so much)
e.punpcklbw(e.xmm0, e.xmm0);
e.punpcklwd(e.xmm0, e.xmm0);
e.pshufd(i.dest, e.xmm0, 0);
}
}
};
EMITTER(SPLAT_I16, MATCH(I<OPCODE_SPLAT, V128<>, I16<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
if (e.IsFeatureEnabled(kX64EmitAVX2)) {
if (i.src1.is_constant) {
// TODO(benvanik): faster constant splats.
e.mov(e.ax, i.src1.constant());
e.vmovd(e.xmm0, e.eax);
e.vpbroadcastw(i.dest, e.xmm0);
} else {
e.vmovd(e.xmm0, i.src1.reg().cvt32());
e.vpbroadcastw(i.dest, e.xmm0);
}
} else {
if (i.src1.is_constant) {
e.mov(e.eax, i.src1.constant());
e.movd(e.xmm0, e.eax);
} else {
e.movd(e.xmm0, i.src1.reg().cvt32());
}
// Credits: VC++ compiler (i love you so much)
e.punpcklwd(e.xmm0, e.xmm0); // unpack low word data
e.pshufd(i.dest, e.xmm0, 0);
}
}
};
EMITTER(SPLAT_I32, MATCH(I<OPCODE_SPLAT, V128<>, I32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
if (e.IsFeatureEnabled(kX64EmitAVX2)) {
if (i.src1.is_constant) {
// TODO(benvanik): faster constant splats.
e.mov(e.eax, i.src1.constant());
e.vmovd(e.xmm0, e.eax);
e.vpbroadcastd(i.dest, e.xmm0);
} else {
e.vmovd(e.xmm0, i.src1);
e.vpbroadcastd(i.dest, e.xmm0);
}
} else {
if (i.src1.is_constant) {
e.mov(e.eax, i.src1.constant());
e.vmovd(e.xmm0, e.eax);
} else {
e.vmovd(e.xmm0, i.src1.reg().cvt32());
}
e.pshufd(i.dest, e.xmm0, 0);
}
}
};
EMITTER(SPLAT_F32, MATCH(I<OPCODE_SPLAT, V128<>, F32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
if (e.IsFeatureEnabled(kX64EmitAVX2)) {
if (i.src1.is_constant) {
// TODO(benvanik): faster constant splats.
e.mov(e.eax, i.src1.value->constant.i32);
e.vmovd(e.xmm0, e.eax);
e.vbroadcastss(i.dest, e.xmm0);
} else {
e.vbroadcastss(i.dest, i.src1);
}
} else {
if (i.src1.is_constant) {
e.mov(e.eax, i.src1.value->constant.i32);
e.vmovd(i.dest, e.eax);
} else {
e.vmovd(i.dest, i.src1.reg().cvt32());
}
e.shufps(i.dest, i.dest, 0);
}
}
};
EMITTER_OPCODE_TABLE(
OPCODE_SPLAT,
SPLAT_I8,
SPLAT_I16,
SPLAT_I32,
SPLAT_F32);
// ============================================================================
// OPCODE_PERMUTE
// ============================================================================
EMITTER(PERMUTE_I32, MATCH(I<OPCODE_PERMUTE, V128<>, I32<>, V128<>, V128<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
assert_true(i.instr->flags == INT32_TYPE);
// Permute words between src2 and src3.
// TODO(benvanik): check src3 for zero. if 0, we can use pshufb.
if (i.src1.is_constant) {
uint32_t control = i.src1.constant();
// Shuffle things into the right places in dest & xmm0,
// then we blend them together.
uint32_t src_control =
(((control >> 24) & 0x3) << 6) |
(((control >> 16) & 0x3) << 4) |
(((control >> 8) & 0x3) << 2) |
(((control >> 0) & 0x3) << 0);
uint32_t blend_control = 0;
if (e.IsFeatureEnabled(kX64EmitAVX2)) {
// Blender for vpblendd
blend_control =
(((control >> 26) & 0x1) << 3) |
(((control >> 18) & 0x1) << 2) |
(((control >> 10) & 0x1) << 1) |
(((control >> 2) & 0x1) << 0);
} else {
// Blender for vpblendw
blend_control =
(((control >> 26) & 0x1) << 6) |
(((control >> 18) & 0x1) << 4) |
(((control >> 10) & 0x1) << 2) |
(((control >> 2) & 0x1) << 0);
blend_control |= blend_control << 1;
}
// TODO(benvanik): if src2/src3 are constants, shuffle now!
Xmm src2;
if (i.src2.is_constant) {
src2 = e.xmm1;
e.LoadConstantXmm(src2, i.src2.constant());
} else {
src2 = i.src2;
}
Xmm src3;
if (i.src3.is_constant) {
src3 = e.xmm2;
e.LoadConstantXmm(src3, i.src3.constant());
} else {
src3 = i.src3;
}
if (i.dest != src3) {
e.vpshufd(i.dest, src2, src_control);
e.vpshufd(e.xmm0, src3, src_control);
} else {
e.vmovaps(e.xmm0, src3);
e.vpshufd(i.dest, src2, src_control);
e.vpshufd(e.xmm0, e.xmm0, src_control);
}
if (e.IsFeatureEnabled(kX64EmitAVX2)) {
e.vpblendd(i.dest, e.xmm0, blend_control); // $0 = $1 <blend> $2
} else {
e.vpblendw(i.dest, e.xmm0, blend_control); // $0 = $1 <blend> $2
}
} else {
// Permute by non-constant.
assert_always();
}
}
};
EMITTER(PERMUTE_V128, MATCH(I<OPCODE_PERMUTE, V128<>, V128<>, V128<>, V128<>>)) {
static void EmitByInt8(X64Emitter& e, const EmitArgType& i) {
// TODO(benvanik): find out how to do this with only one temp register!
// Permute bytes between src2 and src3.
if (i.src3.value->IsConstantZero()) {
// Permuting with src2/zero, so just shuffle/mask.
if (i.src2.value->IsConstantZero()) {
// src2 & src3 are zero, so result will always be zero.
e.vpxor(i.dest, i.dest);
} else {
// Control mask needs to be shuffled.
if (i.src1.is_constant) {
e.LoadConstantXmm(e.xmm0, i.src1.constant());
e.vxorps(e.xmm0, e.xmm0, e.GetXmmConstPtr(XMMSwapWordMask));
} else {
e.vxorps(e.xmm0, i.src1, e.GetXmmConstPtr(XMMSwapWordMask));
}
e.vpand(e.xmm0, e.GetXmmConstPtr(XMMPermuteByteMask));
if (i.src2.is_constant) {
e.LoadConstantXmm(i.dest, i.src2.constant());
e.vpshufb(i.dest, i.dest, e.xmm0);
} else {
e.vpshufb(i.dest, i.src2, e.xmm0);
}
// Build a mask with values in src2 having 0 and values in src3 having 1.
e.vpcmpgtb(e.xmm0, e.xmm0, e.GetXmmConstPtr(XMMPermuteControl15));
e.vpandn(i.dest, e.xmm0, i.dest);
}
} else {
// General permute.
// Control mask needs to be shuffled.
// TODO(benvanik): do constants here instead of in generated code.
if (i.src1.is_constant) {
e.LoadConstantXmm(e.xmm2, i.src1.constant());
e.vxorps(e.xmm2, e.xmm2, e.GetXmmConstPtr(XMMSwapWordMask));
} else {
e.vxorps(e.xmm2, i.src1, e.GetXmmConstPtr(XMMSwapWordMask));
}
e.vpand(e.xmm2, e.GetXmmConstPtr(XMMPermuteByteMask));
Xmm src2_shuf = e.xmm0;
if (i.src2.value->IsConstantZero()) {
e.vpxor(src2_shuf, src2_shuf);
} else if (i.src2.is_constant) {
e.LoadConstantXmm(src2_shuf, i.src2.constant());
e.vpshufb(src2_shuf, src2_shuf, e.xmm2);
} else {
e.vpshufb(src2_shuf, i.src2, e.xmm2);
}
Xmm src3_shuf = e.xmm1;
if (i.src3.value->IsConstantZero()) {
e.vpxor(src3_shuf, src3_shuf);
} else if (i.src3.is_constant) {
e.LoadConstantXmm(src3_shuf, i.src3.constant());
e.vpshufb(src3_shuf, src3_shuf, e.xmm2);
} else {
e.vpshufb(src3_shuf, i.src3, e.xmm2);
}
// Build a mask with values in src2 having 0 and values in src3 having 1.
e.vpcmpgtb(i.dest, e.xmm2, e.GetXmmConstPtr(XMMPermuteControl15));
e.vpblendvb(i.dest, src2_shuf, src3_shuf, i.dest);
}
}
static __m128i EmulateByInt16(void*, __m128i control, __m128i src1, __m128i src2) {
alignas(16) uint16_t c[8];
alignas(16) uint16_t a[8];
alignas(16) uint16_t b[8];
_mm_store_si128(reinterpret_cast<__m128i*>(c), control);
_mm_store_si128(reinterpret_cast<__m128i*>(a), src1);
_mm_store_si128(reinterpret_cast<__m128i*>(b), src2);
for (size_t i = 0; i < 8; ++i) {
uint16_t si = (c[i] & 0xF) ^ 0x1;
c[i] = si >= 8 ? b[si - 8] : a[si];
}
return _mm_load_si128(reinterpret_cast<__m128i*>(c));
}
static void EmitByInt16(X64Emitter& e, const EmitArgType& i) {
// TODO(benvanik): replace with proper version.
assert_true(i.src1.is_constant);
if (i.src1.is_constant) {
e.LoadConstantXmm(e.xmm0, i.src1.constant());
e.lea(e.r8, e.StashXmm(0, e.xmm0));
} else {
e.lea(e.r8, e.StashXmm(0, i.src1));
}
if (i.src2.is_constant) {
e.LoadConstantXmm(e.xmm0, i.src2.constant());
e.lea(e.r9, e.StashXmm(1, e.xmm0));
} else {
e.lea(e.r9, e.StashXmm(1, i.src2));
}
if (i.src3.is_constant) {
e.LoadConstantXmm(e.xmm0, i.src3.constant());
e.lea(e.r10, e.StashXmm(2, e.xmm0));
} else {
e.lea(e.r10, e.StashXmm(2, i.src3));
}
e.CallNativeSafe(reinterpret_cast<void*>(EmulateByInt16));
e.vmovaps(i.dest, e.xmm0);
}
static void EmitByInt32(X64Emitter& e, const EmitArgType& i) {
assert_always();
}
static void Emit(X64Emitter& e, const EmitArgType& i) {
switch (i.instr->flags) {
case INT8_TYPE:
EmitByInt8(e, i);
break;
case INT16_TYPE:
EmitByInt16(e, i);
break;
case INT32_TYPE:
EmitByInt32(e, i);
break;
default:
assert_unhandled_case(i.instr->flags);
return;
}
}
};
EMITTER_OPCODE_TABLE(
OPCODE_PERMUTE,
PERMUTE_I32,
PERMUTE_V128);
// ============================================================================
// OPCODE_SWIZZLE
// ============================================================================
EMITTER(SWIZZLE, MATCH(I<OPCODE_SWIZZLE, V128<>, V128<>, OffsetOp>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
auto element_type = i.instr->flags;
if (element_type == INT8_TYPE) {
assert_always();
} else if (element_type == INT16_TYPE) {
assert_always();
} else if (element_type == INT32_TYPE || element_type == FLOAT32_TYPE) {
uint8_t swizzle_mask = static_cast<uint8_t>(i.src2.value);
e.vpshufd(i.dest, i.src1, swizzle_mask);
} else if (element_type == INT64_TYPE || element_type == FLOAT64_TYPE) {
assert_always();
} else {
assert_always();
}
}
};
EMITTER_OPCODE_TABLE(
OPCODE_SWIZZLE,
SWIZZLE);
// ============================================================================
// OPCODE_PACK
// ============================================================================
EMITTER(PACK, MATCH(I<OPCODE_PACK, V128<>, V128<>, V128<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
switch (i.instr->flags & PACK_TYPE_MODE) {
case PACK_TYPE_D3DCOLOR:
EmitD3DCOLOR(e, i);
break;
case PACK_TYPE_FLOAT16_2:
EmitFLOAT16_2(e, i);
break;
case PACK_TYPE_FLOAT16_4:
EmitFLOAT16_4(e, i);
break;
case PACK_TYPE_SHORT_2:
EmitSHORT_2(e, i);
break;
case PACK_TYPE_8_IN_16:
Emit8_IN_16(e, i, i.instr->flags);
break;
case PACK_TYPE_16_IN_32:
Emit16_IN_32(e, i, i.instr->flags);
break;
default: assert_unhandled_case(i.instr->flags); break;
}
}
static void EmitD3DCOLOR(X64Emitter& e, const EmitArgType& i) {
assert_true(i.src2.value->IsConstantZero());
// Saturate to [3,3....] so that only values between 3...[00] and 3...[FF]
// are valid.
if (i.src1.is_constant) {
e.LoadConstantXmm(i.dest, i.src1.constant());
e.vminps(i.dest, i.dest, e.GetXmmConstPtr(XMMPackD3DCOLORSat));
} else {
e.vminps(i.dest, i.src1, e.GetXmmConstPtr(XMMPackD3DCOLORSat));
}
e.vmaxps(i.dest, i.dest, e.GetXmmConstPtr(XMM3333));
// Extract bytes.
// RGBA (XYZW) -> ARGB (WXYZ)
// w = ((src1.uw & 0xFF) << 24) | ((src1.ux & 0xFF) << 16) |
// ((src1.uy & 0xFF) << 8) | (src1.uz & 0xFF)
e.vpshufb(i.dest, i.dest, e.GetXmmConstPtr(XMMPackD3DCOLOR));
}
static void EmitFLOAT16_2(X64Emitter& e, const EmitArgType& i) {
assert_true(i.src2.value->IsConstantZero());
// http://blogs.msdn.com/b/chuckw/archive/2012/09/11/directxmath-f16c-and-fma.aspx
// dest = [(src1.x | src1.y), 0, 0, 0]
// 0|0|0|0|W|Z|Y|X
e.vcvtps2ph(i.dest, i.dest, B00000011);
// Shuffle to X|Y|0|0|0|0|0|0
e.vpshufb(i.dest, i.dest, e.GetXmmConstPtr(XMMPackFLOAT16_2));
}
static void EmitFLOAT16_4(X64Emitter& e, const EmitArgType& i) {
assert_true(i.src2.value->IsConstantZero());
// dest = [(src1.x | src1.y), (src1.z | src1.w), 0, 0]
// 0|0|0|0|W|Z|Y|X
e.vcvtps2ph(i.dest, i.src1, B00000011);
// Shuffle to X|Y|Z|W|0|0|0|0
e.vpshufb(i.dest, i.dest, e.GetXmmConstPtr(XMMPackFLOAT16_4));
}
static void EmitSHORT_2(X64Emitter& e, const EmitArgType& i) {
assert_true(i.src2.value->IsConstantZero());
// Saturate.
e.vmaxps(i.dest, i.src1, e.GetXmmConstPtr(XMMPackSHORT_2Min));
e.vminps(i.dest, i.dest, e.GetXmmConstPtr(XMMPackSHORT_2Max));
// Pack.
e.vpshufb(i.dest, i.dest, e.GetXmmConstPtr(XMMPackSHORT_2));
}
static __m128i EmulatePack8_IN_16_UN_UN_SAT(void*, __m128i src1,
__m128i src2) {
alignas(16) uint16_t a[8];
alignas(16) uint16_t b[8];
alignas(16) uint8_t c[16];
_mm_store_si128(reinterpret_cast<__m128i*>(a), src1);
_mm_store_si128(reinterpret_cast<__m128i*>(b), src2);
for (int i = 0; i < 8; ++i) {
c[i] = uint8_t(std::max(uint16_t(0), std::min(uint16_t(255), a[i])));
c[i + 8] = uint8_t(std::max(uint16_t(0), std::min(uint16_t(255), b[i])));
}
return _mm_load_si128(reinterpret_cast<__m128i*>(c));
}
static void Emit8_IN_16(X64Emitter& e, const EmitArgType& i, uint32_t flags) {
// TODO(benvanik): handle src2 (or src1) being constant zero
if (IsPackInUnsigned(flags)) {
if (IsPackOutUnsigned(flags)) {
if (IsPackOutSaturate(flags)) {
// unsigned -> unsigned + saturate
if (i.src2.is_constant) {
e.LoadConstantXmm(e.xmm0, i.src2.constant());
e.lea(e.r9, e.StashXmm(1, e.xmm0));
} else {
e.lea(e.r9, e.StashXmm(1, i.src2));
}
e.lea(e.r8, e.StashXmm(0, i.src1));
e.CallNativeSafe(
reinterpret_cast<void*>(EmulatePack8_IN_16_UN_UN_SAT));
e.vmovaps(i.dest, e.xmm0);
} else {
// unsigned -> unsigned
assert_always();
}
} else {
if (IsPackOutSaturate(flags)) {
// unsigned -> signed + saturate
assert_always();
} else {
// unsigned -> signed
assert_always();
}
}
} else {
if (IsPackOutUnsigned(flags)) {
if (IsPackOutSaturate(flags)) {
// signed -> unsigned + saturate
// PACKUSWB / SaturateSignedWordToUnsignedByte
e.vpackuswb(i.dest, i.src1, i.src2);
e.vpshufb(i.dest, i.dest, e.GetXmmConstPtr(XMMByteOrderMask));
} else {
// signed -> unsigned
assert_always();
}
} else {
if (IsPackOutSaturate(flags)) {
// signed -> signed + saturate
// PACKSSWB / SaturateSignedWordToSignedByte
e.vpacksswb(i.dest, i.src1, i.src2);
e.vpshufb(i.dest, i.dest, e.GetXmmConstPtr(XMMByteOrderMask));
} else {
// signed -> signed
assert_always();
}
}
}
}
static void Emit16_IN_32(X64Emitter& e, const EmitArgType& i, uint32_t flags) {
// TODO(benvanik): handle src2 (or src1) being constant zero
if (IsPackInUnsigned(flags)) {
if (IsPackOutUnsigned(flags)) {
if (IsPackOutSaturate(flags)) {
// unsigned -> unsigned + saturate
assert_always();
} else {
// unsigned -> unsigned
assert_always();
}
} else {
if (IsPackOutSaturate(flags)) {
// unsigned -> signed + saturate
assert_always();
} else {
// unsigned -> signed
assert_always();
}
}
} else {
if (IsPackOutUnsigned(flags)) {
if (IsPackOutSaturate(flags)) {
// signed -> unsigned + saturate
// PACKUSDW
// TMP[15:0] <- (DEST[31:0] < 0) ? 0 : DEST[15:0];
// DEST[15:0] <- (DEST[31:0] > FFFFH) ? FFFFH : TMP[15:0];
e.vpackusdw(i.dest, i.src1, i.src2);
e.vpshuflw(i.dest, i.dest, B10110001);
e.vpshufhw(i.dest, i.dest, B10110001);
} else {
// signed -> unsigned
assert_always();
}
} else {
if (IsPackOutSaturate(flags)) {
// signed -> signed + saturate
// PACKSSDW / SaturateSignedDwordToSignedWord
e.vpackssdw(i.dest, i.src1, i.src2);
e.vpshuflw(i.dest, i.dest, B10110001);
e.vpshufhw(i.dest, i.dest, B10110001);
} else {
// signed -> signed
assert_always();
}
}
}
}
};
EMITTER_OPCODE_TABLE(
OPCODE_PACK,
PACK);
// ============================================================================
// OPCODE_UNPACK
// ============================================================================
EMITTER(UNPACK, MATCH(I<OPCODE_UNPACK, V128<>, V128<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
switch (i.instr->flags & PACK_TYPE_MODE) {
case PACK_TYPE_D3DCOLOR:
EmitD3DCOLOR(e, i);
break;
case PACK_TYPE_FLOAT16_2:
EmitFLOAT16_2(e, i);
break;
case PACK_TYPE_FLOAT16_4:
EmitFLOAT16_4(e, i);
break;
case PACK_TYPE_SHORT_2:
EmitSHORT_2(e, i);
break;
case PACK_TYPE_8_IN_16:
Emit8_IN_16(e, i, i.instr->flags);
break;
case PACK_TYPE_16_IN_32:
Emit16_IN_32(e, i, i.instr->flags);
break;
default: assert_unhandled_case(i.instr->flags); break;
}
}
static void EmitD3DCOLOR(X64Emitter& e, const EmitArgType& i) {
// ARGB (WXYZ) -> RGBA (XYZW)
// XMLoadColor
if (i.src1.is_constant) {
if (i.src1.value->IsConstantZero()) {
e.vmovaps(i.dest, e.GetXmmConstPtr(XMMOne));
return;
} else {
assert_always();
}
}
// src = ZZYYXXWW
// Unpack to 000000ZZ,000000YY,000000XX,000000WW
e.vpshufb(i.dest, i.src1, e.GetXmmConstPtr(XMMUnpackD3DCOLOR));
// Add 1.0f to each.
e.vpor(i.dest, e.GetXmmConstPtr(XMMOne));
}
static void EmitFLOAT16_2(X64Emitter& e, const EmitArgType& i) {
// 1 bit sign, 5 bit exponent, 10 bit mantissa
// D3D10 half float format
// TODO(benvanik): http://blogs.msdn.com/b/chuckw/archive/2012/09/11/directxmath-f16c-and-fma.aspx
// Use _mm_cvtph_ps -- requires very modern processors (SSE5+)
// Unpacking half floats: http://fgiesen.wordpress.com/2012/03/28/half-to-float-done-quic/
// Packing half floats: https://gist.github.com/rygorous/2156668
// Load source, move from tight pack of X16Y16.... to X16...Y16...
// Also zero out the high end.
// TODO(benvanik): special case constant unpacks that just get 0/1/etc.
// sx = src.iw >> 16;
// sy = src.iw & 0xFFFF;
// dest = { XMConvertHalfToFloat(sx),
// XMConvertHalfToFloat(sy),
// 0.0,
// 1.0 };
// Shuffle to 0|0|0|0|0|0|Y|X
e.vpshufb(i.dest, i.src1, e.GetXmmConstPtr(XMMUnpackFLOAT16_2));
e.vcvtph2ps(i.dest, i.dest);
e.vpshufd(i.dest, i.dest, B10100100);
e.vpor(i.dest, e.GetXmmConstPtr(XMM0001));
}
static void EmitFLOAT16_4(X64Emitter& e, const EmitArgType& i) {
// src = [(dest.x | dest.y), (dest.z | dest.w), 0, 0]
// Shuffle to 0|0|0|0|W|Z|Y|X
e.vpshufb(i.dest, i.src1, e.GetXmmConstPtr(XMMUnpackFLOAT16_4));
e.vcvtph2ps(i.dest, i.dest);
}
static void EmitSHORT_2(X64Emitter& e, const EmitArgType& i) {
// (VD.x) = 3.0 + (VB.x>>16)*2^-22
// (VD.y) = 3.0 + (VB.x)*2^-22
// (VD.z) = 0.0
// (VD.w) = 1.0
// XMLoadShortN2 plus 3,3,0,3 (for some reason)
// src is (xx,xx,xx,VALUE)
// (VALUE,VALUE,VALUE,VALUE)
Xmm src;
if (i.src1.is_constant) {
if (i.src1.value->IsConstantZero()) {
e.vmovdqa(i.dest, e.GetXmmConstPtr(XMM3301));
return;
} else {
// TODO(benvanik): check other common constants/perform shuffle/or here.
src = e.xmm0;
e.LoadConstantXmm(src, i.src1.constant());
}
} else {
src = i.src1;
}
// Shuffle bytes.
e.vpshufb(i.dest, src, e.GetXmmConstPtr(XMMUnpackSHORT_2));
// Sign extend words.
e.vpslld(i.dest, 16);
e.vpsrad(i.dest, 16);
// Add 3,3,0,1.
e.vpaddd(i.dest, e.GetXmmConstPtr(XMM3301));
}
static void Emit8_IN_16(X64Emitter& e, const EmitArgType& i, uint32_t flags) {
assert_false(IsPackOutSaturate(flags));
if (IsPackToLo(flags)) {
// Unpack to LO.
if (IsPackInUnsigned(flags)) {
if (IsPackOutUnsigned(flags)) {
// unsigned -> unsigned
assert_always();
} else {
// unsigned -> signed
assert_always();
}
} else {
if (IsPackOutUnsigned(flags)) {
// signed -> unsigned
assert_always();
} else {
// signed -> signed
e.vpunpckhbw(i.dest, i.src1, i.src1);
e.vpsrad(i.dest, 8);
}
}
} else {
// Unpack to HI.
if (IsPackInUnsigned(flags)) {
if (IsPackOutUnsigned(flags)) {
// unsigned -> unsigned
assert_always();
} else {
// unsigned -> signed
assert_always();
}
} else {
if (IsPackOutUnsigned(flags)) {
// signed -> unsigned
assert_always();
} else {
// signed -> signed
e.vpunpcklbw(i.dest, i.src1, i.src1);
e.vpsrad(i.dest, 8);
}
}
}
}
static void Emit16_IN_32(X64Emitter& e, const EmitArgType& i, uint32_t flags) {
assert_false(IsPackOutSaturate(flags));
if (IsPackToLo(flags)) {
// Unpack to LO.
if (IsPackInUnsigned(flags)) {
if (IsPackOutUnsigned(flags)) {
// unsigned -> unsigned
assert_always();
} else {
// unsigned -> signed
assert_always();
}
} else {
if (IsPackOutUnsigned(flags)) {
// signed -> unsigned
assert_always();
} else {
// signed -> signed
e.vpunpckhwd(i.dest, i.src1, i.src1);
e.vpsrad(i.dest, 16);
}
}
} else {
// Unpack to HI.
if (IsPackInUnsigned(flags)) {
if (IsPackOutUnsigned(flags)) {
// unsigned -> unsigned
assert_always();
} else {
// unsigned -> signed
assert_always();
}
} else {
if (IsPackOutUnsigned(flags)) {
// signed -> unsigned
assert_always();
} else {
// signed -> signed
e.vpunpcklwd(i.dest, i.src1, i.src1);
e.vpsrad(i.dest, 16);
}
}
}
e.vpshufd(i.dest, i.dest, 0xB1);
}
};
EMITTER_OPCODE_TABLE(
OPCODE_UNPACK,
UNPACK);
// ============================================================================
// OPCODE_COMPARE_EXCHANGE
// ============================================================================
// ============================================================================
// OPCODE_ATOMIC_EXCHANGE
// ============================================================================
// Note that the address we use here is a real, host address!
// This is weird, and should be fixed.
template <typename SEQ, typename REG, typename ARGS>
void EmitAtomicExchangeXX(X64Emitter& e, const ARGS& i) {
if (i.dest == i.src1) {
e.mov(e.rax, i.src1);
if (i.dest != i.src2) {
if (i.src2.is_constant) {
e.mov(i.dest, i.src2.constant());
} else {
e.mov(i.dest, i.src2);
}
}
e.lock();
e.xchg(e.dword[e.rax], i.dest);
} else {
if (i.dest != i.src2) {
if (i.src2.is_constant) {
e.mov(i.dest, i.src2.constant());
} else {
e.mov(i.dest, i.src2);
}
}
e.lock();
e.xchg(e.dword[i.src1.reg()], i.dest);
}
}
EMITTER(ATOMIC_EXCHANGE_I8, MATCH(I<OPCODE_ATOMIC_EXCHANGE, I8<>, I64<>, I8<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitAtomicExchangeXX<ATOMIC_EXCHANGE_I8, Reg8>(e, i);
}
};
EMITTER(ATOMIC_EXCHANGE_I16, MATCH(I<OPCODE_ATOMIC_EXCHANGE, I16<>, I64<>, I16<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitAtomicExchangeXX<ATOMIC_EXCHANGE_I16, Reg16>(e, i);
}
};
EMITTER(ATOMIC_EXCHANGE_I32, MATCH(I<OPCODE_ATOMIC_EXCHANGE, I32<>, I64<>, I32<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitAtomicExchangeXX<ATOMIC_EXCHANGE_I32, Reg32>(e, i);
}
};
EMITTER(ATOMIC_EXCHANGE_I64, MATCH(I<OPCODE_ATOMIC_EXCHANGE, I64<>, I64<>, I64<>>)) {
static void Emit(X64Emitter& e, const EmitArgType& i) {
EmitAtomicExchangeXX<ATOMIC_EXCHANGE_I64, Reg64>(e, i);
}
};
EMITTER_OPCODE_TABLE(
OPCODE_ATOMIC_EXCHANGE,
ATOMIC_EXCHANGE_I8,
ATOMIC_EXCHANGE_I16,
ATOMIC_EXCHANGE_I32,
ATOMIC_EXCHANGE_I64);
// ============================================================================
// OPCODE_ATOMIC_ADD
// ============================================================================
// ============================================================================
// OPCODE_ATOMIC_SUB
// ============================================================================
//SEQUENCE(ADD_ADD_BRANCH, MATCH(
// I<OPCODE_ADD, I32<TAG0>, I32<>, I32C<>>,
// I<OPCODE_ADD, I32<>, I32<TAG0>, I32C<>>,
// I<OPCODE_BRANCH_TRUE, VoidOp, OffsetOp>)) {
// static void Emit(X64Emitter& e, const EmitArgs& _) {
// }
//};
void RegisterSequences() {
#define REGISTER_EMITTER_OPCODE_TABLE(opcode) Register_##opcode()
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_COMMENT);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_NOP);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_SOURCE_OFFSET);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_DEBUG_BREAK);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_DEBUG_BREAK_TRUE);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_TRAP);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_TRAP_TRUE);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_CALL);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_CALL_TRUE);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_CALL_INDIRECT);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_CALL_INDIRECT_TRUE);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_CALL_EXTERN);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_RETURN);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_RETURN_TRUE);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_SET_RETURN_ADDRESS);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_BRANCH);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_BRANCH_TRUE);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_BRANCH_FALSE);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_ASSIGN);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_CAST);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_ZERO_EXTEND);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_SIGN_EXTEND);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_TRUNCATE);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_CONVERT);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_ROUND);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_VECTOR_CONVERT_I2F);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_VECTOR_CONVERT_F2I);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_LOAD_VECTOR_SHL);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_LOAD_VECTOR_SHR);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_LOAD_CLOCK);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_LOAD_LOCAL);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_STORE_LOCAL);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_LOAD_CONTEXT);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_STORE_CONTEXT);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_LOAD);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_STORE);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_MEMSET);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_PREFETCH);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_MAX);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_VECTOR_MAX);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_MIN);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_VECTOR_MIN);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_SELECT);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_IS_TRUE);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_IS_FALSE);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_COMPARE_EQ);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_COMPARE_NE);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_COMPARE_SLT);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_COMPARE_SLE);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_COMPARE_SGT);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_COMPARE_SGE);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_COMPARE_ULT);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_COMPARE_ULE);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_COMPARE_UGT);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_COMPARE_UGE);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_COMPARE_SLT_FLT);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_COMPARE_SLE_FLT);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_COMPARE_SGT_FLT);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_COMPARE_SGE_FLT);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_COMPARE_ULT_FLT);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_COMPARE_ULE_FLT);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_COMPARE_UGT_FLT);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_COMPARE_UGE_FLT);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_DID_CARRY);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_DID_OVERFLOW);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_DID_SATURATE);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_VECTOR_COMPARE_EQ);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_VECTOR_COMPARE_SGT);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_VECTOR_COMPARE_SGE);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_VECTOR_COMPARE_UGT);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_VECTOR_COMPARE_UGE);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_ADD);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_ADD_CARRY);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_VECTOR_ADD);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_SUB);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_VECTOR_SUB);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_MUL);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_MUL_HI);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_DIV);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_MUL_ADD);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_MUL_SUB);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_NEG);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_ABS);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_SQRT);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_RSQRT);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_POW2);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_LOG2);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_DOT_PRODUCT_3);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_DOT_PRODUCT_4);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_AND);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_OR);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_XOR);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_NOT);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_SHL);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_SHR);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_SHA);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_VECTOR_SHL);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_VECTOR_SHR);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_VECTOR_SHA);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_ROTATE_LEFT);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_VECTOR_ROTATE_LEFT);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_VECTOR_AVERAGE);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_BYTE_SWAP);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_CNTLZ);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_INSERT);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_EXTRACT);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_SPLAT);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_PERMUTE);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_SWIZZLE);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_PACK);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_UNPACK);
//REGISTER_EMITTER_OPCODE_TABLE(OPCODE_COMPARE_EXCHANGE);
REGISTER_EMITTER_OPCODE_TABLE(OPCODE_ATOMIC_EXCHANGE);
//REGISTER_EMITTER_OPCODE_TABLE(OPCODE_ATOMIC_ADD);
//REGISTER_EMITTER_OPCODE_TABLE(OPCODE_ATOMIC_SUB);
}
bool SelectSequence(X64Emitter& e, const Instr* i, const Instr** new_tail) {
const InstrKey key(i);
const auto its = sequence_table.equal_range(key);
for (auto it = its.first; it != its.second; ++it) {
if (it->second(e, i, new_tail)) {
return true;
}
}
XELOGE("No sequence match for variant %s", i->opcode->name);
return false;
}
} // namespace x64
} // namespace backend
} // namespace cpu
} // namespace xe
| 33.302717
| 111
| 0.558709
|
Parovozik
|
6041c1602d4b8f6fe2f3fa0c7022fda3e47b6808
| 351
|
cpp
|
C++
|
Source/GASExtensions/Private/GASExtensionsModule.cpp
|
TheEmidee/UEGASExtensions
|
8851dbaf9251ecdc914f381df161484a7c5d4275
|
[
"MIT"
] | null | null | null |
Source/GASExtensions/Private/GASExtensionsModule.cpp
|
TheEmidee/UEGASExtensions
|
8851dbaf9251ecdc914f381df161484a7c5d4275
|
[
"MIT"
] | null | null | null |
Source/GASExtensions/Private/GASExtensionsModule.cpp
|
TheEmidee/UEGASExtensions
|
8851dbaf9251ecdc914f381df161484a7c5d4275
|
[
"MIT"
] | null | null | null |
#include "GASExtensionsModule.h"
class FGASExtensionsModule final : public IGASExtensionsModule
{
public:
void StartupModule() override;
void ShutdownModule() override;
};
IMPLEMENT_MODULE( FGASExtensionsModule, GASExtensions )
void FGASExtensionsModule::StartupModule()
{
}
void FGASExtensionsModule::ShutdownModule()
{
}
| 19.5
| 63
| 0.752137
|
TheEmidee
|
6044713e56ade6398b42c7d010088a01f748f6ca
| 6,377
|
cpp
|
C++
|
src/wasm_ql_pg_plugin.cpp
|
swang-b1/history-tools
|
7ca8e1c6ee35c0b5bd3ad6f5236a00d083887644
|
[
"MIT"
] | 54
|
2019-04-03T11:10:42.000Z
|
2022-03-07T06:18:50.000Z
|
src/wasm_ql_pg_plugin.cpp
|
swang-b1/history-tools
|
7ca8e1c6ee35c0b5bd3ad6f5236a00d083887644
|
[
"MIT"
] | 69
|
2019-05-22T16:07:27.000Z
|
2022-03-29T18:14:20.000Z
|
src/wasm_ql_pg_plugin.cpp
|
swang-b1/history-tools
|
7ca8e1c6ee35c0b5bd3ad6f5236a00d083887644
|
[
"MIT"
] | 47
|
2019-04-18T07:26:56.000Z
|
2022-01-26T13:01:37.000Z
|
// copyright defined in LICENSE.txt
#include "wasm_ql_pg_plugin.hpp"
#include "state_history_pg.hpp"
#include "util.hpp"
#include <fc/exception/exception.hpp>
using namespace appbase;
namespace pg = state_history::pg;
static abstract_plugin& _wasm_ql_pg_plugin = app().register_plugin<wasm_ql_pg_plugin>();
struct pg_database_interface : database_interface, std::enable_shared_from_this<pg_database_interface> {
std::string schema = {};
std::unique_ptr<const pg::config> config = {};
virtual ~pg_database_interface() {}
virtual std::unique_ptr<query_session> create_query_session();
};
struct pg_query_session : query_session {
virtual ~pg_query_session() {}
std::shared_ptr<pg_database_interface> db_iface;
pqxx::connection sql_connection = {};
virtual state_history::fill_status get_fill_status() override {
pqxx::work t(sql_connection);
auto row = t.exec("select head, head_id, irreversible, irreversible_id, first from \"" + db_iface->schema + "\".fill_status")[0];
state_history::fill_status result;
result.head = row[0].as<uint32_t>();
result.head_id = pg::sql_to_checksum256(row[1].c_str());
result.irreversible = row[2].as<uint32_t>();
result.irreversible_id = pg::sql_to_checksum256(row[3].c_str());
result.first = row[4].as<uint32_t>();
return result;
}
virtual std::optional<abieos::checksum256> get_block_id(uint32_t block_num) override {
pqxx::work t(sql_connection);
auto result =
t.exec("select block_id from \"" + db_iface->schema + "\".block_info where block_num=" + pg::sql_str(false, block_num));
if (result.empty())
return {};
return pg::sql_to_checksum256(result[0][0].c_str());
}
virtual std::vector<char> query_database(abieos::input_buffer query_bin, uint32_t head) override {
abieos::name query_name;
abieos::bin_to_native(query_name, query_bin);
// todo: check for false positives in secondary indexes
auto it = db_iface->config->query_map.find(query_name);
if (it == db_iface->config->query_map.end())
throw std::runtime_error("query_database: unknown query: " + (std::string)query_name);
const pg::query& query = *it->second;
uint32_t snapshot_block_num = 0;
if (query.has_block_snapshot)
snapshot_block_num = std::min(head, abieos::bin_to_native<uint32_t>(query_bin));
std::string query_str = "select * from \"" + db_iface->schema + "\"." + query.function + "(";
bool need_sep = false;
if (query.has_block_snapshot) {
query_str += pg::sql_str(false, snapshot_block_num);
need_sep = true;
}
auto add_args = [&](auto& args) {
for (auto& arg : args) {
if (need_sep)
query_str += pg::sep(false);
query_str += arg.bin_to_sql(sql_connection, false, query_bin);
need_sep = true;
}
};
add_args(query.arg_types);
add_args(query.index_obj->range_types);
add_args(query.index_obj->range_types);
auto max_results = abieos::read_raw<uint32_t>(query_bin);
query_str += pg::sep(false) + pg::sql_str(false, std::min(max_results, query.max_results));
query_str += ")";
pqxx::work t(sql_connection);
auto exec_result = t.exec(query_str);
std::vector<char> result;
std::vector<char> row_bin;
abieos::push_varuint32(result, exec_result.size());
for (const auto& r : exec_result) {
row_bin.clear();
int i = 0;
for (size_t field_index = 0; field_index < query.result_fields.size();) {
auto& field = query.result_fields[field_index++];
field.type_obj->sql_to_bin(row_bin, r[i++]);
if (field.begin_optional && !r[i - 1].as<bool>()) {
while (field_index < query.result_fields.size()) {
++field_index;
++i;
if (query.result_fields[field_index - 1].end_optional)
break;
}
}
}
if ((uint32_t)row_bin.size() != row_bin.size())
throw std::runtime_error("query_database: row is too big");
abieos::push_varuint32(result, row_bin.size());
result.insert(result.end(), row_bin.begin(), row_bin.end());
}
t.commit();
if ((uint32_t)result.size() != result.size())
throw std::runtime_error("query_database: result is too big");
return result;
}
}; // pg_query_session
std::unique_ptr<query_session> pg_database_interface::create_query_session() {
auto session = std::make_unique<pg_query_session>();
session->db_iface = shared_from_this();
return session;
}
struct wasm_ql_pg_plugin_impl {
std::shared_ptr<pg_database_interface> interface;
};
wasm_ql_pg_plugin::wasm_ql_pg_plugin()
: my(std::make_shared<wasm_ql_pg_plugin_impl>()) {}
wasm_ql_pg_plugin::~wasm_ql_pg_plugin() {}
void wasm_ql_pg_plugin::set_program_options(options_description& cli, options_description& cfg) {}
void wasm_ql_pg_plugin::plugin_initialize(const variables_map& options) {
try {
my->interface = std::make_shared<pg_database_interface>();
my->interface->schema = options["pg-schema"].as<std::string>();
auto x = read_string(options["query-config"].as<std::string>().c_str());
auto config = std::make_unique<pg::config>();
try {
abieos::json_to_native(*config, x);
} catch (const std::exception& e) {
throw std::runtime_error("error processing " + options["query-config"].as<std::string>() + ": " + e.what());
}
config->prepare(state_history::pg::abi_type_to_sql_type);
my->interface->config = std::move(config);
app().find_plugin<wasm_ql_plugin>()->set_database(my->interface);
}
FC_LOG_AND_RETHROW()
}
void wasm_ql_pg_plugin::plugin_startup() {}
void wasm_ql_pg_plugin::plugin_shutdown() { ilog("wasm_ql_pg_plugin stopped"); }
| 41.409091
| 137
| 0.609691
|
swang-b1
|
6045a51183ec4725c4006fc0c0cb8ae1395aeeec
| 650
|
cpp
|
C++
|
src/connection_options.cpp
|
herrvonregen/abb_librws
|
a34f824b76b7a63b41f53054f1d0588535aa6b39
|
[
"BSD-3-Clause"
] | null | null | null |
src/connection_options.cpp
|
herrvonregen/abb_librws
|
a34f824b76b7a63b41f53054f1d0588535aa6b39
|
[
"BSD-3-Clause"
] | 5
|
2021-11-25T09:24:05.000Z
|
2022-02-21T13:41:14.000Z
|
src/connection_options.cpp
|
NoMagicAi/abb_librws
|
bbd22f45ae43d087f64411d3114658445dd73407
|
[
"BSD-3-Clause"
] | 2
|
2021-03-20T09:30:53.000Z
|
2022-01-02T13:13:30.000Z
|
#include <abb_librws/connection_options.h>
namespace abb :: rws
{
ConnectionOptions::ConnectionOptions(
std::string const& ip_address,
unsigned short port,
std::string const& username,
std::string password,
std::chrono::microseconds connection_timeout,
std::chrono::microseconds send_timeout,
std::chrono::microseconds receive_timeout
)
: ip_address {ip_address}
, port {port}
, username {username}
, password {password}
, connection_timeout {connection_timeout}
, send_timeout {send_timeout}
, receive_timeout {receive_timeout}
{
}
}
| 27.083333
| 53
| 0.650769
|
herrvonregen
|
6045e4fc0854232340d9399ec2234592ba3c3c1b
| 5,405
|
cpp
|
C++
|
src/tests/unittests/wire/WireQueueTests.cpp
|
faro-oss/Dawn
|
0ac7aa3386b597742a45368a28a2e045c122cb8c
|
[
"Apache-2.0"
] | 1
|
2022-02-05T01:08:06.000Z
|
2022-02-05T01:08:06.000Z
|
src/tests/unittests/wire/WireQueueTests.cpp
|
sunnyps/dawn
|
afe91384086551ea3156fc67c525fdf864aa8437
|
[
"Apache-2.0"
] | 1
|
2021-12-18T01:33:44.000Z
|
2021-12-18T01:33:44.000Z
|
src/tests/unittests/wire/WireQueueTests.cpp
|
sunnyps/dawn
|
afe91384086551ea3156fc67c525fdf864aa8437
|
[
"Apache-2.0"
] | null | null | null |
// Copyright 2021 The Dawn Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "tests/unittests/wire/WireTest.h"
#include "dawn_wire/WireClient.h"
using namespace testing;
using namespace dawn_wire;
class MockQueueWorkDoneCallback {
public:
MOCK_METHOD(void, Call, (WGPUQueueWorkDoneStatus status, void* userdata));
};
static std::unique_ptr<MockQueueWorkDoneCallback> mockQueueWorkDoneCallback;
static void ToMockQueueWorkDone(WGPUQueueWorkDoneStatus status, void* userdata) {
mockQueueWorkDoneCallback->Call(status, userdata);
}
class WireQueueTests : public WireTest {
protected:
void SetUp() override {
WireTest::SetUp();
mockQueueWorkDoneCallback = std::make_unique<MockQueueWorkDoneCallback>();
}
void TearDown() override {
WireTest::TearDown();
mockQueueWorkDoneCallback = nullptr;
}
void FlushServer() {
WireTest::FlushServer();
Mock::VerifyAndClearExpectations(&mockQueueWorkDoneCallback);
}
};
// Test that a successful OnSubmittedWorkDone call is forwarded to the client.
TEST_F(WireQueueTests, OnSubmittedWorkDoneSuccess) {
wgpuQueueOnSubmittedWorkDone(queue, 0u, ToMockQueueWorkDone, this);
EXPECT_CALL(api, OnQueueOnSubmittedWorkDone(apiQueue, 0u, _, _))
.WillOnce(InvokeWithoutArgs([&]() {
api.CallQueueOnSubmittedWorkDoneCallback(apiQueue, WGPUQueueWorkDoneStatus_Success);
}));
FlushClient();
EXPECT_CALL(*mockQueueWorkDoneCallback, Call(WGPUQueueWorkDoneStatus_Success, this)).Times(1);
FlushServer();
}
// Test that an error OnSubmittedWorkDone call is forwarded as an error to the client.
TEST_F(WireQueueTests, OnSubmittedWorkDoneError) {
wgpuQueueOnSubmittedWorkDone(queue, 0u, ToMockQueueWorkDone, this);
EXPECT_CALL(api, OnQueueOnSubmittedWorkDone(apiQueue, 0u, _, _))
.WillOnce(InvokeWithoutArgs([&]() {
api.CallQueueOnSubmittedWorkDoneCallback(apiQueue, WGPUQueueWorkDoneStatus_Error);
}));
FlushClient();
EXPECT_CALL(*mockQueueWorkDoneCallback, Call(WGPUQueueWorkDoneStatus_Error, this)).Times(1);
FlushServer();
}
// Test registering an OnSubmittedWorkDone then disconnecting the wire calls the callback with
// device loss
TEST_F(WireQueueTests, OnSubmittedWorkDoneBeforeDisconnect) {
wgpuQueueOnSubmittedWorkDone(queue, 0u, ToMockQueueWorkDone, this);
EXPECT_CALL(api, OnQueueOnSubmittedWorkDone(apiQueue, 0u, _, _))
.WillOnce(InvokeWithoutArgs([&]() {
api.CallQueueOnSubmittedWorkDoneCallback(apiQueue, WGPUQueueWorkDoneStatus_Error);
}));
FlushClient();
EXPECT_CALL(*mockQueueWorkDoneCallback, Call(WGPUQueueWorkDoneStatus_DeviceLost, this))
.Times(1);
GetWireClient()->Disconnect();
}
// Test registering an OnSubmittedWorkDone after disconnecting the wire calls the callback with
// device loss
TEST_F(WireQueueTests, OnSubmittedWorkDoneAfterDisconnect) {
GetWireClient()->Disconnect();
EXPECT_CALL(*mockQueueWorkDoneCallback, Call(WGPUQueueWorkDoneStatus_DeviceLost, this))
.Times(1);
wgpuQueueOnSubmittedWorkDone(queue, 0u, ToMockQueueWorkDone, this);
}
// Hack to pass in test context into user callback
struct TestData {
WireQueueTests* pTest;
WGPUQueue* pTestQueue;
size_t numRequests;
};
static void ToMockQueueWorkDoneWithNewRequests(WGPUQueueWorkDoneStatus status, void* userdata) {
TestData* testData = reinterpret_cast<TestData*>(userdata);
// Mimic the user callback is sending new requests
ASSERT_NE(testData, nullptr);
ASSERT_NE(testData->pTest, nullptr);
ASSERT_NE(testData->pTestQueue, nullptr);
mockQueueWorkDoneCallback->Call(status, testData->pTest);
// Send the requests a number of times
for (size_t i = 0; i < testData->numRequests; i++) {
wgpuQueueOnSubmittedWorkDone(*(testData->pTestQueue), 0u, ToMockQueueWorkDone,
testData->pTest);
}
}
// Test that requests inside user callbacks before disconnect are called
TEST_F(WireQueueTests, OnSubmittedWorkDoneInsideCallbackBeforeDisconnect) {
TestData testData = {this, &queue, 10};
wgpuQueueOnSubmittedWorkDone(queue, 0u, ToMockQueueWorkDoneWithNewRequests, &testData);
EXPECT_CALL(api, OnQueueOnSubmittedWorkDone(apiQueue, 0u, _, _))
.WillOnce(InvokeWithoutArgs([&]() {
api.CallQueueOnSubmittedWorkDoneCallback(apiQueue, WGPUQueueWorkDoneStatus_Error);
}));
FlushClient();
EXPECT_CALL(*mockQueueWorkDoneCallback, Call(WGPUQueueWorkDoneStatus_DeviceLost, this))
.Times(1 + testData.numRequests);
GetWireClient()->Disconnect();
}
// Only one default queue is supported now so we cannot test ~Queue triggering ClearAllCallbacks
// since it is always destructed after the test TearDown, and we cannot create a new queue obj
// with wgpuDeviceGetQueue
| 38.333333
| 98
| 0.741721
|
faro-oss
|
6045f33e8d078d4e0f3910b3c7e29fd49ab02b4d
| 6,885
|
cpp
|
C++
|
cppcache/integration-test/testThinClientRemoteQueryFailoverPdx.cpp
|
mcmellawatt/geode-native
|
53315985c4386e6781473c5713d638c8139e3e8e
|
[
"Apache-2.0"
] | null | null | null |
cppcache/integration-test/testThinClientRemoteQueryFailoverPdx.cpp
|
mcmellawatt/geode-native
|
53315985c4386e6781473c5713d638c8139e3e8e
|
[
"Apache-2.0"
] | null | null | null |
cppcache/integration-test/testThinClientRemoteQueryFailoverPdx.cpp
|
mcmellawatt/geode-native
|
53315985c4386e6781473c5713d638c8139e3e8e
|
[
"Apache-2.0"
] | null | null | null |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "fw_dunit.hpp"
#include <ace/OS.h>
#include <ace/High_Res_Timer.h>
#include <ace/Task.h>
#include <string>
#define ROOT_NAME "testThinClientRemoteQueryFailoverPdx"
#define ROOT_SCOPE DISTRIBUTED_ACK
#include "ThinClientHelper.hpp"
#include <geode/Query.hpp>
#include <geode/QueryService.hpp>
#include <geode/ResultSet.hpp>
#include <geode/StructSet.hpp>
#include <geode/SelectResultsIterator.hpp>
#include "testobject/Portfolio.hpp"
#include "testobject/PortfolioPdx.hpp"
#include "SerializationRegistry.hpp"
#include "CacheRegionHelper.hpp"
using namespace apache::geode::client;
using namespace test;
using namespace testobject;
#define CLIENT1 s1p1
#define LOCATOR s1p2
#define SERVER1 s2p1
#define SERVER2 s2p2
class KillServerThread : public ACE_Task_Base {
public:
bool m_running;
KillServerThread() : m_running(false) {}
int svc(void) {
while (m_running == true) {
CacheHelper::closeServer(1);
LOG("THREAD CLOSED SERVER 1");
m_running = false;
}
return 0;
}
void start() {
m_running = true;
activate();
}
void stop() {
m_running = false;
wait();
}
};
bool isLocator = false;
bool isLocalServer = false;
const char* qRegionNames[] = {"Portfolios", "Positions"};
KillServerThread* kst = nullptr;
const char* poolNames[] = {"Pool1", "Pool2", "Pool3"};
const char* locHostPort =
CacheHelper::getLocatorHostPort(isLocator, isLocalServer, 1);
bool isPoolConfig = false; // To track if pool case is running
DUNIT_TASK_DEFINITION(LOCATOR, StartLocator)
{
// starting locator 1 2
if (isLocator) {
CacheHelper::initLocator(1);
}
LOG("Locator started");
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(SERVER1, CreateServer1WithLocator)
{
LOG("Starting SERVER1...");
if (isLocalServer) {
CacheHelper::initServer(1, "cacheserver_remoteoql.xml", locHostPort);
}
LOG("SERVER1 started with Locator");
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(SERVER2, CreateServer2WithLocator)
{
LOG("Starting SERVER2...");
if (isLocalServer) {
CacheHelper::initServer(2, "cacheserver_remoteoql2.xml", locHostPort);
}
LOG("SERVER2 started");
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT1, RegisterTypesAndCreatePoolAndRegion)
{
LOG("Starting Step One with Pool + Locator lists");
initClient(true);
try {
auto serializationRegistry =
CacheRegionHelper::getCacheImpl(cacheHelper->getCache().get())
->getSerializationRegistry();
serializationRegistry->addType(Position::createDeserializable);
serializationRegistry->addType(Portfolio::createDeserializable);
serializationRegistry->addPdxType(PositionPdx::createDeserializable);
serializationRegistry->addPdxType(PortfolioPdx::createDeserializable);
} catch (const IllegalStateException&) {
// ignore exception
}
isPoolConfig = true;
createPool(poolNames[0], locHostPort, nullptr, 0, true);
createRegionAndAttachPool(qRegionNames[0], USE_ACK, poolNames[0]);
auto rptr = getHelper()->cachePtr->getRegion(qRegionNames[0]);
auto port1 = std::make_shared<PortfolioPdx>(1, 100);
auto port2 = std::make_shared<PortfolioPdx>(2, 200);
auto port3 = std::make_shared<PortfolioPdx>(3, 300);
auto port4 = std::make_shared<PortfolioPdx>(4, 400);
rptr->put("1", port1);
rptr->put("2", port2);
rptr->put("3", port3);
rptr->put("4", port4);
LOG("RegisterTypesAndCreatePoolAndRegion complete.");
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT1, ValidateQueryExecutionAcrossServerFailure)
{
try {
kst = new KillServerThread();
std::shared_ptr<QueryService> qs = nullptr;
if (isPoolConfig) {
auto pool1 = findPool(poolNames[0]);
qs = pool1->getQueryService();
} else {
qs = getHelper()->cachePtr->getQueryService();
}
for (int i = 0; i < 10000; i++) {
auto qry = qs->newQuery("select distinct * from /Portfolios");
std::shared_ptr<SelectResults> results;
results = qry->execute();
if (i == 10) {
kst->start();
}
auto resultsize = results->size();
if (i % 100 == 0) {
printf("Iteration upto %d done, result size is %zd\n", i, resultsize);
}
if (resultsize != 4) // the XMLs for server 1 and server 2 have 1 and 2
// entries respectively
{
LOG("Result size is not 4!");
FAIL("Result size is not 4!");
}
}
kst->stop();
} catch (IllegalStateException& ise) {
char isemsg[500] = {0};
ACE_OS::snprintf(isemsg, 499, "IllegalStateException: %s", ise.what());
LOG(isemsg);
FAIL(isemsg);
} catch (Exception& excp) {
char excpmsg[500] = {0};
ACE_OS::snprintf(excpmsg, 499, "Exception: %s", excp.what());
LOG(excpmsg);
FAIL(excpmsg);
} catch (...) {
LOG("Got an exception!");
FAIL("Got an exception!");
}
LOG("ValidateQueryExecutionAcrossServerFailure complete.");
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(CLIENT1, CloseCache1)
{
LOG("cleanProc 1...");
isPoolConfig = false;
cleanProc();
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(SERVER2, CloseServer2)
{
LOG("closing Server2...");
if (isLocalServer) {
CacheHelper::closeServer(2);
LOG("SERVER2 stopped");
}
}
END_TASK_DEFINITION
DUNIT_TASK_DEFINITION(LOCATOR, CloseLocator)
{
if (isLocator) {
CacheHelper::closeLocator(1);
LOG("Locator1 stopped");
}
}
END_TASK_DEFINITION
void runRemoteQueryFailoverTest(){
CALL_TASK(StartLocator) CALL_TASK(CreateServer1WithLocator)
CALL_TASK(RegisterTypesAndCreatePoolAndRegion)
CALL_TASK(CreateServer2WithLocator)
CALL_TASK(ValidateQueryExecutionAcrossServerFailure)
CALL_TASK(CloseCache1) CALL_TASK(CloseServer2)
CALL_TASK(CloseLocator)}
DUNIT_MAIN {
runRemoteQueryFailoverTest();
}
END_MAIN
| 28.333333
| 80
| 0.67451
|
mcmellawatt
|
604ae7fa0b296d5997e967d03cd3c8ef6f5f86ba
| 2,690
|
cpp
|
C++
|
src/util/generate_error_message.cpp
|
frzfrsfra4/phylanx
|
001fe7081f3a24e56157cdb21b2d126b8953ff5d
|
[
"BSL-1.0"
] | 1
|
2019-08-17T21:19:57.000Z
|
2019-08-17T21:19:57.000Z
|
src/util/generate_error_message.cpp
|
frzfrsfra4/phylanx
|
001fe7081f3a24e56157cdb21b2d126b8953ff5d
|
[
"BSL-1.0"
] | null | null | null |
src/util/generate_error_message.cpp
|
frzfrsfra4/phylanx
|
001fe7081f3a24e56157cdb21b2d126b8953ff5d
|
[
"BSL-1.0"
] | null | null | null |
// Copyright (c) 2017-2018 Hartmut Kaiser
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <phylanx/config.hpp>
#include <phylanx/execution_tree/compiler/primitive_name.hpp>
#include <phylanx/util/generate_error_message.hpp>
#include <hpx/util/format.hpp>
#include <string>
namespace phylanx { namespace util
{
std::string generate_error_message(std::string const& msg,
execution_tree::compiler::primitive_name_parts const& parts,
std::string const& codename)
{
return generate_error_message(msg,
execution_tree::compiler::compose_primitive_name(parts), codename);
}
std::string generate_error_message(std::string const& msg,
std::string const& name, std::string const& codename)
{
if (!name.empty())
{
execution_tree::compiler::primitive_name_parts parts;
if (execution_tree::compiler::parse_primitive_name(name, parts))
{
std::string line_col;
if (parts.tag1 != -1 && parts.tag2 != -1)
{
line_col = hpx::util::format(
"(" PHYLANX_FORMAT_SPEC(1) ", "
PHYLANX_FORMAT_SPEC(2) ")",
parts.tag1, parts.tag2);
}
if (!parts.instance.empty())
{
return hpx::util::format(
PHYLANX_FORMAT_SPEC(1) PHYLANX_FORMAT_SPEC(2)
": " PHYLANX_FORMAT_SPEC(3)
"$" PHYLANX_FORMAT_SPEC(4)
":: " PHYLANX_FORMAT_SPEC(5),
codename.empty() ? "<unknown>" : codename, line_col,
parts.primitive, parts.instance, msg);
}
return hpx::util::format(
PHYLANX_FORMAT_SPEC(1) PHYLANX_FORMAT_SPEC(2)
": " PHYLANX_FORMAT_SPEC(3)
":: " PHYLANX_FORMAT_SPEC(4),
codename.empty() ? "<unknown>" : codename, line_col,
parts.primitive, msg);
}
return hpx::util::format(
PHYLANX_FORMAT_SPEC(1)
": " PHYLANX_FORMAT_SPEC(2)
":: " PHYLANX_FORMAT_SPEC(3),
codename.empty() ? "<unknown>" : codename, name, msg);
}
return hpx::util::format(
PHYLANX_FORMAT_SPEC(1) ": " PHYLANX_FORMAT_SPEC(2),
codename.empty() ? "<unknown>" : codename, msg);
}
}}
| 36.351351
| 80
| 0.528253
|
frzfrsfra4
|
604d7300cddfd486fbb888dc07fbbf241eca145e
| 2,539
|
cpp
|
C++
|
QCompositeManager/extensions.cpp
|
rkoyama1623/Quantum
|
429d11f0b2c737164005ba70c98611baef69d1c5
|
[
"Unlicense"
] | 35
|
2015-01-13T00:57:17.000Z
|
2022-03-16T20:39:56.000Z
|
QCompositeManager/extensions.cpp
|
KR8T3R/Quantum
|
429d11f0b2c737164005ba70c98611baef69d1c5
|
[
"Unlicense"
] | null | null | null |
QCompositeManager/extensions.cpp
|
KR8T3R/Quantum
|
429d11f0b2c737164005ba70c98611baef69d1c5
|
[
"Unlicense"
] | 31
|
2015-01-29T03:59:52.000Z
|
2022-03-16T20:40:43.000Z
|
/*
* KDE Composite Manager,
* Copyright (C) 2003-2005 Fredrik Höglund <fredrik@kde.org>
*
* Based on xcompmgr,
* Copyright (C) 2003 Keith Packard <keithp@keithp.com>
*
* Internal structure and naming style inspired by KWin,
* Copyright (C) 1999, 2000 Matthias Ettrich <ettrich@kde.org>
* Copyright (C) 2003 Lubos Lunak <l.lunak@kde.org>
*
* Permission to use, copy, modify, distribute, and sell this software and its
* documentation for any purpose is hereby granted without fee, provided that
* the above copyright notice appear in all copies and that both that
* copyright notice and this permission notice appear in supporting
* documentation, and that the name of Fredrik Höglund not be used in
* advertising or publicity pertaining to distribution of the software without
* specific, written prior permission. Fredrik Höglund makes no
* representations about the suitability of this software for any purpose. It
* is provided "as is" without express or implied warranty.
*
* FREDRIK HÃGLUND DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
* INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
* EVENT SHALL FREDRIK HÃGLUND BE LIABLE FOR ANY SPECIAL, INDIRECT OR
* CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
* DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
#include "extensions.h"
#include <QDebug>
#include <X11/Xlib.h>
#include <X11/extensions/Xrender.h>
#include <X11/extensions/shape.h>
#include <X11/extensions/Xfixes.h>
#include <X11/extensions/Xdamage.h>
#include <X11/extensions/Xcomposite.h>
extern Display *dpy;
int Extensions::sShapeEventBase = 0;
int Extensions::sDamageEventBase = 0;
bool Extensions::initialize()
{
int eventBase, errorBase;
qDebug() << dpy;
if ( !XShapeQueryExtension( dpy, &sShapeEventBase, &errorBase ) ) {
qFatal("Missing the XShape extension.");
}
if ( !XRenderQueryExtension( dpy, &eventBase, &errorBase ) ) {
qFatal("Missing the XRender extension.");
}
if ( !XCompositeQueryExtension( dpy, &eventBase, &errorBase ) ) {
qFatal("Missing the XComposite extension.");
}
if ( !XDamageQueryExtension( dpy, &sDamageEventBase, &errorBase ) ) {
qFatal("Missing the XDamage extension.");
}
if ( !XFixesQueryExtension( dpy, &eventBase, &errorBase ) ) {
qFatal("Missing the XFixes extension.");
}
return true;
}
| 32.139241
| 78
| 0.729815
|
rkoyama1623
|
6050dc12833f0841262207f43b10fe621533ec75
| 605
|
cpp
|
C++
|
doc/examples/operatorarray__key_type.cpp
|
Hexlord/json
|
66869458b5227170e052d01aa65b47ee8350b666
|
[
"MIT"
] | 23
|
2016-01-20T07:50:24.000Z
|
2021-09-08T05:08:19.000Z
|
json-master/doc/examples/operatorarray__key_type.cpp
|
bobismijnnaam/bobetex
|
9960eafd31c73b4070b236d5dfafd5734492aaf5
|
[
"MIT"
] | 18
|
2016-06-01T11:56:54.000Z
|
2016-06-06T10:58:53.000Z
|
json-master/doc/examples/operatorarray__key_type.cpp
|
bobismijnnaam/bobetex
|
9960eafd31c73b4070b236d5dfafd5734492aaf5
|
[
"MIT"
] | 19
|
2016-01-24T13:05:24.000Z
|
2021-06-25T01:36:47.000Z
|
#include <json.hpp>
using namespace nlohmann;
int main()
{
// create a JSON object
json object =
{
{"one", 1}, {"two", 2}, {"three", 2.9}
};
// output element with key "two"
std::cout << object["two"] << "\n\n";
// change element with key "three"
object["three"] = 3;
// output changed array
std::cout << std::setw(4) << object << "\n\n";
// mention nonexisting key
object["four"];
// write to nonexisting key
object["five"]["really"]["nested"] = true;
// output changed object
std::cout << std::setw(4) << object << '\n';
}
| 19.516129
| 50
| 0.533884
|
Hexlord
|
60530fe1db1e3ff311474eaa583763e2e5a7edc7
| 131,218
|
cpp
|
C++
|
secp256k1-dpct/main.cpp
|
jchlanda/oneAPI-DirectProgramming
|
82a1be635f89b4b2a83e36965a60b19fd71e46b2
|
[
"BSD-3-Clause"
] | null | null | null |
secp256k1-dpct/main.cpp
|
jchlanda/oneAPI-DirectProgramming
|
82a1be635f89b4b2a83e36965a60b19fd71e46b2
|
[
"BSD-3-Clause"
] | null | null | null |
secp256k1-dpct/main.cpp
|
jchlanda/oneAPI-DirectProgramming
|
82a1be635f89b4b2a83e36965a60b19fd71e46b2
|
[
"BSD-3-Clause"
] | null | null | null |
#include <CL/sycl.hpp>
#include <dpct/dpct.hpp>
#include <stdio.h>
#include <string.h>
typedef struct dpct_type_506b7b {
uint n[10];
} secp256k1_fe;
typedef struct dpct_type_7faff8 {
uint n[8];
} secp256k1_fe_storage;
typedef struct dpct_type_ec67f2 {
secp256k1_fe x;
secp256k1_fe y;
} secp256k1_ge;
typedef struct dpct_type_9f8a46 {
secp256k1_fe x;
secp256k1_fe y;
secp256k1_fe z;
} secp256k1_gej;
typedef struct dpct_type_54cde9 {
secp256k1_fe_storage x;
secp256k1_fe_storage y;
} secp256k1_ge_storage;
#define SECP256K1_FE_STORAGE_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {{ (d0), (d1), (d2), (d3), (d4), (d5), (d6), (d7) }}
#define SECP256K1_GE_STORAGE_CONST(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) {SECP256K1_FE_STORAGE_CONST((a),(b),(c),(d),(e),(f),(g),(h)), SECP256K1_FE_STORAGE_CONST((i),(j),(k),(l),(m),(n),(o),(p))}
#define SC SECP256K1_GE_STORAGE_CONST
void secp256k1_fe_from_storage(secp256k1_fe *r, const secp256k1_fe_storage *a) {
r->n[0] = a->n[0] & 0x3FFFFFFUL;
r->n[1] = a->n[0] >> 26 | ((a->n[1] << 6) & 0x3FFFFFFUL);
r->n[2] = a->n[1] >> 20 | ((a->n[2] << 12) & 0x3FFFFFFUL);
r->n[3] = a->n[2] >> 14 | ((a->n[3] << 18) & 0x3FFFFFFUL);
r->n[4] = a->n[3] >> 8 | ((a->n[4] << 24) & 0x3FFFFFFUL);
r->n[5] = (a->n[4] >> 2) & 0x3FFFFFFUL;
r->n[6] = a->n[4] >> 28 | ((a->n[5] << 4) & 0x3FFFFFFUL);
r->n[7] = a->n[5] >> 22 | ((a->n[6] << 10) & 0x3FFFFFFUL);
r->n[8] = a->n[6] >> 16 | ((a->n[7] << 16) & 0x3FFFFFFUL);
r->n[9] = a->n[7] >> 10;
}
void secp256k1_fe_sqr_inner(uint *r, const uint *a) {
ulong c, d;
ulong u0, u1, u2, u3, u4, u5, u6, u7, u8;
uint t9, t0, t1, t2, t3, t4, t5, t6, t7;
const uint M = 0x3FFFFFFUL, R0 = 0x3D10UL, R1 = 0x400UL;
d = (ulong)(a[0]*2) * a[9]
+ (ulong)(a[1]*2) * a[8]
+ (ulong)(a[2]*2) * a[7]
+ (ulong)(a[3]*2) * a[6]
+ (ulong)(a[4]*2) * a[5];
t9 = d & M; d >>= 26;
c = (ulong)a[0] * a[0];
d += (ulong)(a[1]*2) * a[9]
+ (ulong)(a[2]*2) * a[8]
+ (ulong)(a[3]*2) * a[7]
+ (ulong)(a[4]*2) * a[6]
+ (ulong)a[5] * a[5];
u0 = d & M; d >>= 26; c += u0 * R0;
t0 = c & M; c >>= 26; c += u0 * R1;
c += (ulong)(a[0]*2) * a[1];
d += (ulong)(a[2]*2) * a[9]
+ (ulong)(a[3]*2) * a[8]
+ (ulong)(a[4]*2) * a[7]
+ (ulong)(a[5]*2) * a[6];
u1 = d & M; d >>= 26; c += u1 * R0;
t1 = c & M; c >>= 26; c += u1 * R1;
c += (ulong)(a[0]*2) * a[2]
+ (ulong)a[1] * a[1];
d += (ulong)(a[3]*2) * a[9]
+ (ulong)(a[4]*2) * a[8]
+ (ulong)(a[5]*2) * a[7]
+ (ulong)a[6] * a[6];
u2 = d & M; d >>= 26; c += u2 * R0;
t2 = c & M; c >>= 26; c += u2 * R1;
c += (ulong)(a[0]*2) * a[3]
+ (ulong)(a[1]*2) * a[2];
d += (ulong)(a[4]*2) * a[9]
+ (ulong)(a[5]*2) * a[8]
+ (ulong)(a[6]*2) * a[7];
u3 = d & M; d >>= 26; c += u3 * R0;
t3 = c & M; c >>= 26; c += u3 * R1;
c += (ulong)(a[0]*2) * a[4]
+ (ulong)(a[1]*2) * a[3]
+ (ulong)a[2] * a[2];
d += (ulong)(a[5]*2) * a[9]
+ (ulong)(a[6]*2) * a[8]
+ (ulong)a[7] * a[7];
u4 = d & M; d >>= 26; c += u4 * R0;
t4 = c & M; c >>= 26; c += u4 * R1;
c += (ulong)(a[0]*2) * a[5]
+ (ulong)(a[1]*2) * a[4]
+ (ulong)(a[2]*2) * a[3];
d += (ulong)(a[6]*2) * a[9]
+ (ulong)(a[7]*2) * a[8];
u5 = d & M; d >>= 26; c += u5 * R0;
t5 = c & M; c >>= 26; c += u5 * R1;
c += (ulong)(a[0]*2) * a[6]
+ (ulong)(a[1]*2) * a[5]
+ (ulong)(a[2]*2) * a[4]
+ (ulong)a[3] * a[3];
d += (ulong)(a[7]*2) * a[9]
+ (ulong)a[8] * a[8];
u6 = d & M; d >>= 26; c += u6 * R0;
t6 = c & M; c >>= 26; c += u6 * R1;
c += (ulong)(a[0]*2) * a[7]
+ (ulong)(a[1]*2) * a[6]
+ (ulong)(a[2]*2) * a[5]
+ (ulong)(a[3]*2) * a[4];
d += (ulong)(a[8]*2) * a[9];
u7 = d & M; d >>= 26; c += u7 * R0;
t7 = c & M; c >>= 26; c += u7 * R1;
c += (ulong)(a[0]*2) * a[8]
+ (ulong)(a[1]*2) * a[7]
+ (ulong)(a[2]*2) * a[6]
+ (ulong)(a[3]*2) * a[5]
+ (ulong)a[4] * a[4];
d += (ulong)a[9] * a[9];
u8 = d & M; d >>= 26; c += u8 * R0;
r[3] = t3;
r[4] = t4;
r[5] = t5;
r[6] = t6;
r[7] = t7;
r[8] = c & M; c >>= 26; c += u8 * R1;
c += d * R0 + t9;
r[9] = c & (M >> 4); c >>= 22; c += d * (R1 << 4);
d = c * (R0 >> 4) + t0;
r[0] = d & M; d >>= 26;
d += c * (R1 >> 4) + t1;
r[1] = d & M; d >>= 26;
d += t2;
r[2] = d;
}
void secp256k1_fe_sqr(secp256k1_fe *r, const secp256k1_fe *a) {
secp256k1_fe_sqr_inner(r->n, a->n);
}
void secp256k1_fe_normalize_weak(secp256k1_fe *r) {
uint t0 = r->n[0], t1 = r->n[1], t2 = r->n[2], t3 = r->n[3], t4 = r->n[4],
t5 = r->n[5], t6 = r->n[6], t7 = r->n[7], t8 = r->n[8], t9 = r->n[9];
/* Reduce t9 at the start so there will be at most a single carry from the first pass */
uint x = t9 >> 22; t9 &= 0x03FFFFFUL;
/* The first pass ensures the magnitude is 1, ... */
t0 += x * 0x3D1UL; t1 += (x << 6);
t1 += (t0 >> 26); t0 &= 0x3FFFFFFUL;
t2 += (t1 >> 26); t1 &= 0x3FFFFFFUL;
t3 += (t2 >> 26); t2 &= 0x3FFFFFFUL;
t4 += (t3 >> 26); t3 &= 0x3FFFFFFUL;
t5 += (t4 >> 26); t4 &= 0x3FFFFFFUL;
t6 += (t5 >> 26); t5 &= 0x3FFFFFFUL;
t7 += (t6 >> 26); t6 &= 0x3FFFFFFUL;
t8 += (t7 >> 26); t7 &= 0x3FFFFFFUL;
t9 += (t8 >> 26); t8 &= 0x3FFFFFFUL;
r->n[0] = t0; r->n[1] = t1; r->n[2] = t2; r->n[3] = t3; r->n[4] = t4;
r->n[5] = t5; r->n[6] = t6; r->n[7] = t7; r->n[8] = t8; r->n[9] = t9;
}
void secp256k1_fe_mul_inner(uint *r, const uint *a, const uint * b) {
ulong c, d;
ulong u0, u1, u2, u3, u4, u5, u6, u7, u8;
uint t9, t1, t0, t2, t3, t4, t5, t6, t7;
const uint M = 0x3FFFFFFUL, R0 = 0x3D10UL, R1 = 0x400UL;
d = (ulong)a[0] * b[9]
+ (ulong)a[1] * b[8]
+ (ulong)a[2] * b[7]
+ (ulong)a[3] * b[6]
+ (ulong)a[4] * b[5]
+ (ulong)a[5] * b[4]
+ (ulong)a[6] * b[3]
+ (ulong)a[7] * b[2]
+ (ulong)a[8] * b[1]
+ (ulong)a[9] * b[0];
/* VERIFY_BITS(d, 64); */
/* [d 0 0 0 0 0 0 0 0 0] = [p9 0 0 0 0 0 0 0 0 0] */
t9 = d & M; d >>= 26;
/* [d t9 0 0 0 0 0 0 0 0 0] = [p9 0 0 0 0 0 0 0 0 0] */
c = (ulong)a[0] * b[0];
/* [d t9 0 0 0 0 0 0 0 0 c] = [p9 0 0 0 0 0 0 0 0 p0] */
d += (ulong)a[1] * b[9]
+ (ulong)a[2] * b[8]
+ (ulong)a[3] * b[7]
+ (ulong)a[4] * b[6]
+ (ulong)a[5] * b[5]
+ (ulong)a[6] * b[4]
+ (ulong)a[7] * b[3]
+ (ulong)a[8] * b[2]
+ (ulong)a[9] * b[1];
/* [d t9 0 0 0 0 0 0 0 0 c] = [p10 p9 0 0 0 0 0 0 0 0 p0] */
u0 = d & M; d >>= 26; c += u0 * R0;
/* [d u0 t9 0 0 0 0 0 0 0 0 c-u0*R0] = [p10 p9 0 0 0 0 0 0 0 0 p0] */
t0 = c & M; c >>= 26; c += u0 * R1;
/* [d u0 t9 0 0 0 0 0 0 0 c-u0*R1 t0-u0*R0] = [p10 p9 0 0 0 0 0 0 0 0 p0] */
/* [d 0 t9 0 0 0 0 0 0 0 c t0] = [p10 p9 0 0 0 0 0 0 0 0 p0] */
c += (ulong)a[0] * b[1]
+ (ulong)a[1] * b[0];
/* [d 0 t9 0 0 0 0 0 0 0 c t0] = [p10 p9 0 0 0 0 0 0 0 p1 p0] */
d += (ulong)a[2] * b[9]
+ (ulong)a[3] * b[8]
+ (ulong)a[4] * b[7]
+ (ulong)a[5] * b[6]
+ (ulong)a[6] * b[5]
+ (ulong)a[7] * b[4]
+ (ulong)a[8] * b[3]
+ (ulong)a[9] * b[2];
/* [d 0 t9 0 0 0 0 0 0 0 c t0] = [p11 p10 p9 0 0 0 0 0 0 0 p1 p0] */
u1 = d & M; d >>= 26; c += u1 * R0;
/* [d u1 0 t9 0 0 0 0 0 0 0 c-u1*R0 t0] = [p11 p10 p9 0 0 0 0 0 0 0 p1 p0] */
t1 = c & M; c >>= 26; c += u1 * R1;
/* [d u1 0 t9 0 0 0 0 0 0 c-u1*R1 t1-u1*R0 t0] = [p11 p10 p9 0 0 0 0 0 0 0 p1 p0] */
/* [d 0 0 t9 0 0 0 0 0 0 c t1 t0] = [p11 p10 p9 0 0 0 0 0 0 0 p1 p0] */
c += (ulong)a[0] * b[2]
+ (ulong)a[1] * b[1]
+ (ulong)a[2] * b[0];
/* [d 0 0 t9 0 0 0 0 0 0 c t1 t0] = [p11 p10 p9 0 0 0 0 0 0 p2 p1 p0] */
d += (ulong)a[3] * b[9]
+ (ulong)a[4] * b[8]
+ (ulong)a[5] * b[7]
+ (ulong)a[6] * b[6]
+ (ulong)a[7] * b[5]
+ (ulong)a[8] * b[4]
+ (ulong)a[9] * b[3];
/* [d 0 0 t9 0 0 0 0 0 0 c t1 t0] = [p12 p11 p10 p9 0 0 0 0 0 0 p2 p1 p0] */
u2 = d & M; d >>= 26; c += u2 * R0;
/* [d u2 0 0 t9 0 0 0 0 0 0 c-u2*R0 t1 t0] = [p12 p11 p10 p9 0 0 0 0 0 0 p2 p1 p0] */
t2 = c & M; c >>= 26; c += u2 * R1;
/* [d u2 0 0 t9 0 0 0 0 0 c-u2*R1 t2-u2*R0 t1 t0] = [p12 p11 p10 p9 0 0 0 0 0 0 p2 p1 p0] */
/* [d 0 0 0 t9 0 0 0 0 0 c t2 t1 t0] = [p12 p11 p10 p9 0 0 0 0 0 0 p2 p1 p0] */
c += (ulong)a[0] * b[3]
+ (ulong)a[1] * b[2]
+ (ulong)a[2] * b[1]
+ (ulong)a[3] * b[0];
d += (ulong)a[4] * b[9]
+ (ulong)a[5] * b[8]
+ (ulong)a[6] * b[7]
+ (ulong)a[7] * b[6]
+ (ulong)a[8] * b[5]
+ (ulong)a[9] * b[4];
u3 = d & M; d >>= 26; c += u3 * R0;
/* VERIFY_BITS(c, 64); */
/* [d u3 0 0 0 t9 0 0 0 0 0 c-u3*R0 t2 t1 t0] = [p13 p12 p11 p10 p9 0 0 0 0 0 p3 p2 p1 p0] */
t3 = c & M; c >>= 26; c += u3 * R1;
c += (ulong)a[0] * b[4]
+ (ulong)a[1] * b[3]
+ (ulong)a[2] * b[2]
+ (ulong)a[3] * b[1]
+ (ulong)a[4] * b[0];
/* [d 0 0 0 0 t9 0 0 0 0 c t3 t2 t1 t0] = [p13 p12 p11 p10 p9 0 0 0 0 p4 p3 p2 p1 p0] */
d += (ulong)a[5] * b[9]
+ (ulong)a[6] * b[8]
+ (ulong)a[7] * b[7]
+ (ulong)a[8] * b[6]
+ (ulong)a[9] * b[5];
/* [d 0 0 0 0 t9 0 0 0 0 c t3 t2 t1 t0] = [p14 p13 p12 p11 p10 p9 0 0 0 0 p4 p3 p2 p1 p0] */
u4 = d & M; d >>= 26; c += u4 * R0;
/* VERIFY_BITS(c, 64); */
/* [d u4 0 0 0 0 t9 0 0 0 0 c-u4*R0 t3 t2 t1 t0] = [p14 p13 p12 p11 p10 p9 0 0 0 0 p4 p3 p2 p1 p0] */
t4 = c & M; c >>= 26; c += u4 * R1;
/* [d u4 0 0 0 0 t9 0 0 0 c-u4*R1 t4-u4*R0 t3 t2 t1 t0] = [p14 p13 p12 p11 p10 p9 0 0 0 0 p4 p3 p2 p1 p0] */
/* [d 0 0 0 0 0 t9 0 0 0 c t4 t3 t2 t1 t0] = [p14 p13 p12 p11 p10 p9 0 0 0 0 p4 p3 p2 p1 p0] */
c += (ulong)a[0] * b[5]
+ (ulong)a[1] * b[4]
+ (ulong)a[2] * b[3]
+ (ulong)a[3] * b[2]
+ (ulong)a[4] * b[1]
+ (ulong)a[5] * b[0];
/* [d 0 0 0 0 0 t9 0 0 0 c t4 t3 t2 t1 t0] = [p14 p13 p12 p11 p10 p9 0 0 0 p5 p4 p3 p2 p1 p0] */
d += (ulong)a[6] * b[9]
+ (ulong)a[7] * b[8]
+ (ulong)a[8] * b[7]
+ (ulong)a[9] * b[6];
/* [d 0 0 0 0 0 t9 0 0 0 c t4 t3 t2 t1 t0] = [p15 p14 p13 p12 p11 p10 p9 0 0 0 p5 p4 p3 p2 p1 p0] */
u5 = d & M; d >>= 26; c += u5 * R0;
/* VERIFY_BITS(c, 64); */
/* [d u5 0 0 0 0 0 t9 0 0 0 c-u5*R0 t4 t3 t2 t1 t0] = [p15 p14 p13 p12 p11 p10 p9 0 0 0 p5 p4 p3 p2 p1 p0] */
t5 = c & M; c >>= 26; c += u5 * R1;
/* [d u5 0 0 0 0 0 t9 0 0 c-u5*R1 t5-u5*R0 t4 t3 t2 t1 t0] = [p15 p14 p13 p12 p11 p10 p9 0 0 0 p5 p4 p3 p2 p1 p0] */
/* [d 0 0 0 0 0 0 t9 0 0 c t5 t4 t3 t2 t1 t0] = [p15 p14 p13 p12 p11 p10 p9 0 0 0 p5 p4 p3 p2 p1 p0] */
c += (ulong)a[0] * b[6]
+ (ulong)a[1] * b[5]
+ (ulong)a[2] * b[4]
+ (ulong)a[3] * b[3]
+ (ulong)a[4] * b[2]
+ (ulong)a[5] * b[1]
+ (ulong)a[6] * b[0];
/* [d 0 0 0 0 0 0 t9 0 0 c t5 t4 t3 t2 t1 t0] = [p15 p14 p13 p12 p11 p10 p9 0 0 p6 p5 p4 p3 p2 p1 p0] */
d += (ulong)a[7] * b[9]
+ (ulong)a[8] * b[8]
+ (ulong)a[9] * b[7];
/* [d 0 0 0 0 0 0 t9 0 0 c t5 t4 t3 t2 t1 t0] = [p16 p15 p14 p13 p12 p11 p10 p9 0 0 p6 p5 p4 p3 p2 p1 p0] */
u6 = d & M; d >>= 26; c += u6 * R0;
/* VERIFY_BITS(c, 64); */
/* [d u6 0 0 0 0 0 0 t9 0 0 c-u6*R0 t5 t4 t3 t2 t1 t0] = [p16 p15 p14 p13 p12 p11 p10 p9 0 0 p6 p5 p4 p3 p2 p1 p0] */
t6 = c & M; c >>= 26; c += u6 * R1;
/* [d u6 0 0 0 0 0 0 t9 0 c-u6*R1 t6-u6*R0 t5 t4 t3 t2 t1 t0] = [p16 p15 p14 p13 p12 p11 p10 p9 0 0 p6 p5 p4 p3 p2 p1 p0] */
/* [d 0 0 0 0 0 0 0 t9 0 c t6 t5 t4 t3 t2 t1 t0] = [p16 p15 p14 p13 p12 p11 p10 p9 0 0 p6 p5 p4 p3 p2 p1 p0] */
c += (ulong)a[0] * b[7]
+ (ulong)a[1] * b[6]
+ (ulong)a[2] * b[5]
+ (ulong)a[3] * b[4]
+ (ulong)a[4] * b[3]
+ (ulong)a[5] * b[2]
+ (ulong)a[6] * b[1]
+ (ulong)a[7] * b[0];
/* VERIFY_BITS(c, 64); */
/* [d 0 0 0 0 0 0 0 t9 0 c t6 t5 t4 t3 t2 t1 t0] = [p16 p15 p14 p13 p12 p11 p10 p9 0 p7 p6 p5 p4 p3 p2 p1 p0] */
d += (ulong)a[8] * b[9]
+ (ulong)a[9] * b[8];
/* [d 0 0 0 0 0 0 0 t9 0 c t6 t5 t4 t3 t2 t1 t0] = [p17 p16 p15 p14 p13 p12 p11 p10 p9 0 p7 p6 p5 p4 p3 p2 p1 p0] */
u7 = d & M; d >>= 26; c += u7 * R0;
t7 = c & M; c >>= 26; c += u7 * R1;
c += (ulong)a[0] * b[8]
+ (ulong)a[1] * b[7]
+ (ulong)a[2] * b[6]
+ (ulong)a[3] * b[5]
+ (ulong)a[4] * b[4]
+ (ulong)a[5] * b[3]
+ (ulong)a[6] * b[2]
+ (ulong)a[7] * b[1]
+ (ulong)a[8] * b[0];
/* VERIFY_BITS(c, 64); */
/* [d 0 0 0 0 0 0 0 0 t9 c t7 t6 t5 t4 t3 t2 t1 t0] = [p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */
d += (ulong)a[9] * b[9];
/* [d 0 0 0 0 0 0 0 0 t9 c t7 t6 t5 t4 t3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */
u8 = d & M; d >>= 26; c += u8 * R0;
/* [d u8 0 0 0 0 0 0 0 0 t9 c-u8*R0 t7 t6 t5 t4 t3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */
r[3] = t3;
r[4] = t4;
r[5] = t5;
r[6] = t6;
r[7] = t7;
r[8] = c & M; c >>= 26; c += u8 * R1;
c += d * R0 + t9;
r[9] = c & (M >> 4); c >>= 22; c += d * (R1 << 4);
d = c * (R0 >> 4) + t0;
r[0] = d & M; d >>= 26;
d += c * (R1 >> 4) + t1;
r[1] = d & M; d >>= 26;
d += t2;
r[2] = d;
}
void secp256k1_fe_mul(secp256k1_fe *r, const secp256k1_fe *a, const secp256k1_fe * b) {
secp256k1_fe_mul_inner(r->n, a->n, b->n);
}
void secp256k1_fe_add(secp256k1_fe *r, const secp256k1_fe *a) {
r->n[0] += a->n[0];
r->n[1] += a->n[1];
r->n[2] += a->n[2];
r->n[3] += a->n[3];
r->n[4] += a->n[4];
r->n[5] += a->n[5];
r->n[6] += a->n[6];
r->n[7] += a->n[7];
r->n[8] += a->n[8];
r->n[9] += a->n[9];
}
void secp256k1_fe_negate(secp256k1_fe *r, const secp256k1_fe *a, int m) {
r->n[0] = 0x3FFFC2FUL * 2 * (m + 1) - a->n[0];
r->n[1] = 0x3FFFFBFUL * 2 * (m + 1) - a->n[1];
r->n[2] = 0x3FFFFFFUL * 2 * (m + 1) - a->n[2];
r->n[3] = 0x3FFFFFFUL * 2 * (m + 1) - a->n[3];
r->n[4] = 0x3FFFFFFUL * 2 * (m + 1) - a->n[4];
r->n[5] = 0x3FFFFFFUL * 2 * (m + 1) - a->n[5];
r->n[6] = 0x3FFFFFFUL * 2 * (m + 1) - a->n[6];
r->n[7] = 0x3FFFFFFUL * 2 * (m + 1) - a->n[7];
r->n[8] = 0x3FFFFFFUL * 2 * (m + 1) - a->n[8];
r->n[9] = 0x03FFFFFUL * 2 * (m + 1) - a->n[9];
}
void secp256k1_fe_mul_int(secp256k1_fe *r, int a) {
r->n[0] *= a;
r->n[1] *= a;
r->n[2] *= a;
r->n[3] *= a;
r->n[4] *= a;
r->n[5] *= a;
r->n[6] *= a;
r->n[7] *= a;
r->n[8] *= a;
r->n[9] *= a;
}
void secp256k1_fe_set_int(secp256k1_fe *r, int a) {
r->n[0] = a;
r->n[1] = r->n[2] = r->n[3] = r->n[4] = r->n[5] = r->n[6] = r->n[7] = r->n[8] = r->n[9] = 0;
}
void secp256k1_fe_normalize_var(secp256k1_fe *r) {
uint t0 = r->n[0];
uint t1 = r->n[1];
uint t2 = r->n[2];
uint t3 = r->n[3];
uint t4 = r->n[4];
uint t5 = r->n[5];
uint t6 = r->n[6];
uint t7 = r->n[7];
uint t8 = r->n[8];
uint t9 = r->n[9];
/* Reduce t9 at the start so there will be at most a single carry from the first pass */
uint m;
uint x = t9 >> 22; t9 &= 0x03FFFFFUL;
/* The first pass ensures the magnitude is 1, ... */
t0 += x * 0x3D1UL; t1 += (x << 6);
t1 += (t0 >> 26); t0 &= 0x3FFFFFFUL;
t2 += (t1 >> 26); t1 &= 0x3FFFFFFUL;
t3 += (t2 >> 26); t2 &= 0x3FFFFFFUL; m = t2;
t4 += (t3 >> 26); t3 &= 0x3FFFFFFUL; m &= t3;
t5 += (t4 >> 26); t4 &= 0x3FFFFFFUL; m &= t4;
t6 += (t5 >> 26); t5 &= 0x3FFFFFFUL; m &= t5;
t7 += (t6 >> 26); t6 &= 0x3FFFFFFUL; m &= t6;
t8 += (t7 >> 26); t7 &= 0x3FFFFFFUL; m &= t7;
t9 += (t8 >> 26); t8 &= 0x3FFFFFFUL; m &= t8;
/* At most a single final reduction is needed; check if the value is >= the field characteristic */
x = (t9 >> 22) | ((t9 == 0x03FFFFFUL) & (m == 0x3FFFFFFUL)
& ((t1 + 0x40UL + ((t0 + 0x3D1UL) >> 26)) > 0x3FFFFFFUL));
if (x) {
t0 += 0x3D1UL; t1 += (x << 6);
t1 += (t0 >> 26); t0 &= 0x3FFFFFFUL;
t2 += (t1 >> 26); t1 &= 0x3FFFFFFUL;
t3 += (t2 >> 26); t2 &= 0x3FFFFFFUL;
t4 += (t3 >> 26); t3 &= 0x3FFFFFFUL;
t5 += (t4 >> 26); t4 &= 0x3FFFFFFUL;
t6 += (t5 >> 26); t5 &= 0x3FFFFFFUL;
t7 += (t6 >> 26); t6 &= 0x3FFFFFFUL;
t8 += (t7 >> 26); t7 &= 0x3FFFFFFUL;
t9 += (t8 >> 26); t8 &= 0x3FFFFFFUL;
t9 &= 0x03FFFFFUL;
}
r->n[0] = t0; r->n[1] = t1; r->n[2] = t2; r->n[3] = t3; r->n[4] = t4;
r->n[5] = t5; r->n[6] = t6; r->n[7] = t7; r->n[8] = t8; r->n[9] = t9;
}
void secp256k1_fe_clear(secp256k1_fe *a) {
int i;
for (i=0; i<10; i++) {
a->n[i] = 0;
}
}
void secp256k1_fe_inv(secp256k1_fe *r, const secp256k1_fe *a) {
secp256k1_fe x2, x3, x6, x9, x11, x22, x44, x88, x176, x220, x223, t1;
int j;
secp256k1_fe_sqr(&x2, a);
secp256k1_fe_mul(&x2, &x2, a);
secp256k1_fe_sqr(&x3, &x2);
secp256k1_fe_mul(&x3, &x3, a);
x6 = x3;
for (j=0; j<3; j++) {
secp256k1_fe_sqr(&x6, &x6);
}
secp256k1_fe_mul(&x6, &x6, &x3);
x9 = x6;
for (j=0; j<3; j++) {
secp256k1_fe_sqr(&x9, &x9);
}
secp256k1_fe_mul(&x9, &x9, &x3);
x11 = x9;
for (j=0; j<2; j++) {
secp256k1_fe_sqr(&x11, &x11);
}
secp256k1_fe_mul(&x11, &x11, &x2);
x22 = x11;
for (j=0; j<11; j++) {
secp256k1_fe_sqr(&x22, &x22);
}
secp256k1_fe_mul(&x22, &x22, &x11);
x44 = x22;
for (j=0; j<22; j++) {
secp256k1_fe_sqr(&x44, &x44);
}
secp256k1_fe_mul(&x44, &x44, &x22);
x88 = x44;
for (j=0; j<44; j++) {
secp256k1_fe_sqr(&x88, &x88);
}
secp256k1_fe_mul(&x88, &x88, &x44);
x176 = x88;
for (j=0; j<88; j++) {
secp256k1_fe_sqr(&x176, &x176);
}
secp256k1_fe_mul(&x176, &x176, &x88);
x220 = x176;
for (j=0; j<44; j++) {
secp256k1_fe_sqr(&x220, &x220);
}
secp256k1_fe_mul(&x220, &x220, &x44);
x223 = x220;
for (j=0; j<3; j++) {
secp256k1_fe_sqr(&x223, &x223);
}
secp256k1_fe_mul(&x223, &x223, &x3);
t1 = x223;
for (j=0; j<23; j++) {
secp256k1_fe_sqr(&t1, &t1);
}
secp256k1_fe_mul(&t1, &t1, &x22);
for (j=0; j<5; j++) {
secp256k1_fe_sqr(&t1, &t1);
}
secp256k1_fe_mul(&t1, &t1, a);
for (j=0; j<3; j++) {
secp256k1_fe_sqr(&t1, &t1);
}
secp256k1_fe_mul(&t1, &t1, &x2);
for (j=0; j<2; j++) {
secp256k1_fe_sqr(&t1, &t1);
}
secp256k1_fe_mul(r, a, &t1);
}
void secp256k1_fe_get_b32(unsigned char *r, const secp256k1_fe *a) {
r[0] = (a->n[9] >> 14) & 0xff;
r[1] = (a->n[9] >> 6) & 0xff;
r[2] = ((a->n[9] & 0x3F) << 2) | ((a->n[8] >> 24) & 0x3);
r[3] = (a->n[8] >> 16) & 0xff;
r[4] = (a->n[8] >> 8) & 0xff;
r[5] = a->n[8] & 0xff;
r[6] = (a->n[7] >> 18) & 0xff;
r[7] = (a->n[7] >> 10) & 0xff;
r[8] = (a->n[7] >> 2) & 0xff;
r[9] = ((a->n[7] & 0x3) << 6) | ((a->n[6] >> 20) & 0x3f);
r[10] = (a->n[6] >> 12) & 0xff;
r[11] = (a->n[6] >> 4) & 0xff;
r[12] = ((a->n[6] & 0xf) << 4) | ((a->n[5] >> 22) & 0xf);
r[13] = (a->n[5] >> 14) & 0xff;
r[14] = (a->n[5] >> 6) & 0xff;
r[15] = ((a->n[5] & 0x3f) << 2) | ((a->n[4] >> 24) & 0x3);
r[16] = (a->n[4] >> 16) & 0xff;
r[17] = (a->n[4] >> 8) & 0xff;
r[18] = a->n[4] & 0xff;
r[19] = (a->n[3] >> 18) & 0xff;
r[20] = (a->n[3] >> 10) & 0xff;
r[21] = (a->n[3] >> 2) & 0xff;
r[22] = ((a->n[3] & 0x3) << 6) | ((a->n[2] >> 20) & 0x3f);
r[23] = (a->n[2] >> 12) & 0xff;
r[24] = (a->n[2] >> 4) & 0xff;
r[25] = ((a->n[2] & 0xf) << 4) | ((a->n[1] >> 22) & 0xf);
r[26] = (a->n[1] >> 14) & 0xff;
r[27] = (a->n[1] >> 6) & 0xff;
r[28] = ((a->n[1] & 0x3f) << 2) | ((a->n[0] >> 24) & 0x3);
r[29] = (a->n[0] >> 16) & 0xff;
r[30] = (a->n[0] >> 8) & 0xff;
r[31] = a->n[0] & 0xff;
}
void secp256k1_ge_from_storage(secp256k1_ge *r, const secp256k1_ge_storage *a) {
secp256k1_fe_from_storage(&r->x, &a->x);
secp256k1_fe_from_storage(&r->y, &a->y);
}
void secp256k1_gej_set_ge(secp256k1_gej *r, const secp256k1_ge *a) {
r->x = a->x;
r->y = a->y;
secp256k1_fe_set_int(&r->z, 1);
}
void secp256k1_gej_add_ge_var(secp256k1_gej *r, const secp256k1_gej *a, const secp256k1_ge *b, secp256k1_fe *rzr) {
/* 8 mul, 3 sqr, 4 normalize, 12 mul_int/add/negate */
secp256k1_fe z12, u1, u2, s1, s2, h, i, i2, h2, h3, t;
secp256k1_fe_sqr(&z12, &a->z);
u1 = a->x; secp256k1_fe_normalize_weak(&u1);
secp256k1_fe_mul(&u2, &b->x, &z12);
s1 = a->y; secp256k1_fe_normalize_weak(&s1);
secp256k1_fe_mul(&s2, &b->y, &z12); secp256k1_fe_mul(&s2, &s2, &a->z);
secp256k1_fe_negate(&h, &u1, 1); secp256k1_fe_add(&h, &u2);
secp256k1_fe_negate(&i, &s1, 1); secp256k1_fe_add(&i, &s2);
secp256k1_fe_sqr(&i2, &i);
secp256k1_fe_sqr(&h2, &h);
secp256k1_fe_mul(&h3, &h, &h2);
if (rzr) {
*rzr = h;
}
secp256k1_fe_mul(&r->z, &a->z, &h);
secp256k1_fe_mul(&t, &u1, &h2);
r->x = t; secp256k1_fe_mul_int(&r->x, 2); secp256k1_fe_add(&r->x, &h3); secp256k1_fe_negate(&r->x, &r->x, 3); secp256k1_fe_add(&r->x, &i2);
secp256k1_fe_negate(&r->y, &r->x, 5); secp256k1_fe_add(&r->y, &t); secp256k1_fe_mul(&r->y, &r->y, &i);
secp256k1_fe_mul(&h3, &h3, &s1); secp256k1_fe_negate(&h3, &h3, 1);
secp256k1_fe_add(&r->y, &h3);
}
void secp256k1_ge_set_gej(secp256k1_ge *r, secp256k1_gej *a) {
secp256k1_fe z2, z3;
secp256k1_fe_inv(&a->z, &a->z);
secp256k1_fe_sqr(&z2, &a->z);
secp256k1_fe_mul(&z3, &a->z, &z2);
secp256k1_fe_mul(&a->x, &a->x, &z2);
secp256k1_fe_mul(&a->y, &a->y, &z3);
secp256k1_fe_set_int(&a->z, 1);
r->x = a->x;
r->y = a->y;
}
void secp256k1(const secp256k1_ge_storage *prec, unsigned char* result,
sycl::nd_item<3> item_ct1)
{
if (item_ct1.get_local_range().get(2) * item_ct1.get_group(2) +
item_ct1.get_local_id(2)) return;
secp256k1_ge ge[512];
secp256k1_gej sum;
secp256k1_ge_from_storage(&ge[0], &prec[0]);
secp256k1_gej_set_ge(&sum, &ge[0]);
secp256k1_fe z_all = sum.z;
for (uint i=1; i<512; ++i) {
secp256k1_ge_from_storage(&ge[i], &prec[i]);
secp256k1_gej_add_ge_var(&sum, &sum, &ge[i], 0);
secp256k1_fe_mul(&z_all, &z_all, &sum.z);
}
secp256k1_fe_inv(&z_all, &z_all);
secp256k1_fe_get_b32(result, &z_all);
}
int main(int argc, char **argv) {
dpct::device_ext &dev_ct1 = dpct::get_current_device();
sycl::queue &q_ct1 = dev_ct1.default_queue();
secp256k1_ge_storage prec[512] = {
SC(983487347u, 1861041900u, 2599115456u, 565528146u, 1451326239u, 148794576u, 4224640328u, 3120843701u, 2076989736u, 3184115747u, 3754320824u, 2656004457u, 2876577688u, 2388659905u, 3527541004u, 1170708298u),
SC(3830281845u, 3284871255u, 1309883393u, 2806991612u, 1558611192u, 1249416977u, 1614773327u, 1353445208u, 633124399u, 4264439010u, 426432620u, 167800352u, 2355417627u, 2991792291u, 3042397084u, 505150283u),
SC(1792710820u, 2165839471u, 3876070801u, 3603801374u, 2437636273u, 1231643248u, 860890267u, 4002236272u, 3258245037u, 4085545079u, 2695347418u, 288209541u, 484302592u, 139267079u, 14621978u, 2750167787u),
SC(11094760u, 1663454715u, 3104893589u, 1290390142u, 1334245677u, 2671416785u, 3982578986u, 2050971459u, 2136209393u, 1792200847u, 367473428u, 114820199u, 1096121039u, 425028623u, 3983611854u, 923011107u),
SC(461660907u, 483260338u, 3090624303u, 3468817529u, 2869411999u, 3408320195u, 157674611u, 1298485121u, 103769941u, 3030878493u, 1440637991u, 4223892787u, 3840844824u, 2730509202u, 2748389383u, 214732837u),
SC(3283443609u, 2631471420u, 264982313u, 3187722117u, 3429945793u, 4056928493u, 1497022093u, 638309051u, 2303031563u, 1452679770u, 476716869u, 493553758u, 3454202674u, 3741745777u, 4129790071u, 1829770666u),
SC(2763266881u, 438653250u, 3999405133u, 158126044u, 2748183974u, 2939338200u, 3519271531u, 3601510585u, 987660138u, 698279276u, 698337965u, 1923172050u, 1658527181u, 782345045u, 3605004948u, 15611075u),
SC(3568265158u, 1979285296u, 1247944677u, 876477019u, 3828537841u, 1131777357u, 1658789385u, 3080372200u, 3506349824u, 713366149u, 865246815u, 524407977u, 1757013280u, 1813640112u, 902731429u, 313923873u),
SC(1793692126u, 406948681u, 23075151u, 2805328754u, 3264854407u, 427926777u, 2859563730u, 198037267u, 2129133850u, 1089701106u, 3842694445u, 2533380467u, 663211132u, 2312829798u, 807127373u, 38506815u),
SC(3263300518u, 3774427737u, 2005654986u, 284791998u, 1741605027u, 278724609u, 3627067623u, 3025303883u, 417282626u, 3961829139u, 717534956u, 3715499492u, 379232378u, 1104631198u, 3186100441u, 3153840916u),
SC(1212722614u, 2956266711u, 3074799107u, 3489045995u, 2346779929u, 3422717980u, 1268253015u, 1446357559u, 2055290998u, 410965945u, 2228272741u, 3002612624u, 844382671u, 1412583811u, 3199209782u, 3592866396u),
SC(1365068159u, 4067744317u, 2612651255u, 3786899082u, 2944769362u, 3195829907u, 253325927u, 3611092398u, 3664021332u, 173986934u, 1068324321u, 3913258631u, 757066081u, 3024665023u, 742574213u, 3024517360u),
SC(1686440452u, 1988561476u, 754604000u, 1313277943u, 3972816537u, 316394247u, 994407191u, 1904170630u, 2086644946u, 2443632379u, 2709748921u, 1003213045u, 3157743406u, 1758245536u, 3227689301u, 1181052876u),
SC(3282977068u, 2749755947u, 1149647537u, 3051767577u, 2567408320u, 223888601u, 1782024607u, 1040598133u, 3834763422u, 3012232259u, 1356426753u, 2074929973u, 262201927u, 2358783269u, 1512715052u, 597559892u),
SC(3878434820u, 2809459675u, 1110739075u, 695947317u, 3386718576u, 2117846541u, 31792705u, 3621315477u, 3821755067u, 3284294059u, 182757u, 4194671632u, 4268712763u, 1335482921u, 1639518590u, 1643885655u),
SC(1786486241u, 2367070434u, 456182625u, 898034630u, 2025195032u, 3803471405u, 2358553865u, 908230516u, 2887759669u, 2518324u, 3952697231u, 2446050105u, 258193126u, 3175909872u, 3613423880u, 1973719439u),
SC(2450731413u, 2768047193u, 2114778718u, 2363611449u, 3811833768u, 1142236074u, 836975073u, 719658637u, 89564040u, 2055034782u, 2279505737u, 2354364196u, 748992674u, 2341838369u, 3471590741u, 3103440079u),
SC(457107339u, 234212267u, 2808385829u, 1082467153u, 1613477208u, 3837699379u, 3685781168u, 698018196u, 2584486245u, 1427273599u, 4207275348u, 3102061774u, 3618025853u, 1681886269u, 3491183254u, 61130666u),
SC(1810095661u, 485189292u, 516764725u, 1059330697u, 3450816756u, 2832552490u, 493813891u, 1011558969u, 2296450464u, 3845885786u, 2913000318u, 3788404162u, 143232350u, 359561087u, 2060204960u, 2683204223u),
SC(3012330212u, 1040538075u, 1731389562u, 2092033766u, 1634006770u, 629989472u, 1831049270u, 1526328333u, 2651817972u, 2636385075u, 3694287824u, 1240070853u, 1803183336u, 1475508921u, 2910213636u, 803501651u),
SC(2925506593u, 3911544000u, 1647760999u, 3077282783u, 810174083u, 3532746750u, 1218244633u, 1800164995u, 3882366571u, 1552758454u, 417617232u, 3581187042u, 1107218813u, 308444727u, 2996521844u, 3546298006u),
SC(3841529585u, 2842543837u, 2288494105u, 4277587815u, 351020610u, 316127787u, 347470810u, 3045389113u, 3024639459u, 1038031284u, 837880241u, 3673071900u, 873110232u, 3246094570u, 3382157003u, 2031890941u),
SC(1269604407u, 1685288902u, 4078202316u, 3610423837u, 843356019u, 4116145876u, 3730514843u, 788045418u, 1354018886u, 3118713525u, 234872570u, 4197470289u, 2077961707u, 10213883u, 2638019744u, 883368488u),
SC(2256371012u, 1933806057u, 1899377954u, 2639211579u, 3217452631u, 1151725597u, 479445505u, 2647913315u, 3921232647u, 3013405541u, 1698636294u, 4291348568u, 929386421u, 2431356191u, 615106606u, 3635728912u),
SC(2016238746u, 3648008750u, 3741265531u, 1468285316u, 3314132186u, 3225615603u, 2260838904u, 650230459u, 666608997u, 1079817106u, 1685466519u, 3417306450u, 465799968u, 1454367507u, 1432699603u, 4060146438u),
SC(218622838u, 3144062173u, 1298227431u, 1296710013u, 2520686898u, 259313849u, 3925040134u, 8587584u, 45611266u, 1657172483u, 3606314124u, 759386889u, 2140045562u, 3265737381u, 3755961838u, 2873618455u),
SC(917499604u, 3075502984u, 677364865u, 199957985u, 3163427900u, 3464203846u, 2082349760u, 962588488u, 1394141129u, 1751216552u, 3471834965u, 1070173761u, 3655391113u, 2733146365u, 1686618869u, 1417767575u),
SC(3485619732u, 4237744401u, 38484852u, 2062357581u, 2253809979u, 2726578484u, 3538837931u, 2876850528u, 4204679835u, 3188932578u, 2204025751u, 2972778279u, 410709981u, 3746713296u, 2682061958u, 1559674900u),
SC(3955300819u, 2390314746u, 8780989u, 1526705205u, 4147934248u, 1494146575u, 1667625450u, 2277923659u, 406493586u, 957460913u, 3449491434u, 912766689u, 1387230361u, 2368913075u, 3538729245u, 2943257094u),
SC(1164835523u, 3258525964u, 862788422u, 3915615186u, 1495565500u, 4151116061u, 273476183u, 3708703079u, 1646675285u, 2380697417u, 386566820u, 303735559u, 931759265u, 1991815164u, 605297126u, 2505048137u),
SC(1896909316u, 2768974072u, 703676943u, 194614458u, 944517104u, 2321028722u, 3813034930u, 2482042710u, 4285153324u, 3947936591u, 2061596288u, 1167021054u, 224557835u, 3701623985u, 2956197594u, 4068261876u),
SC(4163247502u, 3935767334u, 4212387073u, 3469038512u, 2742333502u, 3242681324u, 333877241u, 186752825u, 1022261243u, 1852327832u, 1749655104u, 4248042849u, 3829051933u, 2527510392u, 903534280u, 803873799u),
SC(3159079334u, 690659487u, 1550245019u, 1719420482u, 1795694879u, 2846363486u, 15987067u, 569538014u, 1561199762u, 967336684u, 3110376818u, 1863433225u, 3468533545u, 3644881587u, 369296717u, 3652676359u),
SC(3438533039u, 1129158329u, 4254995182u, 1172977752u, 1348513792u, 2305760743u, 2805600929u, 1063476339u, 2130605077u, 2318963631u, 222333708u, 4242117337u, 3488879344u, 4152191644u, 1566216757u, 3511639585u),
SC(414049395u, 518193567u, 2908103152u, 3485521646u, 3127487288u, 4257875118u, 4275953437u, 4190818731u, 514254035u, 1676790779u, 3922795604u, 3266003876u, 1240031503u, 615951860u, 1147425993u, 3283995888u),
SC(2344637795u, 454276177u, 1520037565u, 2206099433u, 3893016787u, 1492026382u, 826322062u, 320651796u, 3470670522u, 2971363985u, 1324478262u, 817963303u, 3145830089u, 3033771320u, 2850457153u, 175864218u),
SC(3370489298u, 1718569235u, 523721575u, 2176389434u, 218587365u, 2490878487u, 2288222859u, 812943600u, 2821517993u, 3626217235u, 1545838667u, 3155352961u, 741681736u, 669093936u, 2382929309u, 2620482966u),
SC(3516186683u, 4285635092u, 112960057u, 4231926357u, 1983367601u, 811638777u, 352425005u, 881406190u, 1586726870u, 1270641374u, 969572673u, 3334919462u, 5443202u, 1202991457u, 1920039784u, 684835265u),
SC(3487926112u, 1421368619u, 3777105084u, 683300340u, 1372273739u, 519164830u, 3090058277u, 1966650929u, 2808179530u, 4082516040u, 3050161853u, 2955217595u, 2870730035u, 2812368983u, 823237926u, 2499759082u),
SC(420116030u, 1479628345u, 1468919607u, 1408524558u, 1518349049u, 3834068286u, 2352056000u, 3827608642u, 2975259269u, 3091607462u, 2214091902u, 1601277655u, 882989506u, 1528352914u, 408941671u, 2340962541u),
SC(1239892635u, 3772349433u, 1058531752u, 1409211242u, 2847698653u, 2391143499u, 2637108329u, 3000217976u, 4288568828u, 658925470u, 2552628125u, 1468771377u, 3230644908u, 2692030796u, 7587087u, 1951830015u),
SC(736995476u, 1747351270u, 1163114u, 2026562345u, 3261810630u, 595398226u, 1638337436u, 913924615u, 272242905u, 2792905424u, 556386843u, 2525187487u, 4052079772u, 3989946451u, 2527644148u, 3709255190u),
SC(2516714890u, 4242544138u, 1891445298u, 1825827611u, 3858741928u, 3764110043u, 4223255299u, 2068094187u, 33167132u, 1747162056u, 723745040u, 45767848u, 2130314563u, 3100468655u, 3727838996u, 3428029531u),
SC(294456146u, 4095270098u, 3062253927u, 2761923976u, 2157913192u, 2344315975u, 3331272375u, 3152522033u, 820771632u, 3121327106u, 1472157325u, 1201372141u, 722801401u, 866820160u, 1231468285u, 6166136u),
SC(2585638847u, 1394876113u, 3750575776u, 4144761638u, 1991524028u, 3165938218u, 158354186u, 812072970u, 3814951634u, 2507408645u, 1163603486u, 3566585210u, 1424854671u, 3326584505u, 3332079056u, 1901915986u),
SC(3049477029u, 3362467146u, 2600501326u, 4030960217u, 861735902u, 2447190956u, 2775043422u, 676062106u, 1538957086u, 2273140237u, 35534925u, 1390310379u, 2599406245u, 320935889u, 769230025u, 1241866977u),
SC(863633986u, 1656356192u, 687209691u, 3257947459u, 944771286u, 2566595978u, 3586284316u, 1249271789u, 3782853115u, 3597787480u, 906300809u, 1224395132u, 1470876390u, 2044968575u, 384666520u, 2229055507u),
SC(3972015306u, 1678690614u, 4158796299u, 1477735526u, 1751460077u, 1469605328u, 4128666344u, 1047203608u, 2704497527u, 3719371097u, 617877068u, 2166818425u, 655329252u, 361395292u, 2368569612u, 4000326891u),
SC(1355623958u, 2575138117u, 2562403739u, 1638722303u, 1523970956u, 2189861089u, 3498071469u, 1919711232u, 231840827u, 3230371223u, 143629793u, 1497495034u, 1677900731u, 1608282251u, 3485501508u, 3944969019u),
SC(886482870u, 1933309417u, 2926226694u, 1591769403u, 1331567529u, 2547948025u, 2272381527u, 2180719490u, 586729206u, 3698459560u, 1407601905u, 3690098029u, 3797283007u, 3185415432u, 2807683983u, 743820249u),
SC(2220406124u, 2553072517u, 2268184905u, 3807611008u, 962123447u, 1442022786u, 3119831387u, 2245144291u, 3048799325u, 765814649u, 2779802501u, 3050337097u, 2600783793u, 763045554u, 3651452740u, 1057016581u),
SC(3451851559u, 864607561u, 3244543542u, 2370117179u, 1371306276u, 390003720u, 929868877u, 1869850698u, 3531949911u, 419075495u, 427342596u, 1585514844u, 4047650117u, 3845372526u, 2912023567u, 2794855722u),
SC(1272080061u, 1249052793u, 3406223580u, 3180222548u, 3305857569u, 3627944464u, 989639337u, 2790050407u, 2758101533u, 2203734512u, 1518825984u, 392742217u, 2425492197u, 2028188113u, 3750975833u, 2472872035u),
SC(1718022296u, 3226292642u, 1620876982u, 1500366440u, 376656245u, 341364049u, 1509276702u, 747008556u, 1290140362u, 1157790902u, 2242566110u, 3911630441u, 2511480601u, 3638098785u, 638568919u, 1655301243u),
SC(2276743600u, 1849567056u, 822640453u, 2045065240u, 4229957379u, 1506967879u, 2910446490u, 1217165739u, 643217741u, 3543926561u, 3104741404u, 3028146784u, 375929280u, 475833070u, 1989644595u, 2186093704u),
SC(2198523688u, 3232341965u, 253572105u, 3392169722u, 4019005050u, 128871332u, 90164917u, 2138503228u, 2857287832u, 1362500931u, 2738484248u, 2727207447u, 2851366108u, 651094618u, 2926884083u, 423254183u),
SC(35118683u, 172484830u, 3416100291u, 3700412376u, 540823883u, 3117923166u, 4211300427u, 2853939967u, 3346783680u, 988896867u, 2435731911u, 431849862u, 1744411117u, 2614624696u, 297543835u, 4045956333u),
SC(3853250884u, 2621927678u, 3061260391u, 2978860545u, 4020966302u, 4037334842u, 4009723534u, 1680189348u, 3127049287u, 1501424269u, 1271732744u, 2004026132u, 2179623312u, 2037000629u, 2495416023u, 3576889736u),
SC(1771970765u, 993135396u, 2274060952u, 1278425303u, 1173961441u, 2812998499u, 3792378081u, 2339180374u, 1711421197u, 1710211379u, 2213420101u, 3131984485u, 4023294968u, 11317443u, 3488462274u, 156186322u),
SC(1828023928u, 3606416364u, 840451334u, 2670120381u, 133606952u, 3979411971u, 3756265636u, 3090434524u, 1277480081u, 4153236500u, 1762321014u, 2309317937u, 888707593u, 3246269083u, 985085852u, 1839210952u),
SC(1981590337u, 957784565u, 3778147127u, 3909235993u, 1637480329u, 2280601867u, 1059949562u, 2968107974u, 4043469535u, 4159249472u, 895867525u, 402468881u, 3186079639u, 86430659u, 4027560590u, 4067278225u),
SC(3963997938u, 839996031u, 571331525u, 776702142u, 2399863185u, 3655810429u, 1738528605u, 2929574574u, 2886156335u, 3352266884u, 2399200150u, 1119216390u, 2001330442u, 1142692018u, 1684746191u, 1064710302u),
SC(1881361970u, 1643307161u, 2706528897u, 2595735846u, 3177654277u, 15545698u, 1429642476u, 2237750939u, 2019191955u, 4066851471u, 3438523186u, 56173305u, 546163438u, 1764934268u, 3101952782u, 3383780192u),
SC(2815008973u, 3278450586u, 1220182791u, 3732977113u, 2153332463u, 2653121522u, 1237936443u, 204190827u, 3561117875u, 2030804130u, 157509268u, 1855899717u, 1044294897u, 2837786770u, 2814153431u, 1654668604u),
SC(1622151271u, 634353693u, 3884689189u, 1079019159u, 1060108012u, 22091029u, 115446660u, 534633082u, 1649201031u, 4042006969u, 137296836u, 1833810040u, 1562442638u, 3756418044u, 1181092791u, 160208619u),
SC(1562663069u, 1589588588u, 2484720953u, 4033553041u, 1119890702u, 1146448444u, 124974212u, 1823967544u, 800515771u, 1973272503u, 1462074657u, 1124483621u, 3203313474u, 1285141542u, 2854738281u, 3562644896u),
SC(1138023289u, 2038391829u, 2468643683u, 949488564u, 1016086543u, 2795023162u, 3124274336u, 2612082433u, 3803893695u, 3091535834u, 4021346615u, 1737416887u, 3153001828u, 1918263949u, 2128561912u, 952524797u),
SC(3943586865u, 3646894885u, 2019127100u, 2315419208u, 1161518116u, 1292249075u, 3489387539u, 4173675954u, 691560448u, 2084345818u, 3423296048u, 444365932u, 2317205473u, 1398327084u, 1604520210u, 1666009611u),
SC(2802315204u, 2299944053u, 2128407100u, 3463617348u, 2448441666u, 1070000794u, 1884246751u, 210372176u, 4075251068u, 1818330260u, 3223083664u, 3496698459u, 3376508259u, 4156094473u, 3718580079u, 1962552466u),
SC(194186124u, 2794320749u, 2159380922u, 1927129131u, 1345048290u, 3415779817u, 2512593755u, 1165677766u, 2073034551u, 2574315956u, 437435054u, 4150429800u, 4248768515u, 3178144834u, 1180015424u, 975080438u),
SC(174928435u, 4158717980u, 4003608508u, 3561506628u, 2852686007u, 2729724802u, 1504002726u, 3235296594u, 221206386u, 29543360u, 1903809106u, 1019269350u, 2488604738u, 2948288996u, 833023923u, 2449909516u),
SC(3252518325u, 3856416592u, 721985911u, 2562399482u, 2949653074u, 467584997u, 4100275835u, 855886762u, 1434875587u, 14835128u, 3295402243u, 782094626u, 2843868240u, 3417958407u, 360641371u, 1444533180u),
SC(1862109024u, 2933191225u, 198801920u, 104305860u, 4011109577u, 4122560610u, 1283427153u, 1072910968u, 1957473321u, 1766609671u, 2854361911u, 4075423370u, 2724854995u, 3336067759u, 2831739585u, 400030103u),
SC(3453383733u, 3388805506u, 2297889713u, 531949640u, 2594355026u, 842506873u, 3392184606u, 3495815509u, 345903420u, 1239109165u, 3176194045u, 3176389873u, 2777114661u, 3657799448u, 3763821885u, 4086593267u),
SC(2969423736u, 2622529529u, 2343792056u, 3686453319u, 918349654u, 3813685053u, 195351634u, 2215651341u, 2089448784u, 2444413637u, 2876364832u, 2226337257u, 3056652007u, 707231250u, 3702539781u, 561282206u),
SC(3049935789u, 2012305053u, 2921080511u, 2225835633u, 2565015038u, 3793044966u, 4088579892u, 2862703090u, 248082141u, 2196577601u, 3431211987u, 196767056u, 1180294796u, 2924949673u, 2696237025u, 632085300u),
SC(770670183u, 2030489407u, 913827766u, 28354808u, 2556411291u, 589717159u, 413516142u, 20574376u, 1695189435u, 3750527782u, 3546610407u, 1435363367u, 2770958348u, 2608593137u, 3331479090u, 2086258508u),
SC(2222779586u, 4077859027u, 1090454134u, 2439504603u, 2544922883u, 2183064830u, 1678763169u, 3019219083u, 240763984u, 1050801371u, 206241990u, 3854111478u, 2108674322u, 1500986470u, 222791553u, 3140762944u),
SC(1096246859u, 1269433403u, 2629392854u, 2527728897u, 1446363080u, 2718672644u, 3058137775u, 2846858917u, 65293585u, 1126911579u, 2537719558u, 1249408641u, 5386238u, 686469873u, 367377622u, 3559877098u),
SC(1733527990u, 843256705u, 3149977067u, 552818346u, 826377225u, 245961995u, 2860489859u, 1102123594u, 2576762322u, 2048301596u, 3733352267u, 2926653552u, 3115547804u, 2744342141u, 2395800773u, 2243429789u),
SC(2533741935u, 4150033708u, 3133949860u, 2798619408u, 806119564u, 266064305u, 1385120185u, 1697466874u, 3309272849u, 2305765083u, 4237655511u, 751372374u, 3319766406u, 1139025033u, 1880631363u, 2216696728u),
SC(3979749264u, 1427446648u, 1315917960u, 3919278201u, 3527447043u, 3230304145u, 1984210489u, 2055954841u, 2226125452u, 1654657180u, 2952993132u, 623472013u, 1564350724u, 3251441858u, 510917329u, 977717921u),
SC(555905577u, 3101608559u, 3271774689u, 1980231577u, 37536760u, 162179656u, 2522957948u, 2067517667u, 168118855u, 4239087243u, 4173152820u, 2782395372u, 2971506401u, 2855982516u, 2298196997u, 2806218529u),
SC(1509040764u, 850370852u, 2577061459u, 2207507581u, 3595322161u, 2000554477u, 4031870545u, 814805117u, 323551199u, 3635260690u, 1131475336u, 3484712926u, 2821291631u, 245369191u, 1885454182u, 3761964146u),
SC(1529327297u, 3326406825u, 3128910982u, 2593525414u, 42156971u, 3661621938u, 1244490461u, 1967679138u, 1025455708u, 720268318u, 2871990393u, 1117479541u, 1562094725u, 697888549u, 2324777980u, 3391621955u),
SC(670055855u, 2742056506u, 3803464832u, 2073978745u, 2472669135u, 3453468195u, 1816736658u, 4052898812u, 4008573063u, 3448716784u, 2635548869u, 1651653718u, 831875200u, 3437956895u, 3239576879u, 2353313279u),
SC(3540113602u, 2373194703u, 848875413u, 528313402u, 781027054u, 3320052693u, 3893252952u, 1213587531u, 1750521841u, 1586788154u, 1180481180u, 2340391265u, 2727907152u, 4257315287u, 1672030901u, 3645579941u),
SC(2340972299u, 1929183944u, 1603744771u, 1385803033u, 1212945255u, 3358157939u, 304971975u, 2614002695u, 3381353004u, 990731332u, 848780301u, 852035476u, 1672340734u, 2462927940u, 1317954734u, 2047198676u),
SC(1397828129u, 1248172308u, 2194412927u, 3657598991u, 2085616102u, 1202270518u, 3253032741u, 2632389423u, 1019922267u, 332153082u, 1521672215u, 2163564334u, 3102124007u, 582149809u, 329417494u, 188520915u),
SC(706617574u, 2365306746u, 3961476710u, 3754018908u, 3298852314u, 1319966498u, 2373924403u, 1735507527u, 2985653547u, 1063670015u, 639146151u, 2831556465u, 1223226703u, 2745053007u, 2392123951u, 3006439562u),
SC(1443727067u, 894328718u, 3897696342u, 2862419807u, 1663696040u, 737221545u, 4230565983u, 2037671469u, 3218417760u, 4096761229u, 2223583194u, 192457337u, 2437148391u, 40877205u, 3051452502u, 1404123256u),
SC(616809483u, 3741612436u, 3493946169u, 3863830933u, 661534585u, 1753652070u, 1053684102u, 1191387261u, 1681590552u, 3369920130u, 1353333435u, 3681089999u, 4172047522u, 46648183u, 4019180114u, 919466652u),
SC(87353816u, 3198238907u, 1232123158u, 3291424375u, 3695263554u, 2608617182u, 3798070797u, 3966302680u, 3847946128u, 278442153u, 3929504461u, 3056452729u, 3658519828u, 643043450u, 684101279u, 121314490u),
SC(686618621u, 168961360u, 2197925237u, 1613292190u, 333084038u, 3635587819u, 4032948519u, 3707964851u, 3158182099u, 234103179u, 2284298045u, 3480607911u, 1251956347u, 1974274694u, 4181171310u, 929438050u),
SC(2233115583u, 938378192u, 2199409274u, 1598252782u, 2330561833u, 3726791894u, 776218875u, 3411939105u, 1110676451u, 2474120935u, 2913066780u, 3957172359u, 1578191540u, 587569717u, 2523302528u, 125962068u),
SC(2121069653u, 2640792943u, 2787524602u, 1775169550u, 4137636069u, 1247634947u, 1593538354u, 2981021719u, 1013779675u, 3349939747u, 474464324u, 3800807983u, 274339632u, 2094850473u, 3469944008u, 4151365282u),
SC(3715433378u, 171840999u, 971741983u, 2238541363u, 3192426674u, 4094492328u, 467620204u, 194258737u, 3399274574u, 3279461044u, 1351137305u, 2503870624u, 193649547u, 2998335432u, 1712991547u, 2208648311u),
SC(2555428913u, 869421506u, 166778442u, 4153679692u, 1197236377u, 241935878u, 2637786338u, 1999265363u, 2897031456u, 2998251513u, 547086286u, 886498720u, 2308742633u, 352858212u, 3092243839u, 773593819u),
SC(337200504u, 1399030404u, 72828705u, 213399136u, 3202170111u, 3062657059u, 1061055118u, 494458775u, 156072464u, 4108660682u, 3361078208u, 2090300294u, 2971539355u, 3681445000u, 1744779607u, 686761302u),
SC(3277492425u, 3522618864u, 643530617u, 3964076639u, 1978509205u, 665325373u, 696169182u, 2592458243u, 2486397933u, 223447012u, 1604979091u, 2271093793u, 3084922545u, 3302858388u, 3031087250u, 1063516216u),
SC(3356584800u, 529363654u, 613773845u, 1186481398u, 3211505163u, 123165303u, 4059481794u, 1428486699u, 3074915494u, 3726640351u, 881339493u, 977699355u, 1396125459u, 3984731327u, 1086458841u, 3721516733u),
SC(269451735u, 989948209u, 311519596u, 3229759219u, 101715278u, 276003801u, 727203188u, 454624220u, 2155088951u, 2793076258u, 3170555468u, 952002920u, 2121796311u, 830563326u, 1562604453u, 3066628470u),
SC(399762888u, 2323422917u, 2321550379u, 207422836u, 1226652697u, 1825201637u, 528558453u, 3875352914u, 1719057328u, 2666562229u, 4176209563u, 583366985u, 1138701109u, 758289953u, 52662073u, 918293402u),
SC(4157388463u, 1842676713u, 2794772257u, 2114208937u, 1680405111u, 753984785u, 3430137608u, 1493849205u, 2172497743u, 3830022u, 4063929091u, 1999254948u, 153962958u, 491583925u, 4259603773u, 682388728u),
SC(3892284764u, 2210224198u, 97085365u, 934022966u, 3120556498u, 264721182u, 4011343025u, 1936310374u, 2593930315u, 3833725723u, 4141640186u, 2218699022u, 3726005369u, 649732123u, 1594208266u, 3687592104u),
SC(3661305541u, 3709834743u, 1851009402u, 3602780986u, 250666799u, 1173441109u, 3734473218u, 1804296154u, 1729282666u, 3439817738u, 1884765971u, 4096666384u, 3988665003u, 4256503802u, 2053222254u, 2853986610u),
SC(417666479u, 4268520051u, 3802974299u, 1841513928u, 4041007675u, 563789114u, 3533043334u, 1308819221u, 866092174u, 4038179869u, 4201939600u, 4066261022u, 1758380018u, 4091837615u, 4284827913u, 1677514005u),
SC(1723722734u, 2349413871u, 846419238u, 3229076191u, 3150004227u, 2361299214u, 1712354056u, 2351882123u, 2445958079u, 957461918u, 225210341u, 803052180u, 1590990979u, 660311212u, 2145699387u, 1393326672u),
SC(3639643416u, 3974502485u, 1527161781u, 180938703u, 2788643910u, 3418867931u, 2912046968u, 1776807950u, 1185488163u, 2433308651u, 3682797092u, 1938004308u, 753534320u, 795320477u, 3620835863u, 105275502u),
SC(989224491u, 3070290035u, 3989786823u, 2436788149u, 1397633359u, 2733484183u, 704304527u, 3349453652u, 3674136808u, 2104551350u, 4212497903u, 2460411350u, 3486955763u, 1761471520u, 1998184581u, 2495319592u),
SC(282793969u, 2332069888u, 1712291268u, 3517222842u, 20522682u, 1740053556u, 1372738943u, 2800828874u, 794545204u, 1363434049u, 3589633248u, 663242196u, 2153743019u, 3968122652u, 2744863688u, 2596121676u),
SC(2870523585u, 1439405869u, 2438119706u, 914848314u, 2262774649u, 404517167u, 1916976607u, 2681794713u, 3099128859u, 3707542208u, 4228984251u, 6546639u, 1922067157u, 500889948u, 714001381u, 3135300137u),
SC(3392929934u, 3483303263u, 1976307765u, 4193102460u, 1186037029u, 2559946979u, 3008510830u, 4008303279u, 2792795817u, 3991995u, 311426100u, 3736693519u, 1914150184u, 2000710916u, 1829538652u, 896726226u),
SC(3473142724u, 297762785u, 1185673220u, 3972225082u, 621899093u, 1819279104u, 1900431376u, 2221994154u, 2852913559u, 3581768407u, 3207817907u, 1428681774u, 3343330191u, 2165549552u, 211415337u, 1262086079u),
SC(1568159518u, 3414645127u, 3387315030u, 3545383094u, 3307092119u, 1871203699u, 3356344528u, 2208205606u, 1984240456u, 1553822824u, 1996586455u, 1093535414u, 751818141u, 2709522277u, 834332325u, 2996879219u),
SC(3252620262u, 1610725935u, 709542825u, 1181660454u, 4084478688u, 1130923555u, 2413678545u, 3248667340u, 2830530261u, 725536582u, 3850673996u, 2088519335u, 868155176u, 223946842u, 1968507343u, 1549963360u),
SC(2320406161u, 892569437u, 3092616448u, 1707673477u, 2810327980u, 4012118332u, 4142748730u, 3869507620u, 92116036u, 2366184953u, 1613655167u, 3287845172u, 3562699894u, 416962379u, 1296831910u, 1764080884u),
SC(45078160u, 3147040521u, 3977924485u, 1097174861u, 625925083u, 2053439479u, 3228340300u, 75304135u, 3524751472u, 1003341068u, 3156318916u, 1655110323u, 1486337360u, 3495426543u, 2205859914u, 4129504303u),
SC(179136070u, 2215032909u, 947400282u, 1721490941u, 3257375703u, 3746065879u, 2481020802u, 1203477754u, 1544186038u, 543550381u, 4085618153u, 1601848574u, 738032808u, 1321970306u, 2906258391u, 3047272421u),
SC(1249716000u, 458263861u, 2828755974u, 1760140511u, 1514147100u, 3407967019u, 3844060237u, 102517947u, 225529033u, 2639856492u, 1300412008u, 3897740626u, 3570441124u, 4093670214u, 3351362455u, 590024637u),
SC(1167035839u, 2632944828u, 1562396359u, 1120559767u, 244303722u, 181546963u, 2941229710u, 561240151u, 1460096143u, 346254175u, 110249239u, 1849542582u, 1293066381u, 147850597u, 3876457633u, 1458739232u),
SC(2533499636u, 3080420164u, 197200931u, 500624683u, 758387417u, 2720398129u, 1407768115u, 1475529124u, 1364265290u, 4069280537u, 1716757546u, 3709805168u, 1357954285u, 3857265562u, 3466627967u, 3830420311u),
SC(1593643391u, 105228547u, 3712827232u, 1923217888u, 1012568533u, 3355714151u, 528029511u, 3744649120u, 1997200748u, 2604985542u, 1803182035u, 939655107u, 288091786u, 2936799939u, 4234437447u, 4219765747u),
SC(4293306586u, 716919424u, 760979011u, 3536867423u, 4117027719u, 1461165141u, 807633747u, 3306967909u, 1327104245u, 4288993u, 1708394265u, 2341551077u, 4203016216u, 1355022627u, 2594871517u, 3003370353u),
SC(3539989726u, 2664422354u, 3717852078u, 3493347675u, 431408204u, 2534904428u, 166307432u, 1071633271u, 2817060747u, 2307358268u, 3433391820u, 2071844151u, 219511979u, 303896099u, 3062367591u, 2892429963u),
SC(1521430849u, 1321457442u, 1977165985u, 3332712657u, 3377259048u, 434866482u, 185442588u, 2655667572u, 1565093599u, 3283113197u, 1535104380u, 3878806555u, 2771912862u, 432083506u, 780421961u, 2441979755u),
SC(91851120u, 228847150u, 3596486782u, 2178535008u, 4219396564u, 341504363u, 1118079131u, 834044504u, 2324675143u, 2964510486u, 1663366491u, 339426068u, 2599455152u, 3701183831u, 1086709651u, 812090397u),
SC(3028475944u, 4191152422u, 1836925042u, 3223138538u, 685748126u, 646944669u, 4205775633u, 1329728837u, 3990855947u, 2092573299u, 1336025608u, 1375487930u, 2188514371u, 430312768u, 1649233533u, 1162542961u),
SC(3015000623u, 325176924u, 3212623969u, 1014540936u, 2686878702u, 3453922035u, 257234635u, 689320672u, 395365200u, 3425465866u, 3351439740u, 3293249321u, 2261203941u, 1504215424u, 2365812346u, 2486464854u),
SC(875927111u, 1597748031u, 3937158235u, 1433716656u, 3539791089u, 1352702162u, 1146570941u, 1210801675u, 2091841778u, 1252234389u, 1781967815u, 108023679u, 4156463906u, 1849298948u, 3158166728u, 978898853u),
SC(1342189835u, 1853962572u, 1334929275u, 2688310434u, 1583097217u, 3182342944u, 1463806924u, 1272330490u, 472090228u, 108343030u, 626158941u, 478208262u, 3294264195u, 2684195168u, 3152460770u, 2153166130u),
SC(3196336832u, 463403692u, 2914369607u, 77355408u, 1950461914u, 2402529709u, 553005914u, 1542102018u, 487903348u, 196020857u, 1813404195u, 4204446770u, 3295634806u, 2206606794u, 494127093u, 846727344u),
SC(771871546u, 3238832643u, 2874232693u, 1176661863u, 1772130049u, 1442937700u, 2722327092u, 1148976574u, 4122834849u, 744616687u, 1621674295u, 3475628518u, 2284524224u, 1048213347u, 4058663310u, 153122870u),
SC(3356509186u, 1884900443u, 4108545327u, 3986583476u, 758524745u, 1588296209u, 723393574u, 2862746860u, 2476163508u, 3679829155u, 1401397106u, 1667387791u, 2555611797u, 1998885507u, 3861616822u, 3016121396u),
SC(1082144930u, 2812004556u, 4059994359u, 3621635972u, 687684721u, 3983270965u, 3614380944u, 3981328064u, 767324997u, 4104345798u, 4184408595u, 520362170u, 766639361u, 2118637735u, 1480405192u, 3879741370u),
SC(2400086865u, 1356288676u, 2263936429u, 2831293204u, 528118727u, 762933811u, 1782971542u, 2357556867u, 1020395032u, 35590801u, 2105980457u, 2908398314u, 1176779916u, 965469552u, 4053114186u, 1203094477u),
SC(2470971363u, 1622646280u, 3521284388u, 611900249u, 53592433u, 1667691553u, 3986964859u, 3228144262u, 4160240678u, 1357358974u, 796266088u, 2135382104u, 2999113584u, 425466269u, 866665252u, 3795780335u),
SC(1942107538u, 2061531898u, 486277903u, 2831709377u, 3872945828u, 1947502926u, 3755578321u, 546304669u, 3256189062u, 3873222776u, 979380359u, 3587670204u, 1851918662u, 2435187337u, 1380244930u, 4186681845u),
SC(3850950458u, 1857044284u, 1191196687u, 401916778u, 1094802678u, 1136464563u, 2120150485u, 325136004u, 974963693u, 585059474u, 2531240419u, 1068453941u, 3498354420u, 4245078651u, 3921542910u, 198121299u),
SC(2145536262u, 1213879864u, 1118717819u, 3734026403u, 428130114u, 2135123466u, 4045420301u, 3479846205u, 381626330u, 1157860434u, 2785350296u, 637768566u, 2801530882u, 1480517018u, 2538790153u, 4077551317u),
SC(2899222640u, 2858879423u, 4023946212u, 3203519621u, 2698675175u, 2895781552u, 3987224702u, 3120457323u, 2482773149u, 4275634169u, 1626305806u, 2497520450u, 1604357181u, 2396667630u, 133501825u, 425754851u),
SC(1093436137u, 4178194477u, 4093951855u, 3277329686u, 2989824426u, 784494368u, 2625698979u, 525141656u, 833797048u, 1228803093u, 2037224379u, 1506767058u, 2140956084u, 3014084969u, 2249389870u, 2754500395u),
SC(3234726675u, 1387338169u, 2035693016u, 1580159315u, 2740014444u, 420358668u, 4193254905u, 3166557951u, 3035589053u, 3563526901u, 736535742u, 28001376u, 1900567167u, 1876824307u, 1708886960u, 2448346802u),
SC(3080860944u, 2883831675u, 924844138u, 165846124u, 403587242u, 2292097283u, 3928197057u, 375892634u, 2252310583u, 4209996391u, 3622004117u, 2707281828u, 2986420019u, 3342106111u, 83951999u, 411887793u),
SC(172527491u, 737404283u, 1378219848u, 1967891125u, 3449182151u, 391223470u, 304889116u, 3996348146u, 1311927616u, 1686958697u, 766780722u, 1429807050u, 1546340567u, 1151984543u, 3172111324u, 2189332513u),
SC(3210880994u, 2807853439u, 4215115106u, 907776530u, 73135694u, 2979353837u, 285477682u, 1377541714u, 546842365u, 1106807941u, 4178267211u, 4178357152u, 2629472682u, 1753007362u, 599552459u, 2136234403u),
SC(3236743822u, 2429982619u, 1421470122u, 1518357646u, 275483457u, 2785654877u, 405065849u, 3803799408u, 485052728u, 728694599u, 2522926080u, 2396484137u, 2970704111u, 366573577u, 2787456057u, 3096233215u),
SC(1028153825u, 101097231u, 3719093015u, 1499355615u, 1419801462u, 1110946460u, 271497731u, 588106554u, 1130341153u, 2430884299u, 326125271u, 3541499135u, 1876347220u, 2833401711u, 1027135976u, 641592145u),
SC(2759056966u, 2773771898u, 915395955u, 378399267u, 1065424189u, 3786627878u, 2430240867u, 1910948145u, 1268823138u, 2460932406u, 2049702377u, 3729301642u, 2270156417u, 2935515669u, 1488232015u, 333167852u),
SC(1130030158u, 1325805486u, 1928073773u, 3083689306u, 1906071689u, 2809061745u, 3188612193u, 3317879112u, 3567699092u, 531617155u, 968200745u, 3011814843u, 2232684249u, 3100416438u, 955880884u, 541389696u),
SC(3245402443u, 2411721740u, 362516442u, 179736723u, 1239928465u, 23431842u, 2304788940u, 1454698033u, 431248900u, 3858938538u, 1887822458u, 1775776127u, 653046597u, 2774049761u, 1414971814u, 1569319314u),
SC(704920417u, 4125239619u, 430148455u, 3015651212u, 2310935918u, 1678858669u, 3376497865u, 2535125909u, 400017377u, 1812558422u, 3188521745u, 3651390935u, 2345298458u, 3377548855u, 1062840923u, 3297700764u),
SC(1198357412u, 890731121u, 697460724u, 351217501u, 1219769569u, 940317437u, 2678867462u, 4175440864u, 2131908090u, 1470497863u, 3243074932u, 494367929u, 1767796005u, 457609517u, 3543955443u, 4149669314u),
SC(2890647893u, 2867067516u, 2762753699u, 2227974015u, 1022828403u, 2975716284u, 810630306u, 2107801738u, 1766778088u, 1878607300u, 1247804730u, 429284069u, 773180585u, 3038594965u, 2237573847u, 4237662217u),
SC(1135933156u, 634281942u, 46520021u, 3459499714u, 3745856618u, 2680896277u, 2214246977u, 1778311725u, 3755609700u, 1462691663u, 532464646u, 2021260220u, 3012125251u, 1892990074u, 1736371648u, 2739088972u),
SC(3804290341u, 2530898158u, 627690883u, 3467192350u, 3816583964u, 3490783256u, 2036783742u, 1974061789u, 4168871160u, 3978339846u, 4173216236u, 732951855u, 1616132185u, 4223609757u, 797743411u, 2206950663u),
SC(1331866444u, 3086683411u, 308412705u, 2554456370u, 2967351597u, 1733087234u, 827692265u, 2178921377u, 289799640u, 3318834771u, 2836568844u, 972864473u, 1500041772u, 4280362943u, 2447939655u, 904037199u),
SC(3391923614u, 2903769192u, 3834144138u, 2204143784u, 3953665264u, 1013613048u, 4275124566u, 2254380009u, 4175595257u, 2392625155u, 3832552958u, 2209848288u, 3564495648u, 2361851297u, 2215206748u, 2634903731u),
SC(3941037520u, 2365666457u, 1610398325u, 866573713u, 705163077u, 1512109211u, 2390458066u, 1976812875u, 2857084758u, 3708539243u, 854092926u, 2770390554u, 3156364591u, 136447390u, 1039322495u, 3637639253u),
SC(3679874068u, 3165524081u, 235657258u, 2056673906u, 270355292u, 701332141u, 3374210713u, 4100229496u, 2018939216u, 1505362994u, 989686331u, 2925442307u, 4179636623u, 637307973u, 3518037557u, 4240093409u),
SC(286197159u, 1217476806u, 1373931377u, 3573925838u, 1757245025u, 108852419u, 959661087u, 2721509987u, 123823405u, 395119964u, 4128806145u, 3492638840u, 789641269u, 663309689u, 1335091190u, 3909761814u),
SC(2114197930u, 3273217012u, 1940661926u, 2163906966u, 2123303670u, 414878308u, 233356929u, 871664495u, 3069135830u, 1535289677u, 3883199366u, 1672311108u, 4029021246u, 3634506188u, 2941888534u, 1547199375u),
SC(3960259180u, 1615091325u, 1620898588u, 3363101089u, 2219794907u, 934039044u, 273251845u, 3349991112u, 536889464u, 1065166606u, 2165591368u, 3968048577u, 3521960647u, 1972440812u, 2996053529u, 3367680654u),
SC(2485891685u, 1835858186u, 72029953u, 1996135211u, 3815169470u, 4242647100u, 3409890124u, 1431709388u, 3766365750u, 713252238u, 828380183u, 4212677126u, 346703256u, 1754695691u, 4057960681u, 2858172583u),
SC(136266275u, 1782161742u, 3530966629u, 586004249u, 4076565170u, 3312577895u, 876489815u, 1337331291u, 888213221u, 1813863938u, 1374206604u, 2668794769u, 1377764865u, 784024905u, 1937217146u, 3627318859u),
SC(4186161750u, 3049560710u, 1810996291u, 1342717770u, 2124217256u, 1916618560u, 4136670260u, 994193328u, 299707519u, 382044359u, 3598048722u, 3196118917u, 1358315449u, 521912342u, 3156838683u, 4122728661u),
SC(939267225u, 2510882408u, 2826027661u, 2396536978u, 3106471061u, 742759533u, 13494147u, 684275437u, 3769662715u, 1875002414u, 1146684269u, 3167752575u, 3278332143u, 789595870u, 392640294u, 2752714463u),
SC(1341948462u, 2439353587u, 4194335954u, 1747913821u, 2444768684u, 3688508118u, 985904958u, 1351917941u, 1073165051u, 1471080717u, 2911301092u, 1526345240u, 3378121335u, 3603759243u, 298408956u, 3700586563u),
SC(768143995u, 3015559849u, 803917440u, 4076216623u, 2181646206u, 1394504907u, 4103550766u, 2586780259u, 2146132903u, 2528467950u, 4288774330u, 4277434230u, 4233079764u, 751685015u, 1689565875u, 271910800u),
SC(3281376452u, 3631727304u, 646324697u, 1606373178u, 3213071634u, 3331180703u, 2195122007u, 3549662455u, 188195908u, 2766615075u, 541563331u, 3750074457u, 2301537882u, 1938050313u, 2637425350u, 930585210u),
SC(3541324984u, 3025021488u, 961967352u, 2883342260u, 1791115953u, 1760623833u, 3315383837u, 3369251966u, 3315911652u, 1871148493u, 2491604498u, 1271874682u, 350706514u, 1961904735u, 3348178007u, 3810151810u),
SC(3241391980u, 2699509892u, 2994316388u, 3715979957u, 2191426308u, 2911623554u, 3001094818u, 2672108146u, 1002718225u, 1706079745u, 2478567249u, 1679500649u, 2776278473u, 1632698291u, 2473525446u, 3057863552u),
SC(294473811u, 4198428764u, 2165111046u, 977342291u, 950658751u, 1362860671u, 1381568815u, 4165654500u, 2742156443u, 3373802792u, 668387394u, 853861450u, 2637359866u, 2230427693u, 2824878545u, 103849618u),
SC(703667981u, 341297647u, 1986045687u, 4022611577u, 4119515932u, 502525570u, 864382000u, 408568146u, 1623993579u, 1515217702u, 1701976571u, 1519123656u, 220794715u, 503707450u, 1598098448u, 1792646128u),
SC(2876602938u, 2062812830u, 592002095u, 964212911u, 1742157290u, 2453152641u, 1920771744u, 3744498389u, 861815181u, 448965745u, 2175363707u, 2098578783u, 4173783874u, 2208989085u, 145625870u, 3688955201u),
SC(938020790u, 186217808u, 349235829u, 519257124u, 2685242610u, 1590527094u, 2329590692u, 1198678263u, 2429439347u, 1981005487u, 1049116726u, 1349644548u, 193504650u, 2496138058u, 20076180u, 1915403182u),
SC(1451965994u, 766802222u, 1324674662u, 350355960u, 2823290314u, 951779387u, 2914020724u, 508533147u, 1932833685u, 1640746212u, 1238908653u, 542788672u, 3642566481u, 2475403216u, 1859773861u, 3791645308u),
SC(2385975325u, 3901946471u, 1059505820u, 4136894980u, 3371558324u, 2046981257u, 3127837356u, 3095019775u, 2618964688u, 3208744403u, 2271447215u, 3562826422u, 3752327158u, 2498335203u, 250644830u, 2105168329u),
SC(3475923760u, 323425264u, 3484578422u, 2657477806u, 138246715u, 2224032426u, 1026741249u, 1436653171u, 3097535946u, 3954907075u, 153306250u, 1987577071u, 1136330091u, 1917088242u, 95455667u, 3967280211u),
SC(2886596919u, 3537263282u, 3871156396u, 1985289080u, 3165778829u, 2180614377u, 1071823085u, 1946857657u, 4115069682u, 302722706u, 1817120536u, 1238106603u, 2202932230u, 3047902548u, 3208297762u, 725675045u),
SC(2083716311u, 321936583u, 1157386229u, 758210093u, 3570268096u, 833886820u, 3681471481u, 4249803963u, 2130717687u, 3101800692u, 172642091u, 421697598u, 4220526099u, 1506535732u, 2318522651u, 2076732404u),
SC(208856640u, 4030733534u, 2480428900u, 575090910u, 2370193275u, 1401235634u, 1396054131u, 3388186107u, 1461125298u, 3044442692u, 1666455609u, 2712178876u, 3699523129u, 175969151u, 2654070857u, 1480298430u),
SC(1006030828u, 2198412446u, 471722680u, 1651593837u, 2644180195u, 520432186u, 3370897833u, 1224758384u, 905707335u, 3162313659u, 427715965u, 1348036119u, 7970923u, 3914776522u, 1719464048u, 3087746526u),
SC(873912787u, 1814834283u, 2007356999u, 1342903388u, 2456597479u, 451640963u, 270386192u, 2804676632u, 3347423428u, 1946728624u, 817071823u, 2654597615u, 2075935576u, 4134394912u, 582072193u, 2359391692u),
SC(701959589u, 2450082966u, 3801334037u, 1119476651u, 3004037339u, 2895659371u, 1706080091u, 3016377454u, 2829429308u, 3274085782u, 3716849048u, 2275653490u, 4020356712u, 1066046591u, 4286629474u, 835127193u),
SC(3165586210u, 507538409u, 1576069592u, 2044209233u, 712092282u, 2055526594u, 13545638u, 2637420583u, 2057228124u, 4021333488u, 3231887195u, 3698074935u, 2986196493u, 3191446517u, 1855796754u, 2840543801u),
SC(2049241981u, 3601384056u, 3450756305u, 1891508453u, 3117006888u, 4292069886u, 1305738264u, 1168325042u, 1885311802u, 3504110100u, 2016985184u, 2881133505u, 1880280254u, 2204317009u, 1399753402u, 3367366171u),
SC(3277848307u, 2856992413u, 2480712337u, 2842826539u, 2019400062u, 3739668276u, 3783381527u, 2747809175u, 304494821u, 3082618281u, 475713753u, 3181995879u, 103289908u, 3708783250u, 1444805053u, 2524419441u),
SC(2022030201u, 622422758u, 4099630680u, 255591669u, 2746707126u, 492890866u, 1170945474u, 626140794u, 2553916130u, 3034177025u, 437361978u, 3530139681u, 3716731527u, 788732176u, 2733886498u, 780490151u),
SC(3022387205u, 643413342u, 1262913870u, 882426483u, 3783696379u, 2282658896u, 549384772u, 2907119271u, 2965235271u, 258220726u, 2834889991u, 175082611u, 1532630973u, 2641278331u, 873736728u, 2474793598u),
SC(3436994124u, 1972613506u, 2802593687u, 3277380489u, 4121992441u, 3728497631u, 709132430u, 2822775775u, 2147792195u, 3749335406u, 4209749501u, 3255963905u, 448371535u, 3349728753u, 1134914300u, 2326210644u),
SC(3579789737u, 857648536u, 3677955192u, 2929905256u, 2925305732u, 396144337u, 2879772175u, 611276653u, 1139725609u, 1640545337u, 2376692224u, 2465623832u, 1774091714u, 3594842769u, 2562599181u, 2913715875u),
SC(69398569u, 525452511u, 2938319650u, 1880483009u, 3967907249u, 2829806383u, 1621746321u, 1916983616u, 1370370736u, 248894365u, 3788903479u, 221658457u, 404383926u, 1308961733u, 2635279776u, 2619294254u),
SC(847745551u, 4043085379u, 2601189120u, 3600040994u, 696074066u, 1966732665u, 2566798633u, 2160875716u, 3937088627u, 223752161u, 1824023635u, 1377996649u, 4082040542u, 1765057927u, 3462559245u, 1605863066u),
SC(2848864118u, 745552607u, 3815587692u, 2049639609u, 680251550u, 1505718232u, 39628972u, 2226898497u, 513707523u, 2917769605u, 3496480640u, 2593784936u, 590913979u, 1339822749u, 4138230647u, 49928841u),
SC(2806514274u, 3132555732u, 291777315u, 1351829393u, 2386116447u, 1029032493u, 4242479447u, 4060892676u, 1174959584u, 2813312363u, 4001665503u, 3521645400u, 2629458899u, 2800015182u, 2767567980u, 1450467540u),
SC(1137648243u, 3815904636u, 35128896u, 1498158156u, 2482392993u, 1978830034u, 1585381051u, 335710867u, 529205549u, 1286325760u, 863511412u, 283835652u, 936788847u, 101075250u, 116973165u, 2483395918u),
SC(3811042814u, 1025568765u, 2303929459u, 3941141514u, 909479518u, 1708127829u, 2992362277u, 2201573791u, 823734954u, 2387361592u, 3479939442u, 3649512837u, 1364854u, 1175064965u, 1798998971u, 4010084758u),
SC(1608551539u, 1659476372u, 3926136551u, 3533578126u, 1457941418u, 4020190424u, 1198729568u, 3336914362u, 4181147510u, 1513359382u, 3454065551u, 1215128659u, 1394347719u, 1306437422u, 671973186u, 802663808u),
SC(1546843556u, 1958213360u, 3222927312u, 2732547191u, 1075305498u, 4181416960u, 3176341164u, 843613705u, 2496268523u, 1032252253u, 3102939981u, 2488641222u, 354787535u, 3012081304u, 1337099975u, 411906451u),
SC(2668669863u, 1518051232u, 591131964u, 3625564717u, 2443152079u, 2589878039u, 747840157u, 1417298109u, 2236109461u, 625624150u, 2276484522u, 3671203634u, 3004642785u, 2519941048u, 286358016u, 3502187361u),
SC(3043862272u, 290382966u, 559153561u, 3883639409u, 3906304164u, 1541563334u, 3470977197u, 4214898248u, 602703812u, 594285209u, 2528808255u, 3100412656u, 2962818092u, 1713626799u, 716968139u, 3245684477u),
SC(2849591287u, 2780695223u, 1518691286u, 2959190176u, 132195984u, 1215364670u, 969199256u, 2481548041u, 2367363880u, 2687921445u, 2786812285u, 2680226196u, 1929068126u, 4284277820u, 2652631532u, 1888216766u),
SC(4221543413u, 941544184u, 3103000498u, 2576480775u, 2799149669u, 1305654192u, 3489282068u, 284158188u, 2392559975u, 3208820720u, 1806838706u, 1068764673u, 3216687520u, 3670357690u, 2977855856u, 2151602676u),
SC(3009793609u, 3525092161u, 3245586135u, 574145899u, 4034974232u, 2828949446u, 3457574134u, 1546193476u, 3883480541u, 1976722737u, 3557056370u, 994794948u, 106991499u, 1626704265u, 3534503938u, 3271872260u),
SC(4111653395u, 3737153809u, 724361214u, 4146801440u, 2864192452u, 2352288978u, 4143003150u, 3927435349u, 959755099u, 2267451506u, 2008749851u, 4197184096u, 608903018u, 331201150u, 171852728u, 3631057598u),
SC(1040189192u, 3135235581u, 3623291082u, 2461882244u, 2161120847u, 3614159035u, 1308293611u, 3846387110u, 1899566537u, 2082151738u, 1896999495u, 1814244229u, 1384043307u, 510412164u, 3476482520u, 1522244992u),
SC(3337187848u, 401607407u, 1233709719u, 2407137856u, 4024737998u, 541061391u, 1304919595u, 246716724u, 3564946135u, 4041513396u, 2555398397u, 16604948u, 2211576077u, 2712388351u, 873042891u, 3886941140u),
SC(941124125u, 1620226392u, 1431256941u, 3336438938u, 540497787u, 766040889u, 373284400u, 2979905322u, 177008709u, 2625544842u, 1096614388u, 1196846420u, 4186360501u, 3945210662u, 1143943919u, 3412870088u),
SC(2895190615u, 525902467u, 1367284455u, 2066663630u, 465251607u, 1043189793u, 3148821806u, 3989460909u, 3387524595u, 4067968571u, 1719999600u, 220864914u, 697973681u, 2059667041u, 3220246185u, 695421754u),
SC(2590577156u, 795774194u, 1904860775u, 4031583685u, 3087922830u, 3668434043u, 1959821395u, 3811394838u, 2785704637u, 1682504742u, 1028254204u, 850730757u, 360229062u, 1954705497u, 3724255123u, 4100070091u),
SC(2389626852u, 3853851132u, 3195796535u, 1527199924u, 1636717958u, 3735641313u, 2340881444u, 1438175706u, 1296406867u, 1406099139u, 1135839981u, 3285630759u, 2200113083u, 2680217927u, 97279145u, 1781800696u),
SC(3638948794u, 3243385178u, 2365114888u, 1084927340u, 2097158816u, 336310452u, 231393062u, 580838002u, 3851653288u, 568877195u, 3846156888u, 2754011062u, 3396743120u, 2639744892u, 1431686029u, 1903473537u),
SC(672929266u, 4278630514u, 1561041442u, 629394401u, 4070337497u, 2103696271u, 1114356663u, 4084071767u, 3393530368u, 4249550216u, 4113997504u, 1530567080u, 2126274764u, 3676929390u, 2903800270u, 2831711217u),
SC(1774590259u, 3105493546u, 906525537u, 532177778u, 1023077482u, 1582413022u, 2646097845u, 3428458076u, 414285421u, 1960194778u, 2425645337u, 782659594u, 3724227825u, 4114081279u, 1478362305u, 2537782648u),
SC(3917166800u, 2613468339u, 1109027751u, 2667491623u, 385647357u, 3040475468u, 470189721u, 715873976u, 1126450033u, 763992434u, 2850815403u, 1253615059u, 3081849614u, 1691888978u, 1354336093u, 3217678760u),
SC(4095464112u, 3774124339u, 1954448156u, 2941024780u, 584234335u, 483707475u, 286644251u, 3027719344u, 2257880535u, 651454587u, 3313147574u, 3910046631u, 3169039651u, 2576160449u, 696031594u, 3062648739u),
SC(3054900837u, 3109053155u, 2935799989u, 304144852u, 3697886700u, 1064553036u, 1195677074u, 3398925561u, 3991559971u, 3873262014u, 2104594364u, 3493235682u, 2872792428u, 3787578901u, 495000705u, 1153422238u),
SC(4020389332u, 927192013u, 2251972932u, 3404323722u, 3350728280u, 1270028902u, 459737918u, 2709152689u, 3434679250u, 2153846755u, 931264509u, 2126662946u, 3054979751u, 478875445u, 3173181787u, 2136988011u),
SC(4284049546u, 4227908558u, 367047421u, 3626594909u, 683266175u, 167449575u, 1642758028u, 203888916u, 2541346079u, 2856877101u, 3032791880u, 947365960u, 3274309224u, 1388337804u, 2089622609u, 2510882246u),
SC(1740919499u, 3877396933u, 2326751436u, 2985697421u, 1447445291u, 2255966095u, 1611141497u, 1834170313u, 3589822942u, 2703601378u, 299681739u, 3037417379u, 4014970727u, 2126073701u, 3064037855u, 2610138122u),
SC(612113943u, 1245695464u, 1476531430u, 3079777536u, 1504285401u, 2225606450u, 1678648810u, 943829390u, 446653322u, 1948420681u, 235420476u, 3258122799u, 110378212u, 1165072842u, 821178579u, 1123751364u),
SC(3547216247u, 1712463318u, 2944825066u, 358566040u, 3226130169u, 3598877722u, 1745994951u, 755648908u, 1640001837u, 618372504u, 3714960843u, 3768940664u, 3050068616u, 3559674055u, 3589358798u, 2839014385u),
SC(2963615519u, 749556918u, 1703544736u, 3714369503u, 3794250303u, 2736990653u, 3473783325u, 187948579u, 3344991023u, 2615291805u, 3352394273u, 1176851256u, 636324605u, 342413373u, 3601749395u, 1908387121u),
SC(1456510740u, 215912204u, 253318863u, 2775298218u, 3073705928u, 3154352632u, 3237812190u, 434409115u, 3593346865u, 3020727994u, 1910411353u, 2325723409u, 1818165255u, 3742118891u, 4111316616u, 4010457359u),
SC(2691740498u, 3975883270u, 3562065855u, 1744885675u, 1858951364u, 2782293048u, 2737897143u, 1939635664u, 577670420u, 2332511029u, 3680505471u, 1270825205u, 3377980882u, 280451038u, 932639451u, 530901151u),
SC(2901569236u, 2626505212u, 1775779590u, 378175149u, 2007032171u, 2315048377u, 1708789093u, 1573616959u, 1418282545u, 1543307855u, 3489633010u, 3744345320u, 2558277726u, 1632098179u, 1630179771u, 1410404973u),
SC(867779817u, 4224370363u, 1242180757u, 377585886u, 4220054352u, 130802516u, 2286612526u, 3690324161u, 168683327u, 2352367282u, 3756724843u, 16820454u, 4121820500u, 774287909u, 3499546464u, 2432203874u),
SC(822693957u, 1703644293u, 3960229340u, 2092754577u, 3495958557u, 4288710741u, 4092815138u, 1275224613u, 2592916775u, 472063207u, 2931222331u, 2597044591u, 1261640449u, 1272207288u, 2040245568u, 1417421068u),
SC(1212624844u, 3724128435u, 2580172104u, 625382842u, 1273692890u, 2224567242u, 4268246350u, 675911881u, 2693399366u, 2212843482u, 3533831779u, 548831153u, 3045738097u, 3033563506u, 2981560259u, 3280282777u),
SC(583780584u, 3805688551u, 3154056802u, 1265342235u, 2919963666u, 348340950u, 1643957290u, 2937675860u, 531521986u, 2554579484u, 1858445667u, 4045167738u, 32261687u, 71331634u, 108677060u, 3239178045u),
SC(1344583311u, 144481968u, 4266530071u, 1919888623u, 3530616056u, 405657629u, 550918759u, 2378701874u, 2502453716u, 1249298754u, 2895906070u, 4229345751u, 2698935239u, 1068605837u, 2804235531u, 3419996572u),
SC(3660855132u, 3816892380u, 3431508003u, 1440179111u, 768988979u, 3652895254u, 2084463131u, 3991218655u, 323118457u, 3675476946u, 2157306354u, 2684850253u, 1543808805u, 744627428u, 1091926767u, 3538062578u),
SC(212299625u, 2474466692u, 1704971793u, 3789350230u, 256182388u, 1544421436u, 1581730692u, 1364885237u, 3537961026u, 2803777125u, 3509128589u, 2069072362u, 1096176266u, 640924181u, 3219718394u, 3309717817u),
SC(2373604216u, 2465825031u, 1037036044u, 2538660397u, 3827328679u, 3459992854u, 2334021373u, 3366566203u, 3392318169u, 190647171u, 2398010849u, 2394404134u, 2171187374u, 2435135993u, 77207937u, 3590739715u),
SC(3582764810u, 1359502830u, 1025246886u, 329622637u, 584170095u, 1618468670u, 4135269305u, 1632135623u, 3173068118u, 1159468553u, 2477498366u, 2473706416u, 1990379266u, 3619760163u, 3999703172u, 4001561563u),
SC(2819478132u, 2629026829u, 2945562911u, 1854605392u, 41922071u, 2531530491u, 2316774439u, 3550381961u, 1180787169u, 3914439365u, 3786421842u, 3441223373u, 494782102u, 2858003292u, 1448968751u, 2940369046u),
SC(3794875745u, 2254091108u, 118588821u, 3886088825u, 1251278642u, 1219961983u, 2719820348u, 2423061629u, 2599856244u, 220341580u, 4048073849u, 2104530045u, 811981063u, 3760141810u, 1863614748u, 3139122890u),
SC(3679877447u, 1244259754u, 3066916057u, 2660429719u, 569074139u, 934334703u, 671572554u, 3842972464u, 288530523u, 4182111156u, 1001852850u, 519081958u, 204295960u, 4012888918u, 1945355312u, 1860648163u),
SC(994404842u, 2682995800u, 29922853u, 1597633752u, 1062800697u, 3306110457u, 520491033u, 3356053075u, 2549792314u, 3477041846u, 3253737096u, 1762450113u, 3375037999u, 2602209592u, 3113557911u, 3720142223u),
SC(3017729014u, 3423125690u, 1534829496u, 1346803271u, 888659105u, 1661894766u, 4165031912u, 697485157u, 3575889724u, 1795181757u, 1507549874u, 1480154979u, 3565672142u, 830054113u, 1507719534u, 3652903656u),
SC(2479103645u, 4018184950u, 2479614475u, 3317764526u, 301828742u, 960498044u, 3094690160u, 3809621811u, 2208635829u, 2224317619u, 3998999734u, 1548883437u, 1441132887u, 3683345599u, 2867687577u, 1233120778u),
SC(1791101835u, 1817384161u, 1923325009u, 2735725895u, 3675660639u, 3891077763u, 1995919027u, 1905059636u, 1940967335u, 3392681720u, 367988187u, 3612123786u, 3090191283u, 1256462996u, 3912097760u, 2309957363u),
SC(1966524664u, 3700727165u, 3292074144u, 2147997405u, 2207840483u, 686614845u, 2478395761u, 2099930233u, 1138889901u, 741741915u, 410612689u, 3168582608u, 1480885392u, 2712155566u, 795218052u, 3627485712u),
SC(3751554592u, 1759634227u, 4138518211u, 3130599659u, 3881948336u, 669688286u, 3672211577u, 695226401u, 1226786139u, 1855160209u, 905875552u, 2831529665u, 1625185017u, 3130043300u, 3227522138u, 3659203373u),
SC(3678343731u, 3378294720u, 2783724068u, 44445192u, 1952301657u, 683256120u, 3868461065u, 154627566u, 2492480331u, 688442697u, 2515568703u, 27336037u, 2282124228u, 4010257051u, 1410784834u, 2387531542u),
SC(2767037774u, 3374543263u, 2353734014u, 740321548u, 1502005361u, 4208562518u, 2317313556u, 1296623898u, 2272488031u, 3877484857u, 979844730u, 2613612689u, 786482265u, 1364244620u, 2033173153u, 3134432953u),
SC(245516122u, 2889724376u, 1613118230u, 2868868565u, 1013497115u, 3666944940u, 2501541909u, 815141378u, 779235858u, 1902916979u, 3850855895u, 1167093935u, 1168409941u, 3245780852u, 4226945707u, 4280877886u),
SC(2950670644u, 1870384244u, 3964091927u, 4110714448u, 298132763u, 3177974896u, 3260855649u, 1258311080u, 2976836646u, 3581267654u, 3094482836u, 80535005u, 2024129606u, 168620678u, 4254285674u, 2577025593u),
SC(3844732422u, 2230187449u, 1557375911u, 590961129u, 1701027517u, 331713899u, 3363983326u, 1064211679u, 2469744485u, 3844709006u, 554341548u, 2324111146u, 2812323543u, 1435480032u, 4135550045u, 2872067600u),
SC(2202241595u, 1205836665u, 3131813560u, 1089110772u, 3887508076u, 1233136676u, 3548446202u, 793066767u, 637354793u, 3802923900u, 1174560178u, 382849423u, 962041806u, 1631358036u, 3204426711u, 3944213363u),
SC(817090639u, 1994913738u, 2648494065u, 4177836343u, 3717672761u, 285814645u, 2423315791u, 4135386952u, 3070326434u, 820456062u, 1683759394u, 1267832048u, 63147800u, 1881205741u, 302905775u, 1485684559u),
SC(3370772934u, 1440339939u, 379677041u, 4156026118u, 4200213979u, 1445495145u, 3935749177u, 1783881758u, 1005809262u, 2360538413u, 2323256669u, 457067031u, 3765100747u, 2984166698u, 162921394u, 2668333599u),
SC(3065468376u, 65466803u, 3784968091u, 3673346023u, 584904352u, 663859712u, 1389234596u, 3496407446u, 890179676u, 1850921398u, 3658025032u, 506692469u, 2138612147u, 3661456633u, 4005648844u, 249742373u),
SC(1899194536u, 4093520345u, 3415064568u, 1802810398u, 3207570648u, 296545623u, 1204649995u, 2946774221u, 714728700u, 2767849304u, 2356147373u, 157823549u, 3075725764u, 1119360150u, 4211929128u, 3922170227u),
SC(2659885008u, 598828540u, 2375411681u, 964709383u, 2865976012u, 414712789u, 3082783461u, 6238131u, 3716066600u, 1794924805u, 2313286822u, 946313445u, 2548638721u, 964660560u, 44931074u, 1906436126u),
SC(2640868889u, 3250766894u, 1044803536u, 450207928u, 3025775378u, 1680703708u, 276934172u, 2818613080u, 888828802u, 1753154805u, 531715904u, 3273521379u, 341444872u, 2892600615u, 159622930u, 591479697u),
SC(2952222374u, 1856498301u, 2243569887u, 4213548355u, 4078434310u, 4052372322u, 1416228041u, 2119461034u, 3007622446u, 3050042881u, 2152732646u, 1066024310u, 2582445442u, 682218174u, 2817737782u, 2652201945u),
SC(3623056786u, 3441458982u, 2160322137u, 2871437811u, 2250704419u, 3170723639u, 4221731738u, 2734636927u, 1185229318u, 4274587310u, 2041058099u, 962960905u, 2061052114u, 1268028907u, 2565378146u, 3631942974u),
SC(2141595323u, 160210714u, 2228950125u, 92580378u, 988241665u, 445022223u, 566406519u, 3944609260u, 3366528787u, 4002340061u, 961852007u, 3441093957u, 2459277731u, 1024502537u, 1511457730u, 1148963311u),
SC(3202237129u, 50883717u, 3598269011u, 1607392277u, 1644299309u, 889527980u, 2825840961u, 2861964676u, 3773279883u, 2790748940u, 801518030u, 2192935882u, 499995327u, 1862737584u, 3413876603u, 616426331u),
SC(3686793646u, 20428098u, 3969297914u, 913650165u, 2827686478u, 2379892224u, 454312765u, 2897546672u, 3835444382u, 2882659779u, 3321531897u, 74282757u, 3847182670u, 3541719937u, 3150565224u, 3512719354u),
SC(3784958703u, 2769421682u, 3091517885u, 1991423597u, 3891647149u, 675105671u, 1037706647u, 259233587u, 2569454579u, 2293177837u, 4007742405u, 197079824u, 1273386495u, 3282913176u, 1536053011u, 1223947714u),
SC(434065071u, 3636373224u, 3991878275u, 1096448533u, 2730731688u, 2513540689u, 113291505u, 371784153u, 1849077614u, 2667695479u, 3752135876u, 2789716514u, 3595582551u, 3031878859u, 2074056379u, 3599743336u),
SC(2576095823u, 86681482u, 2327030094u, 1725401015u, 341826214u, 1191297212u, 2343266611u, 1017220807u, 2691244685u, 895382974u, 4111156866u, 2987439990u, 2511968171u, 316177210u, 703101725u, 681437235u),
SC(1669913590u, 387275198u, 763233018u, 736875927u, 3279145343u, 2513945803u, 102030106u, 2618927150u, 2983227004u, 2212337792u, 2816563243u, 666091160u, 3801431258u, 1348390766u, 1055427564u, 1899913269u),
SC(1727153737u, 1379698720u, 2039442996u, 2747321025u, 3954121035u, 3301125252u, 2834061869u, 770560392u, 3966591198u, 1961165929u, 105560134u, 30446389u, 183105111u, 3146477434u, 2246060135u, 288949285u),
SC(1131955257u, 1449655431u, 3518253163u, 4153987991u, 3869923725u, 3198118689u, 1677558296u, 3934028944u, 3706927948u, 1463324750u, 1783261113u, 2788560881u, 3859020908u, 1635416939u, 386489686u, 3874171273u),
SC(2353147804u, 1311416906u, 105984912u, 4224529713u, 1353878621u, 1089374941u, 2359121297u, 1681969049u, 35129792u, 742332537u, 258439575u, 2442989035u, 4253756672u, 1596235232u, 3823082318u, 2381448484u),
SC(1190442982u, 1874855635u, 2229404366u, 3781526169u, 3471201203u, 3683021538u, 2732745990u, 2348452723u, 3499960920u, 3603466370u, 724498153u, 1020423362u, 1277227832u, 1355832959u, 1821604508u, 4167503482u),
SC(2710790336u, 1725181698u, 1411252199u, 4204440724u, 648339034u, 2322949699u, 3414240870u, 2615287106u, 1037187476u, 2391186172u, 1554369130u, 4112504886u, 2086740002u, 3652684450u, 1249425599u, 3565844824u),
SC(1408354486u, 4130212172u, 981550913u, 3804435033u, 2516265052u, 3638635807u, 2435893710u, 2985211455u, 2435388317u, 1122223182u, 4045695068u, 4259175893u, 3130782207u, 1516327754u, 222842940u, 3028641973u),
SC(1020427295u, 3974659064u, 283755394u, 2698482586u, 3731846525u, 2634119332u, 3930615342u, 605884950u, 2153878216u, 408077371u, 3527644242u, 188880174u, 2969085736u, 1358147467u, 199845647u, 4237400215u),
SC(3758107081u, 2242188224u, 2662546131u, 1561030959u, 817813866u, 1223534684u, 4230285749u, 2583147456u, 3162765547u, 3250322233u, 2552007157u, 2082705710u, 2014211252u, 3819533721u, 686101552u, 2812413379u),
SC(2234002525u, 4261429784u, 452225496u, 2303312689u, 1415484610u, 980910758u, 1264265981u, 2116798858u, 2297475165u, 1077069522u, 2336309469u, 1211096986u, 1916895651u, 2716672672u, 195344444u, 4225148444u),
SC(2384904579u, 639141669u, 3509483302u, 2662576077u, 303835927u, 1836480672u, 2477037280u, 2622449130u, 173493653u, 2124329088u, 1602479127u, 4047873800u, 2535334227u, 2829812834u, 2580882819u, 2222121832u),
SC(2119576703u, 2277130384u, 3272897641u, 126602073u, 1915103151u, 123033056u, 3738728306u, 258450927u, 1128202181u, 443393204u, 351769595u, 1486233009u, 4234576346u, 775323398u, 857648792u, 1277112788u),
SC(2993933961u, 1657088997u, 213007534u, 3535372309u, 2026363619u, 3507155973u, 1176191233u, 3237944387u, 1320866873u, 1924765846u, 4159967257u, 1467377957u, 4047884494u, 1497517194u, 1818016460u, 2744622870u),
SC(3694140649u, 652746790u, 951189140u, 2098619655u, 1680509345u, 1352655302u, 1544793909u, 2680376337u, 175255713u, 1388931410u, 2800074562u, 3304804431u, 315774843u, 1088993607u, 1406890395u, 1388997459u),
SC(1251988268u, 2843661694u, 2212874002u, 1534733047u, 1068100174u, 3647918953u, 1789522147u, 3422223776u, 1180289192u, 194862188u, 3422333598u, 3945579082u, 576579849u, 4206528706u, 321834890u, 3661983741u),
SC(2441722449u, 2790322712u, 1527675058u, 1338514239u, 2508809510u, 1706782403u, 1349451633u, 1899600596u, 2552002416u, 3067739742u, 4116665780u, 1305299753u, 1475244152u, 1557749124u, 223984632u, 1615437927u),
SC(2151876908u, 127556265u, 210060943u, 1049978459u, 4151586108u, 2028234025u, 2678412581u, 14644879u, 1565389685u, 3987281138u, 1236497759u, 911479528u, 525893033u, 3024407248u, 3556739040u, 1249730389u),
SC(3301882220u, 3342072153u, 1895573985u, 1790741734u, 1642968660u, 1858970157u, 2235912890u, 1037870412u, 1813672202u, 4049358910u, 3001339515u, 873617077u, 2873055757u, 3206209966u, 4101837524u, 2624469834u),
SC(4012899795u, 1411685889u, 1675925042u, 202568246u, 4145924754u, 1399506949u, 1886987672u, 2758768719u, 2971794908u, 2035585462u, 2543963410u, 2573500478u, 1760956179u, 1439621888u, 1566898017u, 1067574233u),
SC(3011639073u, 2206317754u, 969819721u, 3738742509u, 1138054282u, 2981140865u, 2802091370u, 2603283830u, 4248836099u, 166302652u, 328639577u, 2188432563u, 4067379185u, 146455516u, 3217830067u, 1729299133u),
SC(2609432174u, 2327492074u, 3031491512u, 280817824u, 3549986332u, 3308979407u, 2655280939u, 2768967492u, 254774771u, 1876736424u, 2883942286u, 872093970u, 548753956u, 2234019621u, 957665653u, 3478881725u),
SC(1034467968u, 2792638263u, 3950374324u, 1004331822u, 4143036235u, 3155132214u, 1019409218u, 546983506u, 3592239641u, 3183006100u, 518251172u, 84770439u, 3170919723u, 1246938133u, 2186380724u, 2729251943u),
SC(2721544689u, 3010554855u, 2194979764u, 1031890814u, 3616460865u, 3262672691u, 1238722150u, 2348608514u, 867532033u, 3287518035u, 3647913083u, 717892616u, 1725828253u, 2539969720u, 3705717374u, 4095834467u),
SC(3801315717u, 2112036077u, 3164683094u, 379762771u, 3254176021u, 2342893977u, 1079378879u, 3986955491u, 3221162096u, 2286978182u, 907699080u, 3070638326u, 2125256188u, 2711740807u, 2477965954u, 3570994883u),
SC(1122525264u, 3591379015u, 3651810742u, 1173125667u, 802651485u, 3322599373u, 2702070556u, 2271315927u, 235540800u, 3051400065u, 2042929625u, 1315436250u, 4279660507u, 1222458841u, 1309738265u, 4260103523u),
SC(594338363u, 2705306194u, 3994677390u, 2587445452u, 4092458680u, 2550273883u, 1741901457u, 3089932786u, 995531803u, 1552592484u, 185943397u, 1893151579u, 3925084250u, 2731009314u, 2517191571u, 4184090215u),
SC(2932536533u, 673797799u, 1479658602u, 2730531731u, 1700442209u, 358022048u, 146283469u, 2643625189u, 4024245855u, 4139997168u, 567410177u, 3636916990u, 3268470878u, 314047155u, 1763763844u, 3743541562u),
SC(2662528623u, 240757742u, 3179027416u, 3692044327u, 3913846998u, 3528257504u, 3772979290u, 3628427226u, 305430694u, 2987431446u, 794594234u, 1282518312u, 2985258300u, 3333973163u, 4005806037u, 352754457u),
SC(3782779926u, 4110508606u, 1605467718u, 2642077952u, 458260856u, 2448579418u, 2209203557u, 1968631064u, 3765513190u, 3884784279u, 72532826u, 3248358489u, 3714540198u, 2606678131u, 2904387285u, 2342761321u),
SC(2569288456u, 1815849164u, 4098684446u, 3349474441u, 1410341352u, 1705004747u, 3665708675u, 381020291u, 2679446175u, 1286312468u, 3575935824u, 279271370u, 1077912003u, 190175010u, 425033099u, 3744325826u),
SC(3275514338u, 1559161631u, 799309346u, 2839484106u, 305280450u, 3083836149u, 3876776079u, 2156901234u, 2804804991u, 976629240u, 2694392801u, 1790066514u, 2574196749u, 3029867868u, 2629265170u, 4037575284u),
SC(1179130413u, 2617888591u, 3899256032u, 1057380664u, 3779344699u, 307335646u, 2770957782u, 4141937651u, 1948539189u, 1358438384u, 1093283021u, 4042006857u, 2791989712u, 3594321177u, 1957065458u, 3124610322u),
SC(3050699594u, 4280767227u, 290097946u, 3263540548u, 1572664490u, 4270814667u, 52151354u, 1117313135u, 1865289931u, 3010346790u, 3391620705u, 985710674u, 531658779u, 34923524u, 2455194633u, 2374493465u),
SC(814459970u, 2723917759u, 2477174310u, 3482962885u, 442774037u, 754815613u, 1917888868u, 3158676105u, 2872624459u, 91379209u, 1032043884u, 499991106u, 3778795588u, 3266819779u, 186637454u, 4156664772u),
SC(3016114145u, 1736461604u, 3205169396u, 474612085u, 1216801222u, 2835641401u, 2918409686u, 3164901799u, 3500254583u, 3667239907u, 1848006585u, 4185934990u, 2478171701u, 1851761984u, 1340662725u, 1559796526u),
SC(1360133382u, 1382006343u, 66835972u, 1873466161u, 3876965448u, 3531938445u, 1890798686u, 56472881u, 2533353104u, 4282202369u, 3645923103u, 2705081453u, 1080413790u, 4206709997u, 1506080970u, 1141708053u),
SC(3155358398u, 990848993u, 2462700614u, 1505675146u, 1247358734u, 2575032972u, 826119084u, 1198127946u, 339679848u, 32954015u, 1727305027u, 2972819958u, 3370367283u, 656266618u, 1005181853u, 530330039u),
SC(3988823285u, 1731245632u, 1755055403u, 2560356605u, 3730232548u, 2155413514u, 3035164658u, 598434227u, 1475484312u, 3940474610u, 2415265341u, 1405031819u, 3280870431u, 1844631264u, 1610067224u, 1204362218u),
SC(1269221683u, 2519656157u, 2071625981u, 1090710229u, 3645514314u, 1110844234u, 1924132752u, 892847887u, 4165100719u, 3359788173u, 2008337856u, 938802684u, 991722988u, 4043128230u, 4137074352u, 2561836043u),
SC(1832589817u, 2040030464u, 789572087u, 1743772968u, 1938005249u, 998198464u, 2217413253u, 3247653250u, 2992749980u, 3373002764u, 986086387u, 1921971278u, 715241056u, 1828539457u, 550615731u, 178282236u),
SC(3118922710u, 3133974140u, 3533142743u, 72929286u, 3198298255u, 1502151855u, 108612817u, 3699479089u, 201153487u, 720151169u, 3583408525u, 1210759541u, 1941003258u, 3682465346u, 2883351166u, 3479588638u),
SC(4075012412u, 2384306778u, 990193452u, 4200939253u, 1216259667u, 1834335958u, 3387821687u, 2234670992u, 2076894060u, 1743544524u, 277514132u, 13313187u, 3071041293u, 760793107u, 2011151740u, 278340182u),
SC(320316446u, 4109407361u, 3677628424u, 1674877723u, 3753025818u, 4165197242u, 692690716u, 1774953271u, 682266304u, 195625503u, 3298726133u, 1707479636u, 992898575u, 1463223156u, 2482910366u, 300572397u),
SC(1520231886u, 1533823723u, 2297723983u, 1744831139u, 3633896082u, 1614546195u, 3609911488u, 597627082u, 3251786608u, 4014292809u, 2038611397u, 3607503000u, 437112807u, 3497657145u, 3940533692u, 3708647540u),
SC(1465821699u, 3405111997u, 4003997008u, 4183928939u, 3905462877u, 2705297708u, 2238150313u, 742184835u, 1932143234u, 3664530812u, 2046148339u, 2604237599u, 4176974387u, 4184867654u, 4206884099u, 1348617750u),
SC(3070267841u, 2579987995u, 1969628668u, 3729860143u, 2481075914u, 4102909817u, 3584912684u, 474930687u, 3540071519u, 1029701928u, 1346321162u, 2127250654u, 4129540566u, 3018689710u, 3598109374u, 1767691581u),
SC(864985299u, 1834850557u, 3109924880u, 1664439774u, 3385518451u, 1913308391u, 3218983195u, 392233970u, 3181268563u, 3784201246u, 2379947300u, 4290722005u, 3528628947u, 1006910471u, 535267399u, 1673418747u),
SC(3481601556u, 2233272424u, 379791868u, 257694460u, 1845345200u, 3985799409u, 584988816u, 3412670519u, 3077103055u, 4175161368u, 4242152769u, 288598488u, 1537669756u, 2647153439u, 598939469u, 111034163u),
SC(3810090684u, 1592169812u, 1940268778u, 338895736u, 497628080u, 4216984708u, 228734525u, 1707793534u, 3500988995u, 3892268537u, 3709814459u, 2481503038u, 4285752394u, 3760502218u, 2308351824u, 2442300374u),
SC(1463929836u, 1623537503u, 1841529793u, 2601374939u, 443189997u, 1448667259u, 4277352980u, 774378880u, 1726605682u, 711848571u, 609223830u, 3738657676u, 2710655701u, 2088426244u, 1947361269u, 468110171u),
SC(2120531099u, 3930874976u, 3115446129u, 2510615778u, 1442960918u, 296642718u, 3406147761u, 2917495448u, 3208894642u, 1695107462u, 843596467u, 603763190u, 1560844015u, 355951375u, 3828049563u, 1114999394u),
SC(392371846u, 1379814680u, 1363243524u, 3722538090u, 3145592111u, 38816718u, 107491673u, 1676260498u, 3426355262u, 3831639129u, 1301499599u, 611390527u, 78617678u, 1209558708u, 1668351148u, 226581655u),
SC(1775864961u, 48061652u, 580841005u, 3626988964u, 2557366605u, 3448623530u, 468550727u, 241125115u, 2104687911u, 1089018812u, 1688455712u, 608088120u, 2631681751u, 3937882947u, 2164520114u, 1139400198u),
SC(1995948241u, 208017732u, 1594842091u, 1452072628u, 164448317u, 3854350135u, 770076275u, 3400678444u, 1409557197u, 2571846673u, 1859309672u, 1573355923u, 4217069526u, 686027826u, 3995935263u, 2273570682u),
SC(1765332340u, 4134549941u, 3951557595u, 3076127967u, 1338164033u, 2891454422u, 2393384828u, 3559486836u, 1512470972u, 2204654760u, 3549830481u, 442409089u, 2330531785u, 1174852946u, 1644205035u, 4086947411u),
SC(101372338u, 2692064245u, 4244055656u, 3410522170u, 4098634818u, 592864064u, 2969397292u, 2927795675u, 1397471704u, 1186809213u, 896853288u, 2272821089u, 1950059720u, 3887661868u, 1484362490u, 3234474008u),
SC(493258591u, 1121511261u, 1448191541u, 498182176u, 1918511567u, 1960859517u, 2201745473u, 2498339542u, 2151600957u, 562595706u, 3269711078u, 3616189977u, 2368662366u, 2850210764u, 701321748u, 3255466174u),
SC(3477078337u, 75569968u, 1882477600u, 3795843068u, 3145730975u, 3928889549u, 2226239031u, 2069490233u, 730638780u, 1915612718u, 697919589u, 2467794143u, 374355249u, 3817362210u, 3559591924u, 3708360999u),
SC(4280685228u, 798565835u, 3447110005u, 2990210928u, 1115710197u, 2405737735u, 682820124u, 1699236188u, 3820769325u, 1615231023u, 2368524531u, 257677290u, 4133610712u, 1592505711u, 3475938680u, 1398379699u),
SC(1211755933u, 1247714434u, 1282061171u, 3117211886u, 1838094820u, 562415505u, 2310351523u, 1381183879u, 2707832537u, 117470322u, 2204629759u, 867864819u, 1644915480u, 2820079473u, 134123159u, 540033827u),
SC(15354647u, 1591670498u, 1190718313u, 1541233542u, 4032967122u, 942685588u, 3365116340u, 2946123057u, 2867864034u, 1431712436u, 3664977314u, 4215252548u, 780940535u, 2664802049u, 3657395174u, 3285444551u),
SC(1658777725u, 999313419u, 1418469670u, 1566961954u, 3992026007u, 2649729892u, 1047536246u, 2001445947u, 480933675u, 3175009636u, 3359477823u, 2924980702u, 1231329979u, 95058465u, 767731972u, 3917454032u),
SC(3100292812u, 3884551487u, 4289440287u, 2347826358u, 4211090332u, 670252192u, 3716758936u, 2994228912u, 2525237511u, 3452722491u, 1545378943u, 968437745u, 1479664640u, 1937122359u, 2097556211u, 1258954160u),
SC(1673081263u, 3717060688u, 3652383485u, 75555081u, 339104409u, 625664167u, 2957818922u, 3740706216u, 3722123261u, 2164265628u, 41619746u, 878214721u, 3870587649u, 2665027445u, 2987893003u, 808462477u),
SC(2728711156u, 1086672909u, 2697764898u, 567191765u, 2302742493u, 2005063028u, 2232495503u, 3875528033u, 2914811718u, 3683323689u, 52292746u, 3187471254u, 2532399294u, 4143091019u, 3633190133u, 1590524887u),
SC(606562011u, 2100995962u, 1839922754u, 532687810u, 3616257173u, 1997694206u, 1335550423u, 2205222605u, 261980003u, 2139354528u, 1841614146u, 2937759052u, 2183075601u, 1723571202u, 1493132360u, 3728582316u),
SC(3230250852u, 4168344895u, 2679345329u, 3624060879u, 3868167595u, 1865131300u, 1311805479u, 2393247194u, 2139351328u, 3002812369u, 3350833683u, 3969926321u, 2058779916u, 2490793273u, 2159016099u, 496959402u),
SC(3999308453u, 3487620652u, 1171382066u, 117957864u, 3636774258u, 986365728u, 3378416914u, 2669903071u, 664895567u, 3538730524u, 166402392u, 3635906958u, 157861605u, 242846507u, 3094051413u, 4038067861u),
SC(382205097u, 2344781331u, 2937140170u, 1816057341u, 1469220234u, 1940420467u, 398460121u, 3364520375u, 2104328076u, 82674575u, 2140577888u, 852626945u, 3079841577u, 1473577711u, 1465804966u, 3311176475u),
SC(3267743682u, 1310117768u, 2938225418u, 775374367u, 587863041u, 714539095u, 4061038577u, 3729882348u, 1785496396u, 3211618351u, 2981394335u, 371831223u, 1072350840u, 954419720u, 1959998932u, 2454045566u),
SC(479494208u, 1987289713u, 601690066u, 2245928090u, 1237926728u, 1978426976u, 1024130488u, 2665301570u, 34745753u, 1736556264u, 1653286844u, 3451912851u, 1138975354u, 4048457251u, 1242843993u, 1054377909u),
SC(2738272835u, 2642272027u, 2444253775u, 1913142517u, 529528892u, 363620831u, 2077044016u, 3326463661u, 2845383164u, 2776976386u, 3877921557u, 1199205578u, 3801089501u, 3914384222u, 128907220u, 132434637u),
SC(555642965u, 1828068553u, 165356918u, 537166884u, 2589769988u, 3893921148u, 735041643u, 904961316u, 4137546439u, 3565210697u, 2338345828u, 3841345944u, 2815585062u, 4082424957u, 394326179u, 52753595u),
SC(2015072068u, 2250729799u, 1841411011u, 4036188548u, 1854043669u, 2989277393u, 1318251334u, 1142950047u, 3298447599u, 1053616926u, 3428876739u, 2060285001u, 1941488353u, 2614859778u, 4116063961u, 312196617u),
SC(1645616406u, 2451233446u, 95062652u, 3017612715u, 506657218u, 3839742233u, 3856180001u, 1041180203u, 3937295200u, 1238701953u, 2873597624u, 840250152u, 4243175032u, 930652270u, 1478475816u, 3845467531u),
SC(2614321393u, 2590372819u, 1970957616u, 1961333756u, 2325160725u, 2648338335u, 4165709737u, 2339426256u, 3513486801u, 1496810781u, 1669509351u, 258966927u, 2250252751u, 2239710582u, 802055678u, 4015030700u),
SC(2182037357u, 4101274196u, 1446988332u, 2985927331u, 1146409455u, 3263975303u, 799089634u, 2309382122u, 665330721u, 560691983u, 753778238u, 3562883867u, 3339601863u, 3450049178u, 4100785638u, 1532039755u),
SC(937987686u, 865492161u, 3272849989u, 1734497423u, 343847785u, 3737085537u, 3368433481u, 2949279024u, 3260496520u, 4153917332u, 3410155564u, 3353468255u, 1739756823u, 4095510864u, 3441948540u, 4106520671u),
SC(969989902u, 586815344u, 1052565711u, 1966159036u, 1537747586u, 3037234863u, 3719606179u, 3329895927u, 973453015u, 1072637341u, 4177571198u, 599432355u, 4195257378u, 1974046375u, 3591192312u, 1360444203u),
SC(1198026164u, 4014048326u, 1230325083u, 2325793602u, 2567156447u, 2557610111u, 1955740227u, 1784651885u, 2575049304u, 3122223295u, 1744960108u, 1453452975u, 793595759u, 384704201u, 949316067u, 1790894944u),
SC(4018529616u, 2128595084u, 1769902998u, 3875589577u, 1889584730u, 3454870508u, 2548628163u, 1669330066u, 2128608235u, 3281879031u, 2432452508u, 1883985687u, 588999703u, 2324275250u, 901137249u, 3371400173u),
SC(1200681821u, 3301951048u, 3422623379u, 3571320760u, 874120845u, 3097214442u, 3051103970u, 76968923u, 1387447193u, 2542210132u, 2554494588u, 974855787u, 1477775411u, 3457275362u, 2692305076u, 3235291688u),
SC(3036583757u, 770121165u, 3053454162u, 522789059u, 2626260097u, 3421082942u, 1104884834u, 4070065260u, 4076311070u, 685795393u, 461218278u, 2168728175u, 3856607167u, 813680045u, 2418442649u, 3951931037u),
SC(399941210u, 4052934898u, 1765353186u, 2914831584u, 2330887766u, 5969976u, 1422591474u, 3629530848u, 267437281u, 3214236217u, 4174466044u, 1745439639u, 1864324137u, 3763020267u, 2592531679u, 3537966343u),
SC(3799373953u, 2724639256u, 2001877812u, 1808948841u, 1593274790u, 3054223609u, 1153023507u, 4239996916u, 1351712236u, 3216557202u, 2535804507u, 845372832u, 3782183452u, 3403957512u, 1416495693u, 3105296601u),
SC(1498301404u, 4820973u, 153120459u, 2361034920u, 2023699622u, 3245801726u, 2964952371u, 1041760523u, 268911050u, 2634266058u, 2694116227u, 2027567813u, 2373519386u, 269857075u, 30288097u, 2183065286u),
SC(368526189u, 2559072357u, 1031071164u, 2182129360u, 1944651505u, 636678935u, 1667461006u, 1294621613u, 2608680425u, 3107428868u, 3989419130u, 2232649159u, 2911003556u, 2700112730u, 3650153328u, 3756548335u),
SC(3698493999u, 1617091219u, 2641540351u, 630561052u, 1592442355u, 3183940237u, 801174107u, 179980333u, 696230615u, 150351649u, 23935592u, 3859540912u, 468562123u, 923517953u, 805710396u, 4125457547u),
SC(4165123875u, 2400415189u, 3682055275u, 2069206861u, 3696165550u, 2161642831u, 2037981487u, 1143942884u, 4276433760u, 478865742u, 3086639553u, 1571765198u, 1603084763u, 456679804u, 3651523911u, 1478990563u),
SC(1379203927u, 3646623795u, 568753294u, 3487537539u, 209654607u, 4212153962u, 3351322045u, 2510527877u, 2242635801u, 2829639500u, 3346970138u, 145495350u, 696632584u, 4044305024u, 3898104982u, 4062174566u),
SC(3184334172u, 233736710u, 4174791834u, 4097504403u, 3953706740u, 3822932903u, 2814935218u, 358220985u, 3196193396u, 1102715831u, 1098449313u, 2583469858u, 4124598348u, 1123093599u, 2101489793u, 1348316960u),
SC(2684573108u, 3558789399u, 3119419718u, 3728836869u, 2947343184u, 1623207311u, 3636415221u, 169916282u, 3184581941u, 3445118881u, 2604468839u, 2706071623u, 2898788331u, 1892631561u, 1665094613u, 3179624796u),
SC(906269307u, 3944720044u, 1084033100u, 2261306286u, 1213089531u, 3374722818u, 4231098344u, 3721279388u, 1553093275u, 459717074u, 162554025u, 17748698u, 1178068070u, 962016410u, 2213129285u, 1572961619u),
SC(2793536793u, 1775932955u, 900507119u, 977479138u, 309749318u, 1331949593u, 2418440293u, 531142338u, 4089367200u, 930941048u, 1176503780u, 2036051288u, 3668633163u, 1740102441u, 2194821486u, 1282572570u),
SC(445096529u, 129462470u, 1884373239u, 3466640820u, 1522309741u, 973848773u, 494935215u, 2424005467u, 3247128628u, 259841527u, 186869565u, 3096718001u, 2477168883u, 367986761u, 2999214109u, 2896323771u),
SC(1773026576u, 1379074764u, 3166371072u, 524350604u, 3036223673u, 1696139651u, 617546873u, 4179058200u, 3914872456u, 2598924013u, 3955751324u, 26932306u, 2099484934u, 2862008623u, 768155488u, 1191481499u),
SC(409212209u, 1052910825u, 3688563284u, 4161847970u, 2245294077u, 897499682u, 456221051u, 2079661589u, 3801089560u, 2078041333u, 3137652751u, 2105451951u, 719093028u, 1468410201u, 1515815488u, 563818410u),
SC(3286956100u, 2383742683u, 3943355186u, 2993468102u, 3979091318u, 916735409u, 2964268867u, 305123152u, 4128710652u, 2295714888u, 3626542149u, 3583999711u, 4231472159u, 720391481u, 484199833u, 2335936882u),
SC(538542990u, 4107031584u, 936999250u, 2894531997u, 2884912117u, 1445093734u, 2632468537u, 3748259111u, 2802501861u, 3908527171u, 4249314755u, 2225844668u, 1521902387u, 2622248285u, 2379759782u, 133722185u),
SC(2416004768u, 4150485184u, 2866080852u, 2258165843u, 340095341u, 92175320u, 2597374290u, 3087457719u, 3493438419u, 118989751u, 1753361916u, 2495747807u, 639933700u, 3533266873u, 1436534944u, 1404379078u),
SC(1990073743u, 1730445713u, 289110704u, 2215657403u, 3477688520u, 2065290968u, 1707801924u, 3099400356u, 2323459433u, 2868452324u, 3572002281u, 898120544u, 2341674849u, 1740236652u, 3930315629u, 1721050464u),
SC(2846769158u, 3226467803u, 3972413633u, 3813187604u, 2977554411u, 3119019066u, 187539422u, 440979155u, 821512909u, 1244234014u, 1904979619u, 299169202u, 3071099705u, 3895808241u, 4109203004u, 1385199880u),
SC(20905997u, 2435505711u, 3332489889u, 1573385190u, 58777428u, 1157282938u, 2163099427u, 3928469264u, 1842173836u, 315842099u, 505424769u, 3969121644u, 810696578u, 173164137u, 729323247u, 1406869756u),
SC(2365567579u, 2649935193u, 2748706770u, 3167941363u, 4184592483u, 348144198u, 2780991619u, 3943215641u, 289217556u, 1966918363u, 1264290193u, 2261335810u, 331626257u, 811495510u, 4241198943u, 2401654548u),
SC(2748278563u, 1068204456u, 1543821322u, 1360532269u, 3750838841u, 1738925190u, 1060161426u, 1720702106u, 2569490119u, 2592801160u, 2837017084u, 1662592721u, 1922186968u, 2837375648u, 558451644u, 866947791u),
SC(1192118473u, 405864758u, 2154900285u, 2590455701u, 2443487163u, 774239941u, 1500516041u, 3052959378u, 62497488u, 3655191229u, 1360213674u, 4039219068u, 772399995u, 2523284785u, 1220027510u, 1817586574u),
SC(3940509119u, 3412105989u, 2952834772u, 2565031146u, 420729718u, 3223325741u, 3799285342u, 2722982144u, 3291273242u, 1970130334u, 1752908455u, 718889499u, 3758072739u, 3367451018u, 3926567909u, 4252203926u),
SC(1759002533u, 1487269615u, 2257972014u, 1083840372u, 1641298734u, 2179126519u, 4023242279u, 631576049u, 1738205588u, 618934446u, 2093405187u, 2949307911u, 4007558605u, 1029273367u, 4271100370u, 1039169272u),
SC(1515566465u, 1552043593u, 3679580696u, 2436820824u, 243951212u, 1100063376u, 3060791820u, 2881381702u, 2255810429u, 2661760029u, 976819642u, 3776497474u, 4249702024u, 2024647373u, 110728762u, 1589245846u),
SC(1222066781u, 929871833u, 3542816334u, 2450308476u, 3889263811u, 2063341852u, 1713795617u, 1790265502u, 3640640744u, 702438505u, 3752689618u, 861125705u, 2800024898u, 3273280398u, 381422586u, 3458645582u),
SC(4292194968u, 248883279u, 3851291071u, 2381853448u, 1073433118u, 2354758646u, 509168387u, 1080387022u, 4117133479u, 4274939184u, 1790223702u, 3619550239u, 893146224u, 3535153470u, 2843460502u, 3639480269u),
SC(875705436u, 2649940325u, 3671965902u, 2567151996u, 544268373u, 1955202709u, 305754623u, 1141543641u, 990189469u, 3756473672u, 1148700315u, 1129055741u, 1437435407u, 3710411618u, 2889469156u, 1535007815u),
SC(2884213479u, 1770002877u, 1717656157u, 132095051u, 3410594069u, 2825430154u, 637479405u, 1954348940u, 261832561u, 289175839u, 3006609188u, 2819765533u, 965261546u, 61421601u, 3676726043u, 1762126450u),
SC(1279868755u, 1028393837u, 402310972u, 1124180052u, 1966420832u, 355916436u, 3164845140u, 1987806920u, 2358723546u, 2333235794u, 547656661u, 741426190u, 3791351751u, 229368670u, 2060024860u, 2496159246u),
SC(729000302u, 1895693776u, 4291166676u, 165118594u, 4187486015u, 4003769717u, 4173715283u, 1708863275u, 2571981291u, 3314404862u, 2784625143u, 1378770288u, 471970597u, 2471540726u, 885481379u, 30714732u),
SC(3178372343u, 819515330u, 1006458744u, 1744046151u, 1335890469u, 3720299130u, 3351999440u, 1610902263u, 1660799402u, 3095620625u, 2313473472u, 1025272967u, 2457745086u, 776820149u, 1991370461u, 2446835994u),
SC(1010694829u, 3576636721u, 3447938536u, 3020554334u, 2855010652u, 1077306503u, 2519536483u, 1693776468u, 2719234662u, 2809016552u, 352917716u, 496941437u, 2794886318u, 3290871493u, 85090184u, 2720964345u),
SC(3154596760u, 1177221669u, 1472641897u, 3066862312u, 1973719267u, 3888536326u, 4158066426u, 375731453u, 1194368649u, 504110184u, 3332723499u, 3007941073u, 1703908862u, 2111295124u, 3526651404u, 361981784u),
SC(1082063268u, 2838135921u, 1074670559u, 1981839722u, 68208200u, 3852545089u, 1874506558u, 34706706u, 1621217725u, 2860154504u, 3598425424u, 186699529u, 2022232276u, 1552131421u, 1256799706u, 1237253344u),
SC(4253983049u, 1956128201u, 531971008u, 849224076u, 726267438u, 2775479863u, 1930393199u, 1383823745u, 63229370u, 473494690u, 2189839240u, 2776826045u, 227039104u, 3325879119u, 1283171084u, 96817479u),
SC(3860217166u, 2940528670u, 506602091u, 3419829981u, 506043244u, 614420425u, 2993710593u, 2920806228u, 1333084534u, 3486829092u, 3082898297u, 2169097101u, 1082170030u, 1470175076u, 1320435311u, 574635396u),
SC(3258895975u, 4163242637u, 1293464004u, 352297789u, 3644545561u, 3993568180u, 3296091139u, 1095374790u, 2336524066u, 1528884861u, 4268554127u, 1914733099u, 3903840151u, 419762607u, 2887932559u, 497165606u),
SC(980659287u, 1953455590u, 2112574847u, 735340650u, 1925619502u, 3115495333u, 3627587353u, 1603624354u, 2142860308u, 3379792281u, 1362168334u, 2246175020u, 3677515235u, 2774668056u, 1792230968u, 2199982799u),
SC(3323498046u, 1302414577u, 2803546118u, 580488762u, 3428322024u, 682658893u, 4172122357u, 97546814u, 3512743931u, 2961959221u, 4170912416u, 2164991348u, 3081828834u, 1345963536u, 3053610974u, 512267725u),
SC(4109044470u, 2963061726u, 1107510334u, 767020404u, 632532721u, 4969584u, 2231147626u, 2004993117u, 2229787907u, 2636257111u, 3533633798u, 4022669901u, 2099786750u, 2966651314u, 491396645u, 1164008374u),
SC(1146578221u, 2435053231u, 2036416135u, 3952141868u, 3838293158u, 979053357u, 2978198077u, 3177553682u, 205027764u, 3304212977u, 4039842386u, 2269838528u, 1189968975u, 1530161763u, 3715730701u, 2440676344u),
SC(3853141068u, 3126625672u, 870454728u, 2770453842u, 3177858206u, 2718094073u, 853260005u, 1096986102u, 286922389u, 3880860786u, 1776703863u, 829544988u, 2267526544u, 853417458u, 487507949u, 1744159087u),
SC(2635257045u, 2400379653u, 4082046555u, 3320840431u, 2185118249u, 1851238012u, 586412780u, 198559223u, 4176104900u, 320695580u, 3648763183u, 469999712u, 4056550133u, 1898353926u, 1621070568u, 336190756u),
SC(425773252u, 4192919959u, 695637058u, 2825893835u, 1246684379u, 2776039455u, 335155142u, 875351021u, 3737502706u, 2678257435u, 2570009254u, 557800437u, 3620249817u, 906765743u, 3009358775u, 2003811188u),
SC(3586739762u, 1605178799u, 3207158625u, 2416685060u, 1372280459u, 4291657519u, 3226341120u, 1515806996u, 3830239194u, 2213324751u, 3133089253u, 2615223728u, 3226239280u, 1327007494u, 1747242554u, 1946789201u),
SC(229748829u, 3453591261u, 3328466049u, 1202432283u, 3704729156u, 417637853u, 2491491096u, 4271840908u, 4186017690u, 2332641048u, 730397211u, 1755124885u, 3913997159u, 1855079991u, 3101480857u, 2716742242u),
SC(2131208225u, 203490023u, 3341197434u, 2300918186u, 2246435820u, 116889233u, 936875537u, 1136106357u, 1665211349u, 1592129410u, 3788667018u, 830310025u, 1614112315u, 1756980280u, 1897821395u, 2931105520u),
SC(936572343u, 3328922681u, 652778152u, 4066731934u, 992030872u, 1684535959u, 670262747u, 3130245314u, 2707904872u, 282017684u, 2219138782u, 4140629492u, 2949064430u, 895598721u, 2387828596u, 215164108u),
SC(3493973951u, 3052742089u, 1710913345u, 632879547u, 3449905868u, 723462156u, 2752538048u, 1447512672u, 885479393u, 3088711229u, 4251105939u, 134301981u, 3569471580u, 3111378722u, 264654627u, 482772304u),
SC(3326132753u, 4076881523u, 2748893798u, 2710074042u, 3150043853u, 1630829959u, 2025540868u, 1217571715u, 180553209u, 2317777177u, 1747013269u, 1205226794u, 3222652736u, 1444521786u, 371361777u, 1437728689u),
SC(1980393090u, 1471052682u, 2529544041u, 2419695874u, 3416920350u, 2902943265u, 2292472396u, 378161194u, 2894177140u, 3269090944u, 3526211692u, 925904026u, 454381125u, 305110335u, 190601650u, 3202914870u),
SC(1467005633u, 2266792546u, 3036672011u, 2807172437u, 3596333220u, 2090178779u, 1070591642u, 671033187u, 2186441971u, 1145180231u, 596681715u, 2813955552u, 3463494648u, 1836204490u, 2839238997u, 615421147u),
SC(2486357277u, 2321737088u, 371691250u, 3253348099u, 241336936u, 1054510245u, 3172626830u, 1843946705u, 1551788124u, 1144782604u, 514598370u, 1218251797u, 4004257982u, 3153901098u, 2725745546u, 563089494u),
SC(855278129u, 1794192908u, 2589523709u, 3136624000u, 1751139899u, 1931822141u, 4001840960u, 2373683750u, 3112669843u, 1700902707u, 2492103535u, 1398687385u, 1364870191u, 268889761u, 2577131856u, 3537912469u),
SC(2401910678u, 375305965u, 1845797827u, 1808370621u, 2384610951u, 2115981945u, 1268013032u, 973702739u, 3477996375u, 3401321764u, 2985206092u, 463194589u, 3843250253u, 1296525826u, 200946437u, 4183167840u),
SC(3046164623u, 1698475855u, 4011038180u, 876115994u, 1497982689u, 4198027289u, 3324605264u, 2096750914u, 3052485168u, 3278426185u, 2084420855u, 4155537945u, 890002226u, 613397114u, 2729032243u, 1574013457u),
SC(1904438222u, 1928771619u, 149813336u, 3934581410u, 1242285777u, 1947850577u, 3779741715u, 3156633814u, 827781197u, 3250102070u, 31967352u, 2495163015u, 744720783u, 953132272u, 1221248003u, 3394764122u),
SC(429325682u, 1724343519u, 2839246837u, 3243811869u, 2918477112u, 2913144266u, 1653710327u, 179459835u, 60361632u, 2169500867u, 1216490983u, 2766565465u, 606947728u, 2025715588u, 685534359u, 4134534728u),
SC(4274280104u, 114119435u, 3494981356u, 807288563u, 3579018216u, 2538324541u, 1625485242u, 1907711206u, 3161960219u, 1114518567u, 1717624176u, 786637484u, 3521223946u, 2065514921u, 2344499302u, 2634576753u),
SC(2629293665u, 123297883u, 574084434u, 3835067290u, 2557454780u, 2321556291u, 3989586587u, 455127277u, 561140419u, 336849834u, 3541875999u, 3505843788u, 1100171101u, 1477969571u, 1787186147u, 152619512u),
SC(3646569096u, 2625904850u, 4234890597u, 2139521797u, 1000835213u, 3376846654u, 1685875403u, 2197084269u, 3623130940u, 3174867906u, 4226648907u, 3884803677u, 2168476426u, 3982197216u, 3318351026u, 3368793623u),
SC(2364788399u, 2094495544u, 3600031443u, 52518095u, 3450803164u, 2433684078u, 1127574085u, 3164350498u, 2201911852u, 3482369434u, 3708203090u, 3671504700u, 3052303992u, 3248874335u, 3555217851u, 2846467790u),
SC(2723735014u, 236629053u, 1887196519u, 2848632391u, 455156299u, 2273479869u, 1400856890u, 1826270119u, 221549383u, 3908193465u, 302170230u, 1819428813u, 3807297182u, 1656418004u, 178590097u, 1378626567u),
SC(4132749640u, 115991972u, 785193414u, 2604851835u, 2499003323u, 872920452u, 1114128937u, 3658200701u, 3401955590u, 3496370113u, 3622819064u, 3516038987u, 2562267551u, 1775138324u, 3020878076u, 231617546u),
SC(4077750691u, 2771835701u, 2957045153u, 1367974584u, 376086022u, 1288251730u, 59162210u, 792982409u, 127585792u, 1095980158u, 3149464510u, 200076985u, 2836796255u, 1120639529u, 1417772957u, 3406945969u),
SC(1047410039u, 3156369931u, 3920196112u, 1958431722u, 2537004375u, 3156137498u, 864559652u, 811486751u, 4130646394u, 776484898u, 1011672286u, 1356587260u, 293263635u, 3285964634u, 1777118922u, 490814818u),
SC(829171875u, 1673500241u, 752481928u, 467629104u, 3690456468u, 3869757428u, 3180928024u, 3535831866u, 1109526652u, 1706204822u, 2082824867u, 1246305295u, 1521867554u, 801312055u, 1276205003u, 1542551361u),
SC(864331020u, 2674006384u, 46132127u, 1533172170u, 1617035343u, 3023527714u, 572890670u, 2907267638u, 934257589u, 598131077u, 941083478u, 3858267680u, 1599598982u, 1974889698u, 1276949852u, 264135603u),
SC(839395994u, 1173798234u, 2429488892u, 2352360870u, 1593943673u, 745758510u, 169096299u, 2554493420u, 4227502961u, 2124710128u, 2690424297u, 4138012372u, 1513535824u, 4270029974u, 3102581644u, 450337691u),
SC(3620750541u, 4243659078u, 2546350744u, 2494917421u, 45295851u, 2411574007u, 261198969u, 765587684u, 1188720760u, 1246321531u, 3896103880u, 281900580u, 1599084165u, 359013339u, 1316512053u, 655643585u),
SC(63832981u, 1762179748u, 520016426u, 1020440971u, 236239932u, 2709425734u, 2138406486u, 1393881727u, 4242636743u, 2097184028u, 626362208u, 3610247579u, 581737727u, 1867228809u, 2710068013u, 1594688576u),
SC(794456914u, 295850194u, 3406979639u, 3267947487u, 3923232296u, 2586941699u, 1511972376u, 3045444584u, 3809039136u, 1058680030u, 3972734621u, 1541958123u, 256144497u, 2675339486u, 4055395548u, 4209367667u),
SC(3899025122u, 159421581u, 684898980u, 3299122517u, 4294073145u, 1432967880u, 298637016u, 4169308298u, 2184881981u, 549517384u, 1722336827u, 1446107911u, 3097583453u, 2430049850u, 23871552u, 2769316231u),
SC(454879299u, 2506071180u, 685424913u, 1586115964u, 3739465507u, 1892797750u, 2634261446u, 461271874u, 1602636000u, 1231373405u, 3431819543u, 3678787544u, 826660844u, 1912004887u, 2390177572u, 2745071695u),
SC(4276811043u, 1059097804u, 289900404u, 3137716705u, 3430869283u, 853997644u, 2534016377u, 2935805170u, 1207363272u, 1046214590u, 1464072054u, 3859266163u, 2822765506u, 4056252869u, 3234536856u, 2970346892u),
SC(1107848321u, 3530054002u, 3063728370u, 2411260233u, 2151773796u, 1992367533u, 452845303u, 2000515834u, 2967581171u, 2030577785u, 1361248948u, 320123819u, 1514107806u, 2861220339u, 3414354882u, 3271151930u),
SC(1603129579u, 1475913977u, 3512753704u, 2558173661u, 3149727230u, 2330111694u, 1224500114u, 15318u, 3353016208u, 194039451u, 2805611551u, 1261479176u, 3558608211u, 4084583046u, 2964990209u, 3717911682u),
SC(3375017300u, 1835026114u, 1174849844u, 104042981u, 2705057661u, 3824090647u, 989860283u, 312294099u, 680304336u, 766797089u, 3374619394u, 2401643295u, 2657633584u, 750406370u, 1348478381u, 3389751656u),
SC(3824059184u, 859274310u, 3575417504u, 2031700058u, 3460053353u, 3845330189u, 2749453433u, 4067197094u, 4149711934u, 2506719565u, 493599601u, 1428768643u, 1342993875u, 1964027032u, 407468978u, 2475215503u),
SC(2508265589u, 1835337120u, 144393964u, 1686774423u, 3728282933u, 3548855171u, 2816165978u, 448310785u, 3131571614u, 3211253928u, 3249304541u, 1774134863u, 3772421675u, 3798786595u, 3711817145u, 2169824164u),
SC(32143084u, 2710918433u, 715862337u, 389930087u, 2221145209u, 780694167u, 2803105449u, 3053866952u, 3367190643u, 2356359566u, 3612803918u, 3376924083u, 3128667863u, 1055559333u, 743267127u, 1636229763u),
SC(942152421u, 924529791u, 3200379335u, 2216473553u, 1518198695u, 1749982867u, 3804310737u, 2901470813u, 2348087597u, 2465905835u, 3356813200u, 565045285u, 1150286792u, 2016334277u, 1623662921u, 1744657596u),
SC(1808796868u, 1702566146u, 1375264075u, 2615953000u, 2965950393u, 1695782388u, 2343426588u, 2715536698u, 2228686994u, 3816453121u, 2164987884u, 1041123441u, 667190396u, 2947698065u, 605361351u, 2006737381u),
SC(2152511832u, 2808902472u, 396766736u, 45163647u, 1176778983u, 2964564331u, 3254967387u, 12684777u, 3346396686u, 2654599951u, 2022589511u, 4223927952u, 3434018260u, 782073481u, 3870179765u, 2412969138u),
SC(3506766224u, 4215699755u, 3265132994u, 1596694088u, 2568115528u, 862000635u, 3074727028u, 1746671278u, 3598160479u, 3913583347u, 1987267603u, 2939122739u, 2846590159u, 3081159893u, 3590920954u, 124180600u),
SC(3089031975u, 2914228615u, 3369489731u, 2071754524u, 2422301244u, 3208043074u, 3972514342u, 1324812497u, 1858365131u, 2745510829u, 2851338147u, 1859718474u, 2239378800u, 1627399072u, 2499563783u, 3743438522u),
SC(119920204u, 1093195661u, 297072634u, 3953067261u, 2423631007u, 3776093882u, 2235876342u, 1751039492u, 921352707u, 155940113u, 833209844u, 690647815u, 409140151u, 3292524092u, 509521330u, 2142657976u),
SC(1074172420u, 3956560660u, 2765576142u, 1514152128u, 3815717847u, 4294393136u, 1617070931u, 2372425825u, 3625006267u, 1589460351u, 17469645u, 916374486u, 2628470982u, 4104017283u, 3613829856u, 1296461095u),
SC(2417628797u, 434113733u, 347322148u, 1973353060u, 1052223694u, 2489772785u, 3069882824u, 1672935871u, 3774929361u, 3779403529u, 727455585u, 506274678u, 1974585690u, 2803500332u, 3880352355u, 2852036869u),
SC(4042964279u, 972373289u, 2149449957u, 810333657u, 2740269606u, 4294556254u, 3372093488u, 645110813u, 3441665397u, 248553132u, 4165233804u, 2133925580u, 2024582183u, 974116599u, 2559302342u, 907691640u),
SC(2404290008u, 551018534u, 3459234433u, 419597992u, 1972345324u, 4156305161u, 3527005711u, 604142749u, 2176391549u, 1937020765u, 466413583u, 445259396u, 430417494u, 1889917985u, 1236273825u, 1610962755u),
SC(3907300388u, 461727940u, 3469013130u, 2611871544u, 2277585634u, 1202574863u, 1010420602u, 2298806908u, 2311540248u, 1953724441u, 1877058742u, 992514980u, 2254299312u, 2002098425u, 860900005u, 2890218129u),
SC(3869811984u, 4147212017u, 1313925624u, 3364106784u, 3225286495u, 3842562080u, 4093251003u, 1587351444u, 516793856u, 352093800u, 850522865u, 3087846162u, 2864496532u, 4149152365u, 3698092330u, 2717925551u),
SC(1965851236u, 3216050915u, 2931553633u, 1063637393u, 3533008444u, 2807533139u, 713786812u, 3944556878u, 536199488u, 106266739u, 3659319211u, 4202747077u, 3579273518u, 211354118u, 1876465071u, 298666300u),
SC(2593803771u, 1633427065u, 3267467801u, 875562818u, 1932112370u, 192604181u, 2396580849u, 1484312622u, 970619813u, 4055463243u, 3875191799u, 172341226u, 1555884586u, 3660378812u, 2192229995u, 1183512881u),
SC(336961210u, 2429966559u, 4280956710u, 2595621898u, 1967179407u, 2810053433u, 2360142687u, 1650644566u, 1150788249u, 666068449u, 900169569u, 3144395892u, 1763238854u, 2046390305u, 2536267795u, 226560486u),
SC(223166076u, 782629748u, 1159073256u, 431932633u, 197673913u, 4229233268u, 1812772930u, 453158757u, 3042313935u, 1434181308u, 2430243413u, 4137912981u, 1589402008u, 3204585224u, 3993670050u, 343590532u),
SC(449690994u, 319806074u, 305004892u, 4077917808u, 3624468883u, 2189889725u, 535999042u, 1564399766u, 3100381318u, 880463501u, 2240587453u, 1453850917u, 2098152243u, 187061279u, 2556820292u, 3321055703u),
SC(2475105093u, 2199905630u, 2184413732u, 2864493576u, 650198825u, 1690664913u, 194212127u, 1319451903u, 2033204333u, 444617977u, 3597423908u, 2415512974u, 397802954u, 4193928072u, 2600490466u, 22809172u),
SC(2199507330u, 1506507893u, 579678542u, 2108807958u, 3813449570u, 737470611u, 4033840836u, 824368209u, 97307470u, 3801467614u, 3996740480u, 284558397u, 3641971730u, 3102425622u, 1626983523u, 4002871006u),
SC(487823224u, 1685221259u, 1997782711u, 1617354589u, 3574687528u, 3580399598u, 3792675119u, 351896957u, 66912916u, 3652873852u, 2047393123u, 3611768414u, 3940203191u, 1609681546u, 2501330281u, 3338397968u),
SC(2730586736u, 694867425u, 2095124930u, 2308182438u, 661584751u, 3598273149u, 556778443u, 2107619889u, 2963466614u, 1478501027u, 2730899139u, 738789883u, 87276538u, 423592806u, 3864462020u, 3772277406u),
SC(615994432u, 968963356u, 3436096730u, 3541857676u, 543371738u, 2275571690u, 1485456246u, 2195380075u, 2236529476u, 2740053810u, 3640697310u, 3685787103u, 378155292u, 1257250263u, 1685202225u, 2735940115u),
SC(3365723994u, 3233473616u, 4292918727u, 4028548222u, 2315480265u, 1138806130u, 610060892u, 814547079u, 3846780411u, 1860863520u, 2830655398u, 3594327274u, 381873610u, 2466081500u, 2146090037u, 2438568651u),
SC(626941770u, 734214893u, 2879567852u, 2989408805u, 819182369u, 4154866660u, 3177066349u, 2907236647u, 2043405376u, 148540537u, 1958724781u, 655745771u, 4005742928u, 144708920u, 3195624737u, 3294802440u),
SC(3779690491u, 2872348419u, 3926351178u, 3183728123u, 2998514707u, 1571508624u, 764287321u, 736460288u, 3810086061u, 1355473395u, 2121349842u, 1538668027u, 1962331070u, 2205688849u, 1705565110u, 3438178218u),
SC(3119340081u, 2862892011u, 2581114858u, 2066921503u, 1482724458u, 1516135342u, 3740444348u, 633618335u, 3854505391u, 1040867285u, 312560237u, 3762086043u, 2821402540u, 1874387307u, 1887916767u, 2515566790u),
SC(1169191436u, 2088376053u, 2651309986u, 3120013004u, 424428695u, 705129470u, 3446022537u, 257013236u, 3098335060u, 2794295542u, 2458891541u, 3575471238u, 3093988139u, 352756305u, 1148465314u, 4065705103u),
SC(2320246151u, 3441943859u, 2105839446u, 1127380105u, 433302152u, 114604356u, 3570681481u, 97247661u, 1478288627u, 1953610440u, 2660257199u, 3290436596u, 609329493u, 1805724333u, 3736086099u, 2509400120u),
SC(1290819792u, 4120223469u, 2269129063u, 2015215524u, 702520801u, 846607351u, 2796770526u, 3957217962u, 2455027893u, 1889509516u, 1749703137u, 409248010u, 1011782489u, 3717313435u, 352742190u, 3866665384u),
SC(1226869143u, 860995366u, 3844365560u, 2949031580u, 3131198920u, 89546485u, 3550374405u, 2336022295u, 2754047952u, 527781768u, 297652557u, 3519992023u, 2344059967u, 2826364886u, 2503066147u, 48875956u),
SC(2064223472u, 4170670972u, 3442657693u, 3734351065u, 772127559u, 2976536779u, 3588847655u, 1933986041u, 491681586u, 748272081u, 3711110902u, 3914666890u, 114341382u, 424194151u, 3992044443u, 1638597893u),
SC(573249158u, 2194313036u, 187907496u, 975125755u, 3785334330u, 2337897707u, 3467368030u, 1913319997u, 1920481035u, 3340935483u, 3640747231u, 1093811620u, 1823978310u, 1007954167u, 643612629u, 1829604661u),
SC(2547681801u, 2318731186u, 190788363u, 3020256811u, 3486893617u, 3984808880u, 2217400157u, 2719439921u, 1543838447u, 2725838041u, 2732732651u, 2571102426u, 4039140102u, 346400433u, 2040270036u, 3549499716u),
SC(643254237u, 2668430230u, 4205134369u, 1241842066u, 1038603126u, 4046940321u, 1356505240u, 2462740951u, 1093623353u, 3682382337u, 1023949856u, 433965863u, 805112331u, 2302754433u, 1998109410u, 4044492715u),
SC(2441752430u, 2252063997u, 2276842309u, 358030690u, 1357413447u, 4238381388u, 729209311u, 408685106u, 2773818813u, 1551078407u, 2282378375u, 2363627702u, 1986987347u, 2029101139u, 396284872u, 1060515830u),
SC(1839660827u, 3971561168u, 514020292u, 3393164442u, 2417311433u, 322081286u, 2342249107u, 2921896334u, 2184094080u, 2187706290u, 1072088772u, 1375085125u, 1099278355u, 3824555524u, 3364898024u, 1432019110u),
SC(3154587866u, 2584103018u, 2570472941u, 190918583u, 2889272609u, 1181711055u, 3770557998u, 1440797289u, 2097141926u, 332350415u, 2127204431u, 2527717853u, 2337594658u, 1228349589u, 2504537490u, 1691859104u),
SC(2532748959u, 2217220377u, 1347960721u, 3568791237u, 1006754848u, 1829163834u, 627091706u, 301882799u, 2864915541u, 2898727542u, 4025295836u, 2873293708u, 616372442u, 1615565118u, 3184603530u, 219922979u),
SC(4065131546u, 2586412172u, 4057568976u, 2145140449u, 4279554467u, 2810257176u, 3904752711u, 2810209588u, 3773052477u, 706904008u, 771163317u, 828641491u, 2792483375u, 54985408u, 1913191207u, 1813844703u),
SC(287551380u, 3899600367u, 90305680u, 2494240268u, 2574195029u, 3693451256u, 4269169707u, 3564713593u, 970023080u, 3405034180u, 3840495751u, 1855598979u, 1440012839u, 2625512489u, 158736485u, 2942481089u),
SC(4122519524u, 1833636106u, 1188113836u, 3540572882u, 1065306493u, 3047729005u, 3377954214u, 4036244528u, 2203664835u, 2972626310u, 1822683230u, 3299907923u, 2592781888u, 1044710800u, 933859526u, 2294387247u),
SC(254836555u, 3077209039u, 535256453u, 101338212u, 3343430447u, 1218326710u, 385898477u, 576495253u, 4229958338u, 1000586861u, 2857193350u, 3365919835u, 2393902988u, 3956238913u, 1363218498u, 2904039349u),
SC(3687780594u, 3829065812u, 2247974925u, 3399135869u, 129644861u, 3869455296u, 2030161860u, 1429546345u, 1221870733u, 2363913439u, 220548873u, 402506640u, 3734677759u, 696688039u, 1277503948u, 3712446392u),
SC(950039042u, 2721916669u, 1715447777u, 2391409321u, 640745758u, 1467158564u, 1047624387u, 2688090232u, 4217395116u, 2857348023u, 3303613131u, 2871754673u, 3840979879u, 1809978871u, 2112001747u, 3983580655u),
SC(1540614060u, 100163999u, 1572306537u, 4148257097u, 3031410119u, 2513592251u, 4213023149u, 2655393763u, 2598832624u, 3609693006u, 191271323u, 3328628283u, 74170920u, 2359908075u, 773858187u, 611474774u),
SC(904169586u, 1349784970u, 2368656274u, 3514365666u, 3838066633u, 109687597u, 1597459461u, 3593971003u, 2501130050u, 2075136091u, 1585406194u, 3646943588u, 4286614395u, 3266140461u, 1754828382u, 3143456377u),
SC(2249819706u, 3567094453u, 1822006903u, 1179902375u, 1254849123u, 3988150336u, 1995682734u, 2420061561u, 1159004321u, 1034717096u, 2900885070u, 1692164468u, 2305511426u, 1729510378u, 490582645u, 3089583301u),
SC(2951740380u, 3739114159u, 3700508508u, 269031634u, 4119869919u, 3044364120u, 2737874025u, 408283224u, 3764300973u, 4266881177u, 901644659u, 1028345286u, 1987367331u, 2106662146u, 245692239u, 1801705988u),
SC(728333338u, 757982977u, 374564642u, 2489206473u, 569389015u, 3639213382u, 2410279257u, 502022771u, 1842785627u, 1146360661u, 2209645375u, 283006625u, 3977692584u, 2010485741u, 624474460u, 3464988143u),
SC(3437677747u, 4229741761u, 524305791u, 622165284u, 1832906658u, 616775921u, 3957013250u, 1057153999u, 2543296862u, 2900412000u, 3952324997u, 2137909214u, 756879158u, 2358914795u, 2772117600u, 3012738863u),
SC(1910987988u, 1495405769u, 1433256375u, 2814952911u, 2007695945u, 2796006810u, 932068957u, 3511718813u, 1309447687u, 3249702510u, 558840032u, 3564477427u, 3012501370u, 893979501u, 1892626021u, 4259908548u),
SC(3735637403u, 3223465030u, 3328185020u, 2443427380u, 3588194647u, 1453971837u, 1388889265u, 619521084u, 3017762431u, 638951631u, 779878690u, 1672433767u, 189257931u, 3525584370u, 467378482u, 1580414344u),
SC(1740326806u, 3364799097u, 2280117479u, 3173928606u, 196182123u, 2513688756u, 3785741159u, 105803009u, 720390983u, 1658167586u, 1003552070u, 1237199645u, 2464112010u, 2228138501u, 4072083246u, 3043463824u),
SC(2253990976u, 1907759613u, 41826341u, 3394788573u, 3926296920u, 2069488571u, 3008893045u, 2748025494u, 2453161151u, 706313093u, 2989668723u, 690146828u, 2722307524u, 2778540016u, 804500212u, 2943812543u),
SC(3895076977u, 4227830887u, 2517668608u, 654291094u, 3645938499u, 1853384343u, 3898365875u, 949964733u, 1999811609u, 4040589991u, 2595243943u, 3567588997u, 4239015052u, 3447788988u, 1333073140u, 387434500u),
SC(2617745338u, 852633742u, 2692915105u, 21507515u, 2150775166u, 3329677124u, 3350253188u, 2714039609u, 722933561u, 2247779386u, 3128104147u, 2263910080u, 3565701987u, 1080206536u, 1065289130u, 1465464486u),
SC(2028625713u, 490477891u, 3828899870u, 2827333262u, 4025390057u, 645303682u, 1049143069u, 2619529075u, 2503782621u, 2302340403u, 2418140731u, 662489697u, 1299655806u, 2730027583u, 3172277012u, 1555121340u),
SC(1227465576u, 4186188055u, 1945445231u, 3713842559u, 2833833375u, 39963563u, 1497935191u, 2039267193u, 648193035u, 862129749u, 2067230680u, 323652936u, 1412172008u, 3268418201u, 92721980u, 1725133862u),
SC(3142294756u, 3101500095u, 678671070u, 4070328655u, 1646103012u, 2931768355u, 1450052820u, 3036664456u, 3573028674u, 1333234022u, 19353544u, 3903478868u, 1144323239u, 1802745401u, 2689248101u, 2344057903u),
SC(1878460181u, 398312100u, 3223747754u, 952800941u, 2317571908u, 707058567u, 2692538054u, 3283100410u, 790016661u, 2732292717u, 840073411u, 2772303092u, 1733149205u, 954377558u, 1976383461u, 3555619682u),
SC(3043073118u, 3988558576u, 3364527277u, 2572525707u, 1984812675u, 907786226u, 2355173463u, 3564356699u, 301368907u, 907108737u, 3534700396u, 4268985476u, 2015423457u, 1408288811u, 350602874u, 3013747006u),
SC(3343197847u, 3613988450u, 2923132236u, 2078350840u, 2893073548u, 3806857883u, 2520297714u, 2737040597u, 4270123363u, 842123948u, 1671808972u, 2429482643u, 2795413824u, 3360088499u, 3110760390u, 1756642408u),
SC(3348613721u, 2513282826u, 2737869756u, 1333756870u, 439462686u, 3688296717u, 836819461u, 1693717511u, 3460982009u, 2927554331u, 2059382164u, 4104562673u, 3343263374u, 2416351582u, 150459153u, 461502558u),
SC(680144422u, 2411264808u, 700292385u, 1321567755u, 4229879159u, 4094452100u, 2040576289u, 3270817402u, 2202259517u, 1433140964u, 3060573592u, 4110339019u, 2854691778u, 4089664003u, 3994185997u, 3657370450u),
SC(2057316978u, 2918176633u, 4254682231u, 1769922882u, 3710243176u, 952678560u, 1366865895u, 938684466u, 2690709460u, 2383161641u, 2252474535u, 375919259u, 993593539u, 132684704u, 3890567846u, 1581177230u),
SC(882007322u, 2982658177u, 3913668205u, 1626159438u, 4101301130u, 1110794931u, 2512146900u, 3304411937u, 2398674264u, 2920702389u, 2814584762u, 2889942502u, 3492637232u, 576964088u, 1656165114u, 2959402338u),
SC(733944299u, 161882394u, 2021771232u, 1417913112u, 3386446464u, 3500017204u, 710191602u, 3043314664u, 63929153u, 3215663501u, 3783446324u, 843385535u, 2295995926u, 4256667289u, 3976116578u, 970203859u),
SC(2549199626u, 1826807182u, 486758651u, 1169437438u, 3194853654u, 887932836u, 3083554620u, 4050010040u, 3352011307u, 2292577732u, 1234112290u, 3467019022u, 464801308u, 2141034547u, 1611897902u, 2547693530u),
SC(3050366744u, 1645873728u, 3266179914u, 1042179286u, 3148690840u, 3868476470u, 4177032272u, 1465737711u, 776203120u, 2411258528u, 4064942610u, 2055801863u, 226080029u, 1625531009u, 1687878204u, 405625719u),
SC(1177583865u, 434951215u, 1497219594u, 758210764u, 1960401198u, 1148135837u, 3193194228u, 594172695u, 711270413u, 3786500469u, 2640082390u, 262588006u, 3125113485u, 876438329u, 1210266513u, 1623280150u),
SC(1417604899u, 1365791138u, 789974720u, 2014988785u, 343986301u, 638036826u, 2305125524u, 796347226u, 3949929629u, 3999419566u, 3418726146u, 1675235276u, 3812249948u, 2218538546u, 1713312740u, 969208036u),
SC(2012268962u, 1372883769u, 1660497450u, 1738529228u, 4099469690u, 3992291518u, 3569181768u, 1207513199u, 895436839u, 2970509643u, 1167074347u, 3662966355u, 3688110558u, 488275875u, 546149200u, 882301708u),
SC(2179335873u, 431419264u, 1099603976u, 2126182867u, 2061496831u, 2820633498u, 388651019u, 667374684u, 3719315532u, 3848344517u, 2475819906u, 1831525042u, 1703982345u, 1166431238u, 3458191958u, 1701126298u),
SC(2463394285u, 3767967190u, 2124249905u, 4042720227u, 2546652475u, 3859815214u, 4005065037u, 1683925660u, 614508422u, 2439157748u, 1783875522u, 43662485u, 2163131681u, 55949347u, 4031284320u, 962158034u),
SC(3842200385u, 1548337741u, 4134709070u, 1320341768u, 1476040826u, 2948923768u, 4290414487u, 1426260079u, 944907873u, 4268239236u, 2070796897u, 2646336635u, 901827051u, 3080412463u, 745252994u, 650876372u),
SC(3497488416u, 3480077417u, 3473018085u, 3863724772u, 506196246u, 1330544975u, 414956623u, 4100501688u, 2574983523u, 3295085569u, 672847947u, 2836712420u, 3882507441u, 3415261629u, 3973760389u, 1646047398u),
SC(2283453852u, 119009442u, 906880269u, 1722398293u, 3108347490u, 2158593498u, 3893490354u, 357445754u, 200197489u, 326435615u, 894294620u, 3117954941u, 481597462u, 525104013u, 4139373347u, 261802701u),
SC(2877102266u, 2506087082u, 2980100901u, 629427754u, 2637045837u, 4280436104u, 183069761u, 3868254224u, 1308659889u, 3705018819u, 285167655u, 2622703122u, 2230068327u, 2008428921u, 3355911364u, 1120928260u),
SC(442073827u, 937683792u, 3866751566u, 3276225357u, 452189374u, 2889644694u, 2841596409u, 2844217958u, 3701917204u, 2245351813u, 33407529u, 1458461133u, 4207362153u, 1651911067u, 2711221148u, 2258525340u),
SC(3168765711u, 2371065012u, 4059251820u, 170257517u, 95734073u, 3046696342u, 2169138650u, 2689907503u, 119339997u, 3517609762u, 2301592548u, 3928878160u, 2177159502u, 1418335940u, 672708461u, 1461844860u),
SC(3408457434u, 864702600u, 229967322u, 2493308402u, 1948124958u, 932156145u, 3686409998u, 2620533847u, 3649878625u, 3438060863u, 2105857823u, 4170365282u, 1864819030u, 2216504827u, 2058008633u, 1062295811u),
};
unsigned char output[32];
secp256k1_ge_storage *d_prec;
d_prec = sycl::malloc_device<secp256k1_ge_storage>(512, q_ct1);
q_ct1.memcpy(d_prec, prec, 512 * sizeof(secp256k1_ge_storage)).wait();
unsigned char *d_output;
d_output = (unsigned char *)sycl::malloc_device(32, q_ct1);
for (int n = 0; n < 100; n++) {
q_ct1.submit([&](sycl::handler &cgh) {
cgh.parallel_for(
sycl::nd_range<3>(sycl::range<3>(1, 1, 32), sycl::range<3>(1, 1, 32)),
[=](sycl::nd_item<3> item_ct1) {
secp256k1(d_prec, d_output, item_ct1);
});
});
}
q_ct1.memcpy(output, d_output, 32).wait();
sycl::free(d_prec, q_ct1);
sycl::free(d_output, q_ct1);
char result[64];
for (int i = 0; i < 32; ++i) {
sprintf(result+2*i, "%02x", output[i]);
}
printf("result = %s\n", result);
if (0 == strcmp(result, "bbde464b6355ee6de6deba5ae860f8a66524937eee81dde224a0214efd795d09"))
printf("PASS\n");
else
printf("FAIL\n");
return 0;
}
| 104.058684
| 215
| 0.76238
|
jchlanda
|
60555aeb2f184bacb3a11a19cd737f9aed700633
| 2,316
|
cpp
|
C++
|
libraries/types/native.cpp
|
brendankirby/eos
|
233ba4e54bd53a7cf6ac68898fd25c44345737fa
|
[
"MIT"
] | 2
|
2018-01-06T12:12:28.000Z
|
2021-12-25T11:09:37.000Z
|
libraries/types/native.cpp
|
lijava2002/eos
|
2cc40a4eed76b797ba1382ab461fe8b6d3f518c4
|
[
"MIT"
] | null | null | null |
libraries/types/native.cpp
|
lijava2002/eos
|
2cc40a4eed76b797ba1382ab461fe8b6d3f518c4
|
[
"MIT"
] | 1
|
2021-04-04T23:28:27.000Z
|
2021-04-04T23:28:27.000Z
|
/**
* @file
* @copyright defined in eos/LICENSE.txt
*/
#include <eos/types/native.hpp>
#include <fc/crypto/base58.hpp>
#include <fc/crypto/ripemd160.hpp>
#include <fc/io/raw.hpp>
#include <fc/fixed_string.hpp>
#include <fc/reflect/variant.hpp>
namespace fc {
void to_variant(const eosio::types::name& c, fc::variant& v) { v = std::string(c); }
void from_variant(const fc::variant& v, eosio::types::name& check) { check = v.get_string(); }
void to_variant(const std::vector<eosio::types::field>& c, fc::variant& v) {
fc::mutable_variant_object mvo; mvo.reserve(c.size());
for(const auto& f : c) {
mvo.set(f.name, eosio::types::string(f.type));
}
v = std::move(mvo);
}
void from_variant(const fc::variant& v, std::vector<eosio::types::field>& fields) {
const auto& obj = v.get_object();
fields.reserve(obj.size());
for(const auto& f : obj)
fields.emplace_back(eosio::types::field{ f.key(), f.value().get_string() });
}
void to_variant(const std::map<std::string,eosio::types::struct_t>& c, fc::variant& v)
{
fc::mutable_variant_object mvo; mvo.reserve(c.size());
for(const auto& item : c) {
if(item.second.base.size())
mvo.set(item.first, fc::mutable_variant_object("base",item.second.base)("fields",item.second.fields));
else
mvo.set(item.first, fc::mutable_variant_object("fields",item.second.fields));
}
v = std::move(mvo);
}
void from_variant(const fc::variant& v, std::map<std::string,eosio::types::struct_t>& structs) {
const auto& obj = v.get_object();
structs.clear();
for(const auto& f : obj) {
auto& stru = structs[f.key()];
if(f.value().get_object().contains("fields"))
fc::from_variant(f.value().get_object()["fields"], stru.fields);
if(f.value().get_object().contains("base"))
fc::from_variant(f.value().get_object()["base"], stru.base);
stru.name = f.key();
}
}
}
bool eosio::types::field::operator==(const eosio::types::field& other) const {
return std::tie(name, type) == std::tie(other.name, other.type);
}
bool eosio::types::struct_t::operator==(const eosio::types::struct_t& other) const {
return std::tie(name, base, fields) == std::tie(other.name, other.base, other.fields);
}
| 37.967213
| 113
| 0.630397
|
brendankirby
|
60567f64ea6b6cafabd646832942ed25504ca96a
| 522
|
cpp
|
C++
|
sample/cast/main.cpp
|
januswel/cpplib
|
d1c9e325c18e876f40804240c6a3130d7a79a945
|
[
"MIT"
] | 2
|
2016-04-29T05:23:23.000Z
|
2017-11-05T04:12:56.000Z
|
sample/cast/main.cpp
|
januswel/cpplib
|
d1c9e325c18e876f40804240c6a3130d7a79a945
|
[
"MIT"
] | null | null | null |
sample/cast/main.cpp
|
januswel/cpplib
|
d1c9e325c18e876f40804240c6a3130d7a79a945
|
[
"MIT"
] | null | null | null |
/*
* main.cpp
* sample codes for cast.hpp
*
* Copyright (C) 2010 janus_wel<janus.wel.3@gmail.com>
* see LICENSE for redistributing, modifying, and so on.
* */
#include "../../header/cast.hpp"
#include <iostream>
using namespace std;
using namespace util::cast;
int main(void) {
int i = 'a';
const char* c = pointer_cast<char*>(&i);
const int* const j = constpointer_cast<const int*>(c);
cout
<< i << "\n"
<< *c << "\n"
<< *j << "\n"
<< endl;
return 0;
}
| 18
| 58
| 0.55364
|
januswel
|
605d9b89b38a722259f58628ae73140471594ab5
| 473
|
cpp
|
C++
|
trunk/day38/solution.cpp
|
itsjacob/90pp
|
eca71e624d28d216feb06d615e587fc6792c36b6
|
[
"MIT"
] | null | null | null |
trunk/day38/solution.cpp
|
itsjacob/90pp
|
eca71e624d28d216feb06d615e587fc6792c36b6
|
[
"MIT"
] | null | null | null |
trunk/day38/solution.cpp
|
itsjacob/90pp
|
eca71e624d28d216feb06d615e587fc6792c36b6
|
[
"MIT"
] | null | null | null |
// The API isBadVersion is defined for you.
// bool isBadVersion(int version);
class Solution
{
public:
int firstBadVersion(int n)
{
int left{ 1 };
int right{ n };
while (left <= right) {
int mid = left + (right - left) / 2;
bool isBad = isBadVersion(mid);
if (isBad) {
right = mid - 1;
} else {
left = mid + 1;
}
}
if (left > n || !isBadVersion(left)) {
return -1;
}
return left;
}
};
| 18.192308
| 43
| 0.513742
|
itsjacob
|
605e2407040a053f55d0960c6c2ff08cacccd538
| 2,234
|
cpp
|
C++
|
Div. 2/1481 - Codeforces Round #699 (Div. 2)/1481C.cpp
|
ivvlspirit/Codeforces
|
cf9be21f713b032e23c8794c17fa747f1c1e477c
|
[
"MIT"
] | null | null | null |
Div. 2/1481 - Codeforces Round #699 (Div. 2)/1481C.cpp
|
ivvlspirit/Codeforces
|
cf9be21f713b032e23c8794c17fa747f1c1e477c
|
[
"MIT"
] | null | null | null |
Div. 2/1481 - Codeforces Round #699 (Div. 2)/1481C.cpp
|
ivvlspirit/Codeforces
|
cf9be21f713b032e23c8794c17fa747f1c1e477c
|
[
"MIT"
] | null | null | null |
// If you're hacking me, at least subscribe to my channel at:
// https://www.youtube.com/user/ivanvlahov922
#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int MOD = 1e9+7;
int main(){
#ifdef DEBUG
freopen("..\\input.txt", "r", stdin);
clock_t tStart = clock();
#endif
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int TEST;
cin >> TEST;
for(; TEST; TEST--){
// Don't forget to clear global variables if recursive
int n, m;
cin >> n >> m;
int a[n], b[n];
for(int i=0; i<n; i++){
cin >> a[i];
}
vector<vector<int>> need(n+1), notneed(n+1);
for(int i=0; i<n; i++){
cin >> b[i];
if(a[i] == b[i]){
notneed[b[i]].push_back(i);
}else{
need[b[i]].push_back(i);
}
}
int c[m];
vector<int> fix;
vector<int> vres(m);
for(int i=0; i<m; i++){
cin >> c[i];
if(need[c[i]].size() > 0){
for(auto it : fix){
vres[it] = need[c[i]].back();
}
fix.clear();
vres[i] = need[c[i]].back();
need[c[i]].pop_back();
notneed[c[i]].push_back(vres[i]);
}else{
if(notneed[c[i]].size() > 0){
for(auto it : fix){
vres[it] = notneed[c[i]].back();
}
fix.clear();
vres[i] = notneed[c[i]].back();
}else{
fix.push_back(i);
}
}
}
bool res = true;
for(int i=1; i<=n; i++){
if(need[i].size() > 0) res = false;
}
if(fix.size() > 0) res = false;
if(res){
cout << "YES\n";
for(auto it : vres){
cout << it+1 << " ";
}
}else{
cout << "NO";
}
cout << "\n";
}
#ifdef DEBUG
printf("Time taken: %.2fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC);
#endif
return 0;
}
| 21.480769
| 81
| 0.383617
|
ivvlspirit
|
605f490281f075f418dc1896b26bdc98ff21cf6e
| 2,192
|
cpp
|
C++
|
Socket/QtServer/mainwindow.cpp
|
Sakura1221/QtStudy
|
34d24affada2a10c901fb9571473a33c871201fa
|
[
"MIT"
] | 4
|
2021-06-17T02:58:18.000Z
|
2021-11-09T11:40:37.000Z
|
Socket/QtServer/mainwindow.cpp
|
Sakura1221/QtStudy
|
34d24affada2a10c901fb9571473a33c871201fa
|
[
"MIT"
] | null | null | null |
Socket/QtServer/mainwindow.cpp
|
Sakura1221/QtStudy
|
34d24affada2a10c901fb9571473a33c871201fa
|
[
"MIT"
] | 1
|
2021-06-26T07:42:20.000Z
|
2021-06-26T07:42:20.000Z
|
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QTcpSocket>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
// 窗口标题
setWindowTitle("TCP - 服务器");
// 默认端口号
ui->port->setText("8899");
// 创建监听的服务器对象
m_server = new QTcpServer(this);
// 当启动按钮被按下,服务器启动监听
connect(ui->start, &QPushButton::clicked, this, [=] ()
{
unsigned short port = ui->port->text().toUShort();
// 服务器监听接口
m_server->listen(QHostAddress::Any, port);
ui->start->setDisabled(true);
});
// 当有新的客户端连接
connect(m_server, &QTcpServer::newConnection, this, [=] ()
{
// 服务器从连接队列中取出一个客户端建立连接,并返回与客户端通信的套接字
m_tcp = m_server->nextPendingConnection();
ui->record->append("成功和客户端建立了连接...");
m_status->setPixmap(QPixmap(":/resources/connect.png").scaled(20, 20));
// connect注册信号对应回调时,信号发送者必须是实例化对象
// 因此下面两个connect操作,要写在m_tcp实例化之后
// 当可以接收数据(有数据到达),调用readAll读取数据,并显示在消息记录文本框
connect(m_tcp, &QTcpSocket::readyRead, this, [=]()
{
QByteArray data = m_tcp->readAll();
ui->record->append("客户端:" + data);
});
// 断开连接
connect(m_tcp, &QTcpSocket::disconnected, this, [=] ()
{
ui->record->append("客户端已经断开了连接...");
m_tcp->close();
// m_server对象释放后,m_tcp对象也会释放
// 提前手动释放,节约套接字资源
m_tcp->deleteLater(); // delete m_tcp
m_status->setPixmap(QPixmap(":/resources/disconnect.png").scaled(20, 20));
});
});
// 发送信息
connect(ui->send, &QPushButton::clicked, this, [=] ()
{
// 将数据以纯文本方式取出,QString
QString msg = ui->msg->toPlainText();
// 需要转换成utf8才能发送
m_tcp->write(msg.toUtf8());
ui->record->append("服务器:" + msg);
});
// 状态栏
m_status = new QLabel; // 会被设置在状态栏内,不需要指定父对象
m_status->setPixmap(QPixmap(":/resources/disconnect.png").scaled(20, 20));
ui->statusbar->addWidget(new QLabel("连接状态:")); // 标签栏不需要修改,传入临时对象即可
ui->statusbar->addWidget(m_status);
}
MainWindow::~MainWindow()
{
delete ui;
}
| 26.731707
| 86
| 0.577099
|
Sakura1221
|
6060966db4eec6aa361a043bef7f2f500d5c292c
| 1,983
|
cpp
|
C++
|
OJ/LeetCode/leetcode/problems/669.cpp
|
ONGOING-Z/DataStructure
|
9099393d1c7dfabc3e2939586ea6d1d254631eb2
|
[
"MIT"
] | null | null | null |
OJ/LeetCode/leetcode/problems/669.cpp
|
ONGOING-Z/DataStructure
|
9099393d1c7dfabc3e2939586ea6d1d254631eb2
|
[
"MIT"
] | 2
|
2021-10-31T10:05:45.000Z
|
2022-02-12T15:17:53.000Z
|
OJ/LeetCode/leetcode/669.cpp
|
ONGOING-Z/Learn-Algorithm-and-DataStructure
|
3a512bd83cc6ed5035ac4550da2f511298b947c0
|
[
"MIT"
] | null | null | null |
#include <stdio.h>
#include <vector>
using namespace std;
/* Leetcode */
/* 题目信息 */
/*
* 669. Trim a Binary Search Tree
* Given a binary search tree and the lowest and highest boundaries as L and R, trim the tree so that all its elements lies in [L, R] (R >= L). You might need to change the root of the tree, so the result should return the new root of the trimmed binary search tree.
Example 1:
Input:
1
/ \
0 2
L = 1
R = 2
Output:
1
\
2
Example 2:
Input:
3
/ \
0 4
\
2
/
1
L = 1
R = 3
Output:
3
/
2
/
1
*/
/* my solution */
// none
/* better solution */
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int L, int R) {
if (!root) return root;
if (root->val < L)
return trimBST(root->right, L, R);
if (root->val > R)
return trimBST(root->left, L, R);
root->left = trimBST(root->left, L, R);
root->right = trimBST(root->right, L, R);
return root;
}
};
// better
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int L, int R) {
if (!root) return nullptr;
if (root->val < L)
return trimBST(root->right, L, R);
else if (root->val > R)
return trimBST(root->left, L, R);
else
{
root->left = trimBST(root->left, L, R);
root->right = trimBST(root->right, L, R);
}
return root;
}
};
// 当根结点值小于区域左边界时,对根结点右子树剪枝,当根结点值大于区域右边界时,对根结点左子树剪枝,如果根结点值处于区域之间,不剪枝,并且递归推出其左右子树的剪枝结果。
/* 一些总结 */
// 分类讨论,不在区间之间和在区间之间
| 20.443299
| 266
| 0.545134
|
ONGOING-Z
|
60676c38ad551e4e4985696f6b2933bfae919e06
| 2,588
|
cpp
|
C++
|
src/global.cpp
|
quantum-ket/libket
|
8bd80261a7a4903e4108d19524b5f9eb0907daef
|
[
"Apache-2.0"
] | null | null | null |
src/global.cpp
|
quantum-ket/libket
|
8bd80261a7a4903e4108d19524b5f9eb0907daef
|
[
"Apache-2.0"
] | null | null | null |
src/global.cpp
|
quantum-ket/libket
|
8bd80261a7a4903e4108d19524b5f9eb0907daef
|
[
"Apache-2.0"
] | null | null | null |
/* Copyright 2020, 2021 Evandro Chagas Ribeiro da Rosa <evandro.crr@posgrad.ufsc.br>
* Copyright 2020, 2021 Rafael de Santiago <r.santiago@ufsc.br>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "../include/ket"
using namespace ket;
void ket::process_begin() {
process_stack.push(std::make_shared<process>());
*(process_on_top_stack.top()) = false;
process_on_top_stack.push(std::make_shared<bool>(true));
}
void ket::process_end() {
process_stack.pop();
*(process_on_top_stack.top()) = false;
process_on_top_stack.pop();
*(process_on_top_stack.top()) = true;
}
void ket::jump(const label& label_name) {
if (not *(label_name.process_on_top))
throw std::runtime_error("process out of scope");
process_stack.top()->add_inst("JUMP\t@" + label_name.name);
}
void ket::branch(const future& cond, const label& label_true, const label& label_false) {
if (not *(cond.process_on_top) or not *(label_true.process_on_top) or not *(label_false.process_on_top))
throw std::runtime_error("process out of scope");
process_stack.top()->add_inst("BR\ti" + std::to_string(cond.get_id()) + "\t@" + label_true.name + "\t@" + label_false.name);
}
void ket::ctrl_begin(const quant& q) {
if (not *(q.process_on_top))
throw std::runtime_error("process out of scope");
process_stack.top()->ctrl_begin(q.qubits);
}
void ket::ctrl_end() {
process_stack.top()->ctrl_end();
}
void ket::adj_begin() {
process_stack.top()->adj_begin();
}
void ket::adj_end() {
process_stack.top()->adj_end();
}
future ket::measure(const quant& q) {
if (not *(q.process_on_top))
throw std::runtime_error("process out of scope");
auto [id, result, available] = process_stack.top()->measure(q.qubits);
return future{id, result, available};
}
void ket::plugin(const std::string& name, const quant& q, const std::string& args) {
if (not *(q.process_on_top))
throw std::runtime_error("process out of scope");
process_stack.top()->add_plugin(name, q.qubits, args);
}
| 32.35
| 129
| 0.687403
|
quantum-ket
|
60696697ff580a691d9098935d3adb1cf7888f05
| 2,922
|
cpp
|
C++
|
src/ripple_basics/utility/Sustain.cpp
|
latcoin/rippled
|
ca0740de23ec4366d53b0d3770d9a05fc83072db
|
[
"BSL-1.0"
] | null | null | null |
src/ripple_basics/utility/Sustain.cpp
|
latcoin/rippled
|
ca0740de23ec4366d53b0d3770d9a05fc83072db
|
[
"BSL-1.0"
] | null | null | null |
src/ripple_basics/utility/Sustain.cpp
|
latcoin/rippled
|
ca0740de23ec4366d53b0d3770d9a05fc83072db
|
[
"BSL-1.0"
] | null | null | null |
//------------------------------------------------------------------------------
/*
This file is part of rippled: https://github.com/ripple/rippled
Copyright (c) 2012, 2013 Ripple Labs Inc.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#ifdef __unix__
static pid_t pManager = static_cast<pid_t> (0);
static pid_t pChild = static_cast<pid_t> (0);
static void pass_signal (int a)
{
kill (pChild, a);
}
static void stop_manager (int)
{
kill (pChild, SIGINT);
_exit (0);
}
bool HaveSustain ()
{
return true;
}
std::string StopSustain ()
{
if (getppid () != pManager)
return std::string ();
kill (pManager, SIGHUP);
return "Terminating monitor";
}
std::string DoSustain (std::string logFile)
{
int childCount = 0;
pManager = getpid ();
signal (SIGINT, stop_manager);
signal (SIGHUP, stop_manager);
signal (SIGUSR1, pass_signal);
signal (SIGUSR2, pass_signal);
while (1)
{
++childCount;
pChild = fork ();
if (pChild == -1)
_exit (0);
if (pChild == 0)
{
setCallingThreadName ("main");
signal (SIGINT, SIG_DFL);
signal (SIGHUP, SIG_DFL);
signal (SIGUSR1, SIG_DFL);
signal (SIGUSR2, SIG_DFL);
return str (boost::format ("Launching child %d") % childCount);;
}
setCallingThreadName (boost::str (boost::format ("#%d") % childCount).c_str ());
sleep (9);
do
{
int i;
sleep (1);
waitpid (pChild, &i, 0);
}
while (kill (pChild, 0) == 0);
rename ("core", boost::str (boost::format ("core.%d") % static_cast<int> (pChild)).c_str ());
if (!logFile.empty()) // FIXME: logFile hasn't been set yet
rename (logFile.c_str(),
boost::str (boost::format ("%s.%d") % logFile % static_cast<int> (pChild)).c_str ());
}
}
#else
bool HaveSustain ()
{
return false;
}
std::string DoSustain (std::string)
{
return std::string ();
}
std::string StopSustain ()
{
return std::string ();
}
#endif
| 26.324324
| 101
| 0.573922
|
latcoin
|
6069c146322836118882e72623a9bca76a5e61cf
| 11,076
|
cpp
|
C++
|
box2d/native/src/extension.cpp
|
rgrams/defold-box2d
|
f16c138d2c7260cc04272c30d54cd532b572d6a0
|
[
"MIT"
] | null | null | null |
box2d/native/src/extension.cpp
|
rgrams/defold-box2d
|
f16c138d2c7260cc04272c30d54cd532b572d6a0
|
[
"MIT"
] | null | null | null |
box2d/native/src/extension.cpp
|
rgrams/defold-box2d
|
f16c138d2c7260cc04272c30d54cd532b572d6a0
|
[
"MIT"
] | null | null | null |
// include the Defold SDK
#include <dmsdk/sdk.h>
#define EXTENSION_NAME box2d
#define EXTENSION_NAME_STRING "box2d"
#include <box2d/box2d.h>
#include <utils.h>
#include <extra_utils.h>
#include <world.h>
#include <fixture.h>
#include <body_def.h>
#include <body.h>
#include <joint.h>
#include <draw.h>
#include <joint_def.h>
#include <contact.h>
using namespace box2dDefoldNE;
static int extension_new_world(lua_State *L) {
DM_LUA_STACK_CHECK(L, 1);
utils::check_arg_count(L, 0, 1);
b2Vec2 gravity(0.0f, 0.0f);
if (lua_isuserdata(L, 1)) {
gravity = extra_utils::get_b2vec_safe(L,1, "gravity not vector");
}
World *world = new World(gravity);
world->Push(L);
return 1;
}
static int extension_new_debug_draw(lua_State *L) {
DM_LUA_STACK_CHECK(L, 1);
utils::check_arg_count(L, 1);
Draw* draw = Draw_from_table(L);
draw->Push(L);
return 1;
}
static int b2LinearStiffnessLua(lua_State *L) {
utils::check_arg_count(L, 4);
float frequencyHertz = luaL_checknumber(L,1);
float dampingRatio = luaL_checknumber(L,2);
Body* bodyA = Body_get_userdata_safe(L, 3);
Body* bodyB = Body_get_userdata_safe(L, 4);
float stiffness, damping;
b2LinearStiffness(stiffness, damping, frequencyHertz, dampingRatio, bodyA->body, bodyB->body);
lua_pushnumber(L, stiffness);
lua_pushnumber(L, damping);
return 2;
}
static int b2AngularStiffnessLua(lua_State *L) {
utils::check_arg_count(L, 4);
float frequencyHertz = luaL_checknumber(L,1);
float dampingRatio = luaL_checknumber(L,2);
Body* bodyA = Body_get_userdata_safe(L, 3);
Body* bodyB = Body_get_userdata_safe(L, 4);
float stiffness, damping;
b2AngularStiffness(stiffness, damping, frequencyHertz, dampingRatio, bodyA->body, bodyB->body);
lua_pushnumber(L, stiffness);
lua_pushnumber(L, damping);
return 2;
}
static int InitializeRevoluteJointDef(lua_State *L) {
utils::check_arg_count(L, 3);
b2RevoluteJointDef def;
Body* bodyA = Body_get_userdata_safe(L, 1);
Body* bodyB = Body_get_userdata_safe(L, 2);
b2Vec2 anchor = extra_utils::get_b2vec_safe(L, 3, "anchor not vector");
def.Initialize(bodyA->body,bodyB->body,anchor);
b2JointDef_to_table(L,&def);
return 1;
}
static int InitializePrismaticJointDef(lua_State *L) {
utils::check_arg_count(L, 4);
b2PrismaticJointDef def;
Body* bodyA = Body_get_userdata_safe(L, 1);
Body* bodyB = Body_get_userdata_safe(L, 2);
b2Vec2 anchor = extra_utils::get_b2vec_safe(L, 3, "anchor not vector");
b2Vec2 axis = extra_utils::get_b2vec_safe(L, 4, "axis not vector");
def.Initialize(bodyA->body,bodyB->body,anchor,axis);
b2JointDef_to_table(L,&def);
return 1;
}
static int InitializeDistanceJointDef(lua_State *L) {
utils::check_arg_count(L, 4);
b2DistanceJointDef def;
Body* bodyA = Body_get_userdata_safe(L, 1);
Body* bodyB = Body_get_userdata_safe(L, 2);
b2Vec2 anchorA = extra_utils::get_b2vec_safe(L, 3, "anchorA not vector");
b2Vec2 anchorB = extra_utils::get_b2vec_safe(L, 4, "anchorB not vector");
def.Initialize(bodyA->body,bodyB->body,anchorA,anchorB);
b2JointDef_to_table(L,&def);
return 1;
}
static int InitializePulleyJointDef(lua_State *L) {
utils::check_arg_count(L, 7);
b2PulleyJointDef def;
Body* bodyA = Body_get_userdata_safe(L, 1);
Body* bodyB = Body_get_userdata_safe(L, 2);
b2Vec2 groundAnchorA = extra_utils::get_b2vec_safe(L, 3, "groundAnchorA not vector");
b2Vec2 groundAnchorB = extra_utils::get_b2vec_safe(L, 4, "groundAnchorB not vector");
b2Vec2 anchorA = extra_utils::get_b2vec_safe(L, 5, "anchorA not vector");
b2Vec2 anchorB = extra_utils::get_b2vec_safe(L, 6, "anchorB not vector");
float ratio = luaL_checknumber(L,7);
def.Initialize(bodyA->body,bodyB->body,groundAnchorA,groundAnchorB,anchorA,anchorB,ratio);
b2JointDef_to_table(L,&def);
return 1;
}
static int InitializeMouseJointDef(lua_State *L) {
utils::check_arg_count(L, 2);
b2MouseJointDef def;
def.bodyA = Body_get_userdata_safe(L, 1)->body;
def.bodyB = Body_get_userdata_safe(L, 2)->body;
b2JointDef_to_table(L,&def);
return 1;
}
static int InitializeGearJointDef(lua_State *L) {
utils::check_arg_count(L, 4);
b2GearJointDef def;
def.bodyA = Body_get_userdata_safe(L, 1)->body;
def.bodyB = Body_get_userdata_safe(L, 2)->body;
def.joint1 = Joint_get_userdata_safe(L, 3)->joint;
def.joint2 = Joint_get_userdata_safe(L, 4)->joint;
b2JointDef_to_table(L,&def);
return 1;
}
static int InitializeWheelJointDef(lua_State *L) {
utils::check_arg_count(L, 4);
b2WheelJointDef def;
Body* bodyA = Body_get_userdata_safe(L, 1);
Body* bodyB = Body_get_userdata_safe(L, 2);
b2Vec2 anchor = extra_utils::get_b2vec_safe(L, 3, "anchor not vector");
b2Vec2 axis = extra_utils::get_b2vec_safe(L, 4, "axis not vector");
def.Initialize(bodyA->body,bodyB->body,anchor,axis);
b2JointDef_to_table(L,&def);
return 1;
}
static int InitializeWeldJointDef(lua_State *L) {
utils::check_arg_count(L, 3);
b2WeldJointDef def;
Body* bodyA = Body_get_userdata_safe(L, 1);
Body* bodyB = Body_get_userdata_safe(L, 2);
b2Vec2 anchor = extra_utils::get_b2vec_safe(L, 3, "anchor not vector");
def.Initialize(bodyA->body,bodyB->body,anchor);
b2JointDef_to_table(L,&def);
return 1;
}
static int InitializeFrictionJointDef(lua_State *L) {
utils::check_arg_count(L, 3);
b2FrictionJointDef def;
Body* bodyA = Body_get_userdata_safe(L, 1);
Body* bodyB = Body_get_userdata_safe(L, 2);
b2Vec2 anchor = extra_utils::get_b2vec_safe(L, 3, "anchor not vector");
def.Initialize(bodyA->body,bodyB->body,anchor);
b2JointDef_to_table(L,&def);
return 1;
}
static int InitializeMotorJointDef(lua_State *L) {
utils::check_arg_count(L, 2);
b2MotorJointDef def;
Body* bodyA = Body_get_userdata_safe(L, 1);
Body* bodyB = Body_get_userdata_safe(L, 2);
def.Initialize(bodyA->body,bodyB->body);
b2JointDef_to_table(L,&def);
return 1;
}
static const luaL_reg lua_functions[] = {
{"NewWorld", extension_new_world},
{"NewDebugDraw", extension_new_debug_draw},
{"b2LinearStiffness", b2LinearStiffnessLua},
{"b2AngularStiffness", b2AngularStiffnessLua},
{"InitializeRevoluteJointDef", InitializeRevoluteJointDef},
{"InitializePrismaticJointDef", InitializePrismaticJointDef},
{"InitializeDistanceJointDef", InitializeDistanceJointDef},
{"InitializePulleyJointDef", InitializePulleyJointDef},
{"InitializeMouseJointDef", InitializeMouseJointDef},
{"InitializeGearJointDef", InitializeGearJointDef},
{"InitializeWheelJointDef", InitializeWheelJointDef},
{"InitializeWeldJointDef", InitializeWeldJointDef},
{"InitializeFrictionJointDef", InitializeFrictionJointDef},
{"InitializeMotorJointDef", InitializeMotorJointDef},
{0, 0}
};
dmExtension::Result APP_INITIALIZE(dmExtension::AppParams *params) {
return dmExtension::RESULT_OK;
}
dmExtension::Result APP_FINALIZE(dmExtension::AppParams *params) {
return dmExtension::RESULT_OK;
}
dmExtension::Result INITIALIZE(dmExtension::Params *params) {
dmLogInfo("Box2D NE version %d.%d.%d", b2_version.major, b2_version.minor, b2_version.revision);
lua_State *L = params->m_L;
luaL_register(L, EXTENSION_NAME_STRING, lua_functions);
lua_newtable(L);
lua_pushnumber(L, b2Shape::e_circle);
lua_setfield(L, -2, "e_circle");
lua_pushnumber(L, b2Shape::e_edge);
lua_setfield(L, -2, "e_edge");
lua_pushnumber(L, b2Shape::e_polygon);
lua_setfield(L, -2, "e_polygon");
lua_pushnumber(L, b2Shape::e_chain);
lua_setfield(L, -2, "e_chain");
lua_setfield(L, -2, "b2Shape");
lua_newtable(L);
lua_pushnumber(L, b2BodyType::b2_staticBody);
lua_setfield(L, -2, "b2_staticBody");
lua_pushnumber(L, b2BodyType::b2_kinematicBody);
lua_setfield(L, -2, "b2_kinematicBody");
lua_pushnumber(L, b2BodyType::b2_dynamicBody);
lua_setfield(L, -2, "b2_dynamicBody");
lua_setfield(L, -2, "b2BodyType");
lua_newtable(L);
lua_pushnumber(L, b2JointType::e_unknownJoint);
lua_setfield(L, -2, "e_unknownJoint");
lua_pushnumber(L, b2JointType::e_revoluteJoint);
lua_setfield(L, -2, "e_revoluteJoint");
lua_pushnumber(L, b2JointType::e_prismaticJoint);
lua_setfield(L, -2, "e_prismaticJoint");
lua_pushnumber(L, b2JointType::e_distanceJoint);
lua_setfield(L, -2, "e_distanceJoint");
lua_pushnumber(L, b2JointType::e_pulleyJoint);
lua_setfield(L, -2, "e_pulleyJoint");
lua_pushnumber(L, b2JointType::e_mouseJoint);
lua_setfield(L, -2, "e_mouseJoint");
lua_pushnumber(L, b2JointType::e_gearJoint);
lua_setfield(L, -2, "e_gearJoint");
lua_pushnumber(L, b2JointType::e_wheelJoint);
lua_setfield(L, -2, "e_wheelJoint");
lua_pushnumber(L, b2JointType::e_weldJoint);
lua_setfield(L, -2, "e_weldJoint");
lua_pushnumber(L, b2JointType::e_frictionJoint);
lua_setfield(L, -2, "e_frictionJoint");
lua_pushnumber(L, b2JointType::e_ropeJoint);
lua_setfield(L, -2, "e_ropeJoint");
lua_pushnumber(L, b2JointType::e_motorJoint);
lua_setfield(L, -2, "e_motorJoint");
lua_setfield(L, -2, "b2JointType");
lua_newtable(L);
lua_pushnumber(L, b2Draw::e_shapeBit);
lua_setfield(L, -2, "e_shapeBit");
lua_pushnumber(L, b2Draw::e_jointBit);
lua_setfield(L, -2, "e_jointBit");
lua_pushnumber(L, b2Draw::e_aabbBit);
lua_setfield(L, -2, "e_aabbBit");
lua_pushnumber(L, b2Draw::e_pairBit);
lua_setfield(L, -2, "e_pairBit");
lua_pushnumber(L, b2Draw::e_centerOfMassBit);
lua_setfield(L, -2, "e_centerOfMassBit");
lua_setfield(L, -2, "b2Draw");
lua_newtable(L);
lua_pushnumber(L, b2Manifold::Type::e_circles);
lua_setfield(L, -2, "e_circles");
lua_pushnumber(L, b2Manifold::Type::e_faceA);
lua_setfield(L, -2, "e_faceA");
lua_pushnumber(L, b2Manifold::Type::e_faceB);
lua_setfield(L, -2, "e_faceB");
lua_setfield(L, -2, "b2Manifold_Type");
lua_pop(params->m_L, 1);
WorldInitMetaTable(L);
FixtureInitMetaTable(L);
BodyInitMetaTable(L);
JointInitMetaTable(L);
DrawInitMetaTable(L);
ContactInitMetaTable(L);
return dmExtension::RESULT_OK;
}
dmExtension::Result FINALIZE(dmExtension::Params *params) {
return dmExtension::RESULT_OK;
}
dmExtension::Result UPDATE(dmExtension::Params *params) {
return dmExtension::RESULT_OK;
}
void EXTENSION_ON_EVENT(dmExtension::Params *params, const dmExtension::Event *event) {
switch (event->m_Event) {
case dmExtension::EVENT_ID_ACTIVATEAPP:
break;
case dmExtension::EVENT_ID_DEACTIVATEAPP:
break;
}
}
DM_DECLARE_EXTENSION(EXTENSION_NAME, EXTENSION_NAME_STRING, APP_INITIALIZE, APP_FINALIZE, INITIALIZE, UPDATE, EXTENSION_ON_EVENT, FINALIZE)
| 32.197674
| 139
| 0.701697
|
rgrams
|
606c6f3e7f85beca1aaec88941caccaa06eef880
| 1,120
|
cpp
|
C++
|
aula17092020/Turma.cpp
|
imdcode/imd0030_t02_2020
|
9c08e159752fa3d1169518fcc4a1046c045d7cec
|
[
"MIT"
] | 3
|
2020-09-23T00:59:43.000Z
|
2020-10-06T22:27:00.000Z
|
aula17092020/Turma.cpp
|
imdcode/imd0030_t02_2020
|
9c08e159752fa3d1169518fcc4a1046c045d7cec
|
[
"MIT"
] | null | null | null |
aula17092020/Turma.cpp
|
imdcode/imd0030_t02_2020
|
9c08e159752fa3d1169518fcc4a1046c045d7cec
|
[
"MIT"
] | 4
|
2020-10-05T05:36:25.000Z
|
2020-12-08T02:47:32.000Z
|
#include "turma.hpp"
#include<iostream>
using namespace std;
Turma::Turma (){
this->nome = "A definir";
this->id = "IMD????";
}
Turma::Turma (string nome, string id):nome(nome),id(id){}
Turma::~Turma(){
for (int i = 0; i < this->matriculados; ++i)
{
delete this->alunos[i];
}
}
string
Turma::getNome(){
return this->nome;
}
void
Turma::setNome(string nome){
this->nome = nome;
}
string
Turma::getId(){
return this->id;
}
void
Turma::setId(string id){
this->id = id;
}
int
Turma::getMatriculados(){
return this->matriculados;
}
void
Turma::listarAlunos(){
for (int i = 0; i < this->matriculados; ++i)
{
cout << this->alunos[i]->getNome() << endl;
}
}
void
Turma::addAluno(Aluno* novo){
if (this->matriculados < CAPACIDADE_MAX) {
this->alunos[this->matriculados++] = novo;
}
}
void
Turma::remAluno(string nome){
bool encontrou = false;
for (int i = 0; i < this->matriculados; ++i)
{
if (alunos[i]->getNome() == nome) {
Aluno* tmp = alunos[i];
alunos[i] = alunos[i+1];
alunos[i+1] = tmp;
encontrou = true;
}
}
if (encontrou) {
delete alunos[this->matriculados--];
}
}
| 16.969697
| 57
| 0.61875
|
imdcode
|
606cefe5f1669b3d5f0670349308d3b0c30e7cc9
| 1,119
|
cpp
|
C++
|
shadow/source/DeleteShadowRequest.cpp
|
gregbreen/aws-iot-device-sdk-cpp-v2
|
57ded0046d1cda3b35fbe9298eed308392961435
|
[
"Apache-2.0"
] | 88
|
2019-11-29T19:30:29.000Z
|
2022-03-28T02:29:51.000Z
|
shadow/source/DeleteShadowRequest.cpp
|
gregbreen/aws-iot-device-sdk-cpp-v2
|
57ded0046d1cda3b35fbe9298eed308392961435
|
[
"Apache-2.0"
] | 194
|
2019-12-01T15:54:42.000Z
|
2022-03-31T22:06:11.000Z
|
shadow/source/DeleteShadowRequest.cpp
|
gregbreen/aws-iot-device-sdk-cpp-v2
|
57ded0046d1cda3b35fbe9298eed308392961435
|
[
"Apache-2.0"
] | 64
|
2019-12-17T14:13:40.000Z
|
2022-03-12T07:43:13.000Z
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/iotshadow/DeleteShadowRequest.h>
namespace Aws
{
namespace Iotshadow
{
void DeleteShadowRequest::LoadFromObject(DeleteShadowRequest &val, const Aws::Crt::JsonView &doc)
{
(void)val;
(void)doc;
if (doc.ValueExists("clientToken"))
{
val.ClientToken = doc.GetString("clientToken");
}
}
void DeleteShadowRequest::SerializeToObject(Aws::Crt::JsonObject &object) const
{
(void)object;
if (ClientToken)
{
object.WithString("clientToken", *ClientToken);
}
}
DeleteShadowRequest::DeleteShadowRequest(const Crt::JsonView &doc) { LoadFromObject(*this, doc); }
DeleteShadowRequest &DeleteShadowRequest::operator=(const Crt::JsonView &doc)
{
*this = DeleteShadowRequest(doc);
return *this;
}
} // namespace Iotshadow
} // namespace Aws
| 26.023256
| 106
| 0.578195
|
gregbreen
|
606e095d5c9db8eeaa0ce97f8af023d88969b096
| 11,407
|
cc
|
C++
|
ma/maAdapt.cc
|
Thomas-Ulrich/core
|
1c7bc7ff994c3570ab22b96d37be0c4c993e5940
|
[
"BSD-3-Clause"
] | 138
|
2015-01-05T15:50:20.000Z
|
2022-02-25T01:09:58.000Z
|
ma/maAdapt.cc
|
Thomas-Ulrich/core
|
1c7bc7ff994c3570ab22b96d37be0c4c993e5940
|
[
"BSD-3-Clause"
] | 337
|
2015-08-07T18:24:58.000Z
|
2022-03-31T14:39:03.000Z
|
ma/maAdapt.cc
|
Thomas-Ulrich/core
|
1c7bc7ff994c3570ab22b96d37be0c4c993e5940
|
[
"BSD-3-Clause"
] | 70
|
2015-01-17T00:58:41.000Z
|
2022-02-13T04:58:20.000Z
|
/******************************************************************************
Copyright 2013 Scientific Computation Research Center,
Rensselaer Polytechnic Institute. All rights reserved.
The LICENSE file included with this distribution describes the terms
of the SCOREC Non-Commercial License this program is distributed under.
*******************************************************************************/
#include <PCU.h>
#include <lionPrint.h>
#include "maAdapt.h"
#include "maInput.h"
#include "maTables.h"
#include "maCoarsen.h"
#include "maRefine.h"
#include "maSolutionTransfer.h"
#include "maShape.h"
#include "maShapeHandler.h"
#include "maLayer.h"
#include <apf.h>
#include <cfloat>
#include <pcu_util.h>
#include <stdarg.h>
namespace ma {
Adapt::Adapt(Input* in)
{
input = in;
mesh = in->mesh;
setupFlags(this);
setupQualityCache(this);
deleteCallback = 0;
buildCallback = 0;
sizeField = in->sizeField;
solutionTransfer = in->solutionTransfer;
refine = new Refine(this);
if (in->shapeHandler){
shape = in->shapeHandler(this);
} else
shape = getShapeHandler(this);
if (in->shouldCoarsen)
coarsensLeft = in->maximumIterations;
else
coarsensLeft = 0;
refinesLeft = in->maximumIterations;
resetLayer(this);
if (hasLayer)
checkLayerShape(mesh, "input mesh");
}
Adapt::~Adapt()
{
clearFlags(this);
clearQualityCache(this);
delete refine;
delete shape;
}
void setupFlags(Adapt* a)
{
a->flagsTag = a->mesh->createIntTag("ma_flags",1);
}
void clearFlags(Adapt* a)
{
Mesh* m = a->mesh;
Entity* e;
for (int d=0; d <= 3; ++d)
{
Iterator* it = m->begin(d);
while ((e = m->iterate(it)))
if (m->hasTag(e,a->flagsTag))
m->removeTag(e,a->flagsTag);
m->end(it);
}
m->destroyTag(a->flagsTag);
}
int getFlags(Adapt* a, Entity* e)
{
Mesh* m = a->mesh;
if ( ! m->hasTag(e,a->flagsTag))
return 0; //we assume 0 is the default value for all flags
int flags;
m->getIntTag(e,a->flagsTag,&flags);
return flags;
}
void setFlags(Adapt* a, Entity* e, int flags)
{
a->mesh->setIntTag(e,a->flagsTag,&flags);
}
bool getFlag(Adapt* a, Entity* e, int flag)
{
return flag & getFlags(a,e);
}
void setFlag(Adapt* a, Entity* e, int flag)
{
int flags = getFlags(a,e);
flags |= flag;
setFlags(a,e,flags);
}
void setFlagMatched(Adapt* a, Entity* e, int flag)
{
if (a->mesh->hasMatching()) {
apf::Matches matches;
a->mesh->getMatches(e, matches);
APF_ITERATE(apf::Matches, matches, it) {
PCU_ALWAYS_ASSERT(it->peer == PCU_Comm_Self());
setFlag(a, it->entity, flag);
}
}
setFlag(a, e, flag);
}
void clearFlag(Adapt* a, Entity* e, int flag)
{
int flags = getFlags(a,e);
flags &= ~flag;
setFlags(a,e,flags);
}
void clearFlagMatched(Adapt* a, Entity* e, int flag)
{
if (a->mesh->hasMatching()) {
apf::Matches matches;
a->mesh->getMatches(e, matches);
APF_ITERATE(apf::Matches, matches, it) {
PCU_ALWAYS_ASSERT(it->peer == PCU_Comm_Self());
clearFlag(a, it->entity, flag);
}
}
clearFlag(a, e, flag);
}
void clearFlagFromDimension(Adapt* a, int flag, int dimension)
{
Mesh* m = a->mesh;
Iterator* it = m->begin(dimension);
Entity* e;
while ((e = m->iterate(it)))
clearFlag(a,e,flag);
m->end(it);
}
void setupQualityCache(Adapt* a)
{
a->qualityCache = a->mesh->createDoubleTag("ma_qual_cache",1);
}
void clearQualityCache(Adapt* a)
{
Mesh* m = a->mesh;
Entity* e;
// only faces and regions can have the quality tag
for (int d=2; d <= 3; ++d)
{
Iterator* it = m->begin(d);
while ((e = m->iterate(it)))
if (m->hasTag(e,a->qualityCache))
m->removeTag(e,a->qualityCache);
m->end(it);
}
m->destroyTag(a->qualityCache);
}
double getCachedQuality(Adapt* a, Entity* e)
{
Mesh* m = a->mesh;
int type = m->getType(e);
int ed = apf::Mesh::typeDimension[type];
PCU_ALWAYS_ASSERT(ed == 2 || ed == 3);
if ( ! m->hasTag(e,a->qualityCache))
return 0.0; //we assume 0.0 is the default value for all qualities
double qual;
m->getDoubleTag(e,a->qualityCache,&qual);
return qual;
}
void setCachedQuality(Adapt* a, Entity* e, double q)
{
Mesh* m = a->mesh;
int type = m->getType(e);
int ed = apf::Mesh::typeDimension[type];
PCU_ALWAYS_ASSERT(ed == 2 || ed == 3);
m->setDoubleTag(e,a->qualityCache,&q);
}
void destroyElement(Adapt* a, Entity* e)
{
Mesh* m = a->mesh;
int dim = getDimension(m,e);
if (dim < m->getDimension())
{ //destruction is a no-op if this entity still supports
//higher-order ones
if (m->hasUp(e))
return;
}
Downward down;
int nd = 0;
if (dim > 0)
nd = m->getDownward(e,dim-1,down);
if (a->deleteCallback) a->deleteCallback->call(e);
m->destroy(e);
/* destruction applies recursively to the closure of the entity */
if (dim > 0)
for (int i=0; i < nd; ++i)
destroyElement(a,down[i]);
}
DeleteCallback::DeleteCallback(Adapt* a)
{
this->adapt = a;
a->deleteCallback = this;
}
DeleteCallback::~DeleteCallback()
{
this->adapt->deleteCallback = 0;
}
bool checkFlagConsistency(Adapt* a, int dimension, int flag)
{
Mesh* m = a->mesh;
apf::Sharing* sh = apf::getSharing(m);
PCU_Comm_Begin();
Entity* e;
Iterator* it = m->begin(dimension);
while ((e = m->iterate(it))) {
apf::CopyArray others;
sh->getCopies(e, others);
if (!others.getSize())
continue;
bool value = getFlag(a, e, flag);
APF_ITERATE(apf::CopyArray, others, rit) {
PCU_COMM_PACK(rit->peer, rit->entity);
PCU_COMM_PACK(rit->peer, value);
}
}
m->end(it);
PCU_Comm_Send();
bool ok = true;
while (PCU_Comm_Receive()) {
PCU_COMM_UNPACK(e);
bool value;
PCU_COMM_UNPACK(value);
if(value != getFlag(a,e,flag))
ok = false;
}
delete sh;
return ok;
}
double getDistance(Adapt* a, Entity* v[2])
{
return (getPosition(a->mesh,v[1]) - getPosition(a->mesh,v[0])).getLength();
}
double getDistance(Adapt* a, Entity* v0, Entity* v1)
{
Entity* v[2] = {v0,v1};
return getDistance(a,v);
}
int getClosestPair(Adapt* a, Entity* (*pairs)[2], int n)
{
double min = DBL_MAX;
double distance;
int min_i = -1;
for (int i=0; i < n; ++i)
if ((distance = getDistance(a,pairs[i])) < min)
{
min = distance;
min_i = i;
}
return min_i;
}
/* marks entities of a dimension for which the predicate
returns true with the true flag, and uses the false
flag to prevent duplicate checks of the same entity.
Per the workings of an ma::Operator, it expects the
true flag to be cleared from all entities, so it
always re-evaluates those entities.
returns the total global number of marked entities,
counting shared entities once.
*/
long markEntities(
Adapt* a,
int dimension,
Predicate& predicate,
int trueFlag,
int setFalseFlag,
int allFalseFlags)
{
if (!allFalseFlags) allFalseFlags = setFalseFlag;
Entity* e;
long count = 0;
Mesh* m = a->mesh;
Iterator* it = m->begin(dimension);
while ((e = m->iterate(it)))
{
PCU_ALWAYS_ASSERT( ! getFlag(a,e,trueFlag));
/* this skip conditional is powerful: it affords us a
3X speedup of the entire adaptation in some cases */
if (allFalseFlags & getFlags(a,e))
continue;
if (predicate(e))
{
setFlag(a,e,trueFlag);
if (a->mesh->isOwned(e))
++count;
}
else
setFlag(a,e,setFalseFlag);
}
m->end(it);
return PCU_Add_Long(count);
}
void NewEntities::reset()
{
entities.clear();
}
void NewEntities::addEntity(Entity* e)
{
entities.push_back(e);
}
void NewEntities::call(Entity* e)
{
addEntity(e);
}
void NewEntities::retrieve(EntityArray& a)
{
a.setSize(entities.size());
for (size_t i=0; i < entities.size(); ++i)
a[i] = entities[i];
}
Cavity::Cavity()
{
shouldTransfer = false;
shouldFit = false;
adapter = 0;
solutionTransfer = 0;
shape = 0;
shouldTransferSizeField = false;
}
void Cavity::init(Adapt* a)
{
adapter = a;
solutionTransfer = a->solutionTransfer;
shape = a->shape;
Mesh* m = a->mesh;
shouldTransfer = false;
shouldFit = false;
for (int d=1; d <= m->getDimension(); ++d) {
if (solutionTransfer->hasNodesOn(d))
shouldTransfer = true;
if (shape->hasNodesOn(d))
shouldFit = true;
if (adapter->sizeField->hasNodesOn(d))
shouldTransferSizeField = true;
}
}
void Cavity::beforeBuilding()
{
if (shouldTransfer || shouldFit)
{
newEntities.reset();
setBuildCallback(adapter,&newEntities);
}
}
void Cavity::afterBuilding()
{
if (shouldTransfer || shouldFit)
clearBuildCallback(adapter);
}
void Cavity::beforeTrying()
{
if (shouldFit)
{
newEntities.reset();
setBuildCallback(adapter,&newEntities);
}
}
void Cavity::afterTrying()
{
if (shouldFit)
clearBuildCallback(adapter);
}
void Cavity::transfer(EntityArray& oldElements)
{
if (shouldTransfer)
{
EntityArray a;
newEntities.retrieve(a);
solutionTransfer->onCavity(oldElements,a);
}
if (shouldTransferSizeField)
{
EntityArray a;
newEntities.retrieve(a);
adapter->sizeField->onCavity(oldElements,a);
}
}
void Cavity::fit(EntityArray& oldElements)
{
if (shouldFit)
{
EntityArray a;
newEntities.retrieve(a);
shape->onCavity(oldElements,a);
}
}
Entity* buildVertex(
Adapt* a,
Model* c,
Vector const& point,
Vector const& param)
{
Entity* v = a->mesh->createVertex(c,point,param);
if (a->buildCallback)
a->buildCallback->call(v);
return v;
}
Entity* buildElement(
Adapt* a,
Model* c,
int type,
Entity** verts)
{
return apf::buildElement(a->mesh,c,type,verts,a->buildCallback);
}
Entity* rebuildElement(
Adapt* a,
Entity* original,
Entity* oldVert,
Entity* newVert)
{
return rebuildElement(a->mesh,original,oldVert,newVert,a->buildCallback);
}
void setBuildCallback(Adapt* a, apf::BuildCallback* cb)
{
PCU_ALWAYS_ASSERT(a->buildCallback==0);
a->buildCallback = cb;
}
void clearBuildCallback(Adapt* a)
{
a->buildCallback = 0;
}
void print(const char* format, ...)
{
if (PCU_Comm_Self())
return;
lion_oprint(1,"\nMeshAdapt: ");
va_list ap;
va_start(ap,format);
lion_voprint(1,format,ap);
va_end(ap);
lion_oprint(1,"\n");
}
void setFlagOnClosure(Adapt* a, Entity* element, int flag)
{
Mesh* m = a->mesh;
int D = getDimension(m,element);
for (int d=0; d <= D; ++d)
{
Downward down;
int nd = m->getDownward(element,d,down);
for (int i=0; i < nd; ++i)
setFlag(a,down[i],flag);
}
}
void syncFlag(Adapt* a, int dimension, int flag)
{
Mesh* m = a->mesh;
apf::Sharing* sh = apf::getSharing(m);
PCU_Comm_Begin();
Entity* e;
Iterator* it = m->begin(dimension);
while ((e = m->iterate(it))) {
if (!getFlag(a, e, flag))
continue;
apf::CopyArray others;
sh->getCopies(e, others);
APF_ITERATE(apf::CopyArray, others, rit)
PCU_COMM_PACK(rit->peer, rit->entity);
}
m->end(it);
PCU_Comm_Send();
while (PCU_Comm_Receive()) {
PCU_COMM_UNPACK(e);
setFlag(a,e,flag);
}
delete sh;
}
HasTag::HasTag(Mesh* m, Tag* t)
{
mesh = m;
tag = t;
}
bool HasTag::operator()(Entity* e)
{
return mesh->hasTag(e, tag);
}
HasFlag::HasFlag(Adapt* a, int f)
{
adapter = a;
flag = f;
}
bool HasFlag::operator()(Entity* e)
{
return getFlag(adapter, e, flag);
}
}
| 20.891941
| 80
| 0.628912
|
Thomas-Ulrich
|
606eb35a624944ad107dc4270b9f2edd05008cff
| 900
|
hpp
|
C++
|
include/boost/scope_guard/detail/unwrap_decay.hpp
|
gimesketvirtadieni/boost.scope_guard
|
c7fe05429350b55fdb0521fb13ee6ad28a4f5e1b
|
[
"BSL-1.0"
] | null | null | null |
include/boost/scope_guard/detail/unwrap_decay.hpp
|
gimesketvirtadieni/boost.scope_guard
|
c7fe05429350b55fdb0521fb13ee6ad28a4f5e1b
|
[
"BSL-1.0"
] | null | null | null |
include/boost/scope_guard/detail/unwrap_decay.hpp
|
gimesketvirtadieni/boost.scope_guard
|
c7fe05429350b55fdb0521fb13ee6ad28a4f5e1b
|
[
"BSL-1.0"
] | null | null | null |
// Copyright Yuri Kilochek 2018.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_SCOPE_GUARD_DETAIL_UNWRAP_DECAY_HPP
#define BOOST_SCOPE_GUARD_DETAIL_UNWRAP_DECAY_HPP
#include <tuple>
#include <utility>
#ifndef SCOPE_GUARD_STANDALONE
namespace boost::detail::scope_guard {
#else
namespace util::detail::scope_guard {
#endif
///////////////////////////////////////////////////////////////////////////////
template <typename T>
struct unwrap_decay
: std::tuple_element<0, decltype(std::make_tuple(std::declval<T>()))>
{};
template <typename T>
using unwrap_decay_t = typename unwrap_decay<T>::type;
///////////////////////////////////////////////////////////////////////////////
} // boost::detail::scope_guard
#endif
| 27.272727
| 79
| 0.592222
|
gimesketvirtadieni
|
607035db70221be823ec43b2da7f00f9b1c843a5
| 28,286
|
cpp
|
C++
|
src/cint3c2e.cpp
|
Hendiadyoin1/libcxxint
|
5cb6fd421ed93f707854c203f9f949f73cdea86f
|
[
"BSD-2-Clause"
] | null | null | null |
src/cint3c2e.cpp
|
Hendiadyoin1/libcxxint
|
5cb6fd421ed93f707854c203f9f949f73cdea86f
|
[
"BSD-2-Clause"
] | null | null | null |
src/cint3c2e.cpp
|
Hendiadyoin1/libcxxint
|
5cb6fd421ed93f707854c203f9f949f73cdea86f
|
[
"BSD-2-Clause"
] | null | null | null |
/*
* Copyright (C) 2013- Qiming Sun <osirpt.sun@gmail.com>
*
* 3-center 2-electron integrals
*/
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "cint_bas.hpp"
#include "optimizer.hpp"
#include "g2e.hpp"
#include "cint2e.hpp"
#include "misc.hpp"
#include "cart2sph.hpp"
#include "c2f.hpp"
#define PRIM2CTR0(ctrsymb, gp, ngp) \
if (ctrsymb##_ctr > 1) {\
if (*ctrsymb##empty) { \
CINTprim_to_ctr_0(gctr##ctrsymb, gp, c##ctrsymb+ctrsymb##p, \
ngp, ctrsymb##_prim, ctrsymb##_ctr, \
non0ctr##ctrsymb[ctrsymb##p], \
non0idx##ctrsymb+ctrsymb##p*ctrsymb##_ctr); \
} else { \
CINTprim_to_ctr_1(gctr##ctrsymb, gp, c##ctrsymb+ctrsymb##p, \
ngp, ctrsymb##_prim, ctrsymb##_ctr, \
non0ctr##ctrsymb[ctrsymb##p], \
non0idx##ctrsymb+ctrsymb##p*ctrsymb##_ctr); \
} \
} \
*ctrsymb##empty = 0
int CINT3c2e_loop_nopt(double *gctr, CINTEnvVars *envs)
{
int *shls = envs->shls;
int *bas = envs->bas;
double *env = envs->env;
int i_sh = shls[0];
int j_sh = shls[1];
int k_sh = shls[2];
int i_ctr = envs->x_ctr[0];
int j_ctr = envs->x_ctr[1];
int k_ctr = envs->x_ctr[2];
int i_prim = bas(NPRIM_OF, i_sh);
int j_prim = bas(NPRIM_OF, j_sh);
int k_prim = bas(NPRIM_OF, k_sh);
//double *ri = envs->ri;
//double *rj = envs->rj;
double *ai = env + bas(PTR_EXP, i_sh);
double *aj = env + bas(PTR_EXP, j_sh);
double *ak = env + bas(PTR_EXP, k_sh);
double *ci = env + bas(PTR_COEFF, i_sh);
double *cj = env + bas(PTR_COEFF, j_sh);
double *ck = env + bas(PTR_COEFF, k_sh);
double expcutoff = envs->expcutoff;
double *log_maxci, *log_maxcj;
PairData *pdata_base, *pdata_ij;
log_maxci = new double[i_prim+j_prim];
pdata_base = new PairData[i_prim*j_prim];
log_maxcj = log_maxci + i_prim;
CINTOpt_log_max_pgto_coeff(log_maxci, ci, i_prim, i_ctr);
CINTOpt_log_max_pgto_coeff(log_maxcj, cj, j_prim, j_ctr);
if (CINTset_pairdata(pdata_base, ai, aj, envs->ri, envs->rj,
log_maxci, log_maxcj, envs->li_ceil, envs->lj_ceil,
i_prim, j_prim, SQUARE(envs->rirj), expcutoff)) {
return 0;
}
int n_comp = envs->ncomp_e1 * envs->ncomp_tensor;
double fac1i, fac1j, fac1k;
int ip, jp, kp;
int empty[4] = {1, 1, 1, 1};
int *iempty = empty + 0;
int *jempty = empty + 1;
int *kempty = empty + 2;
int *gempty = empty + 3;
/* COMMON_ENVS_AND_DECLARE end */
double expij;
double *rij;
//const double dist_ij = SQUARE(envs->rirj);
int *idx = new int[envs->nf * 3];
CINTg2e_index_xyz(idx, envs);
int *non0ctri, *non0ctrj, *non0ctrk;
int *non0idxi, *non0idxj, *non0idxk;
non0ctri = new int[i_prim+j_prim+k_prim+i_prim*i_ctr+j_prim*j_ctr+k_prim*k_ctr];
non0ctrj = non0ctri + i_prim;
non0ctrk = non0ctrj + j_prim;
non0idxi = non0ctrk + k_prim;
non0idxj = non0idxi + i_prim*i_ctr;
non0idxk = non0idxj + j_prim*j_ctr;
CINTOpt_non0coeff_byshell(non0idxi, non0ctri, ci, i_prim, i_ctr);
CINTOpt_non0coeff_byshell(non0idxj, non0ctrj, cj, j_prim, j_ctr);
CINTOpt_non0coeff_byshell(non0idxk, non0ctrk, ck, k_prim, k_ctr);
const int nc = i_ctr * j_ctr * k_ctr;
// (irys,i,j,k,l,coord,0:1); +1 for nabla-r12
const int leng = envs->g_size * 3 * ((1<<envs->gbits)+1);
const int lenk = envs->nf * nc * n_comp; // gctrk
const int lenj = envs->nf * i_ctr * j_ctr * n_comp; // gctrj
const int leni = envs->nf * i_ctr * n_comp; // gctri
const int len0 = envs->nf * n_comp; // gout
const int len = leng + lenk + lenj + leni + len0;
double *g = new double[len]; // must be allocated last in this function
double *g1 = g + leng;
double *gout, *gctri, *gctrj, *gctrk;
if (n_comp == 1) {
gctrk = gctr;
} else {
gctrk = g1;
g1 += lenk;
}
if (k_ctr == 1) {
gctrj = gctrk;
jempty = kempty;
} else {
gctrj = g1;
g1 += lenj;
}
if (j_ctr == 1) {
gctri = gctrj;
iempty = jempty;
} else {
gctri = g1;
g1 += leni;
}
if (i_ctr == 1) {
gout = gctri;
gempty = iempty;
} else {
gout = g1;
}
*kempty = 1;
for (kp = 0; kp < k_prim; kp++) {
envs->ak = ak[kp];
envs->akl = ak[kp];
if (k_ctr == 1) {
fac1k = envs->common_factor * ck[kp];
} else {
fac1k = envs->common_factor;
*jempty = 1;
}
pdata_ij = pdata_base;
for (jp = 0; jp < j_prim; jp++) {
envs->aj = aj[jp];
if (j_ctr == 1) {
fac1j = fac1k * cj[jp];
} else {
fac1j = fac1k;
*iempty = 1;
}
for (ip = 0; ip < i_prim; ip++, pdata_ij++) {
if (pdata_ij->cceij > expcutoff) {
goto i_contracted;
}
envs->ai = ai[ip];
envs->aij = ai[ip] + aj[jp];
expij = pdata_ij->eij;
rij = pdata_ij->rij;
envs->rij[0] = rij[0];
envs->rij[1] = rij[1];
envs->rij[2] = rij[2];
envs->rijrx[0] = rij[0] - envs->rx_in_rijrx[0];
envs->rijrx[1] = rij[1] - envs->rx_in_rijrx[1];
envs->rijrx[2] = rij[2] - envs->rx_in_rijrx[2];
if (i_ctr == 1) {
fac1i = fac1j*ci[ip]*expij;
} else {
fac1i = fac1j*expij;
}
if ((*envs->f_g0_2e)(g, fac1i, envs)) {
(*envs->f_gout)(gout, g, idx, envs, *gempty);
PRIM2CTR0(i, gout, envs->nf*n_comp);
}
i_contracted: ;
} // end loop i_prim
if (!*iempty) {
PRIM2CTR0(j, gctri, envs->nf*i_ctr*n_comp);
}
} // end loop j_prim
if (!*jempty) {
PRIM2CTR0(k, gctrj, envs->nf*i_ctr*j_ctr*n_comp);
}
} // end loop k_prim
if (n_comp > 1 && !*kempty) {
CINTdmat_transpose(gctr, gctrk, envs->nf*nc, n_comp);
}
return !*kempty;
}
#define COMMON_ENVS_AND_DECLARE \
int *shls = envs->shls; \
int *bas = envs->bas; \
double *env = envs->env; \
int i_sh = shls[0]; \
int j_sh = shls[1]; \
if (opt->pairdata != NULL && \
opt->pairdata[i_sh*opt->nbas+j_sh] == NOVALUE) { \
return 0; \
} \
int k_sh = shls[2]; \
int i_ctr = envs->x_ctr[0]; \
int j_ctr = envs->x_ctr[1]; \
int k_ctr = envs->x_ctr[2]; \
int i_prim = bas(NPRIM_OF, i_sh); \
int j_prim = bas(NPRIM_OF, j_sh); \
int k_prim = bas(NPRIM_OF, k_sh); \
double *ai = env + bas(PTR_EXP, i_sh); \
double *aj = env + bas(PTR_EXP, j_sh); \
double *ak = env + bas(PTR_EXP, k_sh); \
double *ci = env + bas(PTR_COEFF, i_sh); \
double *cj = env + bas(PTR_COEFF, j_sh); \
double *ck = env + bas(PTR_COEFF, k_sh); \
double expcutoff = envs->expcutoff; \
PairData *pdata_base, *pdata_ij; \
if (opt->pairdata != NULL) { \
pdata_base = opt->pairdata[i_sh*opt->nbas+j_sh]; \
} else { \
double *log_maxci = opt->log_max_coeff[i_sh]; \
double *log_maxcj = opt->log_max_coeff[j_sh]; \
pdata_base = new PairData[i_prim*j_prim]; \
if (CINTset_pairdata(pdata_base, ai, aj, envs->ri, envs->rj, \
log_maxci, log_maxcj, envs->li_ceil, envs->lj_ceil, \
i_prim, j_prim, SQUARE(envs->rirj), expcutoff)) { \
return 0; \
} \
} \
int n_comp = envs->ncomp_e1 * envs->ncomp_tensor; \
double fac1i, fac1j, fac1k; \
int ip, jp, kp; \
int empty[4] = {1, 1, 1, 1}; \
int *iempty = empty + 0; \
int *jempty = empty + 1; \
int *kempty = empty + 2; \
int *gempty = empty + 3; \
int *non0ctri = opt->non0ctr[i_sh]; \
int *non0ctrj = opt->non0ctr[j_sh]; \
int *non0idxi = opt->sortedidx[i_sh]; \
int *non0idxj = opt->sortedidx[j_sh]; \
int *non0ctrk, *non0idxk; \
non0ctrk = new int[k_prim+k_prim*k_ctr]; \
non0idxk = non0ctrk + k_prim; \
CINTOpt_non0coeff_byshell(non0idxk, non0ctrk, ck, k_prim, k_ctr); \
double expij; \
double *rij; \
int *idx = opt->index_xyz_array[envs->i_l*LMAX1*LMAX1 \
+envs->j_l*LMAX1+envs->k_l]; \
if (idx == NULL) { \
idx = new int[envs->nf * 3]; \
CINTg2e_index_xyz(idx, envs); \
}
#define SET_RIJ \
if (pdata_ij->cceij > expcutoff) { \
goto i_contracted; \
} \
envs->ai = ai[ip]; \
envs->aij = ai[ip] + aj[jp]; \
expij = pdata_ij->eij; \
rij = pdata_ij->rij; \
envs->rij[0] = rij[0]; \
envs->rij[1] = rij[1]; \
envs->rij[2] = rij[2]; \
envs->rijrx[0] = rij[0] - envs->rx_in_rijrx[0]; \
envs->rijrx[1] = rij[1] - envs->rx_in_rijrx[1]; \
envs->rijrx[2] = rij[2] - envs->rx_in_rijrx[2]
#define PRIM2CTR(ctrsymb, gp, ngp) \
if (ctrsymb##_ctr > 1) {\
if (*ctrsymb##empty) { \
CINTprim_to_ctr_0(gctr##ctrsymb, gp, c##ctrsymb+ctrsymb##p, \
ngp, ctrsymb##_prim, ctrsymb##_ctr, \
non0ctr##ctrsymb[ctrsymb##p], \
non0idx##ctrsymb+ctrsymb##p*ctrsymb##_ctr); \
} else { \
CINTprim_to_ctr_1(gctr##ctrsymb, gp, c##ctrsymb+ctrsymb##p, \
ngp, ctrsymb##_prim, ctrsymb##_ctr, \
non0ctr##ctrsymb[ctrsymb##p], \
non0idx##ctrsymb+ctrsymb##p*ctrsymb##_ctr); \
} \
} \
*ctrsymb##empty = 0
// i_ctr = j_ctr = k_ctr = 1;
int CINT3c2e_111_loop(double *gctr, CINTEnvVars *envs, const CINTOpt *opt)
{
COMMON_ENVS_AND_DECLARE;
const int nc = 1;
const int leng = envs->g_size * 3 * ((1<<envs->gbits)+1);
const int len0 = envs->nf * n_comp;
const int len = leng + len0;
double *g = new double[len];
double *gout;
if (n_comp == 1) {
gout = gctr;
} else {
gout = g + leng;
}
for (kp = 0; kp < k_prim; kp++) {
envs->ak = ak[kp];
envs->akl = ak[kp];
fac1k = envs->common_factor * ck[kp];
pdata_ij = pdata_base;
for (jp = 0; jp < j_prim; jp++) {
envs->aj = aj[jp];
fac1j = fac1k * cj[jp];
for (ip = 0; ip < i_prim; ip++, pdata_ij++) {
SET_RIJ;
fac1i = fac1j*ci[ip]*expij;
if ((*envs->f_g0_2e)(g, fac1i, envs)) {
(*envs->f_gout)(gout, g, idx, envs, *empty);
*empty = 0;
}
i_contracted: ;
} // end loop i_prim
} // end loop j_prim
} // end loop k_prim
if (n_comp > 1 && !*empty) {
CINTdmat_transpose(gctr, gout, envs->nf*nc, n_comp);
}
return !*empty;
}
// i_ctr = n; j_ctr = k_ctr = 1;
int CINT3c2e_n11_loop(double *gctr, CINTEnvVars *envs, const CINTOpt *opt)
{
COMMON_ENVS_AND_DECLARE;
const int nc = i_ctr;
const int leng = envs->g_size * 3 * ((1<<envs->gbits)+1);
const int leni = envs->nf * i_ctr * n_comp; // gctri
const int len0 = envs->nf * n_comp; // gout
const int len = leng + leni + len0;
double *g = new double[len];
double *g1 = g + leng;
double *gout, *gctri;
if (n_comp == 1) {
gctri = gctr;
} else {
gctri = g1;
g1 += leni;
}
gout = g1;
for (kp = 0; kp < k_prim; kp++) {
envs->ak = ak[kp];
envs->akl = ak[kp];
fac1k = envs->common_factor * ck[kp];
pdata_ij = pdata_base;
for (jp = 0; jp < j_prim; jp++) {
envs->aj = aj[jp];
fac1j = fac1k * cj[jp];
for (ip = 0; ip < i_prim; ip++, pdata_ij++) {
SET_RIJ;
fac1i = fac1j*expij;
if ((*envs->f_g0_2e)(g, fac1i, envs)) {
(*envs->f_gout)(gout, g, idx, envs, 1);
PRIM2CTR(i, gout,envs->nf*n_comp);
}
i_contracted: ;
} // end loop i_prim
} // end loop j_prim
} // end loop k_prim
if (n_comp > 1 && !*iempty) {
CINTdmat_transpose(gctr, gctri, envs->nf*nc, n_comp);
}
return !*iempty;
}
// j_ctr = n; i_ctr = k_ctr = 1;
int CINT3c2e_1n1_loop(double *gctr, CINTEnvVars *envs, const CINTOpt *opt)
{
COMMON_ENVS_AND_DECLARE;
const int nc = j_ctr;
const int leng = envs->g_size * 3 * ((1<<envs->gbits)+1);
const int lenj = envs->nf * j_ctr * n_comp; // gctrj
const int len0 = envs->nf * n_comp; // gout
const int len = leng + lenj + len0;
double *g = new double[len];
double *g1 = g + leng;
double *gout, *gctrj;
if (n_comp == 1) {
gctrj = gctr;
} else {
gctrj = g1;
g1 += lenj;
}
gout = g1;
for (kp = 0; kp < k_prim; kp++) {
envs->ak = ak[kp];
envs->akl = ak[kp];
fac1k = envs->common_factor * ck[kp];
pdata_ij = pdata_base;
for (jp = 0; jp < j_prim; jp++) {
envs->aj = aj[jp];
fac1j = fac1k;
*iempty = 1;
for (ip = 0; ip < i_prim; ip++, pdata_ij++) {
SET_RIJ;
fac1i = fac1j*ci[ip]*expij;
if ((*envs->f_g0_2e)(g, fac1i, envs)) {
(*envs->f_gout)(gout, g, idx, envs, *iempty);
*iempty = 0;
}
i_contracted: ;
} // end loop i_prim
if (!*iempty) {
PRIM2CTR(j, gout,envs->nf*n_comp);
}
} // end loop j_prim
} // end loop k_prim
if (n_comp > 1 && !*jempty) {
CINTdmat_transpose(gctr, gctrj, envs->nf*nc, n_comp);
}
return !*jempty;
}
int CINT3c2e_loop(double *gctr, CINTEnvVars *envs, const CINTOpt *opt)
{
COMMON_ENVS_AND_DECLARE;
const int nc = i_ctr * j_ctr * k_ctr;
// (irys,i,j,k,coord,0:1); +1 for nabla-r12
const int leng = envs->g_size * 3 * ((1<<envs->gbits)+1);
const int lenk = envs->nf * nc * n_comp; // gctrk
const int lenj = envs->nf * i_ctr * j_ctr * n_comp; // gctrj
const int leni = envs->nf * i_ctr * n_comp; // gctri
const int len0 = envs->nf * n_comp; // gout
const int len = leng + lenk + lenj + leni + len0;
double *g = new double[len];
double *g1 = g + leng;
double *gout, *gctri, *gctrj, *gctrk;
if (n_comp == 1) {
gctrk = gctr;
} else {
gctrk = g1;
g1 += lenk;
}
if (k_ctr == 1) {
gctrj = gctrk;
jempty = kempty;
} else {
gctrj = g1;
g1 += lenj;
}
if (j_ctr == 1) {
gctri = gctrj;
iempty = jempty;
} else {
gctri = g1;
g1 += leni;
}
if (i_ctr == 1) {
gout = gctri;
gempty = iempty;
} else {
gout = g1;
}
*kempty = 1;
for (kp = 0; kp < k_prim; kp++) {
envs->ak = ak[kp];
envs->akl = ak[kp];
if (k_ctr == 1) {
fac1k = envs->common_factor * ck[kp];
} else {
fac1k = envs->common_factor;
*jempty = 1;
}
pdata_ij = pdata_base;
for (jp = 0; jp < j_prim; jp++) {
envs->aj = aj[jp];
if (j_ctr == 1) {
fac1j = fac1k * cj[jp];
} else {
fac1j = fac1k;
*iempty = 1;
}
for (ip = 0; ip < i_prim; ip++, pdata_ij++) {
SET_RIJ;
if (i_ctr == 1) {
fac1i = fac1j*ci[ip]*expij;
} else {
fac1i = fac1j*expij;
}
if ((*envs->f_g0_2e)(g, fac1i, envs)) {
(*envs->f_gout)(gout, g, idx, envs, *gempty);
PRIM2CTR(i, gout, envs->nf*n_comp);
}
i_contracted: ;
} // end loop i_prim
if (!*iempty) {
PRIM2CTR(j, gctri, envs->nf*i_ctr*n_comp);
}
} // end loop j_prim
if (!*jempty) {
PRIM2CTR0(k, gctrj, envs->nf*i_ctr*j_ctr*n_comp);
}
} // end loop k_prim
if (n_comp > 1 && !*kempty) {
CINTdmat_transpose(gctr, gctrk, envs->nf*nc, n_comp);
}
return !*kempty;
}
static int (*CINTf_3c2e_loop[8])(double *gctr, CINTEnvVars *envs, const CINTOpt *opt) = {
CINT3c2e_loop,
CINT3c2e_loop,
CINT3c2e_loop,
CINT3c2e_n11_loop,
CINT3c2e_loop,
CINT3c2e_1n1_loop,
CINT3c2e_loop,
CINT3c2e_111_loop,
};
#define PAIRDATA_NON0IDX_SIZE(ps) \
int *bas = envs->bas; \
int *shls = envs->shls; \
int i_prim = bas(NPRIM_OF, shls[0]); \
int j_prim = bas(NPRIM_OF, shls[1]); \
int k_prim = bas(NPRIM_OF, shls[2]); \
int ps = (i_prim*j_prim * 5 \
+ i_prim * x_ctr[0] \
+ j_prim * x_ctr[1] \
+ k_prim * x_ctr[2] \
+(i_prim+j_prim)*2 + k_prim + envs->nf*3);
int CINT3c2e_cart_drv(double *out, int *dims, CINTEnvVars *envs, CINTOpt *opt)
{
int *x_ctr = envs->x_ctr;
int nc = envs->nf * x_ctr[0] * x_ctr[1] * x_ctr[2];
int n_comp = envs->ncomp_e1 * envs->ncomp_tensor;
double *gctr = new double[nc*n_comp];
int n;
int has_value;
if (opt != NULL) {
n = ((envs->x_ctr[0]==1) << 2) + ((envs->x_ctr[1]==1) << 1) + (envs->x_ctr[2]==1);
has_value = CINTf_3c2e_loop[n](gctr, envs, opt);
} else {
has_value = CINT3c2e_loop_nopt(gctr, envs);
}
int counts[4];
counts[0] = envs->nfi * x_ctr[0];
counts[1] = envs->nfj * x_ctr[1];
counts[2] = envs->nfk * x_ctr[2];
counts[3] = 1;
if (dims == NULL) {
dims = counts;
}
int nout = dims[0] * dims[1] * dims[2];
if (has_value) {
for (n = 0; n < n_comp; n++) {
c2s_cart_3c2e1(out+nout*n, gctr+nc*n, dims, envs);
}
} else {
for (n = 0; n < n_comp; n++) {
c2s_dset0(out+nout*n, dims, counts);
}
}
return has_value;
}
int CINT3c2e_spheric_drv(double *out, int *dims, CINTEnvVars *envs, CINTOpt *opt,
void (*f_e1_c2s)(double *bufijk, double *gctr, int *dims,
CINTEnvVars *envs), int is_ssc)
{
int *x_ctr = envs->x_ctr;
int nc = envs->nf * x_ctr[0] * x_ctr[1] * x_ctr[2];
int n_comp = envs->ncomp_e1 * envs->ncomp_tensor;
double *gctr = new double[nc*n_comp];
int n;
int has_value;
if (opt != NULL) {
n = ((envs->x_ctr[0]==1) << 2) + ((envs->x_ctr[1]==1) << 1) + (envs->x_ctr[2]==1);
has_value = CINTf_3c2e_loop[n](gctr, envs, opt);
} else {
has_value = CINT3c2e_loop_nopt(gctr, envs);
}
int counts[4];
counts[0] = (envs->i_l*2+1) * x_ctr[0];
counts[1] = (envs->j_l*2+1) * x_ctr[1];
if (is_ssc) {
counts[2] = envs->nfk * x_ctr[2];
} else {
counts[2] = (envs->k_l*2+1) * x_ctr[2];
}
counts[3] = 1;
if (dims == NULL) {
dims = counts;
}
int nout = dims[0] * dims[1] * dims[2];
if (has_value) {
for (n = 0; n < n_comp; n++) {
(*f_e1_c2s)(out+nout*n, gctr+nc*n, dims, envs);
}
} else {
for (n = 0; n < n_comp; n++) {
c2s_dset0(out+nout*n, dims, counts);
}
}
return has_value;
}
int CINT3c2e_spinor_drv(std::complex<double> *out, int *dims, CINTEnvVars *envs, CINTOpt *opt,
void (*f_e1_c2s)(std::complex<double> *opijk, double *gctr, int *dims,
CINTEnvVars *envs), int is_ssc)
{
int *x_ctr = envs->x_ctr;
int counts[4];
counts[0] = CINTcgto_spinor(envs->shls[0], envs->bas);
counts[1] = CINTcgto_spinor(envs->shls[1], envs->bas);
if (is_ssc) {
counts[2] = envs->nfk * x_ctr[2];
} else {
counts[2] = (envs->k_l*2+1) * x_ctr[2];
}
counts[3] = 1;
int nc = envs->nf * x_ctr[0] * x_ctr[1] * x_ctr[2];
int n_comp = envs->ncomp_e1 * envs->ncomp_e2 * envs->ncomp_tensor;
double *gctr = new double[nc*n_comp];
int n;
int has_value;
if (opt != NULL) {
n = ((envs->x_ctr[0]==1) << 2) + ((envs->x_ctr[1]==1) << 1) + (envs->x_ctr[2]==1);
has_value = CINTf_3c2e_loop[n](gctr, envs, opt);
} else {
has_value = CINT3c2e_loop_nopt(gctr, envs);
}
if (dims == NULL) {
dims = counts;
}
int nout = dims[0] * dims[1] * dims[2];
if (has_value) {
for (n = 0; n < envs->ncomp_e2 * envs->ncomp_tensor; n++) {
(*f_e1_c2s)(out+nout*n, gctr, dims, envs);
gctr += nc * envs->ncomp_e1;
}
} else {
for (n = 0; n < envs->ncomp_e2 * envs->ncomp_tensor; n++) {
c2s_zset0(out+nout*n, dims, counts);
}
}
return has_value;
}
int int3c2e_sph(double *out, int *dims, int *shls, int *atm, int natm,
int *bas, int nbas, double *env, CINTOpt *opt)
{
int ng[] = {0, 0, 0, 0, 0, 1, 1, 1};
CINTEnvVars envs;
CINTinit_int3c2e_EnvVars(&envs, ng, shls, atm, natm, bas, nbas, env);
envs.f_gout = &CINTgout2e;
return CINT3c2e_spheric_drv(out, dims, &envs, opt, &c2s_sph_3c2e1, 0);
}
void int3c2e_optimizer(CINTOpt **opt, int *atm, int natm,
int *bas, int nbas, double *env)
{
int ng[] = {0, 0, 0, 0, 0, 1, 1, 1};
CINTall_3c2e_optimizer(opt, ng, atm, natm, bas, nbas, env);
}
int int3c2e_cart(double *out, int *dims, int *shls, int *atm, int natm,
int *bas, int nbas, double *env, CINTOpt *opt)
{
int ng[] = {0, 0, 0, 0, 0, 1, 1, 1};
CINTEnvVars envs;
CINTinit_int3c2e_EnvVars(&envs, ng, shls, atm, natm, bas, nbas, env);
envs.f_gout = &CINTgout2e;
return CINT3c2e_cart_drv(out, dims, &envs, opt);
}
int int3c2e_spinor(std::complex<double> *out, int *dims, int *shls, int *atm, int natm,
int *bas, int nbas, double *env, CINTOpt *opt)
{
int ng[] = {0, 0, 0, 0, 0, 1, 1, 1};
CINTEnvVars envs;
CINTinit_int3c2e_EnvVars(&envs, ng, shls, atm, natm, bas, nbas, env);
envs.f_gout = &CINTgout2e;
return CINT3c2e_spinor_drv(out, dims, &envs, opt, &c2s_sf_3c2e1, 0);
}
int int3c2e_sph_ssc(double *out, int *dims, int *shls, int *atm, int natm,
int *bas, int nbas, double *env, CINTOpt *opt)
{
int ng[] = {0, 0, 0, 0, 0, 1, 1, 1};
CINTEnvVars envs;
CINTinit_int3c2e_EnvVars(&envs, ng, shls, atm, natm, bas, nbas, env);
envs.f_gout = &CINTgout2e;
return CINT3c2e_spheric_drv(out, dims, &envs, opt, &c2s_sph_3c2e1_ssc, 1);
}
int int3c2e_spinor_ssc(std::complex<double> *out, int *dims, int *shls, int *atm, int natm,
int *bas, int nbas, double *env, CINTOpt *opt)
{
int ng[] = {0, 0, 0, 0, 0, 1, 1, 1};
CINTEnvVars envs;
CINTinit_int3c2e_EnvVars(&envs, ng, shls, atm, natm, bas, nbas, env);
envs.f_gout = &CINTgout2e;
return CINT3c2e_spinor_drv(out, dims, &envs, opt, &c2s_sf_3c2e1_ssc, 1);
}
void CINTgout2e_int3c2e_spsp1(double *g,
double *gout, int *idx, CINTEnvVars *envs, int gout_empty);
int int3c2e_spsp1_spinor_ssc(std::complex<double> *out, int *dims, int *shls, int *atm, int natm,
int *bas, int nbas, double *env, CINTOpt *opt)
{
int ng[] = {1, 1, 0, 0, 2, 4, 1, 1};
CINTEnvVars envs;
CINTinit_int3c2e_EnvVars(&envs, ng, shls, atm, natm, bas, nbas, env);
envs.f_gout = &CINTgout2e_int3c2e_spsp1;
return CINT3c2e_spinor_drv(out, dims, &envs, opt, &c2s_si_3c2e1_ssc, 1);
}
void int3c2e_ssc_optimizer(CINTOpt **opt, int *atm, int natm,
int *bas, int nbas, double *env)
{
int3c2e_ssc_optimizer(opt, atm, natm, bas, nbas, env);
}
ALL_CINT(int3c2e)
ALL_CINT_FORTRAN_(int3c2e)
| 37.464901
| 98
| 0.438662
|
Hendiadyoin1
|
60717acb32b8598890da5fdff1fc80434296afe5
| 2,705
|
cpp
|
C++
|
Source/component_systems/textheader_system.cpp
|
gummikana/CardCreator
|
9a141ccd9e76a3e49d8fc42cc8deaffed3d3eb39
|
[
"MIT"
] | null | null | null |
Source/component_systems/textheader_system.cpp
|
gummikana/CardCreator
|
9a141ccd9e76a3e49d8fc42cc8deaffed3d3eb39
|
[
"MIT"
] | null | null | null |
Source/component_systems/textheader_system.cpp
|
gummikana/CardCreator
|
9a141ccd9e76a3e49d8fc42cc8deaffed3d3eb39
|
[
"MIT"
] | null | null | null |
#include "textheader_system.h"
#include "../global_data.h"
#include <game_utils/font/cfont.h>
#include <utils/filesystem/filesystem.h>
#include "../misc_utils/font_creator.h"
std::string MakeSureFontExists( const std::string& ttf_file, int size )
{
std::string font_name = ceng::GetFilenameWithoutExtension( ttf_file );
if( size <= 0 ) size = 16;
font_name = "data/fonts/" + font_name + "_" + ceng::CastToString( size );
std::string texture_filename = font_name + ".png";
std::string xml_filename = font_name + ".xml";
if( ceng::DoesExist( texture_filename ) == false ||
ceng::DoesExist( xml_filename ) == false )
{
CreateFont( ttf_file, (float)size, xml_filename, texture_filename );
}
return xml_filename;
}
TextHeaderSystem::TextHeaderSystem( SGF::EventManager* eventManager, SGF::EntityManager* entityManager ) :
ComponentUpdator( eventManager, entityManager )
{
}
void TextHeaderSystem::RefreshComponent( SGF::Entity* e, TextHeaderComponent* comp )
{
as::Sprite* mSpriteContainer = GD.mSprite;
std::string font_file = comp->font_file;
if( ceng::GetFileExtension( font_file ) == "ttf" )
font_file = MakeSureFontExists( comp->font_file, comp->font_size );
std::string text = comp->default_text;
if( GD.isCrafting == false )
text = GD.GetData( comp->key_name );
if( ( comp->mSprite == NULL && font_file.empty() == false ) ||
( comp->mSprite && comp->mSprite->GetText() != text ) ||
( comp->mSprite && comp->mSprite->GetFont()->GetFilename() != font_file ) )
{
if( comp->mSprite )
delete comp->mSprite;
else
comp->AddAutoDelete( comp->mSprite );
comp->mSprite = as::LoadTextSprite( font_file );
comp->mSprite->SetName( ceng::CastToString( e->GetID() ) );
comp->mSprite->SetText( text );
/*comp->mSprite->SetCenterOffset( types::vector2( comp->offset_x, comp->offset_y ) );
comp->mSprite->SetZ( comp->z_index );*/
if( mSpriteContainer )
{
// if( comp->z_index == -1 )
mSpriteContainer->addChild( comp->mSprite );
/*else
mSpriteContainer->addChildAt( comp->mSprite, comp->mSprite->GetZ() );*/
}
}
}
void TextHeaderSystem::UpdateComponent( SGF::Entity* e, TextHeaderComponent* comp )
{
// Initialize if it doesn't exist
if( comp->mSprite == NULL || GD.isCrafting == false )
RefreshComponent( e, comp );
// set the transform
if( comp->mSprite )
{
comp->mSprite->SetScaleX( comp->scale_x );
comp->mSprite->SetScaleY( comp->scale_y );
comp->mSprite->SetRotation( comp->rotation );
comp->mSprite->MoveTo( types::vector2( comp->pos_x, comp->pos_y ) );
// set alpha every frame
comp->mSprite->SetAlpha( comp->alpha );
comp->mSprite->SetColor( comp->color_r, comp->color_g, comp->color_b );
}
}
| 29.086022
| 106
| 0.68207
|
gummikana
|
60735d73a2d38c7dd575e06d49d1c2b25d020988
| 14,446
|
hpp
|
C++
|
src/libtriton/includes/triton/exceptions.hpp
|
patacca/Triton
|
e5b6e089efba6bac0731d9abb306351b150ab872
|
[
"Apache-2.0"
] | 2,337
|
2015-06-03T10:26:30.000Z
|
2022-03-30T02:42:26.000Z
|
src/libtriton/includes/triton/exceptions.hpp
|
patacca/Triton
|
e5b6e089efba6bac0731d9abb306351b150ab872
|
[
"Apache-2.0"
] | 914
|
2015-06-03T10:56:48.000Z
|
2022-03-30T11:11:40.000Z
|
src/libtriton/includes/triton/exceptions.hpp
|
patacca/Triton
|
e5b6e089efba6bac0731d9abb306351b150ab872
|
[
"Apache-2.0"
] | 521
|
2015-06-03T10:41:15.000Z
|
2022-03-26T15:45:08.000Z
|
//! \file
/*
** Copyright (C) - Triton
**
** This program is under the terms of the Apache License 2.0.
*/
#ifndef TRITON_EXCEPTIONS_H
#define TRITON_EXCEPTIONS_H
#include <exception>
#include <string>
#include <triton/dllexport.hpp>
#include <triton/tritonTypes.hpp>
//! The Triton namespace
namespace triton {
/*!
* \addtogroup triton
* @{
*/
//! The Exceptions namespace
namespace exceptions {
/*!
* \ingroup triton
* \addtogroup exceptions
* @{
*/
/*! \class Exception
* \brief The root class of all exceptions. */
class Exception : public std::exception {
protected:
//! Defines the exception message.
std::string message;
public:
//! Constructor.
TRITON_EXPORT Exception(const char* message) {
this->message = std::string(message);
};
//! Constructor.
TRITON_EXPORT Exception(const std::string& message) {
this->message = message;
};
//! Destructor.
TRITON_EXPORT virtual ~Exception() throw() {
};
//! Returns the exception message.
TRITON_EXPORT const char* what() const throw () {
return this->message.c_str();
};
};
/*! \class Engines
* \brief The exception class used by all engines. */
class Engines : public triton::exceptions::Exception {
public:
//! Constructor.
TRITON_EXPORT Engines(const char* message) : triton::exceptions::Exception(message) {};
//! Constructor.
TRITON_EXPORT Engines(const std::string& message) : triton::exceptions::Exception(message) {};
};
/*! \class SymbolicEngine
* \brief The exception class used by the symbolic engine. */
class SymbolicEngine : public triton::exceptions::Engines {
public:
//! Constructor.
TRITON_EXPORT SymbolicEngine(const char* message) : triton::exceptions::Engines(message) {};
//! Constructor.
TRITON_EXPORT SymbolicEngine(const std::string& message) : triton::exceptions::Engines(message) {};
};
/*! \class SymbolicExpression
* \brief The exception class used by symbolic expressions. */
class SymbolicExpression : public triton::exceptions::SymbolicEngine {
public:
//! Constructor.
TRITON_EXPORT SymbolicExpression(const char* message) : triton::exceptions::SymbolicEngine(message) {};
//! Constructor.
TRITON_EXPORT SymbolicExpression(const std::string& message) : triton::exceptions::SymbolicEngine(message) {};
};
/*! \class SymbolicSimplification
* \brief The exception class used by symbolic simplifications. */
class SymbolicSimplification : public triton::exceptions::SymbolicEngine {
public:
//! Constructor.
TRITON_EXPORT SymbolicSimplification(const char* message) : triton::exceptions::SymbolicEngine(message) {};
//! Constructor.
TRITON_EXPORT SymbolicSimplification(const std::string& message) : triton::exceptions::SymbolicEngine(message) {};
};
/*! \class SymbolicVariable
* \brief The exception class used by symbolic variables. */
class SymbolicVariable : public triton::exceptions::SymbolicEngine {
public:
//! Constructor.
TRITON_EXPORT SymbolicVariable(const char* message) : triton::exceptions::SymbolicEngine(message) {};
//! Constructor.
TRITON_EXPORT SymbolicVariable(const std::string& message) : triton::exceptions::SymbolicEngine(message) {};
};
/*! \class PathConstraint
* \brief The exception class used by path constraints. */
class PathConstraint : public triton::exceptions::SymbolicEngine {
public:
//! Constructor.
TRITON_EXPORT PathConstraint(const char* message) : triton::exceptions::SymbolicEngine(message) {};
//! Constructor.
TRITON_EXPORT PathConstraint(const std::string& message) : triton::exceptions::SymbolicEngine(message) {};
};
/*! \class PathManager
* \brief The exception class used by the path manager. */
class PathManager : public triton::exceptions::SymbolicEngine {
public:
//! Constructor.
TRITON_EXPORT PathManager(const char* message) : triton::exceptions::SymbolicEngine(message) {};
//! Constructor.
TRITON_EXPORT PathManager(const std::string& message) : triton::exceptions::SymbolicEngine(message) {};
};
/*! \class TaintEngine
* \brief The exception class used by the taint engine. */
class TaintEngine : public triton::exceptions::Engines {
public:
//! Constructor.
TRITON_EXPORT TaintEngine(const char* message) : triton::exceptions::Engines(message) {};
//! Constructor.
TRITON_EXPORT TaintEngine(const std::string& message) : triton::exceptions::Engines(message) {};
};
/*! \class SolverEngine
* \brief The exception class used by the solver engine. */
class SolverEngine : public triton::exceptions::Engines {
public:
//! Constructor.
TRITON_EXPORT SolverEngine(const char* message) : triton::exceptions::Engines(message) {};
//! Constructor.
TRITON_EXPORT SolverEngine(const std::string& message) : triton::exceptions::Engines(message) {};
};
/*! \class SolverModel
* \brief The exception class used by solver models. */
class SolverModel : public triton::exceptions::SolverEngine {
public:
//! Constructor.
TRITON_EXPORT SolverModel(const char* message) : triton::exceptions::SolverEngine(message) {};
//! Constructor.
TRITON_EXPORT SolverModel(const std::string& message) : triton::exceptions::SolverEngine(message) {};
};
/*! \class API
* \brief The exception class used by the Triton's API. */
class API : public triton::exceptions::Exception {
public:
//! Constructor.
TRITON_EXPORT API(const char* message) : triton::exceptions::Exception(message) {};
//! Constructor.
TRITON_EXPORT API(const std::string& message) : triton::exceptions::Exception(message) {};
};
/*! \class Architecture
* \brief The exception class used by architectures. */
class Architecture : public triton::exceptions::Exception {
public:
//! Constructor.
TRITON_EXPORT Architecture(const char* message) : triton::exceptions::Exception(message) {};
//! Constructor.
TRITON_EXPORT Architecture(const std::string& message) : triton::exceptions::Exception(message) {};
};
/*! \class BitsVector
* \brief The exception class used by bitvectors. */
class BitsVector : public triton::exceptions::Architecture {
public:
//! Constructor.
TRITON_EXPORT BitsVector(const char* message) : triton::exceptions::Architecture(message) {};
//! Constructor.
TRITON_EXPORT BitsVector(const std::string& message) : triton::exceptions::Architecture(message) {};
};
/*! \class Immediate
* \brief The exception class used by immediates. */
class Immediate : public triton::exceptions::Architecture {
public:
//! Constructor.
TRITON_EXPORT Immediate(const char* message) : triton::exceptions::Architecture(message) {};
//! Constructor.
TRITON_EXPORT Immediate(const std::string& message) : triton::exceptions::Architecture(message) {};
};
/*! \class Register
* \brief The exception class used by register operands. */
class Register : public triton::exceptions::Architecture {
public:
//! Constructor.
TRITON_EXPORT Register(const char* message) : triton::exceptions::Architecture(message) {};
//! Constructor.
TRITON_EXPORT Register(const std::string& message) : triton::exceptions::Architecture(message) {};
};
/*! \class MemoryAccess
* \brief The exception class used by memory access. */
class MemoryAccess : public triton::exceptions::Architecture {
public:
//! Constructor.
TRITON_EXPORT MemoryAccess(const char* message) : triton::exceptions::Architecture(message) {};
//! Constructor.
TRITON_EXPORT MemoryAccess(const std::string& message) : triton::exceptions::Architecture(message) {};
};
/*! \class OperandWrapper
* \brief The exception class used by operand wrappers. */
class OperandWrapper : public triton::exceptions::Architecture {
public:
//! Constructor.
TRITON_EXPORT OperandWrapper(const char* message) : triton::exceptions::Architecture(message) {};
//! Constructor.
TRITON_EXPORT OperandWrapper(const std::string& message) : triton::exceptions::Architecture(message) {};
};
/*! \class Instruction
* \brief The exception class used by an instruction. */
class Instruction : public triton::exceptions::Architecture {
public:
//! Constructor.
TRITON_EXPORT Instruction(const char* message) : triton::exceptions::Architecture(message) {};
//! Constructor.
TRITON_EXPORT Instruction(const std::string& message) : triton::exceptions::Architecture(message) {};
};
/*! \class Cpu
* \brief The exception class used by all CPUs. */
class Cpu : public triton::exceptions::Architecture {
public:
//! Constructor.
TRITON_EXPORT Cpu(const char* message) : triton::exceptions::Architecture(message) {};
//! Constructor.
TRITON_EXPORT Cpu(const std::string& message) : triton::exceptions::Architecture(message) {};
};
/*! \class ArmOperandProperties
* \brief The exception class used by shift mode. */
class ArmOperandProperties : public triton::exceptions::Architecture {
public:
//! Constructor.
TRITON_EXPORT ArmOperandProperties(const char* message) : triton::exceptions::Architecture(message) {};
//! Constructor.
TRITON_EXPORT ArmOperandProperties(const std::string& message) : triton::exceptions::Architecture(message) {};
};
/*! \class AArch64OperandProperties
* \brief The exception class used by shift mode. */
class AArch64OperandProperties : public triton::exceptions::Architecture {
public:
//! Constructor.
TRITON_EXPORT AArch64OperandProperties(const char* message) : triton::exceptions::Architecture(message) {};
//! Constructor.
TRITON_EXPORT AArch64OperandProperties(const std::string& message) : triton::exceptions::Architecture(message) {};
};
/*! \class IrBuilder
* \brief The exception class used by the IR builder. */
class IrBuilder : public triton::exceptions::Architecture {
public:
//! Constructor.
TRITON_EXPORT IrBuilder(const char* message) : triton::exceptions::Architecture(message) {};
//! Constructor.
TRITON_EXPORT IrBuilder(const std::string& message) : triton::exceptions::Architecture(message) {};
};
/*! \class Disassembly
* \brief The exception class used by the disassembler. */
class Disassembly : public triton::exceptions::Cpu {
public:
//! Constructor.
TRITON_EXPORT Disassembly(const char* message) : triton::exceptions::Cpu(message) {};
//! Constructor.
TRITON_EXPORT Disassembly(const std::string& message) : triton::exceptions::Cpu(message) {};
};
/*! \class Semantics
* \brief The exception class used by all semantics. */
class Semantics : public triton::exceptions::Cpu {
public:
//! Constructor.
TRITON_EXPORT Semantics(const char* message) : triton::exceptions::Cpu(message) {};
//! Constructor.
TRITON_EXPORT Semantics(const std::string& message) : triton::exceptions::Cpu(message) {};
};
/*! \class Ast
* \brief The exception class used by all AST nodes. */
class Ast : public triton::exceptions::Exception {
public:
//! Constructor.
TRITON_EXPORT Ast(const char* message) : triton::exceptions::Exception(message) {};
//! Constructor.
TRITON_EXPORT Ast(const std::string& message) : triton::exceptions::Exception(message) {};
};
/*! \class AstRepresentation
* \brief The exception class used by all AST node representations. */
class AstRepresentation : public triton::exceptions::Ast {
public:
//! Constructor.
TRITON_EXPORT AstRepresentation(const char* message) : triton::exceptions::Ast(message) {};
//! Constructor.
TRITON_EXPORT AstRepresentation(const std::string& message) : triton::exceptions::Ast(message) {};
};
/*! \class AstTranslations
* \brief The exception class used by all AST translations (`z3 <-> triton`). */
class AstTranslations : public triton::exceptions::Ast {
public:
//! Constructor.
TRITON_EXPORT AstTranslations(const char* message) : triton::exceptions::Ast(message) {};
//! Constructor.
TRITON_EXPORT AstTranslations(const std::string& message) : triton::exceptions::Ast(message) {};
};
/*! \class Bindings
* \brief The exception class used by bindings. */
class Bindings : public triton::exceptions::Exception {
public:
//! Constructor.
TRITON_EXPORT Bindings(const char* message) : triton::exceptions::Exception(message) {};
//! Constructor.
TRITON_EXPORT Bindings(const std::string& message) : triton::exceptions::Exception(message) {};
};
/*! \class Callbacks
* \brief The exception class used by callbacks. */
class Callbacks : public triton::exceptions::Exception {
public:
//! Constructor.
TRITON_EXPORT Callbacks(const char* message) : triton::exceptions::Exception(message) {};
//! Constructor.
TRITON_EXPORT Callbacks(const std::string& message) : triton::exceptions::Exception(message) {};
};
/*! \class Callbacks
* \brief The exception class used by python callbacks. */
class PyCallbacks : public triton::exceptions::Exception {
public:
//! Constructor.
TRITON_EXPORT PyCallbacks() : triton::exceptions::Exception("exception info is stored in python state") {};
};
/*! @} End of exceptions namespace */
};
/*! @} End of exceptions namespace */
};
#endif /* TRITON_EXCEPTIONS_HPP */
| 34.070755
| 122
| 0.648069
|
patacca
|
6073c4fdbc240d0ac293714d558bafdb13ddd89d
| 320,752
|
cc
|
C++
|
third/libyuv/source/row_gcc.cc
|
onbings/bofstd
|
366ff7f7d8871d5fa5785d5690d90506a7714ecc
|
[
"MIT"
] | null | null | null |
third/libyuv/source/row_gcc.cc
|
onbings/bofstd
|
366ff7f7d8871d5fa5785d5690d90506a7714ecc
|
[
"MIT"
] | 1
|
2021-03-20T14:46:54.000Z
|
2021-03-20T14:47:10.000Z
|
third/libyuv/source/row_gcc.cc
|
onbings/bofstd
|
366ff7f7d8871d5fa5785d5690d90506a7714ecc
|
[
"MIT"
] | null | null | null |
/*
* Copyright 2011 The LibYuv Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "libyuv/row.h"
#ifdef __cplusplus
namespace libyuv {
extern "C" {
#endif
// This module is for GCC x86 and x64.
#if !defined(LIBYUV_DISABLE_X86) && \
(defined(__x86_64__) || (defined(__i386__) && !defined(_MSC_VER)))
#if defined(HAS_ARGBTOYROW_SSSE3) || defined(HAS_ARGBGRAYROW_SSSE3)
// Constants for ARGB
static const uvec8 kARGBToY = {25u, 129u, 66u, 0u, 25u, 129u, 66u, 0u,
25u, 129u, 66u, 0u, 25u, 129u, 66u, 0u};
// JPeg full range.
static const uvec8 kARGBToYJ = {29u, 150u, 77u, 0u, 29u, 150u, 77u, 0u,
29u, 150u, 77u, 0u, 29u, 150u, 77u, 0u};
static const uvec8 kRGBAToYJ = {0u, 29u, 150u, 77u, 0u, 29u, 150u, 77u,
0u, 29u, 150u, 77u, 0u, 29u, 150u, 77u};
#endif // defined(HAS_ARGBTOYROW_SSSE3) || defined(HAS_ARGBGRAYROW_SSSE3)
#if defined(HAS_ARGBTOYROW_SSSE3) || defined(HAS_I422TOARGBROW_SSSE3)
static const vec8 kARGBToU = {112, -74, -38, 0, 112, -74, -38, 0,
112, -74, -38, 0, 112, -74, -38, 0};
static const vec8 kARGBToUJ = {127, -84, -43, 0, 127, -84, -43, 0,
127, -84, -43, 0, 127, -84, -43, 0};
static const vec8 kARGBToV = {-18, -94, 112, 0, -18, -94, 112, 0,
-18, -94, 112, 0, -18, -94, 112, 0};
static const vec8 kARGBToVJ = {-20, -107, 127, 0, -20, -107, 127, 0,
-20, -107, 127, 0, -20, -107, 127, 0};
// Constants for BGRA
static const uvec8 kBGRAToY = {0u, 66u, 129u, 25u, 0u, 66u, 129u, 25u,
0u, 66u, 129u, 25u, 0u, 66u, 129u, 25u};
static const vec8 kBGRAToU = {0, -38, -74, 112, 0, -38, -74, 112,
0, -38, -74, 112, 0, -38, -74, 112};
static const vec8 kBGRAToV = {0, 112, -94, -18, 0, 112, -94, -18,
0, 112, -94, -18, 0, 112, -94, -18};
// Constants for ABGR
static const uvec8 kABGRToY = {66u, 129u, 25u, 0u, 66u, 129u, 25u, 0u,
66u, 129u, 25u, 0u, 66u, 129u, 25u, 0u};
static const vec8 kABGRToU = {-38, -74, 112, 0, -38, -74, 112, 0,
-38, -74, 112, 0, -38, -74, 112, 0};
static const vec8 kABGRToV = {112, -94, -18, 0, 112, -94, -18, 0,
112, -94, -18, 0, 112, -94, -18, 0};
// Constants for RGBA.
static const uvec8 kRGBAToY = {0u, 25u, 129u, 66u, 0u, 25u, 129u, 66u,
0u, 25u, 129u, 66u, 0u, 25u, 129u, 66u};
static const vec8 kRGBAToU = {0, 112, -74, -38, 0, 112, -74, -38,
0, 112, -74, -38, 0, 112, -74, -38};
static const vec8 kRGBAToV = {0, -18, -94, 112, 0, -18, -94, 112,
0, -18, -94, 112, 0, -18, -94, 112};
static const uvec16 kAddY16 = {0x7e80u, 0x7e80u, 0x7e80u, 0x7e80u,
0x7e80u, 0x7e80u, 0x7e80u, 0x7e80u};
static const uvec8 kAddUV128 = {128u, 128u, 128u, 128u, 128u, 128u, 128u, 128u,
128u, 128u, 128u, 128u, 128u, 128u, 128u, 128u};
static const uvec16 kSub128 = {0x8080u, 0x8080u, 0x8080u, 0x8080u,
0x8080u, 0x8080u, 0x8080u, 0x8080u};
#endif // defined(HAS_ARGBTOYROW_SSSE3) || defined(HAS_I422TOARGBROW_SSSE3)
#ifdef HAS_RGB24TOARGBROW_SSSE3
// Shuffle table for converting RGB24 to ARGB.
static const uvec8 kShuffleMaskRGB24ToARGB = {
0u, 1u, 2u, 12u, 3u, 4u, 5u, 13u, 6u, 7u, 8u, 14u, 9u, 10u, 11u, 15u};
// Shuffle table for converting RAW to ARGB.
static const uvec8 kShuffleMaskRAWToARGB = {2u, 1u, 0u, 12u, 5u, 4u, 3u, 13u,
8u, 7u, 6u, 14u, 11u, 10u, 9u, 15u};
// Shuffle table for converting RAW to RGBA.
static const uvec8 kShuffleMaskRAWToRGBA = {12u, 2u, 1u, 0u, 13u, 5u, 4u, 3u,
14u, 8u, 7u, 6u, 15u, 11u, 10u, 9u};
// Shuffle table for converting RAW to RGB24. First 8.
static const uvec8 kShuffleMaskRAWToRGB24_0 = {
2u, 1u, 0u, 5u, 4u, 3u, 8u, 7u,
128u, 128u, 128u, 128u, 128u, 128u, 128u, 128u};
// Shuffle table for converting RAW to RGB24. Middle 8.
static const uvec8 kShuffleMaskRAWToRGB24_1 = {
2u, 7u, 6u, 5u, 10u, 9u, 8u, 13u,
128u, 128u, 128u, 128u, 128u, 128u, 128u, 128u};
// Shuffle table for converting RAW to RGB24. Last 8.
static const uvec8 kShuffleMaskRAWToRGB24_2 = {
8u, 7u, 12u, 11u, 10u, 15u, 14u, 13u,
128u, 128u, 128u, 128u, 128u, 128u, 128u, 128u};
// Shuffle table for converting ARGB to RGB24.
static const uvec8 kShuffleMaskARGBToRGB24 = {
0u, 1u, 2u, 4u, 5u, 6u, 8u, 9u, 10u, 12u, 13u, 14u, 128u, 128u, 128u, 128u};
// Shuffle table for converting ARGB to RAW.
static const uvec8 kShuffleMaskARGBToRAW = {
2u, 1u, 0u, 6u, 5u, 4u, 10u, 9u, 8u, 14u, 13u, 12u, 128u, 128u, 128u, 128u};
// Shuffle table for converting ARGBToRGB24 for I422ToRGB24. First 8 + next 4
static const uvec8 kShuffleMaskARGBToRGB24_0 = {
0u, 1u, 2u, 4u, 5u, 6u, 8u, 9u, 128u, 128u, 128u, 128u, 10u, 12u, 13u, 14u};
// YUY2 shuf 16 Y to 32 Y.
static const lvec8 kShuffleYUY2Y = {0, 0, 2, 2, 4, 4, 6, 6, 8, 8, 10,
10, 12, 12, 14, 14, 0, 0, 2, 2, 4, 4,
6, 6, 8, 8, 10, 10, 12, 12, 14, 14};
// YUY2 shuf 8 UV to 16 UV.
static const lvec8 kShuffleYUY2UV = {1, 3, 1, 3, 5, 7, 5, 7, 9, 11, 9,
11, 13, 15, 13, 15, 1, 3, 1, 3, 5, 7,
5, 7, 9, 11, 9, 11, 13, 15, 13, 15};
// UYVY shuf 16 Y to 32 Y.
static const lvec8 kShuffleUYVYY = {1, 1, 3, 3, 5, 5, 7, 7, 9, 9, 11,
11, 13, 13, 15, 15, 1, 1, 3, 3, 5, 5,
7, 7, 9, 9, 11, 11, 13, 13, 15, 15};
// UYVY shuf 8 UV to 16 UV.
static const lvec8 kShuffleUYVYUV = {0, 2, 0, 2, 4, 6, 4, 6, 8, 10, 8,
10, 12, 14, 12, 14, 0, 2, 0, 2, 4, 6,
4, 6, 8, 10, 8, 10, 12, 14, 12, 14};
// NV21 shuf 8 VU to 16 UV.
static const lvec8 kShuffleNV21 = {
1, 0, 1, 0, 3, 2, 3, 2, 5, 4, 5, 4, 7, 6, 7, 6,
1, 0, 1, 0, 3, 2, 3, 2, 5, 4, 5, 4, 7, 6, 7, 6,
};
#endif // HAS_RGB24TOARGBROW_SSSE3
#ifdef HAS_J400TOARGBROW_SSE2
void J400ToARGBRow_SSE2(const uint8_t* src_y, uint8_t* dst_argb, int width) {
asm volatile(
"pcmpeqb %%xmm5,%%xmm5 \n"
"pslld $0x18,%%xmm5 \n"
LABELALIGN
"1: \n"
"movq (%0),%%xmm0 \n"
"lea 0x8(%0),%0 \n"
"punpcklbw %%xmm0,%%xmm0 \n"
"movdqa %%xmm0,%%xmm1 \n"
"punpcklwd %%xmm0,%%xmm0 \n"
"punpckhwd %%xmm1,%%xmm1 \n"
"por %%xmm5,%%xmm0 \n"
"por %%xmm5,%%xmm1 \n"
"movdqu %%xmm0,(%1) \n"
"movdqu %%xmm1,0x10(%1) \n"
"lea 0x20(%1),%1 \n"
"sub $0x8,%2 \n"
"jg 1b \n"
: "+r"(src_y), // %0
"+r"(dst_argb), // %1
"+r"(width) // %2
::"memory",
"cc", "xmm0", "xmm1", "xmm5");
}
#endif // HAS_J400TOARGBROW_SSE2
#ifdef HAS_RGB24TOARGBROW_SSSE3
void RGB24ToARGBRow_SSSE3(const uint8_t* src_rgb24,
uint8_t* dst_argb,
int width) {
asm volatile(
"pcmpeqb %%xmm5,%%xmm5 \n" // 0xff000000
"pslld $0x18,%%xmm5 \n"
"movdqa %3,%%xmm4 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"movdqu 0x20(%0),%%xmm3 \n"
"lea 0x30(%0),%0 \n"
"movdqa %%xmm3,%%xmm2 \n"
"palignr $0x8,%%xmm1,%%xmm2 \n"
"pshufb %%xmm4,%%xmm2 \n"
"por %%xmm5,%%xmm2 \n"
"palignr $0xc,%%xmm0,%%xmm1 \n"
"pshufb %%xmm4,%%xmm0 \n"
"movdqu %%xmm2,0x20(%1) \n"
"por %%xmm5,%%xmm0 \n"
"pshufb %%xmm4,%%xmm1 \n"
"movdqu %%xmm0,(%1) \n"
"por %%xmm5,%%xmm1 \n"
"palignr $0x4,%%xmm3,%%xmm3 \n"
"pshufb %%xmm4,%%xmm3 \n"
"movdqu %%xmm1,0x10(%1) \n"
"por %%xmm5,%%xmm3 \n"
"movdqu %%xmm3,0x30(%1) \n"
"lea 0x40(%1),%1 \n"
"sub $0x10,%2 \n"
"jg 1b \n"
: "+r"(src_rgb24), // %0
"+r"(dst_argb), // %1
"+r"(width) // %2
: "m"(kShuffleMaskRGB24ToARGB) // %3
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5");
}
void RAWToARGBRow_SSSE3(const uint8_t* src_raw, uint8_t* dst_argb, int width) {
asm volatile(
"pcmpeqb %%xmm5,%%xmm5 \n" // 0xff000000
"pslld $0x18,%%xmm5 \n"
"movdqa %3,%%xmm4 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"movdqu 0x20(%0),%%xmm3 \n"
"lea 0x30(%0),%0 \n"
"movdqa %%xmm3,%%xmm2 \n"
"palignr $0x8,%%xmm1,%%xmm2 \n"
"pshufb %%xmm4,%%xmm2 \n"
"por %%xmm5,%%xmm2 \n"
"palignr $0xc,%%xmm0,%%xmm1 \n"
"pshufb %%xmm4,%%xmm0 \n"
"movdqu %%xmm2,0x20(%1) \n"
"por %%xmm5,%%xmm0 \n"
"pshufb %%xmm4,%%xmm1 \n"
"movdqu %%xmm0,(%1) \n"
"por %%xmm5,%%xmm1 \n"
"palignr $0x4,%%xmm3,%%xmm3 \n"
"pshufb %%xmm4,%%xmm3 \n"
"movdqu %%xmm1,0x10(%1) \n"
"por %%xmm5,%%xmm3 \n"
"movdqu %%xmm3,0x30(%1) \n"
"lea 0x40(%1),%1 \n"
"sub $0x10,%2 \n"
"jg 1b \n"
: "+r"(src_raw), // %0
"+r"(dst_argb), // %1
"+r"(width) // %2
: "m"(kShuffleMaskRAWToARGB) // %3
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5");
}
// Same code as RAWToARGB with different shuffler and A in low bits
void RAWToRGBARow_SSSE3(const uint8_t* src_raw, uint8_t* dst_rgba, int width) {
asm volatile(
"pcmpeqb %%xmm5,%%xmm5 \n" // 0x000000ff
"psrld $0x18,%%xmm5 \n"
"movdqa %3,%%xmm4 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"movdqu 0x20(%0),%%xmm3 \n"
"lea 0x30(%0),%0 \n"
"movdqa %%xmm3,%%xmm2 \n"
"palignr $0x8,%%xmm1,%%xmm2 \n"
"pshufb %%xmm4,%%xmm2 \n"
"por %%xmm5,%%xmm2 \n"
"palignr $0xc,%%xmm0,%%xmm1 \n"
"pshufb %%xmm4,%%xmm0 \n"
"movdqu %%xmm2,0x20(%1) \n"
"por %%xmm5,%%xmm0 \n"
"pshufb %%xmm4,%%xmm1 \n"
"movdqu %%xmm0,(%1) \n"
"por %%xmm5,%%xmm1 \n"
"palignr $0x4,%%xmm3,%%xmm3 \n"
"pshufb %%xmm4,%%xmm3 \n"
"movdqu %%xmm1,0x10(%1) \n"
"por %%xmm5,%%xmm3 \n"
"movdqu %%xmm3,0x30(%1) \n"
"lea 0x40(%1),%1 \n"
"sub $0x10,%2 \n"
"jg 1b \n"
: "+r"(src_raw), // %0
"+r"(dst_rgba), // %1
"+r"(width) // %2
: "m"(kShuffleMaskRAWToRGBA) // %3
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5");
}
void RAWToRGB24Row_SSSE3(const uint8_t* src_raw,
uint8_t* dst_rgb24,
int width) {
asm volatile(
"movdqa %3,%%xmm3 \n"
"movdqa %4,%%xmm4 \n"
"movdqa %5,%%xmm5 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x4(%0),%%xmm1 \n"
"movdqu 0x8(%0),%%xmm2 \n"
"lea 0x18(%0),%0 \n"
"pshufb %%xmm3,%%xmm0 \n"
"pshufb %%xmm4,%%xmm1 \n"
"pshufb %%xmm5,%%xmm2 \n"
"movq %%xmm0,(%1) \n"
"movq %%xmm1,0x8(%1) \n"
"movq %%xmm2,0x10(%1) \n"
"lea 0x18(%1),%1 \n"
"sub $0x8,%2 \n"
"jg 1b \n"
: "+r"(src_raw), // %0
"+r"(dst_rgb24), // %1
"+r"(width) // %2
: "m"(kShuffleMaskRAWToRGB24_0), // %3
"m"(kShuffleMaskRAWToRGB24_1), // %4
"m"(kShuffleMaskRAWToRGB24_2) // %5
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5");
}
void RGB565ToARGBRow_SSE2(const uint8_t* src, uint8_t* dst, int width) {
asm volatile(
"mov $0x1080108,%%eax \n"
"movd %%eax,%%xmm5 \n"
"pshufd $0x0,%%xmm5,%%xmm5 \n"
"mov $0x20802080,%%eax \n"
"movd %%eax,%%xmm6 \n"
"pshufd $0x0,%%xmm6,%%xmm6 \n"
"pcmpeqb %%xmm3,%%xmm3 \n"
"psllw $0xb,%%xmm3 \n"
"pcmpeqb %%xmm4,%%xmm4 \n"
"psllw $0xa,%%xmm4 \n"
"psrlw $0x5,%%xmm4 \n"
"pcmpeqb %%xmm7,%%xmm7 \n"
"psllw $0x8,%%xmm7 \n"
"sub %0,%1 \n"
"sub %0,%1 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqa %%xmm0,%%xmm1 \n"
"movdqa %%xmm0,%%xmm2 \n"
"pand %%xmm3,%%xmm1 \n"
"psllw $0xb,%%xmm2 \n"
"pmulhuw %%xmm5,%%xmm1 \n"
"pmulhuw %%xmm5,%%xmm2 \n"
"psllw $0x8,%%xmm1 \n"
"por %%xmm2,%%xmm1 \n"
"pand %%xmm4,%%xmm0 \n"
"pmulhuw %%xmm6,%%xmm0 \n"
"por %%xmm7,%%xmm0 \n"
"movdqa %%xmm1,%%xmm2 \n"
"punpcklbw %%xmm0,%%xmm1 \n"
"punpckhbw %%xmm0,%%xmm2 \n"
"movdqu %%xmm1,0x00(%1,%0,2) \n"
"movdqu %%xmm2,0x10(%1,%0,2) \n"
"lea 0x10(%0),%0 \n"
"sub $0x8,%2 \n"
"jg 1b \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
:
: "memory", "cc", "eax", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5",
"xmm6", "xmm7");
}
void ARGB1555ToARGBRow_SSE2(const uint8_t* src, uint8_t* dst, int width) {
asm volatile(
"mov $0x1080108,%%eax \n"
"movd %%eax,%%xmm5 \n"
"pshufd $0x0,%%xmm5,%%xmm5 \n"
"mov $0x42004200,%%eax \n"
"movd %%eax,%%xmm6 \n"
"pshufd $0x0,%%xmm6,%%xmm6 \n"
"pcmpeqb %%xmm3,%%xmm3 \n"
"psllw $0xb,%%xmm3 \n"
"movdqa %%xmm3,%%xmm4 \n"
"psrlw $0x6,%%xmm4 \n"
"pcmpeqb %%xmm7,%%xmm7 \n"
"psllw $0x8,%%xmm7 \n"
"sub %0,%1 \n"
"sub %0,%1 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqa %%xmm0,%%xmm1 \n"
"movdqa %%xmm0,%%xmm2 \n"
"psllw $0x1,%%xmm1 \n"
"psllw $0xb,%%xmm2 \n"
"pand %%xmm3,%%xmm1 \n"
"pmulhuw %%xmm5,%%xmm2 \n"
"pmulhuw %%xmm5,%%xmm1 \n"
"psllw $0x8,%%xmm1 \n"
"por %%xmm2,%%xmm1 \n"
"movdqa %%xmm0,%%xmm2 \n"
"pand %%xmm4,%%xmm0 \n"
"psraw $0x8,%%xmm2 \n"
"pmulhuw %%xmm6,%%xmm0 \n"
"pand %%xmm7,%%xmm2 \n"
"por %%xmm2,%%xmm0 \n"
"movdqa %%xmm1,%%xmm2 \n"
"punpcklbw %%xmm0,%%xmm1 \n"
"punpckhbw %%xmm0,%%xmm2 \n"
"movdqu %%xmm1,0x00(%1,%0,2) \n"
"movdqu %%xmm2,0x10(%1,%0,2) \n"
"lea 0x10(%0),%0 \n"
"sub $0x8,%2 \n"
"jg 1b \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
:
: "memory", "cc", "eax", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5",
"xmm6", "xmm7");
}
void ARGB4444ToARGBRow_SSE2(const uint8_t* src, uint8_t* dst, int width) {
asm volatile(
"mov $0xf0f0f0f,%%eax \n"
"movd %%eax,%%xmm4 \n"
"pshufd $0x0,%%xmm4,%%xmm4 \n"
"movdqa %%xmm4,%%xmm5 \n"
"pslld $0x4,%%xmm5 \n"
"sub %0,%1 \n"
"sub %0,%1 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqa %%xmm0,%%xmm2 \n"
"pand %%xmm4,%%xmm0 \n"
"pand %%xmm5,%%xmm2 \n"
"movdqa %%xmm0,%%xmm1 \n"
"movdqa %%xmm2,%%xmm3 \n"
"psllw $0x4,%%xmm1 \n"
"psrlw $0x4,%%xmm3 \n"
"por %%xmm1,%%xmm0 \n"
"por %%xmm3,%%xmm2 \n"
"movdqa %%xmm0,%%xmm1 \n"
"punpcklbw %%xmm2,%%xmm0 \n"
"punpckhbw %%xmm2,%%xmm1 \n"
"movdqu %%xmm0,0x00(%1,%0,2) \n"
"movdqu %%xmm1,0x10(%1,%0,2) \n"
"lea 0x10(%0),%0 \n"
"sub $0x8,%2 \n"
"jg 1b \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
:
: "memory", "cc", "eax", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5");
}
void ARGBToRGB24Row_SSSE3(const uint8_t* src, uint8_t* dst, int width) {
asm volatile(
"movdqa %3,%%xmm6 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"movdqu 0x20(%0),%%xmm2 \n"
"movdqu 0x30(%0),%%xmm3 \n"
"lea 0x40(%0),%0 \n"
"pshufb %%xmm6,%%xmm0 \n"
"pshufb %%xmm6,%%xmm1 \n"
"pshufb %%xmm6,%%xmm2 \n"
"pshufb %%xmm6,%%xmm3 \n"
"movdqa %%xmm1,%%xmm4 \n"
"psrldq $0x4,%%xmm1 \n"
"pslldq $0xc,%%xmm4 \n"
"movdqa %%xmm2,%%xmm5 \n"
"por %%xmm4,%%xmm0 \n"
"pslldq $0x8,%%xmm5 \n"
"movdqu %%xmm0,(%1) \n"
"por %%xmm5,%%xmm1 \n"
"psrldq $0x8,%%xmm2 \n"
"pslldq $0x4,%%xmm3 \n"
"por %%xmm3,%%xmm2 \n"
"movdqu %%xmm1,0x10(%1) \n"
"movdqu %%xmm2,0x20(%1) \n"
"lea 0x30(%1),%1 \n"
"sub $0x10,%2 \n"
"jg 1b \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
: "m"(kShuffleMaskARGBToRGB24) // %3
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6");
}
void ARGBToRAWRow_SSSE3(const uint8_t* src, uint8_t* dst, int width) {
asm volatile(
"movdqa %3,%%xmm6 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"movdqu 0x20(%0),%%xmm2 \n"
"movdqu 0x30(%0),%%xmm3 \n"
"lea 0x40(%0),%0 \n"
"pshufb %%xmm6,%%xmm0 \n"
"pshufb %%xmm6,%%xmm1 \n"
"pshufb %%xmm6,%%xmm2 \n"
"pshufb %%xmm6,%%xmm3 \n"
"movdqa %%xmm1,%%xmm4 \n"
"psrldq $0x4,%%xmm1 \n"
"pslldq $0xc,%%xmm4 \n"
"movdqa %%xmm2,%%xmm5 \n"
"por %%xmm4,%%xmm0 \n"
"pslldq $0x8,%%xmm5 \n"
"movdqu %%xmm0,(%1) \n"
"por %%xmm5,%%xmm1 \n"
"psrldq $0x8,%%xmm2 \n"
"pslldq $0x4,%%xmm3 \n"
"por %%xmm3,%%xmm2 \n"
"movdqu %%xmm1,0x10(%1) \n"
"movdqu %%xmm2,0x20(%1) \n"
"lea 0x30(%1),%1 \n"
"sub $0x10,%2 \n"
"jg 1b \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
: "m"(kShuffleMaskARGBToRAW) // %3
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6");
}
#ifdef HAS_ARGBTORGB24ROW_AVX2
// vpermd for 12+12 to 24
static const lvec32 kPermdRGB24_AVX = {0, 1, 2, 4, 5, 6, 3, 7};
void ARGBToRGB24Row_AVX2(const uint8_t* src, uint8_t* dst, int width) {
asm volatile(
"vbroadcastf128 %3,%%ymm6 \n"
"vmovdqa %4,%%ymm7 \n"
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm0 \n"
"vmovdqu 0x20(%0),%%ymm1 \n"
"vmovdqu 0x40(%0),%%ymm2 \n"
"vmovdqu 0x60(%0),%%ymm3 \n"
"lea 0x80(%0),%0 \n"
"vpshufb %%ymm6,%%ymm0,%%ymm0 \n" // xxx0yyy0
"vpshufb %%ymm6,%%ymm1,%%ymm1 \n"
"vpshufb %%ymm6,%%ymm2,%%ymm2 \n"
"vpshufb %%ymm6,%%ymm3,%%ymm3 \n"
"vpermd %%ymm0,%%ymm7,%%ymm0 \n" // pack to 24 bytes
"vpermd %%ymm1,%%ymm7,%%ymm1 \n"
"vpermd %%ymm2,%%ymm7,%%ymm2 \n"
"vpermd %%ymm3,%%ymm7,%%ymm3 \n"
"vpermq $0x3f,%%ymm1,%%ymm4 \n" // combine 24 + 8
"vpor %%ymm4,%%ymm0,%%ymm0 \n"
"vmovdqu %%ymm0,(%1) \n"
"vpermq $0xf9,%%ymm1,%%ymm1 \n" // combine 16 + 16
"vpermq $0x4f,%%ymm2,%%ymm4 \n"
"vpor %%ymm4,%%ymm1,%%ymm1 \n"
"vmovdqu %%ymm1,0x20(%1) \n"
"vpermq $0xfe,%%ymm2,%%ymm2 \n" // combine 8 + 24
"vpermq $0x93,%%ymm3,%%ymm3 \n"
"vpor %%ymm3,%%ymm2,%%ymm2 \n"
"vmovdqu %%ymm2,0x40(%1) \n"
"lea 0x60(%1),%1 \n"
"sub $0x20,%2 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
: "m"(kShuffleMaskARGBToRGB24), // %3
"m"(kPermdRGB24_AVX) // %4
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6",
"xmm7");
}
#endif
#ifdef HAS_ARGBTORGB24ROW_AVX512VBMI
// Shuffle table for converting ARGBToRGB24
static const ulvec8 kPermARGBToRGB24_0 = {
0u, 1u, 2u, 4u, 5u, 6u, 8u, 9u, 10u, 12u, 13u,
14u, 16u, 17u, 18u, 20u, 21u, 22u, 24u, 25u, 26u, 28u,
29u, 30u, 32u, 33u, 34u, 36u, 37u, 38u, 40u, 41u};
static const ulvec8 kPermARGBToRGB24_1 = {
10u, 12u, 13u, 14u, 16u, 17u, 18u, 20u, 21u, 22u, 24u,
25u, 26u, 28u, 29u, 30u, 32u, 33u, 34u, 36u, 37u, 38u,
40u, 41u, 42u, 44u, 45u, 46u, 48u, 49u, 50u, 52u};
static const ulvec8 kPermARGBToRGB24_2 = {
21u, 22u, 24u, 25u, 26u, 28u, 29u, 30u, 32u, 33u, 34u,
36u, 37u, 38u, 40u, 41u, 42u, 44u, 45u, 46u, 48u, 49u,
50u, 52u, 53u, 54u, 56u, 57u, 58u, 60u, 61u, 62u};
void ARGBToRGB24Row_AVX512VBMI(const uint8_t* src, uint8_t* dst, int width) {
asm volatile(
"vmovdqa %3,%%ymm5 \n"
"vmovdqa %4,%%ymm6 \n"
"vmovdqa %5,%%ymm7 \n"
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm0 \n"
"vmovdqu 0x20(%0),%%ymm1 \n"
"vmovdqu 0x40(%0),%%ymm2 \n"
"vmovdqu 0x60(%0),%%ymm3 \n"
"lea 0x80(%0),%0 \n"
"vpermt2b %%ymm1,%%ymm5,%%ymm0 \n"
"vpermt2b %%ymm2,%%ymm6,%%ymm1 \n"
"vpermt2b %%ymm3,%%ymm7,%%ymm2 \n"
"vmovdqu %%ymm0,(%1) \n"
"vmovdqu %%ymm1,0x20(%1) \n"
"vmovdqu %%ymm2,0x40(%1) \n"
"lea 0x60(%1),%1 \n"
"sub $0x20,%2 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
: "m"(kPermARGBToRGB24_0), // %3
"m"(kPermARGBToRGB24_1), // %4
"m"(kPermARGBToRGB24_2) // %5
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm5", "xmm6", "xmm7");
}
#endif
#ifdef HAS_ARGBTORAWROW_AVX2
void ARGBToRAWRow_AVX2(const uint8_t* src, uint8_t* dst, int width) {
asm volatile(
"vbroadcastf128 %3,%%ymm6 \n"
"vmovdqa %4,%%ymm7 \n"
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm0 \n"
"vmovdqu 0x20(%0),%%ymm1 \n"
"vmovdqu 0x40(%0),%%ymm2 \n"
"vmovdqu 0x60(%0),%%ymm3 \n"
"lea 0x80(%0),%0 \n"
"vpshufb %%ymm6,%%ymm0,%%ymm0 \n" // xxx0yyy0
"vpshufb %%ymm6,%%ymm1,%%ymm1 \n"
"vpshufb %%ymm6,%%ymm2,%%ymm2 \n"
"vpshufb %%ymm6,%%ymm3,%%ymm3 \n"
"vpermd %%ymm0,%%ymm7,%%ymm0 \n" // pack to 24 bytes
"vpermd %%ymm1,%%ymm7,%%ymm1 \n"
"vpermd %%ymm2,%%ymm7,%%ymm2 \n"
"vpermd %%ymm3,%%ymm7,%%ymm3 \n"
"vpermq $0x3f,%%ymm1,%%ymm4 \n" // combine 24 + 8
"vpor %%ymm4,%%ymm0,%%ymm0 \n"
"vmovdqu %%ymm0,(%1) \n"
"vpermq $0xf9,%%ymm1,%%ymm1 \n" // combine 16 + 16
"vpermq $0x4f,%%ymm2,%%ymm4 \n"
"vpor %%ymm4,%%ymm1,%%ymm1 \n"
"vmovdqu %%ymm1,0x20(%1) \n"
"vpermq $0xfe,%%ymm2,%%ymm2 \n" // combine 8 + 24
"vpermq $0x93,%%ymm3,%%ymm3 \n"
"vpor %%ymm3,%%ymm2,%%ymm2 \n"
"vmovdqu %%ymm2,0x40(%1) \n"
"lea 0x60(%1),%1 \n"
"sub $0x20,%2 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
: "m"(kShuffleMaskARGBToRAW), // %3
"m"(kPermdRGB24_AVX) // %4
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6",
"xmm7");
}
#endif
void ARGBToRGB565Row_SSE2(const uint8_t* src, uint8_t* dst, int width) {
asm volatile(
"pcmpeqb %%xmm3,%%xmm3 \n"
"psrld $0x1b,%%xmm3 \n"
"pcmpeqb %%xmm4,%%xmm4 \n"
"psrld $0x1a,%%xmm4 \n"
"pslld $0x5,%%xmm4 \n"
"pcmpeqb %%xmm5,%%xmm5 \n"
"pslld $0xb,%%xmm5 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqa %%xmm0,%%xmm1 \n"
"movdqa %%xmm0,%%xmm2 \n"
"pslld $0x8,%%xmm0 \n"
"psrld $0x3,%%xmm1 \n"
"psrld $0x5,%%xmm2 \n"
"psrad $0x10,%%xmm0 \n"
"pand %%xmm3,%%xmm1 \n"
"pand %%xmm4,%%xmm2 \n"
"pand %%xmm5,%%xmm0 \n"
"por %%xmm2,%%xmm1 \n"
"por %%xmm1,%%xmm0 \n"
"packssdw %%xmm0,%%xmm0 \n"
"lea 0x10(%0),%0 \n"
"movq %%xmm0,(%1) \n"
"lea 0x8(%1),%1 \n"
"sub $0x4,%2 \n"
"jg 1b \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
::"memory",
"cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5");
}
void ARGBToRGB565DitherRow_SSE2(const uint8_t* src,
uint8_t* dst,
const uint32_t dither4,
int width) {
asm volatile(
"movd %3,%%xmm6 \n"
"punpcklbw %%xmm6,%%xmm6 \n"
"movdqa %%xmm6,%%xmm7 \n"
"punpcklwd %%xmm6,%%xmm6 \n"
"punpckhwd %%xmm7,%%xmm7 \n"
"pcmpeqb %%xmm3,%%xmm3 \n"
"psrld $0x1b,%%xmm3 \n"
"pcmpeqb %%xmm4,%%xmm4 \n"
"psrld $0x1a,%%xmm4 \n"
"pslld $0x5,%%xmm4 \n"
"pcmpeqb %%xmm5,%%xmm5 \n"
"pslld $0xb,%%xmm5 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"paddusb %%xmm6,%%xmm0 \n"
"movdqa %%xmm0,%%xmm1 \n"
"movdqa %%xmm0,%%xmm2 \n"
"pslld $0x8,%%xmm0 \n"
"psrld $0x3,%%xmm1 \n"
"psrld $0x5,%%xmm2 \n"
"psrad $0x10,%%xmm0 \n"
"pand %%xmm3,%%xmm1 \n"
"pand %%xmm4,%%xmm2 \n"
"pand %%xmm5,%%xmm0 \n"
"por %%xmm2,%%xmm1 \n"
"por %%xmm1,%%xmm0 \n"
"packssdw %%xmm0,%%xmm0 \n"
"lea 0x10(%0),%0 \n"
"movq %%xmm0,(%1) \n"
"lea 0x8(%1),%1 \n"
"sub $0x4,%2 \n"
"jg 1b \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
: "m"(dither4) // %3
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6",
"xmm7");
}
#ifdef HAS_ARGBTORGB565DITHERROW_AVX2
void ARGBToRGB565DitherRow_AVX2(const uint8_t* src,
uint8_t* dst,
const uint32_t dither4,
int width) {
asm volatile(
"vbroadcastss %3,%%xmm6 \n"
"vpunpcklbw %%xmm6,%%xmm6,%%xmm6 \n"
"vpermq $0xd8,%%ymm6,%%ymm6 \n"
"vpunpcklwd %%ymm6,%%ymm6,%%ymm6 \n"
"vpcmpeqb %%ymm3,%%ymm3,%%ymm3 \n"
"vpsrld $0x1b,%%ymm3,%%ymm3 \n"
"vpcmpeqb %%ymm4,%%ymm4,%%ymm4 \n"
"vpsrld $0x1a,%%ymm4,%%ymm4 \n"
"vpslld $0x5,%%ymm4,%%ymm4 \n"
"vpslld $0xb,%%ymm3,%%ymm5 \n"
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm0 \n"
"vpaddusb %%ymm6,%%ymm0,%%ymm0 \n"
"vpsrld $0x5,%%ymm0,%%ymm2 \n"
"vpsrld $0x3,%%ymm0,%%ymm1 \n"
"vpsrld $0x8,%%ymm0,%%ymm0 \n"
"vpand %%ymm4,%%ymm2,%%ymm2 \n"
"vpand %%ymm3,%%ymm1,%%ymm1 \n"
"vpand %%ymm5,%%ymm0,%%ymm0 \n"
"vpor %%ymm2,%%ymm1,%%ymm1 \n"
"vpor %%ymm1,%%ymm0,%%ymm0 \n"
"vpackusdw %%ymm0,%%ymm0,%%ymm0 \n"
"vpermq $0xd8,%%ymm0,%%ymm0 \n"
"lea 0x20(%0),%0 \n"
"vmovdqu %%xmm0,(%1) \n"
"lea 0x10(%1),%1 \n"
"sub $0x8,%2 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
: "m"(dither4) // %3
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6",
"xmm7");
}
#endif // HAS_ARGBTORGB565DITHERROW_AVX2
void ARGBToARGB1555Row_SSE2(const uint8_t* src, uint8_t* dst, int width) {
asm volatile(
"pcmpeqb %%xmm4,%%xmm4 \n"
"psrld $0x1b,%%xmm4 \n"
"movdqa %%xmm4,%%xmm5 \n"
"pslld $0x5,%%xmm5 \n"
"movdqa %%xmm4,%%xmm6 \n"
"pslld $0xa,%%xmm6 \n"
"pcmpeqb %%xmm7,%%xmm7 \n"
"pslld $0xf,%%xmm7 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqa %%xmm0,%%xmm1 \n"
"movdqa %%xmm0,%%xmm2 \n"
"movdqa %%xmm0,%%xmm3 \n"
"psrad $0x10,%%xmm0 \n"
"psrld $0x3,%%xmm1 \n"
"psrld $0x6,%%xmm2 \n"
"psrld $0x9,%%xmm3 \n"
"pand %%xmm7,%%xmm0 \n"
"pand %%xmm4,%%xmm1 \n"
"pand %%xmm5,%%xmm2 \n"
"pand %%xmm6,%%xmm3 \n"
"por %%xmm1,%%xmm0 \n"
"por %%xmm3,%%xmm2 \n"
"por %%xmm2,%%xmm0 \n"
"packssdw %%xmm0,%%xmm0 \n"
"lea 0x10(%0),%0 \n"
"movq %%xmm0,(%1) \n"
"lea 0x8(%1),%1 \n"
"sub $0x4,%2 \n"
"jg 1b \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
::"memory",
"cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7");
}
void ARGBToARGB4444Row_SSE2(const uint8_t* src, uint8_t* dst, int width) {
asm volatile(
"pcmpeqb %%xmm4,%%xmm4 \n"
"psllw $0xc,%%xmm4 \n"
"movdqa %%xmm4,%%xmm3 \n"
"psrlw $0x8,%%xmm3 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqa %%xmm0,%%xmm1 \n"
"pand %%xmm3,%%xmm0 \n"
"pand %%xmm4,%%xmm1 \n"
"psrlq $0x4,%%xmm0 \n"
"psrlq $0x8,%%xmm1 \n"
"por %%xmm1,%%xmm0 \n"
"packuswb %%xmm0,%%xmm0 \n"
"lea 0x10(%0),%0 \n"
"movq %%xmm0,(%1) \n"
"lea 0x8(%1),%1 \n"
"sub $0x4,%2 \n"
"jg 1b \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
::"memory",
"cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4");
}
#endif // HAS_RGB24TOARGBROW_SSSE3
/*
ARGBToAR30Row:
Red Blue
With the 8 bit value in the upper bits of a short, vpmulhuw by (1024+4) will
produce a 10 bit value in the low 10 bits of each 16 bit value. This is whats
wanted for the blue channel. The red needs to be shifted 4 left, so multiply by
(1024+4)*16 for red.
Alpha Green
Alpha and Green are already in the high bits so vpand can zero out the other
bits, keeping just 2 upper bits of alpha and 8 bit green. The same multiplier
could be used for Green - (1024+4) putting the 10 bit green in the lsb. Alpha
would be a simple multiplier to shift it into position. It wants a gap of 10
above the green. Green is 10 bits, so there are 6 bits in the low short. 4
more are needed, so a multiplier of 4 gets the 2 bits into the upper 16 bits,
and then a shift of 4 is a multiply of 16, so (4*16) = 64. Then shift the
result left 10 to position the A and G channels.
*/
// Shuffle table for converting RAW to RGB24. Last 8.
static const uvec8 kShuffleRB30 = {128u, 0u, 128u, 2u, 128u, 4u, 128u, 6u,
128u, 8u, 128u, 10u, 128u, 12u, 128u, 14u};
static const uvec8 kShuffleBR30 = {128u, 2u, 128u, 0u, 128u, 6u, 128u, 4u,
128u, 10u, 128u, 8u, 128u, 14u, 128u, 12u};
static const uint32_t kMulRB10 = 1028 * 16 * 65536 + 1028;
static const uint32_t kMaskRB10 = 0x3ff003ff;
static const uint32_t kMaskAG10 = 0xc000ff00;
static const uint32_t kMulAG10 = 64 * 65536 + 1028;
void ARGBToAR30Row_SSSE3(const uint8_t* src, uint8_t* dst, int width) {
asm volatile(
"movdqa %3,%%xmm2 \n" // shuffler for RB
"movd %4,%%xmm3 \n" // multipler for RB
"movd %5,%%xmm4 \n" // mask for R10 B10
"movd %6,%%xmm5 \n" // mask for AG
"movd %7,%%xmm6 \n" // multipler for AG
"pshufd $0x0,%%xmm3,%%xmm3 \n"
"pshufd $0x0,%%xmm4,%%xmm4 \n"
"pshufd $0x0,%%xmm5,%%xmm5 \n"
"pshufd $0x0,%%xmm6,%%xmm6 \n"
"sub %0,%1 \n"
"1: \n"
"movdqu (%0),%%xmm0 \n" // fetch 4 ARGB pixels
"movdqa %%xmm0,%%xmm1 \n"
"pshufb %%xmm2,%%xmm1 \n" // R0B0
"pand %%xmm5,%%xmm0 \n" // A0G0
"pmulhuw %%xmm3,%%xmm1 \n" // X2 R16 X4 B10
"pmulhuw %%xmm6,%%xmm0 \n" // X10 A2 X10 G10
"pand %%xmm4,%%xmm1 \n" // X2 R10 X10 B10
"pslld $10,%%xmm0 \n" // A2 x10 G10 x10
"por %%xmm1,%%xmm0 \n" // A2 R10 G10 B10
"movdqu %%xmm0,(%1,%0) \n" // store 4 AR30 pixels
"add $0x10,%0 \n"
"sub $0x4,%2 \n"
"jg 1b \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
: "m"(kShuffleRB30), // %3
"m"(kMulRB10), // %4
"m"(kMaskRB10), // %5
"m"(kMaskAG10), // %6
"m"(kMulAG10) // %7
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6");
}
void ABGRToAR30Row_SSSE3(const uint8_t* src, uint8_t* dst, int width) {
asm volatile(
"movdqa %3,%%xmm2 \n" // shuffler for RB
"movd %4,%%xmm3 \n" // multipler for RB
"movd %5,%%xmm4 \n" // mask for R10 B10
"movd %6,%%xmm5 \n" // mask for AG
"movd %7,%%xmm6 \n" // multipler for AG
"pshufd $0x0,%%xmm3,%%xmm3 \n"
"pshufd $0x0,%%xmm4,%%xmm4 \n"
"pshufd $0x0,%%xmm5,%%xmm5 \n"
"pshufd $0x0,%%xmm6,%%xmm6 \n"
"sub %0,%1 \n"
"1: \n"
"movdqu (%0),%%xmm0 \n" // fetch 4 ABGR pixels
"movdqa %%xmm0,%%xmm1 \n"
"pshufb %%xmm2,%%xmm1 \n" // R0B0
"pand %%xmm5,%%xmm0 \n" // A0G0
"pmulhuw %%xmm3,%%xmm1 \n" // X2 R16 X4 B10
"pmulhuw %%xmm6,%%xmm0 \n" // X10 A2 X10 G10
"pand %%xmm4,%%xmm1 \n" // X2 R10 X10 B10
"pslld $10,%%xmm0 \n" // A2 x10 G10 x10
"por %%xmm1,%%xmm0 \n" // A2 R10 G10 B10
"movdqu %%xmm0,(%1,%0) \n" // store 4 AR30 pixels
"add $0x10,%0 \n"
"sub $0x4,%2 \n"
"jg 1b \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
: "m"(kShuffleBR30), // %3 reversed shuffler
"m"(kMulRB10), // %4
"m"(kMaskRB10), // %5
"m"(kMaskAG10), // %6
"m"(kMulAG10) // %7
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6");
}
#ifdef HAS_ARGBTOAR30ROW_AVX2
void ARGBToAR30Row_AVX2(const uint8_t* src, uint8_t* dst, int width) {
asm volatile(
"vbroadcastf128 %3,%%ymm2 \n" // shuffler for RB
"vbroadcastss %4,%%ymm3 \n" // multipler for RB
"vbroadcastss %5,%%ymm4 \n" // mask for R10 B10
"vbroadcastss %6,%%ymm5 \n" // mask for AG
"vbroadcastss %7,%%ymm6 \n" // multipler for AG
"sub %0,%1 \n"
"1: \n"
"vmovdqu (%0),%%ymm0 \n" // fetch 8 ARGB pixels
"vpshufb %%ymm2,%%ymm0,%%ymm1 \n" // R0B0
"vpand %%ymm5,%%ymm0,%%ymm0 \n" // A0G0
"vpmulhuw %%ymm3,%%ymm1,%%ymm1 \n" // X2 R16 X4 B10
"vpmulhuw %%ymm6,%%ymm0,%%ymm0 \n" // X10 A2 X10 G10
"vpand %%ymm4,%%ymm1,%%ymm1 \n" // X2 R10 X10 B10
"vpslld $10,%%ymm0,%%ymm0 \n" // A2 x10 G10 x10
"vpor %%ymm1,%%ymm0,%%ymm0 \n" // A2 R10 G10 B10
"vmovdqu %%ymm0,(%1,%0) \n" // store 8 AR30 pixels
"add $0x20,%0 \n"
"sub $0x8,%2 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
: "m"(kShuffleRB30), // %3
"m"(kMulRB10), // %4
"m"(kMaskRB10), // %5
"m"(kMaskAG10), // %6
"m"(kMulAG10) // %7
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6");
}
#endif
#ifdef HAS_ABGRTOAR30ROW_AVX2
void ABGRToAR30Row_AVX2(const uint8_t* src, uint8_t* dst, int width) {
asm volatile(
"vbroadcastf128 %3,%%ymm2 \n" // shuffler for RB
"vbroadcastss %4,%%ymm3 \n" // multipler for RB
"vbroadcastss %5,%%ymm4 \n" // mask for R10 B10
"vbroadcastss %6,%%ymm5 \n" // mask for AG
"vbroadcastss %7,%%ymm6 \n" // multipler for AG
"sub %0,%1 \n"
"1: \n"
"vmovdqu (%0),%%ymm0 \n" // fetch 8 ABGR pixels
"vpshufb %%ymm2,%%ymm0,%%ymm1 \n" // R0B0
"vpand %%ymm5,%%ymm0,%%ymm0 \n" // A0G0
"vpmulhuw %%ymm3,%%ymm1,%%ymm1 \n" // X2 R16 X4 B10
"vpmulhuw %%ymm6,%%ymm0,%%ymm0 \n" // X10 A2 X10 G10
"vpand %%ymm4,%%ymm1,%%ymm1 \n" // X2 R10 X10 B10
"vpslld $10,%%ymm0,%%ymm0 \n" // A2 x10 G10 x10
"vpor %%ymm1,%%ymm0,%%ymm0 \n" // A2 R10 G10 B10
"vmovdqu %%ymm0,(%1,%0) \n" // store 8 AR30 pixels
"add $0x20,%0 \n"
"sub $0x8,%2 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
: "m"(kShuffleBR30), // %3 reversed shuffler
"m"(kMulRB10), // %4
"m"(kMaskRB10), // %5
"m"(kMaskAG10), // %6
"m"(kMulAG10) // %7
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6");
}
#endif
// clang-format off
// TODO(mraptis): Consider passing R, G, B multipliers as parameter.
// round parameter is register containing value to add before shift.
#define RGBTOY(round) \
"1: \n" \
"movdqu (%0),%%xmm0 \n" \
"movdqu 0x10(%0),%%xmm1 \n" \
"movdqu 0x20(%0),%%xmm2 \n" \
"movdqu 0x30(%0),%%xmm3 \n" \
"psubb %%xmm5,%%xmm0 \n" \
"psubb %%xmm5,%%xmm1 \n" \
"psubb %%xmm5,%%xmm2 \n" \
"psubb %%xmm5,%%xmm3 \n" \
"movdqu %%xmm4,%%xmm6 \n" \
"pmaddubsw %%xmm0,%%xmm6 \n" \
"movdqu %%xmm4,%%xmm0 \n" \
"pmaddubsw %%xmm1,%%xmm0 \n" \
"movdqu %%xmm4,%%xmm1 \n" \
"pmaddubsw %%xmm2,%%xmm1 \n" \
"movdqu %%xmm4,%%xmm2 \n" \
"pmaddubsw %%xmm3,%%xmm2 \n" \
"lea 0x40(%0),%0 \n" \
"phaddw %%xmm0,%%xmm6 \n" \
"phaddw %%xmm2,%%xmm1 \n" \
"prefetcht0 1280(%0) \n" \
"paddw %%" #round ",%%xmm6 \n" \
"paddw %%" #round ",%%xmm1 \n" \
"psrlw $0x8,%%xmm6 \n" \
"psrlw $0x8,%%xmm1 \n" \
"packuswb %%xmm1,%%xmm6 \n" \
"movdqu %%xmm6,(%1) \n" \
"lea 0x10(%1),%1 \n" \
"sub $0x10,%2 \n" \
"jg 1b \n"
#define RGBTOY_AVX2(round) \
"1: \n" \
"vmovdqu (%0),%%ymm0 \n" \
"vmovdqu 0x20(%0),%%ymm1 \n" \
"vmovdqu 0x40(%0),%%ymm2 \n" \
"vmovdqu 0x60(%0),%%ymm3 \n" \
"vpsubb %%ymm5, %%ymm0, %%ymm0 \n" \
"vpsubb %%ymm5, %%ymm1, %%ymm1 \n" \
"vpsubb %%ymm5, %%ymm2, %%ymm2 \n" \
"vpsubb %%ymm5, %%ymm3, %%ymm3 \n" \
"vpmaddubsw %%ymm0,%%ymm4,%%ymm0 \n" \
"vpmaddubsw %%ymm1,%%ymm4,%%ymm1 \n" \
"vpmaddubsw %%ymm2,%%ymm4,%%ymm2 \n" \
"vpmaddubsw %%ymm3,%%ymm4,%%ymm3 \n" \
"lea 0x80(%0),%0 \n" \
"vphaddw %%ymm1,%%ymm0,%%ymm0 \n" /* mutates. */ \
"vphaddw %%ymm3,%%ymm2,%%ymm2 \n" \
"prefetcht0 1280(%0) \n" \
"vpaddw %%" #round ",%%ymm0,%%ymm0 \n" /* Add .5 for rounding. */ \
"vpaddw %%" #round ",%%ymm2,%%ymm2 \n" \
"vpsrlw $0x8,%%ymm0,%%ymm0 \n" \
"vpsrlw $0x8,%%ymm2,%%ymm2 \n" \
"vpackuswb %%ymm2,%%ymm0,%%ymm0 \n" /* mutates. */ \
"vpermd %%ymm0,%%ymm6,%%ymm0 \n" /* unmutate. */ \
"vmovdqu %%ymm0,(%1) \n" \
"lea 0x20(%1),%1 \n" \
"sub $0x20,%2 \n" \
"jg 1b \n" \
"vzeroupper \n"
// clang-format on
#ifdef HAS_ARGBTOYROW_SSSE3
// Convert 16 ARGB pixels (64 bytes) to 16 Y values.
void ARGBToYRow_SSSE3(const uint8_t* src_argb, uint8_t* dst_y, int width) {
asm volatile(
"movdqa %3,%%xmm4 \n"
"movdqa %4,%%xmm5 \n"
"movdqa %5,%%xmm7 \n"
LABELALIGN RGBTOY(xmm7)
: "+r"(src_argb), // %0
"+r"(dst_y), // %1
"+r"(width) // %2
: "m"(kARGBToY), // %3
"m"(kSub128), // %4
"m"(kAddY16) // %5
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6",
"xmm7");
}
#endif // HAS_ARGBTOYROW_SSSE3
#ifdef HAS_ARGBTOYJROW_SSSE3
// Convert 16 ARGB pixels (64 bytes) to 16 YJ values.
// Same as ARGBToYRow but different coefficients, no add 16.
void ARGBToYJRow_SSSE3(const uint8_t* src_argb, uint8_t* dst_y, int width) {
asm volatile(
"movdqa %3,%%xmm4 \n"
"movdqa %4,%%xmm5 \n"
LABELALIGN RGBTOY(xmm5)
: "+r"(src_argb), // %0
"+r"(dst_y), // %1
"+r"(width) // %2
: "m"(kARGBToYJ), // %3
"m"(kSub128) // %4
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6");
}
#endif // HAS_ARGBTOYJROW_SSSE3
#ifdef HAS_RGBATOYJROW_SSSE3
// Convert 16 ARGB pixels (64 bytes) to 16 YJ values.
// Same as ARGBToYRow but different coefficients, no add 16.
void RGBAToYJRow_SSSE3(const uint8_t* src_rgba, uint8_t* dst_y, int width) {
asm volatile(
"movdqa %3,%%xmm4 \n"
"movdqa %4,%%xmm5 \n"
LABELALIGN RGBTOY(xmm5)
: "+r"(src_rgba), // %0
"+r"(dst_y), // %1
"+r"(width) // %2
: "m"(kRGBAToYJ), // %3
"m"(kSub128) // %4
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6");
}
#endif // HAS_RGBATOYJROW_SSSE3
#ifdef HAS_ARGBTOYROW_AVX2
// vpermd for vphaddw + vpackuswb vpermd.
static const lvec32 kPermdARGBToY_AVX = {0, 4, 1, 5, 2, 6, 3, 7};
// Convert 32 ARGB pixels (128 bytes) to 32 Y values.
void ARGBToYRow_AVX2(const uint8_t* src_argb, uint8_t* dst_y, int width) {
asm volatile(
"vbroadcastf128 %3,%%ymm4 \n"
"vbroadcastf128 %4,%%ymm5 \n"
"vbroadcastf128 %5,%%ymm7 \n"
"vmovdqu %6,%%ymm6 \n"
LABELALIGN RGBTOY_AVX2(ymm7)
: "+r"(src_argb), // %0
"+r"(dst_y), // %1
"+r"(width) // %2
: "m"(kARGBToY), // %3
"m"(kSub128), // %4
"m"(kAddY16), // %5
"m"(kPermdARGBToY_AVX) // %6
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6",
"xmm7");
}
#endif // HAS_ARGBTOYROW_AVX2
#ifdef HAS_ABGRTOYROW_AVX2
// Convert 32 ABGR pixels (128 bytes) to 32 Y values.
void ABGRToYRow_AVX2(const uint8_t* src_abgr, uint8_t* dst_y, int width) {
asm volatile(
"vbroadcastf128 %3,%%ymm4 \n"
"vbroadcastf128 %4,%%ymm5 \n"
"vbroadcastf128 %5,%%ymm7 \n"
"vmovdqu %6,%%ymm6 \n"
LABELALIGN RGBTOY_AVX2(ymm7)
: "+r"(src_abgr), // %0
"+r"(dst_y), // %1
"+r"(width) // %2
: "m"(kABGRToY), // %3
"m"(kSub128), // %4
"m"(kAddY16), // %5
"m"(kPermdARGBToY_AVX) // %6
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6",
"xmm7");
}
#endif // HAS_ABGRTOYROW_AVX2
#ifdef HAS_ARGBTOYJROW_AVX2
// Convert 32 ARGB pixels (128 bytes) to 32 Y values.
void ARGBToYJRow_AVX2(const uint8_t* src_argb, uint8_t* dst_y, int width) {
asm volatile(
"vbroadcastf128 %3,%%ymm4 \n"
"vbroadcastf128 %4,%%ymm5 \n"
"vmovdqu %5,%%ymm6 \n"
LABELALIGN RGBTOY_AVX2(ymm5)
: "+r"(src_argb), // %0
"+r"(dst_y), // %1
"+r"(width) // %2
: "m"(kARGBToYJ), // %3
"m"(kSub128), // %4
"m"(kPermdARGBToY_AVX) // %5
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6",
"xmm7");
}
#endif // HAS_ARGBTOYJROW_AVX2
#ifdef HAS_RGBATOYJROW_AVX2
// Convert 32 ARGB pixels (128 bytes) to 32 Y values.
void RGBAToYJRow_AVX2(const uint8_t* src_rgba, uint8_t* dst_y, int width) {
asm volatile(
"vbroadcastf128 %3,%%ymm4 \n"
"vbroadcastf128 %4,%%ymm5 \n"
"vmovdqu %5,%%ymm6 \n"
LABELALIGN RGBTOY_AVX2(
ymm5) "vzeroupper \n"
: "+r"(src_rgba), // %0
"+r"(dst_y), // %1
"+r"(width) // %2
: "m"(kRGBAToYJ), // %3
"m"(kSub128), // %4
"m"(kPermdARGBToY_AVX) // %5
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6");
}
#endif // HAS_RGBATOYJROW_AVX2
#ifdef HAS_ARGBTOUVROW_SSSE3
void ARGBToUVRow_SSSE3(const uint8_t* src_argb0,
int src_stride_argb,
uint8_t* dst_u,
uint8_t* dst_v,
int width) {
asm volatile(
"movdqa %5,%%xmm3 \n"
"movdqa %6,%%xmm4 \n"
"movdqa %7,%%xmm5 \n"
"sub %1,%2 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x00(%0,%4,1),%%xmm7 \n"
"pavgb %%xmm7,%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"movdqu 0x10(%0,%4,1),%%xmm7 \n"
"pavgb %%xmm7,%%xmm1 \n"
"movdqu 0x20(%0),%%xmm2 \n"
"movdqu 0x20(%0,%4,1),%%xmm7 \n"
"pavgb %%xmm7,%%xmm2 \n"
"movdqu 0x30(%0),%%xmm6 \n"
"movdqu 0x30(%0,%4,1),%%xmm7 \n"
"pavgb %%xmm7,%%xmm6 \n"
"lea 0x40(%0),%0 \n"
"movdqa %%xmm0,%%xmm7 \n"
"shufps $0x88,%%xmm1,%%xmm0 \n"
"shufps $0xdd,%%xmm1,%%xmm7 \n"
"pavgb %%xmm7,%%xmm0 \n"
"movdqa %%xmm2,%%xmm7 \n"
"shufps $0x88,%%xmm6,%%xmm2 \n"
"shufps $0xdd,%%xmm6,%%xmm7 \n"
"pavgb %%xmm7,%%xmm2 \n"
"movdqa %%xmm0,%%xmm1 \n"
"movdqa %%xmm2,%%xmm6 \n"
"pmaddubsw %%xmm4,%%xmm0 \n"
"pmaddubsw %%xmm4,%%xmm2 \n"
"pmaddubsw %%xmm3,%%xmm1 \n"
"pmaddubsw %%xmm3,%%xmm6 \n"
"phaddw %%xmm2,%%xmm0 \n"
"phaddw %%xmm6,%%xmm1 \n"
"psraw $0x8,%%xmm0 \n"
"psraw $0x8,%%xmm1 \n"
"packsswb %%xmm1,%%xmm0 \n"
"paddb %%xmm5,%%xmm0 \n"
"movlps %%xmm0,(%1) \n"
"movhps %%xmm0,0x00(%1,%2,1) \n"
"lea 0x8(%1),%1 \n"
"sub $0x10,%3 \n"
"jg 1b \n"
: "+r"(src_argb0), // %0
"+r"(dst_u), // %1
"+r"(dst_v), // %2
"+rm"(width) // %3
: "r"((intptr_t)(src_stride_argb)), // %4
"m"(kARGBToV), // %5
"m"(kARGBToU), // %6
"m"(kAddUV128) // %7
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm6", "xmm7");
}
#endif // HAS_ARGBTOUVROW_SSSE3
#ifdef HAS_ARGBTOUVROW_AVX2
// vpshufb for vphaddw + vpackuswb packed to shorts.
static const lvec8 kShufARGBToUV_AVX = {
0, 1, 8, 9, 2, 3, 10, 11, 4, 5, 12, 13, 6, 7, 14, 15,
0, 1, 8, 9, 2, 3, 10, 11, 4, 5, 12, 13, 6, 7, 14, 15};
void ARGBToUVRow_AVX2(const uint8_t* src_argb0,
int src_stride_argb,
uint8_t* dst_u,
uint8_t* dst_v,
int width) {
asm volatile(
"vbroadcastf128 %5,%%ymm5 \n"
"vbroadcastf128 %6,%%ymm6 \n"
"vbroadcastf128 %7,%%ymm7 \n"
"sub %1,%2 \n"
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm0 \n"
"vmovdqu 0x20(%0),%%ymm1 \n"
"vmovdqu 0x40(%0),%%ymm2 \n"
"vmovdqu 0x60(%0),%%ymm3 \n"
"vpavgb 0x00(%0,%4,1),%%ymm0,%%ymm0 \n"
"vpavgb 0x20(%0,%4,1),%%ymm1,%%ymm1 \n"
"vpavgb 0x40(%0,%4,1),%%ymm2,%%ymm2 \n"
"vpavgb 0x60(%0,%4,1),%%ymm3,%%ymm3 \n"
"lea 0x80(%0),%0 \n"
"vshufps $0x88,%%ymm1,%%ymm0,%%ymm4 \n"
"vshufps $0xdd,%%ymm1,%%ymm0,%%ymm0 \n"
"vpavgb %%ymm4,%%ymm0,%%ymm0 \n"
"vshufps $0x88,%%ymm3,%%ymm2,%%ymm4 \n"
"vshufps $0xdd,%%ymm3,%%ymm2,%%ymm2 \n"
"vpavgb %%ymm4,%%ymm2,%%ymm2 \n"
"vpmaddubsw %%ymm7,%%ymm0,%%ymm1 \n"
"vpmaddubsw %%ymm7,%%ymm2,%%ymm3 \n"
"vpmaddubsw %%ymm6,%%ymm0,%%ymm0 \n"
"vpmaddubsw %%ymm6,%%ymm2,%%ymm2 \n"
"vphaddw %%ymm3,%%ymm1,%%ymm1 \n"
"vphaddw %%ymm2,%%ymm0,%%ymm0 \n"
"vpsraw $0x8,%%ymm1,%%ymm1 \n"
"vpsraw $0x8,%%ymm0,%%ymm0 \n"
"vpacksswb %%ymm0,%%ymm1,%%ymm0 \n"
"vpermq $0xd8,%%ymm0,%%ymm0 \n"
"vpshufb %8,%%ymm0,%%ymm0 \n"
"vpaddb %%ymm5,%%ymm0,%%ymm0 \n"
"vextractf128 $0x0,%%ymm0,(%1) \n"
"vextractf128 $0x1,%%ymm0,0x0(%1,%2,1) \n"
"lea 0x10(%1),%1 \n"
"sub $0x20,%3 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_argb0), // %0
"+r"(dst_u), // %1
"+r"(dst_v), // %2
"+rm"(width) // %3
: "r"((intptr_t)(src_stride_argb)), // %4
"m"(kAddUV128), // %5
"m"(kARGBToV), // %6
"m"(kARGBToU), // %7
"m"(kShufARGBToUV_AVX) // %8
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6",
"xmm7");
}
#endif // HAS_ARGBTOUVROW_AVX2
#ifdef HAS_ABGRTOUVROW_AVX2
void ABGRToUVRow_AVX2(const uint8_t* src_abgr0,
int src_stride_abgr,
uint8_t* dst_u,
uint8_t* dst_v,
int width) {
asm volatile(
"vbroadcastf128 %5,%%ymm5 \n"
"vbroadcastf128 %6,%%ymm6 \n"
"vbroadcastf128 %7,%%ymm7 \n"
"sub %1,%2 \n"
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm0 \n"
"vmovdqu 0x20(%0),%%ymm1 \n"
"vmovdqu 0x40(%0),%%ymm2 \n"
"vmovdqu 0x60(%0),%%ymm3 \n"
"vpavgb 0x00(%0,%4,1),%%ymm0,%%ymm0 \n"
"vpavgb 0x20(%0,%4,1),%%ymm1,%%ymm1 \n"
"vpavgb 0x40(%0,%4,1),%%ymm2,%%ymm2 \n"
"vpavgb 0x60(%0,%4,1),%%ymm3,%%ymm3 \n"
"lea 0x80(%0),%0 \n"
"vshufps $0x88,%%ymm1,%%ymm0,%%ymm4 \n"
"vshufps $0xdd,%%ymm1,%%ymm0,%%ymm0 \n"
"vpavgb %%ymm4,%%ymm0,%%ymm0 \n"
"vshufps $0x88,%%ymm3,%%ymm2,%%ymm4 \n"
"vshufps $0xdd,%%ymm3,%%ymm2,%%ymm2 \n"
"vpavgb %%ymm4,%%ymm2,%%ymm2 \n"
"vpmaddubsw %%ymm7,%%ymm0,%%ymm1 \n"
"vpmaddubsw %%ymm7,%%ymm2,%%ymm3 \n"
"vpmaddubsw %%ymm6,%%ymm0,%%ymm0 \n"
"vpmaddubsw %%ymm6,%%ymm2,%%ymm2 \n"
"vphaddw %%ymm3,%%ymm1,%%ymm1 \n"
"vphaddw %%ymm2,%%ymm0,%%ymm0 \n"
"vpsraw $0x8,%%ymm1,%%ymm1 \n"
"vpsraw $0x8,%%ymm0,%%ymm0 \n"
"vpacksswb %%ymm0,%%ymm1,%%ymm0 \n"
"vpermq $0xd8,%%ymm0,%%ymm0 \n"
"vpshufb %8,%%ymm0,%%ymm0 \n"
"vpaddb %%ymm5,%%ymm0,%%ymm0 \n"
"vextractf128 $0x0,%%ymm0,(%1) \n"
"vextractf128 $0x1,%%ymm0,0x0(%1,%2,1) \n"
"lea 0x10(%1),%1 \n"
"sub $0x20,%3 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_abgr0), // %0
"+r"(dst_u), // %1
"+r"(dst_v), // %2
"+rm"(width) // %3
: "r"((intptr_t)(src_stride_abgr)), // %4
"m"(kAddUV128), // %5
"m"(kABGRToV), // %6
"m"(kABGRToU), // %7
"m"(kShufARGBToUV_AVX) // %8
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6",
"xmm7");
}
#endif // HAS_ABGRTOUVROW_AVX2
#ifdef HAS_ARGBTOUVJROW_AVX2
void ARGBToUVJRow_AVX2(const uint8_t* src_argb0,
int src_stride_argb,
uint8_t* dst_u,
uint8_t* dst_v,
int width) {
asm volatile(
"vbroadcastf128 %5,%%ymm5 \n"
"vbroadcastf128 %6,%%ymm6 \n"
"vbroadcastf128 %7,%%ymm7 \n"
"sub %1,%2 \n"
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm0 \n"
"vmovdqu 0x20(%0),%%ymm1 \n"
"vmovdqu 0x40(%0),%%ymm2 \n"
"vmovdqu 0x60(%0),%%ymm3 \n"
"vpavgb 0x00(%0,%4,1),%%ymm0,%%ymm0 \n"
"vpavgb 0x20(%0,%4,1),%%ymm1,%%ymm1 \n"
"vpavgb 0x40(%0,%4,1),%%ymm2,%%ymm2 \n"
"vpavgb 0x60(%0,%4,1),%%ymm3,%%ymm3 \n"
"lea 0x80(%0),%0 \n"
"vshufps $0x88,%%ymm1,%%ymm0,%%ymm4 \n"
"vshufps $0xdd,%%ymm1,%%ymm0,%%ymm0 \n"
"vpavgb %%ymm4,%%ymm0,%%ymm0 \n"
"vshufps $0x88,%%ymm3,%%ymm2,%%ymm4 \n"
"vshufps $0xdd,%%ymm3,%%ymm2,%%ymm2 \n"
"vpavgb %%ymm4,%%ymm2,%%ymm2 \n"
"vpmaddubsw %%ymm7,%%ymm0,%%ymm1 \n"
"vpmaddubsw %%ymm7,%%ymm2,%%ymm3 \n"
"vpmaddubsw %%ymm6,%%ymm0,%%ymm0 \n"
"vpmaddubsw %%ymm6,%%ymm2,%%ymm2 \n"
"vphaddw %%ymm3,%%ymm1,%%ymm1 \n"
"vphaddw %%ymm2,%%ymm0,%%ymm0 \n"
"vpaddw %%ymm5,%%ymm0,%%ymm0 \n"
"vpaddw %%ymm5,%%ymm1,%%ymm1 \n"
"vpsraw $0x8,%%ymm1,%%ymm1 \n"
"vpsraw $0x8,%%ymm0,%%ymm0 \n"
"vpacksswb %%ymm0,%%ymm1,%%ymm0 \n"
"vpermq $0xd8,%%ymm0,%%ymm0 \n"
"vpshufb %8,%%ymm0,%%ymm0 \n"
"vextractf128 $0x0,%%ymm0,(%1) \n"
"vextractf128 $0x1,%%ymm0,0x0(%1,%2,1) \n"
"lea 0x10(%1),%1 \n"
"sub $0x20,%3 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_argb0), // %0
"+r"(dst_u), // %1
"+r"(dst_v), // %2
"+rm"(width) // %3
: "r"((intptr_t)(src_stride_argb)), // %4
"m"(kSub128), // %5
"m"(kARGBToVJ), // %6
"m"(kARGBToUJ), // %7
"m"(kShufARGBToUV_AVX) // %8
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6",
"xmm7");
}
#endif // HAS_ARGBTOUVJROW_AVX2
#ifdef HAS_ARGBTOUVJROW_SSSE3
void ARGBToUVJRow_SSSE3(const uint8_t* src_argb0,
int src_stride_argb,
uint8_t* dst_u,
uint8_t* dst_v,
int width) {
asm volatile(
"movdqa %5,%%xmm3 \n"
"movdqa %6,%%xmm4 \n"
"movdqa %7,%%xmm5 \n"
"sub %1,%2 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x00(%0,%4,1),%%xmm7 \n"
"pavgb %%xmm7,%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"movdqu 0x10(%0,%4,1),%%xmm7 \n"
"pavgb %%xmm7,%%xmm1 \n"
"movdqu 0x20(%0),%%xmm2 \n"
"movdqu 0x20(%0,%4,1),%%xmm7 \n"
"pavgb %%xmm7,%%xmm2 \n"
"movdqu 0x30(%0),%%xmm6 \n"
"movdqu 0x30(%0,%4,1),%%xmm7 \n"
"pavgb %%xmm7,%%xmm6 \n"
"lea 0x40(%0),%0 \n"
"movdqa %%xmm0,%%xmm7 \n"
"shufps $0x88,%%xmm1,%%xmm0 \n"
"shufps $0xdd,%%xmm1,%%xmm7 \n"
"pavgb %%xmm7,%%xmm0 \n"
"movdqa %%xmm2,%%xmm7 \n"
"shufps $0x88,%%xmm6,%%xmm2 \n"
"shufps $0xdd,%%xmm6,%%xmm7 \n"
"pavgb %%xmm7,%%xmm2 \n"
"movdqa %%xmm0,%%xmm1 \n"
"movdqa %%xmm2,%%xmm6 \n"
"pmaddubsw %%xmm4,%%xmm0 \n"
"pmaddubsw %%xmm4,%%xmm2 \n"
"pmaddubsw %%xmm3,%%xmm1 \n"
"pmaddubsw %%xmm3,%%xmm6 \n"
"phaddw %%xmm2,%%xmm0 \n"
"phaddw %%xmm6,%%xmm1 \n"
"paddw %%xmm5,%%xmm0 \n"
"paddw %%xmm5,%%xmm1 \n"
"psraw $0x8,%%xmm0 \n"
"psraw $0x8,%%xmm1 \n"
"packsswb %%xmm1,%%xmm0 \n"
"movlps %%xmm0,(%1) \n"
"movhps %%xmm0,0x00(%1,%2,1) \n"
"lea 0x8(%1),%1 \n"
"sub $0x10,%3 \n"
"jg 1b \n"
: "+r"(src_argb0), // %0
"+r"(dst_u), // %1
"+r"(dst_v), // %2
"+rm"(width) // %3
: "r"((intptr_t)(src_stride_argb)), // %4
"m"(kARGBToVJ), // %5
"m"(kARGBToUJ), // %6
"m"(kSub128) // %7
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm6", "xmm7");
}
#endif // HAS_ARGBTOUVJROW_SSSE3
#ifdef HAS_ARGBTOUV444ROW_SSSE3
void ARGBToUV444Row_SSSE3(const uint8_t* src_argb,
uint8_t* dst_u,
uint8_t* dst_v,
int width) {
asm volatile(
"movdqa %4,%%xmm3 \n"
"movdqa %5,%%xmm4 \n"
"movdqa %6,%%xmm5 \n"
"sub %1,%2 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"movdqu 0x20(%0),%%xmm2 \n"
"movdqu 0x30(%0),%%xmm6 \n"
"pmaddubsw %%xmm4,%%xmm0 \n"
"pmaddubsw %%xmm4,%%xmm1 \n"
"pmaddubsw %%xmm4,%%xmm2 \n"
"pmaddubsw %%xmm4,%%xmm6 \n"
"phaddw %%xmm1,%%xmm0 \n"
"phaddw %%xmm6,%%xmm2 \n"
"psraw $0x8,%%xmm0 \n"
"psraw $0x8,%%xmm2 \n"
"packsswb %%xmm2,%%xmm0 \n"
"paddb %%xmm5,%%xmm0 \n"
"movdqu %%xmm0,(%1) \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"movdqu 0x20(%0),%%xmm2 \n"
"movdqu 0x30(%0),%%xmm6 \n"
"pmaddubsw %%xmm3,%%xmm0 \n"
"pmaddubsw %%xmm3,%%xmm1 \n"
"pmaddubsw %%xmm3,%%xmm2 \n"
"pmaddubsw %%xmm3,%%xmm6 \n"
"phaddw %%xmm1,%%xmm0 \n"
"phaddw %%xmm6,%%xmm2 \n"
"psraw $0x8,%%xmm0 \n"
"psraw $0x8,%%xmm2 \n"
"packsswb %%xmm2,%%xmm0 \n"
"paddb %%xmm5,%%xmm0 \n"
"lea 0x40(%0),%0 \n"
"movdqu %%xmm0,0x00(%1,%2,1) \n"
"lea 0x10(%1),%1 \n"
"sub $0x10,%3 \n"
"jg 1b \n"
: "+r"(src_argb), // %0
"+r"(dst_u), // %1
"+r"(dst_v), // %2
"+rm"(width) // %3
: "m"(kARGBToV), // %4
"m"(kARGBToU), // %5
"m"(kAddUV128) // %6
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm6");
}
#endif // HAS_ARGBTOUV444ROW_SSSE3
void BGRAToYRow_SSSE3(const uint8_t* src_bgra, uint8_t* dst_y, int width) {
asm volatile(
"movdqa %3,%%xmm4 \n"
"movdqa %4,%%xmm5 \n"
"movdqa %5,%%xmm7 \n"
LABELALIGN RGBTOY(xmm7)
: "+r"(src_bgra), // %0
"+r"(dst_y), // %1
"+r"(width) // %2
: "m"(kBGRAToY), // %3
"m"(kSub128), // %4
"m"(kAddY16) // %5
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6",
"xmm7");
}
void BGRAToUVRow_SSSE3(const uint8_t* src_bgra0,
int src_stride_bgra,
uint8_t* dst_u,
uint8_t* dst_v,
int width) {
asm volatile(
"movdqa %5,%%xmm3 \n"
"movdqa %6,%%xmm4 \n"
"movdqa %7,%%xmm5 \n"
"sub %1,%2 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x00(%0,%4,1),%%xmm7 \n"
"pavgb %%xmm7,%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"movdqu 0x10(%0,%4,1),%%xmm7 \n"
"pavgb %%xmm7,%%xmm1 \n"
"movdqu 0x20(%0),%%xmm2 \n"
"movdqu 0x20(%0,%4,1),%%xmm7 \n"
"pavgb %%xmm7,%%xmm2 \n"
"movdqu 0x30(%0),%%xmm6 \n"
"movdqu 0x30(%0,%4,1),%%xmm7 \n"
"pavgb %%xmm7,%%xmm6 \n"
"lea 0x40(%0),%0 \n"
"movdqa %%xmm0,%%xmm7 \n"
"shufps $0x88,%%xmm1,%%xmm0 \n"
"shufps $0xdd,%%xmm1,%%xmm7 \n"
"pavgb %%xmm7,%%xmm0 \n"
"movdqa %%xmm2,%%xmm7 \n"
"shufps $0x88,%%xmm6,%%xmm2 \n"
"shufps $0xdd,%%xmm6,%%xmm7 \n"
"pavgb %%xmm7,%%xmm2 \n"
"movdqa %%xmm0,%%xmm1 \n"
"movdqa %%xmm2,%%xmm6 \n"
"pmaddubsw %%xmm4,%%xmm0 \n"
"pmaddubsw %%xmm4,%%xmm2 \n"
"pmaddubsw %%xmm3,%%xmm1 \n"
"pmaddubsw %%xmm3,%%xmm6 \n"
"phaddw %%xmm2,%%xmm0 \n"
"phaddw %%xmm6,%%xmm1 \n"
"psraw $0x8,%%xmm0 \n"
"psraw $0x8,%%xmm1 \n"
"packsswb %%xmm1,%%xmm0 \n"
"paddb %%xmm5,%%xmm0 \n"
"movlps %%xmm0,(%1) \n"
"movhps %%xmm0,0x00(%1,%2,1) \n"
"lea 0x8(%1),%1 \n"
"sub $0x10,%3 \n"
"jg 1b \n"
: "+r"(src_bgra0), // %0
"+r"(dst_u), // %1
"+r"(dst_v), // %2
"+rm"(width) // %3
: "r"((intptr_t)(src_stride_bgra)), // %4
"m"(kBGRAToV), // %5
"m"(kBGRAToU), // %6
"m"(kAddUV128) // %7
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm6", "xmm7");
}
void ABGRToYRow_SSSE3(const uint8_t* src_abgr, uint8_t* dst_y, int width) {
asm volatile(
"movdqa %3,%%xmm4 \n"
"movdqa %4,%%xmm5 \n"
"movdqa %5,%%xmm7 \n"
LABELALIGN RGBTOY(xmm7)
: "+r"(src_abgr), // %0
"+r"(dst_y), // %1
"+r"(width) // %2
: "m"(kABGRToY), // %3
"m"(kSub128), // %4
"m"(kAddY16) // %5
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6",
"xmm7");
}
void RGBAToYRow_SSSE3(const uint8_t* src_rgba, uint8_t* dst_y, int width) {
asm volatile(
"movdqa %3,%%xmm4 \n"
"movdqa %4,%%xmm5 \n"
"movdqa %5,%%xmm7 \n"
LABELALIGN RGBTOY(xmm7)
: "+r"(src_rgba), // %0
"+r"(dst_y), // %1
"+r"(width) // %2
: "m"(kRGBAToY), // %3
"m"(kSub128), // %4
"m"(kAddY16) // %5
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6",
"xmm7");
}
void ABGRToUVRow_SSSE3(const uint8_t* src_abgr0,
int src_stride_abgr,
uint8_t* dst_u,
uint8_t* dst_v,
int width) {
asm volatile(
"movdqa %5,%%xmm3 \n"
"movdqa %6,%%xmm4 \n"
"movdqa %7,%%xmm5 \n"
"sub %1,%2 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x00(%0,%4,1),%%xmm7 \n"
"pavgb %%xmm7,%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"movdqu 0x10(%0,%4,1),%%xmm7 \n"
"pavgb %%xmm7,%%xmm1 \n"
"movdqu 0x20(%0),%%xmm2 \n"
"movdqu 0x20(%0,%4,1),%%xmm7 \n"
"pavgb %%xmm7,%%xmm2 \n"
"movdqu 0x30(%0),%%xmm6 \n"
"movdqu 0x30(%0,%4,1),%%xmm7 \n"
"pavgb %%xmm7,%%xmm6 \n"
"lea 0x40(%0),%0 \n"
"movdqa %%xmm0,%%xmm7 \n"
"shufps $0x88,%%xmm1,%%xmm0 \n"
"shufps $0xdd,%%xmm1,%%xmm7 \n"
"pavgb %%xmm7,%%xmm0 \n"
"movdqa %%xmm2,%%xmm7 \n"
"shufps $0x88,%%xmm6,%%xmm2 \n"
"shufps $0xdd,%%xmm6,%%xmm7 \n"
"pavgb %%xmm7,%%xmm2 \n"
"movdqa %%xmm0,%%xmm1 \n"
"movdqa %%xmm2,%%xmm6 \n"
"pmaddubsw %%xmm4,%%xmm0 \n"
"pmaddubsw %%xmm4,%%xmm2 \n"
"pmaddubsw %%xmm3,%%xmm1 \n"
"pmaddubsw %%xmm3,%%xmm6 \n"
"phaddw %%xmm2,%%xmm0 \n"
"phaddw %%xmm6,%%xmm1 \n"
"psraw $0x8,%%xmm0 \n"
"psraw $0x8,%%xmm1 \n"
"packsswb %%xmm1,%%xmm0 \n"
"paddb %%xmm5,%%xmm0 \n"
"movlps %%xmm0,(%1) \n"
"movhps %%xmm0,0x00(%1,%2,1) \n"
"lea 0x8(%1),%1 \n"
"sub $0x10,%3 \n"
"jg 1b \n"
: "+r"(src_abgr0), // %0
"+r"(dst_u), // %1
"+r"(dst_v), // %2
"+rm"(width) // %3
: "r"((intptr_t)(src_stride_abgr)), // %4
"m"(kABGRToV), // %5
"m"(kABGRToU), // %6
"m"(kAddUV128) // %7
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm6", "xmm7");
}
void RGBAToUVRow_SSSE3(const uint8_t* src_rgba0,
int src_stride_rgba,
uint8_t* dst_u,
uint8_t* dst_v,
int width) {
asm volatile(
"movdqa %5,%%xmm3 \n"
"movdqa %6,%%xmm4 \n"
"movdqa %7,%%xmm5 \n"
"sub %1,%2 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x00(%0,%4,1),%%xmm7 \n"
"pavgb %%xmm7,%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"movdqu 0x10(%0,%4,1),%%xmm7 \n"
"pavgb %%xmm7,%%xmm1 \n"
"movdqu 0x20(%0),%%xmm2 \n"
"movdqu 0x20(%0,%4,1),%%xmm7 \n"
"pavgb %%xmm7,%%xmm2 \n"
"movdqu 0x30(%0),%%xmm6 \n"
"movdqu 0x30(%0,%4,1),%%xmm7 \n"
"pavgb %%xmm7,%%xmm6 \n"
"lea 0x40(%0),%0 \n"
"movdqa %%xmm0,%%xmm7 \n"
"shufps $0x88,%%xmm1,%%xmm0 \n"
"shufps $0xdd,%%xmm1,%%xmm7 \n"
"pavgb %%xmm7,%%xmm0 \n"
"movdqa %%xmm2,%%xmm7 \n"
"shufps $0x88,%%xmm6,%%xmm2 \n"
"shufps $0xdd,%%xmm6,%%xmm7 \n"
"pavgb %%xmm7,%%xmm2 \n"
"movdqa %%xmm0,%%xmm1 \n"
"movdqa %%xmm2,%%xmm6 \n"
"pmaddubsw %%xmm4,%%xmm0 \n"
"pmaddubsw %%xmm4,%%xmm2 \n"
"pmaddubsw %%xmm3,%%xmm1 \n"
"pmaddubsw %%xmm3,%%xmm6 \n"
"phaddw %%xmm2,%%xmm0 \n"
"phaddw %%xmm6,%%xmm1 \n"
"psraw $0x8,%%xmm0 \n"
"psraw $0x8,%%xmm1 \n"
"packsswb %%xmm1,%%xmm0 \n"
"paddb %%xmm5,%%xmm0 \n"
"movlps %%xmm0,(%1) \n"
"movhps %%xmm0,0x00(%1,%2,1) \n"
"lea 0x8(%1),%1 \n"
"sub $0x10,%3 \n"
"jg 1b \n"
: "+r"(src_rgba0), // %0
"+r"(dst_u), // %1
"+r"(dst_v), // %2
"+rm"(width) // %3
: "r"((intptr_t)(src_stride_rgba)), // %4
"m"(kRGBAToV), // %5
"m"(kRGBAToU), // %6
"m"(kAddUV128) // %7
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm6", "xmm7");
}
#if defined(HAS_I422TOARGBROW_SSSE3) || defined(HAS_I422TOARGBROW_AVX2)
// Read 8 UV from 444
#define READYUV444 \
"movq (%[u_buf]),%%xmm0 \n" \
"movq 0x00(%[u_buf],%[v_buf],1),%%xmm1 \n" \
"lea 0x8(%[u_buf]),%[u_buf] \n" \
"punpcklbw %%xmm1,%%xmm0 \n" \
"movq (%[y_buf]),%%xmm4 \n" \
"punpcklbw %%xmm4,%%xmm4 \n" \
"lea 0x8(%[y_buf]),%[y_buf] \n"
// Read 4 UV from 422, upsample to 8 UV
#define READYUV422 \
"movd (%[u_buf]),%%xmm0 \n" \
"movd 0x00(%[u_buf],%[v_buf],1),%%xmm1 \n" \
"lea 0x4(%[u_buf]),%[u_buf] \n" \
"punpcklbw %%xmm1,%%xmm0 \n" \
"punpcklwd %%xmm0,%%xmm0 \n" \
"movq (%[y_buf]),%%xmm4 \n" \
"punpcklbw %%xmm4,%%xmm4 \n" \
"lea 0x8(%[y_buf]),%[y_buf] \n"
// Read 4 UV from 422 10 bit, upsample to 8 UV
// TODO(fbarchard): Consider shufb to replace pack/unpack
// TODO(fbarchard): Consider pmulhuw to replace psraw
// TODO(fbarchard): Consider pmullw to replace psllw and allow different bits.
#define READYUV210 \
"movq (%[u_buf]),%%xmm0 \n" \
"movq 0x00(%[u_buf],%[v_buf],1),%%xmm1 \n" \
"lea 0x8(%[u_buf]),%[u_buf] \n" \
"punpcklwd %%xmm1,%%xmm0 \n" \
"psraw $0x2,%%xmm0 \n" \
"packuswb %%xmm0,%%xmm0 \n" \
"punpcklwd %%xmm0,%%xmm0 \n" \
"movdqu (%[y_buf]),%%xmm4 \n" \
"psllw $0x6,%%xmm4 \n" \
"lea 0x10(%[y_buf]),%[y_buf] \n"
// Read 4 UV from 422, upsample to 8 UV. With 8 Alpha.
#define READYUVA422 \
"movd (%[u_buf]),%%xmm0 \n" \
"movd 0x00(%[u_buf],%[v_buf],1),%%xmm1 \n" \
"lea 0x4(%[u_buf]),%[u_buf] \n" \
"punpcklbw %%xmm1,%%xmm0 \n" \
"punpcklwd %%xmm0,%%xmm0 \n" \
"movq (%[y_buf]),%%xmm4 \n" \
"punpcklbw %%xmm4,%%xmm4 \n" \
"lea 0x8(%[y_buf]),%[y_buf] \n" \
"movq (%[a_buf]),%%xmm5 \n" \
"lea 0x8(%[a_buf]),%[a_buf] \n"
// Read 4 UV from NV12, upsample to 8 UV
#define READNV12 \
"movq (%[uv_buf]),%%xmm0 \n" \
"lea 0x8(%[uv_buf]),%[uv_buf] \n" \
"punpcklwd %%xmm0,%%xmm0 \n" \
"movq (%[y_buf]),%%xmm4 \n" \
"punpcklbw %%xmm4,%%xmm4 \n" \
"lea 0x8(%[y_buf]),%[y_buf] \n"
// Read 4 VU from NV21, upsample to 8 UV
#define READNV21 \
"movq (%[vu_buf]),%%xmm0 \n" \
"lea 0x8(%[vu_buf]),%[vu_buf] \n" \
"pshufb %[kShuffleNV21], %%xmm0 \n" \
"movq (%[y_buf]),%%xmm4 \n" \
"punpcklbw %%xmm4,%%xmm4 \n" \
"lea 0x8(%[y_buf]),%[y_buf] \n"
// Read 4 YUY2 with 8 Y and update 4 UV to 8 UV.
#define READYUY2 \
"movdqu (%[yuy2_buf]),%%xmm4 \n" \
"pshufb %[kShuffleYUY2Y], %%xmm4 \n" \
"movdqu (%[yuy2_buf]),%%xmm0 \n" \
"pshufb %[kShuffleYUY2UV], %%xmm0 \n" \
"lea 0x10(%[yuy2_buf]),%[yuy2_buf] \n"
// Read 4 UYVY with 8 Y and update 4 UV to 8 UV.
#define READUYVY \
"movdqu (%[uyvy_buf]),%%xmm4 \n" \
"pshufb %[kShuffleUYVYY], %%xmm4 \n" \
"movdqu (%[uyvy_buf]),%%xmm0 \n" \
"pshufb %[kShuffleUYVYUV], %%xmm0 \n" \
"lea 0x10(%[uyvy_buf]),%[uyvy_buf] \n"
#if defined(__x86_64__)
#define YUVTORGB_SETUP(yuvconstants) \
"movdqa (%[yuvconstants]),%%xmm8 \n" \
"movdqa 32(%[yuvconstants]),%%xmm9 \n" \
"movdqa 64(%[yuvconstants]),%%xmm10 \n" \
"movdqa 96(%[yuvconstants]),%%xmm11 \n" \
"movdqa 128(%[yuvconstants]),%%xmm12 \n" \
"movdqa 160(%[yuvconstants]),%%xmm13 \n" \
"movdqa 192(%[yuvconstants]),%%xmm14 \n"
// Convert 8 pixels: 8 UV and 8 Y
#define YUVTORGB16(yuvconstants) \
"movdqa %%xmm0,%%xmm1 \n" \
"movdqa %%xmm0,%%xmm2 \n" \
"movdqa %%xmm0,%%xmm3 \n" \
"movdqa %%xmm11,%%xmm0 \n" \
"pmaddubsw %%xmm8,%%xmm1 \n" \
"psubw %%xmm1,%%xmm0 \n" \
"movdqa %%xmm12,%%xmm1 \n" \
"pmaddubsw %%xmm9,%%xmm2 \n" \
"psubw %%xmm2,%%xmm1 \n" \
"movdqa %%xmm13,%%xmm2 \n" \
"pmaddubsw %%xmm10,%%xmm3 \n" \
"psubw %%xmm3,%%xmm2 \n" \
"pmulhuw %%xmm14,%%xmm4 \n" \
"paddsw %%xmm4,%%xmm0 \n" \
"paddsw %%xmm4,%%xmm1 \n" \
"paddsw %%xmm4,%%xmm2 \n"
#define YUVTORGB_REGS \
"xmm8", "xmm9", "xmm10", "xmm11", "xmm12", "xmm13", "xmm14",
#else
#define YUVTORGB_SETUP(yuvconstants)
// Convert 8 pixels: 8 UV and 8 Y
#define YUVTORGB16(yuvconstants) \
"movdqa %%xmm0,%%xmm1 \n" \
"movdqa %%xmm0,%%xmm2 \n" \
"movdqa %%xmm0,%%xmm3 \n" \
"movdqa 96(%[yuvconstants]),%%xmm0 \n" \
"pmaddubsw (%[yuvconstants]),%%xmm1 \n" \
"psubw %%xmm1,%%xmm0 \n" \
"movdqa 128(%[yuvconstants]),%%xmm1 \n" \
"pmaddubsw 32(%[yuvconstants]),%%xmm2 \n" \
"psubw %%xmm2,%%xmm1 \n" \
"movdqa 160(%[yuvconstants]),%%xmm2 \n" \
"pmaddubsw 64(%[yuvconstants]),%%xmm3 \n" \
"psubw %%xmm3,%%xmm2 \n" \
"pmulhuw 192(%[yuvconstants]),%%xmm4 \n" \
"paddsw %%xmm4,%%xmm0 \n" \
"paddsw %%xmm4,%%xmm1 \n" \
"paddsw %%xmm4,%%xmm2 \n"
#define YUVTORGB_REGS
#endif
#define YUVTORGB(yuvconstants) \
YUVTORGB16(yuvconstants) \
"psraw $0x6,%%xmm0 \n" \
"psraw $0x6,%%xmm1 \n" \
"psraw $0x6,%%xmm2 \n" \
"packuswb %%xmm0,%%xmm0 \n" \
"packuswb %%xmm1,%%xmm1 \n" \
"packuswb %%xmm2,%%xmm2 \n"
// Store 8 ARGB values.
#define STOREARGB \
"punpcklbw %%xmm1,%%xmm0 \n" \
"punpcklbw %%xmm5,%%xmm2 \n" \
"movdqa %%xmm0,%%xmm1 \n" \
"punpcklwd %%xmm2,%%xmm0 \n" \
"punpckhwd %%xmm2,%%xmm1 \n" \
"movdqu %%xmm0,(%[dst_argb]) \n" \
"movdqu %%xmm1,0x10(%[dst_argb]) \n" \
"lea 0x20(%[dst_argb]), %[dst_argb] \n"
// Store 8 RGBA values.
#define STORERGBA \
"pcmpeqb %%xmm5,%%xmm5 \n" \
"punpcklbw %%xmm2,%%xmm1 \n" \
"punpcklbw %%xmm0,%%xmm5 \n" \
"movdqa %%xmm5,%%xmm0 \n" \
"punpcklwd %%xmm1,%%xmm5 \n" \
"punpckhwd %%xmm1,%%xmm0 \n" \
"movdqu %%xmm5,(%[dst_rgba]) \n" \
"movdqu %%xmm0,0x10(%[dst_rgba]) \n" \
"lea 0x20(%[dst_rgba]),%[dst_rgba] \n"
// Store 8 AR30 values.
#define STOREAR30 \
"psraw $0x4,%%xmm0 \n" \
"psraw $0x4,%%xmm1 \n" \
"psraw $0x4,%%xmm2 \n" \
"pminsw %%xmm7,%%xmm0 \n" \
"pminsw %%xmm7,%%xmm1 \n" \
"pminsw %%xmm7,%%xmm2 \n" \
"pmaxsw %%xmm6,%%xmm0 \n" \
"pmaxsw %%xmm6,%%xmm1 \n" \
"pmaxsw %%xmm6,%%xmm2 \n" \
"psllw $0x4,%%xmm2 \n" \
"movdqa %%xmm0,%%xmm3 \n" \
"punpcklwd %%xmm2,%%xmm0 \n" \
"punpckhwd %%xmm2,%%xmm3 \n" \
"movdqa %%xmm1,%%xmm2 \n" \
"punpcklwd %%xmm5,%%xmm1 \n" \
"punpckhwd %%xmm5,%%xmm2 \n" \
"pslld $0xa,%%xmm1 \n" \
"pslld $0xa,%%xmm2 \n" \
"por %%xmm1,%%xmm0 \n" \
"por %%xmm2,%%xmm3 \n" \
"movdqu %%xmm0,(%[dst_ar30]) \n" \
"movdqu %%xmm3,0x10(%[dst_ar30]) \n" \
"lea 0x20(%[dst_ar30]), %[dst_ar30] \n"
void OMITFP I444ToARGBRow_SSSE3(const uint8_t* y_buf,
const uint8_t* u_buf,
const uint8_t* v_buf,
uint8_t* dst_argb,
const struct YuvConstants* yuvconstants,
int width) {
asm volatile (
YUVTORGB_SETUP(yuvconstants)
"sub %[u_buf],%[v_buf] \n"
"pcmpeqb %%xmm5,%%xmm5 \n"
LABELALIGN
"1: \n"
READYUV444
YUVTORGB(yuvconstants)
STOREARGB
"sub $0x8,%[width] \n"
"jg 1b \n"
: [y_buf]"+r"(y_buf), // %[y_buf]
[u_buf]"+r"(u_buf), // %[u_buf]
[v_buf]"+r"(v_buf), // %[v_buf]
[dst_argb]"+r"(dst_argb), // %[dst_argb]
[width]"+rm"(width) // %[width]
: [yuvconstants]"r"(yuvconstants) // %[yuvconstants]
: "memory", "cc", YUVTORGB_REGS
"xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5"
);
}
void OMITFP I422ToRGB24Row_SSSE3(const uint8_t* y_buf,
const uint8_t* u_buf,
const uint8_t* v_buf,
uint8_t* dst_rgb24,
const struct YuvConstants* yuvconstants,
int width) {
asm volatile (
YUVTORGB_SETUP(yuvconstants)
"movdqa %[kShuffleMaskARGBToRGB24_0],%%xmm5 \n"
"movdqa %[kShuffleMaskARGBToRGB24],%%xmm6 \n"
"sub %[u_buf],%[v_buf] \n"
LABELALIGN
"1: \n"
READYUV422
YUVTORGB(yuvconstants)
"punpcklbw %%xmm1,%%xmm0 \n"
"punpcklbw %%xmm2,%%xmm2 \n"
"movdqa %%xmm0,%%xmm1 \n"
"punpcklwd %%xmm2,%%xmm0 \n"
"punpckhwd %%xmm2,%%xmm1 \n"
"pshufb %%xmm5,%%xmm0 \n"
"pshufb %%xmm6,%%xmm1 \n"
"palignr $0xc,%%xmm0,%%xmm1 \n"
"movq %%xmm0,(%[dst_rgb24]) \n"
"movdqu %%xmm1,0x8(%[dst_rgb24]) \n"
"lea 0x18(%[dst_rgb24]),%[dst_rgb24] \n"
"subl $0x8,%[width] \n"
"jg 1b \n"
: [y_buf]"+r"(y_buf), // %[y_buf]
[u_buf]"+r"(u_buf), // %[u_buf]
[v_buf]"+r"(v_buf), // %[v_buf]
[dst_rgb24]"+r"(dst_rgb24), // %[dst_rgb24]
#if defined(__i386__)
[width]"+m"(width) // %[width]
#else
[width]"+rm"(width) // %[width]
#endif
: [yuvconstants]"r"(yuvconstants), // %[yuvconstants]
[kShuffleMaskARGBToRGB24_0]"m"(kShuffleMaskARGBToRGB24_0),
[kShuffleMaskARGBToRGB24]"m"(kShuffleMaskARGBToRGB24)
: "memory", "cc", YUVTORGB_REGS
"xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6"
);
}
void OMITFP I422ToARGBRow_SSSE3(const uint8_t* y_buf,
const uint8_t* u_buf,
const uint8_t* v_buf,
uint8_t* dst_argb,
const struct YuvConstants* yuvconstants,
int width) {
asm volatile (
YUVTORGB_SETUP(yuvconstants)
"sub %[u_buf],%[v_buf] \n"
"pcmpeqb %%xmm5,%%xmm5 \n"
LABELALIGN
"1: \n"
READYUV422
YUVTORGB(yuvconstants)
STOREARGB
"sub $0x8,%[width] \n"
"jg 1b \n"
: [y_buf]"+r"(y_buf), // %[y_buf]
[u_buf]"+r"(u_buf), // %[u_buf]
[v_buf]"+r"(v_buf), // %[v_buf]
[dst_argb]"+r"(dst_argb), // %[dst_argb]
[width]"+rm"(width) // %[width]
: [yuvconstants]"r"(yuvconstants) // %[yuvconstants]
: "memory", "cc", YUVTORGB_REGS
"xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5"
);
}
void OMITFP I422ToAR30Row_SSSE3(const uint8_t* y_buf,
const uint8_t* u_buf,
const uint8_t* v_buf,
uint8_t* dst_ar30,
const struct YuvConstants* yuvconstants,
int width) {
asm volatile (
YUVTORGB_SETUP(yuvconstants)
"sub %[u_buf],%[v_buf] \n"
"pcmpeqb %%xmm5,%%xmm5 \n" // AR30 constants
"psrlw $14,%%xmm5 \n"
"psllw $4,%%xmm5 \n" // 2 alpha bits
"pxor %%xmm6,%%xmm6 \n"
"pcmpeqb %%xmm7,%%xmm7 \n" // 0 for min
"psrlw $6,%%xmm7 \n" // 1023 for max
LABELALIGN
"1: \n"
READYUV422
YUVTORGB16(yuvconstants)
STOREAR30
"sub $0x8,%[width] \n"
"jg 1b \n"
: [y_buf]"+r"(y_buf), // %[y_buf]
[u_buf]"+r"(u_buf), // %[u_buf]
[v_buf]"+r"(v_buf), // %[v_buf]
[dst_ar30]"+r"(dst_ar30), // %[dst_ar30]
[width]"+rm"(width) // %[width]
: [yuvconstants]"r"(yuvconstants) // %[yuvconstants]
: "memory", "cc", YUVTORGB_REGS
"xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7"
);
}
// 10 bit YUV to ARGB
void OMITFP I210ToARGBRow_SSSE3(const uint16_t* y_buf,
const uint16_t* u_buf,
const uint16_t* v_buf,
uint8_t* dst_argb,
const struct YuvConstants* yuvconstants,
int width) {
asm volatile (
YUVTORGB_SETUP(yuvconstants)
"sub %[u_buf],%[v_buf] \n"
"pcmpeqb %%xmm5,%%xmm5 \n"
LABELALIGN
"1: \n"
READYUV210
YUVTORGB(yuvconstants)
STOREARGB
"sub $0x8,%[width] \n"
"jg 1b \n"
: [y_buf]"+r"(y_buf), // %[y_buf]
[u_buf]"+r"(u_buf), // %[u_buf]
[v_buf]"+r"(v_buf), // %[v_buf]
[dst_argb]"+r"(dst_argb), // %[dst_argb]
[width]"+rm"(width) // %[width]
: [yuvconstants]"r"(yuvconstants) // %[yuvconstants]
: "memory", "cc", YUVTORGB_REGS
"xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5"
);
}
// 10 bit YUV to AR30
void OMITFP I210ToAR30Row_SSSE3(const uint16_t* y_buf,
const uint16_t* u_buf,
const uint16_t* v_buf,
uint8_t* dst_ar30,
const struct YuvConstants* yuvconstants,
int width) {
asm volatile (
YUVTORGB_SETUP(yuvconstants)
"sub %[u_buf],%[v_buf] \n"
"pcmpeqb %%xmm5,%%xmm5 \n"
"psrlw $14,%%xmm5 \n"
"psllw $4,%%xmm5 \n" // 2 alpha bits
"pxor %%xmm6,%%xmm6 \n"
"pcmpeqb %%xmm7,%%xmm7 \n" // 0 for min
"psrlw $6,%%xmm7 \n" // 1023 for max
LABELALIGN
"1: \n"
READYUV210
YUVTORGB16(yuvconstants)
STOREAR30
"sub $0x8,%[width] \n"
"jg 1b \n"
: [y_buf]"+r"(y_buf), // %[y_buf]
[u_buf]"+r"(u_buf), // %[u_buf]
[v_buf]"+r"(v_buf), // %[v_buf]
[dst_ar30]"+r"(dst_ar30), // %[dst_ar30]
[width]"+rm"(width) // %[width]
: [yuvconstants]"r"(yuvconstants) // %[yuvconstants]
: "memory", "cc", YUVTORGB_REGS
"xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7"
);
}
#ifdef HAS_I422ALPHATOARGBROW_SSSE3
void OMITFP I422AlphaToARGBRow_SSSE3(const uint8_t* y_buf,
const uint8_t* u_buf,
const uint8_t* v_buf,
const uint8_t* a_buf,
uint8_t* dst_argb,
const struct YuvConstants* yuvconstants,
int width) {
// clang-format off
asm volatile (
YUVTORGB_SETUP(yuvconstants)
"sub %[u_buf],%[v_buf] \n"
LABELALIGN
"1: \n"
READYUVA422
YUVTORGB(yuvconstants)
STOREARGB
"subl $0x8,%[width] \n"
"jg 1b \n"
: [y_buf]"+r"(y_buf), // %[y_buf]
[u_buf]"+r"(u_buf), // %[u_buf]
[v_buf]"+r"(v_buf), // %[v_buf]
[a_buf]"+r"(a_buf), // %[a_buf]
[dst_argb]"+r"(dst_argb), // %[dst_argb]
#if defined(__i386__)
[width]"+m"(width) // %[width]
#else
[width]"+rm"(width) // %[width]
#endif
: [yuvconstants]"r"(yuvconstants) // %[yuvconstants]
: "memory", "cc", YUVTORGB_REGS
"xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5"
);
// clang-format on
}
#endif // HAS_I422ALPHATOARGBROW_SSSE3
void OMITFP NV12ToARGBRow_SSSE3(const uint8_t* y_buf,
const uint8_t* uv_buf,
uint8_t* dst_argb,
const struct YuvConstants* yuvconstants,
int width) {
// clang-format off
asm volatile (
YUVTORGB_SETUP(yuvconstants)
"pcmpeqb %%xmm5,%%xmm5 \n"
LABELALIGN
"1: \n"
READNV12
YUVTORGB(yuvconstants)
STOREARGB
"sub $0x8,%[width] \n"
"jg 1b \n"
: [y_buf]"+r"(y_buf), // %[y_buf]
[uv_buf]"+r"(uv_buf), // %[uv_buf]
[dst_argb]"+r"(dst_argb), // %[dst_argb]
[width]"+rm"(width) // %[width]
: [yuvconstants]"r"(yuvconstants) // %[yuvconstants]
: "memory", "cc", YUVTORGB_REGS
"xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5"
);
// clang-format on
}
void OMITFP NV21ToARGBRow_SSSE3(const uint8_t* y_buf,
const uint8_t* vu_buf,
uint8_t* dst_argb,
const struct YuvConstants* yuvconstants,
int width) {
// clang-format off
asm volatile (
YUVTORGB_SETUP(yuvconstants)
"pcmpeqb %%xmm5,%%xmm5 \n"
LABELALIGN
"1: \n"
READNV21
YUVTORGB(yuvconstants)
STOREARGB
"sub $0x8,%[width] \n"
"jg 1b \n"
: [y_buf]"+r"(y_buf), // %[y_buf]
[vu_buf]"+r"(vu_buf), // %[vu_buf]
[dst_argb]"+r"(dst_argb), // %[dst_argb]
[width]"+rm"(width) // %[width]
: [yuvconstants]"r"(yuvconstants), // %[yuvconstants]
[kShuffleNV21]"m"(kShuffleNV21)
: "memory", "cc", YUVTORGB_REGS
"xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5"
);
// clang-format on
}
void OMITFP YUY2ToARGBRow_SSSE3(const uint8_t* yuy2_buf,
uint8_t* dst_argb,
const struct YuvConstants* yuvconstants,
int width) {
// clang-format off
asm volatile (
YUVTORGB_SETUP(yuvconstants)
"pcmpeqb %%xmm5,%%xmm5 \n"
LABELALIGN
"1: \n"
READYUY2
YUVTORGB(yuvconstants)
STOREARGB
"sub $0x8,%[width] \n"
"jg 1b \n"
: [yuy2_buf]"+r"(yuy2_buf), // %[yuy2_buf]
[dst_argb]"+r"(dst_argb), // %[dst_argb]
[width]"+rm"(width) // %[width]
: [yuvconstants]"r"(yuvconstants), // %[yuvconstants]
[kShuffleYUY2Y]"m"(kShuffleYUY2Y),
[kShuffleYUY2UV]"m"(kShuffleYUY2UV)
: "memory", "cc", YUVTORGB_REGS
"xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5"
);
// clang-format on
}
void OMITFP UYVYToARGBRow_SSSE3(const uint8_t* uyvy_buf,
uint8_t* dst_argb,
const struct YuvConstants* yuvconstants,
int width) {
// clang-format off
asm volatile (
YUVTORGB_SETUP(yuvconstants)
"pcmpeqb %%xmm5,%%xmm5 \n"
LABELALIGN
"1: \n"
READUYVY
YUVTORGB(yuvconstants)
STOREARGB
"sub $0x8,%[width] \n"
"jg 1b \n"
: [uyvy_buf]"+r"(uyvy_buf), // %[uyvy_buf]
[dst_argb]"+r"(dst_argb), // %[dst_argb]
[width]"+rm"(width) // %[width]
: [yuvconstants]"r"(yuvconstants), // %[yuvconstants]
[kShuffleUYVYY]"m"(kShuffleUYVYY),
[kShuffleUYVYUV]"m"(kShuffleUYVYUV)
: "memory", "cc", YUVTORGB_REGS
"xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5"
);
// clang-format on
}
void OMITFP I422ToRGBARow_SSSE3(const uint8_t* y_buf,
const uint8_t* u_buf,
const uint8_t* v_buf,
uint8_t* dst_rgba,
const struct YuvConstants* yuvconstants,
int width) {
asm volatile (
YUVTORGB_SETUP(yuvconstants)
"sub %[u_buf],%[v_buf] \n"
"pcmpeqb %%xmm5,%%xmm5 \n"
LABELALIGN
"1: \n"
READYUV422
YUVTORGB(yuvconstants)
STORERGBA
"sub $0x8,%[width] \n"
"jg 1b \n"
: [y_buf]"+r"(y_buf), // %[y_buf]
[u_buf]"+r"(u_buf), // %[u_buf]
[v_buf]"+r"(v_buf), // %[v_buf]
[dst_rgba]"+r"(dst_rgba), // %[dst_rgba]
[width]"+rm"(width) // %[width]
: [yuvconstants]"r"(yuvconstants) // %[yuvconstants]
: "memory", "cc", YUVTORGB_REGS
"xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5"
);
}
#endif // HAS_I422TOARGBROW_SSSE3
// Read 16 UV from 444
#define READYUV444_AVX2 \
"vmovdqu (%[u_buf]),%%xmm0 \n" \
"vmovdqu 0x00(%[u_buf],%[v_buf],1),%%xmm1 \n" \
"lea 0x10(%[u_buf]),%[u_buf] \n" \
"vpermq $0xd8,%%ymm0,%%ymm0 \n" \
"vpermq $0xd8,%%ymm1,%%ymm1 \n" \
"vpunpcklbw %%ymm1,%%ymm0,%%ymm0 \n" \
"vmovdqu (%[y_buf]),%%xmm4 \n" \
"vpermq $0xd8,%%ymm4,%%ymm4 \n" \
"vpunpcklbw %%ymm4,%%ymm4,%%ymm4 \n" \
"lea 0x10(%[y_buf]),%[y_buf] \n"
// Read 8 UV from 422, upsample to 16 UV.
#define READYUV422_AVX2 \
"vmovq (%[u_buf]),%%xmm0 \n" \
"vmovq 0x00(%[u_buf],%[v_buf],1),%%xmm1 \n" \
"lea 0x8(%[u_buf]),%[u_buf] \n" \
"vpunpcklbw %%ymm1,%%ymm0,%%ymm0 \n" \
"vpermq $0xd8,%%ymm0,%%ymm0 \n" \
"vpunpcklwd %%ymm0,%%ymm0,%%ymm0 \n" \
"vmovdqu (%[y_buf]),%%xmm4 \n" \
"vpermq $0xd8,%%ymm4,%%ymm4 \n" \
"vpunpcklbw %%ymm4,%%ymm4,%%ymm4 \n" \
"lea 0x10(%[y_buf]),%[y_buf] \n"
// Read 8 UV from 210 10 bit, upsample to 16 UV
// TODO(fbarchard): Consider vshufb to replace pack/unpack
// TODO(fbarchard): Consider vunpcklpd to combine the 2 registers into 1.
#define READYUV210_AVX2 \
"vmovdqu (%[u_buf]),%%xmm0 \n" \
"vmovdqu 0x00(%[u_buf],%[v_buf],1),%%xmm1 \n" \
"lea 0x10(%[u_buf]),%[u_buf] \n" \
"vpermq $0xd8,%%ymm0,%%ymm0 \n" \
"vpermq $0xd8,%%ymm1,%%ymm1 \n" \
"vpunpcklwd %%ymm1,%%ymm0,%%ymm0 \n" \
"vpsraw $0x2,%%ymm0,%%ymm0 \n" \
"vpackuswb %%ymm0,%%ymm0,%%ymm0 \n" \
"vpunpcklwd %%ymm0,%%ymm0,%%ymm0 \n" \
"vmovdqu (%[y_buf]),%%ymm4 \n" \
"vpsllw $0x6,%%ymm4,%%ymm4 \n" \
"lea 0x20(%[y_buf]),%[y_buf] \n"
// Read 8 UV from 422, upsample to 16 UV. With 16 Alpha.
#define READYUVA422_AVX2 \
"vmovq (%[u_buf]),%%xmm0 \n" \
"vmovq 0x00(%[u_buf],%[v_buf],1),%%xmm1 \n" \
"lea 0x8(%[u_buf]),%[u_buf] \n" \
"vpunpcklbw %%ymm1,%%ymm0,%%ymm0 \n" \
"vpermq $0xd8,%%ymm0,%%ymm0 \n" \
"vpunpcklwd %%ymm0,%%ymm0,%%ymm0 \n" \
"vmovdqu (%[y_buf]),%%xmm4 \n" \
"vpermq $0xd8,%%ymm4,%%ymm4 \n" \
"vpunpcklbw %%ymm4,%%ymm4,%%ymm4 \n" \
"lea 0x10(%[y_buf]),%[y_buf] \n" \
"vmovdqu (%[a_buf]),%%xmm5 \n" \
"vpermq $0xd8,%%ymm5,%%ymm5 \n" \
"lea 0x10(%[a_buf]),%[a_buf] \n"
// Read 8 UV from NV12, upsample to 16 UV.
#define READNV12_AVX2 \
"vmovdqu (%[uv_buf]),%%xmm0 \n" \
"lea 0x10(%[uv_buf]),%[uv_buf] \n" \
"vpermq $0xd8,%%ymm0,%%ymm0 \n" \
"vpunpcklwd %%ymm0,%%ymm0,%%ymm0 \n" \
"vmovdqu (%[y_buf]),%%xmm4 \n" \
"vpermq $0xd8,%%ymm4,%%ymm4 \n" \
"vpunpcklbw %%ymm4,%%ymm4,%%ymm4 \n" \
"lea 0x10(%[y_buf]),%[y_buf] \n"
// Read 8 VU from NV21, upsample to 16 UV.
#define READNV21_AVX2 \
"vmovdqu (%[vu_buf]),%%xmm0 \n" \
"lea 0x10(%[vu_buf]),%[vu_buf] \n" \
"vpermq $0xd8,%%ymm0,%%ymm0 \n" \
"vpshufb %[kShuffleNV21], %%ymm0, %%ymm0 \n" \
"vmovdqu (%[y_buf]),%%xmm4 \n" \
"vpermq $0xd8,%%ymm4,%%ymm4 \n" \
"vpunpcklbw %%ymm4,%%ymm4,%%ymm4 \n" \
"lea 0x10(%[y_buf]),%[y_buf] \n"
// Read 8 YUY2 with 16 Y and upsample 8 UV to 16 UV.
#define READYUY2_AVX2 \
"vmovdqu (%[yuy2_buf]),%%ymm4 \n" \
"vpshufb %[kShuffleYUY2Y], %%ymm4, %%ymm4 \n" \
"vmovdqu (%[yuy2_buf]),%%ymm0 \n" \
"vpshufb %[kShuffleYUY2UV], %%ymm0, %%ymm0 \n" \
"lea 0x20(%[yuy2_buf]),%[yuy2_buf] \n"
// Read 8 UYVY with 16 Y and upsample 8 UV to 16 UV.
#define READUYVY_AVX2 \
"vmovdqu (%[uyvy_buf]),%%ymm4 \n" \
"vpshufb %[kShuffleUYVYY], %%ymm4, %%ymm4 \n" \
"vmovdqu (%[uyvy_buf]),%%ymm0 \n" \
"vpshufb %[kShuffleUYVYUV], %%ymm0, %%ymm0 \n" \
"lea 0x20(%[uyvy_buf]),%[uyvy_buf] \n"
#if defined(__x86_64__)
#define YUVTORGB_SETUP_AVX2(yuvconstants) \
"vmovdqa (%[yuvconstants]),%%ymm8 \n" \
"vmovdqa 32(%[yuvconstants]),%%ymm9 \n" \
"vmovdqa 64(%[yuvconstants]),%%ymm10 \n" \
"vmovdqa 96(%[yuvconstants]),%%ymm11 \n" \
"vmovdqa 128(%[yuvconstants]),%%ymm12 \n" \
"vmovdqa 160(%[yuvconstants]),%%ymm13 \n" \
"vmovdqa 192(%[yuvconstants]),%%ymm14 \n"
#define YUVTORGB16_AVX2(yuvconstants) \
"vpmaddubsw %%ymm10,%%ymm0,%%ymm2 \n" \
"vpmaddubsw %%ymm9,%%ymm0,%%ymm1 \n" \
"vpmaddubsw %%ymm8,%%ymm0,%%ymm0 \n" \
"vpsubw %%ymm2,%%ymm13,%%ymm2 \n" \
"vpsubw %%ymm1,%%ymm12,%%ymm1 \n" \
"vpsubw %%ymm0,%%ymm11,%%ymm0 \n" \
"vpmulhuw %%ymm14,%%ymm4,%%ymm4 \n" \
"vpaddsw %%ymm4,%%ymm0,%%ymm0 \n" \
"vpaddsw %%ymm4,%%ymm1,%%ymm1 \n" \
"vpaddsw %%ymm4,%%ymm2,%%ymm2 \n"
#define YUVTORGB_REGS_AVX2 \
"xmm8", "xmm9", "xmm10", "xmm11", "xmm12", "xmm13", "xmm14",
#else // Convert 16 pixels: 16 UV and 16 Y.
#define YUVTORGB_SETUP_AVX2(yuvconstants)
#define YUVTORGB16_AVX2(yuvconstants) \
"vpmaddubsw 64(%[yuvconstants]),%%ymm0,%%ymm2 \n" \
"vpmaddubsw 32(%[yuvconstants]),%%ymm0,%%ymm1 \n" \
"vpmaddubsw (%[yuvconstants]),%%ymm0,%%ymm0 \n" \
"vmovdqu 160(%[yuvconstants]),%%ymm3 \n" \
"vpsubw %%ymm2,%%ymm3,%%ymm2 \n" \
"vmovdqu 128(%[yuvconstants]),%%ymm3 \n" \
"vpsubw %%ymm1,%%ymm3,%%ymm1 \n" \
"vmovdqu 96(%[yuvconstants]),%%ymm3 \n" \
"vpsubw %%ymm0,%%ymm3,%%ymm0 \n" \
"vpmulhuw 192(%[yuvconstants]),%%ymm4,%%ymm4 \n" \
"vpaddsw %%ymm4,%%ymm0,%%ymm0 \n" \
"vpaddsw %%ymm4,%%ymm1,%%ymm1 \n" \
"vpaddsw %%ymm4,%%ymm2,%%ymm2 \n"
#define YUVTORGB_REGS_AVX2
#endif
#define YUVTORGB_AVX2(yuvconstants) \
YUVTORGB16_AVX2(yuvconstants) \
"vpsraw $0x6,%%ymm0,%%ymm0 \n" \
"vpsraw $0x6,%%ymm1,%%ymm1 \n" \
"vpsraw $0x6,%%ymm2,%%ymm2 \n" \
"vpackuswb %%ymm0,%%ymm0,%%ymm0 \n" \
"vpackuswb %%ymm1,%%ymm1,%%ymm1 \n" \
"vpackuswb %%ymm2,%%ymm2,%%ymm2 \n"
// Store 16 ARGB values.
#define STOREARGB_AVX2 \
"vpunpcklbw %%ymm1,%%ymm0,%%ymm0 \n" \
"vpermq $0xd8,%%ymm0,%%ymm0 \n" \
"vpunpcklbw %%ymm5,%%ymm2,%%ymm2 \n" \
"vpermq $0xd8,%%ymm2,%%ymm2 \n" \
"vpunpcklwd %%ymm2,%%ymm0,%%ymm1 \n" \
"vpunpckhwd %%ymm2,%%ymm0,%%ymm0 \n" \
"vmovdqu %%ymm1,(%[dst_argb]) \n" \
"vmovdqu %%ymm0,0x20(%[dst_argb]) \n" \
"lea 0x40(%[dst_argb]), %[dst_argb] \n"
// Store 16 AR30 values.
#define STOREAR30_AVX2 \
"vpsraw $0x4,%%ymm0,%%ymm0 \n" \
"vpsraw $0x4,%%ymm1,%%ymm1 \n" \
"vpsraw $0x4,%%ymm2,%%ymm2 \n" \
"vpminsw %%ymm7,%%ymm0,%%ymm0 \n" \
"vpminsw %%ymm7,%%ymm1,%%ymm1 \n" \
"vpminsw %%ymm7,%%ymm2,%%ymm2 \n" \
"vpmaxsw %%ymm6,%%ymm0,%%ymm0 \n" \
"vpmaxsw %%ymm6,%%ymm1,%%ymm1 \n" \
"vpmaxsw %%ymm6,%%ymm2,%%ymm2 \n" \
"vpsllw $0x4,%%ymm2,%%ymm2 \n" \
"vpermq $0xd8,%%ymm0,%%ymm0 \n" \
"vpermq $0xd8,%%ymm1,%%ymm1 \n" \
"vpermq $0xd8,%%ymm2,%%ymm2 \n" \
"vpunpckhwd %%ymm2,%%ymm0,%%ymm3 \n" \
"vpunpcklwd %%ymm2,%%ymm0,%%ymm0 \n" \
"vpunpckhwd %%ymm5,%%ymm1,%%ymm2 \n" \
"vpunpcklwd %%ymm5,%%ymm1,%%ymm1 \n" \
"vpslld $0xa,%%ymm1,%%ymm1 \n" \
"vpslld $0xa,%%ymm2,%%ymm2 \n" \
"vpor %%ymm1,%%ymm0,%%ymm0 \n" \
"vpor %%ymm2,%%ymm3,%%ymm3 \n" \
"vmovdqu %%ymm0,(%[dst_ar30]) \n" \
"vmovdqu %%ymm3,0x20(%[dst_ar30]) \n" \
"lea 0x40(%[dst_ar30]), %[dst_ar30] \n"
#ifdef HAS_I444TOARGBROW_AVX2
// 16 pixels
// 16 UV values with 16 Y producing 16 ARGB (64 bytes).
void OMITFP I444ToARGBRow_AVX2(const uint8_t* y_buf,
const uint8_t* u_buf,
const uint8_t* v_buf,
uint8_t* dst_argb,
const struct YuvConstants* yuvconstants,
int width) {
asm volatile (
YUVTORGB_SETUP_AVX2(yuvconstants)
"sub %[u_buf],%[v_buf] \n"
"vpcmpeqb %%ymm5,%%ymm5,%%ymm5 \n"
LABELALIGN
"1: \n"
READYUV444_AVX2
YUVTORGB_AVX2(yuvconstants)
STOREARGB_AVX2
"sub $0x10,%[width] \n"
"jg 1b \n"
"vzeroupper \n"
: [y_buf]"+r"(y_buf), // %[y_buf]
[u_buf]"+r"(u_buf), // %[u_buf]
[v_buf]"+r"(v_buf), // %[v_buf]
[dst_argb]"+r"(dst_argb), // %[dst_argb]
[width]"+rm"(width) // %[width]
: [yuvconstants]"r"(yuvconstants) // %[yuvconstants]
: "memory", "cc", YUVTORGB_REGS_AVX2
"xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5"
);
}
#endif // HAS_I444TOARGBROW_AVX2
#if defined(HAS_I422TOARGBROW_AVX2)
// 16 pixels
// 8 UV values upsampled to 16 UV, mixed with 16 Y producing 16 ARGB (64 bytes).
void OMITFP I422ToARGBRow_AVX2(const uint8_t* y_buf,
const uint8_t* u_buf,
const uint8_t* v_buf,
uint8_t* dst_argb,
const struct YuvConstants* yuvconstants,
int width) {
asm volatile (
YUVTORGB_SETUP_AVX2(yuvconstants)
"sub %[u_buf],%[v_buf] \n"
"vpcmpeqb %%ymm5,%%ymm5,%%ymm5 \n"
LABELALIGN
"1: \n"
READYUV422_AVX2
YUVTORGB_AVX2(yuvconstants)
STOREARGB_AVX2
"sub $0x10,%[width] \n"
"jg 1b \n"
"vzeroupper \n"
: [y_buf]"+r"(y_buf), // %[y_buf]
[u_buf]"+r"(u_buf), // %[u_buf]
[v_buf]"+r"(v_buf), // %[v_buf]
[dst_argb]"+r"(dst_argb), // %[dst_argb]
[width]"+rm"(width) // %[width]
: [yuvconstants]"r"(yuvconstants) // %[yuvconstants]
: "memory", "cc", YUVTORGB_REGS_AVX2
"xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5"
);
}
#endif // HAS_I422TOARGBROW_AVX2
#if defined(HAS_I422TOAR30ROW_AVX2)
// 16 pixels
// 8 UV values upsampled to 16 UV, mixed with 16 Y producing 16 AR30 (64 bytes).
void OMITFP I422ToAR30Row_AVX2(const uint8_t* y_buf,
const uint8_t* u_buf,
const uint8_t* v_buf,
uint8_t* dst_ar30,
const struct YuvConstants* yuvconstants,
int width) {
asm volatile (
YUVTORGB_SETUP_AVX2(yuvconstants)
"sub %[u_buf],%[v_buf] \n"
"vpcmpeqb %%ymm5,%%ymm5,%%ymm5 \n" // AR30 constants
"vpsrlw $14,%%ymm5,%%ymm5 \n"
"vpsllw $4,%%ymm5,%%ymm5 \n" // 2 alpha bits
"vpxor %%ymm6,%%ymm6,%%ymm6 \n" // 0 for min
"vpcmpeqb %%ymm7,%%ymm7,%%ymm7 \n" // 1023 for max
"vpsrlw $6,%%ymm7,%%ymm7 \n"
LABELALIGN
"1: \n"
READYUV422_AVX2
YUVTORGB16_AVX2(yuvconstants)
STOREAR30_AVX2
"sub $0x10,%[width] \n"
"jg 1b \n"
"vzeroupper \n"
: [y_buf]"+r"(y_buf), // %[y_buf]
[u_buf]"+r"(u_buf), // %[u_buf]
[v_buf]"+r"(v_buf), // %[v_buf]
[dst_ar30]"+r"(dst_ar30), // %[dst_ar30]
[width]"+rm"(width) // %[width]
: [yuvconstants]"r"(yuvconstants) // %[yuvconstants]
: "memory", "cc", YUVTORGB_REGS_AVX2
"xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7"
);
}
#endif // HAS_I422TOAR30ROW_AVX2
#if defined(HAS_I210TOARGBROW_AVX2)
// 16 pixels
// 8 UV values upsampled to 16 UV, mixed with 16 Y producing 16 ARGB (64 bytes).
void OMITFP I210ToARGBRow_AVX2(const uint16_t* y_buf,
const uint16_t* u_buf,
const uint16_t* v_buf,
uint8_t* dst_argb,
const struct YuvConstants* yuvconstants,
int width) {
asm volatile (
YUVTORGB_SETUP_AVX2(yuvconstants)
"sub %[u_buf],%[v_buf] \n"
"vpcmpeqb %%ymm5,%%ymm5,%%ymm5 \n"
LABELALIGN
"1: \n"
READYUV210_AVX2
YUVTORGB_AVX2(yuvconstants)
STOREARGB_AVX2
"sub $0x10,%[width] \n"
"jg 1b \n"
"vzeroupper \n"
: [y_buf]"+r"(y_buf), // %[y_buf]
[u_buf]"+r"(u_buf), // %[u_buf]
[v_buf]"+r"(v_buf), // %[v_buf]
[dst_argb]"+r"(dst_argb), // %[dst_argb]
[width]"+rm"(width) // %[width]
: [yuvconstants]"r"(yuvconstants) // %[yuvconstants]
: "memory", "cc", YUVTORGB_REGS_AVX2
"xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5"
);
}
#endif // HAS_I210TOARGBROW_AVX2
#if defined(HAS_I210TOAR30ROW_AVX2)
// 16 pixels
// 8 UV values upsampled to 16 UV, mixed with 16 Y producing 16 AR30 (64 bytes).
void OMITFP I210ToAR30Row_AVX2(const uint16_t* y_buf,
const uint16_t* u_buf,
const uint16_t* v_buf,
uint8_t* dst_ar30,
const struct YuvConstants* yuvconstants,
int width) {
asm volatile (
YUVTORGB_SETUP_AVX2(yuvconstants)
"sub %[u_buf],%[v_buf] \n"
"vpcmpeqb %%ymm5,%%ymm5,%%ymm5 \n" // AR30 constants
"vpsrlw $14,%%ymm5,%%ymm5 \n"
"vpsllw $4,%%ymm5,%%ymm5 \n" // 2 alpha bits
"vpxor %%ymm6,%%ymm6,%%ymm6 \n" // 0 for min
"vpcmpeqb %%ymm7,%%ymm7,%%ymm7 \n" // 1023 for max
"vpsrlw $6,%%ymm7,%%ymm7 \n"
LABELALIGN
"1: \n"
READYUV210_AVX2
YUVTORGB16_AVX2(yuvconstants)
STOREAR30_AVX2
"sub $0x10,%[width] \n"
"jg 1b \n"
"vzeroupper \n"
: [y_buf]"+r"(y_buf), // %[y_buf]
[u_buf]"+r"(u_buf), // %[u_buf]
[v_buf]"+r"(v_buf), // %[v_buf]
[dst_ar30]"+r"(dst_ar30), // %[dst_ar30]
[width]"+rm"(width) // %[width]
: [yuvconstants]"r"(yuvconstants) // %[yuvconstants]
: "memory", "cc", YUVTORGB_REGS_AVX2
"xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5"
);
}
#endif // HAS_I210TOAR30ROW_AVX2
#if defined(HAS_I422ALPHATOARGBROW_AVX2)
// 16 pixels
// 8 UV values upsampled to 16 UV, mixed with 16 Y and 16 A producing 16 ARGB.
void OMITFP I422AlphaToARGBRow_AVX2(const uint8_t* y_buf,
const uint8_t* u_buf,
const uint8_t* v_buf,
const uint8_t* a_buf,
uint8_t* dst_argb,
const struct YuvConstants* yuvconstants,
int width) {
// clang-format off
asm volatile (
YUVTORGB_SETUP_AVX2(yuvconstants)
"sub %[u_buf],%[v_buf] \n"
LABELALIGN
"1: \n"
READYUVA422_AVX2
YUVTORGB_AVX2(yuvconstants)
STOREARGB_AVX2
"subl $0x10,%[width] \n"
"jg 1b \n"
"vzeroupper \n"
: [y_buf]"+r"(y_buf), // %[y_buf]
[u_buf]"+r"(u_buf), // %[u_buf]
[v_buf]"+r"(v_buf), // %[v_buf]
[a_buf]"+r"(a_buf), // %[a_buf]
[dst_argb]"+r"(dst_argb), // %[dst_argb]
#if defined(__i386__)
[width]"+m"(width) // %[width]
#else
[width]"+rm"(width) // %[width]
#endif
: [yuvconstants]"r"(yuvconstants) // %[yuvconstants]
: "memory", "cc", YUVTORGB_REGS_AVX2
"xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5"
);
// clang-format on
}
#endif // HAS_I422ALPHATOARGBROW_AVX2
#if defined(HAS_I422TORGBAROW_AVX2)
// 16 pixels
// 8 UV values upsampled to 16 UV, mixed with 16 Y producing 16 RGBA (64 bytes).
void OMITFP I422ToRGBARow_AVX2(const uint8_t* y_buf,
const uint8_t* u_buf,
const uint8_t* v_buf,
uint8_t* dst_argb,
const struct YuvConstants* yuvconstants,
int width) {
asm volatile (
YUVTORGB_SETUP_AVX2(yuvconstants)
"sub %[u_buf],%[v_buf] \n"
"vpcmpeqb %%ymm5,%%ymm5,%%ymm5 \n"
LABELALIGN
"1: \n"
READYUV422_AVX2
YUVTORGB_AVX2(yuvconstants)
// Step 3: Weave into RGBA
"vpunpcklbw %%ymm2,%%ymm1,%%ymm1 \n"
"vpermq $0xd8,%%ymm1,%%ymm1 \n"
"vpunpcklbw %%ymm0,%%ymm5,%%ymm2 \n"
"vpermq $0xd8,%%ymm2,%%ymm2 \n"
"vpunpcklwd %%ymm1,%%ymm2,%%ymm0 \n"
"vpunpckhwd %%ymm1,%%ymm2,%%ymm1 \n"
"vmovdqu %%ymm0,(%[dst_argb]) \n"
"vmovdqu %%ymm1,0x20(%[dst_argb]) \n"
"lea 0x40(%[dst_argb]),%[dst_argb] \n"
"sub $0x10,%[width] \n"
"jg 1b \n"
"vzeroupper \n"
: [y_buf]"+r"(y_buf), // %[y_buf]
[u_buf]"+r"(u_buf), // %[u_buf]
[v_buf]"+r"(v_buf), // %[v_buf]
[dst_argb]"+r"(dst_argb), // %[dst_argb]
[width]"+rm"(width) // %[width]
: [yuvconstants]"r"(yuvconstants) // %[yuvconstants]
: "memory", "cc", YUVTORGB_REGS_AVX2
"xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5"
);
}
#endif // HAS_I422TORGBAROW_AVX2
#if defined(HAS_NV12TOARGBROW_AVX2)
// 16 pixels.
// 8 UV values upsampled to 16 UV, mixed with 16 Y producing 16 ARGB (64 bytes).
void OMITFP NV12ToARGBRow_AVX2(const uint8_t* y_buf,
const uint8_t* uv_buf,
uint8_t* dst_argb,
const struct YuvConstants* yuvconstants,
int width) {
// clang-format off
asm volatile (
YUVTORGB_SETUP_AVX2(yuvconstants)
"vpcmpeqb %%ymm5,%%ymm5,%%ymm5 \n"
LABELALIGN
"1: \n"
READNV12_AVX2
YUVTORGB_AVX2(yuvconstants)
STOREARGB_AVX2
"sub $0x10,%[width] \n"
"jg 1b \n"
"vzeroupper \n"
: [y_buf]"+r"(y_buf), // %[y_buf]
[uv_buf]"+r"(uv_buf), // %[uv_buf]
[dst_argb]"+r"(dst_argb), // %[dst_argb]
[width]"+rm"(width) // %[width]
: [yuvconstants]"r"(yuvconstants) // %[yuvconstants]
: "memory", "cc", YUVTORGB_REGS_AVX2
"xmm0", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5"
);
// clang-format on
}
#endif // HAS_NV12TOARGBROW_AVX2
#if defined(HAS_NV21TOARGBROW_AVX2)
// 16 pixels.
// 8 VU values upsampled to 16 UV, mixed with 16 Y producing 16 ARGB (64 bytes).
void OMITFP NV21ToARGBRow_AVX2(const uint8_t* y_buf,
const uint8_t* vu_buf,
uint8_t* dst_argb,
const struct YuvConstants* yuvconstants,
int width) {
// clang-format off
asm volatile (
YUVTORGB_SETUP_AVX2(yuvconstants)
"vpcmpeqb %%ymm5,%%ymm5,%%ymm5 \n"
LABELALIGN
"1: \n"
READNV21_AVX2
YUVTORGB_AVX2(yuvconstants)
STOREARGB_AVX2
"sub $0x10,%[width] \n"
"jg 1b \n"
"vzeroupper \n"
: [y_buf]"+r"(y_buf), // %[y_buf]
[vu_buf]"+r"(vu_buf), // %[vu_buf]
[dst_argb]"+r"(dst_argb), // %[dst_argb]
[width]"+rm"(width) // %[width]
: [yuvconstants]"r"(yuvconstants), // %[yuvconstants]
[kShuffleNV21]"m"(kShuffleNV21)
: "memory", "cc", YUVTORGB_REGS_AVX2
"xmm0", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5"
);
// clang-format on
}
#endif // HAS_NV21TOARGBROW_AVX2
#if defined(HAS_YUY2TOARGBROW_AVX2)
// 16 pixels.
// 8 YUY2 values with 16 Y and 8 UV producing 16 ARGB (64 bytes).
void OMITFP YUY2ToARGBRow_AVX2(const uint8_t* yuy2_buf,
uint8_t* dst_argb,
const struct YuvConstants* yuvconstants,
int width) {
// clang-format off
asm volatile (
YUVTORGB_SETUP_AVX2(yuvconstants)
"vpcmpeqb %%ymm5,%%ymm5,%%ymm5 \n"
LABELALIGN
"1: \n"
READYUY2_AVX2
YUVTORGB_AVX2(yuvconstants)
STOREARGB_AVX2
"sub $0x10,%[width] \n"
"jg 1b \n"
"vzeroupper \n"
: [yuy2_buf]"+r"(yuy2_buf), // %[yuy2_buf]
[dst_argb]"+r"(dst_argb), // %[dst_argb]
[width]"+rm"(width) // %[width]
: [yuvconstants]"r"(yuvconstants), // %[yuvconstants]
[kShuffleYUY2Y]"m"(kShuffleYUY2Y),
[kShuffleYUY2UV]"m"(kShuffleYUY2UV)
: "memory", "cc", YUVTORGB_REGS_AVX2
"xmm0", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5"
);
// clang-format on
}
#endif // HAS_YUY2TOARGBROW_AVX2
#if defined(HAS_UYVYTOARGBROW_AVX2)
// 16 pixels.
// 8 UYVY values with 16 Y and 8 UV producing 16 ARGB (64 bytes).
void OMITFP UYVYToARGBRow_AVX2(const uint8_t* uyvy_buf,
uint8_t* dst_argb,
const struct YuvConstants* yuvconstants,
int width) {
// clang-format off
asm volatile (
YUVTORGB_SETUP_AVX2(yuvconstants)
"vpcmpeqb %%ymm5,%%ymm5,%%ymm5 \n"
LABELALIGN
"1: \n"
READUYVY_AVX2
YUVTORGB_AVX2(yuvconstants)
STOREARGB_AVX2
"sub $0x10,%[width] \n"
"jg 1b \n"
"vzeroupper \n"
: [uyvy_buf]"+r"(uyvy_buf), // %[uyvy_buf]
[dst_argb]"+r"(dst_argb), // %[dst_argb]
[width]"+rm"(width) // %[width]
: [yuvconstants]"r"(yuvconstants), // %[yuvconstants]
[kShuffleUYVYY]"m"(kShuffleUYVYY),
[kShuffleUYVYUV]"m"(kShuffleUYVYUV)
: "memory", "cc", YUVTORGB_REGS_AVX2
"xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5"
);
// clang-format on
}
#endif // HAS_UYVYTOARGBROW_AVX2
#ifdef HAS_I400TOARGBROW_SSE2
void I400ToARGBRow_SSE2(const uint8_t* y_buf,
uint8_t* dst_argb,
const struct YuvConstants* yuvconstants,
int width) {
asm volatile(
"movdqa 192(%3),%%xmm2 \n" // yg = 18997 = 1.164
"movdqa 224(%3),%%xmm3 \n" // ygb = 1160 = 1.164 * 16
"pcmpeqb %%xmm4,%%xmm4 \n" // 0xff000000
"pslld $0x18,%%xmm4 \n"
LABELALIGN
"1: \n"
// Step 1: Scale Y contribution to 8 G values. G = (y - 16) * 1.164
"movq (%0),%%xmm0 \n"
"lea 0x8(%0),%0 \n"
"punpcklbw %%xmm0,%%xmm0 \n"
"pmulhuw %%xmm2,%%xmm0 \n"
"paddsw %%xmm3,%%xmm0 \n"
"psraw $6, %%xmm0 \n"
"packuswb %%xmm0,%%xmm0 \n"
// Step 2: Weave into ARGB
"punpcklbw %%xmm0,%%xmm0 \n"
"movdqa %%xmm0,%%xmm1 \n"
"punpcklwd %%xmm0,%%xmm0 \n"
"punpckhwd %%xmm1,%%xmm1 \n"
"por %%xmm4,%%xmm0 \n"
"por %%xmm4,%%xmm1 \n"
"movdqu %%xmm0,(%1) \n"
"movdqu %%xmm1,0x10(%1) \n"
"lea 0x20(%1),%1 \n"
"sub $0x8,%2 \n"
"jg 1b \n"
: "+r"(y_buf), // %0
"+r"(dst_argb), // %1
"+rm"(width) // %2
: "r"(yuvconstants) // %3
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4");
}
#endif // HAS_I400TOARGBROW_SSE2
#ifdef HAS_I400TOARGBROW_AVX2
// 16 pixels of Y converted to 16 pixels of ARGB (64 bytes).
// note: vpunpcklbw mutates and vpackuswb unmutates.
void I400ToARGBRow_AVX2(const uint8_t* y_buf,
uint8_t* dst_argb,
const struct YuvConstants* yuvconstants,
int width) {
asm volatile(
"vmovdqa 192(%3),%%ymm2 \n" // yg = 18997 = 1.164
"vmovdqa 224(%3),%%ymm3 \n" // ygb = -1160 = 1.164*16
"vpcmpeqb %%ymm4,%%ymm4,%%ymm4 \n" // 0xff000000
"vpslld $0x18,%%ymm4,%%ymm4 \n"
LABELALIGN
"1: \n"
// Step 1: Scale Y contribution to 16 G values. G = (y - 16) * 1.164
"vmovdqu (%0),%%xmm0 \n"
"lea 0x10(%0),%0 \n"
"vpermq $0xd8,%%ymm0,%%ymm0 \n"
"vpunpcklbw %%ymm0,%%ymm0,%%ymm0 \n"
"vpmulhuw %%ymm2,%%ymm0,%%ymm0 \n"
"vpaddsw %%ymm3,%%ymm0,%%ymm0 \n"
"vpsraw $0x6,%%ymm0,%%ymm0 \n"
"vpackuswb %%ymm0,%%ymm0,%%ymm0 \n"
"vpunpcklbw %%ymm0,%%ymm0,%%ymm1 \n"
"vpermq $0xd8,%%ymm1,%%ymm1 \n"
"vpunpcklwd %%ymm1,%%ymm1,%%ymm0 \n"
"vpunpckhwd %%ymm1,%%ymm1,%%ymm1 \n"
"vpor %%ymm4,%%ymm0,%%ymm0 \n"
"vpor %%ymm4,%%ymm1,%%ymm1 \n"
"vmovdqu %%ymm0,(%1) \n"
"vmovdqu %%ymm1,0x20(%1) \n"
"lea 0x40(%1),%1 \n"
"sub $0x10,%2 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(y_buf), // %0
"+r"(dst_argb), // %1
"+rm"(width) // %2
: "r"(yuvconstants) // %3
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4");
}
#endif // HAS_I400TOARGBROW_AVX2
#ifdef HAS_MIRRORROW_SSSE3
// Shuffle table for reversing the bytes.
static const uvec8 kShuffleMirror = {15u, 14u, 13u, 12u, 11u, 10u, 9u, 8u,
7u, 6u, 5u, 4u, 3u, 2u, 1u, 0u};
void MirrorRow_SSSE3(const uint8_t* src, uint8_t* dst, int width) {
intptr_t temp_width = (intptr_t)(width);
asm volatile(
"movdqa %3,%%xmm5 \n"
LABELALIGN
"1: \n"
"movdqu -0x10(%0,%2,1),%%xmm0 \n"
"pshufb %%xmm5,%%xmm0 \n"
"movdqu %%xmm0,(%1) \n"
"lea 0x10(%1),%1 \n"
"sub $0x10,%2 \n"
"jg 1b \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(temp_width) // %2
: "m"(kShuffleMirror) // %3
: "memory", "cc", "xmm0", "xmm5");
}
#endif // HAS_MIRRORROW_SSSE3
#ifdef HAS_MIRRORROW_AVX2
void MirrorRow_AVX2(const uint8_t* src, uint8_t* dst, int width) {
intptr_t temp_width = (intptr_t)(width);
asm volatile(
"vbroadcastf128 %3,%%ymm5 \n"
LABELALIGN
"1: \n"
"vmovdqu -0x20(%0,%2,1),%%ymm0 \n"
"vpshufb %%ymm5,%%ymm0,%%ymm0 \n"
"vpermq $0x4e,%%ymm0,%%ymm0 \n"
"vmovdqu %%ymm0,(%1) \n"
"lea 0x20(%1),%1 \n"
"sub $0x20,%2 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(temp_width) // %2
: "m"(kShuffleMirror) // %3
: "memory", "cc", "xmm0", "xmm5");
}
#endif // HAS_MIRRORROW_AVX2
#ifdef HAS_MIRRORUVROW_SSSE3
// Shuffle table for reversing the UV.
static const uvec8 kShuffleMirrorUV = {14u, 15u, 12u, 13u, 10u, 11u, 8u, 9u,
6u, 7u, 4u, 5u, 2u, 3u, 0u, 1u};
void MirrorUVRow_SSSE3(const uint8_t* src_uv, uint8_t* dst_uv, int width) {
intptr_t temp_width = (intptr_t)(width);
asm volatile(
"movdqa %3,%%xmm5 \n"
LABELALIGN
"1: \n"
"movdqu -0x10(%0,%2,2),%%xmm0 \n"
"pshufb %%xmm5,%%xmm0 \n"
"movdqu %%xmm0,(%1) \n"
"lea 0x10(%1),%1 \n"
"sub $0x8,%2 \n"
"jg 1b \n"
: "+r"(src_uv), // %0
"+r"(dst_uv), // %1
"+r"(temp_width) // %2
: "m"(kShuffleMirrorUV) // %3
: "memory", "cc", "xmm0", "xmm5");
}
#endif // HAS_MIRRORUVROW_SSSE3
#ifdef HAS_MIRRORUVROW_AVX2
void MirrorUVRow_AVX2(const uint8_t* src_uv, uint8_t* dst_uv, int width) {
intptr_t temp_width = (intptr_t)(width);
asm volatile(
"vbroadcastf128 %3,%%ymm5 \n"
LABELALIGN
"1: \n"
"vmovdqu -0x20(%0,%2,2),%%ymm0 \n"
"vpshufb %%ymm5,%%ymm0,%%ymm0 \n"
"vpermq $0x4e,%%ymm0,%%ymm0 \n"
"vmovdqu %%ymm0,(%1) \n"
"lea 0x20(%1),%1 \n"
"sub $0x10,%2 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_uv), // %0
"+r"(dst_uv), // %1
"+r"(temp_width) // %2
: "m"(kShuffleMirrorUV) // %3
: "memory", "cc", "xmm0", "xmm5");
}
#endif // HAS_MIRRORUVROW_AVX2
#ifdef HAS_MIRRORSPLITUVROW_SSSE3
// Shuffle table for reversing the bytes of UV channels.
static const uvec8 kShuffleMirrorSplitUV = {14u, 12u, 10u, 8u, 6u, 4u, 2u, 0u,
15u, 13u, 11u, 9u, 7u, 5u, 3u, 1u};
void MirrorSplitUVRow_SSSE3(const uint8_t* src,
uint8_t* dst_u,
uint8_t* dst_v,
int width) {
intptr_t temp_width = (intptr_t)(width);
asm volatile(
"movdqa %4,%%xmm1 \n"
"lea -0x10(%0,%3,2),%0 \n"
"sub %1,%2 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"lea -0x10(%0),%0 \n"
"pshufb %%xmm1,%%xmm0 \n"
"movlpd %%xmm0,(%1) \n"
"movhpd %%xmm0,0x00(%1,%2,1) \n"
"lea 0x8(%1),%1 \n"
"sub $8,%3 \n"
"jg 1b \n"
: "+r"(src), // %0
"+r"(dst_u), // %1
"+r"(dst_v), // %2
"+r"(temp_width) // %3
: "m"(kShuffleMirrorSplitUV) // %4
: "memory", "cc", "xmm0", "xmm1");
}
#endif // HAS_MIRRORSPLITUVROW_SSSE3
#ifdef HAS_RGB24MIRRORROW_SSSE3
// Shuffle first 5 pixels to last 5 mirrored. first byte zero
static const uvec8 kShuffleMirrorRGB0 = {128u, 12u, 13u, 14u, 9u, 10u, 11u, 6u,
7u, 8u, 3u, 4u, 5u, 0u, 1u, 2u};
// Shuffle last 5 pixels to first 5 mirrored. last byte zero
static const uvec8 kShuffleMirrorRGB1 = {
13u, 14u, 15u, 10u, 11u, 12u, 7u, 8u, 9u, 4u, 5u, 6u, 1u, 2u, 3u, 128u};
// Shuffle 5 pixels at a time (15 bytes)
void RGB24MirrorRow_SSSE3(const uint8_t* src_rgb24,
uint8_t* dst_rgb24,
int width) {
intptr_t temp_width = (intptr_t)(width);
src_rgb24 += width * 3 - 48;
asm volatile(
"movdqa %3,%%xmm4 \n"
"movdqa %4,%%xmm5 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n" // first 5
"movdqu 15(%0),%%xmm1 \n" // next 5
"movdqu 30(%0),%%xmm2 \n" // next 5
"movdqu 32(%0),%%xmm3 \n" // last 1 special
"pshufb %%xmm4,%%xmm0 \n"
"pshufb %%xmm4,%%xmm1 \n"
"pshufb %%xmm4,%%xmm2 \n"
"pshufb %%xmm5,%%xmm3 \n"
"lea -0x30(%0),%0 \n"
"movdqu %%xmm0,32(%1) \n" // last 5
"movdqu %%xmm1,17(%1) \n" // next 5
"movdqu %%xmm2,2(%1) \n" // next 5
"movlpd %%xmm3,0(%1) \n" // first 1
"lea 0x30(%1),%1 \n"
"sub $0x10,%2 \n"
"jg 1b \n"
: "+r"(src_rgb24), // %0
"+r"(dst_rgb24), // %1
"+r"(temp_width) // %2
: "m"(kShuffleMirrorRGB0), // %3
"m"(kShuffleMirrorRGB1) // %4
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5");
}
#endif // HAS_RGB24MIRRORROW_SSSE3
#ifdef HAS_ARGBMIRRORROW_SSE2
void ARGBMirrorRow_SSE2(const uint8_t* src, uint8_t* dst, int width) {
intptr_t temp_width = (intptr_t)(width);
asm volatile(
"lea -0x10(%0,%2,4),%0 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"pshufd $0x1b,%%xmm0,%%xmm0 \n"
"lea -0x10(%0),%0 \n"
"movdqu %%xmm0,(%1) \n"
"lea 0x10(%1),%1 \n"
"sub $0x4,%2 \n"
"jg 1b \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(temp_width) // %2
:
: "memory", "cc", "xmm0");
}
#endif // HAS_ARGBMIRRORROW_SSE2
#ifdef HAS_ARGBMIRRORROW_AVX2
// Shuffle table for reversing the bytes.
static const ulvec32 kARGBShuffleMirror_AVX2 = {7u, 6u, 5u, 4u, 3u, 2u, 1u, 0u};
void ARGBMirrorRow_AVX2(const uint8_t* src, uint8_t* dst, int width) {
intptr_t temp_width = (intptr_t)(width);
asm volatile(
"vmovdqu %3,%%ymm5 \n"
LABELALIGN
"1: \n"
"vpermd -0x20(%0,%2,4),%%ymm5,%%ymm0 \n"
"vmovdqu %%ymm0,(%1) \n"
"lea 0x20(%1),%1 \n"
"sub $0x8,%2 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(temp_width) // %2
: "m"(kARGBShuffleMirror_AVX2) // %3
: "memory", "cc", "xmm0", "xmm5");
}
#endif // HAS_ARGBMIRRORROW_AVX2
#ifdef HAS_SPLITUVROW_AVX2
void SplitUVRow_AVX2(const uint8_t* src_uv,
uint8_t* dst_u,
uint8_t* dst_v,
int width) {
asm volatile(
"vpcmpeqb %%ymm5,%%ymm5,%%ymm5 \n"
"vpsrlw $0x8,%%ymm5,%%ymm5 \n"
"sub %1,%2 \n"
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm0 \n"
"vmovdqu 0x20(%0),%%ymm1 \n"
"lea 0x40(%0),%0 \n"
"vpsrlw $0x8,%%ymm0,%%ymm2 \n"
"vpsrlw $0x8,%%ymm1,%%ymm3 \n"
"vpand %%ymm5,%%ymm0,%%ymm0 \n"
"vpand %%ymm5,%%ymm1,%%ymm1 \n"
"vpackuswb %%ymm1,%%ymm0,%%ymm0 \n"
"vpackuswb %%ymm3,%%ymm2,%%ymm2 \n"
"vpermq $0xd8,%%ymm0,%%ymm0 \n"
"vpermq $0xd8,%%ymm2,%%ymm2 \n"
"vmovdqu %%ymm0,(%1) \n"
"vmovdqu %%ymm2,0x00(%1,%2,1) \n"
"lea 0x20(%1),%1 \n"
"sub $0x20,%3 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_uv), // %0
"+r"(dst_u), // %1
"+r"(dst_v), // %2
"+r"(width) // %3
:
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm5");
}
#endif // HAS_SPLITUVROW_AVX2
#ifdef HAS_SPLITUVROW_SSE2
void SplitUVRow_SSE2(const uint8_t* src_uv,
uint8_t* dst_u,
uint8_t* dst_v,
int width) {
asm volatile(
"pcmpeqb %%xmm5,%%xmm5 \n"
"psrlw $0x8,%%xmm5 \n"
"sub %1,%2 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"lea 0x20(%0),%0 \n"
"movdqa %%xmm0,%%xmm2 \n"
"movdqa %%xmm1,%%xmm3 \n"
"pand %%xmm5,%%xmm0 \n"
"pand %%xmm5,%%xmm1 \n"
"packuswb %%xmm1,%%xmm0 \n"
"psrlw $0x8,%%xmm2 \n"
"psrlw $0x8,%%xmm3 \n"
"packuswb %%xmm3,%%xmm2 \n"
"movdqu %%xmm0,(%1) \n"
"movdqu %%xmm2,0x00(%1,%2,1) \n"
"lea 0x10(%1),%1 \n"
"sub $0x10,%3 \n"
"jg 1b \n"
: "+r"(src_uv), // %0
"+r"(dst_u), // %1
"+r"(dst_v), // %2
"+r"(width) // %3
:
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm5");
}
#endif // HAS_SPLITUVROW_SSE2
#ifdef HAS_MERGEUVROW_AVX2
void MergeUVRow_AVX2(const uint8_t* src_u,
const uint8_t* src_v,
uint8_t* dst_uv,
int width) {
asm volatile(
"sub %0,%1 \n"
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm0 \n"
"vmovdqu 0x00(%0,%1,1),%%ymm1 \n"
"lea 0x20(%0),%0 \n"
"vpunpcklbw %%ymm1,%%ymm0,%%ymm2 \n"
"vpunpckhbw %%ymm1,%%ymm0,%%ymm0 \n"
"vextractf128 $0x0,%%ymm2,(%2) \n"
"vextractf128 $0x0,%%ymm0,0x10(%2) \n"
"vextractf128 $0x1,%%ymm2,0x20(%2) \n"
"vextractf128 $0x1,%%ymm0,0x30(%2) \n"
"lea 0x40(%2),%2 \n"
"sub $0x20,%3 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_u), // %0
"+r"(src_v), // %1
"+r"(dst_uv), // %2
"+r"(width) // %3
:
: "memory", "cc", "xmm0", "xmm1", "xmm2");
}
#endif // HAS_MERGEUVROW_AVX2
#ifdef HAS_MERGEUVROW_SSE2
void MergeUVRow_SSE2(const uint8_t* src_u,
const uint8_t* src_v,
uint8_t* dst_uv,
int width) {
asm volatile(
"sub %0,%1 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x00(%0,%1,1),%%xmm1 \n"
"lea 0x10(%0),%0 \n"
"movdqa %%xmm0,%%xmm2 \n"
"punpcklbw %%xmm1,%%xmm0 \n"
"punpckhbw %%xmm1,%%xmm2 \n"
"movdqu %%xmm0,(%2) \n"
"movdqu %%xmm2,0x10(%2) \n"
"lea 0x20(%2),%2 \n"
"sub $0x10,%3 \n"
"jg 1b \n"
: "+r"(src_u), // %0
"+r"(src_v), // %1
"+r"(dst_uv), // %2
"+r"(width) // %3
:
: "memory", "cc", "xmm0", "xmm1", "xmm2");
}
#endif // HAS_MERGEUVROW_SSE2
// Use scale to convert lsb formats to msb, depending how many bits there are:
// 128 = 9 bits
// 64 = 10 bits
// 16 = 12 bits
// 1 = 16 bits
#ifdef HAS_MERGEUVROW_16_AVX2
void MergeUVRow_16_AVX2(const uint16_t* src_u,
const uint16_t* src_v,
uint16_t* dst_uv,
int scale,
int width) {
// clang-format off
asm volatile (
"vmovd %4,%%xmm3 \n"
"vpunpcklwd %%xmm3,%%xmm3,%%xmm3 \n"
"vbroadcastss %%xmm3,%%ymm3 \n"
"sub %0,%1 \n"
// 16 pixels per loop.
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm0 \n"
"vmovdqu (%0,%1,1),%%ymm1 \n"
"add $0x20,%0 \n"
"vpmullw %%ymm3,%%ymm0,%%ymm0 \n"
"vpmullw %%ymm3,%%ymm1,%%ymm1 \n"
"vpunpcklwd %%ymm1,%%ymm0,%%ymm2 \n" // mutates
"vpunpckhwd %%ymm1,%%ymm0,%%ymm0 \n"
"vextractf128 $0x0,%%ymm2,(%2) \n"
"vextractf128 $0x0,%%ymm0,0x10(%2) \n"
"vextractf128 $0x1,%%ymm2,0x20(%2) \n"
"vextractf128 $0x1,%%ymm0,0x30(%2) \n"
"add $0x40,%2 \n"
"sub $0x10,%3 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_u), // %0
"+r"(src_v), // %1
"+r"(dst_uv), // %2
"+r"(width) // %3
: "r"(scale) // %4
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3");
// clang-format on
}
#endif // HAS_MERGEUVROW_AVX2
// Use scale to convert lsb formats to msb, depending how many bits there are:
// 128 = 9 bits
// 64 = 10 bits
// 16 = 12 bits
// 1 = 16 bits
#ifdef HAS_MULTIPLYROW_16_AVX2
void MultiplyRow_16_AVX2(const uint16_t* src_y,
uint16_t* dst_y,
int scale,
int width) {
// clang-format off
asm volatile (
"vmovd %3,%%xmm3 \n"
"vpunpcklwd %%xmm3,%%xmm3,%%xmm3 \n"
"vbroadcastss %%xmm3,%%ymm3 \n"
"sub %0,%1 \n"
// 16 pixels per loop.
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm0 \n"
"vmovdqu 0x20(%0),%%ymm1 \n"
"vpmullw %%ymm3,%%ymm0,%%ymm0 \n"
"vpmullw %%ymm3,%%ymm1,%%ymm1 \n"
"vmovdqu %%ymm0,(%0,%1) \n"
"vmovdqu %%ymm1,0x20(%0,%1) \n"
"add $0x40,%0 \n"
"sub $0x20,%2 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_y), // %0
"+r"(dst_y), // %1
"+r"(width) // %2
: "r"(scale) // %3
: "memory", "cc", "xmm0", "xmm1", "xmm3");
// clang-format on
}
#endif // HAS_MULTIPLYROW_16_AVX2
// Use scale to convert lsb formats to msb, depending how many bits there are:
// 32768 = 9 bits
// 16384 = 10 bits
// 4096 = 12 bits
// 256 = 16 bits
void Convert16To8Row_SSSE3(const uint16_t* src_y,
uint8_t* dst_y,
int scale,
int width) {
// clang-format off
asm volatile (
"movd %3,%%xmm2 \n"
"punpcklwd %%xmm2,%%xmm2 \n"
"pshufd $0x0,%%xmm2,%%xmm2 \n"
// 32 pixels per loop.
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"add $0x20,%0 \n"
"pmulhuw %%xmm2,%%xmm0 \n"
"pmulhuw %%xmm2,%%xmm1 \n"
"packuswb %%xmm1,%%xmm0 \n"
"movdqu %%xmm0,(%1) \n"
"add $0x10,%1 \n"
"sub $0x10,%2 \n"
"jg 1b \n"
: "+r"(src_y), // %0
"+r"(dst_y), // %1
"+r"(width) // %2
: "r"(scale) // %3
: "memory", "cc", "xmm0", "xmm1", "xmm2");
// clang-format on
}
#ifdef HAS_CONVERT16TO8ROW_AVX2
void Convert16To8Row_AVX2(const uint16_t* src_y,
uint8_t* dst_y,
int scale,
int width) {
// clang-format off
asm volatile (
"vmovd %3,%%xmm2 \n"
"vpunpcklwd %%xmm2,%%xmm2,%%xmm2 \n"
"vbroadcastss %%xmm2,%%ymm2 \n"
// 32 pixels per loop.
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm0 \n"
"vmovdqu 0x20(%0),%%ymm1 \n"
"add $0x40,%0 \n"
"vpmulhuw %%ymm2,%%ymm0,%%ymm0 \n"
"vpmulhuw %%ymm2,%%ymm1,%%ymm1 \n"
"vpackuswb %%ymm1,%%ymm0,%%ymm0 \n" // mutates
"vpermq $0xd8,%%ymm0,%%ymm0 \n"
"vmovdqu %%ymm0,(%1) \n"
"add $0x20,%1 \n"
"sub $0x20,%2 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_y), // %0
"+r"(dst_y), // %1
"+r"(width) // %2
: "r"(scale) // %3
: "memory", "cc", "xmm0", "xmm1", "xmm2");
// clang-format on
}
#endif // HAS_CONVERT16TO8ROW_AVX2
// Use scale to convert to lsb formats depending how many bits there are:
// 512 = 9 bits
// 1024 = 10 bits
// 4096 = 12 bits
// TODO(fbarchard): reduce to SSE2
void Convert8To16Row_SSE2(const uint8_t* src_y,
uint16_t* dst_y,
int scale,
int width) {
// clang-format off
asm volatile (
"movd %3,%%xmm2 \n"
"punpcklwd %%xmm2,%%xmm2 \n"
"pshufd $0x0,%%xmm2,%%xmm2 \n"
// 32 pixels per loop.
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqa %%xmm0,%%xmm1 \n"
"punpcklbw %%xmm0,%%xmm0 \n"
"punpckhbw %%xmm1,%%xmm1 \n"
"add $0x10,%0 \n"
"pmulhuw %%xmm2,%%xmm0 \n"
"pmulhuw %%xmm2,%%xmm1 \n"
"movdqu %%xmm0,(%1) \n"
"movdqu %%xmm1,0x10(%1) \n"
"add $0x20,%1 \n"
"sub $0x10,%2 \n"
"jg 1b \n"
: "+r"(src_y), // %0
"+r"(dst_y), // %1
"+r"(width) // %2
: "r"(scale) // %3
: "memory", "cc", "xmm0", "xmm1", "xmm2");
// clang-format on
}
#ifdef HAS_CONVERT8TO16ROW_AVX2
void Convert8To16Row_AVX2(const uint8_t* src_y,
uint16_t* dst_y,
int scale,
int width) {
// clang-format off
asm volatile (
"vmovd %3,%%xmm2 \n"
"vpunpcklwd %%xmm2,%%xmm2,%%xmm2 \n"
"vbroadcastss %%xmm2,%%ymm2 \n"
// 32 pixels per loop.
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm0 \n"
"vpermq $0xd8,%%ymm0,%%ymm0 \n"
"add $0x20,%0 \n"
"vpunpckhbw %%ymm0,%%ymm0,%%ymm1 \n"
"vpunpcklbw %%ymm0,%%ymm0,%%ymm0 \n"
"vpmulhuw %%ymm2,%%ymm0,%%ymm0 \n"
"vpmulhuw %%ymm2,%%ymm1,%%ymm1 \n"
"vmovdqu %%ymm0,(%1) \n"
"vmovdqu %%ymm1,0x20(%1) \n"
"add $0x40,%1 \n"
"sub $0x20,%2 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_y), // %0
"+r"(dst_y), // %1
"+r"(width) // %2
: "r"(scale) // %3
: "memory", "cc", "xmm0", "xmm1", "xmm2");
// clang-format on
}
#endif // HAS_CONVERT8TO16ROW_AVX2
#ifdef HAS_SPLITRGBROW_SSSE3
// Shuffle table for converting RGB to Planar.
static const uvec8 kShuffleMaskRGBToR0 = {0u, 3u, 6u, 9u, 12u, 15u,
128u, 128u, 128u, 128u, 128u, 128u,
128u, 128u, 128u, 128u};
static const uvec8 kShuffleMaskRGBToR1 = {128u, 128u, 128u, 128u, 128u, 128u,
2u, 5u, 8u, 11u, 14u, 128u,
128u, 128u, 128u, 128u};
static const uvec8 kShuffleMaskRGBToR2 = {128u, 128u, 128u, 128u, 128u, 128u,
128u, 128u, 128u, 128u, 128u, 1u,
4u, 7u, 10u, 13u};
static const uvec8 kShuffleMaskRGBToG0 = {1u, 4u, 7u, 10u, 13u, 128u,
128u, 128u, 128u, 128u, 128u, 128u,
128u, 128u, 128u, 128u};
static const uvec8 kShuffleMaskRGBToG1 = {128u, 128u, 128u, 128u, 128u, 0u,
3u, 6u, 9u, 12u, 15u, 128u,
128u, 128u, 128u, 128u};
static const uvec8 kShuffleMaskRGBToG2 = {128u, 128u, 128u, 128u, 128u, 128u,
128u, 128u, 128u, 128u, 128u, 2u,
5u, 8u, 11u, 14u};
static const uvec8 kShuffleMaskRGBToB0 = {2u, 5u, 8u, 11u, 14u, 128u,
128u, 128u, 128u, 128u, 128u, 128u,
128u, 128u, 128u, 128u};
static const uvec8 kShuffleMaskRGBToB1 = {128u, 128u, 128u, 128u, 128u, 1u,
4u, 7u, 10u, 13u, 128u, 128u,
128u, 128u, 128u, 128u};
static const uvec8 kShuffleMaskRGBToB2 = {128u, 128u, 128u, 128u, 128u, 128u,
128u, 128u, 128u, 128u, 0u, 3u,
6u, 9u, 12u, 15u};
void SplitRGBRow_SSSE3(const uint8_t* src_rgb,
uint8_t* dst_r,
uint8_t* dst_g,
uint8_t* dst_b,
int width) {
asm volatile(
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"movdqu 0x20(%0),%%xmm2 \n"
"pshufb %5, %%xmm0 \n"
"pshufb %6, %%xmm1 \n"
"pshufb %7, %%xmm2 \n"
"por %%xmm1,%%xmm0 \n"
"por %%xmm2,%%xmm0 \n"
"movdqu %%xmm0,(%1) \n"
"lea 0x10(%1),%1 \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"movdqu 0x20(%0),%%xmm2 \n"
"pshufb %8, %%xmm0 \n"
"pshufb %9, %%xmm1 \n"
"pshufb %10, %%xmm2 \n"
"por %%xmm1,%%xmm0 \n"
"por %%xmm2,%%xmm0 \n"
"movdqu %%xmm0,(%2) \n"
"lea 0x10(%2),%2 \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"movdqu 0x20(%0),%%xmm2 \n"
"pshufb %11, %%xmm0 \n"
"pshufb %12, %%xmm1 \n"
"pshufb %13, %%xmm2 \n"
"por %%xmm1,%%xmm0 \n"
"por %%xmm2,%%xmm0 \n"
"movdqu %%xmm0,(%3) \n"
"lea 0x10(%3),%3 \n"
"lea 0x30(%0),%0 \n"
"sub $0x10,%4 \n"
"jg 1b \n"
: "+r"(src_rgb), // %0
"+r"(dst_r), // %1
"+r"(dst_g), // %2
"+r"(dst_b), // %3
"+r"(width) // %4
: "m"(kShuffleMaskRGBToR0), // %5
"m"(kShuffleMaskRGBToR1), // %6
"m"(kShuffleMaskRGBToR2), // %7
"m"(kShuffleMaskRGBToG0), // %8
"m"(kShuffleMaskRGBToG1), // %9
"m"(kShuffleMaskRGBToG2), // %10
"m"(kShuffleMaskRGBToB0), // %11
"m"(kShuffleMaskRGBToB1), // %12
"m"(kShuffleMaskRGBToB2) // %13
: "memory", "cc", "xmm0", "xmm1", "xmm2");
}
#endif // HAS_SPLITRGBROW_SSSE3
#ifdef HAS_MERGERGBROW_SSSE3
// Shuffle table for converting RGB to Planar.
static const uvec8 kShuffleMaskRToRGB0 = {0u, 128u, 128u, 1u, 128u, 128u,
2u, 128u, 128u, 3u, 128u, 128u,
4u, 128u, 128u, 5u};
static const uvec8 kShuffleMaskGToRGB0 = {128u, 0u, 128u, 128u, 1u, 128u,
128u, 2u, 128u, 128u, 3u, 128u,
128u, 4u, 128u, 128u};
static const uvec8 kShuffleMaskBToRGB0 = {128u, 128u, 0u, 128u, 128u, 1u,
128u, 128u, 2u, 128u, 128u, 3u,
128u, 128u, 4u, 128u};
static const uvec8 kShuffleMaskGToRGB1 = {5u, 128u, 128u, 6u, 128u, 128u,
7u, 128u, 128u, 8u, 128u, 128u,
9u, 128u, 128u, 10u};
static const uvec8 kShuffleMaskBToRGB1 = {128u, 5u, 128u, 128u, 6u, 128u,
128u, 7u, 128u, 128u, 8u, 128u,
128u, 9u, 128u, 128u};
static const uvec8 kShuffleMaskRToRGB1 = {128u, 128u, 6u, 128u, 128u, 7u,
128u, 128u, 8u, 128u, 128u, 9u,
128u, 128u, 10u, 128u};
static const uvec8 kShuffleMaskBToRGB2 = {10u, 128u, 128u, 11u, 128u, 128u,
12u, 128u, 128u, 13u, 128u, 128u,
14u, 128u, 128u, 15u};
static const uvec8 kShuffleMaskRToRGB2 = {128u, 11u, 128u, 128u, 12u, 128u,
128u, 13u, 128u, 128u, 14u, 128u,
128u, 15u, 128u, 128u};
static const uvec8 kShuffleMaskGToRGB2 = {128u, 128u, 11u, 128u, 128u, 12u,
128u, 128u, 13u, 128u, 128u, 14u,
128u, 128u, 15u, 128u};
void MergeRGBRow_SSSE3(const uint8_t* src_r,
const uint8_t* src_g,
const uint8_t* src_b,
uint8_t* dst_rgb,
int width) {
asm volatile(
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu (%1),%%xmm1 \n"
"movdqu (%2),%%xmm2 \n"
"pshufb %5, %%xmm0 \n"
"pshufb %6, %%xmm1 \n"
"pshufb %7, %%xmm2 \n"
"por %%xmm1,%%xmm0 \n"
"por %%xmm2,%%xmm0 \n"
"movdqu %%xmm0,(%3) \n"
"movdqu (%0),%%xmm0 \n"
"movdqu (%1),%%xmm1 \n"
"movdqu (%2),%%xmm2 \n"
"pshufb %8, %%xmm0 \n"
"pshufb %9, %%xmm1 \n"
"pshufb %10, %%xmm2 \n"
"por %%xmm1,%%xmm0 \n"
"por %%xmm2,%%xmm0 \n"
"movdqu %%xmm0,16(%3) \n"
"movdqu (%0),%%xmm0 \n"
"movdqu (%1),%%xmm1 \n"
"movdqu (%2),%%xmm2 \n"
"pshufb %11, %%xmm0 \n"
"pshufb %12, %%xmm1 \n"
"pshufb %13, %%xmm2 \n"
"por %%xmm1,%%xmm0 \n"
"por %%xmm2,%%xmm0 \n"
"movdqu %%xmm0,32(%3) \n"
"lea 0x10(%0),%0 \n"
"lea 0x10(%1),%1 \n"
"lea 0x10(%2),%2 \n"
"lea 0x30(%3),%3 \n"
"sub $0x10,%4 \n"
"jg 1b \n"
: "+r"(src_r), // %0
"+r"(src_g), // %1
"+r"(src_b), // %2
"+r"(dst_rgb), // %3
"+r"(width) // %4
: "m"(kShuffleMaskRToRGB0), // %5
"m"(kShuffleMaskGToRGB0), // %6
"m"(kShuffleMaskBToRGB0), // %7
"m"(kShuffleMaskRToRGB1), // %8
"m"(kShuffleMaskGToRGB1), // %9
"m"(kShuffleMaskBToRGB1), // %10
"m"(kShuffleMaskRToRGB2), // %11
"m"(kShuffleMaskGToRGB2), // %12
"m"(kShuffleMaskBToRGB2) // %13
: "memory", "cc", "xmm0", "xmm1", "xmm2");
}
#endif // HAS_MERGERGBROW_SSSE3
#ifdef HAS_COPYROW_SSE2
void CopyRow_SSE2(const uint8_t* src, uint8_t* dst, int width) {
asm volatile(
"test $0xf,%0 \n"
"jne 2f \n"
"test $0xf,%1 \n"
"jne 2f \n"
LABELALIGN
"1: \n"
"movdqa (%0),%%xmm0 \n"
"movdqa 0x10(%0),%%xmm1 \n"
"lea 0x20(%0),%0 \n"
"movdqa %%xmm0,(%1) \n"
"movdqa %%xmm1,0x10(%1) \n"
"lea 0x20(%1),%1 \n"
"sub $0x20,%2 \n"
"jg 1b \n"
"jmp 9f \n"
LABELALIGN
"2: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"lea 0x20(%0),%0 \n"
"movdqu %%xmm0,(%1) \n"
"movdqu %%xmm1,0x10(%1) \n"
"lea 0x20(%1),%1 \n"
"sub $0x20,%2 \n"
"jg 2b \n"
LABELALIGN "9: \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
:
: "memory", "cc", "xmm0", "xmm1");
}
#endif // HAS_COPYROW_SSE2
#ifdef HAS_COPYROW_AVX
void CopyRow_AVX(const uint8_t* src, uint8_t* dst, int width) {
asm volatile(
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm0 \n"
"vmovdqu 0x20(%0),%%ymm1 \n"
"lea 0x40(%0),%0 \n"
"vmovdqu %%ymm0,(%1) \n"
"vmovdqu %%ymm1,0x20(%1) \n"
"lea 0x40(%1),%1 \n"
"sub $0x40,%2 \n"
"jg 1b \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
:
: "memory", "cc", "xmm0", "xmm1");
}
#endif // HAS_COPYROW_AVX
#ifdef HAS_COPYROW_ERMS
// Multiple of 1.
void CopyRow_ERMS(const uint8_t* src, uint8_t* dst, int width) {
size_t width_tmp = (size_t)(width);
asm volatile(
"rep movsb \n"
: "+S"(src), // %0
"+D"(dst), // %1
"+c"(width_tmp) // %2
:
: "memory", "cc");
}
#endif // HAS_COPYROW_ERMS
#ifdef HAS_ARGBCOPYALPHAROW_SSE2
// width in pixels
void ARGBCopyAlphaRow_SSE2(const uint8_t* src, uint8_t* dst, int width) {
asm volatile(
"pcmpeqb %%xmm0,%%xmm0 \n"
"pslld $0x18,%%xmm0 \n"
"pcmpeqb %%xmm1,%%xmm1 \n"
"psrld $0x8,%%xmm1 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm2 \n"
"movdqu 0x10(%0),%%xmm3 \n"
"lea 0x20(%0),%0 \n"
"movdqu (%1),%%xmm4 \n"
"movdqu 0x10(%1),%%xmm5 \n"
"pand %%xmm0,%%xmm2 \n"
"pand %%xmm0,%%xmm3 \n"
"pand %%xmm1,%%xmm4 \n"
"pand %%xmm1,%%xmm5 \n"
"por %%xmm4,%%xmm2 \n"
"por %%xmm5,%%xmm3 \n"
"movdqu %%xmm2,(%1) \n"
"movdqu %%xmm3,0x10(%1) \n"
"lea 0x20(%1),%1 \n"
"sub $0x8,%2 \n"
"jg 1b \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
:
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5");
}
#endif // HAS_ARGBCOPYALPHAROW_SSE2
#ifdef HAS_ARGBCOPYALPHAROW_AVX2
// width in pixels
void ARGBCopyAlphaRow_AVX2(const uint8_t* src, uint8_t* dst, int width) {
asm volatile(
"vpcmpeqb %%ymm0,%%ymm0,%%ymm0 \n"
"vpsrld $0x8,%%ymm0,%%ymm0 \n"
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm1 \n"
"vmovdqu 0x20(%0),%%ymm2 \n"
"lea 0x40(%0),%0 \n"
"vpblendvb %%ymm0,(%1),%%ymm1,%%ymm1 \n"
"vpblendvb %%ymm0,0x20(%1),%%ymm2,%%ymm2 \n"
"vmovdqu %%ymm1,(%1) \n"
"vmovdqu %%ymm2,0x20(%1) \n"
"lea 0x40(%1),%1 \n"
"sub $0x10,%2 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
:
: "memory", "cc", "xmm0", "xmm1", "xmm2");
}
#endif // HAS_ARGBCOPYALPHAROW_AVX2
#ifdef HAS_ARGBEXTRACTALPHAROW_SSE2
// width in pixels
void ARGBExtractAlphaRow_SSE2(const uint8_t* src_argb,
uint8_t* dst_a,
int width) {
asm volatile(
LABELALIGN
"1: \n"
"movdqu (%0), %%xmm0 \n"
"movdqu 0x10(%0), %%xmm1 \n"
"lea 0x20(%0), %0 \n"
"psrld $0x18, %%xmm0 \n"
"psrld $0x18, %%xmm1 \n"
"packssdw %%xmm1, %%xmm0 \n"
"packuswb %%xmm0, %%xmm0 \n"
"movq %%xmm0,(%1) \n"
"lea 0x8(%1), %1 \n"
"sub $0x8, %2 \n"
"jg 1b \n"
: "+r"(src_argb), // %0
"+r"(dst_a), // %1
"+rm"(width) // %2
:
: "memory", "cc", "xmm0", "xmm1");
}
#endif // HAS_ARGBEXTRACTALPHAROW_SSE2
#ifdef HAS_ARGBEXTRACTALPHAROW_AVX2
static const uvec8 kShuffleAlphaShort_AVX2 = {
3u, 128u, 128u, 128u, 7u, 128u, 128u, 128u,
11u, 128u, 128u, 128u, 15u, 128u, 128u, 128u};
void ARGBExtractAlphaRow_AVX2(const uint8_t* src_argb,
uint8_t* dst_a,
int width) {
asm volatile(
"vmovdqa %3,%%ymm4 \n"
"vbroadcastf128 %4,%%ymm5 \n"
LABELALIGN
"1: \n"
"vmovdqu (%0), %%ymm0 \n"
"vmovdqu 0x20(%0), %%ymm1 \n"
"vpshufb %%ymm5,%%ymm0,%%ymm0 \n" // vpsrld $0x18, %%ymm0
"vpshufb %%ymm5,%%ymm1,%%ymm1 \n"
"vmovdqu 0x40(%0), %%ymm2 \n"
"vmovdqu 0x60(%0), %%ymm3 \n"
"lea 0x80(%0), %0 \n"
"vpackssdw %%ymm1, %%ymm0, %%ymm0 \n" // mutates
"vpshufb %%ymm5,%%ymm2,%%ymm2 \n"
"vpshufb %%ymm5,%%ymm3,%%ymm3 \n"
"vpackssdw %%ymm3, %%ymm2, %%ymm2 \n" // mutates
"vpackuswb %%ymm2,%%ymm0,%%ymm0 \n" // mutates.
"vpermd %%ymm0,%%ymm4,%%ymm0 \n" // unmutate.
"vmovdqu %%ymm0,(%1) \n"
"lea 0x20(%1),%1 \n"
"sub $0x20, %2 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_argb), // %0
"+r"(dst_a), // %1
"+rm"(width) // %2
: "m"(kPermdARGBToY_AVX), // %3
"m"(kShuffleAlphaShort_AVX2) // %4
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5");
}
#endif // HAS_ARGBEXTRACTALPHAROW_AVX2
#ifdef HAS_ARGBCOPYYTOALPHAROW_SSE2
// width in pixels
void ARGBCopyYToAlphaRow_SSE2(const uint8_t* src, uint8_t* dst, int width) {
asm volatile(
"pcmpeqb %%xmm0,%%xmm0 \n"
"pslld $0x18,%%xmm0 \n"
"pcmpeqb %%xmm1,%%xmm1 \n"
"psrld $0x8,%%xmm1 \n"
LABELALIGN
"1: \n"
"movq (%0),%%xmm2 \n"
"lea 0x8(%0),%0 \n"
"punpcklbw %%xmm2,%%xmm2 \n"
"punpckhwd %%xmm2,%%xmm3 \n"
"punpcklwd %%xmm2,%%xmm2 \n"
"movdqu (%1),%%xmm4 \n"
"movdqu 0x10(%1),%%xmm5 \n"
"pand %%xmm0,%%xmm2 \n"
"pand %%xmm0,%%xmm3 \n"
"pand %%xmm1,%%xmm4 \n"
"pand %%xmm1,%%xmm5 \n"
"por %%xmm4,%%xmm2 \n"
"por %%xmm5,%%xmm3 \n"
"movdqu %%xmm2,(%1) \n"
"movdqu %%xmm3,0x10(%1) \n"
"lea 0x20(%1),%1 \n"
"sub $0x8,%2 \n"
"jg 1b \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
:
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5");
}
#endif // HAS_ARGBCOPYYTOALPHAROW_SSE2
#ifdef HAS_ARGBCOPYYTOALPHAROW_AVX2
// width in pixels
void ARGBCopyYToAlphaRow_AVX2(const uint8_t* src, uint8_t* dst, int width) {
asm volatile(
"vpcmpeqb %%ymm0,%%ymm0,%%ymm0 \n"
"vpsrld $0x8,%%ymm0,%%ymm0 \n"
LABELALIGN
"1: \n"
"vpmovzxbd (%0),%%ymm1 \n"
"vpmovzxbd 0x8(%0),%%ymm2 \n"
"lea 0x10(%0),%0 \n"
"vpslld $0x18,%%ymm1,%%ymm1 \n"
"vpslld $0x18,%%ymm2,%%ymm2 \n"
"vpblendvb %%ymm0,(%1),%%ymm1,%%ymm1 \n"
"vpblendvb %%ymm0,0x20(%1),%%ymm2,%%ymm2 \n"
"vmovdqu %%ymm1,(%1) \n"
"vmovdqu %%ymm2,0x20(%1) \n"
"lea 0x40(%1),%1 \n"
"sub $0x10,%2 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
:
: "memory", "cc", "xmm0", "xmm1", "xmm2");
}
#endif // HAS_ARGBCOPYYTOALPHAROW_AVX2
#ifdef HAS_SETROW_X86
void SetRow_X86(uint8_t* dst, uint8_t v8, int width) {
size_t width_tmp = (size_t)(width >> 2);
const uint32_t v32 = v8 * 0x01010101u; // Duplicate byte to all bytes.
asm volatile(
"rep stosl \n"
: "+D"(dst), // %0
"+c"(width_tmp) // %1
: "a"(v32) // %2
: "memory", "cc");
}
void SetRow_ERMS(uint8_t* dst, uint8_t v8, int width) {
size_t width_tmp = (size_t)(width);
asm volatile(
"rep stosb \n"
: "+D"(dst), // %0
"+c"(width_tmp) // %1
: "a"(v8) // %2
: "memory", "cc");
}
void ARGBSetRow_X86(uint8_t* dst_argb, uint32_t v32, int width) {
size_t width_tmp = (size_t)(width);
asm volatile(
"rep stosl \n"
: "+D"(dst_argb), // %0
"+c"(width_tmp) // %1
: "a"(v32) // %2
: "memory", "cc");
}
#endif // HAS_SETROW_X86
#ifdef HAS_YUY2TOYROW_SSE2
void YUY2ToYRow_SSE2(const uint8_t* src_yuy2, uint8_t* dst_y, int width) {
asm volatile(
"pcmpeqb %%xmm5,%%xmm5 \n"
"psrlw $0x8,%%xmm5 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"lea 0x20(%0),%0 \n"
"pand %%xmm5,%%xmm0 \n"
"pand %%xmm5,%%xmm1 \n"
"packuswb %%xmm1,%%xmm0 \n"
"movdqu %%xmm0,(%1) \n"
"lea 0x10(%1),%1 \n"
"sub $0x10,%2 \n"
"jg 1b \n"
: "+r"(src_yuy2), // %0
"+r"(dst_y), // %1
"+r"(width) // %2
:
: "memory", "cc", "xmm0", "xmm1", "xmm5");
}
void YUY2ToUVRow_SSE2(const uint8_t* src_yuy2,
int stride_yuy2,
uint8_t* dst_u,
uint8_t* dst_v,
int width) {
asm volatile(
"pcmpeqb %%xmm5,%%xmm5 \n"
"psrlw $0x8,%%xmm5 \n"
"sub %1,%2 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"movdqu 0x00(%0,%4,1),%%xmm2 \n"
"movdqu 0x10(%0,%4,1),%%xmm3 \n"
"lea 0x20(%0),%0 \n"
"pavgb %%xmm2,%%xmm0 \n"
"pavgb %%xmm3,%%xmm1 \n"
"psrlw $0x8,%%xmm0 \n"
"psrlw $0x8,%%xmm1 \n"
"packuswb %%xmm1,%%xmm0 \n"
"movdqa %%xmm0,%%xmm1 \n"
"pand %%xmm5,%%xmm0 \n"
"packuswb %%xmm0,%%xmm0 \n"
"psrlw $0x8,%%xmm1 \n"
"packuswb %%xmm1,%%xmm1 \n"
"movq %%xmm0,(%1) \n"
"movq %%xmm1,0x00(%1,%2,1) \n"
"lea 0x8(%1),%1 \n"
"sub $0x10,%3 \n"
"jg 1b \n"
: "+r"(src_yuy2), // %0
"+r"(dst_u), // %1
"+r"(dst_v), // %2
"+r"(width) // %3
: "r"((intptr_t)(stride_yuy2)) // %4
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm5");
}
void YUY2ToUV422Row_SSE2(const uint8_t* src_yuy2,
uint8_t* dst_u,
uint8_t* dst_v,
int width) {
asm volatile(
"pcmpeqb %%xmm5,%%xmm5 \n"
"psrlw $0x8,%%xmm5 \n"
"sub %1,%2 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"lea 0x20(%0),%0 \n"
"psrlw $0x8,%%xmm0 \n"
"psrlw $0x8,%%xmm1 \n"
"packuswb %%xmm1,%%xmm0 \n"
"movdqa %%xmm0,%%xmm1 \n"
"pand %%xmm5,%%xmm0 \n"
"packuswb %%xmm0,%%xmm0 \n"
"psrlw $0x8,%%xmm1 \n"
"packuswb %%xmm1,%%xmm1 \n"
"movq %%xmm0,(%1) \n"
"movq %%xmm1,0x00(%1,%2,1) \n"
"lea 0x8(%1),%1 \n"
"sub $0x10,%3 \n"
"jg 1b \n"
: "+r"(src_yuy2), // %0
"+r"(dst_u), // %1
"+r"(dst_v), // %2
"+r"(width) // %3
:
: "memory", "cc", "xmm0", "xmm1", "xmm5");
}
void UYVYToYRow_SSE2(const uint8_t* src_uyvy, uint8_t* dst_y, int width) {
asm volatile(
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"lea 0x20(%0),%0 \n"
"psrlw $0x8,%%xmm0 \n"
"psrlw $0x8,%%xmm1 \n"
"packuswb %%xmm1,%%xmm0 \n"
"movdqu %%xmm0,(%1) \n"
"lea 0x10(%1),%1 \n"
"sub $0x10,%2 \n"
"jg 1b \n"
: "+r"(src_uyvy), // %0
"+r"(dst_y), // %1
"+r"(width) // %2
:
: "memory", "cc", "xmm0", "xmm1");
}
void UYVYToUVRow_SSE2(const uint8_t* src_uyvy,
int stride_uyvy,
uint8_t* dst_u,
uint8_t* dst_v,
int width) {
asm volatile(
"pcmpeqb %%xmm5,%%xmm5 \n"
"psrlw $0x8,%%xmm5 \n"
"sub %1,%2 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"movdqu 0x00(%0,%4,1),%%xmm2 \n"
"movdqu 0x10(%0,%4,1),%%xmm3 \n"
"lea 0x20(%0),%0 \n"
"pavgb %%xmm2,%%xmm0 \n"
"pavgb %%xmm3,%%xmm1 \n"
"pand %%xmm5,%%xmm0 \n"
"pand %%xmm5,%%xmm1 \n"
"packuswb %%xmm1,%%xmm0 \n"
"movdqa %%xmm0,%%xmm1 \n"
"pand %%xmm5,%%xmm0 \n"
"packuswb %%xmm0,%%xmm0 \n"
"psrlw $0x8,%%xmm1 \n"
"packuswb %%xmm1,%%xmm1 \n"
"movq %%xmm0,(%1) \n"
"movq %%xmm1,0x00(%1,%2,1) \n"
"lea 0x8(%1),%1 \n"
"sub $0x10,%3 \n"
"jg 1b \n"
: "+r"(src_uyvy), // %0
"+r"(dst_u), // %1
"+r"(dst_v), // %2
"+r"(width) // %3
: "r"((intptr_t)(stride_uyvy)) // %4
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm5");
}
void UYVYToUV422Row_SSE2(const uint8_t* src_uyvy,
uint8_t* dst_u,
uint8_t* dst_v,
int width) {
asm volatile(
"pcmpeqb %%xmm5,%%xmm5 \n"
"psrlw $0x8,%%xmm5 \n"
"sub %1,%2 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"lea 0x20(%0),%0 \n"
"pand %%xmm5,%%xmm0 \n"
"pand %%xmm5,%%xmm1 \n"
"packuswb %%xmm1,%%xmm0 \n"
"movdqa %%xmm0,%%xmm1 \n"
"pand %%xmm5,%%xmm0 \n"
"packuswb %%xmm0,%%xmm0 \n"
"psrlw $0x8,%%xmm1 \n"
"packuswb %%xmm1,%%xmm1 \n"
"movq %%xmm0,(%1) \n"
"movq %%xmm1,0x00(%1,%2,1) \n"
"lea 0x8(%1),%1 \n"
"sub $0x10,%3 \n"
"jg 1b \n"
: "+r"(src_uyvy), // %0
"+r"(dst_u), // %1
"+r"(dst_v), // %2
"+r"(width) // %3
:
: "memory", "cc", "xmm0", "xmm1", "xmm5");
}
#endif // HAS_YUY2TOYROW_SSE2
#ifdef HAS_YUY2TOYROW_AVX2
void YUY2ToYRow_AVX2(const uint8_t* src_yuy2, uint8_t* dst_y, int width) {
asm volatile(
"vpcmpeqb %%ymm5,%%ymm5,%%ymm5 \n"
"vpsrlw $0x8,%%ymm5,%%ymm5 \n"
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm0 \n"
"vmovdqu 0x20(%0),%%ymm1 \n"
"lea 0x40(%0),%0 \n"
"vpand %%ymm5,%%ymm0,%%ymm0 \n"
"vpand %%ymm5,%%ymm1,%%ymm1 \n"
"vpackuswb %%ymm1,%%ymm0,%%ymm0 \n"
"vpermq $0xd8,%%ymm0,%%ymm0 \n"
"vmovdqu %%ymm0,(%1) \n"
"lea 0x20(%1),%1 \n"
"sub $0x20,%2 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_yuy2), // %0
"+r"(dst_y), // %1
"+r"(width) // %2
:
: "memory", "cc", "xmm0", "xmm1", "xmm5");
}
void YUY2ToUVRow_AVX2(const uint8_t* src_yuy2,
int stride_yuy2,
uint8_t* dst_u,
uint8_t* dst_v,
int width) {
asm volatile(
"vpcmpeqb %%ymm5,%%ymm5,%%ymm5 \n"
"vpsrlw $0x8,%%ymm5,%%ymm5 \n"
"sub %1,%2 \n"
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm0 \n"
"vmovdqu 0x20(%0),%%ymm1 \n"
"vpavgb 0x00(%0,%4,1),%%ymm0,%%ymm0 \n"
"vpavgb 0x20(%0,%4,1),%%ymm1,%%ymm1 \n"
"lea 0x40(%0),%0 \n"
"vpsrlw $0x8,%%ymm0,%%ymm0 \n"
"vpsrlw $0x8,%%ymm1,%%ymm1 \n"
"vpackuswb %%ymm1,%%ymm0,%%ymm0 \n"
"vpermq $0xd8,%%ymm0,%%ymm0 \n"
"vpand %%ymm5,%%ymm0,%%ymm1 \n"
"vpsrlw $0x8,%%ymm0,%%ymm0 \n"
"vpackuswb %%ymm1,%%ymm1,%%ymm1 \n"
"vpackuswb %%ymm0,%%ymm0,%%ymm0 \n"
"vpermq $0xd8,%%ymm1,%%ymm1 \n"
"vpermq $0xd8,%%ymm0,%%ymm0 \n"
"vextractf128 $0x0,%%ymm1,(%1) \n"
"vextractf128 $0x0,%%ymm0,0x00(%1,%2,1) \n"
"lea 0x10(%1),%1 \n"
"sub $0x20,%3 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_yuy2), // %0
"+r"(dst_u), // %1
"+r"(dst_v), // %2
"+r"(width) // %3
: "r"((intptr_t)(stride_yuy2)) // %4
: "memory", "cc", "xmm0", "xmm1", "xmm5");
}
void YUY2ToUV422Row_AVX2(const uint8_t* src_yuy2,
uint8_t* dst_u,
uint8_t* dst_v,
int width) {
asm volatile(
"vpcmpeqb %%ymm5,%%ymm5,%%ymm5 \n"
"vpsrlw $0x8,%%ymm5,%%ymm5 \n"
"sub %1,%2 \n"
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm0 \n"
"vmovdqu 0x20(%0),%%ymm1 \n"
"lea 0x40(%0),%0 \n"
"vpsrlw $0x8,%%ymm0,%%ymm0 \n"
"vpsrlw $0x8,%%ymm1,%%ymm1 \n"
"vpackuswb %%ymm1,%%ymm0,%%ymm0 \n"
"vpermq $0xd8,%%ymm0,%%ymm0 \n"
"vpand %%ymm5,%%ymm0,%%ymm1 \n"
"vpsrlw $0x8,%%ymm0,%%ymm0 \n"
"vpackuswb %%ymm1,%%ymm1,%%ymm1 \n"
"vpackuswb %%ymm0,%%ymm0,%%ymm0 \n"
"vpermq $0xd8,%%ymm1,%%ymm1 \n"
"vpermq $0xd8,%%ymm0,%%ymm0 \n"
"vextractf128 $0x0,%%ymm1,(%1) \n"
"vextractf128 $0x0,%%ymm0,0x00(%1,%2,1) \n"
"lea 0x10(%1),%1 \n"
"sub $0x20,%3 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_yuy2), // %0
"+r"(dst_u), // %1
"+r"(dst_v), // %2
"+r"(width) // %3
:
: "memory", "cc", "xmm0", "xmm1", "xmm5");
}
void UYVYToYRow_AVX2(const uint8_t* src_uyvy, uint8_t* dst_y, int width) {
asm volatile(
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm0 \n"
"vmovdqu 0x20(%0),%%ymm1 \n"
"lea 0x40(%0),%0 \n"
"vpsrlw $0x8,%%ymm0,%%ymm0 \n"
"vpsrlw $0x8,%%ymm1,%%ymm1 \n"
"vpackuswb %%ymm1,%%ymm0,%%ymm0 \n"
"vpermq $0xd8,%%ymm0,%%ymm0 \n"
"vmovdqu %%ymm0,(%1) \n"
"lea 0x20(%1),%1 \n"
"sub $0x20,%2 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_uyvy), // %0
"+r"(dst_y), // %1
"+r"(width) // %2
:
: "memory", "cc", "xmm0", "xmm1", "xmm5");
}
void UYVYToUVRow_AVX2(const uint8_t* src_uyvy,
int stride_uyvy,
uint8_t* dst_u,
uint8_t* dst_v,
int width) {
asm volatile(
"vpcmpeqb %%ymm5,%%ymm5,%%ymm5 \n"
"vpsrlw $0x8,%%ymm5,%%ymm5 \n"
"sub %1,%2 \n"
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm0 \n"
"vmovdqu 0x20(%0),%%ymm1 \n"
"vpavgb 0x00(%0,%4,1),%%ymm0,%%ymm0 \n"
"vpavgb 0x20(%0,%4,1),%%ymm1,%%ymm1 \n"
"lea 0x40(%0),%0 \n"
"vpand %%ymm5,%%ymm0,%%ymm0 \n"
"vpand %%ymm5,%%ymm1,%%ymm1 \n"
"vpackuswb %%ymm1,%%ymm0,%%ymm0 \n"
"vpermq $0xd8,%%ymm0,%%ymm0 \n"
"vpand %%ymm5,%%ymm0,%%ymm1 \n"
"vpsrlw $0x8,%%ymm0,%%ymm0 \n"
"vpackuswb %%ymm1,%%ymm1,%%ymm1 \n"
"vpackuswb %%ymm0,%%ymm0,%%ymm0 \n"
"vpermq $0xd8,%%ymm1,%%ymm1 \n"
"vpermq $0xd8,%%ymm0,%%ymm0 \n"
"vextractf128 $0x0,%%ymm1,(%1) \n"
"vextractf128 $0x0,%%ymm0,0x00(%1,%2,1) \n"
"lea 0x10(%1),%1 \n"
"sub $0x20,%3 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_uyvy), // %0
"+r"(dst_u), // %1
"+r"(dst_v), // %2
"+r"(width) // %3
: "r"((intptr_t)(stride_uyvy)) // %4
: "memory", "cc", "xmm0", "xmm1", "xmm5");
}
void UYVYToUV422Row_AVX2(const uint8_t* src_uyvy,
uint8_t* dst_u,
uint8_t* dst_v,
int width) {
asm volatile(
"vpcmpeqb %%ymm5,%%ymm5,%%ymm5 \n"
"vpsrlw $0x8,%%ymm5,%%ymm5 \n"
"sub %1,%2 \n"
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm0 \n"
"vmovdqu 0x20(%0),%%ymm1 \n"
"lea 0x40(%0),%0 \n"
"vpand %%ymm5,%%ymm0,%%ymm0 \n"
"vpand %%ymm5,%%ymm1,%%ymm1 \n"
"vpackuswb %%ymm1,%%ymm0,%%ymm0 \n"
"vpermq $0xd8,%%ymm0,%%ymm0 \n"
"vpand %%ymm5,%%ymm0,%%ymm1 \n"
"vpsrlw $0x8,%%ymm0,%%ymm0 \n"
"vpackuswb %%ymm1,%%ymm1,%%ymm1 \n"
"vpackuswb %%ymm0,%%ymm0,%%ymm0 \n"
"vpermq $0xd8,%%ymm1,%%ymm1 \n"
"vpermq $0xd8,%%ymm0,%%ymm0 \n"
"vextractf128 $0x0,%%ymm1,(%1) \n"
"vextractf128 $0x0,%%ymm0,0x00(%1,%2,1) \n"
"lea 0x10(%1),%1 \n"
"sub $0x20,%3 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_uyvy), // %0
"+r"(dst_u), // %1
"+r"(dst_v), // %2
"+r"(width) // %3
:
: "memory", "cc", "xmm0", "xmm1", "xmm5");
}
#endif // HAS_YUY2TOYROW_AVX2
#ifdef HAS_ARGBBLENDROW_SSSE3
// Shuffle table for isolating alpha.
static const uvec8 kShuffleAlpha = {3u, 0x80, 3u, 0x80, 7u, 0x80, 7u, 0x80,
11u, 0x80, 11u, 0x80, 15u, 0x80, 15u, 0x80};
// Blend 8 pixels at a time
void ARGBBlendRow_SSSE3(const uint8_t* src_argb0,
const uint8_t* src_argb1,
uint8_t* dst_argb,
int width) {
asm volatile(
"pcmpeqb %%xmm7,%%xmm7 \n"
"psrlw $0xf,%%xmm7 \n"
"pcmpeqb %%xmm6,%%xmm6 \n"
"psrlw $0x8,%%xmm6 \n"
"pcmpeqb %%xmm5,%%xmm5 \n"
"psllw $0x8,%%xmm5 \n"
"pcmpeqb %%xmm4,%%xmm4 \n"
"pslld $0x18,%%xmm4 \n"
"sub $0x4,%3 \n"
"jl 49f \n"
// 4 pixel loop.
LABELALIGN
"40: \n"
"movdqu (%0),%%xmm3 \n"
"lea 0x10(%0),%0 \n"
"movdqa %%xmm3,%%xmm0 \n"
"pxor %%xmm4,%%xmm3 \n"
"movdqu (%1),%%xmm2 \n"
"pshufb %4,%%xmm3 \n"
"pand %%xmm6,%%xmm2 \n"
"paddw %%xmm7,%%xmm3 \n"
"pmullw %%xmm3,%%xmm2 \n"
"movdqu (%1),%%xmm1 \n"
"lea 0x10(%1),%1 \n"
"psrlw $0x8,%%xmm1 \n"
"por %%xmm4,%%xmm0 \n"
"pmullw %%xmm3,%%xmm1 \n"
"psrlw $0x8,%%xmm2 \n"
"paddusb %%xmm2,%%xmm0 \n"
"pand %%xmm5,%%xmm1 \n"
"paddusb %%xmm1,%%xmm0 \n"
"movdqu %%xmm0,(%2) \n"
"lea 0x10(%2),%2 \n"
"sub $0x4,%3 \n"
"jge 40b \n"
"49: \n"
"add $0x3,%3 \n"
"jl 99f \n"
// 1 pixel loop.
"91: \n"
"movd (%0),%%xmm3 \n"
"lea 0x4(%0),%0 \n"
"movdqa %%xmm3,%%xmm0 \n"
"pxor %%xmm4,%%xmm3 \n"
"movd (%1),%%xmm2 \n"
"pshufb %4,%%xmm3 \n"
"pand %%xmm6,%%xmm2 \n"
"paddw %%xmm7,%%xmm3 \n"
"pmullw %%xmm3,%%xmm2 \n"
"movd (%1),%%xmm1 \n"
"lea 0x4(%1),%1 \n"
"psrlw $0x8,%%xmm1 \n"
"por %%xmm4,%%xmm0 \n"
"pmullw %%xmm3,%%xmm1 \n"
"psrlw $0x8,%%xmm2 \n"
"paddusb %%xmm2,%%xmm0 \n"
"pand %%xmm5,%%xmm1 \n"
"paddusb %%xmm1,%%xmm0 \n"
"movd %%xmm0,(%2) \n"
"lea 0x4(%2),%2 \n"
"sub $0x1,%3 \n"
"jge 91b \n"
"99: \n"
: "+r"(src_argb0), // %0
"+r"(src_argb1), // %1
"+r"(dst_argb), // %2
"+r"(width) // %3
: "m"(kShuffleAlpha) // %4
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6",
"xmm7");
}
#endif // HAS_ARGBBLENDROW_SSSE3
#ifdef HAS_BLENDPLANEROW_SSSE3
// Blend 8 pixels at a time.
// unsigned version of math
// =((A2*C2)+(B2*(255-C2))+255)/256
// signed version of math
// =(((A2-128)*C2)+((B2-128)*(255-C2))+32768+127)/256
void BlendPlaneRow_SSSE3(const uint8_t* src0,
const uint8_t* src1,
const uint8_t* alpha,
uint8_t* dst,
int width) {
asm volatile(
"pcmpeqb %%xmm5,%%xmm5 \n"
"psllw $0x8,%%xmm5 \n"
"mov $0x80808080,%%eax \n"
"movd %%eax,%%xmm6 \n"
"pshufd $0x0,%%xmm6,%%xmm6 \n"
"mov $0x807f807f,%%eax \n"
"movd %%eax,%%xmm7 \n"
"pshufd $0x0,%%xmm7,%%xmm7 \n"
"sub %2,%0 \n"
"sub %2,%1 \n"
"sub %2,%3 \n"
// 8 pixel loop.
LABELALIGN
"1: \n"
"movq (%2),%%xmm0 \n"
"punpcklbw %%xmm0,%%xmm0 \n"
"pxor %%xmm5,%%xmm0 \n"
"movq (%0,%2,1),%%xmm1 \n"
"movq (%1,%2,1),%%xmm2 \n"
"punpcklbw %%xmm2,%%xmm1 \n"
"psubb %%xmm6,%%xmm1 \n"
"pmaddubsw %%xmm1,%%xmm0 \n"
"paddw %%xmm7,%%xmm0 \n"
"psrlw $0x8,%%xmm0 \n"
"packuswb %%xmm0,%%xmm0 \n"
"movq %%xmm0,(%3,%2,1) \n"
"lea 0x8(%2),%2 \n"
"sub $0x8,%4 \n"
"jg 1b \n"
: "+r"(src0), // %0
"+r"(src1), // %1
"+r"(alpha), // %2
"+r"(dst), // %3
"+rm"(width) // %4
::"memory",
"cc", "eax", "xmm0", "xmm1", "xmm2", "xmm5", "xmm6", "xmm7");
}
#endif // HAS_BLENDPLANEROW_SSSE3
#ifdef HAS_BLENDPLANEROW_AVX2
// Blend 32 pixels at a time.
// unsigned version of math
// =((A2*C2)+(B2*(255-C2))+255)/256
// signed version of math
// =(((A2-128)*C2)+((B2-128)*(255-C2))+32768+127)/256
void BlendPlaneRow_AVX2(const uint8_t* src0,
const uint8_t* src1,
const uint8_t* alpha,
uint8_t* dst,
int width) {
asm volatile(
"vpcmpeqb %%ymm5,%%ymm5,%%ymm5 \n"
"vpsllw $0x8,%%ymm5,%%ymm5 \n"
"mov $0x80808080,%%eax \n"
"vmovd %%eax,%%xmm6 \n"
"vbroadcastss %%xmm6,%%ymm6 \n"
"mov $0x807f807f,%%eax \n"
"vmovd %%eax,%%xmm7 \n"
"vbroadcastss %%xmm7,%%ymm7 \n"
"sub %2,%0 \n"
"sub %2,%1 \n"
"sub %2,%3 \n"
// 32 pixel loop.
LABELALIGN
"1: \n"
"vmovdqu (%2),%%ymm0 \n"
"vpunpckhbw %%ymm0,%%ymm0,%%ymm3 \n"
"vpunpcklbw %%ymm0,%%ymm0,%%ymm0 \n"
"vpxor %%ymm5,%%ymm3,%%ymm3 \n"
"vpxor %%ymm5,%%ymm0,%%ymm0 \n"
"vmovdqu (%0,%2,1),%%ymm1 \n"
"vmovdqu (%1,%2,1),%%ymm2 \n"
"vpunpckhbw %%ymm2,%%ymm1,%%ymm4 \n"
"vpunpcklbw %%ymm2,%%ymm1,%%ymm1 \n"
"vpsubb %%ymm6,%%ymm4,%%ymm4 \n"
"vpsubb %%ymm6,%%ymm1,%%ymm1 \n"
"vpmaddubsw %%ymm4,%%ymm3,%%ymm3 \n"
"vpmaddubsw %%ymm1,%%ymm0,%%ymm0 \n"
"vpaddw %%ymm7,%%ymm3,%%ymm3 \n"
"vpaddw %%ymm7,%%ymm0,%%ymm0 \n"
"vpsrlw $0x8,%%ymm3,%%ymm3 \n"
"vpsrlw $0x8,%%ymm0,%%ymm0 \n"
"vpackuswb %%ymm3,%%ymm0,%%ymm0 \n"
"vmovdqu %%ymm0,(%3,%2,1) \n"
"lea 0x20(%2),%2 \n"
"sub $0x20,%4 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src0), // %0
"+r"(src1), // %1
"+r"(alpha), // %2
"+r"(dst), // %3
"+rm"(width) // %4
::"memory",
"cc", "eax", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6",
"xmm7");
}
#endif // HAS_BLENDPLANEROW_AVX2
#ifdef HAS_ARGBATTENUATEROW_SSSE3
// Shuffle table duplicating alpha.
static const uvec8 kShuffleAlpha0 = {3u, 3u, 3u, 3u, 3u, 3u, 128u, 128u,
7u, 7u, 7u, 7u, 7u, 7u, 128u, 128u};
static const uvec8 kShuffleAlpha1 = {11u, 11u, 11u, 11u, 11u, 11u, 128u, 128u,
15u, 15u, 15u, 15u, 15u, 15u, 128u, 128u};
// Attenuate 4 pixels at a time.
void ARGBAttenuateRow_SSSE3(const uint8_t* src_argb,
uint8_t* dst_argb,
int width) {
asm volatile(
"pcmpeqb %%xmm3,%%xmm3 \n"
"pslld $0x18,%%xmm3 \n"
"movdqa %3,%%xmm4 \n"
"movdqa %4,%%xmm5 \n"
// 4 pixel loop.
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"pshufb %%xmm4,%%xmm0 \n"
"movdqu (%0),%%xmm1 \n"
"punpcklbw %%xmm1,%%xmm1 \n"
"pmulhuw %%xmm1,%%xmm0 \n"
"movdqu (%0),%%xmm1 \n"
"pshufb %%xmm5,%%xmm1 \n"
"movdqu (%0),%%xmm2 \n"
"punpckhbw %%xmm2,%%xmm2 \n"
"pmulhuw %%xmm2,%%xmm1 \n"
"movdqu (%0),%%xmm2 \n"
"lea 0x10(%0),%0 \n"
"pand %%xmm3,%%xmm2 \n"
"psrlw $0x8,%%xmm0 \n"
"psrlw $0x8,%%xmm1 \n"
"packuswb %%xmm1,%%xmm0 \n"
"por %%xmm2,%%xmm0 \n"
"movdqu %%xmm0,(%1) \n"
"lea 0x10(%1),%1 \n"
"sub $0x4,%2 \n"
"jg 1b \n"
: "+r"(src_argb), // %0
"+r"(dst_argb), // %1
"+r"(width) // %2
: "m"(kShuffleAlpha0), // %3
"m"(kShuffleAlpha1) // %4
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5");
}
#endif // HAS_ARGBATTENUATEROW_SSSE3
#ifdef HAS_ARGBATTENUATEROW_AVX2
// Shuffle table duplicating alpha.
static const uvec8 kShuffleAlpha_AVX2 = {6u, 7u, 6u, 7u, 6u, 7u,
128u, 128u, 14u, 15u, 14u, 15u,
14u, 15u, 128u, 128u};
// Attenuate 8 pixels at a time.
void ARGBAttenuateRow_AVX2(const uint8_t* src_argb,
uint8_t* dst_argb,
int width) {
asm volatile(
"vbroadcastf128 %3,%%ymm4 \n"
"vpcmpeqb %%ymm5,%%ymm5,%%ymm5 \n"
"vpslld $0x18,%%ymm5,%%ymm5 \n"
"sub %0,%1 \n"
// 8 pixel loop.
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm6 \n"
"vpunpcklbw %%ymm6,%%ymm6,%%ymm0 \n"
"vpunpckhbw %%ymm6,%%ymm6,%%ymm1 \n"
"vpshufb %%ymm4,%%ymm0,%%ymm2 \n"
"vpshufb %%ymm4,%%ymm1,%%ymm3 \n"
"vpmulhuw %%ymm2,%%ymm0,%%ymm0 \n"
"vpmulhuw %%ymm3,%%ymm1,%%ymm1 \n"
"vpand %%ymm5,%%ymm6,%%ymm6 \n"
"vpsrlw $0x8,%%ymm0,%%ymm0 \n"
"vpsrlw $0x8,%%ymm1,%%ymm1 \n"
"vpackuswb %%ymm1,%%ymm0,%%ymm0 \n"
"vpor %%ymm6,%%ymm0,%%ymm0 \n"
"vmovdqu %%ymm0,0x00(%0,%1,1) \n"
"lea 0x20(%0),%0 \n"
"sub $0x8,%2 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_argb), // %0
"+r"(dst_argb), // %1
"+r"(width) // %2
: "m"(kShuffleAlpha_AVX2) // %3
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6");
}
#endif // HAS_ARGBATTENUATEROW_AVX2
#ifdef HAS_ARGBUNATTENUATEROW_SSE2
// Unattenuate 4 pixels at a time.
void ARGBUnattenuateRow_SSE2(const uint8_t* src_argb,
uint8_t* dst_argb,
int width) {
uintptr_t alpha;
asm volatile(
// 4 pixel loop.
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movzb 0x03(%0),%3 \n"
"punpcklbw %%xmm0,%%xmm0 \n"
"movd 0x00(%4,%3,4),%%xmm2 \n"
"movzb 0x07(%0),%3 \n"
"movd 0x00(%4,%3,4),%%xmm3 \n"
"pshuflw $0x40,%%xmm2,%%xmm2 \n"
"pshuflw $0x40,%%xmm3,%%xmm3 \n"
"movlhps %%xmm3,%%xmm2 \n"
"pmulhuw %%xmm2,%%xmm0 \n"
"movdqu (%0),%%xmm1 \n"
"movzb 0x0b(%0),%3 \n"
"punpckhbw %%xmm1,%%xmm1 \n"
"movd 0x00(%4,%3,4),%%xmm2 \n"
"movzb 0x0f(%0),%3 \n"
"movd 0x00(%4,%3,4),%%xmm3 \n"
"pshuflw $0x40,%%xmm2,%%xmm2 \n"
"pshuflw $0x40,%%xmm3,%%xmm3 \n"
"movlhps %%xmm3,%%xmm2 \n"
"pmulhuw %%xmm2,%%xmm1 \n"
"lea 0x10(%0),%0 \n"
"packuswb %%xmm1,%%xmm0 \n"
"movdqu %%xmm0,(%1) \n"
"lea 0x10(%1),%1 \n"
"sub $0x4,%2 \n"
"jg 1b \n"
: "+r"(src_argb), // %0
"+r"(dst_argb), // %1
"+r"(width), // %2
"=&r"(alpha) // %3
: "r"(fixed_invtbl8) // %4
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5");
}
#endif // HAS_ARGBUNATTENUATEROW_SSE2
#ifdef HAS_ARGBUNATTENUATEROW_AVX2
// Shuffle table duplicating alpha.
static const uvec8 kUnattenShuffleAlpha_AVX2 = {
0u, 1u, 0u, 1u, 0u, 1u, 6u, 7u, 8u, 9u, 8u, 9u, 8u, 9u, 14u, 15u};
// Unattenuate 8 pixels at a time.
void ARGBUnattenuateRow_AVX2(const uint8_t* src_argb,
uint8_t* dst_argb,
int width) {
uintptr_t alpha;
asm volatile(
"sub %0,%1 \n"
"vbroadcastf128 %5,%%ymm5 \n"
// 8 pixel loop.
LABELALIGN
"1: \n"
// replace VPGATHER
"movzb 0x03(%0),%3 \n"
"vmovd 0x00(%4,%3,4),%%xmm0 \n"
"movzb 0x07(%0),%3 \n"
"vmovd 0x00(%4,%3,4),%%xmm1 \n"
"movzb 0x0b(%0),%3 \n"
"vpunpckldq %%xmm1,%%xmm0,%%xmm6 \n"
"vmovd 0x00(%4,%3,4),%%xmm2 \n"
"movzb 0x0f(%0),%3 \n"
"vmovd 0x00(%4,%3,4),%%xmm3 \n"
"movzb 0x13(%0),%3 \n"
"vpunpckldq %%xmm3,%%xmm2,%%xmm7 \n"
"vmovd 0x00(%4,%3,4),%%xmm0 \n"
"movzb 0x17(%0),%3 \n"
"vmovd 0x00(%4,%3,4),%%xmm1 \n"
"movzb 0x1b(%0),%3 \n"
"vpunpckldq %%xmm1,%%xmm0,%%xmm0 \n"
"vmovd 0x00(%4,%3,4),%%xmm2 \n"
"movzb 0x1f(%0),%3 \n"
"vmovd 0x00(%4,%3,4),%%xmm3 \n"
"vpunpckldq %%xmm3,%%xmm2,%%xmm2 \n"
"vpunpcklqdq %%xmm7,%%xmm6,%%xmm3 \n"
"vpunpcklqdq %%xmm2,%%xmm0,%%xmm0 \n"
"vinserti128 $0x1,%%xmm0,%%ymm3,%%ymm3 \n"
// end of VPGATHER
"vmovdqu (%0),%%ymm6 \n"
"vpunpcklbw %%ymm6,%%ymm6,%%ymm0 \n"
"vpunpckhbw %%ymm6,%%ymm6,%%ymm1 \n"
"vpunpcklwd %%ymm3,%%ymm3,%%ymm2 \n"
"vpunpckhwd %%ymm3,%%ymm3,%%ymm3 \n"
"vpshufb %%ymm5,%%ymm2,%%ymm2 \n"
"vpshufb %%ymm5,%%ymm3,%%ymm3 \n"
"vpmulhuw %%ymm2,%%ymm0,%%ymm0 \n"
"vpmulhuw %%ymm3,%%ymm1,%%ymm1 \n"
"vpackuswb %%ymm1,%%ymm0,%%ymm0 \n"
"vmovdqu %%ymm0,0x00(%0,%1,1) \n"
"lea 0x20(%0),%0 \n"
"sub $0x8,%2 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_argb), // %0
"+r"(dst_argb), // %1
"+r"(width), // %2
"=&r"(alpha) // %3
: "r"(fixed_invtbl8), // %4
"m"(kUnattenShuffleAlpha_AVX2) // %5
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6",
"xmm7");
}
#endif // HAS_ARGBUNATTENUATEROW_AVX2
#ifdef HAS_ARGBGRAYROW_SSSE3
// Convert 8 ARGB pixels (64 bytes) to 8 Gray ARGB pixels
void ARGBGrayRow_SSSE3(const uint8_t* src_argb, uint8_t* dst_argb, int width) {
asm volatile(
"movdqa %3,%%xmm4 \n"
"movdqa %4,%%xmm5 \n"
// 8 pixel loop.
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"psubb %%xmm5,%%xmm0 \n"
"psubb %%xmm5,%%xmm1 \n"
"movdqu %%xmm4,%%xmm6 \n"
"pmaddubsw %%xmm0,%%xmm6 \n"
"movdqu %%xmm4,%%xmm0 \n"
"pmaddubsw %%xmm1,%%xmm0 \n"
"phaddw %%xmm0,%%xmm6 \n"
"paddw %%xmm5,%%xmm6 \n"
"psrlw $0x8,%%xmm6 \n"
"packuswb %%xmm6,%%xmm6 \n"
"movdqu (%0),%%xmm2 \n"
"movdqu 0x10(%0),%%xmm3 \n"
"lea 0x20(%0),%0 \n"
"psrld $0x18,%%xmm2 \n"
"psrld $0x18,%%xmm3 \n"
"packuswb %%xmm3,%%xmm2 \n"
"packuswb %%xmm2,%%xmm2 \n"
"movdqa %%xmm6,%%xmm3 \n"
"punpcklbw %%xmm6,%%xmm6 \n"
"punpcklbw %%xmm2,%%xmm3 \n"
"movdqa %%xmm6,%%xmm1 \n"
"punpcklwd %%xmm3,%%xmm6 \n"
"punpckhwd %%xmm3,%%xmm1 \n"
"movdqu %%xmm6,(%1) \n"
"movdqu %%xmm1,0x10(%1) \n"
"lea 0x20(%1),%1 \n"
"sub $0x8,%2 \n"
"jg 1b \n"
: "+r"(src_argb), // %0
"+r"(dst_argb), // %1
"+r"(width) // %2
: "m"(kARGBToYJ), // %3
"m"(kSub128) // %4
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6");
}
#endif // HAS_ARGBGRAYROW_SSSE3
#ifdef HAS_ARGBSEPIAROW_SSSE3
// b = (r * 35 + g * 68 + b * 17) >> 7
// g = (r * 45 + g * 88 + b * 22) >> 7
// r = (r * 50 + g * 98 + b * 24) >> 7
// Constant for ARGB color to sepia tone
static const vec8 kARGBToSepiaB = {17, 68, 35, 0, 17, 68, 35, 0,
17, 68, 35, 0, 17, 68, 35, 0};
static const vec8 kARGBToSepiaG = {22, 88, 45, 0, 22, 88, 45, 0,
22, 88, 45, 0, 22, 88, 45, 0};
static const vec8 kARGBToSepiaR = {24, 98, 50, 0, 24, 98, 50, 0,
24, 98, 50, 0, 24, 98, 50, 0};
// Convert 8 ARGB pixels (32 bytes) to 8 Sepia ARGB pixels.
void ARGBSepiaRow_SSSE3(uint8_t* dst_argb, int width) {
asm volatile(
"movdqa %2,%%xmm2 \n"
"movdqa %3,%%xmm3 \n"
"movdqa %4,%%xmm4 \n"
// 8 pixel loop.
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x10(%0),%%xmm6 \n"
"pmaddubsw %%xmm2,%%xmm0 \n"
"pmaddubsw %%xmm2,%%xmm6 \n"
"phaddw %%xmm6,%%xmm0 \n"
"psrlw $0x7,%%xmm0 \n"
"packuswb %%xmm0,%%xmm0 \n"
"movdqu (%0),%%xmm5 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"pmaddubsw %%xmm3,%%xmm5 \n"
"pmaddubsw %%xmm3,%%xmm1 \n"
"phaddw %%xmm1,%%xmm5 \n"
"psrlw $0x7,%%xmm5 \n"
"packuswb %%xmm5,%%xmm5 \n"
"punpcklbw %%xmm5,%%xmm0 \n"
"movdqu (%0),%%xmm5 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"pmaddubsw %%xmm4,%%xmm5 \n"
"pmaddubsw %%xmm4,%%xmm1 \n"
"phaddw %%xmm1,%%xmm5 \n"
"psrlw $0x7,%%xmm5 \n"
"packuswb %%xmm5,%%xmm5 \n"
"movdqu (%0),%%xmm6 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"psrld $0x18,%%xmm6 \n"
"psrld $0x18,%%xmm1 \n"
"packuswb %%xmm1,%%xmm6 \n"
"packuswb %%xmm6,%%xmm6 \n"
"punpcklbw %%xmm6,%%xmm5 \n"
"movdqa %%xmm0,%%xmm1 \n"
"punpcklwd %%xmm5,%%xmm0 \n"
"punpckhwd %%xmm5,%%xmm1 \n"
"movdqu %%xmm0,(%0) \n"
"movdqu %%xmm1,0x10(%0) \n"
"lea 0x20(%0),%0 \n"
"sub $0x8,%1 \n"
"jg 1b \n"
: "+r"(dst_argb), // %0
"+r"(width) // %1
: "m"(kARGBToSepiaB), // %2
"m"(kARGBToSepiaG), // %3
"m"(kARGBToSepiaR) // %4
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6");
}
#endif // HAS_ARGBSEPIAROW_SSSE3
#ifdef HAS_ARGBCOLORMATRIXROW_SSSE3
// Tranform 8 ARGB pixels (32 bytes) with color matrix.
// Same as Sepia except matrix is provided.
void ARGBColorMatrixRow_SSSE3(const uint8_t* src_argb,
uint8_t* dst_argb,
const int8_t* matrix_argb,
int width) {
asm volatile(
"movdqu (%3),%%xmm5 \n"
"pshufd $0x00,%%xmm5,%%xmm2 \n"
"pshufd $0x55,%%xmm5,%%xmm3 \n"
"pshufd $0xaa,%%xmm5,%%xmm4 \n"
"pshufd $0xff,%%xmm5,%%xmm5 \n"
// 8 pixel loop.
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x10(%0),%%xmm7 \n"
"pmaddubsw %%xmm2,%%xmm0 \n"
"pmaddubsw %%xmm2,%%xmm7 \n"
"movdqu (%0),%%xmm6 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"pmaddubsw %%xmm3,%%xmm6 \n"
"pmaddubsw %%xmm3,%%xmm1 \n"
"phaddsw %%xmm7,%%xmm0 \n"
"phaddsw %%xmm1,%%xmm6 \n"
"psraw $0x6,%%xmm0 \n"
"psraw $0x6,%%xmm6 \n"
"packuswb %%xmm0,%%xmm0 \n"
"packuswb %%xmm6,%%xmm6 \n"
"punpcklbw %%xmm6,%%xmm0 \n"
"movdqu (%0),%%xmm1 \n"
"movdqu 0x10(%0),%%xmm7 \n"
"pmaddubsw %%xmm4,%%xmm1 \n"
"pmaddubsw %%xmm4,%%xmm7 \n"
"phaddsw %%xmm7,%%xmm1 \n"
"movdqu (%0),%%xmm6 \n"
"movdqu 0x10(%0),%%xmm7 \n"
"pmaddubsw %%xmm5,%%xmm6 \n"
"pmaddubsw %%xmm5,%%xmm7 \n"
"phaddsw %%xmm7,%%xmm6 \n"
"psraw $0x6,%%xmm1 \n"
"psraw $0x6,%%xmm6 \n"
"packuswb %%xmm1,%%xmm1 \n"
"packuswb %%xmm6,%%xmm6 \n"
"punpcklbw %%xmm6,%%xmm1 \n"
"movdqa %%xmm0,%%xmm6 \n"
"punpcklwd %%xmm1,%%xmm0 \n"
"punpckhwd %%xmm1,%%xmm6 \n"
"movdqu %%xmm0,(%1) \n"
"movdqu %%xmm6,0x10(%1) \n"
"lea 0x20(%0),%0 \n"
"lea 0x20(%1),%1 \n"
"sub $0x8,%2 \n"
"jg 1b \n"
: "+r"(src_argb), // %0
"+r"(dst_argb), // %1
"+r"(width) // %2
: "r"(matrix_argb) // %3
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6",
"xmm7");
}
#endif // HAS_ARGBCOLORMATRIXROW_SSSE3
#ifdef HAS_ARGBQUANTIZEROW_SSE2
// Quantize 4 ARGB pixels (16 bytes).
void ARGBQuantizeRow_SSE2(uint8_t* dst_argb,
int scale,
int interval_size,
int interval_offset,
int width) {
asm volatile(
"movd %2,%%xmm2 \n"
"movd %3,%%xmm3 \n"
"movd %4,%%xmm4 \n"
"pshuflw $0x40,%%xmm2,%%xmm2 \n"
"pshufd $0x44,%%xmm2,%%xmm2 \n"
"pshuflw $0x40,%%xmm3,%%xmm3 \n"
"pshufd $0x44,%%xmm3,%%xmm3 \n"
"pshuflw $0x40,%%xmm4,%%xmm4 \n"
"pshufd $0x44,%%xmm4,%%xmm4 \n"
"pxor %%xmm5,%%xmm5 \n"
"pcmpeqb %%xmm6,%%xmm6 \n"
"pslld $0x18,%%xmm6 \n"
// 4 pixel loop.
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"punpcklbw %%xmm5,%%xmm0 \n"
"pmulhuw %%xmm2,%%xmm0 \n"
"movdqu (%0),%%xmm1 \n"
"punpckhbw %%xmm5,%%xmm1 \n"
"pmulhuw %%xmm2,%%xmm1 \n"
"pmullw %%xmm3,%%xmm0 \n"
"movdqu (%0),%%xmm7 \n"
"pmullw %%xmm3,%%xmm1 \n"
"pand %%xmm6,%%xmm7 \n"
"paddw %%xmm4,%%xmm0 \n"
"paddw %%xmm4,%%xmm1 \n"
"packuswb %%xmm1,%%xmm0 \n"
"por %%xmm7,%%xmm0 \n"
"movdqu %%xmm0,(%0) \n"
"lea 0x10(%0),%0 \n"
"sub $0x4,%1 \n"
"jg 1b \n"
: "+r"(dst_argb), // %0
"+r"(width) // %1
: "r"(scale), // %2
"r"(interval_size), // %3
"r"(interval_offset) // %4
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6",
"xmm7");
}
#endif // HAS_ARGBQUANTIZEROW_SSE2
#ifdef HAS_ARGBSHADEROW_SSE2
// Shade 4 pixels at a time by specified value.
void ARGBShadeRow_SSE2(const uint8_t* src_argb,
uint8_t* dst_argb,
int width,
uint32_t value) {
asm volatile(
"movd %3,%%xmm2 \n"
"punpcklbw %%xmm2,%%xmm2 \n"
"punpcklqdq %%xmm2,%%xmm2 \n"
// 4 pixel loop.
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"lea 0x10(%0),%0 \n"
"movdqa %%xmm0,%%xmm1 \n"
"punpcklbw %%xmm0,%%xmm0 \n"
"punpckhbw %%xmm1,%%xmm1 \n"
"pmulhuw %%xmm2,%%xmm0 \n"
"pmulhuw %%xmm2,%%xmm1 \n"
"psrlw $0x8,%%xmm0 \n"
"psrlw $0x8,%%xmm1 \n"
"packuswb %%xmm1,%%xmm0 \n"
"movdqu %%xmm0,(%1) \n"
"lea 0x10(%1),%1 \n"
"sub $0x4,%2 \n"
"jg 1b \n"
: "+r"(src_argb), // %0
"+r"(dst_argb), // %1
"+r"(width) // %2
: "r"(value) // %3
: "memory", "cc", "xmm0", "xmm1", "xmm2");
}
#endif // HAS_ARGBSHADEROW_SSE2
#ifdef HAS_ARGBMULTIPLYROW_SSE2
// Multiply 2 rows of ARGB pixels together, 4 pixels at a time.
void ARGBMultiplyRow_SSE2(const uint8_t* src_argb0,
const uint8_t* src_argb1,
uint8_t* dst_argb,
int width) {
asm volatile(
"pxor %%xmm5,%%xmm5 \n"
// 4 pixel loop.
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"lea 0x10(%0),%0 \n"
"movdqu (%1),%%xmm2 \n"
"lea 0x10(%1),%1 \n"
"movdqu %%xmm0,%%xmm1 \n"
"movdqu %%xmm2,%%xmm3 \n"
"punpcklbw %%xmm0,%%xmm0 \n"
"punpckhbw %%xmm1,%%xmm1 \n"
"punpcklbw %%xmm5,%%xmm2 \n"
"punpckhbw %%xmm5,%%xmm3 \n"
"pmulhuw %%xmm2,%%xmm0 \n"
"pmulhuw %%xmm3,%%xmm1 \n"
"packuswb %%xmm1,%%xmm0 \n"
"movdqu %%xmm0,(%2) \n"
"lea 0x10(%2),%2 \n"
"sub $0x4,%3 \n"
"jg 1b \n"
: "+r"(src_argb0), // %0
"+r"(src_argb1), // %1
"+r"(dst_argb), // %2
"+r"(width) // %3
:
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm5");
}
#endif // HAS_ARGBMULTIPLYROW_SSE2
#ifdef HAS_ARGBMULTIPLYROW_AVX2
// Multiply 2 rows of ARGB pixels together, 8 pixels at a time.
void ARGBMultiplyRow_AVX2(const uint8_t* src_argb0,
const uint8_t* src_argb1,
uint8_t* dst_argb,
int width) {
asm volatile(
"vpxor %%ymm5,%%ymm5,%%ymm5 \n"
// 4 pixel loop.
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm1 \n"
"lea 0x20(%0),%0 \n"
"vmovdqu (%1),%%ymm3 \n"
"lea 0x20(%1),%1 \n"
"vpunpcklbw %%ymm1,%%ymm1,%%ymm0 \n"
"vpunpckhbw %%ymm1,%%ymm1,%%ymm1 \n"
"vpunpcklbw %%ymm5,%%ymm3,%%ymm2 \n"
"vpunpckhbw %%ymm5,%%ymm3,%%ymm3 \n"
"vpmulhuw %%ymm2,%%ymm0,%%ymm0 \n"
"vpmulhuw %%ymm3,%%ymm1,%%ymm1 \n"
"vpackuswb %%ymm1,%%ymm0,%%ymm0 \n"
"vmovdqu %%ymm0,(%2) \n"
"lea 0x20(%2),%2 \n"
"sub $0x8,%3 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_argb0), // %0
"+r"(src_argb1), // %1
"+r"(dst_argb), // %2
"+r"(width) // %3
:
: "memory", "cc"
#if defined(__AVX2__)
,
"xmm0", "xmm1", "xmm2", "xmm3", "xmm5"
#endif
);
}
#endif // HAS_ARGBMULTIPLYROW_AVX2
#ifdef HAS_ARGBADDROW_SSE2
// Add 2 rows of ARGB pixels together, 4 pixels at a time.
void ARGBAddRow_SSE2(const uint8_t* src_argb0,
const uint8_t* src_argb1,
uint8_t* dst_argb,
int width) {
asm volatile(
// 4 pixel loop.
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"lea 0x10(%0),%0 \n"
"movdqu (%1),%%xmm1 \n"
"lea 0x10(%1),%1 \n"
"paddusb %%xmm1,%%xmm0 \n"
"movdqu %%xmm0,(%2) \n"
"lea 0x10(%2),%2 \n"
"sub $0x4,%3 \n"
"jg 1b \n"
: "+r"(src_argb0), // %0
"+r"(src_argb1), // %1
"+r"(dst_argb), // %2
"+r"(width) // %3
:
: "memory", "cc", "xmm0", "xmm1");
}
#endif // HAS_ARGBADDROW_SSE2
#ifdef HAS_ARGBADDROW_AVX2
// Add 2 rows of ARGB pixels together, 4 pixels at a time.
void ARGBAddRow_AVX2(const uint8_t* src_argb0,
const uint8_t* src_argb1,
uint8_t* dst_argb,
int width) {
asm volatile(
// 4 pixel loop.
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm0 \n"
"lea 0x20(%0),%0 \n"
"vpaddusb (%1),%%ymm0,%%ymm0 \n"
"lea 0x20(%1),%1 \n"
"vmovdqu %%ymm0,(%2) \n"
"lea 0x20(%2),%2 \n"
"sub $0x8,%3 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_argb0), // %0
"+r"(src_argb1), // %1
"+r"(dst_argb), // %2
"+r"(width) // %3
:
: "memory", "cc", "xmm0");
}
#endif // HAS_ARGBADDROW_AVX2
#ifdef HAS_ARGBSUBTRACTROW_SSE2
// Subtract 2 rows of ARGB pixels, 4 pixels at a time.
void ARGBSubtractRow_SSE2(const uint8_t* src_argb0,
const uint8_t* src_argb1,
uint8_t* dst_argb,
int width) {
asm volatile(
// 4 pixel loop.
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"lea 0x10(%0),%0 \n"
"movdqu (%1),%%xmm1 \n"
"lea 0x10(%1),%1 \n"
"psubusb %%xmm1,%%xmm0 \n"
"movdqu %%xmm0,(%2) \n"
"lea 0x10(%2),%2 \n"
"sub $0x4,%3 \n"
"jg 1b \n"
: "+r"(src_argb0), // %0
"+r"(src_argb1), // %1
"+r"(dst_argb), // %2
"+r"(width) // %3
:
: "memory", "cc", "xmm0", "xmm1");
}
#endif // HAS_ARGBSUBTRACTROW_SSE2
#ifdef HAS_ARGBSUBTRACTROW_AVX2
// Subtract 2 rows of ARGB pixels, 8 pixels at a time.
void ARGBSubtractRow_AVX2(const uint8_t* src_argb0,
const uint8_t* src_argb1,
uint8_t* dst_argb,
int width) {
asm volatile(
// 4 pixel loop.
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm0 \n"
"lea 0x20(%0),%0 \n"
"vpsubusb (%1),%%ymm0,%%ymm0 \n"
"lea 0x20(%1),%1 \n"
"vmovdqu %%ymm0,(%2) \n"
"lea 0x20(%2),%2 \n"
"sub $0x8,%3 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_argb0), // %0
"+r"(src_argb1), // %1
"+r"(dst_argb), // %2
"+r"(width) // %3
:
: "memory", "cc", "xmm0");
}
#endif // HAS_ARGBSUBTRACTROW_AVX2
#ifdef HAS_SOBELXROW_SSE2
// SobelX as a matrix is
// -1 0 1
// -2 0 2
// -1 0 1
void SobelXRow_SSE2(const uint8_t* src_y0,
const uint8_t* src_y1,
const uint8_t* src_y2,
uint8_t* dst_sobelx,
int width) {
asm volatile(
"sub %0,%1 \n"
"sub %0,%2 \n"
"sub %0,%3 \n"
"pxor %%xmm5,%%xmm5 \n"
// 8 pixel loop.
LABELALIGN
"1: \n"
"movq (%0),%%xmm0 \n"
"movq 0x2(%0),%%xmm1 \n"
"punpcklbw %%xmm5,%%xmm0 \n"
"punpcklbw %%xmm5,%%xmm1 \n"
"psubw %%xmm1,%%xmm0 \n"
"movq 0x00(%0,%1,1),%%xmm1 \n"
"movq 0x02(%0,%1,1),%%xmm2 \n"
"punpcklbw %%xmm5,%%xmm1 \n"
"punpcklbw %%xmm5,%%xmm2 \n"
"psubw %%xmm2,%%xmm1 \n"
"movq 0x00(%0,%2,1),%%xmm2 \n"
"movq 0x02(%0,%2,1),%%xmm3 \n"
"punpcklbw %%xmm5,%%xmm2 \n"
"punpcklbw %%xmm5,%%xmm3 \n"
"psubw %%xmm3,%%xmm2 \n"
"paddw %%xmm2,%%xmm0 \n"
"paddw %%xmm1,%%xmm0 \n"
"paddw %%xmm1,%%xmm0 \n"
"pxor %%xmm1,%%xmm1 \n"
"psubw %%xmm0,%%xmm1 \n"
"pmaxsw %%xmm1,%%xmm0 \n"
"packuswb %%xmm0,%%xmm0 \n"
"movq %%xmm0,0x00(%0,%3,1) \n"
"lea 0x8(%0),%0 \n"
"sub $0x8,%4 \n"
"jg 1b \n"
: "+r"(src_y0), // %0
"+r"(src_y1), // %1
"+r"(src_y2), // %2
"+r"(dst_sobelx), // %3
"+r"(width) // %4
:
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm5");
}
#endif // HAS_SOBELXROW_SSE2
#ifdef HAS_SOBELYROW_SSE2
// SobelY as a matrix is
// -1 -2 -1
// 0 0 0
// 1 2 1
void SobelYRow_SSE2(const uint8_t* src_y0,
const uint8_t* src_y1,
uint8_t* dst_sobely,
int width) {
asm volatile(
"sub %0,%1 \n"
"sub %0,%2 \n"
"pxor %%xmm5,%%xmm5 \n"
// 8 pixel loop.
LABELALIGN
"1: \n"
"movq (%0),%%xmm0 \n"
"movq 0x00(%0,%1,1),%%xmm1 \n"
"punpcklbw %%xmm5,%%xmm0 \n"
"punpcklbw %%xmm5,%%xmm1 \n"
"psubw %%xmm1,%%xmm0 \n"
"movq 0x1(%0),%%xmm1 \n"
"movq 0x01(%0,%1,1),%%xmm2 \n"
"punpcklbw %%xmm5,%%xmm1 \n"
"punpcklbw %%xmm5,%%xmm2 \n"
"psubw %%xmm2,%%xmm1 \n"
"movq 0x2(%0),%%xmm2 \n"
"movq 0x02(%0,%1,1),%%xmm3 \n"
"punpcklbw %%xmm5,%%xmm2 \n"
"punpcklbw %%xmm5,%%xmm3 \n"
"psubw %%xmm3,%%xmm2 \n"
"paddw %%xmm2,%%xmm0 \n"
"paddw %%xmm1,%%xmm0 \n"
"paddw %%xmm1,%%xmm0 \n"
"pxor %%xmm1,%%xmm1 \n"
"psubw %%xmm0,%%xmm1 \n"
"pmaxsw %%xmm1,%%xmm0 \n"
"packuswb %%xmm0,%%xmm0 \n"
"movq %%xmm0,0x00(%0,%2,1) \n"
"lea 0x8(%0),%0 \n"
"sub $0x8,%3 \n"
"jg 1b \n"
: "+r"(src_y0), // %0
"+r"(src_y1), // %1
"+r"(dst_sobely), // %2
"+r"(width) // %3
:
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm5");
}
#endif // HAS_SOBELYROW_SSE2
#ifdef HAS_SOBELROW_SSE2
// Adds Sobel X and Sobel Y and stores Sobel into ARGB.
// A = 255
// R = Sobel
// G = Sobel
// B = Sobel
void SobelRow_SSE2(const uint8_t* src_sobelx,
const uint8_t* src_sobely,
uint8_t* dst_argb,
int width) {
asm volatile(
"sub %0,%1 \n"
"pcmpeqb %%xmm5,%%xmm5 \n"
"pslld $0x18,%%xmm5 \n"
// 8 pixel loop.
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x00(%0,%1,1),%%xmm1 \n"
"lea 0x10(%0),%0 \n"
"paddusb %%xmm1,%%xmm0 \n"
"movdqa %%xmm0,%%xmm2 \n"
"punpcklbw %%xmm0,%%xmm2 \n"
"punpckhbw %%xmm0,%%xmm0 \n"
"movdqa %%xmm2,%%xmm1 \n"
"punpcklwd %%xmm2,%%xmm1 \n"
"punpckhwd %%xmm2,%%xmm2 \n"
"por %%xmm5,%%xmm1 \n"
"por %%xmm5,%%xmm2 \n"
"movdqa %%xmm0,%%xmm3 \n"
"punpcklwd %%xmm0,%%xmm3 \n"
"punpckhwd %%xmm0,%%xmm0 \n"
"por %%xmm5,%%xmm3 \n"
"por %%xmm5,%%xmm0 \n"
"movdqu %%xmm1,(%2) \n"
"movdqu %%xmm2,0x10(%2) \n"
"movdqu %%xmm3,0x20(%2) \n"
"movdqu %%xmm0,0x30(%2) \n"
"lea 0x40(%2),%2 \n"
"sub $0x10,%3 \n"
"jg 1b \n"
: "+r"(src_sobelx), // %0
"+r"(src_sobely), // %1
"+r"(dst_argb), // %2
"+r"(width) // %3
:
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm5");
}
#endif // HAS_SOBELROW_SSE2
#ifdef HAS_SOBELTOPLANEROW_SSE2
// Adds Sobel X and Sobel Y and stores Sobel into a plane.
void SobelToPlaneRow_SSE2(const uint8_t* src_sobelx,
const uint8_t* src_sobely,
uint8_t* dst_y,
int width) {
asm volatile(
"sub %0,%1 \n"
"pcmpeqb %%xmm5,%%xmm5 \n"
"pslld $0x18,%%xmm5 \n"
// 8 pixel loop.
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x00(%0,%1,1),%%xmm1 \n"
"lea 0x10(%0),%0 \n"
"paddusb %%xmm1,%%xmm0 \n"
"movdqu %%xmm0,(%2) \n"
"lea 0x10(%2),%2 \n"
"sub $0x10,%3 \n"
"jg 1b \n"
: "+r"(src_sobelx), // %0
"+r"(src_sobely), // %1
"+r"(dst_y), // %2
"+r"(width) // %3
:
: "memory", "cc", "xmm0", "xmm1");
}
#endif // HAS_SOBELTOPLANEROW_SSE2
#ifdef HAS_SOBELXYROW_SSE2
// Mixes Sobel X, Sobel Y and Sobel into ARGB.
// A = 255
// R = Sobel X
// G = Sobel
// B = Sobel Y
void SobelXYRow_SSE2(const uint8_t* src_sobelx,
const uint8_t* src_sobely,
uint8_t* dst_argb,
int width) {
asm volatile(
"sub %0,%1 \n"
"pcmpeqb %%xmm5,%%xmm5 \n"
// 8 pixel loop.
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x00(%0,%1,1),%%xmm1 \n"
"lea 0x10(%0),%0 \n"
"movdqa %%xmm0,%%xmm2 \n"
"paddusb %%xmm1,%%xmm2 \n"
"movdqa %%xmm0,%%xmm3 \n"
"punpcklbw %%xmm5,%%xmm3 \n"
"punpckhbw %%xmm5,%%xmm0 \n"
"movdqa %%xmm1,%%xmm4 \n"
"punpcklbw %%xmm2,%%xmm4 \n"
"punpckhbw %%xmm2,%%xmm1 \n"
"movdqa %%xmm4,%%xmm6 \n"
"punpcklwd %%xmm3,%%xmm6 \n"
"punpckhwd %%xmm3,%%xmm4 \n"
"movdqa %%xmm1,%%xmm7 \n"
"punpcklwd %%xmm0,%%xmm7 \n"
"punpckhwd %%xmm0,%%xmm1 \n"
"movdqu %%xmm6,(%2) \n"
"movdqu %%xmm4,0x10(%2) \n"
"movdqu %%xmm7,0x20(%2) \n"
"movdqu %%xmm1,0x30(%2) \n"
"lea 0x40(%2),%2 \n"
"sub $0x10,%3 \n"
"jg 1b \n"
: "+r"(src_sobelx), // %0
"+r"(src_sobely), // %1
"+r"(dst_argb), // %2
"+r"(width) // %3
:
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6",
"xmm7");
}
#endif // HAS_SOBELXYROW_SSE2
#ifdef HAS_COMPUTECUMULATIVESUMROW_SSE2
// Creates a table of cumulative sums where each value is a sum of all values
// above and to the left of the value, inclusive of the value.
void ComputeCumulativeSumRow_SSE2(const uint8_t* row,
int32_t* cumsum,
const int32_t* previous_cumsum,
int width) {
asm volatile(
"pxor %%xmm0,%%xmm0 \n"
"pxor %%xmm1,%%xmm1 \n"
"sub $0x4,%3 \n"
"jl 49f \n"
"test $0xf,%1 \n"
"jne 49f \n"
// 4 pixel loop.
LABELALIGN
"40: \n"
"movdqu (%0),%%xmm2 \n"
"lea 0x10(%0),%0 \n"
"movdqa %%xmm2,%%xmm4 \n"
"punpcklbw %%xmm1,%%xmm2 \n"
"movdqa %%xmm2,%%xmm3 \n"
"punpcklwd %%xmm1,%%xmm2 \n"
"punpckhwd %%xmm1,%%xmm3 \n"
"punpckhbw %%xmm1,%%xmm4 \n"
"movdqa %%xmm4,%%xmm5 \n"
"punpcklwd %%xmm1,%%xmm4 \n"
"punpckhwd %%xmm1,%%xmm5 \n"
"paddd %%xmm2,%%xmm0 \n"
"movdqu (%2),%%xmm2 \n"
"paddd %%xmm0,%%xmm2 \n"
"paddd %%xmm3,%%xmm0 \n"
"movdqu 0x10(%2),%%xmm3 \n"
"paddd %%xmm0,%%xmm3 \n"
"paddd %%xmm4,%%xmm0 \n"
"movdqu 0x20(%2),%%xmm4 \n"
"paddd %%xmm0,%%xmm4 \n"
"paddd %%xmm5,%%xmm0 \n"
"movdqu 0x30(%2),%%xmm5 \n"
"lea 0x40(%2),%2 \n"
"paddd %%xmm0,%%xmm5 \n"
"movdqu %%xmm2,(%1) \n"
"movdqu %%xmm3,0x10(%1) \n"
"movdqu %%xmm4,0x20(%1) \n"
"movdqu %%xmm5,0x30(%1) \n"
"lea 0x40(%1),%1 \n"
"sub $0x4,%3 \n"
"jge 40b \n"
"49: \n"
"add $0x3,%3 \n"
"jl 19f \n"
// 1 pixel loop.
LABELALIGN
"10: \n"
"movd (%0),%%xmm2 \n"
"lea 0x4(%0),%0 \n"
"punpcklbw %%xmm1,%%xmm2 \n"
"punpcklwd %%xmm1,%%xmm2 \n"
"paddd %%xmm2,%%xmm0 \n"
"movdqu (%2),%%xmm2 \n"
"lea 0x10(%2),%2 \n"
"paddd %%xmm0,%%xmm2 \n"
"movdqu %%xmm2,(%1) \n"
"lea 0x10(%1),%1 \n"
"sub $0x1,%3 \n"
"jge 10b \n"
"19: \n"
: "+r"(row), // %0
"+r"(cumsum), // %1
"+r"(previous_cumsum), // %2
"+r"(width) // %3
:
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5");
}
#endif // HAS_COMPUTECUMULATIVESUMROW_SSE2
#ifdef HAS_CUMULATIVESUMTOAVERAGEROW_SSE2
void CumulativeSumToAverageRow_SSE2(const int32_t* topleft,
const int32_t* botleft,
int width,
int area,
uint8_t* dst,
int count) {
asm volatile(
"movd %5,%%xmm5 \n"
"cvtdq2ps %%xmm5,%%xmm5 \n"
"rcpss %%xmm5,%%xmm4 \n"
"pshufd $0x0,%%xmm4,%%xmm4 \n"
"sub $0x4,%3 \n"
"jl 49f \n"
"cmpl $0x80,%5 \n"
"ja 40f \n"
"pshufd $0x0,%%xmm5,%%xmm5 \n"
"pcmpeqb %%xmm6,%%xmm6 \n"
"psrld $0x10,%%xmm6 \n"
"cvtdq2ps %%xmm6,%%xmm6 \n"
"addps %%xmm6,%%xmm5 \n"
"mulps %%xmm4,%%xmm5 \n"
"cvtps2dq %%xmm5,%%xmm5 \n"
"packssdw %%xmm5,%%xmm5 \n"
// 4 pixel small loop.
LABELALIGN
"4: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"movdqu 0x20(%0),%%xmm2 \n"
"movdqu 0x30(%0),%%xmm3 \n"
"psubd 0x00(%0,%4,4),%%xmm0 \n"
"psubd 0x10(%0,%4,4),%%xmm1 \n"
"psubd 0x20(%0,%4,4),%%xmm2 \n"
"psubd 0x30(%0,%4,4),%%xmm3 \n"
"lea 0x40(%0),%0 \n"
"psubd (%1),%%xmm0 \n"
"psubd 0x10(%1),%%xmm1 \n"
"psubd 0x20(%1),%%xmm2 \n"
"psubd 0x30(%1),%%xmm3 \n"
"paddd 0x00(%1,%4,4),%%xmm0 \n"
"paddd 0x10(%1,%4,4),%%xmm1 \n"
"paddd 0x20(%1,%4,4),%%xmm2 \n"
"paddd 0x30(%1,%4,4),%%xmm3 \n"
"lea 0x40(%1),%1 \n"
"packssdw %%xmm1,%%xmm0 \n"
"packssdw %%xmm3,%%xmm2 \n"
"pmulhuw %%xmm5,%%xmm0 \n"
"pmulhuw %%xmm5,%%xmm2 \n"
"packuswb %%xmm2,%%xmm0 \n"
"movdqu %%xmm0,(%2) \n"
"lea 0x10(%2),%2 \n"
"sub $0x4,%3 \n"
"jge 4b \n"
"jmp 49f \n"
// 4 pixel loop
LABELALIGN
"40: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"movdqu 0x20(%0),%%xmm2 \n"
"movdqu 0x30(%0),%%xmm3 \n"
"psubd 0x00(%0,%4,4),%%xmm0 \n"
"psubd 0x10(%0,%4,4),%%xmm1 \n"
"psubd 0x20(%0,%4,4),%%xmm2 \n"
"psubd 0x30(%0,%4,4),%%xmm3 \n"
"lea 0x40(%0),%0 \n"
"psubd (%1),%%xmm0 \n"
"psubd 0x10(%1),%%xmm1 \n"
"psubd 0x20(%1),%%xmm2 \n"
"psubd 0x30(%1),%%xmm3 \n"
"paddd 0x00(%1,%4,4),%%xmm0 \n"
"paddd 0x10(%1,%4,4),%%xmm1 \n"
"paddd 0x20(%1,%4,4),%%xmm2 \n"
"paddd 0x30(%1,%4,4),%%xmm3 \n"
"lea 0x40(%1),%1 \n"
"cvtdq2ps %%xmm0,%%xmm0 \n"
"cvtdq2ps %%xmm1,%%xmm1 \n"
"mulps %%xmm4,%%xmm0 \n"
"mulps %%xmm4,%%xmm1 \n"
"cvtdq2ps %%xmm2,%%xmm2 \n"
"cvtdq2ps %%xmm3,%%xmm3 \n"
"mulps %%xmm4,%%xmm2 \n"
"mulps %%xmm4,%%xmm3 \n"
"cvtps2dq %%xmm0,%%xmm0 \n"
"cvtps2dq %%xmm1,%%xmm1 \n"
"cvtps2dq %%xmm2,%%xmm2 \n"
"cvtps2dq %%xmm3,%%xmm3 \n"
"packssdw %%xmm1,%%xmm0 \n"
"packssdw %%xmm3,%%xmm2 \n"
"packuswb %%xmm2,%%xmm0 \n"
"movdqu %%xmm0,(%2) \n"
"lea 0x10(%2),%2 \n"
"sub $0x4,%3 \n"
"jge 40b \n"
"49: \n"
"add $0x3,%3 \n"
"jl 19f \n"
// 1 pixel loop
LABELALIGN
"10: \n"
"movdqu (%0),%%xmm0 \n"
"psubd 0x00(%0,%4,4),%%xmm0 \n"
"lea 0x10(%0),%0 \n"
"psubd (%1),%%xmm0 \n"
"paddd 0x00(%1,%4,4),%%xmm0 \n"
"lea 0x10(%1),%1 \n"
"cvtdq2ps %%xmm0,%%xmm0 \n"
"mulps %%xmm4,%%xmm0 \n"
"cvtps2dq %%xmm0,%%xmm0 \n"
"packssdw %%xmm0,%%xmm0 \n"
"packuswb %%xmm0,%%xmm0 \n"
"movd %%xmm0,(%2) \n"
"lea 0x4(%2),%2 \n"
"sub $0x1,%3 \n"
"jge 10b \n"
"19: \n"
: "+r"(topleft), // %0
"+r"(botleft), // %1
"+r"(dst), // %2
"+rm"(count) // %3
: "r"((intptr_t)(width)), // %4
"rm"(area) // %5
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6");
}
#endif // HAS_CUMULATIVESUMTOAVERAGEROW_SSE2
#ifdef HAS_ARGBAFFINEROW_SSE2
// Copy ARGB pixels from source image with slope to a row of destination.
LIBYUV_API
void ARGBAffineRow_SSE2(const uint8_t* src_argb,
int src_argb_stride,
uint8_t* dst_argb,
const float* src_dudv,
int width) {
intptr_t src_argb_stride_temp = src_argb_stride;
intptr_t temp;
asm volatile(
"movq (%3),%%xmm2 \n"
"movq 0x08(%3),%%xmm7 \n"
"shl $0x10,%1 \n"
"add $0x4,%1 \n"
"movd %1,%%xmm5 \n"
"sub $0x4,%4 \n"
"jl 49f \n"
"pshufd $0x44,%%xmm7,%%xmm7 \n"
"pshufd $0x0,%%xmm5,%%xmm5 \n"
"movdqa %%xmm2,%%xmm0 \n"
"addps %%xmm7,%%xmm0 \n"
"movlhps %%xmm0,%%xmm2 \n"
"movdqa %%xmm7,%%xmm4 \n"
"addps %%xmm4,%%xmm4 \n"
"movdqa %%xmm2,%%xmm3 \n"
"addps %%xmm4,%%xmm3 \n"
"addps %%xmm4,%%xmm4 \n"
// 4 pixel loop
LABELALIGN
"40: \n"
"cvttps2dq %%xmm2,%%xmm0 \n" // x,y float->int first 2
"cvttps2dq %%xmm3,%%xmm1 \n" // x,y float->int next 2
"packssdw %%xmm1,%%xmm0 \n" // x, y as 8 shorts
"pmaddwd %%xmm5,%%xmm0 \n" // off = x*4 + y*stride
"movd %%xmm0,%k1 \n"
"pshufd $0x39,%%xmm0,%%xmm0 \n"
"movd %%xmm0,%k5 \n"
"pshufd $0x39,%%xmm0,%%xmm0 \n"
"movd 0x00(%0,%1,1),%%xmm1 \n"
"movd 0x00(%0,%5,1),%%xmm6 \n"
"punpckldq %%xmm6,%%xmm1 \n"
"addps %%xmm4,%%xmm2 \n"
"movq %%xmm1,(%2) \n"
"movd %%xmm0,%k1 \n"
"pshufd $0x39,%%xmm0,%%xmm0 \n"
"movd %%xmm0,%k5 \n"
"movd 0x00(%0,%1,1),%%xmm0 \n"
"movd 0x00(%0,%5,1),%%xmm6 \n"
"punpckldq %%xmm6,%%xmm0 \n"
"addps %%xmm4,%%xmm3 \n"
"movq %%xmm0,0x08(%2) \n"
"lea 0x10(%2),%2 \n"
"sub $0x4,%4 \n"
"jge 40b \n"
"49: \n"
"add $0x3,%4 \n"
"jl 19f \n"
// 1 pixel loop
LABELALIGN
"10: \n"
"cvttps2dq %%xmm2,%%xmm0 \n"
"packssdw %%xmm0,%%xmm0 \n"
"pmaddwd %%xmm5,%%xmm0 \n"
"addps %%xmm7,%%xmm2 \n"
"movd %%xmm0,%k1 \n"
"movd 0x00(%0,%1,1),%%xmm0 \n"
"movd %%xmm0,(%2) \n"
"lea 0x04(%2),%2 \n"
"sub $0x1,%4 \n"
"jge 10b \n"
"19: \n"
: "+r"(src_argb), // %0
"+r"(src_argb_stride_temp), // %1
"+r"(dst_argb), // %2
"+r"(src_dudv), // %3
"+rm"(width), // %4
"=&r"(temp) // %5
:
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6",
"xmm7");
}
#endif // HAS_ARGBAFFINEROW_SSE2
#ifdef HAS_INTERPOLATEROW_SSSE3
// Bilinear filter 16x2 -> 16x1
void InterpolateRow_SSSE3(uint8_t* dst_ptr,
const uint8_t* src_ptr,
ptrdiff_t src_stride,
int dst_width,
int source_y_fraction) {
asm volatile(
"sub %1,%0 \n"
"cmp $0x0,%3 \n"
"je 100f \n"
"cmp $0x80,%3 \n"
"je 50f \n"
"movd %3,%%xmm0 \n"
"neg %3 \n"
"add $0x100,%3 \n"
"movd %3,%%xmm5 \n"
"punpcklbw %%xmm0,%%xmm5 \n"
"punpcklwd %%xmm5,%%xmm5 \n"
"pshufd $0x0,%%xmm5,%%xmm5 \n"
"mov $0x80808080,%%eax \n"
"movd %%eax,%%xmm4 \n"
"pshufd $0x0,%%xmm4,%%xmm4 \n"
// General purpose row blend.
LABELALIGN
"1: \n"
"movdqu (%1),%%xmm0 \n"
"movdqu 0x00(%1,%4,1),%%xmm2 \n"
"movdqa %%xmm0,%%xmm1 \n"
"punpcklbw %%xmm2,%%xmm0 \n"
"punpckhbw %%xmm2,%%xmm1 \n"
"psubb %%xmm4,%%xmm0 \n"
"psubb %%xmm4,%%xmm1 \n"
"movdqa %%xmm5,%%xmm2 \n"
"movdqa %%xmm5,%%xmm3 \n"
"pmaddubsw %%xmm0,%%xmm2 \n"
"pmaddubsw %%xmm1,%%xmm3 \n"
"paddw %%xmm4,%%xmm2 \n"
"paddw %%xmm4,%%xmm3 \n"
"psrlw $0x8,%%xmm2 \n"
"psrlw $0x8,%%xmm3 \n"
"packuswb %%xmm3,%%xmm2 \n"
"movdqu %%xmm2,0x00(%1,%0,1) \n"
"lea 0x10(%1),%1 \n"
"sub $0x10,%2 \n"
"jg 1b \n"
"jmp 99f \n"
// Blend 50 / 50.
LABELALIGN
"50: \n"
"movdqu (%1),%%xmm0 \n"
"movdqu 0x00(%1,%4,1),%%xmm1 \n"
"pavgb %%xmm1,%%xmm0 \n"
"movdqu %%xmm0,0x00(%1,%0,1) \n"
"lea 0x10(%1),%1 \n"
"sub $0x10,%2 \n"
"jg 50b \n"
"jmp 99f \n"
// Blend 100 / 0 - Copy row unchanged.
LABELALIGN
"100: \n"
"movdqu (%1),%%xmm0 \n"
"movdqu %%xmm0,0x00(%1,%0,1) \n"
"lea 0x10(%1),%1 \n"
"sub $0x10,%2 \n"
"jg 100b \n"
"99: \n"
: "+r"(dst_ptr), // %0
"+r"(src_ptr), // %1
"+rm"(dst_width), // %2
"+r"(source_y_fraction) // %3
: "r"((intptr_t)(src_stride)) // %4
: "memory", "cc", "eax", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5");
}
#endif // HAS_INTERPOLATEROW_SSSE3
#ifdef HAS_INTERPOLATEROW_AVX2
// Bilinear filter 32x2 -> 32x1
void InterpolateRow_AVX2(uint8_t* dst_ptr,
const uint8_t* src_ptr,
ptrdiff_t src_stride,
int dst_width,
int source_y_fraction) {
asm volatile(
"cmp $0x0,%3 \n"
"je 100f \n"
"sub %1,%0 \n"
"cmp $0x80,%3 \n"
"je 50f \n"
"vmovd %3,%%xmm0 \n"
"neg %3 \n"
"add $0x100,%3 \n"
"vmovd %3,%%xmm5 \n"
"vpunpcklbw %%xmm0,%%xmm5,%%xmm5 \n"
"vpunpcklwd %%xmm5,%%xmm5,%%xmm5 \n"
"vbroadcastss %%xmm5,%%ymm5 \n"
"mov $0x80808080,%%eax \n"
"vmovd %%eax,%%xmm4 \n"
"vbroadcastss %%xmm4,%%ymm4 \n"
// General purpose row blend.
LABELALIGN
"1: \n"
"vmovdqu (%1),%%ymm0 \n"
"vmovdqu 0x00(%1,%4,1),%%ymm2 \n"
"vpunpckhbw %%ymm2,%%ymm0,%%ymm1 \n"
"vpunpcklbw %%ymm2,%%ymm0,%%ymm0 \n"
"vpsubb %%ymm4,%%ymm1,%%ymm1 \n"
"vpsubb %%ymm4,%%ymm0,%%ymm0 \n"
"vpmaddubsw %%ymm1,%%ymm5,%%ymm1 \n"
"vpmaddubsw %%ymm0,%%ymm5,%%ymm0 \n"
"vpaddw %%ymm4,%%ymm1,%%ymm1 \n"
"vpaddw %%ymm4,%%ymm0,%%ymm0 \n"
"vpsrlw $0x8,%%ymm1,%%ymm1 \n"
"vpsrlw $0x8,%%ymm0,%%ymm0 \n"
"vpackuswb %%ymm1,%%ymm0,%%ymm0 \n"
"vmovdqu %%ymm0,0x00(%1,%0,1) \n"
"lea 0x20(%1),%1 \n"
"sub $0x20,%2 \n"
"jg 1b \n"
"jmp 99f \n"
// Blend 50 / 50.
LABELALIGN
"50: \n"
"vmovdqu (%1),%%ymm0 \n"
"vpavgb 0x00(%1,%4,1),%%ymm0,%%ymm0 \n"
"vmovdqu %%ymm0,0x00(%1,%0,1) \n"
"lea 0x20(%1),%1 \n"
"sub $0x20,%2 \n"
"jg 50b \n"
"jmp 99f \n"
// Blend 100 / 0 - Copy row unchanged.
LABELALIGN
"100: \n"
"rep movsb \n"
"jmp 999f \n"
"99: \n"
"vzeroupper \n"
"999: \n"
: "+D"(dst_ptr), // %0
"+S"(src_ptr), // %1
"+cm"(dst_width), // %2
"+r"(source_y_fraction) // %3
: "r"((intptr_t)(src_stride)) // %4
: "memory", "cc", "eax", "xmm0", "xmm1", "xmm2", "xmm4", "xmm5");
}
#endif // HAS_INTERPOLATEROW_AVX2
#ifdef HAS_ARGBSHUFFLEROW_SSSE3
// For BGRAToARGB, ABGRToARGB, RGBAToARGB, and ARGBToRGBA.
void ARGBShuffleRow_SSSE3(const uint8_t* src_argb,
uint8_t* dst_argb,
const uint8_t* shuffler,
int width) {
asm volatile(
"movdqu (%3),%%xmm5 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"lea 0x20(%0),%0 \n"
"pshufb %%xmm5,%%xmm0 \n"
"pshufb %%xmm5,%%xmm1 \n"
"movdqu %%xmm0,(%1) \n"
"movdqu %%xmm1,0x10(%1) \n"
"lea 0x20(%1),%1 \n"
"sub $0x8,%2 \n"
"jg 1b \n"
: "+r"(src_argb), // %0
"+r"(dst_argb), // %1
"+r"(width) // %2
: "r"(shuffler) // %3
: "memory", "cc", "xmm0", "xmm1", "xmm5");
}
#endif // HAS_ARGBSHUFFLEROW_SSSE3
#ifdef HAS_ARGBSHUFFLEROW_AVX2
// For BGRAToARGB, ABGRToARGB, RGBAToARGB, and ARGBToRGBA.
void ARGBShuffleRow_AVX2(const uint8_t* src_argb,
uint8_t* dst_argb,
const uint8_t* shuffler,
int width) {
asm volatile(
"vbroadcastf128 (%3),%%ymm5 \n"
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm0 \n"
"vmovdqu 0x20(%0),%%ymm1 \n"
"lea 0x40(%0),%0 \n"
"vpshufb %%ymm5,%%ymm0,%%ymm0 \n"
"vpshufb %%ymm5,%%ymm1,%%ymm1 \n"
"vmovdqu %%ymm0,(%1) \n"
"vmovdqu %%ymm1,0x20(%1) \n"
"lea 0x40(%1),%1 \n"
"sub $0x10,%2 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_argb), // %0
"+r"(dst_argb), // %1
"+r"(width) // %2
: "r"(shuffler) // %3
: "memory", "cc", "xmm0", "xmm1", "xmm5");
}
#endif // HAS_ARGBSHUFFLEROW_AVX2
#ifdef HAS_I422TOYUY2ROW_SSE2
void I422ToYUY2Row_SSE2(const uint8_t* src_y,
const uint8_t* src_u,
const uint8_t* src_v,
uint8_t* dst_yuy2,
int width) {
asm volatile(
"sub %1,%2 \n"
LABELALIGN
"1: \n"
"movq (%1),%%xmm2 \n"
"movq 0x00(%1,%2,1),%%xmm1 \n"
"add $0x8,%1 \n"
"punpcklbw %%xmm1,%%xmm2 \n"
"movdqu (%0),%%xmm0 \n"
"add $0x10,%0 \n"
"movdqa %%xmm0,%%xmm1 \n"
"punpcklbw %%xmm2,%%xmm0 \n"
"punpckhbw %%xmm2,%%xmm1 \n"
"movdqu %%xmm0,(%3) \n"
"movdqu %%xmm1,0x10(%3) \n"
"lea 0x20(%3),%3 \n"
"sub $0x10,%4 \n"
"jg 1b \n"
: "+r"(src_y), // %0
"+r"(src_u), // %1
"+r"(src_v), // %2
"+r"(dst_yuy2), // %3
"+rm"(width) // %4
:
: "memory", "cc", "xmm0", "xmm1", "xmm2");
}
#endif // HAS_I422TOYUY2ROW_SSE2
#ifdef HAS_I422TOUYVYROW_SSE2
void I422ToUYVYRow_SSE2(const uint8_t* src_y,
const uint8_t* src_u,
const uint8_t* src_v,
uint8_t* dst_uyvy,
int width) {
asm volatile(
"sub %1,%2 \n"
LABELALIGN
"1: \n"
"movq (%1),%%xmm2 \n"
"movq 0x00(%1,%2,1),%%xmm1 \n"
"add $0x8,%1 \n"
"punpcklbw %%xmm1,%%xmm2 \n"
"movdqu (%0),%%xmm0 \n"
"movdqa %%xmm2,%%xmm1 \n"
"add $0x10,%0 \n"
"punpcklbw %%xmm0,%%xmm1 \n"
"punpckhbw %%xmm0,%%xmm2 \n"
"movdqu %%xmm1,(%3) \n"
"movdqu %%xmm2,0x10(%3) \n"
"lea 0x20(%3),%3 \n"
"sub $0x10,%4 \n"
"jg 1b \n"
: "+r"(src_y), // %0
"+r"(src_u), // %1
"+r"(src_v), // %2
"+r"(dst_uyvy), // %3
"+rm"(width) // %4
:
: "memory", "cc", "xmm0", "xmm1", "xmm2");
}
#endif // HAS_I422TOUYVYROW_SSE2
#ifdef HAS_I422TOYUY2ROW_AVX2
void I422ToYUY2Row_AVX2(const uint8_t* src_y,
const uint8_t* src_u,
const uint8_t* src_v,
uint8_t* dst_yuy2,
int width) {
asm volatile(
"sub %1,%2 \n"
LABELALIGN
"1: \n"
"vpmovzxbw (%1),%%ymm1 \n"
"vpmovzxbw 0x00(%1,%2,1),%%ymm2 \n"
"add $0x10,%1 \n"
"vpsllw $0x8,%%ymm2,%%ymm2 \n"
"vpor %%ymm1,%%ymm2,%%ymm2 \n"
"vmovdqu (%0),%%ymm0 \n"
"add $0x20,%0 \n"
"vpunpcklbw %%ymm2,%%ymm0,%%ymm1 \n"
"vpunpckhbw %%ymm2,%%ymm0,%%ymm2 \n"
"vextractf128 $0x0,%%ymm1,(%3) \n"
"vextractf128 $0x0,%%ymm2,0x10(%3) \n"
"vextractf128 $0x1,%%ymm1,0x20(%3) \n"
"vextractf128 $0x1,%%ymm2,0x30(%3) \n"
"lea 0x40(%3),%3 \n"
"sub $0x20,%4 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_y), // %0
"+r"(src_u), // %1
"+r"(src_v), // %2
"+r"(dst_yuy2), // %3
"+rm"(width) // %4
:
: "memory", "cc", "xmm0", "xmm1", "xmm2");
}
#endif // HAS_I422TOYUY2ROW_AVX2
#ifdef HAS_I422TOUYVYROW_AVX2
void I422ToUYVYRow_AVX2(const uint8_t* src_y,
const uint8_t* src_u,
const uint8_t* src_v,
uint8_t* dst_uyvy,
int width) {
asm volatile(
"sub %1,%2 \n"
LABELALIGN
"1: \n"
"vpmovzxbw (%1),%%ymm1 \n"
"vpmovzxbw 0x00(%1,%2,1),%%ymm2 \n"
"add $0x10,%1 \n"
"vpsllw $0x8,%%ymm2,%%ymm2 \n"
"vpor %%ymm1,%%ymm2,%%ymm2 \n"
"vmovdqu (%0),%%ymm0 \n"
"add $0x20,%0 \n"
"vpunpcklbw %%ymm0,%%ymm2,%%ymm1 \n"
"vpunpckhbw %%ymm0,%%ymm2,%%ymm2 \n"
"vextractf128 $0x0,%%ymm1,(%3) \n"
"vextractf128 $0x0,%%ymm2,0x10(%3) \n"
"vextractf128 $0x1,%%ymm1,0x20(%3) \n"
"vextractf128 $0x1,%%ymm2,0x30(%3) \n"
"lea 0x40(%3),%3 \n"
"sub $0x20,%4 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_y), // %0
"+r"(src_u), // %1
"+r"(src_v), // %2
"+r"(dst_uyvy), // %3
"+rm"(width) // %4
:
: "memory", "cc", "xmm0", "xmm1", "xmm2");
}
#endif // HAS_I422TOUYVYROW_AVX2
#ifdef HAS_ARGBPOLYNOMIALROW_SSE2
void ARGBPolynomialRow_SSE2(const uint8_t* src_argb,
uint8_t* dst_argb,
const float* poly,
int width) {
asm volatile(
"pxor %%xmm3,%%xmm3 \n"
// 2 pixel loop.
LABELALIGN
"1: \n"
"movq (%0),%%xmm0 \n"
"lea 0x8(%0),%0 \n"
"punpcklbw %%xmm3,%%xmm0 \n"
"movdqa %%xmm0,%%xmm4 \n"
"punpcklwd %%xmm3,%%xmm0 \n"
"punpckhwd %%xmm3,%%xmm4 \n"
"cvtdq2ps %%xmm0,%%xmm0 \n"
"cvtdq2ps %%xmm4,%%xmm4 \n"
"movdqa %%xmm0,%%xmm1 \n"
"movdqa %%xmm4,%%xmm5 \n"
"mulps 0x10(%3),%%xmm0 \n"
"mulps 0x10(%3),%%xmm4 \n"
"addps (%3),%%xmm0 \n"
"addps (%3),%%xmm4 \n"
"movdqa %%xmm1,%%xmm2 \n"
"movdqa %%xmm5,%%xmm6 \n"
"mulps %%xmm1,%%xmm2 \n"
"mulps %%xmm5,%%xmm6 \n"
"mulps %%xmm2,%%xmm1 \n"
"mulps %%xmm6,%%xmm5 \n"
"mulps 0x20(%3),%%xmm2 \n"
"mulps 0x20(%3),%%xmm6 \n"
"mulps 0x30(%3),%%xmm1 \n"
"mulps 0x30(%3),%%xmm5 \n"
"addps %%xmm2,%%xmm0 \n"
"addps %%xmm6,%%xmm4 \n"
"addps %%xmm1,%%xmm0 \n"
"addps %%xmm5,%%xmm4 \n"
"cvttps2dq %%xmm0,%%xmm0 \n"
"cvttps2dq %%xmm4,%%xmm4 \n"
"packuswb %%xmm4,%%xmm0 \n"
"packuswb %%xmm0,%%xmm0 \n"
"movq %%xmm0,(%1) \n"
"lea 0x8(%1),%1 \n"
"sub $0x2,%2 \n"
"jg 1b \n"
: "+r"(src_argb), // %0
"+r"(dst_argb), // %1
"+r"(width) // %2
: "r"(poly) // %3
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6");
}
#endif // HAS_ARGBPOLYNOMIALROW_SSE2
#ifdef HAS_ARGBPOLYNOMIALROW_AVX2
void ARGBPolynomialRow_AVX2(const uint8_t* src_argb,
uint8_t* dst_argb,
const float* poly,
int width) {
asm volatile(
"vbroadcastf128 (%3),%%ymm4 \n"
"vbroadcastf128 0x10(%3),%%ymm5 \n"
"vbroadcastf128 0x20(%3),%%ymm6 \n"
"vbroadcastf128 0x30(%3),%%ymm7 \n"
// 2 pixel loop.
LABELALIGN
"1: \n"
"vpmovzxbd (%0),%%ymm0 \n" // 2 ARGB pixels
"lea 0x8(%0),%0 \n"
"vcvtdq2ps %%ymm0,%%ymm0 \n" // X 8 floats
"vmulps %%ymm0,%%ymm0,%%ymm2 \n" // X * X
"vmulps %%ymm7,%%ymm0,%%ymm3 \n" // C3 * X
"vfmadd132ps %%ymm5,%%ymm4,%%ymm0 \n" // result = C0 + C1 * X
"vfmadd231ps %%ymm6,%%ymm2,%%ymm0 \n" // result += C2 * X * X
"vfmadd231ps %%ymm3,%%ymm2,%%ymm0 \n" // result += C3 * X * X *
// X
"vcvttps2dq %%ymm0,%%ymm0 \n"
"vpackusdw %%ymm0,%%ymm0,%%ymm0 \n"
"vpermq $0xd8,%%ymm0,%%ymm0 \n"
"vpackuswb %%xmm0,%%xmm0,%%xmm0 \n"
"vmovq %%xmm0,(%1) \n"
"lea 0x8(%1),%1 \n"
"sub $0x2,%2 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_argb), // %0
"+r"(dst_argb), // %1
"+r"(width) // %2
: "r"(poly) // %3
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6",
"xmm7");
}
#endif // HAS_ARGBPOLYNOMIALROW_AVX2
#ifdef HAS_HALFFLOATROW_SSE2
static float kScaleBias = 1.9259299444e-34f;
void HalfFloatRow_SSE2(const uint16_t* src,
uint16_t* dst,
float scale,
int width) {
scale *= kScaleBias;
asm volatile(
"movd %3,%%xmm4 \n"
"pshufd $0x0,%%xmm4,%%xmm4 \n"
"pxor %%xmm5,%%xmm5 \n"
"sub %0,%1 \n"
// 16 pixel loop.
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm2 \n" // 8 shorts
"add $0x10,%0 \n"
"movdqa %%xmm2,%%xmm3 \n"
"punpcklwd %%xmm5,%%xmm2 \n" // 8 ints in xmm2/1
"cvtdq2ps %%xmm2,%%xmm2 \n" // 8 floats
"punpckhwd %%xmm5,%%xmm3 \n"
"cvtdq2ps %%xmm3,%%xmm3 \n"
"mulps %%xmm4,%%xmm2 \n"
"mulps %%xmm4,%%xmm3 \n"
"psrld $0xd,%%xmm2 \n"
"psrld $0xd,%%xmm3 \n"
"packssdw %%xmm3,%%xmm2 \n"
"movdqu %%xmm2,-0x10(%0,%1,1) \n"
"sub $0x8,%2 \n"
"jg 1b \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
: "m"(scale) // %3
: "memory", "cc", "xmm2", "xmm3", "xmm4", "xmm5");
}
#endif // HAS_HALFFLOATROW_SSE2
#ifdef HAS_HALFFLOATROW_AVX2
void HalfFloatRow_AVX2(const uint16_t* src,
uint16_t* dst,
float scale,
int width) {
scale *= kScaleBias;
asm volatile(
"vbroadcastss %3, %%ymm4 \n"
"vpxor %%ymm5,%%ymm5,%%ymm5 \n"
"sub %0,%1 \n"
// 16 pixel loop.
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm2 \n" // 16 shorts
"add $0x20,%0 \n"
"vpunpckhwd %%ymm5,%%ymm2,%%ymm3 \n" // mutates
"vpunpcklwd %%ymm5,%%ymm2,%%ymm2 \n"
"vcvtdq2ps %%ymm3,%%ymm3 \n"
"vcvtdq2ps %%ymm2,%%ymm2 \n"
"vmulps %%ymm3,%%ymm4,%%ymm3 \n"
"vmulps %%ymm2,%%ymm4,%%ymm2 \n"
"vpsrld $0xd,%%ymm3,%%ymm3 \n"
"vpsrld $0xd,%%ymm2,%%ymm2 \n"
"vpackssdw %%ymm3, %%ymm2, %%ymm2 \n" // unmutates
"vmovdqu %%ymm2,-0x20(%0,%1,1) \n"
"sub $0x10,%2 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
#if defined(__x86_64__)
: "x"(scale) // %3
#else
: "m"(scale) // %3
#endif
: "memory", "cc", "xmm2", "xmm3", "xmm4", "xmm5");
}
#endif // HAS_HALFFLOATROW_AVX2
#ifdef HAS_HALFFLOATROW_F16C
void HalfFloatRow_F16C(const uint16_t* src,
uint16_t* dst,
float scale,
int width) {
asm volatile(
"vbroadcastss %3, %%ymm4 \n"
"sub %0,%1 \n"
// 16 pixel loop.
LABELALIGN
"1: \n"
"vpmovzxwd (%0),%%ymm2 \n" // 16 shorts -> 16 ints
"vpmovzxwd 0x10(%0),%%ymm3 \n"
"vcvtdq2ps %%ymm2,%%ymm2 \n"
"vcvtdq2ps %%ymm3,%%ymm3 \n"
"vmulps %%ymm2,%%ymm4,%%ymm2 \n"
"vmulps %%ymm3,%%ymm4,%%ymm3 \n"
"vcvtps2ph $3, %%ymm2, %%xmm2 \n"
"vcvtps2ph $3, %%ymm3, %%xmm3 \n"
"vmovdqu %%xmm2,0x00(%0,%1,1) \n"
"vmovdqu %%xmm3,0x10(%0,%1,1) \n"
"add $0x20,%0 \n"
"sub $0x10,%2 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
#if defined(__x86_64__)
: "x"(scale) // %3
#else
: "m"(scale) // %3
#endif
: "memory", "cc", "xmm2", "xmm3", "xmm4");
}
#endif // HAS_HALFFLOATROW_F16C
#ifdef HAS_HALFFLOATROW_F16C
void HalfFloat1Row_F16C(const uint16_t* src, uint16_t* dst, float, int width) {
asm volatile(
"sub %0,%1 \n"
// 16 pixel loop.
LABELALIGN
"1: \n"
"vpmovzxwd (%0),%%ymm2 \n" // 16 shorts -> 16 ints
"vpmovzxwd 0x10(%0),%%ymm3 \n"
"vcvtdq2ps %%ymm2,%%ymm2 \n"
"vcvtdq2ps %%ymm3,%%ymm3 \n"
"vcvtps2ph $3, %%ymm2, %%xmm2 \n"
"vcvtps2ph $3, %%ymm3, %%xmm3 \n"
"vmovdqu %%xmm2,0x00(%0,%1,1) \n"
"vmovdqu %%xmm3,0x10(%0,%1,1) \n"
"add $0x20,%0 \n"
"sub $0x10,%2 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
:
: "memory", "cc", "xmm2", "xmm3");
}
#endif // HAS_HALFFLOATROW_F16C
#ifdef HAS_ARGBCOLORTABLEROW_X86
// Tranform ARGB pixels with color table.
void ARGBColorTableRow_X86(uint8_t* dst_argb,
const uint8_t* table_argb,
int width) {
uintptr_t pixel_temp;
asm volatile(
// 1 pixel loop.
LABELALIGN
"1: \n"
"movzb (%0),%1 \n"
"lea 0x4(%0),%0 \n"
"movzb 0x00(%3,%1,4),%1 \n"
"mov %b1,-0x4(%0) \n"
"movzb -0x3(%0),%1 \n"
"movzb 0x01(%3,%1,4),%1 \n"
"mov %b1,-0x3(%0) \n"
"movzb -0x2(%0),%1 \n"
"movzb 0x02(%3,%1,4),%1 \n"
"mov %b1,-0x2(%0) \n"
"movzb -0x1(%0),%1 \n"
"movzb 0x03(%3,%1,4),%1 \n"
"mov %b1,-0x1(%0) \n"
"dec %2 \n"
"jg 1b \n"
: "+r"(dst_argb), // %0
"=&d"(pixel_temp), // %1
"+r"(width) // %2
: "r"(table_argb) // %3
: "memory", "cc");
}
#endif // HAS_ARGBCOLORTABLEROW_X86
#ifdef HAS_RGBCOLORTABLEROW_X86
// Tranform RGB pixels with color table.
void RGBColorTableRow_X86(uint8_t* dst_argb,
const uint8_t* table_argb,
int width) {
uintptr_t pixel_temp;
asm volatile(
// 1 pixel loop.
LABELALIGN
"1: \n"
"movzb (%0),%1 \n"
"lea 0x4(%0),%0 \n"
"movzb 0x00(%3,%1,4),%1 \n"
"mov %b1,-0x4(%0) \n"
"movzb -0x3(%0),%1 \n"
"movzb 0x01(%3,%1,4),%1 \n"
"mov %b1,-0x3(%0) \n"
"movzb -0x2(%0),%1 \n"
"movzb 0x02(%3,%1,4),%1 \n"
"mov %b1,-0x2(%0) \n"
"dec %2 \n"
"jg 1b \n"
: "+r"(dst_argb), // %0
"=&d"(pixel_temp), // %1
"+r"(width) // %2
: "r"(table_argb) // %3
: "memory", "cc");
}
#endif // HAS_RGBCOLORTABLEROW_X86
#ifdef HAS_ARGBLUMACOLORTABLEROW_SSSE3
// Tranform RGB pixels with luma table.
void ARGBLumaColorTableRow_SSSE3(const uint8_t* src_argb,
uint8_t* dst_argb,
int width,
const uint8_t* luma,
uint32_t lumacoeff) {
uintptr_t pixel_temp;
uintptr_t table_temp;
asm volatile(
"movd %6,%%xmm3 \n"
"pshufd $0x0,%%xmm3,%%xmm3 \n"
"pcmpeqb %%xmm4,%%xmm4 \n"
"psllw $0x8,%%xmm4 \n"
"pxor %%xmm5,%%xmm5 \n"
// 4 pixel loop.
LABELALIGN
"1: \n"
"movdqu (%2),%%xmm0 \n"
"pmaddubsw %%xmm3,%%xmm0 \n"
"phaddw %%xmm0,%%xmm0 \n"
"pand %%xmm4,%%xmm0 \n"
"punpcklwd %%xmm5,%%xmm0 \n"
"movd %%xmm0,%k1 \n" // 32 bit offset
"add %5,%1 \n"
"pshufd $0x39,%%xmm0,%%xmm0 \n"
"movzb (%2),%0 \n"
"movzb 0x00(%1,%0,1),%0 \n"
"mov %b0,(%3) \n"
"movzb 0x1(%2),%0 \n"
"movzb 0x00(%1,%0,1),%0 \n"
"mov %b0,0x1(%3) \n"
"movzb 0x2(%2),%0 \n"
"movzb 0x00(%1,%0,1),%0 \n"
"mov %b0,0x2(%3) \n"
"movzb 0x3(%2),%0 \n"
"mov %b0,0x3(%3) \n"
"movd %%xmm0,%k1 \n" // 32 bit offset
"add %5,%1 \n"
"pshufd $0x39,%%xmm0,%%xmm0 \n"
"movzb 0x4(%2),%0 \n"
"movzb 0x00(%1,%0,1),%0 \n"
"mov %b0,0x4(%3) \n"
"movzb 0x5(%2),%0 \n"
"movzb 0x00(%1,%0,1),%0 \n"
"mov %b0,0x5(%3) \n"
"movzb 0x6(%2),%0 \n"
"movzb 0x00(%1,%0,1),%0 \n"
"mov %b0,0x6(%3) \n"
"movzb 0x7(%2),%0 \n"
"mov %b0,0x7(%3) \n"
"movd %%xmm0,%k1 \n" // 32 bit offset
"add %5,%1 \n"
"pshufd $0x39,%%xmm0,%%xmm0 \n"
"movzb 0x8(%2),%0 \n"
"movzb 0x00(%1,%0,1),%0 \n"
"mov %b0,0x8(%3) \n"
"movzb 0x9(%2),%0 \n"
"movzb 0x00(%1,%0,1),%0 \n"
"mov %b0,0x9(%3) \n"
"movzb 0xa(%2),%0 \n"
"movzb 0x00(%1,%0,1),%0 \n"
"mov %b0,0xa(%3) \n"
"movzb 0xb(%2),%0 \n"
"mov %b0,0xb(%3) \n"
"movd %%xmm0,%k1 \n" // 32 bit offset
"add %5,%1 \n"
"movzb 0xc(%2),%0 \n"
"movzb 0x00(%1,%0,1),%0 \n"
"mov %b0,0xc(%3) \n"
"movzb 0xd(%2),%0 \n"
"movzb 0x00(%1,%0,1),%0 \n"
"mov %b0,0xd(%3) \n"
"movzb 0xe(%2),%0 \n"
"movzb 0x00(%1,%0,1),%0 \n"
"mov %b0,0xe(%3) \n"
"movzb 0xf(%2),%0 \n"
"mov %b0,0xf(%3) \n"
"lea 0x10(%2),%2 \n"
"lea 0x10(%3),%3 \n"
"sub $0x4,%4 \n"
"jg 1b \n"
: "=&d"(pixel_temp), // %0
"=&a"(table_temp), // %1
"+r"(src_argb), // %2
"+r"(dst_argb), // %3
"+rm"(width) // %4
: "r"(luma), // %5
"rm"(lumacoeff) // %6
: "memory", "cc", "xmm0", "xmm3", "xmm4", "xmm5");
}
#endif // HAS_ARGBLUMACOLORTABLEROW_SSSE3
#ifdef HAS_NV21TOYUV24ROW_AVX2
// begin NV21ToYUV24Row_C avx2 constants
static const ulvec8 kBLEND0 = {0x80, 0x00, 0x80, 0x80, 0x00, 0x80, 0x80, 0x00,
0x80, 0x80, 0x00, 0x80, 0x80, 0x00, 0x80, 0x80,
0x00, 0x80, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80,
0x00, 0x00, 0x80, 0x00, 0x00, 0x80, 0x00, 0x00};
static const ulvec8 kBLEND1 = {0x00, 0x00, 0x80, 0x00, 0x00, 0x80, 0x00, 0x00,
0x80, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80, 0x00,
0x80, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80, 0x00,
0x00, 0x80, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80};
static const ulvec8 kBLEND2 = {0x80, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80, 0x00,
0x00, 0x80, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80,
0x00, 0x00, 0x80, 0x00, 0x00, 0x80, 0x00, 0x00,
0x80, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80, 0x00};
static const ulvec8 kSHUF0 = {0x00, 0x0b, 0x80, 0x01, 0x0c, 0x80, 0x02, 0x0d,
0x80, 0x03, 0x0e, 0x80, 0x04, 0x0f, 0x80, 0x05,
0x00, 0x0b, 0x80, 0x01, 0x0c, 0x80, 0x02, 0x0d,
0x80, 0x03, 0x0e, 0x80, 0x04, 0x0f, 0x80, 0x05};
static const ulvec8 kSHUF1 = {0x80, 0x00, 0x0b, 0x80, 0x01, 0x0c, 0x80, 0x02,
0x0d, 0x80, 0x03, 0x0e, 0x80, 0x04, 0x0f, 0x80,
0x80, 0x00, 0x0b, 0x80, 0x01, 0x0c, 0x80, 0x02,
0x0d, 0x80, 0x03, 0x0e, 0x80, 0x04, 0x0f, 0x80};
static const ulvec8 kSHUF2 = {0x0a, 0x80, 0x00, 0x0b, 0x80, 0x01, 0x0c, 0x80,
0x02, 0x0d, 0x80, 0x03, 0x0e, 0x80, 0x04, 0x0f,
0x0a, 0x80, 0x00, 0x0b, 0x80, 0x01, 0x0c, 0x80,
0x02, 0x0d, 0x80, 0x03, 0x0e, 0x80, 0x04, 0x0f};
static const ulvec8 kSHUF3 = {0x80, 0x80, 0x06, 0x80, 0x80, 0x07, 0x80, 0x80,
0x08, 0x80, 0x80, 0x09, 0x80, 0x80, 0x0a, 0x80,
0x80, 0x80, 0x06, 0x80, 0x80, 0x07, 0x80, 0x80,
0x08, 0x80, 0x80, 0x09, 0x80, 0x80, 0x0a, 0x80};
static const ulvec8 kSHUF4 = {0x05, 0x80, 0x80, 0x06, 0x80, 0x80, 0x07, 0x80,
0x80, 0x08, 0x80, 0x80, 0x09, 0x80, 0x80, 0x0a,
0x05, 0x80, 0x80, 0x06, 0x80, 0x80, 0x07, 0x80,
0x80, 0x08, 0x80, 0x80, 0x09, 0x80, 0x80, 0x0a};
static const ulvec8 kSHUF5 = {0x80, 0x05, 0x80, 0x80, 0x06, 0x80, 0x80, 0x07,
0x80, 0x80, 0x08, 0x80, 0x80, 0x09, 0x80, 0x80,
0x80, 0x05, 0x80, 0x80, 0x06, 0x80, 0x80, 0x07,
0x80, 0x80, 0x08, 0x80, 0x80, 0x09, 0x80, 0x80};
// NV21ToYUV24Row_AVX2
void NV21ToYUV24Row_AVX2(const uint8_t* src_y,
const uint8_t* src_vu,
uint8_t* dst_yuv24,
int width) {
uint8_t* src_y_ptr;
uint64_t src_offset = 0;
uint64_t width64;
width64 = width;
src_y_ptr = (uint8_t*)src_y;
asm volatile(
"vmovdqu %5, %%ymm0 \n" // init blend value
"vmovdqu %6, %%ymm1 \n" // init blend value
"vmovdqu %7, %%ymm2 \n" // init blend value
// "sub $0x20, %3 \n" //sub 32 from width for final loop
LABELALIGN
"1: \n" // label 1
"vmovdqu (%0,%4), %%ymm3 \n" // src_y
"vmovdqu 1(%1,%4), %%ymm4 \n" // src_uv+1
"vmovdqu (%1), %%ymm5 \n" // src_uv
"vpshufb %8, %%ymm3, %%ymm13 \n" // y, kSHUF0 for shuf
"vpshufb %9, %%ymm4, %%ymm14 \n" // uv+1, kSHUF1 for
// shuf
"vpshufb %10, %%ymm5, %%ymm15 \n" // uv, kSHUF2 for
// shuf
"vpshufb %11, %%ymm3, %%ymm3 \n" // y kSHUF3 for shuf
"vpshufb %12, %%ymm4, %%ymm4 \n" // uv+1 kSHUF4 for
// shuf
"vpblendvb %%ymm0, %%ymm14, %%ymm13, %%ymm12 \n" // blend 0
"vpblendvb %%ymm0, %%ymm13, %%ymm14, %%ymm14 \n" // blend 0
"vpblendvb %%ymm2, %%ymm15, %%ymm12, %%ymm12 \n" // blend 2
"vpblendvb %%ymm1, %%ymm15, %%ymm14, %%ymm13 \n" // blend 1
"vpshufb %13, %%ymm5, %%ymm15 \n" // shuffle const
"vpor %%ymm4, %%ymm3, %%ymm5 \n" // get results
"vmovdqu %%ymm12, 0x20(%2) \n" // store dst_yuv+20h
"vpor %%ymm15, %%ymm5, %%ymm3 \n" // get results
"add $0x20, %4 \n" // add to src buffer
// ptr
"vinserti128 $0x1, %%xmm3, %%ymm13, %%ymm4 \n" // insert
"vperm2i128 $0x31, %%ymm13, %%ymm3, %%ymm5 \n" // insert
"vmovdqu %%ymm4, (%2) \n" // store dst_yuv
"vmovdqu %%ymm5, 0x40(%2) \n" // store dst_yuv+40h
"add $0x60,%2 \n" // add to dst buffer
// ptr
// "cmp %3, %4 \n" //(width64 -
// 32 bytes) and src_offset
"sub $0x20,%3 \n" // 32 pixels per loop
"jg 1b \n"
"vzeroupper \n" // sse-avx2
// transistions
: "+r"(src_y), //%0
"+r"(src_vu), //%1
"+r"(dst_yuv24), //%2
"+r"(width64), //%3
"+r"(src_offset) //%4
: "m"(kBLEND0), //%5
"m"(kBLEND1), //%6
"m"(kBLEND2), //%7
"m"(kSHUF0), //%8
"m"(kSHUF1), //%9
"m"(kSHUF2), //%10
"m"(kSHUF3), //%11
"m"(kSHUF4), //%12
"m"(kSHUF5) //%13
: "memory", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm12",
"xmm13", "xmm14", "xmm15");
}
#endif // HAS_NV21TOYUV24ROW_AVX2
#ifdef HAS_SWAPUVROW_SSSE3
// Shuffle table for reversing the bytes.
static const uvec8 kShuffleUVToVU = {1u, 0u, 3u, 2u, 5u, 4u, 7u, 6u,
9u, 8u, 11u, 10u, 13u, 12u, 15u, 14u};
// Convert UV plane of NV12 to VU of NV21.
void SwapUVRow_SSSE3(const uint8_t* src_uv, uint8_t* dst_vu, int width) {
asm volatile(
"movdqu %3,%%xmm5 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"lea 0x20(%0),%0 \n"
"pshufb %%xmm5,%%xmm0 \n"
"pshufb %%xmm5,%%xmm1 \n"
"movdqu %%xmm0,(%1) \n"
"movdqu %%xmm1,0x10(%1) \n"
"lea 0x20(%1),%1 \n"
"sub $0x10,%2 \n"
"jg 1b \n"
: "+r"(src_uv), // %0
"+r"(dst_vu), // %1
"+r"(width) // %2
: "m"(kShuffleUVToVU) // %3
: "memory", "cc", "xmm0", "xmm1", "xmm5");
}
#endif // HAS_SWAPUVROW_SSSE3
#ifdef HAS_SWAPUVROW_AVX2
void SwapUVRow_AVX2(const uint8_t* src_uv, uint8_t* dst_vu, int width) {
asm volatile(
"vbroadcastf128 %3,%%ymm5 \n"
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm0 \n"
"vmovdqu 0x20(%0),%%ymm1 \n"
"lea 0x40(%0),%0 \n"
"vpshufb %%ymm5,%%ymm0,%%ymm0 \n"
"vpshufb %%ymm5,%%ymm1,%%ymm1 \n"
"vmovdqu %%ymm0,(%1) \n"
"vmovdqu %%ymm1,0x20(%1) \n"
"lea 0x40(%1),%1 \n"
"sub $0x20,%2 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_uv), // %0
"+r"(dst_vu), // %1
"+r"(width) // %2
: "m"(kShuffleUVToVU) // %3
: "memory", "cc", "xmm0", "xmm1", "xmm5");
}
#endif // HAS_SWAPUVROW_AVX2
void HalfMergeUVRow_SSSE3(const uint8_t* src_u,
int src_stride_u,
const uint8_t* src_v,
int src_stride_v,
uint8_t* dst_uv,
int width) {
asm volatile(
"pcmpeqb %%xmm4,%%xmm4 \n"
"psrlw $0xf,%%xmm4 \n"
"packuswb %%xmm4,%%xmm4 \n"
"pxor %%xmm5,%%xmm5 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n" // load 16 U values
"movdqu (%1),%%xmm1 \n" // load 16 V values
"movdqu 0(%0,%4,1),%%xmm2 \n" // 16 from next row
"movdqu 0(%1,%5,1),%%xmm3 \n"
"lea 0x10(%0),%0 \n"
"pmaddubsw %%xmm4,%%xmm0 \n" // half size
"pmaddubsw %%xmm4,%%xmm1 \n"
"pmaddubsw %%xmm4,%%xmm2 \n"
"pmaddubsw %%xmm4,%%xmm3 \n"
"lea 0x10(%1),%1 \n"
"paddw %%xmm2,%%xmm0 \n"
"paddw %%xmm3,%%xmm1 \n"
"psrlw $0x1,%%xmm0 \n"
"psrlw $0x1,%%xmm1 \n"
"pavgw %%xmm5,%%xmm0 \n"
"pavgw %%xmm5,%%xmm1 \n"
"packuswb %%xmm0,%%xmm0 \n"
"packuswb %%xmm1,%%xmm1 \n"
"punpcklbw %%xmm1,%%xmm0 \n"
"movdqu %%xmm0,(%2) \n" // store 8 UV pixels
"lea 0x10(%2),%2 \n"
"sub $0x10,%3 \n" // 16 src pixels per loop
"jg 1b \n"
: "+r"(src_u), // %0
"+r"(src_v), // %1
"+r"(dst_uv), // %2
"+r"(width) // %3
: "r"((intptr_t)(src_stride_u)), // %4
"r"((intptr_t)(src_stride_v)) // %5
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5");
}
void HalfMergeUVRow_AVX2(const uint8_t* src_u,
int src_stride_u,
const uint8_t* src_v,
int src_stride_v,
uint8_t* dst_uv,
int width) {
asm volatile(
"vpcmpeqb %%ymm4,%%ymm4,%%ymm4 \n"
"vpsrlw $0xf,%%ymm4,%%ymm4 \n"
"vpackuswb %%ymm4,%%ymm4,%%ymm4 \n"
"vpxor %%ymm5,%%ymm5,%%ymm5 \n"
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm0 \n" // load 32 U values
"vmovdqu (%1),%%ymm1 \n" // load 32 V values
"vmovdqu 0(%0,%4,1),%%ymm2 \n" // 32 from next row
"vmovdqu 0(%1,%5,1),%%ymm3 \n"
"lea 0x20(%0),%0 \n"
"vpmaddubsw %%ymm4,%%ymm0,%%ymm0 \n" // half size
"vpmaddubsw %%ymm4,%%ymm1,%%ymm1 \n"
"vpmaddubsw %%ymm4,%%ymm2,%%ymm2 \n"
"vpmaddubsw %%ymm4,%%ymm3,%%ymm3 \n"
"lea 0x20(%1),%1 \n"
"vpaddw %%ymm2,%%ymm0,%%ymm0 \n"
"vpaddw %%ymm3,%%ymm1,%%ymm1 \n"
"vpsrlw $0x1,%%ymm0,%%ymm0 \n"
"vpsrlw $0x1,%%ymm1,%%ymm1 \n"
"vpavgw %%ymm5,%%ymm0,%%ymm0 \n"
"vpavgw %%ymm5,%%ymm1,%%ymm1 \n"
"vpackuswb %%ymm0,%%ymm0,%%ymm0 \n"
"vpackuswb %%ymm1,%%ymm1,%%ymm1 \n"
"vpunpcklbw %%ymm1,%%ymm0,%%ymm0 \n"
"vmovdqu %%ymm0,(%2) \n" // store 16 UV pixels
"lea 0x20(%2),%2 \n"
"sub $0x20,%3 \n" // 32 src pixels per loop
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_u), // %0
"+r"(src_v), // %1
"+r"(dst_uv), // %2
"+r"(width) // %3
: "r"((intptr_t)(src_stride_u)), // %4
"r"((intptr_t)(src_stride_v)) // %5
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5");
}
void ClampFloatToZero_SSE2(const float* src_x, float* dst_y, int width) {
asm volatile(
"pxor %%xmm1,%%xmm1 \n"
LABELALIGN
"1: \n"
"movd (%0),%%xmm0 \n" // load float
"maxss %%xmm1, %%xmm0 \n" // clamp to zero
"add 4, %0 \n"
"movd %%xmm0, (%1) \n" // store float
"add 4, %1 \n"
"sub $0x4,%2 \n" // 1 float per loop
"jg 1b \n"
: "+r"(src_x), // %0
"+r"(dst_y), // %1
"+r"(width) // %2
:
: "memory", "cc", "xmm0", "xmm1");
}
#endif // defined(__x86_64__) || defined(__i386__)
#ifdef __cplusplus
} // extern "C"
} // namespace libyuv
#endif
| 44.704111
| 90
| 0.338221
|
onbings
|
6075800f99e5905b5bd48ccc527a9c603d497064
| 1,263
|
cpp
|
C++
|
LabWork1_Q3_StoreLargeNumber/src/AddBigNumber.cpp
|
ming0520/DSA---Workspace
|
ad570544618abb92719278e6ea2a5529445921c3
|
[
"MIT"
] | null | null | null |
LabWork1_Q3_StoreLargeNumber/src/AddBigNumber.cpp
|
ming0520/DSA---Workspace
|
ad570544618abb92719278e6ea2a5529445921c3
|
[
"MIT"
] | null | null | null |
LabWork1_Q3_StoreLargeNumber/src/AddBigNumber.cpp
|
ming0520/DSA---Workspace
|
ad570544618abb92719278e6ea2a5529445921c3
|
[
"MIT"
] | null | null | null |
/*
* AddBigNumber.cpp
*
* Created on: Dec 1, 2019
* Author: mingb
*/
#include "AddBigNumber.h"
BigNumber AddBigNumber::getSum(){return sum;}
AddBigNumber::AddBigNumber() {
// TODO Auto-generated constructor stub
}
AddBigNumber::AddBigNumber(string num1, string num2) {
// TODO Auto-generated constructor stub
bigNumber[0].setNumber(num1);
bigNumber[1].setNumber(num2);
// int minBlock = (bigNumber[0].getMyTop() < bigNumber[1].getMyTop() ?
// bigNumber[0].getMyTop() + 1: bigNumber[1].getMyTop()+ 1);
int maxBlock = (bigNumber[0].getMyTop() < bigNumber[1].getMyTop() ?
bigNumber[1].getMyTop() + 1: bigNumber[0].getMyTop() + 1);
int carry = 0;
int temp = 0;
// cout << bigNumber[0].getMyTop() << " " << bigNumber[1].getMyTop()<< endl;
for(int i = 0; i < maxBlock; i++){
temp = bigNumber[0].getBlock(i) + bigNumber[1].getBlock(i) + carry;
// cout << bigNumber[0].getBlock(i) << "+" << bigNumber[1].getBlock(i)
// << "+" << carry
// << "=" << temp << endl;
if(temp / 1000 != 0)
carry = 1;
else
carry = 0;
temp %= 1000;
sum.push(temp);
temp = 0;
if(i == maxBlock - 1){
if(carry != 0){
sum.push(carry);
}
}
}
}
AddBigNumber::~AddBigNumber() {
// TODO Auto-generated destructor stub
}
| 20.370968
| 77
| 0.606492
|
ming0520
|
607736824a83bbbf4eaa1049e23016932365fd10
| 50,030
|
cpp
|
C++
|
vk_order_independent_transparency/main.cpp
|
yangtzehina/VulkanStudy
|
76af12e46ecbba0a2d22812ebec3faa7383b0328
|
[
"MIT"
] | 1
|
2021-11-11T13:33:54.000Z
|
2021-11-11T13:33:54.000Z
|
vk_order_independent_transparency/main.cpp
|
yangtzehina/VulkanStudy
|
76af12e46ecbba0a2d22812ebec3faa7383b0328
|
[
"MIT"
] | null | null | null |
vk_order_independent_transparency/main.cpp
|
yangtzehina/VulkanStudy
|
76af12e46ecbba0a2d22812ebec3faa7383b0328
|
[
"MIT"
] | null | null | null |
/* Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of NVIDIA CORPORATION nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// This sample demonstrates several ways of rendering transparent objects
// without requiring them to be sorted in advance, including both
// algorithms that produce ground-truth images if given enough memory, and
// an algorithm that produces approximate results.
// For more information on these techniques, run the sample, see
// oitScene.frag.glsl,or read the documentation that comes with this sample.
// Here's how the C++ code is organized:
// oit.h: Main Sample application structure with all functions.
// oitRender.cpp: Main OIT-specific rendering functions.
// oit.cpp: Main OIT-specific resource creation functions.
// oitGui.cpp: GUI for the application.
// utilities_vk.h: Helper functions that can exist without a sample.
// main.cpp: All other functions not specific to OIT.
#pragma warning(disable : 26812) // Disable the warning about Vulkan's enumerations being untyped in VS2019.
#if defined(_WIN32)
// Include Windows before GLFW3 to fix some errors with std::min and std::max
#define WIN32_LEAN_AND_MEAN
#ifndef NOMINMAX
#define NOMINMAX
#endif // #ifndef NOMINMAX
#include <Windows.h>
#endif
#ifndef GLFW_INCLUDE_VULKAN
#define GLFW_INCLUDE_VULKAN
#endif
#include <GLFW/glfw3.h>
#include <algorithm>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <random>
#include <set>
#include <stdexcept>
#include <vector>
#include <imgui/imgui_helper.h>
#include <imgui/imgui_impl_vk.h>
#include <nvpwindow.hpp>
#include <nvh/cameracontrol.hpp>
#include <nvh/fileoperations.hpp>
#include <nvh/misc.hpp>
#include <nvh/nvprint.hpp>
#include <nvh/timesampler.hpp>
#include <nvvk/commands_vk.hpp>
#include <nvvk/descriptorsets_vk.hpp>
#include <nvvk/error_vk.hpp>
#include <nvvk/extensions_vk.hpp>
#include <nvvk/images_vk.hpp>
#include <nvvk/memorymanagement_vk.hpp>
#include <nvvk/pipeline_vk.hpp>
#include <nvvk/profiler_vk.hpp>
#include <nvvk/shadermodulemanager_vk.hpp>
#include <nvvk/shaders_vk.hpp>
#include <nvvk/swapchain_vk.hpp>
#include "oit.h"
// Application constants
const int GRID_SIZE = 16;
const float GLOBAL_SCALE = 8.0f;
///////////////////////////////////////////////////////////////////////////////
// Callbacks //
///////////////////////////////////////////////////////////////////////////////
void Sample::resize(int width, int height)
{
assert(width == m_windowState.m_swapSize[0]);
assert(height == m_windowState.m_swapSize[1]);
updateRendererImmediate(true, false);
}
bool Sample::mouse_pos(int x, int y)
{
return ImGuiH::mouse_pos(x, y);
}
bool Sample::mouse_button(int button, int action)
{
return ImGuiH::mouse_button(button, action);
}
bool Sample::mouse_wheel(int wheel)
{
return ImGuiH::mouse_wheel(wheel);
}
bool Sample::key_char(int key)
{
return ImGuiH::key_char(key);
}
bool Sample::key_button(int button, int action, int mods)
{
return ImGuiH::key_button(button, action, mods);
}
///////////////////////////////////////////////////////////////////////////////
// Object Creation, Destruction, and Recreation //
///////////////////////////////////////////////////////////////////////////////
bool Sample::begin()
{
m_profilerPrint = true;
m_timeInTitle = true;
// Initialize Dear ImGui (we'll call InitVK later)
ImGuiH::Init(m_windowState.m_winSize[0], m_windowState.m_winSize[1], this);
ImGui::GetIO().IniFilename = nullptr; // Don't create a .ini file for storing data across application launches
// Initialize Dear ImGui's Vulkan renderer:
ImGui::InitVK(m_context, m_context.m_physicalDevice, m_context.m_queueGCT, m_context.m_queueGCT.familyIndex, nullptr, 0); // ImGui will use its own render pass
// Initialize all Vulkan components that will be constant throughout the application lifecycle.
// Components that can change are handled by updateRendererFromState.
m_ringFences.init(m_context);
m_ringCmdPool.init(m_context, m_context.m_queueGCT.familyIndex, VK_COMMAND_POOL_CREATE_TRANSIENT_BIT);
m_submission.init(m_context.m_queueGCT.queue);
m_debug.setup(m_context);
createTextureSampler();
m_deviceMemoryAllocator.init(m_context, m_context.m_physicalDevice);
m_allocatorDma.init(m_context, m_context.m_physicalDevice, &m_deviceMemoryAllocator);
// Configure shader system (note that this also creates shader modules as we add them)
{
// Initialize shader system (this keeps track of shaders so that you can reload all of them at once):
m_shaderModuleManager.init(m_context);
// Add search paths for files and includes
m_shaderModuleManager.addDirectory("GLSL_" PROJECT_NAME); // For when running in the install directory
m_shaderModuleManager.addDirectory(".");
m_shaderModuleManager.addDirectory(NVPSystem::exePath() + PROJECT_RELDIRECTORY);
m_shaderModuleManager.addDirectory(NVPSystem::exePath() + PROJECT_RELDIRECTORY + "..");
m_shaderModuleManager.addDirectory(".."); // for when working directory in Debug is $(ProjectDir)
m_shaderModuleManager.addDirectory("../.."); // for when using $(TargetDir)
m_shaderModuleManager.addDirectory("../shipped/" PROJECT_NAME); // For when running from the bin_x64 directory on Linux
m_shaderModuleManager.addDirectory("../../shipped/" PROJECT_NAME); // for when using $(TargetDir)
m_shaderModuleManager.addDirectory("../../../shipped/" PROJECT_NAME); // for when using $(TargetDir) and build_all
// We have to manually set up paths to files we could include.
m_shaderModuleManager.registerInclude("common.h");
m_shaderModuleManager.registerInclude("oitColorDepthDefines.glsl");
m_shaderModuleManager.registerInclude("oitCompositeDefines.glsl");
m_shaderModuleManager.registerInclude("shaderCommon.glsl");
}
// Call updateRendererImmediate to set up the rest of the renderer with the initial swapchain size:
{
updateRendererImmediate(true, true);
}
// Register enumerations with the Dear ImGui registry
{
m_imGuiRegistry.enumAdd(GUI_ALGORITHM, OIT_SIMPLE, "simple");
m_imGuiRegistry.enumAdd(GUI_ALGORITHM, OIT_LINKEDLIST, "linkedlist");
m_imGuiRegistry.enumAdd(GUI_ALGORITHM, OIT_LOOP, "loop32 two pass");
if(m_context.hasDeviceExtension(VK_KHR_SHADER_ATOMIC_INT64_EXTENSION_NAME))
{
m_imGuiRegistry.enumAdd(GUI_ALGORITHM, OIT_LOOP64, "loop64");
}
m_imGuiRegistry.enumAdd(GUI_ALGORITHM, OIT_SPINLOCK, "spinlock");
if(m_context.hasDeviceExtension(VK_EXT_FRAGMENT_SHADER_INTERLOCK_EXTENSION_NAME))
{
m_imGuiRegistry.enumAdd(GUI_ALGORITHM, OIT_INTERLOCK, "interlock");
}
m_imGuiRegistry.enumAdd(GUI_ALGORITHM, OIT_WEIGHTED, "weighted blend");
m_imGuiRegistry.enumAdd(GUI_OITSAMPLES, 1, "1");
m_imGuiRegistry.enumAdd(GUI_OITSAMPLES, 2, "2");
m_imGuiRegistry.enumAdd(GUI_OITSAMPLES, 4, "4");
m_imGuiRegistry.enumAdd(GUI_OITSAMPLES, 8, "8");
m_imGuiRegistry.enumAdd(GUI_OITSAMPLES, 16, "16");
m_imGuiRegistry.enumAdd(GUI_OITSAMPLES, 32, "32");
m_imGuiRegistry.enumAdd(GUI_AA, AA_NONE, "none");
m_imGuiRegistry.enumAdd(GUI_AA, AA_MSAA_4X, "msaa 4x pixel-shading");
m_imGuiRegistry.enumAdd(GUI_AA, AA_SSAA_4X, "msaa 4x sample-shading");
m_imGuiRegistry.enumAdd(GUI_AA, AA_SUPER_4X, "super 4x");
m_imGuiRegistry.enumAdd(GUI_AA, AA_MSAA_8X, "msaa 8x pixel-shading");
m_imGuiRegistry.enumAdd(GUI_AA, AA_SSAA_8X, "msaa 8x sample-shading");
}
// Initialize camera
{
m_cameraControl.m_sceneOrbit = nvmath::vec3(0.0f);
m_cameraControl.m_sceneDimension = static_cast<float>(GRID_SIZE) * 0.25f;
m_cameraControl.m_viewMatrix =
nvmath::look_at(m_cameraControl.m_sceneOrbit - (nvmath::vec3(0, 0, -0.6f) * m_cameraControl.m_sceneDimension * 5.0f),
m_cameraControl.m_sceneOrbit, vec3(0.0f, 1.0f, 0.0f));
}
// Initialize the UBO
m_sceneUbo.alphaMin = 0.2f;
m_sceneUbo.alphaWidth = 0.3f;
m_frame = 0;
m_lastState = m_state;
return true; // Initialization succeeded
}
void Sample::updateRendererImmediate(bool swapchainSizeChanged, bool forceRebuildAll)
{
VkCommandBuffer cmd = createTempCmdBuffer();
cmdUpdateRendererFromState(cmd, swapchainSizeChanged, forceRebuildAll);
vkEndCommandBuffer(cmd);
m_submission.enqueue(cmd);
submissionExecute();
vkDeviceWaitIdle(m_context);
m_ringFences.reset();
m_ringCmdPool.reset();
}
void Sample::cmdUpdateRendererFromState(VkCommandBuffer cmdBuffer, bool swapchainSizeChanged, bool forceRebuildAll)
{
m_state.recomputeAntialiasingSettings();
// Determine what needs to be rebuilt
swapchainSizeChanged |= forceRebuildAll;
const bool vsyncChanged = (m_lastVsync != getVsync()) || forceRebuildAll;
const bool shadersNeedUpdate = (m_state.algorithm != m_lastState.algorithm) //
|| (m_state.oitLayers != m_lastState.oitLayers) //
|| (m_state.tailBlend != m_lastState.tailBlend) //
|| (m_state.msaa != m_lastState.msaa) //
|| (m_state.sampleShading != m_lastState.sampleShading) //
|| forceRebuildAll;
const bool sceneNeedsReinit = (m_state.numObjects != m_lastState.numObjects) //
|| (m_state.scaleWidth != m_lastState.scaleWidth) //
|| (m_state.scaleMin != m_lastState.scaleMin) //
|| (m_state.subdiv != m_lastState.subdiv) //
|| forceRebuildAll;
const bool imagesNeedReinit = (m_state.supersample != m_lastState.supersample) //
|| (m_state.msaa != m_lastState.msaa) //
|| (m_state.algorithm != m_lastState.algorithm) //
|| (m_state.sampleShading != m_lastState.sampleShading) //
|| (m_state.oitLayers != m_lastState.oitLayers) //
|| ((m_state.algorithm == OIT_LINKEDLIST)
&& (m_state.linkedListAllocatedPerElement != m_lastState.linkedListAllocatedPerElement)) //
|| swapchainSizeChanged //
|| forceRebuildAll;
const bool descriptorSetsNeedReinit = ((m_state.algorithm == OIT_LOOP64) && (m_lastState.algorithm != OIT_LOOP64)) //
|| ((m_state.algorithm != OIT_LOOP64) && (m_lastState.algorithm == OIT_LOOP64)) //
|| forceRebuildAll;
const bool framebuffersAndDescriptorsNeedReinit = imagesNeedReinit //
|| vsyncChanged //
|| forceRebuildAll;
const bool renderPassesNeedReinit = (m_state.msaa != m_lastState.msaa) //
|| forceRebuildAll;
const bool pipelinesNeedReinit = (m_state.algorithm != m_lastState.algorithm) //
|| shadersNeedUpdate || imagesNeedReinit;
const bool anythingChanged = shadersNeedUpdate || sceneNeedsReinit || imagesNeedReinit || descriptorSetsNeedReinit
|| framebuffersAndDescriptorsNeedReinit || renderPassesNeedReinit;
if(anythingChanged)
{
vkDeviceWaitIdle(m_context);
LOGI("framebuffer: %d x %d (%d msaa)\n", m_windowState.m_swapSize[0], m_windowState.m_swapSize[1], m_state.msaa);
if(vsyncChanged || swapchainSizeChanged)
{
m_swapChain.cmdUpdateBarriers(cmdBuffer);
createUniformBuffers();
}
if(sceneNeedsReinit)
{
initScene(cmdBuffer);
}
if(imagesNeedReinit)
{
createFrameImages(cmdBuffer);
}
if(descriptorSetsNeedReinit)
{
createDescriptorSets();
}
if(renderPassesNeedReinit)
{
createRenderPasses();
ImGui::ReInitPipelinesVK(m_renderPassGUI);
}
if(framebuffersAndDescriptorsNeedReinit)
{
updateAllDescriptorSets();
createFramebuffers();
}
if(shadersNeedUpdate)
{
createOrReloadShaderModules();
}
if(pipelinesNeedReinit)
{
createGraphicsPipelines();
}
setUpViewportsAndScissors();
m_lastVsync = getVsync();
}
}
void Sample::end()
{
vkDeviceWaitIdle(m_context);
m_profilerVK.deinit();
ImGui::ShutdownVK();
ImGui::DestroyContext();
// From updateRendererFromState
destroyGraphicsPipelines();
m_shaderModuleManager.deinit();
destroyFramebuffers();
destroyRenderPasses();
destroyDescriptorSets();
destroyFrameImages();
destroyScene();
destroyUniformBuffers();
// From begin
m_allocatorDma.deinit();
m_deviceMemoryAllocator.deinit();
destroyTextureSampler();
m_ringCmdPool.deinit();
m_ringFences.deinit();
}
void Sample::destroyTextureSampler()
{
vkDestroySampler(m_context, m_pointSampler, nullptr);
}
void Sample::createTextureSampler()
{
// Create a point sampler using base Vulkan
VkSamplerCreateInfo samplerInfo = nvvk::make<VkSamplerCreateInfo>();
samplerInfo.magFilter = VK_FILTER_LINEAR;
samplerInfo.minFilter = VK_FILTER_LINEAR;
samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.anisotropyEnable = VK_FALSE;
samplerInfo.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK;
samplerInfo.unnormalizedCoordinates = VK_FALSE;
samplerInfo.compareEnable = VK_FALSE;
samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST;
NVVK_CHECK(vkCreateSampler(m_context, &samplerInfo, nullptr, &m_pointSampler));
}
void Sample::destroyUniformBuffers()
{
for(nvvk::BufferDma& uniformBuffer : m_uniformBuffers)
{
m_allocatorDma.destroy(uniformBuffer);
}
}
void Sample::createUniformBuffers()
{
destroyUniformBuffers();
VkDeviceSize bufferSize = sizeof(SceneData);
m_uniformBuffers.resize(m_swapChain.getImageCount());
for(uint32_t i = 0; i < m_swapChain.getImageCount(); i++)
{
m_uniformBuffers[i] = m_allocatorDma.createBuffer(bufferSize, // Buffer size
VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, // Usage
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT // Memory flags
);
}
}
void Sample::destroyScene()
{
m_allocatorDma.destroy(m_indexBuffer);
m_allocatorDma.destroy(m_vertexBuffer);
}
void Sample::initScene(VkCommandBuffer commandBuffer)
{
destroyScene();
// A Mesh consists of vectors of vertices, triangle list indices, and lines.
// It assumes that its type contains variables, at least, each vertex's position, normal, and color.
// (We'll ignore lines when converting this to a vertex and index buffer.)
nvh::geometry::Mesh<Vertex> completeMesh;
// We'll use C++11-style random number generation here, but you could also do this
// with rand() and srand().
std::default_random_engine rnd(3625); // Fixed seed
std::uniform_real_distribution<float> uniformDist;
for(uint32_t i = 0; i < m_state.numObjects; i++)
{
// Generate a random position in [-GLOBAL_SCALE/2, GLOBAL_SCALE/2)^3
nvmath::vec3 center(uniformDist(rnd), uniformDist(rnd), uniformDist(rnd));
center = (center - nvmath::vec3(0.5)) * GLOBAL_SCALE;
// Generate a random radius
float radius = GLOBAL_SCALE * 0.9f / GRID_SIZE;
radius *= uniformDist(rnd) * m_state.scaleWidth + m_state.scaleMin;
// Our vectors are vertical, so this represents a scale followed by a translation:
nvmath::mat4 matrix = nvmath::translation_mat4(center) * nvmath::scale_mat4(nvmath::vec3(radius));
// Add a sphere to the complete mesh, and then color it:
const uint32_t vtxStart = completeMesh.getVerticesCount(); // First vertex to color
nvh::geometry::Sphere<Vertex>::add(completeMesh, matrix, m_state.subdiv * 2, m_state.subdiv);
if(i == 0)
{
m_objectTriangleIndices = completeMesh.getTriangleIndicesCount();
}
// Color in unpremultiplied linear space
nvmath::vec4 color(uniformDist(rnd), uniformDist(rnd), uniformDist(rnd), uniformDist(rnd));
color.x *= color.x;
color.y *= color.y;
color.z *= color.z;
uint32_t vtxEnd = completeMesh.getVerticesCount();
for(uint32_t v = vtxStart; v < vtxEnd; v++)
{
completeMesh.m_vertices[v].color = color;
}
}
// Count the total number of triangle indices
m_sceneTriangleIndices = completeMesh.getTriangleIndicesCount();
// Create the vertex and index buffers and synchronously upload them to the
// GPU, waiting for them to finish uploading. Note that applications may wish
// to implement asynchronous uploads, which you can see how to do in the
// vk_async_resources sample.
// When this goes out of scope, it'll synchronously perform all of the copy operations.
nvvk::StagingMemoryManager scopedTransfer(m_context.m_device, m_context.m_physicalDevice);
{
nvvk::ScopeCommandBuffer cmd(m_context, m_context.m_queueT, m_context.m_queueT);
// Create vertex buffer
VkDeviceSize vtxBufferSize = static_cast<VkDeviceSize>(completeMesh.getVerticesSize());
m_vertexBuffer = m_allocatorDma.createBuffer(vtxBufferSize, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT);
scopedTransfer.cmdToBuffer(cmd, m_vertexBuffer.buffer, 0, vtxBufferSize, completeMesh.m_vertices.data());
m_debug.setObjectName(m_vertexBuffer.buffer, "m_vertexBuffer");
VkDeviceSize idxBufferSize = static_cast<VkDeviceSize>(completeMesh.getTriangleIndicesSize());
m_indexBuffer = m_allocatorDma.createBuffer(idxBufferSize, VK_BUFFER_USAGE_INDEX_BUFFER_BIT);
scopedTransfer.cmdToBuffer(cmd, m_indexBuffer.buffer, 0, idxBufferSize, completeMesh.m_indicesTriangles.data());
m_debug.setObjectName(m_indexBuffer.buffer, "m_indexBuffer");
}
}
void Sample::destroyFramebuffers()
{
vkDestroyFramebuffer(m_context, m_mainColorDepthFramebuffer, nullptr);
m_mainColorDepthFramebuffer = nullptr;
vkDestroyFramebuffer(m_context, m_guiFramebuffer, nullptr);
m_guiFramebuffer = nullptr;
if (m_weightedFramebuffer != nullptr) {
vkDestroyFramebuffer(m_context, m_weightedFramebuffer, nullptr);
m_weightedFramebuffer = nullptr;
}
}
void Sample::createFramebuffers()
{
destroyFramebuffers();
// Color + depth offscreen framebuffer
{
std::array<VkImageView, 2> attachments = {m_colorImage.view, m_depthImage.view};
VkFramebufferCreateInfo fbInfo = nvvk::make<VkFramebufferCreateInfo>();
fbInfo.renderPass = m_renderPassColorDepthClear;
fbInfo.attachmentCount = static_cast<uint32_t>(attachments.size());
fbInfo.pAttachments = attachments.data();
fbInfo.width = m_colorImage.c_width;
fbInfo.height = m_colorImage.c_height;
fbInfo.layers = 1;
NVVK_CHECK(vkCreateFramebuffer(m_context, &fbInfo, NULL, &m_mainColorDepthFramebuffer));
m_debug.setObjectName(m_mainColorDepthFramebuffer, "m_mainColorDepthFramebuffer");
}
// Weighted color + weighted reveal framebuffer (for Weighted, Blended
// Order-Independent Transparency). See the render pass description for more info.
if(m_state.algorithm == OIT_WEIGHTED)
{
std::array<VkImageView, 4> attachments = {m_oitWeightedColorImage.view, //
m_oitWeightedRevealImage.view, //
m_colorImage.view, //
m_depthImage.view};
VkFramebufferCreateInfo framebufferInfo = nvvk::make<VkFramebufferCreateInfo>();
framebufferInfo.renderPass = m_renderPassWeighted;
framebufferInfo.attachmentCount = static_cast<uint32_t>(attachments.size());
framebufferInfo.pAttachments = attachments.data();
framebufferInfo.width = m_oitWeightedColorImage.c_width;
framebufferInfo.height = m_oitWeightedColorImage.c_height;
framebufferInfo.layers = 1;
NVVK_CHECK(vkCreateFramebuffer(m_context, &framebufferInfo, nullptr, &m_weightedFramebuffer));
m_debug.setObjectName(m_weightedFramebuffer, "m_weightedColorRevealFramebuffer");
}
// ui related
{
VkImageView uiTarget = m_guiCompositeImage.view;
// Create framebuffers
VkImageView bindInfos[1];
bindInfos[0] = uiTarget;
VkFramebufferCreateInfo fbInfo = {VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO};
fbInfo.attachmentCount = NV_ARRAY_SIZE(bindInfos);
fbInfo.pAttachments = bindInfos;
fbInfo.width = m_windowState.m_swapSize[0];
fbInfo.height = m_windowState.m_swapSize[1];
fbInfo.layers = 1;
fbInfo.renderPass = m_renderPassGUI;
NVVK_CHECK(vkCreateFramebuffer(m_context, &fbInfo, NULL, &m_guiFramebuffer));
}
}
void Sample::setUpViewportsAndScissors()
{
m_scissorGUI = {0}; // Zero-initialize
m_scissorGUI.extent.width = m_windowState.m_swapSize[0];
m_scissorGUI.extent.height = m_windowState.m_swapSize[1];
m_viewportGUI = {0}; // Zero-initialize
m_viewportGUI.width = static_cast<float>(m_scissorGUI.extent.width);
m_viewportGUI.height = static_cast<float>(m_scissorGUI.extent.height);
m_viewportGUI.minDepth = 0.0f;
m_viewportGUI.maxDepth = 1.0f;
}
void Sample::createOrReloadShaderModule(nvvk::ShaderModuleID& shaderModule,
VkShaderStageFlags shaderStage,
const std::string& filename,
const std::string& prepend)
{
if(shaderModule.isValid())
{
// Reload and recompile this module from source.
m_shaderModuleManager.reloadModule(shaderModule);
}
else
{
// Register and compile the shader module with the shader module manager.
shaderModule = m_shaderModuleManager.createShaderModule(shaderStage, filename, prepend);
}
assert(shaderModule.isValid());
#ifdef _DEBUG
std::string generatedShaderName = filename + " " + prepend;
m_debug.setObjectName(m_shaderModuleManager.get(shaderModule), generatedShaderName.c_str());
#endif // #if _DEBUG
}
void Sample::destroyGraphicsPipeline(VkPipeline& pipeline)
{
if(pipeline != nullptr)
{
vkDestroyPipeline(m_context, pipeline, nullptr);
pipeline = nullptr;
}
}
VkPipeline Sample::createGraphicsPipeline(const nvvk::ShaderModuleID& vertShaderModuleID,
const nvvk::ShaderModuleID& fragShaderModuleID,
BlendMode blendMode,
bool usesVertexInput,
bool isDoubleSided,
VkRenderPass renderPass,
uint32_t subpass)
{
VkShaderModule vertShaderModule = m_shaderModuleManager.get(vertShaderModuleID);
VkShaderModule fragShaderModule = m_shaderModuleManager.get(fragShaderModuleID);
nvvk::GraphicsPipelineGeneratorCombined pipelineState(m_context, m_descriptorInfo.getPipeLayout(), renderPass);
pipelineState.addShader(vertShaderModule, // Shader module
VK_SHADER_STAGE_VERTEX_BIT // Stage
);
pipelineState.addShader(fragShaderModule, // Shader module
VK_SHADER_STAGE_FRAGMENT_BIT // Stage
);
if(usesVertexInput)
{
// Vertex input layout
VkVertexInputBindingDescription bindingDescription = Vertex::getBindingDescription();
auto attributes = Vertex::getAttributeDescriptions();
pipelineState.addBindingDescription(bindingDescription);
for(const auto& attribute : attributes)
{
pipelineState.addAttributeDescription(attribute);
}
}
pipelineState.inputAssemblyState.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
VkViewport viewport = {};
viewport.x = 0.0f;
viewport.y = 0.0f;
viewport.width = static_cast<float>(m_colorImage.c_width);
viewport.height = static_cast<float>(m_colorImage.c_height);
viewport.minDepth = 0.0f;
viewport.maxDepth = 1.0f;
VkRect2D scissor = {};
scissor.offset = {0, 0};
scissor.extent.width = m_colorImage.c_width;
scissor.extent.height = m_colorImage.c_height;
pipelineState.clearDynamicStateEnables();
pipelineState.setViewportsCount(1);
pipelineState.setViewport(0, viewport);
pipelineState.setScissorsCount(1);
pipelineState.setScissor(0, scissor);
// Enable backface culling
pipelineState.rasterizationState.cullMode = (isDoubleSided ? VK_CULL_MODE_NONE : VK_CULL_MODE_BACK_BIT);
pipelineState.rasterizationState.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
pipelineState.rasterizationState.polygonMode = VK_POLYGON_MODE_FILL;
pipelineState.rasterizationState.lineWidth = 1.f;
pipelineState.rasterizationState.depthBiasEnable = false;
pipelineState.rasterizationState.depthBiasConstantFactor = 0.f;
pipelineState.rasterizationState.depthBiasSlopeFactor = 0.f;
pipelineState.multisampleState.rasterizationSamples = (static_cast<VkSampleCountFlagBits>(m_state.msaa));
pipelineState.depthStencilState.depthBoundsTestEnable = false;
const VkCompareOp compareOp = VK_COMPARE_OP_LESS;
const VkColorComponentFlags allBits =
VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
switch(blendMode)
{
case BlendMode::NONE:
// Test and write to depth
pipelineState.depthStencilState.depthTestEnable = true;
pipelineState.depthStencilState.depthWriteEnable = true;
pipelineState.depthStencilState.depthCompareOp = compareOp;
pipelineState.setBlendAttachmentState(0, // Attachment
nvvk::GraphicsPipelineState::makePipelineColorBlendAttachmentState()); // Disable blending
break;
case BlendMode::PREMULTIPLIED:
// Test but don't write to depth
pipelineState.depthStencilState.depthTestEnable = true;
pipelineState.depthStencilState.depthWriteEnable = false;
pipelineState.depthStencilState.depthCompareOp = compareOp;
pipelineState.setBlendAttachmentState(0, // Attachment
nvvk::GraphicsPipelineState::makePipelineColorBlendAttachmentState(
allBits, VK_TRUE, //
VK_BLEND_FACTOR_ONE, // Source color blend factor
VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, // Destination color blend factor
VK_BLEND_OP_ADD, // Color blend operation
VK_BLEND_FACTOR_ONE, // Source alpha blend factor
VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, // Destination alpha blend factor
VK_BLEND_OP_ADD)); // Alpha blend operation
break;
case BlendMode::WEIGHTED_COLOR:
// Test but don't write to depth
pipelineState.depthStencilState.depthTestEnable = true;
pipelineState.depthStencilState.depthWriteEnable = false;
pipelineState.depthStencilState.depthCompareOp = compareOp;
pipelineState.setBlendAttachmentCount(2);
pipelineState.setBlendAttachmentState(0, // Attachment
nvvk::GraphicsPipelineState::makePipelineColorBlendAttachmentState(
allBits, VK_TRUE, //
VK_BLEND_FACTOR_ONE, // Source color blend factor
VK_BLEND_FACTOR_ONE, // Destination color blend factor
VK_BLEND_OP_ADD, // Color blend operation
VK_BLEND_FACTOR_ONE, // Source alpha blend factor
VK_BLEND_FACTOR_ONE, // Destination alpha blend factor
VK_BLEND_OP_ADD)); // Alpha blend operation
pipelineState.setBlendAttachmentState(1, // Attachment
nvvk::GraphicsPipelineState::makePipelineColorBlendAttachmentState(
allBits, VK_TRUE, //
VK_BLEND_FACTOR_ZERO, // Source color blend factor
VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR, // Destination color blend factor
VK_BLEND_OP_ADD, // Color blend operation
VK_BLEND_FACTOR_ZERO, // Source alpha blend factor
VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, // Destination alpha blend factor
VK_BLEND_OP_ADD)); // Alpha blend operation
break;
case BlendMode::WEIGHTED_COMPOSITE:
// Test but don't write to depth
pipelineState.depthStencilState.depthTestEnable = true;
pipelineState.depthStencilState.depthWriteEnable = false;
pipelineState.depthStencilState.depthCompareOp = compareOp;
pipelineState.setBlendAttachmentState(0, // Attachment
nvvk::GraphicsPipelineState::makePipelineColorBlendAttachmentState(
allBits, VK_TRUE, //
VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, // Source color blend factor
VK_BLEND_FACTOR_SRC_ALPHA, // Destination color blend factor
VK_BLEND_OP_ADD, // Color blend operation
VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, // Source alpha blend factor
VK_BLEND_FACTOR_SRC_ALPHA, // Destination alpha blend factor
VK_BLEND_OP_ADD)); // Alpha blend operation
break;
default:
assert(!"Blend mode configuration not implemented!");
break;
}
pipelineState.setRenderPass(renderPass);
pipelineState.createInfo.subpass = subpass;
VkPipeline pipeline = pipelineState.createPipeline();
if(pipeline == VK_NULL_HANDLE)
{
throw std::runtime_error("Failed to create graphics pipeline!");
}
#ifdef _DEBUG
// Generate a name for the graphics pipeline
std::string generatedPipelineName = std::to_string(vertShaderModuleID.m_value) + " " //
+ std::to_string(fragShaderModuleID.m_value) + " " //
+ std::to_string(static_cast<uint32_t>(blendMode)) + " " //
+ std::to_string(usesVertexInput) + " " //
+ std::to_string(reinterpret_cast<uint64_t>(renderPass)) + " " //
+ std::to_string(subpass);
m_debug.setObjectName(pipeline, generatedPipelineName.c_str());
#endif
return pipeline;
}
VkCommandBuffer Sample::createTempCmdBuffer()
{
VkCommandBuffer cmd = m_ringCmdPool.createCommandBuffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, false);
VkCommandBufferBeginInfo beginInfo = nvvk::make<VkCommandBufferBeginInfo>();
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
NVVK_CHECK(vkBeginCommandBuffer(cmd, &beginInfo));
return cmd;
}
///////////////////////////////////////////////////////////////////////////////
// Main rendering logic //
///////////////////////////////////////////////////////////////////////////////
void Sample::updateUniformBuffer(uint32_t currentImage, double time)
{
const uint32_t width = m_colorImage.c_width;
const uint32_t height = m_colorImage.c_height;
const float aspectRatio = static_cast<float>(width) / static_cast<float>(height);
nvmath::mat4 projection = nvmath::perspectiveVK(45.0f, aspectRatio, 0.01f, 50.0f);
nvmath::mat4 view = m_cameraControl.m_viewMatrix;
m_sceneUbo.projViewMatrix = projection * view;
m_sceneUbo.viewMatrix = view;
m_sceneUbo.viewMatrixInverseTranspose = nvmath::transpose(nvmath::invert(view));
m_sceneUbo.viewport = nvmath::ivec3(width, height, width * height);
void* data = m_allocatorDma.map(m_uniformBuffers[currentImage]);
memcpy(data, &m_sceneUbo, sizeof(m_sceneUbo));
m_allocatorDma.unmap(m_uniformBuffers[currentImage]);
}
void Sample::copyOffscreenToBackBuffer(int winWidth, int winHeight, ImDrawData* imguiDrawData)
{
// This function resolves + scales m_colorImage into m_guiCompositeImage, draws the Dear ImGui GUI onto
// m_guiCompositeImage, and then blits m_guiCompositeImage onto the backbuffer. Because m_colorImage is
// generally a different format (B8G8R8A8_SRGB) than m_guiCompositeImage (R8G8B8A8) (which in turn is required by
// linear-space rendering) and sometimes a different size xor has different MSAA samples/pixel, the worst case
// (MSAA resolve + change of format) takes two steps.
// Note that we could do this in one step, and further customize the filters used, using a custom kernel.
// Finally, Vulkan allows us to access the swapchain images themselves. However, while a previous version of this
// sample did that, we now render the GUI to intermediate offscreen image, as this avoids potential problems with
// swapchain recreation, and may be more familiar to developers used to OpenGL applications.
//
// As a result of the differences between MSAA resolve + downscaling, there are a few cases to handle.
// Here's a high-level node graph overview of this function:
//
// MSAA? Downsample? Neither?
// m_colorImage m_colorImage m_colorImage
// | | |
// vkCmdResolveImage vkCmdBlitImage |
// V V |
// m_downsampleImage .-----------*
// | V
// vkCmdCopyImage (reinterpret data)
// V
// m_guiCompositeImage
// |
// render Dear ImGui GUI
// V
// Swapchain
// Start a separate command buffer for this function.
VkCommandBuffer cmdBuffer = createTempCmdBuffer();
nvh::Profiler::SectionID sec = m_profilerVK.beginSection("CopyOffscreenToBackBuffer", cmdBuffer);
// Prepare to transfer from m_colorImage; check its initial state for soundness
assert(m_colorImage.currentLayout == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
assert(m_colorImage.currentAccesses == (VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT));
m_colorImage.transitionTo(cmdBuffer, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_TRANSFER_READ_BIT);
// Tracks the image that will be passed to vkCmdCopyImage
// These are the defaults if no resolve or downsample is required.
VkImage copySrcImage = m_colorImage.image.image;
VkImageLayout copySrcLayout = m_colorImage.currentLayout;
// If resolve or downsample required
if(m_state.msaa != 1 || m_state.supersample != 1)
{
// Prepare to transfer data to m_downsampleImage
m_downsampleImage.transitionTo(cmdBuffer, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT);
// MSAA branch
if(m_state.msaa != 1)
{
// Resolve the MSAA image m_colorImage to m_downsampleImage
VkImageResolve region = {0}; // Zero-initialize
region.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
region.srcSubresource.layerCount = 1;
region.dstSubresource = region.srcSubresource;
region.extent = {m_colorImage.c_width, m_colorImage.c_height, 1};
vkCmdResolveImage(cmdBuffer, // Command buffer
m_colorImage.image.image, // Source image
m_colorImage.currentLayout, // Source image layout
m_downsampleImage.image.image, // Destination image
m_downsampleImage.currentLayout, // Destination image layout
1, // Number of regions
®ion); // Regions
}
else
{
// Downsample m_colorImage to m_downsampleTargeImage
VkImageBlit region = {0}; // Zero-initialize
region.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
region.srcSubresource.layerCount = 1;
region.dstSubresource = region.srcSubresource;
region.srcOffsets[1] = {static_cast<int32_t>(m_colorImage.c_width), //
static_cast<int32_t>(m_colorImage.c_height), //
1};
region.dstOffsets[1] = {static_cast<int32_t>(m_downsampleImage.c_width), //
static_cast<int32_t>(m_downsampleImage.c_height), //
1};
vkCmdBlitImage(cmdBuffer, // Command buffer
m_colorImage.image.image, // Source image
m_colorImage.currentLayout, // Source image
m_downsampleImage.image.image, // Destination image
m_downsampleImage.currentLayout, // Destination image layout
1, // Number of regions
®ion, // Regions
VK_FILTER_LINEAR); // Use tent filtering (= box filtering in this case)
}
// Prepare to transfer data from m_downsampleImage, and set copySrcImage and copySrcLayout.
m_downsampleImage.transitionTo(cmdBuffer, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_TRANSFER_READ_BIT);
copySrcImage = m_downsampleImage.image.image;
copySrcLayout = m_downsampleImage.currentLayout;
}
// Prepare to transfer data to m_guiCompositeImage
m_guiCompositeImage.transitionTo(cmdBuffer, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT);
// Now, we want to copy data from copySrcImage to m_guiCompositeImage instead of blitting it, since blitting will try
// to convert the sRGB data and store it in linear format, which isn't what we want.
{
VkImageCopy region = {0};
region.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
region.srcSubresource.layerCount = 1;
region.dstSubresource = region.srcSubresource;
region.extent = {m_guiCompositeImage.c_width, m_guiCompositeImage.c_height, 1};
vkCmdCopyImage(cmdBuffer, // Command buffer
copySrcImage, // Source image
copySrcLayout, // Source image layout
m_guiCompositeImage.image.image, // Destination image
m_guiCompositeImage.currentLayout, // Destination image layout
1, // Number of regions
®ion); // Regions
}
// Now, render the GUI.
// If draw data exists, we begin a new render pass and call ImGui::RenderDrawDataVK.
// This render pass takes m_guiCompositeImage and transitions it to layout TRANSFER_SRC_OPTIMAL, so if we don't call
// that render pass, we have to do the transition manually.
if(imguiDrawData)
{
VkRenderPassBeginInfo renderPassBeginInfo = nvvk::make<VkRenderPassBeginInfo>();
renderPassBeginInfo.renderPass = m_renderPassGUI;
renderPassBeginInfo.framebuffer = m_guiFramebuffer;
renderPassBeginInfo.renderArea.offset.x = 0;
renderPassBeginInfo.renderArea.offset.y = 0;
renderPassBeginInfo.renderArea.extent.width = winWidth;
renderPassBeginInfo.renderArea.extent.height = winHeight;
renderPassBeginInfo.clearValueCount = 0;
renderPassBeginInfo.pClearValues = nullptr;
vkCmdBeginRenderPass(cmdBuffer, &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE);
vkCmdSetViewport(cmdBuffer, 0, 1, &m_viewportGUI);
vkCmdSetScissor(cmdBuffer, 0, 1, &m_scissorGUI);
ImGui::RenderDrawDataVK(cmdBuffer, imguiDrawData);
vkCmdEndRenderPass(cmdBuffer);
// Since the render pass changed the layout and accesses, we have to tell the ImageAndView abstraction that
// these changed:
m_guiCompositeImage.currentLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
m_guiCompositeImage.currentAccesses = VK_ACCESS_TRANSFER_READ_BIT;
}
else
{
m_guiCompositeImage.transitionTo(cmdBuffer, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_TRANSFER_READ_BIT);
}
// Finally, blit to the swapchain.
{
// Soundness check
assert(m_guiCompositeImage.c_width == winWidth);
assert(m_guiCompositeImage.c_height == winHeight);
VkImageBlit region = {0};
region.dstOffsets[1].x = winWidth;
region.dstOffsets[1].y = winHeight;
region.dstOffsets[1].z = 1;
region.srcOffsets[1].x = winWidth;
region.srcOffsets[1].y = winHeight;
region.srcOffsets[1].z = 1;
region.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
region.dstSubresource.layerCount = 1;
region.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
region.srcSubresource.layerCount = 1;
cmdImageTransition(cmdBuffer, m_swapChain.getActiveImage(), VK_IMAGE_ASPECT_COLOR_BIT, 0, VK_ACCESS_TRANSFER_WRITE_BIT,
VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
vkCmdBlitImage(cmdBuffer, // Command buffer
m_guiCompositeImage.image.image, // Source image
m_guiCompositeImage.currentLayout, // Source image layout
m_swapChain.getActiveImage(), // Destination image
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, // Destination image layout
1, // Number of regions
®ion, // Region
VK_FILTER_NEAREST); // Filter
cmdImageTransition(cmdBuffer, m_swapChain.getActiveImage(), VK_IMAGE_ASPECT_COLOR_BIT, VK_ACCESS_TRANSFER_WRITE_BIT,
0, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR);
}
// Reset the layout of m_colorImage.
m_colorImage.transitionTo(cmdBuffer, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT);
m_profilerVK.endSection(sec, cmdBuffer);
vkEndCommandBuffer(cmdBuffer);
m_submission.enqueue(cmdBuffer);
}
void Sample::submissionExecute(VkFence fence, bool useImageReadWait, bool useImageWriteSignals)
{
if(useImageReadWait && m_submissionWaitForRead)
{
VkSemaphore semRead = m_swapChain.getActiveReadSemaphore();
if(semRead)
{
m_submission.enqueueWait(semRead, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT);
}
m_submissionWaitForRead = false;
}
if(useImageWriteSignals)
{
VkSemaphore semWritten = m_swapChain.getActiveWrittenSemaphore();
if(semWritten)
{
m_submission.enqueueSignal(semWritten);
}
}
m_submission.execute(fence);
}
void Sample::think(double time)
{
int width = m_windowState.m_swapSize[0];
int height = m_windowState.m_swapSize[1];
double frameStartTime = getTime();
// Create Dear ImGui interface
DoGUI(width, height, time);
// If elements of m_state change, this reinitializes parts of the renderer.
updateRendererImmediate(false, false);
// Begin frame
{
m_submissionWaitForRead = true;
m_ringFences.setCycleAndWait(m_frame);
m_ringCmdPool.setCycle(m_ringFences.getCycleIndex());
}
// Update camera
m_cameraControl.processActions(nvmath::vec2i(getWidth(), getHeight()),
nvmath::vec2f(m_windowState.m_mouseCurrent[0], m_windowState.m_mouseCurrent[1]),
m_windowState.m_mouseButtonFlags, m_windowState.m_mouseWheel);
// Update the GPU's uniform buffer
updateUniformBuffer(m_swapChain.getActiveImageIndex(), frameStartTime);
// Record this frame's command buffer
VkCommandBuffer cmdBuffer = m_ringCmdPool.createCommandBuffer();
{
render(cmdBuffer);
NVVK_CHECK(vkEndCommandBuffer(cmdBuffer));
m_submission.enqueue(cmdBuffer);
}
// Render Dear ImGui and translate the internal image to the swapchain
{
ImGui::Render();
copyOffscreenToBackBuffer(width, height, ImGui::GetDrawData());
}
// End frame
{
submissionExecute(m_ringFences.getFence(), true, true);
m_frame++;
ImGui::EndFrame();
m_lastState = m_state;
}
}
int main(int argc, const char** argv)
{
NVPSystem system(argv[0], PROJECT_NAME);
Sample sample;
sample.m_contextInfo.addDeviceExtension(VK_KHR_SAMPLER_MIRROR_CLAMP_TO_EDGE_EXTENSION_NAME);
sample.m_contextInfo.addDeviceExtension(VK_EXT_DESCRIPTOR_INDEXING_EXTENSION_NAME);
sample.m_contextInfo.addDeviceExtension(VK_KHR_MAINTENANCE3_EXTENSION_NAME);
VkPhysicalDevicePipelineExecutablePropertiesFeaturesKHR physicalDevicePipelineExecutableProprtiesFeaturesKHR = {
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_EXECUTABLE_PROPERTIES_FEATURES_KHR, nullptr, VK_TRUE};
sample.m_contextInfo.addDeviceExtension(VK_KHR_PIPELINE_EXECUTABLE_PROPERTIES_EXTENSION_NAME, true,
&physicalDevicePipelineExecutableProprtiesFeaturesKHR);
// These extensions are both optional - there are algorithms we can use if we have them, but
// if the device doesn't support these extensions, we don't allow the user to select those algorithms.
sample.m_contextInfo.addDeviceExtension(VK_KHR_SHADER_ATOMIC_INT64_EXTENSION_NAME, true);
// VK_EXT_FRAGMENT_SHADER_INTERLOCK uses an extension which will be passed to device creation via
// VkDeviceCreateInfo's pNext chain:
VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT m_fragmentShaderInterlockFeatures{
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_INTERLOCK_FEATURES_EXT, // sType
nullptr, // pNext
VK_TRUE, // fragmentShaderSampleInterlock
VK_TRUE, // fragmentShaderPixelInterlock
VK_FALSE};
sample.m_contextInfo.addDeviceExtension(VK_EXT_FRAGMENT_SHADER_INTERLOCK_EXTENSION_NAME, true, &m_fragmentShaderInterlockFeatures);
const int SAMPLE_WIDTH = 1200;
const int SAMPLE_HEIGHT = 1024;
return sample.run(PROJECT_NAME, argc, argv, SAMPLE_WIDTH, SAMPLE_HEIGHT);
}
| 44.510676
| 162
| 0.653288
|
yangtzehina
|
607a661bdf78719090400b32c60cd396d84cb003
| 7,386
|
inl
|
C++
|
Library/Sources/Stroika/Foundation/IO/Network/URI.inl
|
SophistSolutions/Stroika
|
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
|
[
"MIT"
] | 28
|
2015-09-22T21:43:32.000Z
|
2022-02-28T01:35:01.000Z
|
Library/Sources/Stroika/Foundation/IO/Network/URI.inl
|
SophistSolutions/Stroika
|
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
|
[
"MIT"
] | 98
|
2015-01-22T03:21:27.000Z
|
2022-03-02T01:47:00.000Z
|
Library/Sources/Stroika/Foundation/IO/Network/URI.inl
|
SophistSolutions/Stroika
|
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
|
[
"MIT"
] | 4
|
2019-02-21T16:45:25.000Z
|
2022-02-18T13:40:04.000Z
|
/*
* Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved
*/
#ifndef _Stroika_Foundation_IO_Network_URI_inl_
#define _Stroika_Foundation_IO_Network_URI_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
namespace Stroika::Foundation::IO::Network {
/*
********************************************************************************
*************************************** URI ************************************
********************************************************************************
*/
inline URI::URI (const optional<SchemeType>& scheme, const optional<Authority>& authority, const String& path, const optional<String>& query, const optional<String>& fragment)
: fScheme_{scheme}
, fAuthority_{authority}
, fPath_{path}
, fQuery_{query}
, fFragment_{fragment}
{
// @todo probably validate query and fragment args?? Maybe not needed (if not document why)
if (scheme) {
scheme->Validate ();
}
CheckValidPathForAuthority_ (authority, path);
}
inline URI::URI (const string& encodedURI)
: URI{Parse (encodedURI)}
{
}
inline URI::URI (const String& encodedURI)
: URI{Parse (encodedURI)}
{
}
inline bool URI::IsRelativeReference () const
{
shared_lock<const AssertExternallySynchronizedLock> critSec{*this};
return fScheme_.has_value ();
}
inline optional<URI::SchemeType> URI::GetScheme () const
{
shared_lock<const AssertExternallySynchronizedLock> critSec{*this};
return fScheme_;
}
inline void URI::SetScheme (const optional<SchemeType>& scheme)
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
if (scheme) {
scheme->Validate ();
}
fScheme_ = scheme;
}
inline void URI::SetScheme (const SchemeType& scheme)
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
scheme.Validate ();
fScheme_ = scheme;
}
inline optional<URI::Authority> URI::GetAuthority () const
{
shared_lock<const AssertExternallySynchronizedLock> critSec{*this};
return fAuthority_;
}
inline void URI::SetAuthority (const optional<Authority>& authority)
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
CheckValidPathForAuthority_ (authority, fPath_);
fAuthority_ = authority;
}
inline PortType URI::GetPortValue () const
{
shared_lock<const AssertExternallySynchronizedLock> critSec{*this};
optional<PortType> op = fAuthority_ ? fAuthority_->GetPort () : optional<PortType>{};
if (op) {
return *op;
}
static constexpr PortType kDefault_{0}; // should return 80????
if (fScheme_) {
return fScheme_->GetDefaultPort ().value_or (kDefault_);
}
return kDefault_;
}
inline String URI::GetPath () const
{
shared_lock<const AssertExternallySynchronizedLock> critSec{*this};
return fPath_;
}
inline void URI::SetPath (const String& path)
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
CheckValidPathForAuthority_ (fAuthority_, path);
fPath_ = path;
}
inline URI URI::GetSchemeAndAuthority () const
{
return URI{GetScheme (), GetAuthority ()};
}
template <>
inline string URI::GetAuthorityRelativeResource () const
{
shared_lock<const AssertExternallySynchronizedLock> critSec{*this};
return GetAuthorityRelativeResource<String> ().AsASCII ();
}
template <>
inline URI URI::GetAuthorityRelativeResource () const
{
shared_lock<const AssertExternallySynchronizedLock> critSec{*this};
return URI{nullopt, nullopt, GetPath (), GetQuery<String> ()};
}
template <>
inline optional<String> URI::GetAbsPath () const
{
shared_lock<const AssertExternallySynchronizedLock> critSec{*this};
if (fPath_.empty ()) {
return L"/"sv;
}
if (fPath_.StartsWith (L"/")) {
return fPath_;
}
return nullopt;
}
template <>
inline String URI::GetAbsPath () const
{
shared_lock<const AssertExternallySynchronizedLock> critSec{*this};
if (auto op = GetAbsPath<optional<String>> ()) {
return *op;
}
Execution::Throw (Execution::RuntimeErrorException{L"This URI does not have an absolute path"sv});
}
template <>
inline auto URI::GetQuery () const -> optional<String>
{
shared_lock<const AssertExternallySynchronizedLock> critSec{*this};
return fQuery_;
}
template <>
inline auto URI::GetQuery () const -> optional<Query>
{
shared_lock<const AssertExternallySynchronizedLock> critSec{*this};
if (fQuery_) {
return Query{*fQuery_};
}
return nullopt;
}
inline void URI::SetQuery (const optional<String>& query)
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
fQuery_ = query;
}
inline void URI::SetQuery (const optional<Query>& query)
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
fQuery_ = query ? query->ComputeQueryString () : optional<String>{};
}
inline optional<String> URI::GetFragment () const
{
shared_lock<const AssertExternallySynchronizedLock> critSec{*this};
return fFragment_;
}
inline void URI::SetFragment (const optional<String>& fragment)
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
fFragment_ = fragment;
}
#if __cpp_impl_three_way_comparison >= 201907
inline strong_ordering URI::operator<=> (const URI& rhs) const
{
return URI::TWC_ (*this, rhs);
}
inline bool URI::operator== (const URI& rhs) const
{
return URI::TWC_ (*this, rhs) == 0;
}
#endif
#if __cpp_impl_three_way_comparison < 201907
/*
********************************************************************************
******************************** URI operators *********************************
********************************************************************************
*/
inline bool operator< (const URI& lhs, const URI& rhs)
{
return URI::TWC_ (lhs, rhs) < 0;
}
inline bool operator<= (const URI& lhs, const URI& rhs)
{
return URI::TWC_ (lhs, rhs) <= 0;
}
inline bool operator== (const URI& lhs, const URI& rhs)
{
return URI::TWC_ (lhs, rhs) == 0;
}
inline bool operator!= (const URI& lhs, const URI& rhs)
{
return URI::TWC_ (lhs, rhs) != 0;
}
inline bool operator>= (const URI& lhs, const URI& rhs)
{
return URI::TWC_ (lhs, rhs) >= 0;
}
inline bool operator> (const URI& lhs, const URI& rhs)
{
return URI::TWC_ (lhs, rhs) > 0;
}
#endif
}
#endif /*_Stroika_Foundation_IO_Network_URI_inl_*/
| 33.880734
| 179
| 0.563499
|
SophistSolutions
|
607aff99fffdf43a7e119defa8158acf5e5d82db
| 5,496
|
cpp
|
C++
|
Engine/Igneel.D3D10/GraphicBuffer10.cpp
|
ansel86castro/Igneel
|
7a1e6c81e18326aff78be97cc4321f3a610481ff
|
[
"Apache-2.0"
] | 8
|
2017-03-08T20:20:13.000Z
|
2021-12-12T20:20:07.000Z
|
Engine/Igneel.D3D10/GraphicBuffer10.cpp
|
ansel86castro/Igneel
|
7a1e6c81e18326aff78be97cc4321f3a610481ff
|
[
"Apache-2.0"
] | null | null | null |
Engine/Igneel.D3D10/GraphicBuffer10.cpp
|
ansel86castro/Igneel
|
7a1e6c81e18326aff78be97cc4321f3a610481ff
|
[
"Apache-2.0"
] | 4
|
2018-09-28T15:45:08.000Z
|
2021-03-22T17:15:46.000Z
|
#include "Stdafx.h"
#include "GraphicBuffer10.h"
#include "Utils.h"
using namespace System::Runtime::InteropServices;
namespace IgneelD3D10
{
GraphicBuffer10::GraphicBuffer10(ID3D10Device* device, ID3D10Buffer * buffer ,
int size,
int stride,
ResourceUsage usage,
CpuAccessFlags cpuAcces,
D3D10_SUBRESOURCE_DATA* sbData,
ResourceBinding binding)
:GraphicBuffer(size, stride, usage,cpuAcces, binding)
{
_srv = NULL;
_stagingBuffer = NULL;
this->device = device;
this->_buffer = buffer;
if(stride == 2)
this->_format = DXGI_FORMAT_R16_UINT;
else if(stride == 4)
this->_format = DXGI_FORMAT_R32_UINT;
if(FLAG_SET(binding, ResourceBinding::ShaderResource))
{
D3D10_SHADER_RESOURCE_VIEW_DESC viewDesc;
ZeroMemory(&viewDesc, sizeof(D3D10_SHADER_RESOURCE_VIEW_DESC));
viewDesc.ViewDimension = D3D10_SRV_DIMENSION_BUFFER;
viewDesc.Buffer.FirstElement = 0;
viewDesc.Buffer.ElementWidth = stride;
ID3D10ShaderResourceView * pview;
SAFECALL( device->CreateShaderResourceView(_buffer, &viewDesc , &pview) );
_srv = pview;
}
GC::AddMemoryPressure(size);
}
void GraphicBuffer10::CreateStaginResource()
{
if(Usage == ResourceUsage::Default && CpuAccess != CpuAccessFlags::None && _stagingBuffer == NULL)
{
D3D10_BUFFER_DESC stagingDesc;
_buffer->GetDesc(&stagingDesc);
stagingDesc.Usage = D3D10_USAGE_STAGING;
stagingDesc.BindFlags = 0;
stagingDesc.CPUAccessFlags = D3D10_CPU_ACCESS_READ | D3D10_CPU_ACCESS_WRITE;
ID3D10Buffer* staginbBuff;
SAFECALL( device->CreateBuffer(&stagingDesc, NULL, &staginbBuff) );
_stagingBuffer = staginbBuff;
}
}
/*GraphicBuffer10::GraphicBuffer10(ID3D10Device* device, BufferDesc desc)
{
D3D10_BUFFER_DESC bd;
ZeroMemory(&bd, sizeof(D3D10_BUFFER_DESC));
if((desc.Binding & BufferBinding::VertexBuffer) == BufferBinding::VertexBuffer)
bd.BindFlags |= D3D10_BIND_VERTEX_BUFFER;
if((desc.Binding & BufferBinding::IShaderResource) == BufferBinding::IShaderResource)
bd.BindFlags |= D3D10_BIND_SHADER_RESOURCE;
if((desc.Binding & BufferBinding::StreamOutput) == BufferBinding::StreamOutput)
bd.BindFlags |= D3D10_BIND_STREAM_OUTPUT;
bd.ByteWidth = desc.SizeInBytes;
bd.MiscFlags = 0;
bd.Usage = (D3D10_USAGE)desc.Usage;
if(bd.Usage == D3D10_USAGE_DEFAULT)
bd.CPUAccessFlags = 0;
else
bd.CPUAccessFlags = (UINT)desc.Access;
ID3D10Buffer * buffer = NULL;
D3D10_SUBRESOURCE_DATA sbData;
ZeroMemory(&sbData, sizeof(D3D10_SUBRESOURCE_DATA));
if(desc.Data != IntPtr::Zero)
{
sbData.pSysMem = static_cast<void*>(desc.Data);
sbData.SysMemPitch = 0;
sbData.SysMemSlicePitch = 0;
SAFECALL( device->CreateBuffer(&bd, &sbData, &buffer) );
}
else
{
SAFECALL(device->CreateBuffer(&bd, NULL, &buffer) );
}
_buffer = buffer;
_lenght = desc.SizeInBytes;
_usage = desc.Usage;
_cpuAccesType = desc.Access;
_stride = desc.Stride;
binding = desc.Binding;
if((desc.Binding & BufferBinding::IShaderResource) == BufferBinding::IShaderResource)
{
D3D10_SHADER_RESOURCE_VIEW_DESC viewDesc;
ZeroMemory(&viewDesc, sizeof(D3D10_SHADER_RESOURCE_VIEW_DESC));
viewDesc.ViewDimension = D3D10_SRV_DIMENSION_BUFFER;
viewDesc.Buffer.FirstElement = 0;
viewDesc.Buffer.ElementWidth = desc.Stride;
ID3D10ShaderResourceView * pview;
SAFECALL( device->CreateShaderResourceView(_buffer, &viewDesc , &pview) );
_srv = pview;
}
if(desc.Usage == ResourceUsage::Default && desc.Access != CpuAccessFlags::None)
{
D3D10_BUFFER_DESC stagingDesc;
buffer->GetDesc(&stagingDesc);
stagingDesc.Usage = D3D10_USAGE_STAGING;
stagingDesc.BindFlags = 0;
stagingDesc.CPUAccessFlags = D3D10_CPU_ACCESS_READ | D3D10_CPU_ACCESS_WRITE;
ID3D10Buffer* staginbBuff;
if (sbData.pSysMem)
{
SAFECALL( device->CreateBuffer(&stagingDesc, &sbData, &staginbBuff) );
}
else
{
SAFECALL( device->CreateBuffer(&stagingDesc, NULL, &staginbBuff) );
}
_stagingBuffer = staginbBuff;
}
GC::AddMemoryPressure(desc.SizeInBytes);
}*/
IntPtr GraphicBuffer10::Map(MapType map, bool doNotWait)
{
void *pData = NULL;
CreateStaginResource();
if(_stagingBuffer)
{
if((map & MapType::Read) == MapType::Read || (map & MapType::Write) == MapType::Write)
{
device->CopyResource(_stagingBuffer, _buffer);
}
else if(map == MapType::Write_Discard)
{
map = MapType::Write;
}
SAFECALL( _stagingBuffer->Map(static_cast<D3D10_MAP>( map ), doNotWait ? D3D10_MAP_FLAG_DO_NOT_WAIT : 0, &pData));
}
else
{
SAFECALL( _buffer->Map(static_cast<D3D10_MAP>( map ), doNotWait ? D3D10_MAP_FLAG_DO_NOT_WAIT : 0, &pData) );
}
return IntPtr(pData);
}
void GraphicBuffer10::Unmap()
{
if(_stagingBuffer)
{
_stagingBuffer->Unmap();
//void *pData;
//_stagingBuffer->Map(D3D10_MAP::D3D10_MAP_READ, D3D10_MAP_FLAG_DO_NOT_WAIT , &pData);
//device->UpdateSubresource(_buffer, 0, NULL, pData, 0, 0);
device->CopyResource(_buffer,_stagingBuffer);
_stagingBuffer->Release();
_stagingBuffer = NULL;
}
else
{
_buffer->Unmap();
}
}
void GraphicBuffer10::OnDispose(bool disposing)
{
__super::OnDispose(disposing);
if(_buffer)
{
if(_srv)
{
_srv->Release();
_srv = NULL;
}
_buffer->Release();
_buffer = NULL;
if(_stagingBuffer)
{
_stagingBuffer->Release();
_stagingBuffer = NULL;
}
}
}
}
| 26.423077
| 117
| 0.701783
|
ansel86castro
|
607eeae14fee09922cf8d7978fc8cd95420712a8
| 7,204
|
hpp
|
C++
|
include/range/v3/view/intersperse.hpp
|
CornedBee/range-v3
|
99a9f5f70e65dfcf6bbc8894bf2a22d8f5d4552a
|
[
"MIT"
] | null | null | null |
include/range/v3/view/intersperse.hpp
|
CornedBee/range-v3
|
99a9f5f70e65dfcf6bbc8894bf2a22d8f5d4552a
|
[
"MIT"
] | null | null | null |
include/range/v3/view/intersperse.hpp
|
CornedBee/range-v3
|
99a9f5f70e65dfcf6bbc8894bf2a22d8f5d4552a
|
[
"MIT"
] | null | null | null |
/// \file
// Range v3 library
//
// Copyright Eric Niebler 2013-2014
//
// Use, modification and distribution is subject to the
// Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// Project home: https://github.com/ericniebler/range-v3
//
#ifndef RANGES_V3_VIEW_INTERSPERSE_HPP
#define RANGES_V3_VIEW_INTERSPERSE_HPP
#include <utility>
#include <type_traits>
#include <range/v3/range_fwd.hpp>
#include <range/v3/empty.hpp>
#include <range/v3/begin_end.hpp>
#include <range/v3/range.hpp>
#include <range/v3/size.hpp>
#include <range/v3/range_traits.hpp>
#include <range/v3/range_concepts.hpp>
#include <range/v3/range_adaptor.hpp>
#include <range/v3/utility/iterator.hpp>
#include <range/v3/utility/invokable.hpp>
#include <range/v3/view/view.hpp>
namespace ranges
{
inline namespace v3
{
/// \addtogroup group-views
/// @{
template<typename Rng>
struct intersperse_view
: range_adaptor<intersperse_view<Rng>, Rng>
{
private:
friend range_access;
struct sentinel_adaptor;
range_value_t<Rng> val_;
struct cursor_adaptor : adaptor_base
{
private:
friend sentinel_adaptor;
bool toggl_;
range_value_t<Rng> val_;
public:
cursor_adaptor() = default;
cursor_adaptor(range_value_t<Rng> val, bool at_end)
: toggl_(!at_end), val_(std::move(val))
{}
range_value_t<Rng> current(range_iterator_t<Rng> it) const
{
return toggl_ ? *it : val_;
}
bool equal(range_iterator_t<Rng> it0, range_iterator_t<Rng> it1,
cursor_adaptor const & other) const
{
return it0 == it1 && toggl_ == other.toggl_;
}
void next(range_iterator_t<Rng> & it)
{
if(toggl_)
++it;
toggl_ = !toggl_;
}
CONCEPT_REQUIRES(BidirectionalIterable<Rng>())
void prev(range_iterator_t<Rng> & it)
{
toggl_ = !toggl_;
if(toggl_)
--it;
}
CONCEPT_REQUIRES(RandomAccessIterable<Rng>())
range_difference_t<Rng> distance_to(range_iterator_t<Rng> it, range_iterator_t<Rng> other_it,
cursor_adaptor const &other) const
{
auto d = other_it - it;
if(d > 0)
return d * 2 - (toggl_ != other.toggl_);
if(d < 0)
return d * 2 + (toggl_ != other.toggl_);
return other.toggl_ - toggl_;
}
CONCEPT_REQUIRES(RandomAccessIterable<Rng>())
void advance(range_iterator_t<Rng> &it, range_difference_t<Rng> n)
{
ranges::advance(it, n >= 0 ? (n + toggl_) / 2 : (n - !toggl_) / 2);
if(n % 2 != 0)
toggl_ = !toggl_;
}
};
struct sentinel_adaptor : adaptor_base
{
bool empty(range_iterator_t<Rng> it, cursor_adaptor const &other,
range_sentinel_t<Rng> sent)
{
return it == sent;
}
};
cursor_adaptor begin_adaptor() const
{
return {val_, ranges::empty(this->mutable_base())};
}
CONCEPT_REQUIRES(BoundedIterable<Rng>() && !SinglePass<range_iterator_t<Rng>>())
cursor_adaptor end_adaptor() const
{
return {val_, true};
}
CONCEPT_REQUIRES(!BoundedIterable<Rng>() || SinglePass<range_iterator_t<Rng>>())
sentinel_adaptor end_adaptor() const
{
return {};
}
public:
intersperse_view() = default;
intersperse_view(Rng && rng, range_value_t<Rng> val)
: range_adaptor_t<intersperse_view>{std::forward<Rng>(rng)}, val_(std::move(val))
{}
CONCEPT_REQUIRES(SizedIterable<Rng>())
range_size_t<Rng> size() const
{
auto tmp = ranges::size(this->mutable_base());
return tmp ? tmp * 2 - 1 : 0;
}
};
namespace view
{
struct intersperse_fn
{
private:
friend view_access;
template<typename T, CONCEPT_REQUIRES_(SemiRegular<T>())>
static auto bind(intersperse_fn intersperse, T t)
RANGES_DECLTYPE_AUTO_RETURN
(
make_pipeable(std::bind(intersperse, std::placeholders::_1, std::move(t)))
)
public:
template<typename Rng, typename T = range_value_t<Rng>>
using Concept = meta::and_<
InputIterable<Rng>,
Convertible<T, range_value_t<Rng>>,
Convertible<range_reference_t<Rng>, range_value_t<Rng>>,
SemiRegular<range_value_t<Rng>>>;
template<typename Rng,
CONCEPT_REQUIRES_(Concept<Rng>())>
intersperse_view<Rng> operator()(Rng && rng, range_value_t<Rng> val) const
{
return {std::forward<Rng>(rng), {std::move(val)}};
}
#ifndef RANGES_DOXYGEN_INVOKED
template<typename Rng, typename T,
CONCEPT_REQUIRES_(!Concept<Rng, T>())>
void operator()(Rng &&, T &&) const
{
CONCEPT_ASSERT_MSG(InputIterable<Rng>(),
"The object on which view::intersperse operates must be a model of the "
"InputIterable concept.");
CONCEPT_ASSERT_MSG(Convertible<T, range_value_t<Rng>>(),
"The value to intersperse in the range must be convertible to the range's "
"value type.");
CONCEPT_ASSERT_MSG(Convertible<range_reference_t<Rng>, range_value_t<Rng>>(),
"The range's reference type must be convertible to the range's "
"value type.");
CONCEPT_ASSERT_MSG(SemiRegular<range_value_t<Rng>>(),
"The range on which view::intersperse operates must have a value type that "
"models the SemiRegular concept; that is, it must be default constructible, "
"copy and move constructible, and destructible.");
}
#endif
};
/// \relates intersperse_fn
/// \ingroup group-views
constexpr view<intersperse_fn> intersperse{};
}
}
}
#endif
| 37.915789
| 109
| 0.506802
|
CornedBee
|
607f071c94b4b4563fe8455c2b720b0e522fc755
| 870
|
cpp
|
C++
|
06_Cpp_Style/extern_leakage/main.cpp
|
haxpor/APIBook
|
df34e557ebdd3e0c30fc55fb87dd43c72d393d4c
|
[
"MIT"
] | 15
|
2020-01-14T21:00:20.000Z
|
2022-03-20T08:30:23.000Z
|
06_Cpp_Style/extern_leakage/main.cpp
|
haxpor/APIBook
|
df34e557ebdd3e0c30fc55fb87dd43c72d393d4c
|
[
"MIT"
] | 1
|
2019-03-13T01:36:12.000Z
|
2019-03-13T01:36:12.000Z
|
06_Cpp_Style/extern_leakage/main.cpp
|
haxpor/APIBook
|
df34e557ebdd3e0c30fc55fb87dd43c72d393d4c
|
[
"MIT"
] | 10
|
2019-10-21T03:15:24.000Z
|
2021-09-08T01:58:35.000Z
|
/// -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: t -*-
///
/// \file main.cpp
/// \author Martin Reddy
/// \brief Showing how "internal" details can be leaked.
///
/// Copyright (c) 2010, Martin Reddy. All rights reserved.
/// Distributed under the X11/MIT License. See LICENSE.txt.
/// See http://APIBook.com/ for the latest version.
///
#include "myobject.h"
#include <string>
#include <iostream>
// declare the external linkage elements of myobject.cpp
extern void FreeFunction();
extern int INTERNAL_CONSTANT;
extern std::string Filename;
int main(int, char **)
{
// call a function hidden within the myobject.cpp module
FreeFunction();
// access a constant defined within myobject.cpp
std::cout << "Internal constant = " << INTERNAL_CONSTANT << std::endl;
// change global state within myobject.cpp
Filename = "different.txt";
return 0;
}
| 25.588235
| 71
| 0.698851
|
haxpor
|
607f142385fd82cf90be57a79d30b84243650780
| 252
|
cpp
|
C++
|
src/animation/blend_animation_1d.cpp
|
hermet/rive-cpp
|
d69378d97e7d987930c3764655153bf8ddc65966
|
[
"MIT"
] | null | null | null |
src/animation/blend_animation_1d.cpp
|
hermet/rive-cpp
|
d69378d97e7d987930c3764655153bf8ddc65966
|
[
"MIT"
] | null | null | null |
src/animation/blend_animation_1d.cpp
|
hermet/rive-cpp
|
d69378d97e7d987930c3764655153bf8ddc65966
|
[
"MIT"
] | null | null | null |
#include "animation/blend_animation_1d.hpp"
using namespace rive;
StatusCode BlendAnimation1D::onAddedDirty(CoreContext* context)
{
return StatusCode::Ok;
}
StatusCode BlendAnimation1D::onAddedClean(CoreContext* context)
{
return StatusCode::Ok;
}
| 19.384615
| 63
| 0.805556
|
hermet
|
6080622bfa6412d9d19bf5bb449169fc003eb06f
| 9,366
|
cpp
|
C++
|
examples/state/vsgdynamictexture/vsgdynamictexture.cpp
|
andesengineering/vsgExamples
|
ac7f2e021eaa8ffab6bd16253b5c89015c7bf13f
|
[
"MIT"
] | null | null | null |
examples/state/vsgdynamictexture/vsgdynamictexture.cpp
|
andesengineering/vsgExamples
|
ac7f2e021eaa8ffab6bd16253b5c89015c7bf13f
|
[
"MIT"
] | null | null | null |
examples/state/vsgdynamictexture/vsgdynamictexture.cpp
|
andesengineering/vsgExamples
|
ac7f2e021eaa8ffab6bd16253b5c89015c7bf13f
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <vsg/all.h>
void update(vsg::vec4Array2D& image, float value)
{
for (size_t r = 0; r < image.height(); ++r)
{
float r_ratio = static_cast<float>(r) / static_cast<float>(image.height() - 1);
for (size_t c = 0; c < image.width(); ++c)
{
float c_ratio = static_cast<float>(c) / static_cast<float>(image.width() - 1);
vsg::vec2 delta((r_ratio - 0.5f), (c_ratio - 0.5f));
float angle = atan2(delta.x, delta.y);
float distance_from_center = vsg::length(delta);
float intensity = (sin(1.0f * angle + 30.0f * distance_from_center + 10.0f * value) + 1.0f) * 0.5f;
image.set(uint32_t(c), uint32_t(r), vsg::vec4(intensity * intensity, intensity, intensity, 1.0f));
}
}
}
int main(int argc, char** argv)
{
// set up defaults and read command line arguments to override them
vsg::CommandLine arguments(&argc, argv);
auto windowTraits = vsg::WindowTraits::create();
windowTraits->debugLayer = arguments.read({"--debug", "-d"});
windowTraits->apiDumpLayer = arguments.read({"--api", "-a"});
arguments.read({"--window", "-w"}, windowTraits->width, windowTraits->height);
if (arguments.errors()) return arguments.writeErrorMessages(std::cerr);
// set up search paths to SPIRV shaders and textures
vsg::Paths searchPaths = vsg::getEnvPaths("VSG_FILE_PATH");
// load shaders
vsg::ref_ptr<vsg::ShaderStage> vertexShader = vsg::ShaderStage::read(VK_SHADER_STAGE_VERTEX_BIT, "main", vsg::findFile("shaders/vert_PushConstants.spv", searchPaths));
vsg::ref_ptr<vsg::ShaderStage> fragmentShader = vsg::ShaderStage::read(VK_SHADER_STAGE_FRAGMENT_BIT, "main", vsg::findFile("shaders/frag_PushConstants.spv", searchPaths));
if (!vertexShader || !fragmentShader)
{
std::cout << "Could not create shaders." << std::endl;
return 1;
}
// read texture image
auto textureData = vsg::vec4Array2D::create(256, 256);
textureData->getLayout().format = VK_FORMAT_R32G32B32A32_SFLOAT;
update(*textureData, 1.0f);
vsg::write(textureData, "test.vsgt");
// set up graphics pipeline
vsg::DescriptorSetLayoutBindings descriptorBindings{
{0, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT, nullptr} // { binding, descriptorTpe, descriptorCount, stageFlags, pImmutableSamplers}
};
auto descriptorSetLayout = vsg::DescriptorSetLayout::create(descriptorBindings);
vsg::PushConstantRanges pushConstantRanges{
{VK_SHADER_STAGE_VERTEX_BIT, 0, 128} // projection view, and model matrices, actual push constant calls autoaatically provided by the VSG's DispatchTraversal
};
vsg::VertexInputState::Bindings vertexBindingsDescriptions{
VkVertexInputBindingDescription{0, sizeof(vsg::vec3), VK_VERTEX_INPUT_RATE_VERTEX}, // vertex data
VkVertexInputBindingDescription{1, sizeof(vsg::vec3), VK_VERTEX_INPUT_RATE_VERTEX}, // colour data
VkVertexInputBindingDescription{2, sizeof(vsg::vec2), VK_VERTEX_INPUT_RATE_VERTEX} // tex coord data
};
vsg::VertexInputState::Attributes vertexAttributeDescriptions{
VkVertexInputAttributeDescription{0, 0, VK_FORMAT_R32G32B32_SFLOAT, 0}, // vertex data
VkVertexInputAttributeDescription{1, 1, VK_FORMAT_R32G32B32_SFLOAT, 0}, // colour data
VkVertexInputAttributeDescription{2, 2, VK_FORMAT_R32G32_SFLOAT, 0}, // tex coord data
};
vsg::GraphicsPipelineStates pipelineStates{
vsg::VertexInputState::create(vertexBindingsDescriptions, vertexAttributeDescriptions),
vsg::InputAssemblyState::create(),
vsg::RasterizationState::create(),
vsg::MultisampleState::create(),
vsg::ColorBlendState::create(),
vsg::DepthStencilState::create()};
auto pipelineLayout = vsg::PipelineLayout::create(vsg::DescriptorSetLayouts{descriptorSetLayout}, pushConstantRanges);
auto graphicsPipeline = vsg::GraphicsPipeline::create(pipelineLayout, vsg::ShaderStages{vertexShader, fragmentShader}, pipelineStates);
auto bindGraphicsPipeline = vsg::BindGraphicsPipeline::create(graphicsPipeline);
// create texture image and associated DescriptorSets and binding
auto texture = vsg::DescriptorImage::create(vsg::Sampler::create(), textureData, 0, 0, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
auto descriptorSet = vsg::DescriptorSet::create(descriptorSetLayout, vsg::Descriptors{texture});
auto bindDescriptorSet = vsg::BindDescriptorSet::create(VK_PIPELINE_BIND_POINT_GRAPHICS, graphicsPipeline->layout, 0, descriptorSet);
// create StateGroup as the root of the scene/command graph to hold the GraphicsProgram, and binding of Descriptors to decorate the whole graph
auto scenegraph = vsg::StateGroup::create();
scenegraph->add(bindGraphicsPipeline);
scenegraph->add(bindDescriptorSet);
// set up model transformation node
auto transform = vsg::MatrixTransform::create(); // VK_SHADER_STAGE_VERTEX_BIT
// add transform to root of the scene graph
scenegraph->addChild(transform);
// set up vertex and index arrays
auto vertices = vsg::vec3Array::create(
{{-0.5f, -0.5f, 0.0f},
{0.5f, -0.5f, 0.0f},
{0.5f, 0.5f, 0.0f},
{-0.5f, 0.5f, 0.0f},
{-0.5f, -0.5f, -0.5f},
{0.5f, -0.5f, -0.5f},
{0.5f, 0.5f, -0.5f},
{-0.5f, 0.5f, -0.5f}}); // VK_FORMAT_R32G32B32_SFLOAT, VK_VERTEX_INPUT_RATE_INSTANCE, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, VK_SHARING_MODE_EXCLUSIVE
auto colors = vsg::vec3Array::create(uint32_t(vertices->size()), vsg::vec3(1.0f, 1.0f, 1.0f));
auto texcoords = vsg::vec2Array::create(
{{0.0f, 0.0f},
{1.0f, 0.0f},
{1.0f, 1.0f},
{0.0f, 1.0f},
{0.0f, 0.0f},
{1.0f, 0.0f},
{1.0f, 1.0f},
{0.0f, 1.0f}}); // VK_FORMAT_R32G32_SFLOAT, VK_VERTEX_INPUT_RATE_VERTEX, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, VK_SHARING_MODE_EXCLUSIVE
auto indices = vsg::ushortArray::create(
{0, 1, 2,
2, 3, 0,
4, 5, 6,
6, 7, 4}); // VK_BUFFER_USAGE_INDEX_BUFFER_BIT, VK_SHARING_MODE_EXCLUSIVE
// setup geometry
auto drawCommands = vsg::Commands::create();
drawCommands->addChild(vsg::BindVertexBuffers::create(0, vsg::DataList{vertices, colors, texcoords}));
drawCommands->addChild(vsg::BindIndexBuffer::create(indices));
drawCommands->addChild(vsg::DrawIndexed::create(12, 1, 0, 0, 0));
// add drawCommands to transform
transform->addChild(drawCommands);
// create the viewer and assign window(s) to it
auto viewer = vsg::Viewer::create();
auto window = vsg::Window::create(windowTraits);
if (!window)
{
std::cout << "Could not create windows." << std::endl;
return 1;
}
viewer->addWindow(window);
// camera related details
auto viewport = vsg::ViewportState::create(window->extent2D());
auto perspective = vsg::Perspective::create(60.0, static_cast<double>(window->extent2D().width) / static_cast<double>(window->extent2D().height), 0.1, 10.0);
auto lookAt = vsg::LookAt::create(vsg::dvec3(1.0, 1.0, 1.0), vsg::dvec3(0.0, 0.0, 0.0), vsg::dvec3(0.0, 0.0, 1.0));
auto camera = vsg::Camera::create(perspective, lookAt, viewport);
auto commandGraph = vsg::createCommandGraphForView(window, camera, scenegraph);
auto copyCmd = vsg::CopyAndReleaseImage::create();
commandGraph->getChildren().insert(commandGraph->getChildren().begin(), copyCmd);
viewer->assignRecordAndSubmitTaskAndPresentation({commandGraph});
// add event handlers
viewer->addEventHandler(vsg::Trackball::create(camera));
viewer->addEventHandlers({vsg::CloseHandler::create(viewer)});
// compile the Vulkan objects
viewer->compile();
// texture has been filled in so it's now safe to get the ImageInfo that holds the handles to the texture's
vsg::ImageInfo textureImageInfo;
if (!texture->imageInfoList.empty()) textureImageInfo = texture->imageInfoList[0]; // contextID=0, and only one imageData
// create a context to manage the DeviceMemoryPool for us when we need to copy data to a staging buffer
vsg::Context context(window->getOrCreateDevice());
// main frame loop
while (viewer->advanceToNextFrame())
{
// pass any events into EventHandlers assigned to the Viewer
viewer->handleEvents();
// animate the transform
float time = std::chrono::duration<float, std::chrono::seconds::period>(viewer->getFrameStamp()->time - viewer->start_point()).count();
transform->setMatrix(vsg::rotate(time * vsg::radians(90.0f), vsg::vec3(0.0f, 0.0, 1.0f)));
// update texture data
update(*textureData, time);
// transfer data to staging buffer
auto stagingBufferData = vsg::copyDataToStagingBuffer(context, textureData);
// schedule a copy command to do the staging buffer to the texture image, this copy command is recorded to the appropriate command buffer by viewer->recordAndSubmit().
copyCmd->add(stagingBufferData, textureImageInfo);
viewer->update();
viewer->recordAndSubmit();
viewer->present();
}
// clean up done automatically thanks to ref_ptr<>
return 0;
}
| 43.562791
| 175
| 0.682148
|
andesengineering
|
608103e91563b132c650163fb8b7aaff1ede0d1b
| 1,315
|
cpp
|
C++
|
c++/set_mismatch.cpp
|
SongZhao/leetcode
|
4a2b4f554e91f6a2167b336f8a69b80fa9f3f920
|
[
"Apache-2.0"
] | null | null | null |
c++/set_mismatch.cpp
|
SongZhao/leetcode
|
4a2b4f554e91f6a2167b336f8a69b80fa9f3f920
|
[
"Apache-2.0"
] | null | null | null |
c++/set_mismatch.cpp
|
SongZhao/leetcode
|
4a2b4f554e91f6a2167b336f8a69b80fa9f3f920
|
[
"Apache-2.0"
] | null | null | null |
/*
The set S originally contains numbers from 1 to n. But unfortunately, due to the data error, one of the numbers in the set got duplicated to another number in the set, which results in repetition of one number and loss of another number.
Given an array nums representing the data status of this set after the error. Your task is to firstly find the number occurs twice and then find the number that is missing. Return them in the form of an array.
Example 1:
Input: nums = [1,2,2,4]
Output: [2,3]
Note:
The given array size will in the range [2, 10000].
The given array's numbers won't have any order.
*/
/*
* Similar to Find All Numbers Disappeared in an Array
*/
#include "helper.h"
class Solution {
public:
vector<int> findErrorNums(vector<int> &nums) {
vector<int> res;
for (int num:nums) {
num = abs(num);
if (nums[num - 1] < 0) {
res.push_back(num);
} else {
nums[num - 1] = -nums[num - 1];
}
}
for (int i = 0; i < nums.size(); i++) {
if (nums[i] > 0) {
res.push_back(i + 1);
}
}
return res;
}
};
int main() {
Solution s;
vector<int> nums({1, 2, 2, 4});
cout << s.findErrorNums(nums) << endl;
return 0;
}
| 26.836735
| 237
| 0.584791
|
SongZhao
|
60851ef5cb6b0f0afb15e729b1867ab72786f4d4
| 18,680
|
cpp
|
C++
|
profiler.cpp
|
Svengali/cblib
|
77ddfd452cff842575750b9e6d792790f5ec5fee
|
[
"Zlib"
] | 1
|
2021-05-01T04:34:24.000Z
|
2021-05-01T04:34:24.000Z
|
profiler.cpp
|
Svengali/cblib
|
77ddfd452cff842575750b9e6d792790f5ec5fee
|
[
"Zlib"
] | null | null | null |
profiler.cpp
|
Svengali/cblib
|
77ddfd452cff842575750b9e6d792790f5ec5fee
|
[
"Zlib"
] | null | null | null |
#include "Base.h"
#include "Profiler.h"
#include "Vector.h"
#include "Vecsortedpair.h"
#include "Vector_s.h"
#include "Log.h"
#include "File.h"
#define PROFILE_RECORDS
//#define PROFILE_NODES
/**
PROFILE_NODES : track heirarchical time information in realtime
useful for in-game profile HUD
PROFILE_RECORDS : just store a big vector of Push/Pops with times
doesn't provide any realtime feedback
write it out and then run AllocParser to get nice views
either one or both can be enabled
total times for each index are always tracked
**/
/*****************
In-game real-time profiler
Reasonably light-weight when in Disabled
mode.
Clients should primarily use the PROFILE macro, like :
void func()
{
PROFILE(func);
... do stuff ...
}
NOTEZ :
we match strings by pointer !! requires merging of constant strings !!
--------------------------------------------------
This is a hierarchical AND a non-hierarchical , and you want to be able to switch
between them, like how much time does "Vec3::Add" take in *all* calls to
it, not just the call from the current parent
---------------------------------------------------
Descriptions of counters (all counters represent data since last reset)
percent:
The total percentage of total time that this entry was active for.
This figure includes any nested entries also.
millis:
Average millis per frame (since last reset) that this entry and all
nested entries took.
kclcks:
The average amount of 'ticks' that each invocation of this entry took.
counts:
The average amount of times that this entry was invoked per frame.
---------------------------------------------------
The goal will be to later add :
1. Hookup to the XBox system monitor for nice graphs
2. Provide the full stack information to the PC for an interactive
tree-view descent; so you can get nice views like :
GameLoop 100%
GoMgr::Tick 80%
Player::Tick 20%
LookAround 5% (8%)
Musklum::Tick 10%
LookAround 3% (8%)
CameraMgr::Tick 10%
*******************/
#define NUM_ENTRIES_TO_SHOW (20)
START_CB
namespace Profiler
{
bool g_enabled = false;
}
namespace
{
static int s_numNodes = 0;
/*
ProfilerEntry is for counting the total time by Index of
a given PROFILE name
*/
struct ProfilerEntry
{
const char * m_name;
uint64 m_time;
int m_count;
String m_string; // only used by ReadRecords
ProfilerEntry(const char * name) : m_name(name), m_time(0), m_count(0) { }
ProfilerEntry() : m_name(NULL), m_time(0), m_count(0) { }
void Reset()
{
m_time = 0;
m_count = 0;
}
void Increment(const uint64 time)
{
m_time += time;
m_count ++;
}
};
typedef std::pair< const char * , int > charptr_int_pair;
//typedef vecsortedpair< vector< charptr_int_pair >, str_util::str_compare > charptr_int_map;
typedef vecsortedpair< vector< charptr_int_pair > > charptr_int_map;
// compare_ProfilerEntry_by_ticks puts larger ticks first
struct compare_ProfilerEntry_by_seconds :
public cb::binary_function<ProfilerEntry, ProfilerEntry, bool>
{
bool operator()(const ProfilerEntry & e1, const ProfilerEntry & e2) const
{
return e1.m_time > e2.m_time;
}
};
/*
ProfileNode is for counting the CHILD time by Index of
a given PROFILE name
*/
struct ProfileNode
{
const char * m_name;
int m_index;
uint64 m_time;
int m_count;
int m_recursion;
ProfileNode * m_parent;
ProfileNode * m_child;
ProfileNode * m_sibling;
ProfileNode(const char * name,const int index, ProfileNode * parent) :
m_index(index), m_name(name), m_parent(parent), m_time(0), m_count(0), m_recursion(0),
m_sibling(NULL), m_child(NULL)
{
s_numNodes++;
}
// never goes away
//~ProfileNode()
void Reset()
{
m_time = 0;
m_count = 0;
m_recursion = 0;
if ( m_sibling )
{
m_sibling->Reset();
}
if ( m_child )
{
m_child->Reset();
}
}
void Enter()
{
ASSERT( m_recursion >= 0 );
m_count ++;
m_recursion++;
}
bool Leave(const uint64 time)
{
m_recursion--;
ASSERT( m_recursion >= 0 );
if ( m_recursion > 0 )
return false;
m_time += time;
return true;
}
ProfileNode * GetChild( const char * const name, const int index )
{
// Try to find this sub node
ProfileNode * child = m_child;
while ( child )
{
if ( child->m_name == name )
{
return child;
}
child = child->m_sibling;
}
// We didn't find it, so add it
ProfileNode * node = new ProfileNode( name,index, this );
node->m_sibling = m_child;
m_child = node;
return node;
}
};
// compare_ProfileNode_by_seconds puts larger seconds first
struct compare_ProfileNode_by_seconds :
public cb::binary_function<ProfileNode, ProfileNode, bool>
{
bool operator()(const ProfileNode & e1, const ProfileNode & e2) const
{
return e1.m_time > e2.m_time;
}
};
struct ProfilerData
{
public:
static ProfilerData & Instance()
{
static ProfilerData inst;
return inst;
}
ProfilerData() : m_root("root",-1,NULL)
{
m_requestEnabled = false;
m_secondsSinceStart = Profiler::GetSeconds();
m_inspectNode = &m_root;
m_showNodes = true;
#ifdef PROFILE_RECORDS
m_records.reserve(1024);
#endif
m_entries.reserve(32);
m_entries.resize(1); // slot 0 is unused
Reset();
}
void Reset()
{
m_root.Reset();
m_curNode = &m_root;
#ifdef DEBUG_MEMORY
MemorySystem::GetStatistics(&m_lastResetMemoryStats);
#endif
m_lastSeconds = Profiler::GetSeconds();
m_secondsSinceReset = 0.0;
m_framesSinceReset = 0;
//m_stack.clear();
const int n = m_entries.size32();
for(int i=0;i<n;i++)
{
m_entries[i].Reset();
}
}
//-------------------------------------
double m_lastSeconds;
double m_secondsSinceReset;
double m_secondsSinceStart;
int m_framesSinceReset;
bool m_showNodes;
bool m_requestEnabled;
ProfileNode * m_inspectNode;
ProfileNode * m_curNode;
ProfileNode m_root;
charptr_int_map m_nameMap;
vector< ProfilerEntry > m_entries;
//vector_s< int , 256 > m_stack;
vector< Profiler::ProfileRecord > m_records;
#ifdef DEBUG_MEMORY
MemorySystem::Statistics m_lastResetMemoryStats;
#endif
};
} // file-only namespace
//! default is "Disabled"
void Profiler::SetEnabled(const bool yesNo)
{
ProfilerData::Instance().m_requestEnabled = yesNo;
// don't do it until next frame
}
bool Profiler::GetEnabled()
{
return g_enabled;
}
int Profiler::Index(const char * const name)
{
// have to do this even when we're disabled, or we'll screw up the indexing for the future;
// this should only be done in local statics, though, so it doesn't affect our cost
charptr_int_map & map = ProfilerData::Instance().m_nameMap;
const charptr_int_map::const_iterator it = map.find(name);
if ( it != map.end() )
{
return (*it).second;
}
else
{
const int index = ProfilerData::Instance().m_entries.size32();
ASSERT( index > 0 );
ProfilerData::Instance().m_entries.push_back( ProfilerEntry(name) );
map.insert( charptr_int_pair(name,index) );
ASSERT( map.find(name) != map.end() );
return index;
}
}
//! Push & Pop timer blocks
void Profiler::Push(const int index,const char * const name,uint64 time)
{
ASSERT( g_enabled );
ProfilerData & data = ProfilerData::Instance();
ASSERT( index > 0 );
#ifdef PROFILE_RECORDS
data.m_records.push_back( ProfileRecord(index,time) );
#endif
#ifdef PROFILE_NODES
// match strings by pointer !! requires merging of constant strings !!
if ( name != data.m_curNode->m_name )
{
data.m_curNode = data.m_curNode->GetChild(name,index);
}
data.m_curNode->Enter();
#endif
// m_stack is a vector_s , so no allocation is possible
//ProfilerData::Instance().m_stack.push_back(index);
}
void Profiler::Pop(int index, const uint64 delta)
{
//ASSERT( g_enabled );
ASSERT( index > 0 );
ProfilerData & data = ProfilerData::Instance();
#ifdef PROFILE_RECORDS
data.m_records.push_back( ProfileRecord(- index,delta) );
#endif
#ifdef PROFILE_NODES
if ( data.m_curNode && data.m_curNode->m_index == index )
{
if ( data.m_curNode->Leave(delta) )
{
data.m_curNode = data.m_curNode->m_parent;
ASSERT( data.m_curNode != NULL );
}
}
#endif
data.m_entries[index].Increment(delta);
/*
// this can happen due to enable toggles while the stack is active
if ( ! data.m_stack.empty() )
{
int top = data.m_stack.back();
data.m_stack.pop_back();
data.m_entries[top].Increment(delta);
}
*/
}
void Profiler::Reset()
{
ProfilerData & data = ProfilerData::Instance();
data.Reset();
}
void Profiler::Frame()
{
ProfilerData & data = ProfilerData::Instance();
if ( g_enabled )
{
data.m_framesSinceReset ++;
double curSeconds = Profiler::GetSeconds();
data.m_secondsSinceReset += curSeconds - data.m_lastSeconds;
data.m_lastSeconds = curSeconds;
}
if ( data.m_requestEnabled != g_enabled )
{
g_enabled = data.m_requestEnabled;
if ( g_enabled )
{
Reset();
}
}
}
void Profiler::ViewAscend()
{
#ifdef PROFILE_NODES
ProfilerData & data = ProfilerData::Instance();
if ( data.m_showNodes )
{
if ( data.m_inspectNode->m_parent )
{
data.m_inspectNode = data.m_inspectNode->m_parent;
}
}
#endif
}
void Profiler::ViewDescend(int which)
{
#ifdef PROFILE_NODES
ProfilerData & data = ProfilerData::Instance();
if ( data.m_showNodes )
{
ProfileNode * child = data.m_inspectNode->m_child;
ASSERT( which >= 0 );
if ( which < 0 )
return;
for(;;)
{
if ( child == NULL )
return;
if ( which == 0 )
{
data.m_inspectNode = child;
return;
}
child = child->m_sibling;
which--;
}
}
#endif
}
/** Recursively add the given node, and all siblings and children, to
the given vector. */
static void AddNodes(vecsorted< vector_s< ProfileNode, NUM_ENTRIES_TO_SHOW >, compare_ProfileNode_by_seconds >* result, const ProfileNode* node)
{
if (node == NULL)
{
return;
}
if (result->size() < NUM_ENTRIES_TO_SHOW)
{
result->insert(*node);
}
else if (result->back().m_time < node->m_time)
{
result->pop_back();
result->insert(*node);
}
// Add siblings
AddNodes(result, node->m_sibling);
// Add children.
AddNodes(result, node->m_child);
}
namespace Profiler
{
void ReportNodes(const ProfileNode * pNode,bool recurse);
void ReportEntries(bool dumpAll);
};
void Profiler::SetReportNodes(bool enable)
{
ProfilerData::Instance().m_showNodes =enable;
}
bool Profiler::GetReportNodes()
{
return ProfilerData::Instance().m_showNodes;
}
//! Spew it out to a report
void Profiler::Report(bool dumpAll /* = false */)
{
/*
if ( ! g_enabled )
{
lprintf("Report on disabled profiler!!\n");
return;
}
*/
ProfilerData & data = ProfilerData::Instance();
const int frames = data.m_framesSinceReset;
if ( frames == 0 )
{
lprintf("Report on zero frames!! (call Profiler::Frame)\n");
return;
}
const double secondsSinceReset = data.m_secondsSinceReset;
lprintf("----------------------------------------------- Profiler Report Begin\n");
lprintf("------ elapsed : %1.3f frames : %d fps = %1.3f , millis = %1.3f\n",
data.m_secondsSinceReset,data.m_framesSinceReset,
double(frames)/secondsSinceReset, secondsSinceReset*1000.0/double(frames) );
#ifdef PROFILE_NODES
if ( data.m_showNodes )
{
if ( dumpAll )
{
ReportNodes(&data.m_root,true);
}
else
{
ReportNodes(data.m_inspectNode,false);
}
}
else
#endif
{
ReportEntries(dumpAll);
}
//MemorySystem::LogAllAllocations("Profiler Report",data.m_secondsLastReset);
#ifdef DEBUG_MEMORY
MemorySystem::Statistics stats;
MemorySystem::GetStatistics(&stats);
MemorySystem::Statistics diff;
diff.SetDifference(stats,data.m_lastResetMemoryStats);
lprintf("Memory : allocs = %d, frees = %d\n",diff.numAllocs,diff.numFrees);
lprintf("per frame : allocs = %1.3f, frees = %1.3f\n",float(diff.numAllocs)/frames,float(diff.numFrees)/frames);
#endif // DEBUG_MEMORY
lprintf("----------------------------------------------- Profiler Report End\n");
}
void Profiler::ReportNodes(const ProfileNode * pNodeToShow,bool recurse)
{
// sort and only show the top 20 or so
ProfilerData & data = ProfilerData::Instance();
const double secondsSinceReset = data.m_secondsSinceReset;
const int frames = data.m_framesSinceReset;
if ( frames == 0 || secondsSinceReset <= 0 )
return;
double secondsParent;
if ( pNodeToShow == &(data.m_root) )
{
secondsParent = secondsSinceReset;
}
else
{
secondsParent = TimeToSeconds( pNodeToShow->m_time );
}
if ( recurse )
LogPushTab();
lprintf("%-30s : parnt : total : millis: kclocks : counts\n",pNodeToShow->m_name);
if ( secondsParent <= 0 )
{
lprintf("No time in parent!!\n");
if ( recurse )
LogPopTab();
return;
}
//vecsorted< vector_s< ProfileNode, NUM_ENTRIES_TO_SHOW >, compare_ProfileNode_by_seconds > entries;
//vector_s< ProfileNode *, NUM_ENTRIES_TO_SHOW > entries;
vector< ProfileNode * > entries;
entries.reserve(32);
// Use entries in the currently selected branch.
ProfileNode * child = pNodeToShow->m_child;
while( child != NULL )
{
// Sorting fucks up the HUD descent, because it indexes by the normal indexing order
/*
if ( entries.size() < NUM_ENTRIES_TO_SHOW )
{
entries.insert(*child);
}
else if ( child->m_time > entries.back().m_time )
{
entries.pop_back();
entries.insert(*child);
}
*/
entries.push_back(child);
child = child->m_sibling;
}
double secondsSum = 0.0;
// @@ would be nice to know the per-frame max as well
// @@ can also use m_index to show the total time for a Node
for(int i=0;i<entries.size32();i++)
{
const ProfileNode & entry = *(entries[i]);
double seconds = TimeToSeconds( entry.m_time );
double percentTotal = 100.0 * seconds / secondsSinceReset;
double percentParent = 100.0 * seconds / secondsParent;
double millisPerFrame = seconds * 1000.0 / double(frames);
double countsPerFrame = entry.m_count / double(frames);
double kclocksPerCount = ( entry.m_time ) / ( 1000.0 * (entry.m_count == 0 ? 1 : entry.m_count) );
lprintf("%-30s : %5.1f : %5.1f : %5.2f : %7.1f : %5.1f\n",
entry.m_name,
percentParent,
percentTotal,
millisPerFrame,
kclocksPerCount,
countsPerFrame);
secondsSum += seconds;
if ( recurse && entry.m_count > 0 )
{
if ( entry.m_child != NULL )
{
ReportNodes(&entry,true);
}
}
}
// and log missing time not counted in parent
{
double seconds = secondsParent - secondsSum;
double percentTotal = 100.0 * seconds / secondsSinceReset;
double percentParent = 100.0 * seconds / secondsParent;
double millisPerFrame = seconds * 1000.0 / double(frames);
lprintf("%-30s : %5.1f : %5.1f : %5.2f : %7.1f : %5.1f\n",
"missing",
percentParent,
percentTotal,
millisPerFrame,
0.0,
0.0);
}
if ( recurse )
LogPopTab();
}
void Profiler::ReportEntries(bool dumpAll)
{
// sort and only show the top 20 or so
ProfilerData & data = ProfilerData::Instance();
/*
if ( ! data.m_stack.empty() )
{
lprintf("Report on non-empty stack will not be fully accurate!!\n");
}
*/
const double secondsSinceReset = data.m_secondsSinceReset;
const int frames = data.m_framesSinceReset;
const int n = data.m_entries.size32();
if ( n == 0 || frames == 0 )
{
lprintf("Nothing to report!!\n");
return;
}
const ProfilerEntry * pEntries;
int numEntries = 0;
vecsorted< vector_s< ProfilerEntry, NUM_ENTRIES_TO_SHOW >, compare_ProfilerEntry_by_seconds > entries_s;
vector< ProfilerEntry > entries_v;
if ( dumpAll )
{
entries_v.assignv(data.m_entries);
std::sort( entries_v.begin(), entries_v.end(), compare_ProfilerEntry_by_seconds() );
pEntries = entries_v.data();
numEntries = n;
}
else
{
for(int i=0;i<n;i++)
{
const ProfilerEntry & entry = data.m_entries[i];
if ( entries_s.size() < NUM_ENTRIES_TO_SHOW )
{
entries_s.insert(entry);
}
else if ( entry.m_time > entries_s.back().m_time )
{
entries_s.pop_back();
entries_s.insert(entry);
}
}
pEntries = &entries_s[0];
numEntries = entries_s.size32();
}
lprintf("%-40s : percent : millis: kclocks : counts\n","name");
for(int i=0;i<numEntries;i++)
{
const ProfilerEntry & entry = pEntries[i];
if ( entry.m_count == 0 )
continue;
double seconds = TimeToSeconds( entry.m_time );
double percent = 100.0 * seconds / secondsSinceReset;
double millisPerFrame = seconds * 1000.0 / double(frames);
double kclocksPerCount = ( entry.m_time ) / ( 1000.0 * entry.m_count );
double countsPerFrame = entry.m_count / double(frames);
lprintf("%-40s : %-5.1f %% : %-5.2f : %-7.1f : %5.1f\n",
entry.m_name,
percent,
millisPerFrame,
kclocksPerCount,
countsPerFrame);
}
}
void Profiler::GetEntry(const int index, uint64 * pTime, int* pCount)
{
ASSERT( pTime );
ASSERT( pCount );
ProfilerData & data = ProfilerData::Instance();
ASSERT( 0 <= index );
ASSERT( index < data.m_entries.size32() );
const ProfilerEntry& entry = data.m_entries[index];
*pTime = entry.m_time;
*pCount = entry.m_count;
}
void Profiler::WriteRecords(const char * fileName)
{
File f;
if ( ! f.Open(fileName,"wb") )
return;
ProfilerData & data = ProfilerData::Instance();
// write entry names :
f.Put32( data.m_entries.size32() );
for(int i=0; i< data.m_entries.size32(); i++)
{
if ( data.m_entries[i].m_name )
f.WriteCString( data.m_entries[i].m_name );
else
f.WriteCString( "" );
}
f.Put32( data.m_records.size32() );
if ( ! data.m_records.empty() )
{
f.Write( data.m_records.data(), data.m_records.size_bytes() );
}
f.Close();
}
void Profiler::ReadRecords( const char * fileName)
{
File f;
if ( ! f.Open(fileName,"rb") )
return;
ProfilerData & data = ProfilerData::Instance();
// read entry names :
uint32 numEntries = f.Get32();
data.m_entries.resize(numEntries);
for(int i=0; i< data.m_entries.size32(); i++)
{
data.m_entries[i].m_string = f.ReadString();
data.m_entries[i].m_name = data.m_entries[i].m_string.CStr();
}
uint32 numRecords = f.Get32();
data.m_records.resize(numRecords);
f.Read( data.m_records.data(), data.m_records.size_bytes() );
f.Close();
}
const Profiler::ProfileRecord * Profiler::GetRecords(int * pCount)
{
ProfilerData & data = ProfilerData::Instance();
*pCount = data.m_records.size32();
return data.m_records.data();
}
const char * Profiler::GetEntryName(int index)
{
ProfilerData & data = ProfilerData::Instance();
if ( index < 0 || index >= data.m_entries.size() )
return NULL;
return data.m_entries[index].m_name;
}
END_CB
| 21.771562
| 144
| 0.665685
|
Svengali
|
608645bd649ebef74d717c863bb5c4cf4a8bff98
| 216
|
cpp
|
C++
|
test/string_test.cpp
|
sekiya9311/CplusplusAlgorithmLibrary
|
f29dbdfbf3594da055185e39765880ff5d1e64ae
|
[
"Apache-2.0"
] | null | null | null |
test/string_test.cpp
|
sekiya9311/CplusplusAlgorithmLibrary
|
f29dbdfbf3594da055185e39765880ff5d1e64ae
|
[
"Apache-2.0"
] | 8
|
2019-04-13T15:11:11.000Z
|
2020-03-19T17:14:18.000Z
|
test/string_test.cpp
|
sekiya9311/CplusplusAlgorithmLibrary
|
f29dbdfbf3594da055185e39765880ff5d1e64ae
|
[
"Apache-2.0"
] | null | null | null |
#include <bits/stdc++.h>
#include "../string/rolling_hash.cpp"
#include "../string/split.cpp"
#include "../string/join.cpp"
#include "../string/trie.cpp"
#include "../string/binary_trie.cpp"
void string_test() {
}
| 19.636364
| 37
| 0.680556
|
sekiya9311
|
6087df6cfdbbd632419966d9f44f5527cd400b5b
| 2,814
|
cc
|
C++
|
squid/squid3-3.3.8.spaceify/helpers/digest_auth/eDirectory/digest_pw_auth.cc
|
spaceify/spaceify
|
4296d6c93cad32bb735cefc9b8157570f18ffee4
|
[
"MIT"
] | 4
|
2015-01-20T15:25:34.000Z
|
2017-12-20T06:47:42.000Z
|
squid/squid3-3.3.8.spaceify/helpers/digest_auth/eDirectory/digest_pw_auth.cc
|
spaceify/spaceify
|
4296d6c93cad32bb735cefc9b8157570f18ffee4
|
[
"MIT"
] | 4
|
2015-05-15T09:32:55.000Z
|
2016-02-18T13:43:31.000Z
|
squid/squid3-3.3.8.spaceify/helpers/digest_auth/eDirectory/digest_pw_auth.cc
|
spaceify/spaceify
|
4296d6c93cad32bb735cefc9b8157570f18ffee4
|
[
"MIT"
] | null | null | null |
/*
* digest_pw_auth.c
*
* AUTHOR: Robert Collins. Based on ncsa_auth.c by Arjan de Vet
* <Arjan.deVet@adv.iae.nl>
* LDAP backend extension by Flavio Pescuma, MARA Systems AB <flavio@marasystems.com>
*
* Example digest authentication program for Squid, based on the original
* proxy_auth code from client_side.c, written by
* Jon Thackray <jrmt@uk.gdscorp.com>.
*
* - comment lines are possible and should start with a '#';
* - empty or blank lines are possible;
* - file format is username:password
*
* To build a directory integrated backend, you need to be able to
* calculate the HA1 returned to squid. To avoid storing a plaintext
* password you can calculate MD5(username:realm:password) when the
* user changes their password, and store the tuple username:realm:HA1.
* then find the matching username:realm when squid asks for the
* HA1.
*
* This implementation could be improved by using such a triple for
* the file format. However storing such a triple does little to
* improve security: If compromised the username:realm:HA1 combination
* is "plaintext equivalent" - for the purposes of digest authentication
* they allow the user access. Password syncronisation is not tackled
* by digest - just preventing on the wire compromise.
*
* Copyright (c) 2003 Robert Collins <robertc@squid-cache.org>
*/
#include "squid.h"
#include "digest_common.h"
#include "helpers/defines.h"
#include "ldap_backend.h"
#define PROGRAM_NAME "digest_edirectory_auth"
static void
GetHHA1(RequestData * requestData)
{
LDAPHHA1(requestData);
}
static void
ParseBuffer(char *buf, RequestData * requestData)
{
char *p;
requestData->parsed = 0;
if ((p = strchr(buf, '\n')) != NULL)
*p = '\0'; /* strip \n */
if ((requestData->user = strtok(buf, "\"")) == NULL)
return;
if ((requestData->realm = strtok(NULL, "\"")) == NULL)
return;
if ((requestData->realm = strtok(NULL, "\"")) == NULL)
return;
requestData->parsed = -1;
}
static void
OutputHHA1(RequestData * requestData)
{
requestData->error = 0;
GetHHA1(requestData);
if (requestData->error) {
SEND_ERR("No such user");
return;
}
printf("%s\n", requestData->HHA1);
}
static void
DoOneRequest(char *buf)
{
RequestData requestData;
ParseBuffer(buf, &requestData);
if (!requestData.parsed) {
SEND_ERR("");
return;
}
OutputHHA1(&requestData);
}
static void
ProcessArguments(int argc, char **argv)
{
int i;
i = LDAPArguments(argc, argv);
if (i)
exit(i);
}
int
main(int argc, char **argv)
{
char buf[HELPER_INPUT_BUFFER];
setbuf(stdout, NULL);
ProcessArguments(argc, argv);
while (fgets(buf, HELPER_INPUT_BUFFER, stdin) != NULL)
DoOneRequest(buf);
exit(0);
}
| 27.057692
| 85
| 0.676262
|
spaceify
|
608819dffeb64853b58365438eff71ac45fa764b
| 2,419
|
cpp
|
C++
|
transformations/jw/EfficientJW.cpp
|
zpparks314/xacc-vqe
|
37aaadb12d856324532c42ca9f7e56147edbd2e7
|
[
"BSD-3-Clause"
] | 14
|
2017-09-15T19:05:11.000Z
|
2021-11-04T05:24:51.000Z
|
transformations/jw/EfficientJW.cpp
|
zpparks314/xacc-vqe
|
37aaadb12d856324532c42ca9f7e56147edbd2e7
|
[
"BSD-3-Clause"
] | 25
|
2017-08-08T16:03:55.000Z
|
2019-12-22T12:18:27.000Z
|
transformations/jw/EfficientJW.cpp
|
zpparks314/xacc-vqe
|
37aaadb12d856324532c42ca9f7e56147edbd2e7
|
[
"BSD-3-Clause"
] | 17
|
2018-06-25T20:20:16.000Z
|
2021-04-03T18:31:44.000Z
|
#include "EfficientJW.hpp"
#include "XACC.hpp"
#include <ctime>
namespace xacc {
namespace vqe {
std::shared_ptr<IR> EfficientJW::transform(
std::shared_ptr<IR> ir) {
std::complex<double> imag(0,1);
auto fermiKernel = ir->getKernels()[0];
result.clear();
int myStart = 0;
int myEnd = fermiKernel->nInstructions();
auto instructions = fermiKernel->getInstructions();
auto instVec = std::vector<InstPtr>(instructions.begin(), instructions.end());
auto start = std::clock();
// Loop over all Fermionic terms...
for (int z = myStart; z < myEnd; ++z) {
auto f = instVec[z];
auto coeff =
f->getParameter(f->nParameters() - 2).as<std::complex<double>>();
auto fermionVar = f->getParameter(f->nParameters() - 1).as<std::string>();
// Get the creation or annihilation sites
auto termSites = f->bits();
if (termSites.size() == 2) {
int i = termSites[0];
int j = termSites[1];
int pmin = std::min(i,j);
int pmax = std::max(i,j);
PauliOperator Sxi({{i,"X"}}, 0.5), Syi({{i,"Y"}}, 0.5);
PauliOperator Sxj({{j,"X"}}, 0.5), Syj({{j,"Y"}}, 0.5);
PauliOperator sPlusI = Sxi - imag * Syi;
PauliOperator sMinusJ = Sxj + imag * Syj;
std::map<int, std::string> zpm;
int parity = 1;
for (int p = pmin; p < pmax-1; ++p) {
zpm[p] = "Z";
parity *= -1;
}
result += coeff * sPlusI * PauliOperator(zpm, parity) * sMinusJ;
} else if (termSites.size() == 4) {
int i = termSites[0];
int j = termSites[1];
int k = termSites[2];
int l = termSites[3];
int pmin = std::min(j, k);
int pmax = std::max(j, k);
PauliOperator Sxi({{i,"X"}}, 0.5), Syi({{i,"Y"}}, 0.5);
PauliOperator Sxj({{j,"X"}}, 0.5), Syj({{j,"Y"}}, 0.5);
PauliOperator Sxk({{k,"X"}}, 0.5), Syk({{k,"Y"}}, 0.5);
PauliOperator Sxl({{l,"X"}}, 0.5), Syl({{l,"Y"}}, 0.5);
PauliOperator sPlusI = Sxi - imag * Syi;
PauliOperator sPlusJ = Sxj - imag * Syj;
PauliOperator sMinusK = Sxk + imag * Syk;
PauliOperator sMinusL = Sxl + imag * Syl;
std::map<int, std::string> zpm;
int parity = 1;
for (int p = pmin; p < pmax-1; ++p) {
zpm[p] = "Z";
parity *= -1;
}
result += coeff * sPlusI * sPlusJ * PauliOperator(zpm, parity) * sMinusK * sMinusL;
} else if (termSites.size() == 0) {
result += PauliOperator(coeff);
}
}
std::cout << (std::clock() - start) / (double) (CLOCKS_PER_SEC) << "\n";
return result.toXACCIR();
}
}
}
| 24.434343
| 86
| 0.583299
|
zpparks314
|
608acdc2b912ea8d10c5266cef30225a89db6050
| 21,584
|
cpp
|
C++
|
libboost-log/src/syslog_backend.cpp
|
build2-packaging/boost
|
203d505dd3ba04ea50785bc8b247a295db5fc718
|
[
"BSL-1.0"
] | 4
|
2021-02-23T11:24:33.000Z
|
2021-09-11T20:10:46.000Z
|
libboost-log/src/syslog_backend.cpp
|
build2-packaging/boost
|
203d505dd3ba04ea50785bc8b247a295db5fc718
|
[
"BSL-1.0"
] | null | null | null |
libboost-log/src/syslog_backend.cpp
|
build2-packaging/boost
|
203d505dd3ba04ea50785bc8b247a295db5fc718
|
[
"BSL-1.0"
] | null | null | null |
/*
* Copyright Andrey Semashev 2007 - 2020.
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*/
/*!
* \file syslog_backend.cpp
* \author Andrey Semashev
* \date 08.01.2008
*
* \brief This header is the Boost.Log library implementation, see the library documentation
* at http://www.boost.org/doc/libs/release/libs/log/doc/html/index.html.
*/
#include <boost/log/detail/config.hpp>
#ifndef BOOST_LOG_WITHOUT_SYSLOG
#include <ctime>
#include <algorithm>
#include <stdexcept>
#include <boost/limits.hpp>
#include <boost/assert.hpp>
#include <boost/smart_ptr/weak_ptr.hpp>
#include <boost/smart_ptr/shared_ptr.hpp>
#include <boost/smart_ptr/make_shared_object.hpp>
#include <boost/throw_exception.hpp>
#if !defined(BOOST_LOG_NO_ASIO)
#include <boost/asio/buffer.hpp>
#include <boost/asio/socket_base.hpp>
#include <boost/asio/io_context.hpp>
#include <boost/asio/ip/udp.hpp>
#include <boost/asio/ip/address.hpp>
#include <boost/asio/ip/host_name.hpp>
#include <boost/asio/ip/resolver_base.hpp>
#endif
#include <boost/system/error_code.hpp>
#include <boost/date_time/c_time.hpp>
#include <boost/log/sinks/syslog_backend.hpp>
#include <boost/log/sinks/syslog_constants.hpp>
#include <boost/log/detail/singleton.hpp>
#include <boost/log/detail/snprintf.hpp>
#include <boost/log/exceptions.hpp>
#if !defined(BOOST_LOG_NO_THREADS)
#include <boost/thread/locks.hpp>
#include <boost/thread/mutex.hpp>
#endif
#include "unique_ptr.hpp"
#ifdef BOOST_LOG_USE_NATIVE_SYSLOG
#include <syslog.h>
#endif // BOOST_LOG_USE_NATIVE_SYSLOG
#include <boost/log/detail/header.hpp>
namespace boost {
BOOST_LOG_OPEN_NAMESPACE
namespace sinks {
namespace syslog {
//! The function constructs log record level from an integer
BOOST_LOG_API level make_level(int lev)
{
if (BOOST_UNLIKELY(static_cast< unsigned int >(lev) >= 8u))
BOOST_THROW_EXCEPTION(std::out_of_range("syslog level value is out of range"));
return static_cast< level >(lev);
}
//! The function constructs log source facility from an integer
BOOST_LOG_API facility make_facility(int fac)
{
if (BOOST_UNLIKELY((static_cast< unsigned int >(fac) & 7u) != 0u
|| static_cast< unsigned int >(fac) > (23u * 8u)))
{
BOOST_THROW_EXCEPTION(std::out_of_range("syslog facility code value is out of range"));
}
return static_cast< facility >(fac);
}
} // namespace syslog
////////////////////////////////////////////////////////////////////////////////
//! Syslog sink backend implementation
////////////////////////////////////////////////////////////////////////////////
struct syslog_backend::implementation
{
#ifdef BOOST_LOG_USE_NATIVE_SYSLOG
struct native;
#endif // BOOST_LOG_USE_NATIVE_SYSLOG
#if !defined(BOOST_LOG_NO_ASIO)
struct udp_socket_based;
#endif
//! Level mapper
severity_mapper_type m_LevelMapper;
//! Logging facility (portable or native, depending on the backend implementation)
const int m_Facility;
//! Constructor
explicit implementation(int facility) :
m_Facility(facility)
{
}
//! Virtual destructor
virtual ~implementation() {}
//! The method sends the formatted message to the syslog host
virtual void send(syslog::level lev, string_type const& formatted_message) = 0;
};
////////////////////////////////////////////////////////////////////////////////
// Native syslog API support
////////////////////////////////////////////////////////////////////////////////
#ifdef BOOST_LOG_USE_NATIVE_SYSLOG
BOOST_LOG_ANONYMOUS_NAMESPACE {
//! Syslog service initializer (implemented as a weak singleton)
#if !defined(BOOST_LOG_NO_THREADS)
class native_syslog_initializer :
private log::aux::lazy_singleton< native_syslog_initializer, mutex >
#else
class native_syslog_initializer
#endif
{
#if !defined(BOOST_LOG_NO_THREADS)
friend class log::aux::lazy_singleton< native_syslog_initializer, mutex >;
typedef log::aux::lazy_singleton< native_syslog_initializer, mutex > mutex_holder;
#endif
private:
/*!
* \brief Application identification string
*
* \note We have to keep it as an immutable member because some syslog implementations (e.g. glibc)
* do not deep-copy the ident string to internal storage when \c openlog is called
* and instead save a pointer to the user-provided string. This means the user-provided
* string needs to remain accessible for the whole duration of logging.
*
* https://github.com/boostorg/log/issues/97
* https://sourceware.org/bugzilla/show_bug.cgi?id=25442
*/
const std::string m_Ident;
public:
native_syslog_initializer(std::string const& ident, int facility) :
m_Ident(ident)
{
::openlog((m_Ident.empty() ? static_cast< const char* >(NULL) : m_Ident.c_str()), 0, facility);
}
~native_syslog_initializer()
{
::closelog();
}
static shared_ptr< native_syslog_initializer > get_instance(std::string const& ident, int facility)
{
#if !defined(BOOST_LOG_NO_THREADS)
lock_guard< mutex > lock(mutex_holder::get());
#endif
static weak_ptr< native_syslog_initializer > instance;
shared_ptr< native_syslog_initializer > p(instance.lock());
if (!p)
{
p = boost::make_shared< native_syslog_initializer >(ident, facility);
instance = p;
}
return p;
}
BOOST_DELETED_FUNCTION(native_syslog_initializer(native_syslog_initializer const&))
BOOST_DELETED_FUNCTION(native_syslog_initializer& operator= (native_syslog_initializer const&))
};
} // namespace
struct syslog_backend::implementation::native :
public implementation
{
//! Reference to the syslog service initializer
const shared_ptr< native_syslog_initializer > m_pSyslogInitializer;
//! Constructor
native(syslog::facility const& fac, std::string const& ident) :
implementation(convert_facility(fac)),
m_pSyslogInitializer(native_syslog_initializer::get_instance(ident, this->m_Facility))
{
}
//! The method sends the formatted message to the syslog host
void send(syslog::level lev, string_type const& formatted_message) BOOST_OVERRIDE
{
int native_level;
switch (lev)
{
case syslog::emergency:
native_level = LOG_EMERG; break;
case syslog::alert:
native_level = LOG_ALERT; break;
case syslog::critical:
native_level = LOG_CRIT; break;
case syslog::error:
native_level = LOG_ERR; break;
case syslog::warning:
native_level = LOG_WARNING; break;
case syslog::notice:
native_level = LOG_NOTICE; break;
case syslog::debug:
native_level = LOG_DEBUG; break;
default:
native_level = LOG_INFO; break;
}
::syslog(this->m_Facility | native_level, "%s", formatted_message.c_str());
}
private:
//! The function converts portable facility codes to the native codes
static int convert_facility(syslog::facility const& fac)
{
// POSIX does not specify anything except for LOG_USER and LOG_LOCAL*
#ifndef LOG_KERN
#define LOG_KERN LOG_USER
#endif
#ifndef LOG_DAEMON
#define LOG_DAEMON LOG_KERN
#endif
#ifndef LOG_MAIL
#define LOG_MAIL LOG_USER
#endif
#ifndef LOG_AUTH
#define LOG_AUTH LOG_DAEMON
#endif
#ifndef LOG_SYSLOG
#define LOG_SYSLOG LOG_DAEMON
#endif
#ifndef LOG_LPR
#define LOG_LPR LOG_DAEMON
#endif
#ifndef LOG_NEWS
#define LOG_NEWS LOG_USER
#endif
#ifndef LOG_UUCP
#define LOG_UUCP LOG_USER
#endif
#ifndef LOG_CRON
#define LOG_CRON LOG_DAEMON
#endif
#ifndef LOG_AUTHPRIV
#define LOG_AUTHPRIV LOG_AUTH
#endif
#ifndef LOG_FTP
#define LOG_FTP LOG_DAEMON
#endif
static const int native_facilities[24] =
{
LOG_KERN,
LOG_USER,
LOG_MAIL,
LOG_DAEMON,
LOG_AUTH,
LOG_SYSLOG,
LOG_LPR,
LOG_NEWS,
LOG_UUCP,
LOG_CRON,
LOG_AUTHPRIV,
LOG_FTP,
// reserved values
LOG_USER,
LOG_USER,
LOG_USER,
LOG_USER,
LOG_LOCAL0,
LOG_LOCAL1,
LOG_LOCAL2,
LOG_LOCAL3,
LOG_LOCAL4,
LOG_LOCAL5,
LOG_LOCAL6,
LOG_LOCAL7
};
std::size_t n = static_cast< unsigned int >(fac) / 8u;
BOOST_ASSERT(n < sizeof(native_facilities) / sizeof(*native_facilities));
return native_facilities[n];
}
};
#endif // BOOST_LOG_USE_NATIVE_SYSLOG
////////////////////////////////////////////////////////////////////////////////
// Socket-based implementation
////////////////////////////////////////////////////////////////////////////////
#if !defined(BOOST_LOG_NO_ASIO)
BOOST_LOG_ANONYMOUS_NAMESPACE {
//! The shared UDP socket
struct syslog_udp_socket
{
private:
//! The socket primitive
asio::ip::udp::socket m_Socket;
public:
//! The constructor creates a socket bound to the specified local address and port
explicit syslog_udp_socket(asio::io_context& io_ctx, asio::ip::udp const& protocol, asio::ip::udp::endpoint const& local_address) :
m_Socket(io_ctx)
{
m_Socket.open(protocol);
m_Socket.set_option(asio::socket_base::reuse_address(true));
m_Socket.bind(local_address);
}
//! The destructor closes the socket
~syslog_udp_socket()
{
boost::system::error_code ec;
m_Socket.shutdown(asio::socket_base::shutdown_both, ec);
m_Socket.close(ec);
}
//! The method sends the syslog message to the specified endpoint
void send_message(int pri, const char* local_host_name, asio::ip::udp::endpoint const& target, const char* message);
BOOST_DELETED_FUNCTION(syslog_udp_socket(syslog_udp_socket const&))
BOOST_DELETED_FUNCTION(syslog_udp_socket& operator= (syslog_udp_socket const&))
};
//! The class contains the UDP service for syslog sockets to function
class syslog_udp_service :
public log::aux::lazy_singleton< syslog_udp_service, shared_ptr< syslog_udp_service > >
{
friend class log::aux::lazy_singleton< syslog_udp_service, shared_ptr< syslog_udp_service > >;
typedef log::aux::lazy_singleton< syslog_udp_service, shared_ptr< syslog_udp_service > > base_type;
public:
//! The IO context instance
asio::io_context m_IOContext;
//! The local host name to put into log message
std::string m_LocalHostName;
#if !defined(BOOST_LOG_NO_THREADS)
//! A synchronization primitive to protect the host name resolver
mutex m_Mutex;
//! The resolver is used to acquire connection endpoints
asio::ip::udp::resolver m_HostNameResolver;
#endif // !defined(BOOST_LOG_NO_THREADS)
private:
//! Default constructor
syslog_udp_service()
#if !defined(BOOST_LOG_NO_THREADS)
: m_HostNameResolver(m_IOContext)
#endif // !defined(BOOST_LOG_NO_THREADS)
{
boost::system::error_code err;
m_LocalHostName = asio::ip::host_name(err);
}
//! Initializes the singleton instance
static void init_instance()
{
base_type::get_instance().reset(new syslog_udp_service());
}
};
//! The method sends the syslog message to the specified endpoint
void syslog_udp_socket::send_message(
int pri, const char* local_host_name, asio::ip::udp::endpoint const& target, const char* message)
{
std::time_t t = std::time(NULL);
std::tm ts;
std::tm* time_stamp = boost::date_time::c_time::localtime(&t, &ts);
// Month will have to be injected separately, as involving locale won't do here
static const char months[12][4] =
{
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};
// The packet size is mandated in RFC3164, plus one for the terminating zero
char packet[1025];
int n = boost::log::aux::snprintf
(
packet,
sizeof(packet),
"<%d>%s %2d %02d:%02d:%02d %s %s",
pri,
months[time_stamp->tm_mon],
time_stamp->tm_mday,
time_stamp->tm_hour,
time_stamp->tm_min,
time_stamp->tm_sec,
local_host_name,
message
);
if (BOOST_LIKELY(n > 0))
{
std::size_t packet_size = static_cast< std::size_t >(n) >= sizeof(packet) ? sizeof(packet) - 1u : static_cast< std::size_t >(n);
m_Socket.send_to(asio::buffer(packet, packet_size), target);
}
}
} // namespace
struct syslog_backend::implementation::udp_socket_based :
public implementation
{
//! Protocol to be used
asio::ip::udp m_Protocol;
//! Pointer to the list of sockets
shared_ptr< syslog_udp_service > m_pService;
//! Pointer to the socket being used
log::aux::unique_ptr< syslog_udp_socket > m_pSocket;
//! The target host to send packets to
asio::ip::udp::endpoint m_TargetHost;
//! Constructor
explicit udp_socket_based(syslog::facility const& fac, asio::ip::udp const& protocol) :
implementation(fac),
m_Protocol(protocol),
m_pService(syslog_udp_service::get())
{
if (m_Protocol == asio::ip::udp::v4())
{
m_TargetHost = asio::ip::udp::endpoint(asio::ip::address_v4(0x7F000001), 514); // 127.0.0.1:514
}
else
{
// ::1, port 514
asio::ip::address_v6::bytes_type addr;
std::fill_n(addr.data(), addr.size() - 1u, static_cast< unsigned char >(0u));
addr[addr.size() - 1u] = 1u;
m_TargetHost = asio::ip::udp::endpoint(asio::ip::address_v6(addr), 514);
}
}
//! The method sends the formatted message to the syslog host
void send(syslog::level lev, string_type const& formatted_message) BOOST_OVERRIDE
{
if (!m_pSocket.get())
{
asio::ip::udp::endpoint any_local_address;
m_pSocket.reset(new syslog_udp_socket(m_pService->m_IOContext, m_Protocol, any_local_address));
}
m_pSocket->send_message(
this->m_Facility | static_cast< int >(lev),
m_pService->m_LocalHostName.c_str(),
m_TargetHost,
formatted_message.c_str());
}
};
#endif // !defined(BOOST_LOG_NO_ASIO)
////////////////////////////////////////////////////////////////////////////////
// Sink backend implementation
////////////////////////////////////////////////////////////////////////////////
BOOST_LOG_API syslog_backend::syslog_backend()
{
construct(log::aux::empty_arg_list());
}
//! Destructor
BOOST_LOG_API syslog_backend::~syslog_backend()
{
delete m_pImpl;
}
//! The method installs the function object that maps application severity levels to Syslog levels
BOOST_LOG_API void syslog_backend::set_severity_mapper(severity_mapper_type const& mapper)
{
m_pImpl->m_LevelMapper = mapper;
}
//! The method writes the message to the sink
BOOST_LOG_API void syslog_backend::consume(record_view const& rec, string_type const& formatted_message)
{
m_pImpl->send(
m_pImpl->m_LevelMapper.empty() ? syslog::info : m_pImpl->m_LevelMapper(rec),
formatted_message);
}
//! The method creates the backend implementation
BOOST_LOG_API void syslog_backend::construct(syslog::facility fac, syslog::impl_types use_impl, ip_versions ip_version, std::string const& ident)
{
#ifdef BOOST_LOG_USE_NATIVE_SYSLOG
if (use_impl == syslog::native)
{
typedef implementation::native native_impl;
m_pImpl = new native_impl(fac, ident);
return;
}
#endif // BOOST_LOG_USE_NATIVE_SYSLOG
#if !defined(BOOST_LOG_NO_ASIO)
typedef implementation::udp_socket_based udp_socket_based_impl;
asio::ip::udp protocol = asio::ip::udp::v4();
switch (ip_version)
{
case v4:
break;
case v6:
protocol = asio::ip::udp::v6();
break;
default:
BOOST_LOG_THROW_DESCR(setup_error, "Incorrect IP version specified");
}
m_pImpl = new udp_socket_based_impl(fac, protocol);
#endif
}
#if !defined(BOOST_LOG_NO_ASIO)
//! The method sets the local address which log records will be sent from.
BOOST_LOG_API void syslog_backend::set_local_address(std::string const& addr, unsigned short port)
{
#if !defined(BOOST_LOG_NO_THREADS)
typedef implementation::udp_socket_based udp_socket_based_impl;
if (udp_socket_based_impl* impl = dynamic_cast< udp_socket_based_impl* >(m_pImpl))
{
char service_name[std::numeric_limits< unsigned int >::digits10 + 3];
boost::log::aux::snprintf(service_name, sizeof(service_name), "%u", static_cast< unsigned int >(port));
asio::ip::udp::endpoint local_address;
{
lock_guard< mutex > lock(impl->m_pService->m_Mutex);
asio::ip::udp::resolver::results_type results = impl->m_pService->m_HostNameResolver.resolve
(
impl->m_Protocol,
addr,
service_name,
asio::ip::resolver_base::address_configured | asio::ip::resolver_base::passive
);
local_address = *results.cbegin();
}
impl->m_pSocket.reset(new syslog_udp_socket(impl->m_pService->m_IOContext, impl->m_Protocol, local_address));
}
#else
// Boost.ASIO requires threads for the host name resolver,
// so without threads we simply assume the string already contains IP address
set_local_address(boost::asio::ip::address::from_string(addr), port);
#endif // !defined(BOOST_LOG_NO_THREADS)
}
//! The method sets the local address which log records will be sent from.
BOOST_LOG_API void syslog_backend::set_local_address(boost::asio::ip::address const& addr, unsigned short port)
{
typedef implementation::udp_socket_based udp_socket_based_impl;
if (udp_socket_based_impl* impl = dynamic_cast< udp_socket_based_impl* >(m_pImpl))
{
if ((impl->m_Protocol == asio::ip::udp::v4() && !addr.is_v4()) || (impl->m_Protocol == asio::ip::udp::v6() && !addr.is_v6()))
BOOST_LOG_THROW_DESCR(setup_error, "Incorrect IP version specified in the local address");
impl->m_pSocket.reset(new syslog_udp_socket(
impl->m_pService->m_IOContext, impl->m_Protocol, asio::ip::udp::endpoint(addr, port)));
}
}
//! The method sets the address of the remote host where log records will be sent to.
BOOST_LOG_API void syslog_backend::set_target_address(std::string const& addr, unsigned short port)
{
#if !defined(BOOST_LOG_NO_THREADS)
typedef implementation::udp_socket_based udp_socket_based_impl;
if (udp_socket_based_impl* impl = dynamic_cast< udp_socket_based_impl* >(m_pImpl))
{
char service_name[std::numeric_limits< unsigned int >::digits10 + 3];
boost::log::aux::snprintf(service_name, sizeof(service_name), "%u", static_cast< unsigned int >(port));
asio::ip::udp::endpoint remote_address;
{
lock_guard< mutex > lock(impl->m_pService->m_Mutex);
asio::ip::udp::resolver::results_type results = impl->m_pService->m_HostNameResolver.resolve
(
impl->m_Protocol,
addr,
service_name,
asio::ip::resolver_query_base::address_configured
);
remote_address = *results.cbegin();
}
impl->m_TargetHost = remote_address;
}
#else
// Boost.ASIO requires threads for the host name resolver,
// so without threads we simply assume the string already contains IP address
set_target_address(boost::asio::ip::address::from_string(addr), port);
#endif // !defined(BOOST_LOG_NO_THREADS)
}
//! The method sets the address of the remote host where log records will be sent to.
BOOST_LOG_API void syslog_backend::set_target_address(boost::asio::ip::address const& addr, unsigned short port)
{
typedef implementation::udp_socket_based udp_socket_based_impl;
if (udp_socket_based_impl* impl = dynamic_cast< udp_socket_based_impl* >(m_pImpl))
{
if ((impl->m_Protocol == asio::ip::udp::v4() && !addr.is_v4()) || (impl->m_Protocol == asio::ip::udp::v6() && !addr.is_v6()))
BOOST_LOG_THROW_DESCR(setup_error, "Incorrect IP version specified in the target address");
impl->m_TargetHost = asio::ip::udp::endpoint(addr, port);
}
}
#endif // !defined(BOOST_LOG_NO_ASIO)
} // namespace sinks
BOOST_LOG_CLOSE_NAMESPACE // namespace log
} // namespace boost
#include <boost/log/detail/footer.hpp>
#endif // !defined(BOOST_LOG_WITHOUT_SYSLOG)
| 34.151899
| 145
| 0.631996
|
build2-packaging
|
608c46d0b11020771082aecb9d98c66b654dafc7
| 351
|
cpp
|
C++
|
Ass_4/C files/123455.cpp
|
pratik8696/Assignment
|
6fa02f4f7ec135b13dbebea9920eeb2a57bd1489
|
[
"MIT"
] | null | null | null |
Ass_4/C files/123455.cpp
|
pratik8696/Assignment
|
6fa02f4f7ec135b13dbebea9920eeb2a57bd1489
|
[
"MIT"
] | null | null | null |
Ass_4/C files/123455.cpp
|
pratik8696/Assignment
|
6fa02f4f7ec135b13dbebea9920eeb2a57bd1489
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
int main(){
int size;
cin>>size;
int arr[size];
for (int i = 0; i < size; i++)
{
cin>>arr[i];
}
int sum=0;
for (int i = 0; i < size; i++)
{
for (int j = i; j < size; j++)
{
sum =sum+ arr[j];
}
}
cout<<sum;
return 0;
}
| 15.954545
| 38
| 0.407407
|
pratik8696
|
608d7a7339f877b6c70aeb2a7a1cffb8a77b8540
| 2,591
|
hh
|
C++
|
tests/Dispatch/SynchronousTaskGroupSpec.hh
|
GroovyCarrot/hhvm-event-dispatcher
|
0140f298c06ce60eeb2f07e7cc1f95aeca5ca853
|
[
"MIT"
] | null | null | null |
tests/Dispatch/SynchronousTaskGroupSpec.hh
|
GroovyCarrot/hhvm-event-dispatcher
|
0140f298c06ce60eeb2f07e7cc1f95aeca5ca853
|
[
"MIT"
] | null | null | null |
tests/Dispatch/SynchronousTaskGroupSpec.hh
|
GroovyCarrot/hhvm-event-dispatcher
|
0140f298c06ce60eeb2f07e7cc1f95aeca5ca853
|
[
"MIT"
] | null | null | null |
<?hh // partial
namespace Tests\GroovyCarrot\Event\Dispatch;
use GroovyCarrot\Event\EventHandling;
use GroovyCarrot\Event\Dispatch\SynchronousTaskGroup;
use Mockery as m;
class SynchronousTaskGroupSpec extends TaskGroupSpec
{
public function __construct()
{
parent::__construct();
$this->group = SynchronousTaskGroup::newGroup();
}
/**
* @test
*/
public function it_propagates_an_event_to_tasks_synchronously(): void
{
$self = $this;
$order = new Order(Vector{'T-shirt', 'Jeans'});
$event = new OrderPlacedEvent($order);
$step = 0;
$first = m::mock(EventHandling::class);
$first->shouldReceive('handleEvent')
->times(1)
->andReturnUsing(
async function (OrderPlacedEvent $passedEvent): Awaitable<void> use ($self, $event, &$step) {
$this->assertEquals($event, $passedEvent);
$this->assertEquals($event->order, $passedEvent->order);
// Create a delay, if this task was asynchronous then the other
// tasks would continue.
await \HH\Asio\usleep(200000);
$self->assertEquals(0, $step);
$step = 1;
}
);
$second = m::mock(EventHandling::class);
$second->shouldReceive('handleEvent')
->times(1)
->andReturnUsing(
async function (OrderPlacedEvent $passedEvent): Awaitable<void> use ($self, $event, &$step) {
$this->assertEquals($event, $passedEvent);
$this->assertEquals($event->order, $passedEvent->order);
$self->assertEquals(1, $step);
$step = 2;
}
);
$third = m::mock(EventHandling::class);
$third->shouldReceive('handleEvent')
->times(1)
->andReturnUsing(
async function (OrderPlacedEvent $passedEvent): Awaitable<void> use ($self, $event, &$step) {
$this->assertEquals($event, $passedEvent);
$this->assertEquals($event->order, $passedEvent->order);
$self->assertEquals(2, $step);
$step = 3;
}
);
$group = SynchronousTaskGroup::newGroup()
->addTask($first, 0)
->addTask($third, 2)
->addTask($second, 1);
\HH\Asio\join($group->handleEvent($event));
$this->assertEquals(3, $step);
}
}
| 33.217949
| 109
| 0.526438
|
GroovyCarrot
|
6093a4faa2c2fb6cde1c589318d3bbeff4e907cd
| 2,542
|
cpp
|
C++
|
src/blockchain/block.cpp
|
Derik-T/CPP
|
adf8ecb11af5bf96d04182b83ae3fa58ca64bc72
|
[
"MIT"
] | 1
|
2021-08-28T23:51:52.000Z
|
2021-08-28T23:51:52.000Z
|
src/blockchain/block.cpp
|
Derik-T/CPP
|
adf8ecb11af5bf96d04182b83ae3fa58ca64bc72
|
[
"MIT"
] | null | null | null |
src/blockchain/block.cpp
|
Derik-T/CPP
|
adf8ecb11af5bf96d04182b83ae3fa58ca64bc72
|
[
"MIT"
] | null | null | null |
#ifndef BLOCK_CPP
#define BLOCK_CPP
#include "block.h"
#include "utilities/merkle.cpp"
#include <string>
#include <unistd.h>
#define zeroHash "0000000000000000000000"
Block::Block(int height, int difficulty)
{
this->txCount = 0;
this->height = height;
this->difficulty = difficulty;
this->merkleTop = "";
this->proof = "";
this->nonce = 0;
this->timestamp = time(NULL);
}
void Block::setPreviusHash(char prevHash[MAX_BUFFER_SIZE])
{
this->previusHash = prevHash;
}
Block::Block()
{
this->txCount = 0;
this->height = 0;
this->proof = "";
this->difficulty = 0;
this->merkleTop = (char *) "";
this->previusHash = (char *) "";
this->nonce = 0;
this->timestamp = time(NULL);
}
void Block::mining(Mempool ¤tMempool)
{
this->txCount = currentMempool.getTxCount() > MAX_SIZE ? MAX_SIZE : currentMempool.getTxCount();
char dest[100];
for (unsigned register int i = 0; i < this->txCount; i++)
{
this->txVector[i] = currentMempool.pop();
this->txVector[i].getRawData(dest);
//printf("Transaction #%d: %s\n", i, dest);
}
char *rawData = new char[MAX_BUFFER_SIZE], *hash = new char[100], *_rawData = new char[MAX_BUFFER_SIZE];
;
if(txCount > 0)
{
this->merkleTop = createMerkleTree(this->txVector, this->txCount);
rawData = this->getRawData();
}
else
{
strcpy(_rawData, "");
}
strcat(_rawData, this->getRawHeader());
int hInt;
do
{
sprintf(_rawData, "%s%d", rawData, nonce);
bytes2md5(_rawData, 100, hash);
nonce++;
}
while(strncmp(hash, zeroHash, this->difficulty) != 0);
proof = hash;
}
// 16:34
char *Block::getRawData()
{
char *rawData = new char [MAX_DATA_SIZE];
for (unsigned register int i = 0; i < this->txCount; i++)
{
char txData[MAX_BUFFER_SIZE];
this->txVector[i].getRawData(txData);
sprintf(rawData, "%s", txData);
}
return rawData;
}
char *Block::getRawHeader()
{
char *blockHeader = new char [MAX_HEADER_SIZE];
sprintf(blockHeader, "%s%s%d%d%d", this->previusHash,this->merkleTop, this->timestamp, this->txCount, this->height);
return blockHeader;
}
int Block::getTxCount()
{
return this->txCount;
}
Transaction Block::getTxByIndex(int index)
{
return this->txVector[index];
}
char *Block::getMerkleTop()
{
return this->merkleTop;
}
char *Block::getProof()
{
return this->proof;
}
int Block::getHeight()
{
return this->height;
}
#endif
| 23.109091
| 120
| 0.618411
|
Derik-T
|
6093e02bf392c46e106e7106022b52113602dc43
| 1,767
|
hpp
|
C++
|
segmenttree/trees/acl_range-add-chmax-range-sum.hpp
|
rsm9/cplib-cpp
|
269064381eb259a049236335abb31f8f73ded7f4
|
[
"MIT"
] | 4
|
2020-05-13T05:06:22.000Z
|
2020-09-18T17:03:36.000Z
|
segmenttree/trees/acl_range-add-chmax-range-sum.hpp
|
rsm9/cplib-cpp
|
269064381eb259a049236335abb31f8f73ded7f4
|
[
"MIT"
] | 1
|
2019-12-11T13:53:17.000Z
|
2019-12-11T13:53:17.000Z
|
segmenttree/trees/acl_range-add-chmax-range-sum.hpp
|
rsm9/cplib-cpp
|
269064381eb259a049236335abb31f8f73ded7f4
|
[
"MIT"
] | 3
|
2019-12-11T06:45:45.000Z
|
2020-09-07T13:45:32.000Z
|
#pragma once
#include "../acl_beats.hpp"
// CUT begin
// Verified: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0427
namespace RangeAddChmaxRangeSum {
#include <algorithm>
template <typename Num>
inline Num second_lowest(Num a, Num a2, Num c, Num c2) noexcept { // a < a2, c < c2
return a == c ? std::min(a2, c2) : a2 <= c ? a2 : c2 <= a ? c2 : std::max(a, c);
}
using Num = int;
constexpr Num INF = 1 << 30;
struct S {
Num lo, lo2, sum;
unsigned sz, nlo;
bool fail;
S() : lo(INF), lo2(INF), sum(0), sz(0), nlo(0), fail(false) {}
S(Num x, unsigned sz_ = 1)
: lo(x), lo2(INF), sum(Num(x) * sz_), sz(sz_), nlo(sz_), fail(false) {}
};
S e() { return S(); }
S op(S l, S r) {
S ret;
ret.lo = std::min(l.lo, r.lo);
ret.lo2 = second_lowest(l.lo, l.lo2, r.lo, r.lo2);
ret.sum = l.sum + r.sum, ret.sz = l.sz + r.sz;
ret.nlo = l.nlo * (l.lo <= r.lo) + r.nlo * (r.lo <= l.lo);
return ret;
}
struct F {
Num lb, bias;
F() : lb(-INF), bias(0) {}
F(Num chmax_, Num add) : lb(chmax_), bias(add) {}
static F chmax(Num x) noexcept { return F(x, Num(0)); }
static F add(Num x) noexcept { return F(-INF, x); };
};
F composition(F fnew, F fold) {
F ret;
ret.lb = std::max(fold.lb + fold.bias, fnew.lb) - fold.bias;
ret.bias = fold.bias + fnew.bias;
return ret;
}
F id() { return F(); }
S mapping(F f, S x) {
if (x.sz == 0) return e();
if (f.lb < x.lo2) {
Num nxt_lo = std::max(x.lo, f.lb);
x.sum += (nxt_lo - x.lo) * x.nlo + f.bias * x.sz;
x.lo = nxt_lo + f.bias, x.lo2 += f.bias;
return x;
}
x.fail = 1;
return x;
}
using segtree = segtree_beats<S, op, e, F, mapping, composition, id>;
} // namespace RangeAddChmaxRangeSum
| 27.184615
| 84
| 0.550085
|
rsm9
|
6094d7e569a730467a11fd11744caff6bf3d1475
| 4,479
|
cpp
|
C++
|
apps/physx_app.cpp
|
ArcheGraphics/Arche-cpp
|
da6770edd4556a920b3f7298f38176107caf7e3a
|
[
"MIT"
] | 8
|
2022-02-15T12:54:57.000Z
|
2022-03-30T16:35:58.000Z
|
apps/physx_app.cpp
|
yangfengzzz/DigitalArche
|
da6770edd4556a920b3f7298f38176107caf7e3a
|
[
"MIT"
] | null | null | null |
apps/physx_app.cpp
|
yangfengzzz/DigitalArche
|
da6770edd4556a920b3f7298f38176107caf7e3a
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2022 Feng Yang
//
// I am making my contributions/submissions to this project solely in my
// personal capacity and am not conveying any rights to any intellectual
// property of any third parties.
#include "physx_app.h"
#include "mesh/primitive_mesh.h"
#include "mesh/mesh_renderer.h"
#include "material/unlit_material.h"
#include "material/blinn_phong_material.h"
#include "camera.h"
#include "physics/static_collider.h"
#include "physics/dynamic_collider.h"
#include "physics/shape/box_collider_shape.h"
#include "physics/shape/sphere_collider_shape.h"
#include "lighting/point_light.h"
#include "controls/orbit_control.h"
#include <random>
namespace vox {
namespace {
class MoveScript : public Script {
Point3F pos = Point3F(-5, 0, 0);
float vel = 4;
int8_t velSign = -1;
public:
MoveScript(Entity *entity) : Script(entity) {
}
void onUpdate(float deltaTime) override {
if (pos.x >= 5) {
velSign = -1;
}
if (pos.x <= -5) {
velSign = 1;
}
pos.x += deltaTime * vel * float(velSign);
entity()->transform->setPosition(pos);
}
};
// Collision Detection
class CollisionScript : public Script {
MeshRenderer *sphereRenderer;
std::default_random_engine e;
std::uniform_real_distribution<float> u;
public:
CollisionScript(Entity *entity) : Script(entity) {
sphereRenderer = entity->getComponent<MeshRenderer>();
u = std::uniform_real_distribution<float>(0, 1);
}
void onTriggerExit(physics::ColliderShapePtr other) override {
static_cast<BlinnPhongMaterial *>(sphereRenderer->getMaterial().get())->setBaseColor(Color(u(e), u(e), u(e), 1));
}
void onTriggerEnter(physics::ColliderShapePtr other) override {
static_cast<BlinnPhongMaterial *>(sphereRenderer->getMaterial().get())->setBaseColor(Color(u(e), u(e), u(e), 1));
}
};
} // namespace
void PhysXApp::loadScene() {
auto scene = _sceneManager->currentScene();
scene->ambientLight()->setDiffuseSolidColor(Color(1, 1, 1));
auto rootEntity = scene->createRootEntity();
auto cameraEntity = rootEntity->createChild("camera");
cameraEntity->transform->setPosition(10, 10, 10);
cameraEntity->transform->lookAt(Point3F(0, 0, 0));
_mainCamera = cameraEntity->addComponent<Camera>();
cameraEntity->addComponent<control::OrbitControl>();
// init point light
auto light = rootEntity->createChild("light");
light->transform->setPosition(0, 3, 0);
auto pointLight = light->addComponent<PointLight>();
pointLight->intensity = 0.3;
// create box test entity
float cubeSize = 2.0;
auto boxEntity = rootEntity->createChild("BoxEntity");
auto boxMtl = std::make_shared<BlinnPhongMaterial>(_device);
auto boxRenderer = boxEntity->addComponent<MeshRenderer>();
boxMtl->setBaseColor(Color(0.8, 0.3, 0.3, 1.0));
boxRenderer->setMesh(PrimitiveMesh::createCuboid(_device, cubeSize, cubeSize, cubeSize));
boxRenderer->setMaterial(boxMtl);
auto boxCollider = boxEntity->addComponent<physics::StaticCollider>();
// boxCollider->debugEntity = boxEntity;
auto boxColliderShape = std::make_shared<physics::BoxColliderShape>();
boxColliderShape->setSize(Vector3F(cubeSize, cubeSize, cubeSize));
boxCollider->addShape(boxColliderShape);
// create sphere test entity
float radius = 1.25;
auto sphereEntity = rootEntity->createChild("SphereEntity");
sphereEntity->transform->setPosition(Point3F(-5, 0, 0));
auto sphereRenderer = sphereEntity->addComponent<MeshRenderer>();
auto sphereMtl = std::make_shared<BlinnPhongMaterial>(_device);
std::default_random_engine e;
std::uniform_real_distribution<float> u(0, 1);
sphereMtl->setBaseColor(Color(u(e), u(e), u(e), 1));
sphereRenderer->setMesh(PrimitiveMesh::createSphere(_device, radius));
sphereRenderer->setMaterial(sphereMtl);
auto sphereCollider = sphereEntity->addComponent<physics::DynamicCollider>();
// sphereCollider->debugEntity = sphereEntity;
auto sphereColliderShape = std::make_shared<physics::SphereColliderShape>();
sphereColliderShape->setRadius(radius);
sphereColliderShape->setTrigger(true);
sphereCollider->addShape(sphereColliderShape);
sphereEntity->addComponent<CollisionScript>();
sphereEntity->addComponent<MoveScript>();
scene->play();
}
}
| 35.832
| 121
| 0.692789
|
ArcheGraphics
|
609d286c5d08e406c88e4a14a08d10e2ec7e20b5
| 902
|
hpp
|
C++
|
args/core/math/glm/ext/vector_bool1_precision.hpp
|
Algo-ryth-mix/Args-Engine
|
cc5084c5060ff071602cc9e2fdfb52791e65ca5b
|
[
"MIT"
] | null | null | null |
args/core/math/glm/ext/vector_bool1_precision.hpp
|
Algo-ryth-mix/Args-Engine
|
cc5084c5060ff071602cc9e2fdfb52791e65ca5b
|
[
"MIT"
] | null | null | null |
args/core/math/glm/ext/vector_bool1_precision.hpp
|
Algo-ryth-mix/Args-Engine
|
cc5084c5060ff071602cc9e2fdfb52791e65ca5b
|
[
"MIT"
] | null | null | null |
/// @ref ext_vector_bool1_precision
/// @file glm/ext/vector_bool1_precision.hpp
///
/// @defgroup ext_vector_bool1_precision GLM_EXT_vector_bool1_precision
/// @ingroup ext
///
/// Exposes highp_bvec1, mediump_bvec1 and lowp_bvec1 types.
///
/// Include <glm/ext/vector_bool1_precision.hpp> to use the features of this extension.
#pragma once
#include "../detail/type_vec1.hpp"
#if GLM_MESSAGES == GLM_ENABLE && !defined(GLM_EXT_INCLUDED)
# pragma message("GLM: GLM_EXT_vector_bool1_precision extension included")
#endif
namespace args::core::math
{
/// @addtogroup ext_vector_bool1_precision
/// @{
/// 1 component vector of bool values.
typedef vec<1, bool, highp> highp_bvec1;
/// 1 component vector of bool values.
typedef vec<1, bool, mediump> mediump_bvec1;
/// 1 component vector of bool values.
typedef vec<1, bool, lowp> lowp_bvec1;
/// @}
}//namespace args::core::math
| 25.771429
| 87
| 0.735033
|
Algo-ryth-mix
|
609ef720231474288fad06a275d670042525852c
| 491
|
cpp
|
C++
|
cpp/BinaryIndexedTree.cpp
|
cupro29/cupro-library
|
00dff012373d2a35b6645b6e6ff0d0a521ee9077
|
[
"MIT"
] | null | null | null |
cpp/BinaryIndexedTree.cpp
|
cupro29/cupro-library
|
00dff012373d2a35b6645b6e6ff0d0a521ee9077
|
[
"MIT"
] | null | null | null |
cpp/BinaryIndexedTree.cpp
|
cupro29/cupro-library
|
00dff012373d2a35b6645b6e6ff0d0a521ee9077
|
[
"MIT"
] | null | null | null |
#include <vector>
template <class T>
struct BinaryIndexedTree {
BinaryIndexedTree(std::size_t n) : sz(n), d(sz) {}
void add(std::size_t p, T x) {
p++;
while (p <= sz) {
d[p - 1] += x;
p += p & -p;
}
}
T range(std::size_t l, std::size_t r) const { return sum(r) - sum(l); }
T sum(std::size_t r) const {
T res = 0;
while (r > 0) {
res += d[r - 1];
r -= r & -r;
}
return res;
}
private:
std::size_t sz;
std::vector<T> d;
};
| 18.884615
| 73
| 0.490835
|
cupro29
|
60a55873df44e519e8397baf41bcd3bc86de530c
| 18,788
|
cpp
|
C++
|
src/phi_BLR.cpp
|
rchan26/hierarchicalFusion
|
20cb965526b47ae8f0373bdbdcbdb76d99ab8618
|
[
"CC-BY-4.0"
] | 1
|
2021-09-27T15:32:50.000Z
|
2021-09-27T15:32:50.000Z
|
src/phi_BLR.cpp
|
rchan26/hierarchicalFusion
|
20cb965526b47ae8f0373bdbdcbdb76d99ab8618
|
[
"CC-BY-4.0"
] | null | null | null |
src/phi_BLR.cpp
|
rchan26/hierarchicalFusion
|
20cb965526b47ae8f0373bdbdcbdb76d99ab8618
|
[
"CC-BY-4.0"
] | 1
|
2021-12-09T03:22:51.000Z
|
2021-12-09T03:22:51.000Z
|
#include "../inc/helper_functions.hpp"
#include "../inc/phi_BLR.hpp"
using namespace Rcpp;
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::export]]
arma::vec log_BLR_gradient(const arma::vec &beta,
const arma::vec &y_labels,
const arma::mat &X,
const arma::vec &X_beta,
const arma::vec &count,
const arma::vec &prior_means,
const arma::vec &prior_variances,
const double &C) {
arma::vec gradient(beta.size(), arma::fill::zeros);
for (int k=0; k < X.n_cols; ++k) {
for (int i=0; i < X.n_rows; ++i) {
gradient.at(k) += count.at(i)*X.at(i,k)*(y_labels.at(i)-(1/(1+exp(-X_beta.at(i)))));
}
gradient.at(k) -= (beta.at(k)-prior_means.at(k))/(C*prior_variances.at(k));
}
return(gradient);
}
// [[Rcpp::export]]
arma::mat log_BLR_hessian(const arma::mat &X,
const arma::vec &X_beta,
const arma::vec &count,
const arma::vec &prior_variances,
const double &C) {
arma::mat hessian(X.n_cols, X.n_cols, arma::fill::zeros);
for (int i=0; i < X.n_rows; ++i) {
const double exp_X_beta = exp(X_beta.at(i));
const double ratio = exp_X_beta/((1+exp_X_beta)*(1+exp_X_beta));
for (int j=0; j < X.n_cols; ++j) {
for (int k=0; k <= j; ++k) {
hessian.at(j,k) -= count.at(i)*X.at(i,j)*X.at(i,k)*ratio;
}
}
}
for (int j=0; j < X.n_cols; ++j) {
hessian.at(j,j) -= 1/(C*prior_variances.at(j));
for (int k=0; k < j; ++k) {
hessian.at(k,j) = hessian.at(j,k);
}
}
return(hessian);
}
// [[Rcpp::export]]
Rcpp::List ea_phi_BLR_DL_vec(const arma::vec &beta,
const arma::vec &y_labels,
const arma::mat &X,
const arma::vec &count,
const arma::vec &prior_means,
const arma::vec &prior_variances,
const double &C,
const arma::mat &precondition_mat) {
const arma::vec X_beta = X * beta;
const arma::vec gradient = log_BLR_gradient(beta,
y_labels,
X,
X_beta,
count,
prior_means,
prior_variances,
C);
const double t1 = as_scalar((arma::trans(gradient)*precondition_mat)*gradient);
const arma::mat hessian = log_BLR_hessian(X, X_beta, count, prior_variances, C);
const double t2 = arma::trace(precondition_mat*hessian);
return(Rcpp::List::create(Named("phi", 0.5*(t1+t2)),
Named("t1", t1),
Named("t2", t2)));
}
// [[Rcpp::export]]
Rcpp::List ea_phi_BLR_DL_matrix(const arma::mat &beta,
const arma::vec &y_labels,
const arma::mat &X,
const arma::vec &count,
const arma::vec &prior_means,
const arma::vec &prior_variances,
const double &C,
const arma::mat &precondition_mat) {
Rcpp::NumericVector phi(beta.n_rows);
Rcpp::NumericVector t1(beta.n_rows);
Rcpp::NumericVector t2(beta.n_rows);
for (int i=0; i < beta.n_rows; ++i) {
Rcpp::List phi_eval = ea_phi_BLR_DL_vec(arma::trans(beta.row(i)),
y_labels,
X,
count,
prior_means,
prior_variances,
C,
precondition_mat);
phi[i] = phi_eval["phi"];
t1[i] = phi_eval["t1"];
t2[i] = phi_eval["t2"];
}
return(Rcpp::List::create(Rcpp::Named("phi", phi),
Rcpp::Named("t1", t1),
Rcpp::Named("t2", t2)));
}
// [[Rcpp::export]]
double spectral_radius_BLR(const arma::vec &beta,
const int &dim,
const arma::mat &X,
const arma::vec &count,
const arma::vec &prior_variances,
const double &C,
const arma::mat &Lambda) {
const arma::vec X_beta = X * beta;
// arma::mat hessian(dim, dim, arma::fill::zeros);
// for (int i=0; i < X.n_rows; ++i) {
// const double exp_X_beta = exp(X_beta.at(i));
// const double ratio = exp_X_beta/((1+exp_X_beta)*(1+exp_X_beta));
// for (int j=0; j < dim; ++j) {
// for (int k=0; k <= j; ++k) {
// hessian.at(j,k) -= count.at(i)*X.at(i,j)*X.at(i,k)*ratio;
// }
// }
// }
// for (int j=0; j < dim; ++j) {
// hessian.at(j,j) -= 1/(C*prior_variances.at(j));
// for (int k=0; k < j; ++k) {
// hessian.at(k,j) = hessian.at(j,k);
// }
// }
return(spectral_radius(Lambda * log_BLR_hessian(X,
X_beta,
count,
prior_variances,
C)));
}
// [[Rcpp::export]]
Rcpp::List obtain_hypercube_centre_BLR(const Rcpp::List &bessel_layers,
const arma::mat &transform_to_X,
const arma::vec &y_labels,
const arma::mat &X,
const arma::vec &count,
const arma::vec &prior_means,
const arma::vec &prior_variances,
const double &C) {
// calculate the hypercube centre
arma::vec centre(bessel_layers.size(), arma::fill::zeros);
for (int i=0; i < bessel_layers.size(); ++i) {
const Rcpp::List &b_layer = bessel_layers[i];
const double &L = b_layer["L"];
const double &U = b_layer["U"];
centre.at(i) = 0.5*(L+U);
}
const arma::vec beta_hat = transform_to_X*centre;
// evaluate the gradient of the log posterior at the hypercube centre
const arma::vec X_beta = X * beta_hat;
return(Rcpp::List::create(Named("beta_hat", beta_hat),
Named("grad_log_hat", log_BLR_gradient(beta_hat,
y_labels,
X,
X_beta,
count,
prior_means,
prior_variances,
C))));
}
// [[Rcpp::export]]
Rcpp::List spectral_radius_bound_BLR_Z(const int &dim,
const arma::mat &V,
const arma::mat &X,
const arma::vec &count,
const arma::vec &prior_variances,
const double &C,
const arma::mat &sqrt_Lambda) {
arma::mat hessian(dim, dim, arma::fill::zeros);
// obtain the lower and upper bound on X_beta
const arma::mat transformed_X = X * sqrt_Lambda;
arma::vec products(V.n_rows, arma::fill::zeros);
for (int i=0; i < X.n_rows; ++i) {
for (int v=0; v < V.n_rows; ++v) {
products.at(v) = arma::dot(transformed_X.row(i), V.row(v));
}
// e^u/((1+e^u)^2) is largest when x is closest to 0, hence take the smaller of the bounds
const double exp_u = exp(arma::abs(products).min());
const double ratio = exp_u/((1+exp_u)*(1+exp_u));
for (int k=0; k < dim; ++k) {
for (int l=0; l <= k; ++l) {
hessian.at(k,l) -= count.at(i)*transformed_X.at(i,k)*transformed_X.at(i,l)*ratio;
}
}
}
for (int k=0; k < dim; ++k) {
for (int l=0; l <= k; ++l) {
for (int j=0; j < dim; ++j) {
hessian.at(k,l) -= sqrt_Lambda.at(j,k)*sqrt_Lambda(j,l)/(C*prior_variances.at(j));
}
if (l!=k) {
hessian.at(l,k) = hessian.at(k,l);
}
}
}
const arma::vec abs_eigen = abs_eigenvals(hessian);
return(Rcpp::List::create(Named("spectral_radius", abs_eigen.max()),
Named("abs_eigenvals", abs_eigen)));
}
// [[Rcpp::export]]
Rcpp::List spectral_radius_global_bound_BLR_Z(const int &dim,
const arma::mat &X,
const arma::vec &count,
const arma::vec &prior_variances,
const double &C,
const arma::mat &sqrt_Lambda) {
// ----- compute the matrix A = Hessian of the transformed log sub-posterior
const arma::mat transformed_X = X * sqrt_Lambda;
arma::mat hessian(dim, dim, arma::fill::zeros);
for (int i=0; i < X.n_rows; ++i) {
for (int k=0; k < dim; ++k) {
for (int l=0; l <= k; ++l) {
hessian.at(k,l) -= count.at(i)*transformed_X.at(i,k)*transformed_X.at(i,l)/4;
}
}
}
for (int k=0; k < dim; ++k) {
for (int l=0; l <= k; ++l) {
for (int j=0; j < dim; ++j) {
hessian.at(k,l) -= sqrt_Lambda.at(j,k)*sqrt_Lambda(j,l)/(C*prior_variances.at(j));
}
if (l!=k) {
hessian.at(l,k) = hessian.at(k,l);
}
}
}
const arma::vec abs_eigen = abs_eigenvals(hessian);
return(Rcpp::List::create(Named("spectral_radius", abs_eigen.max()),
Named("abs_eigenvals", abs_eigen)));
}
// [[Rcpp::export]]
Rcpp::List ea_phi_BLR_DL_bounds(const arma::vec &beta_hat,
const arma::vec &grad_log_hat,
const int &dim,
const arma::mat &X,
const arma::vec &count,
const arma::vec &prior_variances,
const double &C,
const Rcpp::List &transform_mats,
const Rcpp::List &hypercube_vertices,
const bool &local_bounds) {
const arma::mat &transform_to_X = transform_mats["to_X"];
const arma::mat &transform_to_Z = transform_mats["to_Z"];
const double vec_norm = std::sqrt(arma::sum(arma::square(transform_to_X*grad_log_hat)));
const arma::mat &vertices = hypercube_vertices["vertices"];
const double dist = maximal_distance_hypercube_to_cv(beta_hat,
vertices,
transform_to_X,
transform_to_Z);
const arma::mat &V = hypercube_vertices["V"];
Rcpp::List spectral_radius_bds;
double P_n_Lambda;
if (local_bounds) {
spectral_radius_bds = spectral_radius_bound_BLR_Z(dim,
V,
X,
count,
prior_variances,
C,
transform_to_X);
P_n_Lambda = spectral_radius_bds["spectral_radius"];
} else {
spectral_radius_bds = spectral_radius_global_bound_BLR_Z(dim,
X,
count,
prior_variances,
C,
transform_to_X);
P_n_Lambda = spectral_radius_bds["spectral_radius"];
}
return(Rcpp::List::create(Named("LB", -0.5*dim*P_n_Lambda),
Named("UB", 0.5*((vec_norm+dist*P_n_Lambda)*(vec_norm+dist*P_n_Lambda)+dim*P_n_Lambda)),
Named("dist", dist),
Named("P_n_Lambda", P_n_Lambda),
Named("t1_bds", (vec_norm+dist*P_n_Lambda)*(vec_norm+dist*P_n_Lambda)),
Named("t2_bds", dim*P_n_Lambda)));
}
// [[Rcpp::export]]
double gamma_NB_BLR(const arma::vec ×,
const double &h,
const arma::vec &x0,
const arma::vec &y,
const double &s,
const double &t,
const arma::vec &y_labels,
const arma::mat &X,
const arma::vec &count,
const arma::vec &prior_means,
const arma::vec &prior_variances,
const double &C,
const arma::mat &precondition_mat) {
if (times.size() < 2) {
stop("gamma_NB_BLR: length of times must be at least 2");
}
double sum_phi_eval = 0;
for (int i=0; i < times.size(); ++i) {
const arma::vec eval = (x0*(t-times.at(i))+y*(times.at(i)-s))/(t-s);
Rcpp::List phi = ea_phi_BLR_DL_vec(eval,
y_labels,
X,
count,
prior_means,
prior_variances,
C,
precondition_mat);
const double &phi_eval = phi["phi"];
if (i==0 || i==times.size()-1) {
sum_phi_eval += phi_eval;
} else {
sum_phi_eval += 2*phi_eval;
}
}
return(h*sum_phi_eval/2);
}
// // [[Rcpp::export]]
// double ea_phi_BLR_DL_LB(const arma::mat &X,
// const arma::vec &prior_variances,
// const double &C,
// const arma::mat &precondition_mat) {
// arma::vec design_sum(X.n_cols, arma::fill::zeros);
// double prior_variances_sum = 0;
// for (int k=0; k < X.n_cols; ++k) {
// for (int i=0; i < X.n_rows; ++i) {
// design_sum.at(k) += X.at(i,k)*X.at(i,k);
// }
// design_sum.at(k) *= precondition_mat.at(k,k);
// prior_variances_sum += precondition_mat.at(k,k)/(C*prior_variances.at(k));
// }
// double LB = -(arma::sum(design_sum)/4) - prior_variances_sum;
// return(0.5*LB);
// }
// // [[Rcpp::export]]
// arma::vec log_BLR_gradient_Z(const arma::vec &beta,
// const arma::vec &y_labels,
// const arma::vec &X_beta,
// const arma::mat &transformed_X,
// const arma::vec &prior_means,
// const arma::vec &prior_variances,
// const double &C,
// const arma::mat &sqrt_precondition_mat) {
// arma::vec gradient(beta.size(), arma::fill::zeros);
// for (int k=0; k < transformed_X.n_cols; ++k) {
// for (int i=0; i < transformed_X.n_rows; ++i) {
// gradient.at(k) += transformed_X.at(i,k)*(y_labels.at(i)-(1/(1+exp(-X_beta.at(i)))));
// }
// for (int j=0; j < transformed_X.n_cols; ++j) {
// gradient.at(k) -= (sqrt_precondition_mat.at(j,k)*(beta.at(j)-prior_means.at(j)))/(C*prior_variances.at(j));
// }
// }
// return(gradient);
// }
// // [[Rcpp::export]]
// double term2_Z(const arma::vec &X_beta,
// const arma::mat &transformed_X,
// const arma::vec &prior_variances,
// const double &C,
// const arma::mat &precondition_mat,
// const arma::mat &transform_mat) {
// double divergence = 0;
// for (int k=0; k < transformed_X.n_cols; ++k) {
// for (int i=0; i < transformed_X.n_rows; ++i) {
// const double exp_X_beta = exp(X_beta.at(i));
// const double ratio = exp_X_beta/((1+exp_X_beta)*(1+exp_X_beta));
// divergence -= transformed_X.at(i,k)*transformed_X.at(i,k)*ratio;
// }
// for (int j=0; j < transformed_X.n_cols; ++j) {
// divergence -= (transform_mat.at(j,k)*transform_mat.at(j,k))/(C*prior_variances.at(k));
// }
// }
// return(divergence);
// }
// // [[Rcpp::export]]
// double ea_phi_BLR_DL_vec_Z(const arma::vec &beta,
// const arma::vec &y_labels,
// const arma::mat &X,
// const arma::vec &prior_means,
// const arma::vec &prior_variances,
// const double &C,
// const arma::mat &precondition_mat,
// const arma::mat &transform_mat) {
// const arma::vec X_beta = X * beta;
// const arma::mat transformed_X = X * transform_mat;
// const arma::vec gradient = log_BLR_gradient_Z(beta,
// y_labels,
// X_beta,
// transformed_X,
// prior_means,
// prior_variances,
// C,
// precondition_mat,
// transform_mat);
// const double t1 = arma::dot(gradient, gradient);
// const double t2 = term2_Z(X_beta,
// transformed_X,
// prior_variances,
// C,
// precondition_mat,
// transform_mat);
// return(0.5*(t1+t2));
// }
// // [[Rcpp::export]]
// double term2_X(const arma::mat &X,
// const arma::vec &X_beta,
// const arma::vec &prior_variances,
// const double &C,
// const arma::mat &precondition_mat) {
// const arma::mat hessian = log_BLR_hessian(X, X_beta, prior_variances, C);
// return(arma::trace(precondition_mat * hessian));
// }
| 43.897196
| 116
| 0.439217
|
rchan26
|
60a6f4a7a594236c95eaef2fb9fa30362be15f51
| 1,541
|
cpp
|
C++
|
src/web_server/session/detect_session.cpp
|
X-rays5/web_server
|
c14e2c8e6e53797d2179cb5985a135e34173b3b9
|
[
"MIT"
] | 2
|
2021-09-16T03:22:45.000Z
|
2021-11-09T11:45:07.000Z
|
src/web_server/session/detect_session.cpp
|
X-rays5/web_server
|
c14e2c8e6e53797d2179cb5985a135e34173b3b9
|
[
"MIT"
] | null | null | null |
src/web_server/session/detect_session.cpp
|
X-rays5/web_server
|
c14e2c8e6e53797d2179cb5985a135e34173b3b9
|
[
"MIT"
] | null | null | null |
//
// Created by X-ray on 6/7/2021.
//
#pragma once
#include "detect_session.hpp"
namespace web_server {
namespace session {
void detect_session::run() {
// Set the timeout.
stream_.expires_after(std::chrono::seconds(30));
beast::async_detect_ssl(stream_,buffer_,beast::bind_front_handler(&detect_session::on_detect,this->shared_from_this()));
}
void detect_session::on_detect(beast::error_code ec, boost::tribool result) {
if(ec)
return utility::fail(ec, "detect");
auto config = config::Instance->GetConfig();
if(config.ssl_settings.accept_https && result)
{
std::cout << "Incoming ssl request from: " << ip_ << "\n";
// Launch SSL session
std::make_shared<ssl_http_session>(std::move(stream_), ctx_, std::move(buffer_), doc_root_)->run();
return;
}
if (config.ssl_settings.accept_http || ip_ == "127.0.0.1" || ip_ == "::1") {
std::cout << "Request incoming: " << ip_ << "\n";
// Launch plain session
std::make_shared<plain_http_session>(std::move(stream_), std::move(buffer_), doc_root_)->run();
return;
}
beast::error_code error;
stream_.socket().shutdown(tcp::socket::shutdown_send, error);
if (error)
return utility::fail(error, "shutdown");
}
} // session
} // web_server
| 35.837209
| 132
| 0.546398
|
X-rays5
|
60a9ed5121cfe67a17d8575325d5002ef0999a8d
| 909
|
hh
|
C++
|
maxutils/maxsimd/include/maxsimd/multistmt.hh
|
sdrik/MaxScale
|
c6c318b36dde0a25f22ac3fd59c9d33d774fe37a
|
[
"BSD-3-Clause"
] | null | null | null |
maxutils/maxsimd/include/maxsimd/multistmt.hh
|
sdrik/MaxScale
|
c6c318b36dde0a25f22ac3fd59c9d33d774fe37a
|
[
"BSD-3-Clause"
] | null | null | null |
maxutils/maxsimd/include/maxsimd/multistmt.hh
|
sdrik/MaxScale
|
c6c318b36dde0a25f22ac3fd59c9d33d774fe37a
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* Copyright (c) 2021 MariaDB Corporation Ab
*
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file and at www.mariadb.com/bsl11.
*
* Change Date: 2025-12-13
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2 or later of the General
* Public License.
*/
#pragma once
#include <string>
#include <vector>
namespace maxsimd
{
using Markers = std::vector<const char*>;
/**
* @brief is_multi_stmt Determine if sql contains multiple statements.
* @param sql The sql.
* @param pMarkers Optimization. Pass in the markers, which can be static
* for the caller, reused for each call to make_markers()
* @return bool true if sql contains multiple statements
*/
bool is_multi_stmt(const std::string& sql, Markers* pMarkers);
}
| 27.545455
| 79
| 0.693069
|
sdrik
|
60abec8ed980e14091921b1295712fe53d862b01
| 4,774
|
hh
|
C++
|
src/sgm/GraphScaffold.hh
|
michaelapeterka/GGL
|
99e585b773ad8f33e39160d2cbd71c00e036fa37
|
[
"MIT"
] | 20
|
2017-05-09T15:37:04.000Z
|
2021-11-24T10:51:02.000Z
|
src/sgm/GraphScaffold.hh
|
michaelapeterka/GGL
|
99e585b773ad8f33e39160d2cbd71c00e036fa37
|
[
"MIT"
] | 2
|
2017-05-24T08:00:25.000Z
|
2017-05-24T08:01:01.000Z
|
src/sgm/GraphScaffold.hh
|
michaelapeterka/GGL
|
99e585b773ad8f33e39160d2cbd71c00e036fa37
|
[
"MIT"
] | 7
|
2017-05-29T10:55:18.000Z
|
2020-12-04T14:24:51.000Z
|
#ifndef SGM_GRAPHSCAFFOLD_HH_
#define SGM_GRAPHSCAFFOLD_HH_
#include "sgm/Graph_Interface.hh"
#include "sgm/RP_Hanser96.hh"
namespace sgm {
/*!
* Computes the scaffold annotation of each node, ie. whether it is part of
* a ring, a ring linker, or a dangling end (side chain).
*
* See
* The Properties of Known Drugs. 1. Molecular Frameworks
* Guy W. Bemis and Mark A. Murcko
* J. Med. Chem. 1996, 39, 2887-2893
*
* @author Martin Mann (c) 2013 http://www.bioinf.uni-freiburg.de/~mmann/
*
*/
class GraphScaffold : public RP_Hanser96 {
public:
//! possible scaffold types of graph nodes
enum ScaffoldType {
GST_UNKNOWN, //!< nodes of this type are not processed yet
GST_RING, //!< nodes of this type are part of a ring
GST_LINKER, //!< nodes of this type are part of a ring linker
GST_DANGLING //!< nodes of this type are part of a dangling end / side chain
};
//! assignment of scaffold types for each node index
typedef std::vector< ScaffoldType > ScaffoldAnnotation;
protected:
//! the P-graph to be compressed during the ring perception
using RP_Hanser96::pGraph;
//! the index access for pGraph
using RP_Hanser96::pGraphIndex;
//! the edge label access for pGraph, i.e. the according RingList
using RP_Hanser96::pGraphPath;
//! the degree of each node in pGraph
using RP_Hanser96::pGraphDegree;
//! the nodes to be removed during the ring perception from pGraph
using RP_Hanser96::toRemove;
public:
//! construction
GraphScaffold();
//! destruction
virtual ~GraphScaffold();
/*!
* Identifies the scaffold type for each node in the graph and returns
* the according scaffold annotation.
*
* @param graph the graph to annotate
* @param maxRingSize the maximal size of rings to consider
* @return the scaffold type for each node within the graph, ie. the
* container has as many entries as the graph nodes.
*/
ScaffoldAnnotation
getScaffoldAnnotation( const Graph_Interface & graph
, const size_t maxRingSize = std::numeric_limits<size_t>::max() );
/*!
* Identifies the scaffold type for each node in the graph and returns
* the according scaffold annotation.
*
* @param graph the graph to annotate
* @param reporter the ring reporter to forward all rings to
* @param maxRingSize the maximal size of rings to consider
* @return the scaffold type for each node within the graph, ie. the
* container has as many entries as the graph nodes.
*/
ScaffoldAnnotation
getScaffoldAnnotation( const Graph_Interface & graph
, RingReporter & reporter
, const size_t maxRingSize = std::numeric_limits<size_t>::max());
protected:
/*!
* Identifies the scaffold type for each node in the graph and returns
* the according scaffold annotation.
*
* @param graph the graph to annotate
* @param reporter the ring reporter to forward all rings to (can be
* NULL such that no reporting is done)
* @param maxRingSize the maximal size of rings to consider
* @return the scaffold type for each node within the graph, ie. the
* container has as many entries as the graph nodes.
*/
ScaffoldAnnotation
getScaffoldAnnotation( const Graph_Interface & graph
, RingReporter * reporter
, const size_t maxRingSize );
/*!
* Ring reporter that stores ring annotations and forwards the
* reporting to another ring reporter if given.
*/
class RR_Annotation : public RingReporter {
protected:
//! the annotation to update with ring information
ScaffoldAnnotation & annotation;
//! the next reporter to forward the ring information to if not NULL
RingReporter * nextReporter;
public:
/*!
* Constructions
* @param annotation the annotation to update with ring information
* @param nextReporter the next reporter to forward the ring
* information to if not NULL
*/
RR_Annotation( ScaffoldAnnotation & annotation
, RingReporter * nextReporter = NULL)
: annotation(annotation)
, nextReporter(nextReporter)
{}
virtual
~RR_Annotation()
{}
/*!
* Nodes of the reported ring are accordingly annotated and the
* ring information is forwarded to the next ring reporter
* @param graph the graph that contains the ring
* @param ringList the ring to report
*/
virtual
void
reportRing( const Graph_Interface& graph, const RingList & ringList );
};
};
} // namespace sgm
#endif /* SGM_GRAPHSCAFFOLD_HH_ */
| 30.025157
| 80
| 0.665899
|
michaelapeterka
|
60ac371e8062a35b0466f650d8408c25043a8cfd
| 4,402
|
cpp
|
C++
|
epoll/epoll.cpp
|
NicoleRobin/ZYEvent
|
513380e590fad0f255490726ffaa83b652792273
|
[
"MIT"
] | null | null | null |
epoll/epoll.cpp
|
NicoleRobin/ZYEvent
|
513380e590fad0f255490726ffaa83b652792273
|
[
"MIT"
] | null | null | null |
epoll/epoll.cpp
|
NicoleRobin/ZYEvent
|
513380e590fad0f255490726ffaa83b652792273
|
[
"MIT"
] | null | null | null |
/*******************************************************************************
* File Name : epoll.cpp
* Author : zjw
* Email : emp3XzA3MjJAMTYzLmNvbQo= (base64 encode)
* Create Time : 2015年07月15日 星期三 18时33分00秒
*******************************************************************************/
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/epoll.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <fcntl.h>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <queue>
#include <map>
#include <errno.h>
using namespace std;
const int SERVER_PORT = 8080;
const int RECV_SIZE = 1024;
const int SEND_SIZE = 1040;
const int MAX_EVENTS = 1024;
typedef struct ClientInfo
{
ClientInfo()
{
bzero(&addr, sizeof(addr));
}
sockaddr_in addr;
queue<string> queueBuf;
}ClientInfo;
int main(int argc, char **argv)
{
int server = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in addrServer;
bzero(&addrServer, sizeof(addrServer));
addrServer.sin_family = AF_INET;
addrServer.sin_port = htons(SERVER_PORT);
addrServer.sin_addr.s_addr = INADDR_ANY;
if (bind(server, (struct sockaddr*)&addrServer, sizeof(addrServer)) < 0)
{
perror("bind failed!");
return -1;
}
listen(server, 5);
cout << "server listen on port:" << SERVER_PORT << " ..." << endl;
int epollFd = epoll_create(MAX_EVENTS);
if (epollFd <= 0)
{
perror("epoll_create failed,");
return -1;
}
// set non block
fcntl(server, F_SETFL, O_NONBLOCK);
struct epoll_event ev;
ev.data.fd = server;
ev.events = EPOLLIN;
// register event
if (epoll_ctl(epollFd, EPOLL_CTL_ADD, server, &ev))
{
perror("epoll_ctl failed!");
return -1;
}
struct epoll_event events[100];
int ret = 0;
char recvBuf[RECV_SIZE + 1];
char sendBuf[SEND_SIZE + 1];
int client;
map<int, struct ClientInfo> mapClientInfo;
while (1)
{
// wait epoll
ret = epoll_wait(epollFd, events, 100, 500);
// process active event
for (int i = 0; i < ret; i++)
{
if (events[i].data.fd == server)
{ // a new client connect
sockaddr_in addrClient;
socklen_t len = sizeof(addrClient);
client = accept(server, (struct sockaddr*)&addrClient, &len);
if (client < 0)
{
perror("accept failed!");
return -1;
}
cout << "accept a new client:" << inet_ntoa(addrClient.sin_addr) << endl;
fcntl(client, F_SETFL, O_NONBLOCK);
ev.data.fd = client;
ev.events = EPOLLIN | EPOLLOUT;
epoll_ctl(epollFd, EPOLL_CTL_ADD, client, &ev);
struct ClientInfo info;
info.addr = addrClient;
mapClientInfo.insert(make_pair<int, struct ClientInfo>(client, info));
}
else if (events[i].events & EPOLLIN)
{ // connectting user and sth can be read
if ((client = events[i].data.fd) < 0)
{
continue;
}
memset(recvBuf, 0, RECV_SIZE + 1);
memset(sendBuf, 0, SEND_SIZE + 1);
if ((ret = recv(client, recvBuf, RECV_SIZE, 0)) < 0)
{ // client closed
if (errno == ECONNRESET)
{
close(client);
events[i].data.fd = -1;
cout << "client[" << inet_ntoa(mapClientInfo[client].addr.sin_addr) << "] exit!" << endl;
mapClientInfo.erase(client);
}
else
{
cout << "read from client[" << "ip" << "] failed!" << endl;
}
}
else if (ret = 0)
{
close(client);
events[i].data.fd = -1;
cout << "client[" << inet_ntoa(mapClientInfo[client].addr.sin_addr) << "] exit!" << endl;
mapClientInfo.erase(client);
}
cout << "client[" << inet_ntoa(mapClientInfo[client].addr.sin_addr) << "] said:" << recvBuf;
sprintf(sendBuf, "Your said:%s", recvBuf);
mapClientInfo[client].queueBuf.push(sendBuf);
// set write event
// ev.data.fd = client;
// ev.events = EPOLLOUT;
// epoll_ctl(epollFd, EPOLL_CTL_MOD, client, &ev);
}
else if (events[i].events & EPOLLOUT)
{ // write event
client = events[i].data.fd;
if (!mapClientInfo[client].queueBuf.empty())
{
string strTemp = mapClientInfo[client].queueBuf.front();
mapClientInfo[client].queueBuf.pop();
if ((ret = send(client, strTemp.c_str(), strTemp.length(), 0) < 0))
{
perror("send failed!");
return -1;
}
}
// ev.data.fd = client;
// ev.events = EPOLLIN;
// epoll_ctl(epollFd, EPOLL_CTL_MOD, client, &ev);
}
}
}
close(server);
return 0;
}
| 25.298851
| 96
| 0.607905
|
NicoleRobin
|
60ae397d0b61ca86965216beb74482c1ffb60a96
| 618
|
cc
|
C++
|
kattis/deduplicatingfiles.cc
|
Ashindustry007/competitive-programming
|
2eabd3975c029d235abb7854569593d334acae2f
|
[
"WTFPL"
] | 506
|
2018-08-22T10:30:38.000Z
|
2022-03-31T10:01:49.000Z
|
kattis/deduplicatingfiles.cc
|
Ashindustry007/competitive-programming
|
2eabd3975c029d235abb7854569593d334acae2f
|
[
"WTFPL"
] | 13
|
2019-08-07T18:31:18.000Z
|
2020-12-15T21:54:41.000Z
|
kattis/deduplicatingfiles.cc
|
Ashindustry007/competitive-programming
|
2eabd3975c029d235abb7854569593d334acae2f
|
[
"WTFPL"
] | 234
|
2018-08-06T17:11:41.000Z
|
2022-03-26T10:56:42.000Z
|
// https://open.kattis.com/problems/deduplicatingfiles
#include<bits/stdc++.h>
using namespace std;
using vi=vector<int>;
using vs=vector<string>;
int main(){
int n;
cin>>n;
while(n){
string s;
getline(cin,s);
vi a(n);
vs b(n);
int k=0,l=n;
for(int i=0;i<n;i++){
getline(cin,b[i]);
int x=0;
for(char c:b[i])x^=c;
a[i]=x;
}
for(int i=0;i<n-1;i++){
bool ok=true;
for(int j=i+1;j<n;j++){
if(a[i]!=a[j])continue;
if(b[i]==b[j])ok=false;
else k++;
}
if(!ok)l--;
}
cout<<l<<" "<<k<<endl;
cin>>n;
}
}
| 18.176471
| 54
| 0.475728
|
Ashindustry007
|
60afa75f7666120113a558ee5fcb61816a0bf2af
| 3,643
|
cpp
|
C++
|
libs/sge_engine/src/sge_engine/windows/GameInspectorWindow.cpp
|
ongamex/SGEEngine
|
de17c10bd880e8175ea01588eeefeb70abfbc3d0
|
[
"MIT"
] | 34
|
2021-06-15T10:24:49.000Z
|
2022-03-22T19:20:23.000Z
|
libs/sge_engine/src/sge_engine/windows/GameInspectorWindow.cpp
|
ongamex/SGEEngine
|
de17c10bd880e8175ea01588eeefeb70abfbc3d0
|
[
"MIT"
] | 9
|
2021-03-04T21:34:03.000Z
|
2021-05-04T18:33:47.000Z
|
libs/sge_engine/src/sge_engine/windows/GameInspectorWindow.cpp
|
ongamex/SGEEngine
|
de17c10bd880e8175ea01588eeefeb70abfbc3d0
|
[
"MIT"
] | 2
|
2021-12-29T01:15:22.000Z
|
2022-02-01T10:53:15.000Z
|
#include "GameInspectorWindow.h"
#include "IconsForkAwesome/IconsForkAwesome.h"
#include "sge_core/SGEImGui.h"
#include "sge_engine/EngineGlobal.h"
#include "sge_engine/GameInspector.h"
#include "sge_engine/GameWorld.h"
#include "sge_engine/traits/TraitCamera.h"
#include "sge_utils/sge_utils.h"
#include "sge_utils/utils/strings.h"
namespace sge {
void GameInspectorWindow::update(SGEContext* const UNUSED(sgecon), GameInspector* inspector, const InputState& UNUSED(is)) {
if (isClosed()) {
return;
}
if (ImGui::Begin(m_windowName.c_str(), &m_isOpened)) {
GameWorld* world = inspector->getWorld();
if (ImGui::Button("Undo")) {
inspector->undoCommand();
}
ImGui::SameLine();
if (ImGui::Button("Redo")) {
inspector->redoCommand();
}
ImGui::SameLine();
ImGui::Spacing();
ImGui::SameLine();
if (ImGui::Button("Delete") && inspector->hasSelection()) {
inspector->deleteSelection(false);
}
if (ImGui::Button("Delete Hierarchy") && inspector->hasSelection()) {
inspector->deleteSelection(true);
}
if (ImGui::CollapsingHeader(ICON_FK_CODE " Game World Scripts")) {
std::string label;
std::string currentObjectName;
int indexToDelete = -1;
for (int t = 0; t < int(world->m_scriptObjects.size()); ++t) {
GameObject* const go = world->getObjectById(world->m_scriptObjects[t]);
if (go) {
currentObjectName = go->getDisplayName();
} else {
currentObjectName = "<not-assigned-object>";
}
ImGui::PushID(t);
string_format(label, "Object %d", t);
ImGuiEx::Label(label.c_str(), false);
if (ImGuiEx::InputText("##ObjectName", currentObjectName)) {
GameObject* newObj = world->getObjectByName(currentObjectName.c_str());
if (newObj) {
world->m_scriptObjects[t] = newObj->getId();
}
}
if (ImGui::Button(ICON_FK_EYEDROPPER)) {
auto& selection = inspector->getSelection();
if (selection.size() >= 1) {
GameObject* newObj = world->getObjectById(selection[0].objectId);
if (newObj) {
world->m_scriptObjects[t] = newObj->getId();
}
}
}
ImGui::SameLine();
if (ImGui::Button(ICON_FK_TRASH)) {
indexToDelete = t;
}
ImGui::PopID();
}
if (indexToDelete >= 0) {
world->m_scriptObjects.erase(world->m_scriptObjects.begin() + indexToDelete);
}
if (ImGui::Button(ICON_FK_PLUS " Add")) {
world->m_scriptObjects.push_back(ObjectId());
}
}
// History.
if (ImGui::CollapsingHeader("History")) {
auto commandsNamesGetter = [](void* data, int idx, const char** text) -> bool {
GameInspector* const inspector = (GameInspector*)data;
static std::string commandText;
int const backwardsIdx = int(inspector->m_commandHistory.size()) - idx - 1;
if (backwardsIdx >= 0 && backwardsIdx < int(inspector->m_commandHistory.size())) {
inspector->m_commandHistory[backwardsIdx]->getText(commandText);
*text = commandText.c_str();
return false;
}
return true;
};
// Display a list of all commands.
int curr = 0;
ImGui::ListBox("Cmd History", &curr, commandsNamesGetter, &inspector, inspector->m_lastExecutedCommandIdx + 1, 5);
}
// Stepping.
ImGui::Separator();
{
ImGui::Checkbox("No Auto Step", &inspector->m_disableAutoStepping);
inspector->m_stepOnce = false;
if (ImGui::Button("Step Once")) {
inspector->m_disableAutoStepping = true;
inspector->m_stepOnce = true;
}
ImGui::Text("Steps taken %d", inspector->m_world->totalStepsTaken);
}
ImGui::InputInt("MS Delay", &inspector->getWorld()->debug.forceSleepMs, 1, 10);
}
ImGui::End();
}
} // namespace sge
| 26.985185
| 124
| 0.659347
|
ongamex
|
60b1fde68d5e427ac7b5cd86df4dc6f82d0a4ea8
| 54,892
|
cc
|
C++
|
hyperion/Table.cc
|
mpokorny/legms
|
8ea5d1899ac5e2658ebe481b706430474685bb2d
|
[
"Apache-2.0"
] | 2
|
2021-02-03T00:40:55.000Z
|
2021-02-03T13:30:31.000Z
|
hyperion/Table.cc
|
mpokorny/legms
|
8ea5d1899ac5e2658ebe481b706430474685bb2d
|
[
"Apache-2.0"
] | null | null | null |
hyperion/Table.cc
|
mpokorny/legms
|
8ea5d1899ac5e2658ebe481b706430474685bb2d
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright 2020 Associated Universities, Inc. Washington DC, USA.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <hyperion/hyperion.h>
#include <hyperion/Table.h>
#include <hyperion/PhysicalTable.h>
#include <hyperion/TableMapper.h>
#include <mappers/default_mapper.h>
#include <map>
#include <unordered_set>
using namespace hyperion;
using namespace Legion;
template <size_t N>
std::array<std::tuple<hyperion::string, Column>, N>
to_columns_array(const std::unordered_map<std::string, Column>& cols) {
std::array<std::tuple<hyperion::string, Column>, N> result;
assert(cols.size() < N);
size_t i = 0;
for (auto& nm_col : cols)
result[i++] = nm_col;
if (i < N)
std::get<0>(result[i]) = "";
return result;
}
template <size_t N>
std::unordered_map<std::string, Column>
from_columns_array(
const std::array<std::tuple<hyperion::string, Column>, N>& ary) {
std::unordered_map<std::string, Column> result;
for (size_t i = 0; i < N && std::get<0>(ary[i]).size() > 0; ++i) {
#if HAVE_CXX17
auto& [nm, col] = ary[i];
#else // !HAVE_CXX17
auto& nm = std::get<0>(ary[i]);
auto& col = std::get<1>(ary[i]);
#endif // HAVE_CXX17
result[nm] = col;
}
return result;
}
size_t
Table::add_columns_result_t::legion_buffer_size(void) const {
size_t result = sizeof(unsigned);
for (size_t i = 0; i < cols.size(); ++i) {
#if HAVE_CXX17
auto& [nm, col] = cols[i];
#else // !HAVE_CXX17
auto& nm = std::get<0>(cols[i]);
auto& col = std::get<1>(cols[i]);
#endif // HAVE_CXX17
result += (nm.size() + 1) * sizeof(char) + sizeof(col);
}
return result;
}
size_t
Table::add_columns_result_t::legion_serialize(void* buffer) const {
char* b = static_cast<char*>(buffer);
*reinterpret_cast<unsigned*>(b) = (unsigned)cols.size();
b += sizeof(unsigned);
for (size_t i = 0; i < cols.size(); ++i) {
#if HAVE_CXX17
auto& [nm, col] = cols[i];
#else // !HAVE_CXX17
auto& nm = std::get<0>(cols[i]);
auto& col = std::get<1>(cols[i]);
#endif // HAVE_CXX17
std::strcpy(b, nm.c_str());
b += (nm.size() + 1) * sizeof(char);
*reinterpret_cast<Column*>(b) = col;
b += sizeof(col);
}
return b - static_cast<char*>(buffer);
}
size_t
Table::add_columns_result_t::legion_deserialize(const void* buffer) {
const char* b = static_cast<const char*>(buffer);
unsigned n = *reinterpret_cast<const unsigned*>(b);
b += sizeof(n);
cols.resize(n);
for (size_t i = 0; i < n; ++i) {
#if HAVE_CXX17
auto& [nm, col] = cols[i];
#else // !HAVE_CXX17
auto& nm = std::get<0>(cols[i]);
auto& col = std::get<1>(cols[i]);
#endif // HAVE_CXX17
nm = std::string(b);
b += (nm.size() + 1) * sizeof(char);
col = *reinterpret_cast<const Column*>(b);
b += sizeof(col);
}
return b - static_cast<const char*>(buffer);
}
Table::Table(
Runtime* rt,
ColumnSpace&& index_col_cs,
const LogicalRegion& index_col_region,
const std::unordered_map<std::string, Column>& columns)
: m_index_col_cs(index_col_cs)
, m_index_col_region(index_col_region)
, m_index_col_parent(index_col_region)
, m_columns(columns) {
assert(m_index_col_cs.column_is == m_index_col_region.get_index_space());
}
Table::Table(const Table& other)
: m_index_col_cs(other.m_index_col_cs)
, m_index_col_region(other.m_index_col_region)
, m_index_col_parent(other.m_index_col_parent)
, m_columns(other.m_columns) {}
Table::Table(Table&& other)
: m_index_col_cs(other.m_index_col_cs)
, m_index_col_region(other.m_index_col_region)
, m_index_col_parent(other.m_index_col_parent)
, m_columns(std::move(other).m_columns) {}
Table&
Table::operator=(const Table& rhs) {
Table tmp(rhs);
m_index_col_cs = tmp.m_index_col_cs;
m_index_col_region = tmp.m_index_col_region;
m_index_col_parent = tmp.m_index_col_parent;
m_columns = tmp.m_columns;
return *this;
}
Table&
Table::operator=(Table&& rhs) {
m_index_col_cs = std::move(rhs).m_index_col_cs;
m_index_col_region = std::move(rhs).m_index_col_region;
m_index_col_parent = std::move(rhs).m_index_col_parent;
m_columns = std::move(rhs).m_columns;
return *this;
}
PhysicalTable
Table::attach_columns(
Context ctx,
Runtime* rt,
const CXX_FILESYSTEM_NAMESPACE::path& file_path,
const std::unordered_map<std::string, std::string>& column_paths,
const std::unordered_map<std::string, std::tuple<bool, bool, bool>>&
column_modes) const {
std::unordered_set<std::string> colnames;
for (auto& nm_pth : column_paths) {
auto& nm = std::get<0>(nm_pth);
if (column_modes.count(nm) > 0)
colnames.insert(nm);
}
std::map<std::string, CXX_OPTIONAL_NAMESPACE::optional<Column::Requirements>>
omitted;
for (auto& nm_col : m_columns) {
auto& nm = std::get<0>(nm_col);
if (colnames.count(nm) == 0)
omitted[nm] = CXX_OPTIONAL_NAMESPACE::nullopt;
}
#if HAVE_CXX17
auto [table_reqs, table_parts, table_desc] =
requirements(ctx, rt, ColumnSpacePartition(), omitted);
#else // !HAVE_CXX17
auto reqs = requirements(ctx, rt, ColumnSpacePartition(), omitted);
auto& table_reqs = std::get<0>(reqs);
auto& table_parts = std::get<1>(reqs);
#endif // HAVE_CXX17
PhysicalRegion index_col_md = rt->map_region(ctx, table_reqs[0]);
std::string axes_uid = ColumnSpace::axes_uid(index_col_md);
std::vector<int> index_axes =
ColumnSpace::from_axis_vector(ColumnSpace::axes(index_col_md));
unsigned idx_rank = static_cast<unsigned>(index_axes.size());
std::tuple<LogicalRegion, PhysicalRegion> index_col =
{table_reqs[1].region, rt->map_region(ctx, table_reqs[1])};
std::unordered_map<std::string, std::shared_ptr<PhysicalColumn>> pcols;
for (auto& nm_col : m_columns) {
#if HAVE_CXX17
auto& [nm, col] = nm_col;
#else // !HAVE_CXX17
auto& nm = std::get<0>(nm_col);
auto& col = std::get<1>(nm_col);
#endif // HAVE_CXX17
CXX_OPTIONAL_NAMESPACE::optional<PhysicalRegion> metadata;
if (colnames.count(nm) > 0) {
if (!metadata) {
auto req = col.cs.requirements(READ_ONLY, EXCLUSIVE);
metadata = rt->map_region(ctx, req);
}
CXX_OPTIONAL_NAMESPACE::optional<Keywords::pair<Legion::PhysicalRegion>>
kws;
if (!col.kw.is_empty()) {
auto nkw = col.kw.size(rt);
std::vector<FieldID> fids(nkw);
std::iota(fids.begin(), fids.end(), 0);
auto rqs = col.kw.requirements(rt, fids, READ_ONLY, true).value();
Keywords::pair<Legion::PhysicalRegion> kwprs;
kwprs.type_tags = rt->map_region(ctx, rqs.type_tags);
kwprs.values = rt->map_region(ctx, rqs.values);
kws = kwprs;
}
#ifdef HYPERION_USE_CASACORE
CXX_OPTIONAL_NAMESPACE::optional<MeasRef::DataRegions> mr_drs;
if (!col.mr.is_empty()) {
auto rqs = col.mr.requirements(READ_ONLY, true);
MeasRef::DataRegions prs;
prs.metadata = rt->map_region(ctx, std::get<0>(rqs));
prs.values = rt->map_region(ctx, std::get<1>(rqs));
if (std::get<2>(rqs))
prs.index = rt->map_region(ctx, std::get<2>(rqs).value());
mr_drs = prs;
}
#endif
pcols[nm] =
std::make_shared<PhysicalColumn>(
rt,
col.dt,
col.fid,
idx_rank,
metadata.value(),
col.region,
col.region,
CXX_OPTIONAL_NAMESPACE::nullopt,
kws
#ifdef HYPERION_USE_CASACORE
, mr_drs
, map(
col.rc,
[](const auto& n) {
return
std::make_tuple(
std::string(n),
std::shared_ptr<PhysicalColumn>());
})
#endif
);
}
}
#ifdef HYPERION_USE_CASACORE
// Add pointers to reference columns. This should fail if the reference
// column was left out of the arguments. FIXME!
for (auto& nm_pc : pcols) {
auto& pc = std::get<1>(nm_pc);
if (pc->refcol()) {
auto& rcnm = std::get<0>(pc->refcol().value());
pc->set_refcol(rcnm, pcols.at(rcnm));
}
}
#endif
PhysicalTable result(
axes_uid,
index_axes,
index_col_md,
index_col,
table_reqs[1].parent,
pcols);
result.attach_columns(ctx, rt, file_path, column_paths, column_modes);
for (auto& p : table_parts)
p.destroy(ctx, rt);
return result;
}
PhysicalTable
Table::map_inline(
Context ctx,
Runtime* rt,
const std::map<
std::string,
CXX_OPTIONAL_NAMESPACE::optional<Column::Requirements>>&
column_requirements,
const CXX_OPTIONAL_NAMESPACE::optional<Column::Requirements>&
default_column_requirements) const {
auto reqs =
requirements(
ctx,
rt,
ColumnSpacePartition(),
column_requirements,
default_column_requirements);
#if HAVE_CXX17
auto& [treqs, tparts, tdesc] = reqs;
#else
auto& treqs = std::get<0>(reqs);
auto& tdesc = std::get<2>(reqs);
#endif
std::vector<PhysicalRegion> tprs;
for (auto& tr : treqs)
tprs.push_back(rt->map_region(ctx, tr));
return
std::get<0>(
PhysicalTable::create(
rt,
tdesc,
treqs.begin(),
treqs.end(),
tprs.begin(),
tprs.end())
.value());
}
Table
Table::create(
Context ctx,
Runtime* rt,
ColumnSpace&& index_col_cs,
fields_t&& fields) {
size_t num_cols = 0;
for (auto& cs_tfs : fields) {
#if HAVE_CXX17
auto& [cs, tfs] = cs_tfs;
#else // !HAVE_CXX17
auto& cs = std::get<0>(cs_tfs);
auto& tfs = std::get<1>(cs_tfs);
#endif // HAVE_CXX17
assert(!cs.is_empty());
assert(cs.is_valid());
num_cols += tfs.size();
}
{
std::unordered_set<std::string> cnames;
for (auto& cs_nm_tfs : fields)
for (auto& nm_tf : std::get<1>(cs_nm_tfs))
cnames.insert(std::get<0>(nm_tf));
assert(cnames.count("") == 0);
assert(cnames.size() == num_cols);
}
std::vector<PhysicalRegion> cs_md_prs;
for (auto& cs_tfs : fields) {
cs_md_prs.push_back(
rt->map_region(
ctx,
std::get<0>(cs_tfs).requirements(READ_ONLY, EXCLUSIVE)));
}
// Create the table index column
LogicalRegion index_col_region;
{
FieldSpace fs = rt->create_field_space(ctx);
FieldAllocator fa = rt->create_field_allocator(ctx, fs);
fa.allocate_field(
sizeof(DataType<Table::m_index_col_dt>::ValueType),
Table::m_index_col_fid);
rt->attach_name(fs, Table::m_index_col_fid, "Table::index_column_flag");
index_col_region =
rt->create_logical_region(ctx, index_col_cs.column_is, fs);
}
std::unordered_map<std::string, Column> added;
{
std::vector<
std::tuple<
ColumnSpace,
size_t,
std::vector<std::pair<hyperion::string, TableField>>>>
hcols;
for (size_t i = 0; i < fields.size(); ++i) {
#if HAVE_CXX17
auto& [cs, nm_tfs] = fields[i];
#else // !HAVE_CXX17
auto& cs = std::get<0>(fields[i]);
auto& nm_tfs = std::get<1>(fields[i]);
#endif // HAVE_CXX17
std::vector<std::pair<hyperion::string, TableField>> htfs;
for (auto& nm_tf: nm_tfs)
htfs.emplace_back(std::get<0>(nm_tf), std::get<1>(nm_tf));
hcols.emplace_back(cs, i, htfs);
}
auto index_col_md =
rt->map_region(ctx, index_col_cs.requirements(READ_ONLY, EXCLUSIVE));
auto ixax =
ColumnSpace::from_axis_vector(ColumnSpace::axes(index_col_md));
for (auto& pr : cs_md_prs) {
const ColumnSpace::IndexFlagAccessor<READ_ONLY>
ifl(pr, ColumnSpace::INDEX_FLAG_FID);
if (ifl[0]) {
const ColumnSpace::AxisVectorAccessor<READ_ONLY>
av(pr, ColumnSpace::AXIS_VECTOR_FID);
if (ColumnSpace::size(av[0]) != 1) {
// FIXME: log warning: index columns must have exactly one axis
assert(false);
// FIXME: clean up
return Table();
}
auto i = std::find(ixax.begin(), ixax.end(), av[0][0]);
if (i == ixax.end()) {
// FIXME: log warning: index columns must appear in table index
assert(false);
// FIXME: clean up
return Table();
}
ixax.erase(i);
}
}
if (ixax.size() > 1 || (ixax.size() == 1 && ixax[0] != 0)) {
// FIXME: log warning: table index names missing index column
assert(false);
// FIXME: clean up
return Table();
}
added =
add_columns(
ctx,
rt,
std::move(hcols),
{{}},
cs_md_prs,
{index_col_cs.column_is, index_col_md});
for (auto& pr : cs_md_prs)
rt->unmap_region(ctx, pr);
}
return Table(rt, std::move(index_col_cs), index_col_region, added);
}
ColumnSpace
Table::index_column_space(Context ctx, Runtime* rt) const {
// don't return ColumnSpace of index_col -- we don't want external copies,
// especially in (real) Columns
return m_index_col_cs.clone(ctx, rt);
}
bool
Table::is_empty() const {
return m_index_col_cs.is_empty();
}
std::tuple<
std::vector<RegionRequirement>,
std::vector<ColumnSpacePartition>,
Table::Desc>
Table::requirements(
Context ctx,
Runtime* rt,
const ColumnSpacePartition& table_partition,
const std::map<
std::string,
CXX_OPTIONAL_NAMESPACE::optional<Column::Requirements>>&
column_requirements,
const CXX_OPTIONAL_NAMESPACE::optional<Column::Requirements>&
default_column_requirements) const {
return
Table::requirements(
ctx,
rt,
m_index_col_cs,
m_index_col_region,
m_index_col_parent,
m_columns,
table_partition,
column_requirements,
default_column_requirements);
}
std::tuple<std::vector<Legion::RegionRequirement>, Table::Desc>
Table::requirements() const {
auto reqs =
Table::requirements(
CXX_OPTIONAL_NAMESPACE::nullopt,
CXX_OPTIONAL_NAMESPACE::nullopt,
m_index_col_cs,
m_index_col_region,
m_index_col_parent,
m_columns,
ColumnSpacePartition(),
{},
Column::default_requirements);
#if HAVE_CXX17
auto& [treqs, tparts, tdesc] = reqs;
#else // !HAVE_CXX17
auto& treqs = std::get<0>(reqs);
auto& tdesc = std::get<2>(reqs);
#endif // HAVE_CXX17
return {treqs, tdesc};
}
std::tuple<
std::vector<RegionRequirement>,
std::vector<ColumnSpacePartition>,
Table::Desc>
Table::requirements(
CXX_OPTIONAL_NAMESPACE::optional<Context> ctx,
CXX_OPTIONAL_NAMESPACE::optional<Runtime*> rt,
const ColumnSpace& index_col_cs,
const LogicalRegion& index_col_region,
const LogicalRegion& index_col_parent,
const std::unordered_map<std::string, Column>& columns,
const ColumnSpacePartition& table_partition,
const std::map<
std::string,
CXX_OPTIONAL_NAMESPACE::optional<Column::Requirements>>&
column_requirements,
const CXX_OPTIONAL_NAMESPACE::optional<Column::Requirements>&
default_column_requirements) {
assert(!table_partition.is_valid() || (ctx && rt));
// collect requirement parameters for each column
std::map<std::string, Column::Requirements> column_reqs;
{
#ifdef HYPERION_USE_CASACORE
std::map<std::string, Column::Requirements> mrc_reqs;
#endif
std::map<LogicalRegion, Column::Req> lr_mdreqs;
for (auto& nm_col : columns) {
#if HAVE_CXX17
auto& [nm, col] = nm_col;
#else // !HAVE_CXX17
auto& nm = std::get<0>(nm_col);
auto& col = std::get<1>(nm_col);
#endif // HAVE_CXX17
if ((default_column_requirements
&& (column_requirements.count(nm) == 0
|| column_requirements.at(nm)))
|| (!default_column_requirements
&& (column_requirements.count(nm) > 0
&& column_requirements.at(nm)))) {
Column::Requirements colreqs =
default_column_requirements.value_or(Column::default_requirements);
if (column_requirements.count(nm) > 0)
colreqs = column_requirements.at(nm).value();
column_reqs[nm] = colreqs;
if (lr_mdreqs.count(col.region) == 0) {
lr_mdreqs[col.region] = colreqs.column_space;
} else {
// FIXME: log a warning, and return empty result;
// warning: inconsistent requirements on shared Column metadata
// regions
assert(lr_mdreqs[col.region] == colreqs.column_space);
}
#ifdef HYPERION_USE_CASACORE
if (col.rc)
mrc_reqs[col.rc.value()] = colreqs;
#endif
}
}
#ifdef HYPERION_USE_CASACORE
// apply mode of value column to its measure reference column
#if HAVE_CXX17
for (auto& [nm, rq] : mrc_reqs)
column_reqs.at(nm) = rq;
#else // !HAVE_CXX17
for (auto& nm_rq : mrc_reqs)
column_reqs.at(std::get<0>(nm_rq)) = std::get<1>(nm_rq);
#endif // HAVE_CXX17
#endif
}
// create requirements, applying table_partition as needed
std::multimap<
ColumnSpace,
std::tuple<ColumnSpacePartition, ProjectionID, LogicalPartition, bool>>
partitions;
if (table_partition.is_valid()) {
if (table_partition.column_space.column_is
!= index_col_region.get_index_space()) {
auto csp =
table_partition.project_onto(ctx.value(), rt.value(), index_col_cs)
.get_result<ColumnSpacePartition>();
auto lp =
rt.value()
->get_logical_partition(ctx.value(), index_col_region, csp.column_ip);
partitions.insert({index_col_cs, {csp, 0, lp, true}});
} else {
auto lp =
rt.value()
->get_logical_partition(
ctx.value(),
index_col_region,
table_partition.column_ip);
// set boolean flag to false to indicate that this partition should not be
// returned in list of ColumnSpacePartitions
partitions.insert({index_col_cs, {table_partition, 0, lp, false}});
}
}
// boolean elements in value of following maps is used to track whether the
// requirement has already been added when iterating through columns
std::map<LogicalRegion, std::tuple<bool, RegionRequirement>> md_reqs;
std::map<
std::tuple<
LogicalRegion,
PrivilegeMode,
CoherenceProperty,
MappingTagID,
LogicalPartition>,
std::tuple<bool, RegionRequirement>> val_reqs;
for (auto& nm_col : columns) {
#if HAVE_CXX17
auto& [nm, col] = nm_col;
#else // !HAVE_CXX17
auto& nm = std::get<0>(nm_col);
auto& col = std::get<1>(nm_col);
#endif // HAVE_CXX17
if (column_reqs.count(nm) > 0) {
auto& reqs = column_reqs.at(nm);
if (md_reqs.count(col.region) == 0)
md_reqs[col.region] =
{false,
col.cs.requirements(
reqs.column_space.privilege,
reqs.column_space.coherence)};
decltype(val_reqs)::key_type rg_rq =
{col.region,
reqs.values.privilege,
reqs.values.coherence,
reqs.tag,
reqs.partition};
if (val_reqs.count(rg_rq) == 0) {
if (!table_partition.is_valid()
&& reqs.partition == LogicalPartition::NO_PART) {
// no column partition case
val_reqs[rg_rq] =
{false,
RegionRequirement(
col.region,
reqs.values.privilege,
reqs.values.coherence,
col.region,
reqs.tag)};
} else {
// Need a column partition; either it's provided or it's derived from
// table_partition. First look for existing record of this partition
LogicalPartition lp = LogicalPartition::NO_PART;
CXX_OPTIONAL_NAMESPACE::optional<ProjectionID> pjid;
for (auto p = partitions.lower_bound(col.cs);
(lp == LogicalPartition::NO_PART
&& p != partitions.upper_bound(col.cs));
++p) {
#if HAVE_CXX17
auto& [pcsp, pid, plp, pnew] = std::get<1>(*p);
#else
auto& pid = std::get<1>(std::get<1>(*p));
auto& plp = std::get<2>(std::get<1>(*p));
#endif
if (reqs.partition != LogicalPartition::NO_PART) {
// when a partition is provided, we use it
if (plp == reqs.partition && pid == reqs.projection) {
lp = plp;
pjid = pid;
}
} else if (pid == reqs.projection) {
// when a partition is not provided, use the induced table
// partition
assert(table_partition.is_valid());
lp = plp;
pjid = pid;
}
}
if (lp == LogicalPartition::NO_PART) {
// no record of this partition exists, create one (and if needed,
// create the partition as well)
ColumnSpacePartition csp;
bool new_csp;
if (reqs.partition != LogicalPartition::NO_PART) {
lp = reqs.partition;
csp = ColumnSpacePartition();
new_csp = false;
pjid = reqs.projection;
} else {
assert(table_partition.is_valid());
// use an induced (projected) table partition
csp =
table_partition.project_onto(ctx.value(), rt.value(), col.cs)
.get_result<ColumnSpacePartition>();
lp =
rt.value()
->get_logical_partition(ctx.value(), col.region, csp.column_ip);
new_csp = true;
pjid = reqs.projection;
}
// record this partition
partitions.insert({col.cs, {csp, pjid.value(), lp, new_csp}});
}
assert(pjid);
// record the requirement for this column
val_reqs[rg_rq] =
{false,
RegionRequirement(
lp,
pjid.value(),
reqs.values.privilege,
reqs.values.coherence,
col.region,
reqs.tag)};
}
}
std::get<1>(val_reqs[rg_rq]).add_field(col.fid, reqs.values.mapped);
}
}
std::vector<ColumnSpacePartition> csps_result;
for (auto& cs_part : partitions) {
#if HAVE_CXX17
auto& [csp, pjid, lp, isnew] = std::get<1>(cs_part);
#else // !HAVE_CXX17
auto& part = std::get<1>(cs_part);
auto& csp = std::get<0>(part);
auto& isnew = std::get<3>(part);
#endif
if (isnew)
csps_result.push_back(csp);
}
// gather all requirements, in order set by this traversal of fields
std::vector<RegionRequirement> reqs_result;
// start with index_col ColumnSpace metadata
reqs_result.push_back(index_col_cs.requirements(READ_ONLY, EXCLUSIVE));
// next, index_col index space partition
if (table_partition.is_valid()) {
RegionRequirement req(
std::get<2>(partitions.find(index_col_cs)->second),
0,
{Table::m_index_col_fid},
{}, // always remains unmapped!
WRITE_ONLY,
SIMULTANEOUS,
index_col_region);
reqs_result.push_back(req);
} else {
RegionRequirement req(
index_col_region,
{Table::m_index_col_fid},
{}, // always remains unmapped!
WRITE_ONLY,
SIMULTANEOUS,
index_col_region);
reqs_result.push_back(req);
}
Desc desc_result;
if (ctx && rt) {
auto pr =
rt.value()->map_region(
ctx.value(),
index_col_cs.requirements(LEGION_READ_ONLY, EXCLUSIVE));
desc_result.axes_uid = ColumnSpace::axes_uid(pr);
desc_result.index_axes = ColumnSpace::axes(pr);
rt.value()->unmap_region(ctx.value(), pr);
}
desc_result.num_columns = column_reqs.size();
assert(desc_result.num_columns <= desc_result.columns.size());
// add requirements for all logical regions in all selected columns
size_t desc_idx = 0;
for (auto& nm_col : columns) {
#if HAVE_CXX17
auto& [nm, col] = nm_col;
#else // !HAVE_CXX17
auto& nm = std::get<0>(nm_col);
auto& col = std::get<1>(nm_col);
#endif // HAVE_CXX17
if (column_reqs.count(nm) > 0) {
auto cdesc = col.desc(nm);
auto& reqs = column_reqs.at(nm);
{
auto& added_rq = md_reqs.at(col.region);
#if HAVE_CXX17
auto& [added, rq] = added_rq;
#else // !HAVE_CXX17
auto& added = std::get<0>(added_rq);
auto& rq = std::get<1>(added_rq);
#endif // HAVE_CXX17
if (!added) {
reqs_result.push_back(rq);
added = true;
}
}
decltype(val_reqs)::key_type rg_rq =
{col.region,
reqs.values.privilege,
reqs.values.coherence,
reqs.tag,
reqs.partition};
auto& added_rq = val_reqs.at(rg_rq);
#if HAVE_CXX17
auto& [added, rq] = added_rq;
#else // !HAVE_CXX17
auto& added = std::get<0>(added_rq);
auto& rq = std::get<1>(added_rq);
#endif // HAVE_CXX17
cdesc.region = rq.parent;
if (!added) {
reqs_result.push_back(rq);
added = true;
}
if (cdesc.n_kw > 0) {
auto& kw = col.kw;
assert(cdesc.n_kw == 2);
if (rt) {
auto nkw = kw.size(rt.value());
std::vector<FieldID> fids(nkw);
std::iota(fids.begin(), fids.end(), 0);
auto rqs =
kw.requirements(
rt.value(),
fids,
reqs.keywords.privilege,
reqs.keywords.mapped)
.value();
reqs_result.push_back(rqs.type_tags);
reqs_result.push_back(rqs.values);
} else {
// This is a corner case, which should only be reached when having
// originally called Table::requirements() without arguments, which
// should only be called in Table serialization. In that case, the
// requirement is only used to identify a LogicalRegion, so the FieldIDs
// are basically insignificant -- TODO: do something a bit more
// explicit, which should probably wait until a Keyword dictionary is
// simply a value in a region
LogicalRegion ttlr = kw.type_tags_lr;
LogicalRegion vlr = kw.values_lr;
RegionRequirement tt(ttlr, reqs.keywords.privilege, EXCLUSIVE, ttlr);
tt.add_field(0, reqs.keywords.mapped);
reqs_result.push_back(tt);
RegionRequirement v(vlr, reqs.keywords.privilege, EXCLUSIVE, vlr);
v.add_field(0, reqs.keywords.mapped);
reqs_result.push_back(v);
}
}
#ifdef HYPERION_USE_CASACORE
if (cdesc.n_mr > 0) {
auto& mr = col.mr;
auto rqs =
mr.requirements(reqs.measref.privilege, reqs.measref.mapped);
assert(cdesc.n_mr == 2 || cdesc.n_mr == 3);
reqs_result.push_back(std::get<0>(rqs));
reqs_result.push_back(std::get<1>(rqs));
if (std::get<2>(rqs)) {
assert(cdesc.n_mr == 3);
reqs_result.push_back(std::get<2>(rqs).value());
}
}
#endif
desc_result.columns[desc_idx++] = cdesc;
}
}
return {reqs_result, csps_result, desc_result};
}
TaskID Table::is_conformant_task_id;
const char* Table::is_conformant_task_name = "Table::is_conformant_task";
struct IsConformantArgs {
std::array<std::tuple<hyperion::string, Column>, Table::MAX_COLUMNS> columns;
IndexSpace cs_is;
IndexSpace index_cs_is;
};
bool
Table::is_conformant_task(
const Task* task,
const std::vector<PhysicalRegion>& regions,
Context ctx,
Runtime *rt) {
const IsConformantArgs* args =
static_cast<const IsConformantArgs*>(task->args);
auto columns = from_columns_array(args->columns);
std::tuple<IndexSpace, PhysicalRegion> index_cs =
{args->index_cs_is, regions[0]};
return Table::is_conformant(rt, columns, index_cs, args->cs_is, regions[0]);
}
Future /* bool */
Table::is_conformant(Context ctx, Runtime* rt, const ColumnSpace& cs) const {
if (m_index_col_cs.is_empty())
return Future::from_value(rt, true);
IsConformantArgs args;
args.cs_is = cs.column_is;
args.index_cs_is = m_index_col_cs.column_is;
TaskLauncher task(is_conformant_task_id, TaskArgument(&args, sizeof(args)));
args.columns = to_columns_array<args.columns.size()>(m_columns);
task.add_region_requirement(
m_index_col_cs.requirements(READ_ONLY, EXCLUSIVE));
task.add_region_requirement(cs.requirements(READ_ONLY, EXCLUSIVE));
return rt->execute_task(ctx, task);
}
template <int OBJECT_RANK, int SUBJECT_RANK>
static bool
do_domains_conform(
const DomainT<OBJECT_RANK>& object,
const DomainT<SUBJECT_RANK>& subject) {
// does "subject" conform to "object"?
static_assert(OBJECT_RANK <= SUBJECT_RANK);
bool result = true;
PointInDomainIterator<OBJECT_RANK> opid(object, false);
PointInDomainIterator<SUBJECT_RANK> spid(subject, false);
while (result && spid() && opid()) {
Point<OBJECT_RANK> pt(0);
while (result && spid()) {
for (size_t i = 0; i < OBJECT_RANK; ++i)
pt[i] = spid[i];
result = pt == *opid;
spid++;
}
opid++;
if (!result)
result = opid() && pt == *opid;
else
result = !opid();
}
return result;
}
bool
Table::is_conformant(
Runtime* rt,
const std::unordered_map<std::string, Column>& columns,
const std::tuple<IndexSpace, PhysicalRegion>& index_cs,
const IndexSpace& cs_is,
const PhysicalRegion& cs_md_pr) {
// if this ColumnSpace already exists in the Table, conformance must hold
ColumnSpace cs(cs_is, cs_md_pr.get_logical_region());
assert(!cs.is_empty());
for (auto& nm_col : columns) {
if (cs == std::get<1>(nm_col).cs)
return true;
}
#if HAVE_CXX17
auto& [index_cs_is, index_cs_md_pr] = index_cs;
#else // !HAVE_CXX17
auto& index_cs_is = std::get<0>(index_cs);
auto& index_cs_md_pr = std::get<1>(index_cs);
#endif // HAVE_CXX17
const ColumnSpace::AxisSetUIDAccessor<READ_ONLY>
index_cs_au(index_cs_md_pr, ColumnSpace::AXIS_SET_UID_FID);
const ColumnSpace::AxisVectorAccessor<READ_ONLY>
index_cs_av(index_cs_md_pr, ColumnSpace::AXIS_VECTOR_FID);
const ColumnSpace::AxisSetUIDAccessor<READ_ONLY>
cs_au(cs_md_pr, ColumnSpace::AXIS_SET_UID_FID);
const ColumnSpace::AxisVectorAccessor<READ_ONLY>
cs_av(cs_md_pr, ColumnSpace::AXIS_VECTOR_FID);
const ColumnSpace::IndexFlagAccessor<READ_ONLY>
cs_if(cs_md_pr, ColumnSpace::INDEX_FLAG_FID);
bool result = false;
// for conformance the axis uid must be that of the index column space
if (index_cs_au[0] == cs_au[0]) {
const auto index_ax = ColumnSpace::from_axis_vector(index_cs_av[0]);
const auto cs_ax = ColumnSpace::from_axis_vector(cs_av[0]);
if (!cs_if[0]) {
// for conformance, the cs axis vector must have a prefix equal to the
// axis vector of the index column space
auto p =
std::get<0>(
std::mismatch(
index_ax.begin(),
index_ax.end(),
cs_ax.begin(),
cs_ax.end()));
if (p == index_ax.end()) {
const auto index_cs_d = rt->get_index_space_domain(index_cs_is);
const auto cs_d = rt->get_index_space_domain(cs.column_is);
if (index_cs_d.dense() && cs_d.dense()) {
// when both index_cs and cs IndexSpaces are dense, it's sufficient to
// compare their bounds within the rank of index_cs
const auto index_cs_lo = index_cs_d.lo();
const auto index_cs_hi = index_cs_d.hi();
const auto cs_lo = cs_d.lo();
const auto cs_hi = cs_d.hi();
result = true;
for (int i = 0; result && i < index_cs_d.get_dim(); ++i)
result = index_cs_lo[i] == cs_lo[i] && index_cs_hi[i] == cs_hi[i];
} else {
switch (index_cs_d.get_dim() * LEGION_MAX_DIM + cs_d.get_dim()) {
#define CONFORM(IRANK, CRANK) \
case (IRANK * LEGION_MAX_DIM + CRANK): \
result = \
do_domains_conform<IRANK, CRANK>(index_cs_d, cs_d); \
break;
HYPERION_FOREACH_MN(CONFORM)
#undef CONFORM
default:
assert(false);
break;
}
}
}
} else {
result =
cs_ax.size() == 1
&& std::find(
index_ax.begin(),
index_ax.end(),
cs_ax[0]) != index_ax.end();
}
}
return result;
}
TaskID Table::add_columns_task_id;
const char* Table::add_columns_task_name = "Table::add_columns_task";
struct AddColumnsTaskArgs {
std::array<
std::tuple<ColumnSpace, size_t, hyperion::string, TableField>,
Table::MAX_COLUMNS> new_columns;
std::array<std::tuple<hyperion::string, Column>, Table::MAX_COLUMNS> columns;
IndexSpace index_cs_is;
};
Table::add_columns_result_t
Table::add_columns_task(
const Task* task,
const std::vector<PhysicalRegion>& regions,
Context ctx,
Runtime *rt) {
const AddColumnsTaskArgs* args =
static_cast<const AddColumnsTaskArgs*>(task->args);
auto columns = from_columns_array(args->columns);
std::vector<
std::tuple<
ColumnSpace,
size_t,
std::vector<std::pair<hyperion::string, TableField>>>>
new_columns;
ColumnSpace last_cs;
size_t last_idx;
std::vector<std::pair<hyperion::string, TableField>> nm_tfs;
for (size_t i = 0;
i < args->new_columns.size()
&& std::get<2>(args->new_columns[i]).size() > 0;
++i) {
auto& cs_idx_nm_tf = args->new_columns[i];
#if HAVE_CXX17
auto& [cs, idx, nm, tf] = cs_idx_nm_tf;
#else // !HAVE_CXX17
auto& cs = std::get<0>(cs_idx_nm_tf);
auto& idx = std::get<1>(cs_idx_nm_tf);
auto& nm = std::get<2>(cs_idx_nm_tf);
auto& tf = std::get<3>(cs_idx_nm_tf);
#endif // HAVE_CXX17
if (last_cs != cs) {
if (last_cs.is_valid())
new_columns.emplace_back(last_cs, last_idx, nm_tfs);
last_cs = cs;
last_idx = idx;
nm_tfs.clear();
}
nm_tfs.emplace_back(nm, tf);
}
if (last_cs.is_valid())
new_columns.emplace_back(last_cs, last_idx, nm_tfs);
std::tuple<IndexSpace, PhysicalRegion> index_cs =
{args->index_cs_is, regions[0]};
std::vector<PhysicalRegion> cs_md_prs(regions.begin() + 1, regions.end());
auto added =
add_columns(
ctx,
rt,
std::move(new_columns),
columns,
cs_md_prs,
index_cs);
add_columns_result_t result;
for (auto& nm_col : added) {
#if HAVE_CXX17
auto& [nm, col] = nm_col;
#else //!HAVE_CXX17
auto& nm = std::get<0>(nm_col);
auto& col = std::get<1>(nm_col);
#endif
result.cols.emplace_back(nm, col);
}
return result;
}
bool
Table::add_columns(Context ctx, Runtime* rt, fields_t&& new_columns) {
if (new_columns.size() == 0)
return true;
AddColumnsTaskArgs args;
TaskLauncher task(add_columns_task_id, TaskArgument(&args, sizeof(args)));
args.columns = to_columns_array<args.columns.size()>(m_columns);
std::vector<RegionRequirement> reqs;
args.index_cs_is = m_index_col_cs.column_is;
reqs.push_back(m_index_col_cs.requirements(READ_ONLY, EXCLUSIVE));
std::map<ColumnSpace, size_t> cs_indexes;
for (auto& nm_col : m_columns) {
auto& col = std::get<1>(nm_col);
if (cs_indexes.count(col.cs) == 0) {
size_t i = cs_indexes.size();
cs_indexes[col.cs] = i;
reqs.push_back(col.cs.requirements(READ_ONLY, EXCLUSIVE));
}
}
std::set<std::string> new_cnames;
{
size_t i = 0;
for (auto& cs_nm_tfs: new_columns) {
#if HAVE_CXX17
auto& [cs, nm_tfs] = cs_nm_tfs;
#else // !HAVE_CXX17
auto& cs = std::get<0>(cs_nm_tfs);
auto& nm_tfs = std::get<1>(cs_nm_tfs);
#endif // HAVE_CXX17
if (cs_indexes.count(cs) == 0) {
size_t i = cs_indexes.size();
cs_indexes[cs] = i;
reqs.push_back(cs.requirements(READ_ONLY, EXCLUSIVE));
}
size_t idx = cs_indexes[cs];
for (auto& nm_tf: nm_tfs) {
#if HAVE_CXX17
auto& [nm, tf] = nm_tf;
#else // !HAVE_CXX17
auto& nm = std::get<0>(nm_tf);
auto& tf = std::get<1>(nm_tf);
#endif // HAVE_CXX17
new_cnames.insert(nm);
assert(i <= args.new_columns.size());
args.new_columns[i++] = {cs, idx, string(nm), tf};
}
}
if (i < args.new_columns.size())
args.new_columns[i] = {ColumnSpace(), 0, string(), TableField()};
}
for (auto& req : reqs)
task.add_region_requirement(req);
auto added = rt->execute_task(ctx, task).get_result<add_columns_result_t>();
for (auto& nm_col : added.cols) {
#if HAVE_CXX17
auto& [nm, col] = nm_col;
#else // !HAVE_CXX17
auto& nm = std::get<0>(nm_col);
auto& col = std::get<1>(nm_col);
#endif // HAVE_CXX17
new_cnames.erase(nm);
m_columns[nm] = col;
}
return new_cnames.size() == 0;
}
std::unordered_map<std::string, Column>
Table::add_columns(
Context ctx,
Runtime* rt,
std::vector<
std::tuple<
ColumnSpace,
size_t,
std::vector<std::pair<hyperion::string, TableField>>>>&& new_columns,
const std::unordered_map<std::string, Column>& columns,
const std::vector<PhysicalRegion>& cs_md_prs,
const std::tuple<IndexSpace, PhysicalRegion>& index_cs) {
if (new_columns.size() == 0)
return {};
// check conformance of all ColumnSpaces in new_columns
//
for (auto& cs_idx_nmtfs : new_columns) {
auto& cs = std::get<0>(cs_idx_nmtfs);
auto& idx = std::get<1>(cs_idx_nmtfs);
if (!Table::is_conformant(
rt,
columns,
index_cs,
cs.column_is,
cs_md_prs[idx])) {
// FIXME: log warning: cannot add non-conforming Columns to Table
assert(false);
return {};
}
}
// All ColumnSpaces must have unique axis vectors.
{
std::set<std::vector<int>> axes;
for (auto& pr : cs_md_prs) {
const ColumnSpace::AxisVectorAccessor<READ_ONLY>
ax(pr, ColumnSpace::AXIS_VECTOR_FID);
auto axv = ColumnSpace::from_axis_vector(ax[0]);
if (axes.count(axv) > 0) {
// FIXME: log warning: ColumnSpaces added to Table do not have unique
// axis vectors
assert(false);
return {};
}
axes.insert(axv);
}
}
// column names must be unique
{
std::set<std::string> new_column_names;
for (auto& cs_idx_nmtfs: new_columns) {
for (auto& hnm_tf: std::get<2>(cs_idx_nmtfs)) {
std::string nm = std::get<0>(hnm_tf);
if (columns.count(nm) > 0 || new_column_names.count(nm) > 0) {
assert(false);
return {};
}
new_column_names.insert(nm);
}
}
}
// get ColumnSpace metadata regions for current columns only
std::vector<PhysicalRegion> current_cs_md_prs;
for (auto& pr : cs_md_prs) {
auto c =
std::find_if(
columns.begin(),
columns.end(),
[lr=pr.get_logical_region()](auto& nm_col) {
return lr == std::get<1>(nm_col).cs.metadata_lr;
});
if (c != columns.end())
current_cs_md_prs.push_back(pr);
}
// Create a map from ColumnSpaces to LogicalRegions
std::map<ColumnSpace, LogicalRegion> lrs;
for (auto& nm_col : columns) {
#if HAVE_CXX17
auto& [nm, col] = nm_col;
#else // !HAVE_CXX17
auto& col = std::get<1>(nm_col);
#endif // HAVE_CXX17
if (lrs.count(col.cs) == 0)
lrs[col.cs] = col.region;
}
// add new columns to free_fields_pr
std::unordered_map<std::string, Column> result;
for (auto& cs_idx_nmtfs : new_columns) {
#if HAVE_CXX17
auto& [cs, idx, nm_tfs] = cs_idx_nmtfs;
#else // !HAVE_CXX17
auto& cs = std::get<0>(cs_idx_nmtfs);
auto& nm_tfs = std::get<2>(cs_idx_nmtfs);
#endif // HAVE_CXX17
if (lrs.count(cs) == 0) {
FieldSpace fs = rt->create_field_space(ctx);
auto lr = rt->create_logical_region(ctx, cs.column_is, fs);
lrs[cs] = lr;
}
auto& region = lrs[cs];
std::set<FieldID> fids;
FieldSpace fs = region.get_field_space();
rt->get_field_space_fields(fs, fids);
FieldAllocator fa = rt->create_field_allocator(ctx, fs);
for (auto& nm_tf : nm_tfs) {
auto& nm = std::get<0>(nm_tf);
auto& tf = std::get<1>(nm_tf);
// add field to logical region
assert(fids.count(tf.fid) == 0);
switch(tf.dt) {
#define ALLOC_FLD(DT) \
case DT: \
fa.allocate_field(DataType<DT>::serdez_size, tf.fid); \
break;
HYPERION_FOREACH_DATATYPE(ALLOC_FLD)
#undef ALLOC_FLD
default:
assert(false);
break;
}
rt->attach_name(fs, tf.fid, nm.val);
fids.insert(tf.fid);
// add Column to result
result[nm] =
Column(
tf.dt,
tf.fid,
cs,
region,
region,
tf.kw
#ifdef HYPERION_USE_CASACORE
, tf.mr
, tf.rc
#endif
);
}
}
return result;
}
bool
Table::remove_columns(
Context ctx,
Runtime* rt,
const std::unordered_set<std::string>& columns) {
std::vector<ColumnSpace> css;
std::vector<PhysicalRegion> cs_md_prs;
for (auto& nm_col : m_columns) {
#if HAVE_CXX17
auto& [nm, col] = nm_col;
#else // !HAVE_CXX17
auto& nm = std::get<0>(nm_col);
auto& col = std::get<1>(nm_col);
#endif // HAVE_CXX17
if (columns.count(nm) > 0) {
if (std::find(css.begin(), css.end(), col.cs) == css.end()) {
cs_md_prs.push_back(
rt->map_region(ctx, col.cs.requirements(READ_ONLY, EXCLUSIVE)));
css.push_back(col.cs);
}
}
}
auto result =
Table::remove_columns(ctx, rt, columns, m_columns, css, cs_md_prs);
for (auto& pr : cs_md_prs)
rt->unmap_region(ctx, pr);
if (result) {
std::map<LogicalRegion, ColumnSpace> lrcss;
for (auto& nm : columns) {
auto& col = m_columns.at(nm);
if (lrcss.count(col.region) == 0)
lrcss[col.region] = col.cs;
col.kw.destroy(ctx, rt);
#ifdef HYPERION_USE_CASACORE
col.mr.destroy(ctx, rt);
#endif
m_columns.erase(nm);
}
for (auto& lr_cs : lrcss) {
auto& lr = std::get<0>(lr_cs);
auto& cs = std::get<1>(lr_cs);
std::vector<FieldID> fids;
rt->get_field_space_fields(lr.get_field_space(), fids);
if (fids.size() == 0) {
cs.destroy(ctx, rt, true);
auto fs = lr.get_field_space();
rt->destroy_logical_region(ctx, lr);
rt->destroy_field_space(ctx, fs);
}
}
}
return result;
}
bool
Table::remove_columns(
Context ctx,
Runtime* rt,
const std::unordered_set<std::string>& rm_columns,
const std::unordered_map<std::string, Column>& columns,
const std::vector<ColumnSpace>& css,
const std::vector<PhysicalRegion>& cs_md_prs) {
if (rm_columns.size() == 0)
return true;
// check whether all columns are being removed, which is necessary if index
// columns are to be removed
bool remove_all;
{
std::unordered_set<std::string> all_columns = rm_columns;
for (auto& c : rm_columns)
all_columns.erase(c);
remove_all = all_columns.size() == 0;
}
std::map<ColumnSpace, FieldAllocator> fas;
for (auto& nm : rm_columns) {
auto& col = columns.at(nm);
if (!remove_all) {
auto idx =
std::distance(
css.begin(),
std::find(css.begin(), css.end(), col.cs));
assert(idx < (ssize_t)cs_md_prs.size());
const ColumnSpace::IndexFlagAccessor<READ_ONLY>
ixfl(cs_md_prs[idx], ColumnSpace::INDEX_FLAG_FID);
if (ixfl[0]) {
// FIXME: log warning: cannot remove a table index column
return false;
}
}
if (fas.count(col.cs) == 0)
fas[col.cs] =
rt->create_field_allocator(ctx, col.region.get_field_space());
fas[col.cs].free_field(col.fid);
}
return true;
}
void
Table::destroy(Context ctx, Runtime* rt) {
std::unordered_set<std::string> colnames;
for (auto& nm_col : m_columns)
colnames.insert(std::get<0>(nm_col));
remove_columns(ctx, rt, colnames);
m_index_col_cs.destroy(ctx, rt, false);
auto is = m_index_col_region.get_index_space();
auto fs = m_index_col_region.get_field_space();
rt->destroy_logical_region(ctx, m_index_col_region);
rt->destroy_field_space(ctx, fs);
rt->destroy_index_space(ctx, is);
m_index_col_region = LogicalRegion::NO_REGION;
}
struct PartitionRowsTaskArgs {
IndexSpace ics_is;
std::array<std::pair<bool, size_t>, Table::MAX_COLUMNS> block_sizes;
};
TaskID Table::partition_rows_task_id;
const char* Table::partition_rows_task_name = "Table::partition_rows_task";
ColumnSpacePartition
Table::partition_rows_task(
const Task* task,
const std::vector<PhysicalRegion>& regions,
Context ctx,
Runtime *rt) {
const PartitionRowsTaskArgs* args =
static_cast<const PartitionRowsTaskArgs*>(task->args);
std::vector<CXX_OPTIONAL_NAMESPACE::optional<size_t>> block_sizes;
for (size_t i = 0; i < MAX_COLUMNS; ++i) {
#if HAVE_CXX17
auto& [has_value, value] = args->block_sizes[i];
#else // !HAVE_CXX17
auto& has_value = std::get<0>(args->block_sizes[i]);
auto& value = std::get<1>(args->block_sizes[i]);
#endif // HAVE_CXX17
if (has_value && value == 0)
break;
block_sizes.push_back(
has_value ? value : CXX_OPTIONAL_NAMESPACE::optional<size_t>());
}
return partition_rows(ctx, rt, block_sizes, args->ics_is, regions[0]);
}
Future /* ColumnSpacePartition */
Table::partition_rows(
Context ctx,
Runtime* rt,
const std::vector<CXX_OPTIONAL_NAMESPACE::optional<size_t>>& block_sizes)
const {
PartitionRowsTaskArgs args;
for (size_t i = 0; i < block_sizes.size(); ++i) {
assert(block_sizes[i].value_or(1) > 0);
args.block_sizes[i] =
{(bool)block_sizes[i], block_sizes[i].value_or(0)};
}
args.block_sizes[block_sizes.size()] = {true, 0};
args.ics_is = m_index_col_cs.column_is;
TaskLauncher task(partition_rows_task_id, TaskArgument(&args, sizeof(args)));
task.add_region_requirement(
m_index_col_cs.requirements(READ_ONLY, EXCLUSIVE));
return rt->execute_task(ctx, task);
}
ColumnSpacePartition
Table::partition_rows(
Context ctx,
Runtime* rt,
const std::vector<CXX_OPTIONAL_NAMESPACE::optional<size_t>>& block_sizes,
const IndexSpace& ics_is,
const PhysicalRegion& ics_md_pr) {
ColumnSpacePartition result;
const ColumnSpace::AxisVectorAccessor<READ_ONLY>
ax(ics_md_pr, ColumnSpace::AXIS_VECTOR_FID);
const ColumnSpace::AxisSetUIDAccessor<READ_ONLY>
au(ics_md_pr, ColumnSpace::AXIS_SET_UID_FID);
auto ixax = ax[0];
auto ixax_sz = ColumnSpace::size(ixax);
if (block_sizes.size() > ixax_sz)
return result;
// copy block_sizes, extended to size of ixax with std::nullopt
std::vector<CXX_OPTIONAL_NAMESPACE::optional<size_t>> blkszs(ixax_sz);
{
auto e = std::copy(block_sizes.begin(), block_sizes.end(), blkszs.begin());
std::fill(e, blkszs.end(), CXX_OPTIONAL_NAMESPACE::nullopt);
}
std::vector<std::pair<int, coord_t>> parts;
for (size_t i = 0; i < ixax_sz; ++i)
if (blkszs[i])
parts.emplace_back(ixax[i], blkszs[i].value());
return ColumnSpacePartition::create(ctx, rt, ics_is, au[0], parts, ics_md_pr);
}
TaskID Table::reindexed_task_id;
const char* Table::reindexed_task_name = "Table::reindexed_task";
struct ReindexedTaskArgs {
Table::Desc desc;
std::array<std::pair<int, hyperion::string>, LEGION_MAX_DIM> index_axes;
bool allow_rows;
};
Table
Table::reindexed_task(
const Task* task,
const std::vector<PhysicalRegion>& regions,
Context ctx,
Runtime *rt) {
const ReindexedTaskArgs* args =
static_cast<const ReindexedTaskArgs*>(task->args);
auto ptcr =
PhysicalTable::create(
rt,
args->desc,
task->regions.begin(),
task->regions.end(),
regions.begin(),
regions.end())
.value();
#if HAVE_CXX17
auto& [ptable, rit, pit] = ptcr;
#else // !HAVE_CXX17
auto& ptable = std::get<0>(ptcr);
auto& rit = std::get<1>(ptcr);
auto& pit = std::get<2>(ptcr);
#endif // HAVE_CXX17
assert(rit == task->regions.end());
assert(pit == regions.end());
std::vector<std::pair<int, std::string>> index_axes;
auto iaxp = args->index_axes.begin();
while (iaxp < args->index_axes.end() && std::get<0>(*iaxp) >= 0) {
index_axes.emplace_back(std::get<0>(*iaxp), std::get<1>(*iaxp));
++iaxp;
}
return ptable.reindexed(ctx, rt, index_axes, args->allow_rows);
}
Future /* Table */
Table::reindexed(
Context ctx,
Runtime *rt,
const std::vector<std::pair<int, std::string>>& index_axes,
bool allow_rows) const {
ReindexedTaskArgs args;
args.allow_rows = allow_rows;
auto e =
std::copy(index_axes.begin(), index_axes.end(), args.index_axes.begin());
std::fill(e, args.index_axes.end(), std::make_pair(-1, string()));
auto reqs = requirements(ctx, rt);
#if HAVE_CXX17
auto& [treqs, tparts, tdesc] = reqs;
#else // !HAVE_CXX17
auto& treqs = std::get<0>(reqs);
auto& tdesc = std::get<2>(reqs);
#endif // HAVE_CXX17
args.desc = tdesc;
TaskLauncher task(reindexed_task_id, TaskArgument(&args, sizeof(args)));
for (auto& r : treqs)
task.add_region_requirement(r);
return rt->execute_task(ctx, task);
}
void
Table::preregister_tasks() {
{
// is_conformant_task
is_conformant_task_id = Runtime::generate_static_task_id();
TaskVariantRegistrar registrar(
is_conformant_task_id,
is_conformant_task_name);
registrar.add_constraint(ProcessorConstraint(Processor::LOC_PROC));
registrar.set_idempotent();
registrar.set_leaf();
Runtime::preregister_task_variant<bool, is_conformant_task>(
registrar,
is_conformant_task_name);
}
{
// add_columns_task
add_columns_task_id = Runtime::generate_static_task_id();
TaskVariantRegistrar registrar(add_columns_task_id, add_columns_task_name);
registrar.add_constraint(ProcessorConstraint(Processor::LOC_PROC));
registrar.set_idempotent();
registrar.set_leaf();
Runtime::preregister_task_variant<add_columns_result_t, add_columns_task>(
registrar,
add_columns_task_name);
}
{
// partition_rows_task
partition_rows_task_id = Runtime::generate_static_task_id();
TaskVariantRegistrar
registrar(partition_rows_task_id, partition_rows_task_name);
registrar.add_constraint(ProcessorConstraint(Processor::LOC_PROC));
registrar.set_idempotent();
Runtime::preregister_task_variant<
ColumnSpacePartition,
partition_rows_task>(
registrar,
partition_rows_task_name);
}
{
// reindexed_task
reindexed_task_id = Runtime::generate_static_task_id();
TaskVariantRegistrar
registrar(reindexed_task_id, reindexed_task_name);
registrar.add_constraint(ProcessorConstraint(Processor::LOC_PROC));
registrar.set_idempotent();
Runtime::preregister_task_variant<Table, reindexed_task>(
registrar,
reindexed_task_name);
}
}
size_t
Table::legion_buffer_size(void) const {
#if HAVE_CXX17
auto [treqs, tdesc] = requirements();
#else // !HAVE_CXX17
auto reqs = requirements();
auto& treqs = std::get<0>(reqs);
auto& tdesc = std::get<1>(reqs);
#endif // HAVE_CXX17
return
sizeof(unsigned) // number of columns
+ tdesc.num_columns * sizeof(Column::Desc)
+ sizeof(unsigned) // number of LogicalRegions
+ treqs.size() * sizeof(LogicalRegion);
}
size_t
Table::legion_serialize(void* buffer) const {
#if HAVE_CXX17
auto [treqs, tdesc] = requirements();
#else // !HAVE_CXX17
auto reqs = requirements();
auto& treqs = std::get<0>(reqs);
auto& tdesc = std::get<1>(reqs);
#endif // HAVE_CXX17
char *b = static_cast<char*>(buffer);
*reinterpret_cast<decltype(tdesc.num_columns)*>(b) = tdesc.num_columns;
b += sizeof(tdesc.num_columns);
for (size_t i = 0; i < tdesc.num_columns; ++i) {
*reinterpret_cast<decltype(tdesc.columns)::value_type*>(b) =
tdesc.columns[i];
b += sizeof(decltype(tdesc.columns)::value_type);
}
*reinterpret_cast<unsigned*>(b) = static_cast<unsigned>(treqs.size());
b += sizeof(unsigned);
for (auto& req : treqs) {
*reinterpret_cast<LogicalRegion*>(b) = req.region;
b += sizeof(LogicalRegion);
}
return b - static_cast<char*>(buffer);
}
size_t
Table::legion_deserialize(const void* buffer) {
const char *b = static_cast<const char*>(buffer);
Desc desc;
desc.num_columns = *reinterpret_cast<const decltype(desc.num_columns)*>(b);
b += sizeof(desc.num_columns);
for (size_t i = 0; i < desc.num_columns; ++i) {
desc.columns[i] =
*reinterpret_cast<const decltype(desc.columns)::value_type*>(b);
b += sizeof(decltype(desc.columns)::value_type);
}
std::vector<LogicalRegion> lrs;
unsigned n_lr = *reinterpret_cast<const unsigned*>(b);
b += sizeof(unsigned);
lrs.reserve(n_lr);
for (unsigned i = 0; i < n_lr; ++i) {
lrs.push_back(*reinterpret_cast<const LogicalRegion*>(b));
b += sizeof(LogicalRegion);
}
auto lrp = lrs.begin();
assert(lrp != lrs.end());
m_index_col_cs.metadata_lr = *lrp++;
assert(lrp != lrs.end());
m_index_col_cs.column_is = lrp->get_index_space();
m_index_col_region = *lrp;
m_index_col_parent = *lrp++;
std::map<LogicalRegion, ColumnSpace> css;
for (size_t i = 0; i < desc.num_columns; ++i) {
auto& cdesc = desc.columns[i];
if (css.count(cdesc.region) == 0) {
ColumnSpace cs;
assert(lrp != lrs.end());
cs.metadata_lr = *lrp++;
assert(lrp != lrs.end());
cs.column_is = lrp++->get_index_space();
css[cdesc.region] = cs;
}
Keywords kw;
if (cdesc.n_kw > 0) {
assert(cdesc.n_kw == 2);
assert(lrp != lrs.end());
LogicalRegion tt = *lrp++;
assert(lrp != lrs.end());
LogicalRegion vl = *lrp++;
kw = Keywords(Keywords::pair<LogicalRegion>{tt, vl});
}
#ifdef HYPERION_USE_CASACORE
MeasRef mr;
if (cdesc.n_mr > 0) {
assert(cdesc.n_mr >= 2);
assert(lrp != lrs.end());
LogicalRegion md = *lrp++;
assert(lrp != lrs.end());
LogicalRegion vl = *lrp++;
LogicalRegion ix;
if (cdesc.n_mr > 2) {
assert(cdesc.n_mr == 3);
assert(lrp != lrs.end());
ix = *lrp++;
}
mr = MeasRef(md, vl, ix);
}
CXX_OPTIONAL_NAMESPACE::optional<hyperion::string> rc;
if (cdesc.refcol.size() > 0)
rc = cdesc.refcol;
#endif
m_columns[cdesc.name] =
Column(
cdesc.dt,
cdesc.fid,
css.at(cdesc.region),
cdesc.region,
cdesc.region,
kw
#ifdef HYPERION_USE_CASACORE
, mr
, rc
#endif
);
}
return b - static_cast<const char*>(buffer);
}
// Local Variables:
// mode: c++
// c-basic-offset: 2
// fill-column: 80
// indent-tabs-mode: nil
// End:
| 30.293598
| 82
| 0.63144
|
mpokorny
|
60b2db4f5d31b0bdaa8f838519bc58cc95fe6ee5
| 2,043
|
cpp
|
C++
|
src/BlockEntities/FlowerPotEntity.cpp
|
skpub/cuberite
|
c2f8ceb554982a33bcd4a1e168f6c4e26d0b85dd
|
[
"Apache-2.0"
] | null | null | null |
src/BlockEntities/FlowerPotEntity.cpp
|
skpub/cuberite
|
c2f8ceb554982a33bcd4a1e168f6c4e26d0b85dd
|
[
"Apache-2.0"
] | null | null | null |
src/BlockEntities/FlowerPotEntity.cpp
|
skpub/cuberite
|
c2f8ceb554982a33bcd4a1e168f6c4e26d0b85dd
|
[
"Apache-2.0"
] | null | null | null |
// FlowerPotEntity.cpp
// Implements the cFlowerPotEntity class representing a single flower pot in the world
#include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules
#include "FlowerPotEntity.h"
#include "../Entities/Player.h"
#include "../ClientHandle.h"
#include "../Item.h"
cFlowerPotEntity::cFlowerPotEntity(BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta, Vector3i a_Pos, cWorld * a_World):
Super(a_BlockType, a_BlockMeta, a_Pos, a_World)
{
ASSERT(a_BlockType == E_BLOCK_FLOWER_POT);
}
void cFlowerPotEntity::Destroy(void)
{
// Drop the contents as pickups:
if (!m_Item.IsEmpty())
{
ASSERT(m_World != nullptr);
cItems Pickups;
Pickups.Add(m_Item);
m_World->SpawnItemPickups(Pickups, Vector3d(0.5, 0.5, 0.5) + m_Pos);
m_Item.Empty();
}
}
void cFlowerPotEntity::CopyFrom(const cBlockEntity & a_Src)
{
Super::CopyFrom(a_Src);
auto & src = static_cast<const cFlowerPotEntity &>(a_Src);
m_Item = src.m_Item;
}
bool cFlowerPotEntity::UsedBy(cPlayer * a_Player)
{
if (IsItemInPot())
{
return false;
}
a_Player->GetStatManager().AddValue(Statistic::PotFlower);
cItem SelectedItem = a_Player->GetInventory().GetEquippedItem();
if (IsFlower(SelectedItem.m_ItemType, SelectedItem.m_ItemDamage))
{
m_Item = SelectedItem.CopyOne();
if (!a_Player->IsGameModeCreative())
{
a_Player->GetInventory().RemoveOneEquippedItem();
}
m_World->BroadcastBlockEntity(GetPos(), a_Player->GetClientHandle());
}
return true;
}
void cFlowerPotEntity::SendTo(cClientHandle & a_Client)
{
a_Client.SendUpdateBlockEntity(*this);
}
bool cFlowerPotEntity::IsFlower(short m_ItemType, short m_ItemData)
{
switch (m_ItemType)
{
case E_BLOCK_DANDELION:
case E_BLOCK_FLOWER:
case E_BLOCK_CACTUS:
case E_BLOCK_BROWN_MUSHROOM:
case E_BLOCK_RED_MUSHROOM:
case E_BLOCK_SAPLING:
case E_BLOCK_DEAD_BUSH:
{
return true;
}
case E_BLOCK_TALL_GRASS:
{
return (m_ItemData == static_cast<short>(2));
}
default:
{
return false;
}
}
}
| 17.921053
| 116
| 0.725893
|
skpub
|
60b3fb44c370991f3c2373cec93cb7788e9945ff
| 5,003
|
cpp
|
C++
|
sdk/sdk/driver/demod_ctrl/it9137/tuner/tuner.cpp
|
doyaGu/C0501Q_HWJL01
|
07a71328bd9038453cbb1cf9c276a3dd1e416d63
|
[
"MIT"
] | 1
|
2021-10-09T08:05:50.000Z
|
2021-10-09T08:05:50.000Z
|
sdk/sdk/driver/demod_ctrl/it9137/tuner/tuner.cpp
|
doyaGu/C0501Q_HWJL01
|
07a71328bd9038453cbb1cf9c276a3dd1e416d63
|
[
"MIT"
] | null | null | null |
sdk/sdk/driver/demod_ctrl/it9137/tuner/tuner.cpp
|
doyaGu/C0501Q_HWJL01
|
07a71328bd9038453cbb1cf9c276a3dd1e416d63
|
[
"MIT"
] | null | null | null |
/**
* @(#)Afatech_OMEGA.cpp
*
* ==========================================================
* Version: 2.0
* Date: 2009.06.15
* ==========================================================
*
* ==========================================================
* History:
*
* Date Author Description
* ----------------------------------------------------------
*
* 2009.06.15 M.-C. Ho new tuner
* ==========================================================
*
* Copyright 2009 Afatech, Inc. All rights reserved.
*
*/
#include <stdio.h>
#include "..\type.h"
#include "..\error.h"
#include "..\user.h"
#include "..\register.h"
#include "..\standard.h"
#include "tuner.h"
#include "omega.h"
#include "Firmware_Afa_Omega_Script.h"
#include "Firmware_Afa_Omega_LNA_Config_1_Script.h"
#include "Firmware_Afa_Omega_LNA_Config_2_Script.h"
#include "Firmware_Afa_Omega_Script_V2.h"
#include "Firmware_Afa_Omega_LNA_Config_1_Script_V2.h"
#include "Firmware_Afa_Omega_LNA_Config_2_Script_V2.h"
#include "Firmware_Afa_Omega_LNA_Config_3_Script_V2.h"
#include "Firmware_Afa_Omega_LNA_Config_4_Script_V2I.h"
#include "Firmware_Afa_Omega_LNA_Config_5_Script_V2I.h"
Demodulator* Afatech_OMEGA_demodulator;
Byte Afatech_OMEGA_chip;
Dword OMEGA_open (
IN Demodulator* demodulator,
IN Byte chip
) {
Dword error = Error_NO_ERROR;
Afatech_OMEGA_demodulator = demodulator;
Afatech_OMEGA_chip = chip;
error = omega_init();
return (error);
}
Dword OMEGA_close (
IN Demodulator* demodulator,
IN Byte chip
) {
return (Error_NO_ERROR);
}
Dword OMEGA_set (
IN Demodulator* demodulator,
IN Byte chip,
IN Word bandwidth,
IN Dword frequency
) {
Dword error = Error_NO_ERROR;
Afatech_OMEGA_demodulator = demodulator;
Afatech_OMEGA_chip = chip;
error = omega_setfreq((unsigned int)bandwidth, (unsigned int)frequency);
return (error);
}
TunerDescription tunerDescription= {
OMEGA_open,
OMEGA_close,
OMEGA_set,
NULL,
NULL,
OMEGA_ADDRESS, /** tuner i2c address */
2, /** length of tuner register address */
0, /** tuner if */
False, /** spectrum inverse */
0x38, /** tuner id */
};
Dword OMEGA_supportLNA (
IN Demodulator* demodulator,
IN Byte supporttype
) {
Dword error = Error_INVALID_DEV_TYPE;
Byte chip_version = 0;
Dword chip_Type;
Byte var[2];
error = Standard_readRegister(demodulator, 0, Processor_LINK, chip_version_7_0, &chip_version);
if (error) goto exit;
error = Standard_readRegisters(demodulator, 0, Processor_LINK, chip_version_7_0+1, 2, var);
if (error) goto exit;
chip_Type = var[1]<<8 | var[0];
if(chip_Type==0x9135 && chip_version == 2){
switch (supporttype){
case OMEGA_NORMAL:
tunerDescription.tunerScript = V2_OMEGA_scripts;
tunerDescription.tunerScriptSets = V2_OMEGA_scriptSets;
tunerDescription.tunerId = 0x60;
error = Error_NO_ERROR;
break;
case OMEGA_LNA_Config_1:
tunerDescription.tunerScript = V2_OMEGA_LNA_Config_1_scripts;
tunerDescription.tunerScriptSets = V2_OMEGA_LNA_Config_1_scriptSets;
tunerDescription.tunerId = 0x61;
error = Error_NO_ERROR;
break;
case OMEGA_LNA_Config_2:
tunerDescription.tunerScript = V2_OMEGA_LNA_Config_2_scripts;
tunerDescription.tunerScriptSets = V2_OMEGA_LNA_Config_2_scriptSets;
tunerDescription.tunerId = 0x62;
error = Error_NO_ERROR;
break;
case OMEGA_LNA_Config_3:
tunerDescription.tunerScript = V2_OMEGA_LNA_Config_3_scripts;
tunerDescription.tunerScriptSets = V2_OMEGA_LNA_Config_3_scriptSets;
tunerDescription.tunerId = 0x63;
error = Error_NO_ERROR;
break;
case OMEGA_LNA_Config_4:
tunerDescription.tunerScript = V2I_OMEGA_LNA_Config_4_scripts;
tunerDescription.tunerScriptSets = V2I_OMEGA_LNA_Config_4_scriptSets;
tunerDescription.tunerId = 0x64;
error = Error_NO_ERROR;
break;
case OMEGA_LNA_Config_5:
tunerDescription.tunerScript = V2I_OMEGA_LNA_Config_5_scripts;
tunerDescription.tunerScriptSets = V2I_OMEGA_LNA_Config_5_scriptSets;
tunerDescription.tunerId = 0x65;
error = Error_NO_ERROR;
break;
default:
break;
}
}else{
switch (supporttype){
case OMEGA_NORMAL:
tunerDescription.tunerScript = OMEGA_scripts;
tunerDescription.tunerScriptSets = OMEGA_scriptSets;
tunerDescription.tunerId = 0x38;
error = Error_NO_ERROR;
break;
case OMEGA_LNA_Config_1:
tunerDescription.tunerScript = OMEGA_LNA_Config_1_scripts;
tunerDescription.tunerScriptSets = OMEGA_LNA_Config_1_scriptSets;
tunerDescription.tunerId = 0x51;
error = Error_NO_ERROR;
break;
case OMEGA_LNA_Config_2:
tunerDescription.tunerScript = OMEGA_LNA_Config_2_scripts;
tunerDescription.tunerScriptSets = OMEGA_LNA_Config_2_scriptSets;
tunerDescription.tunerId = 0x52;
error = Error_NO_ERROR;
break;
default:
break;
}
}
exit:
return error;
}
| 28.106742
| 96
| 0.682391
|
doyaGu
|
60c07dd7ce306691f5b3cc463722fef323e853a1
| 2,579
|
cpp
|
C++
|
src/storage/test/unit/src/accessor/IaqDataAccessorTest.cpp
|
karz0n/sensority-collector
|
0d71a2855fa7fcff9c11475dbf1832a598421949
|
[
"MIT"
] | null | null | null |
src/storage/test/unit/src/accessor/IaqDataAccessorTest.cpp
|
karz0n/sensority-collector
|
0d71a2855fa7fcff9c11475dbf1832a598421949
|
[
"MIT"
] | null | null | null |
src/storage/test/unit/src/accessor/IaqDataAccessorTest.cpp
|
karz0n/sensority-collector
|
0d71a2855fa7fcff9c11475dbf1832a598421949
|
[
"MIT"
] | null | null | null |
#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include "storage/DataStorage.hpp"
#include "storage/model/IaqDataModel.hpp"
#include "storage/accessor/IaqDataAccessor.hpp"
#include "tests/Waiter.hpp"
using namespace testing;
using namespace storage;
using namespace std::chrono_literals;
class IaqDataAccessorTest : public Test {
public:
const std::string Values{R"([
{"value": 100.0, "accuracy": 0.01, "staticValue": 120.0, "staticValueAccuracy": 0.01},
{"value": 110.0, "accuracy": 0.02, "staticValue": 130.0, "staticValueAccuracy": 0.02}
])"};
IaqDataAccessorTest()
: storage{std::make_shared<DataStorage>()}
, accessor{storage}
{
}
void
SetUp() override
{
storage->setUp();
}
void
TearDown() override
{
storage->tearDown();
}
static void
SetUpTestSuite()
{
DataStorage::initialize();
}
static void
TearDownTestSuite()
{
DataStorage::uninitialize();
}
public:
DataStorage::Ptr storage;
IaqDataAccessor accessor;
};
static Matcher<IaqData>
matchTo(float value, float accuracy, float staticValue, float staticValueAccuracy)
{
return AllOf(Field(&IaqData::value, FloatEq(value)),
Field(&IaqData::accuracy, FloatEq(accuracy)),
Field(&IaqData::staticValue, FloatEq(staticValue)),
Field(&IaqData::staticValueAccuracy, FloatEq(staticValueAccuracy)));
}
TEST_F(IaqDataAccessorTest, Store)
{
Waiter waiter;
MockFunction<DataAccessor::PutCallbackSignature> putCallback;
EXPECT_CALL(putCallback, Call(IsTrue()));
bool safeGuard{false};
accessor.put(Values, [&](const bool success) {
putCallback.Call(success);
safeGuard = true;
waiter.notifyOne();
});
ASSERT_TRUE(waiter.waitFor(3s, [&]() { return safeGuard; }));
MockFunction<DataAccessor::GetCallbackSignature> getCallback;
EXPECT_CALL(getCallback, Call(Not(IsNull()), IsTrue()));
IDataModel::Ptr dataModel;
safeGuard = false;
accessor.getForLastDay([&](IDataModel::Ptr model, const bool success) {
getCallback.Call(dataModel = std::move(model), success);
safeGuard = true;
waiter.notifyOne();
});
ASSERT_TRUE(waiter.waitFor(3s, [&]() { return safeGuard; }));
ASSERT_TRUE(dataModel->typeIs<IaqDataModel>());
const auto& model = dataModel->castTo<const IaqDataModel>();
EXPECT_THAT(model,
ElementsAre(matchTo(100.0, 0.01, 120.0, 0.01), matchTo(110.0, 0.02, 130.0, 0.02)));
}
| 27.147368
| 99
| 0.64715
|
karz0n
|
60c145bf1d27358691a47b8a7d023f526503034d
| 8,314
|
cpp
|
C++
|
rct_optimizations/src/rct_optimizations/covariance_analysis.cpp
|
m-limbird/robot_cal_tools
|
c3ee0c26895af50219afc450e7e6f866b7b86cbe
|
[
"Apache-2.0"
] | null | null | null |
rct_optimizations/src/rct_optimizations/covariance_analysis.cpp
|
m-limbird/robot_cal_tools
|
c3ee0c26895af50219afc450e7e6f866b7b86cbe
|
[
"Apache-2.0"
] | null | null | null |
rct_optimizations/src/rct_optimizations/covariance_analysis.cpp
|
m-limbird/robot_cal_tools
|
c3ee0c26895af50219afc450e7e6f866b7b86cbe
|
[
"Apache-2.0"
] | null | null | null |
#include <rct_optimizations/covariance_analysis.h>
#include <sstream>
namespace rct_optimizations
{
Eigen::MatrixXd computeCorrelationsFromCovariance(const Eigen::MatrixXd& covariance_matrix)
{
if(covariance_matrix.rows() != covariance_matrix.cols())
throw CovarianceException("Cannot compute correlations from a non-square matrix");
Eigen::Index num_vars = covariance_matrix.rows();
Eigen::MatrixXd out(num_vars, num_vars);
for (Eigen::Index i = 0; i < num_vars; i++)
{
double sigma_i = sqrt(fabs(covariance_matrix(i, i))); // standard deviation at the diagonal element in row i
for (Eigen::Index j = 0; j < num_vars; j++)
{
double sigma_j = sqrt(fabs(covariance_matrix(j, j))); // standard deviation at the diagonal element in column j
if (i == j) // if out(i,j) is a diagonal element
out(static_cast<Eigen::Index>(i), static_cast<Eigen::Index>(j)) = sigma_i;
else
{
if (sigma_i < std::numeric_limits<double>::epsilon()) sigma_i = 1;
if (sigma_j < std::numeric_limits<double>::epsilon()) sigma_j = 1;
out(static_cast<Eigen::Index>(i), static_cast<Eigen::Index>(j)) = covariance_matrix(i, j) / (sigma_i * sigma_j);
}
}
}
return out;
}
CovarianceResult computeCovarianceResults(const Eigen::MatrixXd& cov_matrix, const std::vector<std::string>& parameter_names)
{
// 0. Save original covariance matrix output
// For parameter blocks [p1, p2], the structure of this matrix will be:
/* | p1 | p2 |
* ---|-----------|-----------|
* p1 | C(p1, p1) | C(p1, p2) |
* p2 | C(p2, p1) | C(p2, p2) |
*/
CovarianceResult res;
res.covariance_matrix = cov_matrix;
// 1. Compute matrix of standard deviations and correlation coefficients.
// The arrangement of elements in the correlation matrix matches the order in the covariance matrix.
Eigen::MatrixXd correlation_matrix = computeCorrelationsFromCovariance(cov_matrix);
res.correlation_matrix = correlation_matrix;
// 2. Create NamedParams for covariance and correlation results, which include labels and values for the parameters. Uses top-right triangular part of matrix.
Eigen::Index col_start = 0;
for (Eigen::Index row = 0; row < correlation_matrix.rows(); row++)
{
for (Eigen::Index col = col_start; col < correlation_matrix.rows(); col++)
{
NamedParam p_corr;
p_corr.value = correlation_matrix(row, col);
if (row == col) // diagonal element, standard deviation
{
p_corr.names = std::make_pair(parameter_names[static_cast<std::size_t>(row)], "");
res.standard_deviations.push_back(p_corr);
continue;
}
// otherwise off-diagonal element, correlation coefficient
p_corr.names = std::make_pair(parameter_names[static_cast<std::size_t>(row)], parameter_names[static_cast<std::size_t>(col)]);
res.correlation_coeffs.push_back(p_corr);
// for off-diagonal elements also get covariance
NamedParam p_cov;
p_cov.value = cov_matrix(row, col);
p_cov.names = std::make_pair(parameter_names[static_cast<std::size_t>(row)], parameter_names[static_cast<std::size_t>(col)]);
res.covariances.push_back(p_cov);
}
col_start++;
}
return res;
}
CovarianceResult computeCovariance(ceres::Problem &problem,
const std::map<const double *, std::vector<int> > ¶m_masks,
const ceres::Covariance::Options& options)
{
std::vector<double *> blocks;
problem.GetParameterBlocks(&blocks);
const std::vector<const double *> blocks_const(blocks.begin(), blocks.end());
return computeCovariance(problem, blocks_const, param_masks, options);
}
CovarianceResult computeCovariance(ceres::Problem &problem,
const std::vector<const double *>& parameter_blocks,
const std::map<const double *, std::vector<int> > ¶m_masks,
const ceres::Covariance::Options& options)
{
std::map<const double *, std::vector<std::string>> dummy_param_names;
for (std::size_t block_index = 0; block_index < parameter_blocks.size(); block_index++)
{
int size = problem.ParameterBlockSize(parameter_blocks[block_index]);
std::vector<std::string> block_names;
for (int i = 0; i < size; i++)
{
// names follow format "blockN_elementM"
block_names.emplace_back("block" + std::to_string(block_index) + "_element" + std::to_string(i));
}
dummy_param_names[parameter_blocks[block_index]] = block_names;
}
return computeCovariance(problem, parameter_blocks, dummy_param_names, param_masks, options);
}
CovarianceResult computeCovariance(ceres::Problem &problem,
const std::map<const double *, std::vector<std::string> > ¶m_names,
const std::map<const double *, std::vector<int> > ¶m_masks,
const ceres::Covariance::Options& options)
{
// Get all parameter blocks for the problem
std::vector<double *> parameter_blocks(static_cast<std::size_t>(problem.NumParameterBlocks()));
problem.GetParameterBlocks(¶meter_blocks);
const std::vector<const double *> param_blocks_const(parameter_blocks.begin(), parameter_blocks.end());
return computeCovariance(problem, param_blocks_const, param_names, param_masks, options);
}
CovarianceResult computeCovariance(ceres::Problem &problem,
const std::vector<const double *>& parameter_blocks,
const std::map<const double*, std::vector<std::string>>& param_names,
const std::map<const double*, std::vector<int>>& param_masks,
const ceres::Covariance::Options& options)
{
// 0. Check user-specified arguments
if (parameter_blocks.size() != param_names.size())
throw CovarianceException("Provided vector parameter_names is not same length as provided number of parameter blocks");
Eigen::Index n_params_in_selected = 0;
std::vector<Eigen::Index> tangent_space_indices;
std::vector<std::string> tangent_space_labels;
for (const double* b : parameter_blocks)
{
int block_size = problem.ParameterBlockSize(b);
if (static_cast<std::size_t>(block_size) != param_names.at(b).size())
{
std::stringstream ss;
ss << "Number of parameter labels provided for block does not match actual number of parameters in that block: " \
<< "have " << param_names.at(b).size() << " labels and " << block_size << " parameters";
throw CovarianceException(ss.str());
}
// Extract tangent space
std::vector<int> masks;
auto it = param_masks.find(b);
if (it != param_masks.end())
masks = it->second;
const std::vector<std::string>& label = param_names.at(b);
for (std::size_t i = 0; i < static_cast<std::size_t>(block_size); ++i)
{
if (std::find(masks.begin(), masks.end(), i) == masks.end())
{
tangent_space_indices.push_back(n_params_in_selected + static_cast<Eigen::Index>(i));
tangent_space_labels.push_back(label.at(i));
}
}
n_params_in_selected += block_size;
}
// 1. Compute covariance matrix
ceres::Covariance covariance(options);
if(!covariance.Compute(parameter_blocks, &problem))
throw CovarianceException("Could not compute covariance in computeCovariance()");
Eigen::MatrixXd cov_matrix(n_params_in_selected, n_params_in_selected);
if (!covariance.GetCovarianceMatrix(parameter_blocks, cov_matrix.data()))
{
throw CovarianceException("GetCovarianceMatrix failed in computeCovariance()");
}
// 2. Extract the tangent space cov matrix
Eigen::MatrixXd tangent_space_cov_matrix(tangent_space_labels.size(), tangent_space_labels.size());
for (std::size_t r = 0; r < tangent_space_indices.size(); ++r)
{
for (std::size_t c = 0; c < tangent_space_indices.size(); ++c)
{
tangent_space_cov_matrix(r, c) = cov_matrix(tangent_space_indices[r], tangent_space_indices[c]);
}
}
// 3. Get the covariance results
return computeCovarianceResults(tangent_space_cov_matrix, tangent_space_labels);
}
} // namespace rct_optimizations
| 40.556098
| 160
| 0.66827
|
m-limbird
|
60c370f91241b04e0e20b1fe48bc466e757d5d7b
| 410
|
cpp
|
C++
|
Week7/Example1.cpp
|
Invvk/Programming-Introduction-Lab
|
48c2b05b5fef9a33bef5e2f9fd4f463bd4bc3506
|
[
"MIT"
] | null | null | null |
Week7/Example1.cpp
|
Invvk/Programming-Introduction-Lab
|
48c2b05b5fef9a33bef5e2f9fd4f463bd4bc3506
|
[
"MIT"
] | null | null | null |
Week7/Example1.cpp
|
Invvk/Programming-Introduction-Lab
|
48c2b05b5fef9a33bef5e2f9fd4f463bd4bc3506
|
[
"MIT"
] | null | null | null |
// Example 1: predefined functions
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int x;
double u = 4.2, v = 3.0;
cout << "\t " << u << " to the power of " << v << " = " << pow(u, v) << endl;
cout << "5.0 to the power of 4 = " << pow(5.0, 4) << endl;
u = u + pow(3.0, 3);
cout << "u = " << u << endl;
x = -15;
cout << "Absolute value of x is " << abs(x) << endl;
return 0;
}
| 22.777778
| 78
| 0.509756
|
Invvk
|
60c5286442f3a45793b313a0e1758896a6d4f0c0
| 1,437
|
cpp
|
C++
|
C++/Algorithms/BinaryTrees/inorderTraversal.cpp
|
joao-neves95/Exercises_Challenges_Courses
|
02b6e25d9a270395bbf6dc8111c2419bba4f3edc
|
[
"MIT"
] | null | null | null |
C++/Algorithms/BinaryTrees/inorderTraversal.cpp
|
joao-neves95/Exercises_Challenges_Courses
|
02b6e25d9a270395bbf6dc8111c2419bba4f3edc
|
[
"MIT"
] | 4
|
2018-11-10T01:05:14.000Z
|
2021-06-25T15:16:28.000Z
|
C++/Algorithms/BinaryTrees/inorderTraversal.cpp
|
joao-neves95/Exercises_Challenges_Courses
|
02b6e25d9a270395bbf6dc8111c2419bba4f3edc
|
[
"MIT"
] | null | null | null |
/**
* @file inorderTraversal.cpp
* @author João Neves (https://github.com/joao-neves95)
* @brief
* Traverse the left subtree first. Then visit the root. Finally, traverse the right subtree.
*
* @version 1.0.0
* @copyright Copyright (c) 2021
* (_SHIVAYL_)
*/
#include <vector>
#include <stack>
using namespace std;
/*
Definition for a binary tree node.
*/
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
/**/
class Solution {
public:
vector<int> inorderTraversalIterative(TreeNode* root) {
vector<int> res;
if (root == nullptr) {
return res;
}
stack<TreeNode*> nodeStack;
TreeNode* currNode = root;
while (!nodeStack.empty() || currNode != nullptr) {
while (currNode != nullptr) {
nodeStack.push(currNode);
currNode = currNode->left;
}
// Pop left first.
currNode = nodeStack.top();
nodeStack.pop();
res.push_back(currNode->val);
// Then check right.
currNode = currNode->right;
}
return res;
}
};
int main(int argc, char const *argv[])
{
return 0;
}
| 22.107692
| 94
| 0.565066
|
joao-neves95
|
60c73f98a8dd7de658b5cbac8ba8cd5b38eeafbc
| 882
|
cpp
|
C++
|
src/training/KillsReachedCondition.cpp
|
FreeAllegiance/AllegianceDX7
|
3955756dffea8e7e31d3a55fcf6184232b792195
|
[
"MIT"
] | 76
|
2015-08-18T19:18:40.000Z
|
2022-01-08T12:47:22.000Z
|
src/training/KillsReachedCondition.cpp
|
StudentAlleg/Allegiance
|
e91660a471eb4e57e9cea4c743ad43a82f8c7b18
|
[
"MIT"
] | 37
|
2015-08-14T22:44:12.000Z
|
2020-01-21T01:03:06.000Z
|
src/training/KillsReachedCondition.cpp
|
StudentAlleg/Allegiance
|
e91660a471eb4e57e9cea4c743ad43a82f8c7b18
|
[
"MIT"
] | 42
|
2015-08-13T23:31:35.000Z
|
2022-03-17T02:20:26.000Z
|
#include "pch.h"
#include "KillsReachedCondition.h"
#include "Training.h"
namespace Training
{
//------------------------------------------------------------------------------
// class methods
//------------------------------------------------------------------------------
/* void */ KillsReachedCondition::KillsReachedCondition(int kills) :
m_kills(kills)
{
}
//------------------------------------------------------------------------------
/* void */ KillsReachedCondition::~KillsReachedCondition(void)
{
}
//------------------------------------------------------------------------------
bool KillsReachedCondition::Evaluate(void)
{
if (Training::GetKillCount() >= m_kills)
debugf(">>>reached %d kills\n", m_kills);
return (Training::GetKillCount() >= m_kills);
}
}
| 31.5
| 84
| 0.370748
|
FreeAllegiance
|
60c79940e0b519f64a0eb903fa54ad2c53bb524e
| 2,108
|
cpp
|
C++
|
src/window.cpp
|
pyth/2d_ik_solver
|
70052397404e5eec8b89817698cf49205a98b8be
|
[
"MIT"
] | 4
|
2018-07-09T20:51:05.000Z
|
2022-01-26T05:56:50.000Z
|
src/window.cpp
|
pyth/2d_ik_solver
|
70052397404e5eec8b89817698cf49205a98b8be
|
[
"MIT"
] | null | null | null |
src/window.cpp
|
pyth/2d_ik_solver
|
70052397404e5eec8b89817698cf49205a98b8be
|
[
"MIT"
] | 1
|
2021-12-16T13:47:48.000Z
|
2021-12-16T13:47:48.000Z
|
#include "window.h"
Window::Window() {
running = true;
new_target = false;
active_bone = 0;
window = SDL_CreateWindow("IK Solver", 100, 100, 1024, 768, 0);
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
chain = new Chain(renderer);
Bone *bone1 = new Bone(255, 0, 0);
bone1->set_rot(0.f);
bone1->set_transl(250, 300);
bone1->set_offset(200, 0);
chain->add_link(bone1);
Bone *bone2 = new Bone(0, 255, 0, 0);
bone2->set_offset(100, 0);
chain->add_link(bone2);
Bone *bone3 = new Bone(0, 0, 255, 1);
bone3->set_offset(50, 0);
chain->add_link(bone3);
Bone *bone4 = new Bone(255, 0, 255, 2);
bone4->set_offset(25, 0);
chain->add_link(bone4);
}
Window::~Window() {
delete chain;
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
}
void Window::mainloop() {
while(running) {
SDL_Event e;
if(SDL_PollEvent(&e)) {
switch(e.type) {
case SDL_QUIT:
running = false;
break;
case SDL_KEYDOWN:
switch(e.key.keysym.sym) {
case SDLK_ESCAPE:
running = false;
break;
case SDLK_1:
active_bone = 0;
break;
case SDLK_2:
active_bone = 1;
break;
case SDLK_3:
active_bone = 2;
break;
}
break;
case SDL_MOUSEBUTTONDOWN:
target.x() = (float)e.button.x;
target.y() = (float)e.button.y;
new_target = true;
break;
case SDL_MOUSEWHEEL:
chain->bones[active_bone]->increse_rot(e.wheel.y / 180.0 * M_PI);
break;
}
}
move_to_target();
draw();
SDL_RenderPresent(renderer);
SDL_Delay(1);
}
}
void Window::move_to_target() {
if(new_target) {
Eigen::Vector2d e_tmp = chain->effector;
chain->move_to_target(target);
if((e_tmp - chain->effector).norm() < 0.0001f || (chain->effector - target).norm() < 1)
new_target = false;
}
}
void Window::draw() {
SDL_SetRenderDrawColor(renderer, 100, 100, 100, 255);
SDL_RenderClear(renderer);
chain->draw();
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
SDL_Rect rect;
rect.x = target.x() - 3;
rect.y = target.y() - 3;
rect.w = 5;
rect.h = 5;
SDL_RenderFillRect(renderer, &rect);
}
| 20.466019
| 89
| 0.641841
|
pyth
|
60cbc859fab4a698b435bc37af07705eca251f31
| 542
|
hpp
|
C++
|
Source/State/MenuState.hpp
|
ace13/MiniLD61
|
b2789a6062ba8f64b005c8ae6f81faea44248560
|
[
"MIT"
] | null | null | null |
Source/State/MenuState.hpp
|
ace13/MiniLD61
|
b2789a6062ba8f64b005c8ae6f81faea44248560
|
[
"MIT"
] | null | null | null |
Source/State/MenuState.hpp
|
ace13/MiniLD61
|
b2789a6062ba8f64b005c8ae6f81faea44248560
|
[
"MIT"
] | null | null | null |
#pragma once
#include "StateManager.hpp"
#include <Menu/MenuPane.hpp>
#include <SFML/System/Clock.hpp>
#include <list>
class MenuState : public IState
{
public:
MenuState();
~MenuState();
void init();
void handle_event(sf::Event& ev);
void fixed_update(float dt);
void variadic_update(float dt);
void draw(sf::RenderTarget& target);
void drawUI(sf::RenderTarget& target);
std::string getName() const { return "MenuState"; }
void pushPane(MenuPane* pane);
MenuPane* popPane();
private:
std::list<MenuPane*> mMenuPanes;
};
| 16.9375
| 52
| 0.714022
|
ace13
|
60cca4a9db853bfe5bb71508dbddd3fc0481a457
| 25,610
|
cpp
|
C++
|
pgadmin/frm/frmRestore.cpp
|
jcjc79/pgadmin3
|
be0f94786bf5b8138c9e6ec1b0b295308f8f89b6
|
[
"OLDAP-2.2.1"
] | 5
|
2019-09-18T08:05:31.000Z
|
2021-04-26T03:05:52.000Z
|
pgadmin/frm/frmRestore.cpp
|
theory/pgadmin3
|
5eeee31f8c4f42907b1edf1a6984cdee7323ddaa
|
[
"PostgreSQL"
] | null | null | null |
pgadmin/frm/frmRestore.cpp
|
theory/pgadmin3
|
5eeee31f8c4f42907b1edf1a6984cdee7323ddaa
|
[
"PostgreSQL"
] | 4
|
2020-03-04T09:50:13.000Z
|
2021-02-02T03:28:04.000Z
|
//////////////////////////////////////////////////////////////////////////
//
// pgAdmin III - PostgreSQL Tools
//
// Copyright (C) 2002 - 2013, The pgAdmin Development Team
// This software is released under the PostgreSQL Licence
//
// frmRestore.cpp - Restore database dialogue
//
//////////////////////////////////////////////////////////////////////////
#include "pgAdmin3.h"
// wxWindows headers
#include <wx/wx.h>
#include <wx/settings.h>
#include <wx/process.h>
#include <wx/textbuf.h>
#include <wx/dir.h>
#include <wx/file.h>
#include <wx/filename.h>
// App headers
#include "frm/frmRestore.h"
#include "frm/frmMain.h"
#include "utils/sysLogger.h"
#include "schema/pgTable.h"
#include "schema/pgFunction.h"
#include "schema/pgLanguage.h"
#include "schema/pgConstraints.h"
#include "schema/pgForeignKey.h"
#include "ctl/ctlCheckTreeView.h"
// Icons
#include "images/restore.pngc"
#define nbNotebook CTRL_NOTEBOOK("nbNotebook")
#define txtFilename CTRL_TEXT("txtFilename")
#define btnFilename CTRL_BUTTON("btnFilename")
#define cbFormat CTRL_COMBOBOX("cbFormat")
#define cbRolename CTRL_COMBOBOX("cbRolename")
#define chkOnlyData CTRL_CHECKBOX("chkOnlyData")
#define chkOnlySchema CTRL_CHECKBOX("chkOnlySchema")
#define chkNoOwner CTRL_CHECKBOX("chkNoOwner")
#define chkNoPrivileges CTRL_CHECKBOX("chkNoPrivileges")
#define chkNoTablespaces CTRL_CHECKBOX("chkNoTablespaces")
#define chkCreateDb CTRL_CHECKBOX("chkCreateDb")
#define chkClean CTRL_CHECKBOX("chkClean")
#define chkSingleXact CTRL_CHECKBOX("chkSingleXact")
#define chkDisableTrigger CTRL_CHECKBOX("chkDisableTrigger")
#define chkNoDataForFailedTables CTRL_CHECKBOX("chkNoDataForFailedTables")
#define chkUseSetSession CTRL_CHECKBOX("chkUseSetSession")
#define chkExitOnError CTRL_CHECKBOX("chkExitOnError")
#define txtNumberOfJobs CTRL_TEXT("txtNumberOfJobs")
#define chkVerbose CTRL_CHECKBOX("chkVerbose")
#define stSingleObject CTRL_STATIC("stSingleObject")
#define chkSectionPreData CTRL_CHECKBOX("chkSectionPreData")
#define chkSectionData CTRL_CHECKBOX("chkSectionData")
#define chkSectionPostData CTRL_CHECKBOX("chkSectionPostData")
#define ctvObjects CTRL_CHECKTREEVIEW("ctvObjects")
#define btnView CTRL_BUTTON("btnView")
BEGIN_EVENT_TABLE(frmRestore, ExternProcessDialog)
EVT_TEXT(XRCID("txtFilename"), frmRestore::OnChangeName)
EVT_COMBOBOX(XRCID("cbFormat"), frmRestore::OnChangeFormat)
EVT_CHECKBOX(XRCID("chkOnlyData"), frmRestore::OnChangeData)
EVT_CHECKBOX(XRCID("chkOnlySchema"), frmRestore::OnChangeSchema)
EVT_BUTTON(XRCID("btnFilename"), frmRestore::OnSelectFilename)
EVT_BUTTON(wxID_OK, frmRestore::OnOK)
EVT_BUTTON(XRCID("btnView"), frmRestore::OnView)
EVT_END_PROCESS(-1, frmRestore::OnEndProcess)
EVT_CLOSE( ExternProcessDialog::OnClose)
EVT_CHECKBOX(XRCID("chkSectionPreData"), frmRestore::OnChangeSection)
EVT_CHECKBOX(XRCID("chkSectionData"), frmRestore::OnChangeSection)
EVT_CHECKBOX(XRCID("chkSectionPostData"), frmRestore::OnChangeSection)
END_EVENT_TABLE()
frmRestore::frmRestore(frmMain *_form, pgObject *obj) : ExternProcessDialog(form)
{
object = obj;
if (object->GetMetaType() == PGM_SERVER)
server = (pgServer *)object;
else
server = object->GetDatabase()->GetServer();
form = _form;
wxWindowBase::SetFont(settings->GetSystemFont());
LoadResource(_form, wxT("frmRestore"));
RestorePosition();
SetTitle(object->GetTranslatedMessage(RESTORETITLE));
if (object->GetConnection()->EdbMinimumVersion(8, 0))
restoreExecutable = edbRestoreExecutable;
else if (object->GetConnection()->GetIsGreenplum())
restoreExecutable = gpRestoreExecutable;
else
restoreExecutable = pgRestoreExecutable;
if (object->GetMetaType() != PGM_DATABASE)
{
chkOnlySchema->SetValue(object->GetMetaType() == PGM_FUNCTION
|| object->GetMetaType() == PGM_INDEX
|| object->GetMetaType() == PGM_TRIGGER);
chkOnlyData->SetValue(object->GetMetaType() == PGM_TABLE
|| object->GetMetaType() == GP_PARTITION);
if (object->GetMetaType() != PGM_SCHEMA)
{
chkOnlyData->Disable();
chkOnlySchema->Disable();
}
if (object->GetMetaType() == PGM_FUNCTION)
{
chkClean->SetValue(true);
chkClean->Disable();
}
btnView->Disable();
}
wxString val;
settings->Read(wxT("frmRestore/LastFile"), &val, wxEmptyString);
txtFilename->SetValue(val);
// Icon
SetIcon(*restore_png_ico);
txtMessages = CTRL_TEXT("txtMessages");
// Note that under GTK+, SetMaxLength() function may only be used with single line text controls.
// (see http://docs.wxwidgets.org/2.8/wx_wxtextctrl.html#wxtextctrlsetmaxlength)
#ifndef __WXGTK__
txtMessages->SetMaxLength(0L);
#endif
btnOK->Disable();
filenameValid = false;
if (!server->GetPasswordIsStored())
environment.Add(wxT("PGPASSWORD=") + server->GetPassword());
// Pass the SSL mode via the environment
environment.Add(wxT("PGSSLMODE=") + server->GetConnection()->GetSslModeName());
if (server->GetSSLRootCert() != wxEmptyString)
environment.Add(wxT("PGSSLROOTCERT=") + server->GetSSLRootCert());
if (server->GetSSLCert() != wxEmptyString)
environment.Add(wxT("PGSSLCERT=") + server->GetSSLCert());
if (server->GetSSLKey() != wxEmptyString)
environment.Add(wxT("PGSSLKEY=") + server->GetSSLKey());
if (server->GetSSLCrl() != wxEmptyString)
environment.Add(wxT("PGSSLCRL=") + server->GetSSLCrl());
if (!pgAppMinimumVersion(restoreExecutable, 8, 4))
{
chkNoTablespaces->Disable();
chkSingleXact->Disable();
txtNumberOfJobs->Disable();
cbRolename->Disable();
}
else
{
// Available rolenames
if (server->GetConnection()->BackendMinimumVersion(8, 1))
{
pgSetIterator set(server->GetConnection(),
wxT("SELECT DISTINCT rolname\n")
wxT("FROM pg_roles db\n")
wxT("ORDER BY rolname"));
cbRolename->Append(wxEmptyString);
while(set.RowsLeft())
cbRolename->Append(set.GetVal(wxT("rolname")));
cbRolename->SetValue(server->GetRolename());
cbRolename->Enable(true);
}
else
cbRolename->Disable();
}
if (!pgAppMinimumVersion(restoreExecutable, 8, 2))
{
chkNoDataForFailedTables->Disable();
}
if (!pgAppMinimumVersion(restoreExecutable, 8, 0))
{
chkExitOnError->Disable();
}
cbFormat->Append(_("Custom or tar"));
if (pgAppMinimumVersion(restoreExecutable, 9, 1))
cbFormat->Append(_("Directory"));
cbFormat->SetSelection(0);
if (!pgAppMinimumVersion(restoreExecutable, 9, 2))
{
chkSectionPreData->Disable();
chkSectionData->Disable();
chkSectionPostData->Disable();
}
wxCommandEvent ev;
OnChangeName(ev);
}
frmRestore::~frmRestore()
{
SavePosition();
}
wxString frmRestore::GetHelpPage() const
{
wxString page;
page = wxT("pg/app-pgrestore");
return page;
}
void frmRestore::OnSelectFilename(wxCommandEvent &ev)
{
if (cbFormat->GetSelection() == 0) // custom or tar
{
wxString FilenameOnly;
wxFileName::SplitPath(txtFilename->GetValue(), NULL, NULL, &FilenameOnly, NULL);
#ifdef __WXMSW__
wxFileDialog file(this, _("Select backup filename"), ::wxPathOnly(txtFilename->GetValue()), FilenameOnly,
_("Backup files (*.backup)|*.backup|All files (*.*)|*.*"));
#else
wxFileDialog file(this, _("Select backup filename"), ::wxPathOnly(txtFilename->GetValue()), FilenameOnly,
_("Backup files (*.backup)|*.backup|All files (*)|*"));
#endif
if (file.ShowModal() == wxID_OK)
{
txtFilename->SetValue(file.GetPath());
OnChange(ev);
}
}
else
{
wxDirDialog dir(this, _("Select the backup directory"), txtFilename->GetValue());
if (dir.ShowModal() == wxID_OK)
{
txtFilename->SetValue(dir.GetPath());
OnChange(ev);
}
}
}
void frmRestore::OnChangeFormat(wxCommandEvent &ev)
{
btnView->Enable(cbFormat->GetSelection() == 0);
}
void frmRestore::OnChangeData(wxCommandEvent &ev)
{
chkOnlySchema->Enable(!chkOnlyData->GetValue());
chkSectionPreData->Enable(!chkOnlyData->GetValue());
chkSectionData->Enable(!chkOnlyData->GetValue());
chkSectionPostData->Enable(!chkOnlyData->GetValue());
OnChange(ev);
}
void frmRestore::OnChangeSchema(wxCommandEvent &ev)
{
chkOnlyData->Enable(!chkOnlySchema->GetValue());
chkSectionPreData->Enable(!chkOnlySchema->GetValue());
chkSectionData->Enable(!chkOnlySchema->GetValue());
chkSectionPostData->Enable(!chkOnlySchema->GetValue());
OnChange(ev);
}
void frmRestore::OnChangeSection(wxCommandEvent &ev)
{
bool isSection = chkSectionPreData->GetValue() || chkSectionData->GetValue() || chkSectionPostData->GetValue();
chkOnlySchema->Enable(!isSection);
chkOnlyData->Enable(!isSection);
OnChange(ev);
}
void frmRestore::OnChangeName(wxCommandEvent &ev)
{
wxString name = txtFilename->GetValue();
if (cbFormat->GetSelection() == 0)
{
if (name.IsEmpty() || !wxFile::Exists(name))
filenameValid = false;
else
{
wxFile file(name, wxFile::read);
if (file.IsOpened())
{
char buffer[8];
off_t size = file.Read(buffer, 8);
if (size == 8)
{
if (memcmp(buffer, "PGDMP", 5) && !memcmp(buffer, "toc.dat", 8))
{
// tar format?
file.Seek(512);
size = file.Read(buffer, 8);
}
if (size == 8 && !memcmp(buffer, "PGDMP", 5))
{
// check version here?
filenameValid = true;
}
}
}
}
}
else
{
filenameValid = wxDir::Exists(name);
}
OnChange(ev);
}
void frmRestore::OnChange(wxCommandEvent &ev)
{
btnOK->Enable(filenameValid);
btnView->Enable(filenameValid && object->GetMetaType() == PGM_DATABASE);
}
wxString frmRestore::GetCmd(int step)
{
wxString cmd = getCmdPart1();
return cmd + getCmdPart2(step);
}
wxString frmRestore::GetDisplayCmd(int step)
{
wxString cmd = getCmdPart1();
return cmd + getCmdPart2(step);
}
wxString frmRestore::getCmdPart1()
{
wxString cmd;
cmd = restoreExecutable;
if (!server->GetName().IsEmpty())
cmd += wxT(" --host ") + server->GetName();
cmd += wxT(" --port ") + NumToStr((long)server->GetPort())
+ wxT(" --username ") + commandLineCleanOption(qtIdent(server->GetUsername()))
+ wxT(" --dbname ") + commandLineCleanOption(object->GetDatabase()->GetQuotedIdentifier());
if (!cbRolename->GetValue().IsEmpty())
cmd += wxT(" --role ") + commandLineCleanOption(qtIdent(cbRolename->GetValue()));
if (pgAppMinimumVersion(restoreExecutable, 8, 4))
cmd += wxT(" --no-password ");
return cmd;
}
wxString frmRestore::getCmdPart2(int step)
{
wxString cmd;
wxString restoreExecutable;
if (object->GetConnection()->EdbMinimumVersion(8, 0))
restoreExecutable = edbBackupExecutable;
else if (object->GetConnection()->GetIsGreenplum())
restoreExecutable = gpBackupExecutable;
else
restoreExecutable = pgBackupExecutable;
if (step)
{
cmd.Append(wxT(" --list"));
}
else
{
if (cbFormat->GetSelection() == 1) // directory
{
cmd.Append(wxT(" --format directory"));
}
// Section
if (pgAppMinimumVersion(restoreExecutable, 9, 2))
{
if (chkSectionPreData->GetValue())
cmd.Append(wxT(" --section pre-data"));
if (chkSectionData->GetValue())
cmd.Append(wxT(" --section data"));
if (chkSectionPostData->GetValue())
cmd.Append(wxT(" --section post-data"));
}
if (chkOnlyData->GetValue())
{
cmd.Append(wxT(" --data-only"));
}
else
{
if (chkNoOwner->GetValue())
cmd.Append(wxT(" --no-owner"));
if (chkNoPrivileges->GetValue())
cmd.Append(wxT(" --no-privileges"));
if (chkNoTablespaces->GetValue())
cmd.Append(wxT(" --no-tablespaces"));
}
if (chkOnlySchema->GetValue())
{
cmd.Append(wxT(" --schema-only"));
}
else
{
if (chkDisableTrigger->GetValue())
cmd.Append(wxT(" --disable-triggers"));
}
if (chkCreateDb->GetValue())
cmd.Append(wxT(" --create"));
if (chkClean->GetValue())
cmd.Append(wxT(" --clean"));
if (chkSingleXact->GetValue())
cmd.Append(wxT(" --single-transaction"));
if (chkNoDataForFailedTables->GetValue())
cmd.Append(wxT(" --no-data-for-failed-tables"));
if (chkUseSetSession->GetValue())
cmd.Append(wxT(" --use-set-session-authorization"));
if (chkExitOnError->GetValue())
cmd.Append(wxT(" --exit-on-error"));
if (!txtNumberOfJobs->GetValue().IsEmpty())
cmd.Append(wxT(" --jobs ") + txtNumberOfJobs->GetValue());
// Process selected items
wxTreeItemId root, firstLevelObject, secondLevelObject;
wxTreeItemIdValue firstLevelObjectData, secondLevelObjectData;
bool partialDump = false;
// Get root object
root = ctvObjects->GetRootItem();
if (root && object->GetMetaType() == PGM_DATABASE)
{
// Prepare the array
wxArrayString restoreStrings;
restoreStrings.Add(wxEmptyString, numberOfTOCItems);
restoreTreeItemData *data;
// Loop through first level objects
firstLevelObject = ctvObjects->GetFirstChild(root, firstLevelObjectData);
while (firstLevelObject.IsOk())
{
if (ctvObjects->IsChecked(firstLevelObject))
{
// Write the file
data = (restoreTreeItemData *)ctvObjects->GetItemData(firstLevelObject);
restoreStrings[data->GetId()] = data->GetDesc();
// Loop through second level objects
secondLevelObject = ctvObjects->GetFirstChild(firstLevelObject, secondLevelObjectData);
while (secondLevelObject.IsOk())
{
if (ctvObjects->IsChecked(secondLevelObject))
{
// Write the file
data = (restoreTreeItemData *)ctvObjects->GetItemData(secondLevelObject);
restoreStrings[data->GetId()] = data->GetDesc();
}
else
partialDump = true;
secondLevelObject = ctvObjects->GetNextChild(firstLevelObject, secondLevelObjectData);
}
}
else
partialDump = true;
firstLevelObject = ctvObjects->GetNextChild(root, firstLevelObjectData);
}
// Open a temporary file to store the TOC
restoreTOCFilename = wxFileName::CreateTempFileName(wxT("restore"));
wxFile tocFile;
tocFile.Open(restoreTOCFilename.c_str(), wxFile::write);
// Write all selected items in it
for (int i = 0; i < numberOfTOCItems; i++)
{
if (restoreStrings[i] != wxEmptyString)
{
if (!tocFile.Write(restoreStrings[i] + wxT("\n")))
{
wxLogError(_("Error writing to the temporary file ") + restoreTOCFilename);
}
}
}
// If some items were not checked and if the file still contains something, we have to use the list
if (partialDump && tocFile.Length() > 0)
cmd.Append(wxT(" --use-list \"") + restoreTOCFilename + wxT("\""));
tocFile.Close();
}
else if (object->GetMetaType() != PGM_DATABASE)
{
switch (object->GetMetaType())
{
case PGM_FUNCTION:
cmd.Append(wxT(" --function ") + commandLineCleanOption(qtIdent(object->GetFullName()), true));
break;
case PGM_INDEX:
cmd.Append(wxT(" --index ") + commandLineCleanOption(object->GetQuotedIdentifier(), true));
break;
case PGM_TABLE:
cmd.Append(wxT(" --table ") + commandLineCleanOption(object->GetQuotedIdentifier(), true));
break;
case PGM_TRIGGER:
cmd.Append(wxT(" --trigger ") + commandLineCleanOption(object->GetQuotedIdentifier(), true));
break;
default:
break;
}
if (object->GetMetaType() == PGM_SCHEMA)
cmd.Append(wxT(" --schema ") + commandLineCleanOption(object->GetQuotedIdentifier(), true));
else if (pgAppMinimumVersion(restoreExecutable, 8, 2))
cmd.Append(wxT(" --schema ") + commandLineCleanOption(object->GetSchema()->GetQuotedIdentifier(), true));
}
if (settings->GetIgnoreVersion())
cmd.Append(wxT(" --ignore-version"));
if (chkVerbose->GetValue())
cmd.Append(wxT(" --verbose"));
}
cmd.Append(wxT(" \"") + txtFilename->GetValue() + wxT("\""));
return cmd;
}
void frmRestore::OnView(wxCommandEvent &ev)
{
btnView->Disable();
btnOK->Disable();
viewRunning = true;
Execute(1, false);
btnOK->SetLabel(_("OK"));
done = 0;
}
void frmRestore::OnOK(wxCommandEvent &ev)
{
if (!done)
{
if (processedFile == txtFilename->GetValue())
{
if (wxMessageBox(_("Are you sure you wish to run a restore from this file again?"), _("Repeat restore?"), wxICON_QUESTION | wxYES_NO) != wxYES)
return;
}
processedFile = txtFilename->GetValue();
}
settings->Write(wxT("frmRestore/LastFile"), txtFilename->GetValue());
viewRunning = false;
btnView->Disable();
ExternProcessDialog::OnOK(ev);
}
void frmRestore::OnEndProcess(wxProcessEvent &ev)
{
ExternProcessDialog::OnEndProcess(ev);
if (done && viewRunning && !ev.GetExitCode())
{
done = false;
wxString str = wxTextBuffer::Translate(txtMessages->GetValue(), wxTextFileType_Unix);
wxStringTokenizer line(str, wxT("\n"));
line.GetNextToken();
wxBeginBusyCursor();
wxString i18nbackup = _("Backup");
wxTreeItemId root = ctvObjects->AddRoot(i18nbackup + wxT(" ") + txtFilename->GetValue());
wxString currentSchema = wxT("");
wxTreeItemId currentSchemaNode;
wxTreeItemId schemaNode, lastItem, extensionNode;
wxTreeItemIdValue schemaNodeData, extensionNodeData;
numberOfTOCItems = 0;
while (line.HasMoreTokens())
{
// Read the next line
str = line.GetNextToken();
// If this is the last line, it contains process information - skip it!
if (!line.HasMoreTokens())
continue;
// Skip the few lines of comments
if (str.Left(1) == wxT(";") || str.Left(1) == wxT("P"))
continue;
// Split the line according to spaces
wxStringTokenizer col(str, wxT(" "));
// Column 1 (dumpId)
col.GetNextToken();
// Column 2 (tableOid)
col.GetNextToken();
// Column 3 (oid)
col.GetNextToken();
// Column 4 (desc)
// First interesting information: object's type
wxString type = col.GetNextToken();
if (type == wxT("DATABASE"))
{
// We are restoring a database, not creating one. So ignore
// this line as there is no valid schema info and move on
// to the next object
continue;
}
else if (type == wxT("PROCEDURAL"))
{
// type for a PL is PROCEDURAL LANGUAGE
// we'll keep the next column for the object's type
type = col.GetNextToken();
}
else if (type == wxT("SHELL"))
{
// type for a SHELL is SHELL TYPE
// we'll keep both columns for the object's type
type += col.GetNextToken();
}
else if (type == wxT("OPERATOR"))
{
// type for an operator class is OPERATOR CLASS
// we'll keep the two columns for the object's type
wxString tmp = str.Mid(str.Find(type) + type.Length() + 1, 5);
if (tmp == wxT("CLASS"))
type += wxT(" ") + col.GetNextToken();
}
else if (type == wxT("SEQUENCE"))
{
// type for a sequence can be SEQUENCE, SEQUENCE OWNED BY or SEQUENCE SET
// we'll keep all these columns for the object's type
wxString tmp = str.Mid(str.Find(type) + type.Length() + 1, 3);
if (tmp == wxT("OWN") || tmp == wxT("SET"))
{
type += wxT(" ") + col.GetNextToken();
if (type == wxT("SEQUENCE OWNED"))
type += wxT(" ") + col.GetNextToken();
}
}
else if (type == wxT("FK"))
{
// type for a FK is FK CONSTRAINT
// we'll keep the next column for the object's type
type = col.GetNextToken();
}
else if (type == wxT("TABLE"))
{
if (col.CountTokens() == 4)
{
// TABLE DATA detected
type += wxT(" ") + col.GetNextToken();
}
}
// In case of statements like DEFAULT ACL <schema name> DEFAULT PRIVILEGES FOR TABLES <privilege>
else if (type == wxT("DEFAULT"))
{
// We do not expect the 'DEFAULT <schema> <type> <name>' pattern here.
if (col.CountTokens() != 3)
{
type += wxT(" ") + col.GetNextToken();
if (type != wxT("DEFAULT ACL"))
{
wxLogError(wxString::Format(_("Unexpected DEFAULT statement found: '%s'!"), str.c_str()));
continue;
}
}
}
// Column 5 (namespace)
// Second interesting information: object's schema
wxString schema = col.GetNextToken();
// Column 6 (tag)
// Third interesting information: object's qualified name
//wxString name=col.GetNextToken();
wxString name = str.Mid(str.Find(schema) + schema.Length() + 1).BeforeLast(' ');
// Column 7 (owner)
// Fourth interesting information: object's owner
wxString owner = str.Mid(str.Find(name) + name.Length() + 1);
// New method
if (type == wxT("LANGUAGE"))
{
lastItem = ctvObjects->AppendItem(root, wxT("Language ") + name + wxT(" [") + _("owner") + wxT(": ") + owner + wxT("]"), 1);
}
else if (type == wxT("ACL") && schema == wxT("-"))
{
lastItem = ctvObjects->AppendItem(root, type + wxT(" ") + name, 1);
}
else if (type == wxT("CAST"))
{
lastItem = ctvObjects->AppendItem(root, name, 1);
}
else if (type == wxT("SCHEMA"))
{
currentSchema = name;
lastItem = currentSchemaNode = ctvObjects->AppendItem(root, wxT("Schema ") + name, 1);
}
else if (type == wxT("EXTENSION") && (schema == wxT("-") || schema.IsEmpty()))
{
lastItem = ctvObjects->AppendItem(root,
owner.IsEmpty() ? wxT("Extension ") + name :
wxT("Extension ") + name + wxT("[") + _("owner") + wxT(": ") + owner + wxT("]"), 1);
}
else if (type == wxT("COMMENT") && name.StartsWith(wxT("EXTENSION ")))
{
wxString extension = name.SubString(10, name.Length());
if (ctvObjects->GetItemText(lastItem) == wxT("Extension ") + extension)
{
extensionNode = lastItem;
}
else
{
wxTreeItemId searchStartNode = root;
if (schema != wxT("-"))
{
searchStartNode = currentSchemaNode;
if (schema != currentSchema)
{
searchStartNode = ctvObjects->GetFirstChild(root, schemaNodeData);
bool found = false;
while (searchStartNode.IsOk() && !found)
{
if (ctvObjects->GetItemText(searchStartNode) == wxT("Schema ") + schema)
found = true;
else
searchStartNode = ctvObjects->GetNextChild(root, schemaNodeData);
}
// Found it?
if (!searchStartNode.IsOk())
{
searchStartNode = schemaNode;
}
else
{
searchStartNode = root;
}
}
}
extensionNode = ctvObjects->GetFirstChild(searchStartNode, extensionNodeData);
bool found = false;
while (extensionNode.IsOk() && !found)
{
if (ctvObjects->GetItemText(extensionNode) == wxT("Extension ") + extension)
found = true;
else
extensionNode = ctvObjects->GetNextChild(searchStartNode, schemaNodeData);
}
}
if (extensionNode.IsOk())
{
lastItem = ctvObjects->AppendItem(extensionNode,
owner.IsEmpty() ? type + wxT(" Extension ") + extension :
type + wxT(" Extension ") + extension + wxT(" [") + _("owner") + wxT(": ") + owner + wxT("]"), 1);
}
}
else
{
if (schema != currentSchema)
{
// Loop through the nodes to find the schema
schemaNode = ctvObjects->GetFirstChild(root, schemaNodeData);
bool found = false;
while (schemaNode.IsOk() && !found)
{
if (ctvObjects->GetItemText(schemaNode) == wxT("Schema ") + schema)
found = true;
else
schemaNode = ctvObjects->GetNextChild(root, schemaNodeData);
}
// Found it?
if (schemaNode.IsOk())
{
currentSchema = schema;
currentSchemaNode = schemaNode;
}
// if we are treating a comment, we use the schema of its
// object (ie, the previous line)
else if (type != wxT("COMMENT"))
{
wxLogError(_("Schema node not found for object ") + type + wxT(" ") + name + wxT(" [") + _("owner") + wxT(": ") + owner + wxT("]"));
}
}
lastItem = ctvObjects->AppendItem(currentSchemaNode,
owner.IsEmpty() ? type + wxT(" ") + name :
type + wxT(" ") + name + wxT(" [") + _("owner") + wxT(": ") + owner + wxT("]"), 1);
}
ctvObjects->SetItemData(lastItem, new restoreTreeItemData(numberOfTOCItems, str));
numberOfTOCItems++;
}
wxEndBusyCursor();
nbNotebook->SetSelection(3);
}
else
{
wxRemoveFile(restoreTOCFilename);
}
}
void frmRestore::Go()
{
txtFilename->SetFocus();
Show(true);
}
restoreFactory::restoreFactory(menuFactoryList *list, wxMenu *mnu, ctlMenuToolbar *toolbar) : contextActionFactory(list)
{
mnu->Append(id, _("&Restore..."), _("Restores a backup from a local file"));
}
wxWindow *restoreFactory::StartDialog(frmMain *form, pgObject *obj)
{
frmRestore *frm = new frmRestore(form, obj);
frm->Go();
return 0;
}
bool restoreFactory::CheckEnable(pgObject *obj)
{
if (!obj)
return false;
if (obj->GetConnection() && obj->GetConnection()->EdbMinimumVersion(8, 0))
return obj->CanCreate() && obj->CanRestore() && !edbRestoreExecutable.IsEmpty();
else if (obj->GetConnection() && obj->GetConnection()->GetIsGreenplum())
return obj->CanCreate() && obj->CanRestore() && !gpRestoreExecutable.IsEmpty();
else
return obj->CanCreate() && obj->CanRestore() && !pgRestoreExecutable.IsEmpty();
}
restoreTreeItemData::restoreTreeItemData(int id, const wxString &desc)
{
restoreId = id;
restoreDesc = desc;
}
| 28.487208
| 146
| 0.64385
|
jcjc79
|
60ccc1e33ac5177ccce0692826a0e29a36a47b6c
| 5,710
|
cpp
|
C++
|
be/src/vec/functions/in.cpp
|
xinghuayu007/doris-vectorized
|
dcb0dcb1596bcc73f4497c08a3a212b0c34127f7
|
[
"Apache-2.0"
] | null | null | null |
be/src/vec/functions/in.cpp
|
xinghuayu007/doris-vectorized
|
dcb0dcb1596bcc73f4497c08a3a212b0c34127f7
|
[
"Apache-2.0"
] | null | null | null |
be/src/vec/functions/in.cpp
|
xinghuayu007/doris-vectorized
|
dcb0dcb1596bcc73f4497c08a3a212b0c34127f7
|
[
"Apache-2.0"
] | null | null | null |
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include <fmt/format.h>
#include "vec/columns/column_const.h"
#include "vec/columns/column_nullable.h"
#include "vec/columns/column_set.h"
#include "vec/columns/columns_number.h"
#include "vec/data_types/data_type_nullable.h"
#include "vec/data_types/data_type_number.h"
#include "vec/functions/function.h"
#include "vec/functions/simple_function_factory.h"
namespace doris::vectorized {
/** in(x, set) - function for evaluating the IN
* notIn(x, set) - and NOT IN.
*/
template <bool negative, bool null_in_set>
struct FunctionInName;
template <>
struct FunctionInName<false, false> {
static constexpr auto name = "in";
};
template <>
struct FunctionInName<true, false> {
static constexpr auto name = "not_in";
};
template <>
struct FunctionInName<false, true> {
static constexpr auto name = "in_null_in_set";
};
template <>
struct FunctionInName<true, true> {
static constexpr auto name = "not_in_null_in_set";
};
template <bool negative, bool null_in_set>
class FunctionIn : public IFunction {
public:
static constexpr auto name = FunctionInName<negative, null_in_set>::name;
static FunctionPtr create() { return std::make_shared<FunctionIn>(); }
String get_name() const override { return name; }
size_t get_number_of_arguments() const override { return 2; }
DataTypePtr get_return_type_impl(const DataTypes& /*arguments*/) const override {
return make_nullable(std::make_shared<DataTypeUInt8>());
}
bool use_default_implementation_for_nulls() const override { return false; }
Status execute_impl(Block& block, const ColumnNumbers& arguments, size_t result,
size_t input_rows_count) override {
/// NOTE: after updating this code, check that FunctionIgnoreExceptNull returns the same type of column.
/// Second argument must be ColumnSet.
ColumnPtr column_set_ptr = block.get_by_position(arguments[1]).column;
const ColumnSet* column_set = typeid_cast<const ColumnSet*>(&*column_set_ptr);
if (!column_set) {
return Status::RuntimeError(
fmt::format("Second argument for function '{}' must be Set; found {}",
get_name(), column_set_ptr->get_name()));
}
auto set = column_set->get_data();
/// First argument may be a single column.
const ColumnWithTypeAndName& left_arg = block.get_by_position(arguments[0]);
auto res = ColumnUInt8::create();
ColumnUInt8::Container& vec_res = res->get_data();
vec_res.resize(input_rows_count);
ColumnUInt8::MutablePtr col_null_map_to;
col_null_map_to = ColumnUInt8::create(left_arg.column->size());
auto& vec_null_map_to = col_null_map_to->get_data();
if (set->size() == 0) {
if (negative)
memset(vec_res.data(), 1, vec_res.size());
else
memset(vec_res.data(), 0, vec_res.size());
} else {
auto materialized_column = left_arg.column->convert_to_full_column_if_const();
if (auto* nullable = check_and_get_column<ColumnNullable>(*materialized_column)) {
const auto& nested_column = nullable->get_nested_column();
const auto& null_map = nullable->get_null_map_column().get_data();
for (size_t i = 0; i < input_rows_count; ++i) {
vec_null_map_to[i] = null_map[i];
if (null_map[i]) {
continue;
}
const auto& ref_data = nested_column.get_data_at(i);
vec_res[i] = negative ^ set->find((void*)ref_data.data, ref_data.size);
if constexpr (null_in_set) {
vec_null_map_to[i] = negative == vec_res[i];
}
}
} else {
/// For all rows
for (size_t i = 0; i < input_rows_count; ++i) {
const auto& ref_data = materialized_column->get_data_at(i);
vec_res[i] = negative ^ set->find((void*)ref_data.data, ref_data.size);
if constexpr (null_in_set) {
vec_null_map_to[i] = negative == vec_res[i];
} else {
vec_null_map_to[i] = 0;
}
}
}
}
block.replace_by_position(
result, ColumnNullable::create(std::move(res), std::move(col_null_map_to)));
return Status::OK();
}
};
void register_function_in(SimpleFunctionFactory& factory) {
factory.register_function<FunctionIn<false, false>>();
factory.register_function<FunctionIn<true, false>>();
factory.register_function<FunctionIn<true, true>>();
factory.register_function<FunctionIn<false, true>>();
}
} // namespace doris::vectorized
| 38.322148
| 112
| 0.636602
|
xinghuayu007
|
60cefc8f8589e8e10f6245b17ed825d89e3f7d62
| 1,219
|
hpp
|
C++
|
remodet_repository_wdh_part/include/caffe/pose/xml_modification.hpp
|
UrwLee/Remo_experience
|
a59d5b9d6d009524672e415c77d056bc9dd88c72
|
[
"MIT"
] | null | null | null |
remodet_repository_wdh_part/include/caffe/pose/xml_modification.hpp
|
UrwLee/Remo_experience
|
a59d5b9d6d009524672e415c77d056bc9dd88c72
|
[
"MIT"
] | null | null | null |
remodet_repository_wdh_part/include/caffe/pose/xml_modification.hpp
|
UrwLee/Remo_experience
|
a59d5b9d6d009524672e415c77d056bc9dd88c72
|
[
"MIT"
] | null | null | null |
#ifndef CAFFE_POSE_XML_MODIFICATION_H
#define CAFFE_POSE_XML_MODIFICATION_H
#include <vector>
#include <string>
#include "caffe/tracker/bounding_box.hpp"
#include "glog/logging.h"
#include "caffe/caffe.hpp"
#include "caffe/proto/caffe.pb.h"
#include "caffe/common.hpp"
#include "caffe/pose/pose_image_loader.hpp"
namespace caffe {
/**
* 该类的作用是修改XML文件中的信息,并进行适当修改后保存。
*/
template <typename Dtype>
class XmlModifier {
public:
/**
* xml_folder: -> 读取的xml文件目录
* output_folder: -> 输出保存目录
*/
XmlModifier(const std::string& xml_folder,
const std::string& output_folder);
/**
* 修改方法
*/
void Modify();
private:
/**
* 修改方法
* @param meta [标注信息]
*/
void ModifyXML(MetaData<Dtype>* meta);
/**
* 保存XML方法
* @param meta [标注信息]
* @param xml_name [XML文件名称]
*/
void SaveXml(const MetaData<Dtype>& meta, const std::string& xml_name);
/**
* 加载标注信息
* @param annotation_file [输入XML文件]
* @param meta [标注信息]
* @return [读取成功或失败]
*/
bool LoadAnnotationFromXmlFile(const string& annotation_file, MetaData<Dtype>* meta);
// XML文件目录
std::string xml_folder_;
// 输出路径
std::string output_folder_;
};
}
#endif
| 17.666667
| 87
| 0.647252
|
UrwLee
|
f599a307040c07556b3cca2fc82c56d4a62ada95
| 1,481
|
cpp
|
C++
|
dev/test/so_5/testing/v1/testenv_empty_scenario/main.cpp
|
eao197/so-5-5
|
fa0c31c84d2637dce04e13a155040150d505fbbd
|
[
"BSL-1.0"
] | 76
|
2016-03-25T15:22:03.000Z
|
2022-02-03T15:11:43.000Z
|
dev/test/so_5/testing/v1/testenv_empty_scenario/main.cpp
|
eao197/so-5-5
|
fa0c31c84d2637dce04e13a155040150d505fbbd
|
[
"BSL-1.0"
] | 19
|
2017-03-09T19:21:53.000Z
|
2021-02-24T13:02:18.000Z
|
dev/test/so_5/testing/v1/testenv_empty_scenario/main.cpp
|
eao197/so-5-5
|
fa0c31c84d2637dce04e13a155040150d505fbbd
|
[
"BSL-1.0"
] | 21
|
2016-09-23T10:01:09.000Z
|
2020-08-31T12:01:10.000Z
|
#include <so_5/experimental/testing/v1/all.hpp>
#include <various_helpers_1/time_limited_execution.hpp>
#include <various_helpers_1/ensure.hpp>
#include <utest_helper_1/h/helper.hpp>
namespace tests = so_5::experimental::testing::v1;
UT_UNIT_TEST( empty_scenario_with_one_agent )
{
run_with_time_limit(
[]()
{
tests::testing_env_t env;
env.environment().introduce_coop( [](so_5::coop_t & coop) {
coop.define_agent().on_start( [] {
std::cout << "Hello, World!" << std::endl;
} );
} );
env.scenario().run_for( std::chrono::seconds(1) );
ensure_or_die(
tests::completed() == env.scenario().result(),
"scenario should complete its work" );
},
5 );
}
UT_UNIT_TEST( empty_scenario_without_agents )
{
run_with_time_limit(
[]()
{
tests::testing_env_t env;
env.scenario().run_for( std::chrono::seconds(1) );
ensure_or_die(
tests::completed() == env.scenario().result(),
"scenario should complete its work" );
},
5 );
}
UT_UNIT_TEST( one_agent_no_call_to_run_for )
{
run_with_time_limit(
[]()
{
tests::testing_env_t env;
env.environment().introduce_coop( [](so_5::coop_t & coop) {
coop.define_agent().on_start( [] {
std::cout << "Hello, World!" << std::endl;
} );
} );
},
5 );
}
int
main()
{
UT_RUN_UNIT_TEST( empty_scenario_with_one_agent )
UT_RUN_UNIT_TEST( empty_scenario_without_agents )
UT_RUN_UNIT_TEST( one_agent_no_call_to_run_for )
return 0;
}
| 19.746667
| 62
| 0.66104
|
eao197
|
f5a069b5da75e30a3081847d323475a1b1ebea87
| 3,783
|
cpp
|
C++
|
raygame/Actor.cpp
|
TerrickThib/AIPathFindingExercise
|
bd0dce6000d96ea556ddc36fd7a2eacb06df25b1
|
[
"MIT"
] | null | null | null |
raygame/Actor.cpp
|
TerrickThib/AIPathFindingExercise
|
bd0dce6000d96ea556ddc36fd7a2eacb06df25b1
|
[
"MIT"
] | null | null | null |
raygame/Actor.cpp
|
TerrickThib/AIPathFindingExercise
|
bd0dce6000d96ea556ddc36fd7a2eacb06df25b1
|
[
"MIT"
] | null | null | null |
#include "Actor.h"
#include "Transform2D.h"
#include <string.h>
#include "Collider.h"
#include "Component.h"
Actor::Actor()
{
m_transform = new Transform2D(this);
}
Actor::~Actor()
{
///Deletes all components
for (int i = 0; i < m_componentCount; i++)
delete m_components[i];
delete m_transform;
}
Actor::Actor(float x, float y, const char* name = "Actor")
{
//Initialze default values
m_transform = new Transform2D(this);
m_transform->setLocalPosition({ x,y });
m_name = name;
}
Component* Actor::addComponent(Component* component)
{
//Return null if this component has an owner already
Actor* owner = component->getOwner();
if (owner)
return nullptr;
component->assignOwner(this);
//Create a new array with a size one greater than our old array
Component** appendedArray = new Component * [m_componentCount + 1];
//Copy the values from the old array to the new array
for (int i = 0; i < m_componentCount; i++)
{
appendedArray[i] = m_components[i];
}
//Set the last value in the new array to be the actor we want to add
appendedArray[m_componentCount] = component;
if (m_componentCount > 1)
//Set old array to hold the values of the new array
delete[] m_components;
else if (m_componentCount == 1)
delete m_components;
m_components = appendedArray;
m_componentCount++;
onAddComponent(component);
return component;
}
void Actor::onAddComponent(Component* component)
{
}
bool Actor::removeComponent(Component* component)
{
if (!component)
return false;
bool componentRemoved = false;
//Create a new array with a size one less than our old array
Component** newArray = new Component * [m_componentCount - 1];
//Create variable to access tempArray index
int j = 0;
//Copy values from the old array to the new array
for (int i = 0; i < m_componentCount; i++)
{
if (component != m_components[i])
{
newArray[j] = m_components[i];
j++;
}
else
{
componentRemoved = true;
}
}
if (componentRemoved)
{
delete[] m_components;
//Set the old array to the new array
m_components = newArray;
m_componentCount--;
delete component;
}
else
delete[] newArray;
//Return whether or not the removal was successful
return componentRemoved;
}
void Actor::start()
{
m_started = true;
}
void Actor::onCollision(Actor* other)
{
for (int i = 0; i < m_componentCount; i++)
{
if (!m_components[i]->getEnabled()) continue;
m_components[i]->onCollision(other);
}
}
void Actor::update(float deltaTime)
{
for (int i = 0; i < m_componentCount; i++)
{
if (!m_components[i]->getEnabled()) continue;
if (!m_components[i]->getStarted())
m_components[i]->start();
m_components[i]->update(deltaTime);
}
}
void Actor::draw()
{
for (int i = 0; i < m_componentCount; i++)
{
if (!m_components[i]->getEnabled()) continue;
m_components[i]->draw();
}
}
void Actor::end()
{
m_started = false;
for (int i = 0; i < m_componentCount; i++)
m_components[i]->end();
}
void Actor::onDestroy()
{
for (int i = 0; i < m_componentCount; i++)
m_components[i]->onDestroy();
Transform2D* parent = getTransform()->getParent();
if (getTransform()->getParent())
parent->removeChild(getTransform());
}
bool Actor::checkForCollision(Actor* other)
{
//Call check collision if there is a collider attached to this actor
if (m_collider)
return m_collider->checkCollision(other);
return false;
}
| 22.122807
| 72
| 0.617235
|
TerrickThib
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.