source stringlengths 3 92 | c stringlengths 26 2.25M |
|---|---|
GB_unaryop__minv_fp64_int16.c | //------------------------------------------------------------------------------
// GB_unaryop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_iterator.h"
#include "GB_unaryop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop__minv_fp64_int16
// op(A') function: GB_tran__minv_fp64_int16
// C type: double
// A type: int16_t
// cast: double cij = (double) aij
// unaryop: cij = 1./aij
#define GB_ATYPE \
int16_t
#define GB_CTYPE \
double
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
int16_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = 1./x ;
// casting
#define GB_CASTING(z, aij) \
double z = (double) aij ;
// cij = op (cast (aij))
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GB_GETA (aij, Ax, pA) ; \
/* Cx [pC] = op (cast (aij)) */ \
GB_CASTING (z, aij) ; \
GB_OP (GB_CX (pC), z) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_MINV || GxB_NO_FP64 || GxB_NO_INT16)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__minv_fp64_int16
(
double *Cx, // Cx and Ax may be aliased
int16_t *Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
GB_CAST_OP (p, p) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_tran__minv_fp64_int16
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *GB_RESTRICT *Rowcounts,
GBI_single_iterator Iter,
const int64_t *GB_RESTRICT A_slice,
int naslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#define GB_PHASE_2_OF_2
#include "GB_unaryop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
lap.h | #include <cassert>
#include <cstdio>
#include <limits>
#include <memory>
#include <immintrin.h>
#ifdef __GNUC__
#define always_inline __attribute__((always_inline)) inline
#define restrict __restrict__
#elif _WIN32
#define always_inline __forceinline
#define restrict __restrict
#else
#define always_inline inline
#define restrict
#endif
template <typename idx, typename cost>
always_inline std::tuple<cost, cost, idx, idx>
find_umins_regular(
idx dim, idx i, const cost *restrict assign_cost,
const cost *restrict v) {
const cost *local_cost = &assign_cost[i * dim];
cost umin = local_cost[0] - v[0];
idx j1 = 0;
idx j2 = -1;
cost usubmin = std::numeric_limits<cost>::max();
for (idx j = 1; j < dim; j++) {
cost h = local_cost[j] - v[j];
if (h < usubmin) {
if (h >= umin) {
usubmin = h;
j2 = j;
} else {
usubmin = umin;
umin = h;
j2 = j1;
j1 = j;
}
}
}
return std::make_tuple(umin, usubmin, j1, j2);
}
// These are not constexpr because of typename idx
#define FLOAT_MIN_DIM 64
#define DOUBLE_MIN_DIM 100000 // 64-bit code is actually always slower
template <typename idx>
always_inline std::tuple<float, float, idx, idx>
find_umins_avx2(
idx dim, idx i, const float *restrict assign_cost,
const float *restrict v) {
if (dim < FLOAT_MIN_DIM) {
return find_umins_regular(dim, i, assign_cost, v);
}
const float *local_cost = assign_cost + i * dim;
__m256i idxvec = _mm256_setr_epi32(0, 1, 2, 3, 4, 5, 6, 7);
__m256i j1vec = _mm256_set1_epi32(-1), j2vec = _mm256_set1_epi32(-1);
__m256 uminvec = _mm256_set1_ps(std::numeric_limits<float>::max()),
usubminvec = _mm256_set1_ps(std::numeric_limits<float>::max());
for (idx j = 0; j < dim - 7; j += 8) {
__m256 acvec = _mm256_loadu_ps(local_cost + j);
__m256 vvec = _mm256_loadu_ps(v + j);
__m256 h = _mm256_sub_ps(acvec, vvec);
__m256 cmp = _mm256_cmp_ps(h, uminvec, _CMP_LE_OQ);
usubminvec = _mm256_blendv_ps(usubminvec, uminvec, cmp);
j2vec = _mm256_blendv_epi8(
j2vec, j1vec, reinterpret_cast<__m256i>(cmp));
uminvec = _mm256_blendv_ps(uminvec, h, cmp);
j1vec = _mm256_blendv_epi8(
j1vec, idxvec, reinterpret_cast<__m256i>(cmp));
cmp = _mm256_andnot_ps(cmp, _mm256_cmp_ps(h, usubminvec, _CMP_LT_OQ));
usubminvec = _mm256_blendv_ps(usubminvec, h, cmp);
j2vec = _mm256_blendv_epi8(
j2vec, idxvec, reinterpret_cast<__m256i>(cmp));
idxvec = _mm256_add_epi32(idxvec, _mm256_set1_epi32(8));
}
alignas(__m256) float uminmem[8], usubminmem[8];
alignas(__m256) int32_t j1mem[8], j2mem[8];
_mm256_store_ps(uminmem, uminvec);
_mm256_store_ps(usubminmem, usubminvec);
_mm256_store_si256(reinterpret_cast<__m256i*>(j1mem), j1vec);
_mm256_store_si256(reinterpret_cast<__m256i*>(j2mem), j2vec);
idx j1 = -1, j2 = -1;
float umin = std::numeric_limits<float>::max(),
usubmin = std::numeric_limits<float>::max();
for (int vi = 0; vi < 8; vi++) {
float h = uminmem[vi];
if (h < usubmin) {
idx jnew = j1mem[vi];
if (h >= umin) {
usubmin = h;
j2 = jnew;
} else {
usubmin = umin;
umin = h;
j2 = j1;
j1 = jnew;
}
}
}
for (int vi = 0; vi < 8; vi++) {
float h = usubminmem[vi];
if (h < usubmin) {
usubmin = h;
j2 = j2mem[vi];
}
}
for (idx j = dim & 0xFFFFFFF8u; j < dim; j++) {
float h = local_cost[j] - v[j];
if (h < usubmin) {
if (h >= umin) {
usubmin = h;
j2 = j;
} else {
usubmin = umin;
umin = h;
j2 = j1;
j1 = j;
}
}
}
return std::make_tuple(umin, usubmin, j1, j2);
}
template <typename idx>
always_inline std::tuple<double, double, idx, idx>
find_umins_avx2(
idx dim, idx i, const double *restrict assign_cost,
const double *restrict v) {
if (dim < DOUBLE_MIN_DIM) {
return find_umins_regular(dim, i, assign_cost, v);
}
const double *local_cost = assign_cost + i * dim;
__m256i idxvec = _mm256_setr_epi64x(0, 1, 2, 3);
__m256i j1vec = _mm256_set1_epi64x(-1), j2vec = _mm256_set1_epi64x(-1);
__m256d uminvec = _mm256_set1_pd(std::numeric_limits<double>::max()),
usubminvec = _mm256_set1_pd(std::numeric_limits<double>::max());
for (idx j = 0; j < dim - 3; j += 4) {
__m256d acvec = _mm256_loadu_pd(local_cost + j);
__m256d vvec = _mm256_loadu_pd(v + j);
__m256d h = _mm256_sub_pd(acvec, vvec);
__m256d cmp = _mm256_cmp_pd(h, uminvec, _CMP_LE_OQ);
usubminvec = _mm256_blendv_pd(usubminvec, uminvec, cmp);
j2vec = _mm256_blendv_epi8(
j2vec, j1vec, reinterpret_cast<__m256i>(cmp));
uminvec = _mm256_blendv_pd(uminvec, h, cmp);
j1vec = _mm256_blendv_epi8(
j1vec, idxvec, reinterpret_cast<__m256i>(cmp));
cmp = _mm256_andnot_pd(cmp, _mm256_cmp_pd(h, usubminvec, _CMP_LT_OQ));
usubminvec = _mm256_blendv_pd(usubminvec, h, cmp);
j2vec = _mm256_blendv_epi8(
j2vec, idxvec, reinterpret_cast<__m256i>(cmp));
idxvec = _mm256_add_epi64(idxvec, _mm256_set1_epi64x(4));
}
alignas(__m256d) double uminmem[4], usubminmem[4];
alignas(__m256d) int64_t j1mem[4], j2mem[4];
_mm256_store_pd(uminmem, uminvec);
_mm256_store_pd(usubminmem, usubminvec);
_mm256_store_si256(reinterpret_cast<__m256i*>(j1mem), j1vec);
_mm256_store_si256(reinterpret_cast<__m256i*>(j2mem), j2vec);
idx j1 = -1, j2 = -1;
double umin = std::numeric_limits<double>::max(),
usubmin = std::numeric_limits<double>::max();
for (int vi = 0; vi < 4; vi++) {
double h = uminmem[vi];
if (h < usubmin) {
idx jnew = j1mem[vi];
if (h >= umin) {
usubmin = h;
j2 = jnew;
} else {
usubmin = umin;
umin = h;
j2 = j1;
j1 = jnew;
}
}
}
for (int vi = 0; vi < 4; vi++) {
double h = usubminmem[vi];
if (h < usubmin) {
usubmin = h;
j2 = j2mem[vi];
}
}
for (idx j = dim & 0xFFFFFFFCu; j < dim; j++) {
double h = local_cost[j] - v[j];
if (h < usubmin) {
if (h >= umin) {
usubmin = h;
j2 = j;
} else {
usubmin = umin;
umin = h;
j2 = j1;
j1 = j;
}
}
}
return std::make_tuple(umin, usubmin, j1, j2);
}
template <bool avx2, typename idx, typename cost>
always_inline std::tuple<cost, cost, idx, idx>
find_umins(
idx dim, idx i, const cost *restrict assign_cost,
const cost *restrict v) {
if constexpr(avx2) {
return find_umins_avx2(dim, i, assign_cost, v);
} else {
return find_umins_regular(dim, i, assign_cost, v);
}
}
/// @brief Exact Jonker-Volgenant algorithm.
/// @param dim in problem size
/// @param assign_cost in cost matrix
/// @param verbose in indicates whether to report the progress to stdout
/// @param rowsol out column assigned to row in solution / size dim
/// @param colsol out row assigned to column in solution / size dim
/// @param u out dual variables, row reduction numbers / size dim
/// @param v out dual variables, column reduction numbers / size dim
/// @return achieved minimum assignment cost
template <bool avx2, typename idx, typename cost>
cost lap(int dim, const cost *restrict assign_cost, bool verbose,
idx *restrict rowsol, idx *restrict colsol,
cost *restrict u, cost *restrict v) {
auto free = std::unique_ptr<idx[]>(new idx[dim]); // list of unassigned rows.
auto collist = std::unique_ptr<idx[]>(new idx[dim]); // list of columns to be scanned in various ways.
auto matches = std::unique_ptr<idx[]>(new idx[dim]); // counts how many times a row could be assigned.
auto d = std::unique_ptr<cost[]>(new cost[dim]); // 'cost-distance' in augmenting path calculation.
auto pred = std::unique_ptr<idx[]>(new idx[dim]); // row-predecessor of column in augmenting/alternating path.
// init how many times a row will be assigned in the column reduction.
#if _OPENMP >= 201307
#pragma omp simd
#endif
for (idx i = 0; i < dim; i++) {
matches[i] = 0;
}
// COLUMN REDUCTION
for (idx j = dim - 1; j >= 0; j--) { // reverse order gives better results.
// find minimum cost over rows.
cost min = assign_cost[j];
idx imin = 0;
for (idx i = 1; i < dim; i++) {
const cost *local_cost = &assign_cost[i * dim];
if (local_cost[j] < min) {
min = local_cost[j];
imin = i;
}
}
v[j] = min;
if (++matches[imin] == 1) {
// init assignment if minimum row assigned for first time.
rowsol[imin] = j;
colsol[j] = imin;
} else {
colsol[j] = -1; // row already assigned, column not assigned.
}
}
if (verbose) {
printf("lapjv: COLUMN REDUCTION finished\n");
}
// REDUCTION TRANSFER
idx numfree = 0;
for (idx i = 0; i < dim; i++) {
const cost *local_cost = &assign_cost[i * dim];
if (matches[i] == 0) { // fill list of unassigned 'free' rows.
free[numfree++] = i;
} else if (matches[i] == 1) { // transfer reduction from rows that are assigned once.
idx j1 = rowsol[i];
cost min = std::numeric_limits<cost>::max();
for (idx j = 0; j < dim; j++) {
if (j != j1) {
if (local_cost[j] - v[j] < min) {
min = local_cost[j] - v[j];
}
}
}
v[j1] = v[j1] - min;
}
}
if (verbose) {
printf("lapjv: REDUCTION TRANSFER finished\n");
}
// AUGMENTING ROW REDUCTION
for (int loopcnt = 0; loopcnt < 2; loopcnt++) { // loop to be done twice.
// scan all free rows.
// in some cases, a free row may be replaced with another one to be scanned next.
idx k = 0;
idx prevnumfree = numfree;
numfree = 0; // start list of rows still free after augmenting row reduction.
while (k < prevnumfree) {
idx i = free[k++];
// find minimum and second minimum reduced cost over columns.
cost umin, usubmin;
idx j1, j2;
std::tie(umin, usubmin, j1, j2) = find_umins<avx2>(dim, i, assign_cost, v);
idx i0 = colsol[j1];
cost vj1_new = v[j1] - (usubmin - umin);
bool vj1_lowers = vj1_new < v[j1]; // the trick to eliminate the epsilon bug
if (vj1_lowers) {
// change the reduction of the minimum column to increase the minimum
// reduced cost in the row to the subminimum.
v[j1] = vj1_new;
} else if (i0 >= 0) { // minimum and subminimum equal.
// minimum column j1 is assigned.
// swap columns j1 and j2, as j2 may be unassigned.
j1 = j2;
i0 = colsol[j2];
}
// (re-)assign i to j1, possibly de-assigning an i0.
rowsol[i] = j1;
colsol[j1] = i;
if (i0 >= 0) { // minimum column j1 assigned earlier.
if (vj1_lowers) {
// put in current k, and go back to that k.
// continue augmenting path i - j1 with i0.
free[--k] = i0;
} else {
// no further augmenting reduction possible.
// store i0 in list of free rows for next phase.
free[numfree++] = i0;
}
}
}
if (verbose) {
printf("lapjv: AUGMENTING ROW REDUCTION %d / %d\n", loopcnt + 1, 2);
}
} // for loopcnt
// AUGMENT SOLUTION for each free row.
for (idx f = 0; f < numfree; f++) {
idx endofpath;
idx freerow = free[f]; // start row of augmenting path.
if (verbose) {
printf("lapjv: AUGMENT SOLUTION row %d [%d / %d]\n",
freerow, f + 1, numfree);
}
// Dijkstra shortest path algorithm.
// runs until unassigned column added to shortest path tree.
#if _OPENMP >= 201307
#pragma omp simd
#endif
for (idx j = 0; j < dim; j++) {
d[j] = assign_cost[freerow * dim + j] - v[j];
pred[j] = freerow;
collist[j] = j; // init column list.
}
idx low = 0; // columns in 0..low-1 are ready, now none.
idx up = 0; // columns in low..up-1 are to be scanned for current minimum, now none.
// columns in up..dim-1 are to be considered later to find new minimum,
// at this stage the list simply contains all columns
bool unassigned_found = false;
// initialized in the first iteration: low == up == 0
idx last = 0;
cost min = 0;
do {
if (up == low) { // no more columns to be scanned for current minimum.
last = low - 1;
// scan columns for up..dim-1 to find all indices for which new minimum occurs.
// store these indices between low..up-1 (increasing up).
min = d[collist[up++]];
for (idx k = up; k < dim; k++) {
idx j = collist[k];
cost h = d[j];
if (h <= min) {
if (h < min) { // new minimum.
up = low; // restart list at index low.
min = h;
}
// new index with same minimum, put on undex up, and extend list.
collist[k] = collist[up];
collist[up++] = j;
}
}
// check if any of the minimum columns happens to be unassigned.
// if so, we have an augmenting path right away.
for (idx k = low; k < up; k++) {
if (colsol[collist[k]] < 0) {
endofpath = collist[k];
unassigned_found = true;
break;
}
}
}
if (!unassigned_found) {
// update 'distances' between freerow and all unscanned columns, via next scanned column.
idx j1 = collist[low];
low++;
idx i = colsol[j1];
const cost *local_cost = &assign_cost[i * dim];
cost h = local_cost[j1] - v[j1] - min;
for (idx k = up; k < dim; k++) {
idx j = collist[k];
cost v2 = local_cost[j] - v[j] - h;
if (v2 < d[j]) {
pred[j] = i;
if (v2 == min) { // new column found at same minimum value
if (colsol[j] < 0) {
// if unassigned, shortest augmenting path is complete.
endofpath = j;
unassigned_found = true;
break;
} else { // else add to list to be scanned right away.
collist[k] = collist[up];
collist[up++] = j;
}
}
d[j] = v2;
}
}
}
} while (!unassigned_found);
// update column prices.
#if _OPENMP >= 201307
#pragma omp simd
#endif
for (idx k = 0; k <= last; k++) {
idx j1 = collist[k];
v[j1] = v[j1] + d[j1] - min;
}
// reset row and column assignments along the alternating path.
{
idx i;
do {
i = pred[endofpath];
colsol[endofpath] = i;
idx j1 = endofpath;
endofpath = rowsol[i];
rowsol[i] = j1;
} while (i != freerow);
}
}
if (verbose) {
printf("lapjv: AUGMENT SOLUTION finished\n");
}
// calculate optimal cost.
cost lapcost = 0;
#if _OPENMP >= 201307
#pragma omp simd reduction(+:lapcost)
#endif
for (idx i = 0; i < dim; i++) {
const cost *local_cost = &assign_cost[i * dim];
idx j = rowsol[i];
u[i] = local_cost[j] - v[j];
lapcost += local_cost[j];
}
if (verbose) {
printf("lapjv: optimal cost calculated\n");
}
return lapcost;
}
|
DRACC_OMP_054_Counter_working_atomic_inter_no.c | /*
Counter incrementation on an atomic counter. Inter Region.
*/
#include <stdio.h>
#define N 100000
int countervar = 0;
int count(){
#pragma omp target map(tofrom:countervar) device(0)
#pragma omp teams distribute
for (int i=0; i<N; i++){
#pragma omp atomic update
countervar++;
}
return 0;
}
int main(){
count();
printf("counter: %i expected: 100000\n ",countervar);
return 0;
} |
GB_binop__fmod_fp32.c | //------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_emult.h"
#include "GB_control.h"
#include "GB_ek_slice.h"
#include "GB_dense.h"
#include "GB_atomics.h"
#include "GB_bitmap_assign_methods.h"
#include "GB_binop__include.h"
// C=binop(A,B) is defined by the following types and operators:
// A+B function (eWiseAdd): GB (_AaddB__fmod_fp32)
// A.*B function (eWiseMult): GB (_AemultB)
// A.*B function (eWiseMult): GB (_AemultB_02__fmod_fp32)
// A.*B function (eWiseMult): GB (_AemultB_03__fmod_fp32)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__fmod_fp32)
// A*D function (colscale): GB ((none))
// D*A function (rowscale): GB ((node))
// C+=B function (dense accum): GB (_Cdense_accumB__fmod_fp32)
// C+=b function (dense accum): GB (_Cdense_accumb__fmod_fp32)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__fmod_fp32)
// C=scalar+B GB (_bind1st__fmod_fp32)
// C=scalar+B' GB (_bind1st_tran__fmod_fp32)
// C=A+scalar GB (_bind2nd__fmod_fp32)
// C=A'+scalar GB (_bind2nd_tran__fmod_fp32)
// C type: float
// A type: float
// B,b type: float
// BinaryOp: cij = fmodf (aij, bij)
#define GB_ATYPE \
float
#define GB_BTYPE \
float
#define GB_CTYPE \
float
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
1
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
1
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
float aij = Ax [pA]
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB) \
float bij = Bx [pB]
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
float t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA) \
cij = Ax [pA]
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB) \
cij = Bx [pB]
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z, x, y, i, j) \
z = fmodf (x, y) ;
// true if the binop must be flipped
#define GB_BINOP_FLIP \
1
// op is second
#define GB_OP_IS_SECOND \
0
// do the numerical phases of GB_add and GB_emult
#define GB_PHASE_2_OF_2
// hard-coded loops can be vectorized
#define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_FMOD || GxB_NO_FP32 || GxB_NO_FMOD_FP32)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
#if 0
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
#endif
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_ewise3_noaccum__fmod_fp32)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_dense_ewise3_noaccum_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += B, accumulate a sparse matrix into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumB__fmod_fp32)
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
#include "GB_dense_subassign_23_template.c"
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumb__fmod_fp32)
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
// get the scalar b for C += b, of type float
float bwork = (*((float *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A, bool A_is_pattern,
const GrB_Matrix D, bool D_is_pattern,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
float *restrict Cx = (float *) C->x ;
#include "GB_AxB_colscale_meta.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((node))
(
GrB_Matrix C,
const GrB_Matrix D, bool D_is_pattern,
const GrB_Matrix B, bool B_is_pattern,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
float *restrict Cx = (float *) C->x ;
#include "GB_AxB_rowscale_meta.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// eWiseAdd: C = A+B or C<M> = A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__fmod_fp32)
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool Ch_is_Mh,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GB_WERK_DECLARE (M_ek_slicing, int64_t) ;
GB_WERK_DECLARE (A_ek_slicing, int64_t) ;
GB_WERK_DECLARE (B_ek_slicing, int64_t) ;
#include "GB_add_template.c"
GB_FREE_WORK ;
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C = A.*B or C<M> = A.*B
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_01__fmod_fp32)
(
GrB_Matrix C,
const int C_sparsity,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_01_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_02__fmod_fp32)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool flipxy,
const int64_t *restrict Cp_kfirst,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if GB_BINOP_FLIP
// The operator is not commutative, and does not have a flipped
// variant. For example z=atan2(y,x).
if (flipxy)
{
// use fmult(y,x)
#undef GB_FLIPPED
#define GB_FLIPPED 1
#include "GB_emult_02_template.c"
}
else
{
// use fmult(x,y)
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
}
#else
// No need to handle the flip: the operator is either commutative, or
// has been handled by changing z=div(y,x) to z=rdiv(x,y) for example.
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_03__fmod_fp32)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict Cp_kfirst,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_03_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_bitmap__fmod_fp32)
(
GrB_Matrix C,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_bitmap_emult_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
GrB_Info GB (_bind1st__fmod_fp32)
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
const int8_t *restrict Bb,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
float *Cx = (float *) Cx_output ;
float x = (*((float *) x_input)) ;
float *Bx = (float *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Bb, p)) continue ;
float bij = Bx [p] ;
Cx [p] = fmodf (x, bij) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__fmod_fp32)
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
const int8_t *restrict Ab,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
float *Cx = (float *) Cx_output ;
float *Ax = (float *) Ax_input ;
float y = (*((float *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
float aij = Ax [p] ;
Cx [p] = fmodf (aij, y) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
float aij = Ax [pA] ; \
Cx [pC] = fmodf (x, aij) ; \
}
GrB_Info GB (_bind1st_tran__fmod_fp32)
(
GrB_Matrix C,
const GB_void *x_input,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
// GB_unop_transpose.c uses GB_ATYPE, but A is
// the 2nd input to binary operator z=f(x,y).
#undef GB_ATYPE
#define GB_ATYPE \
float
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
float x = (*((const float *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
float
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
float aij = Ax [pA] ; \
Cx [pC] = fmodf (aij, y) ; \
}
GrB_Info GB (_bind2nd_tran__fmod_fp32)
(
GrB_Matrix C,
const GrB_Matrix A,
const GB_void *y_input,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
float y = (*((const float *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
eavlRadixSortOp.h | // Copyright 2010-2015 UT-Battelle, LLC. See LICENSE.txt for more information.
#ifndef EAVL_RADIX_SORT_OP_H
#define EAVL_RADIX_SORT_OP_H
#include "eavlCUDA.h"
#include "eavlArray.h"
#include "eavlOpDispatch.h"
#include "eavlOperation.h"
#include "eavlException.h"
#include "eavlPrefixSumOp_1.h"
#include <time.h>
#include <limits>
#ifdef HAVE_OPENMP
#include <omp.h>
#endif
#ifndef DOXYGEN
#define WARP_SIZE 32
#define SORT_BLOCK_SIZE 128
#define SCAN_BLOCK_SIZE 256
typedef unsigned int uint;
/* Merge sorted lists A and B into list A. Av and Bv are then values A must have dim >= m+n */
template<class T>
void merge(T A[], T B[], T Av[], T Bv[], int m, int n)
{
int i=0, j=0, k=0;
int size = m+n;
T *C = (T *)malloc(size*sizeof(T));
T *Cv = (T *)malloc(size*sizeof(T));
while (i < m && j < n)
{
if (A[i] <= B[j])
{
C[k] = A[i];
Cv[k] = Av[i++];
}
else
{
C[k] = B[j];
Cv[k] = Bv[j++];
}
k++;
}
if (i < m) for (int p = i; p < m; p++,k++)
{
C[k] = A[p];
Cv[k] = Av[p];
}
else for (int p = j; p < n; p++,k++)
{
C[k] = B[p];
Cv[k] = Bv[p];
}
for( i=0; i<size; i++ )
{
A[i] = C[i];
Av[i] = Cv[i];
}
free(C);
free(Cv);
}
static void insertion_sort(uint *keys, uint *values, int offset, int end) {
int x, y;
uint temp, tempv;
for (x=offset; x<end; ++x)
{
for (y=x; y>offset && keys[y-1]>keys[y]; y--)
{
temp = keys[y];
tempv = values[y];
keys[y] = keys[y-1];
values[y] = values[y-1];
keys[y-1] = temp;
values[y-1] = tempv;
}
}
}
static void radix_sort(uint *keys, uint *values, int offset, int end, int shift) {
int x, y;
uint value, valuev, temp, tempv;
int last[256] = { 0 }, pointer[256];
for (x=offset; x<end; ++x)
{
++last[(keys[x] >> shift) & 0xFF];
}
last[0] += offset;
pointer[0] = offset;
for (x=1; x<256; ++x)
{
pointer[x] = last[x-1];
last[x] += last[x-1];
}
for (x=0; x<256; ++x)
{
while (pointer[x] != last[x])
{
value = keys[pointer[x]];
valuev = values[pointer[x]];
y = (value >> shift) & 0xFF;
while (x != y)
{
temp = keys[pointer[y]];
tempv = values[pointer[y]];
keys[pointer[y]] = value;
values[pointer[y]++] = valuev;
value = temp;
valuev = tempv;
y = (value >> shift) & 0xFF;
}
keys[pointer[x]] = value;
values[pointer[x]++] = valuev;
}
}
if (shift > 0)
{
shift -= 8;
for (x=0; x<256; ++x)
{
temp = x > 0 ? pointer[x] - pointer[x-1] : pointer[0] - offset;
if (temp > 64)
{
radix_sort(keys, values, pointer[x] - temp, pointer[x], shift);
}
else if (temp > 1)
{
insertion_sort(keys, values, pointer[x] - temp, pointer[x]);
}
}
}
}
/* Merges N sorted sub-sections of keys a into final, fully sorted keys a */
static void keysmerge(uint *keys, uint *values, int size, int *index, int N)
{
int i;
while (N > 1)
{
for( i = 0; i < N; i++ ) index[i]=i*size/N;
index[N] = size;
#pragma omp parallel for private(i)
for( i=0; i<N; i+=2 )
{
merge(keys + index[i], keys + index[i+1], values + index[i], values + index[i+1],
index[i+1] - index[i], index[i+2] - index[i+1]);
}
N /= 2;
}
}
struct eavlRadixSortOp_CPU
{
static inline eavlArray::Location location() { return eavlArray::HOST; }
template <class F, class IN, class OUT>
static void call(int nitems, int useValues,
const IN inputs, OUT outputs,
F&)
{
uint *keys = (uint*)inputs.first.array;
uint *values = (uint*)outputs.first.array;
if(!useValues)
{
#pragma omp parallel for
for(int i = 0; i < nitems; i++)
{
values[i] = i;
}
}
#ifdef HAVE_OPENMP
int threads = omp_get_max_threads();
threads = pow(2, floor(log(threads)/log(2))); // needs to be power of 2
int *index = (int *)malloc((threads+1)*sizeof(int));
for(int i = 0; i < threads; i++) index[i] = i*nitems/threads;
index[threads] = nitems;
#pragma omp parallel for
for(int i = 0; i < threads; i++) radix_sort(keys,values,index[i], index[i+1],24);
/* Merge sorted keys pieces */
if( threads > 1 ) keysmerge(keys,values,nitems,index,threads);
#else
radix_sort(keys,values,0, nitems,24);
#endif
}
};
#if defined __CUDACC__
// Alternative macro to catch CUDA errors
#define CUDA_SAFE_CALL( call) do { \
cudaError err = call; \
if (cudaSuccess != err) { \
fprintf(stderr, "Cuda error in file '%s' in line %i : %s.\n", \
__FILE__, __LINE__, cudaGetErrorString( err) ); \
exit(1); \
} \
} while (0)
template<class T, int maxlevel>
__device__ T scanwarp(T val, volatile T* sData)
{
// The following is the same as 2 * WARP_SIZE * warpId + threadInWarp =
// 64*(threadIdx.x >> 5) + (threadIdx.x & (WARP_SIZE - 1))
int idx = 2 * threadIdx.x - (threadIdx.x & (WARP_SIZE - 1));
sData[idx] = 0;
idx += WARP_SIZE;
T t = sData[idx] = val;
if (0 <= maxlevel) { sData[idx] = t = t + sData[idx - 1]; }
if (1 <= maxlevel) { sData[idx] = t = t + sData[idx - 2]; }
if (2 <= maxlevel) { sData[idx] = t = t + sData[idx - 4]; }
if (3 <= maxlevel) { sData[idx] = t = t + sData[idx - 8]; }
if (4 <= maxlevel) { sData[idx] = t = t + sData[idx -16]; }
return sData[idx] - val; // convert inclusive -> exclusive
}
template<class T>
__device__ uint4 scan4(T idata, uint* ptr)
{
//extern __shared__ uint ptr[];
uint idx = threadIdx.x;
uint4 val4 = idata;
uint sum[3];
sum[0] = val4.x;
sum[1] = val4.y + sum[0];
sum[2] = val4.z + sum[1];
uint val = val4.w + sum[2];
val = scanwarp<uint, 4>(val, ptr);
__syncthreads();
if ((idx & (WARP_SIZE - 1)) == WARP_SIZE - 1)
{
ptr[idx >> 5] = val + val4.w + sum[2];
}
__syncthreads();
if (idx < WARP_SIZE)
{
ptr[idx] = scanwarp<uint, 2>(ptr[idx], ptr);
}
__syncthreads();
val += ptr[idx >> 5];
val4.x = val;
val4.y = val + sum[0];
val4.z = val + sum[1];
val4.w = val + sum[2];
return val4;
}
template <int ctasize>
__device__ uint4 rank4(uint4 preds,uint* s_data)
{
uint4 address = scan4<uint4>(preds,s_data);
__shared__ uint numtrue;
if (threadIdx.x == ctasize-1)
{
numtrue = address.w + preds.w;
}
__syncthreads();
uint4 rank;
uint idx = threadIdx.x << 2;
rank.x = (preds.x) ? address.x : numtrue + idx - address.x;
rank.y = (preds.y) ? address.y : numtrue + idx + 1 - address.y;
rank.z = (preds.z) ? address.z : numtrue + idx + 2 - address.z;
rank.w = (preds.w) ? address.w : numtrue + idx + 3 - address.w;
return rank;
}
//----------------------------------------------------------------------------
//
// radixSortBlocks sorts all blocks of data independently in shared
// memory. Each thread block (CTA) sorts one block of 4*CTA_SIZE elements
//
// The radix sort is done in two stages. This stage calls radixSortBlock
// on each block independently, sorting on the basis of bits
// (startbit) -> (startbit + nbits)
//----------------------------------------------------------------------------
template<bool loop>
__global__ void radixSortBlocks(const uint nbits, const uint startbit,
uint4* keysOut, uint4* valuesOut,
uint4* keysIn, uint4* valuesIn,
const size_t totalBlocks)
{
__shared__ uint sMem[512];
uint blockId = blockIdx.x;
uint4 key, value;
while(!loop || blockId < totalBlocks)
{
// Get Indexing information
uint i = threadIdx.x + (blockId * blockDim.x);
uint tid = threadIdx.x;
uint localSize = blockDim.x;
// Load keys and vals from global memory
key = keysIn[i];
value = valuesIn[i];
// For each of the 4 bits
for(uint shift = startbit; shift < (startbit + nbits); ++shift)
{
// Check if the LSB is 0
uint4 lsb;
lsb.x = !((key.x >> shift) & 0x1);
lsb.y = !((key.y >> shift) & 0x1);
lsb.z = !((key.z >> shift) & 0x1);
lsb.w = !((key.w >> shift) & 0x1);
// Do an exclusive scan of how many elems have 0's in the LSB
// When this is finished, address.n will contain the number of
// elems with 0 in the LSB which precede elem n
uint4 rank = rank4<128>(lsb, sMem);
// Scatter keys into local mem
sMem[(rank.x & 3) * localSize + (rank.x >> 2)] = key.x;
sMem[(rank.y & 3) * localSize + (rank.y >> 2)] = key.y;
sMem[(rank.z & 3) * localSize + (rank.z >> 2)] = key.z;
sMem[(rank.w & 3) * localSize + (rank.w >> 2)] = key.w;
__syncthreads();
// Read keys out of local mem into registers, in prep for
// write out to global mem
key.x = sMem[tid];
key.y = sMem[tid + localSize];
key.z = sMem[tid + 2 * localSize];
key.w = sMem[tid + 3 * localSize];
__syncthreads();
// Scatter values into local mem
sMem[(rank.x & 3) * localSize + (rank.x >> 2)] = value.x;
sMem[(rank.y & 3) * localSize + (rank.y >> 2)] = value.y;
sMem[(rank.z & 3) * localSize + (rank.z >> 2)] = value.z;
sMem[(rank.w & 3) * localSize + (rank.w >> 2)] = value.w;
__syncthreads();
// Read keys out of local mem into registers, in prep for
// write out to global mem
value.x = sMem[tid];
value.y = sMem[tid + localSize];
value.z = sMem[tid + 2 * localSize];
value.w = sMem[tid + 3 * localSize];
__syncthreads();
}
keysOut[i] = key;
valuesOut[i] = value;
if(loop)
{
blockId += gridDim.x;
}
else break;
}
}
//----------------------------------------------------------------------------
// Given an keys with blocks sorted according to a 4-bit radix group, each
// block counts the number of keys that fall into each radix in the group, and
// finds the starting offset of each radix in the block. It then writes the
// radix counts to the counters keys, and the starting offsets to the
// blockOffsets keys.
//
//----------------------------------------------------------------------------
template<bool loop>
__global__ void findRadixOffsets(uint2* keys, uint* counters,
uint* blockOffsets, uint startbit, uint numElements, uint totalBlocks)
{
__shared__ uint sStartPointers[16];
extern __shared__ uint sRadix1[];
uint blockId = blockIdx.x;
while(!loop || blockId < totalBlocks)
{
uint localId = threadIdx.x;
uint groupSize = blockDim.x;
uint2 radix2;
radix2 = keys[threadIdx.x + (blockId * blockDim.x)];
sRadix1[2 * localId] = (radix2.x >> startbit) & 0xF;
sRadix1[2 * localId + 1] = (radix2.y >> startbit) & 0xF;
// Finds the position where the sRadix1 entries differ and stores start
// index for each radix.
if(localId < 16)
{
sStartPointers[localId] = 0;
}
__syncthreads();
if((localId > 0) && (sRadix1[localId] != sRadix1[localId - 1]) )
{
sStartPointers[sRadix1[localId]] = localId;
}
if(sRadix1[localId + groupSize] != sRadix1[localId + groupSize - 1])
{
sStartPointers[sRadix1[localId + groupSize]] = localId + groupSize;
}
__syncthreads();
if(localId < 16)
{
blockOffsets[blockId*16 + localId] = sStartPointers[localId];
}
__syncthreads();
// Compute the sizes of each block.
if((localId > 0) && (sRadix1[localId] != sRadix1[localId - 1]) )
{
sStartPointers[sRadix1[localId - 1]] =
localId - sStartPointers[sRadix1[localId - 1]];
}
if(sRadix1[localId + groupSize] != sRadix1[localId + groupSize - 1] )
{
sStartPointers[sRadix1[localId + groupSize - 1]] =
localId + groupSize - sStartPointers[sRadix1[localId +
groupSize - 1]];
}
if(localId == groupSize - 1)
{
sStartPointers[sRadix1[2 * groupSize - 1]] =
2 * groupSize - sStartPointers[sRadix1[2 * groupSize - 1]];
}
__syncthreads();
if(localId < 16)
{
counters[localId * totalBlocks + blockId] = sStartPointers[localId];
}
if(loop)
{
blockId += gridDim.x;
}
else break;
}
}
//----------------------------------------------------------------------------
// reorderData shuffles data in the keys globally after the radix offsets
// have been found. On compute version 1.1 and earlier GPUs, this code depends
// on SORT_BLOCK_SIZE being 16 * number of radices (i.e. 16 * 2^nbits).
//----------------------------------------------------------------------------
template<bool loop>
__global__ void reorderData(uint startbit,
uint *outKeys,
uint *outValues,
uint2 *keys,
uint2 *values,
uint *blockOffsets,
uint *offsets,
uint *sizes,
uint totalBlocks)
{
uint GROUP_SIZE = blockDim.x;
__shared__ uint2 sKeys2[256];
__shared__ uint2 sValues2[256];
__shared__ uint sOffsets[16];
__shared__ uint sBlockOffsets[16];
uint* sKeys1 = (uint*) sKeys2;
uint* sValues1 = (uint*) sValues2;
uint blockId = blockIdx.x;
while(!loop || blockId < totalBlocks)
{
uint i = blockId * blockDim.x + threadIdx.x;
sKeys2[threadIdx.x] = keys[i];
sValues2[threadIdx.x] = values[i];
if(threadIdx.x < 16)
{
sOffsets[threadIdx.x] = offsets[threadIdx.x * totalBlocks + blockId];
sBlockOffsets[threadIdx.x] = blockOffsets[blockId * 16 + threadIdx.x];
}
__syncthreads();
uint radix = (sKeys1[threadIdx.x] >> startbit) & 0xF;
uint globalOffset = sOffsets[radix] + threadIdx.x - sBlockOffsets[radix];
outKeys[globalOffset] = sKeys1[threadIdx.x];
outValues[globalOffset] = sValues1[threadIdx.x];
radix = (sKeys1[threadIdx.x + GROUP_SIZE] >> startbit) & 0xF;
globalOffset = sOffsets[radix] + threadIdx.x + GROUP_SIZE -
sBlockOffsets[radix];
outKeys[globalOffset] = sKeys1[threadIdx.x + GROUP_SIZE];
outValues[globalOffset] = sValues1[threadIdx.x + GROUP_SIZE];
if(loop)
{
blockId += gridDim.x;
__syncthreads();
}
else break;
}
}
template <class T>
__device__ void storeSharedChunkToMem4(T *d_out,
T threadScan[2][4],
T *s_in,
int numElements,
int oDataOffset,
int ai,
int bi,
int aiDev,
int biDev,
bool fullBlock)
{
// Convert to 4-vector
uint4 tempData;
uint4* outData = (uint4*)d_out;
// write results to global memory
T temp;
temp = s_in[ai];
tempData.x = temp;
tempData.y = temp + threadScan[0][0];
tempData.z = temp + threadScan[0][1];
tempData.w = temp + threadScan[0][2];
int i = aiDev * 4;
if (fullBlock || i + 3 < numElements)
{
outData[aiDev] = tempData;
}
else
{
// we can't use vec4 because the original keys isn't a multiple of
// 4 elements
if ( i < numElements) { d_out[i] = tempData.x;
if ((i+1) < numElements) { d_out[i+1] = tempData.y;
if ((i+2) < numElements) { d_out[i+2] = tempData.z; } } }
}
temp = s_in[bi];
tempData.x = temp;
tempData.y = temp + threadScan[1][0];
tempData.z = temp + threadScan[1][1];
tempData.w = temp + threadScan[1][2];
i = biDev * 4;
if (fullBlock || i + 3 < numElements)
{
outData[biDev] = tempData;
}
else
{
// we can't use vec4 because the original keys isn't a multiple of
// 4 elements
if ( i < numElements) { d_out[i] = tempData.x;
if ((i+1) < numElements) { d_out[i+1] = tempData.y;
if ((i+2) < numElements) { d_out[i+2] = tempData.z; } } }
}
}
template<class T>
void radixSortStep(T nbits, uint startbit, uint4* keys, uint4* values,
uint4* tempKeys, uint4* tempValues, uint* counters,
uint* countersSum, uint* blockOffsets,
uint numElements)
{
// Threads handle either 4 or two elements each
const size_t radixGlobalWorkSize = numElements / 4;
const size_t findGlobalWorkSize = numElements / 2;
const size_t reorderGlobalWorkSize = numElements / 2;
// Radix kernel uses block size of 128, others use 256 (same as scan)
const size_t radixBlocks = radixGlobalWorkSize / SORT_BLOCK_SIZE;
const size_t findBlocks = findGlobalWorkSize / SCAN_BLOCK_SIZE;
const size_t reorderBlocks = reorderGlobalWorkSize / SCAN_BLOCK_SIZE;
//cout<<"Num Blocks "<<radixBlocks<<" "<<findBlocks<<endl;
bool loop = radixBlocks > 65535;
if(loop)
{
radixSortBlocks<true>
<<<65535, SORT_BLOCK_SIZE, 4 * sizeof(uint)*SORT_BLOCK_SIZE>>>
(nbits, startbit, tempKeys, tempValues, keys, values, radixBlocks);
}
else
{
radixSortBlocks<false>
<<<radixBlocks, SORT_BLOCK_SIZE, 4 * sizeof(uint)*SORT_BLOCK_SIZE>>>
(nbits, startbit, tempKeys, tempValues, keys, values, radixBlocks);
}
loop = findBlocks > 65535;
if(loop)
{
findRadixOffsets<true>
<<<65535, SCAN_BLOCK_SIZE, 2 * SCAN_BLOCK_SIZE*sizeof(uint)>>>
((uint2*)tempKeys, counters, blockOffsets, startbit, numElements,
findBlocks);
}
else
{
findRadixOffsets<false>
<<<findBlocks, SCAN_BLOCK_SIZE, 2 * SCAN_BLOCK_SIZE*sizeof(uint)>>>
((uint2*)tempKeys, counters, blockOffsets, startbit, numElements,
findBlocks);
}
// using the EAVL scan function.
DummyFunctor dummy;
gpuPrefixSumOp_1_function<DummyFunctor,uint> scanner;
bool inclusive = false;
scanner.call( (int)16*reorderBlocks, inclusive,
counters, 1, 1e9, 1, 0,
countersSum, 1 , 0, dummy);
if(loop)
{
reorderData<true>
<<<65535, SCAN_BLOCK_SIZE>>>
(startbit, (uint*)keys, (uint*)values, (uint2*)tempKeys,
(uint2*)tempValues, blockOffsets, countersSum, counters,
reorderBlocks);
}
else
{
reorderData<false>
<<<reorderBlocks, SCAN_BLOCK_SIZE>>>
(startbit, (uint*)keys, (uint*)values, (uint2*)tempKeys,
(uint2*)tempValues, blockOffsets, countersSum, counters,
reorderBlocks);
}
}
template<class T>
__global__ void interatorKernel(T nitems, volatile uint * ids)
{
int blockId = blockIdx.y * gridDim.x + blockIdx.x;
const int threadID = blockId * blockDim.x + threadIdx.x;
if(threadID > nitems) return;
ids[threadID] = threadID;
}
struct eavlRadixSortOp_GPU
{
static inline eavlArray::Location location() { return eavlArray::DEVICE; }
template <class F, class IN, class OUT>
static void call(int nitems, int useValues,
IN inputs, OUT outputs, F&)
{
uint *_keys;
uint *_values;
//needs to be multiple of 1024;
int extra = nitems % 1024;
int newSize = nitems;
uint bytes = nitems*sizeof(uint);
if(extra != 0)
{
// if the size is not a multiple of 1024, get the padding amount
newSize += 1024 - extra;
bytes = newSize * sizeof(uint);
// create new keys
cudaMalloc((void**)&_keys, bytes);
CUDA_CHECK_ERROR();
cudaMalloc((void**)&_values, bytes);
CUDA_CHECK_ERROR();
// copy the values over
cudaMemcpy(_keys, get<0>(inputs).array, nitems*sizeof(uint), cudaMemcpyDeviceToDevice);
CUDA_CHECK_ERROR();
if(useValues)
{
cudaMemcpy(_values, get<0>(outputs).array, nitems*sizeof(uint), cudaMemcpyDeviceToDevice);
CUDA_CHECK_ERROR();
}
// pad the keys with max values.
uint * temp = &_keys[nitems];
uint maxVal = std::numeric_limits<uint>::max();
cudaMemset(temp, maxVal, (1024 - extra)*sizeof(uint) );
CUDA_CHECK_ERROR();
}
else
{
cudaMalloc((void**)&_keys, bytes);
CUDA_CHECK_ERROR();
cudaMalloc((void**)&_values, bytes);
CUDA_CHECK_ERROR();
cudaMemcpy(_keys, get<0>(inputs).array, nitems*sizeof(uint), cudaMemcpyDeviceToDevice);
CUDA_CHECK_ERROR();
if(useValues)
{
cudaMemcpy(_values, get<0>(outputs).array, nitems*sizeof(uint), cudaMemcpyDeviceToDevice);
CUDA_CHECK_ERROR();
}
}
// Find grid and block dimensions for iterator kernel
int numBlocks = nitems / 256;
if(nitems % 256 > 0) numBlocks++;
int numBlocksX = numBlocks;
int numBlocksY = 1;
if (numBlocks >= 32768)
{
numBlocksY = numBlocks / 32768;
numBlocksX = (numBlocks + numBlocksY-1) / numBlocksY;
}
dim3 threads(256, 1, 1);
dim3 blocks (numBlocksX,numBlocksY, 1);
// Generate keys with values 0 ..numElements to find scatter positions
if(!useValues)
{
interatorKernel<int><<< blocks, threads >>>(newSize, _values);
CUDA_CHECK_ERROR();
}
// Allocate device mem for sorting kernels
uint *dTempKeys, *dTempVals;
CUDA_SAFE_CALL(cudaMalloc((void**)&dTempKeys, bytes));
CUDA_SAFE_CALL(cudaMalloc((void**)&dTempVals, bytes));
// Each thread in the sort kernel handles 4 elements
size_t numSortGroups = newSize / (4 * SORT_BLOCK_SIZE); //Num Blocks
uint* dCounters, *dCounterSums, *dBlockOffsets;
CUDA_SAFE_CALL(cudaMalloc((void**)&dCounters, WARP_SIZE
* numSortGroups * sizeof(uint)));
CUDA_SAFE_CALL(cudaMalloc((void**)&dCounterSums, WARP_SIZE
* numSortGroups * sizeof(uint)));
CUDA_SAFE_CALL(cudaMalloc((void**)&dBlockOffsets, WARP_SIZE
* numSortGroups * sizeof(uint)));
for (int i = 0; i < 32; i += 4)
{
radixSortStep<uint>(4, i, (uint4*)_keys, (uint4*)_values,
(uint4*)dTempKeys, (uint4*)dTempVals, dCounters,
dCounterSums, dBlockOffsets, newSize);
}
//CUDA_SAFE_CALL(cudaDeviceSynchronize());
// Copy values back
cudaMemcpy(get<0>(inputs).array, _keys, nitems*sizeof(uint), cudaMemcpyDeviceToDevice);
CUDA_CHECK_ERROR();
cudaMemcpy(get<0>(outputs).array, _values, nitems*sizeof(uint), cudaMemcpyDeviceToDevice);
CUDA_CHECK_ERROR();
CUDA_SAFE_CALL(cudaFree(_keys));
CUDA_SAFE_CALL(cudaFree(_values));
CUDA_SAFE_CALL(cudaFree(dTempKeys));
CUDA_SAFE_CALL(cudaFree(dTempVals));
CUDA_SAFE_CALL(cudaFree(dCounters));
CUDA_SAFE_CALL(cudaFree(dCounterSums));
CUDA_SAFE_CALL(cudaFree(dBlockOffsets));
}
};
#endif
#endif
// ****************************************************************************
// Class: eavlRadixSortOp
//
// Purpose: to sort arrays of unsigned int keys-value pairs. A boolean flag
// indicates whether to use the values provide(false) or generate
// indexes(true) that provide the scatter postions for more complex
// structures. See testsort.cu for example usage and benckmark versus
// std::sort.
//
// Example : keys [2 0 3 1]
// index [0 1 2 3] (indexes generated internally)
// ---------------
// out index [1 3 0 2]
// [0 1 2 3]
//
// Programmer: Matt Larsen 8/19/2014 (Cuda Kernels adapted from cudpp. CPU version
// adapted from Erik Gorset. See COPYRIGHT.txt )
//
// Modifications:
//
// ****************************************************************************
template <class I, class O>
class eavlRadixSortOp : public eavlOperation
{
protected:
DummyFunctor functor;
I inputs;
O outputs;
int nitems;
int usevals;
public:
eavlRadixSortOp(I i, O o, bool genIndexes)
: inputs(i), outputs(o), nitems(-1)
{
usevals = !genIndexes;
}
eavlRadixSortOp(I i, O o, bool genIndexes, int itemsToProcess)
: inputs(i), outputs(o), nitems(itemsToProcess)
{
usevals = !genIndexes;
}
virtual void GoCPU()
{
int n = 0;
if(nitems > 0) n = nitems;
else n = inputs.first.length();
eavlOpDispatch<eavlRadixSortOp_CPU>(n, usevals, inputs, outputs, functor);
}
virtual void GoGPU()
{
#ifdef HAVE_CUDA
int n=0;
if(nitems > 0) n = nitems;
else n = inputs.first.length();
eavlOpDispatch<eavlRadixSortOp_GPU>(n, usevals, inputs, outputs, functor);
#else
THROW(eavlException,"Executing GPU code without compiling under CUDA compiler.");
#endif
}
};
// helper function for type deduction
template <class I, class O>
eavlRadixSortOp<I,O> *new_eavlRadixSortOp(I i, O o, bool genIndexes)
{
return new eavlRadixSortOp<I,O>(i,o, genIndexes);
}
template <class I, class O>
eavlRadixSortOp<I,O> *new_eavlRadixSortOp(I i, O o, bool genIndexes, int itemsToProcess)
{
return new eavlRadixSortOp<I,O>(i,o, genIndexes, itemsToProcess);
}
#endif
|
omp_ctrmm_batch.c | /**
* @file omp_ctrmm_batch.c
*
* @brief BBLAS omp_ctrmm_batch float _Complex routine.
* BBLAS is a software package provided by Univ. of Manchester,
* Univ. of Tennessee.
*
* @version 1.0.0
* @author Samuel D. Relton
* @author Pedro V. Lara
* @author Mawussi Zounon
* @date 2016-02-20
*
**/
#ifndef DOXYGEN_SHOULD_SKIP_THIS
/**
* Code generation
* @generated from ./bblas_omp/omp_ztrmm_batch.c normal z -> c, Mon Jun 6 09:44:14 2016
**/
#endif
#include<cblas.h>
#include "bblas_omp.h"
#include "bblas.h"
#include <omp.h>
#define COMPLEX
/**
Purpose
-------
<b>ctrmm_batch</b> is an OpenMP version of ctrmm_batch.
It perfoms one of the matrix-matrix operations
arrayB[i] = alpha[i]*op( arrayA[i] )*arrayB[i], or
arrayB[i] = alpha[i]*arrayB[i]*op( arrayA[i] )
where op( X ) is one of
op( X ) = X or
op( X ) = X**T or
op( X ) = X**H,
alpha[i] is a scalar, arrayB[i] is an M[i] by N[i] matrix,
and arrayA[i] is a unit or non-unit, upper or lower triangular matrix.
Fixed and Variable Batch Operations
-----------------------------------
Two types of batch operation are supported depending upon the value of batch_opts.
When <tt>batch_opts = BBLAS_VARIABLE</tt>
- all parameters that are arrays must have length at least batch_count.
- all parameters that are arrays must have all values set.
When <tt>batch_opts = BBLAS_FIXED</tt>
- all parameters that are arrays (except for arrayA, arrayB, and info)
must have length at least one.
- all parameters that are arrays (except for arrayA, arrayB, and info)
need only to have their first value set.
This means that for a <tt>BBLAS_FIXED</tt> batch,
the values of side[0], uplo[0], M[0], N[0], transA[0], diag[0],
alpha[0], lda[0], and ldb[0] are used for all computations.
Parameters
----------
@param[in]
side Array of <tt>enum BBLAS_SIDE</tt>.
Each element side[i] specifies whether op( arrayA[i] )
multiplies arrayB[i] from left or right as follows:
- = 'BblasLeft' arrayB[i] = alpha[i]*op( arrayA[i] )*arrayB[i].
- = 'BblasRight' arrayB[i] = alpha[i]*arrayB[i]*op( arrayA[i] ).
@param[in]
uplo Array of <tt>enum BBLAS_UPLO</tt>.
On entry, uplo[i] specifies whether the matrix arrayA[i] is an
upper or lower triangular matrix as follows:
- = 'BblasUpper' arrayA[i] is an upper triangular matrix.
- = 'BblasLower' arrayA[i] is a lower triangular matrix.
@param[in]
transA Array of <tt>enum BBLAS_TRANS</tt>.
On entry, trans[i] specifies the form of op( arrayA[i] ) to be
used in the matrix multiplication as follows:
- = 'BblasNoTrans' op( arrayA[i] ) = arrayA[i].
- = 'BblasTrans' op( arrayA[i] ) = arrayA[i]**T.
- = 'BblasConjTrans' op( arrayA[i] ) = arrayA[i]**H.
@param[in]
diag - Array of <tt>enum BBLAS_DIAG</tt>.
On entry, diag[i] specifies whether or not arrayA[i] is unit
triangular as follows:
- = 'BblasUnit' arrayA[i] is assumed to be unit triangular.
- = 'BblasNonUnit' arrayA[i] is not assumed to be unit triangular.
@param[in]
M Array of <tt>int</tt>.
Each element M[i] specifies the number of rows of the matrix arrayB[i].
M[i] must be greater than zero.
@param[in]
N Array of <tt>int</tt>.
Each element N[i] specifies the number of columns of the matrix arrayB[i].
N[i] must be greater than zero.
@param[in]
alpha Array of <tt>complex_16</tt>.
@param[in]
arrayA Array of pointers.
Each element arrayA[i] is a pointer to a COMPLEX matrix of
dimension lda[i] by Ka[i],
where Ka[i] = M[i] when side[i] = BblasLeft and is N[i] otherwise.
When using side[i] = BblasLeft the M[i] by M[i] part of arrayA[i]
must contain the triangular matrix:
when uplo[i] = BblasUpper, the upper triangular part of arrayA[i]
must contain the matrix whilst the strictly lower triangular part is not used;
similarly when uplo[i] = BblasLower, the lower triangular part of arrayA[i]
must contain the matrix whilst the strictly upper triangular part is not used.
When using side[i] = BblasRight the N[i] by N[i] part of arrayA[i] must
contain the symmetric matrix:
when uplo[i] = BblasUpper, the upper triangular part of arrayA[i]
must contain the matrix whilst the strictly lower triangular part is not used;
similarly when uplo[i] = BblasLower, the lower triangular part of arrayA[i]
must contain the matrix whilst the strictly upper triangular part is not used.
Note that when diag = BblasUnit the diagonal elements of arrayA[i] are
not used either, they are assumed to be equal to one.
@param[in]
lda Array of <tt>int</tt>.
On entry, lda[i] specifies the first dimension of arrayA[i] as declared
in the calling (sub) program. When side[i] = BblasLeft
then lda[i] must be at least max( 1, M[i] ),
otherwise lda[i] must be at least max( 1, N[i] ).
@param[in,out]
arrayB Array of pointers.
Each element arrayB[i] is a pointer to a COMPLEX matrix of
dimension ldb[i] by N[i].
The leading M[i] by N[i] part of arrayB[i] must contain the matrix elements.
On exit is arrayB[i] overwritten by the updated matrix.
@param[in]
ldb Array of <tt>int</tt>.
Each element ldb[i] specifies the first dimension of arrayB[i] as declared
in the calling (sub) program. Each element ldb[i] must be at least max( 1, M[i] ).
@param[in]
batch_count <tt>int</tt>
The number of matrices to operate on.
@param[in]
batch_opts <tt>enum BBLAS_OPTS</tt>
One of BBLAS_FIXED or BBLAS_VARIABLE depending upon the type of
batch operation required.
@param[out]
info Array of <tt>int</tt>.
Each element info[i] is the error return code of the ith ctrmm in the batch,
these need not be set on entry.
The error codes can be found in bblas_macros.h.
**/
void omp_ctrmm_batch(
const enum BBLAS_SIDE *side, const enum BBLAS_UPLO *uplo,
const enum BBLAS_TRANS *transA, const enum BBLAS_DIAG *diag,
const int *M, const int *N, const BBLAS_Complex32_t *alpha,
const BBLAS_Complex32_t **arrayA, const int *lda,
BBLAS_Complex32_t **arrayB, const int *ldb,
const int batch_count, enum BBLAS_OPTS batch_opts, int *info)
{
/*Local variables */
int first_index = 0;
int batch_iter;
int LDA;
char func_name[15] = "ctrmm_batch";
/* Check input arguments */
if (batch_count < 0)
{
xerbla_batch(func_name, BBLAS_ERR_BATCH_COUNT, -1);
}
if (batch_opts == BBLAS_FIXED)
{
if ((side[first_index] != BblasLeft) &&
(side[first_index] != BblasRight))
{
xerbla_batch(func_name, BBLAS_ERR_SIDE, first_index);
for (batch_iter = 0; batch_iter < batch_count; batch_iter++)
{
info[batch_iter] = BBLAS_ERR_SIDE;
}
return;
}
if ((uplo[first_index] != BblasUpper) &&
(uplo[first_index] != BblasLower))
{
xerbla_batch(func_name, BBLAS_ERR_UPLO, first_index);
for (batch_iter = 0; batch_iter < batch_count; batch_iter++)
{
info[batch_iter] = BBLAS_ERR_UPLO;
}
return;
}
if ((transA[first_index] != BblasNoTrans) &&
(transA[first_index] != BblasTrans) &&
(transA[first_index] != BblasConjTrans))
{
xerbla_batch(func_name, BBLAS_ERR_TRANSA, first_index);
for (batch_iter = 0; batch_iter < batch_count; batch_iter++)
{
info[batch_iter] = BBLAS_ERR_TRANSA;
}
return;
}
if ((diag[first_index] != BblasNonUnit) &&
(diag[first_index] != BblasUnit))
{
xerbla_batch(func_name, BBLAS_ERR_DIAG, first_index);
for (batch_iter = 0; batch_iter < batch_count; batch_iter++)
{
info[batch_iter] = BBLAS_ERR_DIAG;
}
return;
}
if (M[first_index] < 0)
{
xerbla_batch(func_name, BBLAS_ERR_M, first_index);
for (batch_iter = 0; batch_iter < batch_count; batch_iter++)
{
info[batch_iter] = BBLAS_ERR_M;
}
return;
}
if (N[first_index] < 0)
{
xerbla_batch(func_name, BBLAS_ERR_N, first_index);
for (batch_iter = 0; batch_iter < batch_count; batch_iter++)
{
info[batch_iter] = BBLAS_ERR_N;
}
return;
}
if (side[first_index] == BblasLeft)
{
LDA = M[first_index];
} else
{
LDA = N[first_index];
}
if (lda[first_index] < max(1, LDA))
{
xerbla_batch(func_name, BBLAS_ERR_LDA, first_index);
for (batch_iter = 0; batch_iter < batch_count; batch_iter++)
{
info[batch_iter] = BBLAS_ERR_LDA;
}
return;
}
if (ldb[first_index] < max(1, M[first_index])) {
xerbla_batch(func_name, BBLAS_ERR_LDB, first_index);
for (batch_iter = 0; batch_iter < batch_count; batch_iter++)
{
info[batch_iter] = BBLAS_ERR_LDB;
}
return;
}
/* particular case */
if (min(M[first_index], N[first_index]) == 0)
{
for (batch_iter = 0; batch_iter < batch_count; batch_iter++)
{
info[batch_iter] = BBLAS_SUCCESS;
}
return;
}
#pragma omp parallel for private(batch_iter)
for (batch_iter = 0; batch_iter < batch_count; batch_iter++)
{
/*Call to cblas_ctrmm */
cblas_ctrmm(
BblasColMajor,
side[first_index],
uplo[first_index],
transA[first_index],
diag[first_index],
M[first_index],
N[first_index],
CBLAS_SADDR(alpha[first_index]),
arrayA[batch_iter],
lda[first_index],
arrayB[batch_iter],
ldb[first_index]);
/* Successful */
info[batch_iter] = BBLAS_SUCCESS;
} /*END FIXED SIZE FOR LOOP */
}else if (batch_opts == BBLAS_VARIABLE)
{
#pragma omp parallel for private(batch_iter, LDA)
for (batch_iter = 0; batch_iter < batch_count; batch_iter++)
{
/* Check input arguments */
if ((side[batch_iter] != BblasLeft) &&
(side[batch_iter] != BblasRight))
{
xerbla_batch(func_name, BBLAS_ERR_SIDE, batch_iter);
info[batch_iter] = BBLAS_ERR_SIDE;
continue;
}
if ((uplo[batch_iter] != BblasUpper) &&
(uplo[batch_iter] != BblasLower))
{
xerbla_batch(func_name, BBLAS_ERR_UPLO, batch_iter);
info[batch_iter] = BBLAS_ERR_UPLO;
continue;
}
if ((transA[batch_iter] != BblasNoTrans) &&
(transA[batch_iter] != BblasTrans) &&
(transA[batch_iter] != BblasConjTrans))
{
xerbla_batch(func_name, BBLAS_ERR_TRANSA, batch_iter);
info[batch_iter] = BBLAS_ERR_TRANSA;
continue;
}
if (M[batch_iter] < 0)
{
xerbla_batch(func_name, BBLAS_ERR_M, batch_iter);
info[batch_iter] = BBLAS_ERR_M;
continue;
}
if (N[batch_iter] < 0)
{
xerbla_batch(func_name,BBLAS_ERR_N, batch_iter);
info[batch_iter] = BBLAS_ERR_N;
continue;
}
if (side[batch_iter] == BblasLeft)
{
LDA = M[batch_iter];
} else
{
LDA = N[batch_iter];
}
if (lda[batch_iter] < max(1, LDA))
{
xerbla_batch(func_name, BBLAS_ERR_LDA, batch_iter);
info[batch_iter] = BBLAS_ERR_LDA;
continue;
}
if (ldb[batch_iter] < max(1, M[batch_iter]))
{
xerbla_batch(func_name, BBLAS_ERR_LDC, batch_iter);
info[batch_iter] = BBLAS_ERR_LDC;
continue;
}
/* particular case */
if (min(M[batch_iter], N[batch_iter]) == 0)
{
info[batch_iter] = BBLAS_SUCCESS;
continue;
}
cblas_ctrmm(
BblasColMajor,
side[batch_iter],
uplo[batch_iter],
transA[batch_iter],
diag[batch_iter],
M[batch_iter],
N[batch_iter],
CBLAS_SADDR(alpha[batch_iter]),
arrayA[batch_iter],
lda[batch_iter],
arrayB[batch_iter],
ldb[batch_iter]);
/* Successful */
info[batch_iter] = BBLAS_SUCCESS;
}
}else
{
xerbla_batch(func_name, BBLAS_ERR_BATCH_OPTS, -1);
}
}
#undef COMPLEX
|
GB_binop__gt_bool.c |
//------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_emult.h"
#include "GB_control.h"
#include "GB_ek_slice.h"
#include "GB_dense.h"
#include "GB_atomics.h"
#include "GB_bitmap_assign_methods.h"
#include "GB_binop__include.h"
// C=binop(A,B) is defined by the following types and operators:
// A+B function (eWiseAdd): GB (_AaddB__gt_bool)
// A.*B function (eWiseMult): GB (_AemultB_08__gt_bool)
// A.*B function (eWiseMult): GB (_AemultB_02__gt_bool)
// A.*B function (eWiseMult): GB (_AemultB_04__gt_bool)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__gt_bool)
// A*D function (colscale): GB (_AxD__gt_bool)
// D*A function (rowscale): GB (_DxB__gt_bool)
// C+=B function (dense accum): GB (_Cdense_accumB__gt_bool)
// C+=b function (dense accum): GB (_Cdense_accumb__gt_bool)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__gt_bool)
// C=scalar+B GB (_bind1st__gt_bool)
// C=scalar+B' GB (_bind1st_tran__gt_bool)
// C=A+scalar GB (_bind2nd__gt_bool)
// C=A'+scalar GB (_bind2nd_tran__gt_bool)
// C type: bool
// A type: bool
// A pattern? 0
// B type: bool
// B pattern? 0
// BinaryOp: cij = (aij > bij)
#define GB_ATYPE \
bool
#define GB_BTYPE \
bool
#define GB_CTYPE \
bool
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
1
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
1
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA,A_iso) \
bool aij = GBX (Ax, pA, A_iso)
// true if values of A are not used
#define GB_A_IS_PATTERN \
0 \
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB,B_iso) \
bool bij = GBX (Bx, pB, B_iso)
// true if values of B are not used
#define GB_B_IS_PATTERN \
0 \
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
bool t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \
cij = GBX (Ax, pA, A_iso)
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \
cij = GBX (Bx, pB, B_iso)
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z,x,y,i,j) \
z = (x > y) ;
// true if the binop must be flipped
#define GB_BINOP_FLIP \
0
// op is second
#define GB_OP_IS_SECOND \
0
// do the numerical phases of GB_add and GB_emult
#define GB_PHASE_2_OF_2
// hard-coded loops can be vectorized
#define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_GT || GxB_NO_BOOL || GxB_NO_GT_BOOL)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
#if 0
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
#endif
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
void GB (_Cdense_ewise3_noaccum__gt_bool)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_noaccum_template.c"
}
//------------------------------------------------------------------------------
// C += B, accumulate a sparse matrix into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumB__gt_bool)
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
#include "GB_dense_subassign_23_template.c"
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumb__gt_bool)
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
// get the scalar b for C += b, of type bool
bool bwork = (*((bool *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_AxD__gt_bool)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix D,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
bool *restrict Cx = (bool *) C->x ;
#include "GB_AxB_colscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_DxB__gt_bool)
(
GrB_Matrix C,
const GrB_Matrix D,
const GrB_Matrix B,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
bool *restrict Cx = (bool *) C->x ;
#include "GB_AxB_rowscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__gt_bool)
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool is_eWiseUnion,
const GB_void *alpha_scalar_in,
const GB_void *beta_scalar_in,
const bool Ch_is_Mh,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GB_WERK_DECLARE (M_ek_slicing, int64_t) ;
GB_WERK_DECLARE (A_ek_slicing, int64_t) ;
GB_WERK_DECLARE (B_ek_slicing, int64_t) ;
bool alpha_scalar ;
bool beta_scalar ;
if (is_eWiseUnion)
{
alpha_scalar = (*((bool *) alpha_scalar_in)) ;
beta_scalar = (*((bool *) beta_scalar_in )) ;
}
#include "GB_add_template.c"
GB_FREE_WORKSPACE ;
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_08__gt_bool)
(
GrB_Matrix C,
const int C_sparsity,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_08_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_02__gt_bool)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool flipxy,
const int64_t *restrict Cp_kfirst,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if GB_BINOP_FLIP
// The operator is not commutative, and does not have a flipped
// variant. For example z=atan2(y,x).
if (flipxy)
{
// use fmult(y,x)
#undef GB_FLIPPED
#define GB_FLIPPED 1
#include "GB_emult_02_template.c"
}
else
{
// use fmult(x,y)
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
}
#else
// No need to handle the flip: the operator is either commutative, or
// has been handled by changing z=div(y,x) to z=rdiv(x,y) for example.
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_04__gt_bool)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict Cp_kfirst,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_04_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_bitmap__gt_bool)
(
GrB_Matrix C,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_bitmap_emult_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
GrB_Info GB (_bind1st__gt_bool)
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
const int8_t *restrict Bb,
int64_t bnz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
bool *Cx = (bool *) Cx_output ;
bool x = (*((bool *) x_input)) ;
bool *Bx = (bool *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < bnz ; p++)
{
if (!GBB (Bb, p)) continue ;
bool bij = GBX (Bx, p, false) ;
Cx [p] = (x > bij) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__gt_bool)
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
const int8_t *restrict Ab,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
bool *Cx = (bool *) Cx_output ;
bool *Ax = (bool *) Ax_input ;
bool y = (*((bool *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
bool aij = GBX (Ax, p, false) ;
Cx [p] = (aij > y) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
bool aij = GBX (Ax, pA, false) ; \
Cx [pC] = (x > aij) ; \
}
GrB_Info GB (_bind1st_tran__gt_bool)
(
GrB_Matrix C,
const GB_void *x_input,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
// GB_unop_transpose.c uses GB_ATYPE, but A is
// the 2nd input to binary operator z=f(x,y).
#undef GB_ATYPE
#define GB_ATYPE \
bool
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
bool x = (*((const bool *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
bool
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
bool aij = GBX (Ax, pA, false) ; \
Cx [pC] = (aij > y) ; \
}
GrB_Info GB (_bind2nd_tran__gt_bool)
(
GrB_Matrix C,
const GrB_Matrix A,
const GB_void *y_input,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
bool y = (*((const bool *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
schrodinger.c | /*********************************************************************************/
/* */
/* Animation of Schrödinger equation in a planar domain */
/* */
/* N. Berglund, May 2021 */
/* */
/* Feel free to reuse, but if doing so it would be nice to drop a */
/* line to nils.berglund@univ-orleans.fr - Thanks! */
/* */
/* compile with */
/* gcc -o schrodinger schrodinger.c */
/* -L/usr/X11R6/lib -ltiff -lm -lGL -lGLU -lX11 -lXmu -lglut -O3 -fopenmp */
/* */
/* To make a video, set MOVIE to 1 and create subfolder tif_schrod */
/* It may be possible to increase parameter PAUSE */
/* */
/* create movie using */
/* ffmpeg -i wave.%05d.tif -vcodec libx264 wave.mp4 */
/* */
/*********************************************************************************/
/*********************************************************************************/
/* */
/* NB: The algorithm used to simulate the wave equation is highly paralellizable */
/* One could make it much faster by using a GPU */
/* */
/*********************************************************************************/
#include <math.h>
#include <string.h>
#include <GL/glut.h>
#include <GL/glu.h>
#include <unistd.h>
#include <sys/types.h>
#include <tiffio.h> /* Sam Leffler's libtiff library. */
#include <omp.h>
#define MOVIE 0 /* set to 1 to generate movie */
/* General geometrical parameters */
#define WINWIDTH 1280 /* window width */
#define WINHEIGHT 720 /* window height */
// #define NX 1280 /* number of grid points on x axis */
// #define NX 720 /* number of grid points on x axis */
#define NX 640 /* number of grid points on x axis */
#define NY 360 /* number of grid points on y axis */
/* setting NX to WINWIDTH and NY to WINHEIGHT increases resolution */
/* but will multiply run time by 4 */
#define XMIN -2.0
#define XMAX 2.0 /* x interval */
#define YMIN -1.125
#define YMAX 1.125 /* y interval for 9/16 aspect ratio */
#define JULIA_SCALE 1.0 /* scaling for Julia sets */
/* Choice of the billiard table, see list in global_pdes.c */
#define B_DOMAIN 10 /* choice of domain shape */
#define CIRCLE_PATTERN 0 /* pattern of circles, see list in global_pdes.c */
#define P_PERCOL 0.25 /* probability of having a circle in C_RAND_PERCOL arrangement */
#define NPOISSON 300 /* number of points for Poisson C_RAND_POISSON arrangement */
#define RANDOM_POLY_ANGLE 1 /* set to 1 to randomize angle of polygons */
#define LAMBDA 0.1 /* parameter controlling the dimensions of domain */
#define MU 0.03 /* parameter controlling the dimensions of domain */
#define NPOLY 6 /* number of sides of polygon */
#define APOLY 1.0 /* angle by which to turn polygon, in units of Pi/2 */
#define MDEPTH 5 /* depth of computation of Menger gasket */
#define MRATIO 3 /* ratio defining Menger gasket */
#define MANDELLEVEL 1000 /* iteration level for Mandelbrot set */
#define MANDELLIMIT 10.0 /* limit value for approximation of Mandelbrot set */
#define FOCI 1 /* set to 1 to draw focal points of ellipse */
#define NGRIDX 15 /* number of grid point for grid of disks */
#define NGRIDY 20 /* number of grid point for grid of disks */
#define X_SHOOTER -0.2
#define Y_SHOOTER -0.6
#define X_TARGET 0.4
#define Y_TARGET 0.7 /* shooter and target positions in laser fight */
#define ISO_XSHIFT_LEFT -1.65
#define ISO_XSHIFT_RIGHT 0.4
#define ISO_YSHIFT_LEFT -0.05
#define ISO_YSHIFT_RIGHT -0.05
#define ISO_SCALE 0.85 /* coordinates for isospectral billiards */
/* You can add more billiard tables by adapting the functions */
/* xy_in_billiard and draw_billiard in sub_wave.c */
/* Physical patameters of wave equation */
#define DT 0.00000001
// #define DT 0.00000001
// #define DT 0.000000005
// #define DT 0.000000005
#define HBAR 1.0
/* Boundary conditions, see list in global_pdes.c */
#define B_COND 1
/* Parameters for length and speed of simulation */
#define NSTEPS 2500 /* number of frames of movie */
// #define NVID 2000 /* number of iterations between images displayed on screen */
#define NVID 1200 /* number of iterations between images displayed on screen */
#define NSEG 100 /* number of segments of boundary */
#define BOUNDARY_WIDTH 2 /* width of billiard boundary */
#define PAUSE 1000 /* number of frames after which to pause */
#define PSLEEP 1 /* sleep time during pause */
#define SLEEP1 1 /* initial sleeping time */
#define SLEEP2 1 /* final sleeping time */
#define END_FRAMES 100 /* still frames at end of movie */
/* For debugging purposes only */
#define FLOOR 0 /* set to 1 to limit wave amplitude to VMAX */
#define VMAX 10.0 /* max value of wave amplitude */
/* Plot type, see list in global_pdes.c */
#define PLOT 11
/* Color schemes, see list in global_pdes.c */
#define COLOR_PALETTE 10 /* Color palette, see list in global_pdes.c */
#define BLACK 1 /* black background */
#define COLOR_SCHEME 3 /* choice of color scheme */
#define SCALE 1 /* set to 1 to adjust color scheme to variance of field */
#define SLOPE 1.0 /* sensitivity of color on wave amplitude */
#define ATTENUATION 0.0 /* exponential attenuation coefficient of contrast with time */
#define E_SCALE 150.0 /* scaling factor for energy representation */
#define LOG_SCALE 1.0 /* scaling factor for energy log representation */
#define COLORHUE 260 /* initial hue of water color for scheme C_LUM */
#define COLORDRIFT 0.0 /* how much the color hue drifts during the whole simulation */
#define LUMMEAN 0.5 /* amplitude of luminosity variation for scheme C_LUM */
#define LUMAMP 0.3 /* amplitude of luminosity variation for scheme C_LUM */
#define HUEMEAN 180.0 /* mean value of hue for color scheme C_HUE */
#define HUEAMP 180.0 /* amplitude of variation of hue for color scheme C_HUE */
#define DRAW_COLOR_SCHEME 1 /* set to 1 to plot the color scheme */
#define COLORBAR_RANGE 2.0 /* scale of color scheme bar */
#define COLORBAR_RANGE_B 12.0 /* scale of color scheme bar for 2nd part */
#define ROTATE_COLOR_SCHEME 0 /* set to 1 to draw color scheme horizontally */
#include "global_pdes.c"
#include "sub_wave.c"
double courant2; /* Courant parameter squared */
double dx2; /* spatial step size squared */
double intstep; /* integration step */
double intstep1; /* integration step used in absorbing boundary conditions */
void init_coherent_state(double x, double y, double px, double py, double scalex, double *phi[NX],
double *psi[NX], short int *xy_in[NX])
/* initialise field with coherent state of position (x,y) and momentum (px, py) */
/* phi is real part, psi is imaginary part */
{
int i, j;
double xy[2], dist2, module, phase, scale2;
scale2 = scalex*scalex;
for (i=0; i<NX; i++)
for (j=0; j<NY; j++)
{
ij_to_xy(i, j, xy);
xy_in[i][j] = xy_in_billiard(xy[0],xy[1]);
if (xy_in[i][j])
{
dist2 = (xy[0]-x)*(xy[0]-x) + (xy[1]-y)*(xy[1]-y);
module = exp(-dist2/scale2);
if (module < 1.0e-15) module = 1.0e-15;
phase = (px*(xy[0]-x) + py*(xy[1]-y))/scalex;
phi[i][j] = module*cos(phase);
psi[i][j] = module*sin(phase);
}
else
{
phi[i][j] = 0.0;
psi[i][j] = 0.0;
}
}
}
/*********************/
/* animation part */
/*********************/
void schrodinger_color_scheme(double phi, double psi, double scale, int time, double rgb[3])
// double phi, psi, scale, rgb[3];
// int time;
{
double phase, amp, lum;
if (PLOT == P_MODULE)
color_scheme(COLOR_SCHEME, 2.0*module2(phi, psi)-1.0, scale, time, rgb);
else if (PLOT == P_PHASE)
{
amp = module2(phi,psi);
// if (amp < 1.0e-10) amp = 1.0e-10;
phase = argument(phi/amp, psi/amp);
if (phase < 0.0) phase += DPI;
lum = (color_amplitude(amp, scale, time))*0.5;
if (lum < 0.0) lum = 0.0;
hsl_to_rgb(phase*360.0/DPI, 0.9, lum, rgb);
}
else if (PLOT == P_REAL) color_scheme(COLOR_SCHEME, phi, scale, time, rgb);
else if (PLOT == P_IMAGINARY) color_scheme(COLOR_SCHEME, psi, scale, time, rgb);
}
void draw_wave(double *phi[NX], double *psi[NX], short int *xy_in[NX], double scale, int time)
/* draw the field */
{
int i, j;
double rgb[3], xy[2], x1, y1, x2, y2, amp, phase;
glBegin(GL_QUADS);
for (i=0; i<NX; i++)
for (j=0; j<NY; j++)
{
if (xy_in[i][j])
{
schrodinger_color_scheme(phi[i][j],psi[i][j], scale, time, rgb);
glColor3f(rgb[0], rgb[1], rgb[2]);
glVertex2i(i, j);
glVertex2i(i+1, j);
glVertex2i(i+1, j+1);
glVertex2i(i, j+1);
}
}
glEnd ();
}
void evolve_wave_half_old(double *phi_in[NX], double *psi_in[NX], double *phi_out[NX], double *psi_out[NX],
short int *xy_in[NX])
// void evolve_wave_half(phi_in, psi_in, phi_out, psi_out, xy_in)
// /* time step of field evolution */
// /* phi is real part, psi is imaginary part */
// double *phi_in[NX], *psi_in[NX], *phi_out[NX], *psi_out[NX]; short int *xy_in[NX];
{
int i, j, iplus, iminus, jplus, jminus;
double delta1, delta2, x, y;
#pragma omp parallel for private(i,j,iplus,iminus,jplus,jminus,delta1,delta2,x,y)
for (i=0; i<NX; i++){
for (j=0; j<NY; j++){
if (xy_in[i][j]){
/* discretized Laplacian depending on boundary conditions */
if ((B_COND == BC_DIRICHLET)||(B_COND == BC_ABSORBING))
{
iplus = (i+1); if (iplus == NX) iplus = NX-1;
iminus = (i-1); if (iminus == -1) iminus = 0;
jplus = (j+1); if (jplus == NY) jplus = NY-1;
jminus = (j-1); if (jminus == -1) jminus = 0;
}
else if (B_COND == BC_PERIODIC)
{
iplus = (i+1) % NX;
iminus = (i-1) % NX;
if (iminus < 0) iminus += NX;
jplus = (j+1) % NY;
jminus = (j-1) % NY;
if (jminus < 0) jminus += NY;
}
delta1 = phi_in[iplus][j] + phi_in[iminus][j] + phi_in[i][jplus] + phi_in[i][jminus] - 4.0*phi_in[i][j];
delta2 = psi_in[iplus][j] + psi_in[iminus][j] + psi_in[i][jplus] + psi_in[i][jminus] - 4.0*psi_in[i][j];
x = phi_in[i][j];
y = psi_in[i][j];
/* evolve phi and psi */
if (B_COND != BC_ABSORBING)
{
phi_out[i][j] = x - intstep*delta2;
psi_out[i][j] = y + intstep*delta1;
}
else /* case of absorbing b.c. - this is only an approximation of correct way of implementing */
{
/* in the bulk */
if ((i>0)&&(i<NX-1)&&(j>0)&&(j<NY-1))
{
phi_out[i][j] = x - intstep*delta2;
psi_out[i][j] = y + intstep*delta1;
}
/* right border */
else if (i==NX-1)
{
phi_out[i][j] = x - intstep1*(y - psi_in[i-1][j]);
psi_out[i][j] = y + intstep1*(x - phi_in[i-1][j]);
}
/* upper border */
else if (j==NY-1)
{
phi_out[i][j] = x - intstep1*(y - psi_in[i][j-1]);
psi_out[i][j] = y + intstep1*(x - phi_in[i][j-1]);
}
/* left border */
else if (i==0)
{
phi_out[i][j] = x - intstep1*(y - psi_in[1][j]);
psi_out[i][j] = y + intstep1*(x - phi_in[1][j]);
}
/* lower border */
else if (j==0)
{
phi_out[i][j] = x - intstep1*(y - psi_in[i][1]);
psi_out[i][j] = y + intstep1*(x - phi_in[i][1]);
}
}
if (FLOOR)
{
if (phi_out[i][j] > VMAX) phi_out[i][j] = VMAX;
if (phi_out[i][j] < -VMAX) phi_out[i][j] = -VMAX;
if (psi_out[i][j] > VMAX) psi_out[i][j] = VMAX;
if (psi_out[i][j] < -VMAX) psi_out[i][j] = -VMAX;
}
}
}
}
// printf("phi(0,0) = %.3lg, psi(0,0) = %.3lg\n", phi[NX/2][NY/2], psi[NX/2][NY/2]);
}
void evolve_wave_half(double *phi_in[NX], double *psi_in[NX], double *phi_out[NX], double *psi_out[NX],
short int *xy_in[NX])
// void evolve_wave_half(phi_in, psi_in, phi_out, psi_out, xy_in)
// /* time step of field evolution */
// /* phi is real part, psi is imaginary part */
{
int i, j, iplus, iminus, jplus, jminus;
double delta1, delta2, x, y;
#pragma omp parallel for private(i,j,iplus,iminus,jplus,jminus,delta1,delta2,x,y)
for (i=1; i<NX-1; i++){
for (j=1; j<NY-1; j++){
if (xy_in[i][j]){
x = phi_in[i][j];
y = psi_in[i][j];
delta1 = phi_in[i+1][j] + phi_in[i-1][j] + phi_in[i][j+1] + phi_in[i][j-1] - 4.0*x;
delta2 = psi_in[i+1][j] + psi_in[i-1][j] + psi_in[i][j+1] + psi_in[i][j-1] - 4.0*y;
/* evolve phi and psi */
phi_out[i][j] = x - intstep*delta2;
psi_out[i][j] = y + intstep*delta1;
}
}
}
/* left boundary */
for (j=1; j<NY-1; j++){
if (xy_in[0][j]){
x = phi_in[0][j];
y = psi_in[0][j];
switch (B_COND) {
case (BC_DIRICHLET):
{
delta1 = phi_in[1][j] + phi_in[0][j+1] + phi_in[0][j-1] - 3.0*x;
delta2 = psi_in[1][j] + psi_in[0][j+1] + psi_in[0][j-1] - 3.0*y;
phi_out[0][j] = x - intstep*delta2;
psi_out[0][j] = y + intstep*delta1;
break;
}
case (BC_PERIODIC):
{
delta1 = phi_in[1][j] + phi_in[NX-1][j] + phi_in[0][j+1] + phi_in[0][j-1] - 4.0*x;
delta2 = psi_in[1][j] + psi_in[NX-1][j] + psi_in[0][j+1] + psi_in[0][j-1] - 4.0*y;
phi_out[0][j] = x - intstep*delta2;
psi_out[0][j] = y + intstep*delta1;
break;
}
}
}
}
/* right boundary */
for (j=1; j<NY-1; j++){
if (xy_in[0][j]){
x = phi_in[NX-1][j];
y = psi_in[NX-1][j];
switch (B_COND) {
case (BC_DIRICHLET):
{
delta1 = phi_in[NX-2][j] + phi_in[NX-1][j+1] + phi_in[NX-1][j-1] - 3.0*x;
delta2 = psi_in[NX-2][j] + psi_in[NX-1][j+1] + psi_in[NX-1][j-1] - 3.0*y;
phi_out[NX-1][j] = x - intstep*delta2;
psi_out[NX-1][j] = y + intstep*delta1;
break;
}
case (BC_PERIODIC):
{
delta1 = phi_in[NX-2][j] + phi_in[0][j] + phi_in[NX-1][j+1] + phi_in[NX-1][j-1] - 4.0*x;
delta2 = psi_in[NX-2][j] + psi_in[0][j] + psi_in[NX-1][j+1] + psi_in[NX-1][j-1] - 4.0*y;
phi_out[NX-1][j] = x - intstep*delta2;
psi_out[NX-1][j] = y + intstep*delta1;
break;
}
}
}
}
/* top boundary */
for (i=0; i<NX; i++){
if (xy_in[i][NY-1]){
x = phi_in[i][NY-1];
y = psi_in[i][NY-1];
switch (B_COND) {
case (BC_DIRICHLET):
{
iplus = i+1; if (iplus == NX) iplus = NX-1;
iminus = i-1; if (iminus == -1) iminus = 0;
delta1 = phi_in[iplus][NY-1] + phi_in[iminus][NY-1] + phi_in[i][NY-2] - 3.0*x;
delta2 = psi_in[iplus][NY-1] + psi_in[iminus][NY-1] + psi_in[i][NY-2] - 3.0*x;
phi_out[i][NY-1] = x - intstep*delta2;
psi_out[i][NY-1] = y + intstep*delta1;
break;
}
case (BC_PERIODIC):
{
iplus = (i+1) % NX;
iminus = (i-1) % NX;
if (iminus < 0) iminus += NX;
delta1 = phi_in[iplus][NY-1] + phi_in[iminus][NY-1] + phi_in[i][NY-2] + phi_in[i][0] - 4.0*x;
delta2 = psi_in[iplus][NY-1] + psi_in[iminus][NY-1] + psi_in[i][NY-2] + psi_in[i][0] - 4.0*y;
phi_out[i][NY-1] = x - intstep*delta2;
psi_out[i][NY-1] = y + intstep*delta1;
break;
}
}
}
}
/* bottom boundary */
for (i=0; i<NX; i++){
if (xy_in[i][0]){
x = phi_in[i][0];
y = psi_in[i][0];
switch (B_COND) {
case (BC_DIRICHLET):
{
iplus = i+1; if (iplus == NX) iplus = NX-1;
iminus = i-1; if (iminus == -1) iminus = 0;
delta1 = phi_in[iplus][0] + phi_in[iminus][0] + phi_in[i][1] - 3.0*x;
delta2 = psi_in[iplus][0] + psi_in[iminus][0] + psi_in[i][1] - 3.0*x;
phi_out[i][0] = x - intstep*delta2;
psi_out[i][0] = y + intstep*delta1;
break;
}
case (BC_PERIODIC):
{
iplus = (i+1) % NX;
iminus = (i-1) % NX;
if (iminus < 0) iminus += NX;
delta1 = phi_in[iplus][0] + phi_in[iminus][0] + phi_in[i][1] + phi_in[i][NY-1] - 4.0*x;
delta2 = psi_in[iplus][0] + psi_in[iminus][0] + psi_in[i][1] + psi_in[i][NY-1] - 4.0*y;
phi_out[i][0] = x - intstep*delta2;
psi_out[i][0] = y + intstep*delta1;
break;
}
}
}
}
/* for debugging purposes/if there is a risk of blow-up */
if (FLOOR) for (i=0; i<NX; i++){
for (j=0; j<NY; j++){
if (xy_in[i][j] != 0)
{
if (phi_out[i][j] > VMAX) phi_out[i][j] = VMAX;
if (phi_out[i][j] < -VMAX) phi_out[i][j] = -VMAX;
if (psi_out[i][j] > VMAX) psi_out[i][j] = VMAX;
if (psi_out[i][j] < -VMAX) psi_out[i][j] = -VMAX;
}
}
}
}
void evolve_wave(double *phi[NX], double *psi[NX], double *phi_tmp[NX], double *psi_tmp[NX], short int *xy_in[NX])
/* time step of field evolution */
/* phi is real part, psi is imaginary part */
{
evolve_wave_half(phi, psi, phi_tmp, psi_tmp, xy_in);
evolve_wave_half(phi_tmp, psi_tmp, phi, psi, xy_in);
}
double compute_variance(double *phi[NX], double *psi[NX], short int *xy_in[NX])
// double compute_variance(phi, psi, xy_in)
/* compute the variance (total probability) of the field */
// double *phi[NX], *psi[NX]; short int * xy_in[NX];
{
int i, j, n = 0;
double variance = 0.0;
for (i=1; i<NX; i++)
for (j=1; j<NY; j++)
{
if (xy_in[i][j])
{
n++;
variance += phi[i][j]*phi[i][j] + psi[i][j]*psi[i][j];
}
}
if (n==0) n=1;
return(variance/(double)n);
}
void renormalise_field(double *phi[NX], double *psi[NX], short int *xy_in[NX], double variance)
/* renormalise variance of field */
{
int i, j;
double stdv;
stdv = sqrt(variance);
for (i=1; i<NX; i++)
for (j=1; j<NY; j++)
{
if (xy_in[i][j])
{
phi[i][j] = phi[i][j]/stdv;
psi[i][j] = psi[i][j]/stdv;
}
}
}
void draw_color_bar(int plot, double range)
{
if (ROTATE_COLOR_SCHEME) draw_color_scheme(-1.0, -0.8, XMAX - 0.1, -1.0, plot, -range, range);
else draw_color_scheme(1.7, YMIN + 0.1, 1.9, YMAX - 0.1, plot, -range, range);
}
void animation()
{
double time, scale, dx, var;
double *phi[NX], *psi[NX], *phi_tmp[NX], *psi_tmp[NX];
short int *xy_in[NX];
int i, j, s;
/* Since NX and NY are big, it seemed wiser to use some memory allocation here */
for (i=0; i<NX; i++)
{
phi[i] = (double *)malloc(NY*sizeof(double));
psi[i] = (double *)malloc(NY*sizeof(double));
phi_tmp[i] = (double *)malloc(NY*sizeof(double));
psi_tmp[i] = (double *)malloc(NY*sizeof(double));
xy_in[i] = (short int *)malloc(NY*sizeof(short int));
}
/* initialise polyline for von Koch and simular domains */
npolyline = init_polyline(MDEPTH, polyline);
// for (i=0; i<npolyline; i++) printf("vertex %i: (%.3f, %.3f)\n", i, polyline[i].x, polyline[i].y);
dx = (XMAX-XMIN)/((double)NX);
intstep = DT/(dx*dx*HBAR);
intstep1 = DT/(dx*HBAR);
printf("Integration step %.3lg\n", intstep);
/* initialize wave wave function */
init_coherent_state(-0.5, 0.0, 15.0, 0.0, 0.15, phi, psi, xy_in);
// init_coherent_state(0.0, 0.0, 0.0, 5.0, 0.03, phi, psi, xy_in);
// init_coherent_state(-0.5, 0.0, 1.0, 1.0, 0.05, phi, psi, xy_in);
if (SCALE)
{
var = compute_variance(phi,psi, xy_in);
scale = sqrt(1.0 + var);
renormalise_field(phi, psi, xy_in, var);
}
blank();
if (DRAW_COLOR_SCHEME) draw_color_bar(PLOT, COLORBAR_RANGE);
glColor3f(0.0, 0.0, 0.0);
glutSwapBuffers();
sleep(SLEEP1);
for (i=0; i<=NSTEPS; i++)
{
/* compute the variance of the field to adjust color scheme */
/* the color depends on the field divided by sqrt(1 + variance) */
if (SCALE)
{
var = compute_variance(phi,psi, xy_in);
scale = sqrt(1.0 + var);
// printf("Norm: %5lg\t Scaling factor: %5lg\n", var, scale);
renormalise_field(phi, psi, xy_in, var);
}
else scale = 1.0;
draw_wave(phi, psi, xy_in, scale, i);
// printf("Wave drawn\n");
for (j=0; j<NVID; j++) evolve_wave(phi, psi, phi_tmp, psi_tmp, xy_in);
draw_billiard();
if (DRAW_COLOR_SCHEME) draw_color_bar(PLOT, COLORBAR_RANGE);
glutSwapBuffers();
if (MOVIE)
{
save_frame();
/* it seems that saving too many files too fast can cause trouble with the file system */
/* so this is to make a pause from time to time - parameter PAUSE may need adjusting */
if (i % PAUSE == PAUSE - 1)
{
printf("Making a short pause\n");
sleep(PSLEEP);
s = system("mv wave*.tif tif_schrod/");
}
}
}
if (MOVIE)
{
for (i=0; i<END_FRAMES; i++) save_frame();
s = system("mv wave*.tif tif_schrod/");
}
for (i=0; i<NX; i++)
{
free(phi[i]);
free(psi[i]);
free(phi_tmp[i]);
free(psi_tmp[i]);
free(xy_in[i]);
}
}
void display(void)
{
glPushMatrix();
blank();
glutSwapBuffers();
blank();
glutSwapBuffers();
animation();
sleep(SLEEP2);
glPopMatrix();
glutDestroyWindow(glutGetWindow());
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
glutInitWindowSize(WINWIDTH,WINHEIGHT);
glutCreateWindow("Schrodinger equation in a planar domain");
init();
glutDisplayFunc(display);
glutMainLoop();
return 0;
}
|
resize_bilinear.h | // Copyright 2018 Xiaomi, Inc. All rights reserved.
//
// 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.
#ifndef MACE_KERNELS_RESIZE_BILINEAR_H_
#define MACE_KERNELS_RESIZE_BILINEAR_H_
#include <algorithm>
#include <memory>
#include <vector>
#include "mace/core/future.h"
#include "mace/core/tensor.h"
#include "mace/kernels/kernel.h"
#include "mace/utils/quantize.h"
namespace mace {
namespace kernels {
struct CachedInterpolation {
index_t lower; // Lower source index used in the interpolation
index_t upper; // Upper source index used in the interpolation
// 1-D linear iterpolation scale (see:
// https://en.wikipedia.org/wiki/Bilinear_interpolation)
float lerp;
};
inline float CalculateResizeScale(index_t in_size,
index_t out_size,
bool align_corners) {
return (align_corners && out_size > 1)
? (in_size - 1) / static_cast<float>(out_size - 1)
: in_size / static_cast<float>(out_size);
}
inline void ComputeInterpolationWeights(
const index_t out_size,
const index_t in_size,
const float scale,
CachedInterpolation *interpolation) {
interpolation[out_size].lower = 0;
interpolation[out_size].upper = 0;
for (index_t i = out_size - 1; i >= 0; --i) {
const float in = i * scale;
interpolation[i].lower = static_cast<index_t>(in);
interpolation[i].upper = std::min(interpolation[i].lower + 1, in_size - 1);
interpolation[i].lerp = in - interpolation[i].lower;
}
}
template <typename T>
inline T ComputeLerp(const T top_left,
const T top_right,
const T bottom_left,
const T bottom_right,
const float x_lerp,
const float y_lerp);
template <>
inline float ComputeLerp<float>(const float top_left,
const float top_right,
const float bottom_left,
const float bottom_right,
const float x_lerp,
const float y_lerp) {
const float top = top_left + (top_right - top_left) * x_lerp;
const float bottom = bottom_left + (bottom_right - bottom_left) * x_lerp;
return top + (bottom - top) * y_lerp;
}
template <>
inline uint8_t ComputeLerp<uint8_t>(const uint8_t top_left,
const uint8_t top_right,
const uint8_t bottom_left,
const uint8_t bottom_right,
const float x_lerp,
const float y_lerp) {
const float top = top_left + (top_right - top_left) * x_lerp;
const float bottom = bottom_left + (bottom_right - bottom_left) * x_lerp;
return Saturate<uint8_t>(roundf(top + (bottom - top) * y_lerp));
}
template <typename T>
inline void ResizeImageNCHW(const T *images,
const index_t batch_size,
const index_t in_height,
const index_t in_width,
const index_t out_height,
const index_t out_width,
const index_t channels,
const std::vector<CachedInterpolation> &xs_vec,
const std::vector<CachedInterpolation> &ys,
T *output) {
const CachedInterpolation *xs = xs_vec.data();
#pragma omp parallel for collapse(2)
for (index_t b = 0; b < batch_size; ++b) {
for (index_t c = 0; c < channels; ++c) {
const T
*channel_input_ptr =
images + (b * channels + c) * in_height * in_width;
T *channel_output_ptr =
output + (b * channels + c) * out_height * out_width;
for (index_t y = 0; y < out_height; ++y) {
const T *y_lower_input_ptr =
channel_input_ptr + ys[y].lower * in_width;
const T *y_upper_input_ptr =
channel_input_ptr + ys[y].upper * in_width;
const float ys_lerp = ys[y].lerp;
for (index_t x = 0; x < out_width; ++x) {
const float xs_lerp = xs[x].lerp;
const T top_left = y_lower_input_ptr[xs[x].lower];
const T top_right = y_lower_input_ptr[xs[x].upper];
const T bottom_left = y_upper_input_ptr[xs[x].lower];
const T bottom_right = y_upper_input_ptr[xs[x].upper];
channel_output_ptr[y * out_width + x] =
ComputeLerp(top_left, top_right, bottom_left,
bottom_right, xs_lerp, ys_lerp);
}
}
}
}
}
template <typename T>
inline void ResizeImageNHWC(const T *images,
const index_t batch_size,
const index_t in_height,
const index_t in_width,
const index_t out_height,
const index_t out_width,
const index_t channels,
const std::vector<CachedInterpolation> &xs_vec,
const std::vector<CachedInterpolation> &ys,
T *output) {
const CachedInterpolation *xs = xs_vec.data();
for (index_t b = 0; b < batch_size; ++b) {
const T *input_base = images + b * channels * in_height * in_width;
T *output_base = output + b * channels * out_height * out_width;
#pragma omp parallel for
for (index_t y = 0; y < out_height; ++y) {
const T
*y_lower_input_ptr = input_base + ys[y].lower * in_width * channels;
const T
*y_upper_input_ptr = input_base + ys[y].upper * in_width * channels;
const float ys_lerp = ys[y].lerp;
for (index_t x = 0; x < out_width; ++x) {
const float xs_lerp = xs[x].lerp;
const T *top_left = y_lower_input_ptr + xs[x].lower * channels;
const T *top_right = y_lower_input_ptr + xs[x].upper * channels;
const T *bottom_left = y_upper_input_ptr + xs[x].lower * channels;
const T *bottom_right = y_upper_input_ptr + xs[x].upper * channels;
T *output_ptr = output_base + (y * out_width + x) * channels;
for (index_t c = 0; c < channels; ++c) {
output_ptr[c] =
ComputeLerp(top_left[c], top_right[c], bottom_left[c],
bottom_right[c], xs_lerp, ys_lerp);
}
}
}
}
}
template<DeviceType D, typename T>
struct ResizeBilinearFunctor : OpKernel {
ResizeBilinearFunctor(OpKernelContext *context,
const std::vector<index_t> &size,
bool align_corners)
: OpKernel(context), align_corners_(align_corners) {
MACE_CHECK(size.size() == 2);
out_height_ = size[0];
out_width_ = size[1];
}
MaceStatus operator()(const Tensor *input,
Tensor *output,
StatsFuture *future) {
MACE_UNUSED(future);
const index_t batch = input->dim(0);
const index_t channels = input->dim(1);
const index_t in_height = input->dim(2);
const index_t in_width = input->dim(3);
index_t out_height = out_height_;
index_t out_width = out_width_;
MACE_CHECK(out_height > 0 && out_width > 0);
std::vector<index_t> out_shape{batch, channels, out_height, out_width};
MACE_RETURN_IF_ERROR(output->Resize(out_shape));
Tensor::MappingGuard input_mapper(input);
Tensor::MappingGuard output_mapper(output);
const T *input_data = input->data<T>();
T *output_data = output->mutable_data<T>();
if (out_height == in_height && out_width == in_width) {
std::copy(input_data,
input_data + batch * channels * in_height * in_width,
output_data);
return MACE_SUCCESS;
}
float height_scale =
CalculateResizeScale(in_height, out_height, align_corners_);
float width_scale =
CalculateResizeScale(in_width, out_width, align_corners_);
std::vector<CachedInterpolation> ys(out_height + 1);
std::vector<CachedInterpolation> xs(out_width + 1);
// Compute the cached interpolation weights on the x and y dimensions.
ComputeInterpolationWeights(out_height, in_height, height_scale, ys.data());
ComputeInterpolationWeights(out_width, in_width, width_scale, xs.data());
ResizeImageNCHW(input_data,
batch,
in_height,
in_width,
out_height,
out_width,
channels,
xs,
ys,
output_data);
return MACE_SUCCESS;
}
bool align_corners_;
index_t out_height_;
index_t out_width_;
};
template<DeviceType D>
struct ResizeBilinearFunctor<D, uint8_t> : OpKernel {
ResizeBilinearFunctor(OpKernelContext *context,
const std::vector<index_t> &size,
bool align_corners)
: OpKernel(context), align_corners_(align_corners) {
MACE_CHECK(size.size() == 2);
out_height_ = size[0];
out_width_ = size[1];
}
MaceStatus operator()(const Tensor *input,
Tensor *output,
StatsFuture *future) {
MACE_UNUSED(future);
const index_t batch = input->dim(0);
const index_t in_height = input->dim(1);
const index_t in_width = input->dim(2);
const index_t channels = input->dim(3);
index_t out_height = out_height_;
index_t out_width = out_width_;
MACE_CHECK(out_height > 0 && out_width > 0);
std::vector<index_t> out_shape{batch, out_height, out_width, channels};
MACE_RETURN_IF_ERROR(output->Resize(out_shape));
Tensor::MappingGuard input_mapper(input);
Tensor::MappingGuard output_mapper(output);
const uint8_t *input_data = input->data<uint8_t>();
uint8_t *output_data = output->mutable_data<uint8_t>();
if (out_height == in_height && out_width == in_width) {
std::copy(input_data,
input_data + batch * in_height * in_width * channels ,
output_data);
return MACE_SUCCESS;
}
float height_scale =
CalculateResizeScale(in_height, out_height, align_corners_);
float width_scale =
CalculateResizeScale(in_width, out_width, align_corners_);
std::vector<CachedInterpolation> ys(out_height + 1);
std::vector<CachedInterpolation> xs(out_width + 1);
// Compute the cached interpolation weights on the x and y dimensions.
ComputeInterpolationWeights(out_height, in_height, height_scale, ys.data());
ComputeInterpolationWeights(out_width, in_width, width_scale, xs.data());
ResizeImageNHWC(input_data,
batch,
in_height,
in_width,
out_height,
out_width,
channels,
xs,
ys,
output_data);
return MACE_SUCCESS;
}
bool align_corners_;
index_t out_height_;
index_t out_width_;
};
#ifdef MACE_ENABLE_OPENCL
class OpenCLResizeBilinearKernel {
public:
virtual MaceStatus Compute(
OpKernelContext *context,
const Tensor *input,
Tensor *output,
StatsFuture *future) = 0;
MACE_VIRTUAL_EMPTY_DESTRUCTOR(OpenCLResizeBilinearKernel);
};
template<typename T>
struct ResizeBilinearFunctor<DeviceType::GPU, T>
: OpKernel {
ResizeBilinearFunctor(OpKernelContext *context,
const std::vector<index_t> &size,
bool align_corners);
MaceStatus operator()(const Tensor *input,
Tensor *output,
StatsFuture *future);
std::unique_ptr<OpenCLResizeBilinearKernel> kernel_;
};
#endif // MACE_ENABLE_OPENCL
} // namespace kernels
} // namespace mace
#endif // MACE_KERNELS_RESIZE_BILINEAR_H_
|
convolutiondepthwise_3x3_pack8_fp16.h | // Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// 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.
static void convdw3x3s1_fp16_pack8_avx(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt)
{
int w = bottom_blob.w;
int outw = top_blob.w;
int outh = top_blob.h;
const int group = bottom_blob.c;
const float* bias = _bias;
#pragma omp parallel for num_threads(opt.num_threads)
for (int g = 0; g < group; g++)
{
Mat out = top_blob.channel(g);
__m256 _bias0 = bias ? _mm256_loadu_ps((const float*)bias + g * 8) : _mm256_set1_ps(0.f);
const unsigned short* k0 = (const unsigned short*)kernel.row(g);
float* outptr0 = out.row(0);
float* outptr1 = out.row(1);
const Mat img0 = bottom_blob.channel(g);
const float* r0 = img0.row(0);
const float* r1 = img0.row(1);
const float* r2 = img0.row(2);
__m256 _k00 = loadfp16(k0);
__m256 _k01 = loadfp16(k0 + 8);
__m256 _k02 = loadfp16(k0 + 16);
__m256 _k10 = loadfp16(k0 + 24);
__m256 _k11 = loadfp16(k0 + 32);
__m256 _k12 = loadfp16(k0 + 40);
__m256 _k20 = loadfp16(k0 + 48);
__m256 _k21 = loadfp16(k0 + 56);
__m256 _k22 = loadfp16(k0 + 64);
int i = 0;
for (; i < outh; i++)
{
int j = 0;
for (; j + 7 < outw; j += 8)
{
__m256 _sum0 = _bias0;
__m256 _r00 = _mm256_loadu_ps(r0);
__m256 _r01 = _mm256_loadu_ps(r0 + 8);
__m256 _r02 = _mm256_loadu_ps(r0 + 16);
__m256 _r10 = _mm256_loadu_ps(r1);
__m256 _r11 = _mm256_loadu_ps(r1 + 8);
__m256 _r12 = _mm256_loadu_ps(r1 + 16);
__m256 _r20 = _mm256_loadu_ps(r2);
__m256 _r21 = _mm256_loadu_ps(r2 + 8);
__m256 _r22 = _mm256_loadu_ps(r2 + 16);
_sum0 = _mm256_fmadd_ps(_k00, _r00, _sum0);
_sum0 = _mm256_fmadd_ps(_k01, _r01, _sum0);
_sum0 = _mm256_fmadd_ps(_k02, _r02, _sum0);
_sum0 = _mm256_fmadd_ps(_k10, _r10, _sum0);
_sum0 = _mm256_fmadd_ps(_k11, _r11, _sum0);
_sum0 = _mm256_fmadd_ps(_k12, _r12, _sum0);
_sum0 = _mm256_fmadd_ps(_k20, _r20, _sum0);
_sum0 = _mm256_fmadd_ps(_k21, _r21, _sum0);
_sum0 = _mm256_fmadd_ps(_k22, _r22, _sum0);
__m256 _sum1 = _bias0;
__m256 _r03 = _mm256_loadu_ps(r0 + 24);
__m256 _r13 = _mm256_loadu_ps(r1 + 24);
__m256 _r23 = _mm256_loadu_ps(r2 + 24);
_mm256_storeu_ps(outptr0, _sum0);
_sum1 = _mm256_fmadd_ps(_k00, _r01, _sum1);
_sum1 = _mm256_fmadd_ps(_k01, _r02, _sum1);
_sum1 = _mm256_fmadd_ps(_k02, _r03, _sum1);
_sum1 = _mm256_fmadd_ps(_k10, _r11, _sum1);
_sum1 = _mm256_fmadd_ps(_k11, _r12, _sum1);
_sum1 = _mm256_fmadd_ps(_k12, _r13, _sum1);
_sum1 = _mm256_fmadd_ps(_k20, _r21, _sum1);
_sum1 = _mm256_fmadd_ps(_k21, _r22, _sum1);
_sum1 = _mm256_fmadd_ps(_k22, _r23, _sum1);
__m256 _sum2 = _bias0;
__m256 _r04 = _mm256_loadu_ps(r0 + 32);
__m256 _r14 = _mm256_loadu_ps(r1 + 32);
__m256 _r24 = _mm256_loadu_ps(r2 + 32);
_mm256_storeu_ps(outptr0 + 8, _sum1);
_sum2 = _mm256_fmadd_ps(_k00, _r02, _sum2);
_sum2 = _mm256_fmadd_ps(_k01, _r03, _sum2);
_sum2 = _mm256_fmadd_ps(_k02, _r04, _sum2);
_sum2 = _mm256_fmadd_ps(_k10, _r12, _sum2);
_sum2 = _mm256_fmadd_ps(_k11, _r13, _sum2);
_sum2 = _mm256_fmadd_ps(_k12, _r14, _sum2);
_sum2 = _mm256_fmadd_ps(_k20, _r22, _sum2);
_sum2 = _mm256_fmadd_ps(_k21, _r23, _sum2);
_sum2 = _mm256_fmadd_ps(_k22, _r24, _sum2);
__m256 _sum3 = _bias0;
__m256 _r05 = _mm256_loadu_ps(r0 + 40);
__m256 _r15 = _mm256_loadu_ps(r1 + 40);
__m256 _r25 = _mm256_loadu_ps(r2 + 40);
_mm256_storeu_ps(outptr0 + 16, _sum2);
_sum3 = _mm256_fmadd_ps(_k00, _r03, _sum3);
_sum3 = _mm256_fmadd_ps(_k01, _r04, _sum3);
_sum3 = _mm256_fmadd_ps(_k02, _r05, _sum3);
_sum3 = _mm256_fmadd_ps(_k10, _r13, _sum3);
_sum3 = _mm256_fmadd_ps(_k11, _r14, _sum3);
_sum3 = _mm256_fmadd_ps(_k12, _r15, _sum3);
_sum3 = _mm256_fmadd_ps(_k20, _r23, _sum3);
_sum3 = _mm256_fmadd_ps(_k21, _r24, _sum3);
_sum3 = _mm256_fmadd_ps(_k22, _r25, _sum3);
__m256 _sum4 = _bias0;
__m256 _r06 = _mm256_loadu_ps(r0 + 48);
__m256 _r16 = _mm256_loadu_ps(r1 + 48);
__m256 _r26 = _mm256_loadu_ps(r2 + 48);
_mm256_storeu_ps(outptr0 + 24, _sum3);
_sum4 = _mm256_fmadd_ps(_k00, _r04, _sum4);
_sum4 = _mm256_fmadd_ps(_k01, _r05, _sum4);
_sum4 = _mm256_fmadd_ps(_k02, _r06, _sum4);
_sum4 = _mm256_fmadd_ps(_k10, _r14, _sum4);
_sum4 = _mm256_fmadd_ps(_k11, _r15, _sum4);
_sum4 = _mm256_fmadd_ps(_k12, _r16, _sum4);
_sum4 = _mm256_fmadd_ps(_k20, _r24, _sum4);
_sum4 = _mm256_fmadd_ps(_k21, _r25, _sum4);
_sum4 = _mm256_fmadd_ps(_k22, _r26, _sum4);
__m256 _sum5 = _bias0;
__m256 _r07 = _mm256_loadu_ps(r0 + 56);
__m256 _r17 = _mm256_loadu_ps(r1 + 56);
__m256 _r27 = _mm256_loadu_ps(r2 + 56);
_mm256_storeu_ps(outptr0 + 32, _sum4);
_sum5 = _mm256_fmadd_ps(_k00, _r05, _sum5);
_sum5 = _mm256_fmadd_ps(_k01, _r06, _sum5);
_sum5 = _mm256_fmadd_ps(_k02, _r07, _sum5);
_sum5 = _mm256_fmadd_ps(_k10, _r15, _sum5);
_sum5 = _mm256_fmadd_ps(_k11, _r16, _sum5);
_sum5 = _mm256_fmadd_ps(_k12, _r17, _sum5);
_sum5 = _mm256_fmadd_ps(_k20, _r25, _sum5);
_sum5 = _mm256_fmadd_ps(_k21, _r26, _sum5);
_sum5 = _mm256_fmadd_ps(_k22, _r27, _sum5);
__m256 _sum6 = _bias0;
__m256 _r08 = _mm256_loadu_ps(r0 + 64);
__m256 _r18 = _mm256_loadu_ps(r1 + 64);
__m256 _r28 = _mm256_loadu_ps(r2 + 64);
_mm256_storeu_ps(outptr0 + 40, _sum5);
_sum6 = _mm256_fmadd_ps(_k00, _r06, _sum6);
_sum6 = _mm256_fmadd_ps(_k01, _r07, _sum6);
_sum6 = _mm256_fmadd_ps(_k02, _r08, _sum6);
_sum6 = _mm256_fmadd_ps(_k10, _r16, _sum6);
_sum6 = _mm256_fmadd_ps(_k11, _r17, _sum6);
_sum6 = _mm256_fmadd_ps(_k12, _r18, _sum6);
_sum6 = _mm256_fmadd_ps(_k20, _r26, _sum6);
_sum6 = _mm256_fmadd_ps(_k21, _r27, _sum6);
_sum6 = _mm256_fmadd_ps(_k22, _r28, _sum6);
__m256 _sum7 = _bias0;
__m256 _r09 = _mm256_loadu_ps(r0 + 72);
__m256 _r19 = _mm256_loadu_ps(r1 + 72);
__m256 _r29 = _mm256_loadu_ps(r2 + 72);
_mm256_storeu_ps(outptr0 + 48, _sum6);
_sum7 = _mm256_fmadd_ps(_k00, _r07, _sum7);
_sum7 = _mm256_fmadd_ps(_k01, _r08, _sum7);
_sum7 = _mm256_fmadd_ps(_k02, _r09, _sum7);
_sum7 = _mm256_fmadd_ps(_k10, _r17, _sum7);
_sum7 = _mm256_fmadd_ps(_k11, _r18, _sum7);
_sum7 = _mm256_fmadd_ps(_k12, _r19, _sum7);
_sum7 = _mm256_fmadd_ps(_k20, _r27, _sum7);
_sum7 = _mm256_fmadd_ps(_k21, _r28, _sum7);
_sum7 = _mm256_fmadd_ps(_k22, _r29, _sum7);
_mm256_storeu_ps(outptr0 + 56, _sum7);
r0 += 64;
r1 += 64;
r2 += 64;
outptr0 += 64;
}
for (; j + 3 < outw; j += 4)
{
__m256 _sum0 = _bias0;
__m256 _r00 = _mm256_loadu_ps(r0);
__m256 _r01 = _mm256_loadu_ps(r0 + 8);
__m256 _r02 = _mm256_loadu_ps(r0 + 16);
__m256 _r10 = _mm256_loadu_ps(r1);
__m256 _r11 = _mm256_loadu_ps(r1 + 8);
__m256 _r12 = _mm256_loadu_ps(r1 + 16);
__m256 _r20 = _mm256_loadu_ps(r2);
__m256 _r21 = _mm256_loadu_ps(r2 + 8);
__m256 _r22 = _mm256_loadu_ps(r2 + 16);
_sum0 = _mm256_fmadd_ps(_k00, _r00, _sum0);
_sum0 = _mm256_fmadd_ps(_k01, _r01, _sum0);
_sum0 = _mm256_fmadd_ps(_k02, _r02, _sum0);
_sum0 = _mm256_fmadd_ps(_k10, _r10, _sum0);
_sum0 = _mm256_fmadd_ps(_k11, _r11, _sum0);
_sum0 = _mm256_fmadd_ps(_k12, _r12, _sum0);
_sum0 = _mm256_fmadd_ps(_k20, _r20, _sum0);
_sum0 = _mm256_fmadd_ps(_k21, _r21, _sum0);
_sum0 = _mm256_fmadd_ps(_k22, _r22, _sum0);
__m256 _sum1 = _bias0;
__m256 _r03 = _mm256_loadu_ps(r0 + 24);
__m256 _r13 = _mm256_loadu_ps(r1 + 24);
__m256 _r23 = _mm256_loadu_ps(r2 + 24);
_mm256_storeu_ps(outptr0, _sum0);
_sum1 = _mm256_fmadd_ps(_k00, _r01, _sum1);
_sum1 = _mm256_fmadd_ps(_k01, _r02, _sum1);
_sum1 = _mm256_fmadd_ps(_k02, _r03, _sum1);
_sum1 = _mm256_fmadd_ps(_k10, _r11, _sum1);
_sum1 = _mm256_fmadd_ps(_k11, _r12, _sum1);
_sum1 = _mm256_fmadd_ps(_k12, _r13, _sum1);
_sum1 = _mm256_fmadd_ps(_k20, _r21, _sum1);
_sum1 = _mm256_fmadd_ps(_k21, _r22, _sum1);
_sum1 = _mm256_fmadd_ps(_k22, _r23, _sum1);
__m256 _sum2 = _bias0;
__m256 _r04 = _mm256_loadu_ps(r0 + 32);
__m256 _r14 = _mm256_loadu_ps(r1 + 32);
__m256 _r24 = _mm256_loadu_ps(r2 + 32);
_mm256_storeu_ps(outptr0 + 8, _sum1);
_sum2 = _mm256_fmadd_ps(_k00, _r02, _sum2);
_sum2 = _mm256_fmadd_ps(_k01, _r03, _sum2);
_sum2 = _mm256_fmadd_ps(_k02, _r04, _sum2);
_sum2 = _mm256_fmadd_ps(_k10, _r12, _sum2);
_sum2 = _mm256_fmadd_ps(_k11, _r13, _sum2);
_sum2 = _mm256_fmadd_ps(_k12, _r14, _sum2);
_sum2 = _mm256_fmadd_ps(_k20, _r22, _sum2);
_sum2 = _mm256_fmadd_ps(_k21, _r23, _sum2);
_sum2 = _mm256_fmadd_ps(_k22, _r24, _sum2);
__m256 _sum3 = _bias0;
__m256 _r05 = _mm256_loadu_ps(r0 + 40);
__m256 _r15 = _mm256_loadu_ps(r1 + 40);
__m256 _r25 = _mm256_loadu_ps(r2 + 40);
_mm256_storeu_ps(outptr0 + 16, _sum2);
_sum3 = _mm256_fmadd_ps(_k00, _r03, _sum3);
_sum3 = _mm256_fmadd_ps(_k01, _r04, _sum3);
_sum3 = _mm256_fmadd_ps(_k02, _r05, _sum3);
_sum3 = _mm256_fmadd_ps(_k10, _r13, _sum3);
_sum3 = _mm256_fmadd_ps(_k11, _r14, _sum3);
_sum3 = _mm256_fmadd_ps(_k12, _r15, _sum3);
_sum3 = _mm256_fmadd_ps(_k20, _r23, _sum3);
_sum3 = _mm256_fmadd_ps(_k21, _r24, _sum3);
_sum3 = _mm256_fmadd_ps(_k22, _r25, _sum3);
_mm256_storeu_ps(outptr0 + 24, _sum3);
r0 += 32;
r1 += 32;
r2 += 32;
outptr0 += 32;
}
for (; j + 1 < outw; j += 2)
{
__m256 _sum0 = _bias0;
__m256 _r00 = _mm256_loadu_ps(r0);
__m256 _r01 = _mm256_loadu_ps(r0 + 8);
__m256 _r02 = _mm256_loadu_ps(r0 + 16);
__m256 _r10 = _mm256_loadu_ps(r1);
__m256 _r11 = _mm256_loadu_ps(r1 + 8);
__m256 _r12 = _mm256_loadu_ps(r1 + 16);
__m256 _r20 = _mm256_loadu_ps(r2);
__m256 _r21 = _mm256_loadu_ps(r2 + 8);
__m256 _r22 = _mm256_loadu_ps(r2 + 16);
_sum0 = _mm256_fmadd_ps(_k00, _r00, _sum0);
_sum0 = _mm256_fmadd_ps(_k01, _r01, _sum0);
_sum0 = _mm256_fmadd_ps(_k02, _r02, _sum0);
_sum0 = _mm256_fmadd_ps(_k10, _r10, _sum0);
_sum0 = _mm256_fmadd_ps(_k11, _r11, _sum0);
_sum0 = _mm256_fmadd_ps(_k12, _r12, _sum0);
_sum0 = _mm256_fmadd_ps(_k20, _r20, _sum0);
_sum0 = _mm256_fmadd_ps(_k21, _r21, _sum0);
_sum0 = _mm256_fmadd_ps(_k22, _r22, _sum0);
__m256 _sum1 = _bias0;
__m256 _r03 = _mm256_loadu_ps(r0 + 24);
__m256 _r13 = _mm256_loadu_ps(r1 + 24);
__m256 _r23 = _mm256_loadu_ps(r2 + 24);
_mm256_storeu_ps(outptr0, _sum0);
_sum1 = _mm256_fmadd_ps(_k00, _r01, _sum1);
_sum1 = _mm256_fmadd_ps(_k01, _r02, _sum1);
_sum1 = _mm256_fmadd_ps(_k02, _r03, _sum1);
_sum1 = _mm256_fmadd_ps(_k10, _r11, _sum1);
_sum1 = _mm256_fmadd_ps(_k11, _r12, _sum1);
_sum1 = _mm256_fmadd_ps(_k12, _r13, _sum1);
_sum1 = _mm256_fmadd_ps(_k20, _r21, _sum1);
_sum1 = _mm256_fmadd_ps(_k21, _r22, _sum1);
_sum1 = _mm256_fmadd_ps(_k22, _r23, _sum1);
_mm256_storeu_ps(outptr0 + 8, _sum1);
r0 += 16;
r1 += 16;
r2 += 16;
outptr0 += 16;
}
for (; j < outw; j++)
{
__m256 _sum0 = _bias0;
__m256 _r00 = _mm256_loadu_ps(r0);
__m256 _r01 = _mm256_loadu_ps(r0 + 8);
__m256 _r02 = _mm256_loadu_ps(r0 + 16);
__m256 _r10 = _mm256_loadu_ps(r1);
__m256 _r11 = _mm256_loadu_ps(r1 + 8);
__m256 _r12 = _mm256_loadu_ps(r1 + 16);
__m256 _r20 = _mm256_loadu_ps(r2);
__m256 _r21 = _mm256_loadu_ps(r2 + 8);
__m256 _r22 = _mm256_loadu_ps(r2 + 16);
_sum0 = _mm256_fmadd_ps(_k00, _r00, _sum0);
_sum0 = _mm256_fmadd_ps(_k01, _r01, _sum0);
_sum0 = _mm256_fmadd_ps(_k02, _r02, _sum0);
_sum0 = _mm256_fmadd_ps(_k10, _r10, _sum0);
_sum0 = _mm256_fmadd_ps(_k11, _r11, _sum0);
_sum0 = _mm256_fmadd_ps(_k12, _r12, _sum0);
_sum0 = _mm256_fmadd_ps(_k20, _r20, _sum0);
_sum0 = _mm256_fmadd_ps(_k21, _r21, _sum0);
_sum0 = _mm256_fmadd_ps(_k22, _r22, _sum0);
_mm256_storeu_ps(outptr0, _sum0);
r0 += 8;
r1 += 8;
r2 += 8;
outptr0 += 8;
}
r0 += 2 * 8;
r1 += 2 * 8;
r2 += 2 * 8;
}
}
}
static void convdw3x3s2_fp16_pack8_avx(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt)
{
int w = bottom_blob.w;
int outw = top_blob.w;
int outh = top_blob.h;
const int group = bottom_blob.c;
const int tailstep = (w - 2 * outw + w) * 8;
const float* bias = _bias;
#pragma omp parallel for num_threads(opt.num_threads)
for (int g = 0; g < group; g++)
{
Mat out = top_blob.channel(g);
__m256 _bias0 = bias ? _mm256_loadu_ps((const float*)bias + g * 8) : _mm256_set1_ps(0.f);
const unsigned short* k0 = (const unsigned short*)kernel.row(g);
float* outptr0 = out.row(0);
float* outptr1 = out.row(1);
const Mat img0 = bottom_blob.channel(g);
const float* r0 = img0.row(0);
const float* r1 = img0.row(1);
const float* r2 = img0.row(2);
__m256 _k00 = loadfp16(k0);
__m256 _k01 = loadfp16(k0 + 8);
__m256 _k02 = loadfp16(k0 + 16);
__m256 _k10 = loadfp16(k0 + 24);
__m256 _k11 = loadfp16(k0 + 32);
__m256 _k12 = loadfp16(k0 + 40);
__m256 _k20 = loadfp16(k0 + 48);
__m256 _k21 = loadfp16(k0 + 56);
__m256 _k22 = loadfp16(k0 + 64);
int i = 0;
for (; i < outh; i++)
{
int j = 0;
for (; j + 3 < outw; j += 4)
{
__m256 _sum0 = _bias0;
__m256 _r00 = _mm256_loadu_ps(r0);
__m256 _r01 = _mm256_loadu_ps(r0 + 8);
__m256 _r02 = _mm256_loadu_ps(r0 + 16);
__m256 _r10 = _mm256_loadu_ps(r1);
__m256 _r11 = _mm256_loadu_ps(r1 + 8);
__m256 _r12 = _mm256_loadu_ps(r1 + 16);
__m256 _r20 = _mm256_loadu_ps(r2);
__m256 _r21 = _mm256_loadu_ps(r2 + 8);
__m256 _r22 = _mm256_loadu_ps(r2 + 16);
_sum0 = _mm256_fmadd_ps(_k00, _r00, _sum0);
_sum0 = _mm256_fmadd_ps(_k01, _r01, _sum0);
_sum0 = _mm256_fmadd_ps(_k02, _r02, _sum0);
_sum0 = _mm256_fmadd_ps(_k10, _r10, _sum0);
_sum0 = _mm256_fmadd_ps(_k11, _r11, _sum0);
_sum0 = _mm256_fmadd_ps(_k12, _r12, _sum0);
_sum0 = _mm256_fmadd_ps(_k20, _r20, _sum0);
_sum0 = _mm256_fmadd_ps(_k21, _r21, _sum0);
_sum0 = _mm256_fmadd_ps(_k22, _r22, _sum0);
__m256 _sum1 = _bias0;
__m256 _r03 = _mm256_loadu_ps(r0 + 24);
__m256 _r13 = _mm256_loadu_ps(r1 + 24);
__m256 _r23 = _mm256_loadu_ps(r2 + 24);
__m256 _r04 = _mm256_loadu_ps(r0 + 32);
__m256 _r14 = _mm256_loadu_ps(r1 + 32);
__m256 _r24 = _mm256_loadu_ps(r2 + 32);
_mm256_storeu_ps(outptr0, _sum0);
_sum1 = _mm256_fmadd_ps(_k00, _r02, _sum1);
_sum1 = _mm256_fmadd_ps(_k01, _r03, _sum1);
_sum1 = _mm256_fmadd_ps(_k02, _r04, _sum1);
_sum1 = _mm256_fmadd_ps(_k10, _r12, _sum1);
_sum1 = _mm256_fmadd_ps(_k11, _r13, _sum1);
_sum1 = _mm256_fmadd_ps(_k12, _r14, _sum1);
_sum1 = _mm256_fmadd_ps(_k20, _r22, _sum1);
_sum1 = _mm256_fmadd_ps(_k21, _r23, _sum1);
_sum1 = _mm256_fmadd_ps(_k22, _r24, _sum1);
__m256 _sum2 = _bias0;
__m256 _r05 = _mm256_loadu_ps(r0 + 40);
__m256 _r15 = _mm256_loadu_ps(r1 + 40);
__m256 _r25 = _mm256_loadu_ps(r2 + 40);
__m256 _r06 = _mm256_loadu_ps(r0 + 48);
__m256 _r16 = _mm256_loadu_ps(r1 + 48);
__m256 _r26 = _mm256_loadu_ps(r2 + 48);
_mm256_storeu_ps(outptr0 + 8, _sum1);
_sum2 = _mm256_fmadd_ps(_k00, _r04, _sum2);
_sum2 = _mm256_fmadd_ps(_k01, _r05, _sum2);
_sum2 = _mm256_fmadd_ps(_k02, _r06, _sum2);
_sum2 = _mm256_fmadd_ps(_k10, _r14, _sum2);
_sum2 = _mm256_fmadd_ps(_k11, _r15, _sum2);
_sum2 = _mm256_fmadd_ps(_k12, _r16, _sum2);
_sum2 = _mm256_fmadd_ps(_k20, _r24, _sum2);
_sum2 = _mm256_fmadd_ps(_k21, _r25, _sum2);
_sum2 = _mm256_fmadd_ps(_k22, _r26, _sum2);
__m256 _sum3 = _bias0;
__m256 _r07 = _mm256_loadu_ps(r0 + 56);
__m256 _r17 = _mm256_loadu_ps(r1 + 56);
__m256 _r27 = _mm256_loadu_ps(r2 + 56);
__m256 _r08 = _mm256_loadu_ps(r0 + 64);
__m256 _r18 = _mm256_loadu_ps(r1 + 64);
__m256 _r28 = _mm256_loadu_ps(r2 + 64);
_mm256_storeu_ps(outptr0 + 16, _sum2);
_sum3 = _mm256_fmadd_ps(_k00, _r06, _sum3);
_sum3 = _mm256_fmadd_ps(_k01, _r07, _sum3);
_sum3 = _mm256_fmadd_ps(_k02, _r08, _sum3);
_sum3 = _mm256_fmadd_ps(_k10, _r16, _sum3);
_sum3 = _mm256_fmadd_ps(_k11, _r17, _sum3);
_sum3 = _mm256_fmadd_ps(_k12, _r18, _sum3);
_sum3 = _mm256_fmadd_ps(_k20, _r26, _sum3);
_sum3 = _mm256_fmadd_ps(_k21, _r27, _sum3);
_sum3 = _mm256_fmadd_ps(_k22, _r28, _sum3);
_mm256_storeu_ps(outptr0 + 24, _sum3);
r0 += 2 * 32;
r1 += 2 * 32;
r2 += 2 * 32;
outptr0 += 32;
}
for (; j + 1 < outw; j += 2)
{
__m256 _sum0 = _bias0;
__m256 _r00 = _mm256_loadu_ps(r0);
__m256 _r01 = _mm256_loadu_ps(r0 + 8);
__m256 _r02 = _mm256_loadu_ps(r0 + 16);
__m256 _r10 = _mm256_loadu_ps(r1);
__m256 _r11 = _mm256_loadu_ps(r1 + 8);
__m256 _r12 = _mm256_loadu_ps(r1 + 16);
__m256 _r20 = _mm256_loadu_ps(r2);
__m256 _r21 = _mm256_loadu_ps(r2 + 8);
__m256 _r22 = _mm256_loadu_ps(r2 + 16);
_sum0 = _mm256_fmadd_ps(_k00, _r00, _sum0);
_sum0 = _mm256_fmadd_ps(_k01, _r01, _sum0);
_sum0 = _mm256_fmadd_ps(_k02, _r02, _sum0);
_sum0 = _mm256_fmadd_ps(_k10, _r10, _sum0);
_sum0 = _mm256_fmadd_ps(_k11, _r11, _sum0);
_sum0 = _mm256_fmadd_ps(_k12, _r12, _sum0);
_sum0 = _mm256_fmadd_ps(_k20, _r20, _sum0);
_sum0 = _mm256_fmadd_ps(_k21, _r21, _sum0);
_sum0 = _mm256_fmadd_ps(_k22, _r22, _sum0);
__m256 _sum1 = _bias0;
__m256 _r03 = _mm256_loadu_ps(r0 + 24);
__m256 _r13 = _mm256_loadu_ps(r1 + 24);
__m256 _r23 = _mm256_loadu_ps(r2 + 24);
__m256 _r04 = _mm256_loadu_ps(r0 + 32);
__m256 _r14 = _mm256_loadu_ps(r1 + 32);
__m256 _r24 = _mm256_loadu_ps(r2 + 32);
_mm256_storeu_ps(outptr0, _sum0);
_sum1 = _mm256_fmadd_ps(_k00, _r02, _sum1);
_sum1 = _mm256_fmadd_ps(_k01, _r03, _sum1);
_sum1 = _mm256_fmadd_ps(_k02, _r04, _sum1);
_sum1 = _mm256_fmadd_ps(_k10, _r12, _sum1);
_sum1 = _mm256_fmadd_ps(_k11, _r13, _sum1);
_sum1 = _mm256_fmadd_ps(_k12, _r14, _sum1);
_sum1 = _mm256_fmadd_ps(_k20, _r22, _sum1);
_sum1 = _mm256_fmadd_ps(_k21, _r23, _sum1);
_sum1 = _mm256_fmadd_ps(_k22, _r24, _sum1);
_mm256_storeu_ps(outptr0 + 8, _sum1);
r0 += 2 * 16;
r1 += 2 * 16;
r2 += 2 * 16;
outptr0 += 16;
}
for (; j < outw; j++)
{
__m256 _sum0 = _bias0;
__m256 _r00 = _mm256_loadu_ps(r0);
__m256 _r01 = _mm256_loadu_ps(r0 + 8);
__m256 _r02 = _mm256_loadu_ps(r0 + 16);
__m256 _r10 = _mm256_loadu_ps(r1);
__m256 _r11 = _mm256_loadu_ps(r1 + 8);
__m256 _r12 = _mm256_loadu_ps(r1 + 16);
__m256 _r20 = _mm256_loadu_ps(r2);
__m256 _r21 = _mm256_loadu_ps(r2 + 8);
__m256 _r22 = _mm256_loadu_ps(r2 + 16);
_sum0 = _mm256_fmadd_ps(_k00, _r00, _sum0);
_sum0 = _mm256_fmadd_ps(_k01, _r01, _sum0);
_sum0 = _mm256_fmadd_ps(_k02, _r02, _sum0);
_sum0 = _mm256_fmadd_ps(_k10, _r10, _sum0);
_sum0 = _mm256_fmadd_ps(_k11, _r11, _sum0);
_sum0 = _mm256_fmadd_ps(_k12, _r12, _sum0);
_sum0 = _mm256_fmadd_ps(_k20, _r20, _sum0);
_sum0 = _mm256_fmadd_ps(_k21, _r21, _sum0);
_sum0 = _mm256_fmadd_ps(_k22, _r22, _sum0);
_mm256_storeu_ps(outptr0, _sum0);
r0 += 2 * 8;
r1 += 2 * 8;
r2 += 2 * 8;
outptr0 += 8;
}
r0 += tailstep;
r1 += tailstep;
r2 += tailstep;
}
}
}
|
matrice-mpi.c |
/**
* Matrix product with MPI/OpenMP
*
* <p>
* This execution is a hybrid parallel execution
* </p>
*
* @date 19/09/2020
* @author Jerome Dh
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <mpi.h>
#include <omp.h>
#include "matrice-mpi.h"
/**
* Fill matrix with the random values
*
* @param V - Matrix
* @param M - x lenght
* @param N - y lenght
*/
void matrix_fill(float V[][T2], int M, int N) {
for(int i=0; i<M; i++) {
for(int j=0; j<N; j++) {
V[i][j] = (rand() % 2) + 1;
}
}
}
/**
* Print matrix
*/
void matrix_print(float V[][T2], int M, int N) {
for(int i=0; i<M; i++) {
for(int j=0; j<N; j++) {
printf("%.2lf, ", V[i][j]);
}
}
printf("\n");
}
int main(int argc, char** argv) {
srand(time(NULL));
int rank, size, TAG = 200;
MPI_Status status;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
float A[T1][T2];
float B[T1][T2];
float C[T1][T2];
FILE *file_result = fopen(RESULT_FILENAME, "a");
if(file_result == NULL){
exit(EXIT_FAILURE);
}
// Processor clock time
clock_t t1 = clock();
printf("Processus MPI %d/%d..\n", rank+1, size);
// Init all variables and then send to all others processes
if(rank == 0)
{
// Fill the matrixes
matrix_fill(A, T1, T2);
matrix_fill(B, T1, T2);
// Send to all others process
for(int j = 1; j < size; j++)
{
MPI_Send(A, T1 * T2, MPI_FLOAT, j, TAG, MPI_COMM_WORLD);
MPI_Send(B, T1 * T2, MPI_FLOAT, j, TAG + 1, MPI_COMM_WORLD);
}
}
else
{
// Receive from master
MPI_Recv(A, T1 * T2, MPI_FLOAT, 0, TAG, MPI_COMM_WORLD, &status);
MPI_Recv(B, T1 * T2, MPI_FLOAT, 0, TAG + 1, MPI_COMM_WORLD, &status);
}
// Product of A * B
int i, j;
#pragma omp parallel for
for(i = rank * T1/size; i < (rank+1) * T1/size; i++)
{
for(j = 0; j<T2; j++) {
C[i][j] = 0;
for(int k=0; k<T2; k++) {
C[i][j] = C[i][j] + (A[i][k] * B[k][j]);
}
// printf("C[%d][%d]=%.2f, ", i, j, C[i][j]);
fprintf(file_result, "C[%d,%d]=%.2f\n", i, j, C[i][j]);
}
}
MPI_Barrier(MPI_COMM_WORLD);
// End of computing
if(rank == 0)
{
clock_t t2 = clock();
double diff_clock = ((double)t2 - (double)t1) / CLOCKS_PER_SEC;
printf("Fin de calcul !\nTemps Processeur ecoule: %lf sec\n", diff_clock);
// Write in file
FILE *file_out = fopen(OUT_FILENAME, "w");
if(file_result == NULL){
exit(EXIT_FAILURE);
}
fprintf(file_out, "%.5lf", diff_clock);
fclose(file_out);
}
MPI_Finalize();
return EXIT_SUCCESS;
} |
ompcompress.c | #ifdef _OPENMP
#if defined(WITH_IPP)
/*
* This source code file was modified with Intel(R) Integrated Performance Primitives library content
*/
#endif
/* compress 1d contiguous array in parallel */
static void
_t2(compress_omp, Scalar, 1)(zfp_stream* stream, const zfp_field* field)
{
/* array metadata */
const Scalar* data = (const Scalar*)field->data;
uint nx = field->nx;
/* number of omp threads, blocks, and chunks */
uint threads = thread_count_omp(stream);
uint blocks = (nx + 3) / 4;
uint chunks = chunk_count_omp(stream, blocks, threads);
/* allocate per-thread streams */
bitstream** bs = compress_init_par(stream, field, chunks, blocks);
if (!bs)
return;
/* compress chunks of blocks in parallel */
int chunk;
#pragma omp parallel for num_threads(threads)
for (chunk = 0; chunk < (int)chunks; chunk++) {
/* determine range of block indices assigned to this thread */
uint bmin = chunk_offset(blocks, chunks, chunk + 0);
uint bmax = chunk_offset(blocks, chunks, chunk + 1);
uint block;
/* set up thread-local bit stream */
zfp_stream s = *stream;
zfp_stream_set_bit_stream(&s, bs[chunk]);
/* compress sequence of blocks */
for (block = bmin; block < bmax; block++) {
/* determine block origin x within array */
const Scalar* p = data;
uint x = 4 * block;
p += x;
/* compress partial or full block */
if (nx - x < 4)
_t2(zfp_encode_partial_block_strided, Scalar, 1)(&s, p, MIN(nx - x, 4u), 1);
else
_t2(zfp_encode_block, Scalar, 1)(&s, p);
}
}
/* concatenate per-thread streams */
compress_finish_par(stream, bs, chunks);
}
/* compress 1d strided array in parallel */
static void
_t2(compress_strided_omp, Scalar, 1)(zfp_stream* stream, const zfp_field* field)
{
/* array metadata */
const Scalar* data = (const Scalar*)field->data;
uint nx = field->nx;
int sx = field->sx ? field->sx : 1;
/* number of omp threads, blocks, and chunks */
uint threads = thread_count_omp(stream);
uint blocks = (nx + 3) / 4;
uint chunks = chunk_count_omp(stream, blocks, threads);
/* allocate per-thread streams */
bitstream** bs = compress_init_par(stream, field, chunks, blocks);
if (!bs)
return;
/* compress chunks of blocks in parallel */
int chunk;
#pragma omp parallel for num_threads(threads)
for (chunk = 0; chunk < (int)chunks; chunk++) {
/* determine range of block indices assigned to this thread */
uint bmin = chunk_offset(blocks, chunks, chunk + 0);
uint bmax = chunk_offset(blocks, chunks, chunk + 1);
uint block;
/* set up thread-local bit stream */
zfp_stream s = *stream;
zfp_stream_set_bit_stream(&s, bs[chunk]);
/* compress sequence of blocks */
for (block = bmin; block < bmax; block++) {
/* determine block origin x within array */
const Scalar* p = data;
uint x = 4 * block;
p += sx * (ptrdiff_t)x;
/* compress partial or full block */
if (nx - x < 4)
_t2(zfp_encode_partial_block_strided, Scalar, 1)(&s, p, MIN(nx - x, 4u), sx);
else
_t2(zfp_encode_block_strided, Scalar, 1)(&s, p, sx);
}
}
/* concatenate per-thread streams */
compress_finish_par(stream, bs, chunks);
}
/* compress 2d strided array in parallel */
static void
_t2(compress_strided_omp, Scalar, 2)(zfp_stream* stream, const zfp_field* field)
{
/* array metadata */
const Scalar* data = (const Scalar*)field->data;
uint nx = field->nx;
uint ny = field->ny;
int sx = field->sx ? field->sx : 1;
int sy = field->sy ? field->sy : (int)nx;
/* number of omp threads, blocks, and chunks */
uint threads = thread_count_omp(stream);
uint bx = (nx + 3) / 4;
uint by = (ny + 3) / 4;
uint blocks = bx * by;
uint chunks = chunk_count_omp(stream, blocks, threads);
/* allocate per-thread streams */
bitstream** bs = compress_init_par(stream, field, chunks, blocks);
if (!bs)
return;
/* compress chunks of blocks in parallel */
int chunk;
#pragma omp parallel for num_threads(threads)
for (chunk = 0; chunk < (int)chunks; chunk++) {
/* determine range of block indices assigned to this thread */
uint bmin = chunk_offset(blocks, chunks, chunk + 0);
uint bmax = chunk_offset(blocks, chunks, chunk + 1);
uint block;
/* set up thread-local bit stream */
zfp_stream s = *stream;
zfp_stream_set_bit_stream(&s, bs[chunk]);
/* compress sequence of blocks */
for (block = bmin; block < bmax; block++) {
/* determine block origin (x, y) within array */
const Scalar* p = data;
uint b = block;
uint x, y;
x = 4 * (b % bx); b /= bx;
y = 4 * b;
p += sx * (ptrdiff_t)x + sy * (ptrdiff_t)y;
/* compress partial or full block */
if (nx - x < 4 || ny - y < 4)
_t2(zfp_encode_partial_block_strided, Scalar, 2)(&s, p, MIN(nx - x, 4u), MIN(ny - y, 4u), sx, sy);
else
_t2(zfp_encode_block_strided, Scalar, 2)(&s, p, sx, sy);
}
}
/* concatenate per-thread streams */
compress_finish_par(stream, bs, chunks);
}
#if defined(IPP_OPTIMIZATION_ENABLED) && !defined(_SET_TMP_BLOCK_FROM_)
#define _SET_TMP_BLOCK_FROM_
static void CopyFromPartialBlock(const Ipp32f *pSrc, int stepY, int stepZ, int sizeX, int sizeY, int sizeZ, Ipp32f *pTmpBlock)
{
Ipp32f *pTmp;
int x, y, z, serIdx;
int copyX, copyY, copyZ;
for (serIdx = z = 0; z < 4; z++) {
copyZ = (z < sizeZ) ? z : sizeZ - 1;
for (y = 0; y < 4; y++) {
copyY = (y < sizeY) ? y : sizeY - 1;
pTmp = (Ipp32f*)pSrc + copyZ * stepZ + copyY * stepY;
for (x = 0; x < 4; x++) {
copyX = (x < sizeX) ? x : sizeX - 1;
pTmpBlock[serIdx++] = pTmp[copyX];
}
}
}
}
#endif
/* compress 3d strided array in parallel */
static void
_t2(compress_strided_omp, Scalar, 3)(zfp_stream* stream, const zfp_field* field)
{
/* array metadata */
const Scalar* data = (const Scalar*)field->data;
uint nx = field->nx;
uint ny = field->ny;
uint nz = field->nz;
int sx = field->sx ? field->sx : 1;
int sy = field->sy ? field->sy : (int)nx;
int sz = field->sz ? field->sz : (int)(nx * ny);
/* number of omp threads, blocks, and chunks */
uint threads = thread_count_omp(stream);
uint bx = (nx + 3) / 4;
uint by = (ny + 3) / 4;
uint bz = (nz + 3) / 4;
uint blocks = bx * by * bz;
uint chunks = chunk_count_omp(stream, blocks, threads);
/* allocate per-thread streams */
bitstream** bs = compress_init_par(stream, field, chunks, blocks);
#if defined (IPP_OPTIMIZATION_ENABLED)
IppEncodeZfpState_32f* pStates = NULL;
Ipp64u* chunk_bit_lengths = (Ipp64u*)malloc(sizeof(Ipp64u)* chunks);
int srcBlockLineStep = nx * sizeof(Ipp32f);
int srcBlockPlaneStep = ny * srcBlockLineStep;
uint min_bits, max_bits, max_prec;
int min_exp;
int sizeState = 0;
if (!(REVERSIBLE(stream)))
{
zfp_stream_params(stream, &min_bits, &max_bits, &max_prec, &min_exp);
ippsEncodeZfpGetStateSize_32f(&sizeState);
pStates = (IppEncodeZfpState_32f*)ippsMalloc_8u(sizeState * threads);
}
#endif
/* compress chunks of blocks in parallel */
int chunk;
#if !defined (IPP_OPTIMIZATION_ENABLED)
#pragma omp parallel for num_threads(threads)
#else
#pragma omp parallel \
num_threads(threads)
{
bitstream *pBitStream = NULL;
IppEncodeZfpState_32f* pState = NULL;
Ipp32f pTmpBlock[64];
if (!(REVERSIBLE(stream)))
{
pState = (IppEncodeZfpState_32f*)((Ipp8u*)pStates + omp_get_thread_num() * sizeState);
}
#pragma omp for
#endif
for (chunk = 0; chunk < (int)chunks; chunk++) {
/* determine range of block indices assigned to this thread */
uint bmin = chunk_offset(blocks, chunks, chunk + 0);
uint bmax = chunk_offset(blocks, chunks, chunk + 1);
uint block;
/* set up thread-local bit stream */
zfp_stream s = *stream;
zfp_stream_set_bit_stream(&s, bs[chunk]);
#if defined (IPP_OPTIMIZATION_ENABLED)
if (!(REVERSIBLE(stream)))
{
pBitStream = bs[chunk];
ippsEncodeZfpInitLong_32f((Ipp8u*)stream_data(pBitStream), stream_capacity(pBitStream), pState);
ippsEncodeZfpSet_32f(min_bits, max_bits, max_prec, min_exp, pState);
}
#endif
/* compress sequence of blocks */
for (block = bmin; block < bmax; block++) {
/* determine block origin (x, y, z) within array */
const Scalar* p = data;
uint b = block;
uint x, y, z;
x = 4 * (b % bx); b /= bx;
y = 4 * (b % by); b /= by;
z = 4 * b;
p += sx * (ptrdiff_t)x + sy * (ptrdiff_t)y + sz * (ptrdiff_t)z;
/* compress partial or full block */
if (nx - x < 4 || ny - y < 4 || nz - z < 4)
{
#if !defined(IPP_OPTIMIZATION_ENABLED)
_t2(zfp_encode_partial_block_strided, Scalar, 3)(&s, p, MIN(nx - x, 4u), MIN(ny - y, 4u), MIN(nz - z, 4u), sx, sy, sz);
#else
if (!(REVERSIBLE(stream)))
{
CopyFromPartialBlock((const Ipp32f *)p, sy, sz, MIN(nx - x, 4u), MIN(ny - y, 4u), MIN(nz - z, 4u), pTmpBlock);
ippsEncodeZfp444_32f(pTmpBlock, 4 * sizeof(Ipp32f), 4 * 4 * sizeof(Ipp32f), pState);
}
else
{
_t2(zfp_encode_partial_block_strided, Scalar, 3)(&s, p, MIN(nx - x, 4u), MIN(ny - y, 4u), MIN(nz - z, 4u), sx, sy, sz);
}
#endif
}
else
{
#if !defined(IPP_OPTIMIZATION_ENABLED)
_t2(zfp_encode_block_strided, Scalar, 3)(&s, p, sx, sy, sz);
#else
if (!(REVERSIBLE(stream)))
{
ippsEncodeZfp444_32f((const Ipp32f *)p, srcBlockLineStep, srcBlockPlaneStep, pState);
}
else
{
_t2(zfp_encode_block_strided, Scalar, 3)(&s, p, sx, sy, sz);
}
#endif
}
}
#if defined (IPP_OPTIMIZATION_ENABLED)
if (!(REVERSIBLE(stream)) && pState != NULL)
{
Ipp64u chunk_compr_length;
ippsEncodeZfpGetCompressedBitSize_32f(pState, &chunk_bit_lengths[chunk]);
ippsEncodeZfpFlush_32f(pState);
chunk_compr_length = (size_t)((chunk_bit_lengths[chunk] + 7) >> 3);
stream_set_eos(pBitStream, chunk_compr_length);
}
#endif
}
#if defined (IPP_OPTIMIZATION_ENABLED)
}//The end of pragma omp parallel block
/* concatenate per-thread streams */
if (!(REVERSIBLE(stream)) && pStates != NULL)
{
compress_finish_par_opt(stream, bs, chunks, chunk_bit_lengths);
free(chunk_bit_lengths);
ippsFree(pStates);
return;
}
#endif
compress_finish_par(stream, bs, chunks);
}
/* compress 4d strided array in parallel */
static void
_t2(compress_strided_omp, Scalar, 4)(zfp_stream* stream, const zfp_field* field)
{
/* array metadata */
const Scalar* data = field->data;
uint nx = field->nx;
uint ny = field->ny;
uint nz = field->nz;
uint nw = field->nw;
int sx = field->sx ? field->sx : 1;
int sy = field->sy ? field->sy : (int)nx;
int sz = field->sz ? field->sz : (int)(nx * ny);
int sw = field->sw ? field->sw : (int)(nx * ny * nz);
/* number of omp threads, blocks, and chunks */
uint threads = thread_count_omp(stream);
uint bx = (nx + 3) / 4;
uint by = (ny + 3) / 4;
uint bz = (nz + 3) / 4;
uint bw = (nw + 3) / 4;
uint blocks = bx * by * bz * bw;
uint chunks = chunk_count_omp(stream, blocks, threads);
/* allocate per-thread streams */
bitstream** bs = compress_init_par(stream, field, chunks, blocks);
if (!bs)
return;
/* compress chunks of blocks in parallel */
int chunk;
#pragma omp parallel for num_threads(threads)
for (chunk = 0; chunk < (int)chunks; chunk++) {
/* determine range of block indices assigned to this thread */
uint bmin = chunk_offset(blocks, chunks, chunk + 0);
uint bmax = chunk_offset(blocks, chunks, chunk + 1);
uint block;
/* set up thread-local bit stream */
zfp_stream s = *stream;
zfp_stream_set_bit_stream(&s, bs[chunk]);
/* compress sequence of blocks */
for (block = bmin; block < bmax; block++) {
/* determine block origin (x, y, z, w) within array */
const Scalar* p = data;
uint b = block;
uint x, y, z, w;
x = 4 * (b % bx); b /= bx;
y = 4 * (b % by); b /= by;
z = 4 * (b % bz); b /= bz;
w = 4 * b;
p += sx * (ptrdiff_t)x + sy * (ptrdiff_t)y + sz * (ptrdiff_t)z + sw * (ptrdiff_t)w;
/* compress partial or full block */
if (nx - x < 4 || ny - y < 4 || nz - z < 4 || nw - w < 4)
_t2(zfp_encode_partial_block_strided, Scalar, 4)(&s, p, MIN(nx - x, 4u), MIN(ny - y, 4u), MIN(nz - z, 4u), MIN(nw - w, 4u), sx, sy, sz, sw);
else
_t2(zfp_encode_block_strided, Scalar, 4)(&s, p, sx, sy, sz, sw);
}
}
/* concatenate per-thread streams */
compress_finish_par(stream, bs, chunks);
}
#endif
|
fourier.c | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% FFFFF OOO U U RRRR IIIII EEEEE RRRR %
% F O O U U R R I E R R %
% FFF O O U U RRRR I EEE RRRR %
% F O O U U R R I E R R %
% F OOO UUU R R IIIII EEEEE R R %
% %
% %
% MagickCore Discrete Fourier Transform Methods %
% %
% Software Design %
% Sean Burke %
% Fred Weinhaus %
% Cristy %
% July 2009 %
% %
% %
% Copyright 1999-2020 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://imagemagick.org/script/license.php %
% %
% 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 declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/artifact.h"
#include "MagickCore/attribute.h"
#include "MagickCore/blob.h"
#include "MagickCore/cache.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/fourier.h"
#include "MagickCore/log.h"
#include "MagickCore/memory_.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/pixel-private.h"
#include "MagickCore/property.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/resource_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/thread-private.h"
#if defined(MAGICKCORE_FFTW_DELEGATE)
#if defined(MAGICKCORE_HAVE_COMPLEX_H)
#include <complex.h>
#endif
#include <fftw3.h>
#if !defined(MAGICKCORE_HAVE_CABS)
#define cabs(z) (sqrt(z[0]*z[0]+z[1]*z[1]))
#endif
#if !defined(MAGICKCORE_HAVE_CARG)
#define carg(z) (atan2(cimag(z),creal(z)))
#endif
#if !defined(MAGICKCORE_HAVE_CIMAG)
#define cimag(z) (z[1])
#endif
#if !defined(MAGICKCORE_HAVE_CREAL)
#define creal(z) (z[0])
#endif
#endif
/*
Typedef declarations.
*/
typedef struct _FourierInfo
{
PixelChannel
channel;
MagickBooleanType
modulus;
size_t
width,
height;
ssize_t
center;
} FourierInfo;
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C o m p l e x I m a g e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ComplexImages() performs complex mathematics on an image sequence.
%
% The format of the ComplexImages method is:
%
% MagickBooleanType ComplexImages(Image *images,const ComplexOperator op,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o op: A complex operator.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op,
ExceptionInfo *exception)
{
#define ComplexImageTag "Complex/Image"
CacheView
*Ai_view,
*Ar_view,
*Bi_view,
*Br_view,
*Ci_view,
*Cr_view;
const char
*artifact;
const Image
*Ai_image,
*Ar_image,
*Bi_image,
*Br_image;
double
snr;
Image
*Ci_image,
*complex_images,
*Cr_image,
*image;
MagickBooleanType
status;
MagickOffsetType
progress;
size_t
columns,
number_channels,
rows;
ssize_t
y;
assert(images != (Image *) NULL);
assert(images->signature == MagickCoreSignature);
if (images->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
if (images->next == (Image *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),ImageError,
"ImageSequenceRequired","`%s'",images->filename);
return((Image *) NULL);
}
image=CloneImage(images,0,0,MagickTrue,exception);
if (image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
{
image=DestroyImageList(image);
return(image);
}
image->depth=32UL;
complex_images=NewImageList();
AppendImageToList(&complex_images,image);
image=CloneImage(images->next,0,0,MagickTrue,exception);
if (image == (Image *) NULL)
{
complex_images=DestroyImageList(complex_images);
return(complex_images);
}
image->depth=32UL;
AppendImageToList(&complex_images,image);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
{
complex_images=DestroyImageList(complex_images);
return(complex_images);
}
/*
Apply complex mathematics to image pixels.
*/
artifact=GetImageArtifact(images,"complex:snr");
snr=0.0;
if (artifact != (const char *) NULL)
snr=StringToDouble(artifact,(char **) NULL);
Ar_image=images;
Ai_image=images->next;
Br_image=images;
Bi_image=images->next;
if ((images->next->next != (Image *) NULL) &&
(images->next->next->next != (Image *) NULL))
{
Br_image=images->next->next;
Bi_image=images->next->next->next;
}
Cr_image=complex_images;
Ci_image=complex_images->next;
number_channels=MagickMin(MagickMin(MagickMin(
Ar_image->number_channels,Ai_image->number_channels),MagickMin(
Br_image->number_channels,Bi_image->number_channels)),MagickMin(
Cr_image->number_channels,Ci_image->number_channels));
Ar_view=AcquireVirtualCacheView(Ar_image,exception);
Ai_view=AcquireVirtualCacheView(Ai_image,exception);
Br_view=AcquireVirtualCacheView(Br_image,exception);
Bi_view=AcquireVirtualCacheView(Bi_image,exception);
Cr_view=AcquireAuthenticCacheView(Cr_image,exception);
Ci_view=AcquireAuthenticCacheView(Ci_image,exception);
status=MagickTrue;
progress=0;
columns=MagickMin(Cr_image->columns,Ci_image->columns);
rows=MagickMin(Cr_image->rows,Ci_image->rows);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(Cr_image,complex_images,rows,1L)
#endif
for (y=0; y < (ssize_t) rows; y++)
{
register const Quantum
*magick_restrict Ai,
*magick_restrict Ar,
*magick_restrict Bi,
*magick_restrict Br;
register Quantum
*magick_restrict Ci,
*magick_restrict Cr;
register ssize_t
x;
if (status == MagickFalse)
continue;
Ar=GetCacheViewVirtualPixels(Ar_view,0,y,columns,1,exception);
Ai=GetCacheViewVirtualPixels(Ai_view,0,y,columns,1,exception);
Br=GetCacheViewVirtualPixels(Br_view,0,y,columns,1,exception);
Bi=GetCacheViewVirtualPixels(Bi_view,0,y,columns,1,exception);
Cr=QueueCacheViewAuthenticPixels(Cr_view,0,y,columns,1,exception);
Ci=QueueCacheViewAuthenticPixels(Ci_view,0,y,columns,1,exception);
if ((Ar == (const Quantum *) NULL) || (Ai == (const Quantum *) NULL) ||
(Br == (const Quantum *) NULL) || (Bi == (const Quantum *) NULL) ||
(Cr == (Quantum *) NULL) || (Ci == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) columns; x++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) number_channels; i++)
{
switch (op)
{
case AddComplexOperator:
{
Cr[i]=Ar[i]+Br[i];
Ci[i]=Ai[i]+Bi[i];
break;
}
case ConjugateComplexOperator:
default:
{
Cr[i]=Ar[i];
Ci[i]=(-Bi[i]);
break;
}
case DivideComplexOperator:
{
double
gamma;
gamma=QuantumRange*PerceptibleReciprocal(QuantumScale*Br[i]*Br[i]+
QuantumScale*Bi[i]*Bi[i]+snr);
Cr[i]=gamma*(QuantumScale*Ar[i]*Br[i]+QuantumScale*Ai[i]*Bi[i]);
Ci[i]=gamma*(QuantumScale*Ai[i]*Br[i]-QuantumScale*Ar[i]*Bi[i]);
break;
}
case MagnitudePhaseComplexOperator:
{
Cr[i]=sqrt(QuantumScale*Ar[i]*Ar[i]+QuantumScale*Ai[i]*Ai[i]);
Ci[i]=atan2((double) Ai[i],(double) Ar[i])/(2.0*MagickPI)+0.5;
break;
}
case MultiplyComplexOperator:
{
Cr[i]=(QuantumScale*Ar[i]*Br[i]-QuantumScale*Ai[i]*Bi[i]);
Ci[i]=(QuantumScale*Ai[i]*Br[i]+QuantumScale*Ar[i]*Bi[i]);
break;
}
case RealImaginaryComplexOperator:
{
Cr[i]=Ar[i]*cos(2.0*MagickPI*(Ai[i]-0.5));
Ci[i]=Ar[i]*sin(2.0*MagickPI*(Ai[i]-0.5));
break;
}
case SubtractComplexOperator:
{
Cr[i]=Ar[i]-Br[i];
Ci[i]=Ai[i]-Bi[i];
break;
}
}
}
Ar+=GetPixelChannels(Ar_image);
Ai+=GetPixelChannels(Ai_image);
Br+=GetPixelChannels(Br_image);
Bi+=GetPixelChannels(Bi_image);
Cr+=GetPixelChannels(Cr_image);
Ci+=GetPixelChannels(Ci_image);
}
if (SyncCacheViewAuthenticPixels(Ci_view,exception) == MagickFalse)
status=MagickFalse;
if (SyncCacheViewAuthenticPixels(Cr_view,exception) == MagickFalse)
status=MagickFalse;
if (images->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(images,ComplexImageTag,progress,images->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
Cr_view=DestroyCacheView(Cr_view);
Ci_view=DestroyCacheView(Ci_view);
Br_view=DestroyCacheView(Br_view);
Bi_view=DestroyCacheView(Bi_view);
Ar_view=DestroyCacheView(Ar_view);
Ai_view=DestroyCacheView(Ai_view);
if (status == MagickFalse)
complex_images=DestroyImageList(complex_images);
return(complex_images);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% F o r w a r d F o u r i e r T r a n s f o r m I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ForwardFourierTransformImage() implements the discrete Fourier transform
% (DFT) of the image either as a magnitude / phase or real / imaginary image
% pair.
%
% The format of the ForwadFourierTransformImage method is:
%
% Image *ForwardFourierTransformImage(const Image *image,
% const MagickBooleanType modulus,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o modulus: if true, return as transform as a magnitude / phase pair
% otherwise a real / imaginary image pair.
%
% o exception: return any errors or warnings in this structure.
%
*/
#if defined(MAGICKCORE_FFTW_DELEGATE)
static MagickBooleanType RollFourier(const size_t width,const size_t height,
const ssize_t x_offset,const ssize_t y_offset,double *roll_pixels)
{
double
*source_pixels;
MemoryInfo
*source_info;
register ssize_t
i,
x;
ssize_t
u,
v,
y;
/*
Move zero frequency (DC, average color) from (0,0) to (width/2,height/2).
*/
source_info=AcquireVirtualMemory(width,height*sizeof(*source_pixels));
if (source_info == (MemoryInfo *) NULL)
return(MagickFalse);
source_pixels=(double *) GetVirtualMemoryBlob(source_info);
i=0L;
for (y=0L; y < (ssize_t) height; y++)
{
if (y_offset < 0L)
v=((y+y_offset) < 0L) ? y+y_offset+(ssize_t) height : y+y_offset;
else
v=((y+y_offset) > ((ssize_t) height-1L)) ? y+y_offset-(ssize_t) height :
y+y_offset;
for (x=0L; x < (ssize_t) width; x++)
{
if (x_offset < 0L)
u=((x+x_offset) < 0L) ? x+x_offset+(ssize_t) width : x+x_offset;
else
u=((x+x_offset) > ((ssize_t) width-1L)) ? x+x_offset-(ssize_t) width :
x+x_offset;
source_pixels[v*width+u]=roll_pixels[i++];
}
}
(void) memcpy(roll_pixels,source_pixels,height*width*
sizeof(*source_pixels));
source_info=RelinquishVirtualMemory(source_info);
return(MagickTrue);
}
static MagickBooleanType ForwardQuadrantSwap(const size_t width,
const size_t height,double *source_pixels,double *forward_pixels)
{
MagickBooleanType
status;
register ssize_t
x;
ssize_t
center,
y;
/*
Swap quadrants.
*/
center=(ssize_t) (width/2L)+1L;
status=RollFourier((size_t) center,height,0L,(ssize_t) height/2L,
source_pixels);
if (status == MagickFalse)
return(MagickFalse);
for (y=0L; y < (ssize_t) height; y++)
for (x=0L; x < (ssize_t) (width/2L); x++)
forward_pixels[y*width+x+width/2L]=source_pixels[y*center+x];
for (y=1; y < (ssize_t) height; y++)
for (x=0L; x < (ssize_t) (width/2L); x++)
forward_pixels[(height-y)*width+width/2L-x-1L]=
source_pixels[y*center+x+1L];
for (x=0L; x < (ssize_t) (width/2L); x++)
forward_pixels[width/2L-x-1L]=source_pixels[x+1L];
return(MagickTrue);
}
static void CorrectPhaseLHS(const size_t width,const size_t height,
double *fourier_pixels)
{
register ssize_t
x;
ssize_t
y;
for (y=0L; y < (ssize_t) height; y++)
for (x=0L; x < (ssize_t) (width/2L); x++)
fourier_pixels[y*width+x]*=(-1.0);
}
static MagickBooleanType ForwardFourier(const FourierInfo *fourier_info,
Image *image,double *magnitude,double *phase,ExceptionInfo *exception)
{
CacheView
*magnitude_view,
*phase_view;
double
*magnitude_pixels,
*phase_pixels;
Image
*magnitude_image,
*phase_image;
MagickBooleanType
status;
MemoryInfo
*magnitude_info,
*phase_info;
register Quantum
*q;
register ssize_t
x;
ssize_t
i,
y;
magnitude_image=GetFirstImageInList(image);
phase_image=GetNextImageInList(image);
if (phase_image == (Image *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),ImageError,
"ImageSequenceRequired","`%s'",image->filename);
return(MagickFalse);
}
/*
Create "Fourier Transform" image from constituent arrays.
*/
magnitude_info=AcquireVirtualMemory((size_t) fourier_info->width,
fourier_info->height*sizeof(*magnitude_pixels));
phase_info=AcquireVirtualMemory((size_t) fourier_info->width,
fourier_info->height*sizeof(*phase_pixels));
if ((magnitude_info == (MemoryInfo *) NULL) ||
(phase_info == (MemoryInfo *) NULL))
{
if (phase_info != (MemoryInfo *) NULL)
phase_info=RelinquishVirtualMemory(phase_info);
if (magnitude_info != (MemoryInfo *) NULL)
magnitude_info=RelinquishVirtualMemory(magnitude_info);
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(MagickFalse);
}
magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info);
(void) memset(magnitude_pixels,0,fourier_info->width*
fourier_info->height*sizeof(*magnitude_pixels));
phase_pixels=(double *) GetVirtualMemoryBlob(phase_info);
(void) memset(phase_pixels,0,fourier_info->width*
fourier_info->height*sizeof(*phase_pixels));
status=ForwardQuadrantSwap(fourier_info->width,fourier_info->height,
magnitude,magnitude_pixels);
if (status != MagickFalse)
status=ForwardQuadrantSwap(fourier_info->width,fourier_info->height,phase,
phase_pixels);
CorrectPhaseLHS(fourier_info->width,fourier_info->height,phase_pixels);
if (fourier_info->modulus != MagickFalse)
{
i=0L;
for (y=0L; y < (ssize_t) fourier_info->height; y++)
for (x=0L; x < (ssize_t) fourier_info->width; x++)
{
phase_pixels[i]/=(2.0*MagickPI);
phase_pixels[i]+=0.5;
i++;
}
}
magnitude_view=AcquireAuthenticCacheView(magnitude_image,exception);
i=0L;
for (y=0L; y < (ssize_t) fourier_info->height; y++)
{
q=GetCacheViewAuthenticPixels(magnitude_view,0L,y,fourier_info->width,1UL,
exception);
if (q == (Quantum *) NULL)
break;
for (x=0L; x < (ssize_t) fourier_info->width; x++)
{
switch (fourier_info->channel)
{
case RedPixelChannel:
default:
{
SetPixelRed(magnitude_image,ClampToQuantum(QuantumRange*
magnitude_pixels[i]),q);
break;
}
case GreenPixelChannel:
{
SetPixelGreen(magnitude_image,ClampToQuantum(QuantumRange*
magnitude_pixels[i]),q);
break;
}
case BluePixelChannel:
{
SetPixelBlue(magnitude_image,ClampToQuantum(QuantumRange*
magnitude_pixels[i]),q);
break;
}
case BlackPixelChannel:
{
SetPixelBlack(magnitude_image,ClampToQuantum(QuantumRange*
magnitude_pixels[i]),q);
break;
}
case AlphaPixelChannel:
{
SetPixelAlpha(magnitude_image,ClampToQuantum(QuantumRange*
magnitude_pixels[i]),q);
break;
}
}
i++;
q+=GetPixelChannels(magnitude_image);
}
status=SyncCacheViewAuthenticPixels(magnitude_view,exception);
if (status == MagickFalse)
break;
}
magnitude_view=DestroyCacheView(magnitude_view);
i=0L;
phase_view=AcquireAuthenticCacheView(phase_image,exception);
for (y=0L; y < (ssize_t) fourier_info->height; y++)
{
q=GetCacheViewAuthenticPixels(phase_view,0L,y,fourier_info->width,1UL,
exception);
if (q == (Quantum *) NULL)
break;
for (x=0L; x < (ssize_t) fourier_info->width; x++)
{
switch (fourier_info->channel)
{
case RedPixelChannel:
default:
{
SetPixelRed(phase_image,ClampToQuantum(QuantumRange*
phase_pixels[i]),q);
break;
}
case GreenPixelChannel:
{
SetPixelGreen(phase_image,ClampToQuantum(QuantumRange*
phase_pixels[i]),q);
break;
}
case BluePixelChannel:
{
SetPixelBlue(phase_image,ClampToQuantum(QuantumRange*
phase_pixels[i]),q);
break;
}
case BlackPixelChannel:
{
SetPixelBlack(phase_image,ClampToQuantum(QuantumRange*
phase_pixels[i]),q);
break;
}
case AlphaPixelChannel:
{
SetPixelAlpha(phase_image,ClampToQuantum(QuantumRange*
phase_pixels[i]),q);
break;
}
}
i++;
q+=GetPixelChannels(phase_image);
}
status=SyncCacheViewAuthenticPixels(phase_view,exception);
if (status == MagickFalse)
break;
}
phase_view=DestroyCacheView(phase_view);
phase_info=RelinquishVirtualMemory(phase_info);
magnitude_info=RelinquishVirtualMemory(magnitude_info);
return(status);
}
static MagickBooleanType ForwardFourierTransform(FourierInfo *fourier_info,
const Image *image,double *magnitude_pixels,double *phase_pixels,
ExceptionInfo *exception)
{
CacheView
*image_view;
const char
*value;
double
*source_pixels;
fftw_complex
*forward_pixels;
fftw_plan
fftw_r2c_plan;
MemoryInfo
*forward_info,
*source_info;
register const Quantum
*p;
register ssize_t
i,
x;
ssize_t
y;
/*
Generate the forward Fourier transform.
*/
source_info=AcquireVirtualMemory((size_t) fourier_info->width,
fourier_info->height*sizeof(*source_pixels));
if (source_info == (MemoryInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(MagickFalse);
}
source_pixels=(double *) GetVirtualMemoryBlob(source_info);
memset(source_pixels,0,fourier_info->width*fourier_info->height*
sizeof(*source_pixels));
i=0L;
image_view=AcquireVirtualCacheView(image,exception);
for (y=0L; y < (ssize_t) fourier_info->height; y++)
{
p=GetCacheViewVirtualPixels(image_view,0L,y,fourier_info->width,1UL,
exception);
if (p == (const Quantum *) NULL)
break;
for (x=0L; x < (ssize_t) fourier_info->width; x++)
{
switch (fourier_info->channel)
{
case RedPixelChannel:
default:
{
source_pixels[i]=QuantumScale*GetPixelRed(image,p);
break;
}
case GreenPixelChannel:
{
source_pixels[i]=QuantumScale*GetPixelGreen(image,p);
break;
}
case BluePixelChannel:
{
source_pixels[i]=QuantumScale*GetPixelBlue(image,p);
break;
}
case BlackPixelChannel:
{
source_pixels[i]=QuantumScale*GetPixelBlack(image,p);
break;
}
case AlphaPixelChannel:
{
source_pixels[i]=QuantumScale*GetPixelAlpha(image,p);
break;
}
}
i++;
p+=GetPixelChannels(image);
}
}
image_view=DestroyCacheView(image_view);
forward_info=AcquireVirtualMemory((size_t) fourier_info->width,
(fourier_info->height/2+1)*sizeof(*forward_pixels));
if (forward_info == (MemoryInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
source_info=(MemoryInfo *) RelinquishVirtualMemory(source_info);
return(MagickFalse);
}
forward_pixels=(fftw_complex *) GetVirtualMemoryBlob(forward_info);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_ForwardFourierTransform)
#endif
fftw_r2c_plan=fftw_plan_dft_r2c_2d(fourier_info->width,fourier_info->height,
source_pixels,forward_pixels,FFTW_ESTIMATE);
fftw_execute_dft_r2c(fftw_r2c_plan,source_pixels,forward_pixels);
fftw_destroy_plan(fftw_r2c_plan);
source_info=(MemoryInfo *) RelinquishVirtualMemory(source_info);
value=GetImageArtifact(image,"fourier:normalize");
if (LocaleCompare(value,"forward") == 0)
{
double
gamma;
/*
Normalize forward transform.
*/
i=0L;
gamma=PerceptibleReciprocal((double) fourier_info->width*
fourier_info->height);
for (y=0L; y < (ssize_t) fourier_info->height; y++)
for (x=0L; x < (ssize_t) fourier_info->center; x++)
{
#if defined(MAGICKCORE_HAVE_COMPLEX_H)
forward_pixels[i]*=gamma;
#else
forward_pixels[i][0]*=gamma;
forward_pixels[i][1]*=gamma;
#endif
i++;
}
}
/*
Generate magnitude and phase (or real and imaginary).
*/
i=0L;
if (fourier_info->modulus != MagickFalse)
for (y=0L; y < (ssize_t) fourier_info->height; y++)
for (x=0L; x < (ssize_t) fourier_info->center; x++)
{
magnitude_pixels[i]=cabs(forward_pixels[i]);
phase_pixels[i]=carg(forward_pixels[i]);
i++;
}
else
for (y=0L; y < (ssize_t) fourier_info->height; y++)
for (x=0L; x < (ssize_t) fourier_info->center; x++)
{
magnitude_pixels[i]=creal(forward_pixels[i]);
phase_pixels[i]=cimag(forward_pixels[i]);
i++;
}
forward_info=(MemoryInfo *) RelinquishVirtualMemory(forward_info);
return(MagickTrue);
}
static MagickBooleanType ForwardFourierTransformChannel(const Image *image,
const PixelChannel channel,const MagickBooleanType modulus,
Image *fourier_image,ExceptionInfo *exception)
{
double
*magnitude_pixels,
*phase_pixels;
FourierInfo
fourier_info;
MagickBooleanType
status;
MemoryInfo
*magnitude_info,
*phase_info;
fourier_info.width=image->columns;
fourier_info.height=image->rows;
if ((image->columns != image->rows) || ((image->columns % 2) != 0) ||
((image->rows % 2) != 0))
{
size_t extent=image->columns < image->rows ? image->rows : image->columns;
fourier_info.width=(extent & 0x01) == 1 ? extent+1UL : extent;
}
fourier_info.height=fourier_info.width;
fourier_info.center=(ssize_t) (fourier_info.width/2L)+1L;
fourier_info.channel=channel;
fourier_info.modulus=modulus;
magnitude_info=AcquireVirtualMemory((size_t) fourier_info.width,
(fourier_info.height/2+1)*sizeof(*magnitude_pixels));
phase_info=AcquireVirtualMemory((size_t) fourier_info.width,
(fourier_info.height/2+1)*sizeof(*phase_pixels));
if ((magnitude_info == (MemoryInfo *) NULL) ||
(phase_info == (MemoryInfo *) NULL))
{
if (phase_info != (MemoryInfo *) NULL)
phase_info=RelinquishVirtualMemory(phase_info);
if (magnitude_info == (MemoryInfo *) NULL)
magnitude_info=RelinquishVirtualMemory(magnitude_info);
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(MagickFalse);
}
magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info);
phase_pixels=(double *) GetVirtualMemoryBlob(phase_info);
status=ForwardFourierTransform(&fourier_info,image,magnitude_pixels,
phase_pixels,exception);
if (status != MagickFalse)
status=ForwardFourier(&fourier_info,fourier_image,magnitude_pixels,
phase_pixels,exception);
phase_info=RelinquishVirtualMemory(phase_info);
magnitude_info=RelinquishVirtualMemory(magnitude_info);
return(status);
}
#endif
MagickExport Image *ForwardFourierTransformImage(const Image *image,
const MagickBooleanType modulus,ExceptionInfo *exception)
{
Image
*fourier_image;
fourier_image=NewImageList();
#if !defined(MAGICKCORE_FFTW_DELEGATE)
(void) modulus;
(void) ThrowMagickException(exception,GetMagickModule(),
MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn","`%s' (FFTW)",
image->filename);
#else
{
Image
*magnitude_image;
size_t
height,
width;
width=image->columns;
height=image->rows;
if ((image->columns != image->rows) || ((image->columns % 2) != 0) ||
((image->rows % 2) != 0))
{
size_t extent=image->columns < image->rows ? image->rows :
image->columns;
width=(extent & 0x01) == 1 ? extent+1UL : extent;
}
height=width;
magnitude_image=CloneImage(image,width,height,MagickTrue,exception);
if (magnitude_image != (Image *) NULL)
{
Image
*phase_image;
magnitude_image->storage_class=DirectClass;
magnitude_image->depth=32UL;
phase_image=CloneImage(image,width,height,MagickTrue,exception);
if (phase_image == (Image *) NULL)
magnitude_image=DestroyImage(magnitude_image);
else
{
MagickBooleanType
is_gray,
status;
phase_image->storage_class=DirectClass;
phase_image->depth=32UL;
AppendImageToList(&fourier_image,magnitude_image);
AppendImageToList(&fourier_image,phase_image);
status=MagickTrue;
is_gray=IsImageGray(image);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel sections
#endif
{
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp section
#endif
{
MagickBooleanType
thread_status;
if (is_gray != MagickFalse)
thread_status=ForwardFourierTransformChannel(image,
GrayPixelChannel,modulus,fourier_image,exception);
else
thread_status=ForwardFourierTransformChannel(image,
RedPixelChannel,modulus,fourier_image,exception);
if (thread_status == MagickFalse)
status=thread_status;
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp section
#endif
{
MagickBooleanType
thread_status;
thread_status=MagickTrue;
if (is_gray == MagickFalse)
thread_status=ForwardFourierTransformChannel(image,
GreenPixelChannel,modulus,fourier_image,exception);
if (thread_status == MagickFalse)
status=thread_status;
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp section
#endif
{
MagickBooleanType
thread_status;
thread_status=MagickTrue;
if (is_gray == MagickFalse)
thread_status=ForwardFourierTransformChannel(image,
BluePixelChannel,modulus,fourier_image,exception);
if (thread_status == MagickFalse)
status=thread_status;
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp section
#endif
{
MagickBooleanType
thread_status;
thread_status=MagickTrue;
if (image->colorspace == CMYKColorspace)
thread_status=ForwardFourierTransformChannel(image,
BlackPixelChannel,modulus,fourier_image,exception);
if (thread_status == MagickFalse)
status=thread_status;
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp section
#endif
{
MagickBooleanType
thread_status;
thread_status=MagickTrue;
if (image->alpha_trait != UndefinedPixelTrait)
thread_status=ForwardFourierTransformChannel(image,
AlphaPixelChannel,modulus,fourier_image,exception);
if (thread_status == MagickFalse)
status=thread_status;
}
}
if (status == MagickFalse)
fourier_image=DestroyImageList(fourier_image);
fftw_cleanup();
}
}
}
#endif
return(fourier_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I n v e r s e F o u r i e r T r a n s f o r m I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% InverseFourierTransformImage() implements the inverse discrete Fourier
% transform (DFT) of the image either as a magnitude / phase or real /
% imaginary image pair.
%
% The format of the InverseFourierTransformImage method is:
%
% Image *InverseFourierTransformImage(const Image *magnitude_image,
% const Image *phase_image,const MagickBooleanType modulus,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o magnitude_image: the magnitude or real image.
%
% o phase_image: the phase or imaginary image.
%
% o modulus: if true, return transform as a magnitude / phase pair
% otherwise a real / imaginary image pair.
%
% o exception: return any errors or warnings in this structure.
%
*/
#if defined(MAGICKCORE_FFTW_DELEGATE)
static MagickBooleanType InverseQuadrantSwap(const size_t width,
const size_t height,const double *source,double *destination)
{
register ssize_t
x;
ssize_t
center,
y;
/*
Swap quadrants.
*/
center=(ssize_t) (width/2L)+1L;
for (y=1L; y < (ssize_t) height; y++)
for (x=0L; x < (ssize_t) (width/2L+1L); x++)
destination[(height-y)*center-x+width/2L]=source[y*width+x];
for (y=0L; y < (ssize_t) height; y++)
destination[y*center]=source[y*width+width/2L];
for (x=0L; x < center; x++)
destination[x]=source[center-x-1L];
return(RollFourier(center,height,0L,(ssize_t) height/-2L,destination));
}
static MagickBooleanType InverseFourier(FourierInfo *fourier_info,
const Image *magnitude_image,const Image *phase_image,
fftw_complex *fourier_pixels,ExceptionInfo *exception)
{
CacheView
*magnitude_view,
*phase_view;
double
*inverse_pixels,
*magnitude_pixels,
*phase_pixels;
MagickBooleanType
status;
MemoryInfo
*inverse_info,
*magnitude_info,
*phase_info;
register const Quantum
*p;
register ssize_t
i,
x;
ssize_t
y;
/*
Inverse fourier - read image and break down into a double array.
*/
magnitude_info=AcquireVirtualMemory((size_t) fourier_info->width,
fourier_info->height*sizeof(*magnitude_pixels));
phase_info=AcquireVirtualMemory((size_t) fourier_info->width,
fourier_info->height*sizeof(*phase_pixels));
inverse_info=AcquireVirtualMemory((size_t) fourier_info->width,
(fourier_info->height/2+1)*sizeof(*inverse_pixels));
if ((magnitude_info == (MemoryInfo *) NULL) ||
(phase_info == (MemoryInfo *) NULL) ||
(inverse_info == (MemoryInfo *) NULL))
{
if (magnitude_info != (MemoryInfo *) NULL)
magnitude_info=RelinquishVirtualMemory(magnitude_info);
if (phase_info != (MemoryInfo *) NULL)
phase_info=RelinquishVirtualMemory(phase_info);
if (inverse_info != (MemoryInfo *) NULL)
inverse_info=RelinquishVirtualMemory(inverse_info);
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",
magnitude_image->filename);
return(MagickFalse);
}
magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info);
phase_pixels=(double *) GetVirtualMemoryBlob(phase_info);
inverse_pixels=(double *) GetVirtualMemoryBlob(inverse_info);
i=0L;
magnitude_view=AcquireVirtualCacheView(magnitude_image,exception);
for (y=0L; y < (ssize_t) fourier_info->height; y++)
{
p=GetCacheViewVirtualPixels(magnitude_view,0L,y,fourier_info->width,1UL,
exception);
if (p == (const Quantum *) NULL)
break;
for (x=0L; x < (ssize_t) fourier_info->width; x++)
{
switch (fourier_info->channel)
{
case RedPixelChannel:
default:
{
magnitude_pixels[i]=QuantumScale*GetPixelRed(magnitude_image,p);
break;
}
case GreenPixelChannel:
{
magnitude_pixels[i]=QuantumScale*GetPixelGreen(magnitude_image,p);
break;
}
case BluePixelChannel:
{
magnitude_pixels[i]=QuantumScale*GetPixelBlue(magnitude_image,p);
break;
}
case BlackPixelChannel:
{
magnitude_pixels[i]=QuantumScale*GetPixelBlack(magnitude_image,p);
break;
}
case AlphaPixelChannel:
{
magnitude_pixels[i]=QuantumScale*GetPixelAlpha(magnitude_image,p);
break;
}
}
i++;
p+=GetPixelChannels(magnitude_image);
}
}
magnitude_view=DestroyCacheView(magnitude_view);
status=InverseQuadrantSwap(fourier_info->width,fourier_info->height,
magnitude_pixels,inverse_pixels);
(void) memcpy(magnitude_pixels,inverse_pixels,fourier_info->height*
fourier_info->center*sizeof(*magnitude_pixels));
i=0L;
phase_view=AcquireVirtualCacheView(phase_image,exception);
for (y=0L; y < (ssize_t) fourier_info->height; y++)
{
p=GetCacheViewVirtualPixels(phase_view,0,y,fourier_info->width,1,
exception);
if (p == (const Quantum *) NULL)
break;
for (x=0L; x < (ssize_t) fourier_info->width; x++)
{
switch (fourier_info->channel)
{
case RedPixelChannel:
default:
{
phase_pixels[i]=QuantumScale*GetPixelRed(phase_image,p);
break;
}
case GreenPixelChannel:
{
phase_pixels[i]=QuantumScale*GetPixelGreen(phase_image,p);
break;
}
case BluePixelChannel:
{
phase_pixels[i]=QuantumScale*GetPixelBlue(phase_image,p);
break;
}
case BlackPixelChannel:
{
phase_pixels[i]=QuantumScale*GetPixelBlack(phase_image,p);
break;
}
case AlphaPixelChannel:
{
phase_pixels[i]=QuantumScale*GetPixelAlpha(phase_image,p);
break;
}
}
i++;
p+=GetPixelChannels(phase_image);
}
}
if (fourier_info->modulus != MagickFalse)
{
i=0L;
for (y=0L; y < (ssize_t) fourier_info->height; y++)
for (x=0L; x < (ssize_t) fourier_info->width; x++)
{
phase_pixels[i]-=0.5;
phase_pixels[i]*=(2.0*MagickPI);
i++;
}
}
phase_view=DestroyCacheView(phase_view);
CorrectPhaseLHS(fourier_info->width,fourier_info->height,phase_pixels);
if (status != MagickFalse)
status=InverseQuadrantSwap(fourier_info->width,fourier_info->height,
phase_pixels,inverse_pixels);
(void) memcpy(phase_pixels,inverse_pixels,fourier_info->height*
fourier_info->center*sizeof(*phase_pixels));
inverse_info=RelinquishVirtualMemory(inverse_info);
/*
Merge two sets.
*/
i=0L;
if (fourier_info->modulus != MagickFalse)
for (y=0L; y < (ssize_t) fourier_info->height; y++)
for (x=0L; x < (ssize_t) fourier_info->center; x++)
{
#if defined(MAGICKCORE_HAVE_COMPLEX_H)
fourier_pixels[i]=magnitude_pixels[i]*cos(phase_pixels[i])+I*
magnitude_pixels[i]*sin(phase_pixels[i]);
#else
fourier_pixels[i][0]=magnitude_pixels[i]*cos(phase_pixels[i]);
fourier_pixels[i][1]=magnitude_pixels[i]*sin(phase_pixels[i]);
#endif
i++;
}
else
for (y=0L; y < (ssize_t) fourier_info->height; y++)
for (x=0L; x < (ssize_t) fourier_info->center; x++)
{
#if defined(MAGICKCORE_HAVE_COMPLEX_H)
fourier_pixels[i]=magnitude_pixels[i]+I*phase_pixels[i];
#else
fourier_pixels[i][0]=magnitude_pixels[i];
fourier_pixels[i][1]=phase_pixels[i];
#endif
i++;
}
magnitude_info=RelinquishVirtualMemory(magnitude_info);
phase_info=RelinquishVirtualMemory(phase_info);
return(status);
}
static MagickBooleanType InverseFourierTransform(FourierInfo *fourier_info,
fftw_complex *fourier_pixels,Image *image,ExceptionInfo *exception)
{
CacheView
*image_view;
const char
*value;
double
*source_pixels;
fftw_plan
fftw_c2r_plan;
MemoryInfo
*source_info;
register Quantum
*q;
register ssize_t
i,
x;
ssize_t
y;
source_info=AcquireVirtualMemory((size_t) fourier_info->width,
fourier_info->height*sizeof(*source_pixels));
if (source_info == (MemoryInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(MagickFalse);
}
source_pixels=(double *) GetVirtualMemoryBlob(source_info);
value=GetImageArtifact(image,"fourier:normalize");
if (LocaleCompare(value,"inverse") == 0)
{
double
gamma;
/*
Normalize inverse transform.
*/
i=0L;
gamma=PerceptibleReciprocal((double) fourier_info->width*
fourier_info->height);
for (y=0L; y < (ssize_t) fourier_info->height; y++)
for (x=0L; x < (ssize_t) fourier_info->center; x++)
{
#if defined(MAGICKCORE_HAVE_COMPLEX_H)
fourier_pixels[i]*=gamma;
#else
fourier_pixels[i][0]*=gamma;
fourier_pixels[i][1]*=gamma;
#endif
i++;
}
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_InverseFourierTransform)
#endif
fftw_c2r_plan=fftw_plan_dft_c2r_2d(fourier_info->width,fourier_info->height,
fourier_pixels,source_pixels,FFTW_ESTIMATE);
fftw_execute_dft_c2r(fftw_c2r_plan,fourier_pixels,source_pixels);
fftw_destroy_plan(fftw_c2r_plan);
i=0L;
image_view=AcquireAuthenticCacheView(image,exception);
for (y=0L; y < (ssize_t) fourier_info->height; y++)
{
if (y >= (ssize_t) image->rows)
break;
q=GetCacheViewAuthenticPixels(image_view,0L,y,fourier_info->width >
image->columns ? image->columns : fourier_info->width,1UL,exception);
if (q == (Quantum *) NULL)
break;
for (x=0L; x < (ssize_t) fourier_info->width; x++)
{
if (x < (ssize_t) image->columns)
switch (fourier_info->channel)
{
case RedPixelChannel:
default:
{
SetPixelRed(image,ClampToQuantum(QuantumRange*source_pixels[i]),q);
break;
}
case GreenPixelChannel:
{
SetPixelGreen(image,ClampToQuantum(QuantumRange*source_pixels[i]),
q);
break;
}
case BluePixelChannel:
{
SetPixelBlue(image,ClampToQuantum(QuantumRange*source_pixels[i]),
q);
break;
}
case BlackPixelChannel:
{
SetPixelBlack(image,ClampToQuantum(QuantumRange*source_pixels[i]),
q);
break;
}
case AlphaPixelChannel:
{
SetPixelAlpha(image,ClampToQuantum(QuantumRange*source_pixels[i]),
q);
break;
}
}
i++;
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
break;
}
image_view=DestroyCacheView(image_view);
source_info=RelinquishVirtualMemory(source_info);
return(MagickTrue);
}
static MagickBooleanType InverseFourierTransformChannel(
const Image *magnitude_image,const Image *phase_image,
const PixelChannel channel,const MagickBooleanType modulus,
Image *fourier_image,ExceptionInfo *exception)
{
fftw_complex
*inverse_pixels;
FourierInfo
fourier_info;
MagickBooleanType
status;
MemoryInfo
*inverse_info;
fourier_info.width=magnitude_image->columns;
fourier_info.height=magnitude_image->rows;
if ((magnitude_image->columns != magnitude_image->rows) ||
((magnitude_image->columns % 2) != 0) ||
((magnitude_image->rows % 2) != 0))
{
size_t extent=magnitude_image->columns < magnitude_image->rows ?
magnitude_image->rows : magnitude_image->columns;
fourier_info.width=(extent & 0x01) == 1 ? extent+1UL : extent;
}
fourier_info.height=fourier_info.width;
fourier_info.center=(ssize_t) (fourier_info.width/2L)+1L;
fourier_info.channel=channel;
fourier_info.modulus=modulus;
inverse_info=AcquireVirtualMemory((size_t) fourier_info.width,
(fourier_info.height/2+1)*sizeof(*inverse_pixels));
if (inverse_info == (MemoryInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",
magnitude_image->filename);
return(MagickFalse);
}
inverse_pixels=(fftw_complex *) GetVirtualMemoryBlob(inverse_info);
status=InverseFourier(&fourier_info,magnitude_image,phase_image,
inverse_pixels,exception);
if (status != MagickFalse)
status=InverseFourierTransform(&fourier_info,inverse_pixels,fourier_image,
exception);
inverse_info=RelinquishVirtualMemory(inverse_info);
return(status);
}
#endif
MagickExport Image *InverseFourierTransformImage(const Image *magnitude_image,
const Image *phase_image,const MagickBooleanType modulus,
ExceptionInfo *exception)
{
Image
*fourier_image;
assert(magnitude_image != (Image *) NULL);
assert(magnitude_image->signature == MagickCoreSignature);
if (magnitude_image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
magnitude_image->filename);
if (phase_image == (Image *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),ImageError,
"ImageSequenceRequired","`%s'",magnitude_image->filename);
return((Image *) NULL);
}
#if !defined(MAGICKCORE_FFTW_DELEGATE)
fourier_image=(Image *) NULL;
(void) modulus;
(void) ThrowMagickException(exception,GetMagickModule(),
MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn","`%s' (FFTW)",
magnitude_image->filename);
#else
{
fourier_image=CloneImage(magnitude_image,magnitude_image->columns,
magnitude_image->rows,MagickTrue,exception);
if (fourier_image != (Image *) NULL)
{
MagickBooleanType
is_gray,
status;
status=MagickTrue;
is_gray=IsImageGray(magnitude_image);
if (is_gray != MagickFalse)
is_gray=IsImageGray(phase_image);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel sections
#endif
{
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp section
#endif
{
MagickBooleanType
thread_status;
if (is_gray != MagickFalse)
thread_status=InverseFourierTransformChannel(magnitude_image,
phase_image,GrayPixelChannel,modulus,fourier_image,exception);
else
thread_status=InverseFourierTransformChannel(magnitude_image,
phase_image,RedPixelChannel,modulus,fourier_image,exception);
if (thread_status == MagickFalse)
status=thread_status;
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp section
#endif
{
MagickBooleanType
thread_status;
thread_status=MagickTrue;
if (is_gray == MagickFalse)
thread_status=InverseFourierTransformChannel(magnitude_image,
phase_image,GreenPixelChannel,modulus,fourier_image,exception);
if (thread_status == MagickFalse)
status=thread_status;
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp section
#endif
{
MagickBooleanType
thread_status;
thread_status=MagickTrue;
if (is_gray == MagickFalse)
thread_status=InverseFourierTransformChannel(magnitude_image,
phase_image,BluePixelChannel,modulus,fourier_image,exception);
if (thread_status == MagickFalse)
status=thread_status;
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp section
#endif
{
MagickBooleanType
thread_status;
thread_status=MagickTrue;
if (magnitude_image->colorspace == CMYKColorspace)
thread_status=InverseFourierTransformChannel(magnitude_image,
phase_image,BlackPixelChannel,modulus,fourier_image,exception);
if (thread_status == MagickFalse)
status=thread_status;
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp section
#endif
{
MagickBooleanType
thread_status;
thread_status=MagickTrue;
if (magnitude_image->alpha_trait != UndefinedPixelTrait)
thread_status=InverseFourierTransformChannel(magnitude_image,
phase_image,AlphaPixelChannel,modulus,fourier_image,exception);
if (thread_status == MagickFalse)
status=thread_status;
}
}
if (status == MagickFalse)
fourier_image=DestroyImage(fourier_image);
}
fftw_cleanup();
}
#endif
return(fourier_image);
}
|
mmtiled.c | // -----------------------------------------------------------------------------
//
// "CAPIPrecis"
//
// -----------------------------------------------------------------------------
// Copyright (c) 2014-2019 All rights reserved
// -----------------------------------------------------------------------------
// Author : Abdullah Mughrabi
// Email : atmughra@ncsu.edu||atmughrabi@gmail.com
// File : mmtiled.c
// Create : 2019-09-28 14:41:30
// Revise : 2019-11-29 11:17:40
// Editor : Abdullah Mughrabi
// -----------------------------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <string.h>
#include <math.h>
#include <omp.h>
#include "timer.h"
#include "myMalloc.h"
#include "config.h"
#include "mmtiled.h"
struct MatrixArrays *newMatrixArrays(struct Arguments *arguments)
{
struct MatrixArrays *matrixArrays = (struct MatrixArrays *) my_malloc(sizeof(struct MatrixArrays));
matrixArrays->size_n = arguments->size;
matrixArrays->size_tile = arguments->cu_config_2;
matrixArrays->A = (uint32_t *) my_malloc(sizeof(uint32_t) * (matrixArrays->size_n) * (matrixArrays->size_n));
matrixArrays->B = (uint32_t *) my_malloc(sizeof(uint32_t) * (matrixArrays->size_n) * (matrixArrays->size_n));
matrixArrays->C = (uint32_t *) my_malloc(sizeof(uint32_t) * (matrixArrays->size_n) * (matrixArrays->size_n));
return matrixArrays;
}
void freeMatrixArrays(struct MatrixArrays *matrixArrays)
{
if(matrixArrays)
{
if(matrixArrays->A)
free(matrixArrays->A);
if(matrixArrays->B)
free(matrixArrays->B);
if(matrixArrays->C)
free(matrixArrays->C);
free(matrixArrays);
}
}
void initializeMatrixArrays(struct MatrixArrays *matrixArrays)
{
uint64_t i;
uint64_t j;
#pragma omp parallel for private(j)
for(i = 0; i < matrixArrays->size_n; i++)
{
for(j = 0; j < matrixArrays->size_n; j++)
{
// matrixArrays->A[(i * matrixArrays->size_n) + j] = generateRandInt(mt19937var) % 512;
// matrixArrays->B[(i * matrixArrays->size_n) + j] = generateRandInt(mt19937var) % 512;
matrixArrays->A[(i * matrixArrays->size_n) + j] = (i * matrixArrays->size_n) + j;
matrixArrays->B[(i * matrixArrays->size_n) + j] = (i * matrixArrays->size_n) + j;
matrixArrays->C[(i * matrixArrays->size_n) + j] = (i * matrixArrays->size_n) + j;
}
}
}
void resetMatrixArrays(struct MatrixArrays *matrixArrays)
{
uint64_t i;
uint64_t j;
#pragma omp parallel for private(j)
for(i = 0; i < matrixArrays->size_n; i++)
{
for(j = 0; j < matrixArrays->size_n; j++)
{
matrixArrays->C[(i * matrixArrays->size_n) + j] = (i * matrixArrays->size_n) + j;
}
}
}
uint64_t compareMatrixArrays(struct MatrixArrays *matrixArrays1, struct MatrixArrays *matrixArrays2)
{
uint64_t missmatch = 0;
uint64_t i;
uint64_t j;
if(matrixArrays1->size_n != matrixArrays2->size_n)
return 1;
#pragma omp parallel for shared(matrixArrays1,matrixArrays2) private(j) reduction(+: missmatch)
for(i = 0; i < matrixArrays1->size_n; i++)
{
for(j = 0; j < matrixArrays1->size_n; j++)
{
if( matrixArrays1->A[(i * matrixArrays1->size_n) + j] != matrixArrays2->A[(i * matrixArrays2->size_n) + j]
|| matrixArrays1->B[(i * matrixArrays1->size_n) + j] != matrixArrays2->B[(i * matrixArrays2->size_n) + j]
|| matrixArrays1->C[(i * matrixArrays1->size_n) + j] != matrixArrays2->C[(i * matrixArrays2->size_n) + j])
{
// printf("[%llu] %u != %u\n", i, dataArrays->array_receive[i], dataArrays->array_send[i] );
missmatch ++;
}
}
}
return missmatch;
}
uint64_t checksumMatrixArrays(struct MatrixArrays *matrixArrays)
{
uint64_t checksum = 0;
uint64_t i;
uint64_t j;
#pragma omp parallel for shared(matrixArrays) private(j) reduction(+: checksum)
for(i = 0; i < matrixArrays->size_n; i++)
{
for(j = 0; j < matrixArrays->size_n; j++)
{
checksum += matrixArrays->C[(i * matrixArrays->size_n) + j];
}
}
return checksum;
}
void matrixTranspose(struct MatrixArrays *matrixArrays)
{
uint64_t i;
uint64_t j;
uint32_t temp;
for(i = 0; i < matrixArrays->size_n; i++)
{
#pragma omp parallel for private(temp)
for(j = i + 1; j < matrixArrays->size_n; j++)
{
temp = matrixArrays->B[(i * matrixArrays->size_n) + j];
matrixArrays->B[(i * matrixArrays->size_n) + j] = matrixArrays->B[(j * matrixArrays->size_n) + i];
matrixArrays->B[(j * matrixArrays->size_n) + i] = temp;
}
}
}
void matrixMultiplyStandard(struct MatrixArrays *matrixArrays)
{
uint64_t i;
uint64_t j;
uint64_t k;
uint32_t sum;
#pragma omp parallel for private(j,k,sum) schedule(dynamic)
for(i = 0; i < matrixArrays->size_n; i++)
{
for(j = 0; j < matrixArrays->size_n; j++)
{
sum = 0;
for(k = 0; k < matrixArrays->size_n; k++)
{
sum += matrixArrays->A[(i * matrixArrays->size_n) + k] * matrixArrays->B[(k * matrixArrays->size_n) + j];
}
matrixArrays->C[(i * matrixArrays->size_n) + j] = sum;
}
}
}
void matrixMultiplyStandardTransposed(struct MatrixArrays *matrixArrays)
{
uint64_t i;
uint64_t j;
uint64_t k;
uint32_t sum;
#pragma omp parallel for private(j,k,sum) schedule(dynamic)
for(i = 0; i < matrixArrays->size_n; i++)
{
for(j = 0; j < matrixArrays->size_n; j++)
{
sum = 0;
for(k = 0; k < matrixArrays->size_n; k++)
{
sum += matrixArrays->A[(i * matrixArrays->size_n) + k] * matrixArrays->B[(j * matrixArrays->size_n) + k];
}
matrixArrays->C[(i * matrixArrays->size_n) + j] = sum;
}
}
}
void matrixMultiplyTiled(struct MatrixArrays *matrixArrays)
{
uint64_t i;
uint64_t j;
uint64_t k;
uint64_t ii;
uint64_t jj;
uint64_t kk;
uint32_t sum;
#pragma omp parallel for private(j,k,ii,jj,kk,sum) schedule(dynamic)
for(i = 0; i < matrixArrays->size_n; i += matrixArrays->size_tile)
{
for(j = 0; j < matrixArrays->size_n; j += matrixArrays->size_tile)
{
for(k = 0; k < matrixArrays->size_n; k += matrixArrays->size_tile)
{
for (ii = i; ii < MIN(i + matrixArrays->size_tile, matrixArrays->size_n); ii++)
{
for (jj = j; jj < MIN(j + matrixArrays->size_tile, matrixArrays->size_n); jj++)
{
sum = 0;
//#pragma omp parallel for reduction(+:sum)
for (kk = k; kk < MIN(k + matrixArrays->size_tile, matrixArrays->size_n); kk++)
{
sum += matrixArrays->A[(ii * matrixArrays->size_n) + kk] * matrixArrays->B[(kk * matrixArrays->size_n) + jj];
}
matrixArrays->C[(ii * matrixArrays->size_n) + jj] += sum;
}
}
}
}
}
}
void matrixMultiplyTiledTransposed(struct MatrixArrays *matrixArrays, struct Arguments *arguments)
{
uint64_t i;
uint64_t j;
uint64_t k;
uint64_t ii;
uint64_t jj;
// uint64_t kk;
uint32_t sum;
// #pragma omp parallel for private(j,k,ii,jj,kk,sum) schedule(dynamic)
for(i = 0; i < matrixArrays->size_n; i += matrixArrays->size_tile)
{
for(j = 0; j < matrixArrays->size_n; j += matrixArrays->size_tile)
{
for(k = 0; k < matrixArrays->size_n; k += matrixArrays->size_tile)
{
for (ii = i; ii < MIN(i + matrixArrays->size_tile, matrixArrays->size_n); ii++)
{
for (jj = j; jj < MIN(j + matrixArrays->size_tile, matrixArrays->size_n); jj++)
{
sum = 0;
//#pragma omp parallel for reduction(+:sum)
// for (kk = k; kk < MIN(k + matrixArrays->size_tile, matrixArrays->size_n); kk++)
// {
// sum += matrixArrays->A[(ii * matrixArrays->size_n) + kk] * matrixArrays->B[(jj * matrixArrays->size_n) + kk];
// }
matrixArrays->C[(ii * matrixArrays->size_n) + jj] += sum;
printf("i:%lu j:%lu C:%u \n",ii,jj, matrixArrays->C[(ii * matrixArrays->size_n) + jj]);
}
}
break;
}
break;
}
break;
}
} |
sht_init.c | /*
* Copyright (c) 2010-2015 Centre National de la Recherche Scientifique.
* written by Nathanael Schaeffer (CNRS, ISTerre, Grenoble, France).
*
* nathanael.schaeffer@ujf-grenoble.fr
*
* This software is governed by the CeCILL license under French law and
* abiding by the rules of distribution of free software. You can use,
* modify and/or redistribute the software under the terms of the CeCILL
* license as circulated by CEA, CNRS and INRIA at the following URL
* "http://www.cecill.info".
*
* The fact that you are presently reading this means that you have had
* knowledge of the CeCILL license and that you accept its terms.
*
*/
/********************************************************************
* SHTns : Spherical Harmonic Transform for numerical simulations. *
* written by Nathanael Schaeffer / CNRS *
********************************************************************/
/** \internal \file SHT.c
* \brief main source file for SHTns.
* This files contains initialization code and also some partial transforms (point or latitudinal evaluations)
*/
#include <stdio.h>
#include <string.h>
// global variables definitions
#include "sht_private.h"
// cycle counter from FFTW
#include "fftw3/cycle.h"
// chained list of sht_setup : start with NULL
shtns_cfg sht_data = NULL;
#ifdef _OPENMP
int omp_threads = 1; // multi-thread disabled by default.
#if HAVE_LIBFFTW3_OMP
#define OMP_FFTW
#endif
#else
#define omp_threads 1
#endif
static int verbose = 0; // runtime verbosity control: 0 no output, 1 output, 2 debug (if compiled in)
void shtns_verbose(int v) {
verbose = v;
}
/// \internal Abort program with error message.
static void shtns_runerr(const char * error_text)
{
printf("*** [" PACKAGE_NAME "] Run-time error : %s\n",error_text);
exit(1);
}
/* PUBLIC useful functions */
/// returns the l=0, m=0 SH coefficient corresponding to a uniform value of 1.
double sh00_1(shtns_cfg shtns) {
return shtns->Y00_1;
}
/// returns the l=1, m=0 SH coefficient corresponding to cos(theta).
double sh10_ct(shtns_cfg shtns) {
return shtns->Y10_ct;
}
/// returns the l=1, m=1 SH coefficient corresponding to sin(theta).cos(phi).
double sh11_st(shtns_cfg shtns) {
return shtns->Y11_st;
}
/// returns the l,m SH coefficient corresponding to unit energy.
double shlm_e1(shtns_cfg shtns, int l, int m) {
double x = shtns->Y00_1/sqrt(4.*M_PI);
if (SHT_NORM == sht_schmidt) x *= sqrt(2*l+1);
if ((m!=0)&&((shtns->norm & SHT_REAL_NORM)==0)) x *= sqrt(0.5);
return(x);
}
/// \code return (mmax+1)*(lmax+1) - mres*(mmax*(mmax+1))/2; \endcode */
/// \ingroup init
long nlm_calc(long lmax, long mmax, long mres)
{
if (mmax*mres > lmax) mmax = lmax/mres;
return (mmax+1)*(lmax+1) - ((mmax*mres)*(mmax+1))/2; // this is wrong if lmax < mmax*mres
}
/* LEGENDRE FUNCTIONS */
#include "sht_legendre.c"
/* SHT FUNCTIONS */
#include "sht_func.c"
#include "sht_com.c"
/*
INTERNAL INITIALIZATION FUNCTIONS
*/
// sht algorithms (hyb, fly1, ...)
enum sht_algos { SHT_DCT, SHT_MEM, SHT_SV,
SHT_FLY1, SHT_FLY2, SHT_FLY3, SHT_FLY4, SHT_FLY6, SHT_FLY8,
SHT_OMP1, SHT_OMP2, SHT_OMP3, SHT_OMP4, SHT_OMP6, SHT_OMP8,
SHT_NALG };
char* sht_name[SHT_NALG] = {"dct", "mem", "s+v", "fly1", "fly2", "fly3", "fly4", "fly6", "fly8", "omp1", "omp2", "omp3", "omp4", "omp6", "omp8" };
char* sht_type[SHT_NTYP] = {"syn", "ana", "vsy", "van", "gsp", "gto", "v3s", "v3a" };
char* sht_var[SHT_NVAR] = {"std", "ltr", "m" };
int sht_npar[SHT_NTYP] = {2, 2, 4, 4, 3, 3, 6, 6};
#ifdef SHTNS_MEM
extern void* fmem[SHT_NTYP];
extern void* fmem_l[SHT_NTYP];
extern void* fmem_m0[SHT_NTYP];
extern void* fmem_m0l[SHT_NTYP];
#endif
#ifdef SHTNS_DCT
extern void* fdct[SHT_NTYP];
extern void* fdct_l[SHT_NTYP];
extern void* fdct_m0[SHT_NTYP];
extern void* fdct_m0l[SHT_NTYP];
#endif
extern void* ffly[6][SHT_NTYP];
extern void* ffly_m[6][SHT_NTYP];
extern void* ffly_m0[6][SHT_NTYP];
#ifdef _OPENMP
extern void* fomp[6][SHT_NTYP];
#endif
// big array holding all sht functions, variants and algorithms
void* sht_func[SHT_NVAR][SHT_NALG][SHT_NTYP];
/// \internal use on-the-fly alogorithm (guess without measuring)
static void set_sht_fly(shtns_cfg shtns, int typ_start)
{
int algo = SHT_FLY2;
if ((shtns->nthreads > 1) && (sht_func[0][SHT_OMP2][typ_start])) algo = SHT_OMP2;
for (int it=typ_start; it<SHT_NTYP; it++) {
for (int v=0; v<SHT_NVAR; v++)
shtns->ftable[v][it] = sht_func[v][algo][it];
}
}
#ifdef SHTNS_MEM
/// \internal choose memory algorithm everywhere.
static void set_sht_mem(shtns_cfg shtns) {
for (int it=0; it<SHT_NTYP; it++) {
for (int v=0; v<SHT_NVAR; v++)
shtns->ftable[v][it] = sht_func[v][SHT_MEM][it];
shtns->ftable[SHT_M][it] = sht_func[SHT_M][SHT_FLY2][it]; // there is no "mem" algo for SHT_M
}
}
#endif
/// \internal copy all algos to sht_func array (should be called by set_grid before choosing variants).
/// if nphi is 1, axisymmetric algorithms are used.
static void init_sht_array_func(shtns_cfg shtns)
{
int it, j;
int alg_lim = SHT_FLY8;
if (shtns->nlat_2 < 8*VSIZE2) { // limit available on-the-fly algorithm to avoid overflow (and segfaults).
it = shtns->nlat_2 / VSIZE2;
switch(it) {
case 0 : alg_lim = SHT_FLY1-1; break;
case 1 : alg_lim = SHT_FLY1; break;
case 2 : alg_lim = SHT_FLY2; break;
case 3 : alg_lim = SHT_FLY3; break;
case 4 : ;
case 5 : alg_lim = SHT_FLY4; break;
default : alg_lim = SHT_FLY6;
}
}
alg_lim -= SHT_FLY1;
memset(sht_func, 0, SHT_NVAR*SHT_NTYP*SHT_NALG*sizeof(void*) ); // zero out.
sht_func[SHT_STD][SHT_SV][SHT_TYP_3SY] = SHqst_to_spat_2;
sht_func[SHT_LTR][SHT_SV][SHT_TYP_3SY] = SHqst_to_spat_2l;
sht_func[SHT_STD][SHT_SV][SHT_TYP_3AN] = spat_to_SHqst_2;
sht_func[SHT_LTR][SHT_SV][SHT_TYP_3AN] = spat_to_SHqst_2l;
sht_func[SHT_M][SHT_SV][SHT_TYP_3SY] = SHqst_to_spat_2ml;
sht_func[SHT_M][SHT_SV][SHT_TYP_3AN] = spat_to_SHqst_2ml;
if (shtns->nphi==1) { // axisymmetric transform requested.
for (int j=0; j<=alg_lim; j++) {
memcpy(sht_func[SHT_STD][SHT_FLY1 + j], &ffly_m0[j], sizeof(void*)*SHT_NTYP);
memcpy(sht_func[SHT_LTR][SHT_FLY1 + j], &ffly_m0[j], sizeof(void*)*SHT_NTYP);
}
#ifdef SHTNS_DCT
memcpy(sht_func[SHT_STD][SHT_DCT], &fdct_m0, sizeof(void*)*SHT_NTYP);
memcpy(sht_func[SHT_LTR][SHT_DCT], &fdct_m0l, sizeof(void*)*SHT_NTYP);
#endif
#ifdef SHTNS_MEM
memcpy(sht_func[SHT_STD][SHT_MEM], &fmem_m0, sizeof(void*)*SHT_NTYP);
memcpy(sht_func[SHT_LTR][SHT_MEM], &fmem_m0l, sizeof(void*)*SHT_NTYP);
#endif
} else {
for (int j=0; j<=alg_lim; j++) {
memcpy(sht_func[SHT_STD][SHT_FLY1 + j], &ffly[j], sizeof(void*)*SHT_NTYP);
memcpy(sht_func[SHT_LTR][SHT_FLY1 + j], &ffly[j], sizeof(void*)*SHT_NTYP);
memcpy(sht_func[SHT_M][SHT_FLY1 + j], &ffly_m[j], sizeof(void*)*SHT_NTYP);
#ifdef _OPENMP
memcpy(sht_func[SHT_STD][SHT_OMP1 + j], &fomp[j], sizeof(void*)*SHT_NTYP);
memcpy(sht_func[SHT_LTR][SHT_OMP1 + j], &fomp[j], sizeof(void*)*SHT_NTYP);
memcpy(sht_func[SHT_M][SHT_OMP1 + j], &ffly_m[j], sizeof(void*)*SHT_NTYP); // no omp algo for SHT_M, use fly instead
#endif
}
#ifdef SHTNS_DCT
memcpy(sht_func[SHT_STD][SHT_DCT], &fdct, sizeof(void*)*SHT_NTYP);
memcpy(sht_func[SHT_LTR][SHT_DCT], &fdct_l, sizeof(void*)*SHT_NTYP);
#endif
#ifdef SHTNS_MEM
memcpy(sht_func[SHT_STD][SHT_MEM], &fmem, sizeof(void*)*SHT_NTYP);
memcpy(sht_func[SHT_LTR][SHT_MEM], &fmem_l, sizeof(void*)*SHT_NTYP);
#endif
}
#ifdef SHTNS_MEM
set_sht_mem(shtns); // default transform is MEM
#else
set_sht_fly(shtns, 0);
#endif
}
/// \internal return the smallest power of 2 larger than n.
static int next_power_of_2(int n)
{
int f = 1;
if ( (n<=0) || (n>(1<<(sizeof(int)*8-2))) ) return 0;
while (f<n) f*=2;
return f;
}
/// \internal find the closest integer that is larger than n and that contains only factors up to fmax.
/// fmax is 7 for optimal FFTW fourier transforms.
/// return only even integers for n>fmax.
static int fft_int(int n, int fmax)
{
int k,f;
if (n<=fmax) return n;
if (fmax<2) return 0;
if (fmax==2) return next_power_of_2(n);
n -= 2-(n&1); // only even n
do {
n+=2; f=2;
while ((2*f <= n) && ((n&f)==0)) f *= 2; // no divisions for factor 2.
k=3;
while ((k<=fmax) && (k*f <= n)) {
while ((k*f <= n) && (n%(k*f)==0)) f *= k;
k+=2;
}
} while (f != n);
k = next_power_of_2(n); // what is the closest power of 2 ?
if ((k-n)*33 < n) return k; // rather choose power of 2 if not too far (3%)
return n;
}
/// \internal returns an aproximation of the memory usage in mega bytes for the scalar matrices.
/// \ingroup init
static double sht_mem_size(int lmax, int mmax, int mres, int nlat)
{
double s = 1./(1024*1024);
s *= ((nlat+1)/2) * sizeof(double) * nlm_calc(lmax, mmax, mres);
return s;
}
/// \internal return the number of shtns config that contain a reference to the memory location *pp.
static int ref_count(shtns_cfg shtns, void* pp)
{
shtns_cfg s2 = sht_data;
void* p;
long int nref, offset;
if ((pp==NULL) || (shtns==NULL)) return -1; // error.
p = *(void**)pp; // the pointer to memory location that we want to free
if (p == NULL) return 0; // nothing to do.
offset = (char*)pp - (char*)shtns; // relative location in shtns_info structure.
nref = 0; // reference count.
while (s2 != NULL) { // scan all configs.
if ( *(void**)(((char*)s2) + offset) == p ) nref++;
s2 = s2->next;
}
return nref; // will be >= 1 (as shtns is included in search)
}
/// \internal check if the memory location *pp is referenced by another sht config before freeing it.
/// returns the number of other references, or -1 on error. If >=1, the memory location could not be freed.
/// If the return value is 0, the ressource has been freed.
static int free_unused(shtns_cfg shtns, void* pp)
{
int n = ref_count(shtns, pp); // howmany shtns config do reference this memory location ?
if (n <= 0) return n; // nothing to free.
if (n == 1) { // no other reference found...
void** ap = (void**) pp;
free(*ap); // ...so we can free it...
*ap = NULL; // ...and mark as unaloccated.
}
return (n-1);
}
#ifdef SHTNS_MEM
/// \internal Free matrices if on-the-fly has been selected.
static void free_unused_matrices(shtns_cfg shtns)
{
long int marray_size = (MMAX+1)*sizeof(double) + (MIN_ALIGNMENT-1);
int count[SHT_NTYP];
int it, iv, ia, iv2;
for (it=0; it<SHT_NTYP; it++) {
count[it] = 0;
for (iv=0; iv<SHT_NVAR; iv++) {
void* fptr = shtns->ftable[iv][it];
if (fptr != NULL) {
for (ia=0; ia<=SHT_MEM; ia++) // count occurences to mem algo
for (iv2=0; iv2<SHT_NVAR; iv2++)
if (sht_func[iv2][ia][it] == fptr) count[it]++;
}
}
#if SHT_VERBOSE > 1
if (verbose>1) printf(" %d ",count[it]);
#endif
}
if (shtns->dylm == NULL) { // no vector transform : do not try to free
count[SHT_TYP_VAN] = -1; count[SHT_TYP_VSY] = -1;
}
if (count[SHT_TYP_3AN] == 0) { // analysis may be freed.
if (count[SHT_TYP_VAN] == 0) {
PRINT_VERB("freeing vector analysis matrix\n");
free_unused(shtns, &shtns->dzlm);
}
if (count[SHT_TYP_SAN] == 0) {
PRINT_VERB("freeing scalar analysis matrix\n");
free_unused(shtns, &shtns->zlm);
}
} else if (shtns->mmax > 0) { // scalar may be reduced to m=0
if ((count[SHT_TYP_SAN] == 0) && (ref_count(shtns, &shtns->zlm) == 1)) {
PRINT_VERB("keeping scalar analysis matrix up to m=0\n");
shtns->zlm = realloc(shtns->zlm, ((LMAX+1)*NLAT_2 +3)*sizeof(double) + marray_size );
}
}
if (count[SHT_TYP_3SY] == 0) { // synthesis may be freed.
if (count[SHT_TYP_VSY] + count[SHT_TYP_GSP] + count[SHT_TYP_GTO] == 0) {
PRINT_VERB("freeing vector synthesis matrix\n");
free_unused(shtns, &shtns->dylm);
}
if (count[SHT_TYP_SSY] == 0) {
PRINT_VERB("freeing scalar synthesis matrix\n");
free_unused(shtns, &shtns->ylm);
}
} else if (shtns->mmax > 0) { // scalar may be reduced to m=0
if ((count[SHT_TYP_SSY] == 0) && (ref_count(shtns, &shtns->ylm) == 1)) {
PRINT_VERB("keeping scalar synthesis matrix up to m=0\n");
shtns->ylm = realloc(shtns->ylm, (LMAX+2)*NLAT_2*sizeof(double) + marray_size );
}
}
}
#endif
/// \internal allocate arrays for SHT related to a given grid.
static void alloc_SHTarrays(shtns_cfg shtns, int on_the_fly, int vect, int analys)
{
long int im, l0;
long int size, marray_size, lstride;
im = (VSIZE2 > 2) ? VSIZE2 : 2;
l0 = ((NLAT+im-1)/im)*im; // align on vector
shtns->ct = (double *) VMALLOC( sizeof(double) * l0*3 ); /// ct[] (including st and st_1)
shtns->st = shtns->ct + l0; shtns->st_1 = shtns->ct + 2*l0;
shtns->ylm = NULL; shtns->dylm = NULL; // synthesis
shtns->zlm = NULL; shtns->dzlm = NULL; // analysis
if (on_the_fly == 0) { // Allocate legendre functions lookup tables.
marray_size = (MMAX+1)*sizeof(double*) + (MIN_ALIGNMENT-1); // for sse2 alignement
/* ylm */
lstride = (LMAX+1); lstride += (lstride&1); // even stride.
size = sizeof(double) * ((NLM-(LMAX+1)+lstride)*NLAT_2);
if (MMAX == 0) size += 3*sizeof(double); // some overflow needed.
shtns->ylm = (double **) malloc( marray_size + size );
shtns->ylm[0] = (double *) PTR_ALIGN( shtns->ylm + (MMAX+1) );
if (MMAX>0) shtns->ylm[1] = shtns->ylm[0] + NLAT_2*lstride;
for (im=1; im<MMAX; im++) shtns->ylm[im+1] = shtns->ylm[im] + NLAT_2*(LMAX+1-im*MRES);
/* dylm */
if (vect) {
lstride = LMAX; lstride += (lstride&1); // even stride.
size = sizeof(struct DtDp) * ((NLM-(LMAX+1) +lstride/2)*NLAT_2);
if (MMAX == 0) size += 2*sizeof(double); // some overflow needed.
shtns->dylm = (struct DtDp **) malloc( marray_size + size );
shtns->dylm[0] = (struct DtDp *) PTR_ALIGN( shtns->dylm + (MMAX+1) );
if (MMAX>0) shtns->dylm[1] = shtns->dylm[0] + (lstride/2)*NLAT_2; // phi-derivative is zero for m=0
for (im=1; im<MMAX; im++) shtns->dylm[im+1] = shtns->dylm[im] + NLAT_2*(LMAX+1-im*MRES);
}
if (analys) {
/* zlm */
size = sizeof(double) * (NLM*NLAT_2 + (NLAT_2 & 1));
if (MMAX == 0) size += 2*(NLAT_2 & 1)*((LMAX+1) & 1) * sizeof(double);
shtns->zlm = (double **) malloc( marray_size + size );
shtns->zlm[0] = (double *) PTR_ALIGN( shtns->zlm + (MMAX+1) );
if (MMAX>0) shtns->zlm[1] = shtns->zlm[0] + NLAT_2*(LMAX+1) + (NLAT_2&1);
for (im=1; im<MMAX; im++) shtns->zlm[im+1] = shtns->zlm[im] + NLAT_2*(LMAX+1-im*MRES);
/* dzlm */
if (vect) {
size = sizeof(struct DtDp)* (NLM-1)*NLAT_2; // remove l=0
shtns->dzlm = (struct DtDp **) malloc( marray_size + size );
shtns->dzlm[0] = (struct DtDp *) PTR_ALIGN( shtns->dzlm + (MMAX+1) );
if (MMAX>0) shtns->dzlm[1] = shtns->dzlm[0] + NLAT_2*(LMAX);
for (im=1; im<MMAX; im++) shtns->dzlm[im+1] = shtns->dzlm[im] + NLAT_2*(LMAX+1-im*MRES);
}
}
}
#if SHT_VERBOSE > 1
if (verbose>1) printf(" Memory used for Ylm and Zlm matrices = %.3f Mb x2\n",3.0*sizeof(double)*NLM*NLAT_2/(1024.*1024.));
#endif
}
/// \internal free arrays allocated by init_SH_dct
static void free_SH_dct(shtns_cfg shtns)
{
if (shtns->zlm_dct0 == NULL) return;
if (ref_count(shtns, &shtns->dzlm_dct0) == 1) VFREE(shtns->dzlm_dct0);
if (ref_count(shtns, &shtns->zlm_dct0) == 1) VFREE(shtns->zlm_dct0);
shtns->dzlm_dct0 = NULL; shtns->zlm_dct0 = NULL;
free_unused(shtns, &shtns->dykm_dct);
free_unused(shtns, &shtns->ykm_dct);
if (ref_count(shtns, &shtns->idct) == 1) fftw_destroy_plan(shtns->idct); // free unused dct plans
if (ref_count(shtns, &shtns->dct_m0) == 1) fftw_destroy_plan(shtns->dct_m0);
shtns->idct = NULL; shtns->dct_m0 = NULL;
}
/// \internal free arrays allocated by alloc_SHTarrays.
static void free_SHTarrays(shtns_cfg shtns)
{
free_SH_dct(shtns);
free_unused(shtns, &shtns->ylm);
free_unused(shtns, &shtns->dylm);
free_unused(shtns, &shtns->zlm);
free_unused(shtns, &shtns->dzlm);
if (ref_count(shtns, &shtns->ct) == 1) VFREE(shtns->ct);
shtns->ct = NULL; shtns->st = NULL;
if (ref_count(shtns, &shtns->fft) == 1) fftw_destroy_plan(shtns->fft);
if (ref_count(shtns, &shtns->ifft) == 1) fftw_destroy_plan(shtns->ifft);
shtns->fft = NULL; shtns->ifft = NULL; shtns->ncplx_fft = -1; // no fft
}
#ifndef HAVE_FFTW_COST
// substitute undefined symbol in mkl and fftw older than 3.3
#define fftw_cost(a) 0.0
#endif
/// \internal initialize FFTs using FFTW.
/// \param[in] layout defines the spatial layout (see \ref spat).
/// \param[in] on_the_fly is one, if only on-the-fly transform are considered.
/// returns the number of double to be allocated for a spatial field.
static void planFFT(shtns_cfg shtns, int layout, int on_the_fly)
{
double cost_fft_ip, cost_fft_oop, cost_ifft_ip, cost_ifft_oop;
cplx *ShF;
double *Sh;
fftw_plan fft2, ifft2, fft, ifft;
int nfft, ncplx, nreal;
int theta_inc, phi_inc, phi_embed;
#ifdef HAVE_FFTW_COST
int in_place = 1; // try to use in-place real fft.
#else
int in_place = 0; // do not try to use in-place real fft if no timing data available.
#endif
if (NPHI <= 2*MMAX) shtns_runerr("the sampling condition Nphi > 2*Mmax is not met.");
#ifdef OMP_FFTW
if ((shtns->fftw_plan_mode & (FFTW_EXHAUSTIVE | FFTW_PATIENT)) && (omp_threads > 1)) {
shtns->fftw_plan_mode = FFTW_PATIENT;
fftw_plan_with_nthreads(omp_threads);
} else fftw_plan_with_nthreads(shtns->nthreads);
#endif
shtns->k_stride_a = 1; shtns->m_stride_a = NLAT; // default strides
shtns->fft = NULL; shtns->ifft = NULL;
shtns->dct_m0 = NULL; shtns->idct = NULL; // set dct plans to uninitialized.
shtns->nspat = NPHI * NLAT; // default spatial size
if (NPHI==1) // no FFT needed.
{
shtns->fftc_mode = -1; // no FFT
#if SHT_VERBOSE > 0
if (verbose) printf(" => no fft : Mmax=0, Nphi=1, Nlat=%d\n",NLAT);
#endif
shtns->ncplx_fft = -1; // no fft.
return;
}
/* NPHI > 1 */
theta_inc=1; phi_inc=NLAT; phi_embed=2*(NPHI/2+1); // SHT_NATIVE_LAYOUT is the default.
if (layout & SHT_THETA_CONTIGUOUS) { theta_inc=1; phi_inc=NLAT; phi_embed=NPHI; }
if (layout & SHT_PHI_CONTIGUOUS) { phi_inc=1; theta_inc=NPHI; phi_embed=NPHI; }
nfft = NPHI;
ncplx = NPHI/2 +1;
nreal = phi_embed;
if ((theta_inc != 1)||(phi_inc != NLAT)||(nreal < 2*ncplx)) in_place = 0; // we need to do the fft out-of-place.
#if SHT_VERBOSE > 0
if (verbose) {
printf(" => using FFTW : Mmax=%d, Nphi=%d, Nlat=%d (data layout : phi_inc=%d, theta_inc=%d, phi_embed=%d)\n",MMAX,NPHI,NLAT,phi_inc,theta_inc,phi_embed);
if (NPHI <= (SHT_NL_ORDER+1)*MMAX) printf(" !! Warning : anti-aliasing condition Nphi > %d*Mmax is not met !\n", SHT_NL_ORDER+1);
if (NPHI != fft_int(NPHI,7)) printf(" !! Warning : Nphi is not optimal for FFTW !\n");
}
#endif
// Allocate dummy Spatial Fields.
ShF = (cplx *) VMALLOC(ncplx * NLAT * sizeof(cplx));
Sh = (double *) VMALLOC(ncplx * NLAT * sizeof(cplx));
fft = NULL; ifft = NULL; fft2 = NULL; ifft2 = NULL;
// complex fft for fly transform is a bit different.
if (layout & SHT_PHI_CONTIGUOUS) { // out-of-place split dft
fftw_iodim dim, many;
shtns->fftc_mode = 1;
//default internal
dim.n = NPHI; dim.os = 1; dim.is = NLAT; // complex transpose
many.n = NLAT/2; many.os = 2*NPHI; many.is = 2;
shtns->ifftc = fftw_plan_guru_split_dft(1, &dim, 1, &many, ((double*)ShF)+1, (double*)ShF, Sh+NPHI, Sh, shtns->fftw_plan_mode);
// legacy analysis fft
//dim.n = NPHI; dim.is = 1; dim.os = NLAT;
//many.n = NLAT/2; many.is = 2*NPHI; many.os = 2;
// new internal
dim.n = NPHI; dim.is = 1; dim.os = 2; // split complex, but without global transpose (faster).
many.n = NLAT/2; many.is = 2*NPHI; many.os = 2*NPHI;
shtns->fftc = fftw_plan_guru_split_dft(1, &dim, 1, &many, Sh+NPHI, Sh, ((double*)ShF)+1, (double*)ShF, shtns->fftw_plan_mode);
shtns->k_stride_a = NPHI; shtns->m_stride_a = 2;
#if SHT_VERBOSE > 1
if (verbose>1) {
printf(" fftw cost ifftc=%lg, fftc=%lg ",fftw_cost(shtns->ifftc), fftw_cost(shtns->fftc)); fflush(stdout);
}
#endif
} else { //if (layout & SHT_THETA_CONTIGUOUS) { // use only in-place here, supposed to be faster.
shtns->fftc_mode = 0;
shtns->ifftc = fftw_plan_many_dft(1, &nfft, NLAT/2, ShF, &nfft, NLAT/2, 1, ShF, &nfft, NLAT/2, 1, FFTW_BACKWARD, shtns->fftw_plan_mode);
shtns->fftc = shtns->ifftc; // same thing, with m>0 and m<0 exchanged.
#if SHT_VERBOSE > 1
if (verbose>1) {
printf(" fftw cost ifftc=%lg ",fftw_cost(shtns->ifftc)); fflush(stdout);
}
#endif
}
#if _GCC_VEC_
if (on_the_fly == 0)
#endif
{ // the real ffts are required if _GCC_VEC_ == 0 or if on_the_fly is zero.
// IFFT : unnormalized. FFT : must be normalized.
cost_fft_ip = 0.0; cost_ifft_ip = 0.0; cost_fft_oop = 0.0; cost_ifft_oop = 0.0;
if (in_place) { // in-place FFT (if allowed)
ifft2 = fftw_plan_many_dft_c2r(1, &nfft, NLAT, ShF, &ncplx, NLAT, 1, (double*) ShF, &nreal, phi_inc, theta_inc, shtns->fftw_plan_mode);
#if SHT_VERBOSE > 1
if (verbose>1) {
printf(" in-place cost : ifft=%lg ",fftw_cost(ifft2)); fflush(stdout);
}
#endif
if (ifft2 != NULL) {
fft2 = fftw_plan_many_dft_r2c(1, &nfft, NLAT, (double*) ShF, &nreal, phi_inc, theta_inc, ShF, &ncplx, NLAT, 1, shtns->fftw_plan_mode);
#if SHT_VERBOSE > 1
if (verbose>1) {
printf("fft=%lg\n",fftw_cost(fft2)); fflush(stdout);
}
#endif
if (fft2 != NULL) {
cost_fft_ip = fftw_cost(fft2); cost_ifft_ip = fftw_cost(ifft2);
}
}
}
if ( (in_place == 0) || (cost_fft_ip * cost_ifft_ip > 0.0) )
{ // out-of-place FFT
ifft = fftw_plan_many_dft_c2r(1, &nfft, NLAT, ShF, &ncplx, NLAT, 1, Sh, &nreal, phi_inc, theta_inc, shtns->fftw_plan_mode);
#if SHT_VERBOSE > 1
if (verbose>1) { printf(" oop cost : ifft=%lg ",fftw_cost(ifft)); fflush(stdout); }
#endif
if (ifft == NULL) shtns_runerr("[FFTW] ifft planning failed !");
fft = fftw_plan_many_dft_r2c(1, &nfft, NLAT, Sh, &nreal, phi_inc, theta_inc, ShF, &ncplx, NLAT, 1, shtns->fftw_plan_mode);
#if SHT_VERBOSE > 1
if (verbose>1) { printf("fft=%lg\n",fftw_cost(fft)); fflush(stdout); }
#endif
if (fft == NULL) shtns_runerr("[FFTW] fft planning failed !");
cost_fft_oop = fftw_cost(fft); cost_ifft_oop = fftw_cost(ifft);
}
if ( (cost_fft_ip * cost_ifft_ip > 0.0) && (cost_fft_oop * cost_ifft_oop > 0.0) ) { // both have been succesfully timed.
if ( cost_fft_oop + SHT_NL_ORDER*cost_ifft_oop < cost_fft_ip + SHT_NL_ORDER*cost_ifft_ip )
in_place = 0; // disable in-place, because out-of-place is faster.
}
if (in_place) {
/* IN-PLACE FFT */
if (fft != NULL) fftw_destroy_plan(fft);
if (ifft != NULL) fftw_destroy_plan(ifft);
fft = fft2; ifft = ifft2;
shtns->ncplx_fft = 0; // fft is done in-place, no allocation needed.
shtns->nspat = phi_embed * NLAT; // more space must be reserved for inplace ffts.
} else {
/* OUT-OF-PLACE FFT */
if (fft2 != NULL) fftw_destroy_plan(fft2); // use OUT-OF-PLACE FFT
if (ifft2 != NULL) fftw_destroy_plan(ifft2);
shtns->ncplx_fft = ncplx * NLAT; // fft is done out-of-place, store allocation size.
#if SHT_VERBOSE > 1
if (verbose>1) printf(" ** out-of-place fft **\n");
#endif
}
shtns->fft = fft; shtns->ifft = ifft;
}
VFREE(Sh); VFREE(ShF);
#if SHT_VERBOSE > 2
if (verbose>2) {
printf(" *** fft plan :\n");
fftw_print_plan(fft);
printf("\n *** ifft plan :\n");
fftw_print_plan(ifft);
printf("\n");
}
#endif
}
#ifdef SHTNS_DCT
/// \internal initialize DCTs using FFTW. Must be called if MTR_DCT is changed.
static int planDCT(shtns_cfg shtns)
{
double *Sh;
int ndct = NLAT;
fftw_r2r_kind r2r_kind;
fftw_iodim dims, hdims[2];
double Sh0[NLAT] SSE; // temp storage on the stack, aligned.
#ifdef OMP_FFTW
if (shtns->fftw_plan_mode & (FFTW_EXHAUSTIVE | FFTW_PATIENT)) {
fftw_plan_with_nthreads(omp_threads);
} else fftw_plan_with_nthreads(1);
#endif
// Allocate dummy Spatial Fields.
Sh = (double *) VMALLOC((NPHI/2 +1) * NLAT*2 * sizeof(double));
if (shtns->dct_m0 == NULL) { // allocate only once since it does not change.
int stride = (NPHI>1) ? 2 : 1;
r2r_kind = FFTW_REDFT10; // out-of-place.
shtns->dct_m0 = fftw_plan_many_r2r(1, &ndct, 1, Sh, &ndct, stride, stride*NLAT, Sh0, &ndct, 1, NLAT, &r2r_kind, shtns->fftw_plan_mode); // out-of-place.
if (shtns->dct_m0 == NULL) return 0; // dct_m0 planning failed.
#if SHT_VERBOSE > 2
if (verbose>2) {
printf(" *** dct_m0 plan :\n"); fftw_print_plan(shtns->dct_m0); printf("\n");
}
#endif
}
if (NPHI > 1) { // complex data for NPHI>1, recompute as it does depend on MTR_DCT
if (shtns->idct != NULL) fftw_destroy_plan(shtns->idct);
dims.n = NLAT; dims.is = 2; dims.os = 2; // real and imaginary part.
hdims[0].n = MTR_DCT+1; hdims[0].is = 2*NLAT; hdims[0].os = 2*NLAT;
hdims[1].n = 2; hdims[1].is = 1; hdims[1].os = 1;
r2r_kind = FFTW_REDFT01;
shtns->idct = fftw_plan_guru_r2r(1, &dims, 2, hdims, Sh, Sh, &r2r_kind, shtns->fftw_plan_mode);
} else { // NPHI == 1
if (shtns->idct == NULL) {
r2r_kind = FFTW_REDFT01;
shtns->idct = fftw_plan_many_r2r(1, &ndct, 1, Sh, &ndct, 1, NLAT, Sh, &ndct, 1, NLAT, &r2r_kind, shtns->fftw_plan_mode);
}
}
VFREE(Sh);
if (shtns->idct == NULL) return 0; // idct planning failed.
#if SHT_VERBOSE > 2
if (verbose>2) {
printf(" *** idct plan :\n"); fftw_print_plan(shtns->idct); printf("\n");
}
#endif
return 1; // success.
}
/// \internal SET MTR_DCT and updates fftw_plan for DCT's
static int Set_MTR_DCT(shtns_cfg shtns, int m)
{
if ((shtns->zlm_dct0 == NULL)||(m == MTR_DCT)) return MTR_DCT;
if ( m < 0 ) { // don't use dct
shtns->mtr_dct = -1;
} else {
if (m>MMAX) m=MMAX;
shtns->mtr_dct = m;
if (planDCT(shtns) == 0)
shtns->mtr_dct = -1; // failure
}
return MTR_DCT;
}
/// \internal returns the m-truncation of DCT part of synthesis
static int Get_MTR_DCT(shtns_cfg shtns) {
return MTR_DCT;
}
#endif /* SHTNS_DCT */
/// \internal Sets the value tm[im] used for polar optimiation on-the-fly.
static void PolarOptimize(shtns_cfg shtns, double eps)
{
int im, m, l, it;
double v;
double y[LMAX+1];
for (im=0;im<=MMAX;im++) shtns->tm[im] = 0;
if (eps > 0.0) {
for (im=1;im<=MMAX;im++) {
m = im*MRES;
it = shtns->tm[im-1] -1; // tm[im] is monotonic.
do {
it++;
legendre_sphPlm_array(shtns, LMAX, im, shtns->ct[it], y+m);
v = 0.0;
for (l=m; l<=LMAX; l++) {
double ya = fabs(y[l]);
if ( v < ya ) v = ya;
}
} while (v < eps);
shtns->tm[im] = it;
}
#if SHT_VERBOSE > 0
if (verbose) printf(" + polar optimization threshold = %.1e\n",eps);
#endif
#if SHT_VERBOSE > 1
if (verbose>1) {
printf(" tm[im]=");
for (im=0;im<=MMAX;im++)
printf(" %d",shtns->tm[im]);
printf("\n");
}
#endif
}
}
#ifdef SHTNS_MEM
/// \internal Perform some optimization on the SHT matrices.
static void OptimizeMatrices(shtns_cfg shtns, double eps)
{
unsigned short *tm;
double **ylm, **zlm;
struct DtDp** dylm;
struct DtDp** dzlm;
int im,m,l,it;
int vector = (shtns->dylm != NULL);
tm = shtns->tm;
ylm = shtns->ylm; dylm = shtns->dylm;
zlm = shtns->zlm; dzlm = shtns->dzlm;
for (im=0;im<=MMAX;im++) tm[im] = 0;
/// POLAR OPTIMIZATION : analyzing coefficients, some can be safely neglected.
if (eps > 0.0) {
for (im=1;im<=MMAX;im++) {
m = im*MRES;
tm[im] = NLAT_2;
for (l=m;l<=LMAX;l++) {
it = tm[im-1]; // tm[im] is monotonic.
while( fabs(ylm[im][it*(LMAX-m+1) + (l-m)]) < eps ) { it++; }
if (tm[im] > it) tm[im] = it;
}
}
#if SHT_VERBOSE > 0
if (verbose) printf(" + polar optimization threshold = %.1e\n",eps);
#endif
#if SHT_VERBOSE > 1
if (verbose>1) {
printf(" tm[im]=");
for (im=0;im<=MMAX;im++)
printf(" %d",tm[im]);
printf("\n");
}
#endif
for (im=1; im<=MMAX; im++) { // im >= 1
if (tm[im] > 0) { // we can remove the data corresponding to polar values.
m = im*MRES;
ylm[im] += tm[im]*(LMAX-m+1); // shift pointers (still one block for each m)
if (vector) dylm[im] += tm[im]*(LMAX-m+1);
if (zlm[0] != NULL) {
for (l=m; l<LMAX; l+=2) {
for (it=0; it<NLAT_2-tm[im]; it++) { // copy data to avoid cache misses.
zlm[im][(l-m)*(NLAT_2-tm[im]) + it*2] = zlm[im][(l-m)*NLAT_2 + (it+tm[im])*2];
zlm[im][(l-m)*(NLAT_2-tm[im]) + it*2+1] = zlm[im][(l-m)*NLAT_2 + (it+tm[im])*2+1];
if (vector) {
dzlm[im][(l-m)*(NLAT_2-tm[im]) + it*2].t = dzlm[im][(l-m)*NLAT_2 + (it+tm[im])*2].t;
dzlm[im][(l-m)*(NLAT_2-tm[im]) + it*2].p = dzlm[im][(l-m)*NLAT_2 + (it+tm[im])*2].p;
dzlm[im][(l-m)*(NLAT_2-tm[im]) + it*2+1].t = dzlm[im][(l-m)*NLAT_2 + (it+tm[im])*2+1].t;
dzlm[im][(l-m)*(NLAT_2-tm[im]) + it*2+1].p = dzlm[im][(l-m)*NLAT_2 + (it+tm[im])*2+1].p;
}
}
}
if (l==LMAX) {
for (it=0; it<NLAT_2-tm[im]; it++) {
zlm[im][(l-m)*(NLAT_2-tm[im]) + it] = zlm[im][(l-m)*NLAT_2 + (it+tm[im])];
if (vector) {
dzlm[im][(l-m)*(NLAT_2-tm[im]) + it].t = dzlm[im][(l-m)*NLAT_2 + (it+tm[im])].t;
dzlm[im][(l-m)*(NLAT_2-tm[im]) + it].p = dzlm[im][(l-m)*NLAT_2 + (it+tm[im])].p;
}
}
}
}
}
}
}
/// Compression of dzlm for m=0, as .p is 0
if ((vector) && (dzlm[0] != NULL)) { // for sht_reg_poles there is no dzlm defined.
im=0; m=0;
double* yg = (double *) dzlm[im];
for (l=1; l<LMAX; l+=2) { // l=0 is zero, so we start at l=1.
for (it=0; it<NLAT_2; it++) {
yg[(l-1)*NLAT_2 + it*2] = dzlm[im][(l-1)*NLAT_2 + it*2].t; // l
yg[(l-1)*NLAT_2 + it*2+1] = dzlm[im][(l-1)*NLAT_2 + it*2+1].t; // l+1
}
}
if (l==LMAX) { // last l is stored right away, without interleaving.
for (it=0; it<NLAT_2; it++) {
yg[(l-1)*NLAT_2 + it] = dzlm[im][(l-1)*NLAT_2 + it].t; // l (odd)
}
}
}
if ((zlm[0] != NULL) && (NLAT_2 & 1)) {
zlm[0][NLAT_2] = 0.0; // take care to write 0.0 for this sse2 padding value.
if ( (MMAX==0) && (!(LMAX & 1)) ) { // NLAT_2 odd + LMAX even
zlm[0][(LMAX+1)*NLAT_2 +1] = 0.0; // overflow for im=0
zlm[0][(LMAX+1)*NLAT_2 +2] = 0.0;
}
}
}
// how to access the ylm matrix for im=0
#define YL0(it, l) ( shtns->ylm[0][ (it)*(((LMAX+2)>>1)*2) + (l) ] )
#define DYL0(it, l) ( ((double*)(shtns->dylm[0]))[ (it)*(((LMAX+1)>>1)*2) + (l-1) ] )
#define YLM(it, l, im) ( (im==0) ? YL0(it,l) : shtns->ylm[im][(it)*(LMAX-(im)*MRES+1) + ((l)-(im)*MRES)] )
#define DTYLM(it, l, im) ( (im==0) ? ( (l==0) ? 0.0 : DYL0(it,l) ) : shtns->dylm[im][(it)*(LMAX-(im)*MRES+1) + ((l)-(im)*MRES)].t )
#define DPYLM(it, l, im) ( (im==0) ? 0.0 : shtns->dylm[im][(it)*(LMAX-(im)*MRES+1) + ((l)-(im)*MRES)].p )
/// \internal Precompute the matrix for SH synthesis.
static void init_SH_synth(shtns_cfg shtns)
{
double *yl, *dyl; // temp storage for derivative for legendre function values.
long int it,im,m,l;
double *ct = shtns->ct;
double *st = shtns->st;
int vector = (shtns->dylm != NULL);
yl = (double*) malloc( 2*sizeof(double) *(LMAX+1) );
dyl = yl + (LMAX+1);
{ im=0; m=0;
for (it=0; it<NLAT_2; it++) {
legendre_sphPlm_deriv_array_hp(shtns, LMAX, im, ct[it], st[it], yl, dyl); // fixed im legendre functions lookup table.
for (l=0; l<=LMAX; l++) YL0(it, l) = yl[l];
for (l=LMAX+1; l<=LMAX+3; l++) YL0(it, l) = 0.0; // allow overflow.
if (vector) {
for (l=1; l<=LMAX; l++) DYL0(it, l) = dyl[l];
for (l=LMAX+1; l<=LMAX+2; l++) DYL0(it, l) = 0.0; // allow overflow.
}
}
}
for (im=1; im<=MMAX; im++) {
double *ylm = shtns->ylm[im];
struct DtDp* dylm = vector ? shtns->dylm[im] : NULL;
m = im*MRES;
for (it=0; it<NLAT_2; it++) {
legendre_sphPlm_deriv_array_hp(shtns, LMAX, im, ct[it], st[it], yl, dyl); // fixed im legendre functions lookup table.
for (l=m; l<=LMAX; l++) {
ylm[it*(LMAX-m+1) + (l-m)] = yl[l-m] * st[it];
if (vector) {
dylm[it*(LMAX-m+1) + (l-m)].t = dyl[l-m];
dylm[it*(LMAX-m+1) + (l-m)].p = yl[l-m] *m; // 1/sint(t) dYlm/dphi
}
}
}
}
free(yl);
}
/// \internal Precompute matrices for SH synthesis and analysis, on a Gauss-Legendre grid.
static void init_SH_gauss(shtns_cfg shtns)
{
long int it,im,m,l;
int vector = (shtns->dylm != NULL);
init_SH_synth(shtns);
// for analysis (decomposition, direct transform) : transpose and multiply by gauss weight and other normalizations.
// interleave l and l+1 : this stores data in the way it will be read.
double **zlm = shtns->zlm;
struct DtDp** dzlm = shtns->dzlm;
for (im=0; im<=MMAX; im++) {
m = im*MRES;
long int talign = 0;
for (it=0;it<NLAT_2;it++) {
double norm = shtns->wg[it];
if ( (m>0) && (shtns->norm & SHT_REAL_NORM) ) norm *= 2; // "Real" norm : zlm must be doubled for m>0
long int l0 = m;
if (m==0) {
zlm[im][it] = YL0(it, 0) * norm;
// les derivees sont nulles pour l=0
l0++;
talign = (NLAT_2&1);
}
for (l=l0; l<LMAX; l+=2) {
double nz0 = norm; double nz1 = norm;
if (SHT_NORM == sht_schmidt) {
nz0 *= (2*l+1); nz1 *= (2*l+3);
}
zlm[im][(l-m)*NLAT_2 + it*2 +talign] = YLM(it, l, im) * nz0;
zlm[im][(l-m)*NLAT_2 + it*2 +1 +talign] = YLM(it, l+1, im) * nz1;
if (vector) {
nz0 *= shtns->l_2[l]; nz1 *= shtns->l_2[l+1];
dzlm[im][(l-l0)*NLAT_2 + it*2].t = DTYLM(it, l, im) * nz0;
dzlm[im][(l-l0)*NLAT_2 + it*2].p = DPYLM(it, l, im) * nz0;
dzlm[im][(l-l0)*NLAT_2 + it*2+1].t = DTYLM(it, l+1, im) * nz1;
dzlm[im][(l-l0)*NLAT_2 + it*2+1].p = DPYLM(it, l+1, im) * nz1;
}
}
if (l==LMAX) { // last l is stored right away, without interleaving.
double nz0 = norm;
if (SHT_NORM == sht_schmidt) nz0 *= (2*l+1);
zlm[im][(l-m)*NLAT_2 + it +talign] = YLM(it, l, im) * nz0;
if (vector) {
nz0 *= shtns->l_2[l];
dzlm[im][(l-l0)*NLAT_2 + it].t = DTYLM(it, l, im) * nz0;
dzlm[im][(l-l0)*NLAT_2 + it].p = DPYLM(it, l, im) * nz0;
}
}
}
}
}
#endif
#ifdef SHTNS_DCT
static void init_SH_dct_m(shtns_cfg shtns, double* is1, fftw_plan dct, fftw_plan idct, int analysis, const int m0, const int mstep)
{
double *yk, *yk0, *dyk0, *yg; // temp storage
struct DtDp *dyg, *dyk;
int it,im,m,l;
double Z[2*NLAT_2] SSE;
double dZt[2*NLAT_2] SSE;
double dZp[2*NLAT_2] SSE; // equally spaced theta points.
double *st = shtns->st;
double *st_1 = shtns->st_1;
const int vector = (shtns->dylm != NULL);
const int KMAX = LMAX+1;
real iylm_fft_norm = 1.0; // FFT/SHT normalization for zlm (4pi normalized)
if ((SHT_NORM != sht_fourpi)&&(SHT_NORM != sht_schmidt)) iylm_fft_norm = 4*M_PIl; // FFT/SHT normalization for zlm (orthonormalized)
iylm_fft_norm /= (2*NPHI*NLAT_2);
// Even/Odd symmetry : ylm is even or odd across equator, as l-m is even or odd => only NLAT_2 points required.
// temp memory for ykm_dct.
yk = (double *) malloc( sizeof(double) * (KMAX+1)*(LMAX+1) );
dyk = (struct DtDp *) malloc( sizeof(struct DtDp)* (KMAX+1)*(LMAX+1) );
if ((m0==0)&&(analysis)) {
yk0 = (double *) malloc( sizeof(double) * (LMAX/2+1)*(2*NLAT_2) * 2 ); // temp for zlm_dct0
dyk0 = yk0 + (LMAX/2+1)*(2*NLAT_2);
}
for (im=m0; im<=MMAX; im+=mstep) {
m = im*MRES;
// go to DCT space
for (it=0;it<=KMAX;it+=2) {
for(l=m; l<=LMAX; l++) {
yk[(it/2)*(LMAX+1-m) + (l-m)] = 0.0;
dyk[(it/2)*(LMAX+1-m) + (l-m)].t = 0.0;
dyk[(it/2)*(LMAX+1-m) + (l-m)].p = 0.0;
}
}
for (l=m; l<=LMAX; l++) {
if (m & 1) { // m odd
for (it=0; it<NLAT_2; it++) {
Z[it] = YLM(it, l, im) * st[it]; // P[l+1](x) *st
if (vector) {
dZt[it] = DTYLM(it, l, im); // P[l](x) *1
dZp[it] = DPYLM(it, l, im); // P[l-1](x) *1
}
}
} else { // m even
for (it=0; it<NLAT_2; it++) {
Z[it] = YLM(it, l, im); // P[l](x) *1
if (vector) {
dZt[it] = DTYLM(it, l, im) *st[it]; // P[l+1](x) *st
dZp[it] = YLM(it, l, im) * m; // P[l](x) *st
}
}
}
if ((l-m)&1) { // odd
for (it=NLAT_2; it<2*NLAT_2; it++) {
Z[it] = - Z[2*NLAT_2-it-1]; // reconstruct even/odd part
dZt[it] = dZt[2*NLAT_2-it-1];
dZp[it] = - dZp[2*NLAT_2-it-1];
}
} else { // even
for (it=NLAT_2; it<2*NLAT_2; it++) {
Z[it] = Z[2*NLAT_2-it-1]; // reconstruct even/odd part
dZt[it] = - dZt[2*NLAT_2-it-1];
dZp[it] = dZp[2*NLAT_2-it-1];
}
}
fftw_execute_r2r(dct, Z, Z);
fftw_execute_r2r(dct, dZt, dZt);
fftw_execute_r2r(dct, dZp, dZp);
#if SHT_VERBOSE > 1
if ((LMAX <= 12) && (verbose>1))
#pragma omp critical
{
printf("\nl=%d, m=%d ::\t", l,m);
for(it=0;it<2*NLAT_2;it++) printf("%e ",Z[it]/(2*NLAT));
printf("\n dYt ::\t");
for(it=0;it<2*NLAT_2;it++) printf("%e ",dZt[it]/(2*NLAT));
printf("\n dYp ::\t");
for(it=0;it<2*NLAT_2;it++) printf("%e ",dZp[it]/(2*NLAT));
}
#endif
for (it=(l-m)&1; it<=l+1; it+=2) {
yk[(it/2)*(LMAX+1-m) + (l-m)] = Z[it]/(2*NLAT); // and transpose
dyk[(it/2)*(LMAX+1-m) + (l-m)].p = dZp[it]/(2*NLAT);
}
for (it=(l+1-m)&1; it<=l+1; it+=2) {
dyk[(it/2)*(LMAX+1-m) + (l-m)].t = dZt[it]/(2*NLAT);
}
}
/* compute analysis coefficients (fast way)
* Wklm = int(Tk*Ylm) = int(Tk.sum(i,a_ilm*Ti)) = sum(i, a_ilm* int(Tk*Ti)) = sum(i, a_ilm*Jik)
* with Jik = int(Tk*Ti) = 1/(1-(k-i)^2) + 1/(1-(k+i)^2)
*/
if (analysis) {
#if SHT_VERBOSE > 0
if ((LMAX>126)&&(m0==0)&&(verbose)) { // only one thread prints this message.
printf("computing weights m=%d\r",m); fflush(stdout);
}
#endif
for (l=m; l<=LMAX; l++) {
unsigned k0,k1, k,i,d;
double Jik0, Jik1, yy, dyp, dyt;
double lnorm = iylm_fft_norm;
if (SHT_NORM == sht_schmidt) lnorm *= (2*l+1); // Schmidt semi-normalization
if ( (m>0) && (shtns->norm & SHT_REAL_NORM) ) lnorm *= 2; // "real" norm : zlm must be doubled for m>0
k0 = (l-m)&1; k1 = 1-k0;
for(k=0; k<NLAT; k++) { Z[k] = 0.0; dZt[k] = 0.0; dZp[k] = 0.0; }
for (i=0; i<=(l+1)/2; i++) {
yy = yk[i*(LMAX+1-m) + (l-m)] * lnorm;
dyp = dyk[i*(LMAX+1-m) + (l-m)].p * lnorm/(l*(l+1));
dyt = dyk[i*(LMAX+1-m) + (l-m)].t * lnorm/(l*(l+1));
if (i+k0==0) { yy*=0.5; dyp*=0.5; }
if (i+k1==0) dyt*=0.5;
for (k=0; k<NLAT_2; k++) {
d = (k<i) ? i-k : k-i;
Jik0 = is1[(i+k0)+k] + is1[d];
Jik1 = is1[(i+k1)+k] + is1[d];
Z[2*k+k0] += yy * Jik0;
dZt[2*k+k1] += dyt * Jik1;
if (m&1) dZp[2*k+k0] += dyp * Jik0;
}
}
#if SHT_VERBOSE > 1
if ((LMAX <= 12)&&(verbose>1))
#pragma omp critical
{
printf("\nl=%d, m=%d ::\t",l,m);
for (k=0; k<(2*NLAT_2); k++) printf("%f ",Z[k]);
printf("\n dZt ::\t");
for (k=0; k<(2*NLAT_2); k++) printf("%f ",dZt[k]);
if (m&1) {
printf("\n dZp ::\t");
for (k=0; k<(2*NLAT_2); k++) printf("%f ",dZp[k]);
}
}
#endif
if (m == 0) { // we store zlm in dct space for m=0
if (k0==0) {
yk0[((l-m)>>1)*(2*NLAT_2)] = Z[0]*0.5; // store zlm_dct (k=0)
for (k=1; k<(2*NLAT_2); k++) yk0[((l-m)>>1)*(2*NLAT_2) +k] = 0.0; // zero out.
k0=2;
}
for (k=k0; k<(2*NLAT_2); k+=2)
yk0[((l-m)>>1)*(2*NLAT_2) +k] = Z[k]; // store zlm_dct
if (l>0) {
if (k1==0) {
dyk0[((l-1-m)>>1)*(2*NLAT_2)] = dZt[0]*0.5; // store dzlm_dct (k=0)
for (k=1; k<(2*NLAT_2); k++) dyk0[((l-1-m)>>1)*(2*NLAT_2) +k] = 0.0; // zero out.
k1=2;
}
for (k=k1; k<(2*NLAT_2); k+=2)
dyk0[((l-1-m)>>1)*(2*NLAT_2) +k] = dZt[k]; // store dzlm_dct
}
}
fftw_execute_r2r(idct, Z, Z); fftw_execute_r2r(idct, dZt, dZt);
if (m == 0) {
for (it=0; it<NLAT; it++) { dZp[it] = 0.0; dZt[it] *= st_1[it]; }
} else if (m & 1) { // m odd
fftw_execute_r2r(idct, dZp, dZp);
for (it=0; it<NLAT; it++) { Z[it] *= st_1[it]; }
} else { // m even
for (it=0; it<NLAT; it++) { dZp[it] = Z[it]*m/(l*(l+1)*st[it]); dZt[it] *= st_1[it]; }
}
long int l0 = (m==0) ? 1 : m;
long int talign = (m==0)*(NLAT_2 & 1);
long int sk = (l-l0)&1;
if (l==0) {
for (it=0; it<NLAT_2; it++) {
shtns->zlm[im][it] = Z[it];
}
} else if ((sk == 0)&&(l == LMAX)) {
for (it=0; it<NLAT_2; it++) {
shtns->zlm[im][(l-m)*NLAT_2 + it + talign] = Z[it];
if (vector) {
shtns->dzlm[im][(l-l0)*NLAT_2 + it].p = dZp[it];
shtns->dzlm[im][(l-l0)*NLAT_2 + it].t = dZt[it];
}
}
} else {
for (it=0; it<NLAT_2; it++) {
shtns->zlm[im][(l-m-sk)*NLAT_2 + it*2 +sk + talign] = Z[it];
if (vector) {
shtns->dzlm[im][(l-l0-sk)*NLAT_2 + it*2 +sk].p = dZp[it];
shtns->dzlm[im][(l-l0-sk)*NLAT_2 + it*2 +sk].t = dZt[it];
}
}
}
}
}
// Compact the coefficients for improved cache efficiency.
yg = shtns->ykm_dct[im];
for (it=0; it<= KMAX; it+=2) {
l = (it < m) ? m : it-(m&1);
while (l<=LMAX) {
yg[0] = yk[(it/2)*(LMAX+1-m) + (l-m)];
l++; yg++;
}
if ((m==0) && ((LMAX & 1) == 0)) { yg[0] = 0; yg++; } // SSE2 padding.
}
if (MMAX==0) for (int j=0; j<3; j++) yg[j] = 0; // allow some overflow.
if (vector) {
dyg = shtns->dykm_dct[im];
for (it=0; it<= KMAX; it+=2) {
l = (it-2 < m) ? m : it-2+(m&1);
while (l<=LMAX) {
dyg[0].t = dyk[(it/2)*(LMAX+1-m) + (l-m)].t;
dyg[0].p = dyk[(it/2)*(LMAX+1-m) + (l-m)].p;
l++; dyg++;
}
}
if (im == 0) { // compact and reorder m=0 dylm because .p = 0 :
dyg = shtns->dykm_dct[im];
yg = (double *) shtns->dykm_dct[im];
for (it=0; it<= KMAX; it+=2) {
dyg++;
for (l=it-1; l<=LMAX; l++) {
if (l>0) {
yg[0] = dyg[0].t;
yg++; dyg++;
}
}
if (LMAX&1) { // padding for SSE2 alignement.
yg[0] = 0.0; yg++;
}
}
}
}
}
// compact yk to zlm_dct0
if ((m0==0)&&(analysis)) {
long int klim = (LMAX * SHT_NL_ORDER) + 2; // max k needed for nl-terms...
klim = (klim/2)*2; // must be even...
if (klim > 2*NLAT_2) klim = 2*NLAT_2; // but no more than 2*NLAT_2.
shtns->klim = klim; // store for use in codelets.
yg = shtns->zlm_dct0;
for (l=0; l<=LMAX; l+=2) {
for (it=l; it<klim; it++) { // for m=0, zl coeff with i<l are zeros.
*yg = yk0[it];
yg++;
}
yk0 += 2*NLAT_2;
}
if (vector) {
yg = shtns->dzlm_dct0;
for (l=1; l<=LMAX; l+=2) {
for (it=l-1; it<klim; it++) { // for m=0, dzl coeff with i<l-1 are zeros.
*yg = dyk0[it];
yg++;
}
dyk0 += 2*NLAT_2;
}
}
free(yk0 - (2*NLAT_2)*(LMAX/2+1));
}
free(dyk); free(yk);
}
/// \internal Computes the matrices required for SH transform on a regular grid (with or without DCT).
/// \param analysis : 0 => synthesis only.
static void init_SH_dct(shtns_cfg shtns, int analysis)
{
fftw_plan dct, idct;
long int it,im,m,l;
long int sk, dsk;
double Z[2*NLAT_2] SSE;
double is1[NLAT]; // tabulate values for integrals.
const long int marray_size = sizeof(void*)*(MMAX+1) + (MIN_ALIGNMENT-1);
const int vector = (shtns->dylm != NULL);
const int KMAX = LMAX+1;
for(im=0, sk=0, dsk=0; im<=MMAX; im++) { // how much memory to allocate for ykm_dct ?
m = im*MRES;
for (it=0; it<= KMAX; it+=2) {
l = (it < m) ? m : it-(m&1);
sk += LMAX+1 - l;
if ((m==0) && ((LMAX & 1) ==0)) sk++; // SSE padding for m=0
}
for (it=0; it<= KMAX; it+=2) {
l = (it-2 < m) ? m : it-2+(m&1);
dsk += LMAX+1 - l;
}
}
if (MMAX == 0) sk+=3; // allow some overflow.
for (l=0, it=0; l<=LMAX; l+=2) // how much memory for zlm_dct0 ?
it += (2*NLAT_2 -l);
for (l=1, im=0; l<=LMAX; l+=2) // how much memory for dzlm_dct0 ?
im += (2*NLAT_2 -l+1);
#if SHT_VERBOSE > 1
if (verbose>1) printf(" Memory used for Ykm_dct matrices = %.3f Mb\n",sizeof(double)*(sk + 2.*dsk + it)/(1024.*1024.));
#endif
shtns->ykm_dct = (double **) malloc( marray_size + sizeof(double)*sk );
shtns->ykm_dct[0] = (double *) PTR_ALIGN( shtns->ykm_dct + (MMAX+1) );
if (vector) {
shtns->dykm_dct = (struct DtDp **) malloc( marray_size + sizeof(struct DtDp)*dsk );
shtns->dykm_dct[0] = (struct DtDp *) PTR_ALIGN( shtns->dykm_dct + (MMAX+1) );
}
shtns->zlm_dct0 = (double *) VMALLOC( sizeof(double)* it );
if (vector) {
shtns->dzlm_dct0 = (double *) VMALLOC( sizeof(double)* im );
}
for (im=0; im<MMAX; im++) {
m = im*MRES;
for (it=0, sk=0; it<= KMAX; it+=2) {
l = (it < m) ? m : it-(m&1);
sk += LMAX+1 - l;
if ((m==0) && ((LMAX & 1) ==0)) sk++; // SSE padding for m=0
}
for (it=0, dsk=0; it<= KMAX; it+=2) {
l = (it-2 < m) ? m : it-2+(m&1);
dsk += LMAX+1 - l;
}
shtns->ykm_dct[im+1] = shtns->ykm_dct[im] + sk;
if (vector) shtns->dykm_dct[im+1] = shtns->dykm_dct[im] + dsk;
}
#if SHT_VERBOSE > 1
ticks tik0, tik1;
tik0 = getticks();
#endif
#ifdef OMP_FFTW
fftw_plan_with_nthreads(1);
#endif
dct = fftw_plan_r2r_1d( 2*NLAT_2, Z, Z, FFTW_REDFT10, FFTW_MEASURE ); // quick and dirty dct.
idct = fftw_plan_r2r_1d( 2*NLAT_2, Z, Z, FFTW_REDFT01, FFTW_MEASURE ); // quick and dirty idct.
init_SH_synth(shtns);
// precomputation for scalar product of Chebychev polynomials.
for(it=0; it<NLAT; it++)
is1[it] = 1./(1. - 4.*it*it);
#ifdef _OPENMP
#pragma omp parallel
{
int n=omp_get_num_threads();
int k=omp_get_thread_num();
init_SH_dct_m(shtns, is1, dct, idct, analysis, k, n);
}
#else
init_SH_dct_m(shtns, is1, dct, idct, analysis, 0, 1);
#endif
#if SHT_VERBOSE > 1
tik1 = getticks();
if (verbose>1) printf("\n ticks : %.3f\n", elapsed(tik1,tik0)/(NLM*NLAT*(MMAX+1)));
#endif
fftw_destroy_plan(idct); fftw_destroy_plan(dct);
}
#endif /* SHTNS_DCT */
/// \internal Generate a gauss grid (including weights)
static void grid_gauss(shtns_cfg shtns, double latdir)
{
long int it;
real iylm_fft_norm;
real xg[NLAT], wgl[NLAT]; // gauss points and weights.
const int overflow = 8*VSIZE2-1;
shtns->grid = GRID_GAUSS;
shtns->wg = VMALLOC((NLAT_2 +overflow) * sizeof(double)); // gauss weights, double precision.
iylm_fft_norm = 1.0; // FFT/SHT normalization for zlm (4pi normalized)
if ((SHT_NORM != sht_fourpi)&&(SHT_NORM != sht_schmidt)) iylm_fft_norm = 4*M_PIl; // FFT/SHT normalization for zlm (orthonormalized)
iylm_fft_norm /= (2*NPHI);
#if SHT_VERBOSE > 0
if (verbose) {
printf(" => using Gauss nodes\n");
if (2*NLAT <= (SHT_NL_ORDER +1)*LMAX) printf(" !! Warning : Gauss-Legendre anti-aliasing condition 2*Nlat > %d*Lmax is not met.\n",SHT_NL_ORDER+1);
}
#endif
gauss_nodes(xg,wgl,NLAT); // generate gauss nodes and weights : ct = ]1,-1[ = cos(theta)
for (it=0; it<NLAT; it++) {
shtns->ct[it] = latdir * xg[it];
shtns->st[it] = SQRT((1.-xg[it])*(1.+xg[it]));
shtns->st_1[it] = 1.0/SQRT((1.-xg[it])*(1.+xg[it]));
}
for (it=0; it<NLAT_2; it++)
shtns->wg[it] = wgl[it]*iylm_fft_norm; // faster double-precision computations.
if (NLAT & 1) { // odd NLAT : adjust weigth of middle point.
shtns->wg[NLAT_2-1] *= 0.5;
}
for (it=NLAT_2; it < NLAT_2 +overflow; it++) shtns->wg[it] = 0.0; // padding for multi-way algorithm.
#if SHT_VERBOSE > 1
if (verbose>1) {
printf(" NLAT=%d, NLAT_2=%d\n",NLAT,NLAT_2);
// TEST if gauss points are ok.
double tmax = 0.0;
for (it = 0; it<NLAT_2; it++) {
double t = legendre_Pl(NLAT, shtns->ct[it]);
if (t>tmax) tmax = t;
// printf("i=%d, x=%12.12g, p=%12.12g\n",it,ct[it],t);
}
printf(" max zero at Gauss nodes for Pl[l=NLAT] : %g\n",tmax);
if (NLAT_2 < 100) {
printf(" Gauss nodes :");
for (it=0;it<NLAT_2; it++)
printf(" %g",shtns->ct[it]);
printf("\n");
}
}
#endif
}
#ifdef SHTNS_DCT
/// \internal Generate an equi-spaced theta grid (Chebychev points, excluding poles) for Féjer-DCT SHT.
static void grid_dct(shtns_cfg shtns, double latdir)
{
long int it;
shtns->grid = GRID_REGULAR;
#if SHT_VERBOSE > 0
if (verbose) {
printf(" => using equaly spaced nodes with DCT acceleration\n");
if (NLAT <= SHT_NL_ORDER *LMAX) printf(" !! Warning : DCT anti-aliasing condition Nlat > %d*Lmax is not met.\n",SHT_NL_ORDER);
if (NLAT != fft_int(NLAT,7)) printf(" !! Warning : Nlat is not optimal for FFTW !\n");
}
#endif
if (NLAT & 1) shtns_runerr("NLAT must be even (DCT)");
if (NLAT <= LMAX+1) shtns_runerr("NLAT should be at least LMAX+2 (DCT)");
for (it=0; it<NLAT; it++) { // Chebychev points : equaly spaced but skipping poles.
real th = M_PIl; th = (th*(2*it+1))/(2*NLAT);
shtns->ct[it] = latdir * COS(th);
shtns->st[it] = SIN(th);
shtns->st_1[it] = 1.0/SIN(th);
}
#if SHT_VERBOSE > 1
if (verbose>1) {
printf(" NLAT=%d, NLAT_2=%d\n",NLAT,NLAT_2);
double tmax = 0.0;
for (it=0;it<NLAT_2; it++) {
double ct = shtns->ct[it]; double st = shtns->st[it];
double t = fabs((ct*ct + st*st) -1.0);
if (t > tmax) tmax=t;
}
printf(" max st^2 + ct^2 -1 = %g\n",tmax);
if (NLAT_2 < 100) {
printf(" DCT nodes :");
for (it=0; it<NLAT_2; it++)
printf(" %g",shtns->ct[it]);
printf("\n");
}
}
#endif
}
#endif /* SHTNS_DCT */
/// \internal Generate an equi-spaced theta grid including the poles, for synthesis only.
static void grid_equal_polar(shtns_cfg shtns, double latdir)
{
long int j;
shtns->grid = GRID_POLES;
#if SHT_VERBOSE > 0
if (verbose) printf(" => using Equaly Spaced Nodes including poles\n");
#endif
// cos theta of latidunal points (equaly spaced in theta)
double f = M_PIl/(NLAT-1);
for (j=0; j<NLAT; j++) {
shtns->ct[j] = latdir * cos(f*j);
shtns->st[j] = sin(f*j);
shtns->st_1[j] = 1.0/sin(f*j);
}
#if SHT_VERBOSE > 0
if (verbose) printf(" !! Warning : only synthesis (inverse transform) supported for this grid !\n");
#endif
}
/* TEST AND TIMING FUNCTIONS */
/// \internal return the max error for a back-and-forth SHT transform.
/// this function is used to internally measure the accuracy.
double SHT_error(shtns_cfg shtns, int vector)
{
cplx *Tlm0=0, *Slm0=0, *Tlm=0, *Slm=0;
double *Sh=0, *Th=0;
double t, tmax, n2, err;
long int i, jj, nlm_cplx;
srand( time(NULL) ); // init random numbers.
Slm0 = (cplx *) VMALLOC(sizeof(cplx)* NLM);
Slm = (cplx *) VMALLOC(sizeof(cplx)* NLM);
Sh = (double *) VMALLOC( NSPAT_ALLOC(shtns) * sizeof(double) );
if ((Sh==0) || (Slm==0) || (Slm0==0)) shtns_runerr("not enough memory.");
if (vector) {
Tlm0 = (cplx *) VMALLOC(sizeof(cplx)* NLM);
Tlm = (cplx *) VMALLOC(sizeof(cplx)* NLM);
Th = (double *) VMALLOC( NSPAT_ALLOC(shtns) * sizeof(double) );
if ((Th==0) || (Tlm==0) || (Tlm0==0)) vector=0;
}
// m = nphi/2 is also real if nphi is even.
nlm_cplx = ( MMAX*2 == NPHI ) ? LiM(shtns, MRES*MMAX,MMAX) : NLM;
t = 1.0 / (RAND_MAX/2);
for (i=0; i<NLM; i++) {
if ((i<=LMAX)||(i>=nlm_cplx)) { // m=0 or m*2=nphi : real random data
Slm0[i] = t*((double) (rand() - RAND_MAX/2));
if (vector) Tlm0[i] = t*((double) (rand() - RAND_MAX/2));
} else { // m>0 : complex random data
Slm0[i] = t*((double) (rand() - RAND_MAX/2)) + I*t*((double) (rand() - RAND_MAX/2));
if (vector) Tlm0[i] = t*((double) (rand() - RAND_MAX/2)) + I*t*((double) (rand() - RAND_MAX/2));
}
}
SH_to_spat(shtns, Slm0,Sh); // scalar SHT
spat_to_SH(shtns, Sh, Slm);
for (i=0, tmax=0., n2=0., jj=0; i<NLM; i++) { // compute error
t = cabs(Slm[i] - Slm0[i]);
n2 += t*t;
if (t>tmax) { tmax = t; jj = i; }
}
err = tmax;
#if SHT_VERBOSE > 1
if (verbose>1) printf(" scalar SH - poloidal rms error = %.3g max error = %.3g for l=%hu,lm=%ld\n",sqrt(n2/NLM),tmax,shtns->li[jj],jj);
#endif
if (vector) {
Slm0[0] = 0.0; Tlm0[0] = 0.0; // l=0, m=0 n'a pas de signification sph/tor
SHsphtor_to_spat(shtns, Slm0, Tlm0, Sh, Th); // vector SHT
spat_to_SHsphtor(shtns, Sh, Th, Slm, Tlm);
for (i=0, tmax=0., n2=0., jj=0; i<NLM; i++) { // compute error
t = cabs(Slm[i] - Slm0[i]);
n2 += t*t;
if (t>tmax) { tmax = t; jj = i; }
}
if (tmax > err) err = tmax;
#if SHT_VERBOSE > 1
if (verbose>1) printf(" vector SH - spheroidal rms error = %.3g max error = %.3g for l=%hu,lm=%ld\n",sqrt(n2/NLM),tmax,shtns->li[jj],jj);
#endif
for (i=0, tmax=0., n2=0., jj=0; i<NLM; i++) { // compute error
t = cabs(Tlm[i] - Tlm0[i]);
n2 += t*t;
if (t>tmax) { tmax = t; jj = i; }
}
if (tmax > err) err = tmax;
#if SHT_VERBOSE > 1
if (verbose>1) printf(" - toroidal rms error = %.3g max error = %.3g for l=%hu,lm=%ld\n",sqrt(n2/NLM),tmax,shtns->li[jj],jj);
#endif
}
if (Th) VFREE(Th); if (Tlm) VFREE(Tlm); if (Tlm0) VFREE(Tlm0);
VFREE(Sh); VFREE(Slm); VFREE(Slm0);
return(err); // return max error.
}
#if SHT_VERBOSE == 1
#define PRINT_DOT if (verbose>=1) { printf("."); fflush(stdout); }
#else
#define PRINT_DOT (0);
#endif
/// \internal measure time used for a transform function
static double get_time(shtns_cfg shtns, int nloop, int npar, char* name, void *fptr, void *i1, void *i2, void *i3, void *o1, void *o2, void *o3, int l)
{
double t;
int i;
ticks tik0, tik1;
if (fptr == NULL) return(0.0);
tik1 = getticks();
for (i=0; i<nloop; i++) {
switch(npar) {
case 2: (*(pf2l)fptr)(shtns, i1,o1, l); break; // l may be discarded.
case 3: (*(pf3l)fptr)(shtns, i1,o1,o2, l); break;
case 4: (*(pf4l)fptr)(shtns, i1,i2,o1,o2, l); break;
default: (*(pf6l)fptr)(shtns, i1,i2,i3, o1,o2,o3, l); break;
}
if (i==0) tik0 = getticks();
}
if (nloop == 1) {
t = elapsed(tik0, tik1);
} else {
tik1 = getticks();
t = elapsed(tik1, tik0)/(nloop-1); // discard first iteration.
}
#if SHT_VERBOSE > 1
if (verbose>1) { printf(" t(%s) = %.3g",name,t); fflush(stdout); }
#endif
return t;
}
/// \internal choose fastest between on-the-fly and gauss algorithms.
/// *nlp is the number of loops. If zero, it is set to a good value.
/// on_the_fly : 1 = skip all memory algorithm. 0 = include memory and on-the-fly. -1 = test only DCT.
/// returns time without dct / best time with dct (or 0 if no dct available).
static double choose_best_sht(shtns_cfg shtns, int* nlp, int vector, int dct_mtr)
{
cplx *Qlm=0, *Slm=0, *Tlm=0;
double *Qh=0, *Sh=0, *Th=0;
int m, i, i0, minc, nloop, alg_end;
int typ_lim = SHT_NTYP; // time every type.
double t0, t, tt, r;
double tdct, tnodct;
clock_t tcpu;
int on_the_fly_only = (shtns->ylm == NULL); // only on-the-fly.
int otf_analys = (shtns->wg != NULL); // on-the-fly analysis supported.
if (NLAT < VSIZE2*4) return(0.0); // on-the-fly not possible for NLAT_2 < 2*NWAY (overflow) and DCT not efficient for low NLAT.
if ((dct_mtr != 0) && (shtns->ykm_dct == NULL)) return(0.0); // no dct available : do nothing.
size_t nspat = sizeof(double) * NSPAT_ALLOC(shtns);
size_t nspec = sizeof(cplx)* NLM;
if (nspec>nspat) nspat=nspec;
Sh = (double *) VMALLOC(nspat); Slm = (cplx *) VMALLOC(nspec);
if ((Sh==0) || (Slm==0)) shtns_runerr("not enough memory.");
if (vector) {
Th = (double *) VMALLOC(nspat); Qh = (double *) VMALLOC(nspat);
Tlm = (cplx *) VMALLOC(nspec); Qlm = (cplx *) VMALLOC(nspec);
if ( (Th==0) || (Qh==0) || (Tlm==0) || (Qlm==0) ) vector = 0;
}
for (i=0;i<NLM;i++) {
int l = shtns->li[i];
Slm[i] = shtns->l_2[l] + 0.5*I*shtns->l_2[l];
if (vector) {
Tlm[i] = 0.5*shtns->l_2[l] + I*shtns->l_2[l];
Qlm[i] = 3*shtns->l_2[l] + 2*I*shtns->l_2[l];
}
}
#if SHT_VERBOSE > 0
if (verbose) {
if (dct_mtr != 0) printf(" finding optimal m-truncation for DCT synthesis");
else printf(" finding optimal algorithm");
fflush(stdout);
}
#endif
if (*nlp <= 0) {
// find good nloop by requiring less than 3% difference between 2 consecutive timings.
m=0; nloop = 1; // number of loops to get timings.
r = 0.0; tt = 1.0;
do {
if ((r > 0.03)||(tt<0.1)) {
m = 0; nloop *= 3;
} else m++;
tcpu = clock();
t0 = get_time(shtns, nloop, 2, "", sht_func[SHT_STD][SHT_FLY2][SHT_TYP_SSY], Slm, Tlm, Qlm, Sh, Th, Qh, LMAX);
tcpu = clock() - tcpu; tt = 1.e-6 * tcpu;
if (tt >= SHT_TIME_LIMIT) break; // we should not exceed 1 second
t = get_time(shtns, nloop, 2, "", sht_func[SHT_STD][SHT_FLY2][SHT_TYP_SSY], Slm, Tlm, Qlm, Sh, Th, Qh, LMAX);
r = fabs(2.0*(t-t0)/(t+t0));
#if SHT_VERBOSE > 1
if (verbose>1) printf(", nloop=%d, r=%g, m=%d (real time = %g s)\n",nloop,r,m,tt);
if (tt >= 0.01) break; // faster timing in debug mode.
#endif
PRINT_DOT
} while((nloop<10000)&&(m < 3));
*nlp = nloop;
} else {
nloop = *nlp;
}
#if SHT_VERBOSE > 1
if (verbose>1) printf(" => nloop=%d (takes %g s)\n",nloop, tt);
#endif
if (vector == 0) typ_lim = SHT_TYP_VSY; // time only scalar transforms.
// if (tt > 3.0) typ_lim = SHT_TYP_VSY; // time only scalar transforms.
// if (tt > 10.0) goto done; // timing this will be too slow...
int ityp = 0; do {
if ((dct_mtr != 0) && (ityp >= 4)) break; // dct !=0 : only scalar and vector.
if (ityp == 2) nloop = (nloop+1)/2; // scalar ar done.
t0 = 1e100;
i0 = 0;
if (MTR_DCT < 0) i0 = SHT_MEM; // skip dct.
if (on_the_fly_only) i0 = SHT_SV; // only on-the-fly (SV is then also on-the-fly)
alg_end = SHT_NALG;
if (shtns->nthreads <= 1) alg_end = SHT_OMP1; // no OpenMP with 1 thread.
if ((ityp&1) && (otf_analys == 0)) alg_end = SHT_FLY1; // no on-the-fly analysis for regular grid.
for (i=i0, m=0; i<alg_end; i++) {
if (sht_func[0][i][ityp] != NULL) m++; // count number of algos
}
if (m >= 2) { // don't time if there is only 1 algo !
#if SHT_VERBOSE > 1
if (verbose>1) { printf("finding best %s ...",sht_type[ityp]); fflush(stdout); }
#endif
i = i0-1; i0 = -1;
while (++i < alg_end) {
void *pf = sht_func[0][i][ityp];
if (pf != NULL) {
if (ityp&1) { // analysis
t = get_time(shtns, nloop, sht_npar[ityp], sht_name[i], pf, Sh, Th, Qh, Slm, Tlm, Qlm, LMAX);
} else {
t = get_time(shtns, nloop, sht_npar[ityp], sht_name[i], pf, Slm, Tlm, Qlm, Sh, Th, Qh, LMAX);
}
if (i < SHT_FLY1) t *= 1.03; // 3% penality for memory based transforms.
#ifdef _OPENMP
if ((i >= SHT_OMP1)||(i == SHT_SV)) t *= 1.3; // 30% penality for openmp transforms.
#endif
if (t < t0) { i0 = i; t0 = t; PRINT_VERB("*"); }
}
}
if (i0 >= 0) {
for (int iv=0; iv<SHT_NVAR; iv++) {
if (sht_func[iv][i0][ityp]) shtns->ftable[iv][ityp] = sht_func[iv][i0][ityp];
if (ityp == 4) { // only one timing for both gradients variants.
if (sht_func[iv][i0][ityp+1]) shtns->ftable[iv][ityp+1] = sht_func[iv][i0][ityp+1];
}
}
PRINT_DOT
#if SHT_VERBOSE > 1
if (verbose>1) printf(" => %s\n",sht_name[i0]);
#endif
}
}
if (ityp == 4) ityp++; // skip second gradient
} while(++ityp < typ_lim);
#ifdef SHTNS_DCT
if (dct_mtr != 0) { // find the best DCT timings...
#if SHT_VERBOSE > 1
if (verbose>1) { printf("finding best mtr_dct ..."); fflush(stdout); }
#endif
minc = MMAX/20 + 1; // don't test every single m.
m = -1; i = -1; t0 = 0.0; // reference = no dct.
if (sht_func[SHT_STD][SHT_DCT][SHT_TYP_SSY] != NULL)
t0 += get_time(shtns, *nlp, 2, "s", shtns->ftable[SHT_STD][SHT_TYP_SSY], Slm, Tlm, Qlm, Sh, Th, Qh, LMAX);
if ( (sht_func[SHT_STD][SHT_DCT][SHT_TYP_VSY] != NULL) && (vector) )
t0 += get_time(shtns, nloop, 4, "v", shtns->ftable[SHT_STD][SHT_TYP_VSY], Slm, Tlm, Qlm, Sh, Th, Qh, LMAX);
tnodct = t0;
for (m=0; m<=MMAX; m+=minc) {
#if SHT_VERBOSE > 1
if (verbose>1) printf("\n\tm=%d :",m);
#endif
if (Set_MTR_DCT(shtns, m) >= 0) {
t = get_time(shtns, *nlp, 2, "sdct", sht_func[SHT_STD][SHT_DCT][SHT_TYP_SSY], Slm, Tlm, Qlm, Sh, Th, Qh, LMAX);
if (vector)
t += get_time(shtns, nloop, 4, "vdct", sht_func[SHT_STD][SHT_DCT][SHT_TYP_VSY], Slm, Tlm, Qlm, Sh, Th, Qh, LMAX);
if (t < t0) { t0 = t; i = m; PRINT_VERB("*"); }
PRINT_DOT
}
}
tdct = t0;
Set_MTR_DCT(shtns, i); // the best DCT is chosen.
#if SHT_VERBOSE > 0
if (verbose) printf(" mtr_dct=%d (%.1f%% performance gain)", MTR_DCT*MRES, 100.*(tnodct/tdct-1.));
#endif
}
#endif
done:
#if SHT_VERBOSE > 0
if (verbose) printf("\n");
#endif
if (Qlm) VFREE(Qlm); if (Tlm) VFREE(Tlm);
if (Qh) VFREE(Qh); if (Th) VFREE(Th);
if (Slm) VFREE(Slm); if (Sh) VFREE(Sh);
if (dct_mtr > 0) {
return(tnodct/tdct);
} else return(0.0);
}
void shtns_print_version() {
printf("[" PACKAGE_STRING "] built " __DATE__ ", " __TIME__ ", id: " _SIMD_NAME_ "\n");
}
void fprint_ftable(FILE* fp, void* ftable[SHT_NVAR][SHT_NTYP])
{
for (int iv=0; iv<SHT_NVAR; iv++) {
fprintf(fp, "\n %4s:",sht_var[iv]);
void** f = ftable[iv];
for (int it=0; it<SHT_NTYP; it++) {
if (f[it] != NULL) {
for (int ia=0; ia<SHT_NALG; ia++)
if (sht_func[iv][ia][it] == f[it]) {
fprintf(fp, "%5s ",sht_name[ia]); break;
}
} else fprintf(fp, " none ");
}
}
}
void shtns_print_cfg(shtns_cfg shtns)
{
printf("Lmax=%d, Mmax*Mres=%d, Mres=%d, Nlm=%d [%d threads, ",LMAX, MMAX*MRES, MRES, NLM, shtns->nthreads);
if (shtns->norm & SHT_REAL_NORM) printf("'real' norm, ");
if (shtns->norm & SHT_NO_CS_PHASE) printf("no Condon-Shortley phase, ");
if (SHT_NORM == sht_fourpi) printf("4.pi normalized]\n");
else if (SHT_NORM == sht_schmidt) printf("Schmidt semi-normalized]\n");
else printf("orthonormalized]\n");
if (shtns->ct == NULL) return; // no grid is set
switch(shtns->grid) {
case GRID_GAUSS : printf("Gauss grid"); break;
case GRID_REGULAR : printf("Regular grid (mtr_dct=%d)",shtns->mtr_dct); break;
case GRID_POLES : printf("Regular grid including poles"); break;
default : printf("Unknown grid");
}
printf(" : Nlat=%d, Nphi=%d\n", NLAT, NPHI);
printf(" ");
for (int it=0; it<SHT_NTYP; it++)
printf("%5s ",sht_type[it]);
fprint_ftable(stdout, shtns->ftable);
printf("\n");
}
/// \internal saves config to a file for later restart.
int config_save(shtns_cfg shtns, int req_flags)
{
int err = 0;
if (shtns->ct == NULL) return -1; // no grid set
if ((shtns->nphi > 1)||(shtns->mtr_dct >= 0)) {
FILE* f = fopen("shtns_cfg_fftw","w");
if (f != NULL) {
fftw_export_wisdom_to_file(f);
fclose(f);
} else err -= 2;
}
FILE *fcfg = fopen("shtns_cfg","a");
if (fcfg != NULL) {
fprintf(fcfg, "%s %s %d %d %d %d %d %d %d %d %d %d",PACKAGE_VERSION, _SIMD_NAME_, shtns->lmax, shtns->mmax, shtns->mres, shtns->nphi, shtns->nlat, shtns->grid, shtns->nthreads, req_flags, shtns->nlorder, shtns->mtr_dct);
fprint_ftable(fcfg, shtns->ftable);
fprintf(fcfg,"\n");
fclose(fcfg);
} else err -= 4;
#if SHT_VERBOSE > 0
if (err < 0) fprintf(stderr,"! Warning ! SHTns could not save config\n");
#endif
return err;
}
/// \internal try to load config from a file
int config_load(shtns_cfg shtns, int req_flags)
{
void* ft2[SHT_NVAR][SHT_NTYP]; // pointers to transform functions.
int lmax2, mmax2, mres2, nphi2, nlat2, grid2, nthreads2, req_flags2, nlorder2, mtr_dct2;
int found = 0;
char version[32], simd[8], alg[8];
if (shtns->ct == NULL) return -1; // no grid set
if ((req_flags & 255) == sht_quick_init) req_flags += sht_gauss - sht_quick_init; // quick_init uses gauss.
FILE *fcfg = fopen("shtns_cfg","r");
if (fcfg != NULL) {
int i=0;
while(1) {
fscanf(fcfg, "%30s %8s %d %d %d %d %d %d %d %d %d %d",version, simd, &lmax2, &mmax2, &mres2, &nphi2, &nlat2, &grid2, &nthreads2, &req_flags2, &nlorder2, &mtr_dct2);
for (int iv=0; iv<SHT_NVAR; iv++) {
fscanf(fcfg, "%7s", alg);
for (int it=0; it<SHT_NTYP; it++) {
fscanf(fcfg, "%7s", alg),
ft2[iv][it] = 0;
for (int ia=0; ia<SHT_NALG; ia++) {
if (strcmp(alg, sht_name[ia]) == 0) {
ft2[iv][it] = sht_func[iv][ia][it];
break;
}
}
}
}
if (feof(fcfg)) break;
#ifndef SHTNS_DCT
if (mtr_dct2 <= 0)
#endif
if ((shtns->lmax == lmax2) && (shtns->mmax == mmax2) && (shtns->mres == mres2) && (shtns->nthreads == nthreads2) &&
(shtns->nphi == nphi2) && (shtns->nlat == nlat2) && (shtns->grid == grid2) && (req_flags == req_flags2) &&
(shtns->nlorder == nlorder2) && (strcmp(simd, _SIMD_NAME_)==0)) {
#if SHT_VERBOSE > 0
if (verbose > 0) printf(" + using saved config\n");
#endif
#if SHT_VERBOSE > 1
if (verbose > 1) {
fprint_ftable(stdout, ft2);
printf("\n");
}
#endif
#ifdef SHTNS_DCT
Set_MTR_DCT(shtns, mtr_dct2); // use loaded mtr_dct
#endif
for (int iv=0; iv<SHT_NVAR; iv++)
for (int it=0; it<SHT_NTYP; it++)
if (ft2[iv][it]) shtns->ftable[iv][it] = ft2[iv][it]; // accept only non-null pointer
found = 1;
break;
}
}
fclose(fcfg);
return found;
} else {
#if SHT_VERBOSE > 0
if (verbose) fprintf(stderr,"! Warning ! SHTns could not load config\n");
#endif
return -2; // file not found
}
}
/// \internal returns 1 if val cannot fit in dest (unsigned)
#define IS_TOO_LARGE(val, dest) (sizeof(dest) >= sizeof(val)) ? 0 : ( ( val >= (1<<(8*sizeof(dest))) ) ? 1 : 0 )
/// \internal returns the size that must be allocated for an shtns_info.
#define SIZEOF_SHTNS_INFO(mmax) ( sizeof(struct shtns_info) + (mmax+1)*( sizeof(int)+sizeof(unsigned short) ) )
/* PUBLIC INITIALIZATION & DESTRUCTION */
/** \addtogroup init Initialization functions.
*/
//@{
/*! This sets the description of spherical harmonic coefficients.
* It tells SHTns how to interpret spherical harmonic coefficient arrays, and it sets usefull arrays.
* Returns the configuration to be passed to subsequent transform functions, which is basicaly a pointer to a \ref shtns_info struct.
* \param lmax : maximum SH degree that we want to describe.
* \param mmax : number of azimutal wave numbers.
* \param mres : \c 2.pi/mres is the azimutal periodicity. \c mmax*mres is the maximum SH order.
* \param norm : define the normalization of the spherical harmonics (\ref shtns_norm)
* + optionaly disable Condon-Shortley phase (ex: \ref sht_schmidt | \ref SHT_NO_CS_PHASE)
* + optionaly use a 'real' normalization (ex: \ref sht_fourpi | \ref SHT_REAL_NORM)
*/
shtns_cfg shtns_create(int lmax, int mmax, int mres, enum shtns_norm norm)
{
shtns_cfg shtns, s2;
int im, m, l, lm;
int with_cs_phase = 1; /// Condon-Shortley phase (-1)^m is used by default.
double mpos_renorm = 1.0; /// renormalization of m>0.
int larrays_ok = 0;
int legendre_ok = 0;
int l_2_ok = 0;
// if (lmax < 1) shtns_runerr("lmax must be larger than 1");
if (lmax < 2) shtns_runerr("lmax must be at least 2");
if (IS_TOO_LARGE(lmax, shtns->lmax)) shtns_runerr("lmax too large");
if (mmax*mres > lmax) shtns_runerr("MMAX*MRES should not exceed LMAX");
if (mres <= 0) shtns_runerr("MRES must be > 0");
// allocate new setup and initialize some variables (used as flags) :
shtns = malloc( SIZEOF_SHTNS_INFO(mmax) );
if (shtns == NULL) return shtns; // FAIL
{
void **p0 = (void**) &shtns->tm; // first pointer in struct.
void **p1 = (void**) &shtns->Y00_1; // first non-pointer.
while(p0 < p1) *p0++ = NULL; // write NULL to every pointer.
shtns->lmidx = (int*) (shtns + 1); // lmidx is stored at the end of the struct...
shtns->tm = (unsigned short*) (shtns->lmidx + (mmax+1)); // and tm just after.
shtns->ct = NULL; shtns->st = NULL;
shtns->nphi = 0; shtns->nlat = 0; shtns->nlat_2 = 0; shtns->nspat = 0; // public data
}
// copy sizes.
shtns->norm = norm;
if (norm & SHT_NO_CS_PHASE)
with_cs_phase = 0;
if (norm & SHT_REAL_NORM)
mpos_renorm = 0.5; // normalization for 'real' spherical harmonics.
shtns->mmax = mmax; shtns->mres = mres; shtns->lmax = lmax;
shtns->nlm = nlm_calc(lmax, mmax, mres);
shtns->nthreads = omp_threads;
if (omp_threads > mmax+1) shtns->nthreads = mmax+1; // limit the number of threads to mmax+1
#if SHT_VERBOSE > 0
if (verbose) {
shtns_print_version();
printf(" "); shtns_print_cfg(shtns);
}
#endif
s2 = sht_data; // check if some data can be shared ...
while(s2 != NULL) {
if ((s2->mmax >= mmax) && (s2->mres == mres)) {
if (s2->lmax == lmax) { // we can reuse the l-related arrays (li + copy lmidx)
shtns->li = s2->li; shtns->mi = s2->mi;
for (im=0; im<=mmax; im++) shtns->lmidx[im] = s2->lmidx[im];
larrays_ok = 1;
}
if ( (s2->lmax >= lmax) && (s2->norm == norm) ) { // we can reuse the legendre tables.
shtns->alm = s2->alm; shtns->blm = s2->blm;
legendre_ok = 1;
}
}
if (s2->lmax >= lmax) { // we can reuse l_2
shtns->l_2 = s2->l_2;
l_2_ok = 1;
}
s2 = s2->next;
}
if (larrays_ok == 0) {
// alloc spectral arrays
shtns->li = (unsigned short *) malloc( 2*NLM*sizeof(unsigned short) ); // NLM defined at runtime.
shtns->mi = shtns->li + NLM;
for (im=0, lm=0; im<=MMAX; im++) { // init l-related arrays.
m = im*MRES;
shtns->lmidx[im] = lm -m; // virtual pointer for l=0
for (l=im*MRES;l<=LMAX;l++) {
shtns->li[lm] = l; shtns->mi[lm] = m;
lm++;
}
}
if (lm != NLM) shtns_runerr("unexpected error");
}
if (legendre_ok == 0) { // this quickly precomputes some values for the legendre recursion.
legendre_precomp(shtns, SHT_NORM, with_cs_phase, mpos_renorm);
}
if (l_2_ok == 0) {
shtns->l_2 = (double *) malloc( (LMAX+1)*sizeof(double) );
shtns->l_2[0] = 0.0; // undefined for l=0 => replace with 0.
real one = 1.0;
for (l=1; l<=LMAX; l++) shtns->l_2[l] = one/(l*(l+1));
}
switch(SHT_NORM) {
case sht_schmidt:
shtns->Y00_1 = 1.0; shtns->Y10_ct = 1.0;
break;
case sht_fourpi:
shtns->Y00_1 = 1.0; shtns->Y10_ct = sqrt(1./3.);
break;
case sht_orthonormal:
default:
shtns->Y00_1 = sqrt(4.*M_PI); shtns->Y10_ct = sqrt(4.*M_PI/3.);
// Y11_st = sqrt(2.*M_PI/3.); // orthonormal : \f$ \sin\theta\cos\phi/(Y_1^1 + Y_1^{-1}) = -\sqrt{2 \pi /3} \f$
}
shtns->Y11_st = shtns->Y10_ct * sqrt(0.5/mpos_renorm);
if (with_cs_phase) shtns->Y11_st *= -1.0; // correct Condon-Shortley phase
// save a pointer to this setup and return.
shtns->next = sht_data; // reference of previous setup (may be NULL).
sht_data = shtns; // keep track of new setup.
return(shtns);
}
/// Copy a given config but allow a different (smaller) mmax and the possibility to enable/disable fft (beta).
shtns_cfg shtns_create_with_grid(shtns_cfg base, int mmax, int nofft)
{
shtns_cfg shtns;
if (mmax > base->mmax) return (NULL); // fail if mmax larger than source config.
shtns = malloc( SIZEOF_SHTNS_INFO(mmax) );
memcpy(shtns, base, SIZEOF_SHTNS_INFO(mmax) ); // copy all
shtns->lmidx = (int*) shtns+1; // lmidx is stored at the end of the struct...
shtns->tm = (unsigned short*) (shtns->lmidx + (mmax+1)); // ...and tm just after.
if (mmax != shtns->mmax) {
shtns->mmax = mmax;
for (int im=0; im<=mmax; im++) {
shtns->lmidx[im] = base->lmidx[im];
shtns->tm[im] = base->tm[im];
}
#ifdef SHTNS_DCT
if (mmax < shtns->mtr_dct) {
shtns->idct = NULL; // do not destroy the plan of the source.
Set_MTR_DCT(shtns, mmax); // adjut mtr_dct if required.
}
#endif
if (mmax == 0) {
// TODO we may disable fft and replace with a phi-averaging function ...
// ... then switch to axisymmetric functions :
// init_sht_array_func(shtns);
// choose_best_sht(shtns, &nloop, 0);
}
}
if (nofft != 0) {
shtns->ncplx_fft = -1; // fft disabled.
}
// save a pointer to this setup and return.
shtns->next = sht_data; // reference of previous setup (may be NULL).
sht_data = shtns; // keep track of new setup.
return(shtns);
}
/// release all resources allocated by a grid.
void shtns_unset_grid(shtns_cfg shtns)
{
if (ref_count(shtns, &shtns->wg) == 1) VFREE(shtns->wg);
shtns->wg = NULL;
free_SH_dct(shtns);
free_SHTarrays(shtns);
shtns->nlat = 0; shtns->nlat_2 = 0;
shtns->nphi = 0; shtns->nspat = 0;
}
/// release all resources allocated by a given shtns_cfg.
void shtns_destroy(shtns_cfg shtns)
{
free_unused(shtns, &shtns->l_2);
if (shtns->blm != shtns->alm)
free_unused(shtns, &shtns->blm);
free_unused(shtns, &shtns->alm);
free_unused(shtns, &shtns->li);
shtns_unset_grid(shtns);
if (sht_data == shtns) {
sht_data = shtns->next; // forget shtns
} else {
shtns_cfg s2 = sht_data;
while (s2 != NULL) {
if (s2->next == shtns) {
s2->next = shtns->next; // forget shtns
break;
}
s2 = s2->next;
}
}
free(shtns);
}
/// clear all allocated memory (hopefully) and go back to 0 state.
void shtns_reset()
{
while (sht_data != NULL) {
shtns_destroy(sht_data);
}
}
/*! Initialization of Spherical Harmonic transforms (backward and forward, vector and scalar, ...) of given size.
* <b>This function must be called after \ref shtns_create and before any SH transform.</b> and sets all global variables and internal data.
* returns the required number of doubles to be allocated for a spatial field.
* \param shtns is the config created by \ref shtns_create for which the grid will be set.
* \param nlat,nphi pointers to the number of latitudinal and longitudinal grid points respectively. If 0, they are set to optimal values.
* \param nl_order defines the maximum SH degree to be resolved by analysis : lmax_analysis = lmax*nl_order. It is used to set an optimal and anti-aliasing nlat. If 0, the default SHT_DEFAULT_NL_ORDER is used.
* \param flags allows to choose the type of transform (see \ref shtns_type) and the spatial data layout (see \ref spat)
* \param eps polar optimization threshold : polar values of Legendre Polynomials below that threshold are neglected (for high m), leading to increased performance (a few percents)
* 0 = no polar optimization; 1.e-14 = VERY safe; 1.e-10 = safe; 1.e-6 = aggresive, but still good accuracy.
*/
int shtns_set_grid_auto(shtns_cfg shtns, enum shtns_type flags, double eps, int nl_order, int *nlat, int *nphi)
{
double t, mem;
int im,m;
int layout;
int nloop = 0;
int n_gauss = 0;
int on_the_fly = 0;
int quick_init = 0;
int vector = !(flags & SHT_SCALAR_ONLY);
int latdir = (flags & SHT_SOUTH_POLE_FIRST) ? -1 : 1; // choose latitudinal direction (change sign of ct)
int cfg_loaded = 0;
int analys = 1;
const int req_flags = flags; // requested flags.
#if _GCC_VEC_
if (*nlat & 1) shtns_runerr("Nlat must be even\n");
#ifdef __MIC__
if (*nlat % VSIZE2) shtns_runerr("Nlat must be a multiple of 8 for the MIC\n");
#endif
#endif
shtns_unset_grid(shtns); // release grid if previously allocated.
if (nl_order <= 0) nl_order = SHT_DEFAULT_NL_ORDER;
/* shtns.lshift = 0;
if (nl_order == 0) nl_order = SHT_DEFAULT_NL_ORDER;
if (nl_order < 0) { shtns.lshift = -nl_order; nl_order = 1; } // linear with a shift in l.
*/
shtns->nspat = 0;
shtns->nlorder = nl_order;
shtns->mtr_dct = -1; // dct switched off completely.
layout = flags & 0xFFFF00;
flags = flags & 255; // clear higher bits.
switch (flags) {
#ifndef SHTNS_DCT
case sht_auto : flags = sht_gauss; break; // only gauss available.
case sht_reg_fast:
case sht_reg_dct: shtns_runerr("regular grid not available (DCT required)."); break;
#endif
case sht_gauss_fly : flags = sht_gauss; on_the_fly = 1; break;
case sht_quick_init : flags = sht_gauss; quick_init = 1; break;
case sht_reg_poles : analys = 0; quick_init = 1; break;
default : break;
}
#ifndef SHTNS_MEM
on_the_fly = 1;
#endif
if (*nphi == 0) {
*nphi = fft_int((nl_order+1)*MMAX+1, 7); // required fft nodes
}
if (*nlat == 0) {
n_gauss = ((nl_order+1)*LMAX)/2 +1; // required gauss nodes
n_gauss += (n_gauss&1); // even is better.
n_gauss = ((n_gauss+(VSIZE2-1))/VSIZE2) * VSIZE2; // multiple of vector size
if (flags != sht_gauss) {
m = fft_int(nl_order*LMAX+2, 7); // required dct nodes
*nlat = m + (m&1); // even is better.
} else *nlat = n_gauss;
}
mem = sht_mem_size(shtns->lmax, shtns->mmax, shtns->mres, *nlat);
t=mem; if (analys) t*=2; if (vector) t*=3;
#if SHT_VERBOSE > 1
if (verbose>1) printf("Memory required for precomputed matrices (estimate) : %.3f Mb\n",t);
#endif
if ( t > SHTNS_MAX_MEMORY ) { // huge transform has been requested
on_the_fly = 1;
if ( (flags == sht_reg_dct) || (flags == sht_reg_fast) ) shtns_runerr("Memory limit exceeded, try using sht_gauss or increase SHTNS_MAX_MEMORY in sht_config.h");
if (flags != sht_reg_poles) {
flags = sht_gauss;
if (n_gauss > 0) *nlat = n_gauss;
}
// if (t > 10*SHTNS_MAX_MEMORY) quick_init =1; // do not time such large transforms.
}
if (quick_init == 0) { // do not waste too much time finding optimal fftw.
shtns->fftw_plan_mode = FFTW_EXHAUSTIVE; // defines the default FFTW planner mode.
// fftw_set_timelimit(60.0); // do not search plans for more than 1 minute (does it work well ???)
if (*nphi > 512) shtns->fftw_plan_mode = FFTW_PATIENT;
if (*nphi > 1024) shtns->fftw_plan_mode = FFTW_MEASURE;
} else {
shtns->fftw_plan_mode = FFTW_ESTIMATE;
if ((mem < 1.0) && (SHT_VERBOSE < 2)) shtns->nthreads = 1; // disable threads for small transforms (in quickinit mode).
if ((VSIZE2 >= 4) && (*nlat >= VSIZE2*4)) on_the_fly = 1; // with AVX, on-the-fly should be the default (faster).
if ((shtns->nthreads > 1) && (*nlat >= VSIZE2*16)) on_the_fly = 1; // force multi-thread transforms
}
if (flags == sht_auto) {
if ( ((nl_order>=2)&&(MMAX*MRES > LMAX/2)) || (*nlat < SHT_MIN_NLAT_DCT) || (*nlat & 1) || (*nlat <= LMAX+1) ) {
flags = sht_gauss; // avoid computing DCT stuff when it is not expected to be faster.
if (n_gauss > 0) *nlat = n_gauss;
}
}
if (*nlat <= shtns->lmax) shtns_runerr("Nlat must be larger than Lmax");
if (IS_TOO_LARGE(*nlat, shtns->nlat)) shtns_runerr("Nlat too large");
if (IS_TOO_LARGE(*nphi, shtns->nphi)) shtns_runerr("Nphi too large");
// copy to global variables.
shtns->nphi = *nphi;
shtns->nlat_2 = (*nlat+1)/2; shtns->nlat = *nlat;
if (layout & SHT_LOAD_SAVE_CFG) {
FILE* f = fopen("shtns_cfg_fftw","r");
if (f) {
fftw_import_wisdom_from_file(f); // load fftw wisdom.
fclose(f);
}
}
planFFT(shtns, layout, on_the_fly); // initialize fftw
shtns->zlm_dct0 = NULL; // used as a flag.
init_sht_array_func(shtns); // array of SHT functions is now set.
#ifdef SHTNS_DCT
if (flags == sht_reg_dct) { // pure dct.
alloc_SHTarrays(shtns, on_the_fly, vector, analys); // allocate dynamic arrays
grid_dct(shtns, latdir); init_SH_dct(shtns, 1);
OptimizeMatrices(shtns, eps);
Set_MTR_DCT(shtns, MMAX);
if (MTR_DCT != MMAX) shtns_runerr("DCT planning failed.");
}
if ((flags == sht_auto)||(flags == sht_reg_fast))
{
alloc_SHTarrays(shtns, on_the_fly, vector, analys); // allocate dynamic arrays
grid_dct(shtns, latdir); init_SH_dct(shtns, 1);
OptimizeMatrices(shtns, eps);
if (NLAT >= SHT_MIN_NLAT_DCT) { // dct requires large NLAT to perform well.
if ((layout & SHT_LOAD_SAVE_CFG) && (flags == sht_reg_fast))
cfg_loaded = (config_load(shtns, req_flags) > 0);
if (!cfg_loaded) {
t = choose_best_sht(shtns, &nloop, vector, 1); // find optimal MTR_DCT.
if ((n_gauss > 0)&&(flags == sht_auto)) t *= ((double) n_gauss)/NLAT; // we can revert to gauss with a smaller nlat.
if (t < MIN_PERF_IMPROVE_DCT) {
Set_MTR_DCT(shtns, -1); // turn off DCT.
} else {
t = SHT_error(shtns, vector);
if (t > MIN_ACCURACY_DCT) {
#if SHT_VERBOSE > 0
if (verbose) printf(" !! Not enough accuracy (%.3g) => DCT disabled.\n",t);
#endif
#if SHT_VERBOSE < 2
Set_MTR_DCT(shtns, -1); // turn off DCT.
#endif
}
}
}
}
if (MTR_DCT < 0) { // free memory used by DCT and disables DCT.
free_SH_dct(shtns); // free now useless arrays.
if (flags == sht_auto) {
flags = sht_gauss; // switch to gauss grid, even better accuracy.
#if SHT_VERBOSE > 0
if (verbose) printf(" => switching back to Gauss Grid\n");
#endif
for (im=1; im<=MMAX; im++) { // im >= 1
m = im*MRES;
shtns->ylm[im] -= shtns->tm[im]*(LMAX-m+1); // restore pointers altered by OptimizeMatrices().
if (vector) shtns->dylm[im] -= shtns->tm[im]*(LMAX-m+1);
}
if (n_gauss > 0) { // we should use the optimal size for gauss-legendre
free_SHTarrays(shtns);
*nlat = n_gauss;
shtns->nlat_2 = (*nlat+1)/2; shtns->nlat = *nlat;
planFFT(shtns, layout, on_the_fly); // fft must be replanned because NLAT has changed.
}
}
}
}
#endif /* SHTNS_DCT */
if (flags == sht_gauss)
{
alloc_SHTarrays(shtns, on_the_fly, vector, analys); // allocate dynamic arrays
grid_gauss(shtns, latdir);
#ifdef SHTNS_MEM
if (on_the_fly == 0) {
init_SH_gauss(shtns); // precompute matrices
OptimizeMatrices(shtns, eps);
}
#endif
}
if (flags == sht_reg_poles)
{
alloc_SHTarrays(shtns, on_the_fly, vector, 0); // allocate dynamic arrays (no analysis)
grid_equal_polar(shtns, latdir);
#ifdef SHTNS_MEM
if (on_the_fly == 0) {
init_SH_synth(shtns);
for (im=0; im<=MMAX; im++) shtns->tm[im] = 0; // avoid problems with tm[im] modified ????
}
#endif
}
if (on_the_fly == 1) {
#if SHT_VERBOSE > 0
if (verbose) printf(" + using on-the-fly transforms.\n");
#endif
if (NLAT < VSIZE2*4) shtns_runerr("on-the-fly only available for nlat>=32"); // avoid overflow with NLAT_2 < VSIZE2*2
PolarOptimize(shtns, eps);
set_sht_fly(shtns, 0); // switch function pointers to "on-the-fly" functions.
}
if ((layout & SHT_LOAD_SAVE_CFG) && (!cfg_loaded)) cfg_loaded = (config_load(shtns, req_flags) > 0);
if (quick_init == 0) {
if (!cfg_loaded) {
choose_best_sht(shtns, &nloop, vector, 0);
if (layout & SHT_LOAD_SAVE_CFG) config_save(shtns, req_flags);
}
#ifdef SHTNS_MEM
if (on_the_fly == 0) free_unused_matrices(shtns);
#endif
t = SHT_error(shtns, vector); // compute SHT accuracy.
#if SHT_VERBOSE > 0
if (verbose) printf(" + SHT accuracy = %.3g\n",t);
#endif
#if SHT_VERBOSE < 2
if (t > 1.e-3) {
shtns_print_cfg(shtns);
shtns_runerr("bad SHT accuracy"); // stop if something went wrong (but not in debug mode)
}
#endif
}
// set_sht_fly(shtns, SHT_TYP_VAN);
#if SHT_VERBOSE > 1
if ((omp_threads > 1)&&(verbose>1)) printf(" nthreads = %d\n",shtns->nthreads);
#endif
#if SHT_VERBOSE > 0
if (verbose) printf(" => " PACKAGE_NAME " is ready.\n");
#endif
return(shtns->nspat); // returns the number of doubles to be allocated for a spatial field.
}
/*! Initialization of Spherical Harmonic transforms (backward and forward, vector and scalar, ...) of given size.
* <b>This function must be called after \ref shtns_create and before any SH transform.</b> and sets all global variables.
* returns the required number of doubles to be allocated for a spatial field.
* \param shtns is the config created by shtns_create for which the grid will be set.
* \param flags allows to choose the type of transform (see \ref shtns_type) and the spatial data layout (see \ref spat)
* \param eps polar optimization threshold : polar values of Legendre Polynomials below that threshold are neglected (for high m), leading to increased performance (a few percents)
* \param nlat,nphi respectively the number of latitudinal and longitudinal grid points.
* 0 = no polar optimization; 1.e-14 = VERY safe; 1.e-10 = safe; 1.e-6 = aggresive, but still good accuracy.
*/
int shtns_set_grid(shtns_cfg shtns, enum shtns_type flags, double eps, int nlat, int nphi)
{
if ((nlat == 0)||(nphi == 0)) shtns_runerr("nlat or nphi is zero !");
return( shtns_set_grid_auto(shtns, flags, eps, 0, &nlat, &nphi) );
}
/*! Simple initialization of Spherical Harmonic transforms (backward and forward, vector and scalar, ...) of given size.
* This function sets all global variables by calling \ref shtns_create followed by \ref shtns_set_grid, with the
* default normalization and the default polar optimization (see \ref sht_config.h).
* Returns the configuration to be passed to subsequent transform functions, which is basicaly a pointer to a \ref shtns_info struct.
* \param lmax : maximum SH degree that we want to describe.
* \param mmax : number of azimutal wave numbers.
* \param mres : \c 2.pi/mres is the azimutal periodicity. \c mmax*mres is the maximum SH order.
* \param nlat,nphi : respectively the number of latitudinal and longitudinal grid points.
* \param flags allows to choose the type of transform (see \ref shtns_type) and the spatial data layout (see \ref spat)
*/
shtns_cfg shtns_init(enum shtns_type flags, int lmax, int mmax, int mres, int nlat, int nphi)
{
shtns_cfg shtns = shtns_create(lmax, mmax, mres, SHT_DEFAULT_NORM);
if (shtns != NULL)
shtns_set_grid(shtns, flags, SHT_DEFAULT_POLAR_OPT, nlat, nphi);
return shtns;
}
/** Enables OpenMP parallel transforms, if available (see \ref compil).
Call before any initialization of shtns to use mutliple threads. Returns the actual number of threads.
\li If num_threads > 0, specifies the maximum number of threads that should be used.
\li If num_threads <= 0, maximum number of threads is automatically set to the number of processors.
\li If num_threads == 1, openmp will be disabled. */
int shtns_use_threads(int num_threads)
{
#ifdef _OPENMP
int procs = omp_get_num_procs();
if (num_threads <= 0) num_threads = omp_get_max_threads();
else if (num_threads > 4*procs) num_threads = 4*procs; // limit the number of threads
omp_threads = num_threads;
#endif
#ifdef OMP_FFTW
fftw_init_threads(); // enable threads for FFTW.
#endif
return omp_threads;
}
/// fill the given array with Gauss weights. returns the number of weights written, which
/// may be zero if the grid is not a Gauss grid.
int shtns_gauss_wts(shtns_cfg shtns, double *wts)
{
int i = 0;
if (shtns->wg) {
double rescale = 2*NPHI; // weights are stored with a rescaling that depends on SHT_NORM.
if ((SHT_NORM != sht_fourpi)&&(SHT_NORM != sht_schmidt)) rescale *= 0.25/M_PI;
do {
wts[i] = shtns->wg[i] * rescale;
} while(++i < shtns->nlat_2);
}
return i;
}
//@}
#ifdef SHT_F77_API
/* FORTRAN API */
/** \addtogroup fortapi Fortran API.
* Call from fortran without the trailing '_'.
* see the \link SHT_example.f Fortran example \endlink for a simple usage of SHTns from Fortran language.
*/
//@{
/// Set verbosity level
void shtns_verbose_(int *v)
{
shtns_verbose(*v);
}
/// Enable threads
void shtns_use_threads_(int *num_threads)
{
shtns_use_threads(*num_threads);
}
/// Print info
void shtns_print_cfg_()
{
shtns_print_version();
if (sht_data) shtns_print_cfg(sht_data);
}
/// Initializes spherical harmonic transforms of given size using Gauss algorithm with default polar optimization.
void shtns_init_sh_gauss_(int *layout, int *lmax, int *mmax, int *mres, int *nlat, int *nphi)
{
shtns_reset();
shtns_cfg shtns = shtns_create(*lmax, *mmax, *mres, SHT_DEFAULT_NORM);
shtns_set_grid(shtns, sht_gauss | *layout, SHT_DEFAULT_POLAR_OPT, *nlat, *nphi);
}
/// Initializes spherical harmonic transforms of given size using Fastest available algorithm and polar optimization.
void shtns_init_sh_auto_(int *layout, int *lmax, int *mmax, int *mres, int *nlat, int *nphi)
{
shtns_reset();
shtns_cfg shtns = shtns_create(*lmax, *mmax, *mres, SHT_DEFAULT_NORM);
shtns_set_grid(shtns, sht_auto | *layout, SHT_DEFAULT_POLAR_OPT, *nlat, *nphi);
}
/// Initializes spherical harmonic transforms of given size using a regular grid and agressive optimizations.
void shtns_init_sh_reg_fast_(int *layout, int *lmax, int *mmax, int *mres, int *nlat, int *nphi)
{
shtns_reset();
shtns_cfg shtns = shtns_create(*lmax, *mmax, *mres, SHT_DEFAULT_NORM);
shtns_set_grid(shtns, sht_reg_fast | *layout, 1.e-6, *nlat, *nphi);
}
/// Initializes spherical harmonic transform SYNTHESIS ONLY of given size using a regular grid including poles.
void shtns_init_sh_poles_(int *layout, int *lmax, int *mmax, int *mres, int *nlat, int *nphi)
{
shtns_reset();
shtns_cfg shtns = shtns_create(*lmax, *mmax, *mres, SHT_DEFAULT_NORM);
shtns_set_grid(shtns, sht_reg_poles | *layout, 0, *nlat, *nphi);
}
/// Defines the size and convention of the transform.
/// Allow to choose the normalization and whether or not to include the Condon-Shortley phase.
/// \see shtns_create
void shtns_set_size_(int *lmax, int *mmax, int *mres, int *norm)
{
shtns_reset();
shtns_create(*lmax, *mmax, *mres, *norm);
}
/// Precompute matrices for synthesis and analysis.
/// Allow to choose polar optimization threshold and algorithm type.
/// \see shtns_set_grid
void shtns_precompute_(int *type, int *layout, double *eps, int *nlat, int *nphi)
{
shtns_set_grid(sht_data, *type | *layout, *eps, *nlat, *nphi);
}
/// Same as shtns_precompute_ but choose optimal nlat and/or nphi.
/// \see shtns_set_grid_auto
void shtns_precompute_auto_(int *type, int *layout, double *eps, int *nl_order, int *nlat, int *nphi)
{
shtns_set_grid_auto(sht_data, *type | *layout, *eps, *nl_order, nlat, nphi);
}
/// Clear everything
void shtns_reset_() {
shtns_reset();
}
/// returns nlm, the number of complex*16 elements in an SH array.
/// call from fortran using \code call shtns_calc_nlm(nlm, lmax, mmax, mres) \endcode
void shtns_calc_nlm_(int *nlm, const int *const lmax, const int *const mmax, const int *const mres)
{
*nlm = nlm_calc(*lmax, *mmax, *mres);
}
/// returns lm, the index in an SH array of mode (l,m).
/// call from fortran using \code call shtns_lmidx(lm, l, m) \endcode
void shtns_lmidx_(int *lm, const int *const l, const int *const m)
{
unsigned im = *m;
unsigned mres = sht_data->mres;
if (mres > 1) {
unsigned k = im % mres;
im = im / mres;
if (k) printf("wrong m");
}
*lm = LiM(sht_data, *l, im) + 1; // convert to fortran convention index.
}
/// returns l and m, degree and order of an index in SH array lm.
/// call from fortran using \code call shtns_l_m(l, m, lm) \endcode
void shtns_l_m_(int *l, int *m, const int *const lm)
{
*l = sht_data->li[*lm -1]; // convert from fortran convention index.
*m = sht_data->mi[*lm -1];
}
/// fills the given array with the cosine of the co-latitude angle (NLAT real*8)
/// if no grid has been set, the first element will be set to zero.
void shtns_cos_array_(double *costh)
{
if (sht_data->ct) {
for (int i=0; i<sht_data->nlat; i++)
costh[i] = sht_data->ct[i];
} else costh[0] = 0.0; // mark as invalid.
}
/// fills the given array with the gaussian quadrature weights ((NLAT+1)/2 real*8).
/// when there is no gaussian grid, the first element is set to zero.
void shtns_gauss_wts_(double *wts)
{
int i = shtns_gauss_wts(sht_data, wts);
if (i==0) wts[0] = 0; // mark as invalid.
}
/** \name Point evaluation of Spherical Harmonics
Evaluate at a given point (\f$cos(\theta)\f$ and \f$\phi\f$) a spherical harmonic representation.
*/
//@{
/// \see SH_to_point for argument description
void shtns_sh_to_point_(double *spat, cplx *Qlm, double *cost, double *phi)
{
*spat = SH_to_point(sht_data, Qlm, *cost, *phi);
}
/// \see SHqst_to_point for argument description
void shtns_qst_to_point_(double *vr, double *vt, double *vp,
cplx *Qlm, cplx *Slm, cplx *Tlm, double *cost, double *phi)
{
SHqst_to_point(sht_data, Qlm, Slm, Tlm, *cost, *phi, vr, vt, vp);
}
//@}
//@}
#endif
|
graphProcessing.h | /*
FINISH TEMPFLATPATH CODE
AS WRITTEN, THESE FUNCTIONS WILL ONLY WORK WITH GRAPHS THAT ARE IMPLEMENTED IN THE boost NAMESPACE.
*/
#define LP 1
#define PERFDEBUG 0
//#define FULLDEBUG 1
#ifdef _OPENMP
#include <omp.h>
#endif
#include <boost/regex.hpp>
#include <iostream>
#include <fstream>
#include <string>
#include <assert.h>
#include <staticCFG.h>
/**
*@file graphProcessing.h
*Brief Overview of Algorithm:
***********************
*Current Implementation
***********************
*This implementation uses BOOSTs graph structure to analyze the paths of the graph
*The path analyzer sends the user paths to be evaluated by the "analyzePath" function that is user defined
**************************
*Further Improvements: TODO
**************************
@todo utilize BOOST visitors to take advantage of the BOOST graph structures abilities
***************
*Contact Info
***************
*Finally, blame can be assigned to and questions can be forwarded to the author, though response is not guaranteed
*if I'm still at Lawrence
*hoffman34 AT llnl DOT gov
*@author Michael Hoffman
*/
#include <boost/graph/adjacency_list.hpp>
#include <boost/bind.hpp>
#include <boost/foreach.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/graph/graphviz.hpp>
#include <boost/graph/dominator_tree.hpp>
#include <boost/graph/reverse_graph.hpp>
#include <boost/graph/transpose_graph.hpp>
#include <boost/algorithm/string.hpp>
#include <vector>
#include <algorithm>
#include <utility>
#include <iostream>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/time.h>
template <class CFG>
class SgGraphTraversal
{
public:
typedef typename boost::graph_traits<CFG>::vertex_descriptor Vertex;
typedef typename boost::graph_traits<CFG>:: edge_descriptor Edge;
void constructPathAnalyzer(CFG* g, bool unbounded=false, Vertex end=0, Vertex begin=0, bool ns = true);
virtual void analyzePath(std::vector<Vertex>& pth) = 0;
std::vector<int> getInEdges(int& node, CFG*& g);
std::vector<int> getOutEdges(int& node, CFG*& g);
int getTarget(int& n, CFG*& g);
int getSource(int& n, CFG*& g);
std::map<Vertex, int> vertintmap;
std::map<Edge, int> edgeintmap;
std::map<int, Vertex> intvertmap;
std::map<int, Edge> intedgemap;
SgGraphTraversal();
virtual ~SgGraphTraversal();
SgGraphTraversal( SgGraphTraversal &);
SgGraphTraversal &operator=( SgGraphTraversal &);
int pathnum;
void firstPrepGraph(CFG*& g);
private:
int normals;
int abnormals;
bool needssafety;
int recursed;
int checkedfound;
// typedef typename boost::graph_traits<CFG>::vertex_descriptor Vertex;
// typedef typename boost::graph_traits<CFG>:: edge_descriptor Edge;
// std::vector<int> getInEdges(int& node, CFG*& g);
// std::vector<int> getOutEdges(int& node, CFG*& g);
void prepareGraph(CFG*& g);
void findClosuresAndMarkersAndEnumerate(CFG*& g);
// void constructPathAnalyzer(CFG* g, bool unbounded=false, Vertex end=0, Vertex begin=0, bool ns = true);
// virtual void analyzePath(std::vector<Vertex>& pth) = 0;
// void firstPrepGraph(CFG*& g);
int stoppedpaths;
std::set<std::vector<int> > traversePath(int begin, int end, CFG*& g, bool loop=false);
std::set<std::vector<int> > uTraversePath(int begin, int end, CFG*& g, bool loop, std::map<int, std::vector<std::vector<int> > >& localLoops);
std::vector<std::vector<int> > bfsTraversePath(int begin, int end, CFG*& g, bool loop=false);
std::vector<int> unzipPath(std::vector<int>& path, CFG*& g, int start, int end);
std::vector<int> zipPath(std::vector<int>& path, CFG*& g, int start, int end);
std::vector<int> zipPath2(std::vector<int>& path, CFG*& g);
void printCFGNode(int& cf, std::ofstream& o);
void printCFGNodeGeneric(int& cf, std::string prop, std::ofstream& o);
void printCFGEdge(int& cf, CFG*& cfg, std::ofstream& o);
void printHotness(CFG*& g);
void printPathDot(CFG*& g);
void computeOrder(CFG*& g, const int& begin);
void computeSubGraphs(const int& begin, const int &end, CFG*& g, int depthDifferential);
//int getTarget(int& n, CFG*& g);
//int getSource(int& n, CFG*& g);
std::vector<int> sources;
std::vector<int> sinks;
std::vector<int> recursiveLoops;
std::vector<int> recurses;
std::map<int, int> ptsNum;
bool borrowed;
std::set<int> badloop;
std::map<int, std::vector<std::vector<int> > > totalLoops;
// int pathnum;
std::map<int, std::string> nodeStrings;
int sourcenum;
unsigned long long evaledpaths;
int badpaths;
int workingthreadnum;
bool workingthread;
std::map<int, std::set<std::vector<int> > > loopStore;
std::vector<std::vector<int> > pathStore;
std::map<int, std::vector<int> > subpathglobal;
std::map<std::vector<int>, int> subpathglobalinv;
int nextsubpath;
std::vector<int> orderOfNodes;
// std::map<Vertex, int> vertintmap;
// std::map<Edge, int> edgeintmap;
// std::map<int, Vertex> intvertmap;
// std::map<int, Edge> intedgemap;
std::vector<std::map<Vertex, Vertex> > SubGraphGraphMap;
std::vector<std::map<Vertex, Vertex> > GraphSubGraphMap;
std::vector<CFG*> subGraphVector;
void getVertexPath(std::vector<int> path, CFG*& g, std::vector<Vertex>& vertexPath );
void storeCompact(std::vector<int> path);
int nextNode;
int nextEdge;
std::vector<int> markers;
std::vector<int> closures;
std::map<int, int> markerIndex;
std::map<int, std::vector<int> > pathsAtMarkers;
typedef typename boost::graph_traits<CFG>::vertex_iterator vertex_iterator;
typedef typename boost::graph_traits<CFG>::out_edge_iterator out_edge_iterator;
typedef typename boost::graph_traits<CFG>::in_edge_iterator in_edge_iterator;
typedef typename boost::graph_traits<CFG>::edge_iterator edge_iterator;
bool bound;
// SgGraphTraversal();
// virtual ~SgGraphTraversal();
// SgGraphTraversal( SgGraphTraversal &);
// SgGraphTraversal &operator=( SgGraphTraversal &);
};
template<class CFG>
SgGraphTraversal<CFG>::
SgGraphTraversal()
{
}
template<class CFG>
SgGraphTraversal<CFG> &
SgGraphTraversal<CFG>::
operator=( SgGraphTraversal &other)
{
return *this;
}
#ifndef SWIG
template<class CFG>
SgGraphTraversal<CFG>::
~SgGraphTraversal()
{
}
#endif
/**
Gets the source of an edge
SgGraphTraversal::getSource
Input:
@param[edge] int& integer representation of edge in question
@param[g] CFG*& the CFG used
*/
template<class CFG>
inline int
SgGraphTraversal<CFG>::
getSource(int& edge, CFG*& g)
{
Edge e = intedgemap[edge];
Vertex v = boost::source(e, *g);
return(vertintmap[v]);
}
/**
Gets the target of an edge
SgGraphTraversal::getTarget
Input:
@param[edge] int& integer representation of edge in quesution
@param[g] the CFG*& CFG used
*/
template<class CFG>
inline int
SgGraphTraversal<CFG>::
getTarget(int& edge, CFG*& g)
{
Edge e = intedgemap[edge];
Vertex v = boost::target(e, *g);
return(vertintmap[v]);
}
/**
Gets out edges with integer inputs, internal use only
SgGraphTraversal::getInEdges
Input:
@param[node] int, integer representation of the node to get the in edges from
@param[g] CFG* g, CFG
*/
template<class CFG>
std::vector<int>
SgGraphTraversal<CFG>::
getInEdges(int& node, CFG*& g)
{
Vertex getIns = intvertmap[node];
std::vector<int> inedges;
// DQ (4/11/2017): Fix Klockworks issue of uninitialized variables.
#if 1
in_edge_iterator i, j;
#else
// This does not compile.
in_edge_iterator i = inedges.begin();
in_edge_iterator j = i;
#endif
for (boost::tie(i, j) = boost::in_edges(getIns, *g); i != j; ++i)
{
inedges.push_back(edgeintmap[*i]);
}
return inedges;
}
/**
Gets out edges with integer inputs, internal use only
SgGraphTraversal::getOutEdges
Input:
@param[node] int, integer representation of the node to get the out edges from
@param[g] CFG* g, CFG
*/
template<class CFG>
std::vector<int>
SgGraphTraversal<CFG>::
getOutEdges(int &node, CFG*& g)
{
Vertex getOuts = intvertmap[node];
std::vector<int> outedges;
// DQ (4/11/2017): Fix Klockworks issue of uninitialized variables.
#if 1
out_edge_iterator i, j;
#else
// This does not compile.
out_edge_iterator i = outedges.begin();
out_edge_iterator j = i;
#endif
for (boost::tie(i, j) = boost::out_edges(getOuts, *g); i != j; ++i)
{
outedges.push_back(edgeintmap[*i]);
}
return outedges;
}
/**
Condenses paths, currently deprecated...
Input:
@param[pth] std::vector<int> the original path
@param[g] CFG*, the ambient graph
Output:
zipped path
*/
template<class CFG>
inline
std::vector<int>
SgGraphTraversal<CFG>::
zipPath2(std::vector<int>& pth, CFG*& g) {
std::vector<int> npth;
npth.push_back(pth[0]);
for (int i = 1; i < pth.size()-1; i++) {
if (find(closures.begin(), closures.end(), pth[i]) != closures.end()) {
npth.push_back(pth[i]);
}
}
npth.push_back(pth.back());
return npth;
}
/**
Condenses paths to simply the first and last node and the ordered set of edges
taken at nodes with more than 1 outedge
Input:
@param[pth] std::vector<int>, the original path
@param[g] CFG*, the ambient graph
@param[start] integer representation of the first node
@param[end] integer representation of the last node
*/
template<class CFG>
std::vector<int>
SgGraphTraversal<CFG>::
zipPath(std::vector<int>& pth, CFG*& g, int start, int end) {
std::vector<int> subpath;
std::vector<int> movepath;
movepath.push_back(pth.front());
movepath.push_back(pth.back());
for (unsigned int qw = 0; qw < pth.size()-1; qw++) {
if (find(markers.begin(), markers.end(), pth[qw]) != markers.end()) {
std::vector<int> oeds = getOutEdges(pth[qw], g);
for (unsigned int i = 0; i < oeds.size(); i++) {
if (getTarget(oeds[i], g) == pth[qw+1]) {
movepath.push_back(oeds[i]);
}
}
}
}
return movepath;
}
/**
unzips the paths zipped by zipPath
Input:
@param[pzipped] the zipped path
@param[CFG] the ambient graph
@param[start] the integer representation of the first node (used to check that zipPath is working correctly)
@param[end] the integer representation of the end node
*/
template<class CFG>
std::vector<int>
SgGraphTraversal<CFG>::
unzipPath(std::vector<int>& pzipped, CFG*& g, int start, int end) {
ROSE_ASSERT(pzipped[0] == start && (pzipped[1] == end || end == -1));
std::vector<int> zipped;
for (unsigned int i = 2; i < pzipped.size(); i++) {
zipped.push_back(pzipped[i]);
}
std::vector<int> unzipped;
unzipped.push_back(start);
std::vector<int> oeds = getOutEdges(start, g);
if (oeds.size() == 0) {
return unzipped;
}
for (unsigned int i = 0; i < zipped.size(); i++) {
oeds = getOutEdges(unzipped.back(), g);
while (oeds.size() == 1) {
if (getTarget(oeds[0], g) == end && unzipped.size() != 1) {
unzipped.push_back(end);
return unzipped;
}
unzipped.push_back(getTarget(oeds[0], g));
oeds = getOutEdges(unzipped.back(), g);
}
if (oeds.size() == 0) {
return unzipped;
}
if (oeds.size() > 1 && (unzipped.back() != end || (unzipped.size() == 1 && unzipped.back() == end))) {
ROSE_ASSERT(getSource(zipped[i], g) == unzipped.back());
unzipped.push_back(getTarget(zipped[i], g));
}
}
std::vector<int> oeds2 = getOutEdges(unzipped.back(), g);
if (unzipped.back() != end && oeds2.size() != 0) {
while (oeds2.size() == 1 && unzipped.back() != end) {
unzipped.push_back(getTarget(oeds2[0], g));
oeds2 = getOutEdges(unzipped.back(), g);
}
}
return unzipped;
}
/*
Example Time
Example:
timeval tim;
gettimeofday(&tim, NULL);
double t1=tim.tv_sec+(tim.tv_usec/1000000.0);
do_something_long();
gettimeofday(&tim, NULL);
double t2=tim.tv_sec+(tim.tv_usec/1000000.0);
printf("%.6lf seconds elapsed\n", t2-t1);
*/
/**
The function responsible for collecting all paths without loops, and all paths within lops that do not include other loops
then sending those to uTraverse to assemble them into all paths with any combination of loops
Input:
@param[begin] integer representation of the first node
@param[end] integer representation of the last node (or -1 if its not bounded)
@param[g] CFG*, the ambient CFG
@param[loop] boolean expressing whether or not we are calculating paths contained within a loop
*/
template<class CFG>
std::vector<std::vector<int> >
SgGraphTraversal<CFG>::
bfsTraversePath(int begin, int end, CFG*& g, bool loop) {
//perfdebug allows for examining the speed of traversal
#ifdef PERFDEBUG
//timeval tim;
//gettimeofday(&tim, NULL);
//double tim1 = tim.tv_sec+(tim.tv_usec/1000000.0);
#endif
bool recursedloop = loop;
std::map<int, std::vector<std::vector<int> > > PtP;
std::set<int> nodes;
std::vector<std::vector<int> > pathContainer;
//std::vector<std::vector<int> > oldPaths;
std::vector<int> completedLoops;
std::vector<std::vector<int> > npc;
std::vector<int> bgpath;
bgpath.push_back(begin);
pathContainer.push_back(bgpath);
std::vector<std::vector<int> > newPathContainer;
std::vector<std::vector<int> > paths;
std::vector<int> localLoops;
std::map<int, std::vector<std::vector<int> > > globalLoopPaths;
//std::cout << "at the while" << std::endl;
//To keep
while (pathContainer.size() != 0 /*|| oldPaths.size() != 0*/) {
/*
unsigned int mpc = 50000;
if (pathContainer.size() == 0) {
unsigned int mxl = 0;
if (oldPaths.size() > mpc) {
mxl = mpc/2;
}
else {
mxl = oldPaths.size();
}
for (unsigned int k = 0; k < mxl; k++) {
pathContainer.push_back(oldPaths.back());
oldPaths.pop_back();
}
}
if (pathContainer.size() > mpc) {
unsigned int j = 0;
while (j < mpc) {
npc.push_back(pathContainer.back());
pathContainer.pop_back();
j++;
}
oldPaths.insert(oldPaths.end(), pathContainer.begin(), pathContainer.end());
pathContainer = npc;
npc.clear();
}
*/
//iterating through the currently discovered subpaths to build them up
for (unsigned int i = 0; i < pathContainer.size(); i++) {
std::vector<int> npth = pathContainer[i];
std::vector<int> oeds = getOutEdges(npth.back(), g);
std::vector<int> ieds = getInEdges(npth.back(), g);
npth = pathContainer[i];
oeds = getOutEdges(npth.back(), g);
if ((!recursedloop && ((bound && npth.back() == end && npth.size() != 1) || (!bound && oeds.size() == 0))) || (recursedloop && npth.back() == end && npth.size() != 1)) {
std::vector<int> newpth;
newpth = (pathContainer[i]);
std::vector<int> movepath = newpth;//zipPath(newpth, g);
if (recursedloop && newpth.back() == end && newpth.size() != 1) {
paths.push_back(movepath);
}
else if (!recursedloop) {
if (bound && newpth.size() != 1 && newpth.back() == end) {
paths.push_back(movepath);
}
else if (!bound) {
paths.push_back(movepath);
}
}
}
else {
std::vector<int> oeds = getOutEdges(pathContainer[i].back(), g);
for (unsigned int j = 0; j < oeds.size(); j++) {
int tg = getTarget(oeds[j], g);
std::vector<int> newpath = (pathContainer[i]);
//we split up paths into pieces so that they don't take up a lot of memory, basically this is when we run into a path
//more than once, so we attach all paths that go to that path to that particular node via PtP
if (nodes.find(tg) != nodes.end() && find(newpath.begin(), newpath.end(), tg) == newpath.end() && tg != end) {
if (PtP.find(tg) == PtP.end()) {
std::vector<int> nv;
nv.push_back(tg);
newPathContainer.push_back(nv);
PtP[tg].push_back(/*zipPath(*(*/newpath);//, g, newpath.front(), newpath.back()));
}
else {
PtP[tg].push_back(/*zipPath(*/newpath);//, g, newpath.front(), newpath.back()));
}
}
else if (find(newpath.begin(), newpath.end(), getTarget(oeds[j], g)) == newpath.end() || getTarget(oeds[j], g) == end) {
newpath.push_back(tg);
std::vector<int> ieds = getInEdges(tg, g);
if (ieds.size() > 1) {//find(closures.begin(), closures.end(), tg) != closures.end()) {
nodes.insert(tg);
}
newPathContainer.push_back(newpath);
}
else if (tg == end && recursedloop) {
newpath.push_back(tg);
newPathContainer.push_back(newpath);
}
else {//if (find(newpath.begin(), newpath.end(), tg) != newpath.end() && tg != end) {
std::vector<int> ieds = getInEdges(tg, g);
if (ieds.size() > 1/*find(closures.begin(), closures.end(), tg) != closures.end()*/ && find(completedLoops.begin(), completedLoops.end(), tg) == completedLoops.end() /*&& find(localLoops.begin(), localLoops.end(), tg) == localLoops.end()*/ && find(recurses.begin(), recurses.end(), tg) == recurses.end()) {
localLoops.push_back(tg);
nodes.insert(tg);
}
// else if (find(recurses.begin(), recurses.end(), tg) != recurses.end()) {
// }
}
//else {
// std::cout << "problem" << std::endl;
// ROSE_ASSERT(false);
// }
}
}
}
pathContainer = newPathContainer;
newPathContainer.clear();
}
// std::cout << "done while" << std::endl;
pathContainer.clear();
std::vector<std::vector<int> > finnpts;
std::vector<std::vector<int> > npts;
while (true) {
if (paths.size() > 1000000) {
std::cout << "too many paths, consider a subgraph" << std::endl;
ROSE_ABORT();
}
//#pragma omp parallel for schedule(guided)
for (unsigned int qq = 0; qq < paths.size(); qq++) {
std::vector<int> pq = paths[qq];
std::vector<int> qp;
int ppf = paths[qq].front();
if (PtP.find(ppf) != PtP.end()) {
for (unsigned int kk = 0; kk < PtP[ppf].size(); kk++) {
std::vector<int> newpath = /*unzipPath(*/PtP[ppf][kk];//, g, PtP[ppf][kk][0], PtP[ppf][kk][1]);
bool good = true;
if (newpath.back() == newpath.front() && newpath.front() != begin && newpath.size() > 1) {
good = false;
}
else {
// if (find(pq.begin(), pq.end(), newpath.front()) != pq.end() && newpath.front() != begin) {
// good = false;
// }
// else {
for (unsigned int kk1 = 0; kk1 < newpath.size(); kk1++) {
/*
if (newpath.front() == newpath.back()) {
good = false;
break;
}
else */if (find(pq.begin(), pq.end(), newpath[kk1]) != pq.end() && newpath[kk1] != begin) {
good = false;
break;
}
}
//}
}
if (good) {
newpath.insert(newpath.end(), pq.begin(), pq.end());
#pragma omp critical
{
npts.push_back(newpath);
}
}
}
}
else {
std::vector<int> ppq = pq;// zipPath(pq, g, pq.front(), pq.back());
#pragma omp critical
{
finnpts.push_back(ppq);
}
}
}
if (npts.size() == 0) {
break;
}
else {
paths = npts;
npts.clear();
}
}
paths = finnpts;
finnpts.clear();
for (unsigned int k = 0; k < localLoops.size(); k++) {
int lk = localLoops[k];
std::vector<std::vector<int> > loopp;
if (loopStore.find(localLoops[k]) != loopStore.end()) {
loopp.insert(loopp.end(), loopStore[localLoops[k]].begin(), loopStore[localLoops[k]].end());
}
else {
std::map<int, std::vector<std::vector<int> > > localLoopPaths;
completedLoops.push_back(lk);
recurses.push_back(lk);
loopp = bfsTraversePath(lk, lk, g, true);
recurses.pop_back();
}
for (unsigned int ik = 0; ik < loopp.size(); ik++) {
if (find(globalLoopPaths[lk].begin(), globalLoopPaths[lk].end(), loopp[ik]) == globalLoopPaths[lk].end()) {
globalLoopPaths[localLoops[k]].push_back(loopp[ik]);
}
}
}
borrowed = true;
std::vector<std::vector<int> > lps2;
//unsigned int maxpaths = 1000;
//unsigned int pathdivisor = 1;//paths.size()/maxpaths;///paths.size();
//if (pathdivisor < 1) {
//pathdivisor = 1;
//maxpaths = paths.size();
// }
/*
for (unsigned int j = 0; j < pathdivisor+1; j++) {
std::vector<std::vector<int> > npaths;
std::vector<int> dummyvec;
unsigned int mxpths;
if (j < pathdivisor) {
mxpths = maxpaths;
}
else {
mxpths = paths.size() % pathdivisor;
}
for (unsigned int k = 0; k < mxpths; k++) {
npaths.push_back(paths.back());//unzipPath(paths.back(), g, begin, end));
paths.pop_back();
}
*/
pathStore = paths;
paths.clear();
if (!recursedloop) {
uTraversePath(begin, end, g, false, globalLoopPaths);
}
else {
recursed++;
std::set<std::vector<int> > lps = uTraversePath(begin, end, g, true, globalLoopPaths);
recursed--;
for (std::set<std::vector<int> >::iterator ij = lps.begin(); ij != lps.end(); ij++) {
std::vector<int> ijk = (*ij);
lps2.push_back(*ij);
}
}
//}
#ifdef PERFDEBUG
// timeval tim;
//std::cout << "begin: " << begin << " end: " << end << std::endl;
//gettimeofday(&tim, NULL);
//double tim2 = tim.tv_sec+(tim.tv_usec/1000000);
//double timeRet = tim2 - tim1;
//std::cout << "bfs time elapsed: " << timeRet << std::endl;
#endif
return lps2;
}
/**
This function calculates all the permutations of loops on paths
it also throws away duplicate paths
Input:
@param[begin] integer representation of first node
@param[end] integer representation of the final node
@param[g] ambient CFG
@param[globalLoopPaths] connects an integer representation of a node to all possible loops starting at that node
*/
template<class CFG>
std::set<std::vector<int> >
SgGraphTraversal<CFG>::
uTraversePath(int begin, int end, CFG*& g, bool loop, std::map<int, std::vector<std::vector<int> > >& globalLoopPaths) {
//std::cout << "uTraverse" << std::endl;
//int doubledpaths = 0;
int newmil = 1;
//#ifdef LP
//if (loop && loopStore.find(begin) != loopStore.end()) {
// return loopStore[begin];
//}
//#endif
#ifdef PERFDEBUG
//timeval tim;
//gettimeofday(&tim, NULL);
//double t1 = tim.tv_sec+(tim.tv_usec/1000000);
#endif
std::set<std::vector<int> > newpaths;
std::set<std::vector<int> > npaths;
pathnum = 0;
std::vector<int> path;
std::vector<std::vector<int> > paths;
int truepaths = 0;
std::vector<std::vector<int> > checkpaths;
std::vector<std::vector<int> > npathchecker;
std::map<int, int> currents;
//int nnumpaths = 0;
std::set<std::vector<int> > loopPaths;
//bool threadsafe = true;
bool done = false;
std::set<std::vector<int> > fts;
//double ttfors = 0;
//double tperms = 0;
while (true) {
//std::cout << "paths.size() " << paths.size() << std::endl;
if (paths.size() > 1000000) {
std::cout << "nearly 1 million paths with no loops, stopping" << std::endl;
return loopPaths;
std::cout << "ended early" << std::endl;
}
if (done || borrowed) {
if (borrowed) {
paths = pathStore;
pathStore.clear();
}
//std::cout << "paths.size(): " << paths.size() << std::endl;
if (paths.size() != 0) {
}
else {
return loopPaths;
}
// #pragma omp parallel
// {
#pragma omp parallel for schedule(guided)
for (unsigned int qqq = 0; qqq < paths.size(); qqq++) {
// std::cout << "pathcheck" << std::endl;
//int pathevals = 0;
//std::vector<int> zpt = zipPath2(paths[qqq], g);
//std::set<std::vector<int> > boxpaths;
std::set<std::vector<int> > movepaths;
std::vector<int> path;// = paths[qqq];
path = paths[qqq];//unzipPath(paths[qqq], g, begin, end);
truepaths++;
int permnums = 1;
std::vector<int> perms;
std::vector<unsigned int> qs;
std::map<int, std::vector<std::vector<int> > > localLoops;
std::vector<int> takenLoops;
takenLoops.push_back(path[0]);
bool taken = false;
//timeval timfor;
int lost = 0;
//gettimeofday(&timfor, NULL);
//double t1for = timfor.tv_sec + (timfor.tv_usec/1000000);
for (unsigned int q = 1; q < path.size()-1; q++) {
//if (find(closures.begin(), closures.end(), path[q]) != closures.end()) {
if (globalLoopPaths.find(path[q]) != globalLoopPaths.end() /*&& find(lloops.begin(), lloops.end(), path[q]) != lloops.end()*/ && globalLoopPaths[path[q]].size() != 0 /*&& path[q] != begin && path[q] != end*/) {
for (unsigned int qp1 = 0; qp1 < globalLoopPaths[path[q]].size(); qp1++) {
std::vector<int> gp = globalLoopPaths[path[q]][qp1]; //unzipPath(globalLoopPaths[path[q]][qp1],g,path[q],path[q]);
// std::vector<int> zgp = zipPath2(globalLoopPaths[zpt[q]][qp1], g);
for (unsigned int qp2 = 0; qp2 < takenLoops.size(); qp2++) {
if (find(gp.begin(),gp.end(), takenLoops[qp2]) != gp.end()) {
taken = true;
}
}
if (!taken) {
localLoops[path[q]].push_back(gp);
}
else {
lost++;
taken = false;
}
}
if (localLoops[path[q]].size() != 0) {
takenLoops.push_back(path[q]);
permnums *= (localLoops[path[q]].size()+1);
perms.push_back(permnums);
qs.push_back(path[q]);
}
}
}
//}
//if (loop) {
//std::cout << "lostloop: " << lost << std::endl;
//}
//else {
//std::cout << "lostpath: " << lost << std::endl;
//}
//std::cout << "endpathcheck" << std::endl;
//std::cout << "rest" << std::endl;
//std::cout << "permnums: " << permnums << std::endl;
//gettimeofday(&timfor, NULL);
//double t2for = timfor.tv_sec + (timfor.tv_usec/1000000);
//double ttfor = t2for - t1for;
//#pragma omp atomic
//ttfors += ttfor;
//std::set<std::vector<int> > movepaths2;
std::set<std::vector<int> > movepathscheck;
//timeval timperms;
//gettimeofday(&timperms, NULL);
// double t1perm = timperms.tv_sec + (timperms.tv_usec/1000000);
std::vector<int> nvec;
std::vector<std::vector<int> > boxpaths(permnums, nvec);
//#pragma omp parallel for schedule(guided)
for (int i = 1; i <= permnums; i++) {
//bool goodthread = false;
std::vector<int> loopsTaken;
//bool stop = false;
unsigned int j = 0;
std::vector<int> npath;
while (true) {
if (j == perms.size() || perms[j] > i) {
break;
}
else {
j++;
}
}
int pn = i;
std::vector<int> pL;
for (unsigned int j1 = 0; j1 <= j; j1++) {
pL.push_back(-1);
}
for (unsigned int k = j; k > 0; k--) {
int l = 1;
while (perms[k-1]*l < pn) {
l++;
}
pL[k] = l-2;
pn -= (perms[k-1]*(l-1));
}
pL[0] = pn-2;
unsigned int q2 = 0;
for (unsigned int q1 = 0; q1 < path.size(); q1++) {
if (q2 < qs.size()) {
if (qs.size() != 0 && (unsigned)path[q1] == qs[q2] && (size_t)q2 != pL.size()) {
if (pL[q2] == -1) {
npath.push_back(path[q1]);
}
else {
// if (!stop) {
npath.insert(npath.end(), localLoops[path[q1]][pL[q2]].begin(),
localLoops[path[q1]][pL[q2]].end());
// }
}
q2++;
}
else {
npath.push_back(path[q1]);
}
}
else {
npath.push_back(path[q1]);
}
}
#ifdef FULLDEBUG
std::cout << "path: " << std::endl;
for (int qe = 0; qe < npath.size(); qe++) {
std::cout << ", " << npath[qe];
}
std::cout << std::endl;
std::cout << "permnum: " << i << std::endl;
#endif
// bool addit = false;
//if (!stop) {
// if (loop && npath.front() == npath.back()) {
// addit = true;
// }
// else if (!loop && bound && npath.front() == begin && npath.back() == end && npath.size() != 1) {
// addit = true;
// }
// else if (!loop && !bound) {
// addit = true;
// }
// if (!addit) {
// std::cout << "bad path" << std::endl;
// }
//bool extra = false;
//if (addit && !loop) {
//if (movepathscheck.find(npath) == movepathscheck.end()) {
//int mpc = movepathscheck.size();
//std::set<std::vector<int> > movepathspre = movepathscheck;
// movepaths2.insert(npath);
//movepathscheck.insert(npath);
//ROSE_ASSERT(movepathscheck.size() == mpc || movepathspre.find(npath) == movepathspre.end());
//if (movepathscheck.size() == mpc) {
// extra = true;
// }
//}
//else {
//#pragma omp atomic
// doubledpaths++;
// }
//}
//if (!workingthread || threadsafe) {
//if ((newpaths.size() > 1 || i == permnums || threadsafe)) {
// }
// }
// }
//if (!extra)
// {
//if (movepaths2.size() > 0) //|| i == permnums || threadsafe)
// #pragma omp critical
// {
boxpaths[i-1] = npath;
// }
// }
//std::cout << "endrest" << std::endl;
}
evaledpaths += boxpaths.size();
if (evaledpaths > newmil*100000ull) {
//std::cout << "evaledpaths: " << evaledpaths << std::endl;
newmil++;
}
// #pragma omp critical
// {
if (!loop) {
for (std::vector<std::vector<int> >::iterator box = boxpaths.begin(); box != boxpaths.end(); box++) {
std::vector<Vertex> verts;
getVertexPath((*box), g, verts);
#pragma omp critical
{
analyzePath(verts);
}
}
}
else {
#pragma omp critical
{
loopPaths.insert(boxpaths.begin(), boxpaths.end());;
}
}
}
}
//}
/*
#pragma omp atomic
evaledpaths++;
//pathevals++;
if (evaledpaths % 10000 == 0 && evaledpaths != 0) {
std::cout << "evaled paths: " << evaledpaths << std::endl;
}
if (!loop) {
std::vector<Vertex> verts;
getVertexPath(npath, g, verts);
#pragma omp critical
{
#ifdef FULLDEBUG
for (unsigned int aa = 0; aa < npath.size(); aa++) {
if (ptsNum.find(npath[aa]) != ptsNum.end()) {
ptsNum[npath[aa]] += 1;
}
else {
ptsNum[npath[aa]] = 1;
}
}
#endif
analyzePath(verts);
}
}
else if (loop)
{
//std::vector<int> zpth = zipPath(npath, g, npath.front(), npath.back());
#pragma omp critical
{
loopPaths.insert(npath);//zipPath(npath, g, npath.front(), npath.back()));
}
}
else {
}
}
*/
// movepaths2.clear();
// std::cout << "permnums: " << permnums << std::endl;
// std::cout << "evaledpaths final: " << pathevals << std::endl;
//gettimeofday(&timperms, NULL);
//double t2perm = timperms.tv_sec+(timperms.tv_usec/1000000);
//#pragma omp atomic
//tperms += t2perm - t1perm;
// }
//}
//}
//}
#ifdef PERFDEBUG
//gettimeofday(&tim, NULL);
// double t2 = tim.tv_sec+(tim.tv_usec/1000000.0);
// double tperm = t2 - t1perm
//double tX = t2 - t1;
//std::cout << "begin: " << begin << " end: " << end << std::endl;
// std::cout << "uTraverse time: " << tX << std::endl;
// std::cout << "tperms: " << tperms << std::endl;
// std::cout << "ttfors: " << ttfors << std::endl;
// std::cout << "doubledpaths: " << doubledpaths << std::endl;
#endif
#ifdef LP
if (loop) {
#ifdef PERFDEBUG
// std::cout << "loopPaths: " << loopPaths.size() << std::endl;
#endif
loopStore[begin] = loopPaths;
}
#endif
return loopPaths;
}
}
/**
This is the function that is used by the user directly to start the algorithm. It is immediately available to the user
SgGraphTraversal::constructPathAnalyzer
Input:
@param[begin] Vertex, starting node
@param[end] Vertex, endnode
@param[g] CFG* g, CFG calculated previously
*/
template<class CFG>
void
SgGraphTraversal<CFG>::
constructPathAnalyzer(CFG* g, bool unbounded, Vertex begin, Vertex end, bool ns) {
abnormals = 0;
normals = 0;
if (ns) {
needssafety = true;
}
else {
needssafety = false;
}
checkedfound = 0;
recursed = 0;
nextsubpath = 0;
borrowed = true;
stoppedpaths = 0;
evaledpaths = 0;
badpaths = 0;
sourcenum = 0;
prepareGraph(g);
workingthread = false;
workingthreadnum = -1;
//std::cout << "markers: " << markers.size() << std::endl;
//std::cout << "closures: " << closures.size() << std::endl;
//std::cout << "sources: " << sources.size() << std::endl;
//std::cout << "sinks" << sinks.size() << std::endl;
// printHotness(g);
bool subgraph = false;
if (!subgraph) {
if (!unbounded) {
bound = true;
recursiveLoops.clear();
recurses.clear();
std::vector<std::vector<int> > spaths = bfsTraversePath(vertintmap[begin], vertintmap[end], g);
// std::cout << "spaths: " << spaths.size() << std::endl;
}
else {
std::set<int> usedsources;
bound = false;
std::vector<int> localLps;
for (unsigned int j = 0; j < sources.size(); j++) {
sourcenum = sources[j];
recursiveLoops.clear();
recurses.clear();
std::vector<std::vector<int> > spaths = bfsTraversePath(sources[j], -1, g);
}
}
}
//std::cout << "checkedfound: " << checkedfound << std::endl;
printHotness(g);
}
/** DEPRECATED
This is a function to construct subgraphs for parallelization
SgGraphTraversal::computeSubGraphs
Input:
@param[begin] const int, starting point
@param[end] const int ending point
@param[g] const CFG*, control flow graph to compute
@param[depthDifferential] int, used to specify how large the subgraph should be
*/
template<class CFG>
void
SgGraphTraversal<CFG>::
computeSubGraphs(const int& begin, const int &end, CFG*& g, int depthDifferential) {
int minDepth = 0;
int maxDepth = minDepth + depthDifferential;
int currSubGraph = 0;
CFG* subGraph;
std::set<int> foundNodes;
while (true) {
Vertex begin = boost::add_vertex(*subGraphVector[currSubGraph]);
GraphSubGraphMap[currSubGraph][intvertmap[orderOfNodes[minDepth]]] = intvertmap[begin];
SubGraphGraphMap[currSubGraph][intvertmap[begin]] = intvertmap[orderOfNodes[minDepth]];
for (int i = minDepth; i <= maxDepth; i++) {
Vertex v = GraphSubGraphMap[currSubGraph][intvertmap[orderOfNodes[i]]];
std::vector<int> outEdges = getOutEdges(orderOfNodes[i], g);
for (unsigned int j = 0; j < outEdges.size(); j++) {
Vertex u;
if (foundNodes.find(getTarget(outEdges[j], g)) == foundNodes.end()) {
u = GraphSubGraphMap[currSubGraph][intvertmap[getTarget(outEdges[j], g)]];
}
else {
u = boost::add_vertex(*subGraphVector[currSubGraph]);
foundNodes.insert(getTarget(outEdges[j], g));
SubGraphGraphMap[currSubGraph][u] = intvertmap[getTarget(outEdges[j], g)];
GraphSubGraphMap[currSubGraph][intvertmap[getTarget(outEdges[j], g)]] = u;
}
Edge edge;
bool ok;
boost::tie(edge, ok) = boost::add_edge(v,u,*subGraphVector[currSubGraph]);
}
}
minDepth = maxDepth;
if ((unsigned int) minDepth == orderOfNodes.size()-1) {
break;
}
maxDepth += depthDifferential;
if ((unsigned int) maxDepth > orderOfNodes.size()-1)
{
maxDepth = orderOfNodes.size()-1;
}
CFG* newSubGraph;
subGraphVector.push_back(newSubGraph);
currSubGraph++;
}
return;
}
/*
These should NOT be used by the user. They are simply for writing interesting information on the DOT graphs of the CFG
*/
template<class CFG>
void
SgGraphTraversal<CFG>::
printCFGNodeGeneric(int &cf, std::string prop, std::ofstream& o) {
std::string nodeColor = "black";
o << cf << " [label=\"" << " num:" << cf << " prop: " << prop << "\", color=\"" << nodeColor << "\", style=\"" << "solid" << "\"];\n";
}
template<class CFG>
void
SgGraphTraversal<CFG>::
printCFGNode(int& cf, std::ofstream& o)
{
#ifdef FULLDEBUG
int pts = ptsNum[cf];
std::string nodeColor = "black";
o << cf << " [label=\"" << " pts: " << pts << "\", color=\"" << nodeColor << "\", style=\"" << "solid" << "\"];\n";
#endif
#ifndef FULLDEBUG
std::string nodeColor = "black";
o << cf << " [label=\"" << " num:" << cf << "\", color=\"" << nodeColor << "\", style=\"" << "solid" << "\"];\n";
#endif
}
template<class CFG>
void
SgGraphTraversal<CFG>::
printCFGEdge(int& cf, CFG*& cfg, std::ofstream& o)
{
int src = getSource(cf, cfg);
int tar = getTarget(cf, cfg);
o << src << " -> " << tar << " [label=\"" << src << " " << tar << "\", style=\"" << "solid" << "\"];\n";
}
template<class CFG>
void
SgGraphTraversal<CFG>::
printHotness(CFG*& g)
{
const CFG* gc = g;
int currhot = 0;
std::ofstream mf;
std::stringstream filenam;
filenam << "hotness" << currhot << ".dot";
currhot++;
std::string fn = filenam.str();
mf.open(fn.c_str());
mf << "digraph defaultName { \n";
// DQ (4/11/2017): Fix Klockworks issue of uninitialized variables.
#if 1
vertex_iterator v, vend;
edge_iterator e, eend;
#else
// This does not compile.
vertex_iterator v = vertices(*gc).begin();
vertex_iterator vend = v;
edge_iterator e = edges(*gc).begin();
edge_iterator eend = e;
#endif
for (boost::tie(v, vend) = vertices(*gc); v != vend; ++v)
{
printCFGNode(vertintmap[*v], mf);
}
for (tie(e, eend) = edges(*gc); e != eend; ++e)
{
printCFGEdge(edgeintmap[*e], g, mf);
}
mf.close();
}
template<class CFG>
void
SgGraphTraversal<CFG>::
printPathDot(CFG*& g)
{
const CFG* gc = g;
std::ofstream mf;
std::stringstream filenam;
filenam << "pathnums.dot";
std::string fn = filenam.str();
mf.open(fn.c_str());
mf << "digraph defaultName { \n";
vertex_iterator v, vend;
edge_iterator e, eend;
for (tie(v, vend) = vertices(*gc); v != vend; ++v)
{
if (nodeStrings.find(vertintmap[*v]) != nodeStrings.end()) {
int nn = vertintmap[*v];
printCFGNodeGeneric(vertintmap[*v], nodeStrings[nn], mf);
}
else {
printCFGNodeGeneric(vertintmap[*v], "noprop", mf);
}
}
for (tie(e, eend) = edges(*gc); e != eend; ++e)
{
printCFGEdge(edgeintmap[*e], g, mf);
}
mf.close();
}
/**
This is the function that preps the graph for traversal
SgGraphTraversal::prepareGraph
Input:
@param[g] CFG*& g, CFG calculated previously
*/
template<class CFG>
void
SgGraphTraversal<CFG>::
prepareGraph(CFG*& g) {
nextNode = 1;
nextEdge = 1;
findClosuresAndMarkersAndEnumerate(g);
}
/**
DEPRECATED
This is the function that preps the graph for traversal, currently this one isn't used but for many traversals on one visitor
may necessitate
SgGraphTraversal::firstPrepGraph
Input:
@param[g] CFG*& g, CFG calculated previously
*/
template<class CFG>
void
SgGraphTraversal<CFG>::
firstPrepGraph(CFG*& g) {
nextNode = 1;
nextEdge = 1;
findClosuresAndMarkersAndEnumerate(g);
}
/**
This calculates nodes with more than one in edge or more than one out edge
SgGraphTraversal::findClosuresAndMarkers
Input:
@param[g] CFG*& g, CFG calculated previously
*/
template<class CFG>
void
SgGraphTraversal<CFG>::
findClosuresAndMarkersAndEnumerate(CFG*& g)
{
// DQ (4/11/2017): Fix Klockworks issue of uninitialized variables.
#if 1
edge_iterator e, eend;
#else
edge_iterator e = edges(*g).begin();
edge_iterator eend = e;
#endif
for (tie(e, eend) = edges(*g); e != eend; ++e) {
intedgemap[nextEdge] = *e;
edgeintmap[*e] = nextEdge;
nextEdge++;
}
// DQ (4/11/2017): Fix Klockworks issue of uninitialized variables.
#if 1
vertex_iterator v1, vend1;
#else
vertex_iterator v1 = vertices(*g).begin();
vertex_iterator vend1 = v1;
#endif
for (boost::tie(v1, vend1) = vertices(*g); v1 != vend1; ++v1)
{
vertintmap[*v1] = nextNode;
intvertmap[nextNode] = *v1;
nextNode++;
}
// DQ (4/11/2017): Fix Klockworks issue of uninitialized variables.
#if 1
vertex_iterator v, vend;
#else
vertex_iterator v = vertices(*g).begin();
vertex_iterator vend = v;
#endif
for (boost::tie(v, vend) = vertices(*g); v != vend; ++v) {
std::vector<int> outs = getOutEdges(vertintmap[*v], g);
std::vector<int> ins = getInEdges(vertintmap[*v], g);
if (outs.size() > 1)
{
markers.push_back(vertintmap[*v]);
markerIndex[vertintmap[*v]] = markers.size()-1;
for (unsigned int i = 0; i < outs.size(); i++) {
pathsAtMarkers[vertintmap[*v]].push_back(getTarget(outs[i], g));
}
}
if (ins.size() > 1)
{
closures.push_back(vertintmap[*v]);
}
if (outs.size() == 0) {
sinks.push_back(vertintmap[*v]);
}
if (ins.size() == 0) {
sources.push_back(vertintmap[*v]);
}
}
return;
}
/** DEPRECATED
Currently unused but will be necessary for parallelization in progress
SgGraphTraversal::computeOrder
@param[g] CFG* cfg in question
@parm[begin] const int, integer representation of source node
*/
template<class CFG>
void
SgGraphTraversal<CFG>::
computeOrder(CFG*& g, const int& begin) {
std::vector<int> currentNodes;
std::vector<int> newCurrentNodes;
currentNodes.push_back(begin);
std::map<int, int> reverseCurrents;
orderOfNodes.push_back(begin);
std::set<int> heldBackNodes;
while (currentNodes.size() != 0) {
for (unsigned int j = 0; j < currentNodes.size(); j++) {
std::vector<int> inEdges = getInEdges(currentNodes[j], g);
if (inEdges.size() > 1) {
if (reverseCurrents.find(currentNodes[j]) == reverseCurrents.end()) {
reverseCurrents[currentNodes[j]] = 0;
}
if ((unsigned int) reverseCurrents[currentNodes[j]] == inEdges.size() - 1) {
heldBackNodes.erase(currentNodes[j]);
reverseCurrents[currentNodes[j]]++;
std::vector<int> outEdges = getOutEdges(currentNodes[j], g);
for (unsigned int k = 0; k < outEdges.size(); k++) {
newCurrentNodes.push_back(getTarget(outEdges[k], g));
orderOfNodes.push_back(getTarget(outEdges[k], g));
}
}
else if (reverseCurrents[currentNodes[j]] < reverseCurrents.size()) {
reverseCurrents[currentNodes[j]]++;
if (heldBackNodes.find(currentNodes[j]) == heldBackNodes.end()) {
heldBackNodes.insert(currentNodes[j]);
}
}
}
else {
std::vector<int> outEdges = getOutEdges(currentNodes[j], g);
for (unsigned int k = 0; k < outEdges.size(); k++) {
newCurrentNodes.push_back(getTarget(outEdges[k], g));
orderOfNodes.push_back(getTarget(outEdges[k], g));
}
}
}
if (newCurrentNodes.size() == 0 && heldBackNodes.size() != 0) {
for (std::set<int>::iterator q = heldBackNodes.begin(); q != heldBackNodes.end(); q++) {
int qint = *q;
std::vector<int> heldBackOutEdges = getOutEdges(qint, g);
for (unsigned int p = 0; p < heldBackOutEdges.size(); p++) {
newCurrentNodes.push_back(getTarget(heldBackOutEdges[p], g));
}
}
heldBackNodes.clear();
}
currentNodes = newCurrentNodes;
newCurrentNodes.clear();
}
return;
}
/**
Converts the path calculated by this algorithm to Vertices so users can
access data
SgGraphTraversal::getVertexPath
@param[path] integer representation of path
@param[g] CFG*, cfg in question
@param[vertexPath] for some reason this can't be a return value so it is changed via pass by reference
*/
template<class CFG>
void
SgGraphTraversal<CFG>::
getVertexPath(std::vector<int> path, CFG*& g, std::vector<Vertex>& vertexPath) {
for (unsigned int i = 0; i < path.size(); i++) {
vertexPath.push_back(intvertmap[path[i]]);
}
}
/**
DEPRECATED
Currently unused, may eventually be modified for optimal storage purposes
SgGraphTraversal::storeCompact
@param[compactPath] path to be compactified
*/
template<class CFG>
void
SgGraphTraversal<CFG>::
storeCompact(std::vector<int> compactPath) {
return;
}
|
StmtOpenMP.h | //===- StmtOpenMP.h - Classes for OpenMP directives ------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
/// \file
/// This file defines OpenMP AST classes for executable directives and
/// clauses.
///
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_AST_STMTOPENMP_H
#define LLVM_CLANG_AST_STMTOPENMP_H
#include "clang/AST/Expr.h"
#include "clang/AST/OpenMPClause.h"
#include "clang/AST/Stmt.h"
#include "clang/Basic/OpenMPKinds.h"
#include "clang/Basic/SourceLocation.h"
namespace clang {
//===----------------------------------------------------------------------===//
// AST classes for directives.
//===----------------------------------------------------------------------===//
/// This is a basic class for representing single OpenMP executable
/// directive.
///
class OMPExecutableDirective : public Stmt {
friend class ASTStmtReader;
/// Kind of the directive.
OpenMPDirectiveKind Kind;
/// Starting location of the directive (directive keyword).
SourceLocation StartLoc;
/// Ending location of the directive.
SourceLocation EndLoc;
/// Numbers of clauses.
const unsigned NumClauses;
/// Number of child expressions/stmts.
const unsigned NumChildren;
/// Offset from this to the start of clauses.
/// There are NumClauses pointers to clauses, they are followed by
/// NumChildren pointers to child stmts/exprs (if the directive type
/// requires an associated stmt, then it has to be the first of them).
const unsigned ClausesOffset;
/// Get the clauses storage.
MutableArrayRef<OMPClause *> getClauses() {
OMPClause **ClauseStorage = reinterpret_cast<OMPClause **>(
reinterpret_cast<char *>(this) + ClausesOffset);
return MutableArrayRef<OMPClause *>(ClauseStorage, NumClauses);
}
protected:
/// Build instance of directive of class \a K.
///
/// \param SC Statement class.
/// \param K Kind of OpenMP directive.
/// \param StartLoc Starting location of the directive (directive keyword).
/// \param EndLoc Ending location of the directive.
///
template <typename T>
OMPExecutableDirective(const T *, StmtClass SC, OpenMPDirectiveKind K,
SourceLocation StartLoc, SourceLocation EndLoc,
unsigned NumClauses, unsigned NumChildren)
: Stmt(SC), Kind(K), StartLoc(std::move(StartLoc)),
EndLoc(std::move(EndLoc)), NumClauses(NumClauses),
NumChildren(NumChildren),
ClausesOffset(llvm::alignTo(sizeof(T), alignof(OMPClause *))) {}
/// Sets the list of variables for this clause.
///
/// \param Clauses The list of clauses for the directive.
///
void setClauses(ArrayRef<OMPClause *> Clauses);
/// Set the associated statement for the directive.
///
/// /param S Associated statement.
///
void setAssociatedStmt(Stmt *S) {
assert(hasAssociatedStmt() && "no associated statement.");
*child_begin() = S;
}
public:
/// Iterates over a filtered subrange of clauses applied to a
/// directive.
///
/// This iterator visits only clauses of type SpecificClause.
template <typename SpecificClause>
class specific_clause_iterator
: public llvm::iterator_adaptor_base<
specific_clause_iterator<SpecificClause>,
ArrayRef<OMPClause *>::const_iterator, std::forward_iterator_tag,
const SpecificClause *, ptrdiff_t, const SpecificClause *,
const SpecificClause *> {
ArrayRef<OMPClause *>::const_iterator End;
void SkipToNextClause() {
while (this->I != End && !isa<SpecificClause>(*this->I))
++this->I;
}
public:
explicit specific_clause_iterator(ArrayRef<OMPClause *> Clauses)
: specific_clause_iterator::iterator_adaptor_base(Clauses.begin()),
End(Clauses.end()) {
SkipToNextClause();
}
const SpecificClause *operator*() const {
return cast<SpecificClause>(*this->I);
}
const SpecificClause *operator->() const { return **this; }
specific_clause_iterator &operator++() {
++this->I;
SkipToNextClause();
return *this;
}
};
template <typename SpecificClause>
static llvm::iterator_range<specific_clause_iterator<SpecificClause>>
getClausesOfKind(ArrayRef<OMPClause *> Clauses) {
return {specific_clause_iterator<SpecificClause>(Clauses),
specific_clause_iterator<SpecificClause>(
llvm::makeArrayRef(Clauses.end(), 0))};
}
template <typename SpecificClause>
llvm::iterator_range<specific_clause_iterator<SpecificClause>>
getClausesOfKind() const {
return getClausesOfKind<SpecificClause>(clauses());
}
/// Gets a single clause of the specified kind associated with the
/// current directive iff there is only one clause of this kind (and assertion
/// is fired if there is more than one clause is associated with the
/// directive). Returns nullptr if no clause of this kind is associated with
/// the directive.
template <typename SpecificClause>
const SpecificClause *getSingleClause() const {
auto Clauses = getClausesOfKind<SpecificClause>();
if (Clauses.begin() != Clauses.end()) {
assert(std::next(Clauses.begin()) == Clauses.end() &&
"There are at least 2 clauses of the specified kind");
return *Clauses.begin();
}
return nullptr;
}
/// Returns true if the current directive has one or more clauses of a
/// specific kind.
template <typename SpecificClause>
bool hasClausesOfKind() const {
auto Clauses = getClausesOfKind<SpecificClause>();
return Clauses.begin() != Clauses.end();
}
/// Returns starting location of directive kind.
SourceLocation getBeginLoc() const { return StartLoc; }
/// Returns ending location of directive.
SourceLocation getEndLoc() const { return EndLoc; }
/// Set starting location of directive kind.
///
/// \param Loc New starting location of directive.
///
void setLocStart(SourceLocation Loc) { StartLoc = Loc; }
/// Set ending location of directive.
///
/// \param Loc New ending location of directive.
///
void setLocEnd(SourceLocation Loc) { EndLoc = Loc; }
/// Get number of clauses.
unsigned getNumClauses() const { return NumClauses; }
/// Returns specified clause.
///
/// \param i Number of clause.
///
OMPClause *getClause(unsigned i) const { return clauses()[i]; }
/// Returns true if directive has associated statement.
bool hasAssociatedStmt() const { return NumChildren > 0; }
/// Returns statement associated with the directive.
const Stmt *getAssociatedStmt() const {
assert(hasAssociatedStmt() && "no associated statement.");
return *child_begin();
}
Stmt *getAssociatedStmt() {
assert(hasAssociatedStmt() && "no associated statement.");
return *child_begin();
}
/// Returns the captured statement associated with the
/// component region within the (combined) directive.
//
// \param RegionKind Component region kind.
const CapturedStmt *getCapturedStmt(OpenMPDirectiveKind RegionKind) const {
SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
getOpenMPCaptureRegions(CaptureRegions, getDirectiveKind());
assert(std::any_of(
CaptureRegions.begin(), CaptureRegions.end(),
[=](const OpenMPDirectiveKind K) { return K == RegionKind; }) &&
"RegionKind not found in OpenMP CaptureRegions.");
auto *CS = cast<CapturedStmt>(getAssociatedStmt());
for (auto ThisCaptureRegion : CaptureRegions) {
if (ThisCaptureRegion == RegionKind)
return CS;
CS = cast<CapturedStmt>(CS->getCapturedStmt());
}
llvm_unreachable("Incorrect RegionKind specified for directive.");
}
/// Get innermost captured statement for the construct.
CapturedStmt *getInnermostCapturedStmt() {
assert(hasAssociatedStmt() && getAssociatedStmt() &&
"Must have associated statement.");
SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
getOpenMPCaptureRegions(CaptureRegions, getDirectiveKind());
assert(!CaptureRegions.empty() &&
"At least one captured statement must be provided.");
auto *CS = cast<CapturedStmt>(getAssociatedStmt());
for (unsigned Level = CaptureRegions.size(); Level > 1; --Level)
CS = cast<CapturedStmt>(CS->getCapturedStmt());
return CS;
}
const CapturedStmt *getInnermostCapturedStmt() const {
return const_cast<OMPExecutableDirective *>(this)
->getInnermostCapturedStmt();
}
OpenMPDirectiveKind getDirectiveKind() const { return Kind; }
static bool classof(const Stmt *S) {
return S->getStmtClass() >= firstOMPExecutableDirectiveConstant &&
S->getStmtClass() <= lastOMPExecutableDirectiveConstant;
}
child_range children() {
if (!hasAssociatedStmt())
return child_range(child_iterator(), child_iterator());
Stmt **ChildStorage = reinterpret_cast<Stmt **>(getClauses().end());
/// Do not mark all the special expression/statements as children, except
/// for the associated statement.
return child_range(ChildStorage, ChildStorage + 1);
}
ArrayRef<OMPClause *> clauses() { return getClauses(); }
ArrayRef<OMPClause *> clauses() const {
return const_cast<OMPExecutableDirective *>(this)->getClauses();
}
/// Returns whether or not this is a Standalone directive.
///
/// Stand-alone directives are executable directives
/// that have no associated user code.
bool isStandaloneDirective() const;
/// Returns the AST node representing OpenMP structured-block of this
/// OpenMP executable directive,
/// Prerequisite: Executable Directive must not be Standalone directive.
const Stmt *getStructuredBlock() const;
Stmt *getStructuredBlock() {
return const_cast<Stmt *>(
const_cast<const OMPExecutableDirective *>(this)->getStructuredBlock());
}
};
/// This represents '#pragma omp parallel' directive.
///
/// \code
/// #pragma omp parallel private(a,b) reduction(+: c,d)
/// \endcode
/// In this example directive '#pragma omp parallel' has clauses 'private'
/// with the variables 'a' and 'b' and 'reduction' with operator '+' and
/// variables 'c' and 'd'.
///
class OMPParallelDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
/// true if the construct has inner cancel directive.
bool HasCancel;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive (directive keyword).
/// \param EndLoc Ending Location of the directive.
///
OMPParallelDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned NumClauses)
: OMPExecutableDirective(this, OMPParallelDirectiveClass, OMPD_parallel,
StartLoc, EndLoc, NumClauses, 1),
HasCancel(false) {}
/// Build an empty directive.
///
/// \param NumClauses Number of clauses.
///
explicit OMPParallelDirective(unsigned NumClauses)
: OMPExecutableDirective(this, OMPParallelDirectiveClass, OMPD_parallel,
SourceLocation(), SourceLocation(), NumClauses,
1),
HasCancel(false) {}
/// Set cancel state.
void setHasCancel(bool Has) { HasCancel = Has; }
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement associated with the directive.
/// \param HasCancel true if this directive has inner cancel directive.
///
static OMPParallelDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, bool HasCancel);
/// Creates an empty directive with the place for \a N clauses.
///
/// \param C AST context.
/// \param NumClauses Number of clauses.
///
static OMPParallelDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses, EmptyShell);
/// Return true if current directive has inner cancel directive.
bool hasCancel() const { return HasCancel; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPParallelDirectiveClass;
}
};
/// This is a common base class for loop directives ('omp simd', 'omp
/// for', 'omp for simd' etc.). It is responsible for the loop code generation.
///
class OMPLoopDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
/// Number of collapsed loops as specified by 'collapse' clause.
unsigned CollapsedNum;
/// Offsets to the stored exprs.
/// This enumeration contains offsets to all the pointers to children
/// expressions stored in OMPLoopDirective.
/// The first 9 children are necessary for all the loop directives,
/// the next 8 are specific to the worksharing ones, and the next 11 are
/// used for combined constructs containing two pragmas associated to loops.
/// After the fixed children, three arrays of length CollapsedNum are
/// allocated: loop counters, their updates and final values.
/// PrevLowerBound and PrevUpperBound are used to communicate blocking
/// information in composite constructs which require loop blocking
/// DistInc is used to generate the increment expression for the distribute
/// loop when combined with a further nested loop
/// PrevEnsureUpperBound is used as the EnsureUpperBound expression for the
/// for loop when combined with a previous distribute loop in the same pragma
/// (e.g. 'distribute parallel for')
///
enum {
AssociatedStmtOffset = 0,
IterationVariableOffset = 1,
LastIterationOffset = 2,
CalcLastIterationOffset = 3,
PreConditionOffset = 4,
CondOffset = 5,
InitOffset = 6,
IncOffset = 7,
PreInitsOffset = 8,
// The '...End' enumerators do not correspond to child expressions - they
// specify the offset to the end (and start of the following counters/
// updates/finals arrays).
DefaultEnd = 9,
// The following 8 exprs are used by worksharing and distribute loops only.
IsLastIterVariableOffset = 9,
LowerBoundVariableOffset = 10,
UpperBoundVariableOffset = 11,
StrideVariableOffset = 12,
EnsureUpperBoundOffset = 13,
NextLowerBoundOffset = 14,
NextUpperBoundOffset = 15,
NumIterationsOffset = 16,
// Offset to the end for worksharing loop directives.
WorksharingEnd = 17,
PrevLowerBoundVariableOffset = 17,
PrevUpperBoundVariableOffset = 18,
DistIncOffset = 19,
PrevEnsureUpperBoundOffset = 20,
CombinedLowerBoundVariableOffset = 21,
CombinedUpperBoundVariableOffset = 22,
CombinedEnsureUpperBoundOffset = 23,
CombinedInitOffset = 24,
CombinedConditionOffset = 25,
CombinedNextLowerBoundOffset = 26,
CombinedNextUpperBoundOffset = 27,
CombinedDistConditionOffset = 28,
CombinedParForInDistConditionOffset = 29,
// Offset to the end (and start of the following counters/updates/finals
// arrays) for combined distribute loop directives.
CombinedDistributeEnd = 30,
};
/// Get the counters storage.
MutableArrayRef<Expr *> getCounters() {
Expr **Storage = reinterpret_cast<Expr **>(
&(*(std::next(child_begin(), getArraysOffset(getDirectiveKind())))));
return MutableArrayRef<Expr *>(Storage, CollapsedNum);
}
/// Get the private counters storage.
MutableArrayRef<Expr *> getPrivateCounters() {
Expr **Storage = reinterpret_cast<Expr **>(&*std::next(
child_begin(), getArraysOffset(getDirectiveKind()) + CollapsedNum));
return MutableArrayRef<Expr *>(Storage, CollapsedNum);
}
/// Get the updates storage.
MutableArrayRef<Expr *> getInits() {
Expr **Storage = reinterpret_cast<Expr **>(
&*std::next(child_begin(),
getArraysOffset(getDirectiveKind()) + 2 * CollapsedNum));
return MutableArrayRef<Expr *>(Storage, CollapsedNum);
}
/// Get the updates storage.
MutableArrayRef<Expr *> getUpdates() {
Expr **Storage = reinterpret_cast<Expr **>(
&*std::next(child_begin(),
getArraysOffset(getDirectiveKind()) + 3 * CollapsedNum));
return MutableArrayRef<Expr *>(Storage, CollapsedNum);
}
/// Get the final counter updates storage.
MutableArrayRef<Expr *> getFinals() {
Expr **Storage = reinterpret_cast<Expr **>(
&*std::next(child_begin(),
getArraysOffset(getDirectiveKind()) + 4 * CollapsedNum));
return MutableArrayRef<Expr *>(Storage, CollapsedNum);
}
protected:
/// Build instance of loop directive of class \a Kind.
///
/// \param SC Statement class.
/// \param Kind Kind of OpenMP directive.
/// \param StartLoc Starting location of the directive (directive keyword).
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed loops from 'collapse' clause.
/// \param NumClauses Number of clauses.
/// \param NumSpecialChildren Number of additional directive-specific stmts.
///
template <typename T>
OMPLoopDirective(const T *That, StmtClass SC, OpenMPDirectiveKind Kind,
SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, unsigned NumClauses,
unsigned NumSpecialChildren = 0)
: OMPExecutableDirective(That, SC, Kind, StartLoc, EndLoc, NumClauses,
numLoopChildren(CollapsedNum, Kind) +
NumSpecialChildren),
CollapsedNum(CollapsedNum) {}
/// Offset to the start of children expression arrays.
static unsigned getArraysOffset(OpenMPDirectiveKind Kind) {
if (isOpenMPLoopBoundSharingDirective(Kind))
return CombinedDistributeEnd;
if (isOpenMPWorksharingDirective(Kind) || isOpenMPTaskLoopDirective(Kind) ||
isOpenMPDistributeDirective(Kind))
return WorksharingEnd;
return DefaultEnd;
}
/// Children number.
static unsigned numLoopChildren(unsigned CollapsedNum,
OpenMPDirectiveKind Kind) {
return getArraysOffset(Kind) + 5 * CollapsedNum; // Counters,
// PrivateCounters, Inits,
// Updates and Finals
}
void setIterationVariable(Expr *IV) {
*std::next(child_begin(), IterationVariableOffset) = IV;
}
void setLastIteration(Expr *LI) {
*std::next(child_begin(), LastIterationOffset) = LI;
}
void setCalcLastIteration(Expr *CLI) {
*std::next(child_begin(), CalcLastIterationOffset) = CLI;
}
void setPreCond(Expr *PC) {
*std::next(child_begin(), PreConditionOffset) = PC;
}
void setCond(Expr *Cond) {
*std::next(child_begin(), CondOffset) = Cond;
}
void setInit(Expr *Init) { *std::next(child_begin(), InitOffset) = Init; }
void setInc(Expr *Inc) { *std::next(child_begin(), IncOffset) = Inc; }
void setPreInits(Stmt *PreInits) {
*std::next(child_begin(), PreInitsOffset) = PreInits;
}
void setIsLastIterVariable(Expr *IL) {
assert((isOpenMPWorksharingDirective(getDirectiveKind()) ||
isOpenMPTaskLoopDirective(getDirectiveKind()) ||
isOpenMPDistributeDirective(getDirectiveKind())) &&
"expected worksharing loop directive");
*std::next(child_begin(), IsLastIterVariableOffset) = IL;
}
void setLowerBoundVariable(Expr *LB) {
assert((isOpenMPWorksharingDirective(getDirectiveKind()) ||
isOpenMPTaskLoopDirective(getDirectiveKind()) ||
isOpenMPDistributeDirective(getDirectiveKind())) &&
"expected worksharing loop directive");
*std::next(child_begin(), LowerBoundVariableOffset) = LB;
}
void setUpperBoundVariable(Expr *UB) {
assert((isOpenMPWorksharingDirective(getDirectiveKind()) ||
isOpenMPTaskLoopDirective(getDirectiveKind()) ||
isOpenMPDistributeDirective(getDirectiveKind())) &&
"expected worksharing loop directive");
*std::next(child_begin(), UpperBoundVariableOffset) = UB;
}
void setStrideVariable(Expr *ST) {
assert((isOpenMPWorksharingDirective(getDirectiveKind()) ||
isOpenMPTaskLoopDirective(getDirectiveKind()) ||
isOpenMPDistributeDirective(getDirectiveKind())) &&
"expected worksharing loop directive");
*std::next(child_begin(), StrideVariableOffset) = ST;
}
void setEnsureUpperBound(Expr *EUB) {
assert((isOpenMPWorksharingDirective(getDirectiveKind()) ||
isOpenMPTaskLoopDirective(getDirectiveKind()) ||
isOpenMPDistributeDirective(getDirectiveKind())) &&
"expected worksharing loop directive");
*std::next(child_begin(), EnsureUpperBoundOffset) = EUB;
}
void setNextLowerBound(Expr *NLB) {
assert((isOpenMPWorksharingDirective(getDirectiveKind()) ||
isOpenMPTaskLoopDirective(getDirectiveKind()) ||
isOpenMPDistributeDirective(getDirectiveKind())) &&
"expected worksharing loop directive");
*std::next(child_begin(), NextLowerBoundOffset) = NLB;
}
void setNextUpperBound(Expr *NUB) {
assert((isOpenMPWorksharingDirective(getDirectiveKind()) ||
isOpenMPTaskLoopDirective(getDirectiveKind()) ||
isOpenMPDistributeDirective(getDirectiveKind())) &&
"expected worksharing loop directive");
*std::next(child_begin(), NextUpperBoundOffset) = NUB;
}
void setNumIterations(Expr *NI) {
assert((isOpenMPWorksharingDirective(getDirectiveKind()) ||
isOpenMPTaskLoopDirective(getDirectiveKind()) ||
isOpenMPDistributeDirective(getDirectiveKind())) &&
"expected worksharing loop directive");
*std::next(child_begin(), NumIterationsOffset) = NI;
}
void setPrevLowerBoundVariable(Expr *PrevLB) {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
*std::next(child_begin(), PrevLowerBoundVariableOffset) = PrevLB;
}
void setPrevUpperBoundVariable(Expr *PrevUB) {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
*std::next(child_begin(), PrevUpperBoundVariableOffset) = PrevUB;
}
void setDistInc(Expr *DistInc) {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
*std::next(child_begin(), DistIncOffset) = DistInc;
}
void setPrevEnsureUpperBound(Expr *PrevEUB) {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
*std::next(child_begin(), PrevEnsureUpperBoundOffset) = PrevEUB;
}
void setCombinedLowerBoundVariable(Expr *CombLB) {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
*std::next(child_begin(), CombinedLowerBoundVariableOffset) = CombLB;
}
void setCombinedUpperBoundVariable(Expr *CombUB) {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
*std::next(child_begin(), CombinedUpperBoundVariableOffset) = CombUB;
}
void setCombinedEnsureUpperBound(Expr *CombEUB) {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
*std::next(child_begin(), CombinedEnsureUpperBoundOffset) = CombEUB;
}
void setCombinedInit(Expr *CombInit) {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
*std::next(child_begin(), CombinedInitOffset) = CombInit;
}
void setCombinedCond(Expr *CombCond) {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
*std::next(child_begin(), CombinedConditionOffset) = CombCond;
}
void setCombinedNextLowerBound(Expr *CombNLB) {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
*std::next(child_begin(), CombinedNextLowerBoundOffset) = CombNLB;
}
void setCombinedNextUpperBound(Expr *CombNUB) {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
*std::next(child_begin(), CombinedNextUpperBoundOffset) = CombNUB;
}
void setCombinedDistCond(Expr *CombDistCond) {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound distribute sharing directive");
*std::next(child_begin(), CombinedDistConditionOffset) = CombDistCond;
}
void setCombinedParForInDistCond(Expr *CombParForInDistCond) {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound distribute sharing directive");
*std::next(child_begin(),
CombinedParForInDistConditionOffset) = CombParForInDistCond;
}
void setCounters(ArrayRef<Expr *> A);
void setPrivateCounters(ArrayRef<Expr *> A);
void setInits(ArrayRef<Expr *> A);
void setUpdates(ArrayRef<Expr *> A);
void setFinals(ArrayRef<Expr *> A);
public:
/// The expressions built to support OpenMP loops in combined/composite
/// pragmas (e.g. pragma omp distribute parallel for)
struct DistCombinedHelperExprs {
/// DistributeLowerBound - used when composing 'omp distribute' with
/// 'omp for' in a same construct.
Expr *LB;
/// DistributeUpperBound - used when composing 'omp distribute' with
/// 'omp for' in a same construct.
Expr *UB;
/// DistributeEnsureUpperBound - used when composing 'omp distribute'
/// with 'omp for' in a same construct, EUB depends on DistUB
Expr *EUB;
/// Distribute loop iteration variable init used when composing 'omp
/// distribute'
/// with 'omp for' in a same construct
Expr *Init;
/// Distribute Loop condition used when composing 'omp distribute'
/// with 'omp for' in a same construct
Expr *Cond;
/// Update of LowerBound for statically scheduled omp loops for
/// outer loop in combined constructs (e.g. 'distribute parallel for')
Expr *NLB;
/// Update of UpperBound for statically scheduled omp loops for
/// outer loop in combined constructs (e.g. 'distribute parallel for')
Expr *NUB;
/// Distribute Loop condition used when composing 'omp distribute'
/// with 'omp for' in a same construct when schedule is chunked.
Expr *DistCond;
/// 'omp parallel for' loop condition used when composed with
/// 'omp distribute' in the same construct and when schedule is
/// chunked and the chunk size is 1.
Expr *ParForInDistCond;
};
/// The expressions built for the OpenMP loop CodeGen for the
/// whole collapsed loop nest.
struct HelperExprs {
/// Loop iteration variable.
Expr *IterationVarRef;
/// Loop last iteration number.
Expr *LastIteration;
/// Loop number of iterations.
Expr *NumIterations;
/// Calculation of last iteration.
Expr *CalcLastIteration;
/// Loop pre-condition.
Expr *PreCond;
/// Loop condition.
Expr *Cond;
/// Loop iteration variable init.
Expr *Init;
/// Loop increment.
Expr *Inc;
/// IsLastIteration - local flag variable passed to runtime.
Expr *IL;
/// LowerBound - local variable passed to runtime.
Expr *LB;
/// UpperBound - local variable passed to runtime.
Expr *UB;
/// Stride - local variable passed to runtime.
Expr *ST;
/// EnsureUpperBound -- expression UB = min(UB, NumIterations).
Expr *EUB;
/// Update of LowerBound for statically scheduled 'omp for' loops.
Expr *NLB;
/// Update of UpperBound for statically scheduled 'omp for' loops.
Expr *NUB;
/// PreviousLowerBound - local variable passed to runtime in the
/// enclosing schedule or null if that does not apply.
Expr *PrevLB;
/// PreviousUpperBound - local variable passed to runtime in the
/// enclosing schedule or null if that does not apply.
Expr *PrevUB;
/// DistInc - increment expression for distribute loop when found
/// combined with a further loop level (e.g. in 'distribute parallel for')
/// expression IV = IV + ST
Expr *DistInc;
/// PrevEUB - expression similar to EUB but to be used when loop
/// scheduling uses PrevLB and PrevUB (e.g. in 'distribute parallel for'
/// when ensuring that the UB is either the calculated UB by the runtime or
/// the end of the assigned distribute chunk)
/// expression UB = min (UB, PrevUB)
Expr *PrevEUB;
/// Counters Loop counters.
SmallVector<Expr *, 4> Counters;
/// PrivateCounters Loop counters.
SmallVector<Expr *, 4> PrivateCounters;
/// Expressions for loop counters inits for CodeGen.
SmallVector<Expr *, 4> Inits;
/// Expressions for loop counters update for CodeGen.
SmallVector<Expr *, 4> Updates;
/// Final loop counter values for GodeGen.
SmallVector<Expr *, 4> Finals;
/// Init statement for all captured expressions.
Stmt *PreInits;
/// Expressions used when combining OpenMP loop pragmas
DistCombinedHelperExprs DistCombinedFields;
/// Check if all the expressions are built (does not check the
/// worksharing ones).
bool builtAll() {
return IterationVarRef != nullptr && LastIteration != nullptr &&
NumIterations != nullptr && PreCond != nullptr &&
Cond != nullptr && Init != nullptr && Inc != nullptr;
}
/// Initialize all the fields to null.
/// \param Size Number of elements in the counters/finals/updates arrays.
void clear(unsigned Size) {
IterationVarRef = nullptr;
LastIteration = nullptr;
CalcLastIteration = nullptr;
PreCond = nullptr;
Cond = nullptr;
Init = nullptr;
Inc = nullptr;
IL = nullptr;
LB = nullptr;
UB = nullptr;
ST = nullptr;
EUB = nullptr;
NLB = nullptr;
NUB = nullptr;
NumIterations = nullptr;
PrevLB = nullptr;
PrevUB = nullptr;
DistInc = nullptr;
PrevEUB = nullptr;
Counters.resize(Size);
PrivateCounters.resize(Size);
Inits.resize(Size);
Updates.resize(Size);
Finals.resize(Size);
for (unsigned i = 0; i < Size; ++i) {
Counters[i] = nullptr;
PrivateCounters[i] = nullptr;
Inits[i] = nullptr;
Updates[i] = nullptr;
Finals[i] = nullptr;
}
PreInits = nullptr;
DistCombinedFields.LB = nullptr;
DistCombinedFields.UB = nullptr;
DistCombinedFields.EUB = nullptr;
DistCombinedFields.Init = nullptr;
DistCombinedFields.Cond = nullptr;
DistCombinedFields.NLB = nullptr;
DistCombinedFields.NUB = nullptr;
DistCombinedFields.DistCond = nullptr;
DistCombinedFields.ParForInDistCond = nullptr;
}
};
/// Get number of collapsed loops.
unsigned getCollapsedNumber() const { return CollapsedNum; }
Expr *getIterationVariable() const {
return const_cast<Expr *>(reinterpret_cast<const Expr *>(
*std::next(child_begin(), IterationVariableOffset)));
}
Expr *getLastIteration() const {
return const_cast<Expr *>(reinterpret_cast<const Expr *>(
*std::next(child_begin(), LastIterationOffset)));
}
Expr *getCalcLastIteration() const {
return const_cast<Expr *>(reinterpret_cast<const Expr *>(
*std::next(child_begin(), CalcLastIterationOffset)));
}
Expr *getPreCond() const {
return const_cast<Expr *>(reinterpret_cast<const Expr *>(
*std::next(child_begin(), PreConditionOffset)));
}
Expr *getCond() const {
return const_cast<Expr *>(
reinterpret_cast<const Expr *>(*std::next(child_begin(), CondOffset)));
}
Expr *getInit() const {
return const_cast<Expr *>(
reinterpret_cast<const Expr *>(*std::next(child_begin(), InitOffset)));
}
Expr *getInc() const {
return const_cast<Expr *>(
reinterpret_cast<const Expr *>(*std::next(child_begin(), IncOffset)));
}
const Stmt *getPreInits() const {
return *std::next(child_begin(), PreInitsOffset);
}
Stmt *getPreInits() { return *std::next(child_begin(), PreInitsOffset); }
Expr *getIsLastIterVariable() const {
assert((isOpenMPWorksharingDirective(getDirectiveKind()) ||
isOpenMPTaskLoopDirective(getDirectiveKind()) ||
isOpenMPDistributeDirective(getDirectiveKind())) &&
"expected worksharing loop directive");
return const_cast<Expr *>(reinterpret_cast<const Expr *>(
*std::next(child_begin(), IsLastIterVariableOffset)));
}
Expr *getLowerBoundVariable() const {
assert((isOpenMPWorksharingDirective(getDirectiveKind()) ||
isOpenMPTaskLoopDirective(getDirectiveKind()) ||
isOpenMPDistributeDirective(getDirectiveKind())) &&
"expected worksharing loop directive");
return const_cast<Expr *>(reinterpret_cast<const Expr *>(
*std::next(child_begin(), LowerBoundVariableOffset)));
}
Expr *getUpperBoundVariable() const {
assert((isOpenMPWorksharingDirective(getDirectiveKind()) ||
isOpenMPTaskLoopDirective(getDirectiveKind()) ||
isOpenMPDistributeDirective(getDirectiveKind())) &&
"expected worksharing loop directive");
return const_cast<Expr *>(reinterpret_cast<const Expr *>(
*std::next(child_begin(), UpperBoundVariableOffset)));
}
Expr *getStrideVariable() const {
assert((isOpenMPWorksharingDirective(getDirectiveKind()) ||
isOpenMPTaskLoopDirective(getDirectiveKind()) ||
isOpenMPDistributeDirective(getDirectiveKind())) &&
"expected worksharing loop directive");
return const_cast<Expr *>(reinterpret_cast<const Expr *>(
*std::next(child_begin(), StrideVariableOffset)));
}
Expr *getEnsureUpperBound() const {
assert((isOpenMPWorksharingDirective(getDirectiveKind()) ||
isOpenMPTaskLoopDirective(getDirectiveKind()) ||
isOpenMPDistributeDirective(getDirectiveKind())) &&
"expected worksharing loop directive");
return const_cast<Expr *>(reinterpret_cast<const Expr *>(
*std::next(child_begin(), EnsureUpperBoundOffset)));
}
Expr *getNextLowerBound() const {
assert((isOpenMPWorksharingDirective(getDirectiveKind()) ||
isOpenMPTaskLoopDirective(getDirectiveKind()) ||
isOpenMPDistributeDirective(getDirectiveKind())) &&
"expected worksharing loop directive");
return const_cast<Expr *>(reinterpret_cast<const Expr *>(
*std::next(child_begin(), NextLowerBoundOffset)));
}
Expr *getNextUpperBound() const {
assert((isOpenMPWorksharingDirective(getDirectiveKind()) ||
isOpenMPTaskLoopDirective(getDirectiveKind()) ||
isOpenMPDistributeDirective(getDirectiveKind())) &&
"expected worksharing loop directive");
return const_cast<Expr *>(reinterpret_cast<const Expr *>(
*std::next(child_begin(), NextUpperBoundOffset)));
}
Expr *getNumIterations() const {
assert((isOpenMPWorksharingDirective(getDirectiveKind()) ||
isOpenMPTaskLoopDirective(getDirectiveKind()) ||
isOpenMPDistributeDirective(getDirectiveKind())) &&
"expected worksharing loop directive");
return const_cast<Expr *>(reinterpret_cast<const Expr *>(
*std::next(child_begin(), NumIterationsOffset)));
}
Expr *getPrevLowerBoundVariable() const {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
return const_cast<Expr *>(reinterpret_cast<const Expr *>(
*std::next(child_begin(), PrevLowerBoundVariableOffset)));
}
Expr *getPrevUpperBoundVariable() const {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
return const_cast<Expr *>(reinterpret_cast<const Expr *>(
*std::next(child_begin(), PrevUpperBoundVariableOffset)));
}
Expr *getDistInc() const {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
return const_cast<Expr *>(reinterpret_cast<const Expr *>(
*std::next(child_begin(), DistIncOffset)));
}
Expr *getPrevEnsureUpperBound() const {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
return const_cast<Expr *>(reinterpret_cast<const Expr *>(
*std::next(child_begin(), PrevEnsureUpperBoundOffset)));
}
Expr *getCombinedLowerBoundVariable() const {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
return const_cast<Expr *>(reinterpret_cast<const Expr *>(
*std::next(child_begin(), CombinedLowerBoundVariableOffset)));
}
Expr *getCombinedUpperBoundVariable() const {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
return const_cast<Expr *>(reinterpret_cast<const Expr *>(
*std::next(child_begin(), CombinedUpperBoundVariableOffset)));
}
Expr *getCombinedEnsureUpperBound() const {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
return const_cast<Expr *>(reinterpret_cast<const Expr *>(
*std::next(child_begin(), CombinedEnsureUpperBoundOffset)));
}
Expr *getCombinedInit() const {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
return const_cast<Expr *>(reinterpret_cast<const Expr *>(
*std::next(child_begin(), CombinedInitOffset)));
}
Expr *getCombinedCond() const {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
return const_cast<Expr *>(reinterpret_cast<const Expr *>(
*std::next(child_begin(), CombinedConditionOffset)));
}
Expr *getCombinedNextLowerBound() const {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
return const_cast<Expr *>(reinterpret_cast<const Expr *>(
*std::next(child_begin(), CombinedNextLowerBoundOffset)));
}
Expr *getCombinedNextUpperBound() const {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
return const_cast<Expr *>(reinterpret_cast<const Expr *>(
*std::next(child_begin(), CombinedNextUpperBoundOffset)));
}
Expr *getCombinedDistCond() const {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound distribute sharing directive");
return const_cast<Expr *>(reinterpret_cast<const Expr *>(
*std::next(child_begin(), CombinedDistConditionOffset)));
}
Expr *getCombinedParForInDistCond() const {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound distribute sharing directive");
return const_cast<Expr *>(reinterpret_cast<const Expr *>(
*std::next(child_begin(), CombinedParForInDistConditionOffset)));
}
const Stmt *getBody() const {
// This relies on the loop form is already checked by Sema.
const Stmt *Body =
getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers();
Body = cast<ForStmt>(Body)->getBody();
for (unsigned Cnt = 1; Cnt < CollapsedNum; ++Cnt) {
Body = Body->IgnoreContainers();
Body = cast<ForStmt>(Body)->getBody();
}
return Body;
}
ArrayRef<Expr *> counters() { return getCounters(); }
ArrayRef<Expr *> counters() const {
return const_cast<OMPLoopDirective *>(this)->getCounters();
}
ArrayRef<Expr *> private_counters() { return getPrivateCounters(); }
ArrayRef<Expr *> private_counters() const {
return const_cast<OMPLoopDirective *>(this)->getPrivateCounters();
}
ArrayRef<Expr *> inits() { return getInits(); }
ArrayRef<Expr *> inits() const {
return const_cast<OMPLoopDirective *>(this)->getInits();
}
ArrayRef<Expr *> updates() { return getUpdates(); }
ArrayRef<Expr *> updates() const {
return const_cast<OMPLoopDirective *>(this)->getUpdates();
}
ArrayRef<Expr *> finals() { return getFinals(); }
ArrayRef<Expr *> finals() const {
return const_cast<OMPLoopDirective *>(this)->getFinals();
}
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPSimdDirectiveClass ||
T->getStmtClass() == OMPForDirectiveClass ||
T->getStmtClass() == OMPForSimdDirectiveClass ||
T->getStmtClass() == OMPParallelForDirectiveClass ||
T->getStmtClass() == OMPParallelForSimdDirectiveClass ||
T->getStmtClass() == OMPTaskLoopDirectiveClass ||
T->getStmtClass() == OMPTaskLoopSimdDirectiveClass ||
T->getStmtClass() == OMPDistributeDirectiveClass ||
T->getStmtClass() == OMPTargetParallelForDirectiveClass ||
T->getStmtClass() == OMPDistributeParallelForDirectiveClass ||
T->getStmtClass() == OMPDistributeParallelForSimdDirectiveClass ||
T->getStmtClass() == OMPDistributeSimdDirectiveClass ||
T->getStmtClass() == OMPTargetParallelForSimdDirectiveClass ||
T->getStmtClass() == OMPTargetSimdDirectiveClass ||
T->getStmtClass() == OMPTeamsDistributeDirectiveClass ||
T->getStmtClass() == OMPTeamsDistributeSimdDirectiveClass ||
T->getStmtClass() ==
OMPTeamsDistributeParallelForSimdDirectiveClass ||
T->getStmtClass() == OMPTeamsDistributeParallelForDirectiveClass ||
T->getStmtClass() ==
OMPTargetTeamsDistributeParallelForDirectiveClass ||
T->getStmtClass() ==
OMPTargetTeamsDistributeParallelForSimdDirectiveClass ||
T->getStmtClass() == OMPTargetTeamsDistributeDirectiveClass ||
T->getStmtClass() == OMPTargetTeamsDistributeSimdDirectiveClass;
}
};
/// This represents '#pragma omp simd' directive.
///
/// \code
/// #pragma omp simd private(a,b) linear(i,j:s) reduction(+:c,d)
/// \endcode
/// In this example directive '#pragma omp simd' has clauses 'private'
/// with the variables 'a' and 'b', 'linear' with variables 'i', 'j' and
/// linear step 's', 'reduction' with operator '+' and variables 'c' and 'd'.
///
class OMPSimdDirective : public OMPLoopDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
OMPSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, unsigned NumClauses)
: OMPLoopDirective(this, OMPSimdDirectiveClass, OMPD_simd, StartLoc,
EndLoc, CollapsedNum, NumClauses) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
explicit OMPSimdDirective(unsigned CollapsedNum, unsigned NumClauses)
: OMPLoopDirective(this, OMPSimdDirectiveClass, OMPD_simd,
SourceLocation(), SourceLocation(), CollapsedNum,
NumClauses) {}
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param CollapsedNum Number of collapsed loops.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param Exprs Helper expressions for CodeGen.
///
static OMPSimdDirective *Create(const ASTContext &C, SourceLocation StartLoc,
SourceLocation EndLoc, unsigned CollapsedNum,
ArrayRef<OMPClause *> Clauses,
Stmt *AssociatedStmt,
const HelperExprs &Exprs);
/// Creates an empty directive with the place
/// for \a NumClauses clauses.
///
/// \param C AST context.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
static OMPSimdDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses,
unsigned CollapsedNum, EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPSimdDirectiveClass;
}
};
/// This represents '#pragma omp for' directive.
///
/// \code
/// #pragma omp for private(a,b) reduction(+:c,d)
/// \endcode
/// In this example directive '#pragma omp for' has clauses 'private' with the
/// variables 'a' and 'b' and 'reduction' with operator '+' and variables 'c'
/// and 'd'.
///
class OMPForDirective : public OMPLoopDirective {
friend class ASTStmtReader;
/// true if current directive has inner cancel directive.
bool HasCancel;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
OMPForDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, unsigned NumClauses)
: OMPLoopDirective(this, OMPForDirectiveClass, OMPD_for, StartLoc, EndLoc,
CollapsedNum, NumClauses),
HasCancel(false) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
explicit OMPForDirective(unsigned CollapsedNum, unsigned NumClauses)
: OMPLoopDirective(this, OMPForDirectiveClass, OMPD_for, SourceLocation(),
SourceLocation(), CollapsedNum, NumClauses),
HasCancel(false) {}
/// Set cancel state.
void setHasCancel(bool Has) { HasCancel = Has; }
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param CollapsedNum Number of collapsed loops.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param Exprs Helper expressions for CodeGen.
/// \param HasCancel true if current directive has inner cancel directive.
///
static OMPForDirective *Create(const ASTContext &C, SourceLocation StartLoc,
SourceLocation EndLoc, unsigned CollapsedNum,
ArrayRef<OMPClause *> Clauses,
Stmt *AssociatedStmt, const HelperExprs &Exprs,
bool HasCancel);
/// Creates an empty directive with the place
/// for \a NumClauses clauses.
///
/// \param C AST context.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
static OMPForDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses,
unsigned CollapsedNum, EmptyShell);
/// Return true if current directive has inner cancel directive.
bool hasCancel() const { return HasCancel; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPForDirectiveClass;
}
};
/// This represents '#pragma omp for simd' directive.
///
/// \code
/// #pragma omp for simd private(a,b) linear(i,j:s) reduction(+:c,d)
/// \endcode
/// In this example directive '#pragma omp for simd' has clauses 'private'
/// with the variables 'a' and 'b', 'linear' with variables 'i', 'j' and
/// linear step 's', 'reduction' with operator '+' and variables 'c' and 'd'.
///
class OMPForSimdDirective : public OMPLoopDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
OMPForSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, unsigned NumClauses)
: OMPLoopDirective(this, OMPForSimdDirectiveClass, OMPD_for_simd,
StartLoc, EndLoc, CollapsedNum, NumClauses) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
explicit OMPForSimdDirective(unsigned CollapsedNum, unsigned NumClauses)
: OMPLoopDirective(this, OMPForSimdDirectiveClass, OMPD_for_simd,
SourceLocation(), SourceLocation(), CollapsedNum,
NumClauses) {}
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param CollapsedNum Number of collapsed loops.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param Exprs Helper expressions for CodeGen.
///
static OMPForSimdDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses,
Stmt *AssociatedStmt, const HelperExprs &Exprs);
/// Creates an empty directive with the place
/// for \a NumClauses clauses.
///
/// \param C AST context.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
static OMPForSimdDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses,
unsigned CollapsedNum, EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPForSimdDirectiveClass;
}
};
/// This represents '#pragma omp sections' directive.
///
/// \code
/// #pragma omp sections private(a,b) reduction(+:c,d)
/// \endcode
/// In this example directive '#pragma omp sections' has clauses 'private' with
/// the variables 'a' and 'b' and 'reduction' with operator '+' and variables
/// 'c' and 'd'.
///
class OMPSectionsDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
/// true if current directive has inner cancel directive.
bool HasCancel;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param NumClauses Number of clauses.
///
OMPSectionsDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned NumClauses)
: OMPExecutableDirective(this, OMPSectionsDirectiveClass, OMPD_sections,
StartLoc, EndLoc, NumClauses, 1),
HasCancel(false) {}
/// Build an empty directive.
///
/// \param NumClauses Number of clauses.
///
explicit OMPSectionsDirective(unsigned NumClauses)
: OMPExecutableDirective(this, OMPSectionsDirectiveClass, OMPD_sections,
SourceLocation(), SourceLocation(), NumClauses,
1),
HasCancel(false) {}
/// Set cancel state.
void setHasCancel(bool Has) { HasCancel = Has; }
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param HasCancel true if current directive has inner directive.
///
static OMPSectionsDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, bool HasCancel);
/// Creates an empty directive with the place for \a NumClauses
/// clauses.
///
/// \param C AST context.
/// \param NumClauses Number of clauses.
///
static OMPSectionsDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses, EmptyShell);
/// Return true if current directive has inner cancel directive.
bool hasCancel() const { return HasCancel; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPSectionsDirectiveClass;
}
};
/// This represents '#pragma omp section' directive.
///
/// \code
/// #pragma omp section
/// \endcode
///
class OMPSectionDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
/// true if current directive has inner cancel directive.
bool HasCancel;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
///
OMPSectionDirective(SourceLocation StartLoc, SourceLocation EndLoc)
: OMPExecutableDirective(this, OMPSectionDirectiveClass, OMPD_section,
StartLoc, EndLoc, 0, 1),
HasCancel(false) {}
/// Build an empty directive.
///
explicit OMPSectionDirective()
: OMPExecutableDirective(this, OMPSectionDirectiveClass, OMPD_section,
SourceLocation(), SourceLocation(), 0, 1),
HasCancel(false) {}
public:
/// Creates directive.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param HasCancel true if current directive has inner directive.
///
static OMPSectionDirective *Create(const ASTContext &C,
SourceLocation StartLoc,
SourceLocation EndLoc,
Stmt *AssociatedStmt, bool HasCancel);
/// Creates an empty directive.
///
/// \param C AST context.
///
static OMPSectionDirective *CreateEmpty(const ASTContext &C, EmptyShell);
/// Set cancel state.
void setHasCancel(bool Has) { HasCancel = Has; }
/// Return true if current directive has inner cancel directive.
bool hasCancel() const { return HasCancel; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPSectionDirectiveClass;
}
};
/// This represents '#pragma omp single' directive.
///
/// \code
/// #pragma omp single private(a,b) copyprivate(c,d)
/// \endcode
/// In this example directive '#pragma omp single' has clauses 'private' with
/// the variables 'a' and 'b' and 'copyprivate' with variables 'c' and 'd'.
///
class OMPSingleDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param NumClauses Number of clauses.
///
OMPSingleDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned NumClauses)
: OMPExecutableDirective(this, OMPSingleDirectiveClass, OMPD_single,
StartLoc, EndLoc, NumClauses, 1) {}
/// Build an empty directive.
///
/// \param NumClauses Number of clauses.
///
explicit OMPSingleDirective(unsigned NumClauses)
: OMPExecutableDirective(this, OMPSingleDirectiveClass, OMPD_single,
SourceLocation(), SourceLocation(), NumClauses,
1) {}
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
///
static OMPSingleDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt);
/// Creates an empty directive with the place for \a NumClauses
/// clauses.
///
/// \param C AST context.
/// \param NumClauses Number of clauses.
///
static OMPSingleDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses, EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPSingleDirectiveClass;
}
};
/// This represents '#pragma omp master' directive.
///
/// \code
/// #pragma omp master
/// \endcode
///
class OMPMasterDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
///
OMPMasterDirective(SourceLocation StartLoc, SourceLocation EndLoc)
: OMPExecutableDirective(this, OMPMasterDirectiveClass, OMPD_master,
StartLoc, EndLoc, 0, 1) {}
/// Build an empty directive.
///
explicit OMPMasterDirective()
: OMPExecutableDirective(this, OMPMasterDirectiveClass, OMPD_master,
SourceLocation(), SourceLocation(), 0, 1) {}
public:
/// Creates directive.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param AssociatedStmt Statement, associated with the directive.
///
static OMPMasterDirective *Create(const ASTContext &C,
SourceLocation StartLoc,
SourceLocation EndLoc,
Stmt *AssociatedStmt);
/// Creates an empty directive.
///
/// \param C AST context.
///
static OMPMasterDirective *CreateEmpty(const ASTContext &C, EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPMasterDirectiveClass;
}
};
/// This represents '#pragma omp critical' directive.
///
/// \code
/// #pragma omp critical
/// \endcode
///
class OMPCriticalDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
/// Name of the directive.
DeclarationNameInfo DirName;
/// Build directive with the given start and end location.
///
/// \param Name Name of the directive.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param NumClauses Number of clauses.
///
OMPCriticalDirective(const DeclarationNameInfo &Name, SourceLocation StartLoc,
SourceLocation EndLoc, unsigned NumClauses)
: OMPExecutableDirective(this, OMPCriticalDirectiveClass, OMPD_critical,
StartLoc, EndLoc, NumClauses, 1),
DirName(Name) {}
/// Build an empty directive.
///
/// \param NumClauses Number of clauses.
///
explicit OMPCriticalDirective(unsigned NumClauses)
: OMPExecutableDirective(this, OMPCriticalDirectiveClass, OMPD_critical,
SourceLocation(), SourceLocation(), NumClauses,
1),
DirName() {}
/// Set name of the directive.
///
/// \param Name Name of the directive.
///
void setDirectiveName(const DeclarationNameInfo &Name) { DirName = Name; }
public:
/// Creates directive.
///
/// \param C AST context.
/// \param Name Name of the directive.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
///
static OMPCriticalDirective *
Create(const ASTContext &C, const DeclarationNameInfo &Name,
SourceLocation StartLoc, SourceLocation EndLoc,
ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt);
/// Creates an empty directive.
///
/// \param C AST context.
/// \param NumClauses Number of clauses.
///
static OMPCriticalDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses, EmptyShell);
/// Return name of the directive.
///
DeclarationNameInfo getDirectiveName() const { return DirName; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPCriticalDirectiveClass;
}
};
/// This represents '#pragma omp parallel for' directive.
///
/// \code
/// #pragma omp parallel for private(a,b) reduction(+:c,d)
/// \endcode
/// In this example directive '#pragma omp parallel for' has clauses 'private'
/// with the variables 'a' and 'b' and 'reduction' with operator '+' and
/// variables 'c' and 'd'.
///
class OMPParallelForDirective : public OMPLoopDirective {
friend class ASTStmtReader;
/// true if current region has inner cancel directive.
bool HasCancel;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
OMPParallelForDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, unsigned NumClauses)
: OMPLoopDirective(this, OMPParallelForDirectiveClass, OMPD_parallel_for,
StartLoc, EndLoc, CollapsedNum, NumClauses),
HasCancel(false) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
explicit OMPParallelForDirective(unsigned CollapsedNum, unsigned NumClauses)
: OMPLoopDirective(this, OMPParallelForDirectiveClass, OMPD_parallel_for,
SourceLocation(), SourceLocation(), CollapsedNum,
NumClauses),
HasCancel(false) {}
/// Set cancel state.
void setHasCancel(bool Has) { HasCancel = Has; }
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param CollapsedNum Number of collapsed loops.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param Exprs Helper expressions for CodeGen.
/// \param HasCancel true if current directive has inner cancel directive.
///
static OMPParallelForDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses,
Stmt *AssociatedStmt, const HelperExprs &Exprs, bool HasCancel);
/// Creates an empty directive with the place
/// for \a NumClauses clauses.
///
/// \param C AST context.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
static OMPParallelForDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses,
unsigned CollapsedNum,
EmptyShell);
/// Return true if current directive has inner cancel directive.
bool hasCancel() const { return HasCancel; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPParallelForDirectiveClass;
}
};
/// This represents '#pragma omp parallel for simd' directive.
///
/// \code
/// #pragma omp parallel for simd private(a,b) linear(i,j:s) reduction(+:c,d)
/// \endcode
/// In this example directive '#pragma omp parallel for simd' has clauses
/// 'private' with the variables 'a' and 'b', 'linear' with variables 'i', 'j'
/// and linear step 's', 'reduction' with operator '+' and variables 'c' and
/// 'd'.
///
class OMPParallelForSimdDirective : public OMPLoopDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
OMPParallelForSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, unsigned NumClauses)
: OMPLoopDirective(this, OMPParallelForSimdDirectiveClass,
OMPD_parallel_for_simd, StartLoc, EndLoc, CollapsedNum,
NumClauses) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
explicit OMPParallelForSimdDirective(unsigned CollapsedNum,
unsigned NumClauses)
: OMPLoopDirective(this, OMPParallelForSimdDirectiveClass,
OMPD_parallel_for_simd, SourceLocation(),
SourceLocation(), CollapsedNum, NumClauses) {}
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param CollapsedNum Number of collapsed loops.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param Exprs Helper expressions for CodeGen.
///
static OMPParallelForSimdDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses,
Stmt *AssociatedStmt, const HelperExprs &Exprs);
/// Creates an empty directive with the place
/// for \a NumClauses clauses.
///
/// \param C AST context.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
static OMPParallelForSimdDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses,
unsigned CollapsedNum,
EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPParallelForSimdDirectiveClass;
}
};
/// This represents '#pragma omp parallel sections' directive.
///
/// \code
/// #pragma omp parallel sections private(a,b) reduction(+:c,d)
/// \endcode
/// In this example directive '#pragma omp parallel sections' has clauses
/// 'private' with the variables 'a' and 'b' and 'reduction' with operator '+'
/// and variables 'c' and 'd'.
///
class OMPParallelSectionsDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
/// true if current directive has inner cancel directive.
bool HasCancel;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param NumClauses Number of clauses.
///
OMPParallelSectionsDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned NumClauses)
: OMPExecutableDirective(this, OMPParallelSectionsDirectiveClass,
OMPD_parallel_sections, StartLoc, EndLoc,
NumClauses, 1),
HasCancel(false) {}
/// Build an empty directive.
///
/// \param NumClauses Number of clauses.
///
explicit OMPParallelSectionsDirective(unsigned NumClauses)
: OMPExecutableDirective(this, OMPParallelSectionsDirectiveClass,
OMPD_parallel_sections, SourceLocation(),
SourceLocation(), NumClauses, 1),
HasCancel(false) {}
/// Set cancel state.
void setHasCancel(bool Has) { HasCancel = Has; }
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param HasCancel true if current directive has inner cancel directive.
///
static OMPParallelSectionsDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, bool HasCancel);
/// Creates an empty directive with the place for \a NumClauses
/// clauses.
///
/// \param C AST context.
/// \param NumClauses Number of clauses.
///
static OMPParallelSectionsDirective *
CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell);
/// Return true if current directive has inner cancel directive.
bool hasCancel() const { return HasCancel; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPParallelSectionsDirectiveClass;
}
};
/// This represents '#pragma omp task' directive.
///
/// \code
/// #pragma omp task private(a,b) final(d)
/// \endcode
/// In this example directive '#pragma omp task' has clauses 'private' with the
/// variables 'a' and 'b' and 'final' with condition 'd'.
///
class OMPTaskDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
/// true if this directive has inner cancel directive.
bool HasCancel;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param NumClauses Number of clauses.
///
OMPTaskDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned NumClauses)
: OMPExecutableDirective(this, OMPTaskDirectiveClass, OMPD_task, StartLoc,
EndLoc, NumClauses, 1),
HasCancel(false) {}
/// Build an empty directive.
///
/// \param NumClauses Number of clauses.
///
explicit OMPTaskDirective(unsigned NumClauses)
: OMPExecutableDirective(this, OMPTaskDirectiveClass, OMPD_task,
SourceLocation(), SourceLocation(), NumClauses,
1),
HasCancel(false) {}
/// Set cancel state.
void setHasCancel(bool Has) { HasCancel = Has; }
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param HasCancel true, if current directive has inner cancel directive.
///
static OMPTaskDirective *Create(const ASTContext &C, SourceLocation StartLoc,
SourceLocation EndLoc,
ArrayRef<OMPClause *> Clauses,
Stmt *AssociatedStmt, bool HasCancel);
/// Creates an empty directive with the place for \a NumClauses
/// clauses.
///
/// \param C AST context.
/// \param NumClauses Number of clauses.
///
static OMPTaskDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses,
EmptyShell);
/// Return true if current directive has inner cancel directive.
bool hasCancel() const { return HasCancel; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPTaskDirectiveClass;
}
};
/// This represents '#pragma omp taskyield' directive.
///
/// \code
/// #pragma omp taskyield
/// \endcode
///
class OMPTaskyieldDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
///
OMPTaskyieldDirective(SourceLocation StartLoc, SourceLocation EndLoc)
: OMPExecutableDirective(this, OMPTaskyieldDirectiveClass, OMPD_taskyield,
StartLoc, EndLoc, 0, 0) {}
/// Build an empty directive.
///
explicit OMPTaskyieldDirective()
: OMPExecutableDirective(this, OMPTaskyieldDirectiveClass, OMPD_taskyield,
SourceLocation(), SourceLocation(), 0, 0) {}
public:
/// Creates directive.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
///
static OMPTaskyieldDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc);
/// Creates an empty directive.
///
/// \param C AST context.
///
static OMPTaskyieldDirective *CreateEmpty(const ASTContext &C, EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPTaskyieldDirectiveClass;
}
};
/// This represents '#pragma omp barrier' directive.
///
/// \code
/// #pragma omp barrier
/// \endcode
///
class OMPBarrierDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
///
OMPBarrierDirective(SourceLocation StartLoc, SourceLocation EndLoc)
: OMPExecutableDirective(this, OMPBarrierDirectiveClass, OMPD_barrier,
StartLoc, EndLoc, 0, 0) {}
/// Build an empty directive.
///
explicit OMPBarrierDirective()
: OMPExecutableDirective(this, OMPBarrierDirectiveClass, OMPD_barrier,
SourceLocation(), SourceLocation(), 0, 0) {}
public:
/// Creates directive.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
///
static OMPBarrierDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc);
/// Creates an empty directive.
///
/// \param C AST context.
///
static OMPBarrierDirective *CreateEmpty(const ASTContext &C, EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPBarrierDirectiveClass;
}
};
/// This represents '#pragma omp taskwait' directive.
///
/// \code
/// #pragma omp taskwait
/// \endcode
///
class OMPTaskwaitDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
///
OMPTaskwaitDirective(SourceLocation StartLoc, SourceLocation EndLoc)
: OMPExecutableDirective(this, OMPTaskwaitDirectiveClass, OMPD_taskwait,
StartLoc, EndLoc, 0, 0) {}
/// Build an empty directive.
///
explicit OMPTaskwaitDirective()
: OMPExecutableDirective(this, OMPTaskwaitDirectiveClass, OMPD_taskwait,
SourceLocation(), SourceLocation(), 0, 0) {}
public:
/// Creates directive.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
///
static OMPTaskwaitDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc);
/// Creates an empty directive.
///
/// \param C AST context.
///
static OMPTaskwaitDirective *CreateEmpty(const ASTContext &C, EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPTaskwaitDirectiveClass;
}
};
/// This represents '#pragma omp taskgroup' directive.
///
/// \code
/// #pragma omp taskgroup
/// \endcode
///
class OMPTaskgroupDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param NumClauses Number of clauses.
///
OMPTaskgroupDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned NumClauses)
: OMPExecutableDirective(this, OMPTaskgroupDirectiveClass, OMPD_taskgroup,
StartLoc, EndLoc, NumClauses, 2) {}
/// Build an empty directive.
/// \param NumClauses Number of clauses.
///
explicit OMPTaskgroupDirective(unsigned NumClauses)
: OMPExecutableDirective(this, OMPTaskgroupDirectiveClass, OMPD_taskgroup,
SourceLocation(), SourceLocation(), NumClauses,
2) {}
/// Sets the task_reduction return variable.
void setReductionRef(Expr *RR) {
*std::next(child_begin(), 1) = RR;
}
public:
/// Creates directive.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param ReductionRef Reference to the task_reduction return variable.
///
static OMPTaskgroupDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt,
Expr *ReductionRef);
/// Creates an empty directive.
///
/// \param C AST context.
/// \param NumClauses Number of clauses.
///
static OMPTaskgroupDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses, EmptyShell);
/// Returns reference to the task_reduction return variable.
const Expr *getReductionRef() const {
return static_cast<const Expr *>(*std::next(child_begin(), 1));
}
Expr *getReductionRef() {
return static_cast<Expr *>(*std::next(child_begin(), 1));
}
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPTaskgroupDirectiveClass;
}
};
/// This represents '#pragma omp flush' directive.
///
/// \code
/// #pragma omp flush(a,b)
/// \endcode
/// In this example directive '#pragma omp flush' has 2 arguments- variables 'a'
/// and 'b'.
/// 'omp flush' directive does not have clauses but have an optional list of
/// variables to flush. This list of variables is stored within some fake clause
/// FlushClause.
class OMPFlushDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param NumClauses Number of clauses.
///
OMPFlushDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned NumClauses)
: OMPExecutableDirective(this, OMPFlushDirectiveClass, OMPD_flush,
StartLoc, EndLoc, NumClauses, 0) {}
/// Build an empty directive.
///
/// \param NumClauses Number of clauses.
///
explicit OMPFlushDirective(unsigned NumClauses)
: OMPExecutableDirective(this, OMPFlushDirectiveClass, OMPD_flush,
SourceLocation(), SourceLocation(), NumClauses,
0) {}
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param Clauses List of clauses (only single OMPFlushClause clause is
/// allowed).
///
static OMPFlushDirective *Create(const ASTContext &C, SourceLocation StartLoc,
SourceLocation EndLoc,
ArrayRef<OMPClause *> Clauses);
/// Creates an empty directive with the place for \a NumClauses
/// clauses.
///
/// \param C AST context.
/// \param NumClauses Number of clauses.
///
static OMPFlushDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses, EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPFlushDirectiveClass;
}
};
/// This represents '#pragma omp ordered' directive.
///
/// \code
/// #pragma omp ordered
/// \endcode
///
class OMPOrderedDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param NumClauses Number of clauses.
///
OMPOrderedDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned NumClauses)
: OMPExecutableDirective(this, OMPOrderedDirectiveClass, OMPD_ordered,
StartLoc, EndLoc, NumClauses, 1) {}
/// Build an empty directive.
///
/// \param NumClauses Number of clauses.
///
explicit OMPOrderedDirective(unsigned NumClauses)
: OMPExecutableDirective(this, OMPOrderedDirectiveClass, OMPD_ordered,
SourceLocation(), SourceLocation(), NumClauses,
1) {}
public:
/// Creates directive.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
///
static OMPOrderedDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt);
/// Creates an empty directive.
///
/// \param C AST context.
/// \param NumClauses Number of clauses.
///
static OMPOrderedDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses, EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPOrderedDirectiveClass;
}
};
/// This represents '#pragma omp atomic' directive.
///
/// \code
/// #pragma omp atomic capture
/// \endcode
/// In this example directive '#pragma omp atomic' has clause 'capture'.
///
class OMPAtomicDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
/// Used for 'atomic update' or 'atomic capture' constructs. They may
/// have atomic expressions of forms
/// \code
/// x = x binop expr;
/// x = expr binop x;
/// \endcode
/// This field is true for the first form of the expression and false for the
/// second. Required for correct codegen of non-associative operations (like
/// << or >>).
bool IsXLHSInRHSPart;
/// Used for 'atomic update' or 'atomic capture' constructs. They may
/// have atomic expressions of forms
/// \code
/// v = x; <update x>;
/// <update x>; v = x;
/// \endcode
/// This field is true for the first(postfix) form of the expression and false
/// otherwise.
bool IsPostfixUpdate;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param NumClauses Number of clauses.
///
OMPAtomicDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned NumClauses)
: OMPExecutableDirective(this, OMPAtomicDirectiveClass, OMPD_atomic,
StartLoc, EndLoc, NumClauses, 5),
IsXLHSInRHSPart(false), IsPostfixUpdate(false) {}
/// Build an empty directive.
///
/// \param NumClauses Number of clauses.
///
explicit OMPAtomicDirective(unsigned NumClauses)
: OMPExecutableDirective(this, OMPAtomicDirectiveClass, OMPD_atomic,
SourceLocation(), SourceLocation(), NumClauses,
5),
IsXLHSInRHSPart(false), IsPostfixUpdate(false) {}
/// Set 'x' part of the associated expression/statement.
void setX(Expr *X) { *std::next(child_begin()) = X; }
/// Set helper expression of the form
/// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
/// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
void setUpdateExpr(Expr *UE) { *std::next(child_begin(), 2) = UE; }
/// Set 'v' part of the associated expression/statement.
void setV(Expr *V) { *std::next(child_begin(), 3) = V; }
/// Set 'expr' part of the associated expression/statement.
void setExpr(Expr *E) { *std::next(child_begin(), 4) = E; }
public:
/// Creates directive with a list of \a Clauses and 'x', 'v' and 'expr'
/// parts of the atomic construct (see Section 2.12.6, atomic Construct, for
/// detailed description of 'x', 'v' and 'expr').
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param X 'x' part of the associated expression/statement.
/// \param V 'v' part of the associated expression/statement.
/// \param E 'expr' part of the associated expression/statement.
/// \param UE Helper expression of the form
/// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
/// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
/// \param IsXLHSInRHSPart true if \a UE has the first form and false if the
/// second.
/// \param IsPostfixUpdate true if original value of 'x' must be stored in
/// 'v', not an updated one.
static OMPAtomicDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, Expr *X, Expr *V,
Expr *E, Expr *UE, bool IsXLHSInRHSPart, bool IsPostfixUpdate);
/// Creates an empty directive with the place for \a NumClauses
/// clauses.
///
/// \param C AST context.
/// \param NumClauses Number of clauses.
///
static OMPAtomicDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses, EmptyShell);
/// Get 'x' part of the associated expression/statement.
Expr *getX() { return cast_or_null<Expr>(*std::next(child_begin())); }
const Expr *getX() const {
return cast_or_null<Expr>(*std::next(child_begin()));
}
/// Get helper expression of the form
/// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
/// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
Expr *getUpdateExpr() {
return cast_or_null<Expr>(*std::next(child_begin(), 2));
}
const Expr *getUpdateExpr() const {
return cast_or_null<Expr>(*std::next(child_begin(), 2));
}
/// Return true if helper update expression has form
/// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' and false if it has form
/// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
/// Return true if 'v' expression must be updated to original value of
/// 'x', false if 'v' must be updated to the new value of 'x'.
bool isPostfixUpdate() const { return IsPostfixUpdate; }
/// Get 'v' part of the associated expression/statement.
Expr *getV() { return cast_or_null<Expr>(*std::next(child_begin(), 3)); }
const Expr *getV() const {
return cast_or_null<Expr>(*std::next(child_begin(), 3));
}
/// Get 'expr' part of the associated expression/statement.
Expr *getExpr() { return cast_or_null<Expr>(*std::next(child_begin(), 4)); }
const Expr *getExpr() const {
return cast_or_null<Expr>(*std::next(child_begin(), 4));
}
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPAtomicDirectiveClass;
}
};
/// This represents '#pragma omp target' directive.
///
/// \code
/// #pragma omp target if(a)
/// \endcode
/// In this example directive '#pragma omp target' has clause 'if' with
/// condition 'a'.
///
class OMPTargetDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param NumClauses Number of clauses.
///
OMPTargetDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned NumClauses)
: OMPExecutableDirective(this, OMPTargetDirectiveClass, OMPD_target,
StartLoc, EndLoc, NumClauses, 1) {}
/// Build an empty directive.
///
/// \param NumClauses Number of clauses.
///
explicit OMPTargetDirective(unsigned NumClauses)
: OMPExecutableDirective(this, OMPTargetDirectiveClass, OMPD_target,
SourceLocation(), SourceLocation(), NumClauses,
1) {}
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
///
static OMPTargetDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt);
/// Creates an empty directive with the place for \a NumClauses
/// clauses.
///
/// \param C AST context.
/// \param NumClauses Number of clauses.
///
static OMPTargetDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses, EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPTargetDirectiveClass;
}
};
/// This represents '#pragma omp target data' directive.
///
/// \code
/// #pragma omp target data device(0) if(a) map(b[:])
/// \endcode
/// In this example directive '#pragma omp target data' has clauses 'device'
/// with the value '0', 'if' with condition 'a' and 'map' with array
/// section 'b[:]'.
///
class OMPTargetDataDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param NumClauses The number of clauses.
///
OMPTargetDataDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned NumClauses)
: OMPExecutableDirective(this, OMPTargetDataDirectiveClass,
OMPD_target_data, StartLoc, EndLoc, NumClauses,
1) {}
/// Build an empty directive.
///
/// \param NumClauses Number of clauses.
///
explicit OMPTargetDataDirective(unsigned NumClauses)
: OMPExecutableDirective(this, OMPTargetDataDirectiveClass,
OMPD_target_data, SourceLocation(),
SourceLocation(), NumClauses, 1) {}
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
///
static OMPTargetDataDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt);
/// Creates an empty directive with the place for \a N clauses.
///
/// \param C AST context.
/// \param N The number of clauses.
///
static OMPTargetDataDirective *CreateEmpty(const ASTContext &C, unsigned N,
EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPTargetDataDirectiveClass;
}
};
/// This represents '#pragma omp target enter data' directive.
///
/// \code
/// #pragma omp target enter data device(0) if(a) map(b[:])
/// \endcode
/// In this example directive '#pragma omp target enter data' has clauses
/// 'device' with the value '0', 'if' with condition 'a' and 'map' with array
/// section 'b[:]'.
///
class OMPTargetEnterDataDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param NumClauses The number of clauses.
///
OMPTargetEnterDataDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned NumClauses)
: OMPExecutableDirective(this, OMPTargetEnterDataDirectiveClass,
OMPD_target_enter_data, StartLoc, EndLoc,
NumClauses, /*NumChildren=*/1) {}
/// Build an empty directive.
///
/// \param NumClauses Number of clauses.
///
explicit OMPTargetEnterDataDirective(unsigned NumClauses)
: OMPExecutableDirective(this, OMPTargetEnterDataDirectiveClass,
OMPD_target_enter_data, SourceLocation(),
SourceLocation(), NumClauses,
/*NumChildren=*/1) {}
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
///
static OMPTargetEnterDataDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt);
/// Creates an empty directive with the place for \a N clauses.
///
/// \param C AST context.
/// \param N The number of clauses.
///
static OMPTargetEnterDataDirective *CreateEmpty(const ASTContext &C,
unsigned N, EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPTargetEnterDataDirectiveClass;
}
};
/// This represents '#pragma omp target exit data' directive.
///
/// \code
/// #pragma omp target exit data device(0) if(a) map(b[:])
/// \endcode
/// In this example directive '#pragma omp target exit data' has clauses
/// 'device' with the value '0', 'if' with condition 'a' and 'map' with array
/// section 'b[:]'.
///
class OMPTargetExitDataDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param NumClauses The number of clauses.
///
OMPTargetExitDataDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned NumClauses)
: OMPExecutableDirective(this, OMPTargetExitDataDirectiveClass,
OMPD_target_exit_data, StartLoc, EndLoc,
NumClauses, /*NumChildren=*/1) {}
/// Build an empty directive.
///
/// \param NumClauses Number of clauses.
///
explicit OMPTargetExitDataDirective(unsigned NumClauses)
: OMPExecutableDirective(this, OMPTargetExitDataDirectiveClass,
OMPD_target_exit_data, SourceLocation(),
SourceLocation(), NumClauses,
/*NumChildren=*/1) {}
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
///
static OMPTargetExitDataDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt);
/// Creates an empty directive with the place for \a N clauses.
///
/// \param C AST context.
/// \param N The number of clauses.
///
static OMPTargetExitDataDirective *CreateEmpty(const ASTContext &C,
unsigned N, EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPTargetExitDataDirectiveClass;
}
};
/// This represents '#pragma omp target parallel' directive.
///
/// \code
/// #pragma omp target parallel if(a)
/// \endcode
/// In this example directive '#pragma omp target parallel' has clause 'if' with
/// condition 'a'.
///
class OMPTargetParallelDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param NumClauses Number of clauses.
///
OMPTargetParallelDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned NumClauses)
: OMPExecutableDirective(this, OMPTargetParallelDirectiveClass,
OMPD_target_parallel, StartLoc, EndLoc,
NumClauses, /*NumChildren=*/1) {}
/// Build an empty directive.
///
/// \param NumClauses Number of clauses.
///
explicit OMPTargetParallelDirective(unsigned NumClauses)
: OMPExecutableDirective(this, OMPTargetParallelDirectiveClass,
OMPD_target_parallel, SourceLocation(),
SourceLocation(), NumClauses,
/*NumChildren=*/1) {}
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
///
static OMPTargetParallelDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt);
/// Creates an empty directive with the place for \a NumClauses
/// clauses.
///
/// \param C AST context.
/// \param NumClauses Number of clauses.
///
static OMPTargetParallelDirective *
CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPTargetParallelDirectiveClass;
}
};
/// This represents '#pragma omp target parallel for' directive.
///
/// \code
/// #pragma omp target parallel for private(a,b) reduction(+:c,d)
/// \endcode
/// In this example directive '#pragma omp target parallel for' has clauses
/// 'private' with the variables 'a' and 'b' and 'reduction' with operator '+'
/// and variables 'c' and 'd'.
///
class OMPTargetParallelForDirective : public OMPLoopDirective {
friend class ASTStmtReader;
/// true if current region has inner cancel directive.
bool HasCancel;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
OMPTargetParallelForDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, unsigned NumClauses)
: OMPLoopDirective(this, OMPTargetParallelForDirectiveClass,
OMPD_target_parallel_for, StartLoc, EndLoc,
CollapsedNum, NumClauses),
HasCancel(false) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
explicit OMPTargetParallelForDirective(unsigned CollapsedNum,
unsigned NumClauses)
: OMPLoopDirective(this, OMPTargetParallelForDirectiveClass,
OMPD_target_parallel_for, SourceLocation(),
SourceLocation(), CollapsedNum, NumClauses),
HasCancel(false) {}
/// Set cancel state.
void setHasCancel(bool Has) { HasCancel = Has; }
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param CollapsedNum Number of collapsed loops.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param Exprs Helper expressions for CodeGen.
/// \param HasCancel true if current directive has inner cancel directive.
///
static OMPTargetParallelForDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses,
Stmt *AssociatedStmt, const HelperExprs &Exprs, bool HasCancel);
/// Creates an empty directive with the place
/// for \a NumClauses clauses.
///
/// \param C AST context.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
static OMPTargetParallelForDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses,
unsigned CollapsedNum,
EmptyShell);
/// Return true if current directive has inner cancel directive.
bool hasCancel() const { return HasCancel; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPTargetParallelForDirectiveClass;
}
};
/// This represents '#pragma omp teams' directive.
///
/// \code
/// #pragma omp teams if(a)
/// \endcode
/// In this example directive '#pragma omp teams' has clause 'if' with
/// condition 'a'.
///
class OMPTeamsDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param NumClauses Number of clauses.
///
OMPTeamsDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned NumClauses)
: OMPExecutableDirective(this, OMPTeamsDirectiveClass, OMPD_teams,
StartLoc, EndLoc, NumClauses, 1) {}
/// Build an empty directive.
///
/// \param NumClauses Number of clauses.
///
explicit OMPTeamsDirective(unsigned NumClauses)
: OMPExecutableDirective(this, OMPTeamsDirectiveClass, OMPD_teams,
SourceLocation(), SourceLocation(), NumClauses,
1) {}
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
///
static OMPTeamsDirective *Create(const ASTContext &C, SourceLocation StartLoc,
SourceLocation EndLoc,
ArrayRef<OMPClause *> Clauses,
Stmt *AssociatedStmt);
/// Creates an empty directive with the place for \a NumClauses
/// clauses.
///
/// \param C AST context.
/// \param NumClauses Number of clauses.
///
static OMPTeamsDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses, EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPTeamsDirectiveClass;
}
};
/// This represents '#pragma omp cancellation point' directive.
///
/// \code
/// #pragma omp cancellation point for
/// \endcode
///
/// In this example a cancellation point is created for innermost 'for' region.
class OMPCancellationPointDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
OpenMPDirectiveKind CancelRegion;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
///
OMPCancellationPointDirective(SourceLocation StartLoc, SourceLocation EndLoc)
: OMPExecutableDirective(this, OMPCancellationPointDirectiveClass,
OMPD_cancellation_point, StartLoc, EndLoc, 0, 0),
CancelRegion(OMPD_unknown) {}
/// Build an empty directive.
///
explicit OMPCancellationPointDirective()
: OMPExecutableDirective(this, OMPCancellationPointDirectiveClass,
OMPD_cancellation_point, SourceLocation(),
SourceLocation(), 0, 0),
CancelRegion(OMPD_unknown) {}
/// Set cancel region for current cancellation point.
/// \param CR Cancellation region.
void setCancelRegion(OpenMPDirectiveKind CR) { CancelRegion = CR; }
public:
/// Creates directive.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
///
static OMPCancellationPointDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
OpenMPDirectiveKind CancelRegion);
/// Creates an empty directive.
///
/// \param C AST context.
///
static OMPCancellationPointDirective *CreateEmpty(const ASTContext &C,
EmptyShell);
/// Get cancellation region for the current cancellation point.
OpenMPDirectiveKind getCancelRegion() const { return CancelRegion; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPCancellationPointDirectiveClass;
}
};
/// This represents '#pragma omp cancel' directive.
///
/// \code
/// #pragma omp cancel for
/// \endcode
///
/// In this example a cancel is created for innermost 'for' region.
class OMPCancelDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
OpenMPDirectiveKind CancelRegion;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param NumClauses Number of clauses.
///
OMPCancelDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned NumClauses)
: OMPExecutableDirective(this, OMPCancelDirectiveClass, OMPD_cancel,
StartLoc, EndLoc, NumClauses, 0),
CancelRegion(OMPD_unknown) {}
/// Build an empty directive.
///
/// \param NumClauses Number of clauses.
explicit OMPCancelDirective(unsigned NumClauses)
: OMPExecutableDirective(this, OMPCancelDirectiveClass, OMPD_cancel,
SourceLocation(), SourceLocation(), NumClauses,
0),
CancelRegion(OMPD_unknown) {}
/// Set cancel region for current cancellation point.
/// \param CR Cancellation region.
void setCancelRegion(OpenMPDirectiveKind CR) { CancelRegion = CR; }
public:
/// Creates directive.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param Clauses List of clauses.
///
static OMPCancelDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
ArrayRef<OMPClause *> Clauses, OpenMPDirectiveKind CancelRegion);
/// Creates an empty directive.
///
/// \param C AST context.
/// \param NumClauses Number of clauses.
///
static OMPCancelDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses, EmptyShell);
/// Get cancellation region for the current cancellation point.
OpenMPDirectiveKind getCancelRegion() const { return CancelRegion; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPCancelDirectiveClass;
}
};
/// This represents '#pragma omp taskloop' directive.
///
/// \code
/// #pragma omp taskloop private(a,b) grainsize(val) num_tasks(num)
/// \endcode
/// In this example directive '#pragma omp taskloop' has clauses 'private'
/// with the variables 'a' and 'b', 'grainsize' with expression 'val' and
/// 'num_tasks' with expression 'num'.
///
class OMPTaskLoopDirective : public OMPLoopDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
OMPTaskLoopDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, unsigned NumClauses)
: OMPLoopDirective(this, OMPTaskLoopDirectiveClass, OMPD_taskloop,
StartLoc, EndLoc, CollapsedNum, NumClauses) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
explicit OMPTaskLoopDirective(unsigned CollapsedNum, unsigned NumClauses)
: OMPLoopDirective(this, OMPTaskLoopDirectiveClass, OMPD_taskloop,
SourceLocation(), SourceLocation(), CollapsedNum,
NumClauses) {}
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param CollapsedNum Number of collapsed loops.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param Exprs Helper expressions for CodeGen.
///
static OMPTaskLoopDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses,
Stmt *AssociatedStmt, const HelperExprs &Exprs);
/// Creates an empty directive with the place
/// for \a NumClauses clauses.
///
/// \param C AST context.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
static OMPTaskLoopDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses,
unsigned CollapsedNum, EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPTaskLoopDirectiveClass;
}
};
/// This represents '#pragma omp taskloop simd' directive.
///
/// \code
/// #pragma omp taskloop simd private(a,b) grainsize(val) num_tasks(num)
/// \endcode
/// In this example directive '#pragma omp taskloop simd' has clauses 'private'
/// with the variables 'a' and 'b', 'grainsize' with expression 'val' and
/// 'num_tasks' with expression 'num'.
///
class OMPTaskLoopSimdDirective : public OMPLoopDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
OMPTaskLoopSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, unsigned NumClauses)
: OMPLoopDirective(this, OMPTaskLoopSimdDirectiveClass,
OMPD_taskloop_simd, StartLoc, EndLoc, CollapsedNum,
NumClauses) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
explicit OMPTaskLoopSimdDirective(unsigned CollapsedNum, unsigned NumClauses)
: OMPLoopDirective(this, OMPTaskLoopSimdDirectiveClass,
OMPD_taskloop_simd, SourceLocation(), SourceLocation(),
CollapsedNum, NumClauses) {}
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param CollapsedNum Number of collapsed loops.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param Exprs Helper expressions for CodeGen.
///
static OMPTaskLoopSimdDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses,
Stmt *AssociatedStmt, const HelperExprs &Exprs);
/// Creates an empty directive with the place
/// for \a NumClauses clauses.
///
/// \param C AST context.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
static OMPTaskLoopSimdDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses,
unsigned CollapsedNum,
EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPTaskLoopSimdDirectiveClass;
}
};
/// This represents '#pragma omp distribute' directive.
///
/// \code
/// #pragma omp distribute private(a,b)
/// \endcode
/// In this example directive '#pragma omp distribute' has clauses 'private'
/// with the variables 'a' and 'b'
///
class OMPDistributeDirective : public OMPLoopDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
OMPDistributeDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, unsigned NumClauses)
: OMPLoopDirective(this, OMPDistributeDirectiveClass, OMPD_distribute,
StartLoc, EndLoc, CollapsedNum, NumClauses)
{}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
explicit OMPDistributeDirective(unsigned CollapsedNum, unsigned NumClauses)
: OMPLoopDirective(this, OMPDistributeDirectiveClass, OMPD_distribute,
SourceLocation(), SourceLocation(), CollapsedNum,
NumClauses)
{}
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param CollapsedNum Number of collapsed loops.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param Exprs Helper expressions for CodeGen.
///
static OMPDistributeDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses,
Stmt *AssociatedStmt, const HelperExprs &Exprs);
/// Creates an empty directive with the place
/// for \a NumClauses clauses.
///
/// \param C AST context.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
static OMPDistributeDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses,
unsigned CollapsedNum, EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPDistributeDirectiveClass;
}
};
/// This represents '#pragma omp target update' directive.
///
/// \code
/// #pragma omp target update to(a) from(b) device(1)
/// \endcode
/// In this example directive '#pragma omp target update' has clause 'to' with
/// argument 'a', clause 'from' with argument 'b' and clause 'device' with
/// argument '1'.
///
class OMPTargetUpdateDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param NumClauses The number of clauses.
///
OMPTargetUpdateDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned NumClauses)
: OMPExecutableDirective(this, OMPTargetUpdateDirectiveClass,
OMPD_target_update, StartLoc, EndLoc, NumClauses,
1) {}
/// Build an empty directive.
///
/// \param NumClauses Number of clauses.
///
explicit OMPTargetUpdateDirective(unsigned NumClauses)
: OMPExecutableDirective(this, OMPTargetUpdateDirectiveClass,
OMPD_target_update, SourceLocation(),
SourceLocation(), NumClauses, 1) {}
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
///
static OMPTargetUpdateDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt);
/// Creates an empty directive with the place for \a NumClauses
/// clauses.
///
/// \param C AST context.
/// \param NumClauses The number of clauses.
///
static OMPTargetUpdateDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses, EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPTargetUpdateDirectiveClass;
}
};
/// This represents '#pragma omp distribute parallel for' composite
/// directive.
///
/// \code
/// #pragma omp distribute parallel for private(a,b)
/// \endcode
/// In this example directive '#pragma omp distribute parallel for' has clause
/// 'private' with the variables 'a' and 'b'
///
class OMPDistributeParallelForDirective : public OMPLoopDirective {
friend class ASTStmtReader;
/// true if the construct has inner cancel directive.
bool HasCancel = false;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
OMPDistributeParallelForDirective(SourceLocation StartLoc,
SourceLocation EndLoc,
unsigned CollapsedNum, unsigned NumClauses)
: OMPLoopDirective(this, OMPDistributeParallelForDirectiveClass,
OMPD_distribute_parallel_for, StartLoc, EndLoc,
CollapsedNum, NumClauses), HasCancel(false) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
explicit OMPDistributeParallelForDirective(unsigned CollapsedNum,
unsigned NumClauses)
: OMPLoopDirective(this, OMPDistributeParallelForDirectiveClass,
OMPD_distribute_parallel_for, SourceLocation(),
SourceLocation(), CollapsedNum, NumClauses),
HasCancel(false) {}
/// Set cancel state.
void setHasCancel(bool Has) { HasCancel = Has; }
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param CollapsedNum Number of collapsed loops.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param Exprs Helper expressions for CodeGen.
/// \param HasCancel true if this directive has inner cancel directive.
///
static OMPDistributeParallelForDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses,
Stmt *AssociatedStmt, const HelperExprs &Exprs, bool HasCancel);
/// Creates an empty directive with the place
/// for \a NumClauses clauses.
///
/// \param C AST context.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
static OMPDistributeParallelForDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses,
unsigned CollapsedNum,
EmptyShell);
/// Return true if current directive has inner cancel directive.
bool hasCancel() const { return HasCancel; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPDistributeParallelForDirectiveClass;
}
};
/// This represents '#pragma omp distribute parallel for simd' composite
/// directive.
///
/// \code
/// #pragma omp distribute parallel for simd private(x)
/// \endcode
/// In this example directive '#pragma omp distribute parallel for simd' has
/// clause 'private' with the variables 'x'
///
class OMPDistributeParallelForSimdDirective final : public OMPLoopDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
OMPDistributeParallelForSimdDirective(SourceLocation StartLoc,
SourceLocation EndLoc,
unsigned CollapsedNum,
unsigned NumClauses)
: OMPLoopDirective(this, OMPDistributeParallelForSimdDirectiveClass,
OMPD_distribute_parallel_for_simd, StartLoc,
EndLoc, CollapsedNum, NumClauses) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
explicit OMPDistributeParallelForSimdDirective(unsigned CollapsedNum,
unsigned NumClauses)
: OMPLoopDirective(this, OMPDistributeParallelForSimdDirectiveClass,
OMPD_distribute_parallel_for_simd,
SourceLocation(), SourceLocation(), CollapsedNum,
NumClauses) {}
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param CollapsedNum Number of collapsed loops.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param Exprs Helper expressions for CodeGen.
///
static OMPDistributeParallelForSimdDirective *Create(
const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses,
Stmt *AssociatedStmt, const HelperExprs &Exprs);
/// Creates an empty directive with the place for \a NumClauses clauses.
///
/// \param C AST context.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
static OMPDistributeParallelForSimdDirective *CreateEmpty(
const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum,
EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPDistributeParallelForSimdDirectiveClass;
}
};
/// This represents '#pragma omp distribute simd' composite directive.
///
/// \code
/// #pragma omp distribute simd private(x)
/// \endcode
/// In this example directive '#pragma omp distribute simd' has clause
/// 'private' with the variables 'x'
///
class OMPDistributeSimdDirective final : public OMPLoopDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
OMPDistributeSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, unsigned NumClauses)
: OMPLoopDirective(this, OMPDistributeSimdDirectiveClass,
OMPD_distribute_simd, StartLoc, EndLoc, CollapsedNum,
NumClauses) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
explicit OMPDistributeSimdDirective(unsigned CollapsedNum,
unsigned NumClauses)
: OMPLoopDirective(this, OMPDistributeSimdDirectiveClass,
OMPD_distribute_simd, SourceLocation(),
SourceLocation(), CollapsedNum, NumClauses) {}
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param CollapsedNum Number of collapsed loops.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param Exprs Helper expressions for CodeGen.
///
static OMPDistributeSimdDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses,
Stmt *AssociatedStmt, const HelperExprs &Exprs);
/// Creates an empty directive with the place for \a NumClauses clauses.
///
/// \param C AST context.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
static OMPDistributeSimdDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses,
unsigned CollapsedNum,
EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPDistributeSimdDirectiveClass;
}
};
/// This represents '#pragma omp target parallel for simd' directive.
///
/// \code
/// #pragma omp target parallel for simd private(a) map(b) safelen(c)
/// \endcode
/// In this example directive '#pragma omp target parallel for simd' has clauses
/// 'private' with the variable 'a', 'map' with the variable 'b' and 'safelen'
/// with the variable 'c'.
///
class OMPTargetParallelForSimdDirective final : public OMPLoopDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
OMPTargetParallelForSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, unsigned NumClauses)
: OMPLoopDirective(this, OMPTargetParallelForSimdDirectiveClass,
OMPD_target_parallel_for_simd, StartLoc, EndLoc,
CollapsedNum, NumClauses) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
explicit OMPTargetParallelForSimdDirective(unsigned CollapsedNum,
unsigned NumClauses)
: OMPLoopDirective(this, OMPTargetParallelForSimdDirectiveClass,
OMPD_target_parallel_for_simd, SourceLocation(),
SourceLocation(), CollapsedNum, NumClauses) {}
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param CollapsedNum Number of collapsed loops.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param Exprs Helper expressions for CodeGen.
///
static OMPTargetParallelForSimdDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses,
Stmt *AssociatedStmt, const HelperExprs &Exprs);
/// Creates an empty directive with the place for \a NumClauses clauses.
///
/// \param C AST context.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
static OMPTargetParallelForSimdDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses,
unsigned CollapsedNum,
EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPTargetParallelForSimdDirectiveClass;
}
};
/// This represents '#pragma omp target simd' directive.
///
/// \code
/// #pragma omp target simd private(a) map(b) safelen(c)
/// \endcode
/// In this example directive '#pragma omp target simd' has clauses 'private'
/// with the variable 'a', 'map' with the variable 'b' and 'safelen' with
/// the variable 'c'.
///
class OMPTargetSimdDirective final : public OMPLoopDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
OMPTargetSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, unsigned NumClauses)
: OMPLoopDirective(this, OMPTargetSimdDirectiveClass,
OMPD_target_simd, StartLoc, EndLoc, CollapsedNum,
NumClauses) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
explicit OMPTargetSimdDirective(unsigned CollapsedNum, unsigned NumClauses)
: OMPLoopDirective(this, OMPTargetSimdDirectiveClass, OMPD_target_simd,
SourceLocation(),SourceLocation(), CollapsedNum,
NumClauses) {}
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param CollapsedNum Number of collapsed loops.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param Exprs Helper expressions for CodeGen.
///
static OMPTargetSimdDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses,
Stmt *AssociatedStmt, const HelperExprs &Exprs);
/// Creates an empty directive with the place for \a NumClauses clauses.
///
/// \param C AST context.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
static OMPTargetSimdDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses,
unsigned CollapsedNum,
EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPTargetSimdDirectiveClass;
}
};
/// This represents '#pragma omp teams distribute' directive.
///
/// \code
/// #pragma omp teams distribute private(a,b)
/// \endcode
/// In this example directive '#pragma omp teams distribute' has clauses
/// 'private' with the variables 'a' and 'b'
///
class OMPTeamsDistributeDirective final : public OMPLoopDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
OMPTeamsDistributeDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, unsigned NumClauses)
: OMPLoopDirective(this, OMPTeamsDistributeDirectiveClass,
OMPD_teams_distribute, StartLoc, EndLoc,
CollapsedNum, NumClauses) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
explicit OMPTeamsDistributeDirective(unsigned CollapsedNum,
unsigned NumClauses)
: OMPLoopDirective(this, OMPTeamsDistributeDirectiveClass,
OMPD_teams_distribute, SourceLocation(),
SourceLocation(), CollapsedNum, NumClauses) {}
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param CollapsedNum Number of collapsed loops.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param Exprs Helper expressions for CodeGen.
///
static OMPTeamsDistributeDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses,
Stmt *AssociatedStmt, const HelperExprs &Exprs);
/// Creates an empty directive with the place for \a NumClauses clauses.
///
/// \param C AST context.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
static OMPTeamsDistributeDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses,
unsigned CollapsedNum,
EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPTeamsDistributeDirectiveClass;
}
};
/// This represents '#pragma omp teams distribute simd'
/// combined directive.
///
/// \code
/// #pragma omp teams distribute simd private(a,b)
/// \endcode
/// In this example directive '#pragma omp teams distribute simd'
/// has clause 'private' with the variables 'a' and 'b'
///
class OMPTeamsDistributeSimdDirective final : public OMPLoopDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
OMPTeamsDistributeSimdDirective(SourceLocation StartLoc,
SourceLocation EndLoc, unsigned CollapsedNum,
unsigned NumClauses)
: OMPLoopDirective(this, OMPTeamsDistributeSimdDirectiveClass,
OMPD_teams_distribute_simd, StartLoc, EndLoc,
CollapsedNum, NumClauses) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
explicit OMPTeamsDistributeSimdDirective(unsigned CollapsedNum,
unsigned NumClauses)
: OMPLoopDirective(this, OMPTeamsDistributeSimdDirectiveClass,
OMPD_teams_distribute_simd, SourceLocation(),
SourceLocation(), CollapsedNum, NumClauses) {}
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param CollapsedNum Number of collapsed loops.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param Exprs Helper expressions for CodeGen.
///
static OMPTeamsDistributeSimdDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses,
Stmt *AssociatedStmt, const HelperExprs &Exprs);
/// Creates an empty directive with the place
/// for \a NumClauses clauses.
///
/// \param C AST context.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
static OMPTeamsDistributeSimdDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses,
unsigned CollapsedNum,
EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPTeamsDistributeSimdDirectiveClass;
}
};
/// This represents '#pragma omp teams distribute parallel for simd' composite
/// directive.
///
/// \code
/// #pragma omp teams distribute parallel for simd private(x)
/// \endcode
/// In this example directive '#pragma omp teams distribute parallel for simd'
/// has clause 'private' with the variables 'x'
///
class OMPTeamsDistributeParallelForSimdDirective final
: public OMPLoopDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
OMPTeamsDistributeParallelForSimdDirective(SourceLocation StartLoc,
SourceLocation EndLoc,
unsigned CollapsedNum,
unsigned NumClauses)
: OMPLoopDirective(this, OMPTeamsDistributeParallelForSimdDirectiveClass,
OMPD_teams_distribute_parallel_for_simd, StartLoc,
EndLoc, CollapsedNum, NumClauses) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
explicit OMPTeamsDistributeParallelForSimdDirective(unsigned CollapsedNum,
unsigned NumClauses)
: OMPLoopDirective(this, OMPTeamsDistributeParallelForSimdDirectiveClass,
OMPD_teams_distribute_parallel_for_simd,
SourceLocation(), SourceLocation(), CollapsedNum,
NumClauses) {}
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param CollapsedNum Number of collapsed loops.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param Exprs Helper expressions for CodeGen.
///
static OMPTeamsDistributeParallelForSimdDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses,
Stmt *AssociatedStmt, const HelperExprs &Exprs);
/// Creates an empty directive with the place for \a NumClauses clauses.
///
/// \param C AST context.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
static OMPTeamsDistributeParallelForSimdDirective *
CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum,
EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPTeamsDistributeParallelForSimdDirectiveClass;
}
};
/// This represents '#pragma omp teams distribute parallel for' composite
/// directive.
///
/// \code
/// #pragma omp teams distribute parallel for private(x)
/// \endcode
/// In this example directive '#pragma omp teams distribute parallel for'
/// has clause 'private' with the variables 'x'
///
class OMPTeamsDistributeParallelForDirective final : public OMPLoopDirective {
friend class ASTStmtReader;
/// true if the construct has inner cancel directive.
bool HasCancel = false;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
OMPTeamsDistributeParallelForDirective(SourceLocation StartLoc,
SourceLocation EndLoc,
unsigned CollapsedNum,
unsigned NumClauses)
: OMPLoopDirective(this, OMPTeamsDistributeParallelForDirectiveClass,
OMPD_teams_distribute_parallel_for, StartLoc, EndLoc,
CollapsedNum, NumClauses), HasCancel(false) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
explicit OMPTeamsDistributeParallelForDirective(unsigned CollapsedNum,
unsigned NumClauses)
: OMPLoopDirective(this, OMPTeamsDistributeParallelForDirectiveClass,
OMPD_teams_distribute_parallel_for, SourceLocation(),
SourceLocation(), CollapsedNum, NumClauses),
HasCancel(false) {}
/// Set cancel state.
void setHasCancel(bool Has) { HasCancel = Has; }
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param CollapsedNum Number of collapsed loops.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param Exprs Helper expressions for CodeGen.
/// \param HasCancel true if this directive has inner cancel directive.
///
static OMPTeamsDistributeParallelForDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses,
Stmt *AssociatedStmt, const HelperExprs &Exprs, bool HasCancel);
/// Creates an empty directive with the place for \a NumClauses clauses.
///
/// \param C AST context.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
static OMPTeamsDistributeParallelForDirective *
CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum,
EmptyShell);
/// Return true if current directive has inner cancel directive.
bool hasCancel() const { return HasCancel; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPTeamsDistributeParallelForDirectiveClass;
}
};
/// This represents '#pragma omp target teams' directive.
///
/// \code
/// #pragma omp target teams if(a>0)
/// \endcode
/// In this example directive '#pragma omp target teams' has clause 'if' with
/// condition 'a>0'.
///
class OMPTargetTeamsDirective final : public OMPExecutableDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param NumClauses Number of clauses.
///
OMPTargetTeamsDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned NumClauses)
: OMPExecutableDirective(this, OMPTargetTeamsDirectiveClass,
OMPD_target_teams, StartLoc, EndLoc, NumClauses,
1) {}
/// Build an empty directive.
///
/// \param NumClauses Number of clauses.
///
explicit OMPTargetTeamsDirective(unsigned NumClauses)
: OMPExecutableDirective(this, OMPTargetTeamsDirectiveClass,
OMPD_target_teams, SourceLocation(),
SourceLocation(), NumClauses, 1) {}
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
///
static OMPTargetTeamsDirective *Create(const ASTContext &C,
SourceLocation StartLoc,
SourceLocation EndLoc,
ArrayRef<OMPClause *> Clauses,
Stmt *AssociatedStmt);
/// Creates an empty directive with the place for \a NumClauses clauses.
///
/// \param C AST context.
/// \param NumClauses Number of clauses.
///
static OMPTargetTeamsDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses, EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPTargetTeamsDirectiveClass;
}
};
/// This represents '#pragma omp target teams distribute' combined directive.
///
/// \code
/// #pragma omp target teams distribute private(x)
/// \endcode
/// In this example directive '#pragma omp target teams distribute' has clause
/// 'private' with the variables 'x'
///
class OMPTargetTeamsDistributeDirective final : public OMPLoopDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
OMPTargetTeamsDistributeDirective(SourceLocation StartLoc,
SourceLocation EndLoc,
unsigned CollapsedNum, unsigned NumClauses)
: OMPLoopDirective(this, OMPTargetTeamsDistributeDirectiveClass,
OMPD_target_teams_distribute, StartLoc, EndLoc,
CollapsedNum, NumClauses) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
explicit OMPTargetTeamsDistributeDirective(unsigned CollapsedNum,
unsigned NumClauses)
: OMPLoopDirective(this, OMPTargetTeamsDistributeDirectiveClass,
OMPD_target_teams_distribute, SourceLocation(),
SourceLocation(), CollapsedNum, NumClauses) {}
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param CollapsedNum Number of collapsed loops.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param Exprs Helper expressions for CodeGen.
///
static OMPTargetTeamsDistributeDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses,
Stmt *AssociatedStmt, const HelperExprs &Exprs);
/// Creates an empty directive with the place for \a NumClauses clauses.
///
/// \param C AST context.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
static OMPTargetTeamsDistributeDirective *
CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum,
EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPTargetTeamsDistributeDirectiveClass;
}
};
/// This represents '#pragma omp target teams distribute parallel for' combined
/// directive.
///
/// \code
/// #pragma omp target teams distribute parallel for private(x)
/// \endcode
/// In this example directive '#pragma omp target teams distribute parallel
/// for' has clause 'private' with the variables 'x'
///
class OMPTargetTeamsDistributeParallelForDirective final
: public OMPLoopDirective {
friend class ASTStmtReader;
/// true if the construct has inner cancel directive.
bool HasCancel = false;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
OMPTargetTeamsDistributeParallelForDirective(SourceLocation StartLoc,
SourceLocation EndLoc,
unsigned CollapsedNum,
unsigned NumClauses)
: OMPLoopDirective(this,
OMPTargetTeamsDistributeParallelForDirectiveClass,
OMPD_target_teams_distribute_parallel_for, StartLoc,
EndLoc, CollapsedNum, NumClauses),
HasCancel(false) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
explicit OMPTargetTeamsDistributeParallelForDirective(unsigned CollapsedNum,
unsigned NumClauses)
: OMPLoopDirective(
this, OMPTargetTeamsDistributeParallelForDirectiveClass,
OMPD_target_teams_distribute_parallel_for, SourceLocation(),
SourceLocation(), CollapsedNum, NumClauses),
HasCancel(false) {}
/// Set cancel state.
void setHasCancel(bool Has) { HasCancel = Has; }
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param CollapsedNum Number of collapsed loops.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param Exprs Helper expressions for CodeGen.
/// \param HasCancel true if this directive has inner cancel directive.
///
static OMPTargetTeamsDistributeParallelForDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses,
Stmt *AssociatedStmt, const HelperExprs &Exprs, bool HasCancel);
/// Creates an empty directive with the place for \a NumClauses clauses.
///
/// \param C AST context.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
static OMPTargetTeamsDistributeParallelForDirective *
CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum,
EmptyShell);
/// Return true if current directive has inner cancel directive.
bool hasCancel() const { return HasCancel; }
static bool classof(const Stmt *T) {
return T->getStmtClass() ==
OMPTargetTeamsDistributeParallelForDirectiveClass;
}
};
/// This represents '#pragma omp target teams distribute parallel for simd'
/// combined directive.
///
/// \code
/// #pragma omp target teams distribute parallel for simd private(x)
/// \endcode
/// In this example directive '#pragma omp target teams distribute parallel
/// for simd' has clause 'private' with the variables 'x'
///
class OMPTargetTeamsDistributeParallelForSimdDirective final
: public OMPLoopDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
OMPTargetTeamsDistributeParallelForSimdDirective(SourceLocation StartLoc,
SourceLocation EndLoc,
unsigned CollapsedNum,
unsigned NumClauses)
: OMPLoopDirective(this,
OMPTargetTeamsDistributeParallelForSimdDirectiveClass,
OMPD_target_teams_distribute_parallel_for_simd,
StartLoc, EndLoc, CollapsedNum, NumClauses) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
explicit OMPTargetTeamsDistributeParallelForSimdDirective(
unsigned CollapsedNum, unsigned NumClauses)
: OMPLoopDirective(
this, OMPTargetTeamsDistributeParallelForSimdDirectiveClass,
OMPD_target_teams_distribute_parallel_for_simd, SourceLocation(),
SourceLocation(), CollapsedNum, NumClauses) {}
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param CollapsedNum Number of collapsed loops.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param Exprs Helper expressions for CodeGen.
///
static OMPTargetTeamsDistributeParallelForSimdDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses,
Stmt *AssociatedStmt, const HelperExprs &Exprs);
/// Creates an empty directive with the place for \a NumClauses clauses.
///
/// \param C AST context.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
static OMPTargetTeamsDistributeParallelForSimdDirective *
CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum,
EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() ==
OMPTargetTeamsDistributeParallelForSimdDirectiveClass;
}
};
/// This represents '#pragma omp target teams distribute simd' combined
/// directive.
///
/// \code
/// #pragma omp target teams distribute simd private(x)
/// \endcode
/// In this example directive '#pragma omp target teams distribute simd'
/// has clause 'private' with the variables 'x'
///
class OMPTargetTeamsDistributeSimdDirective final : public OMPLoopDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
OMPTargetTeamsDistributeSimdDirective(SourceLocation StartLoc,
SourceLocation EndLoc,
unsigned CollapsedNum,
unsigned NumClauses)
: OMPLoopDirective(this, OMPTargetTeamsDistributeSimdDirectiveClass,
OMPD_target_teams_distribute_simd, StartLoc, EndLoc,
CollapsedNum, NumClauses) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
explicit OMPTargetTeamsDistributeSimdDirective(unsigned CollapsedNum,
unsigned NumClauses)
: OMPLoopDirective(this, OMPTargetTeamsDistributeSimdDirectiveClass,
OMPD_target_teams_distribute_simd, SourceLocation(),
SourceLocation(), CollapsedNum, NumClauses) {}
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param CollapsedNum Number of collapsed loops.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param Exprs Helper expressions for CodeGen.
///
static OMPTargetTeamsDistributeSimdDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses,
Stmt *AssociatedStmt, const HelperExprs &Exprs);
/// Creates an empty directive with the place for \a NumClauses clauses.
///
/// \param C AST context.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
static OMPTargetTeamsDistributeSimdDirective *
CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum,
EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPTargetTeamsDistributeSimdDirectiveClass;
}
};
} // end namespace clang
#endif
|
WindowBasedCFAR.h | #pragma once
#include <opencv2\opencv.hpp>
#include "AbstractCFAR.h"
#include "Detector.h"
#include "GaussianDetector.h"
#include "LogNormalDetector.h"
#include "G0Detector.h"
#include "GammaDetector.h"
#include "RayleighDetector.h"
#include "WeibullDetector.h"
using namespace cv;
using namespace std;
class WindowBasedCFAR : public AbstractCFAR {
public:
enum ClutterDistribution {Unknown=0, Gaussian=1, LogNormal=2, Rayleigh=3, G0=4, Gamma=5, Weibull=6};
WindowBasedCFAR(ClutterDistribution clutterDistribution = Gaussian)
{
this->clutterDistribution = clutterDistribution;
bool orderClutterRegions = false;
}
virtual ~WindowBasedCFAR()
{
}
virtual Mat execute(Mat image, double probabilityOfFalseAlarm, map<string, double>& parameters)
{
this->targetRadius = (int)getParameterValue(parameters, "WB-CFAR.targetRadius", 2);
this->guardRadius = (int)getParameterValue(parameters, "WB-CFAR.guardRadius", 3);
this->clutterRadius = (int)getParameterValue(parameters, "WB-CFAR.clutterRadius", 5);
this->osPercent = getParameterValue(parameters, "AC-CFAR.censoringPercentile", 99.0);
const bool usePowerImage = (clutterDistribution == G0);
if (usePowerImage) {
image.convertTo(image, CV_32F);
image = image.mul(image);
}
Mat targetImage(image.rows, image.cols, CV_8UC1);
switch (image.depth())
{
case CV_8U: detectTargets<unsigned char>(image, targetImage, probabilityOfFalseAlarm, clutterDistribution); break;
case CV_8S: detectTargets<char>(image, targetImage, probabilityOfFalseAlarm, clutterDistribution); break;
case CV_16U: detectTargets<unsigned short>(image, targetImage, probabilityOfFalseAlarm, clutterDistribution); break;
case CV_16S: detectTargets<short>(image, targetImage, probabilityOfFalseAlarm, clutterDistribution); break;
case CV_32S: detectTargets<int>(image, targetImage, probabilityOfFalseAlarm, clutterDistribution); break;
case CV_32F: detectTargets<float>(image, targetImage, probabilityOfFalseAlarm, clutterDistribution); break;
case CV_64F: detectTargets<double>(image, targetImage, probabilityOfFalseAlarm, clutterDistribution); break;
default: targetImage = Scalar(0);
}
return targetImage;
}
virtual int getClutterArea(map<string, double>& parameters)
{
this->targetRadius = (int)parameters["WB-CFAR.targetRadius"];
this->guardRadius = (int)parameters["WB-CFAR.guardRadius"];
this->clutterRadius = (int)parameters["WB-CFAR.clutterRadius"];
const int windowRadius = (targetRadius + guardRadius + clutterRadius);
const int clutterArea = sqr(2 * windowRadius + 1) - sqr(2 * (guardRadius + targetRadius) + 1);
return clutterArea;
}
virtual int getBandWidth(map<string, double>& parameters)
{
this->targetRadius = (int)parameters["WB-CFAR.targetRadius"];
this->guardRadius = (int)parameters["WB-CFAR.guardRadius"];
this->clutterRadius = (int)parameters["WB-CFAR.clutterRadius"];
const int windowRadius = (targetRadius + guardRadius + clutterRadius);
return calculateBandSize(windowRadius);
}
protected:
ClutterDistribution clutterDistribution;
bool orderClutterRegions;
int targetRadius;
int guardRadius;
int clutterRadius;
double osPercent;
template<typename T>
static inline T sqr(T x)
{
return x * x;
}
template<typename T>
void detectTargets(Mat& image, Mat& targetImage, double probabilityOfFalseAlarm, ClutterDistribution clutterDistribution)
{
const int threadCount = min(getThreadCount(), image.rows);
Detector* detector;
double* candidateRegion;
double* clutterRegion;
T* imageDataRow;
unsigned char* targetImageRow;
int x, y, numCandidatePixels, numClutterPixels, limit1, limit2, limit3, numRegion1, numRegion2, numRegion3, numRegion4;
#pragma omp parallel private(detector, candidateRegion, clutterRegion, limit1, limit2, limit3) num_threads(threadCount)
{
detector = createDetector(clutterDistribution);
createCFARRegions(candidateRegion, clutterRegion, limit1, limit2, limit3);
#pragma omp for private(x, y, numCandidatePixels, numClutterPixels, numRegion1, numRegion2, numRegion3, numRegion4, imageDataRow, targetImageRow)
for (y=0; y<image.rows; y++) {
imageDataRow = (T*)(image.data + y * image.step);
targetImageRow = (unsigned char*)(targetImage.data + y * targetImage.step);
for (x=0; x<image.cols; x++) {
targetImageRow[x] = 0;
if (imageDataRow[x] > 0) {
numCandidatePixels = 0;
numClutterPixels = 0;
getRegionPixels<T>(image, x, y, candidateRegion, numCandidatePixels, clutterRegion, numClutterPixels, limit1, limit2, limit3, numRegion1, numRegion2, numRegion3, numRegion4);
if (checkTargetExistance(probabilityOfFalseAlarm, detector, candidateRegion, numCandidatePixels, clutterRegion, numClutterPixels, numRegion1, numRegion2, numRegion3, numRegion4)) {
targetImageRow[x] = UCHAR_MAX;
}
}
}
}
removeCFARRegions(candidateRegion, clutterRegion);
removeDetectors(detector);
}
}
virtual Detector* createDetector(ClutterDistribution clutterDistribution)
{
switch (clutterDistribution )
{
case Gaussian : return new GaussianDetector(); break;
case LogNormal : return new LogNormalDetector(); break;
case Rayleigh : return new RayleighDetector(); break;
case G0 : return new G0Detector(); break;
case Gamma : return new GammaDetector(); break;
case Weibull : return new WeibullDetector(); break;
default: return NULL;
}
}
virtual void removeDetectors(Detector* detector)
{
if (detector != NULL) {
delete detector;
}
}
virtual void createCFARRegions(double*& candidateRegion, double*& clutterRegion, int& limit1, int& limit2, int& limit3)
{
limit1 = targetRadius + guardRadius + clutterRadius;
limit2 = targetRadius + guardRadius;
limit3 = targetRadius;
int maxCandidatePixels = sqr(2 * targetRadius + 1);
int maxClutterPixels = sqr(2 * limit1 + 1) - sqr(2 * limit2 + 1);
candidateRegion = new double[maxCandidatePixels];
clutterRegion = new double[maxClutterPixels];
}
virtual void removeCFARRegions(double*& candidateRegion, double*& clutterRegion)
{
delete candidateRegion;
delete clutterRegion;
}
template<typename T>
void getRegionPixels(Mat& image, const int x, const int y,
double* candidateRegion, int& numCandidatePixels, double* clutterRegion, int& numClutterPixels,
const int& limit1, const int& limit2, const int& limit3,
int& numRegion1, int& numRegion2, int& numRegion3, int& numRegion4)
//Last 4 parameters are only used in VI-CFAR
{
numRegion1 = -9999;
numRegion2 = -9999;
numRegion3 = -9999;
numRegion4 = -9999;
if(orderClutterRegions)
getRegionPixelsClutterOrdered<T>(image, x, y, candidateRegion, numCandidatePixels, clutterRegion, numClutterPixels, limit1, limit2, limit3, numRegion1, numRegion2, numRegion3, numRegion4);
else
getRegionPixelsClutterDisordered<T>(image, x, y, candidateRegion, numCandidatePixels, clutterRegion, numClutterPixels, limit1, limit2, limit3);
}
template<typename T>
void getRegionPixelsClutterDisordered(Mat& image, const int x, const int y,
double* candidateRegion, int& numCandidatePixels, double* clutterRegion, int& numClutterPixels,
const int& limit1, const int& limit2, const int& limit3)
{
int jMin = max(0, y-limit1);
int jMax = min(y-limit2-1, image.rows-1);
int iMin = max(0, x-limit1);
int iMax = min(x+limit1, image.cols-1);
for(int j=jMin; j<=jMax; j++)
{
T* imageRow = (T*)(image.data + j * image.step);
for(int i=iMin; i<=iMax; i++)
{
clutterRegion[numClutterPixels] = imageRow[i];
numClutterPixels++;
}
}
jMin = max(0, y-limit2);
jMax = min(y+limit2, image.rows-1);
for(int j=jMin; j<=jMax; j++)
{
T* imageRow = (T*)(image.data + j * image.step);
iMin = max(0, x-limit1);
iMax = min(x-limit2-1, image.cols-1);
for(int i=iMin; i<=iMax; i++)
{
clutterRegion[numClutterPixels] = imageRow[i];
numClutterPixels++;
}
iMin = max(0, x+limit2+1);
iMax = min(x+limit1, image.cols-1);
for(int i=iMin; i<=iMax; i++)
{
clutterRegion[numClutterPixels] = imageRow[i];
numClutterPixels++;
}
if(j>=y-limit3 && j<=y+limit3)
{
iMin = max(0, x-limit3);
iMax = min(x+limit3, image.cols-1);
for(int i=iMin; i<=iMax; i++)
{
candidateRegion[numCandidatePixels] = imageRow[i];
numCandidatePixels++;
}
}
}
jMin = max(0, y+limit2+1);
jMax = min(y+limit1, image.rows-1);
iMin = max(0, x-limit1);
iMax = min(x+limit1, image.cols-1);
for(int j=jMin; j<=jMax; j++)
{
T* imageRow = (T*)(image.data + j * image.step);
for(int i=iMin; i<=iMax; i++)
{
clutterRegion[numClutterPixels] = imageRow[i];
numClutterPixels++;
}
}
}
template<typename T>
void getRegionPixelsClutterOrdered(Mat& image, const int x, const int y,
double* candidateRegion, int& numCandidatePixels, double* clutterRegion, int& numClutterPixels,
const int& limit1, const int& limit2, const int& limit3,
int& numRegion1, int& numRegion2, int& numRegion3, int& numRegion4)
{
T* imageRow;
int iMin, iMax, iMin1, iMax1, iMin2, iMax2, iMin3, iMax3;
int jMin, jMax;
int i,j;
int numClutterPixelsInRegion1 = 0;
int numClutterPixelsInRegion2 = 0;
int numClutterPixelsInRegion3 = 0;
int numClutterPixelsInRegion4 = 0;
calculateNumberOfElementsInClutterRegions(x, y, image.rows, image.cols, limit1, limit2, limit3, numRegion1, numRegion2, numRegion3, numRegion4);
double* clutterRegion1 = clutterRegion;
double* clutterRegion2 = clutterRegion1 + numRegion1;
double* clutterRegion3 = clutterRegion2 + numRegion2;
double* clutterRegion4 = clutterRegion3 + numRegion3;
jMin = max(0, y-limit1);
jMax = min(y-limit2-1, image.rows-1);
iMin = max(0, x-limit1);
iMax = min(x+limit1, image.cols-1);
//Region1 Limits
iMin1 = iMin;
iMax1 = min(x+limit2, iMax);
//Region2Limits
iMin2 = iMax1 + 1;
iMax2 = iMax;
for(j=jMin; j<=jMax; j++)
{
imageRow = (T*)(image.data + j*image.step);
for(i=iMin1; i<=iMax1; i++)
{
clutterRegion1[numClutterPixelsInRegion1] = imageRow[i];
numClutterPixels++;
numClutterPixelsInRegion1++;
}
for(i=iMin2; i<=iMax2; i++)
{
clutterRegion2[numClutterPixelsInRegion2] = imageRow[i];
numClutterPixels++;
numClutterPixelsInRegion2++;
}
}
jMin = max(0, y-limit2);
jMax = min(y+limit2, image.rows-1);
//Region 3 Limits
iMin1 = max(0, x-limit1);
iMax1 = min(x-limit2-1, image.cols-1);
//Region 2 Limits
iMin2 = max(0, x+limit2+1);
iMax2 = min(x+limit1, image.cols-1);
//Candidate Region Pixels
iMin3 = max(0, x-limit3);
iMax3 = min(x+limit3, image.cols-1);
for(j=jMin; j<=jMax; j++)
{
imageRow = (T*)(image.data + j * image.step);
for(i=iMin1; i<=iMax1; i++)
{
clutterRegion3[numClutterPixelsInRegion3] = imageRow[i];
numClutterPixels++;
numClutterPixelsInRegion3++;
}
if(j>=y-limit3 && j<=y+limit3)
{
for(i=iMin3; i<=iMax3; i++)
{
candidateRegion[numCandidatePixels] = imageRow[i];
numCandidatePixels++;
}
}
for(i=iMin2; i<=iMax2; i++)
{
clutterRegion2[numClutterPixelsInRegion2] = imageRow[i];
numClutterPixels++;
numClutterPixelsInRegion2++;
}
}
jMin = max(0, y+limit2+1);
jMax = min(y+limit1, image.rows-1);
//Region 3 Limits
iMin1 = max(0, x-limit1);
iMax1 = x-limit2-1;
//Region 4 Limits
iMin2 = max(0, x-limit2);
iMax2 = min(x+limit1, image.cols-1);
for(j=jMin; j<=jMax; j++)
{
imageRow = (T*)(image.data + j * image.step);
for(i=iMin1; i<=iMax1; i++)
{
clutterRegion3[numClutterPixelsInRegion3] = imageRow[i];
numClutterPixels++;
numClutterPixelsInRegion3++;
}
for(i=iMin2; i<=iMax2; i++)
{
clutterRegion4[numClutterPixelsInRegion4] = imageRow[i];
numClutterPixels++;
numClutterPixelsInRegion4++;
}
}
}
virtual void calculateNumberOfElementsInClutterRegions(const int& x, const int& y, const int& imageHeight, const int& imageWidth,
const int& limit1, const int& limit2, const int& limit3,
int& numRegion1, int& numRegion2, int& numRegion3, int& numRegion4)
{
int minY, maxY, minX, maxX;
minY = max(y-limit1, 0);
maxY = min(y-limit2-1, imageHeight-1);
minX = max(x-limit1, 0);
maxX = min(x+limit2, imageWidth-1);
numRegion1 = max((maxY-minY+1)*(maxX-minX+1), 0);
minY = max(y-limit1, 0);
maxY = min(y+limit2, imageHeight-1);
minX = max(x+limit2+1, 0);
maxX = min(x+limit1, imageWidth-1);
numRegion2 = max((maxY-minY+1)*(maxX-minX+1), 0);
minY = max(y-limit2, 0);
maxY = min(y+limit1, imageHeight-1);
minX = max(x-limit1, 0);
maxX = min(x-limit2-1, imageWidth-1);
numRegion3 = max((maxY-minY+1)*(maxX-minX+1), 0);
minY = max(y+limit2+1, 0);
maxY = min(y+limit1, imageHeight-1);
minX = max(x-limit2, 0);
maxX = min(x+limit1, imageWidth-1);
numRegion4 = max((maxY-minY+1)*(maxX-minX+1), 0);
}
virtual bool checkTargetExistance(double probabilityOfFalseAlarm, Detector* detector, double* candidateRegion, const int& numCandidatePixels, double* clutterRegion, const int& numClutterPixels, const int& numRegion1, const int& numRegion2, const int& numRegion3, const int& numRegion4)
{
return false;
}
};
|
GB_binop__islt_fp32.c | //------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_ek_slice.h"
#include "GB_dense.h"
#include "GB_mkl.h"
#include "GB_binop__include.h"
// C=binop(A,B) is defined by the following types and operators:
// A+B function (eWiseAdd): GB_AaddB__islt_fp32
// A.*B function (eWiseMult): GB_AemultB__islt_fp32
// A*D function (colscale): GB_AxD__islt_fp32
// D*A function (rowscale): GB_DxB__islt_fp32
// C+=B function (dense accum): GB_Cdense_accumB__islt_fp32
// C+=b function (dense accum): GB_Cdense_accumb__islt_fp32
// C+=A+B function (dense ewise3): (none)
// C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__islt_fp32
// C=scalar+B GB_bind1st__islt_fp32
// C=scalar+B' GB_bind1st_tran__islt_fp32
// C=A+scalar GB_bind2nd__islt_fp32
// C=A'+scalar GB_bind2nd_tran__islt_fp32
// C type: float
// A type: float
// B,b type: float
// BinaryOp: cij = (aij < bij)
#define GB_ATYPE \
float
#define GB_BTYPE \
float
#define GB_CTYPE \
float
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
1
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
1
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
float aij = Ax [pA]
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB) \
float bij = Bx [pB]
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
float t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA) \
cij = Ax [pA]
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB) \
cij = Bx [pB]
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z, x, y) \
z = (x < y) ;
// op is second
#define GB_OP_IS_SECOND \
0
// op is plus_fp32 or plus_fp64
#define GB_OP_IS_PLUS_REAL \
0
// op is minus_fp32 or minus_fp64
#define GB_OP_IS_MINUS_REAL \
0
// GB_cblas_*axpy gateway routine, if it exists for this operator and type:
#define GB_CBLAS_AXPY \
(none)
// do the numerical phases of GB_add and GB_emult
#define GB_PHASE_2_OF_2
// hard-coded loops can be vectorized
#define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_ISLT || GxB_NO_FP32 || GxB_NO_ISLT_FP32)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
#if 0
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void (none)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
#endif
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
GrB_Info GB_Cdense_ewise3_noaccum__islt_fp32
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_dense_ewise3_noaccum_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += B, accumulate a sparse matrix into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB_Cdense_accumB__islt_fp32
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *GB_RESTRICT kfirst_slice,
const int64_t *GB_RESTRICT klast_slice,
const int64_t *GB_RESTRICT pstart_slice,
const int ntasks,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
#include "GB_dense_subassign_23_template.c"
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB_Cdense_accumb__islt_fp32
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
// get the scalar b for C += b, of type float
float bwork = (*((float *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB_AxD__islt_fp32
(
GrB_Matrix C,
const GrB_Matrix A, bool A_is_pattern,
const GrB_Matrix D, bool D_is_pattern,
const int64_t *GB_RESTRICT kfirst_slice,
const int64_t *GB_RESTRICT klast_slice,
const int64_t *GB_RESTRICT pstart_slice,
const int ntasks,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
float *GB_RESTRICT Cx = (float *) C->x ;
#include "GB_AxB_colscale_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB_DxB__islt_fp32
(
GrB_Matrix C,
const GrB_Matrix D, bool D_is_pattern,
const GrB_Matrix B, bool B_is_pattern,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
float *GB_RESTRICT Cx = (float *) C->x ;
#include "GB_AxB_rowscale_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseAdd: C = A+B or C<M> = A+B
//------------------------------------------------------------------------------
GrB_Info GB_AaddB__islt_fp32
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const bool Ch_is_Mh,
const int64_t *GB_RESTRICT C_to_M,
const int64_t *GB_RESTRICT C_to_A,
const int64_t *GB_RESTRICT C_to_B,
const GB_task_struct *GB_RESTRICT TaskList,
const int ntasks,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_add_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C = A.*B or C<M> = A.*B
//------------------------------------------------------------------------------
GrB_Info GB_AemultB__islt_fp32
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *GB_RESTRICT C_to_M,
const int64_t *GB_RESTRICT C_to_A,
const int64_t *GB_RESTRICT C_to_B,
const GB_task_struct *GB_RESTRICT TaskList,
const int ntasks,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
GrB_Info GB_bind1st__islt_fp32
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
float *Cx = (float *) Cx_output ;
float x = (*((float *) x_input)) ;
float *Bx = (float *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
float bij = Bx [p] ;
Cx [p] = (x < bij) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB_bind2nd__islt_fp32
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
float *Cx = (float *) Cx_output ;
float *Ax = (float *) Ax_input ;
float y = (*((float *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
float aij = Ax [p] ;
Cx [p] = (aij < y) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no typcasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
float aij = Ax [pA] ; \
Cx [pC] = (x < aij) ; \
}
GrB_Info GB_bind1st_tran__islt_fp32
(
GrB_Matrix C,
const GB_void *x_input,
const GrB_Matrix A,
int64_t *GB_RESTRICT *Rowcounts,
GBI_single_iterator Iter,
const int64_t *GB_RESTRICT A_slice,
int naslice
)
{
// GB_unop_transpose.c uses GB_ATYPE, but A is
// the 2nd input to binary operator z=f(x,y).
#undef GB_ATYPE
#define GB_ATYPE \
float
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
float x = (*((const float *) x_input)) ;
#define GB_PHASE_2_OF_2
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
float
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typcasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
float aij = Ax [pA] ; \
Cx [pC] = (aij < y) ; \
}
GrB_Info GB_bind2nd_tran__islt_fp32
(
GrB_Matrix C,
const GrB_Matrix A,
const GB_void *y_input,
int64_t *GB_RESTRICT *Rowcounts,
GBI_single_iterator Iter,
const int64_t *GB_RESTRICT A_slice,
int naslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
float y = (*((const float *) y_input)) ;
#define GB_PHASE_2_OF_2
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
parallelcode.c | #include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<time.h>
#include<omp.h>
void sample_rand(const double a, const double b ,const int dim, double *x) {
#pragma omp parallel for
for(int i=0;i<dim;++i) {
double tmp = ((double) rand())/((double) RAND_MAX);
x[i] = (b-a)*tmp + a;
}
}
int main(int argc, char** argv)
{
double start_time = omp_get_wtime();
int NumThreads = 4;
omp_set_num_threads(NumThreads);
long N = atol( argv[1] );
srand(time(NULL)); // each MPI process gets a unique seed
const int dim = 10;
double x[dim]; // array of random numbers
double V = 4.0, integral = 0.0, sum = 0.0;
int count=0;
for(int i=N;i>1;i=i/4)
{
count++; // to get the number of intermediate integrals
}
double integrals[count]; // this array stores all intermediate integral values.
for(int i=0;i<N;i++)
{
sample_rand(-1.,1.,dim,x);
double f;
if(pow(x[0],2)+pow(x[1],2)+pow(x[2],2)+pow(x[3],2)+pow(x[4],2)+pow(x[5],2)+pow(x[6],2)+pow(x[7],2)+pow(x[8],2)+pow(x[9],2)<=1)
f=1.0;
else
f=0.0;
sum+=f;
int k=1;
for(int j=1;j<=i+1;j=pow(4,k))
{
if(i+1==j)
//printf("For iteration %d integral is %lf\n", j,V*sum/N);
integrals[k-1]=V*sum/N;
k++;
}
}
for(int i=0;i<count;i++)
{
printf("%lf %e %e %e\n",pow(4,i+1),integrals[i] ,fabs(integrals[i]-0.0), fabs(integrals[i]-integrals[i+1]));
}
integral = V*sum/N;
double time = omp_get_wtime() - start_time;
//uncomment printf to get integral value
//printf("final integral is:%e\n",integral);
printf("%lf",time);
return 0;
}
|
segment.c | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% SSSSS EEEEE GGGG M M EEEEE N N TTTTT %
% SS E G MM MM E NN N T %
% SSS EEE G GGG M M M EEE N N N T %
% SS E G G M M E N NN T %
% SSSSS EEEEE GGGG M M EEEEE N N T %
% %
% %
% MagickCore Methods to Segment an Image with Thresholding Fuzzy c-Means %
% %
% Software Design %
% Cristy %
% April 1993 %
% %
% %
% Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://imagemagick.org/script/license.php %
% %
% 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. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Segment segments an image by analyzing the histograms of the color
% components and identifying units that are homogeneous with the fuzzy
% c-means technique. The scale-space filter analyzes the histograms of
% the three color components of the image and identifies a set of
% classes. The extents of each class is used to coarsely segment the
% image with thresholding. The color associated with each class is
% determined by the mean color of all pixels within the extents of a
% particular class. Finally, any unclassified pixels are assigned to
% the closest class with the fuzzy c-means technique.
%
% The fuzzy c-Means algorithm can be summarized as follows:
%
% o Build a histogram, one for each color component of the image.
%
% o For each histogram, successively apply the scale-space filter and
% build an interval tree of zero crossings in the second derivative
% at each scale. Analyze this scale-space ''fingerprint'' to
% determine which peaks and valleys in the histogram are most
% predominant.
%
% o The fingerprint defines intervals on the axis of the histogram.
% Each interval contains either a minima or a maxima in the original
% signal. If each color component lies within the maxima interval,
% that pixel is considered ''classified'' and is assigned an unique
% class number.
%
% o Any pixel that fails to be classified in the above thresholding
% pass is classified using the fuzzy c-Means technique. It is
% assigned to one of the classes discovered in the histogram analysis
% phase.
%
% The fuzzy c-Means technique attempts to cluster a pixel by finding
% the local minima of the generalized within group sum of squared error
% objective function. A pixel is assigned to the closest class of
% which the fuzzy membership has a maximum value.
%
% Segment is strongly based on software written by Andy Gallo,
% University of Delaware.
%
% The following reference was used in creating this program:
%
% Young Won Lim, Sang Uk Lee, "On The Color Image Segmentation
% Algorithm Based on the Thresholding and the Fuzzy c-Means
% Techniques", Pattern Recognition, Volume 23, Number 9, pages
% 935-952, 1990.
%
%
*/
#include "MagickCore/studio.h"
#include "MagickCore/cache.h"
#include "MagickCore/color.h"
#include "MagickCore/colormap.h"
#include "MagickCore/colorspace.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/memory_.h"
#include "MagickCore/memory-private.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/pixel-private.h"
#include "MagickCore/quantize.h"
#include "MagickCore/quantum.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/resource_.h"
#include "MagickCore/segment.h"
#include "MagickCore/string_.h"
#include "MagickCore/thread-private.h"
/*
Define declarations.
*/
#define MaxDimension 3
#define DeltaTau 0.5f
#if defined(FastClassify)
#define WeightingExponent 2.0
#define SegmentPower(ratio) (ratio)
#else
#define WeightingExponent 2.5
#define SegmentPower(ratio) pow(ratio,(double) (1.0/(weighting_exponent-1.0)));
#endif
#define Tau 5.2f
/*
Typedef declarations.
*/
typedef struct _ExtentPacket
{
double
center;
ssize_t
index,
left,
right;
} ExtentPacket;
typedef struct _Cluster
{
struct _Cluster
*next;
ExtentPacket
red,
green,
blue;
ssize_t
count,
id;
} Cluster;
typedef struct _IntervalTree
{
double
tau;
ssize_t
left,
right;
double
mean_stability,
stability;
struct _IntervalTree
*sibling,
*child;
} IntervalTree;
typedef struct _ZeroCrossing
{
double
tau,
histogram[256];
short
crossings[256];
} ZeroCrossing;
/*
Constant declarations.
*/
static const int
Blue = 2,
Green = 1,
Red = 0,
SafeMargin = 3,
TreeLength = 600;
/*
Method prototypes.
*/
static double
OptimalTau(const ssize_t *,const double,const double,const double,
const double,short *);
static ssize_t
DefineRegion(const short *,ExtentPacket *);
static void
FreeNodes(IntervalTree *),
InitializeHistogram(const Image *,ssize_t **,ExceptionInfo *),
ScaleSpace(const ssize_t *,const double,double *),
ZeroCrossHistogram(double *,const double,short *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ C l a s s i f y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Classify() defines one or more classes. Each pixel is thresholded to
% determine which class it belongs to. If the class is not identified it is
% assigned to the closest class based on the fuzzy c-Means technique.
%
% The format of the Classify method is:
%
% MagickBooleanType Classify(Image *image,short **extrema,
% const double cluster_threshold,
% const double weighting_exponent,
% const MagickBooleanType verbose,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o image: the image.
%
% o extrema: Specifies a pointer to an array of integers. They
% represent the peaks and valleys of the histogram for each color
% component.
%
% o cluster_threshold: This double represents the minimum number of
% pixels contained in a hexahedra before it can be considered valid
% (expressed as a percentage).
%
% o weighting_exponent: Specifies the membership weighting exponent.
%
% o verbose: A value greater than zero prints detailed information about
% the identified classes.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType Classify(Image *image,short **extrema,
const double cluster_threshold,
const double weighting_exponent,const MagickBooleanType verbose,
ExceptionInfo *exception)
{
#define SegmentImageTag "Segment/Image"
#define ThrowClassifyException(severity,tag,label) \
{\
for (cluster=head; cluster != (Cluster *) NULL; cluster=next_cluster) \
{ \
next_cluster=cluster->next; \
cluster=(Cluster *) RelinquishMagickMemory(cluster); \
} \
if (squares != (double *) NULL) \
{ \
squares-=255; \
free_squares=squares; \
free_squares=(double *) RelinquishMagickMemory(free_squares); \
} \
ThrowBinaryException(severity,tag,label); \
}
CacheView
*image_view;
Cluster
*cluster,
*head,
*last_cluster,
*next_cluster;
ExtentPacket
blue,
green,
red;
MagickOffsetType
progress;
double
*free_squares;
MagickStatusType
status;
register ssize_t
i;
register double
*squares;
size_t
number_clusters;
ssize_t
count,
y;
/*
Form clusters.
*/
cluster=(Cluster *) NULL;
head=(Cluster *) NULL;
squares=(double *) NULL;
(void) memset(&red,0,sizeof(red));
(void) memset(&green,0,sizeof(green));
(void) memset(&blue,0,sizeof(blue));
while (DefineRegion(extrema[Red],&red) != 0)
{
green.index=0;
while (DefineRegion(extrema[Green],&green) != 0)
{
blue.index=0;
while (DefineRegion(extrema[Blue],&blue) != 0)
{
/*
Allocate a new class.
*/
if (head != (Cluster *) NULL)
{
cluster->next=(Cluster *) AcquireMagickMemory(
sizeof(*cluster->next));
cluster=cluster->next;
}
else
{
cluster=(Cluster *) AcquireMagickMemory(sizeof(*cluster));
head=cluster;
}
if (cluster == (Cluster *) NULL)
ThrowClassifyException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
/*
Initialize a new class.
*/
cluster->count=0;
cluster->red=red;
cluster->green=green;
cluster->blue=blue;
cluster->next=(Cluster *) NULL;
}
}
}
if (head == (Cluster *) NULL)
{
/*
No classes were identified-- create one.
*/
cluster=(Cluster *) AcquireMagickMemory(sizeof(*cluster));
if (cluster == (Cluster *) NULL)
ThrowClassifyException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
/*
Initialize a new class.
*/
cluster->count=0;
cluster->red=red;
cluster->green=green;
cluster->blue=blue;
cluster->next=(Cluster *) NULL;
head=cluster;
}
/*
Count the pixels for each cluster.
*/
status=MagickTrue;
count=0;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*p;
register ssize_t
x;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next)
if (((ssize_t) ScaleQuantumToChar(GetPixelRed(image,p)) >=
(cluster->red.left-SafeMargin)) &&
((ssize_t) ScaleQuantumToChar(GetPixelRed(image,p)) <=
(cluster->red.right+SafeMargin)) &&
((ssize_t) ScaleQuantumToChar(GetPixelGreen(image,p)) >=
(cluster->green.left-SafeMargin)) &&
((ssize_t) ScaleQuantumToChar(GetPixelGreen(image,p)) <=
(cluster->green.right+SafeMargin)) &&
((ssize_t) ScaleQuantumToChar(GetPixelBlue(image,p)) >=
(cluster->blue.left-SafeMargin)) &&
((ssize_t) ScaleQuantumToChar(GetPixelBlue(image,p)) <=
(cluster->blue.right+SafeMargin)))
{
/*
Count this pixel.
*/
count++;
cluster->red.center+=(double) ScaleQuantumToChar(
GetPixelRed(image,p));
cluster->green.center+=(double) ScaleQuantumToChar(
GetPixelGreen(image,p));
cluster->blue.center+=(double) ScaleQuantumToChar(
GetPixelBlue(image,p));
cluster->count++;
break;
}
p+=GetPixelChannels(image);
}
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,SegmentImageTag,progress,2*image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
/*
Remove clusters that do not meet minimum cluster threshold.
*/
count=0;
last_cluster=head;
next_cluster=head;
for (cluster=head; cluster != (Cluster *) NULL; cluster=next_cluster)
{
next_cluster=cluster->next;
if ((cluster->count > 0) &&
(cluster->count >= (count*cluster_threshold/100.0)))
{
/*
Initialize cluster.
*/
cluster->id=count;
cluster->red.center/=cluster->count;
cluster->green.center/=cluster->count;
cluster->blue.center/=cluster->count;
count++;
last_cluster=cluster;
continue;
}
/*
Delete cluster.
*/
if (cluster == head)
head=next_cluster;
else
last_cluster->next=next_cluster;
cluster=(Cluster *) RelinquishMagickMemory(cluster);
}
number_clusters=(size_t) count;
if (verbose != MagickFalse)
{
/*
Print cluster statistics.
*/
(void) FormatLocaleFile(stdout,"Fuzzy C-means Statistics\n");
(void) FormatLocaleFile(stdout,"===================\n\n");
(void) FormatLocaleFile(stdout,"\tCluster Threshold = %g\n",(double)
cluster_threshold);
(void) FormatLocaleFile(stdout,"\tWeighting Exponent = %g\n",(double)
weighting_exponent);
(void) FormatLocaleFile(stdout,"\tTotal Number of Clusters = %.20g\n\n",
(double) number_clusters);
/*
Print the total number of points per cluster.
*/
(void) FormatLocaleFile(stdout,"\n\nNumber of Vectors Per Cluster\n");
(void) FormatLocaleFile(stdout,"=============================\n\n");
for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next)
(void) FormatLocaleFile(stdout,"Cluster #%.20g = %.20g\n",(double)
cluster->id,(double) cluster->count);
/*
Print the cluster extents.
*/
(void) FormatLocaleFile(stdout,
"\n\n\nCluster Extents: (Vector Size: %d)\n",MaxDimension);
(void) FormatLocaleFile(stdout,"================");
for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next)
{
(void) FormatLocaleFile(stdout,"\n\nCluster #%.20g\n\n",(double)
cluster->id);
(void) FormatLocaleFile(stdout,
"%.20g-%.20g %.20g-%.20g %.20g-%.20g\n",(double)
cluster->red.left,(double) cluster->red.right,(double)
cluster->green.left,(double) cluster->green.right,(double)
cluster->blue.left,(double) cluster->blue.right);
}
/*
Print the cluster center values.
*/
(void) FormatLocaleFile(stdout,
"\n\n\nCluster Center Values: (Vector Size: %d)\n",MaxDimension);
(void) FormatLocaleFile(stdout,"=====================");
for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next)
{
(void) FormatLocaleFile(stdout,"\n\nCluster #%.20g\n\n",(double)
cluster->id);
(void) FormatLocaleFile(stdout,"%g %g %g\n",(double)
cluster->red.center,(double) cluster->green.center,(double)
cluster->blue.center);
}
(void) FormatLocaleFile(stdout,"\n");
}
if (number_clusters > 256)
ThrowClassifyException(ImageError,"TooManyClusters",image->filename);
/*
Speed up distance calculations.
*/
squares=(double *) AcquireQuantumMemory(513UL,sizeof(*squares));
if (squares == (double *) NULL)
ThrowClassifyException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
squares+=255;
for (i=(-255); i <= 255; i++)
squares[i]=(double) i*(double) i;
/*
Allocate image colormap.
*/
if (AcquireImageColormap(image,number_clusters,exception) == MagickFalse)
ThrowClassifyException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
i=0;
for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next)
{
image->colormap[i].red=(double) ScaleCharToQuantum((unsigned char)
(cluster->red.center+0.5));
image->colormap[i].green=(double) ScaleCharToQuantum((unsigned char)
(cluster->green.center+0.5));
image->colormap[i].blue=(double) ScaleCharToQuantum((unsigned char)
(cluster->blue.center+0.5));
i++;
}
/*
Do course grain classes.
*/
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
Cluster
*clust;
register const PixelInfo
*magick_restrict p;
register ssize_t
x;
register Quantum
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelIndex(image,(Quantum) 0,q);
for (clust=head; clust != (Cluster *) NULL; clust=clust->next)
{
if (((ssize_t) ScaleQuantumToChar(GetPixelRed(image,q)) >=
(clust->red.left-SafeMargin)) &&
((ssize_t) ScaleQuantumToChar(GetPixelRed(image,q)) <=
(clust->red.right+SafeMargin)) &&
((ssize_t) ScaleQuantumToChar(GetPixelGreen(image,q)) >=
(clust->green.left-SafeMargin)) &&
((ssize_t) ScaleQuantumToChar(GetPixelGreen(image,q)) <=
(clust->green.right+SafeMargin)) &&
((ssize_t) ScaleQuantumToChar(GetPixelBlue(image,q)) >=
(clust->blue.left-SafeMargin)) &&
((ssize_t) ScaleQuantumToChar(GetPixelBlue(image,q)) <=
(clust->blue.right+SafeMargin)))
{
/*
Classify this pixel.
*/
SetPixelIndex(image,(Quantum) clust->id,q);
break;
}
}
if (clust == (Cluster *) NULL)
{
double
distance_squared,
local_minima,
numerator,
ratio,
sum;
register ssize_t
j,
k;
/*
Compute fuzzy membership.
*/
local_minima=0.0;
for (j=0; j < (ssize_t) image->colors; j++)
{
sum=0.0;
p=image->colormap+j;
distance_squared=squares[(ssize_t) ScaleQuantumToChar(
GetPixelRed(image,q))-(ssize_t)
ScaleQuantumToChar(ClampToQuantum(p->red))]+squares[(ssize_t)
ScaleQuantumToChar(GetPixelGreen(image,q))-(ssize_t)
ScaleQuantumToChar(ClampToQuantum(p->green))]+squares[(ssize_t)
ScaleQuantumToChar(GetPixelBlue(image,q))-(ssize_t)
ScaleQuantumToChar(ClampToQuantum(p->blue))];
numerator=distance_squared;
for (k=0; k < (ssize_t) image->colors; k++)
{
p=image->colormap+k;
distance_squared=squares[(ssize_t) ScaleQuantumToChar(
GetPixelRed(image,q))-(ssize_t)
ScaleQuantumToChar(ClampToQuantum(p->red))]+squares[
(ssize_t) ScaleQuantumToChar(GetPixelGreen(image,q))-(ssize_t)
ScaleQuantumToChar(ClampToQuantum(p->green))]+squares[
(ssize_t) ScaleQuantumToChar(GetPixelBlue(image,q))-(ssize_t)
ScaleQuantumToChar(ClampToQuantum(p->blue))];
ratio=numerator/distance_squared;
sum+=SegmentPower(ratio);
}
if ((sum != 0.0) && ((1.0/sum) > local_minima))
{
/*
Classify this pixel.
*/
local_minima=1.0/sum;
SetPixelIndex(image,(Quantum) j,q);
}
}
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,SegmentImageTag,progress,2*image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
status&=SyncImage(image,exception);
/*
Relinquish resources.
*/
for (cluster=head; cluster != (Cluster *) NULL; cluster=next_cluster)
{
next_cluster=cluster->next;
cluster=(Cluster *) RelinquishMagickMemory(cluster);
}
squares-=255;
free_squares=squares;
free_squares=(double *) RelinquishMagickMemory(free_squares);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ C o n s o l i d a t e C r o s s i n g s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ConsolidateCrossings() guarantees that an even number of zero crossings
% always lie between two crossings.
%
% The format of the ConsolidateCrossings method is:
%
% ConsolidateCrossings(ZeroCrossing *zero_crossing,
% const size_t number_crossings)
%
% A description of each parameter follows.
%
% o zero_crossing: Specifies an array of structures of type ZeroCrossing.
%
% o number_crossings: This size_t specifies the number of elements
% in the zero_crossing array.
%
*/
static void ConsolidateCrossings(ZeroCrossing *zero_crossing,
const size_t number_crossings)
{
register ssize_t
i,
j,
k,
l;
ssize_t
center,
correct,
count,
left,
right;
/*
Consolidate zero crossings.
*/
for (i=(ssize_t) number_crossings-1; i >= 0; i--)
for (j=0; j <= 255; j++)
{
if (zero_crossing[i].crossings[j] == 0)
continue;
/*
Find the entry that is closest to j and still preserves the
property that there are an even number of crossings between
intervals.
*/
for (k=j-1; k > 0; k--)
if (zero_crossing[i+1].crossings[k] != 0)
break;
left=MagickMax(k,0);
center=j;
for (k=j+1; k < 255; k++)
if (zero_crossing[i+1].crossings[k] != 0)
break;
right=MagickMin(k,255);
/*
K is the zero crossing just left of j.
*/
for (k=j-1; k > 0; k--)
if (zero_crossing[i].crossings[k] != 0)
break;
if (k < 0)
k=0;
/*
Check center for an even number of crossings between k and j.
*/
correct=(-1);
if (zero_crossing[i+1].crossings[j] != 0)
{
count=0;
for (l=k+1; l < center; l++)
if (zero_crossing[i+1].crossings[l] != 0)
count++;
if (((count % 2) == 0) && (center != k))
correct=center;
}
/*
Check left for an even number of crossings between k and j.
*/
if (correct == -1)
{
count=0;
for (l=k+1; l < left; l++)
if (zero_crossing[i+1].crossings[l] != 0)
count++;
if (((count % 2) == 0) && (left != k))
correct=left;
}
/*
Check right for an even number of crossings between k and j.
*/
if (correct == -1)
{
count=0;
for (l=k+1; l < right; l++)
if (zero_crossing[i+1].crossings[l] != 0)
count++;
if (((count % 2) == 0) && (right != k))
correct=right;
}
l=(ssize_t) zero_crossing[i].crossings[j];
zero_crossing[i].crossings[j]=0;
if (correct != -1)
zero_crossing[i].crossings[correct]=(short) l;
}
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D e f i n e R e g i o n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DefineRegion() defines the left and right boundaries of a peak region.
%
% The format of the DefineRegion method is:
%
% ssize_t DefineRegion(const short *extrema,ExtentPacket *extents)
%
% A description of each parameter follows.
%
% o extrema: Specifies a pointer to an array of integers. They
% represent the peaks and valleys of the histogram for each color
% component.
%
% o extents: This pointer to an ExtentPacket represent the extends
% of a particular peak or valley of a color component.
%
*/
static ssize_t DefineRegion(const short *extrema,ExtentPacket *extents)
{
/*
Initialize to default values.
*/
extents->left=0;
extents->center=0.0;
extents->right=255;
/*
Find the left side (maxima).
*/
for ( ; extents->index <= 255; extents->index++)
if (extrema[extents->index] > 0)
break;
if (extents->index > 255)
return(MagickFalse); /* no left side - no region exists */
extents->left=extents->index;
/*
Find the right side (minima).
*/
for ( ; extents->index <= 255; extents->index++)
if (extrema[extents->index] < 0)
break;
extents->right=extents->index-1;
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D e r i v a t i v e H i s t o g r a m %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DerivativeHistogram() determines the derivative of the histogram using
% central differencing.
%
% The format of the DerivativeHistogram method is:
%
% DerivativeHistogram(const double *histogram,
% double *derivative)
%
% A description of each parameter follows.
%
% o histogram: Specifies an array of doubles representing the number
% of pixels for each intensity of a particular color component.
%
% o derivative: This array of doubles is initialized by
% DerivativeHistogram to the derivative of the histogram using central
% differencing.
%
*/
static void DerivativeHistogram(const double *histogram,
double *derivative)
{
register ssize_t
i,
n;
/*
Compute endpoints using second order polynomial interpolation.
*/
n=255;
derivative[0]=(-1.5*histogram[0]+2.0*histogram[1]-0.5*histogram[2]);
derivative[n]=(0.5*histogram[n-2]-2.0*histogram[n-1]+1.5*histogram[n]);
/*
Compute derivative using central differencing.
*/
for (i=1; i < n; i++)
derivative[i]=(histogram[i+1]-histogram[i-1])/2.0;
return;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t I m a g e D y n a m i c T h r e s h o l d %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageDynamicThreshold() returns the dynamic threshold for an image.
%
% The format of the GetImageDynamicThreshold method is:
%
% MagickBooleanType GetImageDynamicThreshold(const Image *image,
% const double cluster_threshold,const double smooth_threshold,
% PixelInfo *pixel,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o image: the image.
%
% o cluster_threshold: This double represents the minimum number of
% pixels contained in a hexahedra before it can be considered valid
% (expressed as a percentage).
%
% o smooth_threshold: the smoothing threshold eliminates noise in the second
% derivative of the histogram. As the value is increased, you can expect a
% smoother second derivative.
%
% o pixel: return the dynamic threshold here.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType GetImageDynamicThreshold(const Image *image,
const double cluster_threshold,const double smooth_threshold,
PixelInfo *pixel,ExceptionInfo *exception)
{
Cluster
*background,
*cluster,
*object,
*head,
*last_cluster,
*next_cluster;
ExtentPacket
blue,
green,
red;
MagickBooleanType
proceed;
double
threshold;
register const Quantum
*p;
register ssize_t
i,
x;
short
*extrema[MaxDimension];
ssize_t
count,
*histogram[MaxDimension],
y;
/*
Allocate histogram and extrema.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
GetPixelInfo(image,pixel);
for (i=0; i < MaxDimension; i++)
{
histogram[i]=(ssize_t *) AcquireQuantumMemory(256UL,sizeof(**histogram));
extrema[i]=(short *) AcquireQuantumMemory(256UL,sizeof(**histogram));
if ((histogram[i] == (ssize_t *) NULL) || (extrema[i] == (short *) NULL))
{
for (i-- ; i >= 0; i--)
{
extrema[i]=(short *) RelinquishMagickMemory(extrema[i]);
histogram[i]=(ssize_t *) RelinquishMagickMemory(histogram[i]);
}
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(MagickFalse);
}
}
/*
Initialize histogram.
*/
InitializeHistogram(image,histogram,exception);
(void) OptimalTau(histogram[Red],Tau,0.2f,DeltaTau,
(smooth_threshold == 0.0f ? 1.0f : smooth_threshold),extrema[Red]);
(void) OptimalTau(histogram[Green],Tau,0.2f,DeltaTau,
(smooth_threshold == 0.0f ? 1.0f : smooth_threshold),extrema[Green]);
(void) OptimalTau(histogram[Blue],Tau,0.2f,DeltaTau,
(smooth_threshold == 0.0f ? 1.0f : smooth_threshold),extrema[Blue]);
/*
Form clusters.
*/
cluster=(Cluster *) NULL;
head=(Cluster *) NULL;
(void) memset(&red,0,sizeof(red));
(void) memset(&green,0,sizeof(green));
(void) memset(&blue,0,sizeof(blue));
while (DefineRegion(extrema[Red],&red) != 0)
{
green.index=0;
while (DefineRegion(extrema[Green],&green) != 0)
{
blue.index=0;
while (DefineRegion(extrema[Blue],&blue) != 0)
{
/*
Allocate a new class.
*/
if (head != (Cluster *) NULL)
{
cluster->next=(Cluster *) AcquireMagickMemory(
sizeof(*cluster->next));
cluster=cluster->next;
}
else
{
cluster=(Cluster *) AcquireMagickMemory(sizeof(*cluster));
head=cluster;
}
if (cluster == (Cluster *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",
image->filename);
return(MagickFalse);
}
/*
Initialize a new class.
*/
cluster->count=0;
cluster->red=red;
cluster->green=green;
cluster->blue=blue;
cluster->next=(Cluster *) NULL;
}
}
}
if (head == (Cluster *) NULL)
{
/*
No classes were identified-- create one.
*/
cluster=(Cluster *) AcquireMagickMemory(sizeof(*cluster));
if (cluster == (Cluster *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(MagickFalse);
}
/*
Initialize a new class.
*/
cluster->count=0;
cluster->red=red;
cluster->green=green;
cluster->blue=blue;
cluster->next=(Cluster *) NULL;
head=cluster;
}
/*
Count the pixels for each cluster.
*/
count=0;
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next)
if (((ssize_t) ScaleQuantumToChar(GetPixelRed(image,p)) >=
(cluster->red.left-SafeMargin)) &&
((ssize_t) ScaleQuantumToChar(GetPixelRed(image,p)) <=
(cluster->red.right+SafeMargin)) &&
((ssize_t) ScaleQuantumToChar(GetPixelGreen(image,p)) >=
(cluster->green.left-SafeMargin)) &&
((ssize_t) ScaleQuantumToChar(GetPixelGreen(image,p)) <=
(cluster->green.right+SafeMargin)) &&
((ssize_t) ScaleQuantumToChar(GetPixelBlue(image,p)) >=
(cluster->blue.left-SafeMargin)) &&
((ssize_t) ScaleQuantumToChar(GetPixelBlue(image,p)) <=
(cluster->blue.right+SafeMargin)))
{
/*
Count this pixel.
*/
count++;
cluster->red.center+=(double) ScaleQuantumToChar(
GetPixelRed(image,p));
cluster->green.center+=(double) ScaleQuantumToChar(
GetPixelGreen(image,p));
cluster->blue.center+=(double) ScaleQuantumToChar(
GetPixelBlue(image,p));
cluster->count++;
break;
}
p+=GetPixelChannels(image);
}
proceed=SetImageProgress(image,SegmentImageTag,(MagickOffsetType) y,
2*image->rows);
if (proceed == MagickFalse)
break;
}
/*
Remove clusters that do not meet minimum cluster threshold.
*/
count=0;
last_cluster=head;
next_cluster=head;
for (cluster=head; cluster != (Cluster *) NULL; cluster=next_cluster)
{
next_cluster=cluster->next;
if ((cluster->count > 0) &&
(cluster->count >= (count*cluster_threshold/100.0)))
{
/*
Initialize cluster.
*/
cluster->id=count;
cluster->red.center/=cluster->count;
cluster->green.center/=cluster->count;
cluster->blue.center/=cluster->count;
count++;
last_cluster=cluster;
continue;
}
/*
Delete cluster.
*/
if (cluster == head)
head=next_cluster;
else
last_cluster->next=next_cluster;
cluster=(Cluster *) RelinquishMagickMemory(cluster);
}
object=head;
background=head;
if (count > 1)
{
object=head->next;
for (cluster=object; cluster->next != (Cluster *) NULL; )
{
if (cluster->count < object->count)
object=cluster;
cluster=cluster->next;
}
background=head->next;
for (cluster=background; cluster->next != (Cluster *) NULL; )
{
if (cluster->count > background->count)
background=cluster;
cluster=cluster->next;
}
}
if (background != (Cluster *) NULL)
{
threshold=(background->red.center+object->red.center)/2.0;
pixel->red=(double) ScaleCharToQuantum((unsigned char)
(threshold+0.5));
threshold=(background->green.center+object->green.center)/2.0;
pixel->green=(double) ScaleCharToQuantum((unsigned char)
(threshold+0.5));
threshold=(background->blue.center+object->blue.center)/2.0;
pixel->blue=(double) ScaleCharToQuantum((unsigned char)
(threshold+0.5));
}
/*
Relinquish resources.
*/
for (cluster=head; cluster != (Cluster *) NULL; cluster=next_cluster)
{
next_cluster=cluster->next;
cluster=(Cluster *) RelinquishMagickMemory(cluster);
}
for (i=0; i < MaxDimension; i++)
{
extrema[i]=(short *) RelinquishMagickMemory(extrema[i]);
histogram[i]=(ssize_t *) RelinquishMagickMemory(histogram[i]);
}
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ I n i t i a l i z e H i s t o g r a m %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% InitializeHistogram() computes the histogram for an image.
%
% The format of the InitializeHistogram method is:
%
% InitializeHistogram(const Image *image,ssize_t **histogram)
%
% A description of each parameter follows.
%
% o image: Specifies a pointer to an Image structure; returned from
% ReadImage.
%
% o histogram: Specifies an array of integers representing the number
% of pixels for each intensity of a particular color component.
%
*/
static void InitializeHistogram(const Image *image,ssize_t **histogram,
ExceptionInfo *exception)
{
register const Quantum
*p;
register ssize_t
i,
x;
ssize_t
y;
/*
Initialize histogram.
*/
for (i=0; i <= 255; i++)
{
histogram[Red][i]=0;
histogram[Green][i]=0;
histogram[Blue][i]=0;
}
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
histogram[Red][(ssize_t) ScaleQuantumToChar(GetPixelRed(image,p))]++;
histogram[Green][(ssize_t) ScaleQuantumToChar(GetPixelGreen(image,p))]++;
histogram[Blue][(ssize_t) ScaleQuantumToChar(GetPixelBlue(image,p))]++;
p+=GetPixelChannels(image);
}
}
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ I n i t i a l i z e I n t e r v a l T r e e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% InitializeIntervalTree() initializes an interval tree from the lists of
% zero crossings.
%
% The format of the InitializeIntervalTree method is:
%
% InitializeIntervalTree(IntervalTree **list,ssize_t *number_nodes,
% IntervalTree *node)
%
% A description of each parameter follows.
%
% o zero_crossing: Specifies an array of structures of type ZeroCrossing.
%
% o number_crossings: This size_t specifies the number of elements
% in the zero_crossing array.
%
*/
static void InitializeList(IntervalTree **list,ssize_t *number_nodes,
IntervalTree *node)
{
if (node == (IntervalTree *) NULL)
return;
if (node->child == (IntervalTree *) NULL)
list[(*number_nodes)++]=node;
InitializeList(list,number_nodes,node->sibling);
InitializeList(list,number_nodes,node->child);
}
static void MeanStability(IntervalTree *node)
{
register IntervalTree
*child;
if (node == (IntervalTree *) NULL)
return;
node->mean_stability=0.0;
child=node->child;
if (child != (IntervalTree *) NULL)
{
register ssize_t
count;
register double
sum;
sum=0.0;
count=0;
for ( ; child != (IntervalTree *) NULL; child=child->sibling)
{
sum+=child->stability;
count++;
}
node->mean_stability=sum/(double) count;
}
MeanStability(node->sibling);
MeanStability(node->child);
}
static void Stability(IntervalTree *node)
{
if (node == (IntervalTree *) NULL)
return;
if (node->child == (IntervalTree *) NULL)
node->stability=0.0;
else
node->stability=node->tau-(node->child)->tau;
Stability(node->sibling);
Stability(node->child);
}
static IntervalTree *InitializeIntervalTree(const ZeroCrossing *zero_crossing,
const size_t number_crossings)
{
IntervalTree
*head,
**list,
*node,
*root;
register ssize_t
i;
ssize_t
j,
k,
left,
number_nodes;
/*
Allocate interval tree.
*/
list=(IntervalTree **) AcquireQuantumMemory((size_t) TreeLength,
sizeof(*list));
if (list == (IntervalTree **) NULL)
return((IntervalTree *) NULL);
/*
The root is the entire histogram.
*/
root=(IntervalTree *) AcquireCriticalMemory(sizeof(*root));
root->child=(IntervalTree *) NULL;
root->sibling=(IntervalTree *) NULL;
root->tau=0.0;
root->left=0;
root->right=255;
root->mean_stability=0.0;
root->stability=0.0;
(void) memset(list,0,TreeLength*sizeof(*list));
for (i=(-1); i < (ssize_t) number_crossings; i++)
{
/*
Initialize list with all nodes with no children.
*/
number_nodes=0;
InitializeList(list,&number_nodes,root);
/*
Split list.
*/
for (j=0; j < number_nodes; j++)
{
head=list[j];
left=head->left;
node=head;
for (k=head->left+1; k < head->right; k++)
{
if (zero_crossing[i+1].crossings[k] != 0)
{
if (node == head)
{
node->child=(IntervalTree *) AcquireMagickMemory(
sizeof(*node->child));
node=node->child;
}
else
{
node->sibling=(IntervalTree *) AcquireMagickMemory(
sizeof(*node->sibling));
node=node->sibling;
}
if (node == (IntervalTree *) NULL)
{
list=(IntervalTree **) RelinquishMagickMemory(list);
FreeNodes(root);
return((IntervalTree *) NULL);
}
node->tau=zero_crossing[i+1].tau;
node->child=(IntervalTree *) NULL;
node->sibling=(IntervalTree *) NULL;
node->left=left;
node->right=k;
left=k;
}
}
if (left != head->left)
{
node->sibling=(IntervalTree *) AcquireMagickMemory(
sizeof(*node->sibling));
node=node->sibling;
if (node == (IntervalTree *) NULL)
{
list=(IntervalTree **) RelinquishMagickMemory(list);
FreeNodes(root);
return((IntervalTree *) NULL);
}
node->tau=zero_crossing[i+1].tau;
node->child=(IntervalTree *) NULL;
node->sibling=(IntervalTree *) NULL;
node->left=left;
node->right=head->right;
}
}
}
/*
Determine the stability: difference between a nodes tau and its child.
*/
Stability(root->child);
MeanStability(root->child);
list=(IntervalTree **) RelinquishMagickMemory(list);
return(root);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ O p t i m a l T a u %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% OptimalTau() finds the optimal tau for each band of the histogram.
%
% The format of the OptimalTau method is:
%
% double OptimalTau(const ssize_t *histogram,const double max_tau,
% const double min_tau,const double delta_tau,
% const double smooth_threshold,short *extrema)
%
% A description of each parameter follows.
%
% o histogram: Specifies an array of integers representing the number
% of pixels for each intensity of a particular color component.
%
% o extrema: Specifies a pointer to an array of integers. They
% represent the peaks and valleys of the histogram for each color
% component.
%
*/
static void ActiveNodes(IntervalTree **list,ssize_t *number_nodes,
IntervalTree *node)
{
if (node == (IntervalTree *) NULL)
return;
if (node->stability >= node->mean_stability)
{
list[(*number_nodes)++]=node;
ActiveNodes(list,number_nodes,node->sibling);
}
else
{
ActiveNodes(list,number_nodes,node->sibling);
ActiveNodes(list,number_nodes,node->child);
}
}
static void FreeNodes(IntervalTree *node)
{
if (node == (IntervalTree *) NULL)
return;
FreeNodes(node->sibling);
FreeNodes(node->child);
node=(IntervalTree *) RelinquishMagickMemory(node);
}
static double OptimalTau(const ssize_t *histogram,const double max_tau,
const double min_tau,const double delta_tau,const double smooth_threshold,
short *extrema)
{
IntervalTree
**list,
*node,
*root;
MagickBooleanType
peak;
double
average_tau,
*derivative,
*second_derivative,
tau,
value;
register ssize_t
i,
x;
size_t
count,
number_crossings;
ssize_t
index,
j,
k,
number_nodes;
ZeroCrossing
*zero_crossing;
/*
Allocate interval tree.
*/
list=(IntervalTree **) AcquireQuantumMemory((size_t) TreeLength,
sizeof(*list));
if (list == (IntervalTree **) NULL)
return(0.0);
/*
Allocate zero crossing list.
*/
count=(size_t) ((max_tau-min_tau)/delta_tau)+2;
zero_crossing=(ZeroCrossing *) AcquireQuantumMemory((size_t) count,
sizeof(*zero_crossing));
if (zero_crossing == (ZeroCrossing *) NULL)
{
list=(IntervalTree **) RelinquishMagickMemory(list);
return(0.0);
}
for (i=0; i < (ssize_t) count; i++)
zero_crossing[i].tau=(-1.0);
/*
Initialize zero crossing list.
*/
derivative=(double *) AcquireCriticalMemory(256*sizeof(*derivative));
second_derivative=(double *) AcquireCriticalMemory(256*
sizeof(*second_derivative));
i=0;
for (tau=max_tau; tau >= min_tau; tau-=delta_tau)
{
zero_crossing[i].tau=tau;
ScaleSpace(histogram,tau,zero_crossing[i].histogram);
DerivativeHistogram(zero_crossing[i].histogram,derivative);
DerivativeHistogram(derivative,second_derivative);
ZeroCrossHistogram(second_derivative,smooth_threshold,
zero_crossing[i].crossings);
i++;
}
/*
Add an entry for the original histogram.
*/
zero_crossing[i].tau=0.0;
for (j=0; j <= 255; j++)
zero_crossing[i].histogram[j]=(double) histogram[j];
DerivativeHistogram(zero_crossing[i].histogram,derivative);
DerivativeHistogram(derivative,second_derivative);
ZeroCrossHistogram(second_derivative,smooth_threshold,
zero_crossing[i].crossings);
number_crossings=(size_t) i;
derivative=(double *) RelinquishMagickMemory(derivative);
second_derivative=(double *) RelinquishMagickMemory(second_derivative);
/*
Ensure the scale-space fingerprints form lines in scale-space, not loops.
*/
ConsolidateCrossings(zero_crossing,number_crossings);
/*
Force endpoints to be included in the interval.
*/
for (i=0; i <= (ssize_t) number_crossings; i++)
{
for (j=0; j < 255; j++)
if (zero_crossing[i].crossings[j] != 0)
break;
zero_crossing[i].crossings[0]=(-zero_crossing[i].crossings[j]);
for (j=255; j > 0; j--)
if (zero_crossing[i].crossings[j] != 0)
break;
zero_crossing[i].crossings[255]=(-zero_crossing[i].crossings[j]);
}
/*
Initialize interval tree.
*/
root=InitializeIntervalTree(zero_crossing,number_crossings);
if (root == (IntervalTree *) NULL)
{
zero_crossing=(ZeroCrossing *) RelinquishMagickMemory(zero_crossing);
list=(IntervalTree **) RelinquishMagickMemory(list);
return(0.0);
}
/*
Find active nodes: stability is greater (or equal) to the mean stability of
its children.
*/
number_nodes=0;
ActiveNodes(list,&number_nodes,root->child);
/*
Initialize extrema.
*/
for (i=0; i <= 255; i++)
extrema[i]=0;
for (i=0; i < number_nodes; i++)
{
/*
Find this tau in zero crossings list.
*/
k=0;
node=list[i];
for (j=0; j <= (ssize_t) number_crossings; j++)
if (zero_crossing[j].tau == node->tau)
k=j;
/*
Find the value of the peak.
*/
peak=zero_crossing[k].crossings[node->right] == -1 ? MagickTrue :
MagickFalse;
index=node->left;
value=zero_crossing[k].histogram[index];
for (x=node->left; x <= node->right; x++)
{
if (peak != MagickFalse)
{
if (zero_crossing[k].histogram[x] > value)
{
value=zero_crossing[k].histogram[x];
index=x;
}
}
else
if (zero_crossing[k].histogram[x] < value)
{
value=zero_crossing[k].histogram[x];
index=x;
}
}
for (x=node->left; x <= node->right; x++)
{
if (index == 0)
index=256;
if (peak != MagickFalse)
extrema[x]=(short) index;
else
extrema[x]=(short) (-index);
}
}
/*
Determine the average tau.
*/
average_tau=0.0;
for (i=0; i < number_nodes; i++)
average_tau+=list[i]->tau;
average_tau*=PerceptibleReciprocal((double) number_nodes);
/*
Relinquish resources.
*/
FreeNodes(root);
zero_crossing=(ZeroCrossing *) RelinquishMagickMemory(zero_crossing);
list=(IntervalTree **) RelinquishMagickMemory(list);
return(average_tau);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ S c a l e S p a c e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ScaleSpace() performs a scale-space filter on the 1D histogram.
%
% The format of the ScaleSpace method is:
%
% ScaleSpace(const ssize_t *histogram,const double tau,
% double *scale_histogram)
%
% A description of each parameter follows.
%
% o histogram: Specifies an array of doubles representing the number
% of pixels for each intensity of a particular color component.
%
*/
static void ScaleSpace(const ssize_t *histogram,const double tau,
double *scale_histogram)
{
double
alpha,
beta,
*gamma,
sum;
register ssize_t
u,
x;
gamma=(double *) AcquireQuantumMemory(256,sizeof(*gamma));
if (gamma == (double *) NULL)
ThrowFatalException(ResourceLimitFatalError,
"UnableToAllocateGammaMap");
alpha=PerceptibleReciprocal(tau*sqrt(2.0*MagickPI));
beta=(-1.0*PerceptibleReciprocal(2.0*tau*tau));
for (x=0; x <= 255; x++)
gamma[x]=0.0;
for (x=0; x <= 255; x++)
{
gamma[x]=exp((double) beta*x*x);
if (gamma[x] < MagickEpsilon)
break;
}
for (x=0; x <= 255; x++)
{
sum=0.0;
for (u=0; u <= 255; u++)
sum+=(double) histogram[u]*gamma[MagickAbsoluteValue(x-u)];
scale_histogram[x]=alpha*sum;
}
gamma=(double *) RelinquishMagickMemory(gamma);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e g m e n t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SegmentImage() segment an image by analyzing the histograms of the color
% components and identifying units that are homogeneous with the fuzzy
% C-means technique.
%
% The format of the SegmentImage method is:
%
% MagickBooleanType SegmentImage(Image *image,
% const ColorspaceType colorspace,const MagickBooleanType verbose,
% const double cluster_threshold,const double smooth_threshold,
% ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o image: the image.
%
% o colorspace: Indicate the colorspace.
%
% o verbose: Set to MagickTrue to print detailed information about the
% identified classes.
%
% o cluster_threshold: This represents the minimum number of pixels
% contained in a hexahedra before it can be considered valid (expressed
% as a percentage).
%
% o smooth_threshold: the smoothing threshold eliminates noise in the second
% derivative of the histogram. As the value is increased, you can expect a
% smoother second derivative.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType SegmentImage(Image *image,
const ColorspaceType colorspace,const MagickBooleanType verbose,
const double cluster_threshold,const double smooth_threshold,
ExceptionInfo *exception)
{
ColorspaceType
previous_colorspace;
MagickBooleanType
status;
register ssize_t
i;
short
*extrema[MaxDimension];
ssize_t
*histogram[MaxDimension];
/*
Allocate histogram and extrema.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
for (i=0; i < MaxDimension; i++)
{
histogram[i]=(ssize_t *) AcquireQuantumMemory(256,sizeof(**histogram));
extrema[i]=(short *) AcquireQuantumMemory(256,sizeof(**extrema));
if ((histogram[i] == (ssize_t *) NULL) || (extrema[i] == (short *) NULL))
{
for (i-- ; i >= 0; i--)
{
extrema[i]=(short *) RelinquishMagickMemory(extrema[i]);
histogram[i]=(ssize_t *) RelinquishMagickMemory(histogram[i]);
}
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename)
}
}
/*
Initialize histogram.
*/
previous_colorspace=image->colorspace;
(void) TransformImageColorspace(image,colorspace,exception);
InitializeHistogram(image,histogram,exception);
(void) OptimalTau(histogram[Red],Tau,0.2,DeltaTau,
smooth_threshold == 0.0 ? 1.0 : smooth_threshold,extrema[Red]);
(void) OptimalTau(histogram[Green],Tau,0.2,DeltaTau,
smooth_threshold == 0.0 ? 1.0 : smooth_threshold,extrema[Green]);
(void) OptimalTau(histogram[Blue],Tau,0.2,DeltaTau,
smooth_threshold == 0.0 ? 1.0 : smooth_threshold,extrema[Blue]);
/*
Classify using the fuzzy c-Means technique.
*/
status=Classify(image,extrema,cluster_threshold,WeightingExponent,verbose,
exception);
(void) TransformImageColorspace(image,previous_colorspace,exception);
/*
Relinquish resources.
*/
for (i=0; i < MaxDimension; i++)
{
extrema[i]=(short *) RelinquishMagickMemory(extrema[i]);
histogram[i]=(ssize_t *) RelinquishMagickMemory(histogram[i]);
}
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ Z e r o C r o s s H i s t o g r a m %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ZeroCrossHistogram() find the zero crossings in a histogram and marks
% directions as: 1 is negative to positive; 0 is zero crossing; and -1
% is positive to negative.
%
% The format of the ZeroCrossHistogram method is:
%
% ZeroCrossHistogram(double *second_derivative,
% const double smooth_threshold,short *crossings)
%
% A description of each parameter follows.
%
% o second_derivative: Specifies an array of doubles representing the
% second derivative of the histogram of a particular color component.
%
% o crossings: This array of integers is initialized with
% -1, 0, or 1 representing the slope of the first derivative of the
% of a particular color component.
%
*/
static void ZeroCrossHistogram(double *second_derivative,
const double smooth_threshold,short *crossings)
{
register ssize_t
i;
ssize_t
parity;
/*
Merge low numbers to zero to help prevent noise.
*/
for (i=0; i <= 255; i++)
if ((second_derivative[i] < smooth_threshold) &&
(second_derivative[i] >= -smooth_threshold))
second_derivative[i]=0.0;
/*
Mark zero crossings.
*/
parity=0;
for (i=0; i <= 255; i++)
{
crossings[i]=0;
if (second_derivative[i] < 0.0)
{
if (parity > 0)
crossings[i]=(-1);
parity=1;
}
else
if (second_derivative[i] > 0.0)
{
if (parity < 0)
crossings[i]=1;
parity=(-1);
}
}
}
|
trsm_c_sky_n_hi_row_conj.c | #include "alphasparse/kernel.h"
#include "alphasparse/util.h"
#include <memory.h>
alphasparse_status_t ONAME(const ALPHA_Number alpha, const ALPHA_SPMAT_SKY *A, const ALPHA_Number *x, const ALPHA_INT columns, const ALPHA_INT ldx, ALPHA_Number *y, const ALPHA_INT ldy)
{
ALPHA_INT m = A->rows;
ALPHA_Complex diag[m];
memset(diag, '\0', m * sizeof(ALPHA_Complex));
ALPHA_INT num_thread = alpha_get_thread_num();
#ifdef _OPENMP
#pragma omp parallel for num_threads(num_thread)
#endif
for (ALPHA_INT r = 1; r < A->rows + 1; r++)
{
const ALPHA_INT indx = A->pointers[r] - 1;
diag[r - 1].real = A->values[indx].real;
diag[r - 1].imag = -A->values[indx].imag;
}
#ifdef _OPENMP
#pragma omp parallel for num_threads(num_thread)
#endif
for(ALPHA_INT out_y_col = 0; out_y_col < columns; out_y_col++)
{
for (ALPHA_INT r = 0; r <A->rows; r++)
{
ALPHA_Complex temp = {.real = 0.f, .imag = 0.f};
ALPHA_INT start = A->pointers[r];
ALPHA_INT end = A->pointers[r + 1];
ALPHA_INT idx = 1;
ALPHA_INT eles_num = end - start;
for (ALPHA_INT ai = start; ai < end - 1; ++ai)
{
ALPHA_INT c = r - eles_num + idx;
ALPHA_Complex cv = A->values[ai];
alpha_conj(cv, cv);
alpha_madde(temp, cv, y[c * ldy + out_y_col]);
idx ++;
}
ALPHA_Complex t;
alpha_mul(t, alpha, x[r * ldx + out_y_col]);
alpha_sub(t, t, temp);
alpha_div(y[r * ldy + out_y_col], t, diag[r]);
}
}
return ALPHA_SPARSE_STATUS_SUCCESS;
}
|
kriging.h | #ifndef __KRIGING_H__69012DAB_4BA5_44E4_9DF9_749A5519E0AD
#define __KRIGING_H__69012DAB_4BA5_44E4_9DF9_749A5519E0AD
namespace hpgl
{
/**/
template<
typename values_t,
typename defineds_t,
typename coord_t,
typename means_t,
typename covariances_t,
typename neighbourhood_lookup_t,
typename weight_calculator_t,
typename result_t>
void kriging(
std::vector<values_t*> values,
std::vector<defineds_t*> defindes,
const std::vector<params_t> & params,
const reducer_t & reducer,
const undefined_handler
)
{
size_t size = input_property.size();
#pragma omp parallel
{
#pragma omp for
for (node_index_t node_idx = 0; node_idx < size; ++node_idx)
{
struct result_t
{
double value;
bool defined;
}
std::vector<result_t> result;
std::vector<indicator_probability_t> probs;
for (int idx = 0; idx < params.m_category_count; ++idx)
{
indicator_probability_t prob;
ki_result_t ki_result = kriging_interpolation(
*params[idx].input_values,
*params[idx].defineds,
node_idx, grid[node_idx], *covariances[idx],
*mps[idx], nblookups[idx], weight_calculator(sk_constraints, input_property), prob);
if (ki_result != KI_SUCCESS)
{
result_t res = {*mps[idx][node_idx], false};
result.push_back(res)
}
else
{
result_t res = {prob, true};
result.push_back_t(res);
}
}
output_poperty.set_at(node_idx, reducer(result));
#pragma omp critical
{
report.next_lap();
}
}
}
report.stop();
}
}
#endif //__KRIGING_H__69012DAB_4BA5_44E4_9DF9_749A5519E0AD |
munit.c | /* Copyright (c) 2013-2018 Evan Nemerson <evan@nemerson.com>
*
* 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.
*/
/*** Configuration ***/
/* This is just where the output from the test goes. It's really just
* meant to let you choose stdout or stderr, but if anyone really want
* to direct it to a file let me know, it would be fairly easy to
* support. */
#if !defined(MUNIT_OUTPUT_FILE)
# define MUNIT_OUTPUT_FILE stdout
#endif
/* This is a bit more useful; it tells µnit how to format the seconds in
* timed tests. If your tests run for longer you might want to reduce
* it, and if your computer is really fast and your tests are tiny you
* can increase it. */
#if !defined(MUNIT_TEST_TIME_FORMAT)
# define MUNIT_TEST_TIME_FORMAT "0.8f"
#endif
/* If you have long test names you might want to consider bumping
* this. The result information takes 43 characters. */
#if !defined(MUNIT_TEST_NAME_LEN)
# define MUNIT_TEST_NAME_LEN 37
#endif
/* If you don't like the timing information, you can disable it by
* defining MUNIT_DISABLE_TIMING. */
#if !defined(MUNIT_DISABLE_TIMING)
# define MUNIT_ENABLE_TIMING
#endif
/*** End configuration ***/
#if defined(_POSIX_C_SOURCE) && (_POSIX_C_SOURCE < 200809L)
# undef _POSIX_C_SOURCE
#endif
#if !defined(_POSIX_C_SOURCE)
# define _POSIX_C_SOURCE 200809L
#endif
/* Solaris freaks out if you try to use a POSIX or SUS standard without
* the "right" C standard. */
#if defined(_XOPEN_SOURCE)
# undef _XOPEN_SOURCE
#endif
#if defined(__STDC_VERSION__)
# if __STDC_VERSION__ >= 201112L
# define _XOPEN_SOURCE 700
# elif __STDC_VERSION__ >= 199901L
# define _XOPEN_SOURCE 600
# endif
#endif
/* Because, according to Microsoft, POSIX is deprecated. You've got
* to appreciate the chutzpah. */
#if defined(_MSC_VER) && !defined(_CRT_NONSTDC_NO_DEPRECATE)
# define _CRT_NONSTDC_NO_DEPRECATE
#endif
#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)
# include <stdbool.h>
#elif defined(_WIN32)
/* https://msdn.microsoft.com/en-us/library/tf4dy80a.aspx */
#endif
#include <limits.h>
#include <time.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <setjmp.h>
#if !defined(MUNIT_NO_NL_LANGINFO) && !defined(_WIN32)
#define MUNIT_NL_LANGINFO
#include <locale.h>
#include <langinfo.h>
#include <strings.h>
#endif
#if !defined(_WIN32)
# include <unistd.h>
# include <sys/types.h>
# include <sys/wait.h>
#else
# include <windows.h>
# include <io.h>
# include <fcntl.h>
# if !defined(STDERR_FILENO)
# define STDERR_FILENO _fileno(stderr)
# endif
#endif
#include "munit.h"
#define MUNIT_STRINGIFY(x) #x
#define MUNIT_XSTRINGIFY(x) MUNIT_STRINGIFY(x)
#if defined(__GNUC__) || defined(__INTEL_COMPILER) || defined(__SUNPRO_CC) || defined(__IBMCPP__)
# define MUNIT_THREAD_LOCAL __thread
#elif (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201102L)) || defined(_Thread_local)
# define MUNIT_THREAD_LOCAL _Thread_local
#elif defined(_WIN32)
# define MUNIT_THREAD_LOCAL __declspec(thread)
#endif
/* MSVC 12.0 will emit a warning at /W4 for code like 'do { ... }
* while (0)', or 'do { ... } while (1)'. I'm pretty sure nobody
* at Microsoft compiles with /W4. */
#if defined(_MSC_VER) && (_MSC_VER <= 1800)
#pragma warning(disable: 4127)
#endif
#if defined(_WIN32) || defined(__EMSCRIPTEN__)
# define MUNIT_NO_FORK
#endif
#if defined(__EMSCRIPTEN__)
# define MUNIT_NO_BUFFER
#endif
/*** Logging ***/
static MunitLogLevel munit_log_level_visible = MUNIT_LOG_INFO;
static MunitLogLevel munit_log_level_fatal = MUNIT_LOG_ERROR;
#if defined(MUNIT_THREAD_LOCAL)
static MUNIT_THREAD_LOCAL munit_bool munit_error_jmp_buf_valid = 0;
static MUNIT_THREAD_LOCAL jmp_buf munit_error_jmp_buf;
#endif
/* At certain warning levels, mingw will trigger warnings about
* suggesting the format attribute, which we've explicity *not* set
* because it will then choke on our attempts to use the MS-specific
* I64 modifier for size_t (which we have to use since MSVC doesn't
* support the C99 z modifier). */
#if defined(__MINGW32__) || defined(__MINGW64__)
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wsuggest-attribute=format"
#endif
MUNIT_PRINTF(5,0)
static void
munit_logf_exv(MunitLogLevel level, FILE* fp, const char* filename, int line, const char* format, va_list ap) {
if (level < munit_log_level_visible)
return;
switch (level) {
case MUNIT_LOG_DEBUG:
fputs("Debug", fp);
break;
case MUNIT_LOG_INFO:
fputs("Info", fp);
break;
case MUNIT_LOG_WARNING:
fputs("Warning", fp);
break;
case MUNIT_LOG_ERROR:
fputs("Error", fp);
break;
default:
munit_logf_ex(MUNIT_LOG_ERROR, filename, line, "Invalid log level (%d)", level);
return;
}
fputs(": ", fp);
if (filename != NULL)
fprintf(fp, "%s:%d: ", filename, line);
vfprintf(fp, format, ap);
fputc('\n', fp);
}
MUNIT_PRINTF(3,4)
static void
munit_logf_internal(MunitLogLevel level, FILE* fp, const char* format, ...) {
va_list ap;
va_start(ap, format);
munit_logf_exv(level, fp, NULL, 0, format, ap);
va_end(ap);
}
static void
munit_log_internal(MunitLogLevel level, FILE* fp, const char* message) {
munit_logf_internal(level, fp, "%s", message);
}
void
munit_logf_ex(MunitLogLevel level, const char* filename, int line, const char* format, ...) {
va_list ap;
va_start(ap, format);
munit_logf_exv(level, stderr, filename, line, format, ap);
va_end(ap);
if (level >= munit_log_level_fatal) {
#if defined(MUNIT_THREAD_LOCAL)
if (munit_error_jmp_buf_valid)
longjmp(munit_error_jmp_buf, 1);
#endif
abort();
}
}
void
munit_errorf_ex(const char* filename, int line, const char* format, ...) {
va_list ap;
va_start(ap, format);
munit_logf_exv(MUNIT_LOG_ERROR, stderr, filename, line, format, ap);
va_end(ap);
#if defined(MUNIT_THREAD_LOCAL)
if (munit_error_jmp_buf_valid)
longjmp(munit_error_jmp_buf, 1);
#endif
abort();
}
#if defined(__MINGW32__) || defined(__MINGW64__)
#pragma GCC diagnostic pop
#endif
#if !defined(MUNIT_STRERROR_LEN)
# define MUNIT_STRERROR_LEN 80
#endif
static void
munit_log_errno(MunitLogLevel level, FILE* fp, const char* msg) {
#if defined(MUNIT_NO_STRERROR_R) || (defined(__MINGW32__) && !defined(MINGW_HAS_SECURE_API))
munit_logf_internal(level, fp, "%s: %s (%d)", msg, strerror(errno), errno);
#else
char munit_error_str[MUNIT_STRERROR_LEN];
munit_error_str[0] = '\0';
#if !defined(_WIN32)
strerror_r(errno, munit_error_str, MUNIT_STRERROR_LEN);
#else
strerror_s(munit_error_str, MUNIT_STRERROR_LEN, errno);
#endif
munit_logf_internal(level, fp, "%s: %s (%d)", msg, munit_error_str, errno);
#endif
}
/*** Memory allocation ***/
void*
munit_malloc_ex(const char* filename, int line, size_t size) {
void* ptr;
if (size == 0)
return NULL;
ptr = calloc(1, size);
if (MUNIT_UNLIKELY(ptr == NULL)) {
munit_logf_ex(MUNIT_LOG_ERROR, filename, line, "Failed to allocate %" MUNIT_SIZE_MODIFIER "u bytes.", size);
}
return ptr;
}
/*** Timer code ***/
#if defined(MUNIT_ENABLE_TIMING)
#define psnip_uint64_t munit_uint64_t
#define psnip_uint32_t munit_uint32_t
/* Code copied from portable-snippets
* <https://github.com/nemequ/portable-snippets/>. If you need to
* change something, please do it there so we can keep the code in
* sync. */
/* Clocks (v1)
* Portable Snippets - https://gitub.com/nemequ/portable-snippets
* Created by Evan Nemerson <evan@nemerson.com>
*
* To the extent possible under law, the authors have waived all
* copyright and related or neighboring rights to this code. For
* details, see the Creative Commons Zero 1.0 Universal license at
* https://creativecommons.org/publicdomain/zero/1.0/
*/
#if !defined(PSNIP_CLOCK_H)
#define PSNIP_CLOCK_H
#if !defined(psnip_uint64_t)
# include "../exact-int/exact-int.h"
#endif
#if !defined(PSNIP_CLOCK_STATIC_INLINE)
# if defined(__GNUC__)
# define PSNIP_CLOCK__COMPILER_ATTRIBUTES __attribute__((__unused__))
# else
# define PSNIP_CLOCK__COMPILER_ATTRIBUTES
# endif
# define PSNIP_CLOCK__FUNCTION PSNIP_CLOCK__COMPILER_ATTRIBUTES static
#endif
enum PsnipClockType {
/* This clock provides the current time, in units since 1970-01-01
* 00:00:00 UTC not including leap seconds. In other words, UNIX
* time. Keep in mind that this clock doesn't account for leap
* seconds, and can go backwards (think NTP adjustments). */
PSNIP_CLOCK_TYPE_WALL = 1,
/* The CPU time is a clock which increases only when the current
* process is active (i.e., it doesn't increment while blocking on
* I/O). */
PSNIP_CLOCK_TYPE_CPU = 2,
/* Monotonic time is always running (unlike CPU time), but it only
ever moves forward unless you reboot the system. Things like NTP
adjustments have no effect on this clock. */
PSNIP_CLOCK_TYPE_MONOTONIC = 3
};
struct PsnipClockTimespec {
psnip_uint64_t seconds;
psnip_uint64_t nanoseconds;
};
/* Methods we support: */
#define PSNIP_CLOCK_METHOD_CLOCK_GETTIME 1
#define PSNIP_CLOCK_METHOD_TIME 2
#define PSNIP_CLOCK_METHOD_GETTIMEOFDAY 3
#define PSNIP_CLOCK_METHOD_QUERYPERFORMANCECOUNTER 4
#define PSNIP_CLOCK_METHOD_MACH_ABSOLUTE_TIME 5
#define PSNIP_CLOCK_METHOD_CLOCK 6
#define PSNIP_CLOCK_METHOD_GETPROCESSTIMES 7
#define PSNIP_CLOCK_METHOD_GETRUSAGE 8
#define PSNIP_CLOCK_METHOD_GETSYSTEMTIMEPRECISEASFILETIME 9
#define PSNIP_CLOCK_METHOD_GETTICKCOUNT64 10
#include <assert.h>
#if defined(HEDLEY_UNREACHABLE)
# define PSNIP_CLOCK_UNREACHABLE() HEDLEY_UNREACHABLE()
#else
# define PSNIP_CLOCK_UNREACHABLE() assert(0)
#endif
/* Choose an implementation */
/* #undef PSNIP_CLOCK_WALL_METHOD */
/* #undef PSNIP_CLOCK_CPU_METHOD */
/* #undef PSNIP_CLOCK_MONOTONIC_METHOD */
/* We want to be able to detect the libc implementation, so we include
<limits.h> (<features.h> isn't available everywhere). */
#if defined(__unix__) || defined(__unix) || defined(__linux__)
# include <limits.h>
# include <unistd.h>
#endif
#if defined(_POSIX_TIMERS) && (_POSIX_TIMERS > 0)
/* These are known to work without librt. If you know of others
* please let us know so we can add them. */
# if \
(defined(__GLIBC__) && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 17))) || \
(defined(__FreeBSD__))
# define PSNIP_CLOCK_HAVE_CLOCK_GETTIME
# elif !defined(PSNIP_CLOCK_NO_LIBRT)
# define PSNIP_CLOCK_HAVE_CLOCK_GETTIME
# endif
#endif
#if defined(_WIN32)
# if !defined(PSNIP_CLOCK_CPU_METHOD)
# define PSNIP_CLOCK_CPU_METHOD PSNIP_CLOCK_METHOD_GETPROCESSTIMES
# endif
# if !defined(PSNIP_CLOCK_MONOTONIC_METHOD)
# define PSNIP_CLOCK_MONOTONIC_METHOD PSNIP_CLOCK_METHOD_QUERYPERFORMANCECOUNTER
# endif
#endif
#if defined(__MACH__) && !defined(__gnu_hurd__)
# if !defined(PSNIP_CLOCK_MONOTONIC_METHOD)
# define PSNIP_CLOCK_MONOTONIC_METHOD PSNIP_CLOCK_METHOD_MACH_ABSOLUTE_TIME
# endif
#endif
#if defined(PSNIP_CLOCK_HAVE_CLOCK_GETTIME)
# include <time.h>
# if !defined(PSNIP_CLOCK_WALL_METHOD)
# if defined(CLOCK_REALTIME_PRECISE)
# define PSNIP_CLOCK_WALL_METHOD PSNIP_CLOCK_METHOD_CLOCK_GETTIME
# define PSNIP_CLOCK_CLOCK_GETTIME_WALL CLOCK_REALTIME_PRECISE
# elif !defined(__sun)
# define PSNIP_CLOCK_WALL_METHOD PSNIP_CLOCK_METHOD_CLOCK_GETTIME
# define PSNIP_CLOCK_CLOCK_GETTIME_WALL CLOCK_REALTIME
# endif
# endif
# if !defined(PSNIP_CLOCK_CPU_METHOD)
# if defined(_POSIX_CPUTIME) || defined(CLOCK_PROCESS_CPUTIME_ID)
# define PSNIP_CLOCK_CPU_METHOD PSNIP_CLOCK_METHOD_CLOCK_GETTIME
# define PSNIP_CLOCK_CLOCK_GETTIME_CPU CLOCK_PROCESS_CPUTIME_ID
# elif defined(CLOCK_VIRTUAL)
# define PSNIP_CLOCK_CPU_METHOD PSNIP_CLOCK_METHOD_CLOCK_GETTIME
# define PSNIP_CLOCK_CLOCK_GETTIME_CPU CLOCK_VIRTUAL
# endif
# endif
# if !defined(PSNIP_CLOCK_MONOTONIC_METHOD)
# if defined(CLOCK_MONOTONIC_RAW)
# define PSNIP_CLOCK_MONOTONIC_METHOD PSNIP_CLOCK_METHOD_CLOCK_GETTIME
# define PSNIP_CLOCK_CLOCK_GETTIME_MONOTONIC CLOCK_MONOTONIC
# elif defined(CLOCK_MONOTONIC_PRECISE)
# define PSNIP_CLOCK_MONOTONIC_METHOD PSNIP_CLOCK_METHOD_CLOCK_GETTIME
# define PSNIP_CLOCK_CLOCK_GETTIME_MONOTONIC CLOCK_MONOTONIC_PRECISE
# elif defined(_POSIX_MONOTONIC_CLOCK) || defined(CLOCK_MONOTONIC)
# define PSNIP_CLOCK_MONOTONIC_METHOD PSNIP_CLOCK_METHOD_CLOCK_GETTIME
# define PSNIP_CLOCK_CLOCK_GETTIME_MONOTONIC CLOCK_MONOTONIC
# endif
# endif
#endif
#if defined(_POSIX_VERSION) && (_POSIX_VERSION >= 200112L)
# if !defined(PSNIP_CLOCK_WALL_METHOD)
# define PSNIP_CLOCK_WALL_METHOD PSNIP_CLOCK_METHOD_GETTIMEOFDAY
# endif
#endif
#if !defined(PSNIP_CLOCK_WALL_METHOD)
# define PSNIP_CLOCK_WALL_METHOD PSNIP_CLOCK_METHOD_TIME
#endif
#if !defined(PSNIP_CLOCK_CPU_METHOD)
# define PSNIP_CLOCK_CPU_METHOD PSNIP_CLOCK_METHOD_CLOCK
#endif
/* Primarily here for testing. */
#if !defined(PSNIP_CLOCK_MONOTONIC_METHOD) && defined(PSNIP_CLOCK_REQUIRE_MONOTONIC)
# error No monotonic clock found.
#endif
/* Implementations */
#if \
(defined(PSNIP_CLOCK_CPU_METHOD) && (PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME)) || \
(defined(PSNIP_CLOCK_WALL_METHOD) && (PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME)) || \
(defined(PSNIP_CLOCK_MONOTONIC_METHOD) && (PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME)) || \
(defined(PSNIP_CLOCK_CPU_METHOD) && (PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_CLOCK)) || \
(defined(PSNIP_CLOCK_WALL_METHOD) && (PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_CLOCK)) || \
(defined(PSNIP_CLOCK_MONOTONIC_METHOD) && (PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_CLOCK)) || \
(defined(PSNIP_CLOCK_CPU_METHOD) && (PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_TIME)) || \
(defined(PSNIP_CLOCK_WALL_METHOD) && (PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_TIME)) || \
(defined(PSNIP_CLOCK_MONOTONIC_METHOD) && (PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_TIME))
# include <time.h>
#endif
#if \
(defined(PSNIP_CLOCK_CPU_METHOD) && (PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_GETTIMEOFDAY)) || \
(defined(PSNIP_CLOCK_WALL_METHOD) && (PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_GETTIMEOFDAY)) || \
(defined(PSNIP_CLOCK_MONOTONIC_METHOD) && (PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_GETTIMEOFDAY))
# include <sys/time.h>
#endif
#if \
(defined(PSNIP_CLOCK_CPU_METHOD) && (PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_GETPROCESSTIMES)) || \
(defined(PSNIP_CLOCK_WALL_METHOD) && (PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_GETPROCESSTIMES)) || \
(defined(PSNIP_CLOCK_MONOTONIC_METHOD) && (PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_GETPROCESSTIMES)) || \
(defined(PSNIP_CLOCK_CPU_METHOD) && (PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_GETTICKCOUNT64)) || \
(defined(PSNIP_CLOCK_WALL_METHOD) && (PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_GETTICKCOUNT64)) || \
(defined(PSNIP_CLOCK_MONOTONIC_METHOD) && (PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_GETTICKCOUNT64))
# include <windows.h>
#endif
#if \
(defined(PSNIP_CLOCK_CPU_METHOD) && (PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_GETRUSAGE)) || \
(defined(PSNIP_CLOCK_WALL_METHOD) && (PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_GETRUSAGE)) || \
(defined(PSNIP_CLOCK_MONOTONIC_METHOD) && (PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_GETRUSAGE))
# include <sys/time.h>
# include <sys/resource.h>
#endif
#if \
(defined(PSNIP_CLOCK_CPU_METHOD) && (PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_MACH_ABSOLUTE_TIME)) || \
(defined(PSNIP_CLOCK_WALL_METHOD) && (PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_MACH_ABSOLUTE_TIME)) || \
(defined(PSNIP_CLOCK_MONOTONIC_METHOD) && (PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_MACH_ABSOLUTE_TIME))
# include <CoreServices/CoreServices.h>
# include <mach/mach.h>
# include <mach/mach_time.h>
#endif
/*** Implementations ***/
#define PSNIP_CLOCK_NSEC_PER_SEC ((psnip_uint32_t) (1000000000ULL))
#if \
(defined(PSNIP_CLOCK_CPU_METHOD) && (PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME)) || \
(defined(PSNIP_CLOCK_WALL_METHOD) && (PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME)) || \
(defined(PSNIP_CLOCK_MONOTONIC_METHOD) && (PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME))
PSNIP_CLOCK__FUNCTION psnip_uint32_t
psnip_clock__clock_getres (clockid_t clk_id) {
struct timespec res;
int r;
r = clock_getres(clk_id, &res);
if (r != 0)
return 0;
return (psnip_uint32_t) (PSNIP_CLOCK_NSEC_PER_SEC / res.tv_nsec);
}
PSNIP_CLOCK__FUNCTION int
psnip_clock__clock_gettime (clockid_t clk_id, struct PsnipClockTimespec* res) {
struct timespec ts;
if (clock_gettime(clk_id, &ts) != 0)
return -10;
res->seconds = (psnip_uint64_t) (ts.tv_sec);
res->nanoseconds = (psnip_uint64_t) (ts.tv_nsec);
return 0;
}
#endif
PSNIP_CLOCK__FUNCTION psnip_uint32_t
psnip_clock_wall_get_precision (void) {
#if !defined(PSNIP_CLOCK_WALL_METHOD)
return 0;
#elif defined(PSNIP_CLOCK_WALL_METHOD) && PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME
return psnip_clock__clock_getres(PSNIP_CLOCK_CLOCK_GETTIME_WALL);
#elif defined(PSNIP_CLOCK_WALL_METHOD) && PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_GETTIMEOFDAY
return 1000000;
#elif defined(PSNIP_CLOCK_WALL_METHOD) && PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_TIME
return 1;
#else
return 0;
#endif
}
PSNIP_CLOCK__FUNCTION int
psnip_clock_wall_get_time (struct PsnipClockTimespec* res) {
(void) res;
#if !defined(PSNIP_CLOCK_WALL_METHOD)
return -2;
#elif defined(PSNIP_CLOCK_WALL_METHOD) && PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME
return psnip_clock__clock_gettime(PSNIP_CLOCK_CLOCK_GETTIME_WALL, res);
#elif defined(PSNIP_CLOCK_WALL_METHOD) && PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_TIME
res->seconds = time(NULL);
res->nanoseconds = 0;
#elif defined(PSNIP_CLOCK_WALL_METHOD) && PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_GETTIMEOFDAY
struct timeval tv;
if (gettimeofday(&tv, NULL) != 0)
return -6;
res->seconds = tv.tv_sec;
res->nanoseconds = tv.tv_usec * 1000;
#else
return -2;
#endif
return 0;
}
PSNIP_CLOCK__FUNCTION psnip_uint32_t
psnip_clock_cpu_get_precision (void) {
#if !defined(PSNIP_CLOCK_CPU_METHOD)
return 0;
#elif defined(PSNIP_CLOCK_CPU_METHOD) && PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME
return psnip_clock__clock_getres(PSNIP_CLOCK_CLOCK_GETTIME_CPU);
#elif defined(PSNIP_CLOCK_CPU_METHOD) && PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_CLOCK
return CLOCKS_PER_SEC;
#elif defined(PSNIP_CLOCK_CPU_METHOD) && PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_GETPROCESSTIMES
return PSNIP_CLOCK_NSEC_PER_SEC / 100;
#else
return 0;
#endif
}
PSNIP_CLOCK__FUNCTION int
psnip_clock_cpu_get_time (struct PsnipClockTimespec* res) {
#if !defined(PSNIP_CLOCK_CPU_METHOD)
(void) res;
return -2;
#elif defined(PSNIP_CLOCK_CPU_METHOD) && PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME
return psnip_clock__clock_gettime(PSNIP_CLOCK_CLOCK_GETTIME_CPU, res);
#elif defined(PSNIP_CLOCK_CPU_METHOD) && PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_CLOCK
clock_t t = clock();
if (t == ((clock_t) -1))
return -5;
res->seconds = t / CLOCKS_PER_SEC;
res->nanoseconds = (t % CLOCKS_PER_SEC) * (PSNIP_CLOCK_NSEC_PER_SEC / CLOCKS_PER_SEC);
#elif defined(PSNIP_CLOCK_CPU_METHOD) && PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_GETPROCESSTIMES
FILETIME CreationTime, ExitTime, KernelTime, UserTime;
LARGE_INTEGER date, adjust;
if (!GetProcessTimes(GetCurrentProcess(), &CreationTime, &ExitTime, &KernelTime, &UserTime))
return -7;
/* http://www.frenk.com/2009/12/convert-filetime-to-unix-timestamp/ */
date.HighPart = UserTime.dwHighDateTime;
date.LowPart = UserTime.dwLowDateTime;
adjust.QuadPart = 11644473600000 * 10000;
date.QuadPart -= adjust.QuadPart;
res->seconds = date.QuadPart / 10000000;
res->nanoseconds = (date.QuadPart % 10000000) * (PSNIP_CLOCK_NSEC_PER_SEC / 100);
#elif PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_GETRUSAGE
struct rusage usage;
if (getrusage(RUSAGE_SELF, &usage) != 0)
return -8;
res->seconds = usage.ru_utime.tv_sec;
res->nanoseconds = tv.tv_usec * 1000;
#else
(void) res;
return -2;
#endif
return 0;
}
PSNIP_CLOCK__FUNCTION psnip_uint32_t
psnip_clock_monotonic_get_precision (void) {
#if !defined(PSNIP_CLOCK_MONOTONIC_METHOD)
return 0;
#elif defined(PSNIP_CLOCK_MONOTONIC_METHOD) && PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME
return psnip_clock__clock_getres(PSNIP_CLOCK_CLOCK_GETTIME_MONOTONIC);
#elif defined(PSNIP_CLOCK_MONOTONIC_METHOD) && PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_MACH_ABSOLUTE_TIME
static mach_timebase_info_data_t tbi = { 0, };
if (tbi.denom == 0)
mach_timebase_info(&tbi);
return (psnip_uint32_t) (tbi.numer / tbi.denom);
#elif defined(PSNIP_CLOCK_MONOTONIC_METHOD) && PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_GETTICKCOUNT64
return 1000;
#elif defined(PSNIP_CLOCK_MONOTONIC_METHOD) && PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_QUERYPERFORMANCECOUNTER
LARGE_INTEGER Frequency;
QueryPerformanceFrequency(&Frequency);
return (psnip_uint32_t) ((Frequency.QuadPart > PSNIP_CLOCK_NSEC_PER_SEC) ? PSNIP_CLOCK_NSEC_PER_SEC : Frequency.QuadPart);
#else
return 0;
#endif
}
PSNIP_CLOCK__FUNCTION int
psnip_clock_monotonic_get_time (struct PsnipClockTimespec* res) {
#if !defined(PSNIP_CLOCK_MONOTONIC_METHOD)
(void) res;
return -2;
#elif defined(PSNIP_CLOCK_MONOTONIC_METHOD) && PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME
return psnip_clock__clock_gettime(PSNIP_CLOCK_CLOCK_GETTIME_MONOTONIC, res);
#elif defined(PSNIP_CLOCK_MONOTONIC_METHOD) && PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_MACH_ABSOLUTE_TIME
psnip_uint64_t nsec = mach_absolute_time();
static mach_timebase_info_data_t tbi = { 0, };
if (tbi.denom == 0)
mach_timebase_info(&tbi);
nsec *= ((psnip_uint64_t) tbi.numer) / ((psnip_uint64_t) tbi.denom);
res->seconds = nsec / PSNIP_CLOCK_NSEC_PER_SEC;
res->nanoseconds = nsec % PSNIP_CLOCK_NSEC_PER_SEC;
#elif defined(PSNIP_CLOCK_MONOTONIC_METHOD) && PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_QUERYPERFORMANCECOUNTER
LARGE_INTEGER t, f;
if (QueryPerformanceCounter(&t) == 0)
return -12;
QueryPerformanceFrequency(&f);
res->seconds = t.QuadPart / f.QuadPart;
res->nanoseconds = t.QuadPart % f.QuadPart;
if (f.QuadPart > PSNIP_CLOCK_NSEC_PER_SEC)
res->nanoseconds /= f.QuadPart / PSNIP_CLOCK_NSEC_PER_SEC;
else
res->nanoseconds *= PSNIP_CLOCK_NSEC_PER_SEC / f.QuadPart;
#elif defined(PSNIP_CLOCK_MONOTONIC_METHOD) && PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_GETTICKCOUNT64
const ULONGLONG msec = GetTickCount64();
res->seconds = msec / 1000;
res->nanoseconds = sec % 1000;
#else
return -2;
#endif
return 0;
}
/* Returns the number of ticks per second for the specified clock.
* For example, a clock with millisecond precision would return 1000,
* and a clock with 1 second (such as the time() function) would
* return 1.
*
* If the requested clock isn't available, it will return 0.
* Hopefully this will be rare, but if it happens to you please let us
* know so we can work on finding a way to support your system.
*
* Note that different clocks on the same system often have a
* different precisions.
*/
PSNIP_CLOCK__FUNCTION psnip_uint32_t
psnip_clock_get_precision (enum PsnipClockType clock_type) {
switch (clock_type) {
case PSNIP_CLOCK_TYPE_MONOTONIC:
return psnip_clock_monotonic_get_precision ();
case PSNIP_CLOCK_TYPE_CPU:
return psnip_clock_cpu_get_precision ();
case PSNIP_CLOCK_TYPE_WALL:
return psnip_clock_wall_get_precision ();
}
PSNIP_CLOCK_UNREACHABLE();
return 0;
}
/* Set the provided timespec to the requested time. Returns 0 on
* success, or a negative value on failure. */
PSNIP_CLOCK__FUNCTION int
psnip_clock_get_time (enum PsnipClockType clock_type, struct PsnipClockTimespec* res) {
assert(res != NULL);
switch (clock_type) {
case PSNIP_CLOCK_TYPE_MONOTONIC:
return psnip_clock_monotonic_get_time (res);
case PSNIP_CLOCK_TYPE_CPU:
return psnip_clock_cpu_get_time (res);
case PSNIP_CLOCK_TYPE_WALL:
return psnip_clock_wall_get_time (res);
}
return -1;
}
#endif /* !defined(PSNIP_CLOCK_H) */
static psnip_uint64_t
munit_clock_get_elapsed(struct PsnipClockTimespec* start, struct PsnipClockTimespec* end) {
psnip_uint64_t r = (end->seconds - start->seconds) * PSNIP_CLOCK_NSEC_PER_SEC;
if (end->nanoseconds < start->nanoseconds) {
r -= (start->nanoseconds - end->nanoseconds);
} else {
r += (end->nanoseconds - start->nanoseconds);
}
return r;
}
#else
# include <time.h>
#endif /* defined(MUNIT_ENABLE_TIMING) */
/*** PRNG stuff ***/
/* This is (unless I screwed up, which is entirely possible) the
* version of PCG with 32-bit state. It was chosen because it has a
* small enough state that we should reliably be able to use CAS
* instead of requiring a lock for thread-safety.
*
* If I did screw up, I probably will not bother changing it unless
* there is a significant bias. It's really not important this be
* particularly strong, as long as it is fairly random it's much more
* important that it be reproducible, so bug reports have a better
* chance of being reproducible. */
#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) && !defined(__STDC_NO_ATOMICS__) && !defined(__EMSCRIPTEN__) && (!defined(__GNUC_MINOR__) || (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ > 8))
# define HAVE_STDATOMIC
#elif defined(__clang__)
# if __has_extension(c_atomic)
# define HAVE_CLANG_ATOMICS
# endif
#endif
/* Workaround for http://llvm.org/bugs/show_bug.cgi?id=26911 */
#if defined(__clang__) && defined(_WIN32)
# undef HAVE_STDATOMIC
# if defined(__c2__)
# undef HAVE_CLANG_ATOMICS
# endif
#endif
#if defined(_OPENMP)
# define ATOMIC_UINT32_T uint32_t
# define ATOMIC_UINT32_INIT(x) (x)
#elif defined(HAVE_STDATOMIC)
# include <stdatomic.h>
# define ATOMIC_UINT32_T _Atomic uint32_t
# define ATOMIC_UINT32_INIT(x) ATOMIC_VAR_INIT(x)
#elif defined(HAVE_CLANG_ATOMICS)
# define ATOMIC_UINT32_T _Atomic uint32_t
# define ATOMIC_UINT32_INIT(x) (x)
#elif defined(_WIN32)
# define ATOMIC_UINT32_T volatile LONG
# define ATOMIC_UINT32_INIT(x) (x)
#else
# define ATOMIC_UINT32_T volatile uint32_t
# define ATOMIC_UINT32_INIT(x) (x)
#endif
static ATOMIC_UINT32_T munit_rand_state = ATOMIC_UINT32_INIT(42);
#if defined(_OPENMP)
static inline void
munit_atomic_store(ATOMIC_UINT32_T* dest, ATOMIC_UINT32_T value) {
#pragma omp critical (munit_atomics)
*dest = value;
}
static inline uint32_t
munit_atomic_load(ATOMIC_UINT32_T* src) {
int ret;
#pragma omp critical (munit_atomics)
ret = *src;
return ret;
}
static inline uint32_t
munit_atomic_cas(ATOMIC_UINT32_T* dest, ATOMIC_UINT32_T* expected, ATOMIC_UINT32_T desired) {
munit_bool ret;
#pragma omp critical (munit_atomics)
{
if (*dest == *expected) {
*dest = desired;
ret = 1;
} else {
ret = 0;
}
}
return ret;
}
#elif defined(HAVE_STDATOMIC)
# define munit_atomic_store(dest, value) atomic_store(dest, value)
# define munit_atomic_load(src) atomic_load(src)
# define munit_atomic_cas(dest, expected, value) atomic_compare_exchange_weak(dest, expected, value)
#elif defined(HAVE_CLANG_ATOMICS)
# define munit_atomic_store(dest, value) __c11_atomic_store(dest, value, __ATOMIC_SEQ_CST)
# define munit_atomic_load(src) __c11_atomic_load(src, __ATOMIC_SEQ_CST)
# define munit_atomic_cas(dest, expected, value) __c11_atomic_compare_exchange_weak(dest, expected, value, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)
#elif defined(__GNUC__) && (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7)
# define munit_atomic_store(dest, value) __atomic_store_n(dest, value, __ATOMIC_SEQ_CST)
# define munit_atomic_load(src) __atomic_load_n(src, __ATOMIC_SEQ_CST)
# define munit_atomic_cas(dest, expected, value) __atomic_compare_exchange_n(dest, expected, value, 1, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)
#elif defined(__GNUC__) && (__GNUC__ >= 4)
# define munit_atomic_store(dest,value) do { *(dest) = (value); } while (0)
# define munit_atomic_load(src) (*(src))
# define munit_atomic_cas(dest, expected, value) __sync_bool_compare_and_swap(dest, *expected, value)
#elif defined(_WIN32) /* Untested */
# define munit_atomic_store(dest,value) do { *(dest) = (value); } while (0)
# define munit_atomic_load(src) (*(src))
# define munit_atomic_cas(dest, expected, value) InterlockedCompareExchange((dest), (value), *(expected))
#else
# warning No atomic implementation, PRNG will not be thread-safe
# define munit_atomic_store(dest, value) do { *(dest) = (value); } while (0)
# define munit_atomic_load(src) (*(src))
static inline munit_bool
munit_atomic_cas(ATOMIC_UINT32_T* dest, ATOMIC_UINT32_T* expected, ATOMIC_UINT32_T desired) {
if (*dest == *expected) {
*dest = desired;
return 1;
} else {
return 0;
}
}
#endif
#define MUNIT_PRNG_MULTIPLIER (747796405U)
#define MUNIT_PRNG_INCREMENT (1729U)
static munit_uint32_t
munit_rand_next_state(munit_uint32_t state) {
return state * MUNIT_PRNG_MULTIPLIER + MUNIT_PRNG_INCREMENT;
}
static munit_uint32_t
munit_rand_from_state(munit_uint32_t state) {
munit_uint32_t res = ((state >> ((state >> 28) + 4)) ^ state) * (277803737U);
res ^= res >> 22;
return res;
}
void
munit_rand_seed(munit_uint32_t seed) {
munit_uint32_t state = munit_rand_next_state(seed + MUNIT_PRNG_INCREMENT);
munit_atomic_store(&munit_rand_state, state);
}
static munit_uint32_t
munit_rand_generate_seed(void) {
munit_uint32_t seed, state;
#if defined(MUNIT_ENABLE_TIMING)
struct PsnipClockTimespec wc = { 0, };
psnip_clock_get_time(PSNIP_CLOCK_TYPE_WALL, &wc);
seed = (munit_uint32_t) wc.nanoseconds;
#else
seed = (munit_uint32_t) time(NULL);
#endif
state = munit_rand_next_state(seed + MUNIT_PRNG_INCREMENT);
return munit_rand_from_state(state);
}
static munit_uint32_t
munit_rand_state_uint32(munit_uint32_t* state) {
const munit_uint32_t old = *state;
*state = munit_rand_next_state(old);
return munit_rand_from_state(old);
}
munit_uint32_t
munit_rand_uint32(void) {
munit_uint32_t old, state;
do {
old = munit_atomic_load(&munit_rand_state);
state = munit_rand_next_state(old);
} while (!munit_atomic_cas(&munit_rand_state, &old, state));
return munit_rand_from_state(old);
}
static void
munit_rand_state_memory(munit_uint32_t* state, size_t size, munit_uint8_t data[MUNIT_ARRAY_PARAM(size)]) {
size_t members_remaining = size / sizeof(munit_uint32_t);
size_t bytes_remaining = size % sizeof(munit_uint32_t);
munit_uint8_t* b = data;
munit_uint32_t rv;
while (members_remaining-- > 0) {
rv = munit_rand_state_uint32(state);
memcpy(b, &rv, sizeof(munit_uint32_t));
b += sizeof(munit_uint32_t);
}
if (bytes_remaining != 0) {
rv = munit_rand_state_uint32(state);
memcpy(b, &rv, bytes_remaining);
}
}
void
munit_rand_memory(size_t size, munit_uint8_t data[MUNIT_ARRAY_PARAM(size)]) {
munit_uint32_t old, state;
do {
state = old = munit_atomic_load(&munit_rand_state);
munit_rand_state_memory(&state, size, data);
} while (!munit_atomic_cas(&munit_rand_state, &old, state));
}
static munit_uint32_t
munit_rand_state_at_most(munit_uint32_t* state, munit_uint32_t salt, munit_uint32_t max) {
/* We want (UINT32_MAX + 1) % max, which in unsigned arithmetic is the same
* as (UINT32_MAX + 1 - max) % max = -max % max. We compute -max using not
* to avoid compiler warnings.
*/
const munit_uint32_t min = (~max + 1U) % max;
munit_uint32_t x;
if (max == (~((munit_uint32_t) 0U)))
return munit_rand_state_uint32(state) ^ salt;
max++;
do {
x = munit_rand_state_uint32(state) ^ salt;
} while (x < min);
return x % max;
}
static munit_uint32_t
munit_rand_at_most(munit_uint32_t salt, munit_uint32_t max) {
munit_uint32_t old, state;
munit_uint32_t retval;
do {
state = old = munit_atomic_load(&munit_rand_state);
retval = munit_rand_state_at_most(&state, salt, max);
} while (!munit_atomic_cas(&munit_rand_state, &old, state));
return retval;
}
int
munit_rand_int_range(int min, int max) {
munit_uint64_t range = (munit_uint64_t) max - (munit_uint64_t) min;
if (min > max)
return munit_rand_int_range(max, min);
if (range > (~((munit_uint32_t) 0U)))
range = (~((munit_uint32_t) 0U));
return min + munit_rand_at_most(0, (munit_uint32_t) range);
}
munit_uint32_t
munit_rand_uint32_range(munit_uint32_t min, munit_uint32_t max) {
munit_uint32_t range = (munit_uint32_t) max - (munit_uint32_t) min;
if (min > max)
return munit_rand_uint32_range(max, min);
return min + munit_rand_at_most(0, (munit_uint32_t) range);
}
double
munit_rand_double(void) {
munit_uint32_t old, state;
double retval = 0.0;
do {
state = old = munit_atomic_load(&munit_rand_state);
/* See http://mumble.net/~campbell/tmp/random_real.c for how to do
* this right. Patches welcome if you feel that this is too
* biased. */
retval = munit_rand_state_uint32(&state) / ((~((munit_uint32_t) 0U)) + 1.0);
} while (!munit_atomic_cas(&munit_rand_state, &old, state));
return retval;
}
/*** Test suite handling ***/
typedef struct {
unsigned int successful;
unsigned int skipped;
unsigned int failed;
unsigned int errored;
#if defined(MUNIT_ENABLE_TIMING)
munit_uint64_t cpu_clock;
munit_uint64_t wall_clock;
#endif
} MunitReport;
typedef struct {
const char* prefix;
const MunitSuite* suite;
const char** tests;
munit_uint32_t seed;
unsigned int iterations;
MunitParameter* parameters;
munit_bool single_parameter_mode;
void* user_data;
MunitReport report;
munit_bool colorize;
munit_bool fork;
munit_bool show_stderr;
munit_bool fatal_failures;
} MunitTestRunner;
const char*
munit_parameters_get(const MunitParameter params[], const char* key) {
const MunitParameter* param;
for (param = params ; param != NULL && param->name != NULL ; param++)
if (strcmp(param->name, key) == 0)
return param->value;
return NULL;
}
#if defined(MUNIT_ENABLE_TIMING)
static void
munit_print_time(FILE* fp, munit_uint64_t nanoseconds) {
fprintf(fp, "%" MUNIT_TEST_TIME_FORMAT, ((double) nanoseconds) / ((double) PSNIP_CLOCK_NSEC_PER_SEC));
}
#endif
/* Add a paramter to an array of parameters. */
static MunitResult
munit_parameters_add(size_t* params_size, MunitParameter* params[MUNIT_ARRAY_PARAM(*params_size)], char* name, char* value) {
*params = realloc(*params, sizeof(MunitParameter) * (*params_size + 2));
if (*params == NULL)
return MUNIT_ERROR;
(*params)[*params_size].name = name;
(*params)[*params_size].value = value;
(*params_size)++;
(*params)[*params_size].name = NULL;
(*params)[*params_size].value = NULL;
return MUNIT_OK;
}
/* Concatenate two strings, but just return one of the components
* unaltered if the other is NULL or "". */
static char*
munit_maybe_concat(size_t* len, char* prefix, char* suffix) {
char* res;
size_t res_l;
const size_t prefix_l = prefix != NULL ? strlen(prefix) : 0;
const size_t suffix_l = suffix != NULL ? strlen(suffix) : 0;
if (prefix_l == 0 && suffix_l == 0) {
res = NULL;
res_l = 0;
} else if (prefix_l == 0 && suffix_l != 0) {
res = suffix;
res_l = suffix_l;
} else if (prefix_l != 0 && suffix_l == 0) {
res = prefix;
res_l = prefix_l;
} else {
res_l = prefix_l + suffix_l;
res = malloc(res_l + 1);
memcpy(res, prefix, prefix_l);
memcpy(res + prefix_l, suffix, suffix_l);
res[res_l] = 0;
}
if (len != NULL)
*len = res_l;
return res;
}
/* Possbily free a string returned by munit_maybe_concat. */
static void
munit_maybe_free_concat(char* s, const char* prefix, const char* suffix) {
if (prefix != s && suffix != s)
free(s);
}
/* Cheap string hash function, just used to salt the PRNG. */
static munit_uint32_t
munit_str_hash(const char* name) {
const char *p;
munit_uint32_t h = 5381U;
for (p = name; *p != '\0'; p++)
h = (h << 5) + h + *p;
return h;
}
static void
munit_splice(int from, int to) {
munit_uint8_t buf[1024];
#if !defined(_WIN32)
ssize_t len;
ssize_t bytes_written;
ssize_t write_res;
#else
int len;
int bytes_written;
int write_res;
#endif
do {
len = read(from, buf, sizeof(buf));
if (len > 0) {
bytes_written = 0;
do {
write_res = write(to, buf + bytes_written, len - bytes_written);
if (write_res < 0)
break;
bytes_written += write_res;
} while (bytes_written < len);
}
else
break;
} while (1);
}
/* This is the part that should be handled in the child process */
static MunitResult
munit_test_runner_exec(MunitTestRunner* runner, const MunitTest* test, const MunitParameter params[], MunitReport* report) {
unsigned int iterations = runner->iterations;
MunitResult result = MUNIT_FAIL;
#if defined(MUNIT_ENABLE_TIMING)
struct PsnipClockTimespec wall_clock_begin = { 0, }, wall_clock_end = { 0, };
struct PsnipClockTimespec cpu_clock_begin = { 0, }, cpu_clock_end = { 0, };
#endif
unsigned int i = 0;
if ((test->options & MUNIT_TEST_OPTION_SINGLE_ITERATION) == MUNIT_TEST_OPTION_SINGLE_ITERATION)
iterations = 1;
else if (iterations == 0)
iterations = runner->suite->iterations;
munit_rand_seed(runner->seed);
do {
void* data = (test->setup == NULL) ? runner->user_data : test->setup(params, runner->user_data);
#if defined(MUNIT_ENABLE_TIMING)
psnip_clock_get_time(PSNIP_CLOCK_TYPE_WALL, &wall_clock_begin);
psnip_clock_get_time(PSNIP_CLOCK_TYPE_CPU, &cpu_clock_begin);
#endif
result = test->test(params, data);
#if defined(MUNIT_ENABLE_TIMING)
psnip_clock_get_time(PSNIP_CLOCK_TYPE_WALL, &wall_clock_end);
psnip_clock_get_time(PSNIP_CLOCK_TYPE_CPU, &cpu_clock_end);
#endif
if (test->tear_down != NULL)
test->tear_down(data);
if (MUNIT_LIKELY(result == MUNIT_OK)) {
report->successful++;
#if defined(MUNIT_ENABLE_TIMING)
report->wall_clock += munit_clock_get_elapsed(&wall_clock_begin, &wall_clock_end);
report->cpu_clock += munit_clock_get_elapsed(&cpu_clock_begin, &cpu_clock_end);
#endif
} else {
switch ((int) result) {
case MUNIT_SKIP:
report->skipped++;
break;
case MUNIT_FAIL:
report->failed++;
break;
case MUNIT_ERROR:
report->errored++;
break;
default:
break;
}
break;
}
} while (++i < iterations);
return result;
}
#if defined(MUNIT_EMOTICON)
# define MUNIT_RESULT_STRING_OK ":)"
# define MUNIT_RESULT_STRING_SKIP ":|"
# define MUNIT_RESULT_STRING_FAIL ":("
# define MUNIT_RESULT_STRING_ERROR ":o"
# define MUNIT_RESULT_STRING_TODO ":/"
#else
# define MUNIT_RESULT_STRING_OK "OK "
# define MUNIT_RESULT_STRING_SKIP "SKIP "
# define MUNIT_RESULT_STRING_FAIL "FAIL "
# define MUNIT_RESULT_STRING_ERROR "ERROR"
# define MUNIT_RESULT_STRING_TODO "TODO "
#endif
static void
munit_test_runner_print_color(const MunitTestRunner* runner, const char* string, char color) {
if (runner->colorize)
fprintf(MUNIT_OUTPUT_FILE, "\x1b[3%cm%s\x1b[39m", color, string);
else
fputs(string, MUNIT_OUTPUT_FILE);
}
#if !defined(MUNIT_NO_BUFFER)
static int
munit_replace_stderr(FILE* stderr_buf) {
if (stderr_buf != NULL) {
const int orig_stderr = dup(STDERR_FILENO);
int errfd = fileno(stderr_buf);
if (MUNIT_UNLIKELY(errfd == -1)) {
exit(EXIT_FAILURE);
}
dup2(errfd, STDERR_FILENO);
return orig_stderr;
}
return -1;
}
static void
munit_restore_stderr(int orig_stderr) {
if (orig_stderr != -1) {
dup2(orig_stderr, STDERR_FILENO);
close(orig_stderr);
}
}
#endif /* !defined(MUNIT_NO_BUFFER) */
/* Run a test with the specified parameters. */
static void
munit_test_runner_run_test_with_params(MunitTestRunner* runner, const MunitTest* test, const MunitParameter params[]) {
MunitResult result = MUNIT_OK;
MunitReport report = {
0, 0, 0, 0,
#if defined(MUNIT_ENABLE_TIMING)
0, 0
#endif
};
unsigned int output_l;
munit_bool first;
const MunitParameter* param;
FILE* stderr_buf;
#if !defined(MUNIT_NO_FORK)
int pipefd[2];
pid_t fork_pid;
int orig_stderr;
ssize_t bytes_written = 0;
ssize_t write_res;
ssize_t bytes_read = 0;
ssize_t read_res;
int status = 0;
pid_t changed_pid;
#endif
if (params != NULL) {
output_l = 2;
fputs(" ", MUNIT_OUTPUT_FILE);
first = 1;
for (param = params ; param != NULL && param->name != NULL ; param++) {
if (!first) {
fputs(", ", MUNIT_OUTPUT_FILE);
output_l += 2;
} else {
first = 0;
}
output_l += fprintf(MUNIT_OUTPUT_FILE, "%s=%s", param->name, param->value);
}
while (output_l++ < MUNIT_TEST_NAME_LEN) {
fputc(' ', MUNIT_OUTPUT_FILE);
}
}
fflush(MUNIT_OUTPUT_FILE);
stderr_buf = NULL;
#if !defined(_WIN32) || defined(__MINGW32__)
stderr_buf = tmpfile();
#else
tmpfile_s(&stderr_buf);
#endif
if (stderr_buf == NULL) {
munit_log_errno(MUNIT_LOG_ERROR, stderr, "unable to create buffer for stderr");
result = MUNIT_ERROR;
goto print_result;
}
#if !defined(MUNIT_NO_FORK)
if (runner->fork) {
pipefd[0] = -1;
pipefd[1] = -1;
if (pipe(pipefd) != 0) {
munit_log_errno(MUNIT_LOG_ERROR, stderr, "unable to create pipe");
result = MUNIT_ERROR;
goto print_result;
}
fork_pid = fork();
if (fork_pid == 0) {
close(pipefd[0]);
orig_stderr = munit_replace_stderr(stderr_buf);
munit_test_runner_exec(runner, test, params, &report);
/* Note that we don't restore stderr. This is so we can buffer
* things written to stderr later on (such as by
* asan/tsan/ubsan, valgrind, etc.) */
close(orig_stderr);
do {
write_res = write(pipefd[1], ((munit_uint8_t*) (&report)) + bytes_written, sizeof(report) - bytes_written);
if (write_res < 0) {
if (stderr_buf != NULL) {
munit_log_errno(MUNIT_LOG_ERROR, stderr, "unable to write to pipe");
}
exit(EXIT_FAILURE);
}
bytes_written += write_res;
} while ((size_t) bytes_written < sizeof(report));
if (stderr_buf != NULL)
fclose(stderr_buf);
close(pipefd[1]);
exit(EXIT_SUCCESS);
} else if (fork_pid == -1) {
close(pipefd[0]);
close(pipefd[1]);
if (stderr_buf != NULL) {
munit_log_errno(MUNIT_LOG_ERROR, stderr, "unable to fork");
}
report.errored++;
result = MUNIT_ERROR;
} else {
close(pipefd[1]);
do {
read_res = read(pipefd[0], ((munit_uint8_t*) (&report)) + bytes_read, sizeof(report) - bytes_read);
if (read_res < 1)
break;
bytes_read += read_res;
} while (bytes_read < (ssize_t) sizeof(report));
changed_pid = waitpid(fork_pid, &status, 0);
if (MUNIT_LIKELY(changed_pid == fork_pid) && MUNIT_LIKELY(WIFEXITED(status))) {
if (bytes_read != sizeof(report)) {
munit_logf_internal(MUNIT_LOG_ERROR, stderr_buf, "child exited unexpectedly with status %d", WEXITSTATUS(status));
report.errored++;
} else if (WEXITSTATUS(status) != EXIT_SUCCESS) {
munit_logf_internal(MUNIT_LOG_ERROR, stderr_buf, "child exited with status %d", WEXITSTATUS(status));
report.errored++;
}
} else {
if (WIFSIGNALED(status)) {
#if defined(_XOPEN_VERSION) && (_XOPEN_VERSION >= 700)
munit_logf_internal(MUNIT_LOG_ERROR, stderr_buf, "child killed by signal %d (%s)", WTERMSIG(status), strsignal(WTERMSIG(status)));
#else
munit_logf_internal(MUNIT_LOG_ERROR, stderr_buf, "child killed by signal %d", WTERMSIG(status));
#endif
} else if (WIFSTOPPED(status)) {
munit_logf_internal(MUNIT_LOG_ERROR, stderr_buf, "child stopped by signal %d", WSTOPSIG(status));
}
report.errored++;
}
close(pipefd[0]);
waitpid(fork_pid, NULL, 0);
}
} else
#endif
{
#if !defined(MUNIT_NO_BUFFER)
const volatile int orig_stderr = munit_replace_stderr(stderr_buf);
#endif
#if defined(MUNIT_THREAD_LOCAL)
if (MUNIT_UNLIKELY(setjmp(munit_error_jmp_buf) != 0)) {
result = MUNIT_FAIL;
report.failed++;
} else {
munit_error_jmp_buf_valid = 1;
result = munit_test_runner_exec(runner, test, params, &report);
}
#else
result = munit_test_runner_exec(runner, test, params, &report);
#endif
#if !defined(MUNIT_NO_BUFFER)
munit_restore_stderr(orig_stderr);
#endif
/* Here just so that the label is used on Windows and we don't get
* a warning */
goto print_result;
}
print_result:
fputs("[ ", MUNIT_OUTPUT_FILE);
if ((test->options & MUNIT_TEST_OPTION_TODO) == MUNIT_TEST_OPTION_TODO) {
if (report.failed != 0 || report.errored != 0 || report.skipped != 0) {
munit_test_runner_print_color(runner, MUNIT_RESULT_STRING_TODO, '3');
result = MUNIT_OK;
} else {
munit_test_runner_print_color(runner, MUNIT_RESULT_STRING_ERROR, '1');
if (MUNIT_LIKELY(stderr_buf != NULL))
munit_log_internal(MUNIT_LOG_ERROR, stderr_buf, "Test marked TODO, but was successful.");
runner->report.failed++;
result = MUNIT_ERROR;
}
} else if (report.failed > 0) {
munit_test_runner_print_color(runner, MUNIT_RESULT_STRING_FAIL, '1');
runner->report.failed++;
result = MUNIT_FAIL;
} else if (report.errored > 0) {
munit_test_runner_print_color(runner, MUNIT_RESULT_STRING_ERROR, '1');
runner->report.errored++;
result = MUNIT_ERROR;
} else if (report.skipped > 0) {
munit_test_runner_print_color(runner, MUNIT_RESULT_STRING_SKIP, '3');
runner->report.skipped++;
result = MUNIT_SKIP;
} else if (report.successful > 1) {
munit_test_runner_print_color(runner, MUNIT_RESULT_STRING_OK, '2');
#if defined(MUNIT_ENABLE_TIMING)
fputs(" ] [ ", MUNIT_OUTPUT_FILE);
munit_print_time(MUNIT_OUTPUT_FILE, report.wall_clock / report.successful);
fputs(" / ", MUNIT_OUTPUT_FILE);
munit_print_time(MUNIT_OUTPUT_FILE, report.cpu_clock / report.successful);
fprintf(MUNIT_OUTPUT_FILE, " CPU ]\n %-" MUNIT_XSTRINGIFY(MUNIT_TEST_NAME_LEN) "s Total: [ ", "");
munit_print_time(MUNIT_OUTPUT_FILE, report.wall_clock);
fputs(" / ", MUNIT_OUTPUT_FILE);
munit_print_time(MUNIT_OUTPUT_FILE, report.cpu_clock);
fputs(" CPU", MUNIT_OUTPUT_FILE);
#endif
runner->report.successful++;
result = MUNIT_OK;
} else if (report.successful > 0) {
munit_test_runner_print_color(runner, MUNIT_RESULT_STRING_OK, '2');
#if defined(MUNIT_ENABLE_TIMING)
fputs(" ] [ ", MUNIT_OUTPUT_FILE);
munit_print_time(MUNIT_OUTPUT_FILE, report.wall_clock);
fputs(" / ", MUNIT_OUTPUT_FILE);
munit_print_time(MUNIT_OUTPUT_FILE, report.cpu_clock);
fputs(" CPU", MUNIT_OUTPUT_FILE);
#endif
runner->report.successful++;
result = MUNIT_OK;
}
fputs(" ]\n", MUNIT_OUTPUT_FILE);
if (stderr_buf != NULL) {
if (result == MUNIT_FAIL || result == MUNIT_ERROR || runner->show_stderr) {
fflush(MUNIT_OUTPUT_FILE);
rewind(stderr_buf);
munit_splice(fileno(stderr_buf), STDERR_FILENO);
fflush(stderr);
}
fclose(stderr_buf);
}
}
static void
munit_test_runner_run_test_wild(MunitTestRunner* runner,
const MunitTest* test,
const char* test_name,
MunitParameter* params,
MunitParameter* p) {
const MunitParameterEnum* pe;
char** values;
MunitParameter* next;
for (pe = test->parameters ; pe != NULL && pe->name != NULL ; pe++) {
if (p->name == pe->name)
break;
}
if (pe == NULL)
return;
for (values = pe->values ; *values != NULL ; values++) {
next = p + 1;
p->value = *values;
if (next->name == NULL) {
munit_test_runner_run_test_with_params(runner, test, params);
} else {
munit_test_runner_run_test_wild(runner, test, test_name, params, next);
}
if (runner->fatal_failures && (runner->report.failed != 0 || runner->report.errored != 0))
break;
}
}
/* Run a single test, with every combination of parameters
* requested. */
static void
munit_test_runner_run_test(MunitTestRunner* runner,
const MunitTest* test,
const char* prefix) {
char* test_name = munit_maybe_concat(NULL, (char*) prefix, (char*) test->name);
/* The array of parameters to pass to
* munit_test_runner_run_test_with_params */
MunitParameter* params = NULL;
size_t params_l = 0;
/* Wildcard parameters are parameters which have possible values
* specified in the test, but no specific value was passed to the
* CLI. That means we want to run the test once for every
* possible combination of parameter values or, if --single was
* passed to the CLI, a single time with a random set of
* parameters. */
MunitParameter* wild_params = NULL;
size_t wild_params_l = 0;
const MunitParameterEnum* pe;
const MunitParameter* cli_p;
munit_bool filled;
unsigned int possible;
char** vals;
size_t first_wild;
const MunitParameter* wp;
int pidx;
munit_rand_seed(runner->seed);
fprintf(MUNIT_OUTPUT_FILE, "%-" MUNIT_XSTRINGIFY(MUNIT_TEST_NAME_LEN) "s", test_name);
if (test->parameters == NULL) {
/* No parameters. Simple, nice. */
munit_test_runner_run_test_with_params(runner, test, NULL);
} else {
fputc('\n', MUNIT_OUTPUT_FILE);
for (pe = test->parameters ; pe != NULL && pe->name != NULL ; pe++) {
/* Did we received a value for this parameter from the CLI? */
filled = 0;
for (cli_p = runner->parameters ; cli_p != NULL && cli_p->name != NULL ; cli_p++) {
if (strcmp(cli_p->name, pe->name) == 0) {
if (MUNIT_UNLIKELY(munit_parameters_add(¶ms_l, ¶ms, pe->name, cli_p->value) != MUNIT_OK))
goto cleanup;
filled = 1;
break;
}
}
if (filled)
continue;
/* Nothing from CLI, is the enum NULL/empty? We're not a
* fuzzer… */
if (pe->values == NULL || pe->values[0] == NULL)
continue;
/* If --single was passed to the CLI, choose a value from the
* list of possibilities randomly. */
if (runner->single_parameter_mode) {
possible = 0;
for (vals = pe->values ; *vals != NULL ; vals++)
possible++;
/* We want the tests to be reproducible, even if you're only
* running a single test, but we don't want every test with
* the same number of parameters to choose the same parameter
* number, so use the test name as a primitive salt. */
pidx = munit_rand_at_most(munit_str_hash(test_name), possible - 1);
if (MUNIT_UNLIKELY(munit_parameters_add(¶ms_l, ¶ms, pe->name, pe->values[pidx]) != MUNIT_OK))
goto cleanup;
} else {
/* We want to try every permutation. Put in a placeholder
* entry, we'll iterate through them later. */
if (MUNIT_UNLIKELY(munit_parameters_add(&wild_params_l, &wild_params, pe->name, NULL) != MUNIT_OK))
goto cleanup;
}
}
if (wild_params_l != 0) {
first_wild = params_l;
for (wp = wild_params ; wp != NULL && wp->name != NULL ; wp++) {
for (pe = test->parameters ; pe != NULL && pe->name != NULL && pe->values != NULL ; pe++) {
if (strcmp(wp->name, pe->name) == 0) {
if (MUNIT_UNLIKELY(munit_parameters_add(¶ms_l, ¶ms, pe->name, pe->values[0]) != MUNIT_OK))
goto cleanup;
}
}
}
munit_test_runner_run_test_wild(runner, test, test_name, params, params + first_wild);
} else {
munit_test_runner_run_test_with_params(runner, test, params);
}
cleanup:
free(params);
free(wild_params);
}
munit_maybe_free_concat(test_name, prefix, test->name);
}
/* Recurse through the suite and run all the tests. If a list of
* tests to run was provied on the command line, run only those
* tests. */
static void
munit_test_runner_run_suite(MunitTestRunner* runner,
const MunitSuite* suite,
const char* prefix) {
size_t pre_l;
char* pre = munit_maybe_concat(&pre_l, (char*) prefix, (char*) suite->prefix);
const MunitTest* test;
const char** test_name;
const MunitSuite* child_suite;
/* Run the tests. */
for (test = suite->tests ; test != NULL && test->test != NULL ; test++) {
if (runner->tests != NULL) { /* Specific tests were requested on the CLI */
for (test_name = runner->tests ; test_name != NULL && *test_name != NULL ; test_name++) {
if ((pre_l == 0 || strncmp(pre, *test_name, pre_l) == 0) &&
strncmp(test->name, *test_name + pre_l, strlen(*test_name + pre_l)) == 0) {
munit_test_runner_run_test(runner, test, pre);
if (runner->fatal_failures && (runner->report.failed != 0 || runner->report.errored != 0))
goto cleanup;
}
}
} else { /* Run all tests */
munit_test_runner_run_test(runner, test, pre);
}
}
if (runner->fatal_failures && (runner->report.failed != 0 || runner->report.errored != 0))
goto cleanup;
/* Run any child suites. */
for (child_suite = suite->suites ; child_suite != NULL && child_suite->prefix != NULL ; child_suite++) {
munit_test_runner_run_suite(runner, child_suite, pre);
}
cleanup:
munit_maybe_free_concat(pre, prefix, suite->prefix);
}
static void
munit_test_runner_run(MunitTestRunner* runner) {
munit_test_runner_run_suite(runner, runner->suite, NULL);
}
static void
munit_print_help(int argc, char* const argv[MUNIT_ARRAY_PARAM(argc + 1)], void* user_data, const MunitArgument arguments[]) {
const MunitArgument* arg;
(void) argc;
printf("USAGE: %s [OPTIONS...] [TEST...]\n\n", argv[0]);
puts(" --seed SEED\n"
" Value used to seed the PRNG. Must be a 32-bit integer in decimal\n"
" notation with no separators (commas, decimals, spaces, etc.), or\n"
" hexidecimal prefixed by \"0x\".\n"
" --iterations N\n"
" Run each test N times. 0 means the default number.\n"
" --param name value\n"
" A parameter key/value pair which will be passed to any test with\n"
" takes a parameter of that name. If not provided, the test will be\n"
" run once for each possible parameter value.\n"
" --list Write a list of all available tests.\n"
" --list-params\n"
" Write a list of all available tests and their possible parameters.\n"
" --single Run each parameterized test in a single configuration instead of\n"
" every possible combination\n"
" --log-visible debug|info|warning|error\n"
" --log-fatal debug|info|warning|error\n"
" Set the level at which messages of different severities are visible,\n"
" or cause the test to terminate.\n"
#if !defined(MUNIT_NO_FORK)
" --no-fork Do not execute tests in a child process. If this option is supplied\n"
" and a test crashes (including by failing an assertion), no further\n"
" tests will be performed.\n"
#endif
" --fatal-failures\n"
" Stop executing tests as soon as a failure is found.\n"
" --show-stderr\n"
" Show data written to stderr by the tests, even if the test succeeds.\n"
" --color auto|always|never\n"
" Colorize (or don't) the output.\n"
/* 12345678901234567890123456789012345678901234567890123456789012345678901234567890 */
" --help Print this help message and exit.\n");
#if defined(MUNIT_NL_LANGINFO)
setlocale(LC_ALL, "");
fputs((strcasecmp("UTF-8", nl_langinfo(CODESET)) == 0) ? "µnit" : "munit", stdout);
#else
puts("munit");
#endif
printf(" %d.%d.%d\n"
"Full documentation at: https://nemequ.github.io/munit/\n",
(MUNIT_CURRENT_VERSION >> 16) & 0xff,
(MUNIT_CURRENT_VERSION >> 8) & 0xff,
(MUNIT_CURRENT_VERSION >> 0) & 0xff);
for (arg = arguments ; arg != NULL && arg->name != NULL ; arg++)
arg->write_help(arg, user_data);
}
static const MunitArgument*
munit_arguments_find(const MunitArgument arguments[], const char* name) {
const MunitArgument* arg;
for (arg = arguments ; arg != NULL && arg->name != NULL ; arg++)
if (strcmp(arg->name, name) == 0)
return arg;
return NULL;
}
static void
munit_suite_list_tests(const MunitSuite* suite, munit_bool show_params, const char* prefix) {
size_t pre_l;
char* pre = munit_maybe_concat(&pre_l, (char*) prefix, (char*) suite->prefix);
const MunitTest* test;
const MunitParameterEnum* params;
munit_bool first;
char** val;
const MunitSuite* child_suite;
for (test = suite->tests ;
test != NULL && test->name != NULL ;
test++) {
if (pre != NULL)
fputs(pre, stdout);
puts(test->name);
if (show_params) {
for (params = test->parameters ;
params != NULL && params->name != NULL ;
params++) {
fprintf(stdout, " - %s: ", params->name);
if (params->values == NULL) {
puts("Any");
} else {
first = 1;
for (val = params->values ;
*val != NULL ;
val++ ) {
if(!first) {
fputs(", ", stdout);
} else {
first = 0;
}
fputs(*val, stdout);
}
putc('\n', stdout);
}
}
}
}
for (child_suite = suite->suites ; child_suite != NULL && child_suite->prefix != NULL ; child_suite++) {
munit_suite_list_tests(child_suite, show_params, pre);
}
munit_maybe_free_concat(pre, prefix, suite->prefix);
}
static munit_bool
munit_stream_supports_ansi(FILE *stream) {
#if !defined(_WIN32)
return isatty(fileno(stream));
#else
#if !defined(__MINGW32__)
size_t ansicon_size = 0;
#endif
if (isatty(fileno(stream))) {
#if !defined(__MINGW32__)
getenv_s(&ansicon_size, NULL, 0, "ANSICON");
return ansicon_size != 0;
#else
return getenv("ANSICON") != NULL;
#endif
}
return 0;
#endif
}
int
munit_suite_main_custom(const MunitSuite* suite, void* user_data,
int argc, char* const argv[MUNIT_ARRAY_PARAM(argc + 1)],
const MunitArgument arguments[]) {
int result = EXIT_FAILURE;
MunitTestRunner runner;
size_t parameters_size = 0;
size_t tests_size = 0;
int arg;
char* envptr;
unsigned long ts;
char* endptr;
unsigned long long iterations;
MunitLogLevel level;
const MunitArgument* argument;
const char** runner_tests;
unsigned int tests_run;
unsigned int tests_total;
runner.prefix = NULL;
runner.suite = NULL;
runner.tests = NULL;
runner.seed = 0;
runner.iterations = 0;
runner.parameters = NULL;
runner.single_parameter_mode = 0;
runner.user_data = NULL;
runner.report.successful = 0;
runner.report.skipped = 0;
runner.report.failed = 0;
runner.report.errored = 0;
#if defined(MUNIT_ENABLE_TIMING)
runner.report.cpu_clock = 0;
runner.report.wall_clock = 0;
#endif
runner.colorize = 0;
#if !defined(_WIN32)
runner.fork = 1;
#else
runner.fork = 0;
#endif
runner.show_stderr = 0;
runner.fatal_failures = 0;
runner.suite = suite;
runner.user_data = user_data;
runner.seed = munit_rand_generate_seed();
runner.colorize = munit_stream_supports_ansi(MUNIT_OUTPUT_FILE);
for (arg = 1 ; arg < argc ; arg++) {
if (strncmp("--", argv[arg], 2) == 0) {
if (strcmp("seed", argv[arg] + 2) == 0) {
if (arg + 1 >= argc) {
munit_logf_internal(MUNIT_LOG_ERROR, stderr, "%s requires an argument", argv[arg]);
goto cleanup;
}
envptr = argv[arg + 1];
ts = strtoul(argv[arg + 1], &envptr, 0);
if (*envptr != '\0' || ts > (~((munit_uint32_t) 0U))) {
munit_logf_internal(MUNIT_LOG_ERROR, stderr, "invalid value ('%s') passed to %s", argv[arg + 1], argv[arg]);
goto cleanup;
}
runner.seed = (munit_uint32_t) ts;
arg++;
} else if (strcmp("iterations", argv[arg] + 2) == 0) {
if (arg + 1 >= argc) {
munit_logf_internal(MUNIT_LOG_ERROR, stderr, "%s requires an argument", argv[arg]);
goto cleanup;
}
endptr = argv[arg + 1];
iterations = strtoul(argv[arg + 1], &endptr, 0);
if (*endptr != '\0' || iterations > UINT_MAX) {
munit_logf_internal(MUNIT_LOG_ERROR, stderr, "invalid value ('%s') passed to %s", argv[arg + 1], argv[arg]);
goto cleanup;
}
runner.iterations = (unsigned int) iterations;
arg++;
} else if (strcmp("param", argv[arg] + 2) == 0) {
if (arg + 2 >= argc) {
munit_logf_internal(MUNIT_LOG_ERROR, stderr, "%s requires two arguments", argv[arg]);
goto cleanup;
}
runner.parameters = realloc(runner.parameters, sizeof(MunitParameter) * (parameters_size + 2));
if (runner.parameters == NULL) {
munit_log_internal(MUNIT_LOG_ERROR, stderr, "failed to allocate memory");
goto cleanup;
}
runner.parameters[parameters_size].name = (char*) argv[arg + 1];
runner.parameters[parameters_size].value = (char*) argv[arg + 2];
parameters_size++;
runner.parameters[parameters_size].name = NULL;
runner.parameters[parameters_size].value = NULL;
arg += 2;
} else if (strcmp("color", argv[arg] + 2) == 0) {
if (arg + 1 >= argc) {
munit_logf_internal(MUNIT_LOG_ERROR, stderr, "%s requires an argument", argv[arg]);
goto cleanup;
}
if (strcmp(argv[arg + 1], "always") == 0)
runner.colorize = 1;
else if (strcmp(argv[arg + 1], "never") == 0)
runner.colorize = 0;
else if (strcmp(argv[arg + 1], "auto") == 0)
runner.colorize = munit_stream_supports_ansi(MUNIT_OUTPUT_FILE);
else {
munit_logf_internal(MUNIT_LOG_ERROR, stderr, "invalid value ('%s') passed to %s", argv[arg + 1], argv[arg]);
goto cleanup;
}
arg++;
} else if (strcmp("help", argv[arg] + 2) == 0) {
munit_print_help(argc, argv, user_data, arguments);
result = EXIT_SUCCESS;
goto cleanup;
} else if (strcmp("single", argv[arg] + 2) == 0) {
runner.single_parameter_mode = 1;
} else if (strcmp("show-stderr", argv[arg] + 2) == 0) {
runner.show_stderr = 1;
#if !defined(_WIN32)
} else if (strcmp("no-fork", argv[arg] + 2) == 0) {
runner.fork = 0;
#endif
} else if (strcmp("fatal-failures", argv[arg] + 2) == 0) {
runner.fatal_failures = 1;
} else if (strcmp("log-visible", argv[arg] + 2) == 0 ||
strcmp("log-fatal", argv[arg] + 2) == 0) {
if (arg + 1 >= argc) {
munit_logf_internal(MUNIT_LOG_ERROR, stderr, "%s requires an argument", argv[arg]);
goto cleanup;
}
if (strcmp(argv[arg + 1], "debug") == 0)
level = MUNIT_LOG_DEBUG;
else if (strcmp(argv[arg + 1], "info") == 0)
level = MUNIT_LOG_INFO;
else if (strcmp(argv[arg + 1], "warning") == 0)
level = MUNIT_LOG_WARNING;
else if (strcmp(argv[arg + 1], "error") == 0)
level = MUNIT_LOG_ERROR;
else {
munit_logf_internal(MUNIT_LOG_ERROR, stderr, "invalid value ('%s') passed to %s", argv[arg + 1], argv[arg]);
goto cleanup;
}
if (strcmp("log-visible", argv[arg] + 2) == 0)
munit_log_level_visible = level;
else
munit_log_level_fatal = level;
arg++;
} else if (strcmp("list", argv[arg] + 2) == 0) {
munit_suite_list_tests(suite, 0, NULL);
result = EXIT_SUCCESS;
goto cleanup;
} else if (strcmp("list-params", argv[arg] + 2) == 0) {
munit_suite_list_tests(suite, 1, NULL);
result = EXIT_SUCCESS;
goto cleanup;
} else {
argument = munit_arguments_find(arguments, argv[arg] + 2);
if (argument == NULL) {
munit_logf_internal(MUNIT_LOG_ERROR, stderr, "unknown argument ('%s')", argv[arg]);
goto cleanup;
}
if (!argument->parse_argument(suite, user_data, &arg, argc, argv))
goto cleanup;
}
} else {
runner_tests = realloc((void*) runner.tests, sizeof(char*) * (tests_size + 2));
if (runner_tests == NULL) {
munit_log_internal(MUNIT_LOG_ERROR, stderr, "failed to allocate memory");
goto cleanup;
}
runner.tests = runner_tests;
runner.tests[tests_size++] = argv[arg];
runner.tests[tests_size] = NULL;
}
}
fflush(stderr);
fprintf(MUNIT_OUTPUT_FILE, "Running test suite with seed 0x%08" PRIx32 "...\n", runner.seed);
munit_test_runner_run(&runner);
tests_run = runner.report.successful + runner.report.failed + runner.report.errored;
tests_total = tests_run + runner.report.skipped;
if (tests_run == 0) {
fprintf(stderr, "No tests run, %d (100%%) skipped.\n", runner.report.skipped);
} else {
fprintf(MUNIT_OUTPUT_FILE, "%d of %d (%0.0f%%) tests successful, %d (%0.0f%%) test skipped.\n",
runner.report.successful, tests_run,
(((double) runner.report.successful) / ((double) tests_run)) * 100.0,
runner.report.skipped,
(((double) runner.report.skipped) / ((double) tests_total)) * 100.0);
}
if (runner.report.failed == 0 && runner.report.errored == 0) {
result = EXIT_SUCCESS;
}
cleanup:
free(runner.parameters);
free((void*) runner.tests);
return result;
}
int
munit_suite_main(const MunitSuite* suite, void* user_data,
int argc, char* const argv[MUNIT_ARRAY_PARAM(argc + 1)]) {
return munit_suite_main_custom(suite, user_data, argc, argv, NULL);
}
|
rose_dep_distance.c | /*
*Test dependence distance
* */
void foo()
{
int i;
int a[100];
/* Constant offset*/
for (i = 0; i <= 98; i += 1) {
a[i + 3] = a[i - 5] + 1;
}
}
void foo2(int j,int k)
{
int i;
int a[100];
/*variable offset*/
for (i = 0; i <= 98; i += 1) {
a[i + j] = a[i + k] + 1;
}
}
int b[100][100];
void foo3()
{
int i;
int j;
/*two level with constant offset*/
#pragma omp parallel for private (i,j)
for (i = 1; i <= 99; i += 1) {
for (j = 1; j <= 99; j += 1) {
b[i][j] = b[i][j - 1] + 1;
}
}
}
|
ft_ao.c | /* Copyright 2014-2018 The PySCF Developers. All Rights Reserved.
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.
*
* Author: Qiming Sun <osirpt.sun@gmail.com>
*/
#include <stdlib.h>
#include <string.h>
#include <complex.h>
#include <assert.h>
#include "config.h"
#include "cint.h"
#include "gto/ft_ao.h"
#include "vhf/fblas.h"
#define INTBUFMAX 16000
#define IMGBLK 80
#define OF_CMPLX 2
#define MIN(X,Y) ((X)<(Y)?(X):(Y))
#define MAX(X,Y) ((X)>(Y)?(X):(Y))
int PBCsizeof_env(int *shls_slice,
int *atm, int natm, int *bas, int nbas, double *env);
static void shift_bas(double *env_loc, double *env, double *Ls, int ptr, int iL)
{
env_loc[ptr+0] = env[ptr+0] + Ls[iL*3+0];
env_loc[ptr+1] = env[ptr+1] + Ls[iL*3+1];
env_loc[ptr+2] = env[ptr+2] + Ls[iL*3+2];
}
/*
* Multiple k-points
*/
static void _ft_fill_k(int (*intor)(), int (*eval_aopair)(), void (*eval_gz)(),
void (*fsort)(), double complex *out, int nkpts,
int comp, int nimgs, int blksize, int ish, int jsh,
double complex *buf, double *env_loc, double *Ls,
double complex *expkL, int *shls_slice, int *ao_loc,
double *sGv, double *b, int *sgxyz, int *gs, int nGv,
int *atm, int natm, int *bas, int nbas, double *env)
{
const int ish0 = shls_slice[0];
const int jsh0 = shls_slice[2];
ish += ish0;
jsh += jsh0;
const int di = ao_loc[ish+1] - ao_loc[ish];
const int dj = ao_loc[jsh+1] - ao_loc[jsh];
const int dij = di * dj;
const char TRANS_N = 'N';
const double complex Z1 = 1;
int jptrxyz = atm[PTR_COORD+bas[ATOM_OF+jsh*BAS_SLOTS]*ATM_SLOTS];
int shls[2] = {ish, jsh};
int dims[2] = {di, dj};
double complex *bufk = buf;
double complex *bufL = buf + dij*blksize * comp * nkpts;
double complex *pbuf;
int gs0, gs1, dg, dijg, empty;
int jL0, jLcount, jL;
int i;
for (gs0 = 0; gs0 < nGv; gs0 += blksize) {
gs1 = MIN(gs0+blksize, nGv);
dg = gs1 - gs0;
dijg = dij * dg * comp;
for (i = 0; i < dijg*nkpts; i++) {
bufk[i] = 0;
}
for (jL0 = 0; jL0 < nimgs; jL0 += IMGBLK) {
jLcount = MIN(IMGBLK, nimgs-jL0);
pbuf = bufL;
for (jL = jL0; jL < jL0+jLcount; jL++) {
shift_bas(env_loc, env, Ls, jptrxyz, jL);
if ((*intor)(pbuf, shls, dims, eval_aopair, eval_gz,
Z1, sGv, b, sgxyz, gs, dg,
atm, natm, bas, nbas, env_loc)) {
} else {
for (i = 0; i < dijg; i++) {
pbuf[i] = 0;
}
}
pbuf += dijg;
}
zgemm_(&TRANS_N, &TRANS_N, &dijg, &nkpts, &jLcount,
&Z1, bufL, &dijg, expkL+jL0, &nimgs,
&Z1, bufk, &dijg);
}
(*fsort)(out, bufk, shls_slice, ao_loc,
nkpts, comp, nGv, ish, jsh, gs0, gs1);
sGv += dg * 3;
if (sgxyz != NULL) {
sgxyz += dg * 3;
}
}
}
/*
* Single k-point
*/
static void _ft_fill_nk1(int (*intor)(), int (*eval_aopair)(), void (*eval_gz)(),
void (*fsort)(), double complex *out, int nkpts,
int comp, int nimgs, int blksize, int ish, int jsh,
double complex *buf, double *env_loc, double *Ls,
double complex *expkL, int *shls_slice, int *ao_loc,
double *sGv, double *b, int *sgxyz, int *gs, int nGv,
int *atm, int natm, int *bas, int nbas, double *env)
{
const int ish0 = shls_slice[0];
const int jsh0 = shls_slice[2];
ish += ish0;
jsh += jsh0;
const int di = ao_loc[ish+1] - ao_loc[ish];
const int dj = ao_loc[jsh+1] - ao_loc[jsh];
const int dij = di * dj;
int jptrxyz = atm[PTR_COORD+bas[ATOM_OF+jsh*BAS_SLOTS]*ATM_SLOTS];
int shls[2] = {ish, jsh};
int dims[2] = {di, dj};
double complex *bufk = buf;
double complex *bufL = buf + dij*blksize * comp;
int gs0, gs1, dg, jL, i;
size_t dijg;
for (gs0 = 0; gs0 < nGv; gs0 += blksize) {
gs1 = MIN(gs0+blksize, nGv);
dg = gs1 - gs0;
dijg = dij * dg * comp;
for (i = 0; i < dijg; i++) {
bufk[i] = 0;
}
for (jL = 0; jL < nimgs; jL++) {
shift_bas(env_loc, env, Ls, jptrxyz, jL);
if ((*intor)(bufL, shls, dims, eval_aopair, eval_gz,
expkL[jL], sGv, b, sgxyz, gs, dg,
atm, natm, bas, nbas, env_loc)) {
for (i = 0; i < dijg; i++) {
bufk[i] += bufL[i];
}
}
}
(*fsort)(out, bufk, shls_slice, ao_loc,
nkpts, comp, nGv, ish, jsh, gs0, gs1);
sGv += dg * 3;
if (sgxyz != NULL) {
sgxyz += dg * 3;
}
}
}
static void sort_s1(double complex *out, double complex *in,
int *shls_slice, int *ao_loc, int nkpts, int comp,
int nGv, int ish, int jsh, int gs0, int gs1)
{
const size_t NGv = nGv;
const int ish0 = shls_slice[0];
const int ish1 = shls_slice[1];
const int jsh0 = shls_slice[2];
const int jsh1 = shls_slice[3];
const size_t naoi = ao_loc[ish1] - ao_loc[ish0];
const size_t naoj = ao_loc[jsh1] - ao_loc[jsh0];
const size_t nijg = naoi * naoj * NGv;
const int di = ao_loc[ish+1] - ao_loc[ish];
const int dj = ao_loc[jsh+1] - ao_loc[jsh];
const int ip = ao_loc[ish] - ao_loc[ish0];
const int jp = ao_loc[jsh] - ao_loc[jsh0];
const int dg = gs1 - gs0;
const size_t dijg = di * dj * dg;
out += (ip * naoj + jp) * NGv + gs0;
int i, j, n, ic, kk;
double complex *pin, *pout;
for (kk = 0; kk < nkpts; kk++) {
for (ic = 0; ic < comp; ic++) {
for (j = 0; j < dj; j++) {
for (i = 0; i < di; i++) {
pout = out + (i*naoj+j) * NGv;
pin = in + (j*di+i) * dg;
for (n = 0; n < dg; n++) {
pout[n] = pin[n];
}
} }
out += nijg;
in += dijg;
} }
}
static void sort_s2_igtj(double complex *out, double complex *in,
int *shls_slice, int *ao_loc, int nkpts, int comp,
int nGv, int ish, int jsh, int gs0, int gs1)
{
const size_t NGv = nGv;
const int ish0 = shls_slice[0];
const int ish1 = shls_slice[1];
const int jsh0 = shls_slice[2];
const size_t off0 = ao_loc[ish0] * (ao_loc[ish0] + 1) / 2;
const size_t nij = ao_loc[ish1] * (ao_loc[ish1] + 1) / 2 - off0;
const size_t nijg = nij * NGv;
const int di = ao_loc[ish+1] - ao_loc[ish];
const int dj = ao_loc[jsh+1] - ao_loc[jsh];
const int dij = di * dj;
const int dg = gs1 - gs0;
const size_t dijg = dij * dg;
const int jp = ao_loc[jsh] - ao_loc[jsh0];
out += (ao_loc[ish]*(ao_loc[ish]+1)/2-off0 + jp) * NGv + gs0;
const int ip1 = ao_loc[ish] + 1;
int i, j, n, ic, kk;
double complex *pin, *pout;
for (kk = 0; kk < nkpts; kk++) {
for (ic = 0; ic < comp; ic++) {
pout = out;
for (i = 0; i < di; i++) {
for (j = 0; j < dj; j++) {
pin = in + (j*di+i) * dg;
for (n = 0; n < dg; n++) {
pout[j*NGv+n] = pin[n];
}
}
pout += (ip1 + i) * NGv;
}
out += nijg;
in += dijg;
} }
}
static void sort_s2_ieqj(double complex *out, double complex *in,
int *shls_slice, int *ao_loc, int nkpts, int comp,
int nGv, int ish, int jsh, int gs0, int gs1)
{
const size_t NGv = nGv;
const int ish0 = shls_slice[0];
const int ish1 = shls_slice[1];
const int jsh0 = shls_slice[2];
const size_t off0 = ao_loc[ish0] * (ao_loc[ish0] + 1) / 2;
const size_t nij = ao_loc[ish1] * (ao_loc[ish1] + 1) / 2 - off0;
const size_t nijg = nij * NGv;
const int di = ao_loc[ish+1] - ao_loc[ish];
const int dj = ao_loc[jsh+1] - ao_loc[jsh];
const int dij = di * dj;
const int dg = gs1 - gs0;
const size_t dijg = dij * dg;
const int jp = ao_loc[jsh] - ao_loc[jsh0];
out += (ao_loc[ish]*(ao_loc[ish]+1)/2-off0 + jp) * NGv + gs0;
const int ip1 = ao_loc[ish] + 1;
int i, j, n, ic, kk;
double complex *pin, *pout;
for (kk = 0; kk < nkpts; kk++) {
for (ic = 0; ic < comp; ic++) {
pout = out;
for (i = 0; i < di; i++) {
for (j = 0; j <= i; j++) {
pin = in + (j*di+i) * dg;
for (n = 0; n < dg; n++) {
pout[j*NGv+n] = pin[n];
}
}
pout += (ip1 + i) * NGv;
}
out += nijg;
in += dijg;
} }
}
void PBC_ft_fill_ks1(int (*intor)(), int (*eval_aopair)(), void (*eval_gz)(),
double complex *out, int nkpts, int comp, int nimgs,
int blksize, int ish, int jsh,
double complex *buf, double *env_loc, double *Ls,
double complex *expkL, int *shls_slice, int *ao_loc,
double *sGv, double *b, int *sgxyz, int *gs, int nGv,
int *atm, int natm, int *bas, int nbas, double *env)
{
_ft_fill_k(intor, eval_aopair, eval_gz, &sort_s1,
out, nkpts, comp, nimgs, blksize, ish, jsh,
buf, env_loc, Ls, expkL, shls_slice, ao_loc,
sGv, b, sgxyz, gs, nGv, atm, natm, bas, nbas, env);
}
void PBC_ft_fill_ks2(int (*intor)(), int (*eval_aopair)(), void (*eval_gz)(),
double complex *out, int nkpts, int comp, int nimgs,
int blksize, int ish, int jsh,
double complex *buf, double *env_loc, double *Ls,
double complex *expkL, int *shls_slice, int *ao_loc,
double *sGv, double *b, int *sgxyz, int *gs, int nGv,
int *atm, int natm, int *bas, int nbas, double *env)
{
int ip = ish + shls_slice[0];
int jp = jsh + shls_slice[2] - nbas;
if (ip > jp) {
_ft_fill_k(intor, eval_aopair, eval_gz, &sort_s2_igtj,
out, nkpts, comp, nimgs, blksize, ish, jsh,
buf, env_loc, Ls, expkL, shls_slice, ao_loc,
sGv, b, sgxyz, gs, nGv, atm, natm, bas, nbas, env);
} else if (ip == jp) {
_ft_fill_k(intor, eval_aopair, eval_gz, &sort_s2_ieqj,
out, nkpts, comp, nimgs, blksize, ish, jsh,
buf, env_loc, Ls, expkL, shls_slice, ao_loc,
sGv, b, sgxyz, gs, nGv, atm, natm, bas, nbas, env);
}
}
void PBC_ft_fill_nk1s1(int (*intor)(), int (*eval_aopair)(), void (*eval_gz)(),
double complex *out, int nkpts, int comp, int nimgs,
int blksize, int ish, int jsh,
double complex *buf, double *env_loc, double *Ls,
double complex *expkL, int *shls_slice, int *ao_loc,
double *sGv, double *b, int *sgxyz, int *gs, int nGv,
int *atm, int natm, int *bas, int nbas, double *env)
{
_ft_fill_nk1(intor, eval_aopair, eval_gz, &sort_s1,
out, nkpts, comp, nimgs, blksize, ish, jsh,
buf, env_loc, Ls, expkL, shls_slice, ao_loc,
sGv, b, sgxyz, gs, nGv, atm, natm, bas, nbas, env);
}
void PBC_ft_fill_nk1s1hermi(int (*intor)(), int (*eval_aopair)(), void (*eval_gz)(),
double complex *out, int nkpts, int comp, int nimgs,
int blksize, int ish, int jsh,
double complex *buf, double *env_loc, double *Ls,
double complex *expkL, int *shls_slice, int *ao_loc,
double *sGv, double *b, int *sgxyz, int *gs, int nGv,
int *atm, int natm, int *bas, int nbas, double *env)
{
int ip = ish + shls_slice[0];
int jp = jsh + shls_slice[2] - nbas;
if (ip >= jp) {
_ft_fill_nk1(intor, eval_aopair, eval_gz, &sort_s1,
out, nkpts, comp, nimgs, blksize, ish, jsh,
buf, env_loc, Ls, expkL, shls_slice, ao_loc,
sGv, b, sgxyz, gs, nGv, atm, natm, bas, nbas, env);
}
}
void PBC_ft_fill_nk1s2(int (*intor)(), int (*eval_aopair)(), void (*eval_gz)(),
double complex *out, int nkpts, int comp, int nimgs,
int blksize, int ish, int jsh,
double complex *buf, double *env_loc, double *Ls,
double complex *expkL, int *shls_slice, int *ao_loc,
double *sGv, double *b, int *sgxyz, int *gs, int nGv,
int *atm, int natm, int *bas, int nbas, double *env)
{
int ip = ish + shls_slice[0];
int jp = jsh + shls_slice[2] - nbas;
if (ip > jp) {
_ft_fill_nk1(intor, eval_aopair, eval_gz, &sort_s2_igtj,
out, nkpts, comp, nimgs, blksize, ish, jsh,
buf, env_loc, Ls, expkL, shls_slice, ao_loc,
sGv, b, sgxyz, gs, nGv, atm, natm, bas, nbas, env);
} else if (ip == jp) {
_ft_fill_nk1(intor, eval_aopair, eval_gz, &sort_s2_ieqj,
out, nkpts, comp, nimgs, blksize, ish, jsh,
buf, env_loc, Ls, expkL, shls_slice, ao_loc,
sGv, b, sgxyz, gs, nGv, atm, natm, bas, nbas, env);
}
}
static int subgroupGv(double *sGv, int *sgxyz, double *Gv, int *gxyz,
int nGv, int bufsize, int *shls_slice, int *ao_loc,
int *atm, int natm, int *bas, int nbas, double *env)
{
int i;
int dimax = 0;
int djmax = 0;
for (i = shls_slice[0]; i < shls_slice[1]; i++) {
dimax = MAX(dimax, ao_loc[i+1]-ao_loc[i]);
}
for (i = shls_slice[2]; i < shls_slice[3]; i++) {
djmax = MAX(djmax, ao_loc[i+1]-ao_loc[i]);
}
int dij = dimax * djmax;
int gblksize = 0xfffffff8 & (bufsize / dij);
int gs0, dg;
for (gs0 = 0; gs0 < nGv; gs0 += gblksize) {
dg = MIN(nGv-gs0, gblksize);
for (i = 0; i < 3; i++) {
memcpy(sGv+dg*i, Gv+nGv*i+gs0, sizeof(double)*dg);
}
sGv += dg * 3;
if (gxyz != NULL) {
for (i = 0; i < 3; i++) {
memcpy(sgxyz+dg*i, gxyz+nGv*i+gs0, sizeof(int)*dg);
}
sgxyz += dg * 3;
}
}
return gblksize;
}
void PBC_ft_latsum_drv(int (*intor)(), void (*eval_gz)(), void (*fill)(),
double complex *out, int nkpts, int comp, int nimgs,
double *Ls, double complex *expkL,
int *shls_slice, int *ao_loc,
double *Gv, double *b, int *gxyz, int *gs, int nGv,
int *atm, int natm, int *bas, int nbas, double *env)
{
const int ish0 = shls_slice[0];
const int ish1 = shls_slice[1];
const int jsh0 = shls_slice[2];
const int jsh1 = shls_slice[3];
const int nish = ish1 - ish0;
const int njsh = jsh1 - jsh0;
double *sGv = malloc(sizeof(double) * nGv * 3);
int *sgxyz = NULL;
if (gxyz != NULL) {
sgxyz = malloc(sizeof(int) * nGv * 3);
}
int blksize;
if (fill == &PBC_ft_fill_nk1s1 || fill == &PBC_ft_fill_nk1s2 ||
fill == &PBC_ft_fill_nk1s1hermi) {
blksize = subgroupGv(sGv, sgxyz, Gv, gxyz, nGv, INTBUFMAX*IMGBLK/2,
shls_slice, ao_loc, atm, natm, bas, nbas, env);
} else {
blksize = subgroupGv(sGv, sgxyz, Gv, gxyz, nGv, INTBUFMAX,
shls_slice, ao_loc, atm, natm, bas, nbas, env);
}
int (*eval_aopair)() = NULL;
if (intor != >O_ft_ovlp_cart && intor != >O_ft_ovlp_sph) {
eval_aopair = >O_aopair_lazy_contract;
}
#pragma omp parallel default(none) \
shared(intor, eval_aopair, eval_gz, fill, out, nkpts, comp, nimgs, \
Ls, expkL, shls_slice, ao_loc, sGv, b, sgxyz, gs, nGv,\
atm, natm, bas, nbas, env, blksize)
{
int i, j, ij;
int nenv = PBCsizeof_env(shls_slice, atm, natm, bas, nbas, env);
nenv = MAX(nenv, PBCsizeof_env(shls_slice+2, atm, natm, bas, nbas, env));
double *env_loc = malloc(sizeof(double)*nenv);
memcpy(env_loc, env, sizeof(double)*nenv);
size_t count = nkpts + IMGBLK;
double complex *buf = malloc(sizeof(double complex)*count*INTBUFMAX*comp);
#pragma omp for schedule(dynamic)
for (ij = 0; ij < nish*njsh; ij++) {
i = ij / njsh;
j = ij % njsh;
(*fill)(intor, eval_aopair, eval_gz,
out, nkpts, comp, nimgs, blksize, i, j,
buf, env_loc, Ls, expkL, shls_slice, ao_loc,
sGv, b, sgxyz, gs, nGv, atm, natm, bas, nbas, env);
}
free(buf);
free(env_loc);
}
free(sGv);
if (sgxyz != NULL) {
free(sgxyz);
}
}
|
gemm.c | #include "gemm.h"
#include "utils.h"
#include "cuda.h"
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
// > Mixed precision functions
#ifdef GPU
extern void parse_output_conv_layer_gpu(int TA, int TB, int M, int N, int K, float *C);
void gemm_gpu(int TA, int TB, int M, int N, int K, float ALPHA, float *A_gpu, int lda, float *B_gpu, int ldb, float BETA, float *C_gpu, int ldc) {
cublasHandle_t handle = blas_handle();
cudaError_t status = (cudaError_t)cublasSgemm(handle, (TB ? CUBLAS_OP_T : CUBLAS_OP_N),
(TA ? CUBLAS_OP_T : CUBLAS_OP_N), N, M, K, &ALPHA, B_gpu, ldb, A_gpu, lda, &BETA, C_gpu, ldc);
check_error(status);
parse_output_conv_layer_gpu(TA, TB, M, N, K, C_gpu);
}
void gemm_gpu(int TA, int TB, int M, int N, int K, float ALPHA, double *A_gpu, int lda, double *B_gpu, int ldb, float BETA, double *C_gpu, int ldc) {
cublasHandle_t handle = blas_handle();
double alpha = ALPHA;
double beta = BETA;
cudaError_t status = (cudaError_t)cublasDgemm(handle, (TB ? CUBLAS_OP_T : CUBLAS_OP_N),
(TA ? CUBLAS_OP_T : CUBLAS_OP_N), N, M, K, &alpha, B_gpu, ldb, A_gpu, lda, &beta, C_gpu, ldc);
check_error(status);
}
void gemm_gpu(int TA, int TB, int M, int N, int K, float ALPHA, half_host *A_gpu, int lda, half_host *B_gpu, int ldb, float BETA, half_host *C_gpu, int ldc) {
cublasHandle_t handle = blas_handle();
half_host alpha = half_host(ALPHA);
half_host beta = half_host(BETA);
cudaError_t status = (cudaError_t)cublasHgemm(handle, (TB ? CUBLAS_OP_T : CUBLAS_OP_N),
(TA ? CUBLAS_OP_T : CUBLAS_OP_N), N, M, K, (half_device*)(&alpha),
(half_device*)B_gpu, ldb, (half_device*)A_gpu, lda, (half_device*)(&beta), (half_device*)C_gpu, ldc);
check_error(status);
}
#endif
// > General functions
void gemm_bin(int M, int N, int K, float ALPHA,
char *A, int lda,
real *B, int ldb,
real *C, int ldc)
{
int i,j,k;
for(i = 0; i < M; ++i){
for(k = 0; k < K; ++k){
char A_PART = A[i*lda+k];
if(A_PART){
for(j = 0; j < N; ++j){
C[i*ldc+j] += B[k*ldb+j];
}
} else {
for(j = 0; j < N; ++j){
C[i*ldc+j] -= B[k*ldb+j];
}
}
}
}
}
real *random_matrix(int rows, int cols)
{
int i;
real *m = (real*)calloc(rows*cols, sizeof(real));
for(i = 0; i < rows*cols; ++i){
m[i] = (float)rand()/RAND_MAX;
}
return m;
}
void time_random_matrix(int TA, int TB, int m, int k, int n)
{
real *a;
if(!TA) a = random_matrix(m,k);
else a = random_matrix(k,m);
int lda = (!TA)?k:m;
real *b;
if(!TB) b = random_matrix(k,n);
else b = random_matrix(n,k);
int ldb = (!TB)?n:k;
real *c = random_matrix(m,n);
int i;
clock_t start = clock(), end;
for(i = 0; i<10; ++i){
gemm_cpu(TA,TB,m,n,k,1,a,lda,b,ldb,1,c,n);
}
end = clock();
printf("Matrix Multiplication %dx%d * %dx%d, TA=%d, TB=%d: %lf ms\n",m,k,k,n, TA, TB, (float)(end-start)/CLOCKS_PER_SEC);
free(a);
free(b);
free(c);
}
void gemm(int TA, int TB, int M, int N, int K, float ALPHA,
real *A, int lda,
real *B, int ldb,
float BETA,
real *C, int ldc)
{
gemm_cpu( TA, TB, M, N, K, ALPHA,A,lda, B, ldb,BETA,C,ldc);
}
void gemm_nn(int M, int N, int K, float ALPHA,
real *A, int lda,
real *B, int ldb,
real *C, int ldc)
{
int i,j,k;
#pragma omp parallel for
for(i = 0; i < M; ++i){
for(k = 0; k < K; ++k){
register float A_PART = ALPHA*A[i*lda+k];
for(j = 0; j < N; ++j){
C[i*ldc+j] += A_PART*B[k*ldb+j];
}
}
}
}
void gemm_nt(int M, int N, int K, float ALPHA,
real *A, int lda,
real *B, int ldb,
real *C, int ldc)
{
int i,j,k;
#pragma omp parallel for
for(i = 0; i < M; ++i){
for(j = 0; j < N; ++j){
register float sum = 0;
for(k = 0; k < K; ++k){
sum += ALPHA*A[i*lda+k]*B[j*ldb + k];
}
C[i*ldc+j] += sum;
}
}
}
void gemm_tn(int M, int N, int K, float ALPHA,
real *A, int lda,
real *B, int ldb,
real *C, int ldc)
{
int i,j,k;
#pragma omp parallel for
for(i = 0; i < M; ++i){
for(k = 0; k < K; ++k){
register float A_PART = ALPHA*A[k*lda+i];
for(j = 0; j < N; ++j){
C[i*ldc+j] += A_PART*B[k*ldb+j];
}
}
}
}
void gemm_tt(int M, int N, int K, float ALPHA,
real *A, int lda,
real *B, int ldb,
real *C, int ldc)
{
int i,j,k;
#pragma omp parallel for
for(i = 0; i < M; ++i){
for(j = 0; j < N; ++j){
register float sum = 0;
for(k = 0; k < K; ++k){
sum += ALPHA*A[i+k*lda]*B[k+j*ldb];
}
C[i*ldc+j] += sum;
}
}
}
void gemm_cpu(int TA, int TB, int M, int N, int K, float ALPHA,
real *A, int lda,
real *B, int ldb,
float BETA,
real *C, int ldc)
{
//printf("cpu: %d %d %d %d %d %f %d %d %f %d\n",TA, TB, M, N, K, ALPHA, lda, ldb, BETA, ldc);
int i, j;
for(i = 0; i < M; ++i){
for(j = 0; j < N; ++j){
C[i*ldc + j] *= BETA;
}
}
if(!TA && !TB)
gemm_nn(M, N, K, ALPHA,A,lda, B, ldb,C,ldc);
else if(TA && !TB)
gemm_tn(M, N, K, ALPHA,A,lda, B, ldb,C,ldc);
else if(!TA && TB)
gemm_nt(M, N, K, ALPHA,A,lda, B, ldb,C,ldc);
else
gemm_tt(M, N, K, ALPHA,A,lda, B, ldb,C,ldc);
}
#ifdef GPU
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
void time_gpu_random_matrix(int TA, int TB, int m, int k, int n)
{
real *a;
if(!TA) a = random_matrix(m,k);
else a = random_matrix(k,m);
int lda = (!TA)?k:m;
real *b;
if(!TB) b = random_matrix(k,n);
else b = random_matrix(n,k);
int ldb = (!TB)?n:k;
real *c = random_matrix(m,n);
int i;
clock_t start = clock(), end;
for(i = 0; i<32; ++i){
gemm_gpu(TA,TB,m,n,k,1,a,lda,b,ldb,1,c,n);
}
end = clock();
printf("Matrix Multiplication %dx%d * %dx%d, TA=%d, TB=%d: %lf s\n",m,k,k,n, TA, TB, (float)(end-start)/CLOCKS_PER_SEC);
free(a);
free(b);
free(c);
}
void time_gpu(int TA, int TB, int m, int k, int n)
{
int iter = 10;
real *a = random_matrix(m,k);
real *b = random_matrix(k,n);
int lda = (!TA)?k:m;
int ldb = (!TB)?n:k;
real *c = random_matrix(m,n);
real *a_cl = cuda_make_array(a, m*k);
real *b_cl = cuda_make_array(b, k*n);
real *c_cl = cuda_make_array(c, m*n);
int i;
clock_t start = clock(), end;
for(i = 0; i<iter; ++i){
gemm_gpu(TA,TB,m,n,k,1,a_cl,lda,b_cl,ldb,1,c_cl,n);
cudaThreadSynchronize();
}
double flop = ((double)m)*n*(2.*k + 2.)*iter;
double gflop = flop/pow(10., 9);
end = clock();
double seconds = sec(end-start);
printf("Matrix Multiplication %dx%d * %dx%d, TA=%d, TB=%d: %lf s, %lf GFLOPS\n",m,k,k,n, TA, TB, seconds, gflop/seconds);
cuda_free(a_cl);
cuda_free(b_cl);
cuda_free(c_cl);
free(a);
free(b);
free(c);
}
void test_gpu_accuracy(int TA, int TB, int m, int k, int n)
{
srand(0);
real *a;
if(!TA) a = random_matrix(m,k);
else a = random_matrix(k,m);
int lda = (!TA)?k:m;
real *b;
if(!TB) b = random_matrix(k,n);
else b = random_matrix(n,k);
int ldb = (!TB)?n:k;
real *c = random_matrix(m,n);
real *c_gpu = random_matrix(m,n);
memset(c, 0, m*n*sizeof(real));
memset(c_gpu, 0, m*n*sizeof(real));
int i;
//pm(m,k,b);
gemm_gpu(TA,TB,m,n,k,1,a,lda,b,ldb,1,c_gpu,n);
//printf("GPU\n");
//pm(m, n, c_gpu);
gemm_cpu(TA,TB,m,n,k,1,a,lda,b,ldb,1,c,n);
//printf("\n\nCPU\n");
//pm(m, n, c);
double sse = 0;
for(i = 0; i < m*n; ++i) {
//printf("%f %f\n", c[i], c_gpu[i]);
sse += pow(c[i]-c_gpu[i], 2);
}
printf("Matrix Multiplication %dx%d * %dx%d, TA=%d, TB=%d: %g SSE\n",m,k,k,n, TA, TB, sse/(m*n));
free(a);
free(b);
free(c);
free(c_gpu);
}
int test_gpu_blas()
{
/*
test_gpu_accuracy(0,0,10,576,75);
test_gpu_accuracy(0,0,17,10,10);
test_gpu_accuracy(1,0,17,10,10);
test_gpu_accuracy(0,1,17,10,10);
test_gpu_accuracy(1,1,17,10,10);
test_gpu_accuracy(0,0,1000,10,100);
test_gpu_accuracy(1,0,1000,10,100);
test_gpu_accuracy(0,1,1000,10,100);
test_gpu_accuracy(1,1,1000,10,100);
test_gpu_accuracy(0,0,10,10,10);
time_gpu(0,0,64,2916,363);
time_gpu(0,0,64,2916,363);
time_gpu(0,0,64,2916,363);
time_gpu(0,0,192,729,1600);
time_gpu(0,0,384,196,1728);
time_gpu(0,0,256,196,3456);
time_gpu(0,0,256,196,2304);
time_gpu(0,0,128,4096,12544);
time_gpu(0,0,128,4096,4096);
*/
time_gpu(0,0,64,75,12544);
time_gpu(0,0,64,75,12544);
time_gpu(0,0,64,75,12544);
time_gpu(0,0,64,576,12544);
time_gpu(0,0,256,2304,784);
time_gpu(1,1,2304,256,784);
time_gpu(0,0,512,4608,196);
time_gpu(1,1,4608,512,196);
return 0;
}
#endif
|
GB_unop__frexpx_fp32_fp32.c | //------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_atomics.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB (_unop_apply__frexpx_fp32_fp32)
// op(A') function: GB (_unop_tran__frexpx_fp32_fp32)
// C type: float
// A type: float
// cast: float cij = aij
// unaryop: cij = GB_frexpxf (aij)
#define GB_ATYPE \
float
#define GB_CTYPE \
float
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
float aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = GB_frexpxf (x) ;
// casting
#define GB_CAST(z, aij) \
float z = aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
float aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
float z = aij ; \
Cx [pC] = GB_frexpxf (z) ; \
}
// true if operator is the identity op with no typecasting
#define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \
0
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_FREXPX || GxB_NO_FP32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__frexpx_fp32_fp32)
(
float *Cx, // Cx and Ax may be aliased
const float *Ax,
const int8_t *restrict Ab, // A->b if A is bitmap
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
// TODO: if OP is ONE and uniform-valued matrices are exploited, then
// do this in O(1) time
if (Ab == NULL)
{
#if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST )
GB_memcpy (Cx, Ax, anz * sizeof (float), nthreads) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
float aij = Ax [p] ;
float z = aij ;
Cx [p] = GB_frexpxf (z) ;
}
#endif
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
float aij = Ax [p] ;
float z = aij ;
Cx [p] = GB_frexpxf (z) ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__frexpx_fp32_fp32)
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
DRB064-outeronly2-orig-no.c | /*
Copyright (c) 2017, Lawrence Livermore National Security, LLC.
Produced at the Lawrence Livermore National Laboratory
Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund,
Markus Schordan, and Ian Karlin
(email: liao6@llnl.gov, lin32@llnl.gov, asplund1@llnl.gov,
schordan1@llnl.gov, karlin1@llnl.gov)
LLNL-CODE-732144
All rights reserved.
This file is part of DataRaceBench. For details, see
https://github.com/LLNL/dataracebench. Please also see the LICENSE file
for our additional BSD notice.
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 disclaimer below.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the disclaimer (as noted below)
in the documentation and/or other materials provided with the
distribution.
* Neither the name of the LLNS/LLNL 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 LAWRENCE LIVERMORE NATIONAL
SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY 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.
*/
/*
Only the outmost loop can be parallelized.
The inner loop has loop carried true data dependence.
However, the loop is not parallelized so no race condition.
*/
#include <omp.h>
int n = 100;
int m = 100;
double b[100][100];
int init()
{
int i;
int j;
int k;
#pragma omp parallel for private (i,j) firstprivate (n,m)
for (i = 0; i <= n - 1; i += 1) {
#pragma omp parallel for private (j)
for (j = 0; j <= m - 1; j += 1) {
b[i][j] = (i * j);
}
}
return 0;
}
void foo(int n,int m)
{
int i;
int j;
#pragma omp parallel for private (i,j) firstprivate (n,m)
for (i = 0; i <= n - 1; i += 1) {
// Be careful about bounds of j
for (j = 1; j <= m - 1; j += 1) {
b[i][j] = b[i][j - 1];
}
}
}
int print()
{
int i;
int j;
int k;
for (i = 0; i <= n - 1; i += 1) {
for (j = 0; j <= m - 1; j += 1) {
printf("%lf\n",b[i][j]);
}
}
return 0;
}
int main()
{
init();
foo(100,100);
print();
return 0;
}
|
omp_get_num_threads.c | #include <stdio.h>
#include "omp.h"
#include "omp_testsuite.h"
int
check_omp_get_num_threads (FILE * logFile)
{
/* checks that omp_get_num_threads is equal to the number of
threads */
int nthreads = 0;
int nthreads_lib = -1;
#pragma omp parallel
{
#pragma omp critical
{
nthreads++;
}
#pragma omp single
{
nthreads_lib = omp_get_num_threads ();
}
} /* end of parallel */
return nthreads == nthreads_lib;
}
int
crosscheck_omp_get_num_threads (FILE * logFile)
{
/* checks that omp_get_num_threads is equal to the number of
threads */
int nthreads = 0;
int nthreads_lib = -1;
#pragma omp parallel
{
#pragma omp critical
{
nthreads++;
}
#pragma omp single
{
/*nthreads_lib=omp_get_num_threads(); */
}
} /* end of parallel */
return nthreads == nthreads_lib;
}
|
mppush2.c | /* C Library for Skeleton 2D Electrostatic MPI/OpenMP PIC Code */
/* written by Viktor K. Decyk, UCLA */
#include <stdlib.h>
#include <stdio.h>
#include <complex.h>
#include <math.h>
#include "mppush2.h"
#include "mpplib2.h"
/*--------------------------------------------------------------------*/
double ranorm() {
/* this program calculates a random number y from a gaussian distribution
with zero mean and unit variance, according to the method of
mueller and box:
y(k) = (-2*ln(x(k)))**1/2*sin(2*pi*x(k+1))
y(k+1) = (-2*ln(x(k)))**1/2*cos(2*pi*x(k+1)),
where x is a random number uniformly distributed on (0,1).
written for the ibm by viktor k. decyk, ucla
local data */
static int r1 = 885098780, r2 = 1824280461;
static int r4 = 1396483093, r5 = 55318673;
static int iflg = 0;
static double h1l = 65531.0, h1u = 32767.0, h2l = 65525.0;
static double r0 = 0.0;
int isc, i1;
double ranorm, r3, asc, bsc, temp;
if (iflg==1) {
ranorm = r0;
r0 = 0.0;
iflg = 0;
return ranorm;
}
isc = 65536;
asc = (double) isc;
bsc = asc*asc;
i1 = r1 - (r1/isc)*isc;
r3 = h1l*(double) r1 + asc*h1u*(double) i1;
i1 = r3/bsc;
r3 -= ((double) i1)*bsc;
bsc = 0.5*bsc;
i1 = r2/isc;
isc = r2 - i1*isc;
r0 = h1l*(double) r2 + asc*h1u*(double) isc;
asc = 1.0/bsc;
isc = r0*asc;
r2 = r0 - ((double) isc)*bsc;
r3 += (double) isc + 2.0*h1u*(double) i1;
isc = r3*asc;
r1 = r3 - ((double) isc)*bsc;
temp = sqrt(-2.0*log((((double) r1) + ((double) r2)*asc)*asc));
isc = 65536;
asc = (double) isc;
bsc = asc*asc;
i1 = r4 - (r4/isc)*isc;
r3 = h2l*(double) r4 + asc*h1u*(double) i1;
i1 = r3/bsc;
r3 -= ((double) i1)*bsc;
bsc = 0.5*bsc;
i1 = r5/isc;
isc = r5 - i1*isc;
r0 = h2l*(double) r5 + asc*h1u*(double) isc;
asc = 1.0/bsc;
isc = r0*asc;
r5 = r0 - ((double) isc)*bsc;
r3 += (double) isc + 2.0*h1u*(double) i1;
isc = r3*asc;
r4 = r3 - ((double) isc)*bsc;
r0 = 6.28318530717959*((((double) r4) + ((double) r5)*asc)*asc);
ranorm = temp*sin(r0);
r0 = temp*cos(r0);
iflg = 1;
return ranorm;
}
/*--------------------------------------------------------------------*/
void cpdicomp2l(float edges[], int *nyp, int *noff, int *nypmx,
int *nypmn, int ny, int kstrt, int nvp, int idps) {
/* this subroutine determines spatial boundaries for uniform particle
decomposition, calculates number of grid points in each spatial
region, and the offset of these grid points from the global address
nvp must be < ny. some combinations of ny and nvp result in a zero
value of nyp. this is not supported.
integer boundaries are set.
input: ny, kstrt, nvp, idps, output: edges, nyp, noff, nypmx, nypmn
edges[0] = lower boundary of particle partition
edges[1] = upper boundary of particle partition
nyp = number of primary (complete) gridpoints in particle partition
noff = lowermost global gridpoint in particle partition
nypmx = maximum size of particle partition, including guard cells
nypmn = minimum value of nyp
ny = system length in y direction
kstrt = starting data block number (processor id + 1)
nvp = number of real or virtual processors
idps = number of partition boundaries
local data */
int kb, kyp;
float at1, any;
int mypm[2], iwork2[2];
any = (float) ny;
/* determine decomposition */
kb = kstrt - 1;
kyp = (ny - 1)/nvp + 1;
at1 = (float) kyp;
edges[0] = at1*(float) kb;
if (edges[0] > any)
edges[0] = any;
*noff = edges[0];
edges[1] = at1*(float) (kb + 1);
if (edges[1] > any)
edges[1] = any;
kb = edges[1];
*nyp = kb - *noff;
/* find maximum/minimum partition size */
mypm[0] = *nyp;
mypm[1] = -(*nyp);
cppimax(mypm,iwork2,2);
*nypmx = mypm[0] + 1;
*nypmn = -mypm[1];
return;
}
/*--------------------------------------------------------------------*/
void cpdistr2(float part[], float edges[], int *npp, int nps, float vtx,
float vty, float vdx, float vdy, int npx, int npy, int nx,
int ny, int idimp, int npmax, int idps, int ipbc, int *ierr) {
/* for 2d code, this subroutine calculates initial particle co-ordinates
and velocities with uniform density and maxwellian velocity with drift
for distributed data.
input: all except part, npp, ierr, output: part, npp, ierr
part[n][0] = position x of particle n in partition
part[n][1] = position y of particle n in partition
part[n][2] = velocity vx of particle n in partition
part[n][3] = velocity vy of particle n in partition
edges[0] = lower boundary of particle partition
edges[1] = upper boundary of particle partition
npp = number of particles in partition
nps = starting address of particles in partition
vtx/vty = thermal velocity of electrons in x/y direction
vdx/vdy = drift velocity of beam electrons in x/y direction
npx/npy = initial number of particles distributed in x/y direction
nx/ny = system length in x/y direction
idimp = size of phase space = 4
npmax = maximum number of particles in each partition
idps = number of partition boundaries
ipbc = particle boundary condition = (0,1,2,3) =
(none,2d periodic,2d reflecting,mixed reflecting/periodic)
ierr = (0,1) = (no,yes) error condition exists
ranorm = gaussian random number with zero mean and unit variance
with spatial decomposition
local data */
int j, k, npt, k1, npxyp;
float edgelx, edgely, at1, at2, xt, yt, vxt, vyt;
double dnpx, dnpxy, dt1;
int ierr1[1], iwork1[1];
double sum3[3], work3[3];
*ierr = 0;
/* particle distribution constant */
dnpx = (double) npx;
/* set boundary values */
edgelx = 0.0;
edgely = 0.0;
at1 = (float) nx/(float) npx;
at2 = (float) ny/(float) npy;
if (ipbc==2) {
edgelx = 1.0;
edgely = 1.0;
at1 = (float) (nx-2)/(float) npx;
at2 = (float) (ny-2)/(float) npy;
}
else if (ipbc==3) {
edgelx = 1.0;
at1 = (float) (nx-2)/(float) npx;
}
npt = *npp;
/* uniform density profile */
for (k = 0; k < npy; k++) {
yt = edgely + at2*(((float) k) + 0.5);
for (j = 0; j < npx; j++) {
xt = edgelx + at1*(((float) j) + 0.5);
/* maxwellian velocity distribution */
vxt = vtx*ranorm();
vyt = vty*ranorm();
if ((yt >= edges[0]) && (yt < edges[1])) {
if (npt < npmax) {
k1 = idimp*npt;
part[k1] = xt;
part[1+k1] = yt;
part[2+k1] = vxt;
part[3+k1] = vyt;
npt += 1;
}
else
*ierr += 1;
}
}
}
npxyp = 0;
/* add correct drift */
sum3[0] = 0.0;
sum3[1] = 0.0;
for (j = nps-1; j < npt; j++) {
npxyp += 1;
sum3[0] += part[2+idimp*j];
sum3[1] += part[3+idimp*j];
}
sum3[2] = npxyp;
cppdsum(sum3,work3,3);
dnpxy = sum3[2];
ierr1[0] = *ierr;
cppimax(ierr1,iwork1,1);
*ierr = ierr1[0];
dt1 = 1.0/dnpxy;
sum3[0] = dt1*sum3[0] - vdx;
sum3[1] = dt1*sum3[1] - vdy;
for (j = nps-1; j < npt; j++) {
part[2+idimp*j] -= sum3[0];
part[3+idimp*j] -= sum3[1];
}
/* process errors */
dnpxy -= dnpx*(double) npy;
if (dnpxy != 0.0)
*ierr = dnpxy;
*npp = npt;
return;
}
/*--------------------------------------------------------------------*/
void cppdblkp2l(float part[], int kpic[], int npp, int noff, int *nppmx,
int idimp, int npmax, int mx, int my, int mx1,
int mxyp1, int *irc) {
/* this subroutine finds the maximum number of particles in each tile of
mx, my to calculate size of segmented particle array ppart
linear interpolation, spatial decomposition in y direction
input: all except kpic, nppmx, output: kpic, nppmx
part = input particle array
part[n][0] = position x of particle n in partition
part[n][1] = position y of particle n in partition
kpic = output number of particles per tile
nppmx = return maximum number of particles in tile
npp = number of particles in partition
noff = backmost global gridpoint in particle partition
idimp = size of phase space = 4
npmax = maximum number of particles in each partition
mx/my = number of grids in sorting cell in x and y
mx1 = (system length in x direction - 1)/mx + 1
mxyp1 = mx1*myp1, where myp1=(partition length in y direction-1)/my+1
irc = maximum overflow, returned only if error occurs, when irc > 0
local data */
int j, k, n, m, mnoff, isum, ist, npx, ierr;
mnoff = noff;
ierr = 0;
/* clear counter array */
for (k = 0; k < mxyp1; k++) {
kpic[k] = 0;
}
/* find how many particles in each tile */
for (j = 0; j < npp; j++) {
n = part[idimp*j];
m = part[1+idimp*j];
n = n/mx;
m = (m - mnoff)/my;
m = n + mx1*m;
if (m < mxyp1) {
kpic[m] += 1;
}
else {
ierr = ierr > m-mxyp1+1 ? ierr : m-mxyp1+1;
}
}
/* find maximum */
isum = 0;
npx = 0;
for (k = 0; k < mxyp1; k++) {
ist = kpic[k];
npx = npx > ist ? npx : ist;
isum += ist;
}
*nppmx = npx;
/* check for errors */
if (ierr > 0) {
*irc = ierr;
}
else if (isum != npp) {
*irc = -1;
}
return;
}
/*--------------------------------------------------------------------*/
void cpppmovin2l(float part[], float ppart[], int kpic[], int npp,
int noff, int nppmx, int idimp, int npmax, int mx,
int my, int mx1, int mxyp1, int *irc) {
/* this subroutine sorts particles by x,y grid in tiles of
mx, my and copies to segmented array ppart
linear interpolation, spatial decomposition in y direction
input: all except ppart, kpic, output: ppart, kpic
part/ppart = input/output particle arrays
part[n][0] = position x of particle n in partition
part[n][1] = position y of particle n in partition
kpic = output number of particles per tile
nppmx = maximum number of particles in tile
npp = number of particles in partition
noff = backmost global gridpoint in particle partition
idimp = size of phase space = 4
npmax = maximum number of particles in each partition
mx/my = number of grids in sorting cell in x and y
mx1 = (system length in x direction - 1)/mx + 1
mxyp1 = mx1*myp1, where myp1=(partition length in y direction-1)/my+1
irc = maximum overflow, returned only if error occurs, when irc > 0
local data */
int i, j, k, n, m, mnoff, ip, ierr;
mnoff = noff;
ierr = 0;
/* clear counter array */
for (k = 0; k < mxyp1; k++) {
kpic[k] = 0;
}
/* find addresses of particles at each tile and reorder particles */
for (j = 0; j < npp; j++) {
n = part[idimp*j];
m = part[1+idimp*j];
n = n/mx;
m = (m - mnoff)/my;
m = n + mx1*m;
ip = kpic[m];
if (ip < nppmx) {
for (i = 0; i < idimp; i++) {
ppart[i+idimp*(ip+nppmx*m)] = part[i+idimp*j]; }
}
else {
ierr = ierr > ip-nppmx+1 ? ierr : ip-nppmx+1;
}
kpic[m] = ip + 1;
}
if (ierr > 0)
*irc = ierr;
return;
}
/*--------------------------------------------------------------------*/
void cpppcheck2l(float ppart[], int kpic[], int noff, int nyp,
int idimp, int nppmx, int nx, int mx, int my, int mx1,
int myp1, int *irc) {
/* this subroutine performs a sanity check to make sure particles sorted
by x,y grid in tiles of mx, my, are all within bounds.
tiles are assumed to be arranged in 2D linear memory
input: all except irc
output: irc
ppart[k][n][0] = position x of particle n in tile k
ppart[k][n][1] = position y of particle n in tile k
kpic[k] = number of reordered output particles in tile k
noff = lowermost global gridpoint in particle partition.
nyp = number of primary (complete) gridpoints in particle partition
idimp = size of phase space = 4
nppmx = maximum number of particles in tile
nx = system length in x direction
mx/my = number of grids in sorting cell in x/y
mx1 = (system length in x direction - 1)/mx + 1
myp1 = (partition length in y direction - 1)/my + 1
irc = particle error, returned only if error occurs, when irc > 0
local data */
int mxyp1, noffp, moffp, nppp, j, k, ist, nn, mm;
float edgelx, edgely, edgerx, edgery, dx, dy;
mxyp1 = mx1*myp1;
/* loop over tiles */
#pragma omp parallel for \
private(j,k,noffp,moffp,nppp,nn,mm,ist,edgelx,edgely,edgerx,edgery,dx, \
dy)
for (k = 0; k < mxyp1; k++) {
noffp = k/mx1;
moffp = my*noffp;
noffp = mx*(k - mx1*noffp);
nppp = kpic[k];
nn = nx - noffp;
nn = mx < nn ? mx : nn;
mm = nyp - moffp;
mm = my < mm ? my : mm;
edgelx = noffp;
edgerx = noffp + nn;
edgely = noff + moffp;
edgery = noff + moffp + mm;
/* loop over particles in tile */
for (j = 0; j < nppp; j++) {
dx = ppart[idimp*(j+nppmx*k)];
dy = ppart[1+idimp*(j+nppmx*k)];
/* find particles going out of bounds */
ist = 0;
if (dx < edgelx)
ist = 1;
if (dx >= edgerx)
ist = 2;
if (dy < edgely)
ist += 3;
if (dy >= edgery)
ist += 6;
if (ist > 0)
*irc = k + 1;
}
}
return;
}
/*--------------------------------------------------------------------*/
void cppgppush2l(float ppart[], float fxy[], int kpic[], int noff,
int nyp, float qbm, float dt, float *ek, int nx,
int ny, int mx, int my, int idimp, int nppmx, int nxv,
int nypmx, int mx1, int mxyp1, int ipbc) {
/* for 2d code, this subroutine updates particle co-ordinates and
velocities using leap-frog scheme in time and first-order linear
interpolation in space, with various boundary conditions
OpenMP version using guard cells, for distributed data
data read in tiles
particles stored segmented array
42 flops/particle, 12 loads, 4 stores
input: all, output: ppart, ek
equations used are:
vx(t+dt/2) = vx(t-dt/2) + (q/m)*fx(x(t),y(t))*dt,
vy(t+dt/2) = vy(t-dt/2) + (q/m)*fy(x(t),y(t))*dt,
where q/m is charge/mass, and
x(t+dt) = x(t) + vx(t+dt/2)*dt, y(t+dt) = y(t) + vy(t+dt/2)*dt
fx(x(t),y(t)) and fy(x(t),y(t)) are approximated by interpolation from
the nearest grid points:
fx(x,y) = (1-dy)*((1-dx)*fx(n,m)+dx*fx(n+1,m)) + dy*((1-dx)*fx(n,m+1)
+ dx*fx(n+1,m+1))
fy(x,y) = (1-dy)*((1-dx)*fy(n,m)+dx*fy(n+1,m)) + dy*((1-dx)*fy(n,m+1)
+ dx*fy(n+1,m+1))
where n,m = leftmost grid points and dx = x-n, dy = y-m
ppart[m][n][0] = position x of particle n in partition in tile m
ppart[m][n][1] = position y of particle n in partition in tile m
ppart[m][n][2] = velocity vx of particle n in partition in tile m
ppart[m][n][3] = velocity vy of particle n in partition in tile m
fxy[k][j][0] = x component of force/charge at grid (j,kk)
fxy[k][j][1] = y component of force/charge at grid (j,kk)
in other words, fxy are the convolutions of the electric field
over the particle shape, where kk = k + noff
kpic = number of particles per tile
noff = lowermost global gridpoint in particle partition.
nyp = number of primary (complete) gridpoints in particle partition
qbm = particle charge/mass
dt = time interval between successive calculations
kinetic energy/mass at time t is also calculated, using
ek = .125*sum((vx(t+dt/2)+vx(t-dt/2))**2+(vy(t+dt/2)+vy(t-dt/2))**2)
nx/ny = system length in x/y direction
mx/my = number of grids in sorting cell in x/y
idimp = size of phase space = 4
nppmx = maximum number of particles in tile
nxv = first dimension of field array, must be >= nx+1
nypmx = maximum size of particle partition, including guard cells.
mx1 = (system length in x direction - 1)/mx + 1
mxyp1 = mx1*myp1, where myp1=(partition length in y direction-1)/my+1
ipbc = particle boundary condition = (0,1,2,3) =
(none,2d periodic,2d reflecting,mixed reflecting/periodic)
local data */
#define MXV 33
#define MYV 33
int noffp, moffp, npoff, nppp;
int mnoff, i, j, k, nn, mm, mxv;
float qtm, edgelx, edgely, edgerx, edgery, dxp, dyp, amx, amy;
float x, y, dx, dy, vx, vy;
float sfxy[2*MXV*MYV];
/* float sfxy[2*(mx+1)*(my+1)]; */
double sum1, sum2;
/* mxv2 = 2*MXV; */
mxv = mx + 1;
qtm = qbm*dt;
sum2 = 0.0;
/* set boundary values */
edgelx = 0.0f;
edgely = 1.0f;
edgerx = (float) (nx);
edgery = (float) (ny-1);
if ((ipbc==2) || (ipbc==3)) {
edgelx = 1.0f;
edgerx = (float) (nx-1);
}
/* error if local array is too small */
/* if ((mx >= MXV) || (my >= MYV)) */
/* return; */
/* loop over tiles */
#pragma omp parallel for \
private(i,j,k,noffp,moffp,nppp,npoff,mnoff,nn,mm,x,y,dxp,dyp,amx,amy, \
dx,dy,vx,vy,sum1,sfxy) \
reduction(+:sum2)
for (k = 0; k < mxyp1; k++) {
noffp = k/mx1;
moffp = my*noffp;
noffp = mx*(k - mx1*noffp);
nppp = kpic[k];
npoff = nppmx*k;
mnoff = moffp + noff;
/* load local fields from global array */
nn = (mx < nx-noffp ? mx : nx-noffp) + 1;
mm = (my < nyp-moffp ? my : nyp-moffp) + 1;
for (j = 0; j < mm; j++) {
for (i = 0; i < nn; i++) {
sfxy[2*(i+mxv*j)] = fxy[2*(i+noffp+nxv*(j+moffp))];
sfxy[1+2*(i+mxv*j)] = fxy[1+2*(i+noffp+nxv*(j+moffp))];
}
}
sum1 = 0.0;
/* loop over particles in tile */
for (j = 0; j < nppp; j++) {
/* find interpolation weights */
x = ppart[idimp*(j+npoff)];
y = ppart[1+idimp*(j+npoff)];
nn = x;
mm = y;
dxp = x - (float) nn;
dyp = y - (float) mm;
nn = 2*(nn - noffp) + 2*mxv*(mm - mnoff);
amx = 1.0f - dxp;
amy = 1.0f - dyp;
/* find acceleration */
dx = amx*sfxy[nn];
dy = amx*sfxy[nn+1];
dx = amy*(dxp*sfxy[nn+2] + dx);
dy = amy*(dxp*sfxy[nn+3] + dy);
nn += 2*mxv;
vx = amx*sfxy[nn];
vy = amx*sfxy[nn+1];
dx += dyp*(dxp*sfxy[nn+2] + vx);
dy += dyp*(dxp*sfxy[nn+3] + vy);
/* new velocity */
vx = ppart[2+idimp*(j+npoff)];
vy = ppart[3+idimp*(j+npoff)];
dx = vx + qtm*dx;
dy = vy + qtm*dy;
/* average kinetic energy */
vx += dx;
vy += dy;
sum1 += vx*vx + vy*vy;
ppart[2+idimp*(j+npoff)] = dx;
ppart[3+idimp*(j+npoff)] = dy;
/* new position */
dx = x + dx*dt;
dy = y + dy*dt;
/* reflecting boundary conditions */
if (ipbc==2) {
if ((dx < edgelx) || (dx >= edgerx)) {
dx = ppart[idimp*(j+npoff)];
ppart[2+idimp*(j+npoff)] = -ppart[2+idimp*(j+npoff)];
}
if ((dy < edgely) || (dy >= edgery)) {
dy = ppart[1+idimp*(j+npoff)];
ppart[3+idimp*(j+npoff)] = -ppart[3+idimp*(j+npoff)];
}
}
/* mixed reflecting/periodic boundary conditions */
else if (ipbc==3) {
if ((dx < edgelx) || (dx >= edgerx)) {
dx = ppart[idimp*(j+npoff)];
ppart[2+idimp*(j+npoff)] = -ppart[2+idimp*(j+npoff)];
}
}
/* set new position */
ppart[idimp*(j+npoff)] = dx;
ppart[1+idimp*(j+npoff)] = dy;
}
sum2 += sum1;
}
/* normalize kinetic energy */
*ek += 0.125f*sum2;
return;
#undef MXV
#undef MYV
}
/*--------------------------------------------------------------------*/
void cppgppushf2l(float ppart[], float fxy[], int kpic[], int ncl[],
int ihole[], int noff, int nyp, float qbm, float dt,
float *ek, int nx, int ny, int mx, int my, int idimp,
int nppmx, int nxv, int nypmx, int mx1, int mxyp1,
int ntmax, int *irc) {
/* for 2d code, this subroutine updates particle co-ordinates and
velocities using leap-frog scheme in time and first-order linear
interpolation in space, with periodic boundary conditions
also determines list of particles which are leaving this tile
OpenMP version using guard cells, for distributed data
data read in tiles
particles stored segmented array
42 flops/particle, 12 loads, 4 stores
input: all except ncl, ihole, irc, output: ppart, ncl, ihole, ek, irc
equations used are:
vx(t+dt/2) = vx(t-dt/2) + (q/m)*fx(x(t),y(t))*dt,
vy(t+dt/2) = vy(t-dt/2) + (q/m)*fy(x(t),y(t))*dt,
where q/m is charge/mass, and
x(t+dt) = x(t) + vx(t+dt/2)*dt, y(t+dt) = y(t) + vy(t+dt/2)*dt
fx(x(t),y(t)) and fy(x(t),y(t)) are approximated by interpolation from
the nearest grid points:
fx(x,y) = (1-dy)*((1-dx)*fx(n,m)+dx*fx(n+1,m)) + dy*((1-dx)*fx(n,m+1)
+ dx*fx(n+1,m+1))
fy(x,y) = (1-dy)*((1-dx)*fy(n,m)+dx*fy(n+1,m)) + dy*((1-dx)*fy(n,m+1)
+ dx*fy(n+1,m+1))
where n,m = leftmost grid points and dx = x-n, dy = y-m
ppart[m][n][0] = position x of particle n in partition in tile m
ppart[m][n][1] = position y of particle n in partition in tile m
ppart[m][n][2] = velocity vx of particle n in partition in tile m
ppart[m][n][3] = velocity vy of particle n in partition in tile m
fxy[k][j][0] = x component of force/charge at grid (j,kk)
fxy[k][j][1] = y component of force/charge at grid (j,kk)
in other words, fxy are the convolutions of the electric field
over the particle shape, where kk = k + noff
kpic[k] = number of particles in tile k
ncl[k][i] = number of particles going to destination i, tile k
ihole[k][:][0] = location of hole in array left by departing particle
ihole[k][:][1] = destination of particle leaving hole
ihole[k][0][0] = ih, number of holes left (error, if negative)
noff = lowermost global gridpoint in particle partition.
nyp = number of primary (complete) gridpoints in particle partition
qbm = particle charge/mass
dt = time interval between successive calculations
kinetic energy/mass at time t is also calculated, using
ek = .125*sum((vx(t+dt/2)+vx(t-dt/2))**2+(vy(t+dt/2)+vy(t-dt/2))**2)
nx/ny = system length in x/y direction
mx/my = number of grids in sorting cell in x/y
idimp = size of phase space = 4
nppmx = maximum number of particles in tile
nxv = first dimension of field array, must be >= nx+1
nypmx = maximum size of particle partition, including guard cells.
mx1 = (system length in x direction - 1)/mx + 1
mxyp1 = mx1*myp1, where myp1=(partition length in y direction-1)/my+1
ntmax = size of hole array for particles leaving tiles
irc = maximum overflow, returned only if error occurs, when irc > 0
optimized version
local data */
#define MXV 33
#define MYV 33
int noffp, moffp, npoff, nppp;
int mnoff, i, j, k, ih, nh, nn, mm, mxv;
float qtm, dxp, dyp, amx, amy;
float x, y, dx, dy, vx, vy;
float anx, any, edgelx, edgely, edgerx, edgery;
float sfxy[2*MXV*MYV];
/* float sfxy[2*(mx+1)*(my+1)]; */
double sum1, sum2;
mxv = mx + 1;
qtm = qbm*dt;
anx = (float) nx;
any = (float) ny;
sum2 = 0.0;
/* error if local array is too small */
/* if ((mx >= MXV) || (my >= MYV)) */
/* return; */
/* loop over tiles */
#pragma omp parallel for \
private(i,j,k,noffp,moffp,nppp,npoff,nn,mm,ih,nh,mnoff,x,y,dxp,dyp, \
amx,amy,dx,dy,vx,vy,edgelx,edgely,edgerx,edgery,sum1,sfxy) \
reduction(+:sum2)
for (k = 0; k < mxyp1; k++) {
noffp = k/mx1;
moffp = my*noffp;
noffp = mx*(k - mx1*noffp);
nppp = kpic[k];
npoff = nppmx*k;
nn = nx - noffp;
nn = mx < nn ? mx : nn;
mm = nyp - moffp;
mm = my < mm ? my : mm;
edgelx = noffp;
edgerx = noffp + nn;
edgely = noff + moffp;
edgery = noff + moffp + mm;
ih = 0;
nh = 0;
nn += 1;
mm += 1;
mnoff = moffp + noff;
/* load local fields from global array */
for (j = 0; j < mm; j++) {
for (i = 0; i < nn; i++) {
sfxy[2*(i+mxv*j)] = fxy[2*(i+noffp+nxv*(j+moffp))];
sfxy[1+2*(i+mxv*j)] = fxy[1+2*(i+noffp+nxv*(j+moffp))];
}
}
/* clear counters */
for (j = 0; j < 8; j++) {
ncl[j+8*k] = 0;
}
sum1 = 0.0;
/* loop over particles in tile */
for (j = 0; j < nppp; j++) {
/* find interpolation weights */
x = ppart[idimp*(j+npoff)];
y = ppart[1+idimp*(j+npoff)];
nn = x;
mm = y;
dxp = x - (float) nn;
dyp = y - (float) mm;
nn = 2*(nn - noffp) + 2*mxv*(mm - mnoff);
amx = 1.0f - dxp;
amy = 1.0f - dyp;
/* find acceleration */
dx = amx*sfxy[nn];
dy = amx*sfxy[nn+1];
dx = amy*(dxp*sfxy[nn+2] + dx);
dy = amy*(dxp*sfxy[nn+3] + dy);
nn += 2*mxv;
vx = amx*sfxy[nn];
vy = amx*sfxy[nn+1];
dx += dyp*(dxp*sfxy[nn+2] + vx);
dy += dyp*(dxp*sfxy[nn+3] + vy);
/* new velocity */
vx = ppart[2+idimp*(j+npoff)];
vy = ppart[3+idimp*(j+npoff)];
dx = vx + qtm*dx;
dy = vy + qtm*dy;
/* average kinetic energy */
vx += dx;
vy += dy;
sum1 += vx*vx + vy*vy;
ppart[2+idimp*(j+npoff)] = dx;
ppart[3+idimp*(j+npoff)] = dy;
/* new position */
dx = x + dx*dt;
dy = y + dy*dt;
/* find particles going out of bounds */
mm = 0;
/* count how many particles are going in each direction in ncl */
/* save their address and destination in ihole */
/* use periodic boundary conditions and check for roundoff error */
/* mm = direction particle is going */
if (dx >= edgerx) {
if (dx >= anx)
dx -= anx;
mm = 2;
}
else if (dx < edgelx) {
if (dx < 0.0f) {
dx += anx;
if (dx < anx)
mm = 1;
else
dx = 0.0;
}
else {
mm = 1;
}
}
if (dy >= edgery) {
if (dy >= any)
dy -= any;
mm += 6;
}
else if (dy < edgely) {
if (dy < 0.0) {
dy += any;
if (dy < any)
mm += 3;
else
dy = 0.0;
}
else {
mm += 3;
}
}
/* set new position */
ppart[idimp*(j+npoff)] = dx;
ppart[1+idimp*(j+npoff)] = dy;
/* increment counters */
if (mm > 0) {
ncl[mm+8*k-1] += 1;
ih += 1;
if (ih <= ntmax) {
ihole[2*(ih+(ntmax+1)*k)] = j + 1;
ihole[1+2*(ih+(ntmax+1)*k)] = mm;
}
else {
nh = 1;
}
}
}
sum2 += sum1;
/* set error and end of file flag */
/* ihole overflow */
if (nh > 0) {
*irc = ih;
ih = -ih;
}
ihole[2*(ntmax+1)*k] = ih;
}
/* normalize kinetic energy */
*ek += 0.125f*sum2;
return;
#undef MXV
#undef MYV
}
/*--------------------------------------------------------------------*/
void cppgppost2l(float ppart[], float q[], int kpic[], int noff,
float qm, int idimp, int nppmx, int mx, int my,
int nxv, int nypmx, int mx1, int mxyp1) {
/* for 2d code, this subroutine calculates particle charge density
using first-order linear interpolation, periodic boundaries
OpenMP version using guard cells, for distributed data
data deposited in tiles
particles stored segmented array
17 flops/particle, 6 loads, 4 stores
input: all, output: q
charge density is approximated by values at the nearest grid points
q(n,m)=qm*(1.-dx)*(1.-dy)
q(n+1,m)=qm*dx*(1.-dy)
q(n,m+1)=qm*(1.-dx)*dy
q(n+1,m+1)=qm*dx*dy
where n,m = leftmost grid points and dx = x-n, dy = y-m
ppart[m][n][0] = position x of particle n in partition in tile m
ppart[m][n][1] = position y of particle n in partition in tile m
q[k][j] = charge density at grid point (j,kk),
where kk = k + noff
kpic = number of particles per tile
noff = lowermost global gridpoint in particle partition.
qm = charge on particle, in units of e
idimp = size of phase space = 4
nppmx = maximum number of particles in tile
mx/my = number of grids in sorting cell in x/y
nxv = first dimension of charge array, must be >= nx+1
nypmx = maximum size of particle partition, including guard cells.
mx1 = (system length in x direction - 1)/mx + 1
mxyp1 = mx1*myp1, where myp1=(partition length in y direction-1)/my+1
local data */
#define MXV 33
#define MYV 33
int noffp, moffp, npoff, nppp, mxv;
int mnoff, i, j, k, nn, mm;
float x, y, dxp, dyp, amx, amy;
float sq[MXV*MYV];
/* float sq[(mx+1)*(my+1)]; */
mxv = mx + 1;
/* error if local array is too small */
/* if ((mx >= MXV) || (my >= MYV)) */
/* return; */
/* loop over tiles */
#pragma omp parallel for \
private(i,j,k,noffp,moffp,nppp,npoff,mnoff,nn,mm,x,y,dxp,dyp,amx,amy, \
sq)
for (k = 0; k < mxyp1; k++) {
noffp = k/mx1;
moffp = my*noffp;
noffp = mx*(k - mx1*noffp);
nppp = kpic[k];
npoff = nppmx*k;
mnoff = moffp + noff;
/* zero out local accumulator */
for (j = 0; j < my+1; j++) {
for (i = 0; i < mx+1; i++) {
sq[i+mxv*j] = 0.0f;
}
}
/* loop over particles in tile */
for (j = 0; j < nppp; j++) {
/* find interpolation weights */
x = ppart[idimp*(j+npoff)];
y = ppart[1+idimp*(j+npoff)];
nn = x;
mm = y;
dxp = qm*(x - (float) nn);
dyp = y - (float) mm;
nn = nn - noffp + mxv*(mm - mnoff);
amx = qm - dxp;
amy = 1.0f - dyp;
/* deposit charge within tile to local accumulator */
x = sq[nn] + amx*amy;
y = sq[nn+1] + dxp*amy;
sq[nn] = x;
sq[nn+1] = y;
nn += mxv;
x = sq[nn] + amx*dyp;
y = sq[nn+1] + dxp*dyp;
sq[nn] = x;
sq[nn+1] = y;
}
/* deposit charge to interior points in global array */
nn = nxv - noffp;
mm = nypmx - moffp;
nn = mx < nn ? mx : nn;
mm = my < mm ? my : mm;
for (j = 1; j < mm; j++) {
for (i = 1; i < nn; i++) {
q[i+noffp+nxv*(j+moffp)] += sq[i+mxv*j];
}
}
/* deposit charge to edge points in global array */
mm = nypmx - moffp;
mm = my+1 < mm ? my+1 : mm;
for (i = 1; i < nn; i++) {
#pragma omp atomic
q[i+noffp+nxv*moffp] += sq[i];
if (mm > my) {
#pragma omp atomic
q[i+noffp+nxv*(mm+moffp-1)] += sq[i+mxv*(mm-1)];
}
}
nn = nxv - noffp;
nn = mx+1 < nn ? mx+1 : nn;
for (j = 0; j < mm; j++) {
#pragma omp atomic
q[noffp+nxv*(j+moffp)] += sq[mxv*j];
if (nn > mx) {
#pragma omp atomic
q[nn+noffp-1+nxv*(j+moffp)] += sq[nn-1+mxv*j];
}
}
}
return;
#undef MXV
#undef MYV
}
/*--------------------------------------------------------------------*/
void cppporder2la(float ppart[], float ppbuff[], float sbufl[],
float sbufr[], int kpic[], int ncl[], int ihole[],
int ncll[], int nclr[], int noff, int nyp, int idimp,
int nppmx, int nx, int ny, int mx, int my, int mx1,
int myp1, int npbmx, int ntmax, int nbmax, int *irc) {
/* this subroutine performs first part of a particle sort by x,y grid
in tiles of mx, my
linear interpolation, with periodic boundary conditions
for distributed data, with 1d domain decomposition in y.
tiles are assumed to be arranged in 2D linear memory
this part of the algorithm has 3 steps. first, one finds particles
leaving tile and stores their number in each directon, location, and
destination in ncl and ihole. then, a prefix scan of ncl is performed
and departing particles are buffered in ppbuff in direction order.
finally, we buffer particles leaving the processor in sbufl and sbufr,
and store particle number offsets in ncll and nclr.
input: all except ppbuff, sbufl, sbufr, ncl, ihole, ncll, nclr, irc
output: ppart, ppbuff, sbufl, sbufr, ncl, ihole, ncll, nclr, irc
ppart[k][n][0] = position x of particle n in tile k
ppart[k][n][1] = position y of particle n in tile k
ppbuff[k][n][i] = i co-ordinate of particle n in tile k
sbufl = buffer for particles being sent to lower processor
sbufr = buffer for particles being sent to upper processor
kpic[k] = number of particles in tile k
ncl(i,k) = number of particles going to destination i, tile k
ihole[k][:][0] = location of hole in array left by departing particle
ihole[k][:][1] = direction destination of particle leaving hole
all for tile k
ihole[k][0][0] = ih, number of holes left (error, if negative)
ncll = number offset being sent to lower processor
nclr = number offset being sent to upper processor
noff = lowermost global gridpoint in particle partition.
nyp = number of primary (complete) gridpoints in particle partition
idimp = size of phase space = 4
nppmx = maximum number of particles in tile
nx/ny = system length in x/y direction
mx/my = number of grids in sorting cell in x/y
mx1 = (system length in x direction - 1)/mx + 1
myp1 = (partition length in y direction - 1)/my + 1
npbmx = size of buffer array ppbuff
ntmax = size of hole array for particles leaving tiles
nbmax = size of buffers for passing particles between processors
irc = maximum overflow, returned only if error occurs, when irc > 0
local data */
int mxyp1, noffp, moffp, nppp;
int i, j, k, ii, jj, ih, nh, ist, nn, mm, isum, ip, j1, kk;
float anx, any, edgelx, edgely, edgerx, edgery, dx, dy;
mxyp1 = mx1*myp1;
anx = (float) nx;
any = (float) ny;
/* find and count particles leaving tiles and determine destination */
/* update ppart, ihole, ncl */
/* loop over tiles */
#pragma omp parallel for \
private(j,k,noffp,moffp,nppp,nn,mm,ih,nh,ist,dx,dy,edgelx,edgely, \
edgerx,edgery)
for (k = 0; k < mxyp1; k++) {
noffp = k/mx1;
moffp = my*noffp;
noffp = mx*(k - mx1*noffp);
nppp = kpic[k];
nn = nx - noffp;
nn = mx < nn ? mx : nn;
mm = nyp - moffp;
mm = my < mm ? my : mm;
ih = 0;
nh = 0;
edgelx = noffp;
edgerx = noffp + nn;
edgely = noff + moffp;
edgery = noff + moffp + mm;
/* clear counters */
for (j = 0; j < 8; j++) {
ncl[j+8*k] = 0;
}
/* loop over particles in tile */
for (j = 0; j < nppp; j++) {
dx = ppart[idimp*(j+nppmx*k)];
dy = ppart[1+idimp*(j+nppmx*k)];
/* find particles going out of bounds */
ist = 0;
/* count how many particles are going in each direction in ncl */
/* save their address and destination in ihole */
/* use periodic boundary conditions and check for roundoff error */
/* ist = direction particle is going */
if (dx >= edgerx) {
if (dx >= anx)
ppart[idimp*(j+nppmx*k)] = dx - anx;
ist = 2;
}
else if (dx < edgelx) {
if (dx < 0.0) {
dx += anx;
if (dx < anx)
ist = 1;
else
dx = 0.0;
ppart[idimp*(j+nppmx*k)] = dx;
}
else {
ist = 1;
}
}
if (dy >= edgery) {
if (dy >= any)
ppart[1+idimp*(j+nppmx*k)] = dy - any;
ist += 6;
}
else if (dy < edgely) {
if (dy < 0.0) {
dy += any;
if (dy < any)
ist += 3;
else
dy = 0.0;
ppart[1+idimp*(j+nppmx*k)] = dy;
}
else {
ist += 3;
}
}
if (ist > 0) {
ncl[ist+8*k-1] += 1;
ih += 1;
if (ih <= ntmax) {
ihole[2*(ih+(ntmax+1)*k)] = j + 1;
ihole[1+2*(ih+(ntmax+1)*k)] = ist;
}
else {
nh = 1;
}
}
}
/* set error and end of file flag */
if (nh > 0) {
*irc = ih;
ih = -ih;
}
ihole[2*(ntmax+1)*k] = ih;
}
/* ihole overflow */
if (*irc > 0)
return;
/* buffer particles that are leaving tile: update ppbuff, ncl */
/* loop over tiles */
#pragma omp parallel for \
private(i,j,k,isum,ist,nh,ip,j1,ii)
for (k = 0; k < mxyp1; k++) {
/* find address offset for ordered ppbuff array */
isum = 0;
for (j = 0; j < 8; j++) {
ist = ncl[j+8*k];
ncl[j+8*k] = isum;
isum += ist;
}
nh = ihole[2*(ntmax+1)*k];
ip = 0;
/* loop over particles leaving tile */
for (j = 0; j < nh; j++) {
/* buffer particles that are leaving tile, in direction order */
j1 = ihole[2*(j+1+(ntmax+1)*k)] - 1;
ist = ihole[1+2*(j+1+(ntmax+1)*k)];
ii = ncl[ist+8*k-1];
if (ii < npbmx) {
for (i = 0; i < idimp; i++) {
ppbuff[i+idimp*(ii+npbmx*k)]
= ppart[i+idimp*(j1+nppmx*k)];
}
}
else {
ip = 1;
}
ncl[ist+8*k-1] = ii + 1;
}
/* set error */
if (ip > 0)
*irc = ncl[7+8*k];
}
/* ppbuff overflow */
if (*irc > 0)
return;
/* buffer particles and their number leaving the node: */
/* update sbufl, sbufr, ncll, nclr */
kk = mx1*(myp1 - 1);
#pragma omp parallel for private(k)
for (k = 0; k < mx1; k++) {
ncll[3*k] = ncl[4+8*k] - ncl[1+8*k];
nclr[3*k] = ncl[7+8*(k+kk)] - ncl[4+8*(k+kk)];
}
/* perform prefix scan */
kk = 1;
L90: if (kk >= mx1)
goto L110;
#pragma omp parallel for private(k,ii,nn,mm)
for (k = 0; k < mx1; k++) {
ii = k/kk;
nn = kk*ii;
mm = 2*nn + kk - 1;
nn += k + kk;
if (nn < mx1) {
ncll[3*nn] += ncll[3*mm];
nclr[3*nn] += nclr[3*mm];
}
}
kk += kk;
goto L90;
L110: kk = mx1*(myp1 - 1);
#pragma omp parallel for private(i,j,k,ii,nn,mm)
for (k = 0; k < mx1; k++) {
ii = ncl[4+8*k] - ncl[1+8*k];
nn = ncll[3*k] - ii;
jj = nbmax - nn;
jj = ii < jj ? ii : jj;
for (j = 0; j < jj; j++) {
for (i = 0; i < idimp; i++) {
sbufl[i+idimp*(j+nn)]
= ppbuff[i+idimp*(j+ncl[1+8*k]+npbmx*k)];
}
}
for (i = 0; i < 3; i++) {
ncll[i+3*k] = ncl[i+2+8*k] - ncl[1+8*k] + nn;
}
ii = ncl[7+8*(k+kk)] - ncl[4+8*(k+kk)];
mm = nclr[3*k] - ii;
jj = nbmax - mm;
jj = ii < jj ? ii : jj;
for (j = 0; j < jj; j++) {
for (i = 0; i < idimp; i++) {
sbufr[i+idimp*(j+mm)]
= ppbuff[i+idimp*(j+ncl[4+8*(k+kk)]+npbmx*(k+kk))];
}
}
for (i = 0; i < 3; i++) {
nclr[i+3*k] = ncl[i+5+8*(k+kk)] - ncl[4+8*(k+kk)] + mm;
}
}
/* sbufl or sbufr overflow */
nn = ncll[3*mx1-1];
mm = nclr[3*mx1-1];
ii = nn > mm ? nn : mm;
if (ii > nbmax)
*irc = ii;
return;
}
/*--------------------------------------------------------------------*/
void cppporderf2la(float ppart[], float ppbuff[], float sbufl[],
float sbufr[], int ncl[], int ihole[], int ncll[],
int nclr[], int idimp, int nppmx, int mx1, int myp1,
int npbmx, int ntmax, int nbmax, int *irc) {
/* this subroutine performs first part of a particle sort by x,y grid
in tiles of mx, my
linear interpolation, with periodic boundary conditions
for distributed data, with 1d domain decomposition in y.
tiles are assumed to be arranged in 2D linear memory
this part of the algorithm has 2 steps. first, a prefix scan of ncl
is performed and departing particles are buffered in ppbuff in
direction order. then, we buffer particles leaving the processor in
sbufl and sbufr, and store particle number offsets in ncll and nclr.
it assumes that the number, location, and destination of particles
leaving a tile have been previously stored in ncl and ihole by the
cppgppushf2l procedure.
input: all except ppbuff, sbufl, sbufr, ncll, nclr, irc
output: ppart, ppbuff, sbufl, sbufr, ncl, ncll, nclr, irc
ppart[k][n][0] = position x of particle n in tile k
ppart[k][n][1] = position y of particle n in tile k
ppbuff[k][n][i] = i co-ordinate of particle n in tile k
sbufl = buffer for particles being sent to lower processor
sbufr = buffer for particles being sent to upper processor
ncl(i,k) = number of particles going to destination i, tile k
ihole[k][:][0] = location of hole in array left by departing particle
ihole[k][:][1] = direction destination of particle leaving hole
all for tile k
ihole[k][0][0] = ih, number of holes left (error, if negative)
ncll = number offset being sent to lower processor
nclr = number offset being sent to upper processor
idimp = size of phase space = 4
nppmx = maximum number of particles in tile
mx1 = (system length in x direction - 1)/mx + 1
myp1 = (partition length in y direction - 1)/my + 1
npbmx = size of buffer array ppbuff
ntmax = size of hole array for particles leaving tiles
nbmax = size of buffers for passing particles between processors
irc = maximum overflow, returned only if error occurs, when irc > 0
local data */
int mxyp1;
int i, j, k, ii, jj, nh, ist, nn, mm, isum, ip, j1, kk;
mxyp1 = mx1*myp1;
/* buffer particles that are leaving tile: update ppbuff, ncl */
/* loop over tiles */
#pragma omp parallel for \
private(i,j,k,isum,ist,nh,ip,j1,ii)
for (k = 0; k < mxyp1; k++) {
/* find address offset for ordered ppbuff array */
isum = 0;
for (j = 0; j < 8; j++) {
ist = ncl[j+8*k];
ncl[j+8*k] = isum;
isum += ist;
}
nh = ihole[2*(ntmax+1)*k];
ip = 0;
/* loop over particles leaving tile */
for (j = 0; j < nh; j++) {
/* buffer particles that are leaving tile, in direction order */
j1 = ihole[2*(j+1+(ntmax+1)*k)] - 1;
ist = ihole[1+2*(j+1+(ntmax+1)*k)];
ii = ncl[ist+8*k-1];
if (ii < npbmx) {
for (i = 0; i < idimp; i++) {
ppbuff[i+idimp*(ii+npbmx*k)]
= ppart[i+idimp*(j1+nppmx*k)];
}
}
else {
ip = 1;
}
ncl[ist+8*k-1] = ii + 1;
}
/* set error */
if (ip > 0)
*irc = ncl[7+8*k];
}
/* ppbuff overflow */
if (*irc > 0)
return;
/* buffer particles and their number leaving the node: */
/* update sbufl, sbufr, ncll, nclr */
kk = mx1*(myp1 - 1);
#pragma omp parallel for private(k)
for (k = 0; k < mx1; k++) {
ncll[3*k] = ncl[4+8*k] - ncl[1+8*k];
nclr[3*k] = ncl[7+8*(k+kk)] - ncl[4+8*(k+kk)];
}
/* perform prefix scan */
kk = 1;
L90: if (kk >= mx1)
goto L110;
#pragma omp parallel for private(k,ii,nn,mm)
for (k = 0; k < mx1; k++) {
ii = k/kk;
nn = kk*ii;
mm = 2*nn + kk - 1;
nn += k + kk;
if (nn < mx1) {
ncll[3*nn] += ncll[3*mm];
nclr[3*nn] += nclr[3*mm];
}
}
kk += kk;
goto L90;
L110: kk = mx1*(myp1 - 1);
#pragma omp parallel for private(i,j,k,ii,nn,mm)
for (k = 0; k < mx1; k++) {
ii = ncl[4+8*k] - ncl[1+8*k];
nn = ncll[3*k] - ii;
jj = nbmax - nn;
jj = ii < jj ? ii : jj;
for (j = 0; j < jj; j++) {
for (i = 0; i < idimp; i++) {
sbufl[i+idimp*(j+nn)]
= ppbuff[i+idimp*(j+ncl[1+8*k]+npbmx*k)];
}
}
for (i = 0; i < 3; i++) {
ncll[i+3*k] = ncl[i+2+8*k] - ncl[1+8*k] + nn;
}
ii = ncl[7+8*(k+kk)] - ncl[4+8*(k+kk)];
mm = nclr[3*k] - ii;
jj = nbmax - mm;
jj = ii < jj ? ii : jj;
for (j = 0; j < jj; j++) {
for (i = 0; i < idimp; i++) {
sbufr[i+idimp*(j+mm)]
= ppbuff[i+idimp*(j+ncl[4+8*(k+kk)]+npbmx*(k+kk))];
}
}
for (i = 0; i < 3; i++) {
nclr[i+3*k] = ncl[i+5+8*(k+kk)] - ncl[4+8*(k+kk)] + mm;
}
}
/* sbufl or sbufr overflow */
nn = ncll[3*mx1-1];
mm = nclr[3*mx1-1];
ii = nn > mm ? nn : mm;
if (ii > nbmax)
*irc = ii;
return;
}
/*--------------------------------------------------------------------*/
void cppporder2lb(float ppart[], float ppbuff[], float rbufl[],
float rbufr[], int kpic[], int ncl[], int ihole[],
int mcll[], int mclr[], int idimp, int nppmx, int mx1,
int myp1, int npbmx, int ntmax, int nbmax, int *irc) {
/* this subroutine performs second part of a particle sort by x,y grid
in tiles of mx, my
linear interpolation, with periodic boundary conditions
for distributed data, with 1d domain decomposition in y.
tiles are assumed to be arranged in 2D linear memory
incoming particles from other tiles are copied from ppbuff, rbufl, and
rbufr into ppart
input: all except ppart, kpic, irc
output: ppart, kpic, irc
ppart[k][n][0] = position x of particle n in tile k
ppart[k][n][1] = position y of particle n in tile k
ppbuff[k][n][i] = i co-ordinate of particle n in tile k
rbufl = buffer for particles being received from lower processor
rbufr = buffer for particles being received from upper processor
kpic[k] = number of particles in tile k
ncl[k][i] = number of particles going to destination i, tile k
ihole[k][:][0] = location of hole in array left by departing particle
ihole[k][:][1] = direction destination of particle leaving hole
all for tile k
ihole[k][0][0] = ih, number of holes left (error, if negative)
mcll = number offset being received from lower processor
mclr = number offset being received from upper processor
idimp = size of phase space = 4
nppmx = maximum number of particles in tile
mx1 = (system length in x direction - 1)/mx + 1
myp1 = (partition length in y direction - 1)/my + 1
npbmx = size of buffer array ppbuff
ntmax = size of hole array for particles leaving tiles
nbmax = size of buffers for passing particles between processors
irc = maximum overflow, returned only if error occurs, when irc > 0
local data */
int mxyp1, nppp, ncoff, noff, moff;
int i, j, k, ii, kx, ky, ih, nh, ist;
int ip, j1, j2, kxl, kxr, kk, kl, kr;
int ks[8];
mxyp1 = mx1*myp1;
/* copy incoming particles from buffer into ppart: update ppart, kpic */
/* loop over tiles */
#pragma omp parallel for \
private(i,j,k,ii,kk,nppp,kx,ky,kl,kr,kxl,kxr,ih,nh,ncoff,noff,moff, \
ist,j1,j2,ip,ks)
for (k = 0; k < mxyp1; k++) {
nppp = kpic[k];
ky = k/mx1;
/* loop over tiles in y */
kk = ky*mx1;
/* find tile above */
kl = (ky - 1)*mx1;
/* find tile below */
kr = (ky + 1)*mx1;
/* loop over tiles in x, assume periodic boundary conditions */
kx = k - ky*mx1;
kxl = kx - 1;
if (kxl < 0)
kxl += mx1;
kxr = kx + 1;
if (kxr >= mx1)
kxr -= mx1;
/* find tile number for different directions */
ks[0] = kxr + kk;
ks[1] = kxl + kk;
ks[2] = kx + kr;
ks[3] = kxr + kr;
ks[4] = kxl + kr;
ks[5] = kx + kl;
ks[6] = kxr + kl;
ks[7] = kxl + kl;
/* loop over directions */
nh = ihole[2*(ntmax+1)*k];
noff = 0;
moff = 0;
if (ky==0) {
if (kx > 0)
noff = mcll[2+3*(kx-1)];
}
if (ky==(myp1-1)) {
if (kx > 0)
moff = mclr[2+3*(kx-1)];
}
ncoff = 0;
ih = 0;
ist = 0;
j1 = 0;
for (ii = 0; ii < 8; ii++) {
/* ip = number of particles coming from direction ii */
if (ks[ii] < 0) {
if (ii > 5)
noff = mcll[ii-6+3*(ks[ii]+mx1)];
ip = mcll[ii-5+3*(ks[ii]+mx1)] - noff;
}
else if (ks[ii] >= mxyp1) {
if (ii > 2)
moff = mclr[ii-3+3*(ks[ii]-mxyp1)];
ip = mclr[ii-2+3*(ks[ii]-mxyp1)] - moff;
}
else {
if (ii > 0)
ncoff = ncl[ii-1+8*ks[ii]];
ip = ncl[ii+8*ks[ii]] - ncoff;
}
for (j = 0; j < ip; j++) {
ih += 1;
/* insert incoming particles into holes */
if (ih <= nh) {
j1 = ihole[2*(ih+(ntmax+1)*k)] - 1;
}
/* place overflow at end of array */
else {
j1 = nppp;
nppp += 1;
}
if (j1 < nppmx) {
if (ks[ii] < 0) {
for (i = 0; i < idimp; i++) {
ppart[i+idimp*(j1+nppmx*k)]
= rbufl[i+idimp*(j+noff)];
}
}
else if (ks[ii] >= mxyp1) {
for (i = 0; i < idimp; i++) {
ppart[i+idimp*(j1+nppmx*k)]
= rbufr[i+idimp*(j+moff)];
}
}
else {
for (i = 0; i < idimp; i++) {
ppart[i+idimp*(j1+nppmx*k)]
= ppbuff[i+idimp*(j+ncoff+npbmx*ks[ii])];
}
}
}
else {
ist = 1;
}
}
}
/* set error */
if (ist > 0)
*irc = j1+1;
/* fill up remaining holes in particle array with particles from bottom */
if (ih < nh) {
ip = nh - ih;
for (j = 0; j < ip; j++) {
j1 = nppp - j - 1;
j2 = ihole[2*(nh-j+(ntmax+1)*k)] - 1;
if (j1 > j2) {
/* move particle only if it is below current hole */
for (i = 0; i < idimp; i++) {
ppart[i+idimp*(j2+nppmx*k)]
= ppart[i+idimp*(j1+nppmx*k)];
}
}
}
nppp -= ip;
}
kpic[k] = nppp;
}
return;
}
/*--------------------------------------------------------------------*/
void cppcguard2xl(float fxy[], int nyp, int nx, int ndim, int nxe,
int nypmx) {
/* replicate extended periodic vector field in x direction
linear interpolation, for distributed data
nyp = number of primary (complete) gridpoints in particle partition
nx = system length in x direction
ndim = leading dimension of array fxy
nxe = first dimension of field arrays, must be >= nx+1
nypmx = maximum size of particle partition, including guard cells
local data */
int i, k, kk, myp1;
/* replicate edges of extended field */
myp1 = nyp + 1;
for (k = 0; k < myp1; k++) {
kk = ndim*nxe*k;
for (i = 0; i < ndim; i++) {
fxy[i+ndim*nx+kk] = fxy[i+kk];
}
}
return;
}
/*--------------------------------------------------------------------*/
void cppaguard2xl(float q[], int nyp, int nx, int nxe, int nypmx) {
/* accumulate extended periodic scalar field in x direction
linear interpolation, for distributed data
nyp = number of primary (complete) gridpoints in particle partition
nx = system length in x direction
nxe = first dimension of field arrays, must be >= nx+1
nypmx = maximum size of particle partition, including guard cells
local data */
int k, myp1;
/* accumulate edges of extended field */
myp1 = nyp + 1;
for (k = 0; k < myp1; k++) {
q[nxe*k] += q[nx+nxe*k];
q[nx+nxe*k] = 0.0;
}
return;
}
/*--------------------------------------------------------------------*/
void cmppois22(float complex q[], float complex fxy[], int isign,
float complex ffc[], float ax, float ay, float affp,
float *we, int nx, int ny, int kstrt, int nyv, int kxp,
int nyhd) {
/* this subroutine solves 2d poisson's equation in fourier space for
force/charge (or convolution of electric field over particle shape)
with periodic boundary conditions, for distributed data.
for isign = 0, input: isign,ax,ay,affp,nx,ny,jblok,nyv,kxp,nyhd,
output: ffc
for isign /= 0, input: q,ffc,isign,nx,ny,nyv,kxp,jblok,nyhd,
output: fxy,we
approximate flop count is: 33*nxc*nyc + 15*(nxc + nyc)
where nxc = (nx/2-1)/nvp, nyc = ny/2 - 1, and nvp = number of procs
the equation used is:
fx[ky][kx] = -sqrt(-1)*kx*g[ky][kx]*s[ky][kx]*q[ky][kx],
fy[ky][kx] = -sqrt(-1)*ky*g[ky][kx]*s[ky][kx]*q[ky][kx],
where kx = 2pi*j/nx, ky = 2pi*k/ny, and j,k = fourier mode numbers,
g[ky][kx] = (affp/(kx**2+ky**2))*s[ky][kx],
s[ky][kx] = exp(-((kx*ax)**2+(ky*ay)**2)/2), except for
fx(kx=pi) = fy(kx=pi) = fx(ky=pi) = fy(ky=pi) = 0, and
fx(kx=0,ky=0) = fy(kx=0,ky=0) = 0.
q[k][j] = complex charge density for fourier mode (jj,k)
fxy[k][j][0] = x component of complex force/charge,
fxy[k][j][1] = y component of complex force/charge,
for fourier mode (jj,k), where jj = j + kxp*(kstrt - 1)
kxp = number of data values per block
kstrt = starting data block number
if isign = 0, form factor array is prepared
if isign is not equal to 0, force/charge is calculated.
aimag(ffc[k][j]) = finite-size particle shape factor s
real(ffc[k][j])) = potential green's function g
for fourier mode (jj,k), where jj = j + kxp*(kstrt - 1)
ax/ay = half-width of particle in x/y direction
affp = normalization constant = nx*ny/np, where np=number of particles
electric field energy is also calculated, using
we = nx*ny*sum((affp/(kx**2+ky**2))*|q[ky][kx]*s[ky][kx]|**2)
nx/ny = system length in x/y direction
nyv = first dimension of field arrays, must be >= ny
nyhd = first dimension of form factor array, must be >= nyh
local data */
int nxh, nyh, ks, joff, kxps, j, jj, jk, jk2, k, k1;
float dnx, dny, dkx, dky, at1, at2, at3, at4;
float complex zero, zt1, zt2;
double wp, sum1;
nxh = nx/2;
nyh = 1 > ny/2 ? 1 : ny/2;
ks = kstrt - 1;
joff = kxp*ks;
kxps = nxh - joff;
kxps = 0 > kxps ? 0 : kxps;
kxps = kxp < kxps ? kxp : kxps;
dnx = 6.28318530717959/(float) nx;
dny = 6.28318530717959/(float) ny;
zero = 0.0 + 0.0*_Complex_I;
if (isign != 0)
goto L30;
if (kstrt > nxh) return;
/* prepare form factor array */
for (j = 0; j < kxps; j++) {
dkx = dnx*(float) (j + joff);
jj = nyhd*j;
at1 = dkx*dkx;
at2 = pow((dkx*ax),2);
for (k = 0; k < nyh; k++) {
dky = dny*(float) k;
at3 = dky*dky + at1;
at4 = exp(-.5*(pow((dky*ay),2) + at2));
if (at3==0.0) {
ffc[k+jj] = affp + 1.0*_Complex_I;
}
else {
ffc[k+jj] = (affp*at4/at3) + at4*_Complex_I;
}
}
}
return;
/* calculate force/charge and sum field energy */
L30: sum1 = 0.0;
if (kstrt > nxh)
goto L70;
/* mode numbers 0 < kx < nx/2 and 0 < ky < ny/2 */
#pragma omp parallel for \
private(j,k,k1,jj,jk,jk2,dkx,at1,at2,at3,zt1,zt2,wp) \
reduction(+:sum1)
for (j = 0; j < kxps; j++) {
dkx = dnx*(float) (j + joff);
jj = nyhd*j;
jk = nyv*j;
jk2 = 2*jk;
wp = 0.0;
if ((j+joff) > 0) {
for (k = 1; k < nyh; k++) {
k1 = ny - k;
at1 = crealf(ffc[k+jj])*cimagf(ffc[k+jj]);
at2 = dkx*at1;
at3 = dny*at1*(float) k;
zt1 = cimagf(q[k+jk]) - crealf(q[k+jk])*_Complex_I;
zt2 = cimagf(q[k1+jk]) - crealf(q[k1+jk])*_Complex_I;
fxy[2*k+jk2] = at2*zt1;
fxy[1+2*k+jk2] = at3*zt1;
fxy[2*k1+jk2] = at2*zt2;
fxy[1+2*k1+jk2] = -at3*zt2;
wp += at1*(q[k+jk]*conjf(q[k+jk])
+ q[k1+jk]*conjf(q[k1+jk]));
}
/* mode numbers ky = 0, ny/2 */
k1 = nyh;
at1 = crealf(ffc[jj])*cimagf(ffc[jj]);
at3 = dkx*at1;
zt1 = cimagf(q[jk]) - crealf(q[jk])*_Complex_I;
fxy[jk2] = at3*zt1;
fxy[1+jk2] = zero;
fxy[2*k1+jk2] = zero;
fxy[1+2*k1+jk2] = zero;
wp += at1*(q[jk]*conjf(q[jk]));
}
sum1 += wp;
}
wp = 0.0;
/* mode numbers kx = 0, nx/2 */
if (ks==0) {
for (k = 1; k < nyh; k++) {
k1 = ny - k;
at1 = crealf(ffc[k])*cimagf(ffc[k]);
at2 = dny*at1*(float) k;
zt1 = cimagf(q[k]) - crealf(q[k])*_Complex_I;
fxy[2*k] = zero;
fxy[1+2*k] = at2*zt1;
fxy[2*k1] = zero;
fxy[1+2*k1] = zero;
wp += at1*(q[k]*conjf(q[k]));
}
k1 = 2*nyh;
fxy[0] = zero;
fxy[1] = zero;
fxy[k1] = zero;
fxy[1+k1] = zero;
}
sum1 += wp;
L70:
*we = sum1*((float) nx)*((float) ny);
return;
}
/*--------------------------------------------------------------------*/
void cwpfft2rinit(int mixup[], float complex sct[], int indx, int indy,
int nxhyd, int nxyhd) {
/* this subroutine calculates tables needed by a two dimensional
real to complex fast fourier transform and its inverse.
input: indx, indy, nxhyd, nxyhd
output: mixup, sct
mixup = array of bit reversed addresses
sct = sine/cosine table
indx/indy = exponent which determines length in x/y direction,
where nx=2**indx, ny=2**indy
nxhyd = maximum of (nx/2,ny)
nxyhd = one half of maximum of (nx,ny)
written by viktor k. decyk, ucla
local data */
int indx1, indx1y, nx, ny, nxy, nxhy, nxyh;
int j, k, lb, ll, jb, it;
float dnxy, arg;
indx1 = indx - 1;
indx1y = indx1 > indy ? indx1 : indy;
nx = 1L<<indx;
ny = 1L<<indy;
nxy = nx > ny ? nx : ny;
nxhy = 1L<<indx1y;
/* bit-reverse index table: mixup[j] = 1 + reversed bits of j */
for (j = 0; j < nxhy; j++) {
lb = j;
ll = 0;
for (k = 0; k < indx1y; k++) {
jb = lb/2;
it = lb - 2*jb;
lb = jb;
ll = 2*ll + it;
}
mixup[j] = ll + 1;
}
/* sine/cosine table for the angles 2*n*pi/nxy */
nxyh = nxy/2;
dnxy = 6.28318530717959/(float) nxy;
for (j = 0; j < nxyh; j++) {
arg = dnxy*(float) j;
sct[j] = cosf(arg) - sinf(arg)*_Complex_I;
}
return;
}
/*--------------------------------------------------------------------*/
void cppfft2rmxx(float complex f[], int isign, int mixup[],
float complex sct[], int indx, int indy, int kstrt,
int kypi, int kypp, int nxvh, int kypd, int nxhyd,
int nxyhd) {
/* this subroutine performs the x part of a two dimensional real to
complex fast fourier transform and its inverse, for a subset of y,
using complex arithmetic, with OpenMP,
for data which is distributed in blocks
for isign = (-1,1), input: all, output: f
for isign = -1, approximate flop count: N*(5*log2(N) + 10)/nvp
for isign = 1, approximate flop count: N*(5*log2(N) + 8)/nvp
where N = (nx/2)*ny, and nvp = number of procs
indx/indy = exponent which determines length in x/y direction,
where nx=2**indx, ny=2**indy
if isign = -1, an inverse fourier transform is performed
f[m][n] = (1/nx*ny)*sum(f[k][j]*exp(-sqrt(-1)*2pi*n*j/nx)
if isign = 1, a forward fourier transform is performed
f[k][j] = sum(f[m][n]*exp(sqrt(-1)*2pi*n*j/nx)
kstrt = starting data block number
kypi = initial y index used
kypp = number of y indices used
nxvh = first dimension of f
kypd = second dimension of f
mixup = array of bit reversed addresses
sct = sine/cosine table
nxhyd = maximum of (nx/2,ny)
nxyhd = one half of maximum of (nx,ny)
the real data is stored in a complex array of length nx/2, ny
with the odd/even x points stored in the real/imaginary parts.
in complex notation, fourier coefficients are stored as follows:
f[k][j] = mode j,kk, where kk = k + kyp*(kstrt - 1)
0 <= j < nx/2 and 0 <= kk < ny, except for
f[k][0] = mode nx/2,kk, where ny/2+1 <= kk < ny, and
imaginary part of f[0][0] = real part of mode nx/2,0 on mode kstrt=0
imaginary part of f[0][0] = real part of mode nx/2,ny/2
on mode kstrt=(ny/2)/kyp
written by viktor k. decyk, ucla
parallel, RISC optimized version
local data */
int indx1, indx1y, nx, nxh, nxhh, ny;
int nxy, nxhy, kypt, j, k, nrx;
int i, m, ns, ns2, km, kmr, k1, k2, j1, j2, nrxb, joff;
float ani;
float complex s, t, t1;
indx1 = indx - 1;
indx1y = indx1 > indy ? indx1 : indy;
nx = 1L<<indx;
nxh = nx/2;
nxhh = nx/4;
ny = 1L<<indy;
nxy = nx > ny ? nx : ny;
nxhy = 1L<<indx1y;
kypt = kypi + kypp - 1;
if (kstrt > ny)
return;
if (isign > 0)
goto L70;
/* inverse fourier transform */
ani = 0.5/(((float) nx)*((float) ny));
nrxb = nxhy/nxh;
nrx = nxy/nxh;
#pragma omp parallel for \
private(i,j,k,m,ns,ns2,km,kmr,k1,k2,j1,j2,joff,s,t,t1)
for (i = kypi-1; i < kypt; i++) {
joff = nxvh*i;
/* bit-reverse array elements in x */
for (j = 0; j < nxh; j++) {
j1 = (mixup[j] - 1)/nrxb;
if (j < j1) {
t = f[j1+joff];
f[j1+joff] = f[j+joff];
f[j+joff] = t;
}
}
/* then transform in x */
ns = 1;
for (m = 0; m < indx1; m++) {
ns2 = ns + ns;
km = nxhh/ns;
kmr = km*nrx;
for (k = 0; k < km; k++) {
k1 = ns2*k;
k2 = k1 + ns;
for (j = 0; j < ns; j++) {
j1 = j + k1;
j2 = j + k2;
s = sct[kmr*j];
t = s*f[j2+joff];
f[j2+joff] = f[j1+joff] - t;
f[j1+joff] += t;
}
}
ns = ns2;
}
/* unscramble coefficients and normalize */
kmr = nxy/nx;
for (j = 1; j < nxhh; j++) {
t1 = cimagf(sct[kmr*j]) - crealf(sct[kmr*j])*_Complex_I;
t = conjf(f[nxh-j+joff]);
s = f[j+joff] + t;
t = (f[j+joff] - t)*t1;
f[j+joff] = ani*(s + t);
f[nxh-j+joff] = ani*conjf(s - t);
}
f[joff] = 2.0*ani*((crealf(f[joff]) + cimagf(f[joff]))
+ (crealf(f[joff]) - cimagf(f[joff]))*_Complex_I);
if (nxhh > 0)
f[nxhh+joff] = 2.0*ani*conjf(f[nxhh+joff]);
}
return;
/* forward fourier transform */
L70: nrxb = nxhy/nxh;
nrx = nxy/nxh;
#pragma omp parallel for \
private(i,j,k,m,ns,ns2,km,kmr,k1,k2,j1,j2,joff,s,t,t1)
for (i = kypi-1; i < kypt; i++) {
joff = nxvh*i;
/* scramble coefficients */
kmr = nxy/nx;
for (j = 1; j < nxhh; j++) {
t1 = cimagf(sct[kmr*j]) + crealf(sct[kmr*j])*_Complex_I;
t = conjf(f[nxh-j+joff]);
s = f[j+joff] + t;
t = (f[j+joff] - t)*t1;
f[j+joff] = s + t;
f[nxh-j+joff] = conjf(s - t);
}
f[joff] = (crealf(f[joff]) + cimagf(f[joff]))
+ (crealf(f[joff]) - cimagf(f[joff]))*_Complex_I;
if (nxhh > 0)
f[nxhh+joff] = 2.0*conjf(f[nxhh+joff]);
/* bit-reverse array elements in x */
for (j = 0; j < nxh; j++) {
j1 = (mixup[j] - 1)/nrxb;
if (j < j1) {
t = f[j1+joff];
f[j1+joff] = f[j+joff];
f[j+joff] = t;
}
}
/* then transform in x */
ns = 1;
for (m = 0; m < indx1; m++) {
ns2 = ns + ns;
km = nxhh/ns;
kmr = km*nrx;
for (k = 0; k < km; k++) {
k1 = ns2*k;
k2 = k1 + ns;
for (j = 0; j < ns; j++) {
j1 = j + k1;
j2 = j + k2;
s = conjf(sct[kmr*j]);
t = s*f[j2+joff];
f[j2+joff] = f[j1+joff] - t;
f[j1+joff] += t;
}
}
ns = ns2;
}
}
return;
}
/*--------------------------------------------------------------------*/
void cppfft2rmxy(float complex g[], int isign, int mixup[],
float complex sct[], int indx, int indy, int kstrt,
int kxpi, int kxpp, int nyv, int kxp, int nxhyd,
int nxyhd) {
/* this subroutine performs the y part of a two dimensional real to
complex fast fourier transform and its inverse, for a subset of x,
using complex arithmetic, with OpenMP,
for data which is distributed in blocks
for isign = (-1,1), input: all, output: g
for isign = -1, approximate flop count: N*(5*log2(N) + 10)/nvp
for isign = 1, approximate flop count: N*(5*log2(N) + 8)/nvp
where N = (nx/2)*ny, and nvp = number of procs
indx/indy = exponent which determines length in x/y direction,
where nx=2**indx, ny=2**indy
if isign = -1, an inverse fourier transform is performed
g[m][n] = sum(g[k][j]*exp(-sqrt(-1)*2pi*m*k/ny))
if isign = 1, a forward fourier transform is performed
g[k][j] = sum(g[m][n]*exp(sqrt(-1)*2pi*m*k/ny))
kstrt = starting data block number
kxp = number of x indices per block
kxpi = initial x index used
kxpp = number of x indices used
nyv = first dimension of g
kxp = number of data values per block in x
mixup = array of bit reversed addresses
sct = sine/cosine table
nxhyd = maximum of (nx/2,ny)
nxyhd = one half of maximum of (nx,ny)
the real data is stored in a complex array of length nx/2, ny
with the odd/even x points stored in the real/imaginary parts.
in complex notation, fourier coefficients are stored as follows:
g[k][j] = mode jj,k, where jj = j + kxp*(kstrt - 1)
0 <= jj < nx/2 and 0 <= k < ny, except for
g[0][k] = mode nx/2,k, where ny/2+1 <= k < ny, and
imaginary part of g[0][0] = real part of mode nx/2,0 and
imaginary part of g[1][ny/2] = real part of mode nx/2,ny/2
on node kstrt=0
written by viktor k. decyk, ucla
parallel, RISC optimized version
local data */
int indx1, indx1y, nx, nxh, ny, nyh;
int nxy, nxhy, ks, kxpt, j, k, nry;
int i, m, ns, ns2, km, kmr, k1, k2, j1, j2, nryb, koff;
float complex s, t;
indx1 = indx - 1;
indx1y = indx1 > indy ? indx1 : indy;
nx = 1L<<indx;
nxh = nx/2;
ny = 1L<<indy;
nyh = ny/2;
nxy = nx > ny ? nx : ny;
nxhy = 1L<<indx1y;
ks = kstrt - 1;
kxpt = kxpi + kxpp - 1;
if (kstrt > nxh)
return;
if (isign > 0)
goto L70;
/* inverse fourier transform */
nryb = nxhy/ny;
nry = nxy/ny;
#pragma omp parallel for \
private(i,j,k,m,ns,ns2,km,kmr,k1,k2,j1,j2,koff,s,t)
for (i = kxpi-1; i < kxpt; i++) {
koff = nyv*i;
/* bit-reverse array elements in y */
for (k = 0; k < ny; k++) {
k1 = (mixup[k] - 1)/nryb;
if (k < k1) {
t = g[k1+koff];
g[k1+koff] = g[k+koff];
g[k+koff] = t;
}
}
/* then transform in y */
ns = 1;
for (m = 0; m < indy; m++) {
ns2 = ns + ns;
km = nyh/ns;
kmr = km*nry;
for (k = 0; k < km; k++) {
k1 = ns2*k;
k2 = k1 + ns;
for (j = 0; j < ns; j++) {
j1 = j + k1;
j2 = j + k2;
s = sct[kmr*j];
t = s*g[j2+koff];
g[j2+koff] = g[j1+koff] - t;
g[j1+koff] += t;
}
}
ns = ns2;
}
}
/* unscramble modes kx = 0, nx/2 */
if ((ks==0) && (kxpi==1)) {
for (k = 1; k < nyh; k++) {
s = g[ny-k];
g[ny-k] = 0.5*(cimagf(g[k] + s) + crealf(g[k] - s)*_Complex_I);
g[k] = 0.5*(crealf(g[k] + s) + cimagf(g[k] - s)*_Complex_I);
}
}
return;
/* forward fourier transform */
L70: nryb = nxhy/ny;
nry = nxy/ny;
/* scramble modes kx = 0, nx/2 */
if ((ks==0) && (kxpi==1)) {
for (k = 1; k < nyh; k++) {
s = cimagf(g[ny-k]) + crealf(g[ny-k])*_Complex_I;
g[ny-k] = conjf(g[k] - s);
g[k] += s;
}
}
#pragma omp parallel for \
private(i,j,k,m,ns,ns2,km,kmr,k1,k2,j1,j2,koff,s,t)
for (i = kxpi-1; i < kxpt; i++) {
koff = nyv*i;
/* bit-reverse array elements in y */
for (k = 0; k < ny; k++) {
k1 = (mixup[k] - 1)/nryb;
if (k < k1) {
t = g[k1+koff];
g[k1+koff] = g[k+koff];
g[k+koff] = t;
}
}
/* then transform in y */
ns = 1;
for (m = 0; m < indy; m++) {
ns2 = ns + ns;
km = nyh/ns;
kmr = km*nry;
for (k = 0; k < km; k++) {
k1 = ns2*k;
k2 = k1 + ns;
for (j = 0; j < ns; j++) {
j1 = j + k1;
j2 = j + k2;
s = conjf(sct[kmr*j]);
t = s*g[j2+koff];
g[j2+koff] = g[j1+koff] - t;
g[j1+koff] += t;
}
}
ns = ns2;
}
}
return;
}
/*--------------------------------------------------------------------*/
void cppfft2rm2xx(float complex f[], int isign, int mixup[],
float complex sct[], int indx, int indy, int kstrt,
int kypi, int kypp, int nxvh, int kypd, int nxhyd,
int nxyhd) {
/* this subroutine performs the x part of 2 two dimensional real to
complex fast fourier transforms and their inverses, for a subset of y,
using complex arithmetic, with OpenMP,
for data which is distributed in blocks
for isign = (-1,1), input: all, output: f
for isign = -1, approximate flop count: N*(5*log2(N) + 10)/nvp
for isign = 1, approximate flop count: N*(5*log2(N) + 8)/nvp
where N = (nx/2)*ny, and nvp = number of procs
indx/indy = exponent which determines length in x/y direction,
where nx=2**indx, ny=2**indy
if isign = -1, an inverse fourier transform is performed
f[m][n][0:1] = (1/nx*ny)*sum(f[k][j][0:1]*exp(-sqrt(-1)*2pi*n*j/nx)
if isign = 1, a forward fourier transform is performed
f[k][j][0:1] = sum(f[m][n][0:1]*exp(sqrt(-1)*2pi*n*j/nx)*
kstrt = starting data block number
kypi = initial y index used
kypp = number of y indices used
nxvh = first dimension of f
kypd = second dimension of f
mixup = array of bit reversed addresses
sct = sine/cosine table
nxhyd = maximum of (nx/2,ny)
nxyhd = one half of maximum of (nx,ny)
the real data is stored in a complex array of length nx/2, ny
with the odd/even x points stored in the real/imaginary parts.
in complex notation, fourier coefficients are stored as follows:
f[k][j][0:1] = mode j,kk, where kk = k + kyp*(kstrt - 1)
0 <= j < nx/2 and 0 <= kk < ny, except for
f[k][0][0:1] = mode nx/2,kk, where ny/2+1 <= kk < ny, and
imaginary part of f[0][0][0:1] = real part of mode nx/2,0
on mode kstrt=0
imaginary part of f[0][0][0:1] = real part of mode nx/2,ny/2
on mode kstrt=(ny/2)/kyp
written by viktor k. decyk, ucla
parallel, RISC optimized version
local data */
int indx1, indx1y, nx, nxh, nxhh, ny;
int nxy, nxhy, kypt, j, k, nrx;
int i, m, ns, ns2, km, kmr, k1, k2, j1, j2, nrxb, joff;
float ani, at1;
float complex s, t, t1, t2;
indx1 = indx - 1;
indx1y = indx1 > indy ? indx1 : indy;
nx = 1L<<indx;
nxh = nx/2;
nxhh = nx/4;
ny = 1L<<indy;
nxy = nx > ny ? nx : ny;
nxhy = 1L<<indx1y;
kypt = kypi + kypp - 1;
if (kstrt > ny)
return;
if (isign > 0)
goto L100;
/* inverse fourier transform */
ani = 0.5/(((float) nx)*((float) ny));
nrxb = nxhy/nxh;
nrx = nxy/nxh;
#pragma omp parallel for \
private(i,j,k,m,ns,ns2,km,kmr,k1,k2,j1,j2,joff,at1,s,t,t1,t2)
for (i = kypi-1; i < kypt; i++) {
joff = 2*nxvh*i;
/* swap complex components */
for (j = 0; j < nxh; j++) {
at1 = cimagf(f[2*j+joff]);
f[2*j+joff] = crealf(f[2*j+joff])
+ crealf(f[1+2*j+joff])*_Complex_I;
f[1+2*j+joff] = at1 + cimagf(f[1+2*j+joff])*_Complex_I;
}
/* bit-reverse array elements in x */
for (j = 0; j < nxh; j++) {
j1 = (mixup[j] - 1)/nrxb;
if (j < j1) {
t1 = f[2*j1+joff];
t2 = f[1+2*j1+joff];
f[2*j1+joff] = f[2*j+joff];
f[1+2*j1+joff] = f[1+2*j+joff];
f[2*j+joff] = t1;
f[1+2*j+joff] = t2;
}
}
/* then transform in x */
ns = 1;
for (m = 0; m < indx1; m++) {
ns2 = ns + ns;
km = nxhh/ns;
kmr = km*nrx;
for (k = 0; k < km; k++) {
k1 = ns2*k;
k2 = k1 + ns;
for (j = 0; j < ns; j++) {
j1 = j + k1;
j2 = j + k2;
s = sct[kmr*j];
t1 = s*f[2*j2+joff];
t2 = s*f[1+2*j2+joff];
f[2*j2+joff] = f[2*j1+joff] - t1;
f[1+2*j2+joff] = f[1+2*j1+joff] - t2;
f[2*j1+joff] += t1;
f[1+2*j1+joff] += t2;
}
}
ns = ns2;
}
/* unscramble coefficients and normalize */
kmr = nxy/nx;
for (j = 1; j < nxhh; j++) {
t1 = cimagf(sct[kmr*j]) - crealf(sct[kmr*j])*_Complex_I;
for (k = 0; k < 2; k++) {
t = conjf(f[k+2*(nxh-j)+joff]);
s = f[k+2*j+joff] + t;
t = (f[k+2*j+joff] - t)*t1;
f[k+2*j+joff] = ani*(s + t);
f[k+2*(nxh-j)+joff] = ani*conjf(s - t);
}
}
for (k = 0; k < 2; k++) {
f[k+joff] = 2.0*ani*((crealf(f[k+joff]) + cimagf(f[k+joff]))
+ (crealf(f[k+joff]) - cimagf(f[k+joff]))*_Complex_I);
if (nxhh > 0)
f[k+2*nxhh+joff] = 2.0*ani*conjf(f[k+2*nxhh+joff]);
}
}
return;
/* forward fourier transform */
L100: nrxb = nxhy/nxh;
nrx = nxy/nxh;
#pragma omp parallel for \
private(i,j,k,m,ns,ns2,km,kmr,k1,k2,j1,j2,joff,at1,s,t,t1,t2)
for (i = kypi-1; i < kypt; i++) {
joff = 2*nxvh*i;
/* scramble coefficients */
kmr = nxy/nx;
for (j = 1; j < nxhh; j++) {
t1 = cimagf(sct[kmr*j]) + crealf(sct[kmr*j])*_Complex_I;
for (k = 0; k < 2; k++) {
t = conjf(f[k+2*(nxh-j)+joff]);
s = f[k+2*j+joff] + t;
t = (f[k+2*j+joff] - t)*t1;
f[k+2*j+joff] = s + t;
f[k+2*(nxh-j)+joff] = conjf(s - t);
}
}
for (k = 0; k < 2; k++) {
f[k+joff] = (crealf(f[k+joff]) + cimagf(f[k+joff]))
+ (crealf(f[k+joff]) - cimagf(f[k+joff]))*_Complex_I;
if (nxhh > 0)
f[k+2*nxhh+joff] = 2.0*conjf(f[k+2*nxhh+joff]);
}
/* bit-reverse array elements in x */
for (j = 0; j < nxh; j++) {
j1 = (mixup[j] - 1)/nrxb;
if (j < j1) {
t1 = f[2*j1+joff];
t2 = f[1+2*j1+joff];
f[2*j1+joff] = f[2*j+joff];
f[1+2*j1+joff] = f[1+2*j+joff];
f[2*j+joff] = t1;
f[1+2*j+joff] = t2;
}
}
/* then transform in x */
ns = 1;
for (m = 0; m < indx1; m++) {
ns2 = ns + ns;
km = nxhh/ns;
kmr = km*nrx;
for (k = 0; k < km; k++) {
k1 = ns2*k;
k2 = k1 + ns;
for (j = 0; j < ns; j++) {
j1 = j + k1;
j2 = j + k2;
s = conjf(sct[kmr*j]);
t1 = s*f[2*j2+joff];
t2 = s*f[1+2*j2+joff];
f[2*j2+joff] = f[2*j1+joff] - t1;
f[1+2*j2+joff] = f[1+2*j1+joff] - t2;
f[2*j1+joff] += t1;
f[1+2*j1+joff] += t2;
}
}
ns = ns2;
}
/* swap complex components */
for (j = 0; j < nxh; j++) {
at1 = cimagf(f[2*j+joff]);
f[2*j+joff] = crealf(f[2*j+joff])
+ crealf(f[1+2*j+joff])*_Complex_I;
f[1+2*j+joff] = at1 + cimagf(f[1+2*j+joff])*_Complex_I;
}
}
return;
}
/*--------------------------------------------------------------------*/
void cppfft2rm2xy(float complex g[], int isign, int mixup[],
float complex sct[], int indx, int indy, int kstrt,
int kxpi, int kxpp, int nyv, int kxp, int nxhyd,
int nxyhd) {
/* this subroutine performs the y part of 2 two dimensional real to
complex fast fourier transforms and their inverses, for a subset of x,
using complex arithmetic, with OpenMP,
for data which is distributed in blocks
for isign = (-1,1), input: all, output: g
for isign = -1, approximate flop count: N*(5*log2(N) + 10)/nvp
for isign = 1, approximate flop count: N*(5*log2(N) + 8)/nvp
where N = (nx/2)*ny, and nvp = number of procs
indx/indy = exponent which determines length in x/y direction,
where nx=2**indx, ny=2**indy
if isign = -1, an inverse fourier transform is performed
g[n][m][0:1] = sum(g[j][k][0:1]*exp(-sqrt(-1)*2pi*m*k/ny))
if isign = 1, a forward fourier transform is performed
g[j][k][0:1] = sum(g[n][m][0:1]*exp(sqrt(-1)*2pi*m*k/ny))
kstrt = starting data block number
kxpi = initial x index used
kxpp = number of x indices used
nyv = first dimension of g
kxp = number of data values per block in x
mixup = array of bit reversed addresses
sct = sine/cosine table
nxhyd = maximum of (nx/2,ny)
nxyhd = one half of maximum of (nx,ny)
the real data is stored in a complex array of length nx/2, ny
with the odd/even x points stored in the real/imaginary parts.
in complex notation, fourier coefficients are stored as follows:
g[j][k][0:1] = mode jj,k, where jj = j + kxp*(kstrt - 1)
0 <= jj < nx/2 and 0 <= k < ny, except for
g[0][k][0:1] = mode nx/2,k, where ny/2+1 <= k < ny, and
imaginary part of g[0][0][0:1] = real part of mode nx/2,0 and
imaginary part of g[0][ny/2][0:1] = real part of mode nx/2,ny/2
on node kstrt=0
written by viktor k. decyk, ucla
parallel, RISC optimized version
local data */
int indx1, indx1y, nx, nxh, ny, nyh;
int nxy, nxhy, ks, kxpt, j, k, nry;
int i, m, ns, ns2, km, kmr, k1, k2, j1, j2, nryb, koff;
float complex s, t1, t2;
indx1 = indx - 1;
indx1y = indx1 > indy ? indx1 : indy;
nx = 1L<<indx;
nxh = nx/2;
ny = 1L<<indy;
nyh = ny/2;
nxy = nx > ny ? nx : ny;
nxhy = 1L<<indx1y;
ks = kstrt - 1;
kxpt = kxpi + kxpp - 1;
if (kstrt > nxh)
return;
if (isign > 0)
goto L80;
/* inverse fourier transform */
nryb = nxhy/ny;
nry = nxy/ny;
#pragma omp parallel for \
private(i,j,k,m,ns,ns2,km,kmr,k1,k2,j1,j2,koff,s,t1,t2)
for (i = kxpi-1; i < kxpt; i++) {
koff = 2*nyv*i;
/* bit-reverse array elements in y */
for (k = 0; k < ny; k++) {
k1 = (mixup[k] - 1)/nryb;
if (k < k1) {
t1 = g[2*k1+koff];
t2 = g[1+2*k1+koff];
g[2*k1+koff] = g[2*k+koff];
g[1+2*k1+koff] = g[1+2*k+koff];
g[2*k+koff] = t1;
g[1+2*k+koff] = t2;
}
}
/* then transform in y */
ns = 1;
for (m = 0; m < indy; m++) {
ns2 = ns + ns;
km = nyh/ns;
kmr = km*nry;
for (k = 0; k < km; k++) {
k1 = ns2*k;
k2 = k1 + ns;
for (j = 0; j < ns; j++) {
j1 = j + k1;
j2 = j + k2;
s = sct[kmr*j];
t1 = s*g[2*j2+koff];
t2 = s*g[1+2*j2+koff];
g[2*j2+koff] = g[2*j1+koff] - t1;
g[1+2*j2+koff] = g[1+2*j1+koff] - t2;
g[2*j1+koff] += t1;
g[1+2*j1+koff] += t2;
}
}
ns = ns2;
}
}
/* unscramble modes kx = 0, nx/2 */
if ((ks==0) && (kxpi==1)) {
for (k = 1; k < nyh; k++) {
for (j = 0; j < 2; j++) {
s = g[j+2*(ny-k)];
g[j+2*(ny-k)] = 0.5*(cimagf(g[j+2*k] + s)
+ crealf(g[j+2*k] - s)*_Complex_I);
g[j+2*k] = 0.5*(crealf(g[j+2*k] + s)
+ cimagf(g[j+2*k] - s)*_Complex_I);
}
}
}
return;
/* forward fourier transform */
L80: nryb = nxhy/ny;
nry = nxy/ny;
/* scramble modes kx = 0, nx/2 */
if ((ks==0) && (kxpi==1)) {
for (k = 1; k < nyh; k++) {
for (j = 0; j < 2; j++) {
s = cimagf(g[j+2*(ny-k)])
+ crealf(g[j+2*(ny-k)])*_Complex_I;
g[j+2*(ny-k)] = conjf(g[j+2*k] - s);
g[j+2*k] += s;
}
}
}
#pragma omp parallel for \
private(i,j,k,m,ns,ns2,km,kmr,k1,k2,j1,j2,koff,s,t1,t2)
for (i = kxpi-1; i < kxpt; i++) {
koff = 2*nyv*i;
/* bit-reverse array elements in y */
for (k = 0; k < ny; k++) {
k1 = (mixup[k] - 1)/nryb;
if (k < k1) {
t1 = g[2*k1+koff];
t2 = g[1+2*k1+koff];
g[2*k1+koff] = g[2*k+koff];
g[1+2*k1+koff] = g[1+2*k+koff];
g[2*k+koff] = t1;
g[1+2*k+koff] = t2;
}
}
/* then transform in y */
ns = 1;
for (m = 0; m < indy; m++) {
ns2 = ns + ns;
km = nyh/ns;
kmr = km*nry;
for (k = 0; k < km; k++) {
k1 = ns2*k;
k2 = k1 + ns;
for (j = 0; j < ns; j++) {
j1 = j + k1;
j2 = j + k2;
s = conjf(sct[kmr*j]);
t1 = s*g[2*j2+koff];
t2 = s*g[1+2*j2+koff];
g[2*j2+koff] = g[2*j1+koff] - t1;
g[1+2*j2+koff] = g[1+2*j1+koff] - t2;
g[2*j1+koff] += t1;
g[1+2*j1+koff] += t2;
}
}
ns = ns2;
}
}
return;
}
/*--------------------------------------------------------------------*/
void cwppfft2rm(float complex f[], float complex g[],
float complex bs[], float complex br[], int isign,
int ntpose, int mixup[], float complex sct[],
float *ttp, int indx, int indy, int kstrt, int nvp,
int nxvh, int nyv, int kxp, int kyp, int kypd,
int nxhyd, int nxyhd) {
/* wrapper function for parallel real to complex fft */
/* parallelized with OpenMP */
/* local data */
int nxh, ny, ks, kxpp, kypp;
static int kxpi = 1, kypi = 1;
float tf;
double dtime;
/* calculate range of indices */
nxh = 1L<<(indx - 1);
ny = 1L<<indy;
ks = kstrt - 1;
kxpp = nxh - kxp*ks;
kxpp = 0 > kxpp ? 0 : kxpp;
kxpp = kxp < kxpp ? kxp : kxpp;
kypp = ny - kyp*ks;
kypp = 0 > kypp ? 0 : kypp;
kypp = kyp < kypp ? kyp : kypp;
/* inverse fourier transform */
if (isign < 0) {
/* perform x fft */
cppfft2rmxx(f,isign,mixup,sct,indx,indy,kstrt,kypi,kypp,nxvh,kypd,
nxhyd,nxyhd);
/* transpose f array to g */
cpwtimera(-1,ttp,&dtime);
cpptpose(f,g,bs,br,nxh,ny,kxp,kyp,kstrt,nvp,nxvh,nyv,kxp,kypd);
cpwtimera(1,ttp,&dtime);
/* perform y fft */
cppfft2rmxy(g,isign,mixup,sct,indx,indy,kstrt,kxpi,kxpp,nyv,kxp,
nxhyd,nxyhd);
/* transpose g array to f */
if (ntpose==0) {
cpwtimera(-1,&tf,&dtime);
cpptpose(g,f,br,bs,ny,nxh,kyp,kxp,kstrt,nvp,nyv,nxvh,kypd,kxp);
cpwtimera(1,&tf,&dtime);
}
}
/* forward fourier transform */
else if (isign > 0) {
/* transpose f array to g */
if (ntpose==0) {
cpwtimera(-1,&tf,&dtime);
cpptpose(f,g,bs,br,nxh,ny,kxp,kyp,kstrt,nvp,nxvh,nyv,kxp,kypd);
cpwtimera(1,&tf,&dtime);
}
/* perform y fft */
cppfft2rmxy(g,isign,mixup,sct,indx,indy,kstrt,kxpi,kxpp,nyv,kxp,
nxhyd,nxyhd);
/* transpose g array to f */
cpwtimera(-1,ttp,&dtime);
cpptpose(g,f,br,bs,ny,nxh,kyp,kxp,kstrt,nvp,nyv,nxvh,kypd,kxp);
cpwtimera(1,ttp,&dtime);
/* perform x fft */
cppfft2rmxx(f,isign,mixup,sct,indx,indy,kstrt,kypi,kypp,nxvh,kypd,
nxhyd,nxyhd);
}
if (ntpose==0)
*ttp += tf;
return;
}
/*--------------------------------------------------------------------*/
void cwppfft2rm2(float complex f[], float complex g[],
float complex bs[], float complex br[], int isign,
int ntpose, int mixup[], float complex sct[],
float *ttp, int indx, int indy, int kstrt, int nvp,
int nxvh, int nyv, int kxp, int kyp, int kypd,
int nxhyd, int nxyhd) {
/* wrapper function for parallel real to complex fft */
/* parallelized with OpenMP */
/* local data */
int nxh, ny, ks, kxpp, kypp;
static int kxpi = 1, kypi = 1;
float tf;
double dtime;
/* calculate range of indices */
nxh = 1L<<(indx - 1);
ny = 1L<<indy;
ks = kstrt - 1;
kxpp = nxh - kxp*ks;
kxpp = 0 > kxpp ? 0 : kxpp;
kxpp = kxp < kxpp ? kxp : kxpp;
kypp = ny - kyp*ks;
kypp = 0 > kypp ? 0 : kypp;
kypp = kyp < kypp ? kyp : kypp;
/* inverse fourier transform */
if (isign < 0) {
/* perform x fft */
cppfft2rm2xx(f,isign,mixup,sct,indx,indy,kstrt,kypi,kypp,nxvh,
kypd,nxhyd,nxyhd);
/* transpose f array to g */
cpwtimera(-1,ttp,&dtime);
cppntpose(f,g,bs,br,nxh,ny,kxp,kyp,kstrt,nvp,2,nxvh,nyv,kxp,kypd);
cpwtimera(1,ttp,&dtime);
/* perform y fft */
cppfft2rm2xy(g,isign,mixup,sct,indx,indy,kstrt,kxpi,kxpp,nyv,kxp,
nxhyd,nxyhd);
/* transpose g array to f */
if (ntpose==0) {
cpwtimera(-1,&tf,&dtime);
cppntpose(g,f,br,bs,ny,nxh,kyp,kxp,kstrt,nvp,2,nyv,nxvh,kypd,
kxp);
cpwtimera(1,&tf,&dtime);
}
}
/* forward fourier transform */
else if (isign > 0) {
/* transpose f array to g */
if (ntpose==0) {
cpwtimera(-1,&tf,&dtime);
cppntpose(f,g,bs,br,nxh,ny,kxp,kyp,kstrt,nvp,2,nxvh,nyv,kxp,
kypd);
cpwtimera(1,&tf,&dtime);
}
/* perform y fft */
cppfft2rm2xy(g,isign,mixup,sct,indx,indy,kstrt,kxpi,kxpp,nyv,kxp,
nxhyd,nxyhd);
/* transpose g array to f */
cpwtimera(-1,ttp,&dtime);
cppntpose(g,f,br,bs,ny,nxh,kyp,kxp,kstrt,nvp,2,nyv,nxvh,kypd,kxp);
cpwtimera(1,ttp,&dtime);
/* perform x fft */
cppfft2rm2xx(f,isign,mixup,sct,indx,indy,kstrt,kypi,kypp,nxvh,
kypd,nxhyd,nxyhd);
}
if (ntpose==0)
*ttp += tf;
return;
}
/*--------------------------------------------------------------------*/
void cpppcopyout(float part[], float ppart[], int kpic[], int *npp,
int npmax, int nppmx, int idimp, int mxyp1, int *irc) {
/* for 2d code, this subroutine copies segmented particle data ppart to
the array part with original tiled layout
spatial decomposition in y direction
input: all except part, npp, irc, output: part, npp, irc
part[j][i] = i-th coordinate for particle j
ppart[k][j][i] = i-th coordinate for particle j in tile k
kpic = number of particles per tilees
npp = number of particles in partition
npmax = maximum number of particles in each partition
nppmx = maximum number of particles in tile
idimp = size of phase space = 5
mxyp1 = total number of tiles in partition
irc = maximum overflow, returned only if error occurs, when irc > 0
local data */
int i, j, k, npoff, nppp, ne, ierr;
npoff = 0;
ierr = 0;
/* loop over tiles */
for (k = 0; k < mxyp1; k++) {
nppp = kpic[k];
ne = nppp + npoff;
if (ne > npmax)
ierr = ierr > ne-npmax ? ierr : ne-npmax;
if (ierr > 0)
nppp = 0;
/* loop over particles in tile */
for (j = 0; j < nppp; j++) {
for (i = 0; i < idimp; i++) {
part[i+idimp*(j+npoff)] = ppart[i+idimp*(j+nppmx*k)];
}
}
npoff += nppp;
}
*npp = npoff;
if (ierr > 0)
*irc = ierr;
return;
}
/* Interfaces to Fortran */
/*--------------------------------------------------------------------*/
void cpdicomp2l_(float *edges, int *nyp, int *noff, int *nypmx,
int *nypmn, int *ny, int *kstrt, int *nvp, int *idps) {
cpdicomp2l(edges,nyp,noff,nypmx,nypmn,*ny,*kstrt,*nvp,*idps);
return;
}
/*--------------------------------------------------------------------*/
void cpdistr2_(float *part, float *edges, int *npp, int *nps, float *vtx,
float *vty, float *vdx, float *vdy, int *npx, int *npy,
int *nx, int *ny, int *idimp, int *npmax, int *idps,
int *ipbc, int *ierr) {
cpdistr2(part,edges,npp,*nps,*vtx,*vty,*vdx,*vdy,*npx,*npy,*nx,*ny,
*idimp,*npmax,*idps,*ipbc,ierr);
return;
}
/*--------------------------------------------------------------------*/
void cppdblkp2l_(float *part, int *kpic, int *npp, int *noff,
int *nppmx, int *idimp, int *npmax, int *mx, int *my,
int *mx1,int *mxyp1, int *irc) {
cppdblkp2l(part,kpic,*npp,*noff,nppmx,*idimp,*npmax,*mx,*my,*mx1,
*mxyp1,irc);
return;
}
/*--------------------------------------------------------------------*/
void cpppmovin2l_(float *part, float *ppart, int *kpic, int *npp,
int *noff, int *nppmx, int *idimp, int *npmax,
int *mx, int *my, int *mx1, int *mxyp1, int *irc) {
cpppmovin2l(part,ppart,kpic,*npp,*noff,*nppmx,*idimp,*npmax,*mx,*my,
*mx1,*mxyp1,irc);
return;
}
/*--------------------------------------------------------------------*/
void cpppcheck2l_(float *ppart, int *kpic, int *noff, int *nyp,
int *idimp, int *nppmx, int *nx, int *mx, int *my,
int *mx1, int *myp1, int *irc) {
cpppcheck2l(ppart,kpic,*noff,*nyp,*idimp,*nppmx,*nx,*mx,*my,*mx1,
*myp1,irc);
return;
}
/*--------------------------------------------------------------------*/
void cppgppush2l_(float *ppart, float *fxy, int *kpic, int *noff,
int *nyp, float *qbm, float *dt, float *ek, int *nx,
int *ny, int *mx, int *my, int *idimp, int *nppmx,
int *nxv, int *nypmx, int *mx1, int *mxyp1,
int *ipbc) {
cppgppush2l(ppart,fxy,kpic,*noff,*nyp,*qbm,*dt,ek,*nx,*ny,*mx,*my,
*idimp,*nppmx,*nxv,*nypmx,*mx1,*mxyp1,*ipbc);
return;
}
/*--------------------------------------------------------------------*/
void cppgppushf2l_(float *ppart, float *fxy, int *kpic, int *ncl,
int *ihole, int *noff, int *nyp, float *qbm,
float *dt, float *ek, int *nx, int *ny, int *mx,
int *my, int *idimp, int *nppmx, int *nxv,
int *nypmx, int *mx1, int *mxyp1, int *ntmax,
int *irc) {
cppgppushf2l(ppart,fxy,kpic,ncl,ihole,*noff,*nyp,*qbm,*dt,ek,*nx,*ny,
*mx,*my,*idimp,*nppmx,*nxv,*nypmx,*mx1,*mxyp1,*ntmax,
irc);
return;
}
/*--------------------------------------------------------------------*/
void cppgppost2l_(float *ppart, float *q, int *kpic, int *noff,
float *qm, int *idimp, int *nppmx, int *mx, int *my,
int *nxv, int *nypmx, int *mx1, int *mxyp1) {
cppgppost2l(ppart,q,kpic,*noff, *qm,*idimp,*nppmx,*mx,*my,*nxv,
*nypmx,*mx1,*mxyp1);
return;
}
/*--------------------------------------------------------------------*/
void cppporder2la_(float *ppart, float *ppbuff, float *sbufl,
float *sbufr, int *kpic, int *ncl, int *ihole,
int *ncll, int *nclr, int *noff, int *nyp,
int *idimp, int *nppmx, int *nx, int *ny, int *mx,
int *my, int *mx1, int *myp1, int *npbmx, int *ntmax,
int *nbmax, int *irc) {
cppporder2la(ppart,ppbuff,sbufl,sbufr,kpic,ncl,ihole,ncll,nclr,*noff,
*nyp,*idimp,*nppmx,*nx,*ny,*mx,*my,*mx1,*myp1,*npbmx,
*ntmax,*nbmax,irc);
return;
}
/*--------------------------------------------------------------------*/
void cppporderf2la_(float *ppart, float *ppbuff, float *sbufl,
float *sbufr, int *ncl, int *ihole, int *ncll,
int *nclr, int *idimp, int *nppmx, int *mx1,
int *myp1, int *npbmx, int *ntmax, int *nbmax,
int *irc) {
cppporderf2la(ppart,ppbuff,sbufl,sbufr,ncl,ihole,ncll,nclr,*idimp,
*nppmx,*mx1,*myp1,*npbmx,*ntmax,*nbmax,irc);
return;
}
/*--------------------------------------------------------------------*/
void cppporder2lb_(float *ppart, float *ppbuff, float *rbufl,
float *rbufr, int *kpic, int *ncl, int *ihole,
int *mcll, int *mclr, int *idimp, int *nppmx,
int *mx1, int *myp1, int *npbmx, int *ntmax,
int *nbmax, int *irc) {
cppporder2lb(ppart,ppbuff,rbufl,rbufr,kpic,ncl,ihole,mcll,mclr,
*idimp,*nppmx,*mx1,*myp1,*npbmx,*ntmax,*nbmax,irc);
return;
}
/*--------------------------------------------------------------------*/
void cppcguard2xl_(float *fxy, int *nyp, int *nx, int *ndim, int *nxe,
int *nypmx) {
cppcguard2xl(fxy,*nyp,*nx,*ndim,*nxe,*nypmx);
return;
}
/*--------------------------------------------------------------------*/
void cppaguard2xl_(float *q, int *nyp, int *nx, int *nxe, int *nypmx) {
cppaguard2xl(q,*nyp,*nx,*nxe,*nypmx);
return;
}
/*--------------------------------------------------------------------*/
void cmppois22_(float complex *q, float complex *fxy, int *isign,
float complex *ffc, float *ax, float *ay, float *affp,
float *we, int *nx, int *ny, int *kstrt, int *nyv,
int *kxp, int *nyhd) {
cmppois22(q,fxy,*isign,ffc,*ax,*ay,*affp,we,*nx,*ny,*kstrt,*nyv,*kxp,
*nyhd);
return;
}
/*--------------------------------------------------------------------*/
void cwpfft2rinit_(int *mixup, float complex *sct, int *indx, int *indy,
int *nxhyd, int *nxyhd) {
cwpfft2rinit(mixup,sct,*indx,*indy,*nxhyd,*nxyhd);
return;
}
/*--------------------------------------------------------------------*/
void cppfft2rmxx_(float complex *f, int *isign, int *mixup,
float complex *sct, int *indx, int *indy, int *kstrt,
int *kypi, int *kypp, int *nxvh, int *kypd,
int *nxhyd, int *nxyhd) {
cppfft2rmxx(f,*isign,mixup,sct,*indx,*indy,*kstrt,*kypi,*kypp,*nxvh,
*kypd,*nxhyd,*nxyhd);
return;
}
/*--------------------------------------------------------------------*/
void cppfft2rmxy_(float complex *g, int *isign, int *mixup,
float complex *sct, int *indx, int *indy, int *kstrt,
int *kxpi, int *kxpp, int *nyv, int *kxp, int *nxhyd,
int *nxyhd) {
cppfft2rmxy(g,*isign,mixup,sct,*indx,*indy,*kstrt,*kxpi,*kxpp,*nyv,
*kxp,*nxhyd,*nxyhd);
return;
}
/*--------------------------------------------------------------------*/
void cppfft2rm2xx_(float complex *f, int *isign, int *mixup,
float complex *sct, int *indx, int *indy, int *kstrt,
int *kypi, int *kypp, int *nxvh, int *kypd,
int *nxhyd, int *nxyhd) {
cppfft2rm2xx(f,*isign,mixup,sct,*indx,*indy,*kstrt,*kypi,*kypp,*nxvh,
*kypd,*nxhyd,*nxyhd);
return;
}
/*--------------------------------------------------------------------*/
void cppfft2rm2xy_(float complex *g, int *isign, int *mixup,
float complex *sct, int *indx, int *indy, int *kstrt,
int *kxpi, int *kxpp, int *nyv, int *kxp, int *nxhyd,
int *nxyhd) {
cppfft2rm2xy(g,*isign,mixup,sct,*indx,*indy,*kstrt,*kxpi,*kxpp,*nyv,
*kxp,*nxhyd,*nxyhd);
return;
}
/*--------------------------------------------------------------------*/
void cwppfft2rm_(float complex *f, float complex *g, float complex *bs,
float complex *br, int *isign, int *ntpose, int *mixup,
float complex *sct, float *ttp, int *indx, int *indy,
int *kstrt, int *nvp, int *nxvh, int *nyv, int *kxp,
int *kyp, int *kypd, int *nxhyd, int *nxyhd) {
cwppfft2rm(f,g,bs,br,*isign,*ntpose,mixup,sct,ttp,*indx,*indy,*kstrt,
*nvp,*nxvh,*nyv,*kxp,*kyp,*kypd,*nxhyd,*nxyhd);
return;
}
/*--------------------------------------------------------------------*/
void cwppfft2rm2_(float complex *f, float complex *g, float complex *bs,
float complex *br, int *isign, int *ntpose,
int *mixup, float complex *sct, float *ttp, int *indx,
int *indy, int *kstrt, int *nvp, int *nxvh, int *nyv,
int *kxp, int *kyp, int *kypd, int *nxhyd,
int *nxyhd) {
cwppfft2rm2(f,g,bs,br,*isign,*ntpose,mixup,sct,ttp,*indx,*indy,
*kstrt,*nvp,*nxvh,*nyv,*kxp,*kyp,*kypd,*nxhyd,*nxyhd);
return;
}
|
GB_unop__exp_fc32_fc32.c | //------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop_apply__exp_fc32_fc32
// op(A') function: GB_unop_tran__exp_fc32_fc32
// C type: GxB_FC32_t
// A type: GxB_FC32_t
// cast: GxB_FC32_t cij = aij
// unaryop: cij = cexpf (aij)
#define GB_ATYPE \
GxB_FC32_t
#define GB_CTYPE \
GxB_FC32_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
GxB_FC32_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = cexpf (x) ;
// casting
#define GB_CAST(z, aij) \
GxB_FC32_t z = aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GxB_FC32_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
GxB_FC32_t z = aij ; \
Cx [pC] = cexpf (z) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_EXP || GxB_NO_FC32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_apply__exp_fc32_fc32
(
GxB_FC32_t *Cx, // Cx and Ax may be aliased
const GxB_FC32_t *Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
GxB_FC32_t aij = Ax [p] ;
GxB_FC32_t z = aij ;
Cx [p] = cexpf (z) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_tran__exp_fc32_fc32
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *GB_RESTRICT *Rowcounts,
GBI_single_iterator Iter,
const int64_t *GB_RESTRICT A_slice,
int naslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#define GB_PHASE_2_OF_2
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
tclo.pluto.c | #include <omp.h>
#include <math.h>
#define ceild(n,d) ceil(((double)(n))/((double)(d)))
#define floord(n,d) floor(((double)(n))/((double)(d)))
#define max(x,y) ((x) > (y)? (x) : (y))
#define min(x,y) ((x) < (y)? (x) : (y))
#include<stdio.h>
#include<stdlib.h>
void printMatrix(int **, int);
int **allocateMatrix(int);
void computeTC(int **matrix, int N)
{
int **reach = allocateMatrix(N);
int i, j, k;
for (i = 0; i < N; i++)
for (j = 0; j < N; j++)
reach[i][j] = matrix[i][j];
int t1, t2, t3, t4, t5;
int lb, ub, lbp, ubp, lb2, ub2;
register int lbv, ubv;
if (N >= 1) {
for (t1=0;t1<=N-1;t1++) {
for (t2=0;t2<=floord(N-1,16);t2++) {
lbp=max(0,ceild(32*t2-N+1,32));
ubp=min(floord(N-1,32),t2);
#pragma omp parallel for private(lbv,ubv,t4,t5)
for (t3=lbp;t3<=ubp;t3++) {
for (t4=32*t2-32*t3;t4<=min(N-1,32*t2-32*t3+31);t4++) {
for (t5=32*t3;t5<=min(N-1,32*t3+31);t5++) {
reach[t4][t5] = reach[t4][t5] || (reach[t4][t1] && reach[t1][t5]);;
}
}
}
}
}
}
printMatrix(reach, N);
}
void printMatrix(int **matrix, int N)
{
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
printf ("%d ", matrix[i][j]);
printf("\n");
}
}
int **allocateMatrix(int N)
{
int **t = (int **) malloc(sizeof(int *) * N);
for (int i = 0 ; i < N ; i++)
{
t[i] = (int *) malloc(sizeof(int) * N);
}
return t;
}
int main(void)
{
const int N = 4;
int **graph = allocateMatrix(N);
int g[4][4]= { {1, 1, 0, 1},
{0, 1, 1, 0},
{0, 0, 1, 1},
{0, 0, 0, 1}
};
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
graph[i][j] = g [i][j];
printMatrix(graph, 4);
computeTC(graph, 4);
return 0;
}
|
GB_reduce_each_index.c | //------------------------------------------------------------------------------
// GB_reduce_each_index: T(i)=reduce(A(i,:)), reduce a matrix to a vector
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// Reduce a matrix to a vector. All entries in A(i,:) are reduced to T(i).
// First, all threads reduce their slice to their own workspace, operating on
// roughly the same number of entries each. The vectors in A are ignored; the
// reduction only depends on the indices. Next, the threads cooperate to
// reduce all workspaces to the workspace of thread 0. Finally, this last
// workspace is collected into T.
{
//--------------------------------------------------------------------------
// get A
//--------------------------------------------------------------------------
const GB_ATYPE *restrict Ax = A->x ;
const int64_t *restrict Ai = A->i ;
const int64_t n = A->vlen ;
size_t zsize = ttype->size ;
//--------------------------------------------------------------------------
// allocate workspace for each thread
//--------------------------------------------------------------------------
int ntasks = 256 * nthreads ;
ntasks = GB_IMIN (ntasks, n) ;
GB_CTYPE *restrict *Works = NULL ; // size nth
bool *restrict *Marks = NULL ; // size nth
int64_t *restrict Tnz = NULL ; // size nth
int64_t *restrict Count = NULL ; // size ntasks+1
GB_CALLOC_MEMORY (Works, nth, sizeof (GB_CTYPE *)) ;
GB_CALLOC_MEMORY (Marks, nth, sizeof (bool *)) ;
GB_CALLOC_MEMORY (Tnz, nth, sizeof (int64_t)) ;
GB_CALLOC_MEMORY (Count, ntasks+1, sizeof (int64_t)) ;
bool ok = (Works != NULL && Marks != NULL && Tnz != NULL && Count != NULL) ;
// This does not need to be parallel. The calloc does not take O(n) time.
if (ok)
{
for (int tid = 0 ; tid < nth ; tid++)
{
GB_MALLOC_MEMORY (Works [tid], n, zsize) ;
GB_CALLOC_MEMORY (Marks [tid], n, sizeof (bool)) ;
ok = ok && (Works [tid] != NULL && Marks [tid] != NULL) ;
}
}
if (!ok)
{
// out of memory
if (Works != NULL)
{
for (int tid = 0 ; tid < nth ; tid++)
{
GB_FREE_MEMORY (Works [tid], n, zsize) ;
}
}
if (Marks != NULL)
{
for (int tid = 0 ; tid < nth ; tid++)
{
GB_FREE_MEMORY (Marks [tid], n, sizeof (bool)) ;
}
}
GB_FREE_MEMORY (Works, nth, sizeof (GB_CTYPE *)) ;
GB_FREE_MEMORY (Marks, nth, sizeof (bool *)) ;
GB_FREE_MEMORY (Tnz, nth, sizeof (int64_t)) ;
GB_FREE_MEMORY (Count, ntasks+1, sizeof (int64_t)) ;
return (GB_OUT_OF_MEMORY) ;
}
//--------------------------------------------------------------------------
// reduce each slice in its own workspace
//--------------------------------------------------------------------------
// each thread reduces its own slice in parallel
#pragma omp parallel for num_threads(nth) schedule(static)
for (int tid = 0 ; tid < nth ; tid++)
{
//----------------------------------------------------------------------
// get the workspace for this thread
//----------------------------------------------------------------------
GB_CTYPE *restrict Work = Works [tid] ;
bool *restrict Mark = Marks [tid] ;
int64_t my_tnz = 0 ;
//----------------------------------------------------------------------
// reduce the entries
//----------------------------------------------------------------------
for (int64_t p = pstart_slice [tid] ; p < pstart_slice [tid+1] ;p++)
{
int64_t i = Ai [p] ;
// ztype aij = (ztype) Ax [p], with typecast
GB_SCALAR (aij) ;
GB_CAST_ARRAY_TO_SCALAR (aij, Ax, p) ;
if (!Mark [i])
{
// first time index i has been seen
// Work [i] = aij ; no typecast
GB_COPY_SCALAR_TO_ARRAY (Work, i, aij) ;
Mark [i] = true ;
my_tnz++ ;
}
else
{
// Work [i] += aij ; no typecast
GB_ADD_SCALAR_TO_ARRAY (Work, i, aij) ;
}
}
Tnz [tid] = my_tnz ;
}
//--------------------------------------------------------------------------
// reduce all workspace to Work [0] and count # entries in T
//--------------------------------------------------------------------------
GB_CTYPE *restrict Work0 = Works [0] ;
bool *restrict Mark0 = Marks [0] ;
int64_t tnz = Tnz [0] ;
if (nth > 1)
{
#pragma omp parallel for num_threads(nthreads) schedule(static) \
reduction(+:tnz)
for (int64_t i = 0 ; i < n ; i++)
{
for (int tid = 1 ; tid < nth ; tid++)
{
const bool *restrict Mark = Marks [tid] ;
if (Mark [i])
{
// thread tid has a contribution to index i
const GB_CTYPE *restrict Work = Works [tid] ;
if (!Mark0 [i])
{
// first time index i has been seen
// Work0 [i] = Work [i] ; no typecast
GB_COPY_ARRAY_TO_ARRAY (Work0, i, Work, i) ;
Mark0 [i] = true ;
tnz++ ;
}
else
{
// Work0 [i] += Work [i] ; no typecast
GB_ADD_ARRAY_TO_ARRAY (Work0, i, Work, i) ;
}
}
}
}
// free all but workspace for thread 0
for (int tid = 1 ; tid < nth ; tid++)
{
GB_FREE_MEMORY (Works [tid], n, zsize) ;
GB_FREE_MEMORY (Marks [tid], n, sizeof (bool)) ;
}
}
//--------------------------------------------------------------------------
// free workspace
//--------------------------------------------------------------------------
GB_FREE_MEMORY (Works, nth, sizeof (GB_CTYPE *)) ;
GB_FREE_MEMORY (Marks, nth, sizeof (bool *)) ;
GB_FREE_MEMORY (Tnz, nth, sizeof (int64_t)) ;
//--------------------------------------------------------------------------
// allocate T
//--------------------------------------------------------------------------
// since T is a GrB_Vector, it is CSC and not hypersparse
GB_CREATE (&T, ttype, n, 1, GB_Ap_calloc, true,
GB_FORCE_NONHYPER, GB_HYPER_DEFAULT, 1, tnz, true, Context) ;
if (info != GrB_SUCCESS)
{
// out of memory
GB_FREE_MEMORY (Work0, n, zsize) ;
GB_FREE_MEMORY (Mark0, n, sizeof (bool)) ;
GB_FREE_MEMORY (Count, ntasks+1, sizeof (int64_t)) ;
return (GB_OUT_OF_MEMORY) ;
}
T->p [0] = 0 ;
T->p [1] = tnz ;
int64_t *restrict Ti = T->i ;
GB_CTYPE *restrict Tx = T->x ;
T->nvec_nonempty = (tnz > 0) ? 1 : 0 ;
//--------------------------------------------------------------------------
// gather the results into T
//--------------------------------------------------------------------------
if (tnz == n)
{
//----------------------------------------------------------------------
// T is dense: transplant Work0 into T->x
//----------------------------------------------------------------------
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (int64_t i = 0 ; i < n ; i++)
{
Ti [i] = i ;
}
GB_FREE_MEMORY (T->x, n, zsize) ;
T->x = Work0 ;
Work0 = NULL ;
}
else
{
//----------------------------------------------------------------------
// T is sparse: gather from Work0 and Mark0
//----------------------------------------------------------------------
if (nthreads == 1)
{
//------------------------------------------------------------------
// gather sparse T using a single thread
//------------------------------------------------------------------
int64_t p = 0 ;
for (int64_t i = 0 ; i < n ; i++)
{
if (Mark0 [i])
{
Ti [p] = i ;
// Tx [p] = Work0 [i], no typecast
GB_COPY_ARRAY_TO_ARRAY (Tx, p, Work0, i) ;
p++ ;
}
}
ASSERT (p == tnz) ;
}
else
{
//------------------------------------------------------------------
// gather sparse T using multiple threads
//------------------------------------------------------------------
// Some tasks may be completely empty and thus take no time at all;
// 256 tasks per thread are created for better load balancing.
#pragma omp parallel for num_threads(nthreads) schedule(dynamic)
for (int taskid = 0 ; taskid < ntasks ; taskid++)
{
int64_t ifirst, ilast, p = 0 ;
GB_PARTITION (ifirst, ilast, n, taskid, ntasks) ;
for (int64_t i = ifirst ; i < ilast ; i++)
{
p += Mark0 [i] ;
}
Count [taskid] = p ;
}
GB_cumsum (Count, ntasks, NULL, 1) ;
#pragma omp parallel for num_threads(nthreads) schedule(dynamic)
for (int64_t taskid = 0 ; taskid < ntasks ; taskid++)
{
int64_t ifirst, ilast, p = Count [taskid] ;
int64_t my_count = (Count [taskid+1] - p) ;
GB_PARTITION (ifirst, ilast, n, taskid, ntasks) ;
if (my_count > 0)
{
for (int64_t i = ifirst ; i < ilast ; i++)
{
if (Mark0 [i])
{
Ti [p] = i ;
// Tx [p] = Work0 [i], no typecast
GB_COPY_ARRAY_TO_ARRAY (Tx, p, Work0, i) ;
p++ ;
}
}
}
}
#ifdef GB_DEBUG
// check result using a single thread
int64_t p = 0 ;
for (int64_t i = 0 ; i < n ; i++)
{
if (Mark0 [i])
{
ASSERT (Ti [p] == i) ;
p++ ;
}
}
ASSERT (p == tnz) ;
#endif
}
}
//--------------------------------------------------------------------------
// free workspace
//--------------------------------------------------------------------------
GB_FREE_MEMORY (Count, ntasks+1, sizeof (int64_t)) ;
GB_FREE_MEMORY (Work0, n, zsize) ;
GB_FREE_MEMORY (Mark0, n, sizeof (bool)) ;
}
|
quicksort_par.c | /*
* Recursive parallel implementation of Quicksort (not optimized!)
* This code is to be used in conjunction with exercises in module [B1] Hybrid Algorithm
*
* @author: Apan Qasem <apan@txstate.edu>
* @date: 04/02/20
*
* @update: 03/13/21
*/
#include<stdlib.h>
#include<stdio.h>
#include<omp.h>
#define VAL_RANGE 1024
#define ELEMENTS_TO_VERIFY 5
void swap(double *x, double *y) {
double tmp;
tmp = (*x);
(*x) = (*y);
(*y) = tmp;
return;
}
/*
* partition array for quicksort
* - move pivot to far right
* - accumulate values smaller than pivot to the left
*/
int partition(double values[], int left, int right, int pivotIndex) {
double pivotValue = values[pivotIndex];
swap(&values[pivotIndex],&values[right]); // Move pivot to end
int storeIndex = left;
for(int i = left; i < right; i++) {
if (values[i] < pivotValue) {
swap(&values[i],&values[storeIndex]);
storeIndex++;
}
}
swap(&values[storeIndex],&values[right]); // Move pivot to its final place
return storeIndex;
}
/*
* recursive quicksort
*/
void quickSort(double values[], int left, int right) {
#pragma omp parallel
{
#pragma omp single
{
if (left < right) {
int pivotIndex = (left + right)/2;
int pivotNewIndex = partition(values, left, right, pivotIndex);
#pragma omp task
quickSort(values, left, pivotNewIndex - 1);
#pragma omp task
quickSort(values, pivotNewIndex + 1, right);
}
}
}
return;
}
/*
* display array contents
*/
void display(double values[], long long N) {
for (int i = 0; i < N; i++)
fprintf(stdout, "%3.4f ", values[i]);
fprintf(stdout, "\n");
}
int main(int argc, char *argv[]) {
if (argc < 3) {
printf("usage: \n");
printf(" ./quicksort N threads\n");
printf(" N = input size\n");
printf(" t = number of OpenMP threads\n");
exit(0);
}
long long N = atoi(argv[1]);
unsigned threads = atoi(argv[2]);
omp_set_num_threads(threads);
double *values = (double *) malloc(sizeof(double) * N);
for (int i = 0; i < N; i++)
values[i] = rand() / (double) (RAND_MAX/VAL_RANGE);
quickSort(values, 0, N - 1);
fprintf(stdout, "Sorted values [0..%d]: ", ELEMENTS_TO_VERIFY - 1);
display(values, ELEMENTS_TO_VERIFY);
return 0;
}
|
restrictpointer1-orig-no.c | /*
Copyright (c) 2017, Lawrence Livermore National Security, LLC.
Produced at the Lawrence Livermore National Laboratory
Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund,
Markus Schordan, and Ian Karlin
(email: liao6@llnl.gov, lin32@llnl.gov, asplund1@llnl.gov,
schordan1@llnl.gov, karlin1@llnl.gov)
LLNL-CODE-732144
All rights reserved.
This file is part of DataRaceBench. For details, see
https://github.com/LLNL/dataracebench. Please also see the LICENSE file
for our additional BSD notice.
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 disclaimer below.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the disclaimer (as noted below)
in the documentation and/or other materials provided with the
distribution.
* Neither the name of the LLNS/LLNL 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 LAWRENCE LIVERMORE NATIONAL
SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY 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.
*/
// restrict pointers: no aliasing
// Array initialization using assignments.
//
// C99 is needed to compile this code
// e.g. gcc -std=c99 -c Stress-1.c
//
#include <stdlib.h>
typedef double real8;
void StressCheckEpsFail(real8 * restrict newSxx, real8 * restrict newSyy, int length)
{
int i;
#pragma omp parallel for private (i) firstprivate (length)
for (i = 0; i <= length - 1; i += 1) {
newSxx[i] = 0.0;
newSyy[i] = 0.0;
}
}
int main()
{
int length=1000;
real8* newSxx = malloc (length* sizeof (real8));
real8* newSyy = malloc (length* sizeof (real8));
StressCheckEpsFail (newSxx, newSyy, length);
free (newSxx);
free (newSyy);
return 0;
}
|
Percent.h | /*
Copyright (c) 2013, Project OSRM, Dennis Luxen, others
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.
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 HOLDER 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 PERCENT_H
#define PERCENT_H
#include "../Util/OpenMPWrapper.h"
#include <iostream>
class Percent
{
public:
explicit Percent(unsigned max_value, unsigned step = 5) { reinit(max_value, step); }
// Reinitializes
void reinit(unsigned max_value, unsigned step = 5)
{
m_max_value = max_value;
m_current_value = 0;
m_percent_interval = m_max_value / 100;
m_next_threshold = m_percent_interval;
m_last_percent = 0;
m_step = step;
}
// If there has been significant progress, display it.
void printStatus(unsigned current_value)
{
if (current_value >= m_next_threshold)
{
m_next_threshold += m_percent_interval;
printPercent(current_value / (double)m_max_value * 100);
}
if (current_value + 1 == m_max_value)
std::cout << " 100%" << std::endl;
}
void printIncrement()
{
#pragma omp atomic
++m_current_value;
printStatus(m_current_value);
}
void printAddition(const unsigned addition)
{
#pragma omp atomic
m_current_value += addition;
printStatus(m_current_value);
}
private:
unsigned m_current_value;
unsigned m_max_value;
unsigned m_percent_interval;
unsigned m_next_threshold;
unsigned m_last_percent;
unsigned m_step;
// Displays progress.
void printPercent(double percent)
{
while (percent >= m_last_percent + m_step)
{
m_last_percent += m_step;
if (m_last_percent % 10 == 0)
{
std::cout << " " << m_last_percent << "% ";
}
else
{
std::cout << ".";
}
std::cout.flush();
}
}
};
#endif // PERCENT_H
|
GB_transpose_bucket.c | //------------------------------------------------------------------------------
// GB_transpose_bucket: transpose and optionally typecast and/or apply operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// C = A' or op(A'). Optionally typecasts from A->type to the new type ctype,
// and/or optionally applies a unary operator.
// If an operator z=op(x) is provided, the type of z must be the same as the
// type of C. The type of A must be compatible with the type of of x (A is
// typecasted into the type of x). These conditions must be checked in the
// caller.
// This function is agnostic for the CSR/CSC format of C and A. C_is_csc is
// defined by the caller and assigned to C->is_csc, but otherwise unused.
// A->is_csc is ignored.
// The input can be hypersparse or non-hypersparse. The output C is always
// non-hypersparse, and never shallow. On input, C is a static header.
// If A is m-by-n in CSC format, with e nonzeros, the time and memory taken is
// O(m+n+e) if A is non-hypersparse, or O(m+e) if hypersparse. This is fine if
// most rows and columns of A are non-empty, but can be very costly if A or A'
// is hypersparse. In particular, if A is a non-hypersparse column vector with
// m >> e, the time and memory is O(m), which can be huge. Thus, for
// hypersparse matrices, or for very sparse matrices, the qsort method should
// be used instead (see GB_transpose).
// This method is parallel, but not highly scalable. At most O(e/m) threads
// are used.
#include "GB_transpose.h"
#define GB_FREE_WORKSPACE \
{ \
if (Workspaces != NULL && Workspaces_size != NULL) \
{ \
for (int tid = 0 ; tid < nworkspaces ; tid++) \
{ \
GB_FREE_WORK (&(Workspaces [tid]), Workspaces_size [tid]) ; \
} \
} \
GB_WERK_POP (A_slice, int64_t) ; \
GB_WERK_POP (Workspaces_size, size_t) ; \
GB_WERK_POP (Workspaces, int64_t *) ; \
}
#define GB_FREE_ALL \
{ \
GB_phbix_free (C) ; \
GB_FREE_WORKSPACE ; \
}
GrB_Info GB_transpose_bucket // bucket transpose; typecast and apply op
(
GrB_Matrix C, // output matrix (static header)
const GB_iso_code C_code_iso, // iso code for C
const GrB_Type ctype, // type of output matrix C
const bool C_is_csc, // format of output matrix C
const GrB_Matrix A, // input matrix
// no operator is applied if op is NULL
const GB_Operator op, // unary/idxunop/binop to apply
const GrB_Scalar scalar, // scalar to bind to binary operator
bool binop_bind1st, // if true, binop(x,A) else binop(A,y)
const int nworkspaces, // # of workspaces to use
const int nthreads, // # of threads to use
GB_Context Context
)
{
//--------------------------------------------------------------------------
// check inputs
//--------------------------------------------------------------------------
ASSERT (C != NULL && (C->static_header || GBNSTATIC)) ;
ASSERT_TYPE_OK (ctype, "ctype for transpose", GB0) ;
ASSERT_MATRIX_OK (A, "A input for transpose_bucket", GB0) ;
ASSERT (!GB_PENDING (A)) ;
ASSERT (!GB_ZOMBIES (A)) ;
ASSERT (GB_JUMBLED_OK (A)) ;
// if op is NULL, then no operator is applied
// This method is only be used when A is sparse or hypersparse.
// The full and bitmap cases are handled in GB_transpose.
ASSERT (!GB_IS_FULL (A)) ;
ASSERT (!GB_IS_BITMAP (A)) ;
ASSERT (GB_IS_SPARSE (A) || GB_IS_HYPERSPARSE (A)) ;
GB_WERK_DECLARE (A_slice, int64_t) ; // size nthreads+1
GB_WERK_DECLARE (Workspaces, int64_t *) ; // size nworkspaces
GB_WERK_DECLARE (Workspaces_size, size_t) ; // size nworkspaces
//--------------------------------------------------------------------------
// get A
//--------------------------------------------------------------------------
int64_t anz = GB_nnz (A) ;
int64_t vlen = A->vlen ;
//--------------------------------------------------------------------------
// determine the number of threads to use
//--------------------------------------------------------------------------
// # of threads to use in the O(vlen) loops below
GB_GET_NTHREADS_MAX (nthreads_max, chunk, Context) ;
int nth = GB_nthreads (vlen, chunk, nthreads_max) ;
//--------------------------------------------------------------------------
// allocate C: always sparse
//--------------------------------------------------------------------------
// The bucket transpose only works when C is sparse.
// A can be sparse or hypersparse.
// C->p is allocated but not initialized.
GrB_Info info ;
// set C->iso = C_iso OK
bool C_iso = (C_code_iso != GB_NON_ISO) ;
GB_OK (GB_new_bix (&C, // sparse, existing header
ctype, A->vdim, vlen, GB_Ap_malloc, C_is_csc,
GxB_SPARSE, true, A->hyper_switch, vlen, anz, true, C_iso, Context)) ;
int64_t *restrict Cp = C->p ;
//--------------------------------------------------------------------------
// allocate workspace
//--------------------------------------------------------------------------
GB_WERK_PUSH (Workspaces, nworkspaces, int64_t *) ;
GB_WERK_PUSH (Workspaces_size, nworkspaces, size_t) ;
if (Workspaces == NULL || Workspaces_size == NULL)
{
// out of memory
GB_FREE_ALL ;
return (GrB_OUT_OF_MEMORY) ;
}
bool ok = true ;
for (int tid = 0 ; tid < nworkspaces ; tid++)
{
Workspaces [tid] = GB_MALLOC_WORK (vlen + 1, int64_t,
&Workspaces_size [tid]) ;
ok = ok && (Workspaces [tid] != NULL) ;
}
if (!ok)
{
// out of memory
GB_FREE_ALL ;
return (GrB_OUT_OF_MEMORY) ;
}
//==========================================================================
// phase1: symbolic analysis
//==========================================================================
// slice the A matrix, perfectly balanced for one task per thread
GB_WERK_PUSH (A_slice, nthreads + 1, int64_t) ;
if (A_slice == NULL)
{
// out of memory
GB_FREE_ALL ;
return (GrB_OUT_OF_MEMORY) ;
}
GB_pslice (A_slice, A->p, A->nvec, nthreads, true) ;
// sum up the row counts and find C->p
if (nthreads == 1)
{
//----------------------------------------------------------------------
// sequential method: A is not sliced
//----------------------------------------------------------------------
// Only requires a single int64 workspace of size vlen for a single
// thread. The resulting C matrix is not jumbled.
GBURBLE ("(1-thread bucket transpose) ") ;
// compute the row counts of A. No need to scan the A->p pointers
ASSERT (nworkspaces == 1) ;
int64_t *restrict workspace = Workspaces [0] ;
memset (workspace, 0, (vlen + 1) * sizeof (int64_t)) ;
const int64_t *restrict Ai = A->i ;
for (int64_t p = 0 ; p < anz ; p++)
{
int64_t i = Ai [p] ;
workspace [i]++ ;
}
// cumulative sum of the workspace, and copy back into C->p
GB_cumsum (workspace, vlen, &(C->nvec_nonempty), 1, NULL) ;
memcpy (Cp, workspace, (vlen + 1) * sizeof (int64_t)) ;
}
else if (nworkspaces == 1)
{
//----------------------------------------------------------------------
// atomic method: A is sliced but workspace is shared
//----------------------------------------------------------------------
// Only requires a single int64 workspace of size vlen, shared by all
// threads. Scales well, but requires atomics. If the # of rows is
// very small and the average row degree is high, this can be very slow
// because of contention on the atomic workspace. Otherwise, it is
// typically faster than the non-atomic method. The resulting C matrix
// is jumbled.
GBURBLE ("(%d-thread atomic bucket transpose) ", nthreads) ;
// compute the row counts of A. No need to scan the A->p pointers
int64_t *restrict workspace = Workspaces [0] ;
GB_memset (workspace, 0, (vlen + 1) * sizeof (int64_t), nth) ;
const int64_t *restrict Ai = A->i ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
int64_t i = Ai [p] ;
// update workspace [i]++ automically:
GB_ATOMIC_UPDATE
workspace [i]++ ;
}
C->jumbled = true ; // atomic transpose leaves C jumbled
// cumulative sum of the workspace, and copy back into C->p
GB_cumsum (workspace, vlen, &(C->nvec_nonempty), nth, Context) ;
GB_memcpy (Cp, workspace, (vlen+ 1) * sizeof (int64_t), nth) ;
}
else
{
//----------------------------------------------------------------------
// non-atomic method
//----------------------------------------------------------------------
// compute the row counts of A for each slice, one per thread; This
// method is parallel, but not highly scalable. Each thread requires
// int64 workspace of size vlen, but no atomics are required. The
// resulting C matrix is not jumbled, so this can save work if C needs
// to be unjumbled later.
GBURBLE ("(%d-thread non-atomic bucket transpose) ", nthreads) ;
ASSERT (nworkspaces == nthreads) ;
const int64_t *restrict Ap = A->p ;
const int64_t *restrict Ah = A->h ;
const int64_t *restrict Ai = A->i ;
int tid ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (tid = 0 ; tid < nthreads ; tid++)
{
// get the row counts for this slice, of size A->vlen
int64_t *restrict workspace = Workspaces [tid] ;
memset (workspace, 0, (vlen + 1) * sizeof (int64_t)) ;
for (int64_t k = A_slice [tid] ; k < A_slice [tid+1] ; k++)
{
// iterate over the entries in A(:,j)
int64_t j = GBH (Ah, k) ;
int64_t pA_start = Ap [k] ;
int64_t pA_end = Ap [k+1] ;
for (int64_t pA = pA_start ; pA < pA_end ; pA++)
{
// count one more entry in C(i,:) for this slice
int64_t i = Ai [pA] ;
workspace [i]++ ;
}
}
}
// cumulative sum of the workspaces across the slices
int64_t i ;
#pragma omp parallel for num_threads(nth) schedule(static)
for (i = 0 ; i < vlen ; i++)
{
int64_t s = 0 ;
for (int tid = 0 ; tid < nthreads ; tid++)
{
int64_t *restrict workspace = Workspaces [tid] ;
int64_t c = workspace [i] ;
workspace [i] = s ;
s += c ;
}
Cp [i] = s ;
}
Cp [vlen] = 0 ;
// compute the vector pointers for C
GB_cumsum (Cp, vlen, &(C->nvec_nonempty), nth, Context) ;
// add Cp back to all Workspaces
#pragma omp parallel for num_threads(nth) schedule(static)
for (i = 0 ; i < vlen ; i++)
{
int64_t s = Cp [i] ;
int64_t *restrict workspace = Workspaces [0] ;
workspace [i] = s ;
for (int tid = 1 ; tid < nthreads ; tid++)
{
int64_t *restrict workspace = Workspaces [tid] ;
workspace [i] += s ;
}
}
}
C->magic = GB_MAGIC ;
//==========================================================================
// phase2: transpose A into C
//==========================================================================
// transpose both the pattern and the values
if (op == NULL)
{
// do not apply an operator; optional typecast to C->type
GB_transpose_ix (C, A, Workspaces, A_slice, nworkspaces, nthreads) ;
}
else
{
// apply an operator, C has type op->ztype
GB_transpose_op (C, C_code_iso, op, scalar, binop_bind1st, A,
Workspaces, A_slice, nworkspaces, nthreads) ;
}
//--------------------------------------------------------------------------
// free workspace and return result
//--------------------------------------------------------------------------
GB_FREE_WORKSPACE ;
ASSERT_MATRIX_OK (C, "C transpose of A", GB0) ;
ASSERT (C->h == NULL) ;
return (GrB_SUCCESS) ;
}
|
activations.c | #include "activations.h"
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <float.h>
char *get_activation_string(ACTIVATION a)
{
switch(a){
case LOGISTIC:
return "logistic";
case LOGGY:
return "loggy";
case RELU:
return "relu";
case ELU:
return "elu";
case SELU:
return "selu";
case RELIE:
return "relie";
case RAMP:
return "ramp";
case LINEAR:
return "linear";
case TANH:
return "tanh";
case PLSE:
return "plse";
case LEAKY:
return "leaky";
case STAIR:
return "stair";
case HARDTAN:
return "hardtan";
case LHTAN:
return "lhtan";
default:
break;
}
return "relu";
}
ACTIVATION get_activation(char *s)
{
if (strcmp(s, "logistic")==0) return LOGISTIC;
if (strcmp(s, "swish") == 0) return SWISH;
if (strcmp(s, "mish") == 0) return MISH;
if (strcmp(s, "normalize_channels") == 0) return NORM_CHAN;
if (strcmp(s, "normalize_channels_softmax") == 0) return NORM_CHAN_SOFTMAX;
if (strcmp(s, "normalize_channels_softmax_maxval") == 0) return NORM_CHAN_SOFTMAX_MAXVAL;
if (strcmp(s, "loggy")==0) return LOGGY;
if (strcmp(s, "relu")==0) return RELU;
if (strcmp(s, "relu6") == 0) return RELU6;
if (strcmp(s, "elu")==0) return ELU;
if (strcmp(s, "selu") == 0) return SELU;
if (strcmp(s, "relie")==0) return RELIE;
if (strcmp(s, "plse")==0) return PLSE;
if (strcmp(s, "hardtan")==0) return HARDTAN;
if (strcmp(s, "lhtan")==0) return LHTAN;
if (strcmp(s, "linear")==0) return LINEAR;
if (strcmp(s, "ramp")==0) return RAMP;
if (strcmp(s, "leaky")==0) return LEAKY;
if (strcmp(s, "tanh")==0) return TANH;
if (strcmp(s, "stair")==0) return STAIR;
fprintf(stderr, "Couldn't find activation function %s, going with ReLU\n", s);
return RELU;
}
float activate(float x, ACTIVATION a)
{
switch(a){
case LINEAR:
return linear_activate(x);
case LOGISTIC:
return logistic_activate(x);
case LOGGY:
return loggy_activate(x);
case RELU:
return relu_activate(x);
case ELU:
return elu_activate(x);
case SELU:
return selu_activate(x);
case RELIE:
return relie_activate(x);
case RAMP:
return ramp_activate(x);
case LEAKY:
return leaky_activate(x);
case TANH:
return tanh_activate(x);
case PLSE:
return plse_activate(x);
case STAIR:
return stair_activate(x);
case HARDTAN:
return hardtan_activate(x);
case LHTAN:
return lhtan_activate(x);
}
return 0;
}
void activate_array(float *x, const int n, const ACTIVATION a)
{
int i;
if (a == LINEAR) {}
else if (a == LEAKY) {
#pragma omp parallel for
for (i = 0; i < n; ++i) {
x[i] = leaky_activate(x[i]);
}
}
else if (a == LOGISTIC) {
#pragma omp parallel for
for (i = 0; i < n; ++i) {
x[i] = logistic_activate(x[i]);
}
}
else {
for (i = 0; i < n; ++i) {
x[i] = activate(x[i], a);
}
}
}
void activate_array_swish(float *x, const int n, float * output_sigmoid, float * output)
{
int i;
#pragma omp parallel for
for (i = 0; i < n; ++i) {
float x_val = x[i];
float sigmoid = logistic_activate(x_val);
output_sigmoid[i] = sigmoid;
output[i] = x_val * sigmoid;
}
}
// https://github.com/digantamisra98/Mish
void activate_array_mish(float *x, const int n, float * activation_input, float * output)
{
const float MISH_THRESHOLD = 20;
int i;
#pragma omp parallel for
for (i = 0; i < n; ++i) {
float x_val = x[i];
activation_input[i] = x_val; // store value before activation
output[i] = x_val * tanh_activate( softplus_activate(x_val, MISH_THRESHOLD) );
}
}
void activate_array_normalize_channels(float *x, const int n, int batch, int channels, int wh_step, float *output)
{
int size = n / channels;
int i;
#pragma omp parallel for
for (i = 0; i < size; ++i) {
int wh_i = i % wh_step;
int b = i / wh_step;
const float eps = 0.0001;
if (i < size) {
float sum = eps;
int k;
for (k = 0; k < channels; ++k) {
float val = x[wh_i + k * wh_step + b*wh_step*channels];
if (val > 0) sum += val;
}
for (k = 0; k < channels; ++k) {
float val = x[wh_i + k * wh_step + b*wh_step*channels];
if (val > 0) val = val / sum;
else val = 0;
output[wh_i + k * wh_step + b*wh_step*channels] = val;
}
}
}
}
void activate_array_normalize_channels_softmax(float *x, const int n, int batch, int channels, int wh_step, float *output, int use_max_val)
{
int size = n / channels;
int i;
#pragma omp parallel for
for (i = 0; i < size; ++i) {
int wh_i = i % wh_step;
int b = i / wh_step;
const float eps = 0.0001;
if (i < size) {
float sum = eps;
float max_val = -FLT_MAX;
int k;
if (use_max_val) {
for (k = 0; k < channels; ++k) {
float val = x[wh_i + k * wh_step + b*wh_step*channels];
if (val > max_val || k == 0) max_val = val;
}
}
else
max_val = 0;
for (k = 0; k < channels; ++k) {
float val = x[wh_i + k * wh_step + b*wh_step*channels];
sum += expf(val - max_val);
}
for (k = 0; k < channels; ++k) {
float val = x[wh_i + k * wh_step + b*wh_step*channels];
val = expf(val - max_val) / sum;
output[wh_i + k * wh_step + b*wh_step*channels] = val;
}
}
}
}
void gradient_array_normalize_channels_softmax(float *x, const int n, int batch, int channels, int wh_step, float *delta)
{
int size = n / channels;
int i;
#pragma omp parallel for
for (i = 0; i < size; ++i) {
int wh_i = i % wh_step;
int b = i / wh_step;
if (i < size) {
float grad = 0;
int k;
for (k = 0; k < channels; ++k) {
const int index = wh_i + k * wh_step + b*wh_step*channels;
float out = x[index];
float d = delta[index];
grad += out*d;
}
for (k = 0; k < channels; ++k) {
const int index = wh_i + k * wh_step + b*wh_step*channels;
float d = delta[index];
d = d * grad;
delta[index] = d;
}
}
}
}
void gradient_array_normalize_channels(float *x, const int n, int batch, int channels, int wh_step, float *delta)
{
int size = n / channels;
int i;
#pragma omp parallel for
for (i = 0; i < size; ++i) {
int wh_i = i % wh_step;
int b = i / wh_step;
if (i < size) {
float grad = 0;
int k;
for (k = 0; k < channels; ++k) {
const int index = wh_i + k * wh_step + b*wh_step*channels;
float out = x[index];
float d = delta[index];
grad += out*d;
}
for (k = 0; k < channels; ++k) {
const int index = wh_i + k * wh_step + b*wh_step*channels;
if (x[index] > 0) {
float d = delta[index];
d = d * grad;
delta[index] = d;
}
}
}
}
}
float gradient(float x, ACTIVATION a)
{
switch(a){
case LINEAR:
return linear_gradient(x);
case LOGISTIC:
return logistic_gradient(x);
case LOGGY:
return loggy_gradient(x);
case RELU:
return relu_gradient(x);
case NORM_CHAN:
//return relu_gradient(x);
case NORM_CHAN_SOFTMAX_MAXVAL:
//...
case NORM_CHAN_SOFTMAX:
printf(" Error: should be used custom NORM_CHAN or NORM_CHAN_SOFTMAX-function for gradient \n");
exit(0);
return 0;
case ELU:
return elu_gradient(x);
case SELU:
return selu_gradient(x);
case RELIE:
return relie_gradient(x);
case RAMP:
return ramp_gradient(x);
case LEAKY:
return leaky_gradient(x);
case TANH:
return tanh_gradient(x);
case PLSE:
return plse_gradient(x);
case STAIR:
return stair_gradient(x);
case HARDTAN:
return hardtan_gradient(x);
case LHTAN:
return lhtan_gradient(x);
}
return 0;
}
void gradient_array(const float *x, const int n, const ACTIVATION a, float *delta)
{
int i;
#pragma omp parallel for
for(i = 0; i < n; ++i){
delta[i] *= gradient(x[i], a);
}
}
// https://github.com/BVLC/caffe/blob/04ab089db018a292ae48d51732dd6c66766b36b6/src/caffe/layers/swish_layer.cpp#L54-L56
void gradient_array_swish(const float *x, const int n, const float * sigmoid, float * delta)
{
int i;
#pragma omp parallel for
for (i = 0; i < n; ++i) {
float swish = x[i];
delta[i] *= swish + sigmoid[i]*(1 - swish);
}
}
// https://github.com/digantamisra98/Mish
void gradient_array_mish(const int n, const float * activation_input, float * delta)
{
int i;
#pragma omp parallel for
for (i = 0; i < n; ++i) {
const float MISH_THRESHOLD = 20.0f;
// implementation from TensorFlow: https://github.com/tensorflow/addons/commit/093cdfa85d334cbe19a37624c33198f3140109ed
// implementation from Pytorch: https://github.com/thomasbrandon/mish-cuda/blob/master/csrc/mish.h#L26-L31
float inp = activation_input[i];
const float sp = softplus_activate(inp, MISH_THRESHOLD);
const float grad_sp = 1 - exp(-sp);
const float tsp = tanh(sp);
const float grad_tsp = (1 - tsp*tsp) * grad_sp;
const float grad = inp * grad_tsp + tsp;
delta[i] *= grad;
//float x = activation_input[i];
//float d = 2 * expf(x) + expf(2 * x) + 2;
//float w = 4 * (x + 1) + 4 * expf(2 * x) + expf(3 * x) + expf(x)*(4 * x + 6);
//float derivative = expf(x) * w / (d * d);
//delta[i] *= derivative;
}
}
|
StmtOpenMP.h | //===- StmtOpenMP.h - Classes for OpenMP directives ------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
/// \file
/// This file defines OpenMP AST classes for executable directives and
/// clauses.
///
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_AST_STMTOPENMP_H
#define LLVM_CLANG_AST_STMTOPENMP_H
#include "clang/AST/Expr.h"
#include "clang/AST/OpenMPClause.h"
#include "clang/AST/Stmt.h"
#include "clang/Basic/OpenMPKinds.h"
#include "clang/Basic/SourceLocation.h"
namespace clang {
//===----------------------------------------------------------------------===//
// AST classes for directives.
//===----------------------------------------------------------------------===//
/// This is a basic class for representing single OpenMP executable
/// directive.
///
class OMPExecutableDirective : public Stmt {
friend class ASTStmtReader;
/// Kind of the directive.
OpenMPDirectiveKind Kind;
/// Starting location of the directive (directive keyword).
SourceLocation StartLoc;
/// Ending location of the directive.
SourceLocation EndLoc;
/// Numbers of clauses.
const unsigned NumClauses;
/// Number of child expressions/stmts.
const unsigned NumChildren;
/// Offset from this to the start of clauses.
/// There are NumClauses pointers to clauses, they are followed by
/// NumChildren pointers to child stmts/exprs (if the directive type
/// requires an associated stmt, then it has to be the first of them).
const unsigned ClausesOffset;
/// Get the clauses storage.
MutableArrayRef<OMPClause *> getClauses() {
OMPClause **ClauseStorage = reinterpret_cast<OMPClause **>(
reinterpret_cast<char *>(this) + ClausesOffset);
return MutableArrayRef<OMPClause *>(ClauseStorage, NumClauses);
}
protected:
/// Build instance of directive of class \a K.
///
/// \param SC Statement class.
/// \param K Kind of OpenMP directive.
/// \param StartLoc Starting location of the directive (directive keyword).
/// \param EndLoc Ending location of the directive.
///
template <typename T>
OMPExecutableDirective(const T *, StmtClass SC, OpenMPDirectiveKind K,
SourceLocation StartLoc, SourceLocation EndLoc,
unsigned NumClauses, unsigned NumChildren)
: Stmt(SC), Kind(K), StartLoc(std::move(StartLoc)),
EndLoc(std::move(EndLoc)), NumClauses(NumClauses),
NumChildren(NumChildren),
ClausesOffset(llvm::alignTo(sizeof(T), alignof(OMPClause *))) {}
/// Sets the list of variables for this clause.
///
/// \param Clauses The list of clauses for the directive.
///
void setClauses(ArrayRef<OMPClause *> Clauses);
/// Set the associated statement for the directive.
///
/// /param S Associated statement.
///
void setAssociatedStmt(Stmt *S) {
assert(hasAssociatedStmt() && "no associated statement.");
*child_begin() = S;
}
public:
/// Iterates over a filtered subrange of clauses applied to a
/// directive.
///
/// This iterator visits only clauses of type SpecificClause.
template <typename SpecificClause>
class specific_clause_iterator
: public llvm::iterator_adaptor_base<
specific_clause_iterator<SpecificClause>,
ArrayRef<OMPClause *>::const_iterator, std::forward_iterator_tag,
const SpecificClause *, ptrdiff_t, const SpecificClause *,
const SpecificClause *> {
ArrayRef<OMPClause *>::const_iterator End;
void SkipToNextClause() {
while (this->I != End && !isa<SpecificClause>(*this->I))
++this->I;
}
public:
explicit specific_clause_iterator(ArrayRef<OMPClause *> Clauses)
: specific_clause_iterator::iterator_adaptor_base(Clauses.begin()),
End(Clauses.end()) {
SkipToNextClause();
}
const SpecificClause *operator*() const {
return cast<SpecificClause>(*this->I);
}
const SpecificClause *operator->() const { return **this; }
specific_clause_iterator &operator++() {
++this->I;
SkipToNextClause();
return *this;
}
};
template <typename SpecificClause>
static llvm::iterator_range<specific_clause_iterator<SpecificClause>>
getClausesOfKind(ArrayRef<OMPClause *> Clauses) {
return {specific_clause_iterator<SpecificClause>(Clauses),
specific_clause_iterator<SpecificClause>(
llvm::makeArrayRef(Clauses.end(), 0))};
}
template <typename SpecificClause>
llvm::iterator_range<specific_clause_iterator<SpecificClause>>
getClausesOfKind() const {
return getClausesOfKind<SpecificClause>(clauses());
}
/// Gets a single clause of the specified kind associated with the
/// current directive iff there is only one clause of this kind (and assertion
/// is fired if there is more than one clause is associated with the
/// directive). Returns nullptr if no clause of this kind is associated with
/// the directive.
template <typename SpecificClause>
const SpecificClause *getSingleClause() const {
auto Clauses = getClausesOfKind<SpecificClause>();
if (Clauses.begin() != Clauses.end()) {
assert(std::next(Clauses.begin()) == Clauses.end() &&
"There are at least 2 clauses of the specified kind");
return *Clauses.begin();
}
return nullptr;
}
/// Returns true if the current directive has one or more clauses of a
/// specific kind.
template <typename SpecificClause>
bool hasClausesOfKind() const {
auto Clauses = getClausesOfKind<SpecificClause>();
return Clauses.begin() != Clauses.end();
}
/// Returns starting location of directive kind.
SourceLocation getBeginLoc() const { return StartLoc; }
/// Returns ending location of directive.
SourceLocation getEndLoc() const { return EndLoc; }
/// Set starting location of directive kind.
///
/// \param Loc New starting location of directive.
///
void setLocStart(SourceLocation Loc) { StartLoc = Loc; }
/// Set ending location of directive.
///
/// \param Loc New ending location of directive.
///
void setLocEnd(SourceLocation Loc) { EndLoc = Loc; }
/// Get number of clauses.
unsigned getNumClauses() const { return NumClauses; }
/// Returns specified clause.
///
/// \param i Number of clause.
///
OMPClause *getClause(unsigned i) const { return clauses()[i]; }
/// Returns true if directive has associated statement.
bool hasAssociatedStmt() const { return NumChildren > 0; }
/// Returns statement associated with the directive.
const Stmt *getAssociatedStmt() const {
assert(hasAssociatedStmt() && "no associated statement.");
return *child_begin();
}
Stmt *getAssociatedStmt() {
assert(hasAssociatedStmt() && "no associated statement.");
return *child_begin();
}
/// Returns the captured statement associated with the
/// component region within the (combined) directive.
//
// \param RegionKind Component region kind.
const CapturedStmt *getCapturedStmt(OpenMPDirectiveKind RegionKind) const {
SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
getOpenMPCaptureRegions(CaptureRegions, getDirectiveKind());
assert(std::any_of(
CaptureRegions.begin(), CaptureRegions.end(),
[=](const OpenMPDirectiveKind K) { return K == RegionKind; }) &&
"RegionKind not found in OpenMP CaptureRegions.");
auto *CS = cast<CapturedStmt>(getAssociatedStmt());
for (auto ThisCaptureRegion : CaptureRegions) {
if (ThisCaptureRegion == RegionKind)
return CS;
CS = cast<CapturedStmt>(CS->getCapturedStmt());
}
llvm_unreachable("Incorrect RegionKind specified for directive.");
}
/// Get innermost captured statement for the construct.
CapturedStmt *getInnermostCapturedStmt() {
assert(hasAssociatedStmt() && getAssociatedStmt() &&
"Must have associated statement.");
SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
getOpenMPCaptureRegions(CaptureRegions, getDirectiveKind());
assert(!CaptureRegions.empty() &&
"At least one captured statement must be provided.");
auto *CS = cast<CapturedStmt>(getAssociatedStmt());
for (unsigned Level = CaptureRegions.size(); Level > 1; --Level)
CS = cast<CapturedStmt>(CS->getCapturedStmt());
return CS;
}
const CapturedStmt *getInnermostCapturedStmt() const {
return const_cast<OMPExecutableDirective *>(this)
->getInnermostCapturedStmt();
}
OpenMPDirectiveKind getDirectiveKind() const { return Kind; }
static bool classof(const Stmt *S) {
return S->getStmtClass() >= firstOMPExecutableDirectiveConstant &&
S->getStmtClass() <= lastOMPExecutableDirectiveConstant;
}
child_range children() {
if (!hasAssociatedStmt())
return child_range(child_iterator(), child_iterator());
Stmt **ChildStorage = reinterpret_cast<Stmt **>(getClauses().end());
/// Do not mark all the special expression/statements as children, except
/// for the associated statement.
return child_range(ChildStorage, ChildStorage + 1);
}
ArrayRef<OMPClause *> clauses() { return getClauses(); }
ArrayRef<OMPClause *> clauses() const {
return const_cast<OMPExecutableDirective *>(this)->getClauses();
}
};
/// This represents '#pragma omp parallel' directive.
///
/// \code
/// #pragma omp parallel private(a,b) reduction(+: c,d)
/// \endcode
/// In this example directive '#pragma omp parallel' has clauses 'private'
/// with the variables 'a' and 'b' and 'reduction' with operator '+' and
/// variables 'c' and 'd'.
///
class OMPParallelDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
/// true if the construct has inner cancel directive.
bool HasCancel;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive (directive keyword).
/// \param EndLoc Ending Location of the directive.
///
OMPParallelDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned NumClauses)
: OMPExecutableDirective(this, OMPParallelDirectiveClass, OMPD_parallel,
StartLoc, EndLoc, NumClauses, 1),
HasCancel(false) {}
/// Build an empty directive.
///
/// \param NumClauses Number of clauses.
///
explicit OMPParallelDirective(unsigned NumClauses)
: OMPExecutableDirective(this, OMPParallelDirectiveClass, OMPD_parallel,
SourceLocation(), SourceLocation(), NumClauses,
1),
HasCancel(false) {}
/// Set cancel state.
void setHasCancel(bool Has) { HasCancel = Has; }
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement associated with the directive.
/// \param HasCancel true if this directive has inner cancel directive.
///
static OMPParallelDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, bool HasCancel);
/// Creates an empty directive with the place for \a N clauses.
///
/// \param C AST context.
/// \param NumClauses Number of clauses.
///
static OMPParallelDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses, EmptyShell);
/// Return true if current directive has inner cancel directive.
bool hasCancel() const { return HasCancel; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPParallelDirectiveClass;
}
};
/// This is a common base class for loop directives ('omp simd', 'omp
/// for', 'omp for simd' etc.). It is responsible for the loop code generation.
///
class OMPLoopDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
/// Number of collapsed loops as specified by 'collapse' clause.
unsigned CollapsedNum;
/// Offsets to the stored exprs.
/// This enumeration contains offsets to all the pointers to children
/// expressions stored in OMPLoopDirective.
/// The first 9 children are necessary for all the loop directives,
/// the next 8 are specific to the worksharing ones, and the next 11 are
/// used for combined constructs containing two pragmas associated to loops.
/// After the fixed children, three arrays of length CollapsedNum are
/// allocated: loop counters, their updates and final values.
/// PrevLowerBound and PrevUpperBound are used to communicate blocking
/// information in composite constructs which require loop blocking
/// DistInc is used to generate the increment expression for the distribute
/// loop when combined with a further nested loop
/// PrevEnsureUpperBound is used as the EnsureUpperBound expression for the
/// for loop when combined with a previous distribute loop in the same pragma
/// (e.g. 'distribute parallel for')
///
enum {
AssociatedStmtOffset = 0,
IterationVariableOffset = 1,
LastIterationOffset = 2,
CalcLastIterationOffset = 3,
PreConditionOffset = 4,
CondOffset = 5,
InitOffset = 6,
IncOffset = 7,
PreInitsOffset = 8,
// The '...End' enumerators do not correspond to child expressions - they
// specify the offset to the end (and start of the following counters/
// updates/finals arrays).
DefaultEnd = 9,
// The following 8 exprs are used by worksharing and distribute loops only.
IsLastIterVariableOffset = 9,
LowerBoundVariableOffset = 10,
UpperBoundVariableOffset = 11,
StrideVariableOffset = 12,
EnsureUpperBoundOffset = 13,
NextLowerBoundOffset = 14,
NextUpperBoundOffset = 15,
NumIterationsOffset = 16,
// Offset to the end for worksharing loop directives.
WorksharingEnd = 17,
PrevLowerBoundVariableOffset = 17,
PrevUpperBoundVariableOffset = 18,
DistIncOffset = 19,
PrevEnsureUpperBoundOffset = 20,
CombinedLowerBoundVariableOffset = 21,
CombinedUpperBoundVariableOffset = 22,
CombinedEnsureUpperBoundOffset = 23,
CombinedInitOffset = 24,
CombinedConditionOffset = 25,
CombinedNextLowerBoundOffset = 26,
CombinedNextUpperBoundOffset = 27,
CombinedDistConditionOffset = 28,
CombinedParForInDistConditionOffset = 29,
// Offset to the end (and start of the following counters/updates/finals
// arrays) for combined distribute loop directives.
CombinedDistributeEnd = 30,
};
/// Get the counters storage.
MutableArrayRef<Expr *> getCounters() {
Expr **Storage = reinterpret_cast<Expr **>(
&(*(std::next(child_begin(), getArraysOffset(getDirectiveKind())))));
return MutableArrayRef<Expr *>(Storage, CollapsedNum);
}
/// Get the private counters storage.
MutableArrayRef<Expr *> getPrivateCounters() {
Expr **Storage = reinterpret_cast<Expr **>(&*std::next(
child_begin(), getArraysOffset(getDirectiveKind()) + CollapsedNum));
return MutableArrayRef<Expr *>(Storage, CollapsedNum);
}
/// Get the updates storage.
MutableArrayRef<Expr *> getInits() {
Expr **Storage = reinterpret_cast<Expr **>(
&*std::next(child_begin(),
getArraysOffset(getDirectiveKind()) + 2 * CollapsedNum));
return MutableArrayRef<Expr *>(Storage, CollapsedNum);
}
/// Get the updates storage.
MutableArrayRef<Expr *> getUpdates() {
Expr **Storage = reinterpret_cast<Expr **>(
&*std::next(child_begin(),
getArraysOffset(getDirectiveKind()) + 3 * CollapsedNum));
return MutableArrayRef<Expr *>(Storage, CollapsedNum);
}
/// Get the final counter updates storage.
MutableArrayRef<Expr *> getFinals() {
Expr **Storage = reinterpret_cast<Expr **>(
&*std::next(child_begin(),
getArraysOffset(getDirectiveKind()) + 4 * CollapsedNum));
return MutableArrayRef<Expr *>(Storage, CollapsedNum);
}
protected:
/// Build instance of loop directive of class \a Kind.
///
/// \param SC Statement class.
/// \param Kind Kind of OpenMP directive.
/// \param StartLoc Starting location of the directive (directive keyword).
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed loops from 'collapse' clause.
/// \param NumClauses Number of clauses.
/// \param NumSpecialChildren Number of additional directive-specific stmts.
///
template <typename T>
OMPLoopDirective(const T *That, StmtClass SC, OpenMPDirectiveKind Kind,
SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, unsigned NumClauses,
unsigned NumSpecialChildren = 0)
: OMPExecutableDirective(That, SC, Kind, StartLoc, EndLoc, NumClauses,
numLoopChildren(CollapsedNum, Kind) +
NumSpecialChildren),
CollapsedNum(CollapsedNum) {}
/// Offset to the start of children expression arrays.
static unsigned getArraysOffset(OpenMPDirectiveKind Kind) {
if (isOpenMPLoopBoundSharingDirective(Kind))
return CombinedDistributeEnd;
if (isOpenMPWorksharingDirective(Kind) || isOpenMPTaskLoopDirective(Kind) ||
isOpenMPDistributeDirective(Kind))
return WorksharingEnd;
return DefaultEnd;
}
/// Children number.
static unsigned numLoopChildren(unsigned CollapsedNum,
OpenMPDirectiveKind Kind) {
return getArraysOffset(Kind) + 5 * CollapsedNum; // Counters,
// PrivateCounters, Inits,
// Updates and Finals
}
void setIterationVariable(Expr *IV) {
*std::next(child_begin(), IterationVariableOffset) = IV;
}
void setLastIteration(Expr *LI) {
*std::next(child_begin(), LastIterationOffset) = LI;
}
void setCalcLastIteration(Expr *CLI) {
*std::next(child_begin(), CalcLastIterationOffset) = CLI;
}
void setPreCond(Expr *PC) {
*std::next(child_begin(), PreConditionOffset) = PC;
}
void setCond(Expr *Cond) {
*std::next(child_begin(), CondOffset) = Cond;
}
void setInit(Expr *Init) { *std::next(child_begin(), InitOffset) = Init; }
void setInc(Expr *Inc) { *std::next(child_begin(), IncOffset) = Inc; }
void setPreInits(Stmt *PreInits) {
*std::next(child_begin(), PreInitsOffset) = PreInits;
}
void setIsLastIterVariable(Expr *IL) {
assert((isOpenMPWorksharingDirective(getDirectiveKind()) ||
isOpenMPTaskLoopDirective(getDirectiveKind()) ||
isOpenMPDistributeDirective(getDirectiveKind())) &&
"expected worksharing loop directive");
*std::next(child_begin(), IsLastIterVariableOffset) = IL;
}
void setLowerBoundVariable(Expr *LB) {
assert((isOpenMPWorksharingDirective(getDirectiveKind()) ||
isOpenMPTaskLoopDirective(getDirectiveKind()) ||
isOpenMPDistributeDirective(getDirectiveKind())) &&
"expected worksharing loop directive");
*std::next(child_begin(), LowerBoundVariableOffset) = LB;
}
void setUpperBoundVariable(Expr *UB) {
assert((isOpenMPWorksharingDirective(getDirectiveKind()) ||
isOpenMPTaskLoopDirective(getDirectiveKind()) ||
isOpenMPDistributeDirective(getDirectiveKind())) &&
"expected worksharing loop directive");
*std::next(child_begin(), UpperBoundVariableOffset) = UB;
}
void setStrideVariable(Expr *ST) {
assert((isOpenMPWorksharingDirective(getDirectiveKind()) ||
isOpenMPTaskLoopDirective(getDirectiveKind()) ||
isOpenMPDistributeDirective(getDirectiveKind())) &&
"expected worksharing loop directive");
*std::next(child_begin(), StrideVariableOffset) = ST;
}
void setEnsureUpperBound(Expr *EUB) {
assert((isOpenMPWorksharingDirective(getDirectiveKind()) ||
isOpenMPTaskLoopDirective(getDirectiveKind()) ||
isOpenMPDistributeDirective(getDirectiveKind())) &&
"expected worksharing loop directive");
*std::next(child_begin(), EnsureUpperBoundOffset) = EUB;
}
void setNextLowerBound(Expr *NLB) {
assert((isOpenMPWorksharingDirective(getDirectiveKind()) ||
isOpenMPTaskLoopDirective(getDirectiveKind()) ||
isOpenMPDistributeDirective(getDirectiveKind())) &&
"expected worksharing loop directive");
*std::next(child_begin(), NextLowerBoundOffset) = NLB;
}
void setNextUpperBound(Expr *NUB) {
assert((isOpenMPWorksharingDirective(getDirectiveKind()) ||
isOpenMPTaskLoopDirective(getDirectiveKind()) ||
isOpenMPDistributeDirective(getDirectiveKind())) &&
"expected worksharing loop directive");
*std::next(child_begin(), NextUpperBoundOffset) = NUB;
}
void setNumIterations(Expr *NI) {
assert((isOpenMPWorksharingDirective(getDirectiveKind()) ||
isOpenMPTaskLoopDirective(getDirectiveKind()) ||
isOpenMPDistributeDirective(getDirectiveKind())) &&
"expected worksharing loop directive");
*std::next(child_begin(), NumIterationsOffset) = NI;
}
void setPrevLowerBoundVariable(Expr *PrevLB) {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
*std::next(child_begin(), PrevLowerBoundVariableOffset) = PrevLB;
}
void setPrevUpperBoundVariable(Expr *PrevUB) {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
*std::next(child_begin(), PrevUpperBoundVariableOffset) = PrevUB;
}
void setDistInc(Expr *DistInc) {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
*std::next(child_begin(), DistIncOffset) = DistInc;
}
void setPrevEnsureUpperBound(Expr *PrevEUB) {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
*std::next(child_begin(), PrevEnsureUpperBoundOffset) = PrevEUB;
}
void setCombinedLowerBoundVariable(Expr *CombLB) {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
*std::next(child_begin(), CombinedLowerBoundVariableOffset) = CombLB;
}
void setCombinedUpperBoundVariable(Expr *CombUB) {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
*std::next(child_begin(), CombinedUpperBoundVariableOffset) = CombUB;
}
void setCombinedEnsureUpperBound(Expr *CombEUB) {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
*std::next(child_begin(), CombinedEnsureUpperBoundOffset) = CombEUB;
}
void setCombinedInit(Expr *CombInit) {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
*std::next(child_begin(), CombinedInitOffset) = CombInit;
}
void setCombinedCond(Expr *CombCond) {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
*std::next(child_begin(), CombinedConditionOffset) = CombCond;
}
void setCombinedNextLowerBound(Expr *CombNLB) {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
*std::next(child_begin(), CombinedNextLowerBoundOffset) = CombNLB;
}
void setCombinedNextUpperBound(Expr *CombNUB) {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
*std::next(child_begin(), CombinedNextUpperBoundOffset) = CombNUB;
}
void setCombinedDistCond(Expr *CombDistCond) {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound distribute sharing directive");
*std::next(child_begin(), CombinedDistConditionOffset) = CombDistCond;
}
void setCombinedParForInDistCond(Expr *CombParForInDistCond) {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound distribute sharing directive");
*std::next(child_begin(),
CombinedParForInDistConditionOffset) = CombParForInDistCond;
}
void setCounters(ArrayRef<Expr *> A);
void setPrivateCounters(ArrayRef<Expr *> A);
void setInits(ArrayRef<Expr *> A);
void setUpdates(ArrayRef<Expr *> A);
void setFinals(ArrayRef<Expr *> A);
public:
/// The expressions built to support OpenMP loops in combined/composite
/// pragmas (e.g. pragma omp distribute parallel for)
struct DistCombinedHelperExprs {
/// DistributeLowerBound - used when composing 'omp distribute' with
/// 'omp for' in a same construct.
Expr *LB;
/// DistributeUpperBound - used when composing 'omp distribute' with
/// 'omp for' in a same construct.
Expr *UB;
/// DistributeEnsureUpperBound - used when composing 'omp distribute'
/// with 'omp for' in a same construct, EUB depends on DistUB
Expr *EUB;
/// Distribute loop iteration variable init used when composing 'omp
/// distribute'
/// with 'omp for' in a same construct
Expr *Init;
/// Distribute Loop condition used when composing 'omp distribute'
/// with 'omp for' in a same construct
Expr *Cond;
/// Update of LowerBound for statically scheduled omp loops for
/// outer loop in combined constructs (e.g. 'distribute parallel for')
Expr *NLB;
/// Update of UpperBound for statically scheduled omp loops for
/// outer loop in combined constructs (e.g. 'distribute parallel for')
Expr *NUB;
/// Distribute Loop condition used when composing 'omp distribute'
/// with 'omp for' in a same construct when schedule is chunked.
Expr *DistCond;
/// 'omp parallel for' loop condition used when composed with
/// 'omp distribute' in the same construct and when schedule is
/// chunked and the chunk size is 1.
Expr *ParForInDistCond;
};
/// The expressions built for the OpenMP loop CodeGen for the
/// whole collapsed loop nest.
struct HelperExprs {
/// Loop iteration variable.
Expr *IterationVarRef;
/// Loop last iteration number.
Expr *LastIteration;
/// Loop number of iterations.
Expr *NumIterations;
/// Calculation of last iteration.
Expr *CalcLastIteration;
/// Loop pre-condition.
Expr *PreCond;
/// Loop condition.
Expr *Cond;
/// Loop iteration variable init.
Expr *Init;
/// Loop increment.
Expr *Inc;
/// IsLastIteration - local flag variable passed to runtime.
Expr *IL;
/// LowerBound - local variable passed to runtime.
Expr *LB;
/// UpperBound - local variable passed to runtime.
Expr *UB;
/// Stride - local variable passed to runtime.
Expr *ST;
/// EnsureUpperBound -- expression UB = min(UB, NumIterations).
Expr *EUB;
/// Update of LowerBound for statically scheduled 'omp for' loops.
Expr *NLB;
/// Update of UpperBound for statically scheduled 'omp for' loops.
Expr *NUB;
/// PreviousLowerBound - local variable passed to runtime in the
/// enclosing schedule or null if that does not apply.
Expr *PrevLB;
/// PreviousUpperBound - local variable passed to runtime in the
/// enclosing schedule or null if that does not apply.
Expr *PrevUB;
/// DistInc - increment expression for distribute loop when found
/// combined with a further loop level (e.g. in 'distribute parallel for')
/// expression IV = IV + ST
Expr *DistInc;
/// PrevEUB - expression similar to EUB but to be used when loop
/// scheduling uses PrevLB and PrevUB (e.g. in 'distribute parallel for'
/// when ensuring that the UB is either the calculated UB by the runtime or
/// the end of the assigned distribute chunk)
/// expression UB = min (UB, PrevUB)
Expr *PrevEUB;
/// Counters Loop counters.
SmallVector<Expr *, 4> Counters;
/// PrivateCounters Loop counters.
SmallVector<Expr *, 4> PrivateCounters;
/// Expressions for loop counters inits for CodeGen.
SmallVector<Expr *, 4> Inits;
/// Expressions for loop counters update for CodeGen.
SmallVector<Expr *, 4> Updates;
/// Final loop counter values for GodeGen.
SmallVector<Expr *, 4> Finals;
/// Init statement for all captured expressions.
Stmt *PreInits;
/// Expressions used when combining OpenMP loop pragmas
DistCombinedHelperExprs DistCombinedFields;
/// Check if all the expressions are built (does not check the
/// worksharing ones).
bool builtAll() {
return IterationVarRef != nullptr && LastIteration != nullptr &&
NumIterations != nullptr && PreCond != nullptr &&
Cond != nullptr && Init != nullptr && Inc != nullptr;
}
/// Initialize all the fields to null.
/// \param Size Number of elements in the counters/finals/updates arrays.
void clear(unsigned Size) {
IterationVarRef = nullptr;
LastIteration = nullptr;
CalcLastIteration = nullptr;
PreCond = nullptr;
Cond = nullptr;
Init = nullptr;
Inc = nullptr;
IL = nullptr;
LB = nullptr;
UB = nullptr;
ST = nullptr;
EUB = nullptr;
NLB = nullptr;
NUB = nullptr;
NumIterations = nullptr;
PrevLB = nullptr;
PrevUB = nullptr;
DistInc = nullptr;
PrevEUB = nullptr;
Counters.resize(Size);
PrivateCounters.resize(Size);
Inits.resize(Size);
Updates.resize(Size);
Finals.resize(Size);
for (unsigned i = 0; i < Size; ++i) {
Counters[i] = nullptr;
PrivateCounters[i] = nullptr;
Inits[i] = nullptr;
Updates[i] = nullptr;
Finals[i] = nullptr;
}
PreInits = nullptr;
DistCombinedFields.LB = nullptr;
DistCombinedFields.UB = nullptr;
DistCombinedFields.EUB = nullptr;
DistCombinedFields.Init = nullptr;
DistCombinedFields.Cond = nullptr;
DistCombinedFields.NLB = nullptr;
DistCombinedFields.NUB = nullptr;
DistCombinedFields.DistCond = nullptr;
DistCombinedFields.ParForInDistCond = nullptr;
}
};
/// Get number of collapsed loops.
unsigned getCollapsedNumber() const { return CollapsedNum; }
Expr *getIterationVariable() const {
return const_cast<Expr *>(reinterpret_cast<const Expr *>(
*std::next(child_begin(), IterationVariableOffset)));
}
Expr *getLastIteration() const {
return const_cast<Expr *>(reinterpret_cast<const Expr *>(
*std::next(child_begin(), LastIterationOffset)));
}
Expr *getCalcLastIteration() const {
return const_cast<Expr *>(reinterpret_cast<const Expr *>(
*std::next(child_begin(), CalcLastIterationOffset)));
}
Expr *getPreCond() const {
return const_cast<Expr *>(reinterpret_cast<const Expr *>(
*std::next(child_begin(), PreConditionOffset)));
}
Expr *getCond() const {
return const_cast<Expr *>(
reinterpret_cast<const Expr *>(*std::next(child_begin(), CondOffset)));
}
Expr *getInit() const {
return const_cast<Expr *>(
reinterpret_cast<const Expr *>(*std::next(child_begin(), InitOffset)));
}
Expr *getInc() const {
return const_cast<Expr *>(
reinterpret_cast<const Expr *>(*std::next(child_begin(), IncOffset)));
}
const Stmt *getPreInits() const {
return *std::next(child_begin(), PreInitsOffset);
}
Stmt *getPreInits() { return *std::next(child_begin(), PreInitsOffset); }
Expr *getIsLastIterVariable() const {
assert((isOpenMPWorksharingDirective(getDirectiveKind()) ||
isOpenMPTaskLoopDirective(getDirectiveKind()) ||
isOpenMPDistributeDirective(getDirectiveKind())) &&
"expected worksharing loop directive");
return const_cast<Expr *>(reinterpret_cast<const Expr *>(
*std::next(child_begin(), IsLastIterVariableOffset)));
}
Expr *getLowerBoundVariable() const {
assert((isOpenMPWorksharingDirective(getDirectiveKind()) ||
isOpenMPTaskLoopDirective(getDirectiveKind()) ||
isOpenMPDistributeDirective(getDirectiveKind())) &&
"expected worksharing loop directive");
return const_cast<Expr *>(reinterpret_cast<const Expr *>(
*std::next(child_begin(), LowerBoundVariableOffset)));
}
Expr *getUpperBoundVariable() const {
assert((isOpenMPWorksharingDirective(getDirectiveKind()) ||
isOpenMPTaskLoopDirective(getDirectiveKind()) ||
isOpenMPDistributeDirective(getDirectiveKind())) &&
"expected worksharing loop directive");
return const_cast<Expr *>(reinterpret_cast<const Expr *>(
*std::next(child_begin(), UpperBoundVariableOffset)));
}
Expr *getStrideVariable() const {
assert((isOpenMPWorksharingDirective(getDirectiveKind()) ||
isOpenMPTaskLoopDirective(getDirectiveKind()) ||
isOpenMPDistributeDirective(getDirectiveKind())) &&
"expected worksharing loop directive");
return const_cast<Expr *>(reinterpret_cast<const Expr *>(
*std::next(child_begin(), StrideVariableOffset)));
}
Expr *getEnsureUpperBound() const {
assert((isOpenMPWorksharingDirective(getDirectiveKind()) ||
isOpenMPTaskLoopDirective(getDirectiveKind()) ||
isOpenMPDistributeDirective(getDirectiveKind())) &&
"expected worksharing loop directive");
return const_cast<Expr *>(reinterpret_cast<const Expr *>(
*std::next(child_begin(), EnsureUpperBoundOffset)));
}
Expr *getNextLowerBound() const {
assert((isOpenMPWorksharingDirective(getDirectiveKind()) ||
isOpenMPTaskLoopDirective(getDirectiveKind()) ||
isOpenMPDistributeDirective(getDirectiveKind())) &&
"expected worksharing loop directive");
return const_cast<Expr *>(reinterpret_cast<const Expr *>(
*std::next(child_begin(), NextLowerBoundOffset)));
}
Expr *getNextUpperBound() const {
assert((isOpenMPWorksharingDirective(getDirectiveKind()) ||
isOpenMPTaskLoopDirective(getDirectiveKind()) ||
isOpenMPDistributeDirective(getDirectiveKind())) &&
"expected worksharing loop directive");
return const_cast<Expr *>(reinterpret_cast<const Expr *>(
*std::next(child_begin(), NextUpperBoundOffset)));
}
Expr *getNumIterations() const {
assert((isOpenMPWorksharingDirective(getDirectiveKind()) ||
isOpenMPTaskLoopDirective(getDirectiveKind()) ||
isOpenMPDistributeDirective(getDirectiveKind())) &&
"expected worksharing loop directive");
return const_cast<Expr *>(reinterpret_cast<const Expr *>(
*std::next(child_begin(), NumIterationsOffset)));
}
Expr *getPrevLowerBoundVariable() const {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
return const_cast<Expr *>(reinterpret_cast<const Expr *>(
*std::next(child_begin(), PrevLowerBoundVariableOffset)));
}
Expr *getPrevUpperBoundVariable() const {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
return const_cast<Expr *>(reinterpret_cast<const Expr *>(
*std::next(child_begin(), PrevUpperBoundVariableOffset)));
}
Expr *getDistInc() const {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
return const_cast<Expr *>(reinterpret_cast<const Expr *>(
*std::next(child_begin(), DistIncOffset)));
}
Expr *getPrevEnsureUpperBound() const {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
return const_cast<Expr *>(reinterpret_cast<const Expr *>(
*std::next(child_begin(), PrevEnsureUpperBoundOffset)));
}
Expr *getCombinedLowerBoundVariable() const {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
return const_cast<Expr *>(reinterpret_cast<const Expr *>(
*std::next(child_begin(), CombinedLowerBoundVariableOffset)));
}
Expr *getCombinedUpperBoundVariable() const {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
return const_cast<Expr *>(reinterpret_cast<const Expr *>(
*std::next(child_begin(), CombinedUpperBoundVariableOffset)));
}
Expr *getCombinedEnsureUpperBound() const {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
return const_cast<Expr *>(reinterpret_cast<const Expr *>(
*std::next(child_begin(), CombinedEnsureUpperBoundOffset)));
}
Expr *getCombinedInit() const {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
return const_cast<Expr *>(reinterpret_cast<const Expr *>(
*std::next(child_begin(), CombinedInitOffset)));
}
Expr *getCombinedCond() const {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
return const_cast<Expr *>(reinterpret_cast<const Expr *>(
*std::next(child_begin(), CombinedConditionOffset)));
}
Expr *getCombinedNextLowerBound() const {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
return const_cast<Expr *>(reinterpret_cast<const Expr *>(
*std::next(child_begin(), CombinedNextLowerBoundOffset)));
}
Expr *getCombinedNextUpperBound() const {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound sharing directive");
return const_cast<Expr *>(reinterpret_cast<const Expr *>(
*std::next(child_begin(), CombinedNextUpperBoundOffset)));
}
Expr *getCombinedDistCond() const {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound distribute sharing directive");
return const_cast<Expr *>(reinterpret_cast<const Expr *>(
*std::next(child_begin(), CombinedDistConditionOffset)));
}
Expr *getCombinedParForInDistCond() const {
assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
"expected loop bound distribute sharing directive");
return const_cast<Expr *>(reinterpret_cast<const Expr *>(
*std::next(child_begin(), CombinedParForInDistConditionOffset)));
}
const Stmt *getBody() const {
// This relies on the loop form is already checked by Sema.
const Stmt *Body =
getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers();
Body = cast<ForStmt>(Body)->getBody();
for (unsigned Cnt = 1; Cnt < CollapsedNum; ++Cnt) {
Body = Body->IgnoreContainers();
Body = cast<ForStmt>(Body)->getBody();
}
return Body;
}
ArrayRef<Expr *> counters() { return getCounters(); }
ArrayRef<Expr *> counters() const {
return const_cast<OMPLoopDirective *>(this)->getCounters();
}
ArrayRef<Expr *> private_counters() { return getPrivateCounters(); }
ArrayRef<Expr *> private_counters() const {
return const_cast<OMPLoopDirective *>(this)->getPrivateCounters();
}
ArrayRef<Expr *> inits() { return getInits(); }
ArrayRef<Expr *> inits() const {
return const_cast<OMPLoopDirective *>(this)->getInits();
}
ArrayRef<Expr *> updates() { return getUpdates(); }
ArrayRef<Expr *> updates() const {
return const_cast<OMPLoopDirective *>(this)->getUpdates();
}
ArrayRef<Expr *> finals() { return getFinals(); }
ArrayRef<Expr *> finals() const {
return const_cast<OMPLoopDirective *>(this)->getFinals();
}
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPSimdDirectiveClass ||
T->getStmtClass() == OMPForDirectiveClass ||
T->getStmtClass() == OMPForSimdDirectiveClass ||
T->getStmtClass() == OMPParallelForDirectiveClass ||
T->getStmtClass() == OMPParallelForSimdDirectiveClass ||
T->getStmtClass() == OMPTaskLoopDirectiveClass ||
T->getStmtClass() == OMPTaskLoopSimdDirectiveClass ||
T->getStmtClass() == OMPDistributeDirectiveClass ||
T->getStmtClass() == OMPTargetParallelForDirectiveClass ||
T->getStmtClass() == OMPDistributeParallelForDirectiveClass ||
T->getStmtClass() == OMPDistributeParallelForSimdDirectiveClass ||
T->getStmtClass() == OMPDistributeSimdDirectiveClass ||
T->getStmtClass() == OMPTargetParallelForSimdDirectiveClass ||
T->getStmtClass() == OMPTargetSimdDirectiveClass ||
T->getStmtClass() == OMPTeamsDistributeDirectiveClass ||
T->getStmtClass() == OMPTeamsDistributeSimdDirectiveClass ||
T->getStmtClass() ==
OMPTeamsDistributeParallelForSimdDirectiveClass ||
T->getStmtClass() == OMPTeamsDistributeParallelForDirectiveClass ||
T->getStmtClass() ==
OMPTargetTeamsDistributeParallelForDirectiveClass ||
T->getStmtClass() ==
OMPTargetTeamsDistributeParallelForSimdDirectiveClass ||
T->getStmtClass() == OMPTargetTeamsDistributeDirectiveClass ||
T->getStmtClass() == OMPTargetTeamsDistributeSimdDirectiveClass;
}
};
/// This represents '#pragma omp simd' directive.
///
/// \code
/// #pragma omp simd private(a,b) linear(i,j:s) reduction(+:c,d)
/// \endcode
/// In this example directive '#pragma omp simd' has clauses 'private'
/// with the variables 'a' and 'b', 'linear' with variables 'i', 'j' and
/// linear step 's', 'reduction' with operator '+' and variables 'c' and 'd'.
///
class OMPSimdDirective : public OMPLoopDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
OMPSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, unsigned NumClauses)
: OMPLoopDirective(this, OMPSimdDirectiveClass, OMPD_simd, StartLoc,
EndLoc, CollapsedNum, NumClauses) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
explicit OMPSimdDirective(unsigned CollapsedNum, unsigned NumClauses)
: OMPLoopDirective(this, OMPSimdDirectiveClass, OMPD_simd,
SourceLocation(), SourceLocation(), CollapsedNum,
NumClauses) {}
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param CollapsedNum Number of collapsed loops.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param Exprs Helper expressions for CodeGen.
///
static OMPSimdDirective *Create(const ASTContext &C, SourceLocation StartLoc,
SourceLocation EndLoc, unsigned CollapsedNum,
ArrayRef<OMPClause *> Clauses,
Stmt *AssociatedStmt,
const HelperExprs &Exprs);
/// Creates an empty directive with the place
/// for \a NumClauses clauses.
///
/// \param C AST context.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
static OMPSimdDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses,
unsigned CollapsedNum, EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPSimdDirectiveClass;
}
};
/// This represents '#pragma omp for' directive.
///
/// \code
/// #pragma omp for private(a,b) reduction(+:c,d)
/// \endcode
/// In this example directive '#pragma omp for' has clauses 'private' with the
/// variables 'a' and 'b' and 'reduction' with operator '+' and variables 'c'
/// and 'd'.
///
class OMPForDirective : public OMPLoopDirective {
friend class ASTStmtReader;
/// true if current directive has inner cancel directive.
bool HasCancel;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
OMPForDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, unsigned NumClauses)
: OMPLoopDirective(this, OMPForDirectiveClass, OMPD_for, StartLoc, EndLoc,
CollapsedNum, NumClauses),
HasCancel(false) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
explicit OMPForDirective(unsigned CollapsedNum, unsigned NumClauses)
: OMPLoopDirective(this, OMPForDirectiveClass, OMPD_for, SourceLocation(),
SourceLocation(), CollapsedNum, NumClauses),
HasCancel(false) {}
/// Set cancel state.
void setHasCancel(bool Has) { HasCancel = Has; }
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param CollapsedNum Number of collapsed loops.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param Exprs Helper expressions for CodeGen.
/// \param HasCancel true if current directive has inner cancel directive.
///
static OMPForDirective *Create(const ASTContext &C, SourceLocation StartLoc,
SourceLocation EndLoc, unsigned CollapsedNum,
ArrayRef<OMPClause *> Clauses,
Stmt *AssociatedStmt, const HelperExprs &Exprs,
bool HasCancel);
/// Creates an empty directive with the place
/// for \a NumClauses clauses.
///
/// \param C AST context.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
static OMPForDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses,
unsigned CollapsedNum, EmptyShell);
/// Return true if current directive has inner cancel directive.
bool hasCancel() const { return HasCancel; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPForDirectiveClass;
}
};
/// This represents '#pragma omp for simd' directive.
///
/// \code
/// #pragma omp for simd private(a,b) linear(i,j:s) reduction(+:c,d)
/// \endcode
/// In this example directive '#pragma omp for simd' has clauses 'private'
/// with the variables 'a' and 'b', 'linear' with variables 'i', 'j' and
/// linear step 's', 'reduction' with operator '+' and variables 'c' and 'd'.
///
class OMPForSimdDirective : public OMPLoopDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
OMPForSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, unsigned NumClauses)
: OMPLoopDirective(this, OMPForSimdDirectiveClass, OMPD_for_simd,
StartLoc, EndLoc, CollapsedNum, NumClauses) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
explicit OMPForSimdDirective(unsigned CollapsedNum, unsigned NumClauses)
: OMPLoopDirective(this, OMPForSimdDirectiveClass, OMPD_for_simd,
SourceLocation(), SourceLocation(), CollapsedNum,
NumClauses) {}
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param CollapsedNum Number of collapsed loops.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param Exprs Helper expressions for CodeGen.
///
static OMPForSimdDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses,
Stmt *AssociatedStmt, const HelperExprs &Exprs);
/// Creates an empty directive with the place
/// for \a NumClauses clauses.
///
/// \param C AST context.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
static OMPForSimdDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses,
unsigned CollapsedNum, EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPForSimdDirectiveClass;
}
};
/// This represents '#pragma omp sections' directive.
///
/// \code
/// #pragma omp sections private(a,b) reduction(+:c,d)
/// \endcode
/// In this example directive '#pragma omp sections' has clauses 'private' with
/// the variables 'a' and 'b' and 'reduction' with operator '+' and variables
/// 'c' and 'd'.
///
class OMPSectionsDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
/// true if current directive has inner cancel directive.
bool HasCancel;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param NumClauses Number of clauses.
///
OMPSectionsDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned NumClauses)
: OMPExecutableDirective(this, OMPSectionsDirectiveClass, OMPD_sections,
StartLoc, EndLoc, NumClauses, 1),
HasCancel(false) {}
/// Build an empty directive.
///
/// \param NumClauses Number of clauses.
///
explicit OMPSectionsDirective(unsigned NumClauses)
: OMPExecutableDirective(this, OMPSectionsDirectiveClass, OMPD_sections,
SourceLocation(), SourceLocation(), NumClauses,
1),
HasCancel(false) {}
/// Set cancel state.
void setHasCancel(bool Has) { HasCancel = Has; }
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param HasCancel true if current directive has inner directive.
///
static OMPSectionsDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, bool HasCancel);
/// Creates an empty directive with the place for \a NumClauses
/// clauses.
///
/// \param C AST context.
/// \param NumClauses Number of clauses.
///
static OMPSectionsDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses, EmptyShell);
/// Return true if current directive has inner cancel directive.
bool hasCancel() const { return HasCancel; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPSectionsDirectiveClass;
}
};
/// This represents '#pragma omp section' directive.
///
/// \code
/// #pragma omp section
/// \endcode
///
class OMPSectionDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
/// true if current directive has inner cancel directive.
bool HasCancel;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
///
OMPSectionDirective(SourceLocation StartLoc, SourceLocation EndLoc)
: OMPExecutableDirective(this, OMPSectionDirectiveClass, OMPD_section,
StartLoc, EndLoc, 0, 1),
HasCancel(false) {}
/// Build an empty directive.
///
explicit OMPSectionDirective()
: OMPExecutableDirective(this, OMPSectionDirectiveClass, OMPD_section,
SourceLocation(), SourceLocation(), 0, 1),
HasCancel(false) {}
public:
/// Creates directive.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param HasCancel true if current directive has inner directive.
///
static OMPSectionDirective *Create(const ASTContext &C,
SourceLocation StartLoc,
SourceLocation EndLoc,
Stmt *AssociatedStmt, bool HasCancel);
/// Creates an empty directive.
///
/// \param C AST context.
///
static OMPSectionDirective *CreateEmpty(const ASTContext &C, EmptyShell);
/// Set cancel state.
void setHasCancel(bool Has) { HasCancel = Has; }
/// Return true if current directive has inner cancel directive.
bool hasCancel() const { return HasCancel; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPSectionDirectiveClass;
}
};
/// This represents '#pragma omp single' directive.
///
/// \code
/// #pragma omp single private(a,b) copyprivate(c,d)
/// \endcode
/// In this example directive '#pragma omp single' has clauses 'private' with
/// the variables 'a' and 'b' and 'copyprivate' with variables 'c' and 'd'.
///
class OMPSingleDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param NumClauses Number of clauses.
///
OMPSingleDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned NumClauses)
: OMPExecutableDirective(this, OMPSingleDirectiveClass, OMPD_single,
StartLoc, EndLoc, NumClauses, 1) {}
/// Build an empty directive.
///
/// \param NumClauses Number of clauses.
///
explicit OMPSingleDirective(unsigned NumClauses)
: OMPExecutableDirective(this, OMPSingleDirectiveClass, OMPD_single,
SourceLocation(), SourceLocation(), NumClauses,
1) {}
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
///
static OMPSingleDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt);
/// Creates an empty directive with the place for \a NumClauses
/// clauses.
///
/// \param C AST context.
/// \param NumClauses Number of clauses.
///
static OMPSingleDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses, EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPSingleDirectiveClass;
}
};
/// This represents '#pragma omp master' directive.
///
/// \code
/// #pragma omp master
/// \endcode
///
class OMPMasterDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
///
OMPMasterDirective(SourceLocation StartLoc, SourceLocation EndLoc)
: OMPExecutableDirective(this, OMPMasterDirectiveClass, OMPD_master,
StartLoc, EndLoc, 0, 1) {}
/// Build an empty directive.
///
explicit OMPMasterDirective()
: OMPExecutableDirective(this, OMPMasterDirectiveClass, OMPD_master,
SourceLocation(), SourceLocation(), 0, 1) {}
public:
/// Creates directive.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param AssociatedStmt Statement, associated with the directive.
///
static OMPMasterDirective *Create(const ASTContext &C,
SourceLocation StartLoc,
SourceLocation EndLoc,
Stmt *AssociatedStmt);
/// Creates an empty directive.
///
/// \param C AST context.
///
static OMPMasterDirective *CreateEmpty(const ASTContext &C, EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPMasterDirectiveClass;
}
};
/// This represents '#pragma omp critical' directive.
///
/// \code
/// #pragma omp critical
/// \endcode
///
class OMPCriticalDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
/// Name of the directive.
DeclarationNameInfo DirName;
/// Build directive with the given start and end location.
///
/// \param Name Name of the directive.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param NumClauses Number of clauses.
///
OMPCriticalDirective(const DeclarationNameInfo &Name, SourceLocation StartLoc,
SourceLocation EndLoc, unsigned NumClauses)
: OMPExecutableDirective(this, OMPCriticalDirectiveClass, OMPD_critical,
StartLoc, EndLoc, NumClauses, 1),
DirName(Name) {}
/// Build an empty directive.
///
/// \param NumClauses Number of clauses.
///
explicit OMPCriticalDirective(unsigned NumClauses)
: OMPExecutableDirective(this, OMPCriticalDirectiveClass, OMPD_critical,
SourceLocation(), SourceLocation(), NumClauses,
1),
DirName() {}
/// Set name of the directive.
///
/// \param Name Name of the directive.
///
void setDirectiveName(const DeclarationNameInfo &Name) { DirName = Name; }
public:
/// Creates directive.
///
/// \param C AST context.
/// \param Name Name of the directive.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
///
static OMPCriticalDirective *
Create(const ASTContext &C, const DeclarationNameInfo &Name,
SourceLocation StartLoc, SourceLocation EndLoc,
ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt);
/// Creates an empty directive.
///
/// \param C AST context.
/// \param NumClauses Number of clauses.
///
static OMPCriticalDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses, EmptyShell);
/// Return name of the directive.
///
DeclarationNameInfo getDirectiveName() const { return DirName; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPCriticalDirectiveClass;
}
};
/// This represents '#pragma omp parallel for' directive.
///
/// \code
/// #pragma omp parallel for private(a,b) reduction(+:c,d)
/// \endcode
/// In this example directive '#pragma omp parallel for' has clauses 'private'
/// with the variables 'a' and 'b' and 'reduction' with operator '+' and
/// variables 'c' and 'd'.
///
class OMPParallelForDirective : public OMPLoopDirective {
friend class ASTStmtReader;
/// true if current region has inner cancel directive.
bool HasCancel;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
OMPParallelForDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, unsigned NumClauses)
: OMPLoopDirective(this, OMPParallelForDirectiveClass, OMPD_parallel_for,
StartLoc, EndLoc, CollapsedNum, NumClauses),
HasCancel(false) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
explicit OMPParallelForDirective(unsigned CollapsedNum, unsigned NumClauses)
: OMPLoopDirective(this, OMPParallelForDirectiveClass, OMPD_parallel_for,
SourceLocation(), SourceLocation(), CollapsedNum,
NumClauses),
HasCancel(false) {}
/// Set cancel state.
void setHasCancel(bool Has) { HasCancel = Has; }
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param CollapsedNum Number of collapsed loops.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param Exprs Helper expressions for CodeGen.
/// \param HasCancel true if current directive has inner cancel directive.
///
static OMPParallelForDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses,
Stmt *AssociatedStmt, const HelperExprs &Exprs, bool HasCancel);
/// Creates an empty directive with the place
/// for \a NumClauses clauses.
///
/// \param C AST context.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
static OMPParallelForDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses,
unsigned CollapsedNum,
EmptyShell);
/// Return true if current directive has inner cancel directive.
bool hasCancel() const { return HasCancel; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPParallelForDirectiveClass;
}
};
/// This represents '#pragma omp parallel for simd' directive.
///
/// \code
/// #pragma omp parallel for simd private(a,b) linear(i,j:s) reduction(+:c,d)
/// \endcode
/// In this example directive '#pragma omp parallel for simd' has clauses
/// 'private' with the variables 'a' and 'b', 'linear' with variables 'i', 'j'
/// and linear step 's', 'reduction' with operator '+' and variables 'c' and
/// 'd'.
///
class OMPParallelForSimdDirective : public OMPLoopDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
OMPParallelForSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, unsigned NumClauses)
: OMPLoopDirective(this, OMPParallelForSimdDirectiveClass,
OMPD_parallel_for_simd, StartLoc, EndLoc, CollapsedNum,
NumClauses) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
explicit OMPParallelForSimdDirective(unsigned CollapsedNum,
unsigned NumClauses)
: OMPLoopDirective(this, OMPParallelForSimdDirectiveClass,
OMPD_parallel_for_simd, SourceLocation(),
SourceLocation(), CollapsedNum, NumClauses) {}
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param CollapsedNum Number of collapsed loops.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param Exprs Helper expressions for CodeGen.
///
static OMPParallelForSimdDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses,
Stmt *AssociatedStmt, const HelperExprs &Exprs);
/// Creates an empty directive with the place
/// for \a NumClauses clauses.
///
/// \param C AST context.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
static OMPParallelForSimdDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses,
unsigned CollapsedNum,
EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPParallelForSimdDirectiveClass;
}
};
/// This represents '#pragma omp parallel sections' directive.
///
/// \code
/// #pragma omp parallel sections private(a,b) reduction(+:c,d)
/// \endcode
/// In this example directive '#pragma omp parallel sections' has clauses
/// 'private' with the variables 'a' and 'b' and 'reduction' with operator '+'
/// and variables 'c' and 'd'.
///
class OMPParallelSectionsDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
/// true if current directive has inner cancel directive.
bool HasCancel;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param NumClauses Number of clauses.
///
OMPParallelSectionsDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned NumClauses)
: OMPExecutableDirective(this, OMPParallelSectionsDirectiveClass,
OMPD_parallel_sections, StartLoc, EndLoc,
NumClauses, 1),
HasCancel(false) {}
/// Build an empty directive.
///
/// \param NumClauses Number of clauses.
///
explicit OMPParallelSectionsDirective(unsigned NumClauses)
: OMPExecutableDirective(this, OMPParallelSectionsDirectiveClass,
OMPD_parallel_sections, SourceLocation(),
SourceLocation(), NumClauses, 1),
HasCancel(false) {}
/// Set cancel state.
void setHasCancel(bool Has) { HasCancel = Has; }
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param HasCancel true if current directive has inner cancel directive.
///
static OMPParallelSectionsDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, bool HasCancel);
/// Creates an empty directive with the place for \a NumClauses
/// clauses.
///
/// \param C AST context.
/// \param NumClauses Number of clauses.
///
static OMPParallelSectionsDirective *
CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell);
/// Return true if current directive has inner cancel directive.
bool hasCancel() const { return HasCancel; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPParallelSectionsDirectiveClass;
}
};
/// This represents '#pragma omp task' directive.
///
/// \code
/// #pragma omp task private(a,b) final(d)
/// \endcode
/// In this example directive '#pragma omp task' has clauses 'private' with the
/// variables 'a' and 'b' and 'final' with condition 'd'.
///
class OMPTaskDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
/// true if this directive has inner cancel directive.
bool HasCancel;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param NumClauses Number of clauses.
///
OMPTaskDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned NumClauses)
: OMPExecutableDirective(this, OMPTaskDirectiveClass, OMPD_task, StartLoc,
EndLoc, NumClauses, 1),
HasCancel(false) {}
/// Build an empty directive.
///
/// \param NumClauses Number of clauses.
///
explicit OMPTaskDirective(unsigned NumClauses)
: OMPExecutableDirective(this, OMPTaskDirectiveClass, OMPD_task,
SourceLocation(), SourceLocation(), NumClauses,
1),
HasCancel(false) {}
/// Set cancel state.
void setHasCancel(bool Has) { HasCancel = Has; }
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param HasCancel true, if current directive has inner cancel directive.
///
static OMPTaskDirective *Create(const ASTContext &C, SourceLocation StartLoc,
SourceLocation EndLoc,
ArrayRef<OMPClause *> Clauses,
Stmt *AssociatedStmt, bool HasCancel);
/// Creates an empty directive with the place for \a NumClauses
/// clauses.
///
/// \param C AST context.
/// \param NumClauses Number of clauses.
///
static OMPTaskDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses,
EmptyShell);
/// Return true if current directive has inner cancel directive.
bool hasCancel() const { return HasCancel; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPTaskDirectiveClass;
}
};
/// This represents '#pragma omp taskyield' directive.
///
/// \code
/// #pragma omp taskyield
/// \endcode
///
class OMPTaskyieldDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
///
OMPTaskyieldDirective(SourceLocation StartLoc, SourceLocation EndLoc)
: OMPExecutableDirective(this, OMPTaskyieldDirectiveClass, OMPD_taskyield,
StartLoc, EndLoc, 0, 0) {}
/// Build an empty directive.
///
explicit OMPTaskyieldDirective()
: OMPExecutableDirective(this, OMPTaskyieldDirectiveClass, OMPD_taskyield,
SourceLocation(), SourceLocation(), 0, 0) {}
public:
/// Creates directive.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
///
static OMPTaskyieldDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc);
/// Creates an empty directive.
///
/// \param C AST context.
///
static OMPTaskyieldDirective *CreateEmpty(const ASTContext &C, EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPTaskyieldDirectiveClass;
}
};
/// This represents '#pragma omp barrier' directive.
///
/// \code
/// #pragma omp barrier
/// \endcode
///
class OMPBarrierDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
///
OMPBarrierDirective(SourceLocation StartLoc, SourceLocation EndLoc)
: OMPExecutableDirective(this, OMPBarrierDirectiveClass, OMPD_barrier,
StartLoc, EndLoc, 0, 0) {}
/// Build an empty directive.
///
explicit OMPBarrierDirective()
: OMPExecutableDirective(this, OMPBarrierDirectiveClass, OMPD_barrier,
SourceLocation(), SourceLocation(), 0, 0) {}
public:
/// Creates directive.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
///
static OMPBarrierDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc);
/// Creates an empty directive.
///
/// \param C AST context.
///
static OMPBarrierDirective *CreateEmpty(const ASTContext &C, EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPBarrierDirectiveClass;
}
};
/// This represents '#pragma omp taskwait' directive.
///
/// \code
/// #pragma omp taskwait
/// \endcode
///
class OMPTaskwaitDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
///
OMPTaskwaitDirective(SourceLocation StartLoc, SourceLocation EndLoc)
: OMPExecutableDirective(this, OMPTaskwaitDirectiveClass, OMPD_taskwait,
StartLoc, EndLoc, 0, 0) {}
/// Build an empty directive.
///
explicit OMPTaskwaitDirective()
: OMPExecutableDirective(this, OMPTaskwaitDirectiveClass, OMPD_taskwait,
SourceLocation(), SourceLocation(), 0, 0) {}
public:
/// Creates directive.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
///
static OMPTaskwaitDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc);
/// Creates an empty directive.
///
/// \param C AST context.
///
static OMPTaskwaitDirective *CreateEmpty(const ASTContext &C, EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPTaskwaitDirectiveClass;
}
};
/// This represents '#pragma omp taskgroup' directive.
///
/// \code
/// #pragma omp taskgroup
/// \endcode
///
class OMPTaskgroupDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param NumClauses Number of clauses.
///
OMPTaskgroupDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned NumClauses)
: OMPExecutableDirective(this, OMPTaskgroupDirectiveClass, OMPD_taskgroup,
StartLoc, EndLoc, NumClauses, 2) {}
/// Build an empty directive.
/// \param NumClauses Number of clauses.
///
explicit OMPTaskgroupDirective(unsigned NumClauses)
: OMPExecutableDirective(this, OMPTaskgroupDirectiveClass, OMPD_taskgroup,
SourceLocation(), SourceLocation(), NumClauses,
2) {}
/// Sets the task_reduction return variable.
void setReductionRef(Expr *RR) {
*std::next(child_begin(), 1) = RR;
}
public:
/// Creates directive.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param ReductionRef Reference to the task_reduction return variable.
///
static OMPTaskgroupDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt,
Expr *ReductionRef);
/// Creates an empty directive.
///
/// \param C AST context.
/// \param NumClauses Number of clauses.
///
static OMPTaskgroupDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses, EmptyShell);
/// Returns reference to the task_reduction return variable.
const Expr *getReductionRef() const {
return static_cast<const Expr *>(*std::next(child_begin(), 1));
}
Expr *getReductionRef() {
return static_cast<Expr *>(*std::next(child_begin(), 1));
}
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPTaskgroupDirectiveClass;
}
};
/// This represents '#pragma omp flush' directive.
///
/// \code
/// #pragma omp flush(a,b)
/// \endcode
/// In this example directive '#pragma omp flush' has 2 arguments- variables 'a'
/// and 'b'.
/// 'omp flush' directive does not have clauses but have an optional list of
/// variables to flush. This list of variables is stored within some fake clause
/// FlushClause.
class OMPFlushDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param NumClauses Number of clauses.
///
OMPFlushDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned NumClauses)
: OMPExecutableDirective(this, OMPFlushDirectiveClass, OMPD_flush,
StartLoc, EndLoc, NumClauses, 0) {}
/// Build an empty directive.
///
/// \param NumClauses Number of clauses.
///
explicit OMPFlushDirective(unsigned NumClauses)
: OMPExecutableDirective(this, OMPFlushDirectiveClass, OMPD_flush,
SourceLocation(), SourceLocation(), NumClauses,
0) {}
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param Clauses List of clauses (only single OMPFlushClause clause is
/// allowed).
///
static OMPFlushDirective *Create(const ASTContext &C, SourceLocation StartLoc,
SourceLocation EndLoc,
ArrayRef<OMPClause *> Clauses);
/// Creates an empty directive with the place for \a NumClauses
/// clauses.
///
/// \param C AST context.
/// \param NumClauses Number of clauses.
///
static OMPFlushDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses, EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPFlushDirectiveClass;
}
};
/// This represents '#pragma omp ordered' directive.
///
/// \code
/// #pragma omp ordered
/// \endcode
///
class OMPOrderedDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param NumClauses Number of clauses.
///
OMPOrderedDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned NumClauses)
: OMPExecutableDirective(this, OMPOrderedDirectiveClass, OMPD_ordered,
StartLoc, EndLoc, NumClauses, 1) {}
/// Build an empty directive.
///
/// \param NumClauses Number of clauses.
///
explicit OMPOrderedDirective(unsigned NumClauses)
: OMPExecutableDirective(this, OMPOrderedDirectiveClass, OMPD_ordered,
SourceLocation(), SourceLocation(), NumClauses,
1) {}
public:
/// Creates directive.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
///
static OMPOrderedDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt);
/// Creates an empty directive.
///
/// \param C AST context.
/// \param NumClauses Number of clauses.
///
static OMPOrderedDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses, EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPOrderedDirectiveClass;
}
};
/// This represents '#pragma omp atomic' directive.
///
/// \code
/// #pragma omp atomic capture
/// \endcode
/// In this example directive '#pragma omp atomic' has clause 'capture'.
///
class OMPAtomicDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
/// Used for 'atomic update' or 'atomic capture' constructs. They may
/// have atomic expressions of forms
/// \code
/// x = x binop expr;
/// x = expr binop x;
/// \endcode
/// This field is true for the first form of the expression and false for the
/// second. Required for correct codegen of non-associative operations (like
/// << or >>).
bool IsXLHSInRHSPart;
/// Used for 'atomic update' or 'atomic capture' constructs. They may
/// have atomic expressions of forms
/// \code
/// v = x; <update x>;
/// <update x>; v = x;
/// \endcode
/// This field is true for the first(postfix) form of the expression and false
/// otherwise.
bool IsPostfixUpdate;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param NumClauses Number of clauses.
///
OMPAtomicDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned NumClauses)
: OMPExecutableDirective(this, OMPAtomicDirectiveClass, OMPD_atomic,
StartLoc, EndLoc, NumClauses, 5),
IsXLHSInRHSPart(false), IsPostfixUpdate(false) {}
/// Build an empty directive.
///
/// \param NumClauses Number of clauses.
///
explicit OMPAtomicDirective(unsigned NumClauses)
: OMPExecutableDirective(this, OMPAtomicDirectiveClass, OMPD_atomic,
SourceLocation(), SourceLocation(), NumClauses,
5),
IsXLHSInRHSPart(false), IsPostfixUpdate(false) {}
/// Set 'x' part of the associated expression/statement.
void setX(Expr *X) { *std::next(child_begin()) = X; }
/// Set helper expression of the form
/// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
/// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
void setUpdateExpr(Expr *UE) { *std::next(child_begin(), 2) = UE; }
/// Set 'v' part of the associated expression/statement.
void setV(Expr *V) { *std::next(child_begin(), 3) = V; }
/// Set 'expr' part of the associated expression/statement.
void setExpr(Expr *E) { *std::next(child_begin(), 4) = E; }
public:
/// Creates directive with a list of \a Clauses and 'x', 'v' and 'expr'
/// parts of the atomic construct (see Section 2.12.6, atomic Construct, for
/// detailed description of 'x', 'v' and 'expr').
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param X 'x' part of the associated expression/statement.
/// \param V 'v' part of the associated expression/statement.
/// \param E 'expr' part of the associated expression/statement.
/// \param UE Helper expression of the form
/// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
/// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
/// \param IsXLHSInRHSPart true if \a UE has the first form and false if the
/// second.
/// \param IsPostfixUpdate true if original value of 'x' must be stored in
/// 'v', not an updated one.
static OMPAtomicDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, Expr *X, Expr *V,
Expr *E, Expr *UE, bool IsXLHSInRHSPart, bool IsPostfixUpdate);
/// Creates an empty directive with the place for \a NumClauses
/// clauses.
///
/// \param C AST context.
/// \param NumClauses Number of clauses.
///
static OMPAtomicDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses, EmptyShell);
/// Get 'x' part of the associated expression/statement.
Expr *getX() { return cast_or_null<Expr>(*std::next(child_begin())); }
const Expr *getX() const {
return cast_or_null<Expr>(*std::next(child_begin()));
}
/// Get helper expression of the form
/// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
/// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
Expr *getUpdateExpr() {
return cast_or_null<Expr>(*std::next(child_begin(), 2));
}
const Expr *getUpdateExpr() const {
return cast_or_null<Expr>(*std::next(child_begin(), 2));
}
/// Return true if helper update expression has form
/// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' and false if it has form
/// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
/// Return true if 'v' expression must be updated to original value of
/// 'x', false if 'v' must be updated to the new value of 'x'.
bool isPostfixUpdate() const { return IsPostfixUpdate; }
/// Get 'v' part of the associated expression/statement.
Expr *getV() { return cast_or_null<Expr>(*std::next(child_begin(), 3)); }
const Expr *getV() const {
return cast_or_null<Expr>(*std::next(child_begin(), 3));
}
/// Get 'expr' part of the associated expression/statement.
Expr *getExpr() { return cast_or_null<Expr>(*std::next(child_begin(), 4)); }
const Expr *getExpr() const {
return cast_or_null<Expr>(*std::next(child_begin(), 4));
}
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPAtomicDirectiveClass;
}
};
/// This represents '#pragma omp target' directive.
///
/// \code
/// #pragma omp target if(a)
/// \endcode
/// In this example directive '#pragma omp target' has clause 'if' with
/// condition 'a'.
///
class OMPTargetDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param NumClauses Number of clauses.
///
OMPTargetDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned NumClauses)
: OMPExecutableDirective(this, OMPTargetDirectiveClass, OMPD_target,
StartLoc, EndLoc, NumClauses, 1) {}
/// Build an empty directive.
///
/// \param NumClauses Number of clauses.
///
explicit OMPTargetDirective(unsigned NumClauses)
: OMPExecutableDirective(this, OMPTargetDirectiveClass, OMPD_target,
SourceLocation(), SourceLocation(), NumClauses,
1) {}
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
///
static OMPTargetDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt);
/// Creates an empty directive with the place for \a NumClauses
/// clauses.
///
/// \param C AST context.
/// \param NumClauses Number of clauses.
///
static OMPTargetDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses, EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPTargetDirectiveClass;
}
};
/// This represents '#pragma omp target data' directive.
///
/// \code
/// #pragma omp target data device(0) if(a) map(b[:])
/// \endcode
/// In this example directive '#pragma omp target data' has clauses 'device'
/// with the value '0', 'if' with condition 'a' and 'map' with array
/// section 'b[:]'.
///
class OMPTargetDataDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param NumClauses The number of clauses.
///
OMPTargetDataDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned NumClauses)
: OMPExecutableDirective(this, OMPTargetDataDirectiveClass,
OMPD_target_data, StartLoc, EndLoc, NumClauses,
1) {}
/// Build an empty directive.
///
/// \param NumClauses Number of clauses.
///
explicit OMPTargetDataDirective(unsigned NumClauses)
: OMPExecutableDirective(this, OMPTargetDataDirectiveClass,
OMPD_target_data, SourceLocation(),
SourceLocation(), NumClauses, 1) {}
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
///
static OMPTargetDataDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt);
/// Creates an empty directive with the place for \a N clauses.
///
/// \param C AST context.
/// \param N The number of clauses.
///
static OMPTargetDataDirective *CreateEmpty(const ASTContext &C, unsigned N,
EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPTargetDataDirectiveClass;
}
};
/// This represents '#pragma omp target enter data' directive.
///
/// \code
/// #pragma omp target enter data device(0) if(a) map(b[:])
/// \endcode
/// In this example directive '#pragma omp target enter data' has clauses
/// 'device' with the value '0', 'if' with condition 'a' and 'map' with array
/// section 'b[:]'.
///
class OMPTargetEnterDataDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param NumClauses The number of clauses.
///
OMPTargetEnterDataDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned NumClauses)
: OMPExecutableDirective(this, OMPTargetEnterDataDirectiveClass,
OMPD_target_enter_data, StartLoc, EndLoc,
NumClauses, /*NumChildren=*/1) {}
/// Build an empty directive.
///
/// \param NumClauses Number of clauses.
///
explicit OMPTargetEnterDataDirective(unsigned NumClauses)
: OMPExecutableDirective(this, OMPTargetEnterDataDirectiveClass,
OMPD_target_enter_data, SourceLocation(),
SourceLocation(), NumClauses,
/*NumChildren=*/1) {}
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
///
static OMPTargetEnterDataDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt);
/// Creates an empty directive with the place for \a N clauses.
///
/// \param C AST context.
/// \param N The number of clauses.
///
static OMPTargetEnterDataDirective *CreateEmpty(const ASTContext &C,
unsigned N, EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPTargetEnterDataDirectiveClass;
}
};
/// This represents '#pragma omp target exit data' directive.
///
/// \code
/// #pragma omp target exit data device(0) if(a) map(b[:])
/// \endcode
/// In this example directive '#pragma omp target exit data' has clauses
/// 'device' with the value '0', 'if' with condition 'a' and 'map' with array
/// section 'b[:]'.
///
class OMPTargetExitDataDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param NumClauses The number of clauses.
///
OMPTargetExitDataDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned NumClauses)
: OMPExecutableDirective(this, OMPTargetExitDataDirectiveClass,
OMPD_target_exit_data, StartLoc, EndLoc,
NumClauses, /*NumChildren=*/1) {}
/// Build an empty directive.
///
/// \param NumClauses Number of clauses.
///
explicit OMPTargetExitDataDirective(unsigned NumClauses)
: OMPExecutableDirective(this, OMPTargetExitDataDirectiveClass,
OMPD_target_exit_data, SourceLocation(),
SourceLocation(), NumClauses,
/*NumChildren=*/1) {}
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
///
static OMPTargetExitDataDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt);
/// Creates an empty directive with the place for \a N clauses.
///
/// \param C AST context.
/// \param N The number of clauses.
///
static OMPTargetExitDataDirective *CreateEmpty(const ASTContext &C,
unsigned N, EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPTargetExitDataDirectiveClass;
}
};
/// This represents '#pragma omp target parallel' directive.
///
/// \code
/// #pragma omp target parallel if(a)
/// \endcode
/// In this example directive '#pragma omp target parallel' has clause 'if' with
/// condition 'a'.
///
class OMPTargetParallelDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param NumClauses Number of clauses.
///
OMPTargetParallelDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned NumClauses)
: OMPExecutableDirective(this, OMPTargetParallelDirectiveClass,
OMPD_target_parallel, StartLoc, EndLoc,
NumClauses, /*NumChildren=*/1) {}
/// Build an empty directive.
///
/// \param NumClauses Number of clauses.
///
explicit OMPTargetParallelDirective(unsigned NumClauses)
: OMPExecutableDirective(this, OMPTargetParallelDirectiveClass,
OMPD_target_parallel, SourceLocation(),
SourceLocation(), NumClauses,
/*NumChildren=*/1) {}
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
///
static OMPTargetParallelDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt);
/// Creates an empty directive with the place for \a NumClauses
/// clauses.
///
/// \param C AST context.
/// \param NumClauses Number of clauses.
///
static OMPTargetParallelDirective *
CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPTargetParallelDirectiveClass;
}
};
/// This represents '#pragma omp target parallel for' directive.
///
/// \code
/// #pragma omp target parallel for private(a,b) reduction(+:c,d)
/// \endcode
/// In this example directive '#pragma omp target parallel for' has clauses
/// 'private' with the variables 'a' and 'b' and 'reduction' with operator '+'
/// and variables 'c' and 'd'.
///
class OMPTargetParallelForDirective : public OMPLoopDirective {
friend class ASTStmtReader;
/// true if current region has inner cancel directive.
bool HasCancel;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
OMPTargetParallelForDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, unsigned NumClauses)
: OMPLoopDirective(this, OMPTargetParallelForDirectiveClass,
OMPD_target_parallel_for, StartLoc, EndLoc,
CollapsedNum, NumClauses),
HasCancel(false) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
explicit OMPTargetParallelForDirective(unsigned CollapsedNum,
unsigned NumClauses)
: OMPLoopDirective(this, OMPTargetParallelForDirectiveClass,
OMPD_target_parallel_for, SourceLocation(),
SourceLocation(), CollapsedNum, NumClauses),
HasCancel(false) {}
/// Set cancel state.
void setHasCancel(bool Has) { HasCancel = Has; }
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param CollapsedNum Number of collapsed loops.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param Exprs Helper expressions for CodeGen.
/// \param HasCancel true if current directive has inner cancel directive.
///
static OMPTargetParallelForDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses,
Stmt *AssociatedStmt, const HelperExprs &Exprs, bool HasCancel);
/// Creates an empty directive with the place
/// for \a NumClauses clauses.
///
/// \param C AST context.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
static OMPTargetParallelForDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses,
unsigned CollapsedNum,
EmptyShell);
/// Return true if current directive has inner cancel directive.
bool hasCancel() const { return HasCancel; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPTargetParallelForDirectiveClass;
}
};
/// This represents '#pragma omp teams' directive.
///
/// \code
/// #pragma omp teams if(a)
/// \endcode
/// In this example directive '#pragma omp teams' has clause 'if' with
/// condition 'a'.
///
class OMPTeamsDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param NumClauses Number of clauses.
///
OMPTeamsDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned NumClauses)
: OMPExecutableDirective(this, OMPTeamsDirectiveClass, OMPD_teams,
StartLoc, EndLoc, NumClauses, 1) {}
/// Build an empty directive.
///
/// \param NumClauses Number of clauses.
///
explicit OMPTeamsDirective(unsigned NumClauses)
: OMPExecutableDirective(this, OMPTeamsDirectiveClass, OMPD_teams,
SourceLocation(), SourceLocation(), NumClauses,
1) {}
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
///
static OMPTeamsDirective *Create(const ASTContext &C, SourceLocation StartLoc,
SourceLocation EndLoc,
ArrayRef<OMPClause *> Clauses,
Stmt *AssociatedStmt);
/// Creates an empty directive with the place for \a NumClauses
/// clauses.
///
/// \param C AST context.
/// \param NumClauses Number of clauses.
///
static OMPTeamsDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses, EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPTeamsDirectiveClass;
}
};
/// This represents '#pragma omp cancellation point' directive.
///
/// \code
/// #pragma omp cancellation point for
/// \endcode
///
/// In this example a cancellation point is created for innermost 'for' region.
class OMPCancellationPointDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
OpenMPDirectiveKind CancelRegion;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
///
OMPCancellationPointDirective(SourceLocation StartLoc, SourceLocation EndLoc)
: OMPExecutableDirective(this, OMPCancellationPointDirectiveClass,
OMPD_cancellation_point, StartLoc, EndLoc, 0, 0),
CancelRegion(OMPD_unknown) {}
/// Build an empty directive.
///
explicit OMPCancellationPointDirective()
: OMPExecutableDirective(this, OMPCancellationPointDirectiveClass,
OMPD_cancellation_point, SourceLocation(),
SourceLocation(), 0, 0),
CancelRegion(OMPD_unknown) {}
/// Set cancel region for current cancellation point.
/// \param CR Cancellation region.
void setCancelRegion(OpenMPDirectiveKind CR) { CancelRegion = CR; }
public:
/// Creates directive.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
///
static OMPCancellationPointDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
OpenMPDirectiveKind CancelRegion);
/// Creates an empty directive.
///
/// \param C AST context.
///
static OMPCancellationPointDirective *CreateEmpty(const ASTContext &C,
EmptyShell);
/// Get cancellation region for the current cancellation point.
OpenMPDirectiveKind getCancelRegion() const { return CancelRegion; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPCancellationPointDirectiveClass;
}
};
/// This represents '#pragma omp cancel' directive.
///
/// \code
/// #pragma omp cancel for
/// \endcode
///
/// In this example a cancel is created for innermost 'for' region.
class OMPCancelDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
OpenMPDirectiveKind CancelRegion;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param NumClauses Number of clauses.
///
OMPCancelDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned NumClauses)
: OMPExecutableDirective(this, OMPCancelDirectiveClass, OMPD_cancel,
StartLoc, EndLoc, NumClauses, 0),
CancelRegion(OMPD_unknown) {}
/// Build an empty directive.
///
/// \param NumClauses Number of clauses.
explicit OMPCancelDirective(unsigned NumClauses)
: OMPExecutableDirective(this, OMPCancelDirectiveClass, OMPD_cancel,
SourceLocation(), SourceLocation(), NumClauses,
0),
CancelRegion(OMPD_unknown) {}
/// Set cancel region for current cancellation point.
/// \param CR Cancellation region.
void setCancelRegion(OpenMPDirectiveKind CR) { CancelRegion = CR; }
public:
/// Creates directive.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param Clauses List of clauses.
///
static OMPCancelDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
ArrayRef<OMPClause *> Clauses, OpenMPDirectiveKind CancelRegion);
/// Creates an empty directive.
///
/// \param C AST context.
/// \param NumClauses Number of clauses.
///
static OMPCancelDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses, EmptyShell);
/// Get cancellation region for the current cancellation point.
OpenMPDirectiveKind getCancelRegion() const { return CancelRegion; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPCancelDirectiveClass;
}
};
/// This represents '#pragma omp taskloop' directive.
///
/// \code
/// #pragma omp taskloop private(a,b) grainsize(val) num_tasks(num)
/// \endcode
/// In this example directive '#pragma omp taskloop' has clauses 'private'
/// with the variables 'a' and 'b', 'grainsize' with expression 'val' and
/// 'num_tasks' with expression 'num'.
///
class OMPTaskLoopDirective : public OMPLoopDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
OMPTaskLoopDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, unsigned NumClauses)
: OMPLoopDirective(this, OMPTaskLoopDirectiveClass, OMPD_taskloop,
StartLoc, EndLoc, CollapsedNum, NumClauses) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
explicit OMPTaskLoopDirective(unsigned CollapsedNum, unsigned NumClauses)
: OMPLoopDirective(this, OMPTaskLoopDirectiveClass, OMPD_taskloop,
SourceLocation(), SourceLocation(), CollapsedNum,
NumClauses) {}
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param CollapsedNum Number of collapsed loops.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param Exprs Helper expressions for CodeGen.
///
static OMPTaskLoopDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses,
Stmt *AssociatedStmt, const HelperExprs &Exprs);
/// Creates an empty directive with the place
/// for \a NumClauses clauses.
///
/// \param C AST context.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
static OMPTaskLoopDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses,
unsigned CollapsedNum, EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPTaskLoopDirectiveClass;
}
};
/// This represents '#pragma omp taskloop simd' directive.
///
/// \code
/// #pragma omp taskloop simd private(a,b) grainsize(val) num_tasks(num)
/// \endcode
/// In this example directive '#pragma omp taskloop simd' has clauses 'private'
/// with the variables 'a' and 'b', 'grainsize' with expression 'val' and
/// 'num_tasks' with expression 'num'.
///
class OMPTaskLoopSimdDirective : public OMPLoopDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
OMPTaskLoopSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, unsigned NumClauses)
: OMPLoopDirective(this, OMPTaskLoopSimdDirectiveClass,
OMPD_taskloop_simd, StartLoc, EndLoc, CollapsedNum,
NumClauses) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
explicit OMPTaskLoopSimdDirective(unsigned CollapsedNum, unsigned NumClauses)
: OMPLoopDirective(this, OMPTaskLoopSimdDirectiveClass,
OMPD_taskloop_simd, SourceLocation(), SourceLocation(),
CollapsedNum, NumClauses) {}
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param CollapsedNum Number of collapsed loops.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param Exprs Helper expressions for CodeGen.
///
static OMPTaskLoopSimdDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses,
Stmt *AssociatedStmt, const HelperExprs &Exprs);
/// Creates an empty directive with the place
/// for \a NumClauses clauses.
///
/// \param C AST context.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
static OMPTaskLoopSimdDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses,
unsigned CollapsedNum,
EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPTaskLoopSimdDirectiveClass;
}
};
/// This represents '#pragma omp distribute' directive.
///
/// \code
/// #pragma omp distribute private(a,b)
/// \endcode
/// In this example directive '#pragma omp distribute' has clauses 'private'
/// with the variables 'a' and 'b'
///
class OMPDistributeDirective : public OMPLoopDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
OMPDistributeDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, unsigned NumClauses)
: OMPLoopDirective(this, OMPDistributeDirectiveClass, OMPD_distribute,
StartLoc, EndLoc, CollapsedNum, NumClauses)
{}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
explicit OMPDistributeDirective(unsigned CollapsedNum, unsigned NumClauses)
: OMPLoopDirective(this, OMPDistributeDirectiveClass, OMPD_distribute,
SourceLocation(), SourceLocation(), CollapsedNum,
NumClauses)
{}
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param CollapsedNum Number of collapsed loops.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param Exprs Helper expressions for CodeGen.
///
static OMPDistributeDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses,
Stmt *AssociatedStmt, const HelperExprs &Exprs);
/// Creates an empty directive with the place
/// for \a NumClauses clauses.
///
/// \param C AST context.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
static OMPDistributeDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses,
unsigned CollapsedNum, EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPDistributeDirectiveClass;
}
};
/// This represents '#pragma omp target update' directive.
///
/// \code
/// #pragma omp target update to(a) from(b) device(1)
/// \endcode
/// In this example directive '#pragma omp target update' has clause 'to' with
/// argument 'a', clause 'from' with argument 'b' and clause 'device' with
/// argument '1'.
///
class OMPTargetUpdateDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param NumClauses The number of clauses.
///
OMPTargetUpdateDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned NumClauses)
: OMPExecutableDirective(this, OMPTargetUpdateDirectiveClass,
OMPD_target_update, StartLoc, EndLoc, NumClauses,
1) {}
/// Build an empty directive.
///
/// \param NumClauses Number of clauses.
///
explicit OMPTargetUpdateDirective(unsigned NumClauses)
: OMPExecutableDirective(this, OMPTargetUpdateDirectiveClass,
OMPD_target_update, SourceLocation(),
SourceLocation(), NumClauses, 1) {}
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
///
static OMPTargetUpdateDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt);
/// Creates an empty directive with the place for \a NumClauses
/// clauses.
///
/// \param C AST context.
/// \param NumClauses The number of clauses.
///
static OMPTargetUpdateDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses, EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPTargetUpdateDirectiveClass;
}
};
/// This represents '#pragma omp distribute parallel for' composite
/// directive.
///
/// \code
/// #pragma omp distribute parallel for private(a,b)
/// \endcode
/// In this example directive '#pragma omp distribute parallel for' has clause
/// 'private' with the variables 'a' and 'b'
///
class OMPDistributeParallelForDirective : public OMPLoopDirective {
friend class ASTStmtReader;
/// true if the construct has inner cancel directive.
bool HasCancel = false;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
OMPDistributeParallelForDirective(SourceLocation StartLoc,
SourceLocation EndLoc,
unsigned CollapsedNum, unsigned NumClauses)
: OMPLoopDirective(this, OMPDistributeParallelForDirectiveClass,
OMPD_distribute_parallel_for, StartLoc, EndLoc,
CollapsedNum, NumClauses), HasCancel(false) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
explicit OMPDistributeParallelForDirective(unsigned CollapsedNum,
unsigned NumClauses)
: OMPLoopDirective(this, OMPDistributeParallelForDirectiveClass,
OMPD_distribute_parallel_for, SourceLocation(),
SourceLocation(), CollapsedNum, NumClauses),
HasCancel(false) {}
/// Set cancel state.
void setHasCancel(bool Has) { HasCancel = Has; }
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param CollapsedNum Number of collapsed loops.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param Exprs Helper expressions for CodeGen.
/// \param HasCancel true if this directive has inner cancel directive.
///
static OMPDistributeParallelForDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses,
Stmt *AssociatedStmt, const HelperExprs &Exprs, bool HasCancel);
/// Creates an empty directive with the place
/// for \a NumClauses clauses.
///
/// \param C AST context.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
static OMPDistributeParallelForDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses,
unsigned CollapsedNum,
EmptyShell);
/// Return true if current directive has inner cancel directive.
bool hasCancel() const { return HasCancel; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPDistributeParallelForDirectiveClass;
}
};
/// This represents '#pragma omp distribute parallel for simd' composite
/// directive.
///
/// \code
/// #pragma omp distribute parallel for simd private(x)
/// \endcode
/// In this example directive '#pragma omp distribute parallel for simd' has
/// clause 'private' with the variables 'x'
///
class OMPDistributeParallelForSimdDirective final : public OMPLoopDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
OMPDistributeParallelForSimdDirective(SourceLocation StartLoc,
SourceLocation EndLoc,
unsigned CollapsedNum,
unsigned NumClauses)
: OMPLoopDirective(this, OMPDistributeParallelForSimdDirectiveClass,
OMPD_distribute_parallel_for_simd, StartLoc,
EndLoc, CollapsedNum, NumClauses) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
explicit OMPDistributeParallelForSimdDirective(unsigned CollapsedNum,
unsigned NumClauses)
: OMPLoopDirective(this, OMPDistributeParallelForSimdDirectiveClass,
OMPD_distribute_parallel_for_simd,
SourceLocation(), SourceLocation(), CollapsedNum,
NumClauses) {}
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param CollapsedNum Number of collapsed loops.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param Exprs Helper expressions for CodeGen.
///
static OMPDistributeParallelForSimdDirective *Create(
const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses,
Stmt *AssociatedStmt, const HelperExprs &Exprs);
/// Creates an empty directive with the place for \a NumClauses clauses.
///
/// \param C AST context.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
static OMPDistributeParallelForSimdDirective *CreateEmpty(
const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum,
EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPDistributeParallelForSimdDirectiveClass;
}
};
/// This represents '#pragma omp distribute simd' composite directive.
///
/// \code
/// #pragma omp distribute simd private(x)
/// \endcode
/// In this example directive '#pragma omp distribute simd' has clause
/// 'private' with the variables 'x'
///
class OMPDistributeSimdDirective final : public OMPLoopDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
OMPDistributeSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, unsigned NumClauses)
: OMPLoopDirective(this, OMPDistributeSimdDirectiveClass,
OMPD_distribute_simd, StartLoc, EndLoc, CollapsedNum,
NumClauses) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
explicit OMPDistributeSimdDirective(unsigned CollapsedNum,
unsigned NumClauses)
: OMPLoopDirective(this, OMPDistributeSimdDirectiveClass,
OMPD_distribute_simd, SourceLocation(),
SourceLocation(), CollapsedNum, NumClauses) {}
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param CollapsedNum Number of collapsed loops.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param Exprs Helper expressions for CodeGen.
///
static OMPDistributeSimdDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses,
Stmt *AssociatedStmt, const HelperExprs &Exprs);
/// Creates an empty directive with the place for \a NumClauses clauses.
///
/// \param C AST context.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
static OMPDistributeSimdDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses,
unsigned CollapsedNum,
EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPDistributeSimdDirectiveClass;
}
};
/// This represents '#pragma omp target parallel for simd' directive.
///
/// \code
/// #pragma omp target parallel for simd private(a) map(b) safelen(c)
/// \endcode
/// In this example directive '#pragma omp target parallel for simd' has clauses
/// 'private' with the variable 'a', 'map' with the variable 'b' and 'safelen'
/// with the variable 'c'.
///
class OMPTargetParallelForSimdDirective final : public OMPLoopDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
OMPTargetParallelForSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, unsigned NumClauses)
: OMPLoopDirective(this, OMPTargetParallelForSimdDirectiveClass,
OMPD_target_parallel_for_simd, StartLoc, EndLoc,
CollapsedNum, NumClauses) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
explicit OMPTargetParallelForSimdDirective(unsigned CollapsedNum,
unsigned NumClauses)
: OMPLoopDirective(this, OMPTargetParallelForSimdDirectiveClass,
OMPD_target_parallel_for_simd, SourceLocation(),
SourceLocation(), CollapsedNum, NumClauses) {}
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param CollapsedNum Number of collapsed loops.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param Exprs Helper expressions for CodeGen.
///
static OMPTargetParallelForSimdDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses,
Stmt *AssociatedStmt, const HelperExprs &Exprs);
/// Creates an empty directive with the place for \a NumClauses clauses.
///
/// \param C AST context.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
static OMPTargetParallelForSimdDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses,
unsigned CollapsedNum,
EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPTargetParallelForSimdDirectiveClass;
}
};
/// This represents '#pragma omp target simd' directive.
///
/// \code
/// #pragma omp target simd private(a) map(b) safelen(c)
/// \endcode
/// In this example directive '#pragma omp target simd' has clauses 'private'
/// with the variable 'a', 'map' with the variable 'b' and 'safelen' with
/// the variable 'c'.
///
class OMPTargetSimdDirective final : public OMPLoopDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
OMPTargetSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, unsigned NumClauses)
: OMPLoopDirective(this, OMPTargetSimdDirectiveClass,
OMPD_target_simd, StartLoc, EndLoc, CollapsedNum,
NumClauses) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
explicit OMPTargetSimdDirective(unsigned CollapsedNum, unsigned NumClauses)
: OMPLoopDirective(this, OMPTargetSimdDirectiveClass, OMPD_target_simd,
SourceLocation(),SourceLocation(), CollapsedNum,
NumClauses) {}
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param CollapsedNum Number of collapsed loops.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param Exprs Helper expressions for CodeGen.
///
static OMPTargetSimdDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses,
Stmt *AssociatedStmt, const HelperExprs &Exprs);
/// Creates an empty directive with the place for \a NumClauses clauses.
///
/// \param C AST context.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
static OMPTargetSimdDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses,
unsigned CollapsedNum,
EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPTargetSimdDirectiveClass;
}
};
/// This represents '#pragma omp teams distribute' directive.
///
/// \code
/// #pragma omp teams distribute private(a,b)
/// \endcode
/// In this example directive '#pragma omp teams distribute' has clauses
/// 'private' with the variables 'a' and 'b'
///
class OMPTeamsDistributeDirective final : public OMPLoopDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
OMPTeamsDistributeDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, unsigned NumClauses)
: OMPLoopDirective(this, OMPTeamsDistributeDirectiveClass,
OMPD_teams_distribute, StartLoc, EndLoc,
CollapsedNum, NumClauses) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
explicit OMPTeamsDistributeDirective(unsigned CollapsedNum,
unsigned NumClauses)
: OMPLoopDirective(this, OMPTeamsDistributeDirectiveClass,
OMPD_teams_distribute, SourceLocation(),
SourceLocation(), CollapsedNum, NumClauses) {}
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param CollapsedNum Number of collapsed loops.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param Exprs Helper expressions for CodeGen.
///
static OMPTeamsDistributeDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses,
Stmt *AssociatedStmt, const HelperExprs &Exprs);
/// Creates an empty directive with the place for \a NumClauses clauses.
///
/// \param C AST context.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
static OMPTeamsDistributeDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses,
unsigned CollapsedNum,
EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPTeamsDistributeDirectiveClass;
}
};
/// This represents '#pragma omp teams distribute simd'
/// combined directive.
///
/// \code
/// #pragma omp teams distribute simd private(a,b)
/// \endcode
/// In this example directive '#pragma omp teams distribute simd'
/// has clause 'private' with the variables 'a' and 'b'
///
class OMPTeamsDistributeSimdDirective final : public OMPLoopDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
OMPTeamsDistributeSimdDirective(SourceLocation StartLoc,
SourceLocation EndLoc, unsigned CollapsedNum,
unsigned NumClauses)
: OMPLoopDirective(this, OMPTeamsDistributeSimdDirectiveClass,
OMPD_teams_distribute_simd, StartLoc, EndLoc,
CollapsedNum, NumClauses) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
explicit OMPTeamsDistributeSimdDirective(unsigned CollapsedNum,
unsigned NumClauses)
: OMPLoopDirective(this, OMPTeamsDistributeSimdDirectiveClass,
OMPD_teams_distribute_simd, SourceLocation(),
SourceLocation(), CollapsedNum, NumClauses) {}
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param CollapsedNum Number of collapsed loops.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param Exprs Helper expressions for CodeGen.
///
static OMPTeamsDistributeSimdDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses,
Stmt *AssociatedStmt, const HelperExprs &Exprs);
/// Creates an empty directive with the place
/// for \a NumClauses clauses.
///
/// \param C AST context.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
static OMPTeamsDistributeSimdDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses,
unsigned CollapsedNum,
EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPTeamsDistributeSimdDirectiveClass;
}
};
/// This represents '#pragma omp teams distribute parallel for simd' composite
/// directive.
///
/// \code
/// #pragma omp teams distribute parallel for simd private(x)
/// \endcode
/// In this example directive '#pragma omp teams distribute parallel for simd'
/// has clause 'private' with the variables 'x'
///
class OMPTeamsDistributeParallelForSimdDirective final
: public OMPLoopDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
OMPTeamsDistributeParallelForSimdDirective(SourceLocation StartLoc,
SourceLocation EndLoc,
unsigned CollapsedNum,
unsigned NumClauses)
: OMPLoopDirective(this, OMPTeamsDistributeParallelForSimdDirectiveClass,
OMPD_teams_distribute_parallel_for_simd, StartLoc,
EndLoc, CollapsedNum, NumClauses) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
explicit OMPTeamsDistributeParallelForSimdDirective(unsigned CollapsedNum,
unsigned NumClauses)
: OMPLoopDirective(this, OMPTeamsDistributeParallelForSimdDirectiveClass,
OMPD_teams_distribute_parallel_for_simd,
SourceLocation(), SourceLocation(), CollapsedNum,
NumClauses) {}
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param CollapsedNum Number of collapsed loops.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param Exprs Helper expressions for CodeGen.
///
static OMPTeamsDistributeParallelForSimdDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses,
Stmt *AssociatedStmt, const HelperExprs &Exprs);
/// Creates an empty directive with the place for \a NumClauses clauses.
///
/// \param C AST context.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
static OMPTeamsDistributeParallelForSimdDirective *
CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum,
EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPTeamsDistributeParallelForSimdDirectiveClass;
}
};
/// This represents '#pragma omp teams distribute parallel for' composite
/// directive.
///
/// \code
/// #pragma omp teams distribute parallel for private(x)
/// \endcode
/// In this example directive '#pragma omp teams distribute parallel for'
/// has clause 'private' with the variables 'x'
///
class OMPTeamsDistributeParallelForDirective final : public OMPLoopDirective {
friend class ASTStmtReader;
/// true if the construct has inner cancel directive.
bool HasCancel = false;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
OMPTeamsDistributeParallelForDirective(SourceLocation StartLoc,
SourceLocation EndLoc,
unsigned CollapsedNum,
unsigned NumClauses)
: OMPLoopDirective(this, OMPTeamsDistributeParallelForDirectiveClass,
OMPD_teams_distribute_parallel_for, StartLoc, EndLoc,
CollapsedNum, NumClauses), HasCancel(false) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
explicit OMPTeamsDistributeParallelForDirective(unsigned CollapsedNum,
unsigned NumClauses)
: OMPLoopDirective(this, OMPTeamsDistributeParallelForDirectiveClass,
OMPD_teams_distribute_parallel_for, SourceLocation(),
SourceLocation(), CollapsedNum, NumClauses),
HasCancel(false) {}
/// Set cancel state.
void setHasCancel(bool Has) { HasCancel = Has; }
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param CollapsedNum Number of collapsed loops.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param Exprs Helper expressions for CodeGen.
/// \param HasCancel true if this directive has inner cancel directive.
///
static OMPTeamsDistributeParallelForDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses,
Stmt *AssociatedStmt, const HelperExprs &Exprs, bool HasCancel);
/// Creates an empty directive with the place for \a NumClauses clauses.
///
/// \param C AST context.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
static OMPTeamsDistributeParallelForDirective *
CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum,
EmptyShell);
/// Return true if current directive has inner cancel directive.
bool hasCancel() const { return HasCancel; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPTeamsDistributeParallelForDirectiveClass;
}
};
/// This represents '#pragma omp target teams' directive.
///
/// \code
/// #pragma omp target teams if(a>0)
/// \endcode
/// In this example directive '#pragma omp target teams' has clause 'if' with
/// condition 'a>0'.
///
class OMPTargetTeamsDirective final : public OMPExecutableDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param NumClauses Number of clauses.
///
OMPTargetTeamsDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned NumClauses)
: OMPExecutableDirective(this, OMPTargetTeamsDirectiveClass,
OMPD_target_teams, StartLoc, EndLoc, NumClauses,
1) {}
/// Build an empty directive.
///
/// \param NumClauses Number of clauses.
///
explicit OMPTargetTeamsDirective(unsigned NumClauses)
: OMPExecutableDirective(this, OMPTargetTeamsDirectiveClass,
OMPD_target_teams, SourceLocation(),
SourceLocation(), NumClauses, 1) {}
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
///
static OMPTargetTeamsDirective *Create(const ASTContext &C,
SourceLocation StartLoc,
SourceLocation EndLoc,
ArrayRef<OMPClause *> Clauses,
Stmt *AssociatedStmt);
/// Creates an empty directive with the place for \a NumClauses clauses.
///
/// \param C AST context.
/// \param NumClauses Number of clauses.
///
static OMPTargetTeamsDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses, EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPTargetTeamsDirectiveClass;
}
};
/// This represents '#pragma omp target teams distribute' combined directive.
///
/// \code
/// #pragma omp target teams distribute private(x)
/// \endcode
/// In this example directive '#pragma omp target teams distribute' has clause
/// 'private' with the variables 'x'
///
class OMPTargetTeamsDistributeDirective final : public OMPLoopDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
OMPTargetTeamsDistributeDirective(SourceLocation StartLoc,
SourceLocation EndLoc,
unsigned CollapsedNum, unsigned NumClauses)
: OMPLoopDirective(this, OMPTargetTeamsDistributeDirectiveClass,
OMPD_target_teams_distribute, StartLoc, EndLoc,
CollapsedNum, NumClauses) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
explicit OMPTargetTeamsDistributeDirective(unsigned CollapsedNum,
unsigned NumClauses)
: OMPLoopDirective(this, OMPTargetTeamsDistributeDirectiveClass,
OMPD_target_teams_distribute, SourceLocation(),
SourceLocation(), CollapsedNum, NumClauses) {}
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param CollapsedNum Number of collapsed loops.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param Exprs Helper expressions for CodeGen.
///
static OMPTargetTeamsDistributeDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses,
Stmt *AssociatedStmt, const HelperExprs &Exprs);
/// Creates an empty directive with the place for \a NumClauses clauses.
///
/// \param C AST context.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
static OMPTargetTeamsDistributeDirective *
CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum,
EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPTargetTeamsDistributeDirectiveClass;
}
};
/// This represents '#pragma omp target teams distribute parallel for' combined
/// directive.
///
/// \code
/// #pragma omp target teams distribute parallel for private(x)
/// \endcode
/// In this example directive '#pragma omp target teams distribute parallel
/// for' has clause 'private' with the variables 'x'
///
class OMPTargetTeamsDistributeParallelForDirective final
: public OMPLoopDirective {
friend class ASTStmtReader;
/// true if the construct has inner cancel directive.
bool HasCancel = false;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
OMPTargetTeamsDistributeParallelForDirective(SourceLocation StartLoc,
SourceLocation EndLoc,
unsigned CollapsedNum,
unsigned NumClauses)
: OMPLoopDirective(this,
OMPTargetTeamsDistributeParallelForDirectiveClass,
OMPD_target_teams_distribute_parallel_for, StartLoc,
EndLoc, CollapsedNum, NumClauses),
HasCancel(false) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
explicit OMPTargetTeamsDistributeParallelForDirective(unsigned CollapsedNum,
unsigned NumClauses)
: OMPLoopDirective(
this, OMPTargetTeamsDistributeParallelForDirectiveClass,
OMPD_target_teams_distribute_parallel_for, SourceLocation(),
SourceLocation(), CollapsedNum, NumClauses),
HasCancel(false) {}
/// Set cancel state.
void setHasCancel(bool Has) { HasCancel = Has; }
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param CollapsedNum Number of collapsed loops.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param Exprs Helper expressions for CodeGen.
/// \param HasCancel true if this directive has inner cancel directive.
///
static OMPTargetTeamsDistributeParallelForDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses,
Stmt *AssociatedStmt, const HelperExprs &Exprs, bool HasCancel);
/// Creates an empty directive with the place for \a NumClauses clauses.
///
/// \param C AST context.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
static OMPTargetTeamsDistributeParallelForDirective *
CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum,
EmptyShell);
/// Return true if current directive has inner cancel directive.
bool hasCancel() const { return HasCancel; }
static bool classof(const Stmt *T) {
return T->getStmtClass() ==
OMPTargetTeamsDistributeParallelForDirectiveClass;
}
};
/// This represents '#pragma omp target teams distribute parallel for simd'
/// combined directive.
///
/// \code
/// #pragma omp target teams distribute parallel for simd private(x)
/// \endcode
/// In this example directive '#pragma omp target teams distribute parallel
/// for simd' has clause 'private' with the variables 'x'
///
class OMPTargetTeamsDistributeParallelForSimdDirective final
: public OMPLoopDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
OMPTargetTeamsDistributeParallelForSimdDirective(SourceLocation StartLoc,
SourceLocation EndLoc,
unsigned CollapsedNum,
unsigned NumClauses)
: OMPLoopDirective(this,
OMPTargetTeamsDistributeParallelForSimdDirectiveClass,
OMPD_target_teams_distribute_parallel_for_simd,
StartLoc, EndLoc, CollapsedNum, NumClauses) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
explicit OMPTargetTeamsDistributeParallelForSimdDirective(
unsigned CollapsedNum, unsigned NumClauses)
: OMPLoopDirective(
this, OMPTargetTeamsDistributeParallelForSimdDirectiveClass,
OMPD_target_teams_distribute_parallel_for_simd, SourceLocation(),
SourceLocation(), CollapsedNum, NumClauses) {}
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param CollapsedNum Number of collapsed loops.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param Exprs Helper expressions for CodeGen.
///
static OMPTargetTeamsDistributeParallelForSimdDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses,
Stmt *AssociatedStmt, const HelperExprs &Exprs);
/// Creates an empty directive with the place for \a NumClauses clauses.
///
/// \param C AST context.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
static OMPTargetTeamsDistributeParallelForSimdDirective *
CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum,
EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() ==
OMPTargetTeamsDistributeParallelForSimdDirectiveClass;
}
};
/// This represents '#pragma omp target teams distribute simd' combined
/// directive.
///
/// \code
/// #pragma omp target teams distribute simd private(x)
/// \endcode
/// In this example directive '#pragma omp target teams distribute simd'
/// has clause 'private' with the variables 'x'
///
class OMPTargetTeamsDistributeSimdDirective final : public OMPLoopDirective {
friend class ASTStmtReader;
/// Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
OMPTargetTeamsDistributeSimdDirective(SourceLocation StartLoc,
SourceLocation EndLoc,
unsigned CollapsedNum,
unsigned NumClauses)
: OMPLoopDirective(this, OMPTargetTeamsDistributeSimdDirectiveClass,
OMPD_target_teams_distribute_simd, StartLoc, EndLoc,
CollapsedNum, NumClauses) {}
/// Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
explicit OMPTargetTeamsDistributeSimdDirective(unsigned CollapsedNum,
unsigned NumClauses)
: OMPLoopDirective(this, OMPTargetTeamsDistributeSimdDirectiveClass,
OMPD_target_teams_distribute_simd, SourceLocation(),
SourceLocation(), CollapsedNum, NumClauses) {}
public:
/// Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param CollapsedNum Number of collapsed loops.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
/// \param Exprs Helper expressions for CodeGen.
///
static OMPTargetTeamsDistributeSimdDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses,
Stmt *AssociatedStmt, const HelperExprs &Exprs);
/// Creates an empty directive with the place for \a NumClauses clauses.
///
/// \param C AST context.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
static OMPTargetTeamsDistributeSimdDirective *
CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum,
EmptyShell);
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPTargetTeamsDistributeSimdDirectiveClass;
}
};
} // end namespace clang
#endif
|
GB_binop__max_int16.c | //------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_emult.h"
#include "GB_control.h"
#include "GB_ek_slice.h"
#include "GB_dense.h"
#include "GB_atomics.h"
#include "GB_bitmap_assign_methods.h"
#include "GB_binop__include.h"
// C=binop(A,B) is defined by the following types and operators:
// A+B function (eWiseAdd): GB (_AaddB__max_int16)
// A.*B function (eWiseMult): GB (_AemultB_01__max_int16)
// A.*B function (eWiseMult): GB (_AemultB_02__max_int16)
// A.*B function (eWiseMult): GB (_AemultB_03__max_int16)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__max_int16)
// A*D function (colscale): GB (_AxD__max_int16)
// D*A function (rowscale): GB (_DxB__max_int16)
// C+=B function (dense accum): GB (_Cdense_accumB__max_int16)
// C+=b function (dense accum): GB (_Cdense_accumb__max_int16)
// C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__max_int16)
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__max_int16)
// C=scalar+B GB (_bind1st__max_int16)
// C=scalar+B' GB (_bind1st_tran__max_int16)
// C=A+scalar GB (_bind2nd__max_int16)
// C=A'+scalar GB (_bind2nd_tran__max_int16)
// C type: int16_t
// A type: int16_t
// B,b type: int16_t
// BinaryOp: cij = GB_IMAX (aij, bij)
#define GB_ATYPE \
int16_t
#define GB_BTYPE \
int16_t
#define GB_CTYPE \
int16_t
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
1
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
1
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA,A_iso) \
int16_t aij = GBX (Ax, pA, A_iso)
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB,B_iso) \
int16_t bij = GBX (Bx, pB, B_iso)
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
int16_t t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \
cij = GBX (Ax, pA, A_iso)
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \
cij = GBX (Bx, pB, B_iso)
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z,x,y,i,j) \
z = GB_IMAX (x, y) ;
// true if the binop must be flipped
#define GB_BINOP_FLIP \
0
// op is second
#define GB_OP_IS_SECOND \
0
// do the numerical phases of GB_add and GB_emult
#define GB_PHASE_2_OF_2
// hard-coded loops can be vectorized
#define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_MAX || GxB_NO_INT16 || GxB_NO_MAX_INT16)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void GB (_Cdense_ewise3_accum__max_int16)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_ewise3_noaccum__max_int16)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_dense_ewise3_noaccum_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += B, accumulate a sparse matrix into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumB__max_int16)
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
#include "GB_dense_subassign_23_template.c"
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumb__max_int16)
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
// get the scalar b for C += b, of type int16_t
int16_t bwork = (*((int16_t *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_AxD__max_int16)
(
GrB_Matrix C,
const GrB_Matrix A, bool A_is_pattern,
const GrB_Matrix D, bool D_is_pattern,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int16_t *restrict Cx = (int16_t *) C->x ;
#include "GB_AxB_colscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_DxB__max_int16)
(
GrB_Matrix C,
const GrB_Matrix D, bool D_is_pattern,
const GrB_Matrix B, bool B_is_pattern,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int16_t *restrict Cx = (int16_t *) C->x ;
#include "GB_AxB_rowscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseAdd: C = A+B or C<M> = A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__max_int16)
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool Ch_is_Mh,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GB_WERK_DECLARE (M_ek_slicing, int64_t) ;
GB_WERK_DECLARE (A_ek_slicing, int64_t) ;
GB_WERK_DECLARE (B_ek_slicing, int64_t) ;
#include "GB_add_template.c"
GB_FREE_WORK ;
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C = A.*B or C<M> = A.*B
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_01__max_int16)
(
GrB_Matrix C,
const int C_sparsity,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_01_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_02__max_int16)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool flipxy,
const int64_t *restrict Cp_kfirst,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if GB_BINOP_FLIP
// The operator is not commutative, and does not have a flipped
// variant. For example z=atan2(y,x).
if (flipxy)
{
// use fmult(y,x)
#undef GB_FLIPPED
#define GB_FLIPPED 1
#include "GB_emult_02_template.c"
}
else
{
// use fmult(x,y)
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
}
#else
// No need to handle the flip: the operator is either commutative, or
// has been handled by changing z=div(y,x) to z=rdiv(x,y) for example.
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_03__max_int16)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict Cp_kfirst,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_03_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_bitmap__max_int16)
(
GrB_Matrix C,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_bitmap_emult_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
GrB_Info GB (_bind1st__max_int16)
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
const int8_t *restrict Bb,
int64_t bnz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int16_t *Cx = (int16_t *) Cx_output ;
int16_t x = (*((int16_t *) x_input)) ;
int16_t *Bx = (int16_t *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < bnz ; p++)
{
if (!GBB (Bb, p)) continue ;
int16_t bij = GBX (Bx, p, false) ;
Cx [p] = GB_IMAX (x, bij) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__max_int16)
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
const int8_t *restrict Ab,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
int16_t *Cx = (int16_t *) Cx_output ;
int16_t *Ax = (int16_t *) Ax_input ;
int16_t y = (*((int16_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
int16_t aij = GBX (Ax, p, false) ;
Cx [p] = GB_IMAX (aij, y) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
int16_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = GB_IMAX (x, aij) ; \
}
GrB_Info GB (_bind1st_tran__max_int16)
(
GrB_Matrix C,
const GB_void *x_input,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
// GB_unop_transpose.c uses GB_ATYPE, but A is
// the 2nd input to binary operator z=f(x,y).
#undef GB_ATYPE
#define GB_ATYPE \
int16_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int16_t x = (*((const int16_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
int16_t
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
int16_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = GB_IMAX (aij, y) ; \
}
GrB_Info GB (_bind2nd_tran__max_int16)
(
GrB_Matrix C,
const GrB_Matrix A,
const GB_void *y_input,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int16_t y = (*((const int16_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
intruder.c | /* =============================================================================
*
* intruder.c
*
* =============================================================================
*
* Copyright (C) Stanford University, 2006. All Rights Reserved.
* Author: Chi Cao Minh
*
* =============================================================================
*
* For the license of bayes/sort.h and bayes/sort.c, please see the header
* of the files.
*
* ------------------------------------------------------------------------
*
* For the license of kmeans, please see kmeans/LICENSE.kmeans
*
* ------------------------------------------------------------------------
*
* For the license of ssca2, please see ssca2/COPYRIGHT
*
* ------------------------------------------------------------------------
*
* For the license of lib/mt19937ar.c and lib/mt19937ar.h, please see the
* header of the files.
*
* ------------------------------------------------------------------------
*
* For the license of lib/rbtree.h and lib/rbtree.c, please see
* lib/LEGALNOTICE.rbtree and lib/LICENSE.rbtree
*
* ------------------------------------------------------------------------
*
* Unless otherwise noted, the following license applies to STAMP files:
*
* Copyright (c) 2007, Stanford University
* 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 Stanford University 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 STANFORD UNIVERSITY ``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 STANFORD UNIVERSITY 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.
*
* =============================================================================
*/
#include <assert.h>
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
#include "decoder.h"
#include "detector.h"
#include "dictionary.h"
#include "packet.h"
#include "stream.h"
#include "thread.h"
#include "timer.h"
#include "tm.h"
#include "../lib/instrument_roi.h"
enum param_types {
PARAM_ATTACK = (unsigned char)'a',
PARAM_LENGTH = (unsigned char)'l',
PARAM_NUM = (unsigned char)'n',
PARAM_SEED = (unsigned char)'s',
PARAM_THREAD = (unsigned char)'t',
};
enum param_defaults {
PARAM_DEFAULT_ATTACK = 10,
PARAM_DEFAULT_LENGTH = 16,
PARAM_DEFAULT_NUM = 1 << 20,
PARAM_DEFAULT_SEED = 1,
PARAM_DEFAULT_THREAD = 1,
};
long global_params[256];
#if 0
= { /* 256 = ascii limit */
[PARAM_ATTACK] = PARAM_DEFAULT_ATTACK,
[PARAM_LENGTH] = PARAM_DEFAULT_LENGTH,
[PARAM_NUM] = PARAM_DEFAULT_NUM,
[PARAM_SEED] = PARAM_DEFAULT_SEED,
[PARAM_THREAD] = PARAM_DEFAULT_THREAD,
};
#endif
void global_param_init()
{
global_params[PARAM_ATTACK] = PARAM_DEFAULT_ATTACK;
global_params[PARAM_LENGTH] = PARAM_DEFAULT_LENGTH;
global_params[PARAM_NUM] = PARAM_DEFAULT_NUM;
global_params[PARAM_SEED] = PARAM_DEFAULT_SEED;
global_params[PARAM_THREAD] = PARAM_DEFAULT_THREAD;
}
typedef struct arg {
/* input: */
stream_t* streamPtr;
decoder_t* decoderPtr;
/* output: */
vector_t** errorVectors;
} arg_t;
/* =============================================================================
* displayUsage
* =============================================================================
*/
static void
displayUsage (const char* appName)
{
printf("Usage: %s [options]\n", appName);
puts("\nOptions: (defaults)\n");
printf(" a <UINT> Percent [a]ttack (%i)\n", PARAM_DEFAULT_ATTACK);
printf(" l <UINT> Max data [l]ength (%i)\n", PARAM_DEFAULT_LENGTH);
printf(" n <UINT> [n]umber of flows (%i)\n", PARAM_DEFAULT_NUM);
printf(" s <UINT> Random [s]eed (%i)\n", PARAM_DEFAULT_SEED);
printf(" t <UINT> Number of [t]hreads (%i)\n", PARAM_DEFAULT_THREAD);
exit(1);
}
/* =============================================================================
* parseArgs
* =============================================================================
*/
static void
parseArgs (long argc, char* const argv[])
{
long i;
long opt;
opterr = 0;
while ((opt = getopt(argc, argv, "a:l:n:s:t:")) != -1) {
switch (opt) {
case 'a':
case 'l':
case 'n':
case 's':
case 't':
global_params[(unsigned char)opt] = atol(optarg);
break;
case '?':
default:
opterr++;
break;
}
}
for (i = optind; i < argc; i++) {
fprintf(stderr, "Non-option argument: %s\n", argv[i]);
opterr++;
}
if (opterr) {
displayUsage(argv[0]);
}
}
/* =============================================================================
* processPackets
* =============================================================================
*/
void
processPackets (void* argPtr)
{
TM_THREAD_ENTER();
long threadId = thread_getId();
stream_t* streamPtr = ((arg_t*)argPtr)->streamPtr;
decoder_t* decoderPtr = ((arg_t*)argPtr)->decoderPtr;
vector_t** errorVectors = ((arg_t*)argPtr)->errorVectors;
detector_t* detectorPtr = PDETECTOR_ALLOC();
assert(detectorPtr);
PDETECTOR_ADDPREPROCESSOR(detectorPtr, &preprocessor_toLower);
vector_t* errorVectorPtr = errorVectors[threadId];
while (1) {
char* bytes;
TM_BEGIN();
bytes = TMSTREAM_GETPACKET(streamPtr);
TM_END();
if (!bytes) {
break;
}
packet_t* packetPtr = (packet_t*)bytes;
long flowId = packetPtr->flowId;
int_error_t error;
TM_BEGIN();
error = TMDECODER_PROCESS(decoderPtr,
bytes,
(PACKET_HEADER_LENGTH + packetPtr->length));
TM_END();
if (error) {
/*
* Currently, stream_generate() does not create these errors.
*/
assert(0);
bool_t status = PVECTOR_PUSHBACK(errorVectorPtr, (void*)flowId);
assert(status);
}
char* data;
long decodedFlowId;
TM_BEGIN();
data = TMDECODER_GETCOMPLETE(decoderPtr, &decodedFlowId);
TM_END();
if (data) {
int_error_t error = PDETECTOR_PROCESS(detectorPtr, data);
P_FREE(data);
if (error) {
bool_t status = PVECTOR_PUSHBACK(errorVectorPtr,
(void*)decodedFlowId);
assert(status);
}
}
}
PDETECTOR_FREE(detectorPtr);
TM_THREAD_EXIT();
}
/* =============================================================================
* main
* =============================================================================
*/
MAIN(argc, argv)
{
/*
* Initialization
*/
global_param_init();
parseArgs(argc, (char** const)argv);
long numThread = global_params[PARAM_THREAD];
SIM_GET_NUM_CPU(numThread);
TM_STARTUP(numThread);
P_MEMORY_STARTUP(numThread);
thread_startup(numThread);
TIMER_T startTime, stopTime;
long percentAttack = global_params[PARAM_ATTACK];
long maxDataLength = global_params[PARAM_LENGTH];
long numFlow = global_params[PARAM_NUM];
long randomSeed = global_params[PARAM_SEED];
printf("Percent attack = %li\n", percentAttack);
printf("Max data length = %li\n", maxDataLength);
printf("Num flow = %li\n", numFlow);
printf("Random seed = %li\n", randomSeed);
dictionary_t* dictionaryPtr = dictionary_alloc();
assert(dictionaryPtr);
stream_t* streamPtr = stream_alloc(percentAttack);
assert(streamPtr);
long numAttack = stream_generate(streamPtr,
dictionaryPtr,
numFlow,
randomSeed,
maxDataLength);
printf("Num attack = %li\n", numAttack);
decoder_t* decoderPtr = decoder_alloc();
assert(decoderPtr);
vector_t** errorVectors = (vector_t**)SEQ_MALLOC(numThread * sizeof(vector_t*));
assert(errorVectors);
long i;
for (i = 0; i < numThread; i++) {
vector_t* errorVectorPtr = vector_alloc(numFlow);
assert(errorVectorPtr);
errorVectors[i] = errorVectorPtr;
}
arg_t arg;
arg.streamPtr = streamPtr;
arg.decoderPtr = decoderPtr;
arg.errorVectors = errorVectors;
/*
* Run transactions
*/
// NB: Since ASF/PTLSim "REAL" is native execution, and since we are using
// wallclock time, we want to be sure we read time inside the
// simulator, or else we report native cycles spent on the benchmark
// instead of simulator cycles.
//GOTO_SIM();
//TIMER_T startTime;
//TIMER_READ(startTime);
BEGIN_ROI;
#ifdef OTM
#pragma omp parallel
{
processPackets((void*)&arg);
}
#else
thread_start(processPackets, (void*)&arg);
#endif
END_ROI;
//TIMER_T stopTime;
//TIMER_READ(stopTime);
// NB: As above, timer reads must be done inside of the simulated region
// for PTLSim/ASF
//GOTO_REAL();
printf("Elapsed time = %f seconds\n", TIMER_DIFF_SECONDS(startTime, stopTime));
/*
* Check solution
*/
long numFound = 0;
for (i = 0; i < numThread; i++) {
vector_t* errorVectorPtr = errorVectors[i];
long e;
long numError = vector_getSize(errorVectorPtr);
numFound += numError;
for (e = 0; e < numError; e++) {
long flowId = (long)vector_at(errorVectorPtr, e);
bool_t status = stream_isAttack(streamPtr, flowId);
assert(status);
}
}
printf("Num found = %li\n", numFound);
assert(numFound == numAttack);
/*
* Clean up
*/
for (i = 0; i < numThread; i++) {
vector_free(errorVectors[i]);
}
SEQ_FREE(errorVectors);
decoder_free(decoderPtr);
stream_free(streamPtr);
dictionary_free(dictionaryPtr);
TM_SHUTDOWN();
P_MEMORY_SHUTDOWN();
thread_shutdown();
MAIN_RETURN(0);
}
/* =============================================================================
*
* End of intruder.c
*
* =============================================================================
*/
|
elgamal_test.c | #include <ristretto_elgamal.h>
#include <omp.h>
#include <time.h>
#include <stdio.h>
/*
* This executable program loads the key and the map and performs some basic checks.
*/
int main() {
ristretto255_scalar_t sk_1[59];
ristretto255_scalar_t sk_2[59];
ristretto255_point_t pk_1[59];
ristretto255_point_t pk_2[59];
ristretto255_point_t pk[59];
printf("\033[0;32m[INFO]\033[0m Loading the two key pairs and the merged public key...\n");
LoadPrivKey(sk_1, "./priv_1.key");
LoadPrivKey(sk_2, "./priv_2.key");
LoadPubKey(pk_1, "./pub_1.key");
LoadPubKey(pk_2, "./pub_2.key");
LoadPubKey(pk, "./pub.key");
printf("\033[0;32m[INFO]\033[0m The key pairs have been loaded.\n");
fastecexp_state st_pk1[60];
fastecexp_state st_pk2[60];
fastecexp_state st_pk[60];
char filename[59][150];
printf("\033[0;32m[INFO]\033[0m Loading the precomputation tables for PK1...\n");
#pragma omp parallel for
for (int i = 0; i < 59; i++) {
sprintf(filename[i], "/table/pub_1_%d.tab", i);
TableLoad(&st_pk1[i], filename[i]);
}
printf("\033[0;32m[INFO]\033[0m PK1's precomputation tables have been loaded.\n");
TableLoad(&st_pk1[59], "/table/pub_1_59.tab");
printf("\033[0;32m[INFO]\033[0m Loading the precomputation tables for PK2...\n");
#pragma omp parallel for
for (int i = 0; i < 59; i++) {
sprintf(filename[i], "/table/pub_2_%d.tab", i);
TableLoad(&st_pk2[i], filename[i]);
}
printf("\033[0;32m[INFO]\033[0m PK2's precomputation tables have been loaded.\n");
TableLoad(&st_pk2[59], "/table/pub_2_59.tab");
printf("\033[0;32m[INFO]\033[0m Loading the precomputation tables for PK...\n");
#pragma omp parallel for
for (int i = 0; i < 59; i++) {
sprintf(filename[i], "/table/pub_%d.tab", i);
TableLoad(&st_pk[i], filename[i]);
}
printf("\033[0;32m[INFO]\033[0m PK's precomputation tables have been loaded.\n");
TableLoad(&st_pk[59], "/table/pub_59.tab");
int BLOCK = 36;
ristretto255_point_t output[59 * BLOCK];
uint8_t input[1827 * BLOCK];
uint8_t recovered[1827 * BLOCK];
size_t actual_size;
FILE *rand_src = fopen("/dev/urandom", "rb");
fread(input, 1827 * BLOCK - 1, 1, rand_src);
fclose(rand_src);
struct timespec t_start, t_end;
printf("\033[0;32m[INFO]\033[0m Testing encoding + decoding, without encryption or decryption.\n");
ristretto_elgamal_encode(output, input, 1827 * BLOCK - 1, 1827 * BLOCK); // warmup
clock_gettime(CLOCK_REALTIME, &t_start);
for (int i = 0; i < 10; i++)
ristretto_elgamal_encode(output, input, 1827 * BLOCK - 1, 1827 * BLOCK);
clock_gettime(CLOCK_REALTIME, &t_end);
printf("\033[0;32m[INFO]\033[0m Encoding time: %lf.\n",
t_end.tv_sec - t_start.tv_sec + (t_end.tv_nsec - t_start.tv_nsec) / 1000000000.);
memset(recovered, 0, 1827 * BLOCK);
clock_gettime(CLOCK_REALTIME, &t_start);
for (int i = 0; i < 10; i++)
ristretto_elgamal_decode(recovered, output, 59 * BLOCK, &actual_size, 1827 * BLOCK);
clock_gettime(CLOCK_REALTIME, &t_end);
printf("\033[0;32m[INFO]\033[0m Decoding time: %lf.\n",
t_end.tv_sec - t_start.tv_sec + (t_end.tv_nsec - t_start.tv_nsec) / 1000000000.);
for (int i = 0; i < 1827 * BLOCK - 1; i++) {
if (recovered[i] != input[i]) {
printf("\033[0;31m[ERROR]\033[0m recovered[%d] = %d, should be %d, point of problem: %d\n", i, recovered[i],
input[i], (i + 31) / 32);
}
}
printf("\033[0;32m[INFO]\033[0m Recovered actual_size = %ld\n", actual_size);
printf("\033[0;32m[INFO]\033[0m Testing encoding + encryption + decryption + decoding, without rerandomization, focusing on key 1.\n");
ristretto255_point_t ct[60 * BLOCK];
ristretto255_point_t recovered_output[59 * BLOCK];
clock_gettime(CLOCK_REALTIME, &t_start);
for (int pp = 0; pp < 10; pp++) {
#pragma omp parallel for
for (int i = 0; i < BLOCK; i++) {
Encrypt(&ct[i * 60], &output[i * 59], st_pk1, rand_src);
}
}
clock_gettime(CLOCK_REALTIME, &t_end);
printf("\033[0;32m[INFO]\033[0m Encryption time: %lf.\n",
t_end.tv_sec - t_start.tv_sec + (t_end.tv_nsec - t_start.tv_nsec) / 1000000000.);
ristretto255_point_t ct_rand[60 * BLOCK];
clock_gettime(CLOCK_REALTIME, &t_start);
for (int pp = 0; pp < 10; pp++) {
#pragma omp parallel for
for (int i = 0; i < BLOCK; i++) {
Rerand_to_cache(&ct_rand[i * 60], st_pk1, rand_src);
}
}
clock_gettime(CLOCK_REALTIME, &t_end);
printf("\033[0;32m[INFO]\033[0m Rerand, offline time: %lf.\n",
t_end.tv_sec - t_start.tv_sec + (t_end.tv_nsec - t_start.tv_nsec) / 1000000000.);
clock_gettime(CLOCK_REALTIME, &t_start);
for (int pp = 0; pp < 10; pp++) {
#pragma omp parallel for
for (int i = 0; i < BLOCK; i++) {
Rerand_use_cache(&ct[i * 60], &ct_rand[i * 60]);
}
}
clock_gettime(CLOCK_REALTIME, &t_end);
printf("\033[0;32m[INFO]\033[0m Rerand, online time: %lf.\n",
t_end.tv_sec - t_start.tv_sec + (t_end.tv_nsec - t_start.tv_nsec) / 1000000000.);
clock_gettime(CLOCK_REALTIME, &t_start);
for (int pp = 0; pp < 10; pp++) {
#pragma omp parallel for
for (int i = 0; i < BLOCK; i++) {
Decrypt(&recovered_output[i * 59], &ct[i * 60], sk_1);
}
}
clock_gettime(CLOCK_REALTIME, &t_end);
printf("\033[0;32m[INFO]\033[0m Decryption time: %lf.\n",
t_end.tv_sec - t_start.tv_sec + (t_end.tv_nsec - t_start.tv_nsec) / 1000000000.);
memset(recovered, 0, 1827 * BLOCK);
ristretto_elgamal_decode(recovered, recovered_output, 59 * BLOCK, &actual_size, 1827 * BLOCK);
for (int i = 0; i < 1827 * BLOCK - 1; i++) {
if (recovered[i] != input[i]) {
printf("\033[0;31m[ERROR]\033[0m recovered[%d] = %d, should be %d, point of problem: %d.\n", i,
recovered[i], input[i], (i + 31) / 32);
break;
}
}
printf("\033[0;32m[INFO]\033[0m Recovered actual_size = %ld.\n", actual_size);
printf("\033[0;32m[INFO]\033[0m Testing encoding + encryption +rerandomization + decryption + decoding, focusing on key 1.\n");
ristretto255_point_t ct_rerand[60 * BLOCK];
#pragma omp parallel for
for (int i = 0; i < BLOCK; i++) {
Encrypt(&ct[i * 60], &output[i * 59], st_pk1, rand_src);
}
clock_gettime(CLOCK_REALTIME, &t_start);
for (int pp = 0; pp < 10; pp++) {
#pragma omp parallel for
for (int i = 0; i < BLOCK; i++) {
Rerand(&ct_rerand[i * 60], &ct[i * 60], st_pk1, rand_src);
}
}
clock_gettime(CLOCK_REALTIME, &t_end);
printf("\033[0;32m[INFO]\033[0m Rerandomization time: %lf.\n",
t_end.tv_sec - t_start.tv_sec + (t_end.tv_nsec - t_start.tv_nsec) / 1000000000.);
#pragma omp parallel for
for (int i = 0; i < BLOCK; i++) {
Decrypt(&recovered_output[i * 59], &ct_rerand[i * 60], sk_1);
}
memset(recovered, 0, 1827 * BLOCK);
ristretto_elgamal_decode(recovered, recovered_output, 59 * BLOCK, &actual_size, 1827 * BLOCK);
for (int i = 0; i < 1827 * BLOCK - 1; i++) {
if (recovered[i] != input[i]) {
printf("\033[0;31m[ERROR]\033[0m recovered[%d] = %d, should be %d, point of problem: %d.\n", i,
recovered[i], input[i], (i + 31) / 32);
}
}
printf("\033[0;32m[INFO]\033[0m Recovered actual_size = %ld.\n", actual_size);
printf("\033[0;32m[INFO]\033[0m Testing encoding + encryption +rerandomization + decryption + decoding, with distributed decryption.\n");
#pragma omp parallel for
for (int i = 0; i < BLOCK; i++) {
Encrypt(&ct[i * 60], &output[i * 59], st_pk, rand_src);
}
/*
* serialize it!
*/
unsigned char *str = malloc(sizeof(char) * Serialize_Malicious_Size(60 * BLOCK));
clock_gettime(CLOCK_REALTIME, &t_start);
for (int pp = 0; pp < 10; pp++) {
Serialize_Malicious(str, ct, 60 * BLOCK);
}
clock_gettime(CLOCK_REALTIME, &t_end);
printf("\033[0;32m[INFO]\033[0m Serialization -- malicious time: %lf.\n",
t_end.tv_sec - t_start.tv_sec + (t_end.tv_nsec - t_start.tv_nsec) / 1000000000.);
/*
* then recover it back.
*/
clock_gettime(CLOCK_REALTIME, &t_start);
for (int pp = 0; pp < 10; pp++) {
Deserialize_Malicious(ct, str, 60 * BLOCK);
}
clock_gettime(CLOCK_REALTIME, &t_end);
printf("\033[0;32m[INFO]\033[0m Deserialization -- malicious time: %lf.\n",
t_end.tv_sec - t_start.tv_sec + (t_end.tv_nsec - t_start.tv_nsec) / 1000000000.);
#pragma omp parallel for
for (int i = 0; i < BLOCK; i++) {
Rerand(&ct_rerand[i * 60], &ct[i * 60], st_pk, rand_src);
}
/*
* serialize it!
*/
unsigned char *str2 = malloc(sizeof(char) * Serialize_Honest_Size(60 * BLOCK));
clock_gettime(CLOCK_REALTIME, &t_start);
for (int pp = 0; pp < 10; pp++) {
Serialize_Honest(str2, ct_rerand, 60 * BLOCK);
}
clock_gettime(CLOCK_REALTIME, &t_end);
printf("\033[0;32m[INFO]\033[0m Serialization -- honest time: %lf.\n",
t_end.tv_sec - t_start.tv_sec + (t_end.tv_nsec - t_start.tv_nsec) / 1000000000.);
/*
* then recover it back.
*/
clock_gettime(CLOCK_REALTIME, &t_start);
for (int pp = 0; pp < 10; pp++) {
Deserialize_Honest(ct_rerand, str2, 60 * BLOCK);
}
clock_gettime(CLOCK_REALTIME, &t_end);
printf("\033[0;32m[INFO]\033[0m Deserialization -- honest time: %lf.\n",
t_end.tv_sec - t_start.tv_sec + (t_end.tv_nsec - t_start.tv_nsec) / 1000000000.);
#pragma omp parallel for
for (int i = 0; i < BLOCK; i++) {
Rerand(&ct[i * 60], &ct_rerand[i * 60], st_pk, rand_src);
}
#pragma omp parallel for
for (int i = 0; i < BLOCK; i++) {
Decrypt(&recovered_output[i * 59], &ct[i * 60], sk_2);
}
ristretto255_point_t recovered_output2[59 * BLOCK];
ristretto255_point_t distributed_decryption_ct[BLOCK][1];
for (int i = 0; i < BLOCK; i++) {
PartDec1(distributed_decryption_ct[i], &ct[i * 60]);
}
#pragma omp parallel for
for (int i = 0; i < BLOCK; i++) {
PartDec2(&recovered_output2[i * 59], distributed_decryption_ct[i], sk_1);
}
#pragma omp parallel for
for (int i = 0; i < BLOCK; i++) {
PartDec3(&recovered_output2[i * 59], &recovered_output[i * 59]);
}
memset(recovered, 0, 1827 * BLOCK);
ristretto_elgamal_decode(recovered, recovered_output2, 59 * BLOCK, &actual_size, 1827 * BLOCK);
for (int i = 0; i < 1827 * BLOCK - 1; i++) {
if (recovered[i] != input[i]) {
printf("\033[0;32m[INFO]\033[0m recovered[%d] = %d, should be %d, point of problem: %d.\n", i, recovered[i],
input[i], (i + 31) / 32);
break;
}
}
printf("\033[0;32m[INFO]\033[0m Recovered actual_size = %ld.\n", actual_size);
fclose(rand_src);
for (int i = 0; i < 59; i++) {
TableRelease(&st_pk1[i]);
TableRelease(&st_pk2[i]);
TableRelease(&st_pk[i]);
}
free(str);
free(str2);
return 0;
}
|
test.c |
#include <stdio.h>
#include <omp.h>
#include "../utilities/check.h"
#include "../utilities/utilities.h"
#define TRIALS (1)
#define N (1024*3)
#define M (65)
#define INIT() INIT_LOOP(N, {C[i] = 1; D[i] = i; E[i] = -i;})
#define ZERO(X) ZERO_ARRAY(N, X)
double A[M][N], B[M][N], C[N], D[N], E[N];
double S[M];
double p[2];
int main(void) {
check_offloading();
INIT();
int cpuExec = 0;
#pragma omp target map(tofrom: cpuExec)
{
cpuExec = omp_is_initial_device();
}
//
// Test: proc_bind clause
//
#undef NESTED_PARALLEL_FOR_CLAUSES
#define NESTED_PARALLEL_FOR_CLAUSES proc_bind(master)
#include "defines.h"
for (int t = 1; t <= 64; t++) {
int threads[1]; threads[0] = t-1;
NESTED_PARALLEL_FOR(
int tid = omp_get_thread_num(); \
S[tid] = 0; \
for (int i = 0; i < N; i++) { \
A[tid][i] = B[tid][i] = 0; \
},
for (int i = 0; i < N; i++) { \
A[tid][i] += C[i] + D[i]; \
B[tid][i] += D[i] + E[i]; \
},
{
double tmp = 0;
for (int i = 0; i < N; i++) {
tmp += A[tid][i] + B[tid][i];
}
S[tid] += tmp;
},
VERIFY(0, t, S[i], (double) SUMS * (N/2*(N+1))))
}
#undef NESTED_PARALLEL_FOR_CLAUSES
#define NESTED_PARALLEL_FOR_CLAUSES proc_bind(close)
#include "defines.h"
for (int t = 1; t <= 64; t++) {
int threads[1]; threads[0] = t-1;
NESTED_PARALLEL_FOR(
int tid = omp_get_thread_num(); \
S[tid] = 0; \
for (int i = 0; i < N; i++) { \
A[tid][i] = B[tid][i] = 0; \
},
for (int i = 0; i < N; i++) { \
A[tid][i] += C[i] + D[i]; \
B[tid][i] += D[i] + E[i]; \
},
{
double tmp = 0;
for (int i = 0; i < N; i++) {
tmp += A[tid][i] + B[tid][i];
}
S[tid] += tmp;
},
VERIFY(0, t, S[i], (double) SUMS * (N/2*(N+1))))
}
#undef NESTED_PARALLEL_FOR_CLAUSES
#define NESTED_PARALLEL_FOR_CLAUSES proc_bind(spread)
#include "defines.h"
for (int t = 1; t <= 64; t++) {
int threads[1]; threads[0] = t-1;
NESTED_PARALLEL_FOR(
int tid = omp_get_thread_num(); \
S[tid] = 0; \
for (int i = 0; i < N; i++) { \
A[tid][i] = B[tid][i] = 0; \
},
for (int i = 0; i < N; i++) { \
A[tid][i] += C[i] + D[i]; \
B[tid][i] += D[i] + E[i]; \
},
{
double tmp = 0;
for (int i = 0; i < N; i++) {
tmp += A[tid][i] + B[tid][i];
}
S[tid] += tmp;
},
VERIFY(0, t, S[i], (double) SUMS * (N/2*(N+1))))
}
//
// Test: private, shared clauses on omp target parallel for with nested parallel.
//
#undef NESTED_PARALLEL_FOR_CLAUSES
#define NESTED_PARALLEL_FOR_CLAUSES private(p,q) shared(A,B,C,D,E)
#include "defines.h"
for (int t = 1; t <= 64; t++) {
int threads[1]; threads[0] = t;
NESTED_PARALLEL_FOR(
double p = 2; \
double q = 4; \
int tid = omp_get_thread_num(); \
S[tid] = 0; \
for (int i = 0; i < N; i++) { \
A[tid][i] = B[tid][i] = 0; \
},
for (int i = 0; i < N; i++) { \
p = C[i] + D[i]; \
q = D[i] + E[i]; \
A[tid][i] += p; \
B[tid][i] += q; \
}
,
{
double tmp = p + q;
for (int i = 0; i < N; i++) {
tmp += A[tid][i] + B[tid][i];
}
S[tid] += tmp;
},
VERIFY(0, t, S[i], (double) 6 + SUMS * (N/2*(N+1))))
}
//
// Test: firstprivate clause on omp target parallel for with nested parallel.
//
#undef NESTED_PARALLEL_FOR_CLAUSES
#define NESTED_PARALLEL_FOR_CLAUSES firstprivate(p,q)
#include "defines.h"
for (int t = 1; t <= 64; t++) {
int threads[1]; threads[0] = t;
NESTED_PARALLEL_FOR(
double p = -4; \
double q = 4; \
int tid = omp_get_thread_num(); \
S[tid] = 0; \
for (int i = 0; i < N; i++) { \
A[tid][i] = B[tid][i] = 0; \
},
for (int i = 0; i < N; i++) { \
A[tid][i] += C[i] + D[i] + p; \
B[tid][i] += D[i] + E[i] + q; \
if (i == N-1) { \
p += 6; \
q += 9; \
} \
}
,
{
double tmp = p + q;
for (int i = 0; i < N; i++) {
tmp += A[tid][i] + B[tid][i];
}
S[tid] += tmp;
},
VERIFY(0, t, S[i], (double) SUMS * (N/2*(N+1))))
}
//
// Test: lastprivate clause on omp target parallel for with nested parallel.
//
for (int t = 1; t <= 64; t++) {
int threads[1]; threads[0] = t;
TESTD("omp target parallel num_threads(t)", {
double q0[1];
double q1[1];
double q2[1];
double q3[1];
int tid = omp_get_thread_num();
S[tid] = 0;
for (int i = 0; i < N; i++) {
A[tid][i] = B[tid][i] = 0;
}
_Pragma("omp parallel for lastprivate(q0) if(threads[0] > 1) num_threads(threads[0])")
for (int i = 0; i < N; i++) {
q0[0] = C[i] + D[i];
A[tid][i] += q0[0];
}
_Pragma("omp parallel for schedule(auto) lastprivate(q1) if(threads[0] > 1) num_threads(threads[0])")
for (int i = 0; i < N; i++) {
q1[0] = C[i] + D[i];
A[tid][i] += q1[0];
}
_Pragma("omp parallel for schedule(static) lastprivate(q2) if(threads[0] > 1) num_threads(threads[0])")
for (int i = 0; i < N; i++) {
q2[0] = D[i] + E[i];
B[tid][i] += q2[0];
}
_Pragma("omp parallel for schedule(static,9) lastprivate(q3) if(threads[0] > 1) num_threads(threads[0])")
for (int i = 0; i < N; i++) {
q3[0] = D[i] + E[i];
B[tid][i] += q3[0];
}
double tmp = q0[0] + q1[0] + q2[0] + q3[0];
for (int i = 0; i < N; i++) {
tmp += A[tid][i] + B[tid][i];
}
S[tid] += tmp;
}, VERIFY(0, t, S[i], (double) 2 * (N + (N/2*(N+1))) ));
}
//
// Test: private clause on omp target parallel for with nested parallel.
//
#undef NESTED_PARALLEL_FOR_CLAUSES
#define NESTED_PARALLEL_FOR_CLAUSES private(p)
#include "defines.h"
for (int t = 1; t <= 64; t++) {
int threads[1]; threads[0] = t;
NESTED_PARALLEL_FOR(
double p[2]; \
p[0] = 2; p[1] = 4; \
int tid = omp_get_thread_num(); \
S[tid] = 0; \
for (int i = 0; i < N; i++) { \
A[tid][i] = B[tid][i] = 0; \
}
,
for (int i = 0; i < N; i++) { \
p[0] = C[i] + D[i]; \
p[1] = D[i] + E[i]; \
A[tid][i] += p[0]; \
B[tid][i] += p[1]; \
}
,
{
double tmp = p[0] + p[1];
for (int i = 0; i < N; i++) {
tmp += A[tid][i] + B[tid][i];
}
S[tid] += tmp;
},
VERIFY(0, t, S[i], (double) 6 + SUMS * (N/2*(N+1))))
}
//
// Test: firstprivate clause on omp target parallel for with nested parallel.
//
#undef NESTED_PARALLEL_FOR_CLAUSES
#define NESTED_PARALLEL_FOR_CLAUSES firstprivate(p)
#include "defines.h"
for (int t = 1; t <= 64; t++) {
int threads[1]; threads[0] = t;
NESTED_PARALLEL_FOR(
double p[2]; \
p[0] = -4; p[1] = 4; \
int tid = omp_get_thread_num(); \
S[tid] = 0; \
for (int i = 0; i < N; i++) { \
A[tid][i] = B[tid][i] = 0; \
}
,
for (int i = 0; i < N; i++) { \
A[tid][i] += C[i] + D[i] + p[0]; \
B[tid][i] += D[i] + E[i] + p[1]; \
if (i == N-1) { \
p[0] += 6; \
p[1] += 9; \
} \
}
,
{
double tmp = p[0] + p[1];
for (int i = 0; i < N; i++) {
tmp += A[tid][i] + B[tid][i];
}
S[tid] += tmp;
},
VERIFY(0, t, S[i], (double) SUMS * (N/2*(N+1))))
}
//
// Test: collapse clause on omp target parallel for with nested parallel.
//
#undef NESTED_PARALLEL_FOR_CLAUSES
#define NESTED_PARALLEL_FOR_CLAUSES collapse(2)
#include "defines.h"
for (int t = 1; t <= 64; t++) {
int threads[1]; threads[0] = t;
NESTED_PARALLEL_FOR(
int tid = omp_get_thread_num(); \
S[tid] = 0; \
for (int i = 0; i < N; i++) { \
A[tid][i] = B[tid][i] = 0; \
}
,
for (int i = 0; i < 1024; i++) { \
for (int j = 0; j < 3; j++) { \
A[tid][i*3+j] += C[i*3+j] + D[i*3+j]; \
B[tid][i*3+j] += D[i*3+j] + E[i*3+j]; \
} \
}
,
{
double tmp = 0;
for (int i = 0; i < N; i++) {
tmp += A[tid][i] + B[tid][i];
}
S[tid] += tmp;
},
VERIFY(0, t, S[i], (double) SUMS * (N/2*(N+1))))
}
//
// Test: ordered clause on omp target parallel for with nested parallel.
//
#undef NESTED_PARALLEL_FOR_CLAUSES
#define NESTED_PARALLEL_FOR_CLAUSES ordered
#include "defines.h"
for (int t = 1; t <= 64; t += 64) {
int threads[1]; threads[0] = t;
NESTED_PARALLEL_FOR(
int tid = omp_get_thread_num(); \
S[tid] = 0; \
,
for (int i = 0; i < N; i++) { \
_Pragma("omp ordered") \
S[tid] += C[i] + D[i]; \
}
,
{
},
VERIFY(0, t, S[i], (double) SUMS * (N/2*(N+1))))
}
//
// Test: Ensure coalesced scheduling on GPU.
//
if (!cpuExec) {
TESTD("omp target parallel num_threads(32)", {
int tid = omp_get_thread_num();
S[tid] = 0;
for (int i = 0; i < 96; i++) {
A[tid][i] = 0;
}
_Pragma("omp parallel for num_threads(32)")
for (int i = 0; i < 96; i++) {
A[tid][i] += i - omp_get_thread_num();
}
_Pragma("omp parallel for schedule(auto) num_threads(32)")
for (int i = 0; i < 96; i++) {
A[tid][i] += i - omp_get_thread_num();
}
_Pragma("omp parallel for schedule(static,1) num_threads(32)")
for (int i = 0; i < 96; i++) {
A[tid][i] += i - omp_get_thread_num();
}
double tmp = 0;
for (int i = 0; i < 96; i++) {
tmp += A[tid][i];
}
S[tid] = tmp;
}, VERIFY(0, 32, S[i], (double) 3 * (32*32 + 64*32) ));
} else {
DUMP_SUCCESS(1);
}
return 0;
}
|
PSFHandle.h | #pragma once
#include "ps/psf/PSFunc.h"
#include "common/thread_safe_hash_map.h"
#include "param.h"
#include <algorithm>
#include <utility>
#include <mutex>
#include <omp.h>
#include <random>
#include <fstream>
namespace ps {
template <>
class PSHandler<PsfGroup::kParameterServer>
: public PSHandler<PsfGroup::kBaseGroup> {
public:
PSHandler<PsfGroup::kParameterServer>() {
}
PSHandler<PsfGroup::kParameterServer>(
const PSHandler<PsfGroup::kParameterServer> &handle) {
}
void serve(const PSFData<DensePull>::Request &request,
PSFData<DensePull>::Response &response) {
Key k = get<0>(request);
size_t len = get<1>(request);
SArray<float> &pull_vals = get<0>(response);
auto iter = const_store.find(k);
if (iter != const_store.end()) {
auto &value_set_ = *iter->second;
size_t data_size = value_set_.size();
CHECK_EQ(len, data_size) << " size mismatch in DensePull " << k
<< " " << len << " " << data_size;
pull_vals.resize(data_size);
auto read_lock = value_set_.read_guard();
std::copy(value_set_.begin(), value_set_.end(), pull_vals.begin());
} else {
LG << "Key does not exist on PS in DensePull" << k;
}
}
void serve(const PSFData<DensePush>::Request &request,
PSFData<DensePush>::Response &response) {
Key k = get<0>(request);
size_t len = get<1>(request);
SArray<float> vals = get<2>(request);
if (const_store.find(k) == const_store.end()) {
store[k] = std::make_shared<Param<float>>(len, OptType::None,
SArray<float>());
}
auto iter = const_store.find(k);
if (iter != const_store.end()) {
CHECK_EQ(len, iter->second->size())
<< k << " " << len << " " << iter->second->size()
<< " size mismatch in DensePush";
// write, discard const qualifier
auto &value_set_ =
*const_cast<typename tmap::mapped_type &>(iter->second);
auto write_lock = value_set_.write_guard();
#pragma omp parallel for num_threads(4)
for (size_t j = 0; j < value_set_.size(); j++)
value_set_[j] += vals[j];
} else {
LG << "Key does not exist on PS in DensePull" << k;
}
}
void serve(const PSFData<DDPushPull>::Request &request,
PSFData<DDPushPull>::Response &response) {
// one key per request.
// with response result
Key k = get<0>(request);
size_t len = get<1>(request);
SArray<float> vals = get<2>(request);
SArray<float> &pull_vals = get<0>(response);
auto iter = const_store.find(k);
if (iter != const_store.end()) {
auto &value_set_ =
*const_cast<typename tmap::mapped_type &>(iter->second);
size_t data_size = value_set_.size();
CHECK_EQ(len, data_size)
<< " size mismatch in DDPushPull " << len << " " << data_size;
pull_vals.resize(data_size);
auto write_lock = value_set_.write_guard();
#pragma omp parallel for num_threads(4)
for (size_t j = 0; j < data_size; j++) {
value_set_[j] += vals[j];
pull_vals[j] = value_set_[j];
}
} else {
LG << "Key does not exist on PS in DensePull" << k;
}
}
void serve(const PSFData<SparsePull>::Request &request,
PSFData<SparsePull>::Response &response) {
// we use length as the offset, i.e., #length = #vals.
// with response result
Key k = get<0>(request);
SArray<size_t> offset = get<1>(request);
SArray<float> &pull_vals = get<0>(response);
auto iter = const_store.find(k);
if (iter != const_store.end()) {
auto &value_set_ =
*std::dynamic_pointer_cast<Param2D<float>>(iter->second);
size_t width = value_set_.width;
pull_vals.resize(offset.size() * width);
auto read_lock = value_set_.read_guard();
#pragma omp parallel for num_threads(4)
for (size_t j = 0; j < offset.size(); ++j) {
auto value_begin = value_set_.data() + offset[j] * width;
auto value_end = value_begin + width;
auto dst_begin = pull_vals.data() + j * width;
std::copy(value_begin, value_end, dst_begin);
}
} else {
// error, the key does not exist on PS.
LF << "[Error] The pulled key: " << k
<< " does not exist on PS in SparsePull.";
}
}
void serve(const PSFData<SparsePush>::Request &request,
PSFData<SparsePush>::Response &response) {
// we use length as the offset, i.e., #length = #vals.
// no response result
Key k = get<0>(request);
SArray<size_t> offsets = get<1>(request);
SArray<float> vals = get<2>(request);
auto iter = const_store.find(k);
if (iter != const_store.end()) {
auto &value_set_ =
*std::dynamic_pointer_cast<Param2D<float>>(iter->second);
size_t width = value_set_.width;
CHECK_EQ(vals.size(), offsets.size() * width)
<< " in Psf::SparsePush check failed,"
<< " size of vals is " << vals.size() << " size of lens is "
<< offsets.size() << " size of width is " << width;
// write, discard const qualifier
auto write_lock = value_set_.write_guard();
#pragma omp parallel for num_threads(4)
for (size_t j = 0; j < offsets.size(); ++j) {
size_t src_offset = j * width;
size_t dst_offset = offsets[j] * width;
for (size_t k = 0; k < width; ++k) {
value_set_[dst_offset + k] += vals[src_offset + k];
}
}
} else {
// error, the key does not exist on PS.
LF << "[Error] The pushed key: " << k
<< " does not exist on PS in SparsePush.";
}
}
void serve(const PSFData<SDPushPull>::Request &request,
PSFData<SDPushPull>::Response &response) {
Key k = get<0>(request);
SArray<size_t> offsets = get<1>(request);
SArray<float> vals = get<2>(request);
size_t len = get<3>(request);
SArray<float> &pull_vals = get<0>(response);
auto iter = const_store.find(k);
if (iter != const_store.end()) {
auto &value_set_ =
*std::dynamic_pointer_cast<Param2D<float>>(iter->second);
size_t width = value_set_.width;
CHECK_EQ(len, value_set_.size())
<< " size mismatch in SDPushPull " << k << " " << len << " "
<< value_set_.size();
// sparsepush phase
if (vals.size() > 0) {
CHECK_EQ(vals.size(), offsets.size() * width)
<< " in Psf::SDPushPull check failed,"
<< " size of vals is " << vals.size() << " size of lens is "
<< offsets.size() << " size of width is " << width;
// write, discard const qualifier
auto write_lock = value_set_.write_guard();
#pragma omp parallel for num_threads(4)
for (size_t j = 0; j < offsets.size(); ++j) {
size_t src_offset = j * width;
size_t dst_offset = offsets[j] * width;
for (size_t k = 0; k < width; ++k) {
value_set_[dst_offset + k] += vals[src_offset + k];
}
}
}
// densepull phase
pull_vals.resize(value_set_.size());
auto read_lock = value_set_.read_guard();
std::copy(value_set_.begin(), value_set_.end(), pull_vals.begin());
} else {
// error, the key does not exist on PS.
LF << "[Error] The pushed key: " << k
<< " does not exist on PS in SDPushPull.";
}
}
void serve(const PSFData<SSPushPull>::Request &request,
PSFData<SSPushPull>::Response &response) {
Key k = get<0>(request);
SArray<size_t> push_offsets = get<1>(request);
SArray<float> vals = get<2>(request);
SArray<size_t> pull_offsets = get<3>(request);
SArray<float> &pull_vals = get<0>(response);
auto iter = const_store.find(k);
if (iter != const_store.end()) {
auto &value_set_ =
*std::dynamic_pointer_cast<Param2D<float>>(iter->second);
size_t width = value_set_.width;
// sparsepush phase
if (vals.size() > 0) {
CHECK_EQ(vals.size(), push_offsets.size() * width)
<< " in Psf::SSPushPull check failed,"
<< " size of vals is " << vals.size() << " size of lens is "
<< push_offsets.size() << " size of width is " << width;
// write, discard const qualifier
auto write_lock = value_set_.write_guard();
#pragma omp parallel for num_threads(4)
for (size_t j = 0; j < push_offsets.size(); ++j) {
size_t src_offset = j * width;
size_t dst_offset = push_offsets[j] * width;
for (size_t k = 0; k < width; ++k) {
value_set_[dst_offset + k] += vals[src_offset + k];
}
}
}
// sparsepull phase
if (pull_offsets.size() > 0) {
pull_vals.resize(pull_offsets.size() * width);
auto read_lock = value_set_.read_guard();
#pragma omp parallel for num_threads(4)
for (size_t j = 0; j < pull_offsets.size(); ++j) {
auto val_begin =
value_set_.begin() + pull_offsets[j] * width;
auto val_end = val_begin + width;
auto dst_begin = pull_vals.begin() + j * width;
std::copy(val_begin, val_end, dst_begin);
}
}
} else {
// error, the key does not exist on PS.
LF << "[Error] The pushed key: " << k
<< " does not exist on PS in SparsePush.";
}
}
void serve(const PSFData<kSyncEmbedding>::Request &request,
PSFData<kSyncEmbedding>::Response &response);
void serve(const PSFData<kPushEmbedding>::Request &request,
PSFData<kPushEmbedding>::Response &response);
void serve(const PSFData<kPushSyncEmbedding>::Request &request,
PSFData<kPushSyncEmbedding>::Response &response);
void serve(const PSFData<ParamInit>::Request &request,
PSFData<ParamInit>::Response &response) {
// one key per request.
// no response result
Key k = get<0>(request);
ParamType param_type = (ParamType)get<1>(request);
size_t len = get<2>(request);
size_t width = get<3>(request);
InitType init_type = (InitType)get<4>(request);
double init_a = get<5>(request);
double init_b = get<6>(request);
unsigned long long seed = get<7>(request);
OptType otype = (OptType)get<8>(request);
SArray<float> lrs = get<9>(request);
if (!try_init_with_no_conflict(k))
return;
Param<float> *newParam = nullptr;
switch (param_type) {
case kParam:
newParam = new Param<float>(len, otype, lrs);
break;
case kParam2D:
newParam = new Param2D<float>(len, width, otype, lrs);
break;
case kCacheTable:
newParam = new CacheTable<float>(len, width, otype, lrs);
}
auto iter = store.find(k);
iter->second = tmap::mapped_type(newParam);
CHECK_EQ(len * width, iter->second->size())
<< k << " " << len << " " << width << " " << iter->second->size()
<< " size mismatch in UniformInit";
// write, discard const qualifier
auto &value_set_ =
*const_cast<typename tmap::mapped_type &>(iter->second);
auto write_lock = value_set_.write_guard();
size_t n_threads = (value_set_.size() >> 25) + 1;
if (n_threads > 16)
n_threads = 16;
if (init_type == InitType::Constant) {
float filled_value = static_cast<float>(init_a);
// #pragma omp parallel for num_threads(4)
for (size_t j = 0; j < value_set_.size(); j++)
value_set_[j] = filled_value;
} else if (init_type == InitType::Uniform) {
std::uniform_real_distribution<float> uniform_dist(init_a, init_b);
#pragma omp parallel num_threads(n_threads)
{
size_t rank = omp_get_thread_num();
size_t num_threads = omp_get_num_threads();
std::default_random_engine generator(seed + rank);
size_t length = value_set_.size() / num_threads;
size_t start = rank * length;
size_t ending = start + length;
if (rank == num_threads - 1)
ending = value_set_.size();
for (size_t j = start; j < ending; ++j) {
value_set_[j] = uniform_dist(generator);
}
}
} else if (init_type == InitType::Normal) {
std::normal_distribution<float> normal_dist(init_a, init_b);
#pragma omp parallel num_threads(n_threads)
{
size_t rank = omp_get_thread_num();
size_t num_threads = omp_get_num_threads();
std::default_random_engine generator(seed + rank);
size_t length = value_set_.size() / num_threads;
size_t start = rank * length;
size_t ending = start + length;
if (rank == num_threads - 1)
ending = value_set_.size();
for (size_t j = start; j < ending; ++j) {
value_set_[j] = normal_dist(generator);
}
}
} else if (init_type == InitType::TruncatedNormal) {
std::normal_distribution<float> truncated_normal_dist(init_a,
init_b);
float upper_limit = init_a + 2 * init_b;
float lower_limit = init_a - 2 * init_b;
#pragma omp parallel num_threads(n_threads)
{
size_t rank = omp_get_thread_num();
size_t num_threads = omp_get_num_threads();
std::default_random_engine generator(seed + rank);
size_t length = value_set_.size() / num_threads;
size_t start = rank * length;
size_t ending = start + length;
if (rank == num_threads - 1)
ending = value_set_.size();
for (size_t j = start; j < ending; ++j) {
float temp = truncated_normal_dist(generator);
while (temp > upper_limit || temp < lower_limit)
temp = truncated_normal_dist(generator);
value_set_[j] = temp;
}
}
}
}
void serve(const PSFData<ParamClear>::Request &request,
PSFData<ParamClear>::Response &response) {
Key k = get<0>(request);
auto iter = store.find(k);
if (iter != store.end()) {
store.erase(iter);
} else {
// error, the key does not exist on PS.
LF << "[Error] The pushed key: " << k
<< " does not exist on PS in ParamClear.";
}
}
void serve(const PSFData<ParamSave>::Request &request,
PSFData<ParamSave>::Response &response) {
Key k = get<0>(request);
SArray<char> address = get<1>(request);
auto iter = store.find(k);
if (iter != store.end()) {
auto &value_set_ = *iter->second;
auto read_lock = value_set_.read_guard();
std::ofstream fout(
std::string(address.data(), address.size()).c_str(),
std::ios::binary);
fout.write((char *)value_set_.data(),
value_set_.size() * sizeof(float));
} else {
// error, the key does not exist on PS.
LF << "[Error] The pushed key: " << k
<< " does not exist on PS in ParamSave.";
}
}
void serve(const PSFData<ParamLoad>::Request &request,
PSFData<ParamLoad>::Response &response) {
Key k = get<0>(request);
SArray<char> address = get<1>(request);
auto iter = store.find(k);
if (iter != store.end()) {
auto &value_set_ = *iter->second;
auto write_lock = value_set_.write_guard();
std::ifstream fin(
std::string(address.data(), address.size()).c_str(),
std::ios::binary);
fin.read((char *)value_set_.data(),
value_set_.size() * sizeof(float));
} else {
// error, the key does not exist on PS.
LF << "[Error] The pushed key: " << k
<< " does not exist on PS in ParamLoad.";
}
}
private:
bool try_init_with_no_conflict(Key key) {
static std::mutex init_mtx;
std::lock_guard<std::mutex> lock(init_mtx);
if (store.find(key) != store.end())
return false;
else {
store[key] = tmap::mapped_type();
return true;
}
}
typedef threadsafe_unordered_map<Key, std::shared_ptr<Param<float>>> tmap;
tmap store;
const tmap &const_store =
store; // const reference to force compiler to use read lock
};
} // namespace ps
|
GB_unaryop__lnot_uint8_int32.c | //------------------------------------------------------------------------------
// GB_unaryop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_iterator.h"
#include "GB_unaryop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop__lnot_uint8_int32
// op(A') function: GB_tran__lnot_uint8_int32
// C type: uint8_t
// A type: int32_t
// cast: uint8_t cij = (uint8_t) aij
// unaryop: cij = !(aij != 0)
#define GB_ATYPE \
int32_t
#define GB_CTYPE \
uint8_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
int32_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = !(x != 0) ;
// casting
#define GB_CASTING(z, x) \
uint8_t z = (uint8_t) x ;
// cij = op (cast (aij))
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GB_GETA (aij, Ax, pA) ; \
/* Cx [pC] = op (cast (aij)) */ \
GB_CASTING (x, aij) ; \
GB_OP (GB_CX (pC), x) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_LNOT || GxB_NO_UINT8 || GxB_NO_INT32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__lnot_uint8_int32
(
uint8_t *restrict Cx,
const int32_t *restrict Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (int64_t p = 0 ; p < anz ; p++)
{
GB_CAST_OP (p, p) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_tran__lnot_uint8_int32
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *restrict *Rowcounts,
GBI_single_iterator Iter,
const int64_t *restrict A_slice,
int naslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#define GB_PHASE_2_OF_2
#include "GB_unaryop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
GB_unop__identity_fc64_int64.c | //------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_atomics.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB (_unop_apply__identity_fc64_int64)
// op(A') function: GB (_unop_tran__identity_fc64_int64)
// C type: GxB_FC64_t
// A type: int64_t
// cast: GxB_FC64_t cij = GxB_CMPLX ((double) (aij), 0)
// unaryop: cij = aij
#define GB_ATYPE \
int64_t
#define GB_CTYPE \
GxB_FC64_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
int64_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = x ;
// casting
#define GB_CAST(z, aij) \
GxB_FC64_t z = GxB_CMPLX ((double) (aij), 0) ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
int64_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
GxB_FC64_t z = GxB_CMPLX ((double) (aij), 0) ; \
Cx [pC] = z ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_IDENTITY || GxB_NO_FC64 || GxB_NO_INT64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__identity_fc64_int64)
(
GxB_FC64_t *Cx, // Cx and Ax may be aliased
const int64_t *Ax,
const int8_t *restrict Ab, // A->b if A is bitmap
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
if (Ab == NULL)
{
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
int64_t aij = Ax [p] ;
GxB_FC64_t z = GxB_CMPLX ((double) (aij), 0) ;
Cx [p] = z ;
}
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
int64_t aij = Ax [p] ;
GxB_FC64_t z = GxB_CMPLX ((double) (aij), 0) ;
Cx [p] = z ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__identity_fc64_int64)
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
Example_target_task_reduction.1.c | /*
* @@name: target_task_reduction.1.c
* @@type: C
* @@compilable: yes
* @@linkable: yes
* @@expect: success
* @@version: omp_5.0
*/
#include <stdio.h>
#pragma omp declare target to(device_compute)
void device_compute(int *);
void host_compute(int *);
int main()
{
int sum = 0;
#pragma omp parallel master
#pragma omp taskgroup task_reduction(+:sum)
{
#pragma omp target in_reduction(+:sum) nowait
device_compute(&sum);
#pragma omp task in_reduction(+:sum)
host_compute(&sum);
}
printf( "sum = %d\n", sum);
//OUTPUT: sum = 2
return 0;
}
void device_compute(int *sum){ *sum = 1; }
void host_compute(int *sum){ *sum = 1; }
|
GB_binop__bclr_uint64.c | //------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_emult.h"
#include "GB_control.h"
#include "GB_ek_slice.h"
#include "GB_dense.h"
#include "GB_atomics.h"
#include "GB_bitmap_assign_methods.h"
#include "GB_binop__include.h"
// C=binop(A,B) is defined by the following types and operators:
// A+B function (eWiseAdd): GB (_AaddB__bclr_uint64)
// A.*B function (eWiseMult): GB (_AemultB)
// A.*B function (eWiseMult): GB (_AemultB_02__bclr_uint64)
// A.*B function (eWiseMult): GB (_AemultB_03__bclr_uint64)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__bclr_uint64)
// A*D function (colscale): GB ((none))
// D*A function (rowscale): GB ((node))
// C+=B function (dense accum): GB (_Cdense_accumB__bclr_uint64)
// C+=b function (dense accum): GB (_Cdense_accumb__bclr_uint64)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__bclr_uint64)
// C=scalar+B GB (_bind1st__bclr_uint64)
// C=scalar+B' GB (_bind1st_tran__bclr_uint64)
// C=A+scalar GB (_bind2nd__bclr_uint64)
// C=A'+scalar GB (_bind2nd_tran__bclr_uint64)
// C type: uint64_t
// A type: uint64_t
// B,b type: uint64_t
// BinaryOp: cij = GB_BITCLR (aij, bij, uint64_t, 64)
#define GB_ATYPE \
uint64_t
#define GB_BTYPE \
uint64_t
#define GB_CTYPE \
uint64_t
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
1
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
1
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
uint64_t aij = Ax [pA]
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB) \
uint64_t bij = Bx [pB]
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
uint64_t t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA) \
cij = Ax [pA]
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB) \
cij = Bx [pB]
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z, x, y, i, j) \
z = GB_BITCLR (x, y, uint64_t, 64) ;
// true if the binop must be flipped
#define GB_BINOP_FLIP \
1
// op is second
#define GB_OP_IS_SECOND \
0
// do the numerical phases of GB_add and GB_emult
#define GB_PHASE_2_OF_2
// hard-coded loops can be vectorized
#define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_BCLR || GxB_NO_UINT64 || GxB_NO_BCLR_UINT64)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
#if 0
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
#endif
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_ewise3_noaccum__bclr_uint64)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_dense_ewise3_noaccum_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += B, accumulate a sparse matrix into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumB__bclr_uint64)
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
#include "GB_dense_subassign_23_template.c"
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumb__bclr_uint64)
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
// get the scalar b for C += b, of type uint64_t
uint64_t bwork = (*((uint64_t *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A, bool A_is_pattern,
const GrB_Matrix D, bool D_is_pattern,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint64_t *restrict Cx = (uint64_t *) C->x ;
#include "GB_AxB_colscale_meta.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((node))
(
GrB_Matrix C,
const GrB_Matrix D, bool D_is_pattern,
const GrB_Matrix B, bool B_is_pattern,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint64_t *restrict Cx = (uint64_t *) C->x ;
#include "GB_AxB_rowscale_meta.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// eWiseAdd: C = A+B or C<M> = A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__bclr_uint64)
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool Ch_is_Mh,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GB_WERK_DECLARE (M_ek_slicing, int64_t) ;
GB_WERK_DECLARE (A_ek_slicing, int64_t) ;
GB_WERK_DECLARE (B_ek_slicing, int64_t) ;
#include "GB_add_template.c"
GB_FREE_WORK ;
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C = A.*B or C<M> = A.*B
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_01__bclr_uint64)
(
GrB_Matrix C,
const int C_sparsity,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_01_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_02__bclr_uint64)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool flipxy,
const int64_t *restrict Cp_kfirst,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if GB_BINOP_FLIP
// The operator is not commutative, and does not have a flipped
// variant. For example z=atan2(y,x).
if (flipxy)
{
// use fmult(y,x)
#undef GB_FLIPPED
#define GB_FLIPPED 1
#include "GB_emult_02_template.c"
}
else
{
// use fmult(x,y)
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
}
#else
// No need to handle the flip: the operator is either commutative, or
// has been handled by changing z=div(y,x) to z=rdiv(x,y) for example.
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_03__bclr_uint64)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict Cp_kfirst,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_03_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_bitmap__bclr_uint64)
(
GrB_Matrix C,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_bitmap_emult_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
GrB_Info GB (_bind1st__bclr_uint64)
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
const int8_t *restrict Bb,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint64_t *Cx = (uint64_t *) Cx_output ;
uint64_t x = (*((uint64_t *) x_input)) ;
uint64_t *Bx = (uint64_t *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Bb, p)) continue ;
uint64_t bij = Bx [p] ;
Cx [p] = GB_BITCLR (x, bij, uint64_t, 64) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__bclr_uint64)
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
const int8_t *restrict Ab,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
uint64_t *Cx = (uint64_t *) Cx_output ;
uint64_t *Ax = (uint64_t *) Ax_input ;
uint64_t y = (*((uint64_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
uint64_t aij = Ax [p] ;
Cx [p] = GB_BITCLR (aij, y, uint64_t, 64) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
uint64_t aij = Ax [pA] ; \
Cx [pC] = GB_BITCLR (x, aij, uint64_t, 64) ; \
}
GrB_Info GB (_bind1st_tran__bclr_uint64)
(
GrB_Matrix C,
const GB_void *x_input,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
// GB_unop_transpose.c uses GB_ATYPE, but A is
// the 2nd input to binary operator z=f(x,y).
#undef GB_ATYPE
#define GB_ATYPE \
uint64_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint64_t x = (*((const uint64_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
uint64_t
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
uint64_t aij = Ax [pA] ; \
Cx [pC] = GB_BITCLR (aij, y, uint64_t, 64) ; \
}
GrB_Info GB (_bind2nd_tran__bclr_uint64)
(
GrB_Matrix C,
const GrB_Matrix A,
const GB_void *y_input,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint64_t y = (*((const uint64_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
3d7pt_var.lbpar.c | #include <omp.h>
#include <math.h>
#define ceild(n,d) ceil(((double)(n))/((double)(d)))
#define floord(n,d) floor(((double)(n))/((double)(d)))
#define max(x,y) ((x) > (y)? (x) : (y))
#define min(x,y) ((x) < (y)? (x) : (y))
/*
* Order-1, 3D 7 point stencil with variable coefficients
* Adapted from PLUTO and Pochoir test bench
*
* Tareq Malas
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#ifdef LIKWID_PERFMON
#include <likwid.h>
#endif
#include "print_utils.h"
#define TESTS 2
#define MAX(a,b) ((a) > (b) ? a : b)
#define MIN(a,b) ((a) < (b) ? a : b)
/* Subtract the `struct timeval' values X and Y,
* storing the result in RESULT.
*
* Return 1 if the difference is negative, otherwise 0.
*/
int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y)
{
/* Perform the carry for the later subtraction by updating y. */
if (x->tv_usec < y->tv_usec)
{
int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec;
}
if (x->tv_usec - y->tv_usec > 1000000)
{
int nsec = (x->tv_usec - y->tv_usec) / 1000000;
y->tv_usec += 1000000 * nsec;
y->tv_sec -= nsec;
}
/* Compute the time remaining to wait.
* tv_usec is certainly positive.
*/
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;
/* Return 1 if result is negative. */
return x->tv_sec < y->tv_sec;
}
int main(int argc, char *argv[])
{
int t, i, j, k, m, test;
int Nx, Ny, Nz, Nt;
if (argc > 3) {
Nx = atoi(argv[1])+2;
Ny = atoi(argv[2])+2;
Nz = atoi(argv[3])+2;
}
if (argc > 4)
Nt = atoi(argv[4]);
// allocate the arrays
double ****A = (double ****) malloc(sizeof(double***)*2);
for(m=0; m<2;m++){
A[m] = (double ***) malloc(sizeof(double**)*Nz);
for(i=0; i<Nz; i++){
A[m][i] = (double**) malloc(sizeof(double*)*Ny);
for(j=0;j<Ny;j++){
A[m][i][j] = (double*) malloc(sizeof(double)*Nx);
}
}
}
double ****coef = (double ****) malloc(sizeof(double***)*7);
for(m=0; m<7;m++){
coef[m] = (double ***) malloc(sizeof(double**)*Nz);
for(i=0; i<Nz; i++){
coef[m][i] = (double**) malloc(sizeof(double*)*Ny);
for(j=0;j<Ny;j++){
coef[m][i][j] = (double*) malloc(sizeof(double)*Nx);
}
}
}
// tile size information, including extra element to decide the list length
int *tile_size = (int*) malloc(sizeof(int));
tile_size[0] = -1;
// The list is modified here before source-to-source transformations
tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5);
tile_size[0] = 24;
tile_size[1] = 24;
tile_size[2] = 8;
tile_size[3] = 2048;
tile_size[4] = -1;
// for timekeeping
int ts_return = -1;
struct timeval start, end, result;
double tdiff = 0.0, min_tdiff=1.e100;
const int BASE = 1024;
// initialize variables
//
srand(42);
for (i = 1; i < Nz; i++) {
for (j = 1; j < Ny; j++) {
for (k = 1; k < Nx; k++) {
A[0][i][j][k] = 1.0 * (rand() % BASE);
}
}
}
for (m=0; m<7; m++) {
for (i=1; i<Nz; i++) {
for (j=1; j<Ny; j++) {
for (k=1; k<Nx; k++) {
coef[m][i][j][k] = 1.0 * (rand() % BASE);
}
}
}
}
#ifdef LIKWID_PERFMON
LIKWID_MARKER_INIT;
#pragma omp parallel
{
LIKWID_MARKER_THREADINIT;
#pragma omp barrier
LIKWID_MARKER_START("calc");
}
#endif
int num_threads = 1;
#if defined(_OPENMP)
num_threads = omp_get_max_threads();
#endif
for(test=0; test<TESTS; test++){
gettimeofday(&start, 0);
// serial execution - Addition: 6 && Multiplication: 2
/* Copyright (C) 1991-2014 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/* This header is separate from features.h so that the compiler can
include it implicitly at the start of every compilation. It must
not itself include <features.h> or any other header that includes
<features.h> because the implicit include comes before any feature
test macros that may be defined in a source file before it first
explicitly includes a system header. GCC knows the name of this
header in order to preinclude it. */
/* glibc's intent is to support the IEC 559 math functionality, real
and complex. If the GCC (4.9 and later) predefined macros
specifying compiler intent are available, use them to determine
whether the overall intent is to support these features; otherwise,
presume an older compiler has intent to support these features and
define these macros by default. */
/* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) /
Unicode 6.0. */
/* We do not support C11 <threads.h>. */
int t1, t2, t3, t4, t5, t6, t7, t8;
int lb, ub, lbp, ubp, lb2, ub2;
register int lbv, ubv;
/* Start of CLooG code */
if ((Nt >= 2) && (Nx >= 3) && (Ny >= 3) && (Nz >= 3)) {
for (t1=-1;t1<=floord(Nt-2,12);t1++) {
lbp=max(ceild(t1,2),ceild(24*t1-Nt+3,24));
ubp=min(floord(Nt+Nz-4,24),floord(12*t1+Nz+9,24));
#pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8)
for (t2=lbp;t2<=ubp;t2++) {
for (t3=max(max(0,ceild(3*t1-1,2)),ceild(24*t2-Nz-4,8));t3<=min(min(min(floord(Nt+Ny-4,8),floord(12*t1+Ny+21,8)),floord(24*t2+Ny+20,8)),floord(24*t1-24*t2+Nz+Ny+19,8));t3++) {
for (t4=max(max(max(0,ceild(3*t1-511,512)),ceild(24*t2-Nz-2044,2048)),ceild(8*t3-Ny-2044,2048));t4<=min(min(min(min(floord(Nt+Nx-4,2048),floord(12*t1+Nx+21,2048)),floord(24*t2+Nx+20,2048)),floord(8*t3+Nx+4,2048)),floord(24*t1-24*t2+Nz+Nx+19,2048));t4++) {
for (t5=max(max(max(max(max(0,12*t1),24*t1-24*t2+1),24*t2-Nz+2),8*t3-Ny+2),2048*t4-Nx+2);t5<=min(min(min(min(min(Nt-2,12*t1+23),24*t2+22),8*t3+6),2048*t4+2046),24*t1-24*t2+Nz+21);t5++) {
for (t6=max(max(24*t2,t5+1),-24*t1+24*t2+2*t5-23);t6<=min(min(24*t2+23,-24*t1+24*t2+2*t5),t5+Nz-2);t6++) {
for (t7=max(8*t3,t5+1);t7<=min(8*t3+7,t5+Ny-2);t7++) {
lbv=max(2048*t4,t5+1);
ubv=min(2048*t4+2047,t5+Nx-2);
#pragma ivdep
#pragma vector always
for (t8=lbv;t8<=ubv;t8++) {
A[( t5 + 1) % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] = (((((((coef[0][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)]) + (coef[1][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6) - 1][ (-t5+t7)][ (-t5+t8)])) + (coef[2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7) - 1][ (-t5+t8)])) + (coef[3][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8) - 1])) + (coef[4][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6) + 1][ (-t5+t7)][ (-t5+t8)])) + (coef[5][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7) + 1][ (-t5+t8)])) + (coef[6][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8) + 1]));;
}
}
}
}
}
}
}
}
}
/* End of CLooG code */
gettimeofday(&end, 0);
ts_return = timeval_subtract(&result, &end, &start);
tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6);
min_tdiff = min(min_tdiff, tdiff);
printf("Rank 0 TEST# %d time: %f\n", test, tdiff);
}
PRINT_RESULTS(1, "variable no-symmetry")
#ifdef LIKWID_PERFMON
#pragma omp parallel
{
LIKWID_MARKER_STOP("calc");
}
LIKWID_MARKER_CLOSE;
#endif
// Free allocated arrays
for(i=0; i<Nz; i++){
for(j=0;j<Ny;j++){
free(A[0][i][j]);
free(A[1][i][j]);
}
free(A[0][i]);
free(A[1][i]);
}
free(A[0]);
free(A[1]);
for(m=0; m<7;m++){
for(i=0; i<Nz; i++){
for(j=0;j<Ny;j++){
free(coef[m][i][j]);
}
free(coef[m][i]);
}
free(coef[m]);
}
return 0;
}
|
ops.h | /*******************************************************************************
* Copyright (c) 2015-2018 Skymind, Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://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.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
#pragma once
#ifndef OPS_H_
#define OPS_H_
#include <op_boilerplate.h>
#include <array/DataTypeUtils.h>
#include <helpers/shape.h>
#include <vector>
#include <Environment.h>
#include <loops/summarystatsreduce.h>
#define MIN 1e-12
#define MAX_FLOAT 1e37
#define MIN_FLOAT 1e-37
#define MAX_INT 2147483647
#define MIN_CUTFOFF -3.79297773665f
#define FLOAT_MIN_NORMAL 1.17549435e-38
#define EPS 1e-5
#define AFFINITY close
#define DOUBLE_PI_T T(2.0 * 3.14159265358979323846)
#define no_op_exec_special static const bool requiresSpecial = false; static void execSpecial(T *dx, Nd4jLong *xShapeBuffer, T *result, Nd4jLong *resultShapeBuffer, T *extraParams, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) {}
#define no_op_exec_special_accumulation static const bool requiresSpecialAccumulation = false; static void execSpecial(T *x, Nd4jLong *xShapeInfo, T *extraParams, T *result, Nd4jLong *resultShapeInfoBuffer, int *dimension, int dimensionLength, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffset){}
#ifdef __CUDACC__
#include <helpers/sharedmem.h>
#define no_op_exec_special_cuda static __device__ void execSpecialCuda(T *dx, Nd4jLong *xShapeBuffer,T *result, Nd4jLong *resultShapeBuffer,T *extraParams, int *allocationPointer, T *reductionPointer, UnifiedSharedMemory *manager, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) {}
#define no_op_exec_special_accumulation_cuda static inline __device__ void execSpecialCuda(T *dx, Nd4jLong *xShapeInfo, T *extraParams, T *result, Nd4jLong *resultShapeInfo, int *dimension, int dimensionLength, T *reductionBuffer, UnifiedSharedMemory *manager, Nd4jLong *tadOnlyShapeInfo, Nd4jLong *tadOffsets) {}
#else
// hacky fix for isnan/being being out of scope
//#ifdef IOS
//#define isinf(x) 0 // this isn't right. But std::isinf fails
//#define isnan(x) 0
//#else
//#define isnan std::isnan
//#define isinf std::isinf
//#endif
#define no_op_exec_special_cuda
#define no_op_exec_special_accumulation_cuda
#endif
#define SELU_ALPHA 1.6732632423543772848170429916717
#define SELU_LAMBDA 1.0507009873554804934193349852946
#ifdef _OPENMP
#pragma omp declare reduction(maxT : float,double,float16 : \
omp_out = nd4j::math::nd4j_max(omp_in, omp_out) )\
initializer (omp_priv=-MAX_FLOAT)
#pragma omp declare reduction(minT : float,double,float16 : \
omp_out = nd4j::math::nd4j_min(omp_in, omp_out) )\
initializer (omp_priv=MAX_FLOAT)
#pragma omp declare reduction(sumT : float,double,float16 : \
omp_out = omp_in + omp_out)\
initializer (omp_priv=0.0f)
#endif
namespace functions {
namespace indexreduce {
template<typename T>
struct IndexValue {
T value;
Nd4jLong index;
};
}
namespace summarystats {
template <typename T>
class SummaryStatsData;
}
}
namespace simdOps {
template<typename T>
class Add {
public:
op_def static T op(T d1, T d2) {
return d1 + d2;
}
op_def static T op(T d1, T d2, T *params) {
return d1 + d2;
}
op_def static T op(T d1) {
return d1;
}
// op for MetaOps
op_def static T op(T d1, T *params) {
return d1 + params[0];
}
op_def static T startingValue() {
return static_cast<T>(0.f);
}
};
template<typename T>
class Subtract {
public:
op_def static T op(T d1, T d2) {
return d1 - d2;
}
op_def static T op(T d1, T d2, T *params) {
return d1 - d2;
}
op_def static T op(T d1) {
return d1;
}
// op for MetaOps
op_def static T op(T d1, T *params) {
return d1 - params[0];
}
};
template<typename T>
class SquaredSubtract {
public:
op_def static T op(T d1, T d2) {
return nd4j::math::nd4j_pow<T>(d1 - d2, static_cast<T>(2.f));
}
op_def static T op(T d1, T d2, T *params) {
return nd4j::math::nd4j_pow<T>(d1 - d2, static_cast<T>(2.f));
}
op_def static T op(T d1) {
return d1;
}
// op for MetaOps
op_def static T op(T d1, T *params) {
return nd4j::math::nd4j_pow<T>(d1 - params[0], static_cast<T>(2.f));
}
};
template<typename T>
class ReverseSubtract {
public:
op_def static T op(T d1, T d2) {
return d2 - d1;
}
op_def static T op(T d1, T d2, T *params) {
return d2 - d1;
}
op_def static T op(T d1) {
return d1;
}
// op for MetaOps
op_def static T op(T d1, T *params) {
return params[0] - d1;
}
};
template<typename T>
class LogPoisonLossFull {
public:
op_def static T op(T z, T c) {
return (nd4j::math::nd4j_exp<T>(c) - z * c + (z * nd4j::math::nd4j_log<T>(z) - z + static_cast<T>(0.5f) * nd4j::math::nd4j_log<T>(DOUBLE_PI_T * z)));
}
op_def static T op(T z, T c, T *params) {
return (nd4j::math::nd4j_exp<T>(c) - z * c + (z * nd4j::math::nd4j_log<T>(z) - z + static_cast<T>(0.5f) * nd4j::math::nd4j_log<T>(DOUBLE_PI_T * z)));
}
op_def static T op(T z) {
return (z * nd4j::math::nd4j_log<T>(z) - z + static_cast<T>(0.5f) * nd4j::math::nd4j_log<T>(DOUBLE_PI_T * z));
}
// op for MetaOps
op_def static T op(T z, T *params) {
return (nd4j::math::nd4j_exp<T>(params[0]) - z * params[0] + (z * nd4j::math::nd4j_log<T>(z) - z + static_cast<T>(0.5f) * nd4j::math::nd4j_log<T>(DOUBLE_PI_T * z)));
}
};
template<typename T>
class LogPoisonLoss {
public:
op_def static T op(T z, T c) {
return (nd4j::math::nd4j_exp<T>(c) - z * c);
}
op_def static T op(T z, T c, T *params) {
return (nd4j::math::nd4j_exp<T>(c) - z * c);
}
op_def static T op(T z) {
return (z);
}
// op for MetaOps
op_def static T op(T z, T *params) {
return (nd4j::math::nd4j_exp<T>(params[0]) - z * params[0]);
}
};
template<typename T>
class Multiply {
public:
op_def static T op(T d1, T d2) {
return d1 * d2;
}
op_def static T op(T d1, T d2, T *params) {
return d1 * d2;
}
op_def static T op(T d1) {
return d1;
}
// op for MetaOps
op_def static T op(T d1, T *params) {
return d1 * params[0];
}
op_def static T startingValue() {
return static_cast<T>(1.f);
}
};
template<typename T>
class Divide {
public:
op_def static T op(T d1, T d2) {
return d1 / d2;
}
op_def static T op(T d1, T d2, T *params) {
return d1 / d2;
}
op_def static T op(T d1) {
return d1;
}
// op for MetaOps
op_def static T op(T d1, T *params) {
return d1 / params[0];
}
op_def static T startingValue() {
return static_cast<T>(1.f);
}
};
template<typename T>
class SafeDivide {
public:
op_def static T op(T d1, T d2) {
if(d2 == static_cast<T>(0.f))
return static_cast<T>(0.f);
return d1 / d2;
}
op_def static T op(T d1, T d2, T *params) {
if(d2 == static_cast<T>(0.f))
return static_cast<T>(0.f);
return d1 / d2;
}
op_def static T op(T d1) {
return d1;
}
// op for MetaOps
op_def static T op(T d1, T *params) {
if(params[0] == static_cast<T>(0.f))
return static_cast<T>(0.f);
return d1 / params[0];
}
};
template<typename T>
class FloorDiv {
public:
op_def static T op(T d1, T d2) {
return nd4j::math::nd4j_floor<T>(d1 / d2);
}
op_def static T op(T d1, T d2, T *params) {
return nd4j::math::nd4j_floor<T>(d1 / d2);
}
op_def static T op(T d1) {
return nd4j::math::nd4j_floor<T>(d1);
}
// op for MetaOps
op_def static T op(T d1, T *params) {
return nd4j::math::nd4j_floor<T>(d1 / params[0]);
}
};
template<typename T>
class TruncateDiv {
public:
op_def static T op(T d1, T d2) {
auto i1 = static_cast<int>(d1);
auto i2 = static_cast<int>(d2);
return static_cast<T>(i1 / i2);
}
op_def static T op(T d1, T d2, T *params) {
auto i1 = static_cast<int>(d1);
auto i2 = static_cast<int>(d2);
return static_cast<T>(i1 / i2);
}
op_def static T op(T d1) {
return d1;
}
// op for MetaOps
op_def static T op(T d1, T *params) {
auto i1 = static_cast<int>(d1);
auto i2 = static_cast<int>(params[0]);
return static_cast<T>(i1 / i2);
}
};
template<typename T>
class Remainder {
public:
op_def static T op(T d1, T d2) {
return nd4j::math::nd4j_remainder(d1, d2);
}
op_def static T op(T d1, T d2, T *params) {
return nd4j::math::nd4j_remainder(d1, d2);
}
op_def static T op(T d1) {
return d1;
}
// op for MetaOps
op_def static T op(T d1, T *params) {
return nd4j::math::nd4j_remainder(d1, params[0]);
}
};
template<typename T>
class FMod {
public:
op_def static T op(T d1, T d2) {
return nd4j::math::nd4j_fmod(d1, d2);
}
op_def static T op(T d1, T d2, T *params) {
return nd4j::math::nd4j_fmod(d1, d2);
}
op_def static T op(T d1) {
return d1;
}
// op for MetaOps
op_def static T op(T d1, T *params) {
return nd4j::math::nd4j_fmod(d1, params[0]);
}
};
template<typename T>
class FloorMod {
public:
op_def static T op(T d1, T d2) {
T m = nd4j::math::nd4j_fmod(d1, d2);;
return (d1 < static_cast<T>(0.0f)) == (d2 < static_cast<T>(0.0f)) ? m : nd4j::math::nd4j_fmod<T>(m + d2, d2);
}
op_def static T op(T d1, T d2, T *params) {
T m = nd4j::math::nd4j_fmod(d1, d2);
return (d1 < static_cast<T>(0.0f)) == (d2 < static_cast<T>(0.0f)) ? m : nd4j::math::nd4j_fmod<T>(m + d2, d2);
}
op_def static T op(T d1) {
return d1;
}
// op for MetaOps
op_def static T op(T d1, T *params) {
T m = nd4j::math::nd4j_fmod(d1, params[0]);
return (d1 < static_cast<T>(0.0f)) == (params[0] < static_cast<T>(0.0f)) ? m : nd4j::math::nd4j_fmod<T>(m + params[0], params[0]);
}
};
template<typename T>
class ReverseDivide {
public:
op_def static T op(T d1, T d2) {
return d2 / d1;
}
op_def static T op(T d1, T d2, T *params) {
return d2 / d1;
}
op_def static T op(T d1) {
return d1;
}
// op for MetaOps
op_def static T op(T d1, T *params) {
return params[0] / d1;
}
};
template<typename T>
class Copy {
public:
op_def static T op(T d1, T d2) {
return d2;
}
op_def static T op(T d1, T d2, T *params) {
return d2;
}
op_def static T op(T d1) {
return d1;
}
// op for MetaOps
op_def static T op(T d1, T *params) {
return params[0];
}
};
template<typename T>
class Copy2 {
public:
op_def static T op(T d1, T d2) {
return d2;
}
op_def static T op(T d1, T d2, T *params) {
return d2;
}
op_def static T op(T d1) {
return d1;
}
// op for MetaOps
op_def static T op(T d1, T *params) {
return params[0];
}
};
template<typename T>
class Axpy {
public:
op_def static T op(T d1, T d2) {
return d2 + d1;
}
op_def static T op(T d1, T d2, T *params) {
T alpha = params[0];
return alpha * d1 + d2;
}
op_def static T op(T d1) {
return d1;
}
};
template<typename T>
class And {
public:
op_def static T op(T d1, T d2) {
return d2 + d1;
}
op_def static T op(T d1, T d2, T *params) {
T comp = params[0];
return d1 != comp && d2 != comp ? static_cast<T>(1.0f) : static_cast<T>(0.0f);
}
op_def static T op(T d1) {
return d1;
}
// op for MetaOps
op_def static T op(T d1, T *params) {
return static_cast<T>(119.0f);
}
};
template<typename T>
class Or {
public:
op_def static T op(T d1, T d2) {
return d2 + d1;
}
op_def static T op(T d1, T d2, T *params) {
T comp = params[0];
return d1 != comp || d2 != comp ? static_cast<T>(1.0f) : static_cast<T>(0.0f);
}
op_def static T op(T d1) {
return d1;
}
// op for MetaOps
op_def static T op(T d1, T *params) {
return static_cast<T>(119.0f);
}
};
template<typename T>
class Xor {
public:
op_def static T op(T d1, T d2) {
return d2 + d1;
}
op_def static T op(T d1, T d2, T *params) {
T comp = params[0];
return ((d1 == comp && d2 != comp)||(d1 != comp && d2 == comp)) ? static_cast<T>(1.0f) : static_cast<T>(0.0f);
}
op_def static T op(T d1) {
return d1;
}
};
template<typename T>
class Not {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
T comp = params[0];
return d1 == comp ? static_cast<T>(1.0f) : static_cast<T>(0.0f);
}
};
template<typename T>
class LogicalNot {
public:
op_def static T op(T d1, T d2) {
return !((int) d1 && (int) d2);
}
op_def static T op(T d1, T d2, T *params) {
return (T) !((int) d1 && (int) d2);
}
op_def static T op(T d1) {
return d1;
}
// op for MetaOps
op_def static T op(T d1, T *params) {
return static_cast<T>(119.0f);
}
};
template<typename T>
class LogicalXor {
public:
op_def static T op(T d1, T d2) {
int i1 = (int) d1;
int i2 = (int) d2;
return (i1 | i2) &~ (i1 & i2);
}
op_def static T op(T d1, T d2, T *params) {
int i1 = (int) d1;
int i2 = (int) d2;
return (i1 | i2) &~ (i1 & i2);
}
op_def static T op(T d1) {
return d1;
}
// op for MetaOps
op_def static T op(T d1, T *params) {
return static_cast<T>(119.0f);
}
};
template<typename T>
class LogicalAnd {
public:
op_def static T op(T d1, T d2) {
return (int) d1 & (int) d2;
}
op_def static T op(T d1, T d2, T *params) {
return (int) d1 & (int) d2;
}
op_def static T op(T d1) {
return d1;
}
// op for MetaOps
op_def static T op(T d1, T *params) {
return static_cast<T>(119.0f);
}
};
template<typename T>
class LogicalOr {
public:
op_def static T op(T d1, T d2) {
return (int) d1 | (int) d2;
}
op_def static T op(T d1, T d2, T *params) {
return (int) d1 | (int) d2;
}
op_def static T op(T d1) {
return d1;
}
// op for MetaOps
op_def static T op(T d1, T *params) {
return static_cast<T>(119.0f);
}
};
template<typename T>
class SetValOrLess {
public:
op_def static T op(T d1, T d2, T *params) {
if (d2 < d1) {
return d1;
}
return d2;
}
};
template<typename T>
class Mod {
public:
/*
// just a optional note, feel free to remove later
op_def static half op(half d1, half d2, half *params) {
return __float2half(simdOps::Mod<float>::op(__half2float(d1), __half2float(d2), nullptr));
}
*/
op_def static T op(T d1, T d2) {
return (int)d1 % (int)d2;
}
op_def static T op(T d1, T d2, T *params) {
return (int)d1 % (int)d2;
}
// op for MetaOp
op_def static T op(T d1, T *params) {
return (int)d1 % (int)params[0];
}
};
template<typename T>
class ReverseMod {
public:
op_def static T op(T d1, T d2) {
return (int)d2 % (int)d1;
}
op_def static T op(T d1, T d2, T *params) {
return (int)d2 % (int)d1;
}
// op for MetaOp
op_def static T op(T d1, T *params) {
return (int)params[0] % (int)d1;
}
};
/**
* Whether 2 elements in an array
* are epsilion equal
*/
template<typename T>
class Epsilon {
public:
op_def static T op(T d1, T d2, T *params) {
T diff = d1 - d2;
T absDiff = nd4j::math::nd4j_abs<T>(diff);
if (absDiff <= static_cast<T>(MIN))
return static_cast<T>(1.0f);
return static_cast<T>(0.0f);
}
op_def static T op(T d1, T *params) {
return d1;
}
};
template<typename T>
class EqualTo {
public:
op_def static T op(T d1, T d2) {
return d1 == d2;
}
op_def static T op(T d1, T d2, T *params) {
return d1 == d2;
}
op_def static T op(T d1, T *params) {
return d1;
}
};
template<typename T>
class NotEqualTo {
public:
op_def static T op(T d1, T d2) {
return d1 != d2;
}
op_def static T op(T d1, T d2, T *params) {
return d1 != d2;
}
op_def static T op(T d1, T *params) {
return d1;
}
};
template<typename T>
class GreaterThanOrEqual {
public:
op_def static T op(T d1, T d2) {
return d1 >= d2;
}
op_def static T op(T d1, T d2, T *params) {
return d1 >= d2;
}
// FIXME: this signature clashes with MetaOp stuff
op_def static T op(T d1, T *params) {
return d1;
}
};
template<typename T>
class GreaterThan {
public:
op_def static T op(T d1, T d2) {
return d1 > d2;
}
op_def static T op(T d1, T d2, T *params) {
return d1 > d2;
}
// FIXME: this signature clashes with MetaOp stuff
op_def static T op(T d1, T *params) {
return d1;
}
};
template<typename T>
class LessThan {
public:
op_def static T op(T d1, T d2) {
return d1 < d2;
}
op_def static T op(T d1, T d2, T *params) {
return d1 < d2;
}
op_def static T op(T d1, T *params) {
return d1;
}
};
template<typename T>
class LessThanOrEqual {
public:
op_def static T op(T d1, T d2) {
return d1 <= d2;
}
op_def static T op(T d1, T d2, T *params) {
return d1 <= d2;
}
op_def static T op(T d1, T *params) {
return d1;
}
};
template<typename T>
class Abs {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return nd4j::math::nd4j_abs<T>(d1);
}
};
template<typename T>
class Ceiling {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return nd4j::math::nd4j_ceil<T>(d1);
}
};
template<typename T>
class Cosine {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return nd4j::math::nd4j_cos<T>(d1);
}
};
template<typename T>
class Exp {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return nd4j::math::nd4j_exp<T>(d1);
}
};
template<typename T>
class HardTanhDerivative {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return ((d1 >= static_cast<T>(-1.0f) && d1 <= static_cast<T>(1.0f)) ? static_cast<T>(1.0f) : static_cast<T>(0.0f));
}
};
template<typename T>
class HardTanh {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
if (d1 < static_cast<T>(-1.0f))
return static_cast<T>(-1.0f);
else if (d1 > static_cast<T>(1.0f))
return static_cast<T>(1.0f);
else
return d1;
}
};
template<typename T>
class Floor {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return nd4j::math::nd4j_floor<T>(d1);
}
};
template<typename T>
class Log {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return nd4j::math::nd4j_log<T>(d1);
}
};
template<typename T>
class Log1p {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return nd4j::math::nd4j_log<T>(1+d1);
}
};
template<typename T>
class LogX {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return nd4j::math::nd4j_log<T>(d1) / nd4j::math::nd4j_log<T>(params[0]) ;
}
};
template<typename T>
class StabilizeFP16 {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
if (d1 <= static_cast<T>(0.f)) return static_cast<T>(0.001f);
else return d1;
}
};
template<typename T>
class SpecialDerivative {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return d1 * (static_cast<T>(1.0f) - d1);
}
};
template<typename T>
class Neg {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return -d1;
}
};
template<typename T>
class Erf {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return nd4j::math::nd4j_erf<T>(d1);
}
};
template<typename T>
class Erfc {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return nd4j::math::nd4j_erfc<T>(d1);
}
};
template<typename T>
class Reciprocal {
public:
no_op_exec_special
no_op_exec_special_cuda
// op_def static T op(T d1) {
// return (T(1.0f) / d1);
// }
// op for MetaOps
op_def static T op(T d1, T *params) {
return (static_cast<T>(1.0f)/d1);
}
};
template<typename T>
class Sqr {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return nd4j::math::nd4j_pow<T>(d1, static_cast<T>(2.f));
}
op_def static T op(T d1) {
return nd4j::math::nd4j_pow<T>(d1, static_cast<T>(2.0f));
}
};
template<typename T>
class RelativeError {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return nd4j::math::nd4j_re<T>(d1, params[0]);
}
op_def static T op(T d1, T d2) {
return nd4j::math::nd4j_re<T>(d1, d2);
}
op_def static T op(T d1, T d2, T *params) {
return nd4j::math::nd4j_re<T>(d1, d2);
}
op_def static T op(T d1) {
return static_cast<T>(0.0f);
}
};
template<typename T>
class BinaryRelativeError {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
T d2 = params[0];
T threshold = params[1];
return nd4j::math::nd4j_re<T>(d1, d2) > threshold ? static_cast<T>(1.0f) : static_cast<T>(0.0f);
}
op_def static T op(T d1, T d2, T *params) {
T threshold = params[0];
return nd4j::math::nd4j_re<T>(d1, d2) > threshold ? static_cast<T>(1.0f) : static_cast<T>(0.0f);
}
op_def static T op(T d1) {
return static_cast<T>(0.0f);
}
};
template<typename T>
class BinaryMinimumAbsoluteRelativeError {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
T d2 = params[0];
T thresholdRelative = params[1];
T thresholdAbsolute = params[2];
return nd4j::math::nd4j_re<T>(d1, d2) > thresholdRelative ? (nd4j::math::nd4j_abs<T>(d1 - d2) < thresholdAbsolute ? static_cast<T>(0.0f) : static_cast<T>(1.0f)) : static_cast<T>(0.0f);
}
op_def static T op(T d1, T d2, T *params) {
T thresholdRelative = params[0];
T thresholdAbsolute = params[1];
return nd4j::math::nd4j_re<T>(d1, d2) > thresholdRelative ? (nd4j::math::nd4j_abs<T>(d1 - d2) < thresholdAbsolute ? static_cast<T>(0.0f) : static_cast<T>(1.0f)) : static_cast<T>(0.0f);
}
op_def static T op(T d1) {
return static_cast<T>(0.0f);
}
};
template<typename T>
class Pow {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return nd4j::math::nd4j_pow<T>(d1, params[0]);
}
op_def static T op(T d1, T d2) {
return nd4j::math::nd4j_pow<T>(d1, d2);
}
op_def static T op(T d1, T d2, T *params) {
return nd4j::math::nd4j_pow<T>(d1, d2);
}
op_def static T op(T d1) {
return d1;
}
};
template<typename T>
class PowDerivative {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return params[0] * nd4j::math::nd4j_pow<T>(d1, params[0] - static_cast<T>(1.f));
}
op_def static T op(T d1, T d2) {
return d2 * nd4j::math::nd4j_pow<T>(d1, d2 - static_cast<T>(1.f));
}
op_def static T op(T d1, T d2, T *params) {
return d2 * nd4j::math::nd4j_pow<T>(d1, d2 - static_cast<T>(1.f));
}
op_def static T op(T d1) {
return d1;
}
};
template<typename T>
class Round {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return nd4j::math::nd4j_round<T>(d1);
}
};
template<typename T>
class IsNan {
public:
no_op_exec_special
no_op_exec_special_cuda
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
op_def static T op(T d1, T *params) {
return nd4j::math::nd4j_isnan(d1) ? static_cast<T>(1.0f) : static_cast<T>(0.0f);
}
op_def static T startingValue(const T *input) {
return static_cast<T>(0.0f);
}
op_def static T merge(T old, T opOutput, T *extraParams) {
return opOutput + old;
}
op_def static T update(T old, T opOutput, T *extraParams) {
return opOutput + old;
}
op_def static T postProcess(T reduction, Nd4jLong n, T *extraParams) {
return reduction;
}
};
template<typename T>
class Expm1 {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return nd4j::math::nd4j_exp(d1) - static_cast<T>(1.0f);
}
};
template<typename T>
class IsInf {
public:
no_op_exec_special
no_op_exec_special_cuda
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
op_def static T op(T d1, T *params) {
return nd4j::math::nd4j_isinf<T>(d1) ? static_cast<T>(1.0f) : static_cast<T>(0.0f);
}
op_def static T startingValue(const T *input) {
return static_cast<T>(0.0f);
}
op_def static T merge(T old, T opOutput, T *extraParams) {
return opOutput + old;
}
op_def static T update(T old, T opOutput, T *extraParams) {
return opOutput + old;
}
op_def static T postProcess(T reduction, Nd4jLong n, T *extraParams) {
return reduction;
}
};
template<typename T>
class IsInfOrNan{
public:
no_op_exec_special
no_op_exec_special_cuda
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
op_def static T op(T d1, T *params) {
return nd4j::math::nd4j_isfin<T>(d1) ? static_cast<T>(0.0f) : static_cast<T>(1.0f);
}
op_def static T startingValue(const T *input) {
return static_cast<T>(0.0f);
}
op_def static T merge(T old, T opOutput, T *extraParams) {
return opOutput + old;
}
op_def static T update(T old, T opOutput, T *extraParams) {
return opOutput + old;
}
op_def static T postProcess(T reduction, Nd4jLong n, T *extraParams) {
return reduction;
}
};
template<typename T>
class IsFinite {
public:
no_op_exec_special
no_op_exec_special_cuda
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
op_def static T op(T d1, T *params) {
return nd4j::math::nd4j_isfin<T>(d1) ? static_cast<T>(1.0f) : static_cast<T>(0.0f);
}
op_def static T startingValue(const T *input) {
return static_cast<T>(0.0f);
}
op_def static T merge(T old, T opOutput, T *extraParams) {
return opOutput + old;
}
op_def static T update(T old, T opOutput, T *extraParams) {
return opOutput + old;
}
op_def static T postProcess(T reduction, Nd4jLong n, T *extraParams) {
return reduction;
}
};
template<typename T>
class ClipByValue {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
if (d1 > params[1])
return params[1];
else if (d1 < params[0])
return params[0];
else return d1;
}
};
template<typename T>
class Swish {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return d1 * nd4j::math::nd4j_sigmoid<T>(d1);
}
};
template<typename T>
class SwishDerivative {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
T ex = nd4j::math::nd4j_pow<T>(static_cast<T>(M_E), d1);
return (ex * (d1 + ex + static_cast<T>(1.f))) / nd4j::math::nd4j_pow<T>((ex + static_cast<T>(1.f)) , static_cast<T>(2.0f));
}
};
template<typename T>
class LogSigmoid {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return nd4j::math::nd4j_log(nd4j::math::nd4j_sigmoid<T>(d1));
}
};
template<typename T>
class LogSigmoidDerivative {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
T ex = nd4j::math::nd4j_pow<T>(M_E, d1);
return static_cast<T>(1.f) / (ex + static_cast<T>(1.f));
}
};
template<typename T>
class Sigmoid {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return nd4j::math::nd4j_sigmoid<T>(d1);
}
};
template<typename T>
class SigmoidDerivative {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return nd4j::math::nd4j_sigmoidderivative<T>(d1);
}
};
template<typename T>
class HardSigmoid {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return nd4j::math::nd4j_min<T>(static_cast<T>(1.0f), nd4j::math::nd4j_max<T>(static_cast<T>(0.0f), (static_cast<T>(0.2f)) * d1 + static_cast<T>(0.5f)));
}
};
template<typename T>
class HardSigmoidDerivative {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return d1 < static_cast<T>(-2.5f) || d1 > static_cast<T>(2.5f) ? static_cast<T>(0.0f) : static_cast<T>(0.2f);
}
};
/**
* Scale to be between a min and max
*/
template<typename T>
class SetRange {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
T min = params[0];
T max = params[1];
if (d1 >= min && d1 <= max)
return d1;
if (min == static_cast<T>(0.0f) && max == static_cast<T>(1.0f)) {
auto val = static_cast<T>(1.0f) / (static_cast<T>(1.0f) + nd4j::math::nd4j_exp<T>(-d1));
return (nd4j::math::nd4j_floor<T>(val * (max - min)) + min);
}
auto ret = (nd4j::math::nd4j_floor<T>(d1 * (max - min)) + min);
return ret;
}
};
template<typename T>
class Sin {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return nd4j::math::nd4j_sin<T>(d1);
}
};
template<typename T>
class Square {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return d1 * d1;
}
};
template<typename T>
class Sqrt {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return nd4j::math::nd4j_sqrt<T>(d1);
}
};
template<typename T>
class RSqrt {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return static_cast<T>(1.0f) / nd4j::math::nd4j_sqrt<T>(d1);
}
};
template<typename T>
class Rint {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return nd4j::math::nd4j_rint<T>(d1);
}
};
template<typename T>
class SoftPlus {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return nd4j::math::softplus<T>(d1);
}
};
template<typename T>
class Sign {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return (d1 > static_cast<T>(0.0f)) - (d1 < static_cast<T>(0.0f));
}
};
template<typename T>
class TimesOneMinus {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return d1 * (static_cast<T>(1.0f) - d1);
}
};
template<typename T>
class RationalTanh {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
// keep 2/3 as runtime variable, to match precision
auto dis = (static_cast<T>(2.0f) / static_cast<T>(3.0f)) * d1;
auto tanh = nd4j::math::nd4j_sgn<T>(dis) * (static_cast<T>(1.0f) - (static_cast<T>(1.0f) / (static_cast<T>(1.0f) + nd4j::math::nd4j_abs<T>(dis) + nd4j::math::nd4j_pow<T>(dis, static_cast<T>(2.0f)) + static_cast<T>(1.41645f) * nd4j::math::nd4j_pow<T>(dis, static_cast<T>(4.0f)) )));
return static_cast<T>(1.7159f) * tanh;
}
};
template<typename T>
class RationalTanhDerivative {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
auto dis = (static_cast<T>(2.0f) / static_cast<T>(3.0f)) * d1;
auto a = static_cast<T>(1.0f) + nd4j::math::nd4j_abs<T>(dis) + nd4j::math::nd4j_pow<T>(dis, static_cast<T>(2.)) + static_cast<T>(1.41645f) * nd4j::math::nd4j_pow<T>(dis, static_cast<T>(4.f));
auto tDeriv = (static_cast<T>(1.0f) + nd4j::math::nd4j_sign<T>(dis) * (static_cast<T>(2.0f) * dis + static_cast<T>(4.0f) * static_cast<T>(1.41645f) * nd4j::math::nd4j_pow<T>(dis, static_cast<T>(3.f)))) / (a * a);
return static_cast<T>(1.7159f) * (static_cast<T>(2.0f) / static_cast<T>(3.0f)) * tDeriv;
}
};
template<typename T>
class Tanh {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return nd4j::math::nd4j_tanh<T>(d1);
}
};
template<typename T>
class RectifiedTanh {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return nd4j::math::nd4j_max<T>(static_cast<T>(0.0f), nd4j::math::nd4j_tanh<T>(d1));
}
};
template<typename T>
class RectifiedTanhDerivative {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return d1 > static_cast<T>(0.0f) ? nd4j::math::nd4j_tanhderivative<T>(d1) : static_cast<T>(0.0f);
}
};
template<typename T>
class ATanh {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return nd4j::math::nd4j_atanh<T>(d1);
}
};
template<typename T>
class TanhDerivative {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return nd4j::math::nd4j_tanhderivative<T>(d1);
}
};
template<typename T>
class Cube {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return d1 * d1 * d1;
}
};
template<typename T>
class CubeDerivative {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return 3 * d1 * d1;
}
};
template<typename T>
class ACos {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return nd4j::math::nd4j_acos<T>(d1);
}
};
template<typename T>
class ASinh {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return nd4j::math::nd4j_asinh<T>(d1);
}
};
template<typename T>
class ASinhDerivative {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return static_cast<T>(1.f) / (nd4j::math::nd4j_sqrt(nd4j::math::nd4j_pow(d1, static_cast<T>(2.f)) + static_cast<T>(1.f)));
}
};
template<typename T>
class ACosh {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return nd4j::math::nd4j_acosh<T>(d1);
}
};
template<typename T>
class ACoshDerivative {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return static_cast<T>(1.f) / (nd4j::math::nd4j_sqrt(d1 - static_cast<T>(1.f)) * nd4j::math::nd4j_sqrt(d1 + static_cast<T>(1.f)));
}
};
template<typename T>
class Ones {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return static_cast<T>(1.0f);
}
};
template<typename T>
class SoftSign {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return nd4j::math::nd4j_softsign<T>(d1);
}
};
template<typename T>
class SoftSignDerivative {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return nd4j::math::nd4j_softsignderivative<T>(d1);
}
};
template<typename T>
class MatchCondition {
public:
no_op_exec_special
no_op_exec_special_cuda
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
op_def static T startingValue(const T *input) {
return static_cast<T>(0.0f);
}
op_def static T merge(T old, T opOutput, T *extraParams) {
return old + opOutput;
}
op_def static T update(T old, T opOutput, T *extraParams) {
return old + opOutput;
}
// this op return 1.0 if condition met, 0.0 otherwise
op_def static T op(T d1, T *extraParams) {
T compare = extraParams[0];
T eps = extraParams[1];
auto mode = static_cast<int>(extraParams[2]);
//nd4j_printf("value: %f; comp: %f; eps: %f; mode: %i;\n", d1, compare, eps, mode);
switch (mode) {
case 0: // equals
return nd4j::math::nd4j_abs<T>(d1 - compare) <= eps ? 1.0f : 0.0f;
case 1: // not equals
return nd4j::math::nd4j_abs<T>(d1 - compare) > eps ? 1.0f : 0.0f;
case 2: // less_than
return d1 < compare ? 1.0f : 0.0f;
case 3: // greater_than
return d1 > compare ? 1.0f : 0.0f;
case 4: // less_or_equals_than
return d1 <= compare ? 1.0f : 0.0f;
case 5: // greater_or_equals_than
return d1 >= compare ? 1.0f : 0.0f;
case 6: // abs_less_than
return nd4j::math::nd4j_abs<T>(d1) < compare ? 1.0f : 0.0f;
case 7: // abs_greater_than
return nd4j::math::nd4j_abs<T>(d1) > compare ? 1.0f : 0.0f;
case 8: // is inf
return nd4j::math::nd4j_isinf(d1) ? 1.0f : 0.0f;
case 9: // is nan
return nd4j::math::nd4j_isnan(d1) ? 1.0f : 0.0f;
case 10:
return (d1 == compare) ? 1.0f : 0.0f;
case 11:
return (d1 != compare) ? 1.0f : 0.0f;
case 12: // abs_greater_or_equals_than
return nd4j::math::nd4j_abs<T>(d1) >= compare ? 1.0f : 0.0f;
case 13: // abs_less_or_equals_than
return nd4j::math::nd4j_abs<T>(d1) <= compare ? 1.0f : 0.0f;
default:
printf("Undefined match condition: [%i]\n", mode);
}
return d1;
}
op_def static T postProcess(T reduction, Nd4jLong n, T *extraParams) {
return reduction;
}
};
template<typename T>
class ELU {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return nd4j::math::nd4j_elu<T>(d1);
}
};
template<typename T>
class ELUDerivative {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return nd4j::math::nd4j_eluderivative<T>(d1);
}
};
template<typename T>
class RELU {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return d1 < params[0] ? params[0] : d1;
}
};
template<typename T>
class RELU6 {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
T relu = d1 < params[0] ? params[0] : d1;
return relu < static_cast<T>(6.f) ? relu : static_cast<T>(6.f);
}
};
template<typename T>
class LeakyRELU {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return nd4j::math::nd4j_leakyrelu<T>(d1, params[0]);
}
};
template<typename T>
class SELU {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return d1 > static_cast<T>(0.0f) ? static_cast<T>(SELU_LAMBDA) * d1 : static_cast<T>(SELU_LAMBDA) * (static_cast<T>(SELU_ALPHA) * nd4j::math::nd4j_exp<T>(d1) - static_cast<T>(SELU_ALPHA));
}
};
template<typename T>
class SELUDerivative {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return d1 > static_cast<T>(0.0f) ? static_cast<T>(SELU_LAMBDA) : static_cast<T>(SELU_ALPHA) * static_cast<T>(SELU_LAMBDA) * nd4j::math::nd4j_exp<T>(d1);
}
};
template<typename T>
class LeakyRELUDerivative {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
if (d1 >= static_cast<T>(0.0f))
return static_cast<T>(1.0f);
else
return params[0];
}
};
template<typename T>
class ASin {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return nd4j::math::nd4j_asin<T>(d1);
}
};
template<typename T>
class Sinh {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return nd4j::math::nd4j_sinh<T>(d1);
}
};
template<typename T>
class SinhDerivative {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return nd4j::math::nd4j_cosh<T>(d1);
}
};
template<typename T>
class Cosh {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return nd4j::math::nd4j_cosh<T>(d1);
}
};
template<typename T>
class Tan {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return nd4j::math::nd4j_tan<T>(d1);
}
};
template<typename T>
class TanDerivative {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return static_cast<T>(1.0f) / nd4j::math::nd4j_pow<T>(nd4j::math::nd4j_cos<T>(d1), static_cast<T>(2.0f));
}
};
template<typename T>
class ATan {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return nd4j::math::nd4j_atan(d1);
}
};
template<typename T>
class Atan2 {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T d2) {
return nd4j::math::nd4j_atan2<T>(d2, d1);
}
op_def static T op(T d1, T d2, T *params) {
return nd4j::math::nd4j_atan2<T>(d2, d1);
}
// op for MetaOps
op_def static T op(T d1, T *params) {
return nd4j::math::nd4j_atan2<T>(params[0], d1);
}
};
template<typename T>
class Identity {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return d1;
}
};
template<typename T>
class Stabilize {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
T k = params[0];
if (d1 * k > static_cast<T>(- MIN_CUTFOFF))
return static_cast<T>(- MIN_CUTFOFF) / k;
else if (d1 * k < static_cast<T>(MIN_CUTFOFF))
return static_cast<T>(MIN_CUTFOFF) / k;
return d1;
}
};
template<typename T>
class Step {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return (d1 > params[0] ? static_cast<T>(1.0f) : static_cast<T>(0.0f));
}
};
template<typename T>
class OneMinus {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
return static_cast<T>(1.0f) - d1;
}
};
template<typename T>
class Sum {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
op_def static T startingValue(const T *input) {
return static_cast<T>(0.0f);
}
op_def static T merge(T old, T opOutput, T *extraParams) {
return opOutput + old;
}
op_def static T update(T old, T opOutput, T *extraParams) {
return opOutput + old;
}
op_def static T op(T d1, T *extraParams) {
return d1;
}
op_def static T postProcess(T reduction, Nd4jLong n, T *extraParams) {
return reduction;
}
};
template<typename T>
class ShannonEntropy {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
op_def static T startingValue(const T *input) {
return static_cast<T>(0.0f);
}
op_def static T merge(T old, T opOutput, T *extraParams) {
return opOutput + old;
}
op_def static T update(T old, T opOutput, T *extraParams) {
return opOutput + old;
}
op_def static T op(T d1, T *extraParams) {
return nd4j::math::nd4j_pow<T>(d1, static_cast<T>(2.0f)) * nd4j::math::nd4j_log<T>(nd4j::math::nd4j_pow<T>(d1, static_cast<T>(2.0f)));
}
op_def static T postProcess(T reduction, Nd4jLong n, T *extraParams) {
return -reduction;
}
};
template<typename T>
class LogEntropy {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
op_def static T startingValue(const T *input) {
return static_cast<T>(0.0f);
}
op_def static T merge(T old, T opOutput, T *extraParams) {
return opOutput + old;
}
op_def static T update(T old, T opOutput, T *extraParams) {
return opOutput + old;
}
op_def static T op(T d1, T *extraParams) {
return d1 * nd4j::math::nd4j_log<T>(d1);
}
op_def static T postProcess(T reduction, Nd4jLong n, T *extraParams) {
//entropy is -sum(p(x) * log(p(x))); log entropy is log of this
return nd4j::math::nd4j_log<T>(-reduction);
}
};
template<typename T>
class Entropy {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
op_def static T startingValue(const T *input) {
return static_cast<T>(0.0f);
}
op_def static T merge(T old, T opOutput, T *extraParams) {
return opOutput + old;
}
op_def static T update(T old, T opOutput, T *extraParams) {
return opOutput + old;
}
op_def static T op(T d1, T *extraParams) {
return d1 * nd4j::math::nd4j_log<T>(d1);
}
op_def static T postProcess(T reduction, Nd4jLong n, T *extraParams) {
return -reduction; //entropy is -sum(p(x) * log(p(x)))
}
};
template<typename T>
class ASum {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
op_def static T startingValue(const T *input) {
return static_cast<T>(0.0f);
}
op_def static T merge(T old, T opOutput, T *extraParams) {
return nd4j::math::nd4j_abs<T>(opOutput) + nd4j::math::nd4j_abs<T>(old);
}
op_def static T update(T old, T opOutput, T *extraParams) {
return nd4j::math::nd4j_abs<T>(opOutput) + nd4j::math::nd4j_abs<T>(old);
}
op_def static T op(T d1, T *extraParams) {
return nd4j::math::nd4j_abs<T>(d1);
}
op_def static T postProcess(T reduction, Nd4jLong n, T *extraParams) {
return nd4j::math::nd4j_abs<T>(reduction);
}
};
template<typename T>
class CountNonZero {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
op_def static T startingValue(const T *input) {
return static_cast<T>(0.0f);
}
op_def static T merge(T old, T opOutput, T *extraParams) {
return opOutput + old;
}
op_def static T update(T old, T opOutput, T *extraParams) {
return opOutput + old;
}
op_def static T op(T d1, T *extraParams) {
return d1 == static_cast<T>(0.0f) ? static_cast<T>(0.0f) : static_cast<T>(1.0f);
}
op_def static T postProcess(T reduction, Nd4jLong n, T *extraParams) {
return reduction;
}
};
template<typename T>
class CountZero {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
op_def static T startingValue(const T *input) {
return static_cast<T>(0.0f);
}
op_def static T merge(T old, T opOutput, T *extraParams) {
return opOutput + old;
}
op_def static T update(T old, T opOutput, T *extraParams) {
return opOutput + old;
}
op_def static T op(T d1, T *extraParams) {
return d1 == static_cast<T>(0.0f) ? static_cast<T>(1.0f) : static_cast<T>(0.0f);
}
op_def static T postProcess(T reduction, Nd4jLong n, T *extraParams) {
return reduction;
}
};
template<typename T>
class Prod {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
op_def static T startingValue(const T *input) {
return static_cast<T>(1.0f);
}
op_def static T merge(T old, T opOutput, T *extraParams) {
return opOutput * old;
}
op_def static T update(T old, T opOutput, T *extraParams) {
return opOutput * old;
}
op_def static T op(T d1, T *extraParams) {
return d1;
}
op_def static T postProcess(T reduction, Nd4jLong n, T *extraParams) {
return reduction;
}
};
template<typename T>
class Any {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
op_def static T startingValue(const T *input) {
return static_cast<T>(0.0f);
}
op_def static T merge(T old, T opOutput, T *extraParams) {
return opOutput + old;
}
op_def static T update(T old, T opOutput, T *extraParams) {
return opOutput + old;
}
op_def static T op(T d1, T *extraParams) {
return d1;
}
op_def static T postProcess(T reduction, Nd4jLong n, T *extraParams) {
return reduction > static_cast<T>(0.0f) ? static_cast<T>(1.0f) : static_cast<T>(0.0f) ;
}
};
template<typename T>
class All {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
op_def static T startingValue(const T *input) {
return static_cast<T>(1.0f);
}
op_def static T merge(T old, T opOutput, T *extraParams) {
return opOutput * old;
}
op_def static T update(T old, T opOutput, T *extraParams) {
return opOutput * old;
}
op_def static T op(T d1, T *extraParams) {
return d1;
}
op_def static T postProcess(T reduction, Nd4jLong n, T *extraParams) {
return reduction > static_cast<T>(0.0f) ? static_cast<T>(1.0f) : static_cast<T>(0.0f);
}
};
template<typename T>
class Mean {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
op_def static T startingValue(const T *input) {
return static_cast<T>(0.0f);
}
op_def static T merge(T old, T opOutput, T *extraParams) {
return opOutput + old;
}
op_def static T update(T old, T opOutput, T *extraParams) {
return opOutput + old;
}
op_def static T op(T d1, T *extraParams) {
return d1;
}
op_def static T postProcess(T reduction, Nd4jLong n, T *extraParams) {
return reduction / (int) n;
}
};
template<typename T>
class AMean {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
op_def static T startingValue(const T *input) {
return static_cast<T>(0.0f);
}
op_def static T merge(T old, T opOutput, T *extraParams) {
return nd4j::math::nd4j_abs<T>(opOutput) + nd4j::math::nd4j_abs<T>(old);
}
op_def static T update(T old, T opOutput, T *extraParams) {
return nd4j::math::nd4j_abs<T>(opOutput) + nd4j::math::nd4j_abs<T>(old);
}
op_def static T op(T d1, T *extraParams) {
return nd4j::math::nd4j_abs<T>(d1);
}
op_def static T postProcess(T reduction, Nd4jLong n, T *extraParams) {
return nd4j::math::nd4j_abs<T>(reduction) / static_cast<T>(n);
}
};
template<typename T>
class Max {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
op_def static T startingValue(const T *input) {
return input[0];
}
op_def static T merge(T old, T opOutput, T *extraParams) {
return nd4j::math::nd4j_max<T>(old, opOutput);
}
op_def static T update(T old, T opOutput, T *extraParams) {
return nd4j::math::nd4j_max<T>(opOutput, old);
}
op_def static T op(T d1, T d2, T *params) {
return nd4j::math::nd4j_max<T>(d1, d2);
}
op_def static T op(T d1, T d2) {
return nd4j::math::nd4j_max<T>(d1, d2);
}
// FIXME: this signature overlaps with MetaOp
op_def static T op(T d1, T *extraParams) {
return d1;
}
op_def static T postProcess(T reduction, Nd4jLong n, T *extraParams) {
return reduction;
}
};
template<typename T>
class AMax {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
op_def static T startingValue(const T *input) {
return input[0];
}
op_def static T merge(T old, T opOutput, T *extraParams) {
return nd4j::math::nd4j_max<T>(nd4j::math::nd4j_abs<T>(old), nd4j::math::nd4j_abs<T>(opOutput));
}
op_def static T update(T old, T opOutput, T *extraParams) {
return nd4j::math::nd4j_max<T>(nd4j::math::nd4j_abs<T>(opOutput), nd4j::math::nd4j_abs<T>(old));
}
op_def static T op(T d1, T d2, T *params) {
return nd4j::math::nd4j_max<T>(nd4j::math::nd4j_abs<T>(d1), nd4j::math::nd4j_abs<T>(d2));
}
op_def static T op(T d1, T d2) {
return nd4j::math::nd4j_abs<T>(d1) > nd4j::math::nd4j_abs<T>(d2) ? d1 : d2;
}
// FIXME: this signature overlaps with MetaOp
op_def static T op(T d1, T *extraParams) {
return nd4j::math::nd4j_abs<T>(d1);
}
op_def static T postProcess(T reduction, Nd4jLong n, T *extraParams) {
return nd4j::math::nd4j_abs<T>(reduction);
}
};
template<typename T>
class AMin {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
op_def static T startingValue(const T *input) {
return input[0];
}
op_def static T merge(T old, T opOutput, T *extraParams) {
return nd4j::math::nd4j_min<T>(nd4j::math::nd4j_abs<T>(old), nd4j::math::nd4j_abs<T>(opOutput));
}
op_def static T update(T old, T opOutput, T *extraParams) {
return nd4j::math::nd4j_min<T>(nd4j::math::nd4j_abs<T>(opOutput), nd4j::math::nd4j_abs<T>(old));
}
op_def static T op(T d1, T d2, T *params) {
return nd4j::math::nd4j_min(nd4j::math::nd4j_abs<T>(d1), nd4j::math::nd4j_abs<T>(d2));
}
op_def static T op(T d1, T d2) {
return nd4j::math::nd4j_abs<T>(d1) < nd4j::math::nd4j_abs<T>(d2) ? d1 : d2;
}
// FIXME: this signature overlaps with MetaOp
op_def static T op(T d1, T *extraParams) {
return nd4j::math::nd4j_abs<T>(d1);
}
op_def static T postProcess(T reduction, Nd4jLong n, T *extraParams) {
return nd4j::math::nd4j_abs<T>(reduction);
}
};
template<typename T>
class Min {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
op_def static T startingValue(const T *input) {
return input[0];
}
op_def static T merge(T old, T opOutput, T *extraParams) {
return nd4j::math::nd4j_min<T>(old, opOutput);
}
op_def static T update(T old, T opOutput, T *extraParams) {
return nd4j::math::nd4j_min<T>(opOutput, old);
}
op_def static T op(T d1, T d2, T *params) {
return nd4j::math::nd4j_min(d1, d2);
}
op_def static T op(T d1, T d2) {
return nd4j::math::nd4j_min(d1, d2);
}
// FIXME: this signature overlaps with MetaOp
op_def static T op(T d1, T *extraParams) {
return d1;
}
op_def static T postProcess(T reduction, Nd4jLong n, T *extraParams) {
return reduction;
}
};
template<typename T>
class Norm1 {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
op_def static T startingValue(const T *input) {
return static_cast<T>(0.0f);
}
op_def static T merge(T old, T opOutput, T *extraParams) {
return opOutput + old;
}
op_def static T update(T old, T opOutput, T *extraParams) {
return opOutput + old;
}
op_def static T op(T d1, T *extraParams) {
return nd4j::math::nd4j_abs<T>(d1);
}
op_def static T postProcess(T reduction, Nd4jLong n, T *extraParams) {
return reduction;
}
};
template<typename T>
class Norm2 {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
op_def static T startingValue(const T *input) {
return static_cast<T>(0.0f);
}
op_def static T merge(T old, T opOutput, T *extraParams) {
return opOutput + old;
}
op_def static T update(T old, T opOutput, T *extraParams) {
return opOutput + old;
}
op_def static T postProcess(T reduction, Nd4jLong n, T *extraParams) {
return nd4j::math::nd4j_sqrt<T>(reduction);
}
op_def static T op(T d1, T *extraParams) {
return d1 * d1;
}
};
template<typename T>
class SquaredNorm {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
op_def static T startingValue(const T *input) {
return static_cast<T>(0.0f);
}
op_def static T merge(T old, T opOutput, T *extraParams) {
return opOutput + old;
}
op_def static T update(T old, T opOutput, T *extraParams) {
return opOutput + old;
}
op_def static T op(T d1, T *extraParams) {
return d1 * d1;
}
op_def static T postProcess(T reduction, Nd4jLong n, T *extraParams) {
return reduction;
}
};
template<typename T>
class NormFrobenius {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
op_def static T startingValue(const T *input) {
return static_cast<T>(0.0f);
}
op_def static T merge(T old, T opOutput, T *extraParams) {
return opOutput + old;
}
op_def static T update(T old, T opOutput, T *extraParams) {
return opOutput + old;
}
op_def static T op(T d1, T *extraParams) {
T v = nd4j::math::nd4j_abs(d1);
return v * v;
}
op_def static T postProcess(T reduction, Nd4jLong n, T *extraParams) {
return nd4j::math::nd4j_sqrt<T>(reduction);
}
};
template<typename T>
class NormP {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
op_def static T startingValue(const T *input) {
return static_cast<T>(0.0f);
}
op_def static T merge(T old, T opOutput, T *extraParams) {
return opOutput + old;
}
op_def static T update(T old, T opOutput, T *extraParams) {
return opOutput + old;
}
op_def static T op(T d1, T *extraParams) {
return nd4j::math::nd4j_pow(nd4j::math::nd4j_abs(d1), extraParams[0]);
}
op_def static T postProcess(T reduction, Nd4jLong n, T *extraParams) {
return nd4j::math::nd4j_pow(reduction, static_cast<T>(1.0f) / extraParams[0]);
}
};
template<typename T>
class NormMax {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
op_def static T startingValue(const T *input) {
return static_cast<T>(0.0f);
}
op_def static T merge(T old, T opOutput, T *extraParams) {
return opOutput + old;
}
op_def static T update(T old, T opOutput, T *extraParams) {
return nd4j::math::nd4j_max<T>(nd4j::math::nd4j_abs<T>(old),
nd4j::math::nd4j_abs<T>(opOutput));
}
op_def static T op(T d1, T *extraParams) {
return d1;
}
op_def static T postProcess(T reduction, Nd4jLong n, T *extraParams) {
return nd4j::math::nd4j_max<T>(nd4j::math::nd4j_abs<T>(reduction),
nd4j::math::nd4j_abs<T>(reduction));
}
};
template<typename T>
class Variance {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
op_def static T startingValue(const T *input) {
return static_cast<T>(0.0f);
}
op_def static T merge(T old, T opOutput, T *extraParams) {
return old + opOutput;
}
op_def static T update(T old, T opOutput, T *extraParams) {
return old + opOutput;
}
op_def static T op(T d1, T *extraParams) {
T mean = extraParams[0];
T ret = d1 - mean;
return ret * ret;
}
op_def static T postProcess(T reduction, Nd4jLong n, T *extraParams) {
// T bias = extraParams[1];
// return (reduction - (nd4j::math::nd4j_pow<T>(bias, static_cast<T>(2.0f)) / static_cast<T>(n))) / (n - 1)
return reduction / static_cast<T>(n - 1);
}
};
/**
* Standard deviation of a buffer
*/
template<typename T>
class StandardDeviation {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
op_def static T startingValue(const T *input) {
return static_cast<T>(0.0f);
}
op_def static T merge(T old, T opOutput, T *extraParams) {
return old + opOutput;
}
op_def static T update(T old, T opOutput, T *extraParams) {
return old + opOutput;
}
op_def static T op(T d1, T *extraParams) {
T mean = extraParams[0];
T ret = d1 - mean;
return ret * ret;
}
op_def static T postProcess(T reduction, Nd4jLong n, T *extraParams) {
T ret = Variance<T>::postProcess(reduction, n, extraParams);
T sqrtRet = nd4j::math::nd4j_sqrt<T>(ret);
return sqrtRet;
}
};
template<typename T>
class CosineSimilarity {
public:
static const int extraParamsLen = 2;
op_def static T *generateExtraParams() {
//T *extraParams = new T[2];
return nullptr;
}
op_def static void finalizeExtraParams(T *extraParams) {
//delete[] extraParams;
}
op_def static T startingValue(T *input) {
return static_cast<T>(0.0f);
}
op_def static T postProcess(T reduction, Nd4jLong n, T *extraParams) {
return reduction / (nd4j::math::nd4j_sqrt<T>(extraParams[0]) * nd4j::math::nd4j_sqrt<T>(extraParams[1]));
}
op_def static T op(T d1, T d2, T *extraParams) {
extraParams[0] += d1 * d1;
extraParams[1] += d2 * d2;
return (d1 * d2);
}
op_def static void aggregateExtraParams(T *extraParamsTotal, T *extraParamsLocal) {
extraParamsTotal[0] += extraParamsLocal[0];
extraParamsTotal[1] += extraParamsLocal[1];
}
#ifdef __CUDACC__
static _CUDA_D inline T opAtomic(T d1, T d2, T *extraParams) {
nd4j::math::atomics::nd4j_atomicAdd(&extraParams[0],static_cast<T>(d1 * d1));
nd4j::math::atomics::nd4j_atomicAdd(&extraParams[1],static_cast<T>(d2 * d2));
return (d1 * d2);
}
#endif
op_def static T update(T old, T opOutput, T *extraParams) {
return old + opOutput;
}
op_def static T merge(T old, T opOutput, T *extraParams) {
return update(old, opOutput, extraParams);
}
};
template<typename T>
class JaccardDistance {
public:
static const int extraParamsLen = 2;
op_def static T *generateExtraParams() {
//T *extraParams = new T[2];
return nullptr;
}
op_def static void finalizeExtraParams(T *extraParams) {
//delete[] extraParams;
}
op_def static T startingValue(T *input) {
return static_cast<T>(0.0f);
}
op_def static T postProcess(T reduction, Nd4jLong n, T *extraParams) {
// num / denom
return (static_cast<T>(1.0f)) - (extraParams[0] / extraParams[1]);
}
op_def static T num(T d1, T d2) {
return nd4j::math::nd4j_min<T>(d1, d2);
}
op_def static T denom(T d1, T d2) {
return nd4j::math::nd4j_max<T>(d1, d2);
}
op_def static T op(T d1, T d2, T *extraParams) {
extraParams[0] += num(d1, d2);
extraParams[1] += denom(d1, d2);
return static_cast<T>(0.0f);
}
op_def static void aggregateExtraParams(T *extraParamsTotal, T *extraParamsLocal) {
extraParamsTotal[0] += extraParamsLocal[0];
extraParamsTotal[1] += extraParamsLocal[1];
}
#ifdef __CUDACC__
__device__
static inline T opAtomic(T d1, T d2, T *extraParams) {
nd4j::math::atomics::nd4j_atomicAdd(&extraParams[0],num(d1, d2));
nd4j::math::atomics::nd4j_atomicAdd(&extraParams[1], denom(d1, d2));
return static_cast<T>(0.0f);
}
#endif
op_def static T update(T old, T opOutput, T *extraParams) {
return old + opOutput;
}
op_def static T merge(T old, T opOutput, T *extraParams) {
return update(old, opOutput, extraParams);
}
};
template<typename T>
class SimpleHammingDistance {
public:
static const int extraParamsLen = 0;
op_def static T *generateExtraParams() {
//T *extraParams = new T[2];
return nullptr;
}
op_def static void finalizeExtraParams(T *extraParams) {
//delete[] extraParams;
}
op_def static T startingValue(T *input) {
return static_cast<T>(0.0f);
}
op_def static T postProcess(T reduction, Nd4jLong n, T *extraParams) {
return static_cast<T>(reduction / n);
}
op_def static T op(T d1, T d2, T *extraParams) {
return (d1 == d2) ? static_cast<T>(0.0f) : static_cast<T>(1.0f);
}
op_def static void aggregateExtraParams(T *extraParamsTotal, T *extraParamsLocal) {
}
#ifdef __CUDACC__
__device__
static inline T opAtomic(T d1, T d2, T *extraParams) {
return op(d1, d2, extraParams);
}
#endif
op_def static T update(T old, T opOutput, T *extraParams) {
return old + opOutput;
}
op_def static T merge(T old, T opOutput, T *extraParams) {
return update(old, opOutput, extraParams);
}
};
template<typename T>
class CosineDistance {
public:
static const int extraParamsLen = 2;
op_def static T *generateExtraParams() {
//T *extraParams = new T[2];
return nullptr;
}
op_def static void finalizeExtraParams(T *extraParams) {
//delete[] extraParams;
}
op_def static T startingValue(T *input) {
return static_cast<T>(0.0f);
}
op_def static T postProcess(T reduction, Nd4jLong n, T *extraParams) {
return (static_cast<T>(1.0f)) - (reduction / (nd4j::math::nd4j_sqrt<T>(extraParams[0]) * nd4j::math::nd4j_sqrt<T>(extraParams[1])));
}
op_def static T op(T d1, T d2, T *extraParams) {
extraParams[0] += nd4j::math::nd4j_abs<T>(d1) * nd4j::math::nd4j_abs<T>(d1);
extraParams[1] += nd4j::math::nd4j_abs<T>(d2) * nd4j::math::nd4j_abs<T>(d2);
return (d1 * d2);
}
op_def static void aggregateExtraParams(T *extraParamsTotal, T *extraParamsLocal) {
extraParamsTotal[0] += extraParamsLocal[0];
extraParamsTotal[1] += extraParamsLocal[1];
}
#ifdef __CUDACC__
static _CUDA_D inline T opAtomic(T d1, T d2, T *extraParams) {
nd4j::math::atomics::nd4j_atomicAdd(&extraParams[0], nd4j::math::nd4j_abs<T>(d1) * nd4j::math::nd4j_abs<T>(d1));
nd4j::math::atomics::nd4j_atomicAdd(&extraParams[1], nd4j::math::nd4j_abs<T>(d2) * nd4j::math::nd4j_abs<T>(d2));
return (d1 * d2);
}
#endif
op_def static T update(T old, T opOutput, T *extraParams) {
return old + opOutput;
}
op_def static T merge(T old, T opOutput, T *extraParams) {
return update(old, opOutput, extraParams);
}
};
/**
* Dot product between 2 arrays
*/
template<typename T>
class Dot {
public:
static const int extraParamsLen = 0;
op_def static T * generateExtraParams() {
return nullptr;
}
op_def static void finalizeExtraParams(T *extraParamsRef) {
//no-op
//delete[] * extraParamsRef;
}
op_def static T startingValue(T *input) {
return static_cast<T>(0.0f);
}
op_def static T postProcess(T reduction, Nd4jLong n, T *extraParamsRef) {
return reduction;
}
op_def static T op(T d1, T d2, T *extraParamsRef) {
return d1 * d2;
}
#ifdef __CUDACC__
__device__
static inline T opAtomic(T d1, T d2, T *extraParamsRef) {
return op(d1, d2, extraParamsRef);
}
#endif
op_def static T update(T old, T opOutput, T *extraParamsRef) {
return opOutput + old;
}
op_def static T merge(T old, T opOutput, T *extraParamsRef) {
return update(old, opOutput, extraParamsRef);
}
op_def static void aggregateExtraParams(T *extraParamsTotal, T *extraParamsLocal) {}
};
/**
* Op to check equality within arrays
*/
template<typename T>
class EqualsWithEps {
public:
static const int extraParamsLen = 0;
op_def static T * generateExtraParams() {
return nullptr;
}
op_def static void finalizeExtraParams(T *extraParamsRef) {
//no-op
}
op_def static T startingValue(T *input) {
return static_cast<T>(0.0f);
}
op_def static T postProcess(T reduction, Nd4jLong n, T *extraParamsRef) {
return reduction;
}
op_def static T op(T d1, T d2, T *extraParamsRef) {
T eps = extraParamsRef[2];
T diff = nd4j::math::nd4j_abs<T>(d1 - d2);
// works well except in the range of very large numbers
if (diff <= eps)
return static_cast<T>(0.f);
// Knuth approach
// works well except in the range of very small numbers
if (diff <= nd4j::math::nd4j_max(nd4j::math::nd4j_abs(d1), nd4j::math::nd4j_abs(d2)) * eps)
return static_cast<T>(0.f);
return static_cast<T>(1.f);
}
#ifdef __CUDACC__
__device__
static inline T opAtomic(T d1, T d2, T *extraParamsRef) {
return op(d1, d2, extraParamsRef);
}
#endif
op_def static T update(T old, T opOutput, T *extraParamsRef) {
return opOutput + old;
}
op_def static T merge(T old, T opOutput, T *extraParamsRef) {
return update(old, opOutput, extraParamsRef);
}
op_def static void aggregateExtraParams(T *extraParamsTotal, T *extraParamsLocal) {}
};
template<typename T>
class EuclideanDistance {
public:
static const int extraParamsLen = 0;
op_def static T * generateExtraParams() {
return nullptr;
}
op_def static void finalizeExtraParams(T *extraParamsRef) {
//no-op
}
op_def static T startingValue(T *input) {
return static_cast<T>(0.0f);
}
op_def static T postProcess(T reduction, Nd4jLong n, T *extraParamsRef) {
return nd4j::math::nd4j_sqrt<T>(reduction);
}
op_def static T op(T d1, T d2, T *extraParamsRef) {
T ret = d1 - d2;
return ret * ret;
}
#ifdef __CUDACC__
__device__
static inline T opAtomic(T d1, T d2, T *extraParamsRef) {
return op(d1, d2, extraParamsRef);
}
#endif
op_def static T update(T old, T opOutput, T *extraParamsRef) {
return opOutput + old;
}
op_def static T merge(T old, T opOutput, T *extraParamsRef) {
return update(old, opOutput, extraParamsRef);
}
op_def static void aggregateExtraParams(T *extraParamsTotal, T *extraParamsLocal) {}
};
template<typename T>
class ManhattanDistance {
public:
static const int extraParamsLen = 0;
op_def static T * generateExtraParams() {
return nullptr;
}
op_def static void finalizeExtraParams(T *extraParamsRef) {
//no-op
}
op_def static T startingValue(T *input) {
return static_cast<T>(0.0f);
}
op_def static T postProcess(T reduction, Nd4jLong n, T *extraParamsRef) {
return reduction;
}
op_def static T op(T d1, T d2, T *extraParamsRef) {
return nd4j::math::nd4j_abs<T>(d1 - d2);
}
op_def static T update(T old, T opOutput, T *extraParamsRef) {
return old + opOutput;
}
op_def static void aggregateExtraParams(T *extraParamsTotal, T *extraParamsLocal) {
}
#ifdef __CUDACC__
__device__
static inline T opAtomic(T d1, T d2, T *extraParamsRef) {
return op(d1, d2, extraParamsRef);
}
#endif
#ifndef __clang__
#pragma omp declare simd uniform(extraParamsRef)
#endif
op_def static T merge(T old, T opOutput, T *extraParamsRef) {
return update(old, opOutput, extraParamsRef);
}
};
template<typename T>
class IndexAbsoluteMax {
public:
#ifdef __CUDACC__
__host__ __device__
#endif
static inline functions::indexreduce::IndexValue<T> op(functions::indexreduce::IndexValue<T> val, T *extraParams) {
return nd4j::math::nd4j_abs<T>(val);
}
#ifdef __CUDACC__
__host__ __device__
#endif
static inline functions::indexreduce::IndexValue<T> update(
functions::indexreduce::IndexValue<T> old,
functions::indexreduce::IndexValue<T> opOutput, T *extraParams) {
opOutput.value = nd4j::math::nd4j_abs<T>(opOutput.value);
old.value = nd4j::math::nd4j_abs<T>(old.value);
if (opOutput.value > old.value)
return opOutput;
#ifdef __CUDACC__
// workaround for cuda race condition at merge phase
else if (opOutput.value == old.value && opOutput.index < old.index)
return opOutput;
#elif defined(__GNUC__)
#endif
return old;
}
#ifdef __CUDACC__
__host__ __device__
#endif
static inline functions::indexreduce::IndexValue<T> merge(
functions::indexreduce::IndexValue<T> f1,
functions::indexreduce::IndexValue<T> f2, T *extraParams) {
if (nd4j::math::nd4j_abs<T>(f1.value) > nd4j::math::nd4j_abs<T>(f2.value))
return f2;
return f1;
}
#ifdef __CUDACC__
__host__ __device__
#endif
static inline functions::indexreduce::IndexValue<T> postProcess(
functions::indexreduce::IndexValue<T> reduction, int n, int xOffset,
T *dx, int incx, T *extraParams, T *result) {
return reduction;
}
#ifdef __CUDACC__
__host__ __device__
#endif
static inline T startingValue(T *input) {
return MIN_FLOAT;
}
#ifdef __CUDACC__
__host__ __device__
#endif
static inline functions::indexreduce::IndexValue<T> startingIndexValue(T *input) {
functions::indexreduce::IndexValue<T> local;
local.value = startingValue(input);
local.index = 0;
return local;
}
#ifdef __CUDACC__
__host__ __device__
#endif
static inline functions::indexreduce::IndexValue<T> op(functions::indexreduce::IndexValue<T> d1,
functions::indexreduce::IndexValue<T> d2, T *extraParams) {
return d1;
}
};
template<typename T>
class FirstIndex {
public:
#ifdef __CUDACC__
__host__ __device__
#endif
static inline functions::indexreduce::IndexValue<T> op(functions::indexreduce::IndexValue<T> val, T *extraParams) {
return val;
}
#ifdef __CUDACC__
__host__ __device__
#endif
static functions::indexreduce::IndexValue<T> update(
functions::indexreduce::IndexValue<T> old,
functions::indexreduce::IndexValue<T> opOutput, T *extraParams) {
#ifdef __CUDACC__
if (opOutput.index < 0)
return old;
#endif
T res = simdOps::MatchCondition<T>::op(opOutput.value, extraParams);
//printf("res: %f; oldIdx: %i; newIdx: %i\n", res, old.index, opOutput.index);
if (res == static_cast<T>(0.0f))
return old;
if (old.index < 0)
return opOutput;
if (old.index > opOutput.index)
return opOutput;
return old;
}
#ifdef __CUDACC__
__host__ __device__
#endif
static inline T startingValue(T *input) {
return - nd4j::DataTypeUtils::max<T>();
}
#ifdef __CUDACC__
__host__ __device__
#endif
static inline functions::indexreduce::IndexValue<T> startingIndexValue(T *input) {
functions::indexreduce::IndexValue<T> local;
local.value = startingValue(input);
local.index = -1;
return local;
}
#ifdef __CUDACC__
__host__ __device__
#endif
static inline functions::indexreduce::IndexValue<T> op(functions::indexreduce::IndexValue<T> d1,
functions::indexreduce::IndexValue<T> d2, T *extraParams) {
return d1;
}
#ifdef __CUDACC__
__host__ __device__
#endif
static inline functions::indexreduce::IndexValue<T> merge(
functions::indexreduce::IndexValue<T> f1,
functions::indexreduce::IndexValue<T> f2, T *extraParams) {
if (f1.index > f2.index)
return f2;
return f1;
}
#ifdef __CUDACC__
__host__ __device__
#endif
static inline functions::indexreduce::IndexValue<T> postProcess(
functions::indexreduce::IndexValue<T> reduction, int n, int xOffset,
T *dx, int incx, T *extraParams, T *result) {
return reduction;
}
};
template<typename T>
class LastIndex {
public:
#ifdef __CUDACC__
__host__ __device__
#endif
static inline functions::indexreduce::IndexValue<T> op(functions::indexreduce::IndexValue<T> val, T *extraParams) {
return val;
}
#ifdef __CUDACC__
__host__ __device__
#endif
static functions::indexreduce::IndexValue<T> update(
functions::indexreduce::IndexValue<T> old,
functions::indexreduce::IndexValue<T> opOutput, T *extraParams) {
#ifdef __CUDACC__
if (opOutput.index < 0)
return old;
#endif
T res = simdOps::MatchCondition<T>::op(opOutput.value, extraParams);
if (res == static_cast<T>(0.0f))
return old;
if (old.index < 0)
return opOutput;
if (old.index < opOutput.index)
return opOutput;
return old;
}
#ifdef __CUDACC__
__host__ __device__
#endif
static inline T startingValue(T *input) {
return -nd4j::DataTypeUtils::max<T>();
}
#ifdef __CUDACC__
__host__ __device__
#endif
static inline functions::indexreduce::IndexValue<T> startingIndexValue(T *input) {
functions::indexreduce::IndexValue<T> local;
local.value = startingValue(input);
local.index = -1;
return local;
}
#ifdef __CUDACC__
__host__ __device__
#endif
static inline functions::indexreduce::IndexValue<T> op(functions::indexreduce::IndexValue<T> d1,
functions::indexreduce::IndexValue<T> d2, T *extraParams) {
return d1;
}
#ifdef __CUDACC__
__host__ __device__
#endif
static inline functions::indexreduce::IndexValue<T> merge(
functions::indexreduce::IndexValue<T> f1,
functions::indexreduce::IndexValue<T> f2, T *extraParams) {
if (f1.index < f2.index)
return f2;
return f1;
}
#ifdef __CUDACC__
__host__ __device__
#endif
static inline functions::indexreduce::IndexValue<T> postProcess(
functions::indexreduce::IndexValue<T> reduction, int n, int xOffset,
T *dx, int incx, T *extraParams, T *result) {
return reduction;
}
};
template<typename T>
class IndexMax {
public:
#ifdef __CUDACC__
__host__ __device__
#endif
static inline functions::indexreduce::IndexValue<T> op(functions::indexreduce::IndexValue<T> val, T *extraParams) {
return val;
}
#ifdef __CUDACC__
__host__ __device__
#endif
static functions::indexreduce::IndexValue<T> update(
functions::indexreduce::IndexValue<T> old,
functions::indexreduce::IndexValue<T> opOutput, T *extraParams) {
if (opOutput.value > old.value) {
return opOutput;
}
#ifdef __CUDACC__
// workaround for cuda race condition at merge phase
else if (opOutput.value == old.value && opOutput.index < old.index)
return opOutput;
#elif defined(__GNUC__)
#endif
return old;
}
#ifdef __CUDACC__
__host__ __device__
#endif
static inline functions::indexreduce::IndexValue<T> merge(
functions::indexreduce::IndexValue<T> f1,
functions::indexreduce::IndexValue<T> f2, T *extraParams) {
if (f1.value > f2.value)
return f2;
return f1;
}
#ifdef __CUDACC__
__host__ __device__
#endif
static inline functions::indexreduce::IndexValue<T> postProcess(
functions::indexreduce::IndexValue<T> reduction, int n, int xOffset,
T *dx, int incx, T *extraParams, T *result) {
return reduction;
}
#ifdef __CUDACC__
__host__ __device__
#endif
static inline T startingValue(T *input) {
return -nd4j::DataTypeUtils::max<T>();
}
#ifdef __CUDACC__
__host__ __device__
#endif
static inline functions::indexreduce::IndexValue<T> startingIndexValue(T *input) {
functions::indexreduce::IndexValue<T> local;
local.value = startingValue(input);
local.index = 0;
return local;
}
#ifdef __CUDACC__
__host__ __device__
#endif
static inline functions::indexreduce::IndexValue<T> op(functions::indexreduce::IndexValue<T> d1,
functions::indexreduce::IndexValue<T> d2, T *extraParams) {
return d1;
}
};
template<typename T>
class IndexAbsoluteMin {
public:
#ifdef __CUDACC__
__host__ __device__
#endif
static inline functions::indexreduce::IndexValue<T> op(
functions::indexreduce::IndexValue<T> val, T *extraParams) {
return val;
}
#ifdef __CUDACC__
__host__ __device__
#endif
static inline T startingValue(T *input) {
return nd4j::DataTypeUtils::max<T>();
}
#ifdef __CUDACC__
__host__ __device__
#endif
static inline functions::indexreduce::IndexValue<T> startingIndexValue(T *input) {
functions::indexreduce::IndexValue<T> local;
local.value = startingValue(input);
local.index = 0;
return local;
}
#ifdef __CUDACC__
__host__ __device__
#endif
static inline functions::indexreduce::IndexValue<T> update(
functions::indexreduce::IndexValue<T> old,
functions::indexreduce::IndexValue<T> opOutput, T *extraParams) {
opOutput.value = nd4j::math::nd4j_abs<T>(opOutput.value);
old.value = nd4j::math::nd4j_abs<T>(old.value);
if (opOutput.value < old.value)
return opOutput;
#ifdef __CUDACC__
// workaround for cuda race condition at merge phase
else if (opOutput.value == old.value && opOutput.index < old.index)
return opOutput;
#elif defined(__GNUC__)
#endif
return old;
}
#ifdef __CUDACC__
__host__ __device__
#endif
static inline functions::indexreduce::IndexValue<T> merge(
functions::indexreduce::IndexValue<T> f1,
functions::indexreduce::IndexValue<T> f2, T *extraParams) {
if (nd4j::math::nd4j_abs<T>(f1.value) < nd4j::math::nd4j_abs<T>(f2.value))
return f2;
return f1;
}
#ifdef __CUDACC__
__host__ __device__
#endif
static inline functions::indexreduce::IndexValue<T> postProcess(
functions::indexreduce::IndexValue<T> reduction, int n, int xOffset,
T *dx, int incx, T *extraParams, T *result) {
return reduction;
}
#ifdef __CUDACC__
__host__ __device__
#endif
static inline functions::indexreduce::IndexValue<T> op(functions::indexreduce::IndexValue<T> d1,
functions::indexreduce::IndexValue<T> d2, T *extraParams) {
return d1;
}
};
template<typename T>
class IndexMin {
public:
#ifdef __CUDACC__
__host__ __device__
#endif
static inline functions::indexreduce::IndexValue<T> op(
functions::indexreduce::IndexValue<T> val, T *extraParams) {
return val;
}
#ifdef __CUDACC__
__host__ __device__
#endif
static inline T startingValue(T *input) {
return nd4j::DataTypeUtils::max<T>();
}
#ifdef __CUDACC__
__host__ __device__
#endif
static inline functions::indexreduce::IndexValue<T> startingIndexValue(T *input) {
functions::indexreduce::IndexValue<T> local;
local.value = startingValue(input);
local.index = 0;
return local;
}
#ifdef __CUDACC__
__host__ __device__
#endif
static inline functions::indexreduce::IndexValue<T> update(
functions::indexreduce::IndexValue<T> old,
functions::indexreduce::IndexValue<T> opOutput, T *extraParams) {
if (opOutput.value < old.value)
return opOutput;
#ifdef __CUDACC__
// workaround for cuda race condition at merge phase
else if (opOutput.value == old.value && opOutput.index < old.index)
return opOutput;
#elif defined(__GNUC__)
#endif
return old;
}
#ifdef __CUDACC__
__host__ __device__
#endif
static inline functions::indexreduce::IndexValue<T> merge(
functions::indexreduce::IndexValue<T> f1,
functions::indexreduce::IndexValue<T> f2, T *extraParams) {
if (f1.value < f2.value)
return f2;
return f1;
}
#ifdef __CUDACC__
__host__ __device__
#endif
static inline functions::indexreduce::IndexValue<T> postProcess(
functions::indexreduce::IndexValue<T> reduction, int n, int xOffset,
T *dx, int incx, T *extraParams, T *result) {
return reduction;
}
#ifdef __CUDACC__
__host__ __device__
#endif
static inline functions::indexreduce::IndexValue<T> op(functions::indexreduce::IndexValue<T> d1,
functions::indexreduce::IndexValue<T> d2, T *extraParams) {
return d1;
}
};
template<typename T>
class SummaryStatsVariance {
public:
static _CUDA_HD inline T getValue(const bool biasCorrected, functions::summarystats::SummaryStatsData<T> val) {
if (biasCorrected) {
T ret = val.varianceBiasCorrected();
if (ret < static_cast<T>(0.0f))
return val.variance();
return ret;
}
return val.variance();
}
static _CUDA_HD inline functions::summarystats::SummaryStatsData<T> op(functions::summarystats::SummaryStatsData<T> d1,T *extraParams) {
return d1;
}
};
template<typename T>
class SummaryStatsStandardDeviation {
public:
static _CUDA_HD inline T getValue(const bool biasCorrected, functions::summarystats::SummaryStatsData<T> val) {
if (biasCorrected) {
T ret = val.varianceBiasCorrected();
if (ret < static_cast<T>(0.0f))
return nd4j::math::nd4j_sqrt(val.variance());
else
return nd4j::math::nd4j_sqrt(ret);
}
return nd4j::math::nd4j_sqrt(val.variance());
}
static _CUDA_HD inline functions::summarystats::SummaryStatsData<T> op(functions::summarystats::SummaryStatsData<T> d1,T *extraParams) {
return d1;
}
};
template<typename T>
class DropOut {
public:
no_op_exec_special
no_op_exec_special_cuda
inline _CUDA_D static T op(T d1, T *params) {
T prob = params[0];
#ifdef __CUDACC__
T length = params[1];
T tid = gridDim.x * blockDim.x + threadIdx.x;
T rnd = nd4j::math::nd4j_abs<T>(nd4j::math::nd4j_cos<T>(static_cast<T>(clock64()) * static_cast<T>(tid) + static_cast<T>(length) * static_cast<T>(tid)));
#else
T rnd = static_cast<T>(rand() / RAND_MAX);
#endif
return rnd >= prob ? static_cast<T>(0.0f) : d1;
}
};
template<typename T>
class DropOutInverted {
public:
no_op_exec_special
no_op_exec_special_cuda
#ifdef __CUDACC__
__device__
#endif
inline static T op(T d1, T *params) {
T prob = params[0];
#ifdef __CUDACC__
T length = params[1];
T tid = gridDim.x * blockDim.x + threadIdx.x;
T rnd = nd4j::math::nd4j_abs<T>(nd4j::math::nd4j_cos<T>(static_cast<T>(clock64()) * static_cast<T>(tid) + static_cast<T>(length) * static_cast<T>(tid)));
#else
T rnd = static_cast<T>(rand() / RAND_MAX);
#endif
return rnd >= prob ? static_cast<T>(0.0f) : d1 / prob;
}
};
template<typename T>
class ReplaceNans {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static T op(T d1, T *params) {
T replacement = params[0];
return nd4j::math::nd4j_isnan(d1) ? replacement : d1 ;
}
};
// this op is used for conditional pairwise transforms only
template<typename T>
class CompareAndReplace{
public:
no_op_exec_special
no_op_exec_special_cuda
// op definition for PairWise Transform
op_def static T op(T d1, T d2, T *params) {
T compare = params[0];
T eps = params[2];
int mode = (int) params[3];
if (mode == 0) // equals
if (nd4j::math::nd4j_abs<T>(d1 - compare) <= eps)
return d2;
else
return d1;
else if (mode == 1) // not equals eps
if (nd4j::math::nd4j_abs<T>(d1 - compare) > eps)
return d2;
else
return d1;
else if (mode == 2) // less_than eps
if (d1 < compare)
return d2;
else
return d1;
else if (mode ==3) // greater_than
if (d1 > compare)
return d2;
else
return d1;
else if (mode == 4) // less_or_equals_than
if (d1 <= compare)
return d2;
else
return d1;
else if (mode == 5) // greater_or_equals_than
if (d1 >= compare)
return d2;
else
return d1;
else if (mode == 6) // abs_less_than
if (nd4j::math::nd4j_abs<T>(d1) < compare)
return d2;
else
return d1;
else if (mode == 7) // abs_greater_than
if (nd4j::math::nd4j_abs<T>(d1) > compare)
return d2;
else
return d1;
else if (mode == 8) // is inf
if (nd4j::math::nd4j_isinf(d1))
return d2;
else
return d1;
else if (mode == 9) // is nan
if (nd4j::math::nd4j_isnan(d1))
return d2;
else
return d1;
else if (mode == 10)
if (d1 == compare)
return d2;
else
return d1;
else if (mode == 11)
if (d1 != compare)
return d2;
else
return d1;
else if (mode == 12) // abs_greater_or_equals_than
if (nd4j::math::nd4j_abs<T>(d1) >= compare)
return d2;
else
return d1;
else if (mode == 13) // abs_less_or_equals_than
if (nd4j::math::nd4j_abs<T>(d1) <= compare)
return d2;
else
return d1;
else
printf("Undefined boolean operation: [%i]\n", mode);
return d1;
}
};
template<typename T>
class CompareAndSet {
public:
no_op_exec_special
no_op_exec_special_cuda
// op definition for Transform
op_def static T op(T d1, T *params) {
T compare = params[0];
T set = params[1];
T eps = params[2];
// with mode == 0 we do set if d1 equals to compare, and with mode == 1 - we go otherwise
int mode = (int) params[3];
if (mode == 0) // equals
if (nd4j::math::nd4j_abs<T>(d1 - compare) <= eps)
return set;
else
return d1;
//return nd4j::math::nd4j_abs<T>(d1 - compare) <= eps ? set : d1;
else if (mode == 1) // not equals
if (nd4j::math::nd4j_abs<T>(d1 - compare) > eps)
return set;
else
return d1;
//return nd4j::math::nd4j_abs<T>(d1 - compare) > eps ? set : d1;
else if (mode == 2) // less_than
if (d1 < compare)
return set;
else
return d1;
else if (mode ==3) // greater_than
if (d1 > compare)
return set;
else
return d1;
else if (mode == 4) // less_or_equals_than
if (d1 <= compare)
return set;
else
return d1;
else if (mode == 5) // greater_or_equals_than
if (d1 >= compare)
return set;
else
return d1;
else if (mode == 6) // abs_less_than
if (nd4j::math::nd4j_abs<T>(d1) < compare)
return set;
else
return d1;
else if (mode == 7) // abs_greater_than
if (nd4j::math::nd4j_abs<T>(d1) > compare)
return set;
else
return d1;
else if (mode == 8) // is inf
if (nd4j::math::nd4j_isinf(d1))
return set;
else
return d1;
else if (mode == 9) // is nan
if (nd4j::math::nd4j_isnan(d1))
return set;
else
return d1;
else if (mode == 10)
if (d1 == compare)
return set;
else
return d1;
else if (mode == 11)
if (d1 != compare)
return set;
else
return d1;
else if (mode == 12) // abs_greater_or_equals_than
if (nd4j::math::nd4j_abs<T>(d1) >= compare)
return set;
else
return d1;
else if (mode == 13) // abs_less_or_equals_than
if (nd4j::math::nd4j_abs<T>(d1) <= compare)
return set;
else
return d1;
else
printf("Undefined boolean operation: [%i]\n", mode);
return d1;
}
// op definition for PairWise Transform
op_def static T op(T d1, T d2, T *params) {
T compare = params[0];
T eps = params[2];
int mode = (int) params[3];
if (mode == 0) // equals
if (nd4j::math::nd4j_abs<T>(d2 - compare) <= eps)
return d2;
else
return d1;
else if (mode == 1) // not equals
if (nd4j::math::nd4j_abs<T>(d2 - compare) > eps)
return d2;
else
return d1;
else if (mode == 2) // less_than
if (d2 < compare)
return d2;
else
return d1;
else if (mode ==3) // greater_than
if (d2 > compare)
return d2;
else
return d1;
else if (mode == 4) // less_or_equals_than
if (d2 <= compare)
return d2;
else
return d1;
else if (mode == 5) // greater_or_equals_than
if (d2 >= compare)
return d2;
else
return d1;
else if (mode == 6) // abs_less_than
if (nd4j::math::nd4j_abs<T>(d2) < compare)
return d2;
else
return d1;
else if (mode == 7) // abs_greater_than
if (nd4j::math::nd4j_abs<T>(d2) > compare)
return d2;
else
return d1;
else if (mode == 8) // is inf
if (nd4j::math::nd4j_isinf(d2))
return d2;
else
return d1;
else if (mode == 9) // is nan
if (nd4j::math::nd4j_isnan(d2))
return d2;
else
return d1;
else if (mode == 10)
if (d2 == compare)
return d2;
else
return d1;
else if (mode == 11)
if (d2 != compare)
return d2;
else
return d1;
else if (mode == 12) // abs_greater_or_equals_than
if (nd4j::math::nd4j_abs<T>(d1) >= compare)
return d2;
else
return d1;
else if (mode == 13) // abs_less_or_equals_than
if (nd4j::math::nd4j_abs<T>(d1) <= compare)
return d2;
else
return d1;
else
printf("Undefined boolean operation: [%i]\n", mode);
return d1;
}
};
}
#endif
|
critical.c | /* Copyright (C) 2005, 2009 Free Software Foundation, Inc.
Contributed by Richard Henderson <rth@redhat.com>.
This file is part of the GNU OpenMP Library (libgomp).
Libgomp is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3, or (at your option)
any later version.
Libgomp is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
Under Section 7 of GPL version 3, you are granted additional
permissions described in the GCC Runtime Library Exception, version
3.1, as published by the Free Software Foundation.
You should have received a copy of the GNU General Public License and
a copy of the GCC Runtime Library Exception along with this program;
see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
<http://www.gnu.org/licenses/>. */
/* This file handles the CRITICAL construct. */
#include "libgomp.h"
#include <stdlib.h>
static gomp_mutex_t default_lock;
void
GOMP_critical_start (void)
{
gomp_mutex_lock (&default_lock);
}
void
GOMP_critical_end (void)
{
gomp_mutex_unlock (&default_lock);
}
#ifndef HAVE_SYNC_BUILTINS
static gomp_mutex_t create_lock_lock;
#endif
void
GOMP_critical_name_start (void **pptr)
{
gomp_mutex_t *plock;
/* If a mutex fits within the space for a pointer, and is zero initialized,
then use the pointer space directly. */
if (GOMP_MUTEX_INIT_0
&& sizeof (gomp_mutex_t) <= sizeof (void *)
&& __alignof (gomp_mutex_t) <= sizeof (void *))
plock = (gomp_mutex_t *)pptr;
/* Otherwise we have to be prepared to malloc storage. */
else
{
plock = *pptr;
if (plock == NULL)
{
#ifdef HAVE_SYNC_BUILTINS
gomp_mutex_t *nlock = gomp_malloc (sizeof (gomp_mutex_t));
gomp_mutex_init (nlock);
plock = __sync_val_compare_and_swap (pptr, NULL, nlock);
if (plock != NULL)
{
gomp_mutex_destroy (nlock);
free (nlock);
}
else
plock = nlock;
#else
gomp_mutex_lock (&create_lock_lock);
plock = *pptr;
if (plock == NULL)
{
plock = gomp_malloc (sizeof (gomp_mutex_t));
gomp_mutex_init (plock);
__sync_synchronize ();
*pptr = plock;
}
gomp_mutex_unlock (&create_lock_lock);
#endif
}
}
gomp_mutex_lock (plock);
}
void
GOMP_critical_name_end (void **pptr)
{
gomp_mutex_t *plock;
/* If a mutex fits within the space for a pointer, and is zero initialized,
then use the pointer space directly. */
if (GOMP_MUTEX_INIT_0
&& sizeof (gomp_mutex_t) <= sizeof (void *)
&& __alignof (gomp_mutex_t) <= sizeof (void *))
plock = (gomp_mutex_t *)pptr;
else
plock = *pptr;
gomp_mutex_unlock (plock);
}
/* This mutex is used when atomic operations don't exist for the target
in the mode requested. The result is not globally atomic, but works so
long as all parallel references are within #pragma omp atomic directives.
According to responses received from omp@openmp.org, appears to be within
spec. Which makes sense, since that's how several other compilers
handle this situation as well. */
static gomp_mutex_t atomic_lock;
void
GOMP_atomic_start (void)
{
gomp_mutex_lock (&atomic_lock);
}
void
GOMP_atomic_end (void)
{
gomp_mutex_unlock (&atomic_lock);
}
#if !GOMP_MUTEX_INIT_0
static void __attribute__((constructor))
initialize_critical (void)
{
gomp_mutex_init (&default_lock);
gomp_mutex_init (&atomic_lock);
#ifndef HAVE_SYNC_BUILTINS
gomp_mutex_init (&create_lock_lock);
#endif
}
#endif
|
par_relax_more.c | /******************************************************************************
* Copyright 1998-2019 Lawrence Livermore National Security, LLC and other
* HYPRE Project Developers. See the top-level COPYRIGHT file for details.
*
* SPDX-License-Identifier: (Apache-2.0 OR MIT)
******************************************************************************/
/******************************************************************************
*
* a few more relaxation schemes: Chebychev, FCF-Jacobi, CG -
* these do not go through the CF interface (hypre_BoomerAMGRelaxIF)
*
*****************************************************************************/
#include "_hypre_parcsr_ls.h"
#include "float.h"
HYPRE_Int hypre_LINPACKcgtql1(HYPRE_Int*,HYPRE_Real *,HYPRE_Real *,HYPRE_Int *);
/******************************************************************************
*
*use max norm to estimate largest eigenvalue
*
*****************************************************************************/
HYPRE_Int hypre_ParCSRMaxEigEstimate(hypre_ParCSRMatrix *A, /* matrix to relax with */
HYPRE_Int scale, /* scale by diagonal?*/
HYPRE_Real *max_eig)
{
HYPRE_Real e_max;
HYPRE_Real row_sum, max_norm;
HYPRE_Real *A_diag_data;
HYPRE_Real *A_offd_data;
HYPRE_Real temp;
HYPRE_Real diag_value;
HYPRE_Int pos_diag, neg_diag;
HYPRE_Int A_num_rows;
HYPRE_Int *A_diag_i;
HYPRE_Int *A_offd_i;
HYPRE_Int j;
HYPRE_Int i, start;
/* estimate with the inf-norm of A - should be ok for SPD matrices */
A_num_rows = hypre_CSRMatrixNumRows(hypre_ParCSRMatrixDiag(A));
A_diag_i = hypre_CSRMatrixI(hypre_ParCSRMatrixDiag(A));
A_diag_data = hypre_CSRMatrixData(hypre_ParCSRMatrixDiag(A));
A_offd_i = hypre_CSRMatrixI(hypre_ParCSRMatrixOffd(A));
A_offd_data = hypre_CSRMatrixData(hypre_ParCSRMatrixOffd(A));
max_norm = 0.0;
pos_diag = neg_diag = 0;
for ( i = 0; i < A_num_rows; i++ )
{
start = A_diag_i[i];
diag_value = A_diag_data[start];
if (diag_value > 0)
{
pos_diag++;
}
if (diag_value < 0)
{
neg_diag++;
diag_value = -diag_value;
}
row_sum = diag_value;
/*for (j = 0; j < row_length; j++)*/
for (j = start+1; j < A_diag_i[i+1]; j++)
{
row_sum += fabs(A_diag_data[j]);
}
for (j = A_offd_i[i]; j < A_offd_i[i+1]; j++)
{
row_sum += fabs(A_offd_data[j]);
}
if (scale)
{
if (diag_value != 0.0)
row_sum = row_sum/diag_value;
}
if ( row_sum > max_norm ) max_norm = row_sum;
}
/* get max across procs */
hypre_MPI_Allreduce(&max_norm, &temp, 1, HYPRE_MPI_REAL, hypre_MPI_MAX, hypre_ParCSRMatrixComm(A));
max_norm = temp;
/* from Charles */
if ( pos_diag == 0 && neg_diag > 0 ) max_norm = - max_norm;
/* eig estimates */
e_max = max_norm;
/* return */
*max_eig = e_max;
return hypre_error_flag;
}
/******************************************************************************
use CG to get the eigenvalue estimate
scale means get eig est of (D^{-1/2} A D^{-1/2}
******************************************************************************/
HYPRE_Int hypre_ParCSRMaxEigEstimateCG(hypre_ParCSRMatrix *A, /* matrix to relax with */
HYPRE_Int scale, /* scale by diagonal?*/
HYPRE_Int max_iter,
HYPRE_Real *max_eig,
HYPRE_Real *min_eig)
{
HYPRE_Int i, j, err;
hypre_ParVector *p;
hypre_ParVector *s;
hypre_ParVector *r;
hypre_ParVector *ds;
hypre_ParVector *u;
HYPRE_Real *tridiag = NULL;
HYPRE_Real *trioffd = NULL;
HYPRE_Real lambda_max ;
HYPRE_Real beta, gamma = 0.0, alpha, sdotp, gamma_old, alphainv;
HYPRE_Real diag;
HYPRE_Real lambda_min;
HYPRE_Real *s_data, *p_data, *ds_data, *u_data;
HYPRE_Int local_size = hypre_CSRMatrixNumRows(hypre_ParCSRMatrixDiag(A));
hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A);
HYPRE_Real *A_diag_data = hypre_CSRMatrixData(A_diag);
HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag);
/* check the size of A - don't iterate more than the size */
HYPRE_BigInt size = hypre_ParCSRMatrixGlobalNumRows(A);
if (size < (HYPRE_BigInt) max_iter)
max_iter = (HYPRE_Int) size;
/* create some temp vectors: p, s, r , ds, u*/
r = hypre_ParVectorCreate(hypre_ParCSRMatrixComm(A),
hypre_ParCSRMatrixGlobalNumRows(A),
hypre_ParCSRMatrixRowStarts(A));
hypre_ParVectorInitialize(r);
hypre_ParVectorSetPartitioningOwner(r,0);
p = hypre_ParVectorCreate(hypre_ParCSRMatrixComm(A),
hypre_ParCSRMatrixGlobalNumRows(A),
hypre_ParCSRMatrixRowStarts(A));
hypre_ParVectorInitialize(p);
hypre_ParVectorSetPartitioningOwner(p,0);
s = hypre_ParVectorCreate(hypre_ParCSRMatrixComm(A),
hypre_ParCSRMatrixGlobalNumRows(A),
hypre_ParCSRMatrixRowStarts(A));
hypre_ParVectorInitialize(s);
hypre_ParVectorSetPartitioningOwner(s,0);
ds = hypre_ParVectorCreate(hypre_ParCSRMatrixComm(A),
hypre_ParCSRMatrixGlobalNumRows(A),
hypre_ParCSRMatrixRowStarts(A));
hypre_ParVectorInitialize(ds);
hypre_ParVectorSetPartitioningOwner(ds,0);
u = hypre_ParVectorCreate(hypre_ParCSRMatrixComm(A),
hypre_ParCSRMatrixGlobalNumRows(A),
hypre_ParCSRMatrixRowStarts(A));
hypre_ParVectorInitialize(u);
hypre_ParVectorSetPartitioningOwner(u,0);
/* point to local data */
s_data = hypre_VectorData(hypre_ParVectorLocalVector(s));
p_data = hypre_VectorData(hypre_ParVectorLocalVector(p));
ds_data = hypre_VectorData(hypre_ParVectorLocalVector(ds));
u_data = hypre_VectorData(hypre_ParVectorLocalVector(u));
/* make room for tri-diag matrix */
tridiag = hypre_CTAlloc(HYPRE_Real, max_iter+1, HYPRE_MEMORY_HOST);
trioffd = hypre_CTAlloc(HYPRE_Real, max_iter+1, HYPRE_MEMORY_HOST);
for (i=0; i < max_iter + 1; i++)
{
tridiag[i] = 0;
trioffd[i] = 0;
}
/* set residual to random */
hypre_ParVectorSetRandomValues(r,1);
if (scale)
{
for (i = 0; i < local_size; i++)
{
diag = A_diag_data[A_diag_i[i]];
ds_data[i] = 1/sqrt(diag);
}
}
else
{
/* set ds to 1 */
hypre_ParVectorSetConstantValues(ds,1.0);
}
/* gamma = <r,Cr> */
gamma = hypre_ParVectorInnerProd(r,p);
/* for the initial filling of the tridiag matrix */
beta = 1.0;
i = 0;
while (i < max_iter)
{
/* s = C*r */
/* TO DO: C = diag scale */
hypre_ParVectorCopy(r, s);
/*gamma = <r,Cr> */
gamma_old = gamma;
gamma = hypre_ParVectorInnerProd(r,s);
if (i==0)
{
beta = 1.0;
/* p_0 = C*r */
hypre_ParVectorCopy(s, p);
}
else
{
/* beta = gamma / gamma_old */
beta = gamma / gamma_old;
/* p = s + beta p */
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE
#endif
for (j=0; j < local_size; j++)
{
p_data[j] = s_data[j] + beta*p_data[j];
}
}
if (scale)
{
/* s = D^{-1/2}A*D^{-1/2}*p */
for (j = 0; j < local_size; j++)
{
u_data[j] = ds_data[j] * p_data[j];
}
hypre_ParCSRMatrixMatvec(1.0, A, u, 0.0, s);
for (j = 0; j < local_size; j++)
{
s_data[j] = ds_data[j] * s_data[j];
}
}
else
{
/* s = A*p */
hypre_ParCSRMatrixMatvec(1.0, A, p, 0.0, s);
}
/* <s,p> */
sdotp = hypre_ParVectorInnerProd(s,p);
/* alpha = gamma / <s,p> */
alpha = gamma/sdotp;
/* get tridiagonal matrix */
alphainv = 1.0/alpha;
tridiag[i+1] = alphainv;
tridiag[i] *= beta;
tridiag[i] += alphainv;
trioffd[i+1] = alphainv;
trioffd[i] *= sqrt(beta);
/* x = x + alpha*p */
/* don't need */
/* r = r - alpha*s */
hypre_ParVectorAxpy( -alpha, s, r);
i++;
}
/* eispack routine - eigenvalues return in tridiag and ordered*/
hypre_LINPACKcgtql1(&i,tridiag,trioffd,&err);
lambda_max = tridiag[i-1];
lambda_min = tridiag[0];
/* hypre_printf("linpack max eig est = %g\n", lambda_max);*/
/* hypre_printf("linpack min eig est = %g\n", lambda_min);*/
hypre_TFree(tridiag, HYPRE_MEMORY_HOST);
hypre_TFree(trioffd, HYPRE_MEMORY_HOST);
hypre_ParVectorDestroy(r);
hypre_ParVectorDestroy(s);
hypre_ParVectorDestroy(p);
hypre_ParVectorDestroy(ds);
hypre_ParVectorDestroy(u);
/* return */
*max_eig = lambda_max;
*min_eig = lambda_min;
return hypre_error_flag;
}
/******************************************************************************
Chebyshev relaxation
Can specify order 1-4 (this is the order of the resid polynomial)- here we
explicitly code the coefficients (instead of
iteratively determining)
variant 0: standard chebyshev
this is rlx 11 if scale = 0, and 16 if scale == 1
variant 1: modified cheby: T(t)* f(t) where f(t) = (1-b/t)
this is rlx 15 if scale = 0, and 17 if scale == 1
ratio indicates the percentage of the whole spectrum to use (so .5
means half, and .1 means 10percent)
*******************************************************************************/
HYPRE_Int hypre_ParCSRRelax_Cheby(hypre_ParCSRMatrix *A, /* matrix to relax with */
hypre_ParVector *f, /* right-hand side */
HYPRE_Real max_eig,
HYPRE_Real min_eig,
HYPRE_Real fraction,
HYPRE_Int order, /* polynomial order */
HYPRE_Int scale, /* scale by diagonal?*/
HYPRE_Int variant,
hypre_ParVector *u, /* initial/updated approximation */
hypre_ParVector *v /* temporary vector */,
hypre_ParVector *r /*another temp vector */ )
{
hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A);
HYPRE_Real *A_diag_data = hypre_CSRMatrixData(A_diag);
HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag);
HYPRE_Real *u_data = hypre_VectorData(hypre_ParVectorLocalVector(u));
HYPRE_Real *f_data = hypre_VectorData(hypre_ParVectorLocalVector(f));
HYPRE_Real *v_data = hypre_VectorData(hypre_ParVectorLocalVector(v));
HYPRE_Real *r_data = hypre_VectorData(hypre_ParVectorLocalVector(r));
HYPRE_Real theta, delta;
HYPRE_Real den;
HYPRE_Real upper_bound, lower_bound;
HYPRE_Int i, j;
HYPRE_Int num_rows = hypre_CSRMatrixNumRows(A_diag);
HYPRE_Real coefs[5];
HYPRE_Real mult;
HYPRE_Real *orig_u;
HYPRE_Real tmp_d;
HYPRE_Int cheby_order;
HYPRE_Real *ds_data, *tmp_data;
HYPRE_Real diag;
hypre_ParVector *ds;
hypre_ParVector *tmp_vec;
/* u = u + p(A)r */
if (order > 4)
order = 4;
if (order < 1)
order = 1;
/* we are using the order of p(A) */
cheby_order = order -1;
/* make sure we are large enough - Adams et al. 2003 */
upper_bound = max_eig * 1.1;
/* lower_bound = max_eig/fraction; */
lower_bound = (upper_bound - min_eig)* fraction + min_eig;
/* theta and delta */
theta = (upper_bound + lower_bound)/2;
delta = (upper_bound - lower_bound)/2;
if (variant == 1 )
{
switch ( cheby_order ) /* these are the corresponding cheby polynomials: u = u_o + s(A)r_0 - so order is
one less that resid poly: r(t) = 1 - t*s(t) */
{
case 0:
coefs[0] = 1.0/theta;
break;
case 1: /* (del - t + 2*th)/(th^2 + del*th) */
den = (theta*theta + delta*theta);
coefs[0] = (delta + 2*theta)/den;
coefs[1] = -1.0/den;
break;
case 2: /* (4*del*th - del^2 - t*(2*del + 6*th) + 2*t^2 + 6*th^2)/(2*del*th^2 - del^2*th - del^3 + 2*th^3)*/
den = 2*delta*theta*theta - delta*delta*theta - pow(delta,3) + 2*pow(theta,3);
coefs[0] = (4*delta*theta - pow(delta,2) + 6*pow(theta,2))/den;
coefs[1] = -(2*delta + 6*theta)/den;
coefs[2] = 2/den;
break;
case 3: /* -(6*del^2*th - 12*del*th^2 - t^2*(4*del + 16*th) + t*(12*del*th - 3*del^2 + 24*th^2) + 3*del^3 + 4*t^3 - 16*th^3)/(4*del*th^3 - 3*del^2*th^2 - 3*del^3*th + 4*th^4)*/
den = - (4*delta*pow(theta,3) - 3*pow(delta,2)*pow(theta,2) - 3*pow(delta,3)*theta + 4*pow(theta,4) );
coefs[0] = (6*pow(delta,2)*theta - 12*delta*pow(theta,2) + 3*pow(delta,3) - 16*pow(theta,3) )/den;
coefs[1] = (12*delta*theta - 3*pow(delta,2) + 24*pow(theta,2))/den;
coefs[2] = -( 4*delta + 16*theta)/den;
coefs[3] = 4/den;
break;
}
}
else /* standard chebyshev */
{
switch ( cheby_order ) /* these are the corresponding cheby polynomials: u = u_o + s(A)r_0 - so order is
one less thatn resid poly: r(t) = 1 - t*s(t) */
{
case 0:
coefs[0] = 1.0/theta;
break;
case 1: /* ( 2*t - 4*th)/(del^2 - 2*th^2) */
den = delta*delta - 2*theta*theta;
coefs[0] = -4*theta/den;
coefs[1] = 2/den;
break;
case 2: /* (3*del^2 - 4*t^2 + 12*t*th - 12*th^2)/(3*del^2*th - 4*th^3)*/
den = 3*(delta*delta)*theta - 4*(theta*theta*theta);
coefs[0] = (3*delta*delta - 12 *theta*theta)/den;
coefs[1] = 12*theta/den;
coefs[2] = -4/den;
break;
case 3: /*(t*(8*del^2 - 48*th^2) - 16*del^2*th + 32*t^2*th - 8*t^3 + 32*th^3)/(del^4 - 8*del^2*th^2 + 8*th^4)*/
den = pow(delta,4) - 8*delta*delta*theta*theta + 8*pow(theta,4);
coefs[0] = (32*pow(theta,3)- 16*delta*delta*theta)/den;
coefs[1] = (8*delta*delta - 48*theta*theta)/den;
coefs[2] = 32*theta/den;
coefs[3] = -8/den;
break;
}
}
orig_u = hypre_CTAlloc(HYPRE_Real, num_rows, HYPRE_MEMORY_HOST);
if (!scale)
{
/* get residual: r = f - A*u */
hypre_ParVectorCopy(f, r);
hypre_ParCSRMatrixMatvec(-1.0, A, u, 1.0, r);
for ( i = 0; i < num_rows; i++ )
{
orig_u[i] = u_data[i];
u_data[i] = r_data[i] * coefs[cheby_order];
}
for (i = cheby_order - 1; i >= 0; i-- )
{
hypre_ParCSRMatrixMatvec(1.0, A, u, 0.0, v);
mult = coefs[i];
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE
#endif
for ( j = 0; j < num_rows; j++ )
{
u_data[j] = mult * r_data[j] + v_data[j];
}
}
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for ( i = 0; i < num_rows; i++ )
{
u_data[i] = orig_u[i] + u_data[i];
}
}
else /* scaling! */
{
/*grab 1/sqrt(diagonal) */
ds = hypre_ParVectorCreate(hypre_ParCSRMatrixComm(A),
hypre_ParCSRMatrixGlobalNumRows(A),
hypre_ParCSRMatrixRowStarts(A));
hypre_ParVectorInitialize(ds);
hypre_ParVectorSetPartitioningOwner(ds,0);
ds_data = hypre_VectorData(hypre_ParVectorLocalVector(ds));
tmp_vec = hypre_ParVectorCreate(hypre_ParCSRMatrixComm(A),
hypre_ParCSRMatrixGlobalNumRows(A),
hypre_ParCSRMatrixRowStarts(A));
hypre_ParVectorInitialize(tmp_vec);
hypre_ParVectorSetPartitioningOwner(tmp_vec,0);
tmp_data = hypre_VectorData(hypre_ParVectorLocalVector(tmp_vec));
/* get ds_data and get scaled residual: r = D^(-1/2)f -
* D^(-1/2)A*u */
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(j,diag) HYPRE_SMP_SCHEDULE
#endif
for (j = 0; j < num_rows; j++)
{
diag = A_diag_data[A_diag_i[j]];
ds_data[j] = 1/sqrt(diag);
r_data[j] = ds_data[j] * f_data[j];
}
hypre_ParCSRMatrixMatvec(-1.0, A, u, 0.0, tmp_vec);
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE
#endif
for ( j = 0; j < num_rows; j++ )
{
r_data[j] += ds_data[j] * tmp_data[j];
}
/* save original u, then start
the iteration by multiplying r by the cheby coef.*/
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE
#endif
for ( j = 0; j < num_rows; j++ )
{
orig_u[j] = u_data[j]; /* orig, unscaled u */
u_data[j] = r_data[j] * coefs[cheby_order];
}
/* now do the other coefficients */
for (i = cheby_order - 1; i >= 0; i-- )
{
/* v = D^(-1/2)AD^(-1/2)u */
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE
#endif
for ( j = 0; j < num_rows; j++ )
{
tmp_data[j] = ds_data[j] * u_data[j];
}
hypre_ParCSRMatrixMatvec(1.0, A, tmp_vec, 0.0, v);
/* u_new = coef*r + v*/
mult = coefs[i];
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(j,tmp_d) HYPRE_SMP_SCHEDULE
#endif
for ( j = 0; j < num_rows; j++ )
{
tmp_d = ds_data[j]* v_data[j];
u_data[j] = mult * r_data[j] + tmp_d;
}
} /* end of cheby_order loop */
/* now we have to scale u_data before adding it to u_orig*/
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE
#endif
for ( j = 0; j < num_rows; j++ )
{
u_data[j] = orig_u[j] + ds_data[j]*u_data[j];
}
hypre_ParVectorDestroy(ds);
hypre_ParVectorDestroy(tmp_vec);
}/* end of scaling code */
hypre_TFree(orig_u, HYPRE_MEMORY_HOST);
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* hypre_BoomerAMGRelax_FCFJacobi
*--------------------------------------------------------------------------*/
HYPRE_Int hypre_BoomerAMGRelax_FCFJacobi( hypre_ParCSRMatrix *A,
hypre_ParVector *f,
HYPRE_Int *cf_marker,
HYPRE_Real relax_weight,
hypre_ParVector *u,
hypre_ParVector *Vtemp)
{
HYPRE_Int i;
HYPRE_Int relax_points[3];
HYPRE_Int relax_type = 0;
relax_points[0] = -1; /*F */
relax_points[1] = 1; /*C */
relax_points[2] = -1; /*F */
/* cf == NULL --> size == 0 */
if (cf_marker == NULL)
{
hypre_assert(hypre_CSRMatrixNumRows(hypre_ParCSRMatrixDiag(A)) == 0);
}
for (i=0; i < 3; i++)
{
hypre_BoomerAMGRelax(A,
f,
cf_marker,
relax_type,
relax_points[i],
relax_weight,
0.0,
NULL,
u,
Vtemp, NULL);
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* CG Smoother -
*
*--------------------------------------------------------------------------*/
HYPRE_Int hypre_ParCSRRelax_CG( HYPRE_Solver solver,
hypre_ParCSRMatrix *A,
hypre_ParVector *f,
hypre_ParVector *u,
HYPRE_Int num_its)
{
HYPRE_PCGSetMaxIter(solver, num_its); /* max iterations */
HYPRE_PCGSetTol(solver, 0.0); /* max iterations */
HYPRE_ParCSRPCGSolve(solver, (HYPRE_ParCSRMatrix)A, (HYPRE_ParVector)f, (HYPRE_ParVector)u);
#if 0
{
HYPRE_Int myid;
HYPRE_Int num_iterations;
HYPRE_Real final_res_norm;
hypre_MPI_Comm_rank(hypre_MPI_COMM_WORLD, &myid);
HYPRE_PCGGetNumIterations(solver, &num_iterations);
HYPRE_PCGGetFinalRelativeResidualNorm(solver, &final_res_norm);
if (myid ==0)
{
hypre_printf(" -----CG PCG Iterations = %d\n", num_iterations);
hypre_printf(" -----CG PCG Final Relative Residual Norm = %e\n", final_res_norm);
}
}
#endif
return hypre_error_flag;
}
/* tql1.f --
this is the eispack translation - from Barry Smith in Petsc
Note that this routine always uses real numbers (not complex) even
if the underlying matrix is Hermitian. This is because the Lanczos
process applied to Hermitian matrices always produces a real,
symmetric tridiagonal matrix.
*/
HYPRE_Real hypre_LINPACKcgpthy(HYPRE_Real*,HYPRE_Real*);
HYPRE_Int hypre_LINPACKcgtql1(HYPRE_Int *n,HYPRE_Real *d,HYPRE_Real *e,HYPRE_Int *ierr)
{
/* System generated locals */
HYPRE_Int i__1,i__2;
HYPRE_Real d__1,d__2,c_b10 = 1.0;
/* Local variables */
HYPRE_Real c,f,g,h;
HYPRE_Int i,j,l,m;
HYPRE_Real p,r,s,c2,c3 = 0.0;
HYPRE_Int l1,l2;
HYPRE_Real s2 = 0.0;
HYPRE_Int ii;
HYPRE_Real dl1,el1;
HYPRE_Int mml;
HYPRE_Real tst1,tst2;
/* THIS SUBROUTINE IS A TRANSLATION OF THE ALGOL PROCEDURE TQL1, */
/* NUM. MATH. 11, 293-306(1968) BY BOWDLER, MARTIN, REINSCH, AND */
/* WILKINSON. */
/* HANDBOOK FOR AUTO. COMP., VOL.II-LINEAR ALGEBRA, 227-240(1971). */
/* THIS SUBROUTINE FINDS THE EIGENVALUES OF A SYMMETRIC */
/* TRIDIAGONAL MATRIX BY THE QL METHOD. */
/* ON INPUT */
/* N IS THE ORDER OF THE MATRIX. */
/* D CONTAINS THE DIAGONAL ELEMENTS OF THE INPUT MATRIX. */
/* E CONTAINS THE SUBDIAGONAL ELEMENTS OF THE INPUT MATRIX */
/* IN ITS LAST N-1 POSITIONS. E(1) IS ARBITRARY. */
/* ON OUTPUT */
/* D CONTAINS THE EIGENVALUES IN ASCENDING ORDER. IF AN */
/* ERROR EXIT IS MADE, THE EIGENVALUES ARE CORRECT AND */
/* ORDERED FOR INDICES 1,2,...IERR-1, BUT MAY NOT BE */
/* THE SMALLEST EIGENVALUES. */
/* E HAS BEEN DESTROYED. */
/* IERR IS SET TO */
/* ZERO FOR NORMAL RETURN, */
/* J IF THE J-TH EIGENVALUE HAS NOT BEEN */
/* DETERMINED AFTER 30 ITERATIONS. */
/* CALLS CGPTHY FOR DSQRT(A*A + B*B) . */
/* QUESTIONS AND COMMENTS SHOULD BE DIRECTED TO BURTON S. GARBOW, */
/* MATHEMATICS AND COMPUTER SCIENCE DIV, ARGONNE NATIONAL LABORATORY
*/
/* THIS VERSION DATED AUGUST 1983. */
/* ------------------------------------------------------------------
*/
HYPRE_Real ds;
--e;
--d;
*ierr = 0;
if (*n == 1) {
goto L1001;
}
i__1 = *n;
for (i = 2; i <= i__1; ++i) {
e[i - 1] = e[i];
}
f = 0.;
tst1 = 0.;
e[*n] = 0.;
i__1 = *n;
for (l = 1; l <= i__1; ++l) {
j = 0;
h = (d__1 = d[l],fabs(d__1)) + (d__2 = e[l],fabs(d__2));
if (tst1 < h) {
tst1 = h;
}
/* .......... LOOK FOR SMALL SUB-DIAGONAL ELEMENT .......... */
i__2 = *n;
for (m = l; m <= i__2; ++m) {
tst2 = tst1 + (d__1 = e[m],fabs(d__1));
if (tst2 == tst1) {
goto L120;
}
/* .......... E(N) IS ALWAYS ZERO,SO THERE IS NO EXIT */
/* THROUGH THE BOTTOM OF THE LOOP .......... */
}
L120:
if (m == l) {
goto L210;
}
L130:
if (j == 30) {
goto L1000;
}
++j;
/* .......... FORM SHIFT .......... */
l1 = l + 1;
l2 = l1 + 1;
g = d[l];
p = (d[l1] - g) / (e[l] * 2.);
r = hypre_LINPACKcgpthy(&p,&c_b10);
ds = 1.0; if (p < 0.0) ds = -1.0;
d[l] = e[l] / (p + ds*r);
d[l1] = e[l] * (p + ds*r);
dl1 = d[l1];
h = g - d[l];
if (l2 > *n) {
goto L145;
}
i__2 = *n;
for (i = l2; i <= i__2; ++i) {
d[i] -= h;
}
L145:
f += h;
/* .......... QL TRANSFORMATION .......... */
p = d[m];
c = 1.;
c2 = c;
el1 = e[l1];
s = 0.;
mml = m - l;
/* .......... FOR I=M-1 STEP -1 UNTIL L DO -- .......... */
i__2 = mml;
for (ii = 1; ii <= i__2; ++ii) {
c3 = c2;
c2 = c;
s2 = s;
i = m - ii;
g = c * e[i];
h = c * p;
r = hypre_LINPACKcgpthy(&p,&e[i]);
e[i + 1] = s * r;
s = e[i] / r;
c = p / r;
p = c * d[i] - s * g;
d[i + 1] = h + s * (c * g + s * d[i]);
}
p = -s * s2 * c3 * el1 * e[l] / dl1;
e[l] = s * p;
d[l] = c * p;
tst2 = tst1 + (d__1 = e[l],fabs(d__1));
if (tst2 > tst1) {
goto L130;
}
L210:
p = d[l] + f;
/* .......... ORDER EIGENVALUES .......... */
if (l == 1) {
goto L250;
}
/* .......... FOR I=L STEP -1 UNTIL 2 DO -- .......... */
i__2 = l;
for (ii = 2; ii <= i__2; ++ii) {
i = l + 2 - ii;
if (p >= d[i - 1]) {
goto L270;
}
d[i] = d[i - 1];
}
L250:
i = 1;
L270:
d[i] = p;
}
goto L1001;
/* .......... SET ERROR -- NO CONVERGENCE TO AN */
/* EIGENVALUE AFTER 30 ITERATIONS .......... */
L1000:
*ierr = l;
L1001:
return 0;
} /* cgtql1_ */
HYPRE_Real hypre_LINPACKcgpthy(HYPRE_Real *a,HYPRE_Real *b)
{
/* System generated locals */
HYPRE_Real ret_val,d__1,d__2,d__3;
/* Local variables */
HYPRE_Real p,r,s,t,u;
/* FINDS DSQRT(A**2+B**2) WITHOUT OVERFLOW OR DESTRUCTIVE UNDERFLOW */
/* Computing MAX */
d__1 = fabs(*a),d__2 = fabs(*b);
p = hypre_max(d__1,d__2);
if (!p) {
goto L20;
}
/* Computing MIN */
d__2 = fabs(*a),d__3 = fabs(*b);
/* Computing 2nd power */
d__1 = hypre_min(d__2,d__3) / p;
r = d__1 * d__1;
L10:
t = r + 4.;
if (t == 4.) {
goto L20;
}
s = r / t;
u = s * 2. + 1.;
p = u * p;
/* Computing 2nd power */
d__1 = s / u;
r = d__1 * d__1 * r;
goto L10;
L20:
ret_val = p;
return ret_val;
} /* cgpthy_ */
/*--------------------------------------------------------------------------
* hypre_ParCSRRelax_L1_Jacobi (same as the one in AMS, but this allows CF)
u += w D^{-1}(f - A u), where D_ii = ||A(i,:)||_1
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_ParCSRRelax_L1_Jacobi( hypre_ParCSRMatrix *A,
hypre_ParVector *f,
HYPRE_Int *cf_marker,
HYPRE_Int relax_points,
HYPRE_Real relax_weight,
HYPRE_Real *l1_norms,
hypre_ParVector *u,
hypre_ParVector *Vtemp )
{
MPI_Comm comm = hypre_ParCSRMatrixComm(A);
hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A);
HYPRE_Real *A_diag_data = hypre_CSRMatrixData(A_diag);
HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag);
HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag);
hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A);
HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd);
HYPRE_Real *A_offd_data = hypre_CSRMatrixData(A_offd);
HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd);
hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A);
hypre_ParCSRCommHandle *comm_handle;
HYPRE_Int n = hypre_CSRMatrixNumRows(A_diag);
HYPRE_Int num_cols_offd = hypre_CSRMatrixNumCols(A_offd);
hypre_Vector *u_local = hypre_ParVectorLocalVector(u);
HYPRE_Real *u_data = hypre_VectorData(u_local);
hypre_Vector *f_local = hypre_ParVectorLocalVector(f);
HYPRE_Real *f_data = hypre_VectorData(f_local);
hypre_Vector *Vtemp_local = hypre_ParVectorLocalVector(Vtemp);
HYPRE_Real *Vtemp_data = hypre_VectorData(Vtemp_local);
HYPRE_Real *Vext_data = NULL;
HYPRE_Real *v_buf_data;
HYPRE_Int i, j;
HYPRE_Int ii, jj;
HYPRE_Int num_sends;
HYPRE_Int index, start;
HYPRE_Int num_procs, my_id ;
HYPRE_Real zero = 0.0;
HYPRE_Real res;
hypre_MPI_Comm_size(comm,&num_procs);
hypre_MPI_Comm_rank(comm,&my_id);
if (num_procs > 1)
{
num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg);
v_buf_data = hypre_CTAlloc(HYPRE_Real,
hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_HOST);
Vext_data = hypre_CTAlloc(HYPRE_Real, num_cols_offd, HYPRE_MEMORY_HOST);
if (num_cols_offd)
{
A_offd_j = hypre_CSRMatrixJ(A_offd);
A_offd_data = hypre_CSRMatrixData(A_offd);
}
index = 0;
for (i = 0; i < num_sends; i++)
{
start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i);
for (j=start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++)
v_buf_data[index++]
= u_data[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)];
}
comm_handle = hypre_ParCSRCommHandleCreate( 1, comm_pkg, v_buf_data,
Vext_data);
}
/*-----------------------------------------------------------------
* Copy current approximation into temporary vector.
*-----------------------------------------------------------------*/
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < n; i++)
{
Vtemp_data[i] = u_data[i];
}
if (num_procs > 1)
{
hypre_ParCSRCommHandleDestroy(comm_handle);
comm_handle = NULL;
}
/*-----------------------------------------------------------------
* Relax all points.
*-----------------------------------------------------------------*/
if (relax_points == 0)
{
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i,ii,jj,res) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < n; i++)
{
/*-----------------------------------------------------------
* If diagonal is nonzero, relax point i; otherwise, skip it.
*-----------------------------------------------------------*/
if (A_diag_data[A_diag_i[i]] != zero)
{
res = f_data[i];
for (jj = A_diag_i[i]; jj < A_diag_i[i+1]; jj++)
{
ii = A_diag_j[jj];
res -= A_diag_data[jj] * Vtemp_data[ii];
}
for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++)
{
ii = A_offd_j[jj];
res -= A_offd_data[jj] * Vext_data[ii];
}
u_data[i] += (relax_weight*res) / l1_norms[i];
}
}
}
/*-----------------------------------------------------------------
* Relax only C or F points as determined by relax_points.
*-----------------------------------------------------------------*/
else
{
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i,ii,jj,res) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < n; i++)
{
/*-----------------------------------------------------------
* If i is of the right type ( C or F ) and diagonal is
* nonzero, relax point i; otherwise, skip it.
*-----------------------------------------------------------*/
if (cf_marker[i] == relax_points
&& A_diag_data[A_diag_i[i]] != zero)
{
res = f_data[i];
for (jj = A_diag_i[i]; jj < A_diag_i[i+1]; jj++)
{
ii = A_diag_j[jj];
res -= A_diag_data[jj] * Vtemp_data[ii];
}
for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++)
{
ii = A_offd_j[jj];
res -= A_offd_data[jj] * Vext_data[ii];
}
u_data[i] += (relax_weight * res) / l1_norms[i];
}
}
}
if (num_procs > 1)
{
hypre_TFree(Vext_data, HYPRE_MEMORY_HOST);
hypre_TFree(v_buf_data, HYPRE_MEMORY_HOST);
}
return 0;
}
|
concurrent-curl-openmp.c | #include "helpers.h"
#include "urls.h"
#include <curl/curl.h>
#include <stdio.h>
#include <stdlib.h>
void *dispatch_request(char *url) {
CURL *curl = curl_easy_init();
int http_code = 0;
if (!curl) {
exit(EXIT_FAILURE);
}
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, callback);
curl_easy_perform(curl);
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
print_response_status_code(url, http_code);
curl_easy_cleanup(curl);
return NULL;
}
int main() {
int urls_length = (sizeof(urls) / sizeof(urls[0]));
#pragma omp parallel for
for (int i = 0; i < urls_length; i += 1) {
dispatch_request(urls[i]);
}
}
|
svm.h | #ifndef SVM_H
#define SVM_H
#include <linalg.h>
template <typename T>
T normsq(const Vector<T>& x, const Vector<T>& y) {
return x.nrm2sq()+y.nrm2sq()-2*y.dot(x);
}
template <typename T>
void miso_svm_aux(const Vector<T>& y, const Matrix<T>& X, Vector<T>& w, const T R, const T lambda, const T eps, const int max_iter) {
const int n = y.n();
w.setZeros();
const T L = R+lambda;
const T deltaT = n*MIN(T(1.0)/n,lambda/(2*L));
Vector<T> xi;
Vector<T> alpha(n);
alpha.setZeros();
Vector<T> C(n);
C.setZeros();
Vector<T> tmp;
T dualold=0;
T dual=0;
for (int ii = 0; ii<max_iter; ++ii) {
if (ii > 0 && (ii % (10*n)) == 0) {
X.mult(alpha,w,T(1.0)/n); // to improve numerical stability
X.multTrans(w,tmp);
T primal=0;
for (int kk=0; kk<n; ++kk) {
const T los=MAX(0,1-y[kk]*tmp[kk]);
primal += los*los;
}
primal *= T(0.5)/n;
T reg=0.5*lambda*w.nrm2sq();
primal += reg;
dual=C.mean() - reg;
if (dual <= dualold || (primal - dual) < eps) {
#pragma omp critical
{
cout << "Solver has finished after " << ii << " iterations, primal: " << primal << ", dual: " << dual << ", gap: " << (primal-dual) << endl;
}
break;
}
dualold=dual;
}
const int ind = random() % n;
const T yi=y[ind];
X.refCol(ind,xi);
const T beta = yi*xi.dot(w);
const T gamma=MAX(T(1.0)-beta,0);
T newalpha;
C[ind]=(T(1.0)-deltaT)*C[ind]+deltaT*(T(0.5)*gamma*gamma+beta*gamma);
newalpha=(T(1.0)-deltaT)*(alpha[ind])+deltaT*yi*gamma/lambda;
w.add(xi,(newalpha-alpha[ind])/n);
alpha[ind]=newalpha;
}
};
template <typename T>
void miso_svm_onevsrest(const Vector<T>& yAll, const Matrix<T>& X, Matrix<T>& W, const T lambda, const T eps, const int max_iter, const bool accelerated = false) {
const int n = yAll.n();
const int p = X.m();
const int nclasses=yAll.maxval()+1;
W.resize(p,nclasses);
Vector<T> normX;
X.norm_2sq_cols(normX);
const T R = normX.mean();
cout << "Value of R: " << R << endl;
cout << "Problem size: p x n: " << p << " " << n << endl;
cout << "*********************" << endl;
cout << "Processes Lambda " << lambda << endl;
cout << "Eps " << eps << endl;
int jj;
#pragma omp parallel for private(jj)
for (jj = 0; jj<nclasses; ++jj) {
Vector<T> w;
W.refCol(jj,w);
Vector<T> y(n);
for (int ii = 0; ii<n; ++ii)
y[ii]= abs<T>((yAll[ii] - T(jj))) < T(0.1) ? T(1.0) : -T(1.0);
if (accelerated && T(2.0)*R/n > lambda) {
accelerated_miso_svm_aux(y,X,w,R,lambda,eps,max_iter);
} else {
miso_svm_aux(y,X,w,R,lambda,eps,max_iter);
}
}
}
template <typename T>
void miso_svm(const Vector<T>& y, const Matrix<T>& X, Matrix<T>& W, const Vector<T>& tablambda, const T eps, const int max_iter) {
const int n = y.n();
const int p = X.m();
const int nlambda=tablambda.n();
W.resize(p,nlambda);
W.setZeros();
Vector<T> normX;
X.norm_2sq_cols(normX);
const T R = normX.fmax();
cout << "Problem size: p x n: " << p << " " << n << endl;
for (int jj = 0; jj<nlambda; ++jj) {
const T lambda=tablambda[jj];
cout << "*********************" << endl;
cout << "Processes Lambda " << lambda << endl;
Vector<T> w;
W.refCol(jj,w);
miso_svm_aux(y,X,w,R,lambda,eps,max_iter);
}
}
template <typename T>
void accelerated_miso_svm_aux(const Vector<T>& y, const Matrix<T>& X, Vector<T>& w, const T R, const T lambda, const T eps, const int max_iter) {
const int n = y.n();
const int p = X.m();
w.setZeros();
Vector<T> alpha(n);
alpha.setZeros();
Vector<T> C(n);
C.setZeros();
Vector<T> z(p);
z.setZeros();
Vector<T> zold(p);
zold.setZeros();
Vector<T> wold(p);
wold.setZeros();
Vector<T> xtw(n);
xtw.setZeros();
const T kappa = (T(2.0)*R/n-lambda);
const T q = lambda/(lambda+kappa);
const T qp = T(0.9)*sqrt(q);
const T alphak = sqrt(q);
const T betak=(T(1.0)-alphak)/(T(1.0)+alphak);
T epsk=T(1.0);
T gapk=T(1.0);
T gap=T(1.0);
int total_iters=0;
int counter = 1;
T gapold=T(1.0);
for (int ii=0; ii<max_iter; ++ii) {
epsk *= (T(1.0)-qp);
// check if continue or not
wold.copy(w);
if ((total_iters / (10*n)) >= counter) {
++counter;
w.copy(z);
w.scal(kappa/(kappa+lambda));
X.mult(alpha,w,lambda/(n*(kappa+lambda)),T(1.0));
} else {
w.add(z,kappa/(kappa+lambda));
w.add(zold,-kappa/(kappa+lambda));
}
const T diffNorm = normsq(z,zold);
gapk=(n*(gapk + T(0.5)*(kappa*kappa/(lambda+kappa))*diffNorm));
T loss;
int num_iters;
accelerated_miso_svm_aux2(y, X, w, alpha, C, loss, gapk, num_iters, z, kappa, R, lambda, epsk);
total_iters += num_iters;
const T primal = loss+T(0.5)*lambda*w.nrm2sq();
Vector<T> ws;
ws.copy(w);
ws.scal((kappa+lambda)/lambda);
ws.add(z,-kappa/lambda);
const T dual=C.mean() - T(0.5)*lambda*ws.nrm2sq();
gap=primal-dual;
if ((ii > 30 && gap >= gapold) || gap <= eps || total_iters >= max_iter) {
#pragma omp critical
{
cout << "Iteration " << total_iters << ", inner it: " << ii << ", loss: " << loss << ", primal: " << primal << ", dual: " << dual << ", gap: " << (primal-dual) << endl;
}
break;
}
gapold=gap;
zold.copy(z);
z.copy(w);
z.scal(T(1.0)+betak);
z.add(wold,-betak);
}
};
// need to restart !
template <typename T>
void accelerated_miso_svm_aux2(const Vector<T>& y, const Matrix<T>& X, Vector<T>& w, Vector<T>& alpha, Vector<T>& C, T& loss,T& gap, int& num_iters, const Vector<T>& z, const T kappa, const T R, const T lambda, const T eps) {
const int n = y.n();
// const int p = X.m();
const long long max_iter = static_cast<long long>(floor(log(double(eps)/double(gap))/log(double(1.0)-double(1.0)/n)));
Vector<T> tmp;
Vector<T> xi;
//const T deltaT = n*MIN(T(1.0)/n,(lambda+kappa)/(2*R));
for (int ii = 0; ii<max_iter; ++ii) {
if (ii > 0 && (ii % (n)) == 0) {
loss=0;
X.multTrans(w,tmp);
for (int kk=0; kk<n; ++kk) {
const T los=MAX(0,1-y[kk]*tmp[kk]);
loss += los*los;
}
loss *= T(0.5)/n;
const T reg=T(0.5)*(lambda+kappa)*w.nrm2sq();
const T primal = loss+ reg - kappa*w.dot(z);
const T dual=C.mean() - reg;
if ((primal - dual) < eps) {
// cout << " Inner iteration " << ii << ", loss: " << loss << ", primal: " << primal << ", dual: " << dual << ", gap: " << (primal-dual) << "eps: " << eps << endl;
gap=primal-dual;
num_iters=ii;
break;
}
}
const int ind = random() % n;
const T yi=y[ind];
X.refCol(ind,xi);
const T beta = yi*xi.dot(w);
const T gamma=MAX(T(1.0)-beta,0);
T newalpha;
//if (deltaT > 0.999999999999999999) {
C[ind]=T(0.5)*gamma*gamma+beta*gamma;
newalpha=yi*gamma/lambda;
if (newalpha != alpha[ind])
w.add(xi,lambda*(newalpha-alpha[ind])/(n*(lambda+kappa)));
//} else {
// C[ind]=(T(1.0)-deltaT)*C[ind]+deltaT*(T(0.5)*gamma*gamma+beta*gamma);
// newalpha=(T(1.0)-deltaT)*(alpha[ind])+deltaT*yi*gamma/lambda;
// w.add(xi,lambda*(newalpha-alpha[ind])/(n*(lambda+kappa)));
//` }
alpha[ind]=newalpha;
}
}
#endif
|
matrix_funs_intel_mkl.c | #include "mkl_scalapack.h"
#include "matrix_funs_intel_mkl.h"
double get_seconds_frac(struct timeval start_timeval, struct timeval end_timeval){
long secs_used, micros_used;
secs_used=(end_timeval.tv_sec - start_timeval.tv_sec);
micros_used= ((secs_used*1000000) + end_timeval.tv_usec) - (start_timeval.tv_usec);
return (micros_used/1e6);
}
/* initialize new matrix and set all entries to zero */
mat * matrix_new(int nrows, int ncols)
{
mat *M = malloc(sizeof(mat));
//M->d = (double*)mkl_calloc(nrows*ncols, sizeof(double), 64);
M->d = (double*)calloc(nrows*ncols, sizeof(double));
M->nrows = nrows;
M->ncols = ncols;
return M;
}
/* initialize new vector and set all entries to zero */
vec * vector_new(int nrows)
{
vec *v = malloc(sizeof(vec));
//v->d = (double*)mkl_calloc(nrows,sizeof(double), 64);
v->d = (double*)calloc(nrows,sizeof(double));
v->nrows = nrows;
return v;
}
void matrix_delete(mat *M)
{
//mkl_free(M->d);
free(M->d);
free(M);
}
void vector_delete(vec *v)
{
//mkl_free(v->d);
free(v->d);
free(v);
}
/* copy contents of mat S to D */
void matrix_copy(mat *D, mat *S){
int i;
//#pragma omp parallel for
#pragma omp parallel shared(D,S) private(i)
{
#pragma omp for
for(i=0; i<((S->nrows)*(S->ncols)); i++){
D->d[i] = S->d[i];
}
}
}
/* initialize a random matrix */
void initialize_random_matrix(mat *M){
int i,m,n;
double val;
m = M->nrows;
n = M->ncols;
float a=0.0,sigma=1.0;
int N = m*n;
float *r;
VSLStreamStatePtr stream;
r = (float*)malloc(N*sizeof(float));
vslNewStream( &stream, BRNG, time(NULL) );
//vslNewStream( &stream, BRNG, SEED );
vsRngGaussian( METHOD, stream, N, r, a, sigma );
// read and set elements
#pragma omp parallel shared(M,N,r) private(i,val)
{
#pragma omp parallel for
for(i=0; i<N; i++){
val = r[i];
M->d[i] = val;
}
}
free(r);
}
/* initialize new matrix and set all entries to zero for float*/
void matrix_matrix_mult_row(mat *A, mat* B, mat* C){
double alpha, beta;
alpha = 1.0; beta = 0.0;
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, A->nrows, B->ncols, A->ncols, alpha, A->d, A->ncols, B->d, B->ncols, beta, C->d, C->ncols);
}
void matrix_transpose_matrix_mult_row(mat *A, mat* B, mat* C){
double alpha, beta;
alpha = 1.0; beta = 0.0;
cblas_dgemm(CblasRowMajor, CblasTrans, CblasNoTrans, A->ncols, B->ncols, A->nrows, alpha, A->d, A->ncols, B->d, B->ncols, beta, C->d, C->ncols);
}
/* C = A*B, A is a file on hard disk */
void matrix_matrix_mult_disk(FILE *A, mat *B, mat *C, int row, int col, int l){
int row_size = l;
int read_row_size = row_size;
double alpha, beta;
int i, j; // count
int m=row, n=col, k=B->ncols;
alpha = 1.0;
beta = 0.0;
// printf("matrix_matrix_mult_disk is running\n");
float *M_f = (float*)malloc(read_row_size*n*sizeof(float));
double *M = (double*)malloc(read_row_size*n*sizeof(double));
struct timeval start_timeval_1, end_timeval_1;
struct timeval start_timeval_2, end_timeval_2;
double sum = 0;
double time_1, time_2;
gettimeofday(&start_timeval_1, NULL);
for (i = 0; i < m; i += row_size){
if (row_size > (m - i))
read_row_size = m - i;
gettimeofday(&start_timeval_2, NULL); //time_2
fread(M_f, sizeof(float), n*read_row_size, A);
#pragma omp parallel shared(M, M_f,n,read_row_size) private(j)
{
#pragma omp parallel for
for(j=0; j<n*read_row_size; j++){
M[j] = M_f[j]; //leixing zhuanhuan
}
}
gettimeofday(&end_timeval_2, NULL);
sum += get_seconds_frac(start_timeval_2 ,end_timeval_2);
/* 1*n , n*k = 1*k , all m*k */
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, read_row_size, B->ncols, n, alpha, M, n, B->d, B->ncols, beta, C->d+i*k, C->ncols);
}
gettimeofday(&end_timeval_1, NULL);
time_1 = get_seconds_frac(start_timeval_1 ,end_timeval_1);
time_2 = sum;
printf("Time for reading data file_(fread-time1): %g second\n",time_2);
printf("Time for matrix_matrix_mult: %g second\n", time_1);
free(M_f);
free(M);
}
/* C = A^T*B ; column major */
/* n*m , m*k = n*k , all n*k */
void matrix_transpose_matrix_mult_disk(FILE *A, mat *B, mat *C, int row, int col, int l){
int row_size = l;
int read_row_size = row_size;
double alpha, beta;
int i, j; // count
int m=row, n=col, k=B->ncols;
float *M_f = (float*)malloc(read_row_size*n*sizeof(float));
double *M = (double*)malloc(read_row_size*n*sizeof(double));;
// printf("matrix_transpose_matrix_mult_disk is running\n");
alpha = 1.0;
beta = 1.0;
// innitial C=0
#pragma omp parallel shared(C) private(i)
{
#pragma omp parallel for
for(i=0; i < (C->nrows*C->ncols); i++){
C->d[i] = 0.0;
}
}
struct timeval start_timeval_1, end_timeval_1;
struct timeval start_timeval_2, end_timeval_2;
double sum = 0;
double time_1, time_2;
gettimeofday(&start_timeval_1, NULL);
for (i = 0; i < m; i += row_size){
if (row_size > (m-i) )
read_row_size = m-i;
gettimeofday(&start_timeval_2, NULL); //time_2
fread(M_f, sizeof(float), n*read_row_size, A);
// cblas_dcopy(k, B->d+i*k, 1, g_row, 1); //g_row = g[i];
#pragma omp parallel shared(M,M_f,n,read_row_size) private(j)
{
#pragma omp parallel for
for(j=0; j < n * read_row_size; j++){
M[j] = M_f[j];
}
}
gettimeofday(&end_timeval_2, NULL);
sum += get_seconds_frac(start_timeval_2 ,end_timeval_2);
cblas_dgemm(CblasRowMajor, CblasTrans, CblasNoTrans, n, B->ncols, read_row_size, alpha, M, n, B->d+i*k, B->ncols, beta, C->d, C->ncols);
}
gettimeofday(&end_timeval_1, NULL);
time_1 = get_seconds_frac(start_timeval_1 ,end_timeval_1);
time_2 = sum;
printf("Time for reading data file_(fread-time2): %g second\n",time_2);
printf("Time for matrix_transpose_matrix_mult: %g second\n", time_1);
free(M_f);
free(M);
}
/* Performs [Q,R] = qr(M,'0') compact QR factorization
M is mxn ; Q is mxn ; R is min(m,n) x min(m,n) */
void compact_QR_factorization(mat *M, mat *Q, mat *R){
int i,j,m,n,k;
m = M->nrows; n = M->ncols;
k = min(m,n);
mat *R_full = matrix_new(m,n);
matrix_copy(R_full,M);
//vec *tau = vector_new(n);
vec *tau = vector_new(k);
// get R
//printf("get R..\n");
//LAPACKE_dgeqrf(CblasColMajor, m, n, R_full->d, n, tau->d);
LAPACKE_dgeqrf(LAPACK_ROW_MAJOR, R_full->nrows, R_full->ncols, R_full->d, R_full->ncols, tau->d);
for(i=0; i<k; i++){
for(j=0; j<k; j++){
if(j>=i){
matrix_set_element(R,i,j,matrix_get_element(R_full,i,j));
}
}
}
// get Q
matrix_copy(Q,R_full);
//printf("dorgqr..\n");
LAPACKE_dorgqr(LAPACK_ROW_MAJOR, Q->nrows, Q->ncols, min(Q->ncols,Q->nrows), Q->d, Q->ncols, tau->d);
// clean up
matrix_delete(R_full);
vector_delete(tau);
}
/* orth (Q)*/
void QR_factorization_getQ_inplace(mat *Q){
int i,j,m,n,k;
m = Q->nrows; n = Q->ncols;
k = min(m,n);
vec *tau = vector_new(k);
/* do QR */ //sometime core dump, bug of MKL
//LAPACKE_dgeqrf(LAPACK_ROW_MAJOR, m, n, Q->d, n, tau->d);
/* do QRCP */ //more stable, but more expensive
printf("Warning: use QRCP to replace QR! (see line 269 of matrix_funs_intel_mkl.c)\n");
int *jpvt = (int *)malloc(sizeof(int)*n);
LAPACKE_dgeqpf(LAPACK_ROW_MAJOR, m, n, Q->d, n, jpvt, tau->d);
free(jpvt);
LAPACKE_dorgqr(LAPACK_ROW_MAJOR, m, n, k, Q->d, n, tau->d);
vector_delete(tau);
}
/* M(:,inds) = Mc */
void matrix_set_selected_columns(mat *M, int *inds, mat *Mc){
int i;
vec *col_vec;
#pragma omp parallel shared(M,Mc,inds) private(i,col_vec)
{
#pragma omp parallel for
for(i=0; i<(Mc->ncols); i++){
col_vec = vector_new(M->nrows);
matrix_get_col(Mc,i,col_vec);
matrix_set_col(M,inds[i],col_vec);
vector_delete(col_vec);
}
}
}
/* M(inds,:) = Mr */
void matrix_set_selected_rows(mat *M, int *inds, mat *Mr){ //modify
int i;
vec *row_vec;
#pragma omp parallel shared(M,Mr,inds) private(i,row_vec)
{
#pragma omp parallel for
for(i=0; i<(Mr->nrows); i++){
row_vec = vector_new(M->ncols);
matrix_get_row(Mr,i,row_vec);
matrix_set_row(M,inds[i],row_vec);
vector_delete(row_vec);
}
}
}
/* Mc = M(:,inds) */
void matrix_get_selected_columns(mat *M, int *inds, mat *Mc){ //modify
int i;
vec *col_vec;
#pragma omp parallel shared(M,Mc,inds) private(i,col_vec)
{
#pragma omp parallel for
for(i=0; i<(Mc->ncols); i++){
col_vec = vector_new(M->nrows);
matrix_get_col(M,inds[i],col_vec);
matrix_set_col(Mc,i,col_vec);
vector_delete(col_vec);
}
}
}
/* extract column of a matrix into a vector */
void matrix_get_col(mat *M, int j, vec *column_vec){//modify
int i;
// unclear
#pragma omp parallel shared(column_vec,M,j) private(i)
{//unclear
#pragma omp parallel for
for(i=0; i<M->nrows; i++){
vector_set_element(column_vec,i,matrix_get_element(M,i,j));
}
}
}
/* extract row i of a matrix into a vector */
void matrix_get_row(mat *M, int i, vec *row_vec){//modify
int j;
#pragma omp parallel shared(row_vec,M,i) private(j)
{
#pragma omp parallel for
for(j=0; j<M->ncols; j++){
vector_set_element(row_vec,j,matrix_get_element(M,i,j));
}
}
}
/* set column of matrix to vector */
void matrix_set_col(mat *M, int j, vec *column_vec){ //modify
int i;
#pragma omp parallel shared(column_vec,M,j) private(i)
{
#pragma omp for
for(i=0; i<M->nrows; i++){
matrix_set_element(M,i,j,vector_get_element(column_vec,i));
}
}
}
/* put vector row_vec as row i of a matrix */
void matrix_set_row(mat *M, int i, vec *row_vec){ //modify
int j;
#pragma omp parallel shared(row_vec,M,i) private(j)
{
#pragma omp parallel for
for(j=0; j<M->ncols; j++){
matrix_set_element(M,i,j,vector_get_element(row_vec,j));
}
}
}
/* set vector element */
void vector_set_element(vec *v, int row_num, double val){ //modify
v->d[row_num] = val;
}
/* set element in column major format */
void matrix_set_element(mat *M, int row_num, int col_num, double val){ //modify
M->d[row_num*(M->ncols) + col_num] = val;
}
/* get element in column major format */
double matrix_get_element(mat *M, int row_num, int col_num){ //modify
return M->d[row_num*(M->ncols) + col_num];
}
double vector_get_element(vec *v, int row_num){
return v->d[row_num];
}
/*********************Lijian***********************/
/* C = A*B & D = A^T*C */
void matrix_union_matrix_mult_disk_mem(FILE *A, mat *B, mat *C, mat *D, int row, int col, int row_size){
int read_row_size = row_size;
double alpha, beta ,gama;
int i, j; // count
int m=row, n=col, k=B->ncols;
float *M_f = (float*)malloc(read_row_size*n*sizeof(float));
double *M = (double*)malloc(read_row_size*n*sizeof(double));
// double *g_row= (double*)malloc(k*sizeof(double)); //C's row vector'
//printf("matrix_union_matrix_mult_disk_mem is running\n");
alpha = 1.0;
beta = 0.0;
gama = 1.0;
struct timeval start_timeval_1, end_timeval_1;
struct timeval start_timeval_2, end_timeval_2;
double sum = 0;
double time_1, time_2;
gettimeofday(&start_timeval_1, NULL); //time_1
// #pragma omp parallel shared(D) private(i)
// {
// #pragma omp parallel for
// for(i=0; i < (D->nrows*D->ncols); i++){
// D->d[i] = 0.0;
// }
// }
for (i = 0; i < m; i += row_size)
{
if (row_size > (m-i) )
read_row_size = m-i;
gettimeofday(&start_timeval_2, NULL); //time_2
fread(M_f, sizeof(float), n*read_row_size, A);
#pragma omp parallel shared(M,M_f,n,read_row_size) private(j)
{
#pragma omp parallel for
for(j=0; j < n*read_row_size; j++){
M[j] = M_f[j];
}
}
gettimeofday(&end_timeval_2, NULL);
sum += get_seconds_frac(start_timeval_2 ,end_timeval_2);
// C = A*D
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, read_row_size, B->ncols, n, alpha, M, n, B->d, B->ncols, beta, C->d+i*k, C->ncols);
// B = A^T*C exchange B & C
// cblas_dcopy(k, C->d+i*k, 1, g_row, 1); //g_row = g[i];
// cblas_dger(CblasRowMajor, D->nrows, D->ncols, alpha, M, 1, g_row, 1, D->d, D->ncols); //A := alpha*x*y'+ A,
cblas_dgemm(CblasRowMajor, CblasTrans, CblasNoTrans, n, C->ncols, read_row_size, alpha, M, n, C->d+i*k, C->ncols, gama, D->d, D->ncols);
}
gettimeofday(&end_timeval_1, NULL);
time_1 = get_seconds_frac(start_timeval_1 ,end_timeval_1);
time_2 = sum;
printf("Time for reading data file_(fread-time): %g second\n",time_2);
printf("Time for matrix_union_matrix_mult: %g second\n", time_1);
//printf("matrix_union_mem is %d KB\n", getCurrentRSS()/1024);
free(M_f);
free(M);
}
//input A B C
//output D E
// D=A*B E=A^T*C
void matrix_union_matrix_mult_disk_mem_2(FILE *A, mat *B, mat *C, mat *D, mat*E, int row, int col, int row_size){
int read_row_size = row_size;
double alpha, beta ,gama;
int i, j; // count
int m=row, n=col, k=B->ncols;
float *M_f = (float*)malloc(read_row_size*n*sizeof(float));
double *M = (double*)malloc(read_row_size*n*sizeof(double));
// double *g_row= (double*)malloc(k*sizeof(double)); //C's row vector'
//printf("matrix_union_matrix_mult_disk_mem_2 is running\n");
//matrix_copy(D,B); //D=B
// float *a_g_mult=(float*)malloc(n*k*sizeof(float)); // ai * gi , n*k
alpha = 1.0;
beta = 0.0;
gama = 1.0;
struct timeval start_timeval_1, end_timeval_1;
struct timeval start_timeval_2, end_timeval_2;
double sum = 0;
double time_1, time_2;
gettimeofday(&start_timeval_1, NULL); //time_1
// #pragma omp parallel shared(E) private(i)
// {
// #pragma omp parallel for
// for(i=0; i < (E->nrows*E->ncols); i++){
// E->d[i] = 0.0;
// }
// }
for (i = 0; i < m; i += row_size)
{
if (row_size > (m-i) )
read_row_size = m-i;
gettimeofday(&start_timeval_2, NULL); //time_2
fread(M_f, sizeof(float), n*read_row_size, A);
#pragma omp parallel shared(M,M_f,n,read_row_size) private(j)
{
#pragma omp parallel for
for(j=0; j < n*read_row_size; j++){
M[j] = M_f[j];
}
}
gettimeofday(&end_timeval_2, NULL);
sum += get_seconds_frac(start_timeval_2 ,end_timeval_2);
// C = A*D
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, read_row_size, B->ncols, n, alpha, M, n, B->d, B->ncols, beta, D->d+i*k, D->ncols);
// B = A^T*C exchange B & C
// cblas_dcopy(k, C->d+i*k, 1, g_row, 1); //g_row = g[i];
// cblas_dger(CblasRowMajor, D->nrows, D->ncols, alpha, M, 1, g_row, 1, D->d, D->ncols); //A := alpha*x*y'+ A,
cblas_dgemm(CblasRowMajor, CblasTrans, CblasNoTrans, n, C->ncols, read_row_size, alpha, M, n, C->d+(i*C->ncols), C->ncols, gama, E->d, E->ncols);
}
gettimeofday(&end_timeval_1, NULL);
time_1 = get_seconds_frac(start_timeval_1 ,end_timeval_1);
time_2 = sum;
printf("Time for reading data file_(fread-time): %g second\n",time_2);
printf("Time for matrix_union_matrix_mult2: %g second\n", time_1);
free(M_f);
free(M);
}
/* k*n = k*k k*k n*k */
void svd_row_cut (mat *A, mat *U, vec *E, mat * V)
{
int m = A->nrows;
int n = A->ncols;
int i, j;
// mat *A_in = matrix_new(m,n);;
// matrix_copy(A_in, A);
// printf("dong tai sheng qing\n");
// double *u = (double*)malloc(m*m*sizeof(double));
double *vt = (double*)malloc(n*m*sizeof(double));
// printf("svd is running\n");
// LAPACKE_dgesvd(LAPACK_ROW_MAJOR, 'A', 'S', m, n, A->d, n, E->d, U->d, m, vt, n, superb);
// LAPACKE_dgesdd( int matrix_layout, char jobz, lapack_int m, lapack_int n, double* a, lapack_int lda, double* s, double* u, lapack_int ldu, double* vt, lapack_int ldvt );
LAPACKE_dgesdd(LAPACK_ROW_MAJOR,'S', m, n, A->d, n, E->d, U->d, m, vt, n);
//printf("Complete Lapack svd\n\n");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
V->d[j * m + i] = vt[i * n+ j] ;
}
}
// printf("svd_row_cut is over\n");
// matrix_delete(A_in);
free(vt);
}
/* D = M(:,inds)' */
void matrix_get_selected_columns_and_transpose(mat *M, int *inds, mat *Mc){
int i;
vec *col_vec;
#pragma omp parallel shared(M,Mc,inds) private(i,col_vec)
{
#pragma omp parallel for
for(i=0; i<(Mc->nrows); i++){
col_vec = vector_new(M->nrows);
matrix_get_col(M,inds[i],col_vec);
matrix_set_row(Mc,i,col_vec);
vector_delete(col_vec);
}
}
}
void linear_solve_UTxb(mat *A, mat *b) {
LAPACKE_dtrtrs(LAPACK_ROW_MAJOR, 'U', 'T', 'N', //unclear
b->nrows,
b->ncols,
A->d,
A->ncols,
b->d,
b->ncols
);
}
/* C = beta*C + alpha*A(1:Anrows, 1:Ancols)[T]*B(1:Bnrows, 1:Bncols)[T] */
void submatrix_submatrix_mult_with_ab(mat *A, mat *B, mat *C,
int Anrows, int Ancols, int Bnrows, int Bncols, int transa, int transb, double alpha, double beta) {
int opAnrows, opAncols, opBnrows, opBncols;
if (transa == CblasTrans) {
opAnrows = Ancols;
opAncols = Anrows;
} else {
opAnrows = Anrows;
opAncols = Ancols;
}
if (transb == CblasTrans) {
opBnrows = Bncols;
opBncols = Bnrows;
} else {
opBnrows = Bnrows;
opBncols = Bncols;
}
if (opAncols != opBnrows) {
printf("error in submatrix_submatrix_mult()");
exit(0);
}
cblas_dgemm(CblasRowMajor, transa, transb,
opAnrows, opBncols, // m, n,
opAncols, // k
alpha, A->d, A->ncols, // lda // modify
B->d, B->ncols, // ldb
beta, C->d, C->ncols // ldc
);
}
void submatrix_submatrix_mult(mat *A, mat *B, mat *C, int Anrows, int Ancols, int Bnrows, int Bncols, int transa, int transb) {
double alpha, beta;
alpha = 1.0; beta = 0.0;
submatrix_submatrix_mult_with_ab(A, B, C, Anrows, Ancols, Bnrows, Bncols, transa, transb, alpha, beta);
}
|
rose_cancel.c | #include <stdio.h>
#ifdef _OPENMP
#include <omp.h>
#endif
#include "libxomp.h"
struct OUT__1__9556___data
{
void *iend_p;
void *ist_p;
}
;
static void OUT__1__9556__(void *__out_argv);
void foo(int iend,int ist)
{
int i;
struct OUT__1__9556___data __out_argv1__9556__;
__out_argv1__9556__ . ist_p = ((void *)(&ist));
__out_argv1__9556__ . iend_p = ((void *)(&iend));
XOMP_parallel_start(OUT__1__9556__,&__out_argv1__9556__,1,0,"/home/awang15/Projects/rexdev/rex_src/tests/nonsmoke/functional/CompileTests/OpenMP_tests/cancel.c",8);
XOMP_parallel_end("/home/awang15/Projects/rexdev/rex_src/tests/nonsmoke/functional/CompileTests/OpenMP_tests/cancel.c",18);
}
static void OUT__1__9556__(void *__out_argv)
{
int *iend = (int *)(((struct OUT__1__9556___data *)__out_argv) -> iend_p);
int *ist = (int *)(((struct OUT__1__9556___data *)__out_argv) -> ist_p);
if (XOMP_single()) {
printf("Using %d threads.\n",(omp_get_num_threads()));
}
XOMP_barrier();
{
int _p_i;
long p_index_;
long p_lower_;
long p_upper_;
XOMP_loop_default( *iend, *ist,-1,&p_lower_,&p_upper_);
for (p_index_ = p_lower_; p_index_ >= p_upper_; p_index_ += -1) {
printf("Iteration %d is carried out by thread %d\n",p_index_,(omp_get_thread_num()));
}
}
#pragma omp cancel parallel
}
|
function.h | #ifndef FUNCTION_
#define FUNCTION_
#include <iostream>
#include <algorithm>
#include <cstring>
#include "util.h"
//////////////////////////// Hierarchy of classes: ///////////////////////////////////////
//
// base clas = function<>
// | |
// function1D<> funProxy<>
//
// function2D<funProxy>
//
//*****************************************//
// Classes also used in this header file //
//*****************************************//
class intpar;
//class intpari;
//*******************************************************//
// Classes and functions implemented in this header file //
//*******************************************************//
template<class T> class functionb;
template<class T> class function1D;
template<class T> class funProxy;
template<class T> class function2D;
//********************************************************************************//
// Base class for two derived classes: function1D<T> and function2D<T>. //
// It is also used as a proxy class for function2D. Function2D<T> consists of //
// arrays of function<T> rather than functions1D<T>. //
// Memory is allocated in a fortran-like fashion for better performance. //
// Linear interpolation is implemented with the operator() that takes one //
// argument (class intpar). //
//********************************************************************************//
template<class T>
class functionb{
protected:
T *f;
int N0, N;
public:
T& operator[](int i) {Assert(i<N,"Out of range in functionb[]"); return f[i];}
const T& operator[](int i) const {Assert(i<N,"Out of range in functionb[]"); return f[i];}
const T& last() const {return f[N-1];}
int size() const { return N;}
int fullsize() const { return N0;}
T operator()(const intpar& ip) const;
// T operator()(const intpari& ip, const functionb& fp) const;
functionb& operator+=(const functionb& m);
functionb& operator*=(const T& m);
T accumulate();
T* MemPt(){return f;}
const T* MemPt() const{return f;}
functionb& operator=(const T& c);
template <class meshx>
void CalcFermOnMesh(double beta, const meshx& om);
template <class meshx>
void CalcLogOnMesh(const meshx& om);
template <class meshx>
void CalcTanhOnMesh(double beta, const meshx& om);
template <class meshx>
void CalcBoseOnMesh(double beta, const meshx& om);
template <class meshx, class functiond>
void KramarsKronig(const meshx& om, const functiond& logo);
template <class meshx, class functiond, class functiond1D>
void KramarsKronig(const functiond& Sigt, const meshx& om, const functiond1D& fe, const functiond1D& logo);
template <class functor>
void Set(functor& functn);
void SetProduct(const functionb& m, const T& p);
void SumUp(const functionb<T>& x, const functionb<T>& y);
protected:
functionb() : f(NULL), N0(0), N(0) {};
explicit functionb(int N_) : N0(N_), N(N_) {};
~functionb(){};
functionb(const functionb&){};
template<class U> friend class function2D;
template <class U> friend U scalar_product(const functionb<U>& f1, const functionb<U>& f2);
};
//******************************************************************//
// One dimensional functions derived from function<T>. It has it's //
// own constructors and destructors. //
//******************************************************************//
template <class T>
class function1D : public functionb<T>{
public:
function1D(){};
explicit function1D(int N_);
~function1D();
function1D(const function1D& m);
void resize(int N_);
// equivalent to f=-f0
function1D& assignm(const function1D& f0);
function1D& operator=(const function1D& m);
function1D& operator=(const T& c) {functionb<T>::operator=(c); return *this;}
template <class meshx>
void CalcFermOnMesh(double beta, const meshx& om);
template <class meshx>
void CalcLogOnMesh(const meshx& om);
template <class meshx>
void CalcBoseOnMesh(double beta, const meshx& om);
template <class meshx>
void CalcTanhOnMesh(double beta, const meshx& om);
template <class meshx, class functiond>
void KramarsKronig(const functiond& Sigt, const meshx& om, const functiond& fe, const functiond& logo);
template <class meshx, class functiond>
void KramarsKronig(const meshx& om, const functiond& logo);
function1D<double> treshold(const function1D<double>& fe);
};
template <class T>
class funProxy : public functionb<T>{
public:
void Initialize(int N_, T* f_);
void ReInitialize(int N_, T* f_);
void resize(int N_);
funProxy& operator=(const functionb<T>& m);
~funProxy(){};
};
//**********************************************************************//
// Two dimentional function<T> derived from function<T>. It consists //
// of an array of function<T> rather tham function1D<T>. //
// Constructor calls operator new and aferwords placement new operator //
// to allocate the whole memory in one single large peace. //
//**********************************************************************//
template<class T>
class function2D{
protected:
void *memory;
T* data;
funProxy<T> *f;
int N0, Nd0, N, Nd;
public:
function2D() : memory(NULL), N0(0), Nd0(0), N(0), Nd(0) {};
function2D(int N_, int Nd_);
~function2D();
funProxy<T>& operator[](int i) {Assert(i<N,"Out of range in function2D[]"); return f[i];}
const funProxy<T>& operator[](int i) const {Assert(i<N,"Out of range in function2D[]"); return f[i];}
const T& operator()(int i, int j) const {Assert(i<N && j<Nd,"Out of range in function2D(i,j)"); return f[i].f[j];}
T& operator()(int i, int j) {Assert(i<N && j<Nd,"Out of range in function2D(i,j)"); return f[i].f[j];}
T* MemPt() { return data;}
const T* MemPt() const { return data;}
int size_N() const {return N;}
int size_Nd() const {return Nd;}
int fullsize_N() const {return N0;}
int fullsize_Nd() const {return Nd0;}
int lda() const {return Nd0;}
void resize(int N_, int Nd_);
function2D& operator=(const function2D& m);
function2D& operator+=(double x);
function2D& operator+=(const function2D& m);
function2D& operator-=(double x);
function2D& operator-=(const function2D& m);
function2D& operator=(const T& u);
function2D& operator*=(const T& x);
template <class functor>
void Set(functor& functn);
template <class functor, class W>
void Set(functor& functn, const function2D<W>& Um);
// void Product(const function2D& A, const function2D& B, const T& alpha, const T& beta);
void Product(const function2D& A, const function2D& B, int start=0, int end=-1, const T& alpha=1, const T& beta=0);
void DotProduct(const function2D& A, const function2D& B, const T& alpha=1, const T& beta=0);
void TProduct(const function2D& A, const function2D& B, const T& alpha=1, const T& beta=0);
void SymmProduct(const function2D& A, const function2D& B, const T& alpha=1, const T& beta=0);
void TSymmProduct(const function2D& A, const function2D& B, const T& alpha=1, const T& beta=0);
template <class meshx, class functiond>
void KramarsKronig(const meshx& om, const functiond& logo, functiond& sum, functiond& odvSig);
};
template <class fun, class fun1, class fun2>
void multiply(fun& f, const fun1& a, const fun2& b);
// functionb ////////////////////////////////////////////////////////////////
template<class T>
inline T functionb<T>::operator()(const intpar& ip) const
{
return f[ip.i]+ip.p*(f[ip.i+1]-f[ip.i]);
}
template<class T>
inline functionb<T>& functionb<T>::operator+=(const functionb& m)
{
SUNCA_LOG(if (N!=m.size()) std::cerr << "Functions not of equal length! Can't sum!" << std::endl;)
for (int i=0; i<N; i++) f[i] += m[i];
return *this;
}
template<class T>
inline functionb<T>& functionb<T>::operator*=(const T& m)
{
for (int i=0; i<N; i++) f[i] *= m;
return *this;
}
template <class T>
inline T functionb<T>::accumulate()
{
T sum(0);
for (int i=0; i<N; ++i) sum += f[i];
return sum;
}
template <class T>
inline functionb<T>& functionb<T>::operator=(const T& c)
{
SUNCA_LOG(if (N<=0) std::cerr << "Size of function is non positive! "<<N<<std::endl;)
for (int i=0; i<N; i++) f[i] = c;
return *this;
}
template <class T>
template <class meshx>
inline void functionb<T>::CalcFermOnMesh(double beta, const meshx& om)
{
for (int i=0; i<om.size(); i++){
f[i] = 1.0/(1.0+exp(om[i]*beta));
}
}
template <class T>
template <class meshx>
inline void functionb<T>::CalcBoseOnMesh(double beta, const meshx& om)
{
for (int i=0; i<om.size(); i++){
f[i] = 1.0/(exp(om[i]*beta)-1.0);
}
}
template <class T>
template <class meshx>
inline void functionb<T>::CalcTanhOnMesh(double beta, const meshx& om)
{
for (int i=0; i<om.size(); i++){
double e = exp(beta*om[i]);
f[i] = (e-1)/(e+1);
}
}
template <class T>
template <class meshx>
inline void functionb<T>::CalcLogOnMesh(const meshx& om)
{
for (int i=0; i<om.size(); i++){
f[i] = (i!=0 && i!=om.size()-1) ? log((om.last()-om[i])/(om[i]-om[0])) : 0.0;
}
}
template <class T>
template <class meshx, class functiond>
void functionb<T>::KramarsKronig(const meshx& om, const functiond& logo)
{
if (logo.size()!=om.size()||om.size()!=N)
std::cerr<<"Functions not of equal size in KramarsKronig"<<std::endl;
#pragma omp parallel for
for (int i=0; i<om.size(); i++){
const double omom2 = (i>0) ? om.Delta(i-1) : 0.0;
const int ip1 = (i<om.size()-1) ? i+1 : i, im1 = (i>0) ? i-1 : i;
const double odvSig = 0.5*(om.Delta(i)*(f[ip1].imag()-f[i].imag()) + omom2*(f[i].imag()-f[im1].imag()));
const double Sigii = f[i].imag();
double sum = 0;
for (int j=0; j<om.size(); j++){
if (i!=j)
sum += (f[j].imag()-Sigii)*om.Dh(j)/(om[j]-om[i]);
else
sum += odvSig*om.Dh(j);
}
f[i].real()=(sum+Sigii*logo[i])/M_PI;
}
}
template <class T>
template <class meshx, class functiond, class functiond1D>
inline void functionb<T>::KramarsKronig(const functiond& Sigi, const meshx& om, const functiond1D& fe, const functiond1D& logo)
{
if (fe.size()!=om.size()||Sigi.size()!=om.size())
std::cerr<<"Functions not of equal size in KramarsKronig"<<std::endl;
for (int i=0; i<om.size(); i++) f[i].imag()=(1-fe[i])*Sigi[i];
KramarsKronig(om, logo);
}
template <class T>
template <class functor>
inline void functionb<T>::Set(functor& functn)
{
for (int i=0; i<N; i++) f[i]=functn(f[i]);
}
template <class T>
inline void functionb<T>::SetProduct(const functionb& m, const T& p)
{
SUNCA_LOG(if (N<m.N) std::cerr<<"Size of function too small in SetProduct!"<<std::endl;);
for (int i=0; i<m.N; i++) f[i] = m.f[i]*p;
}
template <class T>
void functionb<T>::SumUp(const functionb<T>& x, const functionb<T>& y)
{
if (x.size()!=y.size()) std::cerr<<"Size of functions to sum up is different!"<<std::endl;
if (N<x.size()) {
std::cerr<<"The target function to small in the SumUp function! Can't continue!"<<std::endl;
return;
}
for (int i=0; i<x.size(); i++){
f[i] = x[i]+y[i];
}
}
// function1D ////////////////////////////////////////////////////////////
template<class T>
inline function1D<T>::function1D(int N_) : functionb<T>(N_)
{
this->f = new T[N_];
}
template<class T>
inline function1D<T>::~function1D()
{
delete[] this->f;
this->f = NULL;
}
template<class T>
inline void function1D<T>::resize(int n)
{
if (n>this->N0){
if (this->f) delete[] this->f;
this->f = new T[n];
this->N0=n;
}
this->N = n;
}
template<class T>
inline function1D<T>::function1D(const function1D& m)
{
resize(m.N);
std::copy(m.f,m.f+this->N,this->f);
}
template <class T>
inline function1D<T>& function1D<T>::operator=(const function1D<T>& m)
{
resize(m.N);
std::copy(m.f,m.f+this->N,this->f);
return *this;
}
template<class T>
inline function1D<T>& function1D<T>::assignm(const function1D& f0)
{
resize(f0.N);
for (int i=0; i<this->N; i++) this->f[i] = -f0.f[i];
return *this;
}
template <class T>
template <class meshx>
inline void function1D<T>::CalcFermOnMesh(double beta, const meshx& om)
{
resize(om.size());
functionb<double>::CalcFermOnMesh(beta,om);
}
template <class T>
template <class meshx>
inline void function1D<T>::CalcBoseOnMesh(double beta, const meshx& om)
{
resize(om.size());
functionb<double>::CalcBoseOnMesh(beta,om);
}
template <class T>
template <class meshx>
inline void function1D<T>::CalcTanhOnMesh(double beta, const meshx& om)
{
resize(om.size());
functionb<double>::CalcTanhOnMesh(beta,om);
}
template <class T>
template <class meshx>
inline void function1D<T>::CalcLogOnMesh(const meshx& om)
{
resize(om.size());
functionb<double>::CalcLogOnMesh(om);
}
template <class T>
template <class meshx, class functiond>
inline void function1D<T>::KramarsKronig(const functiond& Sigi, const meshx& om, const functiond& fe, const functiond& logo)
{
resize(om.size());
functionb<T>::KramarsKronig(Sigi, om, fe, logo);
}
template <class T>
template <class meshx, class functiond>
inline void function1D<T>::KramarsKronig(const meshx& om, const functiond& logo)
{
resize(om.size());
functionb<T>::KramarsKronig(om, logo);
}
template <>
inline function1D<double> function1D<double>::treshold(const function1D<double>& fe)
{
SUNCA_LOG(if (fe.size()!=N) std::cerr<<"Fermi function not of correct size!"<<std::endl;);
function1D<double> S(N);
for (int i=0; i<N; i++) S[i]=f[i]*(1-fe[i]);
return S;
}
// funProxy ///////////////////////////////////////////////////////////////
template <class T>
inline void funProxy<T>::Initialize(int N_, T* f_)
{
this->N = this->N0 = N_; this->f = f_;
}
template <class T>
inline void funProxy<T>::ReInitialize(int N_, T* f_)
{
this->N = N_; this->f = f_;
}
template <class T>
inline void funProxy<T>::resize(int N_)
{
if (N_>this->N0) std::cerr<<"Can't resize funProxy, to small funProxy!"<<std::endl;
else this->N=N_;
}
template <class T>
inline funProxy<T>& funProxy<T>::operator=(const functionb<T>& m)
{
resize(m.size());
std::copy(m.MemPt(),m.MemPt()+this->N,this->f);
return *this;
}
// function2D ////////////////////////////////////////////////////////////
template<class T>
function2D<T>::function2D(int N_, int Nd_) : N0(N_), Nd0(Nd_), N(N_), Nd(Nd_)
{
memory = operator new (sizeof(funProxy<T>)*N0+sizeof(T)*Nd0*N0+HPoffset);
Assert(memory!=NULL,"Out of memory");
f = new (memory) funProxy<T>[N0];
int offset = sizeof(funProxy<T>)*N0+HPoffset;
data = reinterpret_cast<T*>(static_cast<char*>(memory)+offset);
for (int i=0; i<N0; i++) f[i].Initialize(Nd0,data+i*Nd0);
}
template<class T>
function2D<T>::~function2D()
{
for (int i=0; i<N0; i++){
f[i].~funProxy<T>();
}
operator delete(memory);
memory = NULL;
}
template <class T>
inline function2D<T>& function2D<T>::operator=(const function2D& m)
{
if (m.N<=N0 && m.Nd<=Nd0){
N = m.N; Nd = m.Nd;
for (int i=0; i<N; i++) memcpy(f[i].f, m.f[i].f, sizeof(T)*Nd);
} else{
int msize = sizeof(funProxy<T>)*m.N+sizeof(T)*m.Nd*m.N+HPoffset;
operator delete(memory);
memory = operator new (msize);
Assert(memory!=NULL,"Out of memory");
memcpy(memory, m.memory, msize);
N = N0 = m.N; Nd = Nd0 = m.Nd;
f = new (memory) funProxy<T>[N];
int offset = sizeof(funProxy<T>)*N+HPoffset;
data = reinterpret_cast<T*>(static_cast<char*>(memory)+offset);
for (int i=0; i<N; i++) f[i].Initialize(Nd, data+i*Nd);
}
return *this;
}
template <class T>
inline void function2D<T>::resize(int N_, int Nd_)
{
if (N_>N0 || Nd_>Nd0){
// clog<<"Deleting function2D and resizing from "<<N0<<" "<<Nd0<<" to "<<N_<<" "<<Nd_<<std::endl;
int msize = sizeof(funProxy<T>)*N_ +sizeof(T)*Nd_*N_+HPoffset;
operator delete(memory);
memory = operator new (msize);
Assert(memory!=NULL,"Out of memory");
N = N0 = N_; Nd = Nd0 = Nd_;
f = new (memory) funProxy<T>[N];
int offset = sizeof(funProxy<T>)*N+HPoffset;
data = reinterpret_cast<T*>(static_cast<char*>(memory)+offset);
for (int i=0; i<N; i++) f[i].Initialize(Nd, data+i*Nd);
} else{
N = N_; Nd = Nd_;
}
}
template <class T>
template <class functor>
inline void function2D<T>::Set(functor& functn)
{
for (int i=0; i<N; i++)
for (int j=0; j<Nd; j++)
f[i][j] = functn(f[i][j]);
}
template <class T>
template <class functor, class W>
inline void function2D<T>::Set(functor& functn, const function2D<W>& Um)
{
if (N0<Um.size_N() || Nd0<Um.size_Nd()){
std::cerr << "To small function2D for Set functor!" << std::endl;
return;
}
N = Um.size_N();
if (Nd != Um.size_Nd()){
Nd = Um.size_Nd();
for (int i=0; i<N; i++) f[i].resize(Nd);
}
for (int i=0; i<N; i++)
for (int j=0; j<Nd; j++)
f[i][j] = functn(Um[i][j]);
}
// template <class T>
// inline void function2D<T>::Product(const function2D& A, const function2D& B, const T& alpha=1, const T& beta=0)
// {
// if (A.Nd != B.Nd || !B.N || !A.N || !A.Nd || !B.Nd || N0<A.N || Nd0<B.N)
// std::cerr << " Matrix sizes not correct" << std::endl;
// xgemm("T", "N", B.N, A.N, B.Nd, alpha, B.MemPt(), B.Nd0, A.MemPt(), A.Nd0, beta, MemPt(), Nd0);
// N = A.N; Nd = B.N;
// }
template <class T>
inline void function2D<T>::Product(const function2D& A, const function2D& B, int start, int end, const T& alpha, const T& beta)
{
if (end==0){end=B.N;}
if (A.Nd != B.Nd || !B.N || !A.N || !A.Nd || !B.Nd || N0<A.N || Nd0<end-start || end>B.N || start>=B.N)
std::cerr << " Matrix sizes not correct" << std::endl;
xgemm("T", "N", end-start, A.N, B.Nd, alpha, B[start].MemPt(), B.Nd0, A.MemPt(), A.Nd0, beta, MemPt(), Nd0);
N = A.N; Nd = end-start;
}
template <class T>
inline void function2D<T>::TProduct(const function2D& A, const function2D& B, const T& alpha, const T& beta)
{
if (A.Nd != B.Nd || !B.N || !A.N || !A.Nd || !B.Nd || N0<B.N || Nd0<A.N)
std::cerr << " Matrix sizes not correct" << std::endl;
// clog<<"A.MemPt()="<<A.MemPt()<<" B.MemPt()="<<B.MemPt()<<" C.MemPt()="<<MemPt()<<std::endl;
// clog<<"A.End()="<<A.MemPt()+A.N0*A.Nd0<<" B.End()="<<B.MemPt()+B.N0*B.Nd0<<" C.Endt()="<<MemPt()+N0*Nd0<<std::endl;
xgemm("T", "N", A.N, B.N, A.Nd, alpha, A.MemPt(), A.Nd0, B.MemPt(), B.Nd0, beta, MemPt(), Nd0);
N = B.N; Nd = A.N;
}
template <class T>
inline void function2D<T>::SymmProduct(const function2D& A, const function2D& B, const T& alpha, const T& beta)
{
if (A.Nd != B.Nd || !B.N || !A.N || !A.Nd || !B.Nd || N0<A.N || Nd0<B.N)
std::cerr << " Matrix sizes not correct" << std::endl;
xsymm("R", "L", A.N, B.N, alpha, A.MemPt(), A.Nd0, B.MemPt(), B.Nd0, beta, MemPt(), Nd0);
N = B.N; Nd = A.N;
}
template <class T>
inline void function2D<T>::TSymmProduct(const function2D& A, const function2D& B, const T& alpha, const T& beta)
{
if (A.Nd != B.Nd || !B.N || !A.N || !A.Nd || !B.Nd || N0<A.N || Nd0<B.N)
std::cerr << " Matrix sizes not correct" << std::endl;
xsymm("L", "L", A.N, B.N, alpha, A.MemPt(), A.Nd0, B.MemPt(), B.Nd0, beta, MemPt(), Nd0);
N = B.N; Nd = A.N;
}
template <class T>
inline void function2D<T>::DotProduct(const function2D& A, const function2D& B, const T& alpha, const T& beta)
{
if (B.N != A.Nd || !B.N || !A.N || !A.Nd || !B.Nd || Nd0<B.Nd || N0<A.N)
std::cerr << " Matrix sizes not correct" << std::endl;
// xgemm("T", "T", A.N, B.Nd, A.Nd, alpha, A.MemPt(), A.Nd0, B.MemPt(), B.Nd0, beta, MemPt(), Nd0);
xgemm("N", "N", B.Nd, A.N, B.N, alpha, B.MemPt(), B.Nd0, A.MemPt(), A.Nd0, beta, MemPt(), Nd0);
Nd = B.Nd; N = A.N;
}
template <class T>
inline function2D<T>& function2D<T>::operator+=(double x)
{
if (N!=Nd || !Nd || !N) {
std::cerr << "Can't add number to non-square matrix!" << std::endl;
return *this;
}
for (int i=0; i<Nd; i++) f[i][i] += x;
return *this;
}
template <class T>
inline function2D<T>& function2D<T>::operator+=(const function2D& m)
{
if (N!=m.N || Nd!=m.Nd) {
std::cerr << "Can't sum different matrices!" << std::endl;
return *this;
}
for (int i=0; i<N; i++)
for (int j=0; j<Nd; j++)
f[i][j] += m[i][j];
return *this;
}
template <class T>
inline function2D<T>& function2D<T>::operator-=(double x)
{
if (N!=Nd || !N || !Nd) {
std::cerr << "Can't add number to non-square matrix!" << std::endl;
return *this;
}
for (int i=0; i<Nd; i++) f[i][i] -= x;
return *this;
}
template <class T>
inline function2D<T>& function2D<T>::operator-=(const function2D& m)
{
if (N!=m.N || Nd!=m.Nd) {
std::cerr << "Can't sum different matrices!" << std::endl;
return *this;
}
for (int i=0; i<N; i++)
for (int j=0; j<Nd; j++)
f[i][j] -= m[i][j];
return *this;
}
template <class T>
inline function2D<T>& function2D<T>::operator=(const T& u)
{
for (int i=0; i<N; i++) for (int j=0; j<Nd; j++) f[i].f[j]=u;
return *this;
}
template <class T>
inline function2D<T>& function2D<T>::operator*=(const T& x)
{
for (int i=0; i<N; i++) for (int j=0; j<Nd; j++) f[i][j] *= x;
return *this;
}
template <class T>
template <class meshx, class functiond>
void function2D<T>::KramarsKronig(const meshx& om, const functiond& logo, functiond& sum, functiond& odvSig)
{
sum.resize(size_Nd()); odvSig.resize(size_Nd());
if (logo.size()!=om.size()||om.size()!=N)
std::cerr<<"Functions not of equal size in KramarsKronig"<<std::endl;
for (int i=0; i<om.size(); i++){
const double omom2 = (i>0) ? om.Delta(i-1) : 0.0;
const int ip1 = (i<om.size()-1) ? i+1 : i, im1 = (i>0) ? i-1 : i;
for (int l=0; l<size_Nd(); l++)
odvSig[l] = 0.5*(om.Delta(i)*(f[ip1][l].imag()-f[i][l].imag()) + omom2*(f[i][l].imag()-f[im1][l].imag()));
for (int l=0; l<size_Nd(); l++) sum[l] = 0;
T *g0 = f[i].MemPt();
for (int j=0; j<om.size(); j++){
double dh = om.Dh(j), dhdom = dh/(om[j]-om[i]);
T *g = f[j].MemPt();
if (i!=j)
for (int l=0; l<size_Nd(); l++) sum[l] += (g[l].imag()-g0[l].imag())*dhdom;
else
for (int l=0; l<size_Nd(); l++) sum[l] += odvSig[l]*dh;
}
for (int l=0; l<size_Nd(); l++) f[i][l].real()=(sum[l]+g0[l].imag()*logo[i])/M_PI;
}
}
template <class fun, class fun1, class fun2>
inline void multiply(fun& f, const fun1& a, const fun2& b)
{
SUNCA_LOG(if (a.size()!=b.size()) std::cerr << "Functions not of equal length! Can't multiply!" << std::endl;);
f.resize(a.size());
for (int i=0; i<f.size(); i++) f[i] = a[i]*b[i];
}
template <class T>
std::ostream& operator<<(std::ostream& stream, const functionb<T>& f)
{
int width = stream.width();
for (int i=0; i<f.size(); i++) stream<<i<<" "<<std::setw(width)<<f[i]<<std::endl;
return stream;
}
template <class T>
std::ostream& operator<<(std::ostream& stream, const function2D<T>& f)
{
int width = stream.width();
for (int i=0; i<f.size_N(); i++){
for (int j=0; j<f.size_Nd(); j++)
stream<<std::setw(width)<<f[i][j]<<" ";
stream<<std::endl;
}
return stream;
}
template<class meshx, class functionx>
void print(std::ostream& stream, const meshx& om, const functionx& f, int width)
{
if (om.size()!=f.size()) std::cerr<<"Can't print objectc of different size!"<<std::endl;
for (int i=0; i<om.size(); i++)
stream <<std::setw(width)<<om[i]<<std::setw(width)<<f[i]<<std::endl;
}
template<class meshx, class functionx, class functiony>
void print(std::ostream& stream, const meshx& om, const functionx& f1, const functiony& f2, int width)
{
if (om.size()!=f1.size() || om.size()!=f2.size()) std::cerr<<"Can't print objectc of different size!"<<std::endl;
for (int i=0; i<om.size(); i++)
stream <<std::setw(width)<<om[i]<<std::setw(width)<<f1[i]<<std::setw(width)<<f2[i]<<std::endl;
}
template<class meshx, class functionx, class functiony, class functionz>
void print(std::ostream& stream, const meshx& om, const functionx& f1, const functiony& f2, const functionz& f3, int width)
{
if (om.size()!=f1.size() || om.size()!=f2.size() || om.size()!=f3.size()) std::cerr<<"Can't print objectc of different size!"<<std::endl;
for (int i=0; i<om.size(); i++)
stream <<std::setw(width)<<om[i]<<std::setw(width)<<f1[i]<<std::setw(width)<<f2[i]<<std::setw(width)<<f3[i]<<std::endl;
}
template<class meshx, class functionx, class functiony, class functionz, class functionw>
void print(std::ostream& stream, const meshx& om, const functionx& f1, const functiony& f2, const functionz& f3, const functionw& f4, int width)
{
if (om.size()!=f1.size() || om.size()!=f2.size() || om.size()!=f3.size() || om.size()!=f4.size())
std::cerr<<"Can't print objectc of different size!"<<std::endl;
for (int i=0; i<om.size(); i++)
stream <<std::setw(width)<<om[i]<<std::setw(width)<<f1[i]<<std::setw(width)<<f2[i]<<std::setw(width)<<f3[i]<<std::setw(width)<<f4[i]<<std::endl;
}
template<class meshx, class functionx, class functiony, class functionz, class functiona, class functionb>
void print(std::ostream& stream, const meshx& om, const functionx& f1, const functiony& f2, const functionz& f3,
const functiona& f4, const functionb& f5, int width)
{
if (om.size()!=f1.size() || om.size()!=f2.size() || om.size()!=f3.size() || om.size()!=f4.size() || om.size()!=f5.size())
std::cerr<<"Can't print objectc of different size!"<<std::endl;
for (int i=0; i<om.size(); i++)
stream <<std::setw(width)<<om[i]<<std::setw(width)<<f1[i]<<std::setw(width)<<f2[i]<<std::setw(width)<<f3[i]<<std::setw(width)<<f4[i]<<std::setw(width)<<f5[i]<<std::endl;
}
template<class meshx, class functionx, class functiony, class functionz, class functiona, class functionb, class functionc>
void print(std::ostream& stream, const meshx& om, const functionx& f1, const functiony& f2, const functionz& f3,
const functiona& f4, const functionb& f5, const functionc& f6, int width)
{
if (om.size()!=f1.size() || om.size()!=f2.size() || om.size()!=f3.size() || om.size()!=f4.size() || om.size()!=f5.size() || om.size()!=f6.size())
std::cerr<<"Can't print objectc of different size!"<<std::endl;
for (int i=0; i<om.size(); i++)
stream <<std::setw(width)<<om[i]<<std::setw(width)<<f1[i]<<std::setw(width)<<f2[i]<<std::setw(width)<<f3[i]<<std::setw(width)<<f4[i]<<std::setw(width)<<f5[i]<<std::setw(width)<<f6[i]<<std::endl;
}
template<class meshx, class functionx, class functiony, class functionz, class functiona, class functionb, class functionc>
void print(std::ostream& stream, const meshx& om, const functionx& f1, const functiony& f2, const functionz& f3,
const functiona& f4, const functionb& f5, const functionc& f6, const functiona& f7, const functionb& f8, const functionc& f9,
int width)
{
if (om.size()!=f1.size() || om.size()!=f2.size() || om.size()!=f3.size() || om.size()!=f4.size() || om.size()!=f5.size() || om.size()!=f6.size())
std::cerr<<"Can't print objectc of different size!"<<std::endl;
for (int i=0; i<om.size(); i++)
stream <<std::setw(width)<<om[i]<<std::setw(width)<<f1[i]<<std::setw(width)<<f2[i]<<std::setw(width)<<f3[i]<<std::setw(width)<<f4[i]<<std::setw(width)<<f5[i]<<std::setw(width)<<f6[i]<<std::setw(width)<<f7[i]<<std::setw(width)<<f8[i]<<std::setw(width)<<f9[i]<<std::endl;
}
template<class meshx, class functionx, class functiony, class functionz, class functiona, class functionb, class functionc, class functiond, class functione, class functionf, class functiong>
void print(std::ostream& stream, const meshx& om, const functionx& f1, const functiony& f2, const functionz& f3,
const functiona& f4, const functionb& f5, const functionc& f6, const functiond& f7, const functione& f8, const functionf& f9, const functiong& f10,
int width)
{
if (om.size()!=f1.size() || om.size()!=f2.size() || om.size()!=f3.size() || om.size()!=f4.size() || om.size()!=f5.size() || om.size()!=f6.size())
std::cerr<<"Can't print objectc of different size!"<<std::endl;
for (int i=0; i<om.size(); i++)
stream <<std::setw(width)<<om[i]<<std::setw(width)<<f1[i]<<std::setw(width)<<f2[i]<<std::setw(width)<<f3[i]<<std::setw(width)<<f4[i]<<std::setw(width)<<f5[i]<<std::setw(width)<<f6[i]<<std::setw(width)<<f7[i]<<std::setw(width)<<f8[i]<<std::setw(width)<<f9[i]<<std::setw(width)<<f10[i]<<std::endl;
}
template <class T>
inline T scalar_product(const functionb<T>& f1, const functionb<T>& f2)
{
static const int incr=1;
Assert(f1.size()==f2.size(),"Sizes not the same in scalar_product!");
return ddot_(&f1.N, f1.f, &incr, f2.f, &incr);
}
template <class funProxy>
inline int SolveSOLA(function2D<funProxy>& A, function2D<funProxy>& B, function1D<int>& ipiv)
{
return xgesv(A.size_Nd(), B.size_N(), A.MemPt(), A.fullsize_Nd(), ipiv.MemPt(), B.MemPt(), B.fullsize_Nd());
}
template <class funProxy, class T>
inline int SolveSOLA(function2D<funProxy>& A, function1D<T>& B, function1D<int>& ipiv)
{
return xgesv(A.size_Nd(), 1, A.MemPt(), A.fullsize_Nd(), ipiv.MemPt(), B.MemPt(), B.fullsize());
}
inline double logpart(double a, double b, double x)
{
return log(fabs((b-x)/(x-a)));
}
template <class complexn>
inline complexn logpart(double a, double b, const complexn& x)
{
return log((b-x)/(a-x));
}
template <class T, class meshx>
T KramarsKronig(const functionb<double>& fi, const meshx& om, const T& x, int i0, double S0)
{
T sum=0;
for (int j=0; j<i0-1; j++) sum += (fi[j]-S0)*om.Dh(j)/(om[j]-x);
if (i0>0) sum += (fi[i0-1]-S0)*(om.Dh(i0-1)+0.5*om.Dh(i0))/(om[i0-1]-x);
if (i0<om.size()-1) sum += (fi[i0+1]-S0)*(om.Dh(i0+1)+0.5*om.Dh(i0))/(om[i0+1]-x);
for (int j=i0+2; j<om.size(); j++) sum += (fi[j]-S0)*om.Dh(j)/(om[j]-x);
if (x!=om.last() && x!=om[0]) sum += S0*logpart(om[0],om.last(),x);
return sum/M_PI;
}
#endif
|
task_dep-3.c | /* { dg-do run } */
#include <stdlib.h>
int main()
{
int x = 0;
#pragma omp parallel
#pragma omp single
{
#pragma omp task shared(x) depend(out: x)
x = 1;
#pragma omp task shared(x) depend(out: x)
x = 2;
#pragma omp taskwait
if (x != 1 && x != 2)
abort ();
}
return 0;
}
|
SPHCalcHydroForceFunctor.h | /**
* @file SPHCalcHydroForceFunctor.h
* @author seckler
* @date 22.01.18
*/
#pragma once
#include "autopas/autopasIncludes.h"
#include "autopas/sph/SPHKernels.h"
#include "autopas/sph/SPHParticle.h"
namespace autopas {
namespace sph {
/**
* Class that defines the hydrodynamic force functor.
* It is used to calculate the force based on the given SPH kernels.
*/
class SPHCalcHydroForceFunctor
: public Functor<SPHParticle, FullParticleCell<SPHParticle>, SPHParticle::SoAArraysType, SPHCalcHydroForceFunctor> {
public:
/// particle type
typedef SPHParticle Particle;
/// soa arrays type
typedef SPHParticle::SoAArraysType SoAArraysType;
/// particle cell type
typedef FullParticleCell<Particle> ParticleCell;
SPHCalcHydroForceFunctor()
// the actual cutoff used is dynamic. 0 is used to pass the sanity check.
: autopas::Functor<Particle, ParticleCell, SoAArraysType, SPHCalcHydroForceFunctor>(0.){};
bool isRelevantForTuning() override { return true; }
bool allowsNewton3() override { return true; }
bool allowsNonNewton3() override { return true; }
/**
* Calculates the contribution of the interaction of particle i and j to the
* hydrodynamic force.
* It is not symmetric, because the smoothing lenghts of the two particles can
* be different.
* @param i first particle of the interaction
* @param j second particle of the interaction
* @param newton3 defines whether or whether not to use newton 3
*/
void AoSFunctor(SPHParticle &i, SPHParticle &j, bool newton3 = true) override {
const std::array<double, 3> dr = ArrayMath::sub(i.getR(), j.getR());
// const PS::F64vec dr = ep_i[i].pos - ep_j[j].pos;
double cutoff = i.getSmoothingLength() * autopas::sph::SPHKernels::getKernelSupportRadius();
if (autopas::ArrayMath::dot(dr, dr) >= cutoff * cutoff) {
return;
}
const std::array<double, 3> dv = ArrayMath::sub(i.getV(), j.getV());
// const PS::F64vec dv = ep_i[i].vel - ep_j[j].vel;
double dvdr = ArrayMath::dot(dv, dr);
const double w_ij = (dvdr < 0) ? dvdr / sqrt(ArrayMath::dot(dr, dr)) : 0;
// const PS::F64 w_ij = (dv * dr < 0) ? dv * dr / sqrt(dr * dr) : 0;
const double v_sig = i.getSoundSpeed() + j.getSoundSpeed() - 3.0 * w_ij;
// const PS::F64 v_sig = ep_i[i].snds + ep_j[j].snds - 3.0 * w_ij;
i.checkAndSetVSigMax(v_sig);
if (newton3) {
j.checkAndSetVSigMax(v_sig); // Newton 3
// v_sig_max = std::max(v_sig_max, v_sig);
}
const double AV = -0.5 * v_sig * w_ij / (0.5 * (i.getDensity() + j.getDensity()));
// const PS::F64 AV = - 0.5 * v_sig * w_ij / (0.5 * (ep_i[i].dens +
// ep_j[j].dens));
const std::array<double, 3> gradW_ij = ArrayMath::mulScalar(
ArrayMath::add(SPHKernels::gradW(dr, i.getSmoothingLength()), SPHKernels::gradW(dr, j.getSmoothingLength())),
0.5);
// const PS::F64vec gradW_ij = 0.5 * (gradW(dr, ep_i[i].smth) + gradW(dr,
// ep_j[j].smth));
double scale =
i.getPressure() / (i.getDensity() * i.getDensity()) + j.getPressure() / (j.getDensity() * j.getDensity()) + AV;
i.subAcceleration(ArrayMath::mulScalar(gradW_ij, scale * j.getMass()));
// hydro[i].acc -= ep_j[j].mass * (ep_i[i].pres / (ep_i[i].dens *
// ep_i[i].dens) + ep_j[j].pres / (ep_j[j].dens * ep_j[j].dens) + AV) *
// gradW_ij;
if (newton3) {
j.addAcceleration(ArrayMath::mulScalar(gradW_ij, scale * i.getMass()));
// Newton3, gradW_ij = -gradW_ji
}
double scale2i = j.getMass() * (i.getPressure() / (i.getDensity() * i.getDensity()) + 0.5 * AV);
i.addEngDot(ArrayMath::dot(gradW_ij, dv) * scale2i);
// hydro[i].eng_dot += ep_j[j].mass * (ep_i[i].pres / (ep_i[i].dens *
// ep_i[i].dens) + 0.5 * AV) * dv * gradW_ij;
if (newton3) {
double scale2j = i.getMass() * (j.getPressure() / (j.getDensity() * j.getDensity()) + 0.5 * AV);
j.addEngDot(ArrayMath::dot(gradW_ij, dv) * scale2j);
// Newton 3
}
}
/**
* @copydoc Functor::SoAFunctor(SoAView<SoAArraysType>, bool)
* This functor ignores the newton3 value, as we do not expect any benefit from disabling newton3.
*/
void SoAFunctor(SoAView<SoAArraysType> soa, bool newton3) override {
if (soa.getNumParticles() == 0) return;
double *const __restrict__ massptr = soa.begin<autopas::sph::SPHParticle::AttributeNames::mass>();
double *const __restrict__ densityptr = soa.begin<autopas::sph::SPHParticle::AttributeNames::density>();
double *const __restrict__ smthptr = soa.begin<autopas::sph::SPHParticle::AttributeNames::smth>();
double *const __restrict__ soundSpeedptr = soa.begin<autopas::sph::SPHParticle::AttributeNames::soundSpeed>();
double *const __restrict__ pressureptr = soa.begin<autopas::sph::SPHParticle::AttributeNames::pressure>();
double *const __restrict__ vsigmaxptr = soa.begin<autopas::sph::SPHParticle::AttributeNames::vsigmax>();
double *const __restrict__ engDotptr = soa.begin<autopas::sph::SPHParticle::AttributeNames::engDot>();
double *const __restrict__ xptr = soa.begin<autopas::sph::SPHParticle::AttributeNames::posX>();
double *const __restrict__ yptr = soa.begin<autopas::sph::SPHParticle::AttributeNames::posY>();
double *const __restrict__ zptr = soa.begin<autopas::sph::SPHParticle::AttributeNames::posZ>();
double *const __restrict__ velXptr = soa.begin<autopas::sph::SPHParticle::AttributeNames::velX>();
double *const __restrict__ velYptr = soa.begin<autopas::sph::SPHParticle::AttributeNames::velY>();
double *const __restrict__ velZptr = soa.begin<autopas::sph::SPHParticle::AttributeNames::velZ>();
double *const __restrict__ accXptr = soa.begin<autopas::sph::SPHParticle::AttributeNames::accX>();
double *const __restrict__ accYptr = soa.begin<autopas::sph::SPHParticle::AttributeNames::accY>();
double *const __restrict__ accZptr = soa.begin<autopas::sph::SPHParticle::AttributeNames::accZ>();
for (unsigned int i = 0; i < soa.getNumParticles(); ++i) {
double localvsigmax = 0.;
double localengdotsum = 0.;
double localAccX = 0.;
double localAccY = 0.;
double localAccZ = 0.;
// icpc vectorizes this.
// g++ only with -ffast-math or -funsafe-math-optimizations
//#pragma omp simd reduction(+ : localengdotsum, localAccX, localAccY, localAccZ), reduction(max : localvsigmax)
for (unsigned int j = i + 1; j < soa.getNumParticles(); ++j) {
const double drx = xptr[i] - xptr[j];
const double dry = yptr[i] - yptr[j];
const double drz = zptr[i] - zptr[j];
const double drx2 = drx * drx;
const double dry2 = dry * dry;
const double drz2 = drz * drz;
const double dr2 = drx2 + dry2 + drz2;
double cutoff = smthptr[i] * autopas::sph::SPHKernels::getKernelSupportRadius();
if (dr2 >= cutoff * cutoff) continue;
const double dvX = velXptr[i] - velXptr[j];
const double dvY = velYptr[i] - velYptr[j];
const double dvZ = velZptr[i] - velZptr[j];
// const PS::F64vec dv = ep_i[i].vel - ep_j[j].vel;
double dvdr = dvX * drx + dvY * dry + dvZ * drz;
const double w_ij = (dvdr < 0) ? dvdr / sqrt(dr2) : 0;
// const PS::F64 w_ij = (dv * dr < 0) ? dv * dr / sqrt(dr * dr) : 0;
const double v_sig = soundSpeedptr[i] + soundSpeedptr[j] - 3.0 * w_ij;
// const PS::F64 v_sig = ep_i[i].snds + ep_j[j].snds - 3.0 * w_ij;
localvsigmax = std::max(localvsigmax, v_sig);
// vsigmaxptr[j] = std::max(vsigmaxptr[j], v_sig); // Newton 3
vsigmaxptr[j] = vsigmaxptr[j] > v_sig ? vsigmaxptr[j] : v_sig; // Newton 3
// v_sig_max = std::max(v_sig_max, v_sig);
const double AV = -0.5 * v_sig * w_ij / (0.5 * (densityptr[i] + densityptr[j]));
// const PS::F64 AV = - 0.5 * v_sig * w_ij / (0.5 * (ep_i[i].dens +
// ep_j[j].dens));
const std::array<double, 3> gradW_ij =
ArrayMath::mulScalar(ArrayMath::add(SPHKernels::gradW({drx, dry, drz}, smthptr[i]),
SPHKernels::gradW({drx, dry, drz}, smthptr[j])),
0.5);
// const PS::F64vec gradW_ij = 0.5 * (gradW(dr, ep_i[i].smth) + gradW(dr,
// ep_j[j].smth));
double scale =
pressureptr[i] / (densityptr[i] * densityptr[i]) + pressureptr[j] / (densityptr[j] * densityptr[j]) + AV;
const double massscale = scale * massptr[j];
localAccX -= gradW_ij[0] * massscale;
localAccY -= gradW_ij[1] * massscale;
localAccZ -= gradW_ij[2] * massscale;
// hydro[i].acc -= ep_j[j].mass * (ep_i[i].pres / (ep_i[i].dens *
// ep_i[i].dens) + ep_j[j].pres / (ep_j[j].dens * ep_j[j].dens) + AV) *
// gradW_ij;
const double massscale2 = scale * massptr[i];
accXptr[j] += gradW_ij[0] * massscale2;
accYptr[j] += gradW_ij[1] * massscale2;
accZptr[j] += gradW_ij[2] * massscale2;
// Newton3, gradW_ij = -gradW_ji
double scale2i = massptr[j] * (pressureptr[i] / (densityptr[i] * densityptr[i]) + 0.5 * AV);
localengdotsum += (gradW_ij[0] * dvX + gradW_ij[1] * dvY + gradW_ij[2] * dvZ) * scale2i;
// hydro[i].eng_dot += ep_j[j].mass * (ep_i[i].pres / (ep_i[i].dens *
// ep_i[i].dens) + 0.5 * AV) * dv * gradW_ij;
double scale2j = massptr[i] * (pressureptr[j] / (densityptr[j] * densityptr[j]) + 0.5 * AV);
engDotptr[j] += (gradW_ij[0] * dvX + gradW_ij[1] * dvY + gradW_ij[2] * dvZ) * scale2j;
// Newton 3
}
engDotptr[i] += localengdotsum;
accXptr[i] += localAccX;
accYptr[i] += localAccY;
accZptr[i] += localAccZ;
vsigmaxptr[i] = std::max(localvsigmax, vsigmaxptr[i]);
}
}
/**
* @copydoc Functor::SoAFunctor(SoAView<SoAArraysType>, SoAView<SoAArraysType>, bool)
*/
void SoAFunctor(SoAView<SoAArraysType> soa1, SoAView<SoAArraysType> soa2, bool newton3) override {
if (soa1.getNumParticles() == 0 || soa2.getNumParticles() == 0) return;
double *const __restrict__ massptr1 = soa1.begin<autopas::sph::SPHParticle::AttributeNames::mass>();
double *const __restrict__ densityptr1 = soa1.begin<autopas::sph::SPHParticle::AttributeNames::density>();
double *const __restrict__ smthptr1 = soa1.begin<autopas::sph::SPHParticle::AttributeNames::smth>();
double *const __restrict__ soundSpeedptr1 = soa1.begin<autopas::sph::SPHParticle::AttributeNames::soundSpeed>();
double *const __restrict__ pressureptr1 = soa1.begin<autopas::sph::SPHParticle::AttributeNames::pressure>();
double *const __restrict__ vsigmaxptr1 = soa1.begin<autopas::sph::SPHParticle::AttributeNames::vsigmax>();
double *const __restrict__ engDotptr1 = soa1.begin<autopas::sph::SPHParticle::AttributeNames::engDot>();
double *const __restrict__ xptr1 = soa1.begin<autopas::sph::SPHParticle::AttributeNames::posX>();
double *const __restrict__ yptr1 = soa1.begin<autopas::sph::SPHParticle::AttributeNames::posY>();
double *const __restrict__ zptr1 = soa1.begin<autopas::sph::SPHParticle::AttributeNames::posZ>();
double *const __restrict__ velXptr1 = soa1.begin<autopas::sph::SPHParticle::AttributeNames::velX>();
double *const __restrict__ velYptr1 = soa1.begin<autopas::sph::SPHParticle::AttributeNames::velY>();
double *const __restrict__ velZptr1 = soa1.begin<autopas::sph::SPHParticle::AttributeNames::velZ>();
double *const __restrict__ accXptr1 = soa1.begin<autopas::sph::SPHParticle::AttributeNames::accX>();
double *const __restrict__ accYptr1 = soa1.begin<autopas::sph::SPHParticle::AttributeNames::accY>();
double *const __restrict__ accZptr1 = soa1.begin<autopas::sph::SPHParticle::AttributeNames::accZ>();
double *const __restrict__ massptr2 = soa2.begin<autopas::sph::SPHParticle::AttributeNames::mass>();
double *const __restrict__ densityptr2 = soa2.begin<autopas::sph::SPHParticle::AttributeNames::density>();
double *const __restrict__ smthptr2 = soa2.begin<autopas::sph::SPHParticle::AttributeNames::smth>();
double *const __restrict__ soundSpeedptr2 = soa2.begin<autopas::sph::SPHParticle::AttributeNames::soundSpeed>();
double *const __restrict__ pressureptr2 = soa2.begin<autopas::sph::SPHParticle::AttributeNames::pressure>();
double *const __restrict__ vsigmaxptr2 = soa2.begin<autopas::sph::SPHParticle::AttributeNames::vsigmax>();
double *const __restrict__ engDotptr2 = soa2.begin<autopas::sph::SPHParticle::AttributeNames::engDot>();
double *const __restrict__ xptr2 = soa2.begin<autopas::sph::SPHParticle::AttributeNames::posX>();
double *const __restrict__ yptr2 = soa2.begin<autopas::sph::SPHParticle::AttributeNames::posY>();
double *const __restrict__ zptr2 = soa2.begin<autopas::sph::SPHParticle::AttributeNames::posZ>();
double *const __restrict__ velXptr2 = soa2.begin<autopas::sph::SPHParticle::AttributeNames::velX>();
double *const __restrict__ velYptr2 = soa2.begin<autopas::sph::SPHParticle::AttributeNames::velY>();
double *const __restrict__ velZptr2 = soa2.begin<autopas::sph::SPHParticle::AttributeNames::velZ>();
double *const __restrict__ accXptr2 = soa2.begin<autopas::sph::SPHParticle::AttributeNames::accX>();
double *const __restrict__ accYptr2 = soa2.begin<autopas::sph::SPHParticle::AttributeNames::accY>();
double *const __restrict__ accZptr2 = soa2.begin<autopas::sph::SPHParticle::AttributeNames::accZ>();
for (unsigned int i = 0; i < soa1.getNumParticles(); ++i) {
double localvsigmax = 0.;
double localengdotsum = 0.;
double localAccX = 0.;
double localAccY = 0.;
double localAccZ = 0.;
// icpc vectorizes this.
// g++ only with -ffast-math or -funsafe-math-optimizations
//#pragma omp simd reduction(+ : localengdotsum, localAccX, localAccY, localAccZ), reduction(max : localvsigmax)
for (unsigned int j = 0; j < soa2.getNumParticles(); ++j) {
const double drx = xptr1[i] - xptr2[j];
const double dry = yptr1[i] - yptr2[j];
const double drz = zptr1[i] - zptr2[j];
const double drx2 = drx * drx;
const double dry2 = dry * dry;
const double drz2 = drz * drz;
const double dr2 = drx2 + dry2 + drz2;
double cutoff = smthptr1[i] * autopas::sph::SPHKernels::getKernelSupportRadius();
if (dr2 >= cutoff * cutoff) continue;
const double dvX = velXptr1[i] - velXptr2[j];
const double dvY = velYptr1[i] - velYptr2[j];
const double dvZ = velZptr1[i] - velZptr2[j];
// const PS::F64vec dv = ep_i[i].vel - ep_j[j].vel;
double dvdr = dvX * drx + dvY * dry + dvZ * drz;
const double w_ij = (dvdr < 0) ? dvdr / sqrt(dr2) : 0;
// const PS::F64 w_ij = (dv * dr < 0) ? dv * dr / sqrt(dr * dr) : 0;
const double v_sig = soundSpeedptr1[i] + soundSpeedptr2[j] - 3.0 * w_ij;
// const PS::F64 v_sig = ep_i[i].snds + ep_j[j].snds - 3.0 * w_ij;
localvsigmax = std::max(localvsigmax, v_sig);
if (newton3) {
// vsigmaxptr2[j] = std::max(vsigmaxptr2[j], v_sig); // Newton 3
vsigmaxptr2[j] = vsigmaxptr2[j] > v_sig ? vsigmaxptr2[j] : v_sig; // Newton 3
// v_sig_max = std::max(v_sig_max, v_sig);
}
const double AV = -0.5 * v_sig * w_ij / (0.5 * (densityptr1[i] + densityptr2[j]));
// const PS::F64 AV = - 0.5 * v_sig * w_ij / (0.5 * (ep_i[i].dens +
// ep_j[j].dens));
const std::array<double, 3> gradW_ij =
ArrayMath::mulScalar(ArrayMath::add(SPHKernels::gradW({drx, dry, drz}, smthptr1[i]),
SPHKernels::gradW({drx, dry, drz}, smthptr2[j])),
0.5);
// const PS::F64vec gradW_ij = 0.5 * (gradW(dr, ep_i[i].smth) + gradW(dr,
// ep_j[j].smth));
double scale = pressureptr1[i] / (densityptr1[i] * densityptr1[i]) +
pressureptr2[j] / (densityptr2[j] * densityptr2[j]) + AV;
const double massscale = scale * massptr2[j];
localAccX -= gradW_ij[0] * massscale;
localAccY -= gradW_ij[1] * massscale;
localAccZ -= gradW_ij[2] * massscale;
// hydro[i].acc -= ep_j[j].mass * (ep_i[i].pres / (ep_i[i].dens *
// ep_i[i].dens) + ep_j[j].pres / (ep_j[j].dens * ep_j[j].dens) + AV) *
// gradW_ij;
if (newton3) {
const double massscale = scale * massptr1[i];
accXptr2[j] += gradW_ij[0] * massscale;
accYptr2[j] += gradW_ij[1] * massscale;
accZptr2[j] += gradW_ij[2] * massscale;
// Newton3, gradW_ij = -gradW_ji
}
double scale2i = massptr2[j] * (pressureptr1[i] / (densityptr1[i] * densityptr1[i]) + 0.5 * AV);
localengdotsum += (gradW_ij[0] * dvX + gradW_ij[1] * dvY + gradW_ij[2] * dvZ) * scale2i;
// hydro[i].eng_dot += ep_j[j].mass * (ep_i[i].pres / (ep_i[i].dens *
// ep_i[i].dens) + 0.5 * AV) * dv * gradW_ij;
if (newton3) {
double scale2j = massptr1[i] * (pressureptr2[j] / (densityptr2[j] * densityptr2[j]) + 0.5 * AV);
engDotptr2[j] += (gradW_ij[0] * dvX + gradW_ij[1] * dvY + gradW_ij[2] * dvZ) * scale2j;
// Newton 3
}
}
engDotptr1[i] += localengdotsum;
accXptr1[i] += localAccX;
accYptr1[i] += localAccY;
accZptr1[i] += localAccZ;
vsigmaxptr1[i] = std::max(localvsigmax, vsigmaxptr1[i]);
}
}
// clang-format off
/**
* @copydoc Functor::SoAFunctor(SoAView<SoAArraysType>, const std::vector<std::vector<size_t, autopas::AlignedAllocator<size_t>>> &, size_t, size_t, bool)
*/
// clang-format on
void SoAFunctor(SoAView<SoAArraysType> soa,
const std::vector<std::vector<size_t, autopas::AlignedAllocator<size_t>>> &neighborList, size_t iFrom,
size_t iTo, bool newton3) override {
if (soa.getNumParticles() == 0) return;
double *const __restrict__ massptr = soa.begin<autopas::sph::SPHParticle::AttributeNames::mass>();
double *const __restrict__ densityptr = soa.begin<autopas::sph::SPHParticle::AttributeNames::density>();
double *const __restrict__ smthptr = soa.begin<autopas::sph::SPHParticle::AttributeNames::smth>();
double *const __restrict__ soundSpeedptr = soa.begin<autopas::sph::SPHParticle::AttributeNames::soundSpeed>();
double *const __restrict__ pressureptr = soa.begin<autopas::sph::SPHParticle::AttributeNames::pressure>();
double *const __restrict__ vsigmaxptr = soa.begin<autopas::sph::SPHParticle::AttributeNames::vsigmax>();
double *const __restrict__ engDotptr = soa.begin<autopas::sph::SPHParticle::AttributeNames::engDot>();
double *const __restrict__ xptr = soa.begin<autopas::sph::SPHParticle::AttributeNames::posX>();
double *const __restrict__ yptr = soa.begin<autopas::sph::SPHParticle::AttributeNames::posY>();
double *const __restrict__ zptr = soa.begin<autopas::sph::SPHParticle::AttributeNames::posZ>();
double *const __restrict__ velXptr = soa.begin<autopas::sph::SPHParticle::AttributeNames::velX>();
double *const __restrict__ velYptr = soa.begin<autopas::sph::SPHParticle::AttributeNames::velY>();
double *const __restrict__ velZptr = soa.begin<autopas::sph::SPHParticle::AttributeNames::velZ>();
double *const __restrict__ accXptr = soa.begin<autopas::sph::SPHParticle::AttributeNames::accX>();
double *const __restrict__ accYptr = soa.begin<autopas::sph::SPHParticle::AttributeNames::accY>();
double *const __restrict__ accZptr = soa.begin<autopas::sph::SPHParticle::AttributeNames::accZ>();
for (unsigned int i = iFrom; i < iTo; ++i) {
double localvsigmax = 0.;
double localengdotsum = 0.;
double localAccX = 0.;
double localAccY = 0.;
double localAccZ = 0.;
auto ¤tList = neighborList[i];
size_t listSize = currentList.size();
// icpc vectorizes this.
// g++ only with -ffast-math or -funsafe-math-optimizations
//#pragma omp simd reduction(+ : localengdotsum, localAccX, localAccY, localAccZ), reduction(max : localvsigmax)
for (unsigned int j = 0; j < listSize; ++j) {
const double drx = xptr[i] - xptr[currentList[j]];
const double dry = yptr[i] - yptr[currentList[j]];
const double drz = zptr[i] - zptr[currentList[j]];
const double drx2 = drx * drx;
const double dry2 = dry * dry;
const double drz2 = drz * drz;
const double dr2 = drx2 + dry2 + drz2;
double cutoff = smthptr[i] * autopas::sph::SPHKernels::getKernelSupportRadius();
if (dr2 >= cutoff * cutoff) continue;
const double dvX = velXptr[i] - velXptr[currentList[j]];
const double dvY = velYptr[i] - velYptr[currentList[j]];
const double dvZ = velZptr[i] - velZptr[currentList[j]];
// const PS::F64vec dv = ep_i[i].vel - ep_j[currentList[j]].vel;
double dvdr = dvX * drx + dvY * dry + dvZ * drz;
const double w_ij = (dvdr < 0) ? dvdr / sqrt(dr2) : 0;
// const PS::F64 w_ij = (dv * dr < 0) ? dv * dr / sqrt(dr * dr) : 0;
const double v_sig = soundSpeedptr[i] + soundSpeedptr[currentList[j]] - 3.0 * w_ij;
// const PS::F64 v_sig = ep_i[i].snds + ep_j[currentList[j]].snds - 3.0 * w_ij;
localvsigmax = std::max(localvsigmax, v_sig);
if (newton3) {
// vsigmaxptr[currentList[j]] = std::max(vsigmaxptr[currentList[j]], v_sig); // Newton 3
vsigmaxptr[currentList[j]] =
vsigmaxptr[currentList[j]] > v_sig ? vsigmaxptr[currentList[j]] : v_sig; // Newton 3
// v_sig_max = std::max(v_sig_max, v_sig);
}
const double AV = -0.5 * v_sig * w_ij / (0.5 * (densityptr[i] + densityptr[currentList[j]]));
// const PS::F64 AV = - 0.5 * v_sig * w_ij / (0.5 * (ep_i[i].dens +
// ep_j[currentList[j]].dens));
const std::array<double, 3> gradW_ij =
ArrayMath::mulScalar(ArrayMath::add(SPHKernels::gradW({drx, dry, drz}, smthptr[i]),
SPHKernels::gradW({drx, dry, drz}, smthptr[currentList[j]])),
0.5);
// const PS::F64vec gradW_ij = 0.5 * (gradW(dr, ep_i[i].smth) + gradW(dr,
// ep_j[currentList[j]].smth));
double scale = pressureptr[i] / (densityptr[i] * densityptr[i]) +
pressureptr[currentList[j]] / (densityptr[currentList[j]] * densityptr[currentList[j]]) + AV;
const double massscale = scale * massptr[currentList[j]];
localAccX -= gradW_ij[0] * massscale;
localAccY -= gradW_ij[1] * massscale;
localAccZ -= gradW_ij[2] * massscale;
// hydro[i].acc -= ep_j[currentList[j]].mass * (ep_i[i].pres / (ep_i[i].dens *
// ep_i[i].dens) + ep_j[currentList[j]].pres / (ep_j[currentList[j]].dens * ep_j[currentList[j]].dens) + AV) *
// gradW_ij;
if (newton3) {
const double massscale = scale * massptr[i];
accXptr[currentList[j]] += gradW_ij[0] * massscale;
accYptr[currentList[j]] += gradW_ij[1] * massscale;
accZptr[currentList[j]] += gradW_ij[2] * massscale;
// Newton3, gradW_ij = -gradW_ji
}
double scale2i = massptr[currentList[j]] * (pressureptr[i] / (densityptr[i] * densityptr[i]) + 0.5 * AV);
localengdotsum += (gradW_ij[0] * dvX + gradW_ij[1] * dvY + gradW_ij[2] * dvZ) * scale2i;
// hydro[i].eng_dot += ep_j[currentList[j]].mass * (ep_i[i].pres / (ep_i[i].dens *
// ep_i[i].dens) + 0.5 * AV) * dv * gradW_ij;
if (newton3) {
double scale2j =
massptr[i] *
(pressureptr[currentList[j]] / (densityptr[currentList[j]] * densityptr[currentList[j]]) + 0.5 * AV);
engDotptr[currentList[j]] += (gradW_ij[0] * dvX + gradW_ij[1] * dvY + gradW_ij[2] * dvZ) * scale2j;
// Newton 3
}
}
engDotptr[i] += localengdotsum;
accXptr[i] += localAccX;
accYptr[i] += localAccY;
accZptr[i] += localAccZ;
vsigmaxptr[i] = std::max(localvsigmax, vsigmaxptr[i]);
}
}
/**
* @copydoc Functor::getNeededAttr()
*/
constexpr static const std::array<typename SPHParticle::AttributeNames, 16> getNeededAttr() {
///@todo distinguish between N3 and notN3
return std::array<typename SPHParticle::AttributeNames, 16>{
SPHParticle::AttributeNames::mass, SPHParticle::AttributeNames::density,
SPHParticle::AttributeNames::smth, SPHParticle::AttributeNames::soundSpeed,
SPHParticle::AttributeNames::pressure, SPHParticle::AttributeNames::vsigmax,
SPHParticle::AttributeNames::engDot, SPHParticle::AttributeNames::posX,
SPHParticle::AttributeNames::posY, SPHParticle::AttributeNames::posZ,
SPHParticle::AttributeNames::velX, SPHParticle::AttributeNames::velY,
SPHParticle::AttributeNames::velZ, SPHParticle::AttributeNames::accX,
SPHParticle::AttributeNames::accY, SPHParticle::AttributeNames::accZ};
}
/**
* @copydoc Functor::getNeededAttr(std::false_type)
*/
constexpr static const std::array<typename SPHParticle::AttributeNames, 11> getNeededAttr(std::false_type) {
///@todo distinguish between N3 and notN3
return std::array<typename SPHParticle::AttributeNames, 11>{
SPHParticle::AttributeNames::mass, SPHParticle::AttributeNames::density,
SPHParticle::AttributeNames::smth, SPHParticle::AttributeNames::soundSpeed,
SPHParticle::AttributeNames::pressure, SPHParticle::AttributeNames::posX,
SPHParticle::AttributeNames::posY, SPHParticle::AttributeNames::posZ,
SPHParticle::AttributeNames::velX, SPHParticle::AttributeNames::velY,
SPHParticle::AttributeNames::velZ};
}
/**
* @copydoc Functor::getComputedAttr()
*/
constexpr static const std::array<typename sph::SPHParticle::AttributeNames, 5> getComputedAttr() {
return std::array<typename SPHParticle::AttributeNames, 5>{
SPHParticle::AttributeNames::vsigmax, SPHParticle::AttributeNames::engDot, SPHParticle::AttributeNames::accX,
SPHParticle::AttributeNames::accY, SPHParticle::AttributeNames::accZ};
}
/**
* Get the number of floating point operations used in one full kernel call
* @return the number of floating point operations
*/
static unsigned long getNumFlopsPerKernelCall() {
///@todo return correct flopcount
return 1ul;
}
};
} // namespace sph
} // namespace autopas
|
saxpy-omp2.c | /**
* @file saxpy.c
*
* @brief saxpy performs the \c axpy computation in single-precision on both
* host and accelerator. The performance (in MFLOPS) on host and accelerator is
* compared and the numerical results are also verified for consistency.
*
* The \c axpy computation is defined as:
*
* y := a * x + y
*
* where:
*
* - a is a scalar.
* - x and y are vectors each with n elements.
*
* Please note that in this version only <em>one GPU thread</em> is used.
*
* Offload to GPU:
*
* gcc -fopenmp -foffload=nvptx-none saxpy.c
*
*/
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <omp.h>
#include "utils.h"
#define TWO02 (1 << 2)
#define TWO04 (1 << 4)
#define TWO08 (1 << 8)
#ifndef N
#define N (1 << 20)
#endif
int main(int argc, char *argv[])
{
int i, n = N,
iret = 0;
float a = 101.0f / TWO02,
b, c,
*x, *y, *z;
struct timespec rt[2];
double wt; // walltime
if (argc > 1)
n = atoi(argv[1]);
/*
* 0. prepare x, y, and z
*
* y := a * x + y (on host)
* z := a * x + z (on accel)
*/
if (NULL == (x = (float *)malloc(sizeof(*x) * n)))
{
printf("error: memory allocation for 'x'\n");
iret = -1;
}
if (NULL == (y = (float *)malloc(sizeof(*y) * n)))
{
printf("error: memory allocation for 'y'\n");
iret = -1;
}
if (NULL == (z = (float *)malloc(sizeof(*z) * n)))
{
printf("error: memory allocation for 'z'\n");
iret = -1;
}
if (0 != iret)
{
free(x);
free(y);
free(z);
exit(EXIT_FAILURE);
}
b = rand() % TWO04;
c = rand() % TWO08;
for (i = 0; i < n; i++)
{
x[i] = b / (float)TWO02;
y[i] = z[i] = c / (float)TWO04;
}
/*
* 1. saxpy on host
*/
clock_gettime(CLOCK_REALTIME, rt + 0);
for (i = 0; i < n; i++)
{
y[i] = a * x[i] + y[i];
}
clock_gettime(CLOCK_REALTIME, rt + 1);
wt = (rt[1].tv_sec - rt[0].tv_sec) + 1.0e-9 * (rt[1].tv_nsec - rt[0].tv_nsec);
printf("saxpy on host : %9.3f sec %9.1f MFLOPS\n", wt, 2.0 * n / (1.0e6 * wt));
/*
* 2. saxpy on accel
*/
clock_gettime(CLOCK_REALTIME, rt + 0);
#pragma omp target parallel for map(to \
: a, n, x [0:n]) map(tofrom \
: z [0:n])
for (int i = 0; i < n; i++)
{
z[i] = a * x[i] + z[i];
}
clock_gettime(CLOCK_REALTIME, rt + 1);
wt = (rt[1].tv_sec - rt[0].tv_sec) + 1.0e-9 * (rt[1].tv_nsec - rt[0].tv_nsec);
printf("saxpy on accel: %9.3f sec %9.1f MFLOPS\n", wt, 2.0 * n / (1.0e6 * wt));
/*
* 3. verify numerical consistency
*/
for (i = 0; i < n; i++)
{
iret = *(int *)(y + i) ^ *(int *)(z + i);
assert(iret == 0);
}
return 0;
}
|
GB_binop__bxor_uint8.c |
//------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_emult.h"
#include "GB_control.h"
#include "GB_ek_slice.h"
#include "GB_dense.h"
#include "GB_atomics.h"
#include "GB_bitmap_assign_methods.h"
#include "GB_binop__include.h"
// C=binop(A,B) is defined by the following types and operators:
// A+B function (eWiseAdd): GB (_AaddB__bxor_uint8)
// A.*B function (eWiseMult): GB (_AemultB_08__bxor_uint8)
// A.*B function (eWiseMult): GB (_AemultB_02__bxor_uint8)
// A.*B function (eWiseMult): GB (_AemultB_04__bxor_uint8)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__bxor_uint8)
// A*D function (colscale): GB (_AxD__bxor_uint8)
// D*A function (rowscale): GB (_DxB__bxor_uint8)
// C+=B function (dense accum): GB (_Cdense_accumB__bxor_uint8)
// C+=b function (dense accum): GB (_Cdense_accumb__bxor_uint8)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__bxor_uint8)
// C=scalar+B GB (_bind1st__bxor_uint8)
// C=scalar+B' GB (_bind1st_tran__bxor_uint8)
// C=A+scalar GB (_bind2nd__bxor_uint8)
// C=A'+scalar GB (_bind2nd_tran__bxor_uint8)
// C type: uint8_t
// A type: uint8_t
// A pattern? 0
// B type: uint8_t
// B pattern? 0
// BinaryOp: cij = (aij) ^ (bij)
#define GB_ATYPE \
uint8_t
#define GB_BTYPE \
uint8_t
#define GB_CTYPE \
uint8_t
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
1
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
1
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA,A_iso) \
uint8_t aij = GBX (Ax, pA, A_iso)
// true if values of A are not used
#define GB_A_IS_PATTERN \
0 \
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB,B_iso) \
uint8_t bij = GBX (Bx, pB, B_iso)
// true if values of B are not used
#define GB_B_IS_PATTERN \
0 \
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
uint8_t t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \
cij = GBX (Ax, pA, A_iso)
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \
cij = GBX (Bx, pB, B_iso)
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z,x,y,i,j) \
z = (x) ^ (y) ;
// true if the binop must be flipped
#define GB_BINOP_FLIP \
0
// op is second
#define GB_OP_IS_SECOND \
0
// do the numerical phases of GB_add and GB_emult
#define GB_PHASE_2_OF_2
// hard-coded loops can be vectorized
#define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_BXOR || GxB_NO_UINT8 || GxB_NO_BXOR_UINT8)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
#if 0
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
#endif
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
void GB (_Cdense_ewise3_noaccum__bxor_uint8)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_noaccum_template.c"
}
//------------------------------------------------------------------------------
// C += B, accumulate a sparse matrix into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumB__bxor_uint8)
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
#include "GB_dense_subassign_23_template.c"
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumb__bxor_uint8)
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
// get the scalar b for C += b, of type uint8_t
uint8_t bwork = (*((uint8_t *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_AxD__bxor_uint8)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix D,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint8_t *restrict Cx = (uint8_t *) C->x ;
#include "GB_AxB_colscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_DxB__bxor_uint8)
(
GrB_Matrix C,
const GrB_Matrix D,
const GrB_Matrix B,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint8_t *restrict Cx = (uint8_t *) C->x ;
#include "GB_AxB_rowscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__bxor_uint8)
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool is_eWiseUnion,
const GB_void *alpha_scalar_in,
const GB_void *beta_scalar_in,
const bool Ch_is_Mh,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GB_WERK_DECLARE (M_ek_slicing, int64_t) ;
GB_WERK_DECLARE (A_ek_slicing, int64_t) ;
GB_WERK_DECLARE (B_ek_slicing, int64_t) ;
uint8_t alpha_scalar ;
uint8_t beta_scalar ;
if (is_eWiseUnion)
{
alpha_scalar = (*((uint8_t *) alpha_scalar_in)) ;
beta_scalar = (*((uint8_t *) beta_scalar_in )) ;
}
#include "GB_add_template.c"
GB_FREE_WORKSPACE ;
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_08__bxor_uint8)
(
GrB_Matrix C,
const int C_sparsity,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_08_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_02__bxor_uint8)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool flipxy,
const int64_t *restrict Cp_kfirst,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if GB_BINOP_FLIP
// The operator is not commutative, and does not have a flipped
// variant. For example z=atan2(y,x).
if (flipxy)
{
// use fmult(y,x)
#undef GB_FLIPPED
#define GB_FLIPPED 1
#include "GB_emult_02_template.c"
}
else
{
// use fmult(x,y)
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
}
#else
// No need to handle the flip: the operator is either commutative, or
// has been handled by changing z=div(y,x) to z=rdiv(x,y) for example.
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_04__bxor_uint8)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict Cp_kfirst,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_04_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_bitmap__bxor_uint8)
(
GrB_Matrix C,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_bitmap_emult_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
GrB_Info GB (_bind1st__bxor_uint8)
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
const int8_t *restrict Bb,
int64_t bnz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint8_t *Cx = (uint8_t *) Cx_output ;
uint8_t x = (*((uint8_t *) x_input)) ;
uint8_t *Bx = (uint8_t *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < bnz ; p++)
{
if (!GBB (Bb, p)) continue ;
uint8_t bij = GBX (Bx, p, false) ;
Cx [p] = (x) ^ (bij) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__bxor_uint8)
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
const int8_t *restrict Ab,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
uint8_t *Cx = (uint8_t *) Cx_output ;
uint8_t *Ax = (uint8_t *) Ax_input ;
uint8_t y = (*((uint8_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
uint8_t aij = GBX (Ax, p, false) ;
Cx [p] = (aij) ^ (y) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
uint8_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = (x) ^ (aij) ; \
}
GrB_Info GB (_bind1st_tran__bxor_uint8)
(
GrB_Matrix C,
const GB_void *x_input,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
// GB_unop_transpose.c uses GB_ATYPE, but A is
// the 2nd input to binary operator z=f(x,y).
#undef GB_ATYPE
#define GB_ATYPE \
uint8_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint8_t x = (*((const uint8_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
uint8_t
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
uint8_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = (aij) ^ (y) ; \
}
GrB_Info GB (_bind2nd_tran__bxor_uint8)
(
GrB_Matrix C,
const GrB_Matrix A,
const GB_void *y_input,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint8_t y = (*((const uint8_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
GB_binop__pow_uint64.c | //------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_emult.h"
#include "GB_control.h"
#include "GB_ek_slice.h"
#include "GB_dense.h"
#include "GB_atomics.h"
#include "GB_bitmap_assign_methods.h"
#include "GB_binop__include.h"
// C=binop(A,B) is defined by the following types and operators:
// A+B function (eWiseAdd): GB (_AaddB__pow_uint64)
// A.*B function (eWiseMult): GB (_AemultB_08__pow_uint64)
// A.*B function (eWiseMult): GB (_AemultB_02__pow_uint64)
// A.*B function (eWiseMult): GB (_AemultB_04__pow_uint64)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__pow_uint64)
// A*D function (colscale): GB ((none))
// D*A function (rowscale): GB ((none))
// C+=B function (dense accum): GB (_Cdense_accumB__pow_uint64)
// C+=b function (dense accum): GB (_Cdense_accumb__pow_uint64)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__pow_uint64)
// C=scalar+B GB (_bind1st__pow_uint64)
// C=scalar+B' GB (_bind1st_tran__pow_uint64)
// C=A+scalar GB (_bind2nd__pow_uint64)
// C=A'+scalar GB (_bind2nd_tran__pow_uint64)
// C type: uint64_t
// A type: uint64_t
// B,b type: uint64_t
// BinaryOp: cij = GB_pow_uint64 (aij, bij)
#define GB_ATYPE \
uint64_t
#define GB_BTYPE \
uint64_t
#define GB_CTYPE \
uint64_t
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
1
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
1
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA,A_iso) \
uint64_t aij = GBX (Ax, pA, A_iso)
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB,B_iso) \
uint64_t bij = GBX (Bx, pB, B_iso)
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
uint64_t t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \
cij = GBX (Ax, pA, A_iso)
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \
cij = GBX (Bx, pB, B_iso)
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z,x,y,i,j) \
z = GB_pow_uint64 (x, y) ;
// true if the binop must be flipped
#define GB_BINOP_FLIP \
1
// op is second
#define GB_OP_IS_SECOND \
0
// do the numerical phases of GB_add and GB_emult
#define GB_PHASE_2_OF_2
// hard-coded loops can be vectorized
#define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_POW || GxB_NO_UINT64 || GxB_NO_POW_UINT64)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
#if 0
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
#endif
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_ewise3_noaccum__pow_uint64)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_dense_ewise3_noaccum_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += B, accumulate a sparse matrix into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumB__pow_uint64)
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
#include "GB_dense_subassign_23_template.c"
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumb__pow_uint64)
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
// get the scalar b for C += b, of type uint64_t
uint64_t bwork = (*((uint64_t *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A, bool A_is_pattern,
const GrB_Matrix D, bool D_is_pattern,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint64_t *restrict Cx = (uint64_t *) C->x ;
#include "GB_AxB_colscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
GrB_Matrix C,
const GrB_Matrix D, bool D_is_pattern,
const GrB_Matrix B, bool B_is_pattern,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint64_t *restrict Cx = (uint64_t *) C->x ;
#include "GB_AxB_rowscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__pow_uint64)
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool Ch_is_Mh,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GB_WERK_DECLARE (M_ek_slicing, int64_t) ;
GB_WERK_DECLARE (A_ek_slicing, int64_t) ;
GB_WERK_DECLARE (B_ek_slicing, int64_t) ;
#include "GB_add_template.c"
GB_FREE_WORK ;
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_08__pow_uint64)
(
GrB_Matrix C,
const int C_sparsity,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_08_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_02__pow_uint64)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool flipxy,
const int64_t *restrict Cp_kfirst,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if GB_BINOP_FLIP
// The operator is not commutative, and does not have a flipped
// variant. For example z=atan2(y,x).
if (flipxy)
{
// use fmult(y,x)
#undef GB_FLIPPED
#define GB_FLIPPED 1
#include "GB_emult_02_template.c"
}
else
{
// use fmult(x,y)
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
}
#else
// No need to handle the flip: the operator is either commutative, or
// has been handled by changing z=div(y,x) to z=rdiv(x,y) for example.
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_04__pow_uint64)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict Cp_kfirst,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_04_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_bitmap__pow_uint64)
(
GrB_Matrix C,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_bitmap_emult_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
GrB_Info GB (_bind1st__pow_uint64)
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
const int8_t *restrict Bb,
int64_t bnz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint64_t *Cx = (uint64_t *) Cx_output ;
uint64_t x = (*((uint64_t *) x_input)) ;
uint64_t *Bx = (uint64_t *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < bnz ; p++)
{
if (!GBB (Bb, p)) continue ;
uint64_t bij = GBX (Bx, p, false) ;
Cx [p] = GB_pow_uint64 (x, bij) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__pow_uint64)
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
const int8_t *restrict Ab,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
uint64_t *Cx = (uint64_t *) Cx_output ;
uint64_t *Ax = (uint64_t *) Ax_input ;
uint64_t y = (*((uint64_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
uint64_t aij = GBX (Ax, p, false) ;
Cx [p] = GB_pow_uint64 (aij, y) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
uint64_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = GB_pow_uint64 (x, aij) ; \
}
GrB_Info GB (_bind1st_tran__pow_uint64)
(
GrB_Matrix C,
const GB_void *x_input,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
// GB_unop_transpose.c uses GB_ATYPE, but A is
// the 2nd input to binary operator z=f(x,y).
#undef GB_ATYPE
#define GB_ATYPE \
uint64_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint64_t x = (*((const uint64_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
uint64_t
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
uint64_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = GB_pow_uint64 (aij, y) ; \
}
GrB_Info GB (_bind2nd_tran__pow_uint64)
(
GrB_Matrix C,
const GrB_Matrix A,
const GB_void *y_input,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint64_t y = (*((const uint64_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
GB_unop__identity_fc32_uint16.c | //------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_atomics.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB (_unop_apply__identity_fc32_uint16)
// op(A') function: GB (_unop_tran__identity_fc32_uint16)
// C type: GxB_FC32_t
// A type: uint16_t
// cast: GxB_FC32_t cij = GxB_CMPLXF ((float) (aij), 0)
// unaryop: cij = aij
#define GB_ATYPE \
uint16_t
#define GB_CTYPE \
GxB_FC32_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
uint16_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = x ;
// casting
#define GB_CAST(z, aij) \
GxB_FC32_t z = GxB_CMPLXF ((float) (aij), 0) ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
uint16_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
GxB_FC32_t z = GxB_CMPLXF ((float) (aij), 0) ; \
Cx [pC] = z ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_IDENTITY || GxB_NO_FC32 || GxB_NO_UINT16)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__identity_fc32_uint16)
(
GxB_FC32_t *Cx, // Cx and Ax may be aliased
const uint16_t *Ax,
const int8_t *restrict Ab, // A->b if A is bitmap
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
if (Ab == NULL)
{
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
uint16_t aij = Ax [p] ;
GxB_FC32_t z = GxB_CMPLXF ((float) (aij), 0) ;
Cx [p] = z ;
}
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
uint16_t aij = Ax [p] ;
GxB_FC32_t z = GxB_CMPLXF ((float) (aij), 0) ;
Cx [p] = z ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__identity_fc32_uint16)
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
ccl_utils.c | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_errno.h>
#include "ccl.h"
/* ------- ROUTINE: ccl_linear spacing ------
INPUTS: [xmin,xmax] of the interval to be divided in N bins
OUTPUT: bin edges in range [xmin,xmax]
*/
double * ccl_linear_spacing(double xmin, double xmax, int N)
{
double dx = (xmax-xmin)/(N -1.);
double * x = malloc(sizeof(double)*N);
if (x==NULL) {
ccl_raise_warning(
CCL_ERROR_MEMORY,
"ERROR: Could not allocate memory for linear-spaced array (N=%d)\n", N);
return x;
}
for (int i=0; i<N; i++) {
x[i] = xmin + dx*i;
}
x[0]=xmin; //Make sure roundoff errors don't spoil edges
x[N-1]=xmax; //Make sure roundoff errors don't spoil edges
return x;
}
/* ------- ROUTINE: ccl_linlog spacing ------
* INPUTS: [xminlog,xmax] of the interval to be divided in bins
* xmin when linear spacing starts
* Nlog number of logarithmically spaced bins
* Nlin number of linearly spaced bins
* OUTPUT: bin edges in range [xminlog,xmax]
* */
double * ccl_linlog_spacing(double xminlog, double xmin, double xmax, int Nlog, int Nlin)
{
if (Nlog<2) {
ccl_raise_warning(
CCL_ERROR_LINLOGSPACE,
"ERROR: Cannot make log-spaced array with %d points - need at least 2\n", Nlog);
return NULL;
}
if (!(xminlog>0 && xmin>0)) {
ccl_raise_warning(
CCL_ERROR_LINLOGSPACE,
"ERROR: Cannot make log-spaced array xminlog or xmin non-positive (had %le, %le)\n", xminlog, xmin);
return NULL;
}
if (xminlog>xmin){
ccl_raise_warning(CCL_ERROR_LINLOGSPACE, "ERROR: xminlog must be smaller as xmin");
return NULL;
}
if (xmin>xmax){
ccl_raise_warning(CCL_ERROR_LINLOGSPACE, "ERROR: xmin must be smaller as xmax");
return NULL;
}
double * x = malloc(sizeof(double)*(Nlin+Nlog-1));
if (x==NULL) {
ccl_raise_warning(
CCL_ERROR_MEMORY,
"ERROR: Could not allocate memory for array of size (Nlin+Nlog-1)=%d)\n", (Nlin+Nlog-1));
return x;
}
double dx = (xmax-xmin)/(Nlin -1.);
double log_xchange = log(xmin);
double log_xmin = log(xminlog);
double dlog_x = (log_xchange - log_xmin) / (Nlog-1.);
for (int i=0; i<Nlin+Nlog-1; i++) {
if (i<Nlog)
x[i] = exp(log_xmin + dlog_x*i);
if (i>=Nlog)
x[i] = xmin + dx*(i-Nlog+1);
}
x[0]=xminlog; //Make sure roundoff errors don't spoil edges
x[Nlog-1]=xmin; //Make sure roundoff errors don't spoil edges
x[Nlin+Nlog-2]=xmax; //Make sure roundoff errors don't spoil edges
return x;
}
/* ------- ROUTINE: ccl_log spacing ------
INPUTS: [xmin,xmax] of the interval to be divided logarithmically in N bins
TASK: divide an interval in N logarithmic bins
OUTPUT: bin edges in range [xmin,xmax]
*/
double * ccl_log_spacing(double xmin, double xmax, int N)
{
if (N<2) {
ccl_raise_warning(
CCL_ERROR_LOGSPACE,
"ERROR: Cannot make log-spaced array with %d points - need at least 2\n", N);
return NULL;
}
if (!(xmin>0 && xmax>0)) {
ccl_raise_warning(
CCL_ERROR_LOGSPACE,
"ERROR: Cannot make log-spaced array xmax or xmax non-positive (had %le, %le)\n", xmin, xmax);
return NULL;
}
double log_xmax = log(xmax);
double log_xmin = log(xmin);
double dlog_x = (log_xmax - log_xmin) / (N-1.);
double * x = malloc(sizeof(double)*N);
if (x==NULL) {
ccl_raise_warning(
CCL_ERROR_MEMORY,
"ERROR: Could not allocate memory for log-spaced array (N=%d)\n", N);
return x;
}
double xratio = exp(dlog_x);
x[0] = xmin; //Make sure roundoff errors don't spoil edges
for (int i=1; i<N-1; i++) {
x[i] = x[i-1] * xratio;
}
x[N-1]=xmax; //Make sure roundoff errors don't spoil edges
return x;
}
#define CCL_GAMMA1 2.6789385347077476336556 //Gamma(1/3)
#define CCL_GAMMA2 1.3541179394264004169452 //Gamma(2/3)
#define CCL_ROOTPI12 21.269446210866192327578 //12*sqrt(pi)
double ccl_j_bessel(int l,double x)
{
double jl;
double ax=fabs(x);
double ax2=x*x;
if(l<0) {
fprintf(stderr,"CosmoMas: l>0 for Bessel function");
exit(1);
}
if(l<7) {
if(l==0) {
if(ax<0.1) jl=1-ax2*(1-ax2/20.)/6.;
else jl=sin(x)/x;
}
else if(l==1) {
if(ax<0.2) jl=ax*(1-ax2*(1-ax2/28)/10)/3;
else jl=(sin(x)/ax-cos(x))/ax;
}
else if(l==2) {
if(ax<0.3) jl=ax2*(1-ax2*(1-ax2/36)/14)/15;
else jl=(-3*cos(x)/ax-sin(x)*(1-3/ax2))/ax;
}
else if(l==3) {
if(ax<0.4)
jl=ax*ax2*(1-ax2*(1-ax2/44)/18)/105;
else
jl=(cos(x)*(1-15/ax2)-sin(x)*(6-15/ax2)/ax)/ax;
}
else if(l==4) {
if(ax<0.6)
jl=ax2*ax2*(1-ax2*(1-ax2/52)/22)/945;
else
jl=(sin(x)*(1-(45-105/ax2)/ax2)+cos(x)*(10-105/ax2)/ax)/ax;
}
else if(l==5) {
if(ax<1.0)
jl=ax2*ax2*ax*(1-ax2*(1-ax2/60)/26)/10395;
else {
jl=(sin(x)*(15-(420-945/ax2)/ax2)/ax-
cos(x)*(1-(105-945/ax2)/ax2))/ax;
}
}
else {
if(ax<1.0)
jl=ax2*ax2*ax2*(1-ax2*(1-ax2/68)/30)/135135;
else {
jl=(sin(x)*(-1+(210-(4725-10395/ax2)/ax2)/ax2)+
cos(x)*(-21+(1260-10395/ax2)/ax2)/ax)/ax;
}
}
}
else {
double nu=l+0.5;
double nu2=nu*nu;
if(ax<1.0E-40) jl=0;
else if((ax2/l)<0.5) {
jl=(exp(l*log(ax/nu)-M_LN2+nu*(1-M_LN2)-(1-(1-3.5/nu2)/(30*nu2))/(12*nu))/nu)*
(1-ax2/(4*nu+4)*(1-ax2/(8*nu+16)*(1-ax2/(12*nu+36))));
}
else if((l*l/ax)<0.5) {
double beta=ax-0.5*M_PI*(l+1);
jl=(cos(beta)*(1-(nu2-0.25)*(nu2-2.25)/(8*ax2)*(1-(nu2-6.25)*(nu2-12.25)/(48*ax2)))-
sin(beta)*(nu2-0.25)/(2*ax)*(1-(nu2-2.25)*(nu2-6.25)/(24*ax2)*
(1-(nu2-12.25)*(nu2-20.25)/(80*ax2))))/ax;
}
else {
double l3=pow(nu,0.325);
if(ax<nu-1.31*l3) {
double cosb=nu/ax;
double sx=sqrt(nu2-ax2);
double cotb=nu/sx;
double secb=ax/nu;
double beta=log(cosb+sx/ax);
double cot3b=cotb*cotb*cotb;
double cot6b=cot3b*cot3b;
double sec2b=secb*secb;
double expterm=((2+3*sec2b)*cot3b/24
-((4+sec2b)*sec2b*cot6b/16
+((16-(1512+(3654+375*sec2b)*sec2b)*sec2b)*cot3b/5760
+(32+(288+(232+13*sec2b)*sec2b)*sec2b)*sec2b*cot6b/(128*nu))*
cot6b/nu)/nu)/nu;
jl=sqrt(cotb*cosb)/(2*nu)*exp(-nu*beta+nu/cotb-expterm);
}
else if(ax>nu+1.48*l3) {
double cosb=nu/ax;
double sx=sqrt(ax2-nu2);
double cotb=nu/sx;
double secb=ax/nu;
double beta=acos(cosb);
double cot3b=cotb*cotb*cotb;
double cot6b=cot3b*cot3b;
double sec2b=secb*secb;
double trigarg=nu/cotb-nu*beta-0.25*M_PI-
((2+3*sec2b)*cot3b/24+(16-(1512+(3654+375*sec2b)*sec2b)*sec2b)*
cot3b*cot6b/(5760*nu2))/nu;
double expterm=((4+sec2b)*sec2b*cot6b/16-
(32+(288+(232+13*sec2b)*sec2b)*sec2b)*
sec2b*cot6b*cot6b/(128*nu2))/nu2;
jl=sqrt(cotb*cosb)/nu*exp(-expterm)*cos(trigarg);
}
else {
double beta=ax-nu;
double beta2=beta*beta;
double sx=6/ax;
double sx2=sx*sx;
double secb=pow(sx,0.3333333333333333333333);
double sec2b=secb*secb;
jl=(CCL_GAMMA1*secb+beta*CCL_GAMMA2*sec2b
-(beta2/18-1.0/45.0)*beta*sx*secb*CCL_GAMMA1
-((beta2-1)*beta2/36+1.0/420.0)*sx*sec2b*CCL_GAMMA2
+(((beta2/1620-7.0/3240.0)*beta2+1.0/648.0)*beta2-1.0/8100.0)*sx2*secb*CCL_GAMMA1
+(((beta2/4536-1.0/810.0)*beta2+19.0/11340.0)*beta2-13.0/28350.0)*beta*sx2*sec2b*CCL_GAMMA2
-((((beta2/349920-1.0/29160.0)*beta2+71.0/583200.0)*beta2-121.0/874800.0)*
beta2+7939.0/224532000.0)*beta*sx2*sx*secb*CCL_GAMMA1)*sqrt(sx)/CCL_ROOTPI12;
}
}
}
if((x<0)&&(l%2!=0)) jl=-jl;
return jl;
}
void ccl_integ_spline(int ny, int nx,double *x,double **y,
double a, double b, double *result,
const gsl_interp_type *T, int *status)
{
if(b==a) {
int iyy;
for(iyy=0; iyy<ny; iyy++)
result[iyy]=0;
return;
}
if(b<a) {
b=x[nx-1];
a=x[0];
}
if((b>x[nx-1]) || (a<x[0])) {
ccl_raise_warning(CCL_ERROR_SPLINE,
"ERROR: integration limits beyond interpolated range\n");
*status = CCL_ERROR_SPLINE;
return;
}
if(*status==0) {
#pragma omp parallel default(none) \
shared(nx, ny, x, y, a, b, result, T, status)
{
int iy;
int local_status=0;
gsl_interp_accel *ia = NULL;
gsl_spline *s = NULL;
s = gsl_spline_alloc(T, nx);
if(s == NULL)
local_status = CCL_ERROR_MEMORY;
if(!local_status) {
ia = gsl_interp_accel_alloc();
if(ia == NULL)
local_status = CCL_ERROR_MEMORY;
}
if(!local_status) {
#pragma omp for
for(iy=0; iy<ny; iy++) {
if(!local_status) {
if(gsl_spline_init(s, x, y[iy], nx)) {
local_status = CCL_ERROR_SPLINE;
result[iy] = NAN;
}
}
if(!local_status) {
int sstat = gsl_spline_eval_integ_e(s, a, b, ia, &(result[iy]));
if(sstat) {
local_status = CCL_ERROR_SPLINE_EV;
result[iy] = NAN;
}
}
}
}
gsl_spline_free(s);
gsl_interp_accel_free(ia);
if (local_status) {
#pragma omp atomic write
*status = local_status;
}
} //end omp parallel
}
}
|
GB_subassign_11.c | //------------------------------------------------------------------------------
// GB_subassign_11: C(I,J)<M,repl> += scalar ; using S
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// Method 11: C(I,J)<M,repl> += scalar ; using S
// M: present
// Mask_comp: false
// C_replace: true
// accum: present
// A: scalar
// S: constructed
// C, M: not bitmap
#include "GB_unused.h"
#include "GB_subassign_methods.h"
GrB_Info GB_subassign_11
(
GrB_Matrix C,
// input:
const GrB_Index *I,
const int64_t ni,
const int64_t nI,
const int Ikind,
const int64_t Icolon [3],
const GrB_Index *J,
const int64_t nj,
const int64_t nJ,
const int Jkind,
const int64_t Jcolon [3],
const GrB_Matrix M,
const bool Mask_struct,
const GrB_BinaryOp accum,
const void *scalar,
const GrB_Type atype,
GB_Context Context
)
{
//--------------------------------------------------------------------------
// check inputs
//--------------------------------------------------------------------------
ASSERT (!GB_IS_BITMAP (C)) ; ASSERT (!GB_IS_FULL (C)) ;
ASSERT (!GB_aliased (C, M)) ; // NO ALIAS of C==M
//--------------------------------------------------------------------------
// S = C(I,J)
//--------------------------------------------------------------------------
GB_EMPTY_TASKLIST ;
GB_OK (GB_subassign_symbolic (&S, C, I, ni, J, nj, true, Context)) ;
//--------------------------------------------------------------------------
// get inputs
//--------------------------------------------------------------------------
GB_MATRIX_WAIT_IF_JUMBLED (M) ;
GB_GET_C ; // C must not be bitmap
GB_GET_MASK ;
GB_GET_ACCUM_SCALAR ;
GB_GET_S ;
//--------------------------------------------------------------------------
// Method 11: C(I,J)<M,repl> += scalar ; using S
//--------------------------------------------------------------------------
// Time: Optimal. All entries in M+S must be examined. All entries in S
// are modified: if M(i,j)=1 then S(i,j) is used to write to the
// corresponding entry in C. If M(i,j) is not present, or zero, then the
// entry in C is cleared (because of C_replace). If S(i,j) is not present,
// and M(i,j)=1, then the scalar is inserted into C. The only case that
// can be skipped is if neither S nor M is present. As a result, this
// method need not traverse all of IxJ. It can limit its traversal to the
// pattern of M+S.
// Method 09 and Method 11 are very similar.
//--------------------------------------------------------------------------
// Parallel: M+S (Methods 02, 04, 09, 10, 11, 12, 14, 16, 18, 20)
//--------------------------------------------------------------------------
if (M_is_bitmap)
{
// all of IxJ must be examined
GB_SUBASSIGN_IXJ_SLICE ;
}
else
{
// traverse all M+S
GB_SUBASSIGN_TWO_SLICE (M, S) ;
}
//--------------------------------------------------------------------------
// phase 1: create zombies, update entries, and count pending tuples
//--------------------------------------------------------------------------
if (M_is_bitmap)
{
//----------------------------------------------------------------------
// phase1: M is bitmap
//----------------------------------------------------------------------
#pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) \
reduction(+:nzombies)
for (taskid = 0 ; taskid < ntasks ; taskid++)
{
//------------------------------------------------------------------
// get the task descriptor
//------------------------------------------------------------------
GB_GET_IXJ_TASK_DESCRIPTOR_PHASE1 (iM_start, iM_end) ;
//------------------------------------------------------------------
// compute all vectors in this task
//------------------------------------------------------------------
for (int64_t j = kfirst ; j <= klast ; j++)
{
//--------------------------------------------------------------
// get S(iM_start:iM_end,j)
//--------------------------------------------------------------
GB_GET_VECTOR_FOR_IXJ (S, iM_start) ;
int64_t pM_start = j * Mvlen ;
//--------------------------------------------------------------
// do a 2-way merge of S(iM_start:iM_end,j) and M(ditto,j)
//--------------------------------------------------------------
for (int64_t iM = iM_start ; iM < iM_end ; iM++)
{
int64_t pM = pM_start + iM ;
bool Sfound = (pS < pS_end) && (GBI (Si, pS, Svlen) == iM) ;
bool mij = Mb [pM] && GB_mcast (Mx, pM, msize) ;
if (Sfound && !mij)
{
// S (i,j) is present but M (i,j) is false
// ----[C A 0] or [X A 0]-------------------------------
// [X A 0]: action: ( X ): still a zombie
// [C A 0]: C_repl: action: ( delete ): becomes zombie
GB_C_S_LOOKUP ;
GB_DELETE_ENTRY ;
GB_NEXT (S) ;
}
else if (!Sfound && mij)
{
// S (i,j) is not present, M (i,j) is true
// ----[. A 1]------------------------------------------
// [. A 1]: action: ( insert )
task_pending++ ;
}
else if (Sfound && mij)
{
// S (i,j) present and M (i,j) is true
GB_C_S_LOOKUP ;
// ----[C A 1] or [X A 1]-------------------------------
// [C A 1]: action: ( =C+A ): apply accum
// [X A 1]: action: ( undelete ): zombie lives
GB_withaccum_C_A_1_scalar ;
GB_NEXT (S) ;
}
}
}
GB_PHASE1_TASK_WRAPUP ;
}
}
else
{
//----------------------------------------------------------------------
// phase1: M is hypersparse, sparse, or full
//----------------------------------------------------------------------
#pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) \
reduction(+:nzombies)
for (taskid = 0 ; taskid < ntasks ; taskid++)
{
//------------------------------------------------------------------
// get the task descriptor
//------------------------------------------------------------------
GB_GET_TASK_DESCRIPTOR_PHASE1 ;
//------------------------------------------------------------------
// compute all vectors in this task
//------------------------------------------------------------------
for (int64_t k = kfirst ; k <= klast ; k++)
{
//--------------------------------------------------------------
// get S(:,j) and M(:,j)
//--------------------------------------------------------------
int64_t j = GBH (Zh, k) ;
GB_GET_MAPPED (pM, pM_end, pA, pA_end, Mp, j, k, Z_to_X, Mvlen);
GB_GET_MAPPED (pS, pS_end, pB, pB_end, Sp, j, k, Z_to_S, Svlen);
//--------------------------------------------------------------
// do a 2-way merge of S(:,j) and M(:,j)
//--------------------------------------------------------------
// jC = J [j] ; or J is a colon expression
// int64_t jC = GB_ijlist (J, j, Jkind, Jcolon) ;
// while both list S (:,j) and M (:,j) have entries
while (pS < pS_end && pM < pM_end)
{
int64_t iS = GBI (Si, pS, Svlen) ;
int64_t iM = GBI (Mi, pM, Mvlen) ;
if (iS < iM)
{
// S (i,j) is present but M (i,j) is not
// ----[C A 0] or [X A 0]-------------------------------
// [X A 0]: action: ( X ): still a zombie
// [C A 0]: C_repl: action: ( delete ): becomes zombie
GB_C_S_LOOKUP ;
GB_DELETE_ENTRY ;
GB_NEXT (S) ;
}
else if (iM < iS)
{
// S (i,j) is not present, M (i,j) is present
if (GB_mcast (Mx, pM, msize))
{
// ----[. A 1]--------------------------------------
// [. A 1]: action: ( insert )
task_pending++ ;
}
GB_NEXT (M) ;
}
else
{
// both S (i,j) and M (i,j) present
GB_C_S_LOOKUP ;
if (GB_mcast (Mx, pM, msize))
{
// ----[C A 1] or [X A 1]---------------------------
// [C A 1]: action: ( =C+A ): apply accum
// [X A 1]: action: ( undelete ): zombie lives
GB_withaccum_C_A_1_scalar ;
}
else
{
// ----[C A 0] or [X A 0]---------------------------
// [X A 0]: action: ( X ): still a zombie
// [C A 0]: C_repl: action: ( delete ): now zombie
GB_DELETE_ENTRY ;
}
GB_NEXT (S) ;
GB_NEXT (M) ;
}
}
// while list S (:,j) has entries. List M (:,j) exhausted.
while (pS < pS_end)
{
// S (i,j) is present but M (i,j) is not
// ----[C A 0] or [X A 0]-----------------------------------
// [X A 0]: action: ( X ): still a zombie
// [C A 0]: C_repl: action: ( delete ): becomes zombie
GB_C_S_LOOKUP ;
GB_DELETE_ENTRY ;
GB_NEXT (S) ;
}
// while list M (:,j) has entries. List S (:,j) exhausted.
while (pM < pM_end)
{
// S (i,j) is not present, M (i,j) is present
if (GB_mcast (Mx, pM, msize))
{
// ----[. A 1]------------------------------------------
// [. A 1]: action: ( insert )
task_pending++ ;
}
GB_NEXT (M) ;
}
}
GB_PHASE1_TASK_WRAPUP ;
}
}
//--------------------------------------------------------------------------
// phase 2: insert pending tuples
//--------------------------------------------------------------------------
GB_PENDING_CUMSUM ;
if (M_is_bitmap)
{
//----------------------------------------------------------------------
// phase2: M is bitmap
//----------------------------------------------------------------------
#pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) \
reduction(&&:pending_sorted)
for (taskid = 0 ; taskid < ntasks ; taskid++)
{
//------------------------------------------------------------------
// get the task descriptor
//------------------------------------------------------------------
GB_GET_IXJ_TASK_DESCRIPTOR_PHASE2 (iM_start, iM_end) ;
//------------------------------------------------------------------
// compute all vectors in this task
//------------------------------------------------------------------
for (int64_t j = kfirst ; j <= klast ; j++)
{
//--------------------------------------------------------------
// get S(iM_start:iM_end,j)
//--------------------------------------------------------------
GB_GET_VECTOR_FOR_IXJ (S, iM_start) ;
int64_t pM_start = j * Mvlen ;
//--------------------------------------------------------------
// do a 2-way merge of S(iM_start:iM_end,j) and M(ditto,j)
//--------------------------------------------------------------
// jC = J [j] ; or J is a colon expression
int64_t jC = GB_ijlist (J, j, Jkind, Jcolon) ;
for (int64_t iM = iM_start ; iM < iM_end ; iM++)
{
int64_t pM = pM_start + iM ;
bool Sfound = (pS < pS_end) && (GBI (Si, pS, Svlen) == iM) ;
bool mij = Mb [pM] && GB_mcast (Mx, pM, msize) ;
if (!Sfound && mij)
{
// S (i,j) is not present, M (i,j) is true
// ----[. A 1]------------------------------------------
// [. A 1]: action: ( insert )
int64_t iC = GB_ijlist (I, iM, Ikind, Icolon) ;
GB_PENDING_INSERT (scalar) ;
}
else if (Sfound)
{
// S (i,j) present
GB_NEXT (S) ;
}
}
}
GB_PHASE2_TASK_WRAPUP ;
}
}
else
{
//----------------------------------------------------------------------
// phase2: M is hypersparse, sparse, or full
//----------------------------------------------------------------------
#pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) \
reduction(&&:pending_sorted)
for (taskid = 0 ; taskid < ntasks ; taskid++)
{
//------------------------------------------------------------------
// get the task descriptor
//------------------------------------------------------------------
GB_GET_TASK_DESCRIPTOR_PHASE2 ;
//------------------------------------------------------------------
// compute all vectors in this task
//------------------------------------------------------------------
for (int64_t k = kfirst ; k <= klast ; k++)
{
//--------------------------------------------------------------
// get S(:,j) and M(:,j)
//--------------------------------------------------------------
int64_t j = GBH (Zh, k) ;
GB_GET_MAPPED (pM, pM_end, pA, pA_end, Mp, j, k, Z_to_X, Mvlen);
GB_GET_MAPPED (pS, pS_end, pB, pB_end, Sp, j, k, Z_to_S, Svlen);
//--------------------------------------------------------------
// do a 2-way merge of S(:,j) and M(:,j)
//--------------------------------------------------------------
// jC = J [j] ; or J is a colon expression
int64_t jC = GB_ijlist (J, j, Jkind, Jcolon) ;
// while both list S (:,j) and M (:,j) have entries
while (pS < pS_end && pM < pM_end)
{
int64_t iS = GBI (Si, pS, Svlen) ;
int64_t iM = GBI (Mi, pM, Mvlen) ;
if (iS < iM)
{
// S (i,j) is present but M (i,j) is not
GB_NEXT (S) ;
}
else if (iM < iS)
{
// S (i,j) is not present, M (i,j) is present
if (GB_mcast (Mx, pM, msize))
{
// ----[. A 1]--------------------------------------
// [. A 1]: action: ( insert )
int64_t iC = GB_ijlist (I, iM, Ikind, Icolon) ;
GB_PENDING_INSERT (scalar) ;
}
GB_NEXT (M) ;
}
else
{
// both S (i,j) and M (i,j) present
GB_NEXT (S) ;
GB_NEXT (M) ;
}
}
// while list M (:,j) has entries. List S (:,j) exhausted.
while (pM < pM_end)
{
// S (i,j) is not present, M (i,j) is present
if (GB_mcast (Mx, pM, msize))
{
// ----[. A 1]------------------------------------------
// [. A 1]: action: ( insert )
int64_t iM = GBI (Mi, pM, Mvlen) ;
int64_t iC = GB_ijlist (I, iM, Ikind, Icolon) ;
GB_PENDING_INSERT (scalar) ;
}
GB_NEXT (M) ;
}
}
GB_PHASE2_TASK_WRAPUP ;
}
}
//--------------------------------------------------------------------------
// finalize the matrix and return result
//--------------------------------------------------------------------------
GB_SUBASSIGN_WRAPUP ;
}
|
GB_unaryop__one_bool_bool.c | //------------------------------------------------------------------------------
// GB_unaryop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_iterator.h"
#include "GB_unaryop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop__one_bool_bool
// op(A') function: GB_tran__one_bool_bool
// C type: bool
// A type: bool
// cast: ;
// unaryop: cij = true
#define GB_ATYPE \
bool
#define GB_CTYPE \
bool
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
;
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = true ;
// casting
#define GB_CASTING(z, x) \
; ;
// cij = op (cast (aij))
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GB_GETA (aij, Ax, pA) ; \
/* Cx [pC] = op (cast (aij)) */ \
GB_CASTING (x, aij) ; \
GB_OP (GB_CX (pC), x) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_ONE || GxB_NO_BOOL)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__one_bool_bool
(
bool *restrict Cx,
const bool *restrict Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (int64_t p = 0 ; p < anz ; p++)
{
GB_CAST_OP (p, p) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_tran__one_bool_bool
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *restrict *Rowcounts,
GBI_single_iterator Iter,
const int64_t *restrict A_slice,
int naslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#define GB_PHASE_2_OF_2
#include "GB_unaryop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
GB_unop__minv_fc32_fc32.c | //------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_atomics.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB (_unop_apply__minv_fc32_fc32)
// op(A') function: GB (_unop_tran__minv_fc32_fc32)
// C type: GxB_FC32_t
// A type: GxB_FC32_t
// cast: GxB_FC32_t cij = aij
// unaryop: cij = GB_FC32_minv (aij)
#define GB_ATYPE \
GxB_FC32_t
#define GB_CTYPE \
GxB_FC32_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
GxB_FC32_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = GB_FC32_minv (x) ;
// casting
#define GB_CAST(z, aij) \
GxB_FC32_t z = aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GxB_FC32_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
GxB_FC32_t z = aij ; \
Cx [pC] = GB_FC32_minv (z) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_MINV || GxB_NO_FC32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__minv_fc32_fc32)
(
GxB_FC32_t *Cx, // Cx and Ax may be aliased
const GxB_FC32_t *Ax,
const int8_t *restrict Ab, // A->b if A is bitmap
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
if (Ab == NULL)
{
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
GxB_FC32_t aij = Ax [p] ;
GxB_FC32_t z = aij ;
Cx [p] = GB_FC32_minv (z) ;
}
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
GxB_FC32_t aij = Ax [p] ;
GxB_FC32_t z = aij ;
Cx [p] = GB_FC32_minv (z) ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__minv_fc32_fc32)
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
OpenMPClause.h | //===- OpenMPClause.h - Classes for OpenMP clauses --------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
/// \brief This file defines OpenMP AST classes for clauses.
/// There are clauses for executable directives, clauses for declarative
/// directives and clauses which can be used in both kinds of directives.
///
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_AST_OPENMPCLAUSE_H
#define LLVM_CLANG_AST_OPENMPCLAUSE_H
#include "clang/AST/Expr.h"
#include "clang/AST/Stmt.h"
#include "clang/Basic/OpenMPKinds.h"
#include "clang/Basic/SourceLocation.h"
namespace clang {
//===----------------------------------------------------------------------===//
// AST classes for clauses.
//===----------------------------------------------------------------------===//
/// \brief This is a basic class for representing single OpenMP clause.
///
class OMPClause {
/// \brief Starting location of the clause (the clause keyword).
SourceLocation StartLoc;
/// \brief Ending location of the clause.
SourceLocation EndLoc;
/// \brief Kind of the clause.
OpenMPClauseKind Kind;
protected:
OMPClause(OpenMPClauseKind K, SourceLocation StartLoc, SourceLocation EndLoc)
: StartLoc(StartLoc), EndLoc(EndLoc), Kind(K) {}
public:
/// \brief Returns the starting location of the clause.
SourceLocation getLocStart() const { return StartLoc; }
/// \brief Returns the ending location of the clause.
SourceLocation getLocEnd() const { return EndLoc; }
/// \brief Sets the starting location of the clause.
void setLocStart(SourceLocation Loc) { StartLoc = Loc; }
/// \brief Sets the ending location of the clause.
void setLocEnd(SourceLocation Loc) { EndLoc = Loc; }
/// \brief Returns kind of OpenMP clause (private, shared, reduction, etc.).
OpenMPClauseKind getClauseKind() const { return Kind; }
bool isImplicit() const { return StartLoc.isInvalid(); }
typedef StmtIterator child_iterator;
typedef ConstStmtIterator const_child_iterator;
typedef llvm::iterator_range<child_iterator> child_range;
typedef llvm::iterator_range<const_child_iterator> const_child_range;
child_range children();
const_child_range children() const {
auto Children = const_cast<OMPClause *>(this)->children();
return const_child_range(Children.begin(), Children.end());
}
static bool classof(const OMPClause *) { return true; }
};
/// Class that handles pre-initialization statement for some clauses, like
/// 'shedule', 'firstprivate' etc.
class OMPClauseWithPreInit {
friend class OMPClauseReader;
/// Pre-initialization statement for the clause.
Stmt *PreInit;
/// Region that captures the associated stmt.
OpenMPDirectiveKind CaptureRegion;
protected:
/// Set pre-initialization statement for the clause.
void setPreInitStmt(Stmt *S, OpenMPDirectiveKind ThisRegion = OMPD_unknown) {
PreInit = S;
CaptureRegion = ThisRegion;
}
OMPClauseWithPreInit(const OMPClause *This)
: PreInit(nullptr), CaptureRegion(OMPD_unknown) {
assert(get(This) && "get is not tuned for pre-init.");
}
public:
/// Get pre-initialization statement for the clause.
const Stmt *getPreInitStmt() const { return PreInit; }
/// Get pre-initialization statement for the clause.
Stmt *getPreInitStmt() { return PreInit; }
/// Get capture region for the stmt in the clause.
OpenMPDirectiveKind getCaptureRegion() { return CaptureRegion; }
static OMPClauseWithPreInit *get(OMPClause *C);
static const OMPClauseWithPreInit *get(const OMPClause *C);
};
/// Class that handles post-update expression for some clauses, like
/// 'lastprivate', 'reduction' etc.
class OMPClauseWithPostUpdate : public OMPClauseWithPreInit {
friend class OMPClauseReader;
/// Post-update expression for the clause.
Expr *PostUpdate;
protected:
/// Set pre-initialization statement for the clause.
void setPostUpdateExpr(Expr *S) { PostUpdate = S; }
OMPClauseWithPostUpdate(const OMPClause *This)
: OMPClauseWithPreInit(This), PostUpdate(nullptr) {
assert(get(This) && "get is not tuned for post-update.");
}
public:
/// Get post-update expression for the clause.
const Expr *getPostUpdateExpr() const { return PostUpdate; }
/// Get post-update expression for the clause.
Expr *getPostUpdateExpr() { return PostUpdate; }
static OMPClauseWithPostUpdate *get(OMPClause *C);
static const OMPClauseWithPostUpdate *get(const OMPClause *C);
};
/// \brief This represents clauses with the list of variables like 'private',
/// 'firstprivate', 'copyin', 'shared', or 'reduction' clauses in the
/// '#pragma omp ...' directives.
template <class T> class OMPVarListClause : public OMPClause {
friend class OMPClauseReader;
/// \brief Location of '('.
SourceLocation LParenLoc;
/// \brief Number of variables in the list.
unsigned NumVars;
protected:
/// \brief Fetches list of variables associated with this clause.
MutableArrayRef<Expr *> getVarRefs() {
return MutableArrayRef<Expr *>(
static_cast<T *>(this)->template getTrailingObjects<Expr *>(), NumVars);
}
/// \brief Sets the list of variables for this clause.
void setVarRefs(ArrayRef<Expr *> VL) {
assert(VL.size() == NumVars &&
"Number of variables is not the same as the preallocated buffer");
std::copy(VL.begin(), VL.end(),
static_cast<T *>(this)->template getTrailingObjects<Expr *>());
}
/// \brief Build a clause with \a N variables
///
/// \param K Kind of the clause.
/// \param StartLoc Starting location of the clause (the clause keyword).
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param N Number of the variables in the clause.
///
OMPVarListClause(OpenMPClauseKind K, SourceLocation StartLoc,
SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N)
: OMPClause(K, StartLoc, EndLoc), LParenLoc(LParenLoc), NumVars(N) {}
public:
typedef MutableArrayRef<Expr *>::iterator varlist_iterator;
typedef ArrayRef<const Expr *>::iterator varlist_const_iterator;
typedef llvm::iterator_range<varlist_iterator> varlist_range;
typedef llvm::iterator_range<varlist_const_iterator> varlist_const_range;
unsigned varlist_size() const { return NumVars; }
bool varlist_empty() const { return NumVars == 0; }
varlist_range varlists() {
return varlist_range(varlist_begin(), varlist_end());
}
varlist_const_range varlists() const {
return varlist_const_range(varlist_begin(), varlist_end());
}
varlist_iterator varlist_begin() { return getVarRefs().begin(); }
varlist_iterator varlist_end() { return getVarRefs().end(); }
varlist_const_iterator varlist_begin() const { return getVarRefs().begin(); }
varlist_const_iterator varlist_end() const { return getVarRefs().end(); }
/// \brief Sets the location of '('.
void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
/// \brief Returns the location of '('.
SourceLocation getLParenLoc() const { return LParenLoc; }
/// \brief Fetches list of all variables in the clause.
ArrayRef<const Expr *> getVarRefs() const {
return llvm::makeArrayRef(
static_cast<const T *>(this)->template getTrailingObjects<Expr *>(),
NumVars);
}
};
/// \brief This represents 'if' clause in the '#pragma omp ...' directive.
///
/// \code
/// #pragma omp parallel if(parallel:a > 5)
/// \endcode
/// In this example directive '#pragma omp parallel' has simple 'if' clause with
/// condition 'a > 5' and directive name modifier 'parallel'.
///
class OMPIfClause : public OMPClause, public OMPClauseWithPreInit {
friend class OMPClauseReader;
/// \brief Location of '('.
SourceLocation LParenLoc;
/// \brief Condition of the 'if' clause.
Stmt *Condition;
/// \brief Location of ':' (if any).
SourceLocation ColonLoc;
/// \brief Directive name modifier for the clause.
OpenMPDirectiveKind NameModifier;
/// \brief Name modifier location.
SourceLocation NameModifierLoc;
/// \brief Set condition.
///
void setCondition(Expr *Cond) { Condition = Cond; }
/// \brief Set directive name modifier for the clause.
///
void setNameModifier(OpenMPDirectiveKind NM) { NameModifier = NM; }
/// \brief Set location of directive name modifier for the clause.
///
void setNameModifierLoc(SourceLocation Loc) { NameModifierLoc = Loc; }
/// \brief Set location of ':'.
///
void setColonLoc(SourceLocation Loc) { ColonLoc = Loc; }
public:
/// \brief Build 'if' clause with condition \a Cond.
///
/// \param NameModifier [OpenMP 4.1] Directive name modifier of clause.
/// \param Cond Condition of the clause.
/// \param HelperCond Helper condition for the clause.
/// \param CaptureRegion Innermost OpenMP region where expressions in this
/// clause must be captured.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param NameModifierLoc Location of directive name modifier.
/// \param ColonLoc [OpenMP 4.1] Location of ':'.
/// \param EndLoc Ending location of the clause.
///
OMPIfClause(OpenMPDirectiveKind NameModifier, Expr *Cond, Stmt *HelperCond,
OpenMPDirectiveKind CaptureRegion, SourceLocation StartLoc,
SourceLocation LParenLoc, SourceLocation NameModifierLoc,
SourceLocation ColonLoc, SourceLocation EndLoc)
: OMPClause(OMPC_if, StartLoc, EndLoc), OMPClauseWithPreInit(this),
LParenLoc(LParenLoc), Condition(Cond), ColonLoc(ColonLoc),
NameModifier(NameModifier), NameModifierLoc(NameModifierLoc) {
setPreInitStmt(HelperCond, CaptureRegion);
}
/// \brief Build an empty clause.
///
OMPIfClause()
: OMPClause(OMPC_if, SourceLocation(), SourceLocation()),
OMPClauseWithPreInit(this), LParenLoc(), Condition(nullptr), ColonLoc(),
NameModifier(OMPD_unknown), NameModifierLoc() {}
/// \brief Sets the location of '('.
void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
/// \brief Returns the location of '('.
SourceLocation getLParenLoc() const { return LParenLoc; }
/// \brief Return the location of ':'.
SourceLocation getColonLoc() const { return ColonLoc; }
/// \brief Returns condition.
Expr *getCondition() const { return cast_or_null<Expr>(Condition); }
/// \brief Return directive name modifier associated with the clause.
OpenMPDirectiveKind getNameModifier() const { return NameModifier; }
/// \brief Return the location of directive name modifier.
SourceLocation getNameModifierLoc() const { return NameModifierLoc; }
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_if;
}
child_range children() { return child_range(&Condition, &Condition + 1); }
};
/// \brief This represents 'final' clause in the '#pragma omp ...' directive.
///
/// \code
/// #pragma omp task final(a > 5)
/// \endcode
/// In this example directive '#pragma omp task' has simple 'final'
/// clause with condition 'a > 5'.
///
class OMPFinalClause : public OMPClause {
friend class OMPClauseReader;
/// \brief Location of '('.
SourceLocation LParenLoc;
/// \brief Condition of the 'if' clause.
Stmt *Condition;
/// \brief Set condition.
///
void setCondition(Expr *Cond) { Condition = Cond; }
public:
/// \brief Build 'final' clause with condition \a Cond.
///
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param Cond Condition of the clause.
/// \param EndLoc Ending location of the clause.
///
OMPFinalClause(Expr *Cond, SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc)
: OMPClause(OMPC_final, StartLoc, EndLoc), LParenLoc(LParenLoc),
Condition(Cond) {}
/// \brief Build an empty clause.
///
OMPFinalClause()
: OMPClause(OMPC_final, SourceLocation(), SourceLocation()),
LParenLoc(SourceLocation()), Condition(nullptr) {}
/// \brief Sets the location of '('.
void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
/// \brief Returns the location of '('.
SourceLocation getLParenLoc() const { return LParenLoc; }
/// \brief Returns condition.
Expr *getCondition() const { return cast_or_null<Expr>(Condition); }
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_final;
}
child_range children() { return child_range(&Condition, &Condition + 1); }
};
/// \brief This represents 'num_threads' clause in the '#pragma omp ...'
/// directive.
///
/// \code
/// #pragma omp parallel num_threads(6)
/// \endcode
/// In this example directive '#pragma omp parallel' has simple 'num_threads'
/// clause with number of threads '6'.
///
class OMPNumThreadsClause : public OMPClause, public OMPClauseWithPreInit {
friend class OMPClauseReader;
/// \brief Location of '('.
SourceLocation LParenLoc;
/// \brief Condition of the 'num_threads' clause.
Stmt *NumThreads;
/// \brief Set condition.
///
void setNumThreads(Expr *NThreads) { NumThreads = NThreads; }
public:
/// \brief Build 'num_threads' clause with condition \a NumThreads.
///
/// \param NumThreads Number of threads for the construct.
/// \param HelperNumThreads Helper Number of threads for the construct.
/// \param CaptureRegion Innermost OpenMP region where expressions in this
/// clause must be captured.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
///
OMPNumThreadsClause(Expr *NumThreads, Stmt *HelperNumThreads,
OpenMPDirectiveKind CaptureRegion,
SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc)
: OMPClause(OMPC_num_threads, StartLoc, EndLoc),
OMPClauseWithPreInit(this), LParenLoc(LParenLoc),
NumThreads(NumThreads) {
setPreInitStmt(HelperNumThreads, CaptureRegion);
}
/// \brief Build an empty clause.
///
OMPNumThreadsClause()
: OMPClause(OMPC_num_threads, SourceLocation(), SourceLocation()),
OMPClauseWithPreInit(this), LParenLoc(SourceLocation()),
NumThreads(nullptr) {}
/// \brief Sets the location of '('.
void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
/// \brief Returns the location of '('.
SourceLocation getLParenLoc() const { return LParenLoc; }
/// \brief Returns number of threads.
Expr *getNumThreads() const { return cast_or_null<Expr>(NumThreads); }
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_num_threads;
}
child_range children() { return child_range(&NumThreads, &NumThreads + 1); }
};
/// \brief This represents 'safelen' clause in the '#pragma omp ...'
/// directive.
///
/// \code
/// #pragma omp simd safelen(4)
/// \endcode
/// In this example directive '#pragma omp simd' has clause 'safelen'
/// with single expression '4'.
/// If the safelen clause is used then no two iterations executed
/// concurrently with SIMD instructions can have a greater distance
/// in the logical iteration space than its value. The parameter of
/// the safelen clause must be a constant positive integer expression.
///
class OMPSafelenClause : public OMPClause {
friend class OMPClauseReader;
/// \brief Location of '('.
SourceLocation LParenLoc;
/// \brief Safe iteration space distance.
Stmt *Safelen;
/// \brief Set safelen.
void setSafelen(Expr *Len) { Safelen = Len; }
public:
/// \brief Build 'safelen' clause.
///
/// \param Len Expression associated with this clause.
/// \param StartLoc Starting location of the clause.
/// \param EndLoc Ending location of the clause.
///
OMPSafelenClause(Expr *Len, SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc)
: OMPClause(OMPC_safelen, StartLoc, EndLoc), LParenLoc(LParenLoc),
Safelen(Len) {}
/// \brief Build an empty clause.
///
explicit OMPSafelenClause()
: OMPClause(OMPC_safelen, SourceLocation(), SourceLocation()),
LParenLoc(SourceLocation()), Safelen(nullptr) {}
/// \brief Sets the location of '('.
void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
/// \brief Returns the location of '('.
SourceLocation getLParenLoc() const { return LParenLoc; }
/// \brief Return safe iteration space distance.
Expr *getSafelen() const { return cast_or_null<Expr>(Safelen); }
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_safelen;
}
child_range children() { return child_range(&Safelen, &Safelen + 1); }
};
/// \brief This represents 'simdlen' clause in the '#pragma omp ...'
/// directive.
///
/// \code
/// #pragma omp simd simdlen(4)
/// \endcode
/// In this example directive '#pragma omp simd' has clause 'simdlen'
/// with single expression '4'.
/// If the 'simdlen' clause is used then it specifies the preferred number of
/// iterations to be executed concurrently. The parameter of the 'simdlen'
/// clause must be a constant positive integer expression.
///
class OMPSimdlenClause : public OMPClause {
friend class OMPClauseReader;
/// \brief Location of '('.
SourceLocation LParenLoc;
/// \brief Safe iteration space distance.
Stmt *Simdlen;
/// \brief Set simdlen.
void setSimdlen(Expr *Len) { Simdlen = Len; }
public:
/// \brief Build 'simdlen' clause.
///
/// \param Len Expression associated with this clause.
/// \param StartLoc Starting location of the clause.
/// \param EndLoc Ending location of the clause.
///
OMPSimdlenClause(Expr *Len, SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc)
: OMPClause(OMPC_simdlen, StartLoc, EndLoc), LParenLoc(LParenLoc),
Simdlen(Len) {}
/// \brief Build an empty clause.
///
explicit OMPSimdlenClause()
: OMPClause(OMPC_simdlen, SourceLocation(), SourceLocation()),
LParenLoc(SourceLocation()), Simdlen(nullptr) {}
/// \brief Sets the location of '('.
void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
/// \brief Returns the location of '('.
SourceLocation getLParenLoc() const { return LParenLoc; }
/// \brief Return safe iteration space distance.
Expr *getSimdlen() const { return cast_or_null<Expr>(Simdlen); }
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_simdlen;
}
child_range children() { return child_range(&Simdlen, &Simdlen + 1); }
};
/// \brief This represents 'collapse' clause in the '#pragma omp ...'
/// directive.
///
/// \code
/// #pragma omp simd collapse(3)
/// \endcode
/// In this example directive '#pragma omp simd' has clause 'collapse'
/// with single expression '3'.
/// The parameter must be a constant positive integer expression, it specifies
/// the number of nested loops that should be collapsed into a single iteration
/// space.
///
class OMPCollapseClause : public OMPClause {
friend class OMPClauseReader;
/// \brief Location of '('.
SourceLocation LParenLoc;
/// \brief Number of for-loops.
Stmt *NumForLoops;
/// \brief Set the number of associated for-loops.
void setNumForLoops(Expr *Num) { NumForLoops = Num; }
public:
/// \brief Build 'collapse' clause.
///
/// \param Num Expression associated with this clause.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
///
OMPCollapseClause(Expr *Num, SourceLocation StartLoc,
SourceLocation LParenLoc, SourceLocation EndLoc)
: OMPClause(OMPC_collapse, StartLoc, EndLoc), LParenLoc(LParenLoc),
NumForLoops(Num) {}
/// \brief Build an empty clause.
///
explicit OMPCollapseClause()
: OMPClause(OMPC_collapse, SourceLocation(), SourceLocation()),
LParenLoc(SourceLocation()), NumForLoops(nullptr) {}
/// \brief Sets the location of '('.
void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
/// \brief Returns the location of '('.
SourceLocation getLParenLoc() const { return LParenLoc; }
/// \brief Return the number of associated for-loops.
Expr *getNumForLoops() const { return cast_or_null<Expr>(NumForLoops); }
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_collapse;
}
child_range children() { return child_range(&NumForLoops, &NumForLoops + 1); }
};
/// \brief This represents 'default' clause in the '#pragma omp ...' directive.
///
/// \code
/// #pragma omp parallel default(shared)
/// \endcode
/// In this example directive '#pragma omp parallel' has simple 'default'
/// clause with kind 'shared'.
///
class OMPDefaultClause : public OMPClause {
friend class OMPClauseReader;
/// \brief Location of '('.
SourceLocation LParenLoc;
/// \brief A kind of the 'default' clause.
OpenMPDefaultClauseKind Kind;
/// \brief Start location of the kind in source code.
SourceLocation KindKwLoc;
/// \brief Set kind of the clauses.
///
/// \param K Argument of clause.
///
void setDefaultKind(OpenMPDefaultClauseKind K) { Kind = K; }
/// \brief Set argument location.
///
/// \param KLoc Argument location.
///
void setDefaultKindKwLoc(SourceLocation KLoc) { KindKwLoc = KLoc; }
public:
/// \brief Build 'default' clause with argument \a A ('none' or 'shared').
///
/// \param A Argument of the clause ('none' or 'shared').
/// \param ALoc Starting location of the argument.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
///
OMPDefaultClause(OpenMPDefaultClauseKind A, SourceLocation ALoc,
SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc)
: OMPClause(OMPC_default, StartLoc, EndLoc), LParenLoc(LParenLoc),
Kind(A), KindKwLoc(ALoc) {}
/// \brief Build an empty clause.
///
OMPDefaultClause()
: OMPClause(OMPC_default, SourceLocation(), SourceLocation()),
LParenLoc(SourceLocation()), Kind(OMPC_DEFAULT_unknown),
KindKwLoc(SourceLocation()) {}
/// \brief Sets the location of '('.
void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
/// \brief Returns the location of '('.
SourceLocation getLParenLoc() const { return LParenLoc; }
/// \brief Returns kind of the clause.
OpenMPDefaultClauseKind getDefaultKind() const { return Kind; }
/// \brief Returns location of clause kind.
SourceLocation getDefaultKindKwLoc() const { return KindKwLoc; }
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_default;
}
child_range children() {
return child_range(child_iterator(), child_iterator());
}
};
/// \brief This represents 'proc_bind' clause in the '#pragma omp ...'
/// directive.
///
/// \code
/// #pragma omp parallel proc_bind(master)
/// \endcode
/// In this example directive '#pragma omp parallel' has simple 'proc_bind'
/// clause with kind 'master'.
///
class OMPProcBindClause : public OMPClause {
friend class OMPClauseReader;
/// \brief Location of '('.
SourceLocation LParenLoc;
/// \brief A kind of the 'proc_bind' clause.
OpenMPProcBindClauseKind Kind;
/// \brief Start location of the kind in source code.
SourceLocation KindKwLoc;
/// \brief Set kind of the clause.
///
/// \param K Kind of clause.
///
void setProcBindKind(OpenMPProcBindClauseKind K) { Kind = K; }
/// \brief Set clause kind location.
///
/// \param KLoc Kind location.
///
void setProcBindKindKwLoc(SourceLocation KLoc) { KindKwLoc = KLoc; }
public:
/// \brief Build 'proc_bind' clause with argument \a A ('master', 'close' or
/// 'spread').
///
/// \param A Argument of the clause ('master', 'close' or 'spread').
/// \param ALoc Starting location of the argument.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
///
OMPProcBindClause(OpenMPProcBindClauseKind A, SourceLocation ALoc,
SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc)
: OMPClause(OMPC_proc_bind, StartLoc, EndLoc), LParenLoc(LParenLoc),
Kind(A), KindKwLoc(ALoc) {}
/// \brief Build an empty clause.
///
OMPProcBindClause()
: OMPClause(OMPC_proc_bind, SourceLocation(), SourceLocation()),
LParenLoc(SourceLocation()), Kind(OMPC_PROC_BIND_unknown),
KindKwLoc(SourceLocation()) {}
/// \brief Sets the location of '('.
void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
/// \brief Returns the location of '('.
SourceLocation getLParenLoc() const { return LParenLoc; }
/// \brief Returns kind of the clause.
OpenMPProcBindClauseKind getProcBindKind() const { return Kind; }
/// \brief Returns location of clause kind.
SourceLocation getProcBindKindKwLoc() const { return KindKwLoc; }
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_proc_bind;
}
child_range children() {
return child_range(child_iterator(), child_iterator());
}
};
/// \brief This represents 'schedule' clause in the '#pragma omp ...' directive.
///
/// \code
/// #pragma omp for schedule(static, 3)
/// \endcode
/// In this example directive '#pragma omp for' has 'schedule' clause with
/// arguments 'static' and '3'.
///
class OMPScheduleClause : public OMPClause, public OMPClauseWithPreInit {
friend class OMPClauseReader;
/// \brief Location of '('.
SourceLocation LParenLoc;
/// \brief A kind of the 'schedule' clause.
OpenMPScheduleClauseKind Kind;
/// \brief Modifiers for 'schedule' clause.
enum {FIRST, SECOND, NUM_MODIFIERS};
OpenMPScheduleClauseModifier Modifiers[NUM_MODIFIERS];
/// \brief Locations of modifiers.
SourceLocation ModifiersLoc[NUM_MODIFIERS];
/// \brief Start location of the schedule ind in source code.
SourceLocation KindLoc;
/// \brief Location of ',' (if any).
SourceLocation CommaLoc;
/// \brief Chunk size.
Expr *ChunkSize;
/// \brief Set schedule kind.
///
/// \param K Schedule kind.
///
void setScheduleKind(OpenMPScheduleClauseKind K) { Kind = K; }
/// \brief Set the first schedule modifier.
///
/// \param M Schedule modifier.
///
void setFirstScheduleModifier(OpenMPScheduleClauseModifier M) {
Modifiers[FIRST] = M;
}
/// \brief Set the second schedule modifier.
///
/// \param M Schedule modifier.
///
void setSecondScheduleModifier(OpenMPScheduleClauseModifier M) {
Modifiers[SECOND] = M;
}
/// \brief Set location of the first schedule modifier.
///
void setFirstScheduleModifierLoc(SourceLocation Loc) {
ModifiersLoc[FIRST] = Loc;
}
/// \brief Set location of the second schedule modifier.
///
void setSecondScheduleModifierLoc(SourceLocation Loc) {
ModifiersLoc[SECOND] = Loc;
}
/// \brief Set schedule modifier location.
///
/// \param M Schedule modifier location.
///
void setScheduleModifer(OpenMPScheduleClauseModifier M) {
if (Modifiers[FIRST] == OMPC_SCHEDULE_MODIFIER_unknown)
Modifiers[FIRST] = M;
else {
assert(Modifiers[SECOND] == OMPC_SCHEDULE_MODIFIER_unknown);
Modifiers[SECOND] = M;
}
}
/// \brief Sets the location of '('.
///
/// \param Loc Location of '('.
///
void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
/// \brief Set schedule kind start location.
///
/// \param KLoc Schedule kind location.
///
void setScheduleKindLoc(SourceLocation KLoc) { KindLoc = KLoc; }
/// \brief Set location of ','.
///
/// \param Loc Location of ','.
///
void setCommaLoc(SourceLocation Loc) { CommaLoc = Loc; }
/// \brief Set chunk size.
///
/// \param E Chunk size.
///
void setChunkSize(Expr *E) { ChunkSize = E; }
public:
/// \brief Build 'schedule' clause with schedule kind \a Kind and chunk size
/// expression \a ChunkSize.
///
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param KLoc Starting location of the argument.
/// \param CommaLoc Location of ','.
/// \param EndLoc Ending location of the clause.
/// \param Kind Schedule kind.
/// \param ChunkSize Chunk size.
/// \param HelperChunkSize Helper chunk size for combined directives.
/// \param M1 The first modifier applied to 'schedule' clause.
/// \param M1Loc Location of the first modifier
/// \param M2 The second modifier applied to 'schedule' clause.
/// \param M2Loc Location of the second modifier
///
OMPScheduleClause(SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation KLoc, SourceLocation CommaLoc,
SourceLocation EndLoc, OpenMPScheduleClauseKind Kind,
Expr *ChunkSize, Stmt *HelperChunkSize,
OpenMPScheduleClauseModifier M1, SourceLocation M1Loc,
OpenMPScheduleClauseModifier M2, SourceLocation M2Loc)
: OMPClause(OMPC_schedule, StartLoc, EndLoc), OMPClauseWithPreInit(this),
LParenLoc(LParenLoc), Kind(Kind), KindLoc(KLoc), CommaLoc(CommaLoc),
ChunkSize(ChunkSize) {
setPreInitStmt(HelperChunkSize);
Modifiers[FIRST] = M1;
Modifiers[SECOND] = M2;
ModifiersLoc[FIRST] = M1Loc;
ModifiersLoc[SECOND] = M2Loc;
}
/// \brief Build an empty clause.
///
explicit OMPScheduleClause()
: OMPClause(OMPC_schedule, SourceLocation(), SourceLocation()),
OMPClauseWithPreInit(this), Kind(OMPC_SCHEDULE_unknown),
ChunkSize(nullptr) {
Modifiers[FIRST] = OMPC_SCHEDULE_MODIFIER_unknown;
Modifiers[SECOND] = OMPC_SCHEDULE_MODIFIER_unknown;
}
/// \brief Get kind of the clause.
///
OpenMPScheduleClauseKind getScheduleKind() const { return Kind; }
/// \brief Get the first modifier of the clause.
///
OpenMPScheduleClauseModifier getFirstScheduleModifier() const {
return Modifiers[FIRST];
}
/// \brief Get the second modifier of the clause.
///
OpenMPScheduleClauseModifier getSecondScheduleModifier() const {
return Modifiers[SECOND];
}
/// \brief Get location of '('.
///
SourceLocation getLParenLoc() { return LParenLoc; }
/// \brief Get kind location.
///
SourceLocation getScheduleKindLoc() { return KindLoc; }
/// \brief Get the first modifier location.
///
SourceLocation getFirstScheduleModifierLoc() const {
return ModifiersLoc[FIRST];
}
/// \brief Get the second modifier location.
///
SourceLocation getSecondScheduleModifierLoc() const {
return ModifiersLoc[SECOND];
}
/// \brief Get location of ','.
///
SourceLocation getCommaLoc() { return CommaLoc; }
/// \brief Get chunk size.
///
Expr *getChunkSize() { return ChunkSize; }
/// \brief Get chunk size.
///
const Expr *getChunkSize() const { return ChunkSize; }
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_schedule;
}
child_range children() {
return child_range(reinterpret_cast<Stmt **>(&ChunkSize),
reinterpret_cast<Stmt **>(&ChunkSize) + 1);
}
};
/// \brief This represents 'ordered' clause in the '#pragma omp ...' directive.
///
/// \code
/// #pragma omp for ordered (2)
/// \endcode
/// In this example directive '#pragma omp for' has 'ordered' clause with
/// parameter 2.
///
class OMPOrderedClause : public OMPClause {
friend class OMPClauseReader;
/// \brief Location of '('.
SourceLocation LParenLoc;
/// \brief Number of for-loops.
Stmt *NumForLoops;
/// \brief Set the number of associated for-loops.
void setNumForLoops(Expr *Num) { NumForLoops = Num; }
public:
/// \brief Build 'ordered' clause.
///
/// \param Num Expression, possibly associated with this clause.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
///
OMPOrderedClause(Expr *Num, SourceLocation StartLoc,
SourceLocation LParenLoc, SourceLocation EndLoc)
: OMPClause(OMPC_ordered, StartLoc, EndLoc), LParenLoc(LParenLoc),
NumForLoops(Num) {}
/// \brief Build an empty clause.
///
explicit OMPOrderedClause()
: OMPClause(OMPC_ordered, SourceLocation(), SourceLocation()),
LParenLoc(SourceLocation()), NumForLoops(nullptr) {}
/// \brief Sets the location of '('.
void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
/// \brief Returns the location of '('.
SourceLocation getLParenLoc() const { return LParenLoc; }
/// \brief Return the number of associated for-loops.
Expr *getNumForLoops() const { return cast_or_null<Expr>(NumForLoops); }
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_ordered;
}
child_range children() { return child_range(&NumForLoops, &NumForLoops + 1); }
};
/// \brief This represents 'nowait' clause in the '#pragma omp ...' directive.
///
/// \code
/// #pragma omp for nowait
/// \endcode
/// In this example directive '#pragma omp for' has 'nowait' clause.
///
class OMPNowaitClause : public OMPClause {
public:
/// \brief Build 'nowait' clause.
///
/// \param StartLoc Starting location of the clause.
/// \param EndLoc Ending location of the clause.
///
OMPNowaitClause(SourceLocation StartLoc, SourceLocation EndLoc)
: OMPClause(OMPC_nowait, StartLoc, EndLoc) {}
/// \brief Build an empty clause.
///
OMPNowaitClause()
: OMPClause(OMPC_nowait, SourceLocation(), SourceLocation()) {}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_nowait;
}
child_range children() {
return child_range(child_iterator(), child_iterator());
}
};
/// \brief This represents 'untied' clause in the '#pragma omp ...' directive.
///
/// \code
/// #pragma omp task untied
/// \endcode
/// In this example directive '#pragma omp task' has 'untied' clause.
///
class OMPUntiedClause : public OMPClause {
public:
/// \brief Build 'untied' clause.
///
/// \param StartLoc Starting location of the clause.
/// \param EndLoc Ending location of the clause.
///
OMPUntiedClause(SourceLocation StartLoc, SourceLocation EndLoc)
: OMPClause(OMPC_untied, StartLoc, EndLoc) {}
/// \brief Build an empty clause.
///
OMPUntiedClause()
: OMPClause(OMPC_untied, SourceLocation(), SourceLocation()) {}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_untied;
}
child_range children() {
return child_range(child_iterator(), child_iterator());
}
};
/// \brief This represents 'mergeable' clause in the '#pragma omp ...'
/// directive.
///
/// \code
/// #pragma omp task mergeable
/// \endcode
/// In this example directive '#pragma omp task' has 'mergeable' clause.
///
class OMPMergeableClause : public OMPClause {
public:
/// \brief Build 'mergeable' clause.
///
/// \param StartLoc Starting location of the clause.
/// \param EndLoc Ending location of the clause.
///
OMPMergeableClause(SourceLocation StartLoc, SourceLocation EndLoc)
: OMPClause(OMPC_mergeable, StartLoc, EndLoc) {}
/// \brief Build an empty clause.
///
OMPMergeableClause()
: OMPClause(OMPC_mergeable, SourceLocation(), SourceLocation()) {}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_mergeable;
}
child_range children() {
return child_range(child_iterator(), child_iterator());
}
};
/// \brief This represents 'read' clause in the '#pragma omp atomic' directive.
///
/// \code
/// #pragma omp atomic read
/// \endcode
/// In this example directive '#pragma omp atomic' has 'read' clause.
///
class OMPReadClause : public OMPClause {
public:
/// \brief Build 'read' clause.
///
/// \param StartLoc Starting location of the clause.
/// \param EndLoc Ending location of the clause.
///
OMPReadClause(SourceLocation StartLoc, SourceLocation EndLoc)
: OMPClause(OMPC_read, StartLoc, EndLoc) {}
/// \brief Build an empty clause.
///
OMPReadClause() : OMPClause(OMPC_read, SourceLocation(), SourceLocation()) {}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_read;
}
child_range children() {
return child_range(child_iterator(), child_iterator());
}
};
/// \brief This represents 'write' clause in the '#pragma omp atomic' directive.
///
/// \code
/// #pragma omp atomic write
/// \endcode
/// In this example directive '#pragma omp atomic' has 'write' clause.
///
class OMPWriteClause : public OMPClause {
public:
/// \brief Build 'write' clause.
///
/// \param StartLoc Starting location of the clause.
/// \param EndLoc Ending location of the clause.
///
OMPWriteClause(SourceLocation StartLoc, SourceLocation EndLoc)
: OMPClause(OMPC_write, StartLoc, EndLoc) {}
/// \brief Build an empty clause.
///
OMPWriteClause()
: OMPClause(OMPC_write, SourceLocation(), SourceLocation()) {}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_write;
}
child_range children() {
return child_range(child_iterator(), child_iterator());
}
};
/// \brief This represents 'update' clause in the '#pragma omp atomic'
/// directive.
///
/// \code
/// #pragma omp atomic update
/// \endcode
/// In this example directive '#pragma omp atomic' has 'update' clause.
///
class OMPUpdateClause : public OMPClause {
public:
/// \brief Build 'update' clause.
///
/// \param StartLoc Starting location of the clause.
/// \param EndLoc Ending location of the clause.
///
OMPUpdateClause(SourceLocation StartLoc, SourceLocation EndLoc)
: OMPClause(OMPC_update, StartLoc, EndLoc) {}
/// \brief Build an empty clause.
///
OMPUpdateClause()
: OMPClause(OMPC_update, SourceLocation(), SourceLocation()) {}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_update;
}
child_range children() {
return child_range(child_iterator(), child_iterator());
}
};
/// \brief This represents 'capture' clause in the '#pragma omp atomic'
/// directive.
///
/// \code
/// #pragma omp atomic capture
/// \endcode
/// In this example directive '#pragma omp atomic' has 'capture' clause.
///
class OMPCaptureClause : public OMPClause {
public:
/// \brief Build 'capture' clause.
///
/// \param StartLoc Starting location of the clause.
/// \param EndLoc Ending location of the clause.
///
OMPCaptureClause(SourceLocation StartLoc, SourceLocation EndLoc)
: OMPClause(OMPC_capture, StartLoc, EndLoc) {}
/// \brief Build an empty clause.
///
OMPCaptureClause()
: OMPClause(OMPC_capture, SourceLocation(), SourceLocation()) {}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_capture;
}
child_range children() {
return child_range(child_iterator(), child_iterator());
}
};
/// \brief This represents 'seq_cst' clause in the '#pragma omp atomic'
/// directive.
///
/// \code
/// #pragma omp atomic seq_cst
/// \endcode
/// In this example directive '#pragma omp atomic' has 'seq_cst' clause.
///
class OMPSeqCstClause : public OMPClause {
public:
/// \brief Build 'seq_cst' clause.
///
/// \param StartLoc Starting location of the clause.
/// \param EndLoc Ending location of the clause.
///
OMPSeqCstClause(SourceLocation StartLoc, SourceLocation EndLoc)
: OMPClause(OMPC_seq_cst, StartLoc, EndLoc) {}
/// \brief Build an empty clause.
///
OMPSeqCstClause()
: OMPClause(OMPC_seq_cst, SourceLocation(), SourceLocation()) {}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_seq_cst;
}
child_range children() {
return child_range(child_iterator(), child_iterator());
}
};
/// \brief This represents clause 'private' in the '#pragma omp ...' directives.
///
/// \code
/// #pragma omp parallel private(a,b)
/// \endcode
/// In this example directive '#pragma omp parallel' has clause 'private'
/// with the variables 'a' and 'b'.
///
class OMPPrivateClause final
: public OMPVarListClause<OMPPrivateClause>,
private llvm::TrailingObjects<OMPPrivateClause, Expr *> {
friend TrailingObjects;
friend OMPVarListClause;
friend class OMPClauseReader;
/// \brief Build clause with number of variables \a N.
///
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param N Number of the variables in the clause.
///
OMPPrivateClause(SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc, unsigned N)
: OMPVarListClause<OMPPrivateClause>(OMPC_private, StartLoc, LParenLoc,
EndLoc, N) {}
/// \brief Build an empty clause.
///
/// \param N Number of variables.
///
explicit OMPPrivateClause(unsigned N)
: OMPVarListClause<OMPPrivateClause>(OMPC_private, SourceLocation(),
SourceLocation(), SourceLocation(),
N) {}
/// \brief Sets the list of references to private copies with initializers for
/// new private variables.
/// \param VL List of references.
void setPrivateCopies(ArrayRef<Expr *> VL);
/// \brief Gets the list of references to private copies with initializers for
/// new private variables.
MutableArrayRef<Expr *> getPrivateCopies() {
return MutableArrayRef<Expr *>(varlist_end(), varlist_size());
}
ArrayRef<const Expr *> getPrivateCopies() const {
return llvm::makeArrayRef(varlist_end(), varlist_size());
}
public:
/// \brief Creates clause with a list of variables \a VL.
///
/// \param C AST context.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param VL List of references to the variables.
/// \param PrivateVL List of references to private copies with initializers.
///
static OMPPrivateClause *Create(const ASTContext &C, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc, ArrayRef<Expr *> VL,
ArrayRef<Expr *> PrivateVL);
/// \brief Creates an empty clause with the place for \a N variables.
///
/// \param C AST context.
/// \param N The number of variables.
///
static OMPPrivateClause *CreateEmpty(const ASTContext &C, unsigned N);
typedef MutableArrayRef<Expr *>::iterator private_copies_iterator;
typedef ArrayRef<const Expr *>::iterator private_copies_const_iterator;
typedef llvm::iterator_range<private_copies_iterator> private_copies_range;
typedef llvm::iterator_range<private_copies_const_iterator>
private_copies_const_range;
private_copies_range private_copies() {
return private_copies_range(getPrivateCopies().begin(),
getPrivateCopies().end());
}
private_copies_const_range private_copies() const {
return private_copies_const_range(getPrivateCopies().begin(),
getPrivateCopies().end());
}
child_range children() {
return child_range(reinterpret_cast<Stmt **>(varlist_begin()),
reinterpret_cast<Stmt **>(varlist_end()));
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_private;
}
};
/// \brief This represents clause 'firstprivate' in the '#pragma omp ...'
/// directives.
///
/// \code
/// #pragma omp parallel firstprivate(a,b)
/// \endcode
/// In this example directive '#pragma omp parallel' has clause 'firstprivate'
/// with the variables 'a' and 'b'.
///
class OMPFirstprivateClause final
: public OMPVarListClause<OMPFirstprivateClause>,
public OMPClauseWithPreInit,
private llvm::TrailingObjects<OMPFirstprivateClause, Expr *> {
friend TrailingObjects;
friend OMPVarListClause;
friend class OMPClauseReader;
/// \brief Build clause with number of variables \a N.
///
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param N Number of the variables in the clause.
///
OMPFirstprivateClause(SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc, unsigned N)
: OMPVarListClause<OMPFirstprivateClause>(OMPC_firstprivate, StartLoc,
LParenLoc, EndLoc, N),
OMPClauseWithPreInit(this) {}
/// \brief Build an empty clause.
///
/// \param N Number of variables.
///
explicit OMPFirstprivateClause(unsigned N)
: OMPVarListClause<OMPFirstprivateClause>(
OMPC_firstprivate, SourceLocation(), SourceLocation(),
SourceLocation(), N),
OMPClauseWithPreInit(this) {}
/// \brief Sets the list of references to private copies with initializers for
/// new private variables.
/// \param VL List of references.
void setPrivateCopies(ArrayRef<Expr *> VL);
/// \brief Gets the list of references to private copies with initializers for
/// new private variables.
MutableArrayRef<Expr *> getPrivateCopies() {
return MutableArrayRef<Expr *>(varlist_end(), varlist_size());
}
ArrayRef<const Expr *> getPrivateCopies() const {
return llvm::makeArrayRef(varlist_end(), varlist_size());
}
/// \brief Sets the list of references to initializer variables for new
/// private variables.
/// \param VL List of references.
void setInits(ArrayRef<Expr *> VL);
/// \brief Gets the list of references to initializer variables for new
/// private variables.
MutableArrayRef<Expr *> getInits() {
return MutableArrayRef<Expr *>(getPrivateCopies().end(), varlist_size());
}
ArrayRef<const Expr *> getInits() const {
return llvm::makeArrayRef(getPrivateCopies().end(), varlist_size());
}
public:
/// \brief Creates clause with a list of variables \a VL.
///
/// \param C AST context.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param VL List of references to the original variables.
/// \param PrivateVL List of references to private copies with initializers.
/// \param InitVL List of references to auto generated variables used for
/// initialization of a single array element. Used if firstprivate variable is
/// of array type.
/// \param PreInit Statement that must be executed before entering the OpenMP
/// region with this clause.
///
static OMPFirstprivateClause *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc, ArrayRef<Expr *> VL, ArrayRef<Expr *> PrivateVL,
ArrayRef<Expr *> InitVL, Stmt *PreInit);
/// \brief Creates an empty clause with the place for \a N variables.
///
/// \param C AST context.
/// \param N The number of variables.
///
static OMPFirstprivateClause *CreateEmpty(const ASTContext &C, unsigned N);
typedef MutableArrayRef<Expr *>::iterator private_copies_iterator;
typedef ArrayRef<const Expr *>::iterator private_copies_const_iterator;
typedef llvm::iterator_range<private_copies_iterator> private_copies_range;
typedef llvm::iterator_range<private_copies_const_iterator>
private_copies_const_range;
private_copies_range private_copies() {
return private_copies_range(getPrivateCopies().begin(),
getPrivateCopies().end());
}
private_copies_const_range private_copies() const {
return private_copies_const_range(getPrivateCopies().begin(),
getPrivateCopies().end());
}
typedef MutableArrayRef<Expr *>::iterator inits_iterator;
typedef ArrayRef<const Expr *>::iterator inits_const_iterator;
typedef llvm::iterator_range<inits_iterator> inits_range;
typedef llvm::iterator_range<inits_const_iterator> inits_const_range;
inits_range inits() {
return inits_range(getInits().begin(), getInits().end());
}
inits_const_range inits() const {
return inits_const_range(getInits().begin(), getInits().end());
}
child_range children() {
return child_range(reinterpret_cast<Stmt **>(varlist_begin()),
reinterpret_cast<Stmt **>(varlist_end()));
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_firstprivate;
}
};
/// \brief This represents clause 'lastprivate' in the '#pragma omp ...'
/// directives.
///
/// \code
/// #pragma omp simd lastprivate(a,b)
/// \endcode
/// In this example directive '#pragma omp simd' has clause 'lastprivate'
/// with the variables 'a' and 'b'.
class OMPLastprivateClause final
: public OMPVarListClause<OMPLastprivateClause>,
public OMPClauseWithPostUpdate,
private llvm::TrailingObjects<OMPLastprivateClause, Expr *> {
// There are 4 additional tail-allocated arrays at the end of the class:
// 1. Contains list of pseudo variables with the default initialization for
// each non-firstprivate variables. Used in codegen for initialization of
// lastprivate copies.
// 2. List of helper expressions for proper generation of assignment operation
// required for lastprivate clause. This list represents private variables
// (for arrays, single array element).
// 3. List of helper expressions for proper generation of assignment operation
// required for lastprivate clause. This list represents original variables
// (for arrays, single array element).
// 4. List of helper expressions that represents assignment operation:
// \code
// DstExprs = SrcExprs;
// \endcode
// Required for proper codegen of final assignment performed by the
// lastprivate clause.
//
friend TrailingObjects;
friend OMPVarListClause;
friend class OMPClauseReader;
/// \brief Build clause with number of variables \a N.
///
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param N Number of the variables in the clause.
///
OMPLastprivateClause(SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc, unsigned N)
: OMPVarListClause<OMPLastprivateClause>(OMPC_lastprivate, StartLoc,
LParenLoc, EndLoc, N),
OMPClauseWithPostUpdate(this) {}
/// \brief Build an empty clause.
///
/// \param N Number of variables.
///
explicit OMPLastprivateClause(unsigned N)
: OMPVarListClause<OMPLastprivateClause>(
OMPC_lastprivate, SourceLocation(), SourceLocation(),
SourceLocation(), N),
OMPClauseWithPostUpdate(this) {}
/// \brief Get the list of helper expressions for initialization of private
/// copies for lastprivate variables.
MutableArrayRef<Expr *> getPrivateCopies() {
return MutableArrayRef<Expr *>(varlist_end(), varlist_size());
}
ArrayRef<const Expr *> getPrivateCopies() const {
return llvm::makeArrayRef(varlist_end(), varlist_size());
}
/// \brief Set list of helper expressions, required for proper codegen of the
/// clause. These expressions represent private variables (for arrays, single
/// array element) in the final assignment statement performed by the
/// lastprivate clause.
void setSourceExprs(ArrayRef<Expr *> SrcExprs);
/// \brief Get the list of helper source expressions.
MutableArrayRef<Expr *> getSourceExprs() {
return MutableArrayRef<Expr *>(getPrivateCopies().end(), varlist_size());
}
ArrayRef<const Expr *> getSourceExprs() const {
return llvm::makeArrayRef(getPrivateCopies().end(), varlist_size());
}
/// \brief Set list of helper expressions, required for proper codegen of the
/// clause. These expressions represent original variables (for arrays, single
/// array element) in the final assignment statement performed by the
/// lastprivate clause.
void setDestinationExprs(ArrayRef<Expr *> DstExprs);
/// \brief Get the list of helper destination expressions.
MutableArrayRef<Expr *> getDestinationExprs() {
return MutableArrayRef<Expr *>(getSourceExprs().end(), varlist_size());
}
ArrayRef<const Expr *> getDestinationExprs() const {
return llvm::makeArrayRef(getSourceExprs().end(), varlist_size());
}
/// \brief Set list of helper assignment expressions, required for proper
/// codegen of the clause. These expressions are assignment expressions that
/// assign private copy of the variable to original variable.
void setAssignmentOps(ArrayRef<Expr *> AssignmentOps);
/// \brief Get the list of helper assignment expressions.
MutableArrayRef<Expr *> getAssignmentOps() {
return MutableArrayRef<Expr *>(getDestinationExprs().end(), varlist_size());
}
ArrayRef<const Expr *> getAssignmentOps() const {
return llvm::makeArrayRef(getDestinationExprs().end(), varlist_size());
}
public:
/// \brief Creates clause with a list of variables \a VL.
///
/// \param C AST context.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param VL List of references to the variables.
/// \param SrcExprs List of helper expressions for proper generation of
/// assignment operation required for lastprivate clause. This list represents
/// private variables (for arrays, single array element).
/// \param DstExprs List of helper expressions for proper generation of
/// assignment operation required for lastprivate clause. This list represents
/// original variables (for arrays, single array element).
/// \param AssignmentOps List of helper expressions that represents assignment
/// operation:
/// \code
/// DstExprs = SrcExprs;
/// \endcode
/// Required for proper codegen of final assignment performed by the
/// lastprivate clause.
/// \param PreInit Statement that must be executed before entering the OpenMP
/// region with this clause.
/// \param PostUpdate Expression that must be executed after exit from the
/// OpenMP region with this clause.
///
static OMPLastprivateClause *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc, ArrayRef<Expr *> VL, ArrayRef<Expr *> SrcExprs,
ArrayRef<Expr *> DstExprs, ArrayRef<Expr *> AssignmentOps,
Stmt *PreInit, Expr *PostUpdate);
/// \brief Creates an empty clause with the place for \a N variables.
///
/// \param C AST context.
/// \param N The number of variables.
///
static OMPLastprivateClause *CreateEmpty(const ASTContext &C, unsigned N);
typedef MutableArrayRef<Expr *>::iterator helper_expr_iterator;
typedef ArrayRef<const Expr *>::iterator helper_expr_const_iterator;
typedef llvm::iterator_range<helper_expr_iterator> helper_expr_range;
typedef llvm::iterator_range<helper_expr_const_iterator>
helper_expr_const_range;
/// \brief Set list of helper expressions, required for generation of private
/// copies of original lastprivate variables.
void setPrivateCopies(ArrayRef<Expr *> PrivateCopies);
helper_expr_const_range private_copies() const {
return helper_expr_const_range(getPrivateCopies().begin(),
getPrivateCopies().end());
}
helper_expr_range private_copies() {
return helper_expr_range(getPrivateCopies().begin(),
getPrivateCopies().end());
}
helper_expr_const_range source_exprs() const {
return helper_expr_const_range(getSourceExprs().begin(),
getSourceExprs().end());
}
helper_expr_range source_exprs() {
return helper_expr_range(getSourceExprs().begin(), getSourceExprs().end());
}
helper_expr_const_range destination_exprs() const {
return helper_expr_const_range(getDestinationExprs().begin(),
getDestinationExprs().end());
}
helper_expr_range destination_exprs() {
return helper_expr_range(getDestinationExprs().begin(),
getDestinationExprs().end());
}
helper_expr_const_range assignment_ops() const {
return helper_expr_const_range(getAssignmentOps().begin(),
getAssignmentOps().end());
}
helper_expr_range assignment_ops() {
return helper_expr_range(getAssignmentOps().begin(),
getAssignmentOps().end());
}
child_range children() {
return child_range(reinterpret_cast<Stmt **>(varlist_begin()),
reinterpret_cast<Stmt **>(varlist_end()));
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_lastprivate;
}
};
/// \brief This represents clause 'shared' in the '#pragma omp ...' directives.
///
/// \code
/// #pragma omp parallel shared(a,b)
/// \endcode
/// In this example directive '#pragma omp parallel' has clause 'shared'
/// with the variables 'a' and 'b'.
///
class OMPSharedClause final
: public OMPVarListClause<OMPSharedClause>,
private llvm::TrailingObjects<OMPSharedClause, Expr *> {
friend TrailingObjects;
friend OMPVarListClause;
/// \brief Build clause with number of variables \a N.
///
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param N Number of the variables in the clause.
///
OMPSharedClause(SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc, unsigned N)
: OMPVarListClause<OMPSharedClause>(OMPC_shared, StartLoc, LParenLoc,
EndLoc, N) {}
/// \brief Build an empty clause.
///
/// \param N Number of variables.
///
explicit OMPSharedClause(unsigned N)
: OMPVarListClause<OMPSharedClause>(OMPC_shared, SourceLocation(),
SourceLocation(), SourceLocation(),
N) {}
public:
/// \brief Creates clause with a list of variables \a VL.
///
/// \param C AST context.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param VL List of references to the variables.
///
static OMPSharedClause *Create(const ASTContext &C, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc, ArrayRef<Expr *> VL);
/// \brief Creates an empty clause with \a N variables.
///
/// \param C AST context.
/// \param N The number of variables.
///
static OMPSharedClause *CreateEmpty(const ASTContext &C, unsigned N);
child_range children() {
return child_range(reinterpret_cast<Stmt **>(varlist_begin()),
reinterpret_cast<Stmt **>(varlist_end()));
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_shared;
}
};
/// \brief This represents clause 'reduction' in the '#pragma omp ...'
/// directives.
///
/// \code
/// #pragma omp parallel reduction(+:a,b)
/// \endcode
/// In this example directive '#pragma omp parallel' has clause 'reduction'
/// with operator '+' and the variables 'a' and 'b'.
///
class OMPReductionClause final
: public OMPVarListClause<OMPReductionClause>,
public OMPClauseWithPostUpdate,
private llvm::TrailingObjects<OMPReductionClause, Expr *> {
friend TrailingObjects;
friend OMPVarListClause;
friend class OMPClauseReader;
/// \brief Location of ':'.
SourceLocation ColonLoc;
/// \brief Nested name specifier for C++.
NestedNameSpecifierLoc QualifierLoc;
/// \brief Name of custom operator.
DeclarationNameInfo NameInfo;
/// \brief Build clause with number of variables \a N.
///
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param ColonLoc Location of ':'.
/// \param N Number of the variables in the clause.
/// \param QualifierLoc The nested-name qualifier with location information
/// \param NameInfo The full name info for reduction identifier.
///
OMPReductionClause(SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation ColonLoc, SourceLocation EndLoc, unsigned N,
NestedNameSpecifierLoc QualifierLoc,
const DeclarationNameInfo &NameInfo)
: OMPVarListClause<OMPReductionClause>(OMPC_reduction, StartLoc,
LParenLoc, EndLoc, N),
OMPClauseWithPostUpdate(this), ColonLoc(ColonLoc),
QualifierLoc(QualifierLoc), NameInfo(NameInfo) {}
/// \brief Build an empty clause.
///
/// \param N Number of variables.
///
explicit OMPReductionClause(unsigned N)
: OMPVarListClause<OMPReductionClause>(OMPC_reduction, SourceLocation(),
SourceLocation(), SourceLocation(),
N),
OMPClauseWithPostUpdate(this), ColonLoc(), QualifierLoc(), NameInfo() {}
/// \brief Sets location of ':' symbol in clause.
void setColonLoc(SourceLocation CL) { ColonLoc = CL; }
/// \brief Sets the name info for specified reduction identifier.
void setNameInfo(DeclarationNameInfo DNI) { NameInfo = DNI; }
/// \brief Sets the nested name specifier.
void setQualifierLoc(NestedNameSpecifierLoc NSL) { QualifierLoc = NSL; }
/// \brief Set list of helper expressions, required for proper codegen of the
/// clause. These expressions represent private copy of the reduction
/// variable.
void setPrivates(ArrayRef<Expr *> Privates);
/// \brief Get the list of helper privates.
MutableArrayRef<Expr *> getPrivates() {
return MutableArrayRef<Expr *>(varlist_end(), varlist_size());
}
ArrayRef<const Expr *> getPrivates() const {
return llvm::makeArrayRef(varlist_end(), varlist_size());
}
/// \brief Set list of helper expressions, required for proper codegen of the
/// clause. These expressions represent LHS expression in the final
/// reduction expression performed by the reduction clause.
void setLHSExprs(ArrayRef<Expr *> LHSExprs);
/// \brief Get the list of helper LHS expressions.
MutableArrayRef<Expr *> getLHSExprs() {
return MutableArrayRef<Expr *>(getPrivates().end(), varlist_size());
}
ArrayRef<const Expr *> getLHSExprs() const {
return llvm::makeArrayRef(getPrivates().end(), varlist_size());
}
/// \brief Set list of helper expressions, required for proper codegen of the
/// clause. These expressions represent RHS expression in the final
/// reduction expression performed by the reduction clause.
/// Also, variables in these expressions are used for proper initialization of
/// reduction copies.
void setRHSExprs(ArrayRef<Expr *> RHSExprs);
/// \brief Get the list of helper destination expressions.
MutableArrayRef<Expr *> getRHSExprs() {
return MutableArrayRef<Expr *>(getLHSExprs().end(), varlist_size());
}
ArrayRef<const Expr *> getRHSExprs() const {
return llvm::makeArrayRef(getLHSExprs().end(), varlist_size());
}
/// \brief Set list of helper reduction expressions, required for proper
/// codegen of the clause. These expressions are binary expressions or
/// operator/custom reduction call that calculates new value from source
/// helper expressions to destination helper expressions.
void setReductionOps(ArrayRef<Expr *> ReductionOps);
/// \brief Get the list of helper reduction expressions.
MutableArrayRef<Expr *> getReductionOps() {
return MutableArrayRef<Expr *>(getRHSExprs().end(), varlist_size());
}
ArrayRef<const Expr *> getReductionOps() const {
return llvm::makeArrayRef(getRHSExprs().end(), varlist_size());
}
public:
/// \brief Creates clause with a list of variables \a VL.
///
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param ColonLoc Location of ':'.
/// \param EndLoc Ending location of the clause.
/// \param VL The variables in the clause.
/// \param QualifierLoc The nested-name qualifier with location information
/// \param NameInfo The full name info for reduction identifier.
/// \param Privates List of helper expressions for proper generation of
/// private copies.
/// \param LHSExprs List of helper expressions for proper generation of
/// assignment operation required for copyprivate clause. This list represents
/// LHSs of the reduction expressions.
/// \param RHSExprs List of helper expressions for proper generation of
/// assignment operation required for copyprivate clause. This list represents
/// RHSs of the reduction expressions.
/// Also, variables in these expressions are used for proper initialization of
/// reduction copies.
/// \param ReductionOps List of helper expressions that represents reduction
/// expressions:
/// \code
/// LHSExprs binop RHSExprs;
/// operator binop(LHSExpr, RHSExpr);
/// <CutomReduction>(LHSExpr, RHSExpr);
/// \endcode
/// Required for proper codegen of final reduction operation performed by the
/// reduction clause.
/// \param PreInit Statement that must be executed before entering the OpenMP
/// region with this clause.
/// \param PostUpdate Expression that must be executed after exit from the
/// OpenMP region with this clause.
///
static OMPReductionClause *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation ColonLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL,
NestedNameSpecifierLoc QualifierLoc,
const DeclarationNameInfo &NameInfo, ArrayRef<Expr *> Privates,
ArrayRef<Expr *> LHSExprs, ArrayRef<Expr *> RHSExprs,
ArrayRef<Expr *> ReductionOps, Stmt *PreInit, Expr *PostUpdate);
/// \brief Creates an empty clause with the place for \a N variables.
///
/// \param C AST context.
/// \param N The number of variables.
///
static OMPReductionClause *CreateEmpty(const ASTContext &C, unsigned N);
/// \brief Gets location of ':' symbol in clause.
SourceLocation getColonLoc() const { return ColonLoc; }
/// \brief Gets the name info for specified reduction identifier.
const DeclarationNameInfo &getNameInfo() const { return NameInfo; }
/// \brief Gets the nested name specifier.
NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
typedef MutableArrayRef<Expr *>::iterator helper_expr_iterator;
typedef ArrayRef<const Expr *>::iterator helper_expr_const_iterator;
typedef llvm::iterator_range<helper_expr_iterator> helper_expr_range;
typedef llvm::iterator_range<helper_expr_const_iterator>
helper_expr_const_range;
helper_expr_const_range privates() const {
return helper_expr_const_range(getPrivates().begin(), getPrivates().end());
}
helper_expr_range privates() {
return helper_expr_range(getPrivates().begin(), getPrivates().end());
}
helper_expr_const_range lhs_exprs() const {
return helper_expr_const_range(getLHSExprs().begin(), getLHSExprs().end());
}
helper_expr_range lhs_exprs() {
return helper_expr_range(getLHSExprs().begin(), getLHSExprs().end());
}
helper_expr_const_range rhs_exprs() const {
return helper_expr_const_range(getRHSExprs().begin(), getRHSExprs().end());
}
helper_expr_range rhs_exprs() {
return helper_expr_range(getRHSExprs().begin(), getRHSExprs().end());
}
helper_expr_const_range reduction_ops() const {
return helper_expr_const_range(getReductionOps().begin(),
getReductionOps().end());
}
helper_expr_range reduction_ops() {
return helper_expr_range(getReductionOps().begin(),
getReductionOps().end());
}
child_range children() {
return child_range(reinterpret_cast<Stmt **>(varlist_begin()),
reinterpret_cast<Stmt **>(varlist_end()));
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_reduction;
}
};
/// \brief This represents clause 'linear' in the '#pragma omp ...'
/// directives.
///
/// \code
/// #pragma omp simd linear(a,b : 2)
/// \endcode
/// In this example directive '#pragma omp simd' has clause 'linear'
/// with variables 'a', 'b' and linear step '2'.
///
class OMPLinearClause final
: public OMPVarListClause<OMPLinearClause>,
public OMPClauseWithPostUpdate,
private llvm::TrailingObjects<OMPLinearClause, Expr *> {
friend TrailingObjects;
friend OMPVarListClause;
friend class OMPClauseReader;
/// \brief Modifier of 'linear' clause.
OpenMPLinearClauseKind Modifier;
/// \brief Location of linear modifier if any.
SourceLocation ModifierLoc;
/// \brief Location of ':'.
SourceLocation ColonLoc;
/// \brief Sets the linear step for clause.
void setStep(Expr *Step) { *(getFinals().end()) = Step; }
/// \brief Sets the expression to calculate linear step for clause.
void setCalcStep(Expr *CalcStep) { *(getFinals().end() + 1) = CalcStep; }
/// \brief Build 'linear' clause with given number of variables \a NumVars.
///
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param ColonLoc Location of ':'.
/// \param EndLoc Ending location of the clause.
/// \param NumVars Number of variables.
///
OMPLinearClause(SourceLocation StartLoc, SourceLocation LParenLoc,
OpenMPLinearClauseKind Modifier, SourceLocation ModifierLoc,
SourceLocation ColonLoc, SourceLocation EndLoc,
unsigned NumVars)
: OMPVarListClause<OMPLinearClause>(OMPC_linear, StartLoc, LParenLoc,
EndLoc, NumVars),
OMPClauseWithPostUpdate(this), Modifier(Modifier),
ModifierLoc(ModifierLoc), ColonLoc(ColonLoc) {}
/// \brief Build an empty clause.
///
/// \param NumVars Number of variables.
///
explicit OMPLinearClause(unsigned NumVars)
: OMPVarListClause<OMPLinearClause>(OMPC_linear, SourceLocation(),
SourceLocation(), SourceLocation(),
NumVars),
OMPClauseWithPostUpdate(this), Modifier(OMPC_LINEAR_val), ModifierLoc(),
ColonLoc() {}
/// \brief Gets the list of initial values for linear variables.
///
/// There are NumVars expressions with initial values allocated after the
/// varlist, they are followed by NumVars update expressions (used to update
/// the linear variable's value on current iteration) and they are followed by
/// NumVars final expressions (used to calculate the linear variable's
/// value after the loop body). After these lists, there are 2 helper
/// expressions - linear step and a helper to calculate it before the
/// loop body (used when the linear step is not constant):
///
/// { Vars[] /* in OMPVarListClause */; Privates[]; Inits[]; Updates[];
/// Finals[]; Step; CalcStep; }
///
MutableArrayRef<Expr *> getPrivates() {
return MutableArrayRef<Expr *>(varlist_end(), varlist_size());
}
ArrayRef<const Expr *> getPrivates() const {
return llvm::makeArrayRef(varlist_end(), varlist_size());
}
MutableArrayRef<Expr *> getInits() {
return MutableArrayRef<Expr *>(getPrivates().end(), varlist_size());
}
ArrayRef<const Expr *> getInits() const {
return llvm::makeArrayRef(getPrivates().end(), varlist_size());
}
/// \brief Sets the list of update expressions for linear variables.
MutableArrayRef<Expr *> getUpdates() {
return MutableArrayRef<Expr *>(getInits().end(), varlist_size());
}
ArrayRef<const Expr *> getUpdates() const {
return llvm::makeArrayRef(getInits().end(), varlist_size());
}
/// \brief Sets the list of final update expressions for linear variables.
MutableArrayRef<Expr *> getFinals() {
return MutableArrayRef<Expr *>(getUpdates().end(), varlist_size());
}
ArrayRef<const Expr *> getFinals() const {
return llvm::makeArrayRef(getUpdates().end(), varlist_size());
}
/// \brief Sets the list of the copies of original linear variables.
/// \param PL List of expressions.
void setPrivates(ArrayRef<Expr *> PL);
/// \brief Sets the list of the initial values for linear variables.
/// \param IL List of expressions.
void setInits(ArrayRef<Expr *> IL);
public:
/// \brief Creates clause with a list of variables \a VL and a linear step
/// \a Step.
///
/// \param C AST Context.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param Modifier Modifier of 'linear' clause.
/// \param ModifierLoc Modifier location.
/// \param ColonLoc Location of ':'.
/// \param EndLoc Ending location of the clause.
/// \param VL List of references to the variables.
/// \param PL List of private copies of original variables.
/// \param IL List of initial values for the variables.
/// \param Step Linear step.
/// \param CalcStep Calculation of the linear step.
/// \param PreInit Statement that must be executed before entering the OpenMP
/// region with this clause.
/// \param PostUpdate Expression that must be executed after exit from the
/// OpenMP region with this clause.
static OMPLinearClause *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc,
OpenMPLinearClauseKind Modifier, SourceLocation ModifierLoc,
SourceLocation ColonLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL,
ArrayRef<Expr *> PL, ArrayRef<Expr *> IL, Expr *Step, Expr *CalcStep,
Stmt *PreInit, Expr *PostUpdate);
/// \brief Creates an empty clause with the place for \a NumVars variables.
///
/// \param C AST context.
/// \param NumVars Number of variables.
///
static OMPLinearClause *CreateEmpty(const ASTContext &C, unsigned NumVars);
/// \brief Set modifier.
void setModifier(OpenMPLinearClauseKind Kind) { Modifier = Kind; }
/// \brief Return modifier.
OpenMPLinearClauseKind getModifier() const { return Modifier; }
/// \brief Set modifier location.
void setModifierLoc(SourceLocation Loc) { ModifierLoc = Loc; }
/// \brief Return modifier location.
SourceLocation getModifierLoc() const { return ModifierLoc; }
/// \brief Sets the location of ':'.
void setColonLoc(SourceLocation Loc) { ColonLoc = Loc; }
/// \brief Returns the location of ':'.
SourceLocation getColonLoc() const { return ColonLoc; }
/// \brief Returns linear step.
Expr *getStep() { return *(getFinals().end()); }
/// \brief Returns linear step.
const Expr *getStep() const { return *(getFinals().end()); }
/// \brief Returns expression to calculate linear step.
Expr *getCalcStep() { return *(getFinals().end() + 1); }
/// \brief Returns expression to calculate linear step.
const Expr *getCalcStep() const { return *(getFinals().end() + 1); }
/// \brief Sets the list of update expressions for linear variables.
/// \param UL List of expressions.
void setUpdates(ArrayRef<Expr *> UL);
/// \brief Sets the list of final update expressions for linear variables.
/// \param FL List of expressions.
void setFinals(ArrayRef<Expr *> FL);
typedef MutableArrayRef<Expr *>::iterator privates_iterator;
typedef ArrayRef<const Expr *>::iterator privates_const_iterator;
typedef llvm::iterator_range<privates_iterator> privates_range;
typedef llvm::iterator_range<privates_const_iterator> privates_const_range;
privates_range privates() {
return privates_range(getPrivates().begin(), getPrivates().end());
}
privates_const_range privates() const {
return privates_const_range(getPrivates().begin(), getPrivates().end());
}
typedef MutableArrayRef<Expr *>::iterator inits_iterator;
typedef ArrayRef<const Expr *>::iterator inits_const_iterator;
typedef llvm::iterator_range<inits_iterator> inits_range;
typedef llvm::iterator_range<inits_const_iterator> inits_const_range;
inits_range inits() {
return inits_range(getInits().begin(), getInits().end());
}
inits_const_range inits() const {
return inits_const_range(getInits().begin(), getInits().end());
}
typedef MutableArrayRef<Expr *>::iterator updates_iterator;
typedef ArrayRef<const Expr *>::iterator updates_const_iterator;
typedef llvm::iterator_range<updates_iterator> updates_range;
typedef llvm::iterator_range<updates_const_iterator> updates_const_range;
updates_range updates() {
return updates_range(getUpdates().begin(), getUpdates().end());
}
updates_const_range updates() const {
return updates_const_range(getUpdates().begin(), getUpdates().end());
}
typedef MutableArrayRef<Expr *>::iterator finals_iterator;
typedef ArrayRef<const Expr *>::iterator finals_const_iterator;
typedef llvm::iterator_range<finals_iterator> finals_range;
typedef llvm::iterator_range<finals_const_iterator> finals_const_range;
finals_range finals() {
return finals_range(getFinals().begin(), getFinals().end());
}
finals_const_range finals() const {
return finals_const_range(getFinals().begin(), getFinals().end());
}
child_range children() {
return child_range(reinterpret_cast<Stmt **>(varlist_begin()),
reinterpret_cast<Stmt **>(varlist_end()));
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_linear;
}
};
/// \brief This represents clause 'aligned' in the '#pragma omp ...'
/// directives.
///
/// \code
/// #pragma omp simd aligned(a,b : 8)
/// \endcode
/// In this example directive '#pragma omp simd' has clause 'aligned'
/// with variables 'a', 'b' and alignment '8'.
///
class OMPAlignedClause final
: public OMPVarListClause<OMPAlignedClause>,
private llvm::TrailingObjects<OMPAlignedClause, Expr *> {
friend TrailingObjects;
friend OMPVarListClause;
friend class OMPClauseReader;
/// \brief Location of ':'.
SourceLocation ColonLoc;
/// \brief Sets the alignment for clause.
void setAlignment(Expr *A) { *varlist_end() = A; }
/// \brief Build 'aligned' clause with given number of variables \a NumVars.
///
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param ColonLoc Location of ':'.
/// \param EndLoc Ending location of the clause.
/// \param NumVars Number of variables.
///
OMPAlignedClause(SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation ColonLoc, SourceLocation EndLoc,
unsigned NumVars)
: OMPVarListClause<OMPAlignedClause>(OMPC_aligned, StartLoc, LParenLoc,
EndLoc, NumVars),
ColonLoc(ColonLoc) {}
/// \brief Build an empty clause.
///
/// \param NumVars Number of variables.
///
explicit OMPAlignedClause(unsigned NumVars)
: OMPVarListClause<OMPAlignedClause>(OMPC_aligned, SourceLocation(),
SourceLocation(), SourceLocation(),
NumVars),
ColonLoc(SourceLocation()) {}
public:
/// \brief Creates clause with a list of variables \a VL and alignment \a A.
///
/// \param C AST Context.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param ColonLoc Location of ':'.
/// \param EndLoc Ending location of the clause.
/// \param VL List of references to the variables.
/// \param A Alignment.
static OMPAlignedClause *Create(const ASTContext &C, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation ColonLoc,
SourceLocation EndLoc, ArrayRef<Expr *> VL,
Expr *A);
/// \brief Creates an empty clause with the place for \a NumVars variables.
///
/// \param C AST context.
/// \param NumVars Number of variables.
///
static OMPAlignedClause *CreateEmpty(const ASTContext &C, unsigned NumVars);
/// \brief Sets the location of ':'.
void setColonLoc(SourceLocation Loc) { ColonLoc = Loc; }
/// \brief Returns the location of ':'.
SourceLocation getColonLoc() const { return ColonLoc; }
/// \brief Returns alignment.
Expr *getAlignment() { return *varlist_end(); }
/// \brief Returns alignment.
const Expr *getAlignment() const { return *varlist_end(); }
child_range children() {
return child_range(reinterpret_cast<Stmt **>(varlist_begin()),
reinterpret_cast<Stmt **>(varlist_end()));
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_aligned;
}
};
/// \brief This represents clause 'copyin' in the '#pragma omp ...' directives.
///
/// \code
/// #pragma omp parallel copyin(a,b)
/// \endcode
/// In this example directive '#pragma omp parallel' has clause 'copyin'
/// with the variables 'a' and 'b'.
///
class OMPCopyinClause final
: public OMPVarListClause<OMPCopyinClause>,
private llvm::TrailingObjects<OMPCopyinClause, Expr *> {
// Class has 3 additional tail allocated arrays:
// 1. List of helper expressions for proper generation of assignment operation
// required for copyin clause. This list represents sources.
// 2. List of helper expressions for proper generation of assignment operation
// required for copyin clause. This list represents destinations.
// 3. List of helper expressions that represents assignment operation:
// \code
// DstExprs = SrcExprs;
// \endcode
// Required for proper codegen of propagation of master's thread values of
// threadprivate variables to local instances of that variables in other
// implicit threads.
friend TrailingObjects;
friend OMPVarListClause;
friend class OMPClauseReader;
/// \brief Build clause with number of variables \a N.
///
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param N Number of the variables in the clause.
///
OMPCopyinClause(SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc, unsigned N)
: OMPVarListClause<OMPCopyinClause>(OMPC_copyin, StartLoc, LParenLoc,
EndLoc, N) {}
/// \brief Build an empty clause.
///
/// \param N Number of variables.
///
explicit OMPCopyinClause(unsigned N)
: OMPVarListClause<OMPCopyinClause>(OMPC_copyin, SourceLocation(),
SourceLocation(), SourceLocation(),
N) {}
/// \brief Set list of helper expressions, required for proper codegen of the
/// clause. These expressions represent source expression in the final
/// assignment statement performed by the copyin clause.
void setSourceExprs(ArrayRef<Expr *> SrcExprs);
/// \brief Get the list of helper source expressions.
MutableArrayRef<Expr *> getSourceExprs() {
return MutableArrayRef<Expr *>(varlist_end(), varlist_size());
}
ArrayRef<const Expr *> getSourceExprs() const {
return llvm::makeArrayRef(varlist_end(), varlist_size());
}
/// \brief Set list of helper expressions, required for proper codegen of the
/// clause. These expressions represent destination expression in the final
/// assignment statement performed by the copyin clause.
void setDestinationExprs(ArrayRef<Expr *> DstExprs);
/// \brief Get the list of helper destination expressions.
MutableArrayRef<Expr *> getDestinationExprs() {
return MutableArrayRef<Expr *>(getSourceExprs().end(), varlist_size());
}
ArrayRef<const Expr *> getDestinationExprs() const {
return llvm::makeArrayRef(getSourceExprs().end(), varlist_size());
}
/// \brief Set list of helper assignment expressions, required for proper
/// codegen of the clause. These expressions are assignment expressions that
/// assign source helper expressions to destination helper expressions
/// correspondingly.
void setAssignmentOps(ArrayRef<Expr *> AssignmentOps);
/// \brief Get the list of helper assignment expressions.
MutableArrayRef<Expr *> getAssignmentOps() {
return MutableArrayRef<Expr *>(getDestinationExprs().end(), varlist_size());
}
ArrayRef<const Expr *> getAssignmentOps() const {
return llvm::makeArrayRef(getDestinationExprs().end(), varlist_size());
}
public:
/// \brief Creates clause with a list of variables \a VL.
///
/// \param C AST context.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param VL List of references to the variables.
/// \param SrcExprs List of helper expressions for proper generation of
/// assignment operation required for copyin clause. This list represents
/// sources.
/// \param DstExprs List of helper expressions for proper generation of
/// assignment operation required for copyin clause. This list represents
/// destinations.
/// \param AssignmentOps List of helper expressions that represents assignment
/// operation:
/// \code
/// DstExprs = SrcExprs;
/// \endcode
/// Required for proper codegen of propagation of master's thread values of
/// threadprivate variables to local instances of that variables in other
/// implicit threads.
///
static OMPCopyinClause *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc, ArrayRef<Expr *> VL, ArrayRef<Expr *> SrcExprs,
ArrayRef<Expr *> DstExprs, ArrayRef<Expr *> AssignmentOps);
/// \brief Creates an empty clause with \a N variables.
///
/// \param C AST context.
/// \param N The number of variables.
///
static OMPCopyinClause *CreateEmpty(const ASTContext &C, unsigned N);
typedef MutableArrayRef<Expr *>::iterator helper_expr_iterator;
typedef ArrayRef<const Expr *>::iterator helper_expr_const_iterator;
typedef llvm::iterator_range<helper_expr_iterator> helper_expr_range;
typedef llvm::iterator_range<helper_expr_const_iterator>
helper_expr_const_range;
helper_expr_const_range source_exprs() const {
return helper_expr_const_range(getSourceExprs().begin(),
getSourceExprs().end());
}
helper_expr_range source_exprs() {
return helper_expr_range(getSourceExprs().begin(), getSourceExprs().end());
}
helper_expr_const_range destination_exprs() const {
return helper_expr_const_range(getDestinationExprs().begin(),
getDestinationExprs().end());
}
helper_expr_range destination_exprs() {
return helper_expr_range(getDestinationExprs().begin(),
getDestinationExprs().end());
}
helper_expr_const_range assignment_ops() const {
return helper_expr_const_range(getAssignmentOps().begin(),
getAssignmentOps().end());
}
helper_expr_range assignment_ops() {
return helper_expr_range(getAssignmentOps().begin(),
getAssignmentOps().end());
}
child_range children() {
return child_range(reinterpret_cast<Stmt **>(varlist_begin()),
reinterpret_cast<Stmt **>(varlist_end()));
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_copyin;
}
};
/// \brief This represents clause 'copyprivate' in the '#pragma omp ...'
/// directives.
///
/// \code
/// #pragma omp single copyprivate(a,b)
/// \endcode
/// In this example directive '#pragma omp single' has clause 'copyprivate'
/// with the variables 'a' and 'b'.
///
class OMPCopyprivateClause final
: public OMPVarListClause<OMPCopyprivateClause>,
private llvm::TrailingObjects<OMPCopyprivateClause, Expr *> {
friend TrailingObjects;
friend OMPVarListClause;
friend class OMPClauseReader;
/// \brief Build clause with number of variables \a N.
///
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param N Number of the variables in the clause.
///
OMPCopyprivateClause(SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc, unsigned N)
: OMPVarListClause<OMPCopyprivateClause>(OMPC_copyprivate, StartLoc,
LParenLoc, EndLoc, N) {}
/// \brief Build an empty clause.
///
/// \param N Number of variables.
///
explicit OMPCopyprivateClause(unsigned N)
: OMPVarListClause<OMPCopyprivateClause>(
OMPC_copyprivate, SourceLocation(), SourceLocation(),
SourceLocation(), N) {}
/// \brief Set list of helper expressions, required for proper codegen of the
/// clause. These expressions represent source expression in the final
/// assignment statement performed by the copyprivate clause.
void setSourceExprs(ArrayRef<Expr *> SrcExprs);
/// \brief Get the list of helper source expressions.
MutableArrayRef<Expr *> getSourceExprs() {
return MutableArrayRef<Expr *>(varlist_end(), varlist_size());
}
ArrayRef<const Expr *> getSourceExprs() const {
return llvm::makeArrayRef(varlist_end(), varlist_size());
}
/// \brief Set list of helper expressions, required for proper codegen of the
/// clause. These expressions represent destination expression in the final
/// assignment statement performed by the copyprivate clause.
void setDestinationExprs(ArrayRef<Expr *> DstExprs);
/// \brief Get the list of helper destination expressions.
MutableArrayRef<Expr *> getDestinationExprs() {
return MutableArrayRef<Expr *>(getSourceExprs().end(), varlist_size());
}
ArrayRef<const Expr *> getDestinationExprs() const {
return llvm::makeArrayRef(getSourceExprs().end(), varlist_size());
}
/// \brief Set list of helper assignment expressions, required for proper
/// codegen of the clause. These expressions are assignment expressions that
/// assign source helper expressions to destination helper expressions
/// correspondingly.
void setAssignmentOps(ArrayRef<Expr *> AssignmentOps);
/// \brief Get the list of helper assignment expressions.
MutableArrayRef<Expr *> getAssignmentOps() {
return MutableArrayRef<Expr *>(getDestinationExprs().end(), varlist_size());
}
ArrayRef<const Expr *> getAssignmentOps() const {
return llvm::makeArrayRef(getDestinationExprs().end(), varlist_size());
}
public:
/// \brief Creates clause with a list of variables \a VL.
///
/// \param C AST context.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param VL List of references to the variables.
/// \param SrcExprs List of helper expressions for proper generation of
/// assignment operation required for copyprivate clause. This list represents
/// sources.
/// \param DstExprs List of helper expressions for proper generation of
/// assignment operation required for copyprivate clause. This list represents
/// destinations.
/// \param AssignmentOps List of helper expressions that represents assignment
/// operation:
/// \code
/// DstExprs = SrcExprs;
/// \endcode
/// Required for proper codegen of final assignment performed by the
/// copyprivate clause.
///
static OMPCopyprivateClause *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc, ArrayRef<Expr *> VL, ArrayRef<Expr *> SrcExprs,
ArrayRef<Expr *> DstExprs, ArrayRef<Expr *> AssignmentOps);
/// \brief Creates an empty clause with \a N variables.
///
/// \param C AST context.
/// \param N The number of variables.
///
static OMPCopyprivateClause *CreateEmpty(const ASTContext &C, unsigned N);
typedef MutableArrayRef<Expr *>::iterator helper_expr_iterator;
typedef ArrayRef<const Expr *>::iterator helper_expr_const_iterator;
typedef llvm::iterator_range<helper_expr_iterator> helper_expr_range;
typedef llvm::iterator_range<helper_expr_const_iterator>
helper_expr_const_range;
helper_expr_const_range source_exprs() const {
return helper_expr_const_range(getSourceExprs().begin(),
getSourceExprs().end());
}
helper_expr_range source_exprs() {
return helper_expr_range(getSourceExprs().begin(), getSourceExprs().end());
}
helper_expr_const_range destination_exprs() const {
return helper_expr_const_range(getDestinationExprs().begin(),
getDestinationExprs().end());
}
helper_expr_range destination_exprs() {
return helper_expr_range(getDestinationExprs().begin(),
getDestinationExprs().end());
}
helper_expr_const_range assignment_ops() const {
return helper_expr_const_range(getAssignmentOps().begin(),
getAssignmentOps().end());
}
helper_expr_range assignment_ops() {
return helper_expr_range(getAssignmentOps().begin(),
getAssignmentOps().end());
}
child_range children() {
return child_range(reinterpret_cast<Stmt **>(varlist_begin()),
reinterpret_cast<Stmt **>(varlist_end()));
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_copyprivate;
}
};
/// \brief This represents implicit clause 'flush' for the '#pragma omp flush'
/// directive.
/// This clause does not exist by itself, it can be only as a part of 'omp
/// flush' directive. This clause is introduced to keep the original structure
/// of \a OMPExecutableDirective class and its derivatives and to use the
/// existing infrastructure of clauses with the list of variables.
///
/// \code
/// #pragma omp flush(a,b)
/// \endcode
/// In this example directive '#pragma omp flush' has implicit clause 'flush'
/// with the variables 'a' and 'b'.
///
class OMPFlushClause final
: public OMPVarListClause<OMPFlushClause>,
private llvm::TrailingObjects<OMPFlushClause, Expr *> {
friend TrailingObjects;
friend OMPVarListClause;
/// \brief Build clause with number of variables \a N.
///
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param N Number of the variables in the clause.
///
OMPFlushClause(SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc, unsigned N)
: OMPVarListClause<OMPFlushClause>(OMPC_flush, StartLoc, LParenLoc,
EndLoc, N) {}
/// \brief Build an empty clause.
///
/// \param N Number of variables.
///
explicit OMPFlushClause(unsigned N)
: OMPVarListClause<OMPFlushClause>(OMPC_flush, SourceLocation(),
SourceLocation(), SourceLocation(),
N) {}
public:
/// \brief Creates clause with a list of variables \a VL.
///
/// \param C AST context.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param VL List of references to the variables.
///
static OMPFlushClause *Create(const ASTContext &C, SourceLocation StartLoc,
SourceLocation LParenLoc, SourceLocation EndLoc,
ArrayRef<Expr *> VL);
/// \brief Creates an empty clause with \a N variables.
///
/// \param C AST context.
/// \param N The number of variables.
///
static OMPFlushClause *CreateEmpty(const ASTContext &C, unsigned N);
child_range children() {
return child_range(reinterpret_cast<Stmt **>(varlist_begin()),
reinterpret_cast<Stmt **>(varlist_end()));
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_flush;
}
};
/// \brief This represents implicit clause 'depend' for the '#pragma omp task'
/// directive.
///
/// \code
/// #pragma omp task depend(in:a,b)
/// \endcode
/// In this example directive '#pragma omp task' with clause 'depend' with the
/// variables 'a' and 'b' with dependency 'in'.
///
class OMPDependClause final
: public OMPVarListClause<OMPDependClause>,
private llvm::TrailingObjects<OMPDependClause, Expr *> {
friend TrailingObjects;
friend OMPVarListClause;
friend class OMPClauseReader;
/// \brief Dependency type (one of in, out, inout).
OpenMPDependClauseKind DepKind;
/// \brief Dependency type location.
SourceLocation DepLoc;
/// \brief Colon location.
SourceLocation ColonLoc;
/// \brief Build clause with number of variables \a N.
///
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param N Number of the variables in the clause.
///
OMPDependClause(SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc, unsigned N)
: OMPVarListClause<OMPDependClause>(OMPC_depend, StartLoc, LParenLoc,
EndLoc, N),
DepKind(OMPC_DEPEND_unknown) {}
/// \brief Build an empty clause.
///
/// \param N Number of variables.
///
explicit OMPDependClause(unsigned N)
: OMPVarListClause<OMPDependClause>(OMPC_depend, SourceLocation(),
SourceLocation(), SourceLocation(),
N),
DepKind(OMPC_DEPEND_unknown) {}
/// \brief Set dependency kind.
void setDependencyKind(OpenMPDependClauseKind K) { DepKind = K; }
/// \brief Set dependency kind and its location.
void setDependencyLoc(SourceLocation Loc) { DepLoc = Loc; }
/// \brief Set colon location.
void setColonLoc(SourceLocation Loc) { ColonLoc = Loc; }
public:
/// \brief Creates clause with a list of variables \a VL.
///
/// \param C AST context.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param DepKind Dependency type.
/// \param DepLoc Location of the dependency type.
/// \param ColonLoc Colon location.
/// \param VL List of references to the variables.
static OMPDependClause *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc, OpenMPDependClauseKind DepKind,
SourceLocation DepLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VL);
/// \brief Creates an empty clause with \a N variables.
///
/// \param C AST context.
/// \param N The number of variables.
///
static OMPDependClause *CreateEmpty(const ASTContext &C, unsigned N);
/// \brief Get dependency type.
OpenMPDependClauseKind getDependencyKind() const { return DepKind; }
/// \brief Get dependency type location.
SourceLocation getDependencyLoc() const { return DepLoc; }
/// \brief Get colon location.
SourceLocation getColonLoc() const { return ColonLoc; }
/// Set the loop counter value for the depend clauses with 'sink|source' kind
/// of dependency. Required for codegen.
void setCounterValue(Expr *V);
/// Get the loop counter value.
Expr *getCounterValue();
/// Get the loop counter value.
const Expr *getCounterValue() const;
child_range children() {
return child_range(reinterpret_cast<Stmt **>(varlist_begin()),
reinterpret_cast<Stmt **>(varlist_end()));
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_depend;
}
};
/// \brief This represents 'device' clause in the '#pragma omp ...'
/// directive.
///
/// \code
/// #pragma omp target device(a)
/// \endcode
/// In this example directive '#pragma omp target' has clause 'device'
/// with single expression 'a'.
///
class OMPDeviceClause : public OMPClause {
friend class OMPClauseReader;
/// \brief Location of '('.
SourceLocation LParenLoc;
/// \brief Device number.
Stmt *Device;
/// \brief Set the device number.
///
/// \param E Device number.
///
void setDevice(Expr *E) { Device = E; }
public:
/// \brief Build 'device' clause.
///
/// \param E Expression associated with this clause.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
///
OMPDeviceClause(Expr *E, SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc)
: OMPClause(OMPC_device, StartLoc, EndLoc), LParenLoc(LParenLoc),
Device(E) {}
/// \brief Build an empty clause.
///
OMPDeviceClause()
: OMPClause(OMPC_device, SourceLocation(), SourceLocation()),
LParenLoc(SourceLocation()), Device(nullptr) {}
/// \brief Sets the location of '('.
void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
/// \brief Returns the location of '('.
SourceLocation getLParenLoc() const { return LParenLoc; }
/// \brief Return device number.
Expr *getDevice() { return cast<Expr>(Device); }
/// \brief Return device number.
Expr *getDevice() const { return cast<Expr>(Device); }
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_device;
}
child_range children() { return child_range(&Device, &Device + 1); }
};
/// \brief This represents 'threads' clause in the '#pragma omp ...' directive.
///
/// \code
/// #pragma omp ordered threads
/// \endcode
/// In this example directive '#pragma omp ordered' has simple 'threads' clause.
///
class OMPThreadsClause : public OMPClause {
public:
/// \brief Build 'threads' clause.
///
/// \param StartLoc Starting location of the clause.
/// \param EndLoc Ending location of the clause.
///
OMPThreadsClause(SourceLocation StartLoc, SourceLocation EndLoc)
: OMPClause(OMPC_threads, StartLoc, EndLoc) {}
/// \brief Build an empty clause.
///
OMPThreadsClause()
: OMPClause(OMPC_threads, SourceLocation(), SourceLocation()) {}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_threads;
}
child_range children() {
return child_range(child_iterator(), child_iterator());
}
};
/// \brief This represents 'simd' clause in the '#pragma omp ...' directive.
///
/// \code
/// #pragma omp ordered simd
/// \endcode
/// In this example directive '#pragma omp ordered' has simple 'simd' clause.
///
class OMPSIMDClause : public OMPClause {
public:
/// \brief Build 'simd' clause.
///
/// \param StartLoc Starting location of the clause.
/// \param EndLoc Ending location of the clause.
///
OMPSIMDClause(SourceLocation StartLoc, SourceLocation EndLoc)
: OMPClause(OMPC_simd, StartLoc, EndLoc) {}
/// \brief Build an empty clause.
///
OMPSIMDClause() : OMPClause(OMPC_simd, SourceLocation(), SourceLocation()) {}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_simd;
}
child_range children() {
return child_range(child_iterator(), child_iterator());
}
};
/// \brief Struct that defines common infrastructure to handle mappable
/// expressions used in OpenMP clauses.
class OMPClauseMappableExprCommon {
public:
// \brief Class that represents a component of a mappable expression. E.g.
// for an expression S.a, the first component is a declaration reference
// expression associated with 'S' and the second is a member expression
// associated with the field declaration 'a'. If the expression is an array
// subscript it may not have any associated declaration. In that case the
// associated declaration is set to nullptr.
class MappableComponent {
// \brief Expression associated with the component.
Expr *AssociatedExpression = nullptr;
// \brief Declaration associated with the declaration. If the component does
// not have a declaration (e.g. array subscripts or section), this is set to
// nullptr.
ValueDecl *AssociatedDeclaration = nullptr;
public:
explicit MappableComponent() {}
explicit MappableComponent(Expr *AssociatedExpression,
ValueDecl *AssociatedDeclaration)
: AssociatedExpression(AssociatedExpression),
AssociatedDeclaration(
AssociatedDeclaration
? cast<ValueDecl>(AssociatedDeclaration->getCanonicalDecl())
: nullptr) {}
Expr *getAssociatedExpression() const { return AssociatedExpression; }
ValueDecl *getAssociatedDeclaration() const {
return AssociatedDeclaration;
}
};
// \brief List of components of an expression. This first one is the whole
// expression and the last one is the base expression.
typedef SmallVector<MappableComponent, 8> MappableExprComponentList;
typedef ArrayRef<MappableComponent> MappableExprComponentListRef;
// \brief List of all component lists associated to the same base declaration.
// E.g. if both 'S.a' and 'S.b' are a mappable expressions, each will have
// their component list but the same base declaration 'S'.
typedef SmallVector<MappableExprComponentList, 8> MappableExprComponentLists;
typedef ArrayRef<MappableExprComponentList> MappableExprComponentListsRef;
protected:
// \brief Return the total number of elements in a list of component lists.
static unsigned
getComponentsTotalNumber(MappableExprComponentListsRef ComponentLists);
// \brief Return the total number of elements in a list of declarations. All
// declarations are expected to be canonical.
static unsigned
getUniqueDeclarationsTotalNumber(ArrayRef<ValueDecl *> Declarations);
};
/// \brief This represents clauses with a list of expressions that are mappable.
/// Examples of these clauses are 'map' in
/// '#pragma omp target [enter|exit] [data]...' directives, and 'to' and 'from
/// in '#pragma omp target update...' directives.
template <class T>
class OMPMappableExprListClause : public OMPVarListClause<T>,
public OMPClauseMappableExprCommon {
friend class OMPClauseReader;
/// \brief Number of unique declarations in this clause.
unsigned NumUniqueDeclarations;
/// \brief Number of component lists in this clause.
unsigned NumComponentLists;
/// \brief Total number of components in this clause.
unsigned NumComponents;
protected:
/// \brief Get the unique declarations that are in the trailing objects of the
/// class.
MutableArrayRef<ValueDecl *> getUniqueDeclsRef() {
return MutableArrayRef<ValueDecl *>(
static_cast<T *>(this)->template getTrailingObjects<ValueDecl *>(),
NumUniqueDeclarations);
}
/// \brief Get the unique declarations that are in the trailing objects of the
/// class.
ArrayRef<ValueDecl *> getUniqueDeclsRef() const {
return ArrayRef<ValueDecl *>(
static_cast<const T *>(this)
->template getTrailingObjects<ValueDecl *>(),
NumUniqueDeclarations);
}
/// \brief Set the unique declarations that are in the trailing objects of the
/// class.
void setUniqueDecls(ArrayRef<ValueDecl *> UDs) {
assert(UDs.size() == NumUniqueDeclarations &&
"Unexpected amount of unique declarations.");
std::copy(UDs.begin(), UDs.end(), getUniqueDeclsRef().begin());
}
/// \brief Get the number of lists per declaration that are in the trailing
/// objects of the class.
MutableArrayRef<unsigned> getDeclNumListsRef() {
return MutableArrayRef<unsigned>(
static_cast<T *>(this)->template getTrailingObjects<unsigned>(),
NumUniqueDeclarations);
}
/// \brief Get the number of lists per declaration that are in the trailing
/// objects of the class.
ArrayRef<unsigned> getDeclNumListsRef() const {
return ArrayRef<unsigned>(
static_cast<const T *>(this)->template getTrailingObjects<unsigned>(),
NumUniqueDeclarations);
}
/// \brief Set the number of lists per declaration that are in the trailing
/// objects of the class.
void setDeclNumLists(ArrayRef<unsigned> DNLs) {
assert(DNLs.size() == NumUniqueDeclarations &&
"Unexpected amount of list numbers.");
std::copy(DNLs.begin(), DNLs.end(), getDeclNumListsRef().begin());
}
/// \brief Get the cumulative component lists sizes that are in the trailing
/// objects of the class. They are appended after the number of lists.
MutableArrayRef<unsigned> getComponentListSizesRef() {
return MutableArrayRef<unsigned>(
static_cast<T *>(this)->template getTrailingObjects<unsigned>() +
NumUniqueDeclarations,
NumComponentLists);
}
/// \brief Get the cumulative component lists sizes that are in the trailing
/// objects of the class. They are appended after the number of lists.
ArrayRef<unsigned> getComponentListSizesRef() const {
return ArrayRef<unsigned>(
static_cast<const T *>(this)->template getTrailingObjects<unsigned>() +
NumUniqueDeclarations,
NumComponentLists);
}
/// \brief Set the cumulative component lists sizes that are in the trailing
/// objects of the class.
void setComponentListSizes(ArrayRef<unsigned> CLSs) {
assert(CLSs.size() == NumComponentLists &&
"Unexpected amount of component lists.");
std::copy(CLSs.begin(), CLSs.end(), getComponentListSizesRef().begin());
}
/// \brief Get the components that are in the trailing objects of the class.
MutableArrayRef<MappableComponent> getComponentsRef() {
return MutableArrayRef<MappableComponent>(
static_cast<T *>(this)
->template getTrailingObjects<MappableComponent>(),
NumComponents);
}
/// \brief Get the components that are in the trailing objects of the class.
ArrayRef<MappableComponent> getComponentsRef() const {
return ArrayRef<MappableComponent>(
static_cast<const T *>(this)
->template getTrailingObjects<MappableComponent>(),
NumComponents);
}
/// \brief Set the components that are in the trailing objects of the class.
/// This requires the list sizes so that it can also fill the original
/// expressions, which are the first component of each list.
void setComponents(ArrayRef<MappableComponent> Components,
ArrayRef<unsigned> CLSs) {
assert(Components.size() == NumComponents &&
"Unexpected amount of component lists.");
assert(CLSs.size() == NumComponentLists &&
"Unexpected amount of list sizes.");
std::copy(Components.begin(), Components.end(), getComponentsRef().begin());
}
/// \brief Fill the clause information from the list of declarations and
/// associated component lists.
void setClauseInfo(ArrayRef<ValueDecl *> Declarations,
MappableExprComponentListsRef ComponentLists) {
// Perform some checks to make sure the data sizes are consistent with the
// information available when the clause was created.
assert(getUniqueDeclarationsTotalNumber(Declarations) ==
NumUniqueDeclarations &&
"Unexpected number of mappable expression info entries!");
assert(getComponentsTotalNumber(ComponentLists) == NumComponents &&
"Unexpected total number of components!");
assert(Declarations.size() == ComponentLists.size() &&
"Declaration and component lists size is not consistent!");
assert(Declarations.size() == NumComponentLists &&
"Unexpected declaration and component lists size!");
// Organize the components by declaration and retrieve the original
// expression. Original expressions are always the first component of the
// mappable component list.
llvm::DenseMap<ValueDecl *, SmallVector<MappableExprComponentListRef, 8>>
ComponentListMap;
{
auto CI = ComponentLists.begin();
for (auto DI = Declarations.begin(), DE = Declarations.end(); DI != DE;
++DI, ++CI) {
assert(!CI->empty() && "Invalid component list!");
ComponentListMap[*DI].push_back(*CI);
}
}
// Iterators of the target storage.
auto UniqueDeclarations = getUniqueDeclsRef();
auto UDI = UniqueDeclarations.begin();
auto DeclNumLists = getDeclNumListsRef();
auto DNLI = DeclNumLists.begin();
auto ComponentListSizes = getComponentListSizesRef();
auto CLSI = ComponentListSizes.begin();
auto Components = getComponentsRef();
auto CI = Components.begin();
// Variable to compute the accumulation of the number of components.
unsigned PrevSize = 0u;
// Scan all the declarations and associated component lists.
for (auto &M : ComponentListMap) {
// The declaration.
auto *D = M.first;
// The component lists.
auto CL = M.second;
// Initialize the entry.
*UDI = D;
++UDI;
*DNLI = CL.size();
++DNLI;
// Obtain the cumulative sizes and concatenate all the components in the
// reserved storage.
for (auto C : CL) {
// Accumulate with the previous size.
PrevSize += C.size();
// Save the size.
*CLSI = PrevSize;
++CLSI;
// Append components after the current components iterator.
CI = std::copy(C.begin(), C.end(), CI);
}
}
}
/// \brief Build a clause for \a NumUniqueDeclarations declarations, \a
/// NumComponentLists total component lists, and \a NumComponents total
/// components.
///
/// \param K Kind of the clause.
/// \param StartLoc Starting location of the clause (the clause keyword).
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param NumVars Number of expressions listed in the clause.
/// \param NumUniqueDeclarations Number of unique base declarations in this
/// clause.
/// \param NumComponentLists Number of component lists in this clause - one
/// list for each expression in the clause.
/// \param NumComponents Total number of expression components in the clause.
///
OMPMappableExprListClause(OpenMPClauseKind K, SourceLocation StartLoc,
SourceLocation LParenLoc, SourceLocation EndLoc,
unsigned NumVars, unsigned NumUniqueDeclarations,
unsigned NumComponentLists, unsigned NumComponents)
: OMPVarListClause<T>(K, StartLoc, LParenLoc, EndLoc, NumVars),
NumUniqueDeclarations(NumUniqueDeclarations),
NumComponentLists(NumComponentLists), NumComponents(NumComponents) {}
public:
/// \brief Return the number of unique base declarations in this clause.
unsigned getUniqueDeclarationsNum() const { return NumUniqueDeclarations; }
/// \brief Return the number of lists derived from the clause expressions.
unsigned getTotalComponentListNum() const { return NumComponentLists; }
/// \brief Return the total number of components in all lists derived from the
/// clause.
unsigned getTotalComponentsNum() const { return NumComponents; }
/// \brief Iterator that browse the components by lists. It also allows
/// browsing components of a single declaration.
class const_component_lists_iterator
: public llvm::iterator_adaptor_base<
const_component_lists_iterator,
MappableExprComponentListRef::const_iterator,
std::forward_iterator_tag, MappableComponent, ptrdiff_t,
MappableComponent, MappableComponent> {
// The declaration the iterator currently refers to.
ArrayRef<ValueDecl *>::iterator DeclCur;
// The list number associated with the current declaration.
ArrayRef<unsigned>::iterator NumListsCur;
// Remaining lists for the current declaration.
unsigned RemainingLists;
// The cumulative size of the previous list, or zero if there is no previous
// list.
unsigned PrevListSize;
// The cumulative sizes of the current list - it will delimit the remaining
// range of interest.
ArrayRef<unsigned>::const_iterator ListSizeCur;
ArrayRef<unsigned>::const_iterator ListSizeEnd;
// Iterator to the end of the components storage.
MappableExprComponentListRef::const_iterator End;
public:
/// \brief Construct an iterator that scans all lists.
explicit const_component_lists_iterator(
ArrayRef<ValueDecl *> UniqueDecls, ArrayRef<unsigned> DeclsListNum,
ArrayRef<unsigned> CumulativeListSizes,
MappableExprComponentListRef Components)
: const_component_lists_iterator::iterator_adaptor_base(
Components.begin()),
DeclCur(UniqueDecls.begin()), NumListsCur(DeclsListNum.begin()),
RemainingLists(0u), PrevListSize(0u),
ListSizeCur(CumulativeListSizes.begin()),
ListSizeEnd(CumulativeListSizes.end()), End(Components.end()) {
assert(UniqueDecls.size() == DeclsListNum.size() &&
"Inconsistent number of declarations and list sizes!");
if (!DeclsListNum.empty())
RemainingLists = *NumListsCur;
}
/// \brief Construct an iterator that scan lists for a given declaration \a
/// Declaration.
explicit const_component_lists_iterator(
const ValueDecl *Declaration, ArrayRef<ValueDecl *> UniqueDecls,
ArrayRef<unsigned> DeclsListNum, ArrayRef<unsigned> CumulativeListSizes,
MappableExprComponentListRef Components)
: const_component_lists_iterator(UniqueDecls, DeclsListNum,
CumulativeListSizes, Components) {
// Look for the desired declaration. While we are looking for it, we
// update the state so that we know the component where a given list
// starts.
for (; DeclCur != UniqueDecls.end(); ++DeclCur, ++NumListsCur) {
if (*DeclCur == Declaration)
break;
assert(*NumListsCur > 0 && "No lists associated with declaration??");
// Skip the lists associated with the current declaration, but save the
// last list size that was skipped.
std::advance(ListSizeCur, *NumListsCur - 1);
PrevListSize = *ListSizeCur;
++ListSizeCur;
}
// If we didn't find any declaration, advance the iterator to after the
// last component and set remaining lists to zero.
if (ListSizeCur == CumulativeListSizes.end()) {
this->I = End;
RemainingLists = 0u;
return;
}
// Set the remaining lists with the total number of lists of the current
// declaration.
RemainingLists = *NumListsCur;
// Adjust the list size end iterator to the end of the relevant range.
ListSizeEnd = ListSizeCur;
std::advance(ListSizeEnd, RemainingLists);
// Given that the list sizes are cumulative, the index of the component
// that start the list is the size of the previous list.
std::advance(this->I, PrevListSize);
}
// Return the array with the current list. The sizes are cumulative, so the
// array size is the difference between the current size and previous one.
std::pair<const ValueDecl *, MappableExprComponentListRef>
operator*() const {
assert(ListSizeCur != ListSizeEnd && "Invalid iterator!");
return std::make_pair(
*DeclCur,
MappableExprComponentListRef(&*this->I, *ListSizeCur - PrevListSize));
}
std::pair<const ValueDecl *, MappableExprComponentListRef>
operator->() const {
return **this;
}
// Skip the components of the current list.
const_component_lists_iterator &operator++() {
assert(ListSizeCur != ListSizeEnd && RemainingLists &&
"Invalid iterator!");
// If we don't have more lists just skip all the components. Otherwise,
// advance the iterator by the number of components in the current list.
if (std::next(ListSizeCur) == ListSizeEnd) {
this->I = End;
RemainingLists = 0;
} else {
std::advance(this->I, *ListSizeCur - PrevListSize);
PrevListSize = *ListSizeCur;
// We are done with a declaration, move to the next one.
if (!(--RemainingLists)) {
++DeclCur;
++NumListsCur;
RemainingLists = *NumListsCur;
assert(RemainingLists && "No lists in the following declaration??");
}
}
++ListSizeCur;
return *this;
}
};
typedef llvm::iterator_range<const_component_lists_iterator>
const_component_lists_range;
/// \brief Iterators for all component lists.
const_component_lists_iterator component_lists_begin() const {
return const_component_lists_iterator(
getUniqueDeclsRef(), getDeclNumListsRef(), getComponentListSizesRef(),
getComponentsRef());
}
const_component_lists_iterator component_lists_end() const {
return const_component_lists_iterator(
ArrayRef<ValueDecl *>(), ArrayRef<unsigned>(), ArrayRef<unsigned>(),
MappableExprComponentListRef(getComponentsRef().end(),
getComponentsRef().end()));
}
const_component_lists_range component_lists() const {
return {component_lists_begin(), component_lists_end()};
}
/// \brief Iterators for component lists associated with the provided
/// declaration.
const_component_lists_iterator
decl_component_lists_begin(const ValueDecl *VD) const {
return const_component_lists_iterator(
VD, getUniqueDeclsRef(), getDeclNumListsRef(),
getComponentListSizesRef(), getComponentsRef());
}
const_component_lists_iterator decl_component_lists_end() const {
return component_lists_end();
}
const_component_lists_range decl_component_lists(const ValueDecl *VD) const {
return {decl_component_lists_begin(VD), decl_component_lists_end()};
}
/// Iterators to access all the declarations, number of lists, list sizes, and
/// components.
typedef ArrayRef<ValueDecl *>::iterator const_all_decls_iterator;
typedef llvm::iterator_range<const_all_decls_iterator> const_all_decls_range;
const_all_decls_range all_decls() const {
auto A = getUniqueDeclsRef();
return const_all_decls_range(A.begin(), A.end());
}
typedef ArrayRef<unsigned>::iterator const_all_num_lists_iterator;
typedef llvm::iterator_range<const_all_num_lists_iterator>
const_all_num_lists_range;
const_all_num_lists_range all_num_lists() const {
auto A = getDeclNumListsRef();
return const_all_num_lists_range(A.begin(), A.end());
}
typedef ArrayRef<unsigned>::iterator const_all_lists_sizes_iterator;
typedef llvm::iterator_range<const_all_lists_sizes_iterator>
const_all_lists_sizes_range;
const_all_lists_sizes_range all_lists_sizes() const {
auto A = getComponentListSizesRef();
return const_all_lists_sizes_range(A.begin(), A.end());
}
typedef ArrayRef<MappableComponent>::iterator const_all_components_iterator;
typedef llvm::iterator_range<const_all_components_iterator>
const_all_components_range;
const_all_components_range all_components() const {
auto A = getComponentsRef();
return const_all_components_range(A.begin(), A.end());
}
};
/// \brief This represents clause 'map' in the '#pragma omp ...'
/// directives.
///
/// \code
/// #pragma omp target map(a,b)
/// \endcode
/// In this example directive '#pragma omp target' has clause 'map'
/// with the variables 'a' and 'b'.
///
class OMPMapClause final : public OMPMappableExprListClause<OMPMapClause>,
private llvm::TrailingObjects<
OMPMapClause, Expr *, ValueDecl *, unsigned,
OMPClauseMappableExprCommon::MappableComponent> {
friend TrailingObjects;
friend OMPVarListClause;
friend OMPMappableExprListClause;
friend class OMPClauseReader;
/// Define the sizes of each trailing object array except the last one. This
/// is required for TrailingObjects to work properly.
size_t numTrailingObjects(OverloadToken<Expr *>) const {
return varlist_size();
}
size_t numTrailingObjects(OverloadToken<ValueDecl *>) const {
return getUniqueDeclarationsNum();
}
size_t numTrailingObjects(OverloadToken<unsigned>) const {
return getUniqueDeclarationsNum() + getTotalComponentListNum();
}
/// \brief Map type modifier for the 'map' clause.
OpenMPMapClauseKind MapTypeModifier;
/// \brief Map type for the 'map' clause.
OpenMPMapClauseKind MapType;
/// \brief Is this an implicit map type or not.
bool MapTypeIsImplicit;
/// \brief Location of the map type.
SourceLocation MapLoc;
/// \brief Colon location.
SourceLocation ColonLoc;
/// \brief Set type modifier for the clause.
///
/// \param T Type Modifier for the clause.
///
void setMapTypeModifier(OpenMPMapClauseKind T) { MapTypeModifier = T; }
/// \brief Set type for the clause.
///
/// \param T Type for the clause.
///
void setMapType(OpenMPMapClauseKind T) { MapType = T; }
/// \brief Set type location.
///
/// \param TLoc Type location.
///
void setMapLoc(SourceLocation TLoc) { MapLoc = TLoc; }
/// \brief Set colon location.
void setColonLoc(SourceLocation Loc) { ColonLoc = Loc; }
/// \brief Build a clause for \a NumVars listed expressions, \a
/// NumUniqueDeclarations declarations, \a NumComponentLists total component
/// lists, and \a NumComponents total expression components.
///
/// \param MapTypeModifier Map type modifier.
/// \param MapType Map type.
/// \param MapTypeIsImplicit Map type is inferred implicitly.
/// \param MapLoc Location of the map type.
/// \param StartLoc Starting location of the clause.
/// \param EndLoc Ending location of the clause.
/// \param NumVars Number of expressions listed in this clause.
/// \param NumUniqueDeclarations Number of unique base declarations in this
/// clause.
/// \param NumComponentLists Number of component lists in this clause.
/// \param NumComponents Total number of expression components in the clause.
///
explicit OMPMapClause(OpenMPMapClauseKind MapTypeModifier,
OpenMPMapClauseKind MapType, bool MapTypeIsImplicit,
SourceLocation MapLoc, SourceLocation StartLoc,
SourceLocation LParenLoc, SourceLocation EndLoc,
unsigned NumVars, unsigned NumUniqueDeclarations,
unsigned NumComponentLists, unsigned NumComponents)
: OMPMappableExprListClause(OMPC_map, StartLoc, LParenLoc, EndLoc,
NumVars, NumUniqueDeclarations,
NumComponentLists, NumComponents),
MapTypeModifier(MapTypeModifier), MapType(MapType),
MapTypeIsImplicit(MapTypeIsImplicit), MapLoc(MapLoc) {}
/// \brief Build an empty clause.
///
/// \param NumVars Number of expressions listed in this clause.
/// \param NumUniqueDeclarations Number of unique base declarations in this
/// clause.
/// \param NumComponentLists Number of component lists in this clause.
/// \param NumComponents Total number of expression components in the clause.
///
explicit OMPMapClause(unsigned NumVars, unsigned NumUniqueDeclarations,
unsigned NumComponentLists, unsigned NumComponents)
: OMPMappableExprListClause(
OMPC_map, SourceLocation(), SourceLocation(), SourceLocation(),
NumVars, NumUniqueDeclarations, NumComponentLists, NumComponents),
MapTypeModifier(OMPC_MAP_unknown), MapType(OMPC_MAP_unknown),
MapTypeIsImplicit(false), MapLoc() {}
public:
/// \brief Creates clause with a list of variables \a VL.
///
/// \param C AST context.
/// \param StartLoc Starting location of the clause.
/// \param EndLoc Ending location of the clause.
/// \param Vars The original expression used in the clause.
/// \param Declarations Declarations used in the clause.
/// \param ComponentLists Component lists used in the clause.
/// \param TypeModifier Map type modifier.
/// \param Type Map type.
/// \param TypeIsImplicit Map type is inferred implicitly.
/// \param TypeLoc Location of the map type.
///
static OMPMapClause *Create(const ASTContext &C, SourceLocation StartLoc,
SourceLocation LParenLoc, SourceLocation EndLoc,
ArrayRef<Expr *> Vars,
ArrayRef<ValueDecl *> Declarations,
MappableExprComponentListsRef ComponentLists,
OpenMPMapClauseKind TypeModifier,
OpenMPMapClauseKind Type, bool TypeIsImplicit,
SourceLocation TypeLoc);
/// \brief Creates an empty clause with the place for for \a NumVars original
/// expressions, \a NumUniqueDeclarations declarations, \NumComponentLists
/// lists, and \a NumComponents expression components.
///
/// \param C AST context.
/// \param NumVars Number of expressions listed in the clause.
/// \param NumUniqueDeclarations Number of unique base declarations in this
/// clause.
/// \param NumComponentLists Number of unique base declarations in this
/// clause.
/// \param NumComponents Total number of expression components in the clause.
///
static OMPMapClause *CreateEmpty(const ASTContext &C, unsigned NumVars,
unsigned NumUniqueDeclarations,
unsigned NumComponentLists,
unsigned NumComponents);
/// \brief Fetches mapping kind for the clause.
OpenMPMapClauseKind getMapType() const LLVM_READONLY { return MapType; }
/// \brief Is this an implicit map type?
/// We have to capture 'IsMapTypeImplicit' from the parser for more
/// informative error messages. It helps distinguish map(r) from
/// map(tofrom: r), which is important to print more helpful error
/// messages for some target directives.
bool isImplicitMapType() const LLVM_READONLY { return MapTypeIsImplicit; }
/// \brief Fetches the map type modifier for the clause.
OpenMPMapClauseKind getMapTypeModifier() const LLVM_READONLY {
return MapTypeModifier;
}
/// \brief Fetches location of clause mapping kind.
SourceLocation getMapLoc() const LLVM_READONLY { return MapLoc; }
/// \brief Get colon location.
SourceLocation getColonLoc() const { return ColonLoc; }
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_map;
}
child_range children() {
return child_range(
reinterpret_cast<Stmt **>(varlist_begin()),
reinterpret_cast<Stmt **>(varlist_end()));
}
};
/// \brief This represents 'num_teams' clause in the '#pragma omp ...'
/// directive.
///
/// \code
/// #pragma omp teams num_teams(n)
/// \endcode
/// In this example directive '#pragma omp teams' has clause 'num_teams'
/// with single expression 'n'.
///
class OMPNumTeamsClause : public OMPClause, public OMPClauseWithPreInit {
friend class OMPClauseReader;
/// \brief Location of '('.
SourceLocation LParenLoc;
/// \brief NumTeams number.
Stmt *NumTeams;
/// \brief Set the NumTeams number.
///
/// \param E NumTeams number.
///
void setNumTeams(Expr *E) { NumTeams = E; }
public:
/// \brief Build 'num_teams' clause.
///
/// \param E Expression associated with this clause.
/// \param HelperE Helper Expression associated with this clause.
/// \param CaptureRegion Innermost OpenMP region where expressions in this
/// clause must be captured.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
///
OMPNumTeamsClause(Expr *E, Stmt *HelperE, OpenMPDirectiveKind CaptureRegion,
SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc)
: OMPClause(OMPC_num_teams, StartLoc, EndLoc), OMPClauseWithPreInit(this),
LParenLoc(LParenLoc), NumTeams(E) {
setPreInitStmt(HelperE, CaptureRegion);
}
/// \brief Build an empty clause.
///
OMPNumTeamsClause()
: OMPClause(OMPC_num_teams, SourceLocation(), SourceLocation()),
OMPClauseWithPreInit(this), LParenLoc(SourceLocation()),
NumTeams(nullptr) {}
/// \brief Sets the location of '('.
void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
/// \brief Returns the location of '('.
SourceLocation getLParenLoc() const { return LParenLoc; }
/// \brief Return NumTeams number.
Expr *getNumTeams() { return cast<Expr>(NumTeams); }
/// \brief Return NumTeams number.
Expr *getNumTeams() const { return cast<Expr>(NumTeams); }
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_num_teams;
}
child_range children() { return child_range(&NumTeams, &NumTeams + 1); }
};
/// \brief This represents 'thread_limit' clause in the '#pragma omp ...'
/// directive.
///
/// \code
/// #pragma omp teams thread_limit(n)
/// \endcode
/// In this example directive '#pragma omp teams' has clause 'thread_limit'
/// with single expression 'n'.
///
class OMPThreadLimitClause : public OMPClause, public OMPClauseWithPreInit {
friend class OMPClauseReader;
/// \brief Location of '('.
SourceLocation LParenLoc;
/// \brief ThreadLimit number.
Stmt *ThreadLimit;
/// \brief Set the ThreadLimit number.
///
/// \param E ThreadLimit number.
///
void setThreadLimit(Expr *E) { ThreadLimit = E; }
public:
/// \brief Build 'thread_limit' clause.
///
/// \param E Expression associated with this clause.
/// \param HelperE Helper Expression associated with this clause.
/// \param CaptureRegion Innermost OpenMP region where expressions in this
/// clause must be captured.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
///
OMPThreadLimitClause(Expr *E, Stmt *HelperE,
OpenMPDirectiveKind CaptureRegion,
SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc)
: OMPClause(OMPC_thread_limit, StartLoc, EndLoc),
OMPClauseWithPreInit(this), LParenLoc(LParenLoc), ThreadLimit(E) {
setPreInitStmt(HelperE, CaptureRegion);
}
/// \brief Build an empty clause.
///
OMPThreadLimitClause()
: OMPClause(OMPC_thread_limit, SourceLocation(), SourceLocation()),
OMPClauseWithPreInit(this), LParenLoc(SourceLocation()),
ThreadLimit(nullptr) {}
/// \brief Sets the location of '('.
void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
/// \brief Returns the location of '('.
SourceLocation getLParenLoc() const { return LParenLoc; }
/// \brief Return ThreadLimit number.
Expr *getThreadLimit() { return cast<Expr>(ThreadLimit); }
/// \brief Return ThreadLimit number.
Expr *getThreadLimit() const { return cast<Expr>(ThreadLimit); }
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_thread_limit;
}
child_range children() { return child_range(&ThreadLimit, &ThreadLimit + 1); }
};
/// \brief This represents 'priority' clause in the '#pragma omp ...'
/// directive.
///
/// \code
/// #pragma omp task priority(n)
/// \endcode
/// In this example directive '#pragma omp teams' has clause 'priority' with
/// single expression 'n'.
///
class OMPPriorityClause : public OMPClause {
friend class OMPClauseReader;
/// \brief Location of '('.
SourceLocation LParenLoc;
/// \brief Priority number.
Stmt *Priority;
/// \brief Set the Priority number.
///
/// \param E Priority number.
///
void setPriority(Expr *E) { Priority = E; }
public:
/// \brief Build 'priority' clause.
///
/// \param E Expression associated with this clause.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
///
OMPPriorityClause(Expr *E, SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc)
: OMPClause(OMPC_priority, StartLoc, EndLoc), LParenLoc(LParenLoc),
Priority(E) {}
/// \brief Build an empty clause.
///
OMPPriorityClause()
: OMPClause(OMPC_priority, SourceLocation(), SourceLocation()),
LParenLoc(SourceLocation()), Priority(nullptr) {}
/// \brief Sets the location of '('.
void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
/// \brief Returns the location of '('.
SourceLocation getLParenLoc() const { return LParenLoc; }
/// \brief Return Priority number.
Expr *getPriority() { return cast<Expr>(Priority); }
/// \brief Return Priority number.
Expr *getPriority() const { return cast<Expr>(Priority); }
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_priority;
}
child_range children() { return child_range(&Priority, &Priority + 1); }
};
/// \brief This represents 'grainsize' clause in the '#pragma omp ...'
/// directive.
///
/// \code
/// #pragma omp taskloop grainsize(4)
/// \endcode
/// In this example directive '#pragma omp taskloop' has clause 'grainsize'
/// with single expression '4'.
///
class OMPGrainsizeClause : public OMPClause {
friend class OMPClauseReader;
/// \brief Location of '('.
SourceLocation LParenLoc;
/// \brief Safe iteration space distance.
Stmt *Grainsize;
/// \brief Set safelen.
void setGrainsize(Expr *Size) { Grainsize = Size; }
public:
/// \brief Build 'grainsize' clause.
///
/// \param Size Expression associated with this clause.
/// \param StartLoc Starting location of the clause.
/// \param EndLoc Ending location of the clause.
///
OMPGrainsizeClause(Expr *Size, SourceLocation StartLoc,
SourceLocation LParenLoc, SourceLocation EndLoc)
: OMPClause(OMPC_grainsize, StartLoc, EndLoc), LParenLoc(LParenLoc),
Grainsize(Size) {}
/// \brief Build an empty clause.
///
explicit OMPGrainsizeClause()
: OMPClause(OMPC_grainsize, SourceLocation(), SourceLocation()),
LParenLoc(SourceLocation()), Grainsize(nullptr) {}
/// \brief Sets the location of '('.
void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
/// \brief Returns the location of '('.
SourceLocation getLParenLoc() const { return LParenLoc; }
/// \brief Return safe iteration space distance.
Expr *getGrainsize() const { return cast_or_null<Expr>(Grainsize); }
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_grainsize;
}
child_range children() { return child_range(&Grainsize, &Grainsize + 1); }
};
/// \brief This represents 'nogroup' clause in the '#pragma omp ...' directive.
///
/// \code
/// #pragma omp taskloop nogroup
/// \endcode
/// In this example directive '#pragma omp taskloop' has 'nogroup' clause.
///
class OMPNogroupClause : public OMPClause {
public:
/// \brief Build 'nogroup' clause.
///
/// \param StartLoc Starting location of the clause.
/// \param EndLoc Ending location of the clause.
///
OMPNogroupClause(SourceLocation StartLoc, SourceLocation EndLoc)
: OMPClause(OMPC_nogroup, StartLoc, EndLoc) {}
/// \brief Build an empty clause.
///
OMPNogroupClause()
: OMPClause(OMPC_nogroup, SourceLocation(), SourceLocation()) {}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_nogroup;
}
child_range children() {
return child_range(child_iterator(), child_iterator());
}
};
/// \brief This represents 'num_tasks' clause in the '#pragma omp ...'
/// directive.
///
/// \code
/// #pragma omp taskloop num_tasks(4)
/// \endcode
/// In this example directive '#pragma omp taskloop' has clause 'num_tasks'
/// with single expression '4'.
///
class OMPNumTasksClause : public OMPClause {
friend class OMPClauseReader;
/// \brief Location of '('.
SourceLocation LParenLoc;
/// \brief Safe iteration space distance.
Stmt *NumTasks;
/// \brief Set safelen.
void setNumTasks(Expr *Size) { NumTasks = Size; }
public:
/// \brief Build 'num_tasks' clause.
///
/// \param Size Expression associated with this clause.
/// \param StartLoc Starting location of the clause.
/// \param EndLoc Ending location of the clause.
///
OMPNumTasksClause(Expr *Size, SourceLocation StartLoc,
SourceLocation LParenLoc, SourceLocation EndLoc)
: OMPClause(OMPC_num_tasks, StartLoc, EndLoc), LParenLoc(LParenLoc),
NumTasks(Size) {}
/// \brief Build an empty clause.
///
explicit OMPNumTasksClause()
: OMPClause(OMPC_num_tasks, SourceLocation(), SourceLocation()),
LParenLoc(SourceLocation()), NumTasks(nullptr) {}
/// \brief Sets the location of '('.
void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
/// \brief Returns the location of '('.
SourceLocation getLParenLoc() const { return LParenLoc; }
/// \brief Return safe iteration space distance.
Expr *getNumTasks() const { return cast_or_null<Expr>(NumTasks); }
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_num_tasks;
}
child_range children() { return child_range(&NumTasks, &NumTasks + 1); }
};
/// \brief This represents 'hint' clause in the '#pragma omp ...' directive.
///
/// \code
/// #pragma omp critical (name) hint(6)
/// \endcode
/// In this example directive '#pragma omp critical' has name 'name' and clause
/// 'hint' with argument '6'.
///
class OMPHintClause : public OMPClause {
friend class OMPClauseReader;
/// \brief Location of '('.
SourceLocation LParenLoc;
/// \brief Hint expression of the 'hint' clause.
Stmt *Hint;
/// \brief Set hint expression.
///
void setHint(Expr *H) { Hint = H; }
public:
/// \brief Build 'hint' clause with expression \a Hint.
///
/// \param Hint Hint expression.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
///
OMPHintClause(Expr *Hint, SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc)
: OMPClause(OMPC_hint, StartLoc, EndLoc), LParenLoc(LParenLoc),
Hint(Hint) {}
/// \brief Build an empty clause.
///
OMPHintClause()
: OMPClause(OMPC_hint, SourceLocation(), SourceLocation()),
LParenLoc(SourceLocation()), Hint(nullptr) {}
/// \brief Sets the location of '('.
void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
/// \brief Returns the location of '('.
SourceLocation getLParenLoc() const { return LParenLoc; }
/// \brief Returns number of threads.
Expr *getHint() const { return cast_or_null<Expr>(Hint); }
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_hint;
}
child_range children() { return child_range(&Hint, &Hint + 1); }
};
/// \brief This represents 'dist_schedule' clause in the '#pragma omp ...'
/// directive.
///
/// \code
/// #pragma omp distribute dist_schedule(static, 3)
/// \endcode
/// In this example directive '#pragma omp distribute' has 'dist_schedule'
/// clause with arguments 'static' and '3'.
///
class OMPDistScheduleClause : public OMPClause, public OMPClauseWithPreInit {
friend class OMPClauseReader;
/// \brief Location of '('.
SourceLocation LParenLoc;
/// \brief A kind of the 'schedule' clause.
OpenMPDistScheduleClauseKind Kind;
/// \brief Start location of the schedule kind in source code.
SourceLocation KindLoc;
/// \brief Location of ',' (if any).
SourceLocation CommaLoc;
/// \brief Chunk size.
Expr *ChunkSize;
/// \brief Set schedule kind.
///
/// \param K Schedule kind.
///
void setDistScheduleKind(OpenMPDistScheduleClauseKind K) { Kind = K; }
/// \brief Sets the location of '('.
///
/// \param Loc Location of '('.
///
void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
/// \brief Set schedule kind start location.
///
/// \param KLoc Schedule kind location.
///
void setDistScheduleKindLoc(SourceLocation KLoc) { KindLoc = KLoc; }
/// \brief Set location of ','.
///
/// \param Loc Location of ','.
///
void setCommaLoc(SourceLocation Loc) { CommaLoc = Loc; }
/// \brief Set chunk size.
///
/// \param E Chunk size.
///
void setChunkSize(Expr *E) { ChunkSize = E; }
public:
/// \brief Build 'dist_schedule' clause with schedule kind \a Kind and chunk
/// size expression \a ChunkSize.
///
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param KLoc Starting location of the argument.
/// \param CommaLoc Location of ','.
/// \param EndLoc Ending location of the clause.
/// \param Kind DistSchedule kind.
/// \param ChunkSize Chunk size.
/// \param HelperChunkSize Helper chunk size for combined directives.
///
OMPDistScheduleClause(SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation KLoc, SourceLocation CommaLoc,
SourceLocation EndLoc,
OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize,
Stmt *HelperChunkSize)
: OMPClause(OMPC_dist_schedule, StartLoc, EndLoc),
OMPClauseWithPreInit(this), LParenLoc(LParenLoc), Kind(Kind),
KindLoc(KLoc), CommaLoc(CommaLoc), ChunkSize(ChunkSize) {
setPreInitStmt(HelperChunkSize);
}
/// \brief Build an empty clause.
///
explicit OMPDistScheduleClause()
: OMPClause(OMPC_dist_schedule, SourceLocation(), SourceLocation()),
OMPClauseWithPreInit(this), Kind(OMPC_DIST_SCHEDULE_unknown),
ChunkSize(nullptr) {}
/// \brief Get kind of the clause.
///
OpenMPDistScheduleClauseKind getDistScheduleKind() const { return Kind; }
/// \brief Get location of '('.
///
SourceLocation getLParenLoc() { return LParenLoc; }
/// \brief Get kind location.
///
SourceLocation getDistScheduleKindLoc() { return KindLoc; }
/// \brief Get location of ','.
///
SourceLocation getCommaLoc() { return CommaLoc; }
/// \brief Get chunk size.
///
Expr *getChunkSize() { return ChunkSize; }
/// \brief Get chunk size.
///
const Expr *getChunkSize() const { return ChunkSize; }
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_dist_schedule;
}
child_range children() {
return child_range(reinterpret_cast<Stmt **>(&ChunkSize),
reinterpret_cast<Stmt **>(&ChunkSize) + 1);
}
};
/// \brief This represents 'defaultmap' clause in the '#pragma omp ...' directive.
///
/// \code
/// #pragma omp target defaultmap(tofrom: scalar)
/// \endcode
/// In this example directive '#pragma omp target' has 'defaultmap' clause of kind
/// 'scalar' with modifier 'tofrom'.
///
class OMPDefaultmapClause : public OMPClause {
friend class OMPClauseReader;
/// \brief Location of '('.
SourceLocation LParenLoc;
/// \brief Modifiers for 'defaultmap' clause.
OpenMPDefaultmapClauseModifier Modifier;
/// \brief Locations of modifiers.
SourceLocation ModifierLoc;
/// \brief A kind of the 'defaultmap' clause.
OpenMPDefaultmapClauseKind Kind;
/// \brief Start location of the defaultmap kind in source code.
SourceLocation KindLoc;
/// \brief Set defaultmap kind.
///
/// \param K Defaultmap kind.
///
void setDefaultmapKind(OpenMPDefaultmapClauseKind K) { Kind = K; }
/// \brief Set the defaultmap modifier.
///
/// \param M Defaultmap modifier.
///
void setDefaultmapModifier(OpenMPDefaultmapClauseModifier M) {
Modifier = M;
}
/// \brief Set location of the defaultmap modifier.
///
void setDefaultmapModifierLoc(SourceLocation Loc) {
ModifierLoc = Loc;
}
/// \brief Sets the location of '('.
///
/// \param Loc Location of '('.
///
void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
/// \brief Set defaultmap kind start location.
///
/// \param KLoc Defaultmap kind location.
///
void setDefaultmapKindLoc(SourceLocation KLoc) { KindLoc = KLoc; }
public:
/// \brief Build 'defaultmap' clause with defaultmap kind \a Kind
///
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param KLoc Starting location of the argument.
/// \param EndLoc Ending location of the clause.
/// \param Kind Defaultmap kind.
/// \param M The modifier applied to 'defaultmap' clause.
/// \param MLoc Location of the modifier
///
OMPDefaultmapClause(SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation MLoc, SourceLocation KLoc,
SourceLocation EndLoc, OpenMPDefaultmapClauseKind Kind,
OpenMPDefaultmapClauseModifier M)
: OMPClause(OMPC_defaultmap, StartLoc, EndLoc), LParenLoc(LParenLoc),
Modifier(M), ModifierLoc(MLoc), Kind(Kind), KindLoc(KLoc) {}
/// \brief Build an empty clause.
///
explicit OMPDefaultmapClause()
: OMPClause(OMPC_defaultmap, SourceLocation(), SourceLocation()),
Modifier(OMPC_DEFAULTMAP_MODIFIER_unknown),
Kind(OMPC_DEFAULTMAP_unknown) {}
/// \brief Get kind of the clause.
///
OpenMPDefaultmapClauseKind getDefaultmapKind() const { return Kind; }
/// \brief Get the modifier of the clause.
///
OpenMPDefaultmapClauseModifier getDefaultmapModifier() const {
return Modifier;
}
/// \brief Get location of '('.
///
SourceLocation getLParenLoc() { return LParenLoc; }
/// \brief Get kind location.
///
SourceLocation getDefaultmapKindLoc() { return KindLoc; }
/// \brief Get the modifier location.
///
SourceLocation getDefaultmapModifierLoc() const {
return ModifierLoc;
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_defaultmap;
}
child_range children() {
return child_range(child_iterator(), child_iterator());
}
};
/// \brief This represents clause 'to' in the '#pragma omp ...'
/// directives.
///
/// \code
/// #pragma omp target update to(a,b)
/// \endcode
/// In this example directive '#pragma omp target update' has clause 'to'
/// with the variables 'a' and 'b'.
///
class OMPToClause final : public OMPMappableExprListClause<OMPToClause>,
private llvm::TrailingObjects<
OMPToClause, Expr *, ValueDecl *, unsigned,
OMPClauseMappableExprCommon::MappableComponent> {
friend TrailingObjects;
friend OMPVarListClause;
friend OMPMappableExprListClause;
friend class OMPClauseReader;
/// Define the sizes of each trailing object array except the last one. This
/// is required for TrailingObjects to work properly.
size_t numTrailingObjects(OverloadToken<Expr *>) const {
return varlist_size();
}
size_t numTrailingObjects(OverloadToken<ValueDecl *>) const {
return getUniqueDeclarationsNum();
}
size_t numTrailingObjects(OverloadToken<unsigned>) const {
return getUniqueDeclarationsNum() + getTotalComponentListNum();
}
/// \brief Build clause with number of variables \a NumVars.
///
/// \param StartLoc Starting location of the clause.
/// \param EndLoc Ending location of the clause.
/// \param NumVars Number of expressions listed in this clause.
/// \param NumUniqueDeclarations Number of unique base declarations in this
/// clause.
/// \param NumComponentLists Number of component lists in this clause.
/// \param NumComponents Total number of expression components in the clause.
///
explicit OMPToClause(SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc, unsigned NumVars,
unsigned NumUniqueDeclarations,
unsigned NumComponentLists, unsigned NumComponents)
: OMPMappableExprListClause(OMPC_to, StartLoc, LParenLoc, EndLoc, NumVars,
NumUniqueDeclarations, NumComponentLists,
NumComponents) {}
/// \brief Build an empty clause.
///
/// \param NumVars Number of expressions listed in this clause.
/// \param NumUniqueDeclarations Number of unique base declarations in this
/// clause.
/// \param NumComponentLists Number of component lists in this clause.
/// \param NumComponents Total number of expression components in the clause.
///
explicit OMPToClause(unsigned NumVars, unsigned NumUniqueDeclarations,
unsigned NumComponentLists, unsigned NumComponents)
: OMPMappableExprListClause(
OMPC_to, SourceLocation(), SourceLocation(), SourceLocation(),
NumVars, NumUniqueDeclarations, NumComponentLists, NumComponents) {}
public:
/// \brief Creates clause with a list of variables \a Vars.
///
/// \param C AST context.
/// \param StartLoc Starting location of the clause.
/// \param EndLoc Ending location of the clause.
/// \param Vars The original expression used in the clause.
/// \param Declarations Declarations used in the clause.
/// \param ComponentLists Component lists used in the clause.
///
static OMPToClause *Create(const ASTContext &C, SourceLocation StartLoc,
SourceLocation LParenLoc, SourceLocation EndLoc,
ArrayRef<Expr *> Vars,
ArrayRef<ValueDecl *> Declarations,
MappableExprComponentListsRef ComponentLists);
/// \brief Creates an empty clause with the place for \a NumVars variables.
///
/// \param C AST context.
/// \param NumVars Number of expressions listed in the clause.
/// \param NumUniqueDeclarations Number of unique base declarations in this
/// clause.
/// \param NumComponentLists Number of unique base declarations in this
/// clause.
/// \param NumComponents Total number of expression components in the clause.
///
static OMPToClause *CreateEmpty(const ASTContext &C, unsigned NumVars,
unsigned NumUniqueDeclarations,
unsigned NumComponentLists,
unsigned NumComponents);
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_to;
}
child_range children() {
return child_range(reinterpret_cast<Stmt **>(varlist_begin()),
reinterpret_cast<Stmt **>(varlist_end()));
}
};
/// \brief This represents clause 'from' in the '#pragma omp ...'
/// directives.
///
/// \code
/// #pragma omp target update from(a,b)
/// \endcode
/// In this example directive '#pragma omp target update' has clause 'from'
/// with the variables 'a' and 'b'.
///
class OMPFromClause final
: public OMPMappableExprListClause<OMPFromClause>,
private llvm::TrailingObjects<
OMPFromClause, Expr *, ValueDecl *, unsigned,
OMPClauseMappableExprCommon::MappableComponent> {
friend TrailingObjects;
friend OMPVarListClause;
friend OMPMappableExprListClause;
friend class OMPClauseReader;
/// Define the sizes of each trailing object array except the last one. This
/// is required for TrailingObjects to work properly.
size_t numTrailingObjects(OverloadToken<Expr *>) const {
return varlist_size();
}
size_t numTrailingObjects(OverloadToken<ValueDecl *>) const {
return getUniqueDeclarationsNum();
}
size_t numTrailingObjects(OverloadToken<unsigned>) const {
return getUniqueDeclarationsNum() + getTotalComponentListNum();
}
/// \brief Build clause with number of variables \a NumVars.
///
/// \param StartLoc Starting location of the clause.
/// \param EndLoc Ending location of the clause.
/// \param NumVars Number of expressions listed in this clause.
/// \param NumUniqueDeclarations Number of unique base declarations in this
/// clause.
/// \param NumComponentLists Number of component lists in this clause.
/// \param NumComponents Total number of expression components in the clause.
///
explicit OMPFromClause(SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc, unsigned NumVars,
unsigned NumUniqueDeclarations,
unsigned NumComponentLists, unsigned NumComponents)
: OMPMappableExprListClause(OMPC_from, StartLoc, LParenLoc, EndLoc,
NumVars, NumUniqueDeclarations,
NumComponentLists, NumComponents) {}
/// \brief Build an empty clause.
///
/// \param NumVars Number of expressions listed in this clause.
/// \param NumUniqueDeclarations Number of unique base declarations in this
/// clause.
/// \param NumComponentLists Number of component lists in this clause.
/// \param NumComponents Total number of expression components in the clause.
///
explicit OMPFromClause(unsigned NumVars, unsigned NumUniqueDeclarations,
unsigned NumComponentLists, unsigned NumComponents)
: OMPMappableExprListClause(
OMPC_from, SourceLocation(), SourceLocation(), SourceLocation(),
NumVars, NumUniqueDeclarations, NumComponentLists, NumComponents) {}
public:
/// \brief Creates clause with a list of variables \a Vars.
///
/// \param C AST context.
/// \param StartLoc Starting location of the clause.
/// \param EndLoc Ending location of the clause.
/// \param Vars The original expression used in the clause.
/// \param Declarations Declarations used in the clause.
/// \param ComponentLists Component lists used in the clause.
///
static OMPFromClause *Create(const ASTContext &C, SourceLocation StartLoc,
SourceLocation LParenLoc, SourceLocation EndLoc,
ArrayRef<Expr *> Vars,
ArrayRef<ValueDecl *> Declarations,
MappableExprComponentListsRef ComponentLists);
/// \brief Creates an empty clause with the place for \a NumVars variables.
///
/// \param C AST context.
/// \param NumVars Number of expressions listed in the clause.
/// \param NumUniqueDeclarations Number of unique base declarations in this
/// clause.
/// \param NumComponentLists Number of unique base declarations in this
/// clause.
/// \param NumComponents Total number of expression components in the clause.
///
static OMPFromClause *CreateEmpty(const ASTContext &C, unsigned NumVars,
unsigned NumUniqueDeclarations,
unsigned NumComponentLists,
unsigned NumComponents);
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_from;
}
child_range children() {
return child_range(reinterpret_cast<Stmt **>(varlist_begin()),
reinterpret_cast<Stmt **>(varlist_end()));
}
};
/// This represents clause 'use_device_ptr' in the '#pragma omp ...'
/// directives.
///
/// \code
/// #pragma omp target data use_device_ptr(a,b)
/// \endcode
/// In this example directive '#pragma omp target data' has clause
/// 'use_device_ptr' with the variables 'a' and 'b'.
///
class OMPUseDevicePtrClause final
: public OMPMappableExprListClause<OMPUseDevicePtrClause>,
private llvm::TrailingObjects<
OMPUseDevicePtrClause, Expr *, ValueDecl *, unsigned,
OMPClauseMappableExprCommon::MappableComponent> {
friend TrailingObjects;
friend OMPVarListClause;
friend OMPMappableExprListClause;
friend class OMPClauseReader;
/// Define the sizes of each trailing object array except the last one. This
/// is required for TrailingObjects to work properly.
size_t numTrailingObjects(OverloadToken<Expr *>) const {
return 3 * varlist_size();
}
size_t numTrailingObjects(OverloadToken<ValueDecl *>) const {
return getUniqueDeclarationsNum();
}
size_t numTrailingObjects(OverloadToken<unsigned>) const {
return getUniqueDeclarationsNum() + getTotalComponentListNum();
}
/// Build clause with number of variables \a NumVars.
///
/// \param StartLoc Starting location of the clause.
/// \param EndLoc Ending location of the clause.
/// \param NumVars Number of expressions listed in this clause.
/// \param NumUniqueDeclarations Number of unique base declarations in this
/// clause.
/// \param NumComponentLists Number of component lists in this clause.
/// \param NumComponents Total number of expression components in the clause.
///
explicit OMPUseDevicePtrClause(SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc, unsigned NumVars,
unsigned NumUniqueDeclarations,
unsigned NumComponentLists,
unsigned NumComponents)
: OMPMappableExprListClause(OMPC_use_device_ptr, StartLoc, LParenLoc,
EndLoc, NumVars, NumUniqueDeclarations,
NumComponentLists, NumComponents) {}
/// Build an empty clause.
///
/// \param NumVars Number of expressions listed in this clause.
/// \param NumUniqueDeclarations Number of unique base declarations in this
/// clause.
/// \param NumComponentLists Number of component lists in this clause.
/// \param NumComponents Total number of expression components in the clause.
///
explicit OMPUseDevicePtrClause(unsigned NumVars,
unsigned NumUniqueDeclarations,
unsigned NumComponentLists,
unsigned NumComponents)
: OMPMappableExprListClause(OMPC_use_device_ptr, SourceLocation(),
SourceLocation(), SourceLocation(), NumVars,
NumUniqueDeclarations, NumComponentLists,
NumComponents) {}
/// Sets the list of references to private copies with initializers for new
/// private variables.
/// \param VL List of references.
void setPrivateCopies(ArrayRef<Expr *> VL);
/// Gets the list of references to private copies with initializers for new
/// private variables.
MutableArrayRef<Expr *> getPrivateCopies() {
return MutableArrayRef<Expr *>(varlist_end(), varlist_size());
}
ArrayRef<const Expr *> getPrivateCopies() const {
return llvm::makeArrayRef(varlist_end(), varlist_size());
}
/// Sets the list of references to initializer variables for new private
/// variables.
/// \param VL List of references.
void setInits(ArrayRef<Expr *> VL);
/// Gets the list of references to initializer variables for new private
/// variables.
MutableArrayRef<Expr *> getInits() {
return MutableArrayRef<Expr *>(getPrivateCopies().end(), varlist_size());
}
ArrayRef<const Expr *> getInits() const {
return llvm::makeArrayRef(getPrivateCopies().end(), varlist_size());
}
public:
/// Creates clause with a list of variables \a Vars.
///
/// \param C AST context.
/// \param StartLoc Starting location of the clause.
/// \param EndLoc Ending location of the clause.
/// \param Vars The original expression used in the clause.
/// \param PrivateVars Expressions referring to private copies.
/// \param Inits Expressions referring to private copy initializers.
/// \param Declarations Declarations used in the clause.
/// \param ComponentLists Component lists used in the clause.
///
static OMPUseDevicePtrClause *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc, ArrayRef<Expr *> Vars,
ArrayRef<Expr *> PrivateVars, ArrayRef<Expr *> Inits,
ArrayRef<ValueDecl *> Declarations,
MappableExprComponentListsRef ComponentLists);
/// Creates an empty clause with the place for \a NumVars variables.
///
/// \param C AST context.
/// \param NumVars Number of expressions listed in the clause.
/// \param NumUniqueDeclarations Number of unique base declarations in this
/// clause.
/// \param NumComponentLists Number of unique base declarations in this
/// clause.
/// \param NumComponents Total number of expression components in the clause.
///
static OMPUseDevicePtrClause *CreateEmpty(const ASTContext &C,
unsigned NumVars,
unsigned NumUniqueDeclarations,
unsigned NumComponentLists,
unsigned NumComponents);
typedef MutableArrayRef<Expr *>::iterator private_copies_iterator;
typedef ArrayRef<const Expr *>::iterator private_copies_const_iterator;
typedef llvm::iterator_range<private_copies_iterator> private_copies_range;
typedef llvm::iterator_range<private_copies_const_iterator>
private_copies_const_range;
private_copies_range private_copies() {
return private_copies_range(getPrivateCopies().begin(),
getPrivateCopies().end());
}
private_copies_const_range private_copies() const {
return private_copies_const_range(getPrivateCopies().begin(),
getPrivateCopies().end());
}
typedef MutableArrayRef<Expr *>::iterator inits_iterator;
typedef ArrayRef<const Expr *>::iterator inits_const_iterator;
typedef llvm::iterator_range<inits_iterator> inits_range;
typedef llvm::iterator_range<inits_const_iterator> inits_const_range;
inits_range inits() {
return inits_range(getInits().begin(), getInits().end());
}
inits_const_range inits() const {
return inits_const_range(getInits().begin(), getInits().end());
}
child_range children() {
return child_range(reinterpret_cast<Stmt **>(varlist_begin()),
reinterpret_cast<Stmt **>(varlist_end()));
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_use_device_ptr;
}
};
/// This represents clause 'is_device_ptr' in the '#pragma omp ...'
/// directives.
///
/// \code
/// #pragma omp target is_device_ptr(a,b)
/// \endcode
/// In this example directive '#pragma omp target' has clause
/// 'is_device_ptr' with the variables 'a' and 'b'.
///
class OMPIsDevicePtrClause final
: public OMPMappableExprListClause<OMPIsDevicePtrClause>,
private llvm::TrailingObjects<
OMPIsDevicePtrClause, Expr *, ValueDecl *, unsigned,
OMPClauseMappableExprCommon::MappableComponent> {
friend TrailingObjects;
friend OMPVarListClause;
friend OMPMappableExprListClause;
friend class OMPClauseReader;
/// Define the sizes of each trailing object array except the last one. This
/// is required for TrailingObjects to work properly.
size_t numTrailingObjects(OverloadToken<Expr *>) const {
return varlist_size();
}
size_t numTrailingObjects(OverloadToken<ValueDecl *>) const {
return getUniqueDeclarationsNum();
}
size_t numTrailingObjects(OverloadToken<unsigned>) const {
return getUniqueDeclarationsNum() + getTotalComponentListNum();
}
/// Build clause with number of variables \a NumVars.
///
/// \param StartLoc Starting location of the clause.
/// \param EndLoc Ending location of the clause.
/// \param NumVars Number of expressions listed in this clause.
/// \param NumUniqueDeclarations Number of unique base declarations in this
/// clause.
/// \param NumComponentLists Number of component lists in this clause.
/// \param NumComponents Total number of expression components in the clause.
///
explicit OMPIsDevicePtrClause(SourceLocation StartLoc,
SourceLocation LParenLoc, SourceLocation EndLoc,
unsigned NumVars,
unsigned NumUniqueDeclarations,
unsigned NumComponentLists,
unsigned NumComponents)
: OMPMappableExprListClause(OMPC_is_device_ptr, StartLoc, LParenLoc,
EndLoc, NumVars, NumUniqueDeclarations,
NumComponentLists, NumComponents) {}
/// Build an empty clause.
///
/// \param NumVars Number of expressions listed in this clause.
/// \param NumUniqueDeclarations Number of unique base declarations in this
/// clause.
/// \param NumComponentLists Number of component lists in this clause.
/// \param NumComponents Total number of expression components in the clause.
///
explicit OMPIsDevicePtrClause(unsigned NumVars,
unsigned NumUniqueDeclarations,
unsigned NumComponentLists,
unsigned NumComponents)
: OMPMappableExprListClause(OMPC_is_device_ptr, SourceLocation(),
SourceLocation(), SourceLocation(), NumVars,
NumUniqueDeclarations, NumComponentLists,
NumComponents) {}
public:
/// Creates clause with a list of variables \a Vars.
///
/// \param C AST context.
/// \param StartLoc Starting location of the clause.
/// \param EndLoc Ending location of the clause.
/// \param Vars The original expression used in the clause.
/// \param Declarations Declarations used in the clause.
/// \param ComponentLists Component lists used in the clause.
///
static OMPIsDevicePtrClause *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc, ArrayRef<Expr *> Vars,
ArrayRef<ValueDecl *> Declarations,
MappableExprComponentListsRef ComponentLists);
/// Creates an empty clause with the place for \a NumVars variables.
///
/// \param C AST context.
/// \param NumVars Number of expressions listed in the clause.
/// \param NumUniqueDeclarations Number of unique base declarations in this
/// clause.
/// \param NumComponentLists Number of unique base declarations in this
/// clause.
/// \param NumComponents Total number of expression components in the clause.
///
static OMPIsDevicePtrClause *CreateEmpty(const ASTContext &C,
unsigned NumVars,
unsigned NumUniqueDeclarations,
unsigned NumComponentLists,
unsigned NumComponents);
child_range children() {
return child_range(reinterpret_cast<Stmt **>(varlist_begin()),
reinterpret_cast<Stmt **>(varlist_end()));
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_is_device_ptr;
}
};
} // end namespace clang
#endif // LLVM_CLANG_AST_OPENMPCLAUSE_H
|
graph_verifier.h | // Copyright (c) 2015, The Regents of the University of California (Regents)
// See LICENSE.txt for license details
#ifndef GRAPH_H_
#define GRAPH_H_
#include <cinttypes>
#include <iostream>
#include <type_traits>
#include "pvector.h"
#include "util.h"
/*
GAP Benchmark Suite
Class: CSRGraph
Author: Scott Beamer
Simple container for graph in CSR format
- Intended to be constructed by a Builder
- To make weighted, set DestID_ template type to NodeWeight
- MakeInverse parameter controls whether graph stores its inverse
*/
// Used to hold node & weight, with another node it makes a weighted edge
template <typename NodeID_, typename WeightT_>
struct NodeWeight {
NodeID_ v;
WeightT_ w;
NodeWeight() {}
NodeWeight(NodeID_ v) : v(v), w(1) {}
NodeWeight(NodeID_ v, WeightT_ w) : v(v), w(w) {}
bool operator< (const NodeWeight& rhs) const {
return v == rhs.v ? w < rhs.w : v < rhs.v;
}
// doesn't check WeightT_s, needed to remove duplicate edges
bool operator== (const NodeWeight& rhs) const {
return v == rhs.v;
}
// doesn't check WeightT_s, needed to remove self edges
bool operator== (const NodeID_& rhs) const {
return v == rhs;
}
operator NodeID_() {
return v;
}
};
template <typename NodeID_, typename WeightT_>
std::ostream& operator<<(std::ostream& os,
const NodeWeight<NodeID_, WeightT_>& nw) {
os << nw.v << " " << nw.w;
return os;
}
template <typename NodeID_, typename WeightT_>
std::istream& operator>>(std::istream& is, NodeWeight<NodeID_, WeightT_>& nw) {
is >> nw.v >> nw.w;
return is;
}
// Syntatic sugar for an edge
template <typename SrcT, typename DstT = SrcT>
struct EdgePair {
SrcT u;
DstT v;
EdgePair() {}
EdgePair(SrcT u, DstT v) : u(u), v(v) {}
};
// SG = serialized graph, these types are for writing graph to file
typedef int32_t SGID;
typedef EdgePair<SGID> SGEdge;
typedef int64_t SGOffset;
template <class NodeID_, class DestID_ = NodeID_, bool MakeInverse = true>
class CSRGraph {
// Used to access neighbors of vertex, basically sugar for iterators
class Neighborhood {
NodeID_ n_;
DestID_** g_index_;
public:
Neighborhood(NodeID_ n, DestID_** g_index) : n_(n), g_index_(g_index) {}
typedef DestID_* iterator;
iterator begin() { return g_index_[n_]; }
iterator end() { return g_index_[n_+1]; }
};
void ReleaseResources() {
//added a second condition to prevent double free (transpose graphs)
if (out_index_ != nullptr)
delete[] out_index_;
if (out_neighbors_ != nullptr)
delete[] out_neighbors_;
if (directed_) {
if (in_index_ != nullptr)
delete[] in_index_;
if (in_neighbors_ != nullptr)
delete[] in_neighbors_;
}
if (flags_ != nullptr)
delete[] flags_;
}
public:
CSRGraph() : directed_(false), num_nodes_(-1), num_edges_(-1),
out_index_(nullptr), out_neighbors_(nullptr),
in_index_(nullptr), in_neighbors_(nullptr), flags_(nullptr){}
CSRGraph(int64_t num_nodes, DestID_** index, DestID_* neighs) :
directed_(false), num_nodes_(num_nodes),
out_index_(index), out_neighbors_(neighs),
in_index_(index), in_neighbors_(neighs) {
num_edges_ = (out_index_[num_nodes_] - out_index_[0]) / 2;
//adding flags used for deduplication
flags_ = new int[num_nodes_];
//adding offsets for load balacne scheme
SetUpOffsets(true);
}
CSRGraph(int64_t num_nodes, DestID_** out_index, DestID_* out_neighs,
DestID_** in_index, DestID_* in_neighs) :
directed_(true), num_nodes_(num_nodes),
out_index_(out_index), out_neighbors_(out_neighs),
in_index_(in_index), in_neighbors_(in_neighs) , is_transpose_(false){
num_edges_ = out_index_[num_nodes_] - out_index_[0];
flags_ = new int[num_nodes_];
SetUpOffsets(true);
}
CSRGraph(int64_t num_nodes, DestID_** out_index, DestID_* out_neighs,
DestID_** in_index, DestID_* in_neighs, bool is_transpose) :
directed_(true), num_nodes_(num_nodes),
out_index_(out_index), out_neighbors_(out_neighs),
in_index_(in_index), in_neighbors_(in_neighs) , is_transpose_(is_transpose){
num_edges_ = out_index_[num_nodes_] - out_index_[0];
flags_ = new int[num_nodes_];
SetUpOffsets(true);
}
CSRGraph(CSRGraph&& other) : directed_(other.directed_),
num_nodes_(other.num_nodes_), num_edges_(other.num_edges_),
out_index_(other.out_index_), out_neighbors_(other.out_neighbors_),
in_index_(other.in_index_), in_neighbors_(other.in_neighbors_), is_transpose_(false) {
other.num_edges_ = -1;
other.num_nodes_ = -1;
other.out_index_ = nullptr;
other.out_neighbors_ = nullptr;
other.in_index_ = nullptr;
other.in_neighbors_ = nullptr;
other.flags_ = nullptr;
other.offsets_ = nullptr;
}
~CSRGraph() {
if (!is_transpose_)
ReleaseResources();
}
CSRGraph& operator=(CSRGraph&& other) {
if (this != &other) {
if (!is_transpose_)
ReleaseResources();
directed_ = other.directed_;
num_edges_ = other.num_edges_;
num_nodes_ = other.num_nodes_;
out_index_ = other.out_index_;
out_neighbors_ = other.out_neighbors_;
in_index_ = other.in_index_;
in_neighbors_ = other.in_neighbors_;
other.num_edges_ = -1;
other.num_nodes_ = -1;
other.out_index_ = nullptr;
other.out_neighbors_ = nullptr;
other.in_index_ = nullptr;
other.in_neighbors_ = nullptr;
other.flags_ = nullptr;
other.offsets_ = nullptr;
}
return *this;
}
bool directed() const {
return directed_;
}
int64_t num_nodes() const {
return num_nodes_;
}
int64_t num_edges() const {
return num_edges_;
}
int64_t num_edges_directed() const {
return directed_ ? num_edges_ : 2*num_edges_;
}
int64_t out_degree(NodeID_ v) const {
return out_index_[v+1] - out_index_[v];
}
int64_t in_degree(NodeID_ v) const {
static_assert(MakeInverse, "Graph inversion disabled but reading inverse");
return in_index_[v+1] - in_index_[v];
}
Neighborhood out_neigh(NodeID_ n) const {
return Neighborhood(n, out_index_);
}
Neighborhood in_neigh(NodeID_ n) const {
static_assert(MakeInverse, "Graph inversion disabled but reading inverse");
return Neighborhood(n, in_index_);
}
void PrintStats() const {
std::cout << "Graph has " << num_nodes_ << " nodes and "
<< num_edges_ << " ";
if (!directed_)
std::cout << "un";
std::cout << "directed edges for degree: ";
std::cout << num_edges_/num_nodes_ << std::endl;
}
void PrintTopology() const {
for (NodeID_ i=0; i < num_nodes_; i++) {
std::cout << i << ": ";
for (DestID_ j : out_neigh(i)) {
std::cout << j << " ";
}
std::cout << std::endl;
}
}
static DestID_** GenIndex(const pvector<SGOffset> &offsets, DestID_* neighs) {
NodeID_ length = offsets.size();
DestID_** index = new DestID_*[length];
#pragma omp parallel for
for (NodeID_ n=0; n < length; n++)
index[n] = neighs + offsets[n];
return index;
}
pvector<SGOffset> VertexOffsets(bool in_graph = false) const {
pvector<SGOffset> offsets(num_nodes_+1);
for (NodeID_ n=0; n < num_nodes_+1; n++)
if (in_graph)
offsets[n] = in_index_[n] - in_index_[0];
else
offsets[n] = out_index_[n] - out_index_[0];
return offsets;
}
void SetUpOffsets(bool in_graph = false) {
offsets_ = new SGOffset[num_nodes_+1];
for (NodeID_ n=0; n < num_nodes_+1; n++)
if (in_graph)
offsets_[n] = in_index_[n] - in_index_[0];
else
offsets_[n] = out_index_[n] - out_index_[0];
}
Range<NodeID_> vertices() const {
return Range<NodeID_>(num_nodes());
}
//useful for deduplication
int* flags_;
SGOffset * offsets_;
//we are making these fields public to for transpose and other operations on graphs
//private:
bool directed_;
int64_t num_nodes_;
int64_t num_edges_;
DestID_** out_index_;
DestID_* out_neighbors_;
DestID_** in_index_;
DestID_* in_neighbors_;
bool is_transpose_;
};
#endif // GRAPH_H_
|
wino_conv_kernel_mips.c | /*
* 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.
*/
/*
* Copyright (c) 2021, OPEN AI LAB
* Author: qtang@openailab.com
*/
#include <stdint.h>
#include <stdlib.h>
#include <math.h>
#include "wino_conv_kernel_mips.h"
#define TILE 4
#define ELEM_SIZE ((TILE + 2) * (TILE + 2))
#define WINO_MAX(a, b) ((a) > (b) ? (a) : (b))
#define WINO_MIN(a, b) ((a) < (b) ? (a) : (b))
static void relu(float* data, int size, int activation)
{
for (int i = 0; i < size; i++)
{
data[i] = WINO_MAX(data[i], ( float )0);
if (activation > 0)
{
data[i] = WINO_MIN(data[i], ( float )activation);
}
}
}
static int get_private_mem_size(struct tensor* filter, struct conv_param* param)
{
int output_c = filter->dims[0];
int input_c = filter->dims[1];
int trans_ker_size = output_c * input_c * ELEM_SIZE * sizeof(float);
return trans_ker_size + 128; // caution
}
static void pad_0_align_2D(float* dst, float* src, int m, int n, int m_align, int n_align, int pad_h, int pad_w)
{
int i;
if (n >= n_align && m >= m_align)
{
memcpy(dst, src, m * n * sizeof(float));
return;
}
for (i = 0; i < m; ++i)
{
memcpy(dst + (i + pad_h) * n_align + pad_w, src + i * n, n * sizeof(float));
}
}
// pad 0 in right and down side on 3D
static void pad_0_align_3D(float* dst, float* src, int m, int n, int m_align, int n_align, int c, int pad_h, int pad_w)
{
int i;
if (n >= n_align && m >= m_align)
{
memcpy(dst, src, c * m * n * sizeof(float));
return;
}
for (i = 0; i < c; ++i)
{
pad_0_align_2D(dst + i * m_align * n_align, src + i * m * n, m, n, m_align, n_align, pad_h, pad_w);
}
}
static void delete_0_2D(float* dst, float* src, int m_align, int n_align, int m, int n, int pad_h, int pad_w)
{
int i;
if (n >= n_align && m >= m_align)
{
memcpy(dst, src, m * n * sizeof(float));
return;
}
for (i = 0; i < m; ++i)
{
memcpy(dst + i * n, src + (i + pad_h) * n_align + pad_w, n * sizeof(float));
}
}
// pad 0 in right and down side on 3D
static void delete_0_3D(float* dst, float* src, int m_align, int n_align, int m, int n, int c, int pad_h, int pad_w)
{
int i;
if (n >= n_align && m >= m_align)
{
memcpy(dst, src, c * m * n * sizeof(float));
return;
}
for (i = 0; i < c; ++i)
{
delete_0_2D(dst + i * m * n, src + i * m_align * n_align, m_align, n_align, m, n, pad_h, pad_w);
}
}
void conv3x3s1_winograd43_sse(float* bottom_blob, float* top_blob, float* kernel_tm_test, float* dot_block,
float* transform_input, float* output_bordered, float* _bias, int w, int h, int inch,
int outw, int outh, int outch, int num_thread)
{
size_t elemsize = sizeof(float);
const float* bias = _bias;
// pad to 4n+2, winograd F(4,3)
float* bottom_blob_bordered = bottom_blob;
int outw_align = (outw + 3) / 4 * 4;
int outh_align = (outh + 3) / 4 * 4;
w = outw_align + 2;
h = outh_align + 2;
// BEGIN transform input
float* bottom_blob_tm = NULL;
{
int w_tm = outw_align / 4 * 6;
int h_tm = outh_align / 4 * 6;
int nColBlocks = h_tm / 6; // may be the block num in Feathercnn
int nRowBlocks = w_tm / 6;
const int tiles = nColBlocks * nRowBlocks;
const int tiles_n = 4 * inch * tiles;
bottom_blob_tm = transform_input;
// BT
// const float itm[4][4] = {
// {4.0f, 0.0f, -5.0f, 0.0f, 1.0f, 0.0f},
// {0.0f,-4.0f, -4.0f, 1.0f, 1.0f, 0.0f},
// {0.0f, 4.0f, -4.0f,-1.0f, 1.0f, 0.0f},
// {0.0f,-2.0f, -1.0f, 2.0f, 1.0f, 0.0f},
// {0.0f, 2.0f, -1.0f,-2.0f, 1.0f, 0.0f},
// {0.0f, 4.0f, 0.0f,-5.0f, 0.0f, 1.0f}
// };
// 0 = 4 * r00 - 5 * r02 + r04
// 1 = -4 * (r01 + r02) + r03 + r04
// 2 = 4 * (r01 - r02) - r03 + r04
// 3 = -2 * r01 - r02 + 2 * r03 + r04
// 4 = 2 * r01 - r02 - 2 * r03 + r04
// 5 = 4 * r01 - 5 * r03 + r05
// 0 = 4 * r00 - 5 * r02 + r04
// 1 = -4 * (r01 + r02) + r03 + r04
// 2 = 4 * (r01 - r02) - r03 + r04
// 3 = -2 * r01 - r02 + 2 * r03 + r04
// 4 = 2 * r01 - r02 - 2 * r03 + r04
// 5 = 4 * r01 - 5 * r03 + r05
#pragma omp parallel for num_threads(num_thread)
for (int q = 0; q < inch; q++)
{
const float* img = bottom_blob_bordered + q * w * h;
for (int j = 0; j < nColBlocks; j++)
{
const float* r0 = img + w * j * 4;
const float* r1 = r0 + w;
const float* r2 = r1 + w;
const float* r3 = r2 + w;
const float* r4 = r3 + w;
const float* r5 = r4 + w;
for (int i = 0; i < nRowBlocks; i++)
{
float* out_tm0 = bottom_blob_tm + 4 * inch * (j * nRowBlocks + i) + 4 * q;
float* out_tm1 = out_tm0 + tiles_n;
float* out_tm2 = out_tm0 + 2 * tiles_n;
float* out_tm3 = out_tm0 + 3 * tiles_n;
float* out_tm4 = out_tm0 + 4 * tiles_n;
float* out_tm5 = out_tm0 + 5 * tiles_n;
float* out_tm6 = out_tm0 + 6 * tiles_n;
float* out_tm7 = out_tm0 + 7 * tiles_n;
float* out_tm8 = out_tm0 + 8 * tiles_n;
float d0[6], d1[6], d2[6], d3[6], d4[6], d5[6];
float w0[6], w1[6], w2[6], w3[6], w4[6], w5[6];
float t0[6], t1[6], t2[6], t3[6], t4[6], t5[6];
// load
for (int n = 0; n < 6; n++)
{
d0[n] = r0[n];
d1[n] = r1[n];
d2[n] = r2[n];
d3[n] = r3[n];
d4[n] = r4[n];
d5[n] = r5[n];
}
// w = B_t * d
for (int n = 0; n < 6; n++)
{
w0[n] = 4 * d0[n] - 5 * d2[n] + d4[n];
w1[n] = -4 * d1[n] - 4 * d2[n] + d3[n] + d4[n];
w2[n] = 4 * d1[n] - 4 * d2[n] - d3[n] + d4[n];
w3[n] = -2 * d1[n] - d2[n] + 2 * d3[n] + d4[n];
w4[n] = 2 * d1[n] - d2[n] - 2 * d3[n] + d4[n];
w5[n] = 4 * d1[n] - 5 * d3[n] + d5[n];
}
// transpose d to d_t
{
t0[0] = w0[0];
t1[0] = w0[1];
t2[0] = w0[2];
t3[0] = w0[3];
t4[0] = w0[4];
t5[0] = w0[5];
t0[1] = w1[0];
t1[1] = w1[1];
t2[1] = w1[2];
t3[1] = w1[3];
t4[1] = w1[4];
t5[1] = w1[5];
t0[2] = w2[0];
t1[2] = w2[1];
t2[2] = w2[2];
t3[2] = w2[3];
t4[2] = w2[4];
t5[2] = w2[5];
t0[3] = w3[0];
t1[3] = w3[1];
t2[3] = w3[2];
t3[3] = w3[3];
t4[3] = w3[4];
t5[3] = w3[5];
t0[4] = w4[0];
t1[4] = w4[1];
t2[4] = w4[2];
t3[4] = w4[3];
t4[4] = w4[4];
t5[4] = w4[5];
t0[5] = w5[0];
t1[5] = w5[1];
t2[5] = w5[2];
t3[5] = w5[3];
t4[5] = w5[4];
t5[5] = w5[5];
}
// d = B_t * d_t
for (int n = 0; n < 6; n++)
{
d0[n] = 4 * t0[n] - 5 * t2[n] + t4[n];
d1[n] = -4 * t1[n] - 4 * t2[n] + t3[n] + t4[n];
d2[n] = 4 * t1[n] - 4 * t2[n] - t3[n] + t4[n];
d3[n] = -2 * t1[n] - t2[n] + 2 * t3[n] + t4[n];
d4[n] = 2 * t1[n] - t2[n] - 2 * t3[n] + t4[n];
d5[n] = 4 * t1[n] - 5 * t3[n] + t5[n];
}
// save to out_tm
{
out_tm0[0] = d0[0];
out_tm0[1] = d0[1];
out_tm0[2] = d0[2];
out_tm0[3] = d0[3];
out_tm1[0] = d0[4];
out_tm1[1] = d0[5];
out_tm1[2] = d1[0];
out_tm1[3] = d1[1];
out_tm2[0] = d1[2];
out_tm2[1] = d1[3];
out_tm2[2] = d1[4];
out_tm2[3] = d1[5];
out_tm3[0] = d2[0];
out_tm3[1] = d2[1];
out_tm3[2] = d2[2];
out_tm3[3] = d2[3];
out_tm4[0] = d2[4];
out_tm4[1] = d2[5];
out_tm4[2] = d3[0];
out_tm4[3] = d3[1];
out_tm5[0] = d3[2];
out_tm5[1] = d3[3];
out_tm5[2] = d3[4];
out_tm5[3] = d3[5];
out_tm6[0] = d4[0];
out_tm6[1] = d4[1];
out_tm6[2] = d4[2];
out_tm6[3] = d4[3];
out_tm7[0] = d4[4];
out_tm7[1] = d4[5];
out_tm7[2] = d5[0];
out_tm7[3] = d5[1];
out_tm8[0] = d5[2];
out_tm8[1] = d5[3];
out_tm8[2] = d5[4];
out_tm8[3] = d5[5];
}
r0 += 4;
r1 += 4;
r2 += 4;
r3 += 4;
r4 += 4;
r5 += 4;
}
}
}
}
// BEGIN dot
float* top_blob_tm = NULL;
{
int w_tm = outw_align / 4 * 6;
int h_tm = outh_align / 4 * 6;
int nColBlocks = h_tm / 6; // may be the block num in Feathercnn
int nRowBlocks = w_tm / 6;
const int tiles = nColBlocks * nRowBlocks;
const int tiles_n = 36 * tiles;
top_blob_tm = dot_block;
#pragma omp parallel for num_threads(num_thread)
for (int r = 0; r < 9; r++)
{
int nn_outch = 0;
int remain_outch_start = 0;
nn_outch = outch >> 3;
remain_outch_start = nn_outch << 3;
for (int pp = 0; pp < nn_outch; pp++)
{
int p = pp << 3;
float* output0_tm = top_blob_tm + tiles_n * p;
float* output1_tm = top_blob_tm + tiles_n * (p + 1);
float* output2_tm = top_blob_tm + tiles_n * (p + 2);
float* output3_tm = top_blob_tm + tiles_n * (p + 3);
float* output4_tm = top_blob_tm + tiles_n * (p + 4);
float* output5_tm = top_blob_tm + tiles_n * (p + 5);
float* output6_tm = top_blob_tm + tiles_n * (p + 6);
float* output7_tm = top_blob_tm + tiles_n * (p + 7);
output0_tm = output0_tm + r * 4;
output1_tm = output1_tm + r * 4;
output2_tm = output2_tm + r * 4;
output3_tm = output3_tm + r * 4;
output4_tm = output4_tm + r * 4;
output5_tm = output5_tm + r * 4;
output6_tm = output6_tm + r * 4;
output7_tm = output7_tm + r * 4;
for (int i = 0; i < tiles; i++)
{
const float* kptr = kernel_tm_test + 4 * r * inch * outch + p / 8 * inch * 32;
const float* r0 = bottom_blob_tm + 4 * inch * (tiles * r + i);
#if __mips_msa
v4f32 _sum0 = {0.f};
v4f32 _sum1 = {0.f};
v4f32 _sum2 = {0.f};
v4f32 _sum3 = {0.f};
v4f32 _sum4 = {0.f};
v4f32 _sum5 = {0.f};
v4f32 _sum6 = {0.f};
v4f32 _sum7 = {0.f};
int q = 0;
for (; q + 3 < inch; q = q + 4)
{
v4f32 _r0 = (v4f32)__msa_ld_w(r0, 0);
v4f32 _r1 = (v4f32)__msa_ld_w(r0 + 4, 0);
v4f32 _r2 = (v4f32)__msa_ld_w(r0 + 8, 0);
v4f32 _r3 = (v4f32)__msa_ld_w(r0 + 12, 0);
v4f32 _k0 = (v4f32)__msa_ld_w(kptr, 0);
v4f32 _k1 = (v4f32)__msa_ld_w(kptr + 4, 0);
v4f32 _k2 = (v4f32)__msa_ld_w(kptr + 8, 0);
v4f32 _k3 = (v4f32)__msa_ld_w(kptr + 12, 0);
v4f32 _k4 = (v4f32)__msa_ld_w(kptr + 16, 0);
v4f32 _k5 = (v4f32)__msa_ld_w(kptr + 20, 0);
v4f32 _k6 = (v4f32)__msa_ld_w(kptr + 24, 0);
v4f32 _k7 = (v4f32)__msa_ld_w(kptr + 28, 0);
_sum0 = __msa_fmadd_w(_sum0, _r0, _k0);
_sum1 = __msa_fmadd_w(_sum1, _r0, _k1);
_sum2 = __msa_fmadd_w(_sum2, _r0, _k2);
_sum3 = __msa_fmadd_w(_sum3, _r0, _k3);
_sum4 = __msa_fmadd_w(_sum4, _r0, _k4);
_sum5 = __msa_fmadd_w(_sum5, _r0, _k5);
_sum6 = __msa_fmadd_w(_sum6, _r0, _k6);
_sum7 = __msa_fmadd_w(_sum7, _r0, _k7);
kptr += 32;
_k0 = (v4f32)__msa_ld_w(kptr, 0);
_k1 = (v4f32)__msa_ld_w(kptr + 4, 0);
_k2 = (v4f32)__msa_ld_w(kptr + 8, 0);
_k3 = (v4f32)__msa_ld_w(kptr + 12, 0);
_k4 = (v4f32)__msa_ld_w(kptr + 16, 0);
_k5 = (v4f32)__msa_ld_w(kptr + 20, 0);
_k6 = (v4f32)__msa_ld_w(kptr + 24, 0);
_k7 = (v4f32)__msa_ld_w(kptr + 28, 0);
_sum0 = __msa_fmadd_w(_sum0, _r1, _k0);
_sum1 = __msa_fmadd_w(_sum1, _r1, _k1);
_sum2 = __msa_fmadd_w(_sum2, _r1, _k2);
_sum3 = __msa_fmadd_w(_sum3, _r1, _k3);
_sum4 = __msa_fmadd_w(_sum4, _r1, _k4);
_sum5 = __msa_fmadd_w(_sum5, _r1, _k5);
_sum6 = __msa_fmadd_w(_sum6, _r1, _k6);
_sum7 = __msa_fmadd_w(_sum7, _r1, _k7);
kptr += 32;
_k0 = (v4f32)__msa_ld_w(kptr, 0);
_k1 = (v4f32)__msa_ld_w(kptr + 4, 0);
_k2 = (v4f32)__msa_ld_w(kptr + 8, 0);
_k3 = (v4f32)__msa_ld_w(kptr + 12, 0);
_k4 = (v4f32)__msa_ld_w(kptr + 16, 0);
_k5 = (v4f32)__msa_ld_w(kptr + 20, 0);
_k6 = (v4f32)__msa_ld_w(kptr + 24, 0);
_k7 = (v4f32)__msa_ld_w(kptr + 28, 0);
_sum0 = __msa_fmadd_w(_sum0, _r2, _k0);
_sum1 = __msa_fmadd_w(_sum1, _r2, _k1);
_sum2 = __msa_fmadd_w(_sum2, _r2, _k2);
_sum3 = __msa_fmadd_w(_sum3, _r2, _k3);
_sum4 = __msa_fmadd_w(_sum4, _r2, _k4);
_sum5 = __msa_fmadd_w(_sum5, _r2, _k5);
_sum6 = __msa_fmadd_w(_sum6, _r2, _k6);
_sum7 = __msa_fmadd_w(_sum7, _r2, _k7);
kptr += 32;
_k0 = (v4f32)__msa_ld_w(kptr, 0);
_k1 = (v4f32)__msa_ld_w(kptr + 4, 0);
_k2 = (v4f32)__msa_ld_w(kptr + 8, 0);
_k3 = (v4f32)__msa_ld_w(kptr + 12, 0);
_k4 = (v4f32)__msa_ld_w(kptr + 16, 0);
_k5 = (v4f32)__msa_ld_w(kptr + 20, 0);
_k6 = (v4f32)__msa_ld_w(kptr + 24, 0);
_k7 = (v4f32)__msa_ld_w(kptr + 28, 0);
_sum0 = __msa_fmadd_w(_sum0, _r3, _k0);
_sum1 = __msa_fmadd_w(_sum1, _r3, _k1);
_sum2 = __msa_fmadd_w(_sum2, _r3, _k2);
_sum3 = __msa_fmadd_w(_sum3, _r3, _k3);
_sum4 = __msa_fmadd_w(_sum4, _r3, _k4);
_sum5 = __msa_fmadd_w(_sum5, _r3, _k5);
_sum6 = __msa_fmadd_w(_sum6, _r3, _k6);
_sum7 = __msa_fmadd_w(_sum7, _r3, _k7);
kptr += 32;
r0 += 16;
}
for (; q < inch; q++)
{
v4f32 _r0 = (v4f32)__msa_ld_w(r0, 0);
v4f32 _k0 = (v4f32)__msa_ld_w(kptr, 0);
v4f32 _k1 = (v4f32)__msa_ld_w(kptr + 4, 0);
v4f32 _k2 = (v4f32)__msa_ld_w(kptr + 8, 0);
v4f32 _k3 = (v4f32)__msa_ld_w(kptr + 12, 0);
v4f32 _k4 = (v4f32)__msa_ld_w(kptr + 16, 0);
v4f32 _k5 = (v4f32)__msa_ld_w(kptr + 20, 0);
v4f32 _k6 = (v4f32)__msa_ld_w(kptr + 24, 0);
v4f32 _k7 = (v4f32)__msa_ld_w(kptr + 28, 0);
_sum0 = __msa_fmadd_w(_sum0, _r0, _k0);
_sum1 = __msa_fmadd_w(_sum1, _r0, _k1);
_sum2 = __msa_fmadd_w(_sum2, _r0, _k2);
_sum3 = __msa_fmadd_w(_sum3, _r0, _k3);
_sum4 = __msa_fmadd_w(_sum4, _r0, _k4);
_sum5 = __msa_fmadd_w(_sum5, _r0, _k5);
_sum6 = __msa_fmadd_w(_sum6, _r0, _k6);
_sum7 = __msa_fmadd_w(_sum7, _r0, _k7);
kptr += 32;
r0 += 4;
}
__msa_st_w((v4i32)_sum0, output0_tm, 0);
__msa_st_w((v4i32)_sum1, output1_tm, 0);
__msa_st_w((v4i32)_sum2, output2_tm, 0);
__msa_st_w((v4i32)_sum3, output3_tm, 0);
__msa_st_w((v4i32)_sum4, output4_tm, 0);
__msa_st_w((v4i32)_sum5, output5_tm, 0);
__msa_st_w((v4i32)_sum6, output6_tm, 0);
__msa_st_w((v4i32)_sum7, output7_tm, 0);
#else
float sum0[4] = {0};
float sum1[4] = {0};
float sum2[4] = {0};
float sum3[4] = {0};
float sum4[4] = {0};
float sum5[4] = {0};
float sum6[4] = {0};
float sum7[4] = {0};
for (int q = 0; q < inch; q++)
{
for (int n = 0; n < 4; n++)
{
sum0[n] += r0[n] * kptr[n];
sum1[n] += r0[n] * kptr[n + 4];
sum2[n] += r0[n] * kptr[n + 8];
sum3[n] += r0[n] * kptr[n + 12];
sum4[n] += r0[n] * kptr[n + 16];
sum5[n] += r0[n] * kptr[n + 20];
sum6[n] += r0[n] * kptr[n + 24];
sum7[n] += r0[n] * kptr[n + 28];
}
kptr += 32;
r0 += 4;
}
for (int n = 0; n < 4; n++)
{
output0_tm[n] = sum0[n];
output1_tm[n] = sum1[n];
output2_tm[n] = sum2[n];
output3_tm[n] = sum3[n];
output4_tm[n] = sum4[n];
output5_tm[n] = sum5[n];
output6_tm[n] = sum6[n];
output7_tm[n] = sum7[n];
}
#endif // __mips_msa
output0_tm += 36;
output1_tm += 36;
output2_tm += 36;
output3_tm += 36;
output4_tm += 36;
output5_tm += 36;
output6_tm += 36;
output7_tm += 36;
}
}
nn_outch = (outch - remain_outch_start) >> 2;
for (int pp = 0; pp < nn_outch; pp++)
{
int p = remain_outch_start + pp * 4;
float* output0_tm = top_blob_tm + tiles_n * p;
float* output1_tm = top_blob_tm + tiles_n * (p + 1);
float* output2_tm = top_blob_tm + tiles_n * (p + 2);
float* output3_tm = top_blob_tm + tiles_n * (p + 3);
output0_tm = output0_tm + r * 4;
output1_tm = output1_tm + r * 4;
output2_tm = output2_tm + r * 4;
output3_tm = output3_tm + r * 4;
for (int i = 0; i < tiles; i++)
{
const float* kptr = kernel_tm_test + 4 * r * inch * outch + (p / 8 + (p % 8) / 4) * inch * 32;
const float* r0 = bottom_blob_tm + 4 * inch * (tiles * r + i);
#if __mips_msa
v4f32 _sum0 = {0.f};
v4f32 _sum1 = {0.f};
v4f32 _sum2 = {0.f};
v4f32 _sum3 = {0.f};
for (int q = 0; q < inch; q++)
{
v4f32 _r0 = (v4f32)__msa_ld_w(r0, 0);
v4f32 _k0 = (v4f32)__msa_ld_w(kptr, 0);
v4f32 _k1 = (v4f32)__msa_ld_w(kptr + 4, 0);
v4f32 _k2 = (v4f32)__msa_ld_w(kptr + 8, 0);
v4f32 _k3 = (v4f32)__msa_ld_w(kptr + 12, 0);
_sum0 = __msa_fmadd_w(_sum0, _r0, _k0);
_sum1 = __msa_fmadd_w(_sum1, _r0, _k1);
_sum2 = __msa_fmadd_w(_sum2, _r0, _k2);
_sum3 = __msa_fmadd_w(_sum3, _r0, _k3);
kptr += 16;
r0 += 4;
}
__msa_st_w((v4i32)_sum0, output0_tm, 0);
__msa_st_w((v4i32)_sum1, output1_tm, 0);
__msa_st_w((v4i32)_sum2, output2_tm, 0);
__msa_st_w((v4i32)_sum3, output3_tm, 0);
#else
float sum0[4] = {0};
float sum1[4] = {0};
float sum2[4] = {0};
float sum3[4] = {0};
for (int q = 0; q < inch; q++)
{
for (int n = 0; n < 4; n++)
{
sum0[n] += r0[n] * kptr[n];
sum1[n] += r0[n] * kptr[n + 4];
sum2[n] += r0[n] * kptr[n + 8];
sum3[n] += r0[n] * kptr[n + 12];
}
kptr += 16;
r0 += 4;
}
for (int n = 0; n < 4; n++)
{
output0_tm[n] = sum0[n];
output1_tm[n] = sum1[n];
output2_tm[n] = sum2[n];
output3_tm[n] = sum3[n];
}
#endif // __mips_msa
output0_tm += 36;
output1_tm += 36;
output2_tm += 36;
output3_tm += 36;
}
}
remain_outch_start += nn_outch << 2;
for (int p = remain_outch_start; p < outch; p++)
{
float* output0_tm = top_blob_tm + 36 * tiles * p;
output0_tm = output0_tm + r * 4;
for (int i = 0; i < tiles; i++)
{
const float* kptr = kernel_tm_test + 4 * r * inch * outch + (p / 8 + (p % 8) / 4 + p % 4) * inch * 32;
const float* r0 = bottom_blob_tm + 4 * inch * (tiles * r + i);
#if __mips_msa
v4f32 _sum0 = {0.f};
for (int q = 0; q < inch; q++)
{
v4f32 _r0 = (v4f32)__msa_ld_w(r0, 0);
v4f32 _k0 = (v4f32)__msa_ld_w(kptr, 0);
_sum0 = __msa_fmadd_w(_sum0, _r0, _k0);
kptr += 16;
r0 += 4;
}
__msa_st_w((v4i32)_sum0, output0_tm, 0);
#else
float sum0[4] = {0};
for (int q = 0; q < inch; q++)
{
for (int n = 0; n < 4; n++)
{
sum0[n] += ( int )r0[n] * kptr[n];
}
kptr += 4;
r0 += 4;
}
for (int n = 0; n < 4; n++)
{
output0_tm[n] = sum0[n];
}
#endif // __mips_msa
output0_tm += 36;
}
}
}
}
// END dot
// BEGIN transform output
float* top_blob_bordered = NULL;
if (outw_align == outw && outh_align == outh)
{
top_blob_bordered = top_blob;
}
else
{
top_blob_bordered = output_bordered;
}
{
// AT
// const float itm[4][6] = {
// {1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f},
// {0.0f, 1.0f, -1.0f, 2.0f, -2.0f, 0.0f},
// {0.0f, 1.0f, 1.0f, 4.0f, 4.0f, 0.0f},
// {0.0f, 1.0f, -1.0f, 8.0f, -8.0f, 1.0f}
// };
// 0 = r00 + r01 + r02 + r03 + r04
// 1 = r01 - r02 + 2 * (r03 - r04)
// 2 = r01 + r02 + 4 * (r03 + r04)
// 3 = r01 - r02 + 8 * (r03 - r04) + r05
int w_tm = outw_align / 4 * 6;
int h_tm = outh_align / 4 * 6;
int nColBlocks = h_tm / 6; // may be the block num in Feathercnn
int nRowBlocks = w_tm / 6;
const int tiles = nColBlocks * nRowBlocks;
#pragma omp parallel for num_threads(num_thread)
for (int p = 0; p < outch; p++)
{
float* out_tile = top_blob_tm + 36 * tiles * p;
float* outRow0 = top_blob_bordered + outw_align * outh_align * p;
float* outRow1 = outRow0 + outw_align;
float* outRow2 = outRow0 + outw_align * 2;
float* outRow3 = outRow0 + outw_align * 3;
const float bias0 = bias ? bias[p] : 0.f;
for (int j = 0; j < nColBlocks; j++)
{
for (int i = 0; i < nRowBlocks; i++)
{
// TODO AVX2
float s0[6], s1[6], s2[6], s3[6], s4[6], s5[6];
float w0[6], w1[6], w2[6], w3[6];
float d0[4], d1[4], d2[4], d3[4], d4[4], d5[4];
float o0[4], o1[4], o2[4], o3[4];
// load
for (int n = 0; n < 6; n++)
{
s0[n] = out_tile[n];
s1[n] = out_tile[n + 6];
s2[n] = out_tile[n + 12];
s3[n] = out_tile[n + 18];
s4[n] = out_tile[n + 24];
s5[n] = out_tile[n + 30];
}
// w = A_T * W
for (int n = 0; n < 6; n++)
{
w0[n] = s0[n] + s1[n] + s2[n] + s3[n] + s4[n];
w1[n] = s1[n] - s2[n] + 2 * s3[n] - 2 * s4[n];
w2[n] = s1[n] + s2[n] + 4 * s3[n] + 4 * s4[n];
w3[n] = s1[n] - s2[n] + 8 * s3[n] - 8 * s4[n] + s5[n];
}
// transpose w to w_t
{
d0[0] = w0[0];
d0[1] = w1[0];
d0[2] = w2[0];
d0[3] = w3[0];
d1[0] = w0[1];
d1[1] = w1[1];
d1[2] = w2[1];
d1[3] = w3[1];
d2[0] = w0[2];
d2[1] = w1[2];
d2[2] = w2[2];
d2[3] = w3[2];
d3[0] = w0[3];
d3[1] = w1[3];
d3[2] = w2[3];
d3[3] = w3[3];
d4[0] = w0[4];
d4[1] = w1[4];
d4[2] = w2[4];
d4[3] = w3[4];
d5[0] = w0[5];
d5[1] = w1[5];
d5[2] = w2[5];
d5[3] = w3[5];
}
// Y = A_T * w_t
for (int n = 0; n < 4; n++)
{
o0[n] = d0[n] + d1[n] + d2[n] + d3[n] + d4[n];
o1[n] = d1[n] - d2[n] + 2 * d3[n] - 2 * d4[n];
o2[n] = d1[n] + d2[n] + 4 * d3[n] + 4 * d4[n];
o3[n] = d1[n] - d2[n] + 8 * d3[n] - 8 * d4[n] + d5[n];
}
// save to top blob tm
for (int n = 0; n < 4; n++)
{
outRow0[n] = o0[n] + bias0;
outRow1[n] = o1[n] + bias0;
outRow2[n] = o2[n] + bias0;
outRow3[n] = o3[n] + bias0;
}
out_tile += 36;
outRow0 += 4;
outRow1 += 4;
outRow2 += 4;
outRow3 += 4;
}
outRow0 += outw_align * 3;
outRow1 += outw_align * 3;
outRow2 += outw_align * 3;
outRow3 += outw_align * 3;
}
}
}
// END transform output
if (outw_align != outw || outh_align != outw)
{
delete_0_3D(top_blob, top_blob_bordered, outh_align, outw_align, outh, outw, outch, 0, 0);
}
}
void conv3x3s1_winograd43_transform_kernel_sse(const float* kernel, float* kernel_wino, int inch, int outch)
{
float* kernel_tm = ( float* )sys_malloc(6 * 6 * inch * outch * sizeof(float));
// G
const float ktm[6][3] = {
{1.0f / 4, 0.0f, 0.0f}, {-1.0f / 6, -1.0f / 6, -1.0f / 6}, {-1.0f / 6, 1.0f / 6, -1.0f / 6},
{1.0f / 24, 1.0f / 12, 1.0f / 6}, {1.0f / 24, -1.0f / 12, 1.0f / 6}, {0.0f, 0.0f, 1.0f}};
#pragma omp parallel for
for (int p = 0; p < outch; p++)
{
for (int q = 0; q < inch; q++)
{
const float* kernel0 = kernel + p * inch * 9 + q * 9;
float* kernel_tm0 = kernel_tm + p * inch * 36 + q * 36;
// transform kernel
const float* k0 = kernel0;
const float* k1 = kernel0 + 3;
const float* k2 = kernel0 + 6;
// h
float tmp[6][3] = {0};
for (int i = 0; i < 6; i++)
{
tmp[i][0] = k0[0] * ktm[i][0] + k0[1] * ktm[i][1] + k0[2] * ktm[i][2];
tmp[i][1] = k1[0] * ktm[i][0] + k1[1] * ktm[i][1] + k1[2] * ktm[i][2];
tmp[i][2] = k2[0] * ktm[i][0] + k2[1] * ktm[i][1] + k2[2] * ktm[i][2];
}
// U
for (int j = 0; j < 6; j++)
{
float* tmpp = &tmp[j][0];
for (int i = 0; i < 6; i++)
{
kernel_tm0[j * 6 + i] = tmpp[0] * ktm[i][0] + tmpp[1] * ktm[i][1] + tmpp[2] * ktm[i][2];
}
}
}
}
float* kernel_tm_test = kernel_wino;
for (int r = 0; r < 9; r++)
{
int p = 0;
for (; p + 7 < outch; p += 8)
{
const float* kernel0 = ( const float* )kernel_tm + p * inch * 36;
const float* kernel1 = ( const float* )kernel_tm + (p + 1) * inch * 36;
const float* kernel2 = ( const float* )kernel_tm + (p + 2) * inch * 36;
const float* kernel3 = ( const float* )kernel_tm + (p + 3) * inch * 36;
const float* kernel4 = ( const float* )kernel_tm + (p + 4) * inch * 36;
const float* kernel5 = ( const float* )kernel_tm + (p + 5) * inch * 36;
const float* kernel6 = ( const float* )kernel_tm + (p + 6) * inch * 36;
const float* kernel7 = ( const float* )kernel_tm + (p + 7) * inch * 36;
float* ktmp = kernel_tm_test + p / 8 * inch * 32;
for (int q = 0; q < inch; q++)
{
ktmp[0] = kernel0[r * 4 + 0];
ktmp[1] = kernel0[r * 4 + 1];
ktmp[2] = kernel0[r * 4 + 2];
ktmp[3] = kernel0[r * 4 + 3];
ktmp[4] = kernel1[r * 4 + 0];
ktmp[5] = kernel1[r * 4 + 1];
ktmp[6] = kernel1[r * 4 + 2];
ktmp[7] = kernel1[r * 4 + 3];
ktmp[8] = kernel2[r * 4 + 0];
ktmp[9] = kernel2[r * 4 + 1];
ktmp[10] = kernel2[r * 4 + 2];
ktmp[11] = kernel2[r * 4 + 3];
ktmp[12] = kernel3[r * 4 + 0];
ktmp[13] = kernel3[r * 4 + 1];
ktmp[14] = kernel3[r * 4 + 2];
ktmp[15] = kernel3[r * 4 + 3];
ktmp[16] = kernel4[r * 4 + 0];
ktmp[17] = kernel4[r * 4 + 1];
ktmp[18] = kernel4[r * 4 + 2];
ktmp[19] = kernel4[r * 4 + 3];
ktmp[20] = kernel5[r * 4 + 0];
ktmp[21] = kernel5[r * 4 + 1];
ktmp[22] = kernel5[r * 4 + 2];
ktmp[23] = kernel5[r * 4 + 3];
ktmp[24] = kernel6[r * 4 + 0];
ktmp[25] = kernel6[r * 4 + 1];
ktmp[26] = kernel6[r * 4 + 2];
ktmp[27] = kernel6[r * 4 + 3];
ktmp[28] = kernel7[r * 4 + 0];
ktmp[29] = kernel7[r * 4 + 1];
ktmp[30] = kernel7[r * 4 + 2];
ktmp[31] = kernel7[r * 4 + 3];
ktmp += 32;
kernel0 += 36;
kernel1 += 36;
kernel2 += 36;
kernel3 += 36;
kernel4 += 36;
kernel5 += 36;
kernel6 += 36;
kernel7 += 36;
}
}
for (; p + 3 < outch; p += 4)
{
const float* kernel0 = ( const float* )kernel_tm + p * inch * 36;
const float* kernel1 = ( const float* )kernel_tm + (p + 1) * inch * 36;
const float* kernel2 = ( const float* )kernel_tm + (p + 2) * inch * 36;
const float* kernel3 = ( const float* )kernel_tm + (p + 3) * inch * 36;
float* ktmp = kernel_tm_test + (p / 8 + (p % 8) / 4) * inch * 32;
for (int q = 0; q < inch; q++)
{
ktmp[0] = kernel0[r * 4 + 0];
ktmp[1] = kernel0[r * 4 + 1];
ktmp[2] = kernel0[r * 4 + 2];
ktmp[3] = kernel0[r * 4 + 3];
ktmp[4] = kernel1[r * 4 + 0];
ktmp[5] = kernel1[r * 4 + 1];
ktmp[6] = kernel1[r * 4 + 2];
ktmp[7] = kernel1[r * 4 + 3];
ktmp[8] = kernel2[r * 4 + 0];
ktmp[9] = kernel2[r * 4 + 1];
ktmp[10] = kernel2[r * 4 + 2];
ktmp[11] = kernel2[r * 4 + 3];
ktmp[12] = kernel3[r * 4 + 0];
ktmp[13] = kernel3[r * 4 + 1];
ktmp[14] = kernel3[r * 4 + 2];
ktmp[15] = kernel3[r * 4 + 3];
ktmp += 16;
kernel0 += 36;
kernel1 += 36;
kernel2 += 36;
kernel3 += 36;
}
}
for (; p < outch; p++)
{
const float* kernel0 = ( const float* )kernel_tm + p * inch * 36;
float* ktmp = kernel_tm_test + (p / 8 + (p % 8) / 4 + p % 4) * inch * 32;
for (int q = 0; q < inch; q++)
{
ktmp[0] = kernel0[r * 4 + 0];
ktmp[1] = kernel0[r * 4 + 1];
ktmp[2] = kernel0[r * 4 + 2];
ktmp[3] = kernel0[r * 4 + 3];
ktmp += 4;
kernel0 += 36;
}
}
kernel_tm_test += 4 * inch * outch;
}
free(kernel_tm);
}
int wino_conv_hcl_prerun(struct tensor* input_tensor, struct tensor* filter_tensor,
struct tensor* output_tensor, struct conv_priv_info* priv_info, struct conv_param* param)
{
int batch = input_tensor->dims[0];
int input_c = input_tensor->dims[1];
int input_h = input_tensor->dims[2];
int input_w = input_tensor->dims[3];
int output_c = output_tensor->dims[1];
int output_h = output_tensor->dims[2];
int output_w = output_tensor->dims[3];
int pad_h = param->pad_h0;
int pad_w = param->pad_w0;
float* kernel = ( float* )filter_tensor->data;
if (!priv_info->external_interleave_mem)
{
int mem_size = get_private_mem_size(filter_tensor, param);
void* mem = sys_malloc(mem_size);
priv_info->interleave_buffer = mem;
priv_info->interleave_buffer_size = mem_size;
}
int block_h = (output_h + TILE - 1) / TILE;
int block_w = (output_w + TILE - 1) / TILE;
int block = block_h * block_w;
int padded_inh = TILE * block_h + 2 * pad_h;
int padded_inw = TILE * block_w + 2 * pad_w;
int pad_inhw = padded_inh * padded_inw;
int outw = block_w * TILE;
int outh = block_h * TILE;
priv_info->input_pad = ( float* )sys_malloc(batch * input_c * pad_inhw * sizeof(float));
memset(priv_info->input_pad, 0, batch * input_c * pad_inhw * sizeof(float));
priv_info->dot_block = ( float* )sys_malloc(ELEM_SIZE * block * output_c * sizeof(float));
priv_info->transform_input = ( float* )sys_malloc(ELEM_SIZE * block * input_c * sizeof(float));
priv_info->output_bordered = NULL;
if (outw != output_w || outh != output_h)
{
priv_info->output_bordered = ( float* )sys_malloc(outw * outh * output_c * sizeof(float));
}
conv3x3s1_winograd43_transform_kernel_sse(kernel, ( float* )priv_info->interleave_buffer, input_c, output_c);
return 0;
}
int wino_conv_hcl_postrun(struct conv_priv_info* priv_info)
{
if (!priv_info->external_interleave_mem && priv_info->interleave_buffer != NULL)
{
sys_free(priv_info->interleave_buffer);
priv_info->interleave_buffer = NULL;
}
if (priv_info->input_pad)
{
sys_free(priv_info->input_pad);
priv_info->input_pad = NULL;
}
if (priv_info->dot_block)
{
sys_free(priv_info->dot_block);
priv_info->dot_block = NULL;
}
if (priv_info->transform_input)
{
sys_free(priv_info->transform_input);
priv_info->transform_input = NULL;
}
if (priv_info->output_bordered)
{
sys_free(priv_info->output_bordered);
priv_info->output_bordered = NULL;
}
return 0;
}
int wino_conv_hcl_run(struct tensor* input_tensor, struct tensor* filter_tensor, struct tensor* bias_tensor,
struct tensor* output_tensor, struct conv_priv_info* priv_info, struct conv_param* param,
int num_thread, int cpu_affinity)
{
/* param */
// TLOG_ERR("wino run\n");
int kernel_h = param->kernel_h;
int kernel_w = param->kernel_w;
int stride_h = param->stride_h;
int stride_w = param->stride_w;
int dilation_h = param->dilation_h;
int dilation_w = param->dilation_w;
int pad_h0 = param->pad_h0;
int pad_w0 = param->pad_w0;
int act_type = param->activation;
int group = param->group;
int batch = input_tensor->dims[0];
int in_c = input_tensor->dims[1];
int in_c_g = input_tensor->dims[1] / group;
int in_h = input_tensor->dims[2];
int in_w = input_tensor->dims[3];
int input_size = in_c * in_h * in_w;
int input_size_g = in_c_g * in_h * in_w;
int kernel_size = in_c * kernel_h * kernel_w;
int out_c = output_tensor->dims[1];
int out_h = output_tensor->dims[2];
int out_w = output_tensor->dims[3];
int out_hw = out_h * out_w;
int output_size = out_c * out_h * out_w;
int out_c_align = ((out_c + 3) & -4);
/* wino param */
int block_h = (out_h + TILE - 1) / TILE;
int block_w = (out_w + TILE - 1) / TILE;
int block_hw = block_h * block_w;
int padded_in_h = block_h * TILE + 2 * pad_h0;
int padded_in_w = block_w * TILE + 2 * pad_h0;
int padded_in_hw = padded_in_h * padded_in_w;
/* buffer addr */
float* input = ( float* )input_tensor->data;
float* output = ( float* )output_tensor->data;
float* biases = NULL;
if (bias_tensor != NULL)
biases = ( float* )bias_tensor->data;
pad_0_align_3D(priv_info->input_pad, input, in_h, in_w, padded_in_h, padded_in_w, in_c, pad_h0, pad_w0);
for (int i = 0; i < batch; i++)
{
for (int g = 0; g < group; g++)
{
conv3x3s1_winograd43_sse(priv_info->input_pad + i * input_size + g * input_size_g, output,
priv_info->interleave_buffer, priv_info->dot_block, priv_info->transform_input,
priv_info->output_bordered, biases, padded_in_w, padded_in_h, in_c, out_w, out_h,
out_c, num_thread);
}
}
if (act_type >= 0)
{
relu(output, batch * output_size, act_type);
}
return 0;
}
|
convolution_3x3_e2e_int8.h | // BUG1989 is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2019 BUG1989 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// 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.
#if __ARM_NEON
#include <arm_neon.h>
#include <math.h>
#endif // __ARM_NEON
/*
* conv3x3s1 int8 e2e unroll outch 2
*/
static void conv3x3s1_int8_e2e_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Option& opt)
{
int w = bottom_blob.w;
int h = bottom_blob.h;
int inch = bottom_blob.c;
int outw = top_blob.w;
int outh = top_blob.h;
int outch = top_blob.c;
const signed char* kernel = _kernel;
int nn_outch = outch >> 1;
int remain_outch_start = nn_outch << 1;
#pragma omp parallel for num_threads(opt.num_threads)
for (int pp=0; pp < nn_outch; pp++)
{
int p = pp * 2;
Mat out0 = top_blob.channel(p);
Mat out1 = top_blob.channel(p+1);
out0.fill(0);
out1.fill(0);
const signed char* kernel0 = (const signed char *)kernel + p * inch * 9;
const signed char* kernel1 = (const signed char *)kernel + (p + 1) * inch * 9;
for (int q=0; q<inch; q++)
{
short* outptr0 = out0;
short* outptr1 = out1;
short* outptr0n = outptr0 + outw;
short* outptr1n = outptr1 + outw;
const signed char* img0 = bottom_blob.channel(q);
const signed char* r0 = img0;
const signed char* r1 = img0 + w;
const signed char* r2 = img0 + w * 2;
const signed char* r3 = img0 + w * 3;
const signed char* k00 = kernel0;
const signed char* k03 = kernel0 + 3;
const signed char* k06 = kernel0 + 6;
const signed char* k10 = kernel1;
const signed char* k13 = kernel1 + 3;
const signed char* k16 = kernel1 + 6;
int i = 0;
int8x8_t _k00 = vdup_n_s8(kernel0[0]);
int8x8_t _k01 = vdup_n_s8(kernel0[1]);
int8x8_t _k02 = vdup_n_s8(kernel0[2]);
int8x8_t _k03 = vdup_n_s8(kernel0[3]);
int8x8_t _k04 = vdup_n_s8(kernel0[4]);
int8x8_t _k05 = vdup_n_s8(kernel0[5]);
int8x8_t _k06 = vdup_n_s8(kernel0[6]);
int8x8_t _k07 = vdup_n_s8(kernel0[7]);
int8x8_t _k08 = vdup_n_s8(kernel0[8]);
int8x8_t _k10 = vdup_n_s8(kernel1[0]);
int8x8_t _k11 = vdup_n_s8(kernel1[1]);
int8x8_t _k12 = vdup_n_s8(kernel1[2]);
int8x8_t _k13 = vdup_n_s8(kernel1[3]);
int8x8_t _k14 = vdup_n_s8(kernel1[4]);
int8x8_t _k15 = vdup_n_s8(kernel1[5]);
int8x8_t _k16 = vdup_n_s8(kernel1[6]);
int8x8_t _k17 = vdup_n_s8(kernel1[7]);
int8x8_t _k18 = vdup_n_s8(kernel1[8]);
for (; i+1 < outh; i+=2)
{
int nn = outw >> 3;
int remain = outw & 7;
for (; nn > 0; nn--)
{
// outch 0
int8x8_t _r0 = vld1_s8(r0);
int8x8_t _r0n = vld1_s8(r0+8);
int8x8_t _r01 = vext_s8(_r0, _r0n, 1);
int8x8_t _r02 = vext_s8(_r0, _r0n, 2);
int16x8_t _sum0 = vmull_s8(_r0, _k00);
_sum0 = vmlal_s8(_sum0, _r01, _k01);
_sum0 = vmlal_s8(_sum0, _r02, _k02);
int8x8_t _r1 = vld1_s8(r1);
int8x8_t _r1n = vld1_s8(r1+8);
int8x8_t _r11 = vext_s8(_r1, _r1n, 1);
int8x8_t _r12 = vext_s8(_r1, _r1n, 2);
_sum0 = vmlal_s8(_sum0, _r1, _k03);
_sum0 = vmlal_s8(_sum0, _r11, _k04);
_sum0 = vmlal_s8(_sum0, _r12, _k05);
int16x8_t _sum1 = vmull_s8(_r1, _k00);
_sum1 = vmlal_s8(_sum1, _r11, _k01);
_sum1 = vmlal_s8(_sum1, _r12, _k02);
int8x8_t _r2 = vld1_s8(r2);
int8x8_t _r2n = vld1_s8(r2+8);
int8x8_t _r21 = vext_s8(_r2, _r2n, 1);
int8x8_t _r22 = vext_s8(_r2, _r2n, 2);
_sum0 = vmlal_s8(_sum0, _r2, _k06);
_sum0 = vmlal_s8(_sum0, _r21, _k07);
_sum0 = vmlal_s8(_sum0, _r22, _k08);
_sum1 = vmlal_s8(_sum1, _r2, _k03);
_sum1 = vmlal_s8(_sum1, _r21, _k04);
_sum1 = vmlal_s8(_sum1, _r22, _k05);
int8x8_t _r3 = vld1_s8(r3);
int8x8_t _r3n = vld1_s8(r3+8);
int8x8_t _r31 = vext_s8(_r3, _r3n, 1);
int8x8_t _r32 = vext_s8(_r3, _r3n, 2);
_sum1 = vmlal_s8(_sum1, _r3, _k06);
_sum1 = vmlal_s8(_sum1, _r31, _k07);
_sum1 = vmlal_s8(_sum1, _r32, _k08);
int16x8_t sum0_s16 = vld1q_s16(outptr0);
sum0_s16 = vqaddq_s16(sum0_s16, _sum0);
vst1q_s16(outptr0, sum0_s16);
int16x8_t sum1_s16 = vld1q_s16(outptr0n);
sum1_s16 = vqaddq_s16(sum1_s16, _sum1);
vst1q_s16(outptr0n, sum1_s16);
// outch 1
_sum0 = vmull_s8(_r0, _k10);
_sum0 = vmlal_s8(_sum0, _r01, _k11);
_sum0 = vmlal_s8(_sum0, _r02, _k12);
_sum0 = vmlal_s8(_sum0, _r1, _k13);
_sum0 = vmlal_s8(_sum0, _r11, _k14);
_sum0 = vmlal_s8(_sum0, _r12, _k15);
_sum0 = vmlal_s8(_sum0, _r2, _k16);
_sum0 = vmlal_s8(_sum0, _r21, _k17);
_sum0 = vmlal_s8(_sum0, _r22, _k18);
_sum1 = vmull_s8(_r1, _k10);
_sum1 = vmlal_s8(_sum1, _r11, _k11);
_sum1 = vmlal_s8(_sum1, _r12, _k12);
_sum1 = vmlal_s8(_sum1, _r2, _k13);
_sum1 = vmlal_s8(_sum1, _r21, _k14);
_sum1 = vmlal_s8(_sum1, _r22, _k15);
_sum1 = vmlal_s8(_sum1, _r3, _k16);
_sum1 = vmlal_s8(_sum1, _r31, _k17);
_sum1 = vmlal_s8(_sum1, _r32, _k18);
sum0_s16 = vld1q_s16(outptr1);
sum0_s16 = vqaddq_s16(sum0_s16, _sum0);
vst1q_s16(outptr1, sum0_s16);
sum1_s16 = vld1q_s16(outptr1n);
sum1_s16 = vqaddq_s16(sum1_s16, _sum1);
vst1q_s16(outptr1n, sum1_s16);
r0 += 8;
r1 += 8;
r2 += 8;
r3 += 8;
outptr0 += 8;
outptr1 += 8;
outptr0n += 8;
outptr1n += 8;
}
if (remain >= 4)
{
remain -= 4;
// outch 0
int8x8_t _r0 = vld1_s8(r0);
int8x8_t _r0n = vld1_s8(r0+8);
int8x8_t _r01 = vext_s8(_r0, _r0n, 1);
int8x8_t _r02 = vext_s8(_r0, _r0n, 2);
int16x8_t _sum0 = vmull_s8(_r0, _k00);
_sum0 = vmlal_s8(_sum0, _r01, _k01);
_sum0 = vmlal_s8(_sum0, _r02, _k02);
int8x8_t _r1 = vld1_s8(r1);
int8x8_t _r1n = vld1_s8(r1+8);
int8x8_t _r11 = vext_s8(_r1, _r1n, 1);
int8x8_t _r12 = vext_s8(_r1, _r1n, 2);
_sum0 = vmlal_s8(_sum0, _r1, _k03);
_sum0 = vmlal_s8(_sum0, _r11, _k04);
_sum0 = vmlal_s8(_sum0, _r12, _k05);
int16x8_t _sum1 = vmull_s8(_r1, _k00);
_sum1 = vmlal_s8(_sum1, _r11, _k01);
_sum1 = vmlal_s8(_sum1, _r12, _k02);
int8x8_t _r2 = vld1_s8(r2);
int8x8_t _r2n = vld1_s8(r2+8);
int8x8_t _r21 = vext_s8(_r2, _r2n, 1);
int8x8_t _r22 = vext_s8(_r2, _r2n, 2);
_sum0 = vmlal_s8(_sum0, _r2, _k06);
_sum0 = vmlal_s8(_sum0, _r21, _k07);
_sum0 = vmlal_s8(_sum0, _r22, _k08);
_sum1 = vmlal_s8(_sum1, _r2, _k03);
_sum1 = vmlal_s8(_sum1, _r21, _k04);
_sum1 = vmlal_s8(_sum1, _r22, _k05);
int8x8_t _r3 = vld1_s8(r3);
int8x8_t _r3n = vld1_s8(r3+8);
int8x8_t _r31 = vext_s8(_r3, _r3n, 1);
int8x8_t _r32 = vext_s8(_r3, _r3n, 2);
_sum1 = vmlal_s8(_sum1, _r3, _k06);
_sum1 = vmlal_s8(_sum1, _r31, _k07);
_sum1 = vmlal_s8(_sum1, _r32, _k08);
int16x4_t sum0_s16 = vld1_s16(outptr0);
sum0_s16 = vqadd_s16(sum0_s16, vget_low_s16(_sum0));
vst1_s16(outptr0, sum0_s16);
int16x4_t sum1_s16 = vld1_s16(outptr0n);
sum1_s16 = vqadd_s16(sum1_s16, vget_low_s16(_sum1));
vst1_s16(outptr0n, sum1_s16);
// outch 1
_sum0 = vmull_s8(_r0, _k10);
_sum0 = vmlal_s8(_sum0, _r01, _k11);
_sum0 = vmlal_s8(_sum0, _r02, _k12);
_sum0 = vmlal_s8(_sum0, _r1, _k13);
_sum0 = vmlal_s8(_sum0, _r11, _k14);
_sum0 = vmlal_s8(_sum0, _r12, _k15);
_sum0 = vmlal_s8(_sum0, _r2, _k16);
_sum0 = vmlal_s8(_sum0, _r21, _k17);
_sum0 = vmlal_s8(_sum0, _r22, _k18);
_sum1 = vmull_s8(_r1, _k10);
_sum1 = vmlal_s8(_sum1, _r11, _k11);
_sum1 = vmlal_s8(_sum1, _r12, _k12);
_sum1 = vmlal_s8(_sum1, _r2, _k13);
_sum1 = vmlal_s8(_sum1, _r21, _k14);
_sum1 = vmlal_s8(_sum1, _r22, _k15);
_sum1 = vmlal_s8(_sum1, _r3, _k16);
_sum1 = vmlal_s8(_sum1, _r31, _k17);
_sum1 = vmlal_s8(_sum1, _r32, _k18);
sum0_s16 = vld1_s16(outptr1);
sum0_s16 = vqadd_s16(sum0_s16, vget_low_s16(_sum0));
vst1_s16(outptr1, sum0_s16);
sum1_s16 = vld1_s16(outptr1n);
sum1_s16 = vqadd_s16(sum1_s16, vget_low_s16(_sum1));
vst1_s16(outptr1n, sum1_s16);
r0 += 4;
r1 += 4;
r2 += 4;
r3 += 4;
outptr0 += 4;
outptr1 += 4;
outptr0n += 4;
outptr1n += 4;
}
for (; remain>0; remain--)
{
short sum0 = 0;
short sum0n = 0;
short sum1 = 0;
short sum1n = 0;
//ToDo Neon
sum0 += (short)r0[0] * kernel0[0];
sum0 += (short)r0[1] * kernel0[1];
sum0 += (short)r0[2] * kernel0[2];
sum0 += (short)r1[0] * kernel0[3];
sum0 += (short)r1[1] * kernel0[4];
sum0 += (short)r1[2] * kernel0[5];
sum0 += (short)r2[0] * kernel0[6];
sum0 += (short)r2[1] * kernel0[7];
sum0 += (short)r2[2] * kernel0[8];
sum1 += (short)r0[0] * kernel1[0];
sum1 += (short)r0[1] * kernel1[1];
sum1 += (short)r0[2] * kernel1[2];
sum1 += (short)r1[0] * kernel1[3];
sum1 += (short)r1[1] * kernel1[4];
sum1 += (short)r1[2] * kernel1[5];
sum1 += (short)r2[0] * kernel1[6];
sum1 += (short)r2[1] * kernel1[7];
sum1 += (short)r2[2] * kernel1[8];
sum0n += (short)r1[0] * kernel0[0];
sum0n += (short)r1[1] * kernel0[1];
sum0n += (short)r1[2] * kernel0[2];
sum0n += (short)r2[0] * kernel0[3];
sum0n += (short)r2[1] * kernel0[4];
sum0n += (short)r2[2] * kernel0[5];
sum0n += (short)r3[0] * kernel0[6];
sum0n += (short)r3[1] * kernel0[7];
sum0n += (short)r3[2] * kernel0[8];
sum1n += (short)r1[0] * kernel1[0];
sum1n += (short)r1[1] * kernel1[1];
sum1n += (short)r1[2] * kernel1[2];
sum1n += (short)r2[0] * kernel1[3];
sum1n += (short)r2[1] * kernel1[4];
sum1n += (short)r2[2] * kernel1[5];
sum1n += (short)r3[0] * kernel1[6];
sum1n += (short)r3[1] * kernel1[7];
sum1n += (short)r3[2] * kernel1[8];
*outptr0 += sum0;
*outptr1 += sum1;
*outptr0n += sum0n;
*outptr1n += sum1n;
r0++;
r1++;
r2++;
r3++;
outptr0++;
outptr1++;
outptr0n++;
outptr1n++;
}
r0 += 2 + w;
r1 += 2 + w;
r2 += 2 + w;
r3 += 2 + w;
outptr0 += outw;
outptr1 += outw;
outptr0n += outw;
outptr1n += outw;
}
for (; i < outh; i++)
{
int nn = outw >> 3;
int remain = outw & 7;
for (; nn > 0; nn--)
{
// outch 0
int8x8_t _r0 = vld1_s8(r0);
int8x8_t _r0n = vld1_s8(r0+8);
int8x8_t _r01 = vext_s8(_r0, _r0n, 1);
int8x8_t _r02 = vext_s8(_r0, _r0n, 2);
int16x8_t _sum0 = vmull_s8(_r0, _k00);
_sum0 = vmlal_s8(_sum0, _r01, _k01);
_sum0 = vmlal_s8(_sum0, _r02, _k02);
int8x8_t _r1 = vld1_s8(r1);
int8x8_t _r1n = vld1_s8(r1+8);
int8x8_t _r11 = vext_s8(_r1, _r1n, 1);
int8x8_t _r12 = vext_s8(_r1, _r1n, 2);
_sum0 = vmlal_s8(_sum0, _r1, _k03);
_sum0 = vmlal_s8(_sum0, _r11, _k04);
_sum0 = vmlal_s8(_sum0, _r12, _k05);
int8x8_t _r2 = vld1_s8(r2);
int8x8_t _r2n = vld1_s8(r2+8);
int8x8_t _r21 = vext_s8(_r2, _r2n, 1);
int8x8_t _r22 = vext_s8(_r2, _r2n, 2);
_sum0 = vmlal_s8(_sum0, _r2, _k06);
_sum0 = vmlal_s8(_sum0, _r21, _k07);
_sum0 = vmlal_s8(_sum0, _r22, _k08);
int16x8_t sum0_s16 = vld1q_s16(outptr0);
sum0_s16 = vqaddq_s16(sum0_s16, _sum0);
vst1q_s16(outptr0, sum0_s16);
// outch 1
_sum0 = vmull_s8(_r0, _k10);
_sum0 = vmlal_s8(_sum0, _r01, _k11);
_sum0 = vmlal_s8(_sum0, _r02, _k12);
_sum0 = vmlal_s8(_sum0, _r1, _k13);
_sum0 = vmlal_s8(_sum0, _r11, _k14);
_sum0 = vmlal_s8(_sum0, _r12, _k15);
_sum0 = vmlal_s8(_sum0, _r2, _k16);
_sum0 = vmlal_s8(_sum0, _r21, _k17);
_sum0 = vmlal_s8(_sum0, _r22, _k18);
sum0_s16 = vld1q_s16(outptr1);
sum0_s16 = vqaddq_s16(sum0_s16, _sum0);
vst1q_s16(outptr1, sum0_s16);
r0 += 8;
r1 += 8;
r2 += 8;
outptr0 += 8;
outptr1 += 8;
}
for (; remain>0; remain--)
{
short sum0 = 0;
short sum1 = 0;
sum0 += (short)r0[0] * kernel0[0];
sum0 += (short)r0[1] * kernel0[1];
sum0 += (short)r0[2] * kernel0[2];
sum0 += (short)r1[0] * kernel0[3];
sum0 += (short)r1[1] * kernel0[4];
sum0 += (short)r1[2] * kernel0[5];
sum0 += (short)r2[0] * kernel0[6];
sum0 += (short)r2[1] * kernel0[7];
sum0 += (short)r2[2] * kernel0[8];
sum1 += (short)r0[0] * kernel1[0];
sum1 += (short)r0[1] * kernel1[1];
sum1 += (short)r0[2] * kernel1[2];
sum1 += (short)r1[0] * kernel1[3];
sum1 += (short)r1[1] * kernel1[4];
sum1 += (short)r1[2] * kernel1[5];
sum1 += (short)r2[0] * kernel1[6];
sum1 += (short)r2[1] * kernel1[7];
sum1 += (short)r2[2] * kernel1[8];
*outptr0 += sum0;
*outptr1 += sum1;
r0++;
r1++;
r2++;
outptr0++;
outptr1++;
}
r0 += 2;
r1 += 2;
r2 += 2;
}
kernel0 += 9;
kernel1 += 9;
}
}
#pragma omp parallel for num_threads(opt.num_threads)
for (int p=remain_outch_start; p<outch; p++)
{
Mat out0 = top_blob.channel(p);
out0.fill(0);
const signed char* kernel0 = (const signed char *)kernel + p * inch * 9;
for (int q=0; q<inch; q++)
{
short* outptr0 = out0;
short* outptr0n = outptr0 + outw;
const signed char* img0 = bottom_blob.channel(q);
const signed char* r0 = img0;
const signed char* r1 = img0 + w;
const signed char* r2 = img0 + w * 2;
const signed char* r3 = img0 + w * 3;
const signed char* k00 = kernel0;
const signed char* k03 = kernel0 + 3;
const signed char* k06 = kernel0 + 6;
int i = 0;
int8x8_t _k00 = vdup_n_s8(kernel0[0]);
int8x8_t _k01 = vdup_n_s8(kernel0[1]);
int8x8_t _k02 = vdup_n_s8(kernel0[2]);
int8x8_t _k03 = vdup_n_s8(kernel0[3]);
int8x8_t _k04 = vdup_n_s8(kernel0[4]);
int8x8_t _k05 = vdup_n_s8(kernel0[5]);
int8x8_t _k06 = vdup_n_s8(kernel0[6]);
int8x8_t _k07 = vdup_n_s8(kernel0[7]);
int8x8_t _k08 = vdup_n_s8(kernel0[8]);
for (; i+1 < outh; i+=2)
{
int nn = outw >> 3;
int remain = outw & 7;
for (; nn > 0; nn--)
{
int8x8_t _r0 = vld1_s8(r0);
int8x8_t _r0n = vld1_s8(r0+8);
int8x8_t _r01 = vext_s8(_r0, _r0n, 1);
int8x8_t _r02 = vext_s8(_r0, _r0n, 2);
int16x8_t _sum0 = vmull_s8(_r0, _k00);
_sum0 = vmlal_s8(_sum0, _r01, _k01);
_sum0 = vmlal_s8(_sum0, _r02, _k02);
int8x8_t _r1 = vld1_s8(r1);
int8x8_t _r1n = vld1_s8(r1+8);
int8x8_t _r11 = vext_s8(_r1, _r1n, 1);
int8x8_t _r12 = vext_s8(_r1, _r1n, 2);
_sum0 = vmlal_s8(_sum0, _r1, _k03);
_sum0 = vmlal_s8(_sum0, _r11, _k04);
_sum0 = vmlal_s8(_sum0, _r12, _k05);
int16x8_t _sum1 = vmull_s8(_r1, _k00);
_sum1 = vmlal_s8(_sum1, _r11, _k01);
_sum1 = vmlal_s8(_sum1, _r12, _k02);
int8x8_t _r2 = vld1_s8(r2);
int8x8_t _r2n = vld1_s8(r2+8);
int8x8_t _r21 = vext_s8(_r2, _r2n, 1);
int8x8_t _r22 = vext_s8(_r2, _r2n, 2);
_sum0 = vmlal_s8(_sum0, _r2, _k06);
_sum0 = vmlal_s8(_sum0, _r21, _k07);
_sum0 = vmlal_s8(_sum0, _r22, _k08);
_sum1 = vmlal_s8(_sum1, _r2, _k03);
_sum1 = vmlal_s8(_sum1, _r21, _k04);
_sum1 = vmlal_s8(_sum1, _r22, _k05);
int8x8_t _r3 = vld1_s8(r3);
int8x8_t _r3n = vld1_s8(r3+8);
int8x8_t _r31 = vext_s8(_r3, _r3n, 1);
int8x8_t _r32 = vext_s8(_r3, _r3n, 2);
_sum1 = vmlal_s8(_sum1, _r3, _k06);
_sum1 = vmlal_s8(_sum1, _r31, _k07);
_sum1 = vmlal_s8(_sum1, _r32, _k08);
int16x8_t sum0_s16 = vld1q_s16(outptr0);
sum0_s16 = vqaddq_s16(sum0_s16, _sum0);
vst1q_s16(outptr0, sum0_s16);
int16x8_t sum1_s16 = vld1q_s16(outptr0n);
sum1_s16 = vqaddq_s16(sum1_s16, _sum1);
vst1q_s16(outptr0n, sum1_s16);
r0 += 8;
r1 += 8;
r2 += 8;
r3 += 8;
outptr0 += 8;
outptr0n += 8;
}
if (remain >= 4)
{
remain -= 4;
int8x8_t _r0 = vld1_s8(r0);
int8x8_t _r0n = vld1_s8(r0+8);
int8x8_t _r01 = vext_s8(_r0, _r0n, 1);
int8x8_t _r02 = vext_s8(_r0, _r0n, 2);
int16x8_t _sum0 = vmull_s8(_r0, _k00);
_sum0 = vmlal_s8(_sum0, _r01, _k01);
_sum0 = vmlal_s8(_sum0, _r02, _k02);
int8x8_t _r1 = vld1_s8(r1);
int8x8_t _r1n = vld1_s8(r1+8);
int8x8_t _r11 = vext_s8(_r1, _r1n, 1);
int8x8_t _r12 = vext_s8(_r1, _r1n, 2);
_sum0 = vmlal_s8(_sum0, _r1, _k03);
_sum0 = vmlal_s8(_sum0, _r11, _k04);
_sum0 = vmlal_s8(_sum0, _r12, _k05);
int16x8_t _sum1 = vmull_s8(_r1, _k00);
_sum1 = vmlal_s8(_sum1, _r11, _k01);
_sum1 = vmlal_s8(_sum1, _r12, _k02);
int8x8_t _r2 = vld1_s8(r2);
int8x8_t _r2n = vld1_s8(r2+8);
int8x8_t _r21 = vext_s8(_r2, _r2n, 1);
int8x8_t _r22 = vext_s8(_r2, _r2n, 2);
_sum0 = vmlal_s8(_sum0, _r2, _k06);
_sum0 = vmlal_s8(_sum0, _r21, _k07);
_sum0 = vmlal_s8(_sum0, _r22, _k08);
_sum1 = vmlal_s8(_sum1, _r2, _k03);
_sum1 = vmlal_s8(_sum1, _r21, _k04);
_sum1 = vmlal_s8(_sum1, _r22, _k05);
int8x8_t _r3 = vld1_s8(r3);
int8x8_t _r3n = vld1_s8(r3+8);
int8x8_t _r31 = vext_s8(_r3, _r3n, 1);
int8x8_t _r32 = vext_s8(_r3, _r3n, 2);
_sum1 = vmlal_s8(_sum1, _r3, _k06);
_sum1 = vmlal_s8(_sum1, _r31, _k07);
_sum1 = vmlal_s8(_sum1, _r32, _k08);
int16x4_t sum0_s16 = vld1_s16(outptr0);
sum0_s16 = vqadd_s16(sum0_s16, vget_low_s16(_sum0));
vst1_s16(outptr0, sum0_s16);
int16x4_t sum1_s16 = vld1_s16(outptr0n);
sum1_s16 = vqadd_s16(sum1_s16, vget_low_s16(_sum1));
vst1_s16(outptr0n, sum1_s16);
r0 += 4;
r1 += 4;
r2 += 4;
r3 += 4;
outptr0 += 4;
outptr0n += 4;
}
for (; remain>0; remain--)
{
// Todo neon
short sum0 = 0;
short sum0n = 0;
sum0 += (short)r0[0] * kernel0[0];
sum0 += (short)r0[1] * kernel0[1];
sum0 += (short)r0[2] * kernel0[2];
sum0 += (short)r1[0] * kernel0[3];
sum0 += (short)r1[1] * kernel0[4];
sum0 += (short)r1[2] * kernel0[5];
sum0 += (short)r2[0] * kernel0[6];
sum0 += (short)r2[1] * kernel0[7];
sum0 += (short)r2[2] * kernel0[8];
sum0n += (short)r1[0] * kernel0[0];
sum0n += (short)r1[1] * kernel0[1];
sum0n += (short)r1[2] * kernel0[2];
sum0n += (short)r2[0] * kernel0[3];
sum0n += (short)r2[1] * kernel0[4];
sum0n += (short)r2[2] * kernel0[5];
sum0n += (short)r3[0] * kernel0[6];
sum0n += (short)r3[1] * kernel0[7];
sum0n += (short)r3[2] * kernel0[8];
*outptr0 += sum0;
*outptr0n += sum0n;
r0++;
r1++;
r2++;
r3++;
outptr0++;
outptr0n++;
}
r0 += 2 + w;
r1 += 2 + w;
r2 += 2 + w;
r3 += 2 + w;
outptr0 += outw;
outptr0n += outw;
}
for (; i < outh; i++)
{
int nn = outw >> 3;
int remain = outw & 7;
for (; nn > 0; nn--)
{
int8x8_t _r0 = vld1_s8(r0);
int8x8_t _r0n = vld1_s8(r0+8);
int8x8_t _r01 = vext_s8(_r0, _r0n, 1);
int8x8_t _r02 = vext_s8(_r0, _r0n, 2);
int16x8_t _sum0 = vmull_s8(_r0, _k00);
_sum0 = vmlal_s8(_sum0, _r01, _k01);
_sum0 = vmlal_s8(_sum0, _r02, _k02);
int8x8_t _r1 = vld1_s8(r1);
int8x8_t _r1n = vld1_s8(r1+8);
int8x8_t _r11 = vext_s8(_r1, _r1n, 1);
int8x8_t _r12 = vext_s8(_r1, _r1n, 2);
_sum0 = vmlal_s8(_sum0, _r1, _k03);
_sum0 = vmlal_s8(_sum0, _r11, _k04);
_sum0 = vmlal_s8(_sum0, _r12, _k05);
int8x8_t _r2 = vld1_s8(r2);
int8x8_t _r2n = vld1_s8(r2+8);
int8x8_t _r21 = vext_s8(_r2, _r2n, 1);
int8x8_t _r22 = vext_s8(_r2, _r2n, 2);
_sum0 = vmlal_s8(_sum0, _r2, _k06);
_sum0 = vmlal_s8(_sum0, _r21, _k07);
_sum0 = vmlal_s8(_sum0, _r22, _k08);
int16x4_t sum0_s16 = vld1_s16(outptr0);
sum0_s16 = vqadd_s16(sum0_s16, vget_low_s16(_sum0));
vst1_s16(outptr0, sum0_s16);
r0 += 8;
r1 += 8;
r2 += 8;
outptr0 += 8;
}
for (; remain>0; remain--)
{
short sum0 = 0;
sum0 += (short)r0[0] * kernel0[0];
sum0 += (short)r0[1] * kernel0[1];
sum0 += (short)r0[2] * kernel0[2];
sum0 += (short)r1[0] * kernel0[3];
sum0 += (short)r1[1] * kernel0[4];
sum0 += (short)r1[2] * kernel0[5];
sum0 += (short)r2[0] * kernel0[6];
sum0 += (short)r2[1] * kernel0[7];
sum0 += (short)r2[2] * kernel0[8];
*outptr0 += sum0;
r0++;
r1++;
r2++;
outptr0++;
}
r0 += 2;
r1 += 2;
r2 += 2;
}
kernel0 += 9;
}
}
}
/*
* conv3x3s2 int8 e2e unroll outch 4
*/
static void conv3x3s2_int8_e2e_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Option& opt)
{
int w = bottom_blob.w;
int h = bottom_blob.h;
int inch = bottom_blob.c;
int outw = top_blob.w;
int outh = top_blob.h;
int outch = top_blob.c;
const int tailstep = w - 2 * outw + w;
const signed char* kernel = _kernel;
int nn_outch = outch >> 2;
int remain_outch_start = nn_outch << 2;
#pragma omp parallel for num_threads(opt.num_threads)
for (int pp=0; pp < nn_outch; pp++)
{
int p = pp * 4;
Mat out0 = top_blob.channel(p);
Mat out1 = top_blob.channel(p + 1);
Mat out2 = top_blob.channel(p + 2);
Mat out3 = top_blob.channel(p + 3);
out0.fill(0.f);
out1.fill(0.f);
out2.fill(0.f);
out3.fill(0.f);
const signed char* kernel0 = (const signed char*)kernel + p * inch * 9;
const signed char* kernel1 = (const signed char*)kernel + (p + 1) * inch * 9;
const signed char* kernel2 = (const signed char*)kernel + (p + 2) * inch * 9;
const signed char* kernel3 = (const signed char*)kernel + (p + 3) * inch * 9;
for (int q=0; q<inch; q++)
{
short* outptr0 = out0;
short* outptr1 = out1;
short* outptr2 = out2;
short* outptr3 = out3;
const signed char* img0 = bottom_blob.channel(q);
const signed char* r0 = img0;
const signed char* r1 = img0 + w;
const signed char* r2 = img0 + w * 2;
int i = 0;
int8x16_t _k0 = vld1q_s8(kernel0);
int8x16_t _k1 = vld1q_s8(kernel1);
int8x16_t _k2 = vld1q_s8(kernel2);
int8x16_t _k3 = vld1q_s8(kernel3);
for (; i < outh; i++)
{
int nn = outw >> 3;
int remain = outw & 7;
if (nn > 0)
{
asm volatile(
"0: \n"
// r0
"prfm pldl1keep, [%5, #128] \n"
"ld2 {v4.8b, v5.8b}, [%5], #16 \n"
"ld2 {v6.8b, v7.8b}, [%5] \n"
"ext v8.8b, v4.8b, v6.8b, #1 \n"
"dup v9.8b, %16.b[0] \n"
"dup v10.8b, %17.b[0] \n"
"dup v11.8b, %18.b[0] \n"
"dup v12.8b, %19.b[0] \n"
"smull v13.8h, v4.8b, v9.8b \n"
"smull v14.8h, v4.8b, v10.8b \n"
"smull v15.8h, v4.8b, v11.8b \n"
"smull v16.8h, v4.8b, v12.8b \n"
"dup v9.8b, %16.b[1] \n"
"dup v10.8b, %17.b[1] \n"
"dup v11.8b, %18.b[1] \n"
"dup v12.8b, %19.b[1] \n"
"smlal v13.8h, v5.8b, v9.8b \n"
"smlal v14.8h, v5.8b, v10.8b \n"
"smlal v15.8h, v5.8b, v11.8b \n"
"smlal v16.8h, v5.8b, v12.8b \n"
"dup v9.8b, %16.b[2] \n"
"dup v10.8b, %17.b[2] \n"
"dup v11.8b, %18.b[2] \n"
"dup v12.8b, %19.b[2] \n"
"smlal v13.8h, v8.8b, v9.8b \n"
"smlal v14.8h, v8.8b, v10.8b \n"
"smlal v15.8h, v8.8b, v11.8b \n"
"smlal v16.8h, v8.8b, v12.8b \n"
// r1
"prfm pldl1keep, [%6, #128] \n"
"ld2 {v4.8b, v5.8b}, [%6], #16 \n"
"ld2 {v6.8b, v7.8b}, [%6] \n"
"ext v8.8b, v4.8b, v6.8b, #1 \n"
"dup v9.8b, %16.b[3] \n"
"dup v10.8b, %17.b[3] \n"
"dup v11.8b, %18.b[3] \n"
"dup v12.8b, %19.b[3] \n"
"smlal v13.8h, v4.8b, v9.8b \n"
"smlal v14.8h, v4.8b, v10.8b \n"
"smlal v15.8h, v4.8b, v11.8b \n"
"smlal v16.8h, v4.8b, v12.8b \n"
"dup v9.8b, %16.b[4] \n"
"dup v10.8b, %17.b[4] \n"
"dup v11.8b, %18.b[4] \n"
"dup v12.8b, %19.b[4] \n"
"smlal v13.8h, v5.8b, v9.8b \n"
"smlal v14.8h, v5.8b, v10.8b \n"
"smlal v15.8h, v5.8b, v11.8b \n"
"smlal v16.8h, v5.8b, v12.8b \n"
"dup v9.8b, %16.b[5] \n"
"dup v10.8b, %17.b[5] \n"
"dup v11.8b, %18.b[5] \n"
"dup v12.8b, %19.b[5] \n"
"smlal v13.8h, v8.8b, v9.8b \n"
"smlal v14.8h, v8.8b, v10.8b \n"
"smlal v15.8h, v8.8b, v11.8b \n"
"smlal v16.8h, v8.8b, v12.8b \n"
// r2
"prfm pldl1keep, [%7, #128] \n"
"ld2 {v4.8b, v5.8b}, [%7], #16 \n"
"ld2 {v6.8b, v7.8b}, [%7] \n"
"ext v8.8b, v4.8b, v6.8b, #1 \n"
"dup v9.8b, %16.b[6] \n"
"dup v10.8b, %17.b[6] \n"
"dup v11.8b, %18.b[6] \n"
"dup v12.8b, %19.b[6] \n"
"smlal v13.8h, v4.8b, v9.8b \n"
"smlal v14.8h, v4.8b, v10.8b \n"
"smlal v15.8h, v4.8b, v11.8b \n"
"smlal v16.8h, v4.8b, v12.8b \n"
"dup v9.8b, %16.b[7] \n"
"dup v10.8b, %17.b[7] \n"
"dup v11.8b, %18.b[7] \n"
"dup v12.8b, %19.b[7] \n"
"smlal v13.8h, v5.8b, v9.8b \n"
"smlal v14.8h, v5.8b, v10.8b \n"
"smlal v15.8h, v5.8b, v11.8b \n"
"smlal v16.8h, v5.8b, v12.8b \n"
"dup v9.8b, %16.b[8] \n"
"dup v10.8b, %17.b[8] \n"
"dup v11.8b, %18.b[8] \n"
"dup v12.8b, %19.b[8] \n"
"smlal v13.8h, v8.8b, v9.8b \n"
"smlal v14.8h, v8.8b, v10.8b \n"
"smlal v15.8h, v8.8b, v11.8b \n"
"smlal v16.8h, v8.8b, v12.8b \n"
// sum0 - sum3
"prfm pldl1keep, [%1, #128] \n"
"prfm pldl1keep, [%2, #128] \n"
"prfm pldl1keep, [%3, #128] \n"
"prfm pldl1keep, [%4, #128] \n"
"ld1 {v17.8h}, [%1] \n"
"ld1 {v19.8h}, [%2] \n"
"ld1 {v21.8h}, [%3] \n"
"ld1 {v23.8h}, [%4] \n"
"sqadd v17.8h, v17.8h, v13.8h \n"
"sqadd v19.8h, v19.8h, v14.8h \n"
"sqadd v21.8h, v21.8h, v15.8h \n"
"sqadd v23.8h, v23.8h, v16.8h \n"
"st1 {v17.8h}, [%1], #16 \n"
"st1 {v19.8h}, [%2], #16 \n"
"st1 {v21.8h}, [%3], #16 \n"
"st1 {v23.8h}, [%4], #16 \n"
"subs %w0, %w0, #1 \n"
"bne 0b \n"
: "=r"(nn), //%0
"=r"(outptr0), //%1
"=r"(outptr1), //%2
"=r"(outptr2), //%3
"=r"(outptr3), //%4
"=r"(r0), //%5
"=r"(r1), //%6
"=r"(r2) //%7
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(outptr2),
"4"(outptr3),
"5"(r0),
"6"(r1),
"7"(r2),
"w"(_k0), //%16
"w"(_k1), //%17
"w"(_k2), //%18
"w"(_k3) //%19
: "cc", "memory", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24"
);
}
for (; remain>0; remain--)
{
short sum0 = 0;
short sum1 = 0;
short sum2 = 0;
short sum3 = 0;
sum0 += (short)r0[0] * kernel0[0];
sum0 += (short)r0[1] * kernel0[1];
sum0 += (short)r0[2] * kernel0[2];
sum0 += (short)r1[0] * kernel0[3];
sum0 += (short)r1[1] * kernel0[4];
sum0 += (short)r1[2] * kernel0[5];
sum0 += (short)r2[0] * kernel0[6];
sum0 += (short)r2[1] * kernel0[7];
sum0 += (short)r2[2] * kernel0[8];
sum1 += (short)r0[0] * kernel1[0];
sum1 += (short)r0[1] * kernel1[1];
sum1 += (short)r0[2] * kernel1[2];
sum1 += (short)r1[0] * kernel1[3];
sum1 += (short)r1[1] * kernel1[4];
sum1 += (short)r1[2] * kernel1[5];
sum1 += (short)r2[0] * kernel1[6];
sum1 += (short)r2[1] * kernel1[7];
sum1 += (short)r2[2] * kernel1[8];
sum2 += (short)r0[0] * kernel2[0];
sum2 += (short)r0[1] * kernel2[1];
sum2 += (short)r0[2] * kernel2[2];
sum2 += (short)r1[0] * kernel2[3];
sum2 += (short)r1[1] * kernel2[4];
sum2 += (short)r1[2] * kernel2[5];
sum2 += (short)r2[0] * kernel2[6];
sum2 += (short)r2[1] * kernel2[7];
sum2 += (short)r2[2] * kernel2[8];
sum3 += (short)r0[0] * kernel3[0];
sum3 += (short)r0[1] * kernel3[1];
sum3 += (short)r0[2] * kernel3[2];
sum3 += (short)r1[0] * kernel3[3];
sum3 += (short)r1[1] * kernel3[4];
sum3 += (short)r1[2] * kernel3[5];
sum3 += (short)r2[0] * kernel3[6];
sum3 += (short)r2[1] * kernel3[7];
sum3 += (short)r2[2] * kernel3[8];
*outptr0 += sum0;
*outptr1 += sum1;
*outptr2 += sum2;
*outptr3 += sum3;
r0 += 2;
r1 += 2;
r2 += 2;
outptr0++;
outptr1++;
outptr2++;
outptr3++;
}
r0 += tailstep;
r1 += tailstep;
r2 += tailstep;
}
kernel0 += 9;
kernel1 += 9;
kernel2 += 9;
kernel3 += 9;
}
}
#pragma omp parallel for num_threads(opt.num_threads)
for (int p=remain_outch_start; p<outch; p++)
{
Mat out0 = top_blob.channel(p);
out0.fill(0.f);
const signed char* kernel0 = (const signed char*)kernel + p * inch * 9;
for (int q=0; q<inch; q++)
{
short* outptr0 = out0;
const signed char* img0 = bottom_blob.channel(q);
const signed char* r0 = img0;
const signed char* r1 = img0 + w;
const signed char* r2 = img0 + w * 2;
const signed char* k00 = kernel0;
const signed char* k01 = kernel0 + 3;
const signed char* k02 = kernel0 + 6;
int i = 0;
int8x8_t _k0 = vdup_n_s8(kernel[0]);
int8x8_t _k1 = vdup_n_s8(kernel[1]);
int8x8_t _k2 = vdup_n_s8(kernel[2]);
int8x8_t _k3 = vdup_n_s8(kernel[3]);
int8x8_t _k4 = vdup_n_s8(kernel[4]);
int8x8_t _k5 = vdup_n_s8(kernel[5]);
int8x8_t _k6 = vdup_n_s8(kernel[6]);
int8x8_t _k7 = vdup_n_s8(kernel[7]);
int8x8_t _k8 = vdup_n_s8(kernel[8]);
for (; i < outh; i++)
{
int nn = outw >> 3;
int remain = outw & 7;
for (; nn >0; nn--)
{
int8x8x2_t _r0 = vld2_s8(r0);
int8x8x2_t _r0n = vld2_s8(r0+16);
int8x8_t _r00 = _r0.val[0];
int8x8_t _r01 = _r0.val[1];
int8x8_t _r02 = vext_s8(_r00, _r0n.val[0], 1);
int16x8_t _sum = vmull_s8(_r00, _k0);
_sum = vmlal_s8(_sum, _r01, _k1);
_sum = vmlal_s8(_sum, _r02, _k2);
int8x8x2_t _r1 = vld2_s8(r1);
int8x8x2_t _r1n = vld2_s8(r1+16);
int8x8_t _r10 = _r1.val[0];
int8x8_t _r11 = _r1.val[1];
int8x8_t _r12 = vext_s8(_r10, _r1n.val[0], 1);
_sum = vmlal_s8(_sum, _r10, _k3);
_sum = vmlal_s8(_sum, _r11, _k4);
_sum = vmlal_s8(_sum, _r12, _k5);
int8x8x2_t _r2 = vld2_s8(r2);
int8x8x2_t _r2n = vld2_s8(r2+16);
int8x8_t _r20 = _r2.val[0];
int8x8_t _r21 = _r2.val[1];
int8x8_t _r22 = vext_s8(_r20, _r2n.val[0], 1);
_sum = vmlal_s8(_sum, _r20, _k6);
_sum = vmlal_s8(_sum, _r21, _k7);
_sum = vmlal_s8(_sum, _r22, _k8);
int16x8_t sum0_s16 = vld1q_s16(outptr0);
sum0_s16 = vqaddq_s16(sum0_s16, _sum);
vst1q_s16(outptr0, sum0_s16);
r0 += 16;
r1 += 16;
r2 += 16;
outptr0 += 8;
}
for (; remain>0; remain--)
{
short sum0 = 0;
sum0 += (short)r0[0] * kernel0[0];
sum0 += (short)r0[1] * kernel0[1];
sum0 += (short)r0[2] * kernel0[2];
sum0 += (short)r1[0] * kernel0[3];
sum0 += (short)r1[1] * kernel0[4];
sum0 += (short)r1[2] * kernel0[5];
sum0 += (short)r2[0] * kernel0[6];
sum0 += (short)r2[1] * kernel0[7];
sum0 += (short)r2[2] * kernel0[8];
*outptr0 += sum0;
r0 += 2;
r1 += 2;
r2 += 2;
outptr0++;
}
r0 += tailstep;
r1 += tailstep;
r2 += tailstep;
}
kernel0 += 9;
}
}
}
static void conv3x3s2_packed_int8_e2e_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Option& opt)
{
int w = bottom_blob.w;
int inch = bottom_blob.c;
int outw = top_blob.w;
int outh = top_blob.h;
int outch = top_blob.c;
const int tailstep = w - 2*outw + w;
int nn_outch = outch >> 3;
int remain_outch_start = nn_outch << 3;
#pragma omp parallel for num_threads(opt.num_threads)
for (int pp=0; pp<nn_outch; pp++)
{
int p = pp * 8;
Mat out0 = top_blob.channel(p+0);
Mat out1 = top_blob.channel(p+1);
Mat out2 = top_blob.channel(p+2);
Mat out3 = top_blob.channel(p+3);
Mat out4 = top_blob.channel(p+4);
Mat out5 = top_blob.channel(p+5);
Mat out6 = top_blob.channel(p+6);
Mat out7 = top_blob.channel(p+7);
out0.fill(0);
out1.fill(0);
out2.fill(0);
out3.fill(0);
out4.fill(0);
out5.fill(0);
out6.fill(0);
out7.fill(0);
const signed char* ktmp = _kernel.channel(p/8);
for (int q=0; q<inch; q++)
{
short* outptr0 = out0;
short* outptr1 = out1;
short* outptr2 = out2;
short* outptr3 = out3;
short* outptr4 = out4;
short* outptr5 = out5;
short* outptr6 = out6;
short* outptr7 = out7;
const signed char* img0 = bottom_blob.channel(q);
const signed char* r0 = img0;
const signed char* r1 = img0 + w;
const signed char* r2 = img0 + w*2;
int i = 0;
for (; i < outh; i++)
{
#if 0 //__ARM_NEON
#if __aarch64__
int nn = outw >> 3;
int remain = outw & 7;
#else
int nn = outw >> 2;
int remain = outw & 3;
#endif // __aarch64__
#else
int remain = outw;
#endif // __ARM_NEON
#if 0 // __ARM_NEON
#if __aarch64__
if (nn > 0)
{
asm volatile(
"0: \n"
"ld1 {v0.8b, v1.8b, v2.8b}, [%12], #24 \n"//ktmp
"ld2 {v3.8b, v4.8b}, [%9], #16 \n"//r0-r2
"ld2 {v5.8b, v6.8b}, [%9] \n"
"ld1 {v8.4s, v9.4s}, [%1] \n"//out0
"ld1 {v10.4s, v11.4s}, [%2] \n"//out1
"ld1 {v12.4s, v13.4s}, [%3] \n"//out2
"ld1 {v14.4s, v15.4s}, [%4] \n"//out3
"ld1 {v16.4s, v17.4s}, [%5] \n"//out4
"ld1 {v18.4s, v19.4s}, [%6] \n"//out5
"ld1 {v20.4s, v21.4s}, [%7] \n"//out6
"ld1 {v22.4s, v23.4s}, [%8] \n"//out7
"ext v7.8b, v3.8b, v5.8b, #1 \n"
"sshll v0.8h, v0.8b, #0 \n"//(k00-k70)
"sshll v1.8h, v1.8b, #0 \n"//(k01-k71)
"sshll v2.8h, v2.8b, #0 \n"//(k02-k72)
"sshll v3.8h, v3.8b, #0 \n"// r0
"sshll v4.8h, v4.8b, #0 \n"// r1
"sshll v7.8h, v7.8b, #0 \n"// r2
// r0
"smlal v8.4s, v3.4h, v0.h[0] \n"// out0 += (r00-r07)*k00
"smlal2 v9.4s, v3.8h, v0.h[0] \n"
"smlal v10.4s, v3.4h, v0.h[1] \n"// out1 += (r00-r07)*k10
"smlal2 v11.4s, v3.8h, v0.h[1] \n"
"smlal v12.4s, v3.4h, v0.h[2] \n"// out2 += (r00-r07)*k20
"smlal2 v13.4s, v3.8h, v0.h[2] \n"
"smlal v14.4s, v3.4h, v0.h[3] \n"// out3 += (r00-r07)*k30
"smlal2 v15.4s, v3.8h, v0.h[3] \n"
"smlal v16.4s, v3.4h, v0.h[4] \n"// out4 += (r00-r07)*k40
"smlal2 v17.4s, v3.8h, v0.h[4] \n"
"smlal v18.4s, v3.4h, v0.h[5] \n"// out5 += (r00-r07)*k50
"smlal2 v19.4s, v3.8h, v0.h[5] \n"
"smlal v20.4s, v3.4h, v0.h[6] \n"// out6 += (r00-r07)*k60
"smlal2 v21.4s, v3.8h, v0.h[6] \n"
"smlal v22.4s, v3.4h, v0.h[7] \n"// out7 += (r00-r07)*k70
"smlal2 v23.4s, v3.8h, v0.h[7] \n"
// r1
"smlal v8.4s, v4.4h, v1.h[0] \n"// out0 += (r10-r17)*k01
"smlal2 v9.4s, v4.8h, v1.h[0] \n"
"smlal v10.4s, v4.4h, v1.h[1] \n"// out1 += (r10-r17)*k11
"smlal2 v11.4s, v4.8h, v1.h[1] \n"
"smlal v12.4s, v4.4h, v1.h[2] \n"// out2 += (r10-r17)*k21
"smlal2 v13.4s, v4.8h, v1.h[2] \n"
"smlal v14.4s, v4.4h, v1.h[3] \n"// out3 += (r10-r17)*k31
"smlal2 v15.4s, v4.8h, v1.h[3] \n"
"smlal v16.4s, v4.4h, v1.h[4] \n"// out4 += (r10-r17)*k41
"smlal2 v17.4s, v4.8h, v1.h[4] \n"
"smlal v18.4s, v4.4h, v1.h[5] \n"// out5 += (r10-r17)*k51
"smlal2 v19.4s, v4.8h, v1.h[5] \n"
"smlal v20.4s, v4.4h, v1.h[6] \n"// out6 += (r10-r17)*k61
"smlal2 v21.4s, v4.8h, v1.h[6] \n"
"smlal v22.4s, v4.4h, v1.h[7] \n"// out7 += (r10-r17)*k71
"smlal2 v23.4s, v4.8h, v1.h[7] \n"
// r2
"smlal v8.4s, v7.4h, v2.h[0] \n"// out0 += (r20-r27)*k02
"smlal2 v9.4s, v7.8h, v2.h[0] \n"
"smlal v10.4s, v7.4h, v2.h[1] \n"// out1 += (r20-r27)*k12
"smlal2 v11.4s, v7.8h, v2.h[1] \n"
"smlal v12.4s, v7.4h, v2.h[2] \n"// out2 += (r20-r27)*k22
"smlal2 v13.4s, v7.8h, v2.h[2] \n"
"smlal v14.4s, v7.4h, v2.h[3] \n"// out3 += (r20-r27)*k32
"smlal2 v15.4s, v7.8h, v2.h[3] \n"
"smlal v16.4s, v7.4h, v2.h[4] \n"// out4 += (r20-r27)*k42
"smlal2 v17.4s, v7.8h, v2.h[4] \n"
"smlal v18.4s, v7.4h, v2.h[5] \n"// out5 += (r20-r27)*k52
"smlal2 v19.4s, v7.8h, v2.h[5] \n"
"smlal v20.4s, v7.4h, v2.h[6] \n"// out6 += (r20-r27)*k62
"smlal2 v21.4s, v7.8h, v2.h[6] \n"
"smlal v22.4s, v7.4h, v2.h[7] \n"// out7 += (r20-r27)*k72
"smlal2 v23.4s, v7.8h, v2.h[7] \n"
"ld1 {v0.8b, v1.8b, v2.8b}, [%12], #24 \n"//ktmp
"ld2 {v3.8b, v4.8b}, [%10], #16 \n"//r3-r5
"ld2 {v5.8b, v6.8b}, [%10] \n"
"ext v7.8b, v3.8b, v5.8b, #1 \n"
"sshll v0.8h, v0.8b, #0 \n"//(k03-k73)
"sshll v1.8h, v1.8b, #0 \n"//(k04-k74)
"sshll v2.8h, v2.8b, #0 \n"//(k05-k75)
"sshll v3.8h, v3.8b, #0 \n"// r3
"sshll v4.8h, v4.8b, #0 \n"// r4
"sshll v7.8h, v7.8b, #0 \n"// r5
// r3
"smlal v8.4s, v3.4h, v0.h[0] \n"// out0 += (r30-r37)*k03
"smlal2 v9.4s, v3.8h, v0.h[0] \n"
"smlal v10.4s, v3.4h, v0.h[1] \n"// out1 += (r30-r37)*k13
"smlal2 v11.4s, v3.8h, v0.h[1] \n"
"smlal v12.4s, v3.4h, v0.h[2] \n"// out2 += (r30-r37)*k23
"smlal2 v13.4s, v3.8h, v0.h[2] \n"
"smlal v14.4s, v3.4h, v0.h[3] \n"// out3 += (r30-r37)*k33
"smlal2 v15.4s, v3.8h, v0.h[3] \n"
"smlal v16.4s, v3.4h, v0.h[4] \n"// out4 += (r30-r37)*k43
"smlal2 v17.4s, v3.8h, v0.h[4] \n"
"smlal v18.4s, v3.4h, v0.h[5] \n"// out5 += (r30-r37)*k53
"smlal2 v19.4s, v3.8h, v0.h[5] \n"
"smlal v20.4s, v3.4h, v0.h[6] \n"// out6 += (r30-r37)*k63
"smlal2 v21.4s, v3.8h, v0.h[6] \n"
"smlal v22.4s, v3.4h, v0.h[7] \n"// out7 += (r30-r37)*k73
"smlal2 v23.4s, v3.8h, v0.h[7] \n"
// r4
"smlal v8.4s, v4.4h, v1.h[0] \n"// out0 += (r40-r47)*k04
"smlal2 v9.4s, v4.8h, v1.h[0] \n"
"smlal v10.4s, v4.4h, v1.h[1] \n"// out1 += (r40-r47)*k14
"smlal2 v11.4s, v4.8h, v1.h[1] \n"
"smlal v12.4s, v4.4h, v1.h[2] \n"// out2 += (r40-r47)*k24
"smlal2 v13.4s, v4.8h, v1.h[2] \n"
"smlal v14.4s, v4.4h, v1.h[3] \n"// out3 += (r40-r47)*k34
"smlal2 v15.4s, v4.8h, v1.h[3] \n"
"smlal v16.4s, v4.4h, v1.h[4] \n"// out4 += (r40-r47)*k44
"smlal2 v17.4s, v4.8h, v1.h[4] \n"
"smlal v18.4s, v4.4h, v1.h[5] \n"// out5 += (r40-r47)*k54
"smlal2 v19.4s, v4.8h, v1.h[5] \n"
"smlal v20.4s, v4.4h, v1.h[6] \n"// out6 += (r40-r47)*k64
"smlal2 v21.4s, v4.8h, v1.h[6] \n"
"smlal v22.4s, v4.4h, v1.h[7] \n"// out7 += (r40-r47)*k74
"smlal2 v23.4s, v4.8h, v1.h[7] \n"
// r5
"smlal v8.4s, v7.4h, v2.h[0] \n"// out0 += (r50-r57)*k05
"smlal2 v9.4s, v7.8h, v2.h[0] \n"
"smlal v10.4s, v7.4h, v2.h[1] \n"// out1 += (r50-r57)*k15
"smlal2 v11.4s, v7.8h, v2.h[1] \n"
"smlal v12.4s, v7.4h, v2.h[2] \n"// out2 += (r50-r57)*k25
"smlal2 v13.4s, v7.8h, v2.h[2] \n"
"smlal v14.4s, v7.4h, v2.h[3] \n"// out3 += (r50-r57)*k35
"smlal2 v15.4s, v7.8h, v2.h[3] \n"
"smlal v16.4s, v7.4h, v2.h[4] \n"// out4 += (r50-r57)*k45
"smlal2 v17.4s, v7.8h, v2.h[4] \n"
"smlal v18.4s, v7.4h, v2.h[5] \n"// out5 += (r50-r57)*k55
"smlal2 v19.4s, v7.8h, v2.h[5] \n"
"smlal v20.4s, v7.4h, v2.h[6] \n"// out6 += (r50-r57)*k65
"smlal2 v21.4s, v7.8h, v2.h[6] \n"
"smlal v22.4s, v7.4h, v2.h[7] \n"// out7 += (r50-r57)*k75
"smlal2 v23.4s, v7.8h, v2.h[7] \n"
"ld1 {v0.8b, v1.8b, v2.8b}, [%12], #24 \n"//ktmp
"ld2 {v3.8b, v4.8b}, [%11], #16 \n"//r6-r8
"ld2 {v5.8b, v6.8b}, [%11] \n"
"ext v7.8b, v3.8b, v5.8b, #1 \n"
"sshll v0.8h, v0.8b, #0 \n"//(k06-k76)
"sshll v1.8h, v1.8b, #0 \n"//(k07-k77)
"sshll v2.8h, v2.8b, #0 \n"//(k08-k78)
"sshll v3.8h, v3.8b, #0 \n"// r6
"sshll v4.8h, v4.8b, #0 \n"// r7
"sshll v7.8h, v7.8b, #0 \n"// r8
// r6
"smlal v8.4s, v3.4h, v0.h[0] \n"// out0 += (r60-r67)*k06
"smlal2 v9.4s, v3.8h, v0.h[0] \n"
"smlal v10.4s, v3.4h, v0.h[1] \n"// out1 += (r60-r67)*k16
"smlal2 v11.4s, v3.8h, v0.h[1] \n"
"smlal v12.4s, v3.4h, v0.h[2] \n"// out2 += (r60-r67)*k26
"smlal2 v13.4s, v3.8h, v0.h[2] \n"
"smlal v14.4s, v3.4h, v0.h[3] \n"// out3 += (r60-r67)*k36
"smlal2 v15.4s, v3.8h, v0.h[3] \n"
"smlal v16.4s, v3.4h, v0.h[4] \n"// out4 += (r60-r67)*k46
"smlal2 v17.4s, v3.8h, v0.h[4] \n"
"smlal v18.4s, v3.4h, v0.h[5] \n"// out5 += (r60-r67)*k56
"smlal2 v19.4s, v3.8h, v0.h[5] \n"
"smlal v20.4s, v3.4h, v0.h[6] \n"// out6 += (r60-r67)*k66
"smlal2 v21.4s, v3.8h, v0.h[6] \n"
"smlal v22.4s, v3.4h, v0.h[7] \n"// out7 += (r60-r67)*k76
"smlal2 v23.4s, v3.8h, v0.h[7] \n"
// r7
"smlal v8.4s, v4.4h, v1.h[0] \n"// out0 += (r70-r77)*k07
"smlal2 v9.4s, v4.8h, v1.h[0] \n"
"smlal v10.4s, v4.4h, v1.h[1] \n"// out1 += (r70-r77)*k17
"smlal2 v11.4s, v4.8h, v1.h[1] \n"
"smlal v12.4s, v4.4h, v1.h[2] \n"// out2 += (r70-r77)*k27
"smlal2 v13.4s, v4.8h, v1.h[2] \n"
"smlal v14.4s, v4.4h, v1.h[3] \n"// out3 += (r70-r77)*k37
"smlal2 v15.4s, v4.8h, v1.h[3] \n"
"smlal v16.4s, v4.4h, v1.h[4] \n"// out4 += (r70-r77)*k47
"smlal2 v17.4s, v4.8h, v1.h[4] \n"
"smlal v18.4s, v4.4h, v1.h[5] \n"// out5 += (r70-r77)*k57
"smlal2 v19.4s, v4.8h, v1.h[5] \n"
"smlal v20.4s, v4.4h, v1.h[6] \n"// out6 += (r70-r77)*k67
"smlal2 v21.4s, v4.8h, v1.h[6] \n"
"smlal v22.4s, v4.4h, v1.h[7] \n"// out7 += (r70-r77)*k77
"smlal2 v23.4s, v4.8h, v1.h[7] \n"
// r8
"smlal v8.4s, v7.4h, v2.h[0] \n"// out0 += (r80-r87)*k08
"smlal2 v9.4s, v7.8h, v2.h[0] \n"
"smlal v10.4s, v7.4h, v2.h[1] \n"// out1 += (r80-r87)*k18
"smlal2 v11.4s, v7.8h, v2.h[1] \n"
"smlal v12.4s, v7.4h, v2.h[2] \n"// out2 += (r80-r87)*k28
"smlal2 v13.4s, v7.8h, v2.h[2] \n"
"smlal v14.4s, v7.4h, v2.h[3] \n"// out3 += (r80-r87)*k38
"smlal2 v15.4s, v7.8h, v2.h[3] \n"
"smlal v16.4s, v7.4h, v2.h[4] \n"// out4 += (r80-r87)*k48
"smlal2 v17.4s, v7.8h, v2.h[4] \n"
"smlal v18.4s, v7.4h, v2.h[5] \n"// out5 += (r80-r87)*k58
"smlal2 v19.4s, v7.8h, v2.h[5] \n"
"smlal v20.4s, v7.4h, v2.h[6] \n"// out6 += (r80-r87)*k68
"smlal2 v21.4s, v7.8h, v2.h[6] \n"
"smlal v22.4s, v7.4h, v2.h[7] \n"// out7 += (r80-r87)*k78
"smlal2 v23.4s, v7.8h, v2.h[7] \n"
"st1 {v8.4s, v9.4s}, [%1], #32 \n"
"st1 {v10.4s, v11.4s}, [%2], #32 \n"
"st1 {v12.4s, v13.4s}, [%3], #32 \n"
"st1 {v14.4s, v15.4s}, [%4], #32 \n"
"st1 {v16.4s, v17.4s}, [%5], #32 \n"
"st1 {v18.4s, v19.4s}, [%6], #32 \n"
"st1 {v20.4s, v21.4s}, [%7], #32 \n"
"st1 {v22.4s, v23.4s}, [%8], #32 \n"
"subs %w0, %w0, #1 \n"
"sub %12, %12, #72 \n"// reset ktmp
"bne 0b \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr1), // %2
"=r"(outptr2), // %3
"=r"(outptr3), // %4
"=r"(outptr4), // %5
"=r"(outptr5), // %6
"=r"(outptr6), // %7
"=r"(outptr7), // %8
"=r"(r0), // %9
"=r"(r1), // %10
"=r"(r2), // %11
"=r"(ktmp) // %12
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(outptr2),
"4"(outptr3),
"5"(outptr4),
"6"(outptr5),
"7"(outptr6),
"8"(outptr7),
"9"(r0),
"10"(r1),
"11"(r2),
"12"(ktmp)
: "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23"
);
}
#else // __aarch64__
if (nn > 0)
{
asm volatile(
"0: \n"
"pld [%1, #128] \n"
"vld1.s32 {d16-d17}, [%1] \n"// out0
"pld [%2, #128] \n"
"vld1.s32 {d18-d19}, [%2] \n"// out1
"pld [%3, #128] \n"
"vld1.s32 {d20-d21}, [%3] \n"// out2
"pld [%4, #128] \n"
"vld1.s32 {d22-d23}, [%4] \n"// out3
// r0
"pld [%9, #64] \n"
"vld2.s8 {d8-d9}, [%9] \n"// d8(a00 a02 a04 a06 a08 a010 a012 a014), d9(a01 a03 a05 a07 a09 a011 a013 a015)
"add %9, #8 \n"
"pld [%12, #64] \n"
"vld1.s8 {d0-d2}, [%12]! \n"// d0(k00-k70) d1(k01-k71) d2(k02-k72)
"pld [%5, #128] \n"
"vld1.s32 {d24-d25}, [%5] \n"// out4
"pld [%6, #128] \n"
"vld1.s32 {d26-d27}, [%6] \n"// out5
"vmovl.s8 q2, d2 \n"// q2(k02-k72)
"vmovl.s8 q1, d1 \n"// q1(k01-k71)
"vmovl.s8 q0, d0 \n"// q0(k00-k70)
"vext.s8 d12, d8, d8, #1 \n"// d12(a02 a04 a06 a08 x x x x)
"pld [%7, #128] \n"
"vld1.s32 {d28-d29}, [%7] \n"// out6
"vmovl.s8 q5, d9 \n"// q5(a01 a03 a05 a07 a09 a011 a013 a015) d11
"vmovl.s8 q4, d8 \n"// q4(a00 a02 a04 a06 a08 a010 a012 a014) d9
"vmovl.s8 q6, d12 \n"// q6(a02 a04 a06 a08 a010 a012 a014 a016) d13
"pld [%8, #128] \n"
"vld1.s32 {d30-d31}, [%8] \n"// out7
"vmlal.s16 q8, d8, d0[0] \n"// sum0 += (a00 a02 a04 a06) * k00
"vmlal.s16 q9, d8, d0[1] \n"// sum1 += (a00 a02 a04 a06) * k10
"vmlal.s16 q10, d8, d0[2] \n"// sum2 += (a00 a02 a04 a06) * k20
"vmlal.s16 q11, d8, d0[3] \n"// sum3 += (a00 a02 a04 a06) * k30
"vmlal.s16 q12, d8, d1[0] \n"// sum4 += (a00 a02 a04 a06) * k40
"vmlal.s16 q13, d8, d1[1] \n"// sum5 += (a00 a02 a04 a06) * k50
"vmlal.s16 q14, d8, d1[2] \n"// sum6 += (a00 a02 a04 a06) * k60
"vmlal.s16 q15, d8, d1[3] \n"// sum7 += (a00 a02 a04 a06) * k70
"vmlal.s16 q8, d10, d2[0] \n"// sum0 += (a01-a07) * k01
"vmlal.s16 q9, d10, d2[1] \n"// sum1 += (a01-a07) * k11
"vmlal.s16 q10, d10, d2[2] \n"// sum2 += (a01-a07) * k21
"vmlal.s16 q11, d10, d2[3] \n"// sum3 += (a01-a07) * k31
"vmlal.s16 q12, d10, d3[0] \n"// sum4 += (a01-a07) * k41
"vmlal.s16 q13, d10, d3[1] \n"// sum5 += (a01-a07) * k51
"vmlal.s16 q14, d10, d3[2] \n"// sum6 += (a01-a07) * k61
"vmlal.s16 q15, d10, d3[3] \n"// sum7 += (a01-a07) * k71
"pld [%10, #64] \n"
"vld2.s8 {d8-d9}, [%10] \n"// d8(a10 a12 a14 a16 a18 a110 a112 a114), d9(a11 a13 a15 a17 a19 a111 a113 a115)
"add %10, #8 \n"
"vmlal.s16 q8, d12, d4[0] \n"// sum0 += (a02-a08) * k02
"vmlal.s16 q9, d12, d4[1] \n"// sum1 += (a02-a08) * k12
"vmlal.s16 q10, d12, d4[2] \n"// sum2 += (a02-a08) * k22
"vmlal.s16 q11, d12, d4[3] \n"// sum3 += (a02-a08) * k32
"pld [%12, #64] \n"
"vld1.s8 {d0-d2}, [%12]! \n"// d0(k03-k73) d1(k04-k74) d2(k05-k75)
"vmlal.s16 q12, d12, d5[0] \n"// sum4 += (a02-a08) * k42
"vmlal.s16 q13, d12, d5[1] \n"// sum5 += (a02-a08) * k52
"vmlal.s16 q14, d12, d5[2] \n"// sum6 += (a02-a08) * k62
"vmlal.s16 q15, d12, d5[3] \n"// sum7 += (a02-a08) * k72
// r1
"vext.s8 d12, d8, d8, #1 \n"// d12(a12 a14 a16 a18 x x x x)
"vmovl.s8 q2, d2 \n"// q2(k05-k75)
"vmovl.s8 q1, d1 \n"// q1(k04-k74)
"vmovl.s8 q0, d0 \n"// q0(k03-k73)
"vmovl.s8 q5, d9 \n"// q5(a11-a115)
"vmovl.s8 q4, d8 \n"// q4(a10-a114)
"vmovl.s8 q6, d12 \n"// q6(a12-a116)
"vmlal.s16 q8, d8, d0[0] \n"// sum0 += (a10-a16) * k03
"vmlal.s16 q9, d8, d0[1] \n"// sum1 += (a10-a16) * k13
"vmlal.s16 q10, d8, d0[2] \n"// sum2 += (a10-a16) * k23
"vmlal.s16 q11, d8, d0[3] \n"// sum3 += (a10-a16) * k33
"vmlal.s16 q12, d8, d1[0] \n"// sum4 += (a10-a16) * k43
"vmlal.s16 q13, d8, d1[1] \n"// sum5 += (a10-a16) * k53
"vmlal.s16 q14, d8, d1[2] \n"// sum6 += (a10-a16) * k63
"vmlal.s16 q15, d8, d1[3] \n"// sum7 += (a10-a16) * k73
"vmlal.s16 q8, d10, d2[0] \n"// sum0 += (a11-a17) * k04
"vmlal.s16 q9, d10, d2[1] \n"// sum1 += (a11-a17) * k14
"vmlal.s16 q10, d10, d2[2] \n"// sum2 += (a11-a17) * k24
"vmlal.s16 q11, d10, d2[3] \n"// sum3 += (a11-a17) * k34
"vmlal.s16 q12, d10, d3[0] \n"// sum4 += (a11-a17) * k44
"vmlal.s16 q13, d10, d3[1] \n"// sum5 += (a11-a17) * k54
"vmlal.s16 q14, d10, d3[2] \n"// sum6 += (a11-a17) * k64
"vmlal.s16 q15, d10, d3[3] \n"// sum7 += (a11-a17) * k74
"pld [%11, #64] \n"
"vld2.s8 {d8-d9}, [%11] \n"// d8(a20 a22 a24 a26 a28 a210 a212 a214), d9(a21 a23 a25 a27 a29 a211 a213 a215)
"add %11, #8 \n"
"vmlal.s16 q8, d12, d4[0] \n"// sum0 += (a12-a18) * k05
"vmlal.s16 q9, d12, d4[1] \n"// sum1 += (a12-a18) * k15
"vmlal.s16 q10, d12, d4[2] \n"// sum2 += (a12-a18) * k25
"vmlal.s16 q11, d12, d4[3] \n"// sum3 += (a12-a18) * k35
"pld [%12, #64] \n"
"vld1.s8 {d0-d2}, [%12]! \n"// d0(k06-k76) d1(k07-k77) d2(k08-k78)
"vmlal.s16 q12, d12, d5[0] \n"// sum4 += (a12-a18) * k45
"vmlal.s16 q13, d12, d5[1] \n"// sum5 += (a12-a18) * k55
"vmlal.s16 q14, d12, d5[2] \n"// sum6 += (a12-a18) * k65
"vmlal.s16 q15, d12, d5[3] \n"// sum7 += (a12-a18) * k75
// r2
"vext.s8 d12, d8, d8, #1 \n"// d12(a22 a24 a26 a28 x x x x)
"vmovl.s8 q2, d2 \n"// q2(k08-k78)
"vmovl.s8 q1, d1 \n"// q1(k07-k77)
"vmovl.s8 q0, d0 \n"// q0(k06-k76)
"vmovl.s8 q5, d9 \n"// q5(a21-a215)
"vmovl.s8 q4, d8 \n"// q4(a20-a214)
"vmovl.s8 q6, d12 \n"// q6(a22-a216)
"vmlal.s16 q8, d8, d0[0] \n"// sum0 += (a20-a26) * k06
"vmlal.s16 q9, d8, d0[1] \n"// sum1 += (a20-a26) * k16
"vmlal.s16 q10, d8, d0[2] \n"// sum2 += (a20-a26) * k26
"vmlal.s16 q11, d8, d0[3] \n"// sum3 += (a20-a26) * k36
"vmlal.s16 q12, d8, d1[0] \n"// sum4 += (a20-a26) * k46
"vmlal.s16 q13, d8, d1[1] \n"// sum5 += (a20-a26) * k56
"vmlal.s16 q14, d8, d1[2] \n"// sum6 += (a20-a26) * k66
"vmlal.s16 q15, d8, d1[3] \n"// sum7 += (a20-a26) * k76
"vmlal.s16 q8, d10, d2[0] \n"// sum0 += (a21-a27) * k07
"vmlal.s16 q9, d10, d2[1] \n"// sum1 += (a21-a27) * k17
"vmlal.s16 q10, d10, d2[2] \n"// sum2 += (a21-a27) * k27
"vmlal.s16 q11, d10, d2[3] \n"// sum3 += (a21-a27) * k37
"vmlal.s16 q12, d10, d3[0] \n"// sum4 += (a21-a27) * k47
"vmlal.s16 q13, d10, d3[1] \n"// sum5 += (a21-a27) * k57
"vmlal.s16 q14, d10, d3[2] \n"// sum6 += (a21-a27) * k67
"vmlal.s16 q15, d10, d3[3] \n"// sum7 += (a21-a27) * k77
"vmlal.s16 q8, d12, d4[0] \n"// sum0 += (a22-a28) * k08
"vmlal.s16 q9, d12, d4[1] \n"// sum1 += (a22-a28) * k18
"vmlal.s16 q10, d12, d4[2] \n"// sum2 += (a22-a28) * k28
"vmlal.s16 q11, d12, d4[3] \n"// sum3 += (a22-a28) * k38
"vmlal.s16 q12, d12, d5[0] \n"// sum4 += (a22-a28) * k48
"vmlal.s16 q13, d12, d5[1] \n"// sum5 += (a22-a28) * k58
"vmlal.s16 q14, d12, d5[2] \n"// sum6 += (a22-a28) * k68
"vmlal.s16 q15, d12, d5[3] \n"// sum7 += (a22-a28) * k78
// save s32 to memory
"sub %12, %12, #72 \n"
"vst1.s32 {d16-d17}, [%1]! \n"// out0
"vst1.s32 {d18-d19}, [%2]! \n"// out1
"vst1.s32 {d20-d21}, [%3]! \n"// out2
"vst1.s32 {d22-d23}, [%4]! \n"// out3
"subs %0, #1 \n"
"vst1.s32 {d24-d25}, [%5]! \n"// out4
"vst1.s32 {d26-d27}, [%6]! \n"// out5
"vst1.s32 {d28-d29}, [%7]! \n"// out6
"vst1.s32 {d30-d31}, [%8]! \n"// out7
"bne 0b \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr1), // %2
"=r"(outptr2), // %3
"=r"(outptr3), // %4
"=r"(outptr4), // %5
"=r"(outptr5), // %6
"=r"(outptr6), // %7
"=r"(outptr7), // %8
"=r"(r0), // %9
"=r"(r1), // %10
"=r"(r2), // %11
"=r"(ktmp) // %12
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(outptr2),
"4"(outptr3),
"5"(outptr4),
"6"(outptr5),
"7"(outptr6),
"8"(outptr7),
"9"(r0),
"10"(r1),
"11"(r2),
"12"(ktmp)
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"
);
}
#endif // __aarch64__
#endif // __ARM_NEON
for (; remain>0; remain--)
{
#if 0 //__ARM_NEON
#if __aarch64__
int8x8_t _r0_s8 = vld1_s8(r0);// (a00 a01 a02 ....)
int8x8_t _r1_s8 = vld1_s8(r1);// (a10 a11 a12 ....)
int8x8_t _r2_s8 = vld1_s8(r2);// (a20 a21 a22 ....)
int16x8_t _r0 = vmovl_s8(_r0_s8);
int16x8_t _r1 = vmovl_s8(_r1_s8);
int16x8_t _r2 = vmovl_s8(_r2_s8);
int32x4_t _sum03, _sum47;
_sum03 = vld1q_lane_s32(outptr0, _sum03, 0);// out0
_sum03 = vld1q_lane_s32(outptr1, _sum03, 1);// out1
_sum03 = vld1q_lane_s32(outptr2, _sum03, 2);// out2
_sum03 = vld1q_lane_s32(outptr3, _sum03, 3);// out3
_sum47 = vld1q_lane_s32(outptr4, _sum47, 0);// out4
_sum47 = vld1q_lane_s32(outptr5, _sum47, 1);// out5
_sum47 = vld1q_lane_s32(outptr6, _sum47, 2);// out6
_sum47 = vld1q_lane_s32(outptr7, _sum47, 3);// out7
// k0 - k2
int8x8_t _k0_8 = vld1_s8(ktmp); //(k00-k70)
int8x8_t _k1_8 = vld1_s8(ktmp+8); //(k01-k71)
int8x8_t _k2_8 = vld1_s8(ktmp+16); //(k02-k72)
int16x8_t _k0 = vmovl_s8(_k0_8);
int16x8_t _k1 = vmovl_s8(_k1_8);
int16x8_t _k2 = vmovl_s8(_k2_8);
int32x4_t _sum0 = vmull_laneq_s16(vget_low_s16(_k0), _r0, 0);
int32x4_t _sum0n = vmull_laneq_s16(vget_high_s16(_k0), _r0, 0);
int32x4_t _sum1 = vmull_laneq_s16(vget_low_s16(_k1), _r0, 1);
int32x4_t _sum1n = vmull_laneq_s16(vget_high_s16(_k1), _r0, 1);
_sum03 = vmlal_laneq_s16(_sum03, vget_low_s16(_k2), _r0, 2);
_sum47 = vmlal_laneq_s16(_sum47, vget_high_s16(_k2), _r0, 2);
// k3 - k5
_k0_8 = vld1_s8(ktmp+24); //(k03-k73)
_k1_8 = vld1_s8(ktmp+32); //(k04-k74)
_k2_8 = vld1_s8(ktmp+40); //(k05-k75)
_k0 = vmovl_s8(_k0_8);
_k1 = vmovl_s8(_k1_8);
_k2 = vmovl_s8(_k2_8);
_sum0 = vmlal_laneq_s16(_sum0, vget_low_s16(_k0), _r1, 0);
_sum0n = vmlal_laneq_s16(_sum0n, vget_high_s16(_k0), _r1, 0);
_sum1 = vmlal_laneq_s16(_sum1, vget_low_s16(_k1), _r1, 1);
_sum1n = vmlal_laneq_s16(_sum1n, vget_high_s16(_k1), _r1, 1);
_sum03 = vmlal_laneq_s16(_sum03, vget_low_s16(_k2), _r1, 2);
_sum47 = vmlal_laneq_s16(_sum47, vget_high_s16(_k2), _r1, 2);
// k6 - k8
_k0_8 = vld1_s8(ktmp+48); //(k06-k76)
_k1_8 = vld1_s8(ktmp+56); //(k07-k77)
_k2_8 = vld1_s8(ktmp+64); //(k08-k78)
_k0 = vmovl_s8(_k0_8);
_k1 = vmovl_s8(_k1_8);
_k2 = vmovl_s8(_k2_8);
_sum0 = vmlal_laneq_s16(_sum0, vget_low_s16(_k0), _r2, 0);
_sum0n = vmlal_laneq_s16(_sum0n, vget_high_s16(_k0), _r2, 0);
_sum1 = vmlal_laneq_s16(_sum1, vget_low_s16(_k1), _r2, 1);
_sum1n = vmlal_laneq_s16(_sum1n, vget_high_s16(_k1), _r2, 1);
_sum03 = vmlal_laneq_s16(_sum03, vget_low_s16(_k2), _r2, 2);
_sum47 = vmlal_laneq_s16(_sum47, vget_high_s16(_k2), _r2, 2);
_sum0 = vaddq_s32(_sum0, _sum1);
_sum0n = vaddq_s32(_sum0n, _sum1n);
_sum03 = vaddq_s32(_sum03, _sum0);
_sum47 = vaddq_s32(_sum47, _sum0n);
vst1q_lane_s32(outptr0, _sum03, 0);
vst1q_lane_s32(outptr1, _sum03, 1);
vst1q_lane_s32(outptr2, _sum03, 2);
vst1q_lane_s32(outptr3, _sum03, 3);
vst1q_lane_s32(outptr4, _sum47, 0);
vst1q_lane_s32(outptr5, _sum47, 1);
vst1q_lane_s32(outptr6, _sum47, 2);
vst1q_lane_s32(outptr7, _sum47, 3);
outptr0++;
outptr1++;
outptr2++;
outptr3++;
outptr4++;
outptr5++;
outptr6++;
outptr7++;
#else // __aarch64__
asm volatile(
"pld [%8, #64] \n"
"vld1.s8 {d0}, [%8] \n"// d0(a00 a01 a02 ....)
"pld [%9, #64] \n"
"vld1.s8 {d2}, [%9] \n"// d2(a10 a11 a12 ....)
"pld [%10, #64] \n"
"vld1.s8 {d4}, [%10] \n"// d4(a20 a21 a22 ....)
"pld [%11, #64] \n"
"vld1.s8 {d6-d8}, [%11]! \n"// d6(k00-k70) d7(k01-k71) d8(k02-k72)
"vmovl.s8 q0, d0 \n"// d0(a00 a01 a02 x)
"vmovl.s8 q1, d2 \n"// d2(a10 a11 a12 x)
"vmovl.s8 q2, d4 \n"// d4(a20 a21 a22 x)
"vmovl.s8 q5, d8 \n"// d10(k02-k32) d11(k42-k72)
"vmovl.s8 q4, d7 \n"// d8(k01-k31) d9(k41-k71)
"vmovl.s8 q3, d6 \n"// d6(k00-k30) d7(k40-k70)
"vld1.s32 {d20[0]}, [%0] \n"// out0 q10
"vld1.s32 {d20[1]}, [%1] \n"// out1
"vld1.s32 {d21[0]}, [%2] \n"// out2
"vld1.s32 {d21[1]}, [%3] \n"// out3
"pld [%11, #64] \n"
"vld1.s8 {d24-d26}, [%11]! \n"
"vmovl.s8 q14, d26 \n"// d28(k05-k35) d29(k45-k75)
"vmovl.s8 q13, d25 \n"// d26(k04-k34) d27(k44-k74)
"vmovl.s8 q12, d24 \n"// d24(k03-k33) d25(k43-k73)
"vld1.s32 {d22[0]}, [%4] \n"// out4 q11
"vld1.s32 {d22[1]}, [%5] \n"// out5
"vld1.s32 {d23[0]}, [%6] \n"// out6
"vld1.s32 {d23[1]}, [%7] \n"// out7
"vmull.s16 q6, d6, d0[0] \n"// a00 x (k00-k30)
"vmull.s16 q7, d7, d0[0] \n"// a00 x (k40-k70)
"vmull.s16 q8, d8, d0[1] \n"// a01 x (k01-k31)
"vmull.s16 q9, d9, d0[1] \n"// a01 x (k41-k71)
"vmlal.s16 q10, d10, d0[2] \n"// a02 x (k02-k32)
"vmlal.s16 q11, d11, d0[2] \n"// a02 x (k42-k72)
"pld [%11, #64] \n"
"vld1.s8 {d6-d8}, [%11]! \n"
"vmovl.s8 q5, d8 \n"// d10(k08-k38) d11(k48-k78)
"vmovl.s8 q4, d7 \n"// d8(k07-k37) d9(k47-k77)
"vmovl.s8 q3, d6 \n"// d6(k06-k36) d7(k46-k76)
"vmlal.s16 q6, d24, d2[0] \n"// a10 x (k03-k33)
"vmlal.s16 q7, d25, d2[0] \n"// a10 x (k43-k73)
"vmlal.s16 q8, d26, d2[1] \n"// a11 x (k04-k34)
"vmlal.s16 q9, d27, d2[1] \n"// a11 x (k44-k74)
"vmlal.s16 q10, d28, d2[2] \n"// a12 x (k05-k35)
"vmlal.s16 q11, d29, d2[2] \n"// a12 x (k45-k75)
"vmlal.s16 q6, d6, d4[0] \n"// a20 x (k06-k36)
"vmlal.s16 q7, d7, d4[0] \n"// a20 x (k46-k76)
"vmlal.s16 q8, d8, d4[1] \n"// a21 x (k07-k37)
"vmlal.s16 q9, d9, d4[1] \n"// a21 x (k47-k77)
"vmlal.s16 q10, d10, d4[2] \n"// a22 x (k08-k38)
"vmlal.s16 q11, d11, d4[2] \n"// a22 x (k48-k78)
"vadd.s32 q8, q8, q6 \n"
"vadd.s32 q9, q9, q7 \n"
"sub %11, %11, #72 \n"
"vadd.s32 q10, q10, q8 \n"
"vadd.s32 q11, q11, q9 \n"
"vst1.s32 {d20[0]}, [%0]! \n"// out0
"vst1.s32 {d20[1]}, [%1]! \n"// out1
"vst1.s32 {d21[0]}, [%2]! \n"// out2
"vst1.s32 {d21[1]}, [%3]! \n"// out3
"vst1.s32 {d22[0]}, [%4]! \n"// out4
"vst1.s32 {d22[1]}, [%5]! \n"// out5
"vst1.s32 {d23[0]}, [%6]! \n"// out6
"vst1.s32 {d23[1]}, [%7]! \n"// out7
: "=r"(outptr0), // %0
"=r"(outptr1), // %1
"=r"(outptr2), // %2
"=r"(outptr3), // %3
"=r"(outptr4), // %4
"=r"(outptr5), // %5
"=r"(outptr6), // %6
"=r"(outptr7), // %7
"=r"(r0), // %8
"=r"(r1), // %9
"=r"(r2), // %10
"=r"(ktmp) // %11
: "0"(outptr0),
"1"(outptr1),
"2"(outptr2),
"3"(outptr3),
"4"(outptr4),
"5"(outptr5),
"6"(outptr6),
"7"(outptr7),
"8"(r0),
"9"(r1),
"10"(r2),
"11"(ktmp)
: "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"
);
#endif // __aarch64__
#else // __ARM_NEON
short sum0 = 0;
short sum1 = 0;
short sum2 = 0;
short sum3 = 0;
short sum4 = 0;
short sum5 = 0;
short sum6 = 0;
short sum7 = 0;
sum0 += (short)r0[0] * ktmp[0];
sum1 += (short)r0[0] * ktmp[1];
sum2 += (short)r0[0] * ktmp[2];
sum3 += (short)r0[0] * ktmp[3];
sum4 += (short)r0[0] * ktmp[4];
sum5 += (short)r0[0] * ktmp[5];
sum6 += (short)r0[0] * ktmp[6];
sum7 += (short)r0[0] * ktmp[7];
ktmp += 8;
sum0 += (short)r0[1] * ktmp[0];
sum1 += (short)r0[1] * ktmp[1];
sum2 += (short)r0[1] * ktmp[2];
sum3 += (short)r0[1] * ktmp[3];
sum4 += (short)r0[1] * ktmp[4];
sum5 += (short)r0[1] * ktmp[5];
sum6 += (short)r0[1] * ktmp[6];
sum7 += (short)r0[1] * ktmp[7];
ktmp += 8;
sum0 += (short)r0[2] * ktmp[0];
sum1 += (short)r0[2] * ktmp[1];
sum2 += (short)r0[2] * ktmp[2];
sum3 += (short)r0[2] * ktmp[3];
sum4 += (short)r0[2] * ktmp[4];
sum5 += (short)r0[2] * ktmp[5];
sum6 += (short)r0[2] * ktmp[6];
sum7 += (short)r0[2] * ktmp[7];
ktmp += 8;
sum0 += (short)r1[0] * ktmp[0];
sum1 += (short)r1[0] * ktmp[1];
sum2 += (short)r1[0] * ktmp[2];
sum3 += (short)r1[0] * ktmp[3];
sum4 += (short)r1[0] * ktmp[4];
sum5 += (short)r1[0] * ktmp[5];
sum6 += (short)r1[0] * ktmp[6];
sum7 += (short)r1[0] * ktmp[7];
ktmp += 8;
sum0 += (short)r1[1] * ktmp[0];
sum1 += (short)r1[1] * ktmp[1];
sum2 += (short)r1[1] * ktmp[2];
sum3 += (short)r1[1] * ktmp[3];
sum4 += (short)r1[1] * ktmp[4];
sum5 += (short)r1[1] * ktmp[5];
sum6 += (short)r1[1] * ktmp[6];
sum7 += (short)r1[1] * ktmp[7];
ktmp += 8;
sum0 += (short)r1[2] * ktmp[0];
sum1 += (short)r1[2] * ktmp[1];
sum2 += (short)r1[2] * ktmp[2];
sum3 += (short)r1[2] * ktmp[3];
sum4 += (short)r1[2] * ktmp[4];
sum5 += (short)r1[2] * ktmp[5];
sum6 += (short)r1[2] * ktmp[6];
sum7 += (short)r1[2] * ktmp[7];
ktmp += 8;
sum0 += (short)r2[0] * ktmp[0];
sum1 += (short)r2[0] * ktmp[1];
sum2 += (short)r2[0] * ktmp[2];
sum3 += (short)r2[0] * ktmp[3];
sum4 += (short)r2[0] * ktmp[4];
sum5 += (short)r2[0] * ktmp[5];
sum6 += (short)r2[0] * ktmp[6];
sum7 += (short)r2[0] * ktmp[7];
ktmp += 8;
sum0 += (short)r2[1] * ktmp[0];
sum1 += (short)r2[1] * ktmp[1];
sum2 += (short)r2[1] * ktmp[2];
sum3 += (short)r2[1] * ktmp[3];
sum4 += (short)r2[1] * ktmp[4];
sum5 += (short)r2[1] * ktmp[5];
sum6 += (short)r2[1] * ktmp[6];
sum7 += (short)r2[1] * ktmp[7];
ktmp += 8;
sum0 += (short)r2[2] * ktmp[0];
sum1 += (short)r2[2] * ktmp[1];
sum2 += (short)r2[2] * ktmp[2];
sum3 += (short)r2[2] * ktmp[3];
sum4 += (short)r2[2] * ktmp[4];
sum5 += (short)r2[2] * ktmp[5];
sum6 += (short)r2[2] * ktmp[6];
sum7 += (short)r2[2] * ktmp[7];
ktmp += 8;
*outptr0 += sum0;
*outptr1 += sum1;
*outptr2 += sum2;
*outptr3 += sum3;
*outptr4 += sum4;
*outptr5 += sum5;
*outptr6 += sum6;
*outptr7 += sum7;
ktmp -= 8*9;
outptr0++;
outptr1++;
outptr2++;
outptr3++;
outptr4++;
outptr5++;
outptr6++;
outptr7++;
#endif // __ARM_NEON
r0 += 2;
r1 += 2;
r2 += 2;
}
r0 += tailstep;
r1 += tailstep;
r2 += tailstep;
}
ktmp += 8*9;
}
}
#pragma omp parallel for num_threads(opt.num_threads)
for (int p=remain_outch_start; p<outch; p++)
{
Mat out = top_blob.channel(p);
out.fill(0);
const signed char* ktmp = _kernel.channel(p/8 + p%8);
for (int q=0; q<inch; q++)
{
short* outptr = out;
const signed char* img0 = bottom_blob.channel(q);
const signed char* r0 = img0;
const signed char* r1 = img0 + w;
const signed char* r2 = img0 + w*2;
int i = 0;
for (; i < outh; i++)
{
#if 0 //__ARM_NEON
int nn = outw >> 3;
int remain = outw & 7;
#else
int remain = outw;
#endif // __ARM_NEON
#if 0 //__ARM_NEON
#if __aarch64__
if (nn > 0)
{
asm volatile(
"0: \n"
"ld1 {v0.8b, v1.8b}, [%5] \n"//ktmp
"ld2 {v2.8b, v3.8b}, [%2], #16 \n"//r0-r2
"ld2 {v4.8b, v5.8b}, [%2] \n"
"ld2 {v6.8b, v7.8b}, [%3], #16 \n"//r3-r5
"ld2 {v8.8b, v9.8b}, [%3] \n"
"ld2 {v10.8b, v11.8b}, [%4], #16 \n"//r6-r8
"ld2 {v12.8b, v13.8b}, [%4] \n"
"ld1 {v14.4s, v15.4s}, [%1] \n"//out0
"ext v4.8b, v2.8b, v4.8b, #1 \n"
"ext v8.8b, v6.8b, v8.8b, #1 \n"
"ext v12.8b, v10.8b, v12.8b, #1 \n"
"sshll v0.8h, v0.8b, #0 \n"//(k0-k7)
"sshll v1.8h, v1.8b, #0 \n"//(k8)
"sshll v2.8h, v2.8b, #0 \n"// r0
"sshll v3.8h, v3.8b, #0 \n"// r1
"sshll v4.8h, v4.8b, #0 \n"// r2
"sshll v6.8h, v6.8b, #0 \n"// r3
"sshll v7.8h, v7.8b, #0 \n"// r4
"sshll v8.8h, v8.8b, #0 \n"// r5
"sshll v10.8h, v10.8b, #0 \n"// r6
"sshll v11.8h, v11.8b, #0 \n"// r7
"sshll v12.8h, v12.8b, #0 \n"// r8
// r0
"smull v16.4s, v2.4h, v0.h[0] \n"// out = r0*k0
"smull2 v17.4s, v2.8h, v0.h[0] \n"
"smull v18.4s, v3.4h, v0.h[1] \n"// outn = r1*k1
"smull2 v19.4s, v3.8h, v0.h[1] \n"
"smlal v16.4s, v4.4h, v0.h[2] \n"// out = r2*k2
"smlal2 v17.4s, v4.8h, v0.h[2] \n"
"smlal v18.4s, v6.4h, v0.h[3] \n"// outn = r3*k3
"smlal2 v19.4s, v6.8h, v0.h[3] \n"
"smlal v16.4s, v7.4h, v0.h[4] \n"// out = r4*k4
"smlal2 v17.4s, v7.8h, v0.h[4] \n"
"smlal v18.4s, v8.4h, v0.h[5] \n"// outn = r5*k5
"smlal2 v19.4s, v8.8h, v0.h[5] \n"
"smlal v16.4s, v10.4h, v0.h[6] \n"// out = r6*k6
"smlal2 v17.4s, v10.8h, v0.h[6] \n"
"smlal v18.4s, v11.4h, v0.h[7] \n"// outn = r7*k7
"smlal2 v19.4s, v11.8h, v0.h[7] \n"
"smlal v16.4s, v12.4h, v1.h[0] \n"// out = r8*k8
"smlal2 v17.4s, v12.8h, v1.h[0] \n"
"add v8.4s, v16.4s, v18.4s \n"
"add v9.4s, v17.4s, v19.4s \n"
"st1 {v8.4s, v9.4s}, [%1], #32 \n"
"subs %w0, %w0, #1 \n"
"bne 0b \n"
: "=r"(nn), // %0
"=r"(outptr), // %1
"=r"(r0), // %2
"=r"(r1), // %3
"=r"(r2), // %4
"=r"(ktmp) // %5
: "0"(nn),
"1"(outptr),
"2"(r0),
"3"(r1),
"4"(r2),
"5"(ktmp)
: "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19"
);
}
#else
if (nn > 0)
{
asm volatile(
"vld1.s8 {d0-d1}, [%5] \n"// d0(k0 - k7) d1(k8 ...)
"vmovl.s8 q1, d1 \n"// d2(k8 ...)
"vmovl.s8 q0, d0 \n"// d0(k0 - k3) d1(k4 - k7)
"0: \n"
"pld [%2, #192] \n"
"vld2.s8 {d4-d5}, [%2]! \n"// r0 d4(a00 a02 ... a014) d5(a01 a03 ... a015)
"vld2.s8 {d8-d9}, [%2] \n"// d8(a016 ....)
"vld2.s8 {d10-d11}, [%3]! \n"// r1 d10(a10 a12 ... a114) d11(a11 a13 ... a115)
"vld2.s8 {d14-d15}, [%3] \n"// d14(a116 ....)
"vld2.s8 {d16-d17}, [%4]! \n"// r2 d16(a20 a22 ... a214) d17(a21 a23 ... a215)
"vld2.s8 {d20-d21}, [%4] \n"// d20(a216 ....)
"vld1.s32 {d22-d25}, [%1] \n"// q11(out0 - out3) q12(out4 - out7)
"vext.s8 d8, d4, d8, #1 \n"// d8(a02 a04 ... a016)
"vext.s8 d14, d10, d14, #1 \n"// d14(a12 a14 ... a116)
"vext.s8 d20, d16, d20, #1 \n"// d20(a22 a24 ... a216)
"vmovl.s8 q3, d5 \n"// q3(a01 a03 ... a015)
"vmovl.s8 q2, d4 \n"// q2(a00 a02 ... a014)
"vmovl.s8 q4, d8 \n"// q4(a02 a04 ... a016)
"vmovl.s8 q6, d11 \n"// q6(a11 a13 ... a115)
"vmovl.s8 q5, d10 \n"// q5(a10 a12 ... a114)
"vmovl.s8 q7, d14 \n"// q7(a12 a14 ... a116)
"vmovl.s8 q9, d17 \n"// q9(a21 a23 ... a215)
"vmovl.s8 q8, d16 \n"// q8(a20 a22 ... a214)
"vmovl.s8 q10, d20 \n"// q10(a22 a24 ... a216)
"vmlal.s16 q11, d4, d0[0] \n"// k0
"vmlal.s16 q12, d5, d0[0] \n"
"vmull.s16 q13, d6, d0[1] \n"// k1
"vmull.s16 q14, d7, d0[1] \n"
"vmlal.s16 q11, d8, d0[2] \n"// k2
"vmlal.s16 q12, d9, d0[2] \n"
"vmlal.s16 q13, d12, d1[0] \n"// k4
"vmlal.s16 q14, d13, d1[0] \n"
"vmlal.s16 q11, d10, d0[3] \n"// k3
"vmlal.s16 q12, d11, d0[3] \n"
"vmlal.s16 q13, d14, d1[1] \n"// k5
"vmlal.s16 q14, d15, d1[1] \n"
"vmlal.s16 q11, d16, d1[2] \n"// k6
"vmlal.s16 q12, d17, d1[2] \n"
"vmlal.s16 q13, d18, d1[3] \n"// k7
"vmlal.s16 q14, d19, d1[3] \n"
"vmlal.s16 q11, d20, d2[0] \n"// k8
"vmlal.s16 q12, d21, d2[0] \n"
"vadd.s32 q11, q11, q13 \n"
"vadd.s32 q12, q12, q14 \n"
"vst1.32 {d22-d25}, [%1]! \n"
"subs %0, #1 \n"
"bne 0b \n"
: "=r"(nn), // %0
"=r"(outptr), // %1
"=r"(r0), // %2
"=r"(r1), // %3
"=r"(r2), // %4
"=r"(ktmp) // %5
: "0"(nn),
"1"(outptr),
"2"(r0),
"3"(r1),
"4"(r2),
"5"(ktmp)
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"
);
}
#endif // __aarch64__
#endif // __ARM_NEON
if (remain > 0)
{
#if 0 //__ARM_NEON
int8x8_t _k01234567s8 = vld1_s8(ktmp);
int8x8_t _k8xxxxxxxs8 = vld1_s8(ktmp+8);
int8x8_t _k34567xxxs8 = vext_s8(_k01234567s8, _k01234567s8, 3);
int8x8_t _k678xxxxxs8 = vext_s8(_k01234567s8, _k8xxxxxxxs8, 6);
int16x8_t _k0123_s16 = vmovl_s8(_k01234567s8);
int16x8_t _k3456_s16 = vmovl_s8(_k34567xxxs8);
int16x8_t _k678x_s16 = vmovl_s8(_k678xxxxxs8);
#endif
for (; remain>0; remain--)
{
#if 0 //__ARM_NEON
int8x8_t _r00s8 = vld1_s8(r0);
int8x8_t _r10s8 = vld1_s8(r1);
int8x8_t _r20s8 = vld1_s8(r2);
int16x8_t _r00s16 = vmovl_s8(_r00s8);
int16x8_t _r10s16 = vmovl_s8(_r10s8);
int16x8_t _r20s16 = vmovl_s8(_r20s8);
int32x4_t _sum = vmull_s16(vget_low_s16(_r00s16), vget_low_s16(_k0123_s16));
_sum = vmlal_s16(_sum, vget_low_s16(_r10s16), vget_low_s16(_k3456_s16));
_sum = vmlal_s16(_sum, vget_low_s16(_r20s16), vget_low_s16(_k678x_s16));
_sum = vsetq_lane_s32(*outptr, _sum, 3);
#if __aarch64__
*outptr = vaddvq_s32(_sum);
#else
int32x2_t _ss = vadd_s32(vget_low_s32(_sum), vget_high_s32(_sum));
_ss = vpadd_s32(_ss, _ss);
*outptr = vget_lane_s32(_ss, 0);
#endif // __aarch64__
#else
short sum = 0;
sum += (short)r0[0] * ktmp[0];
sum += (short)r0[1] * ktmp[1];
sum += (short)r0[2] * ktmp[2];
sum += (short)r1[0] * ktmp[3];
sum += (short)r1[1] * ktmp[4];
sum += (short)r1[2] * ktmp[5];
sum += (short)r2[0] * ktmp[6];
sum += (short)r2[1] * ktmp[7];
sum += (short)r2[2] * ktmp[8];
*outptr += sum;
#endif // __ARM_NEON
r0 += 2;
r1 += 2;
r2 += 2;
outptr++;
}
}
r0 += tailstep;
r1 += tailstep;
r2 += tailstep;
}
ktmp += 9;
}
}
} |
EmbeddingBag.h | /******************************************************************************
* Copyright (c) Intel Corporation - All rights reserved. *
* This file is part of the LIBXSMM library. *
* *
* For information on the license, see the LICENSE file. *
* Further information: https://github.com/libxsmm/libxsmm/ *
* SPDX-License-Identifier: BSD-3-Clause *
******************************************************************************/
/* Dhiraj Kalamkar, Evangelos Georganas (Intel Corp.)
******************************************************************************/
#if defined(USE_LIBXSMM_JIT)
#include <libxsmm.h>
#endif
#include "utils.h"
#include "rtm.h"
template <typename T>
class EmbeddingBagImpl
{
public:
EmbeddingBagImpl(long M, long E) : M(M), E(E)
{
#ifdef USE_LIBXSMM_JIT
libxsmm_meltw_unary_shape unary_shape_f32 = libxsmm_create_meltw_unary_shape( E, 0, _ld, _ld, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32 );
libxsmm_meltw_unary_shape unary_shape_f16 = libxsmm_create_meltw_unary_shape( E, 0, _ld, _ld, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32 );
libxsmm_meltw_binary_shape binary_shape_f32 = libxsmm_create_meltw_binary_shape( E, 1, _ld, _ld, _ld, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32 );
weight_ = (T*)my_malloc((size_t)M * E * sizeof(T), alignment);
_ld = E;
if (sizeof(T) == 4) {
kernel = libxsmm_dispatch_meltw_unary_v2( LIBXSMM_MELTW_TYPE_UNARY_REDUCE_COLS_IDX, unary_shape_f32, (sizeof(long) == 8) ? LIBXSMM_MELTW_FLAG_UNARY_IDX_SIZE_8BYTES : LIBXSMM_MELTW_FLAG_UNARY_IDX_SIZE_4BYTES );
} else {
kernel = libxsmm_dispatch_meltw_unary_v2( LIBXSMM_MELTW_TYPE_UNARY_REDUCE_COLS_IDX, unary_shape_f16, (sizeof(long) == 8) ? LIBXSMM_MELTW_FLAG_UNARY_IDX_SIZE_8BYTES : LIBXSMM_MELTW_FLAG_UNARY_IDX_SIZE_4BYTES );
}
kernel1 = libxsmm_dispatch_meltw_unary_v2( LIBXSMM_MELTW_TYPE_UNARY_REPLICATE_COL_VAR, unary_shape_f32, LIBXSMM_MELTW_FLAG_UNARY_NONE );
kernel2 = libxsmm_dispatch_meltw_binary_v2( LIBXSMM_MELTW_TYPE_BINARY_MULADD, binary_shape_f32, LIBXSMM_MELTW_FLAG_BINARY_BCAST_SCALAR_IN_0 );
#endif
}
~EmbeddingBagImpl()
{
my_free(weight_);
weight_ = 0;
}
void init(T low = -0.1, T high = 0.1)
{
init_random(M * E, weight_, low, high);
}
#ifdef USE_LIBXSMM_JIT
void forward(long N, long NS, const long *offsets, const long *indices, T *output_)
{
T(*__restrict weight)[E] = (T(*)[*])weight_;
T(*__restrict output)[E] = (T(*)[*])output_;
#pragma omp parallel for
for (int n = 0; n < N; n++)
{
libxsmm_meltw_unary_param params;
auto start = offsets[n];
auto end = (n < N - 1 ? offsets[n + 1] : NS);
unsigned long long __n = end-start;
params.in.primary = weight;
params.in.secondary = (void*)&indices[start];
params.in.tertiary = &__n;
params.out.primary = &output[n][0];
kernel( ¶ms );
}
}
#else
void forward(long N, long NS, const long *offsets, const long *indices, T *output_)
{
T(*__restrict weight)[E] = (T(*)[*])weight_;
T(*__restrict output)[E] = (T(*)[*])output_;
#pragma omp parallel for
for (long n = 0; n < N; n++)
{
auto start = offsets[n];
auto end = (n < N - 1 ? offsets[n + 1] : NS);
#pragma omp simd
for (long v = 0; v < E; v++)
output[n][v] = 0;
for (long s = start; s < end; s++)
{
auto ind = indices[s];
#pragma omp simd
for (long v = 0; v < E; v++)
{
output[n][v] += weight[ind][v];
}
}
}
}
#endif
#ifdef USE_LIBXSMM_JIT
void backward(long N, long NS, const T *gradout_, const long *offsets, const long *indices, T *values_)
{
T(*__restrict gradout)[E] = (T(*)[*])gradout_;
T(*__restrict values)[E] = (T(*)[*])values_;
int _ld = E;
#pragma omp parallel for
for (long n = 0; n < N; n++)
{
libxsmm_meltw_unary_param unary_param;
auto start = offsets[n];
auto end = (n < N - 1 ? offsets[n + 1] : NS);
unsigned long long _N = end-start;
unary_param.in.primary = (void*)&gradout[n][0];
unary_param.out.primary = (void*)&values[start][0];
unary_param.op.primary = (void*)&_N;
kernel1(&unary_param);
}
}
#else
void backward(long N, long NS, const T *gradout_, const long *offsets, const long *indices, T *values_)
{
T(*__restrict gradout)[E] = (T(*)[*])gradout_;
T(*__restrict values)[E] = (T(*)[*])values_;
#pragma omp parallel for
for (long n = 0; n < N; n++)
{
auto start = offsets[n];
auto end = (n < N - 1 ? offsets[n + 1] : NS);
for (long s = start; s < end; s++)
{
#pragma omp simd
#ifdef STREAMING_WRITES
#pragma vector nontemporal(values)
#endif
for (long v = 0; v < E; v++)
values[s][v] = gradout[n][v];
}
}
}
#endif
#ifdef USE_LIBXSMM_JIT
void update(long NS, const T *grads_, const long *indices, float lr, long M, int use_rtm)
{
int use_lock_free = use_rtm == 0 ? 1: 0;
T(*__restrict weight)[E] = (T(*)[*])weight_;
T(*__restrict grads)[E] = (T(*)[*])grads_;
int _ld = E;
if(use_lock_free) {
/*printf("Using lock free update\n");*/
int max_thr = omp_get_max_threads();
if(M < max_thr) max_thr = M;
#pragma omp parallel num_threads(max_thr)
{
int tid = omp_get_thread_num();
for(long i = 0; i < NS; i++) {
auto ind = indices[i];
if(ind % max_thr == tid) {
libxsmm_meltw_binary_param binary_param;
binary_param.in0.primary = (void*)&lr;
binary_param.in1.primary = (void*)&grads[i][0];
binary_param.out.primary = (void*)&weight[ind][0];
{
kernel2(&binary_param);
}
}
}
}
} else {
SimpleSpinLock fallBackLock;
#pragma omp parallel for
for (long i = 0; i < NS; i++)
{
libxsmm_meltw_binary_param binary_param;
long ind = indices[i];
binary_param.in0.primary = (void*)&lr;
binary_param.in1.primary = (void*)&grads[i][0];
binary_param.out.primary = (void*)&weight[ind][0];
{
TransactionScope guard(fallBackLock, 100, 0);
kernel2(&binary_param);
}
}
}
}
#else
void update(long NS, const T *grads_, const long *indices, float lr, long M, int use_rtm)
{
T(*__restrict weight)[E] = (T(*)[*])weight_;
T(*__restrict grads)[E] = (T(*)[*])grads_;
int use_lock_free = use_rtm == 0 ? 1: 0;
if(use_lock_free) {
int max_thr = omp_get_max_threads();
if(M < max_thr) max_thr = M;
#pragma omp parallel num_threads(max_thr)
{
int tid = omp_get_thread_num();
for(long i = 0; i < NS; i++) {
auto ind = indices[i];
if(ind % max_thr == tid) {
#pragma omp simd
for (long v = 0; v < E; v++)
weight[ind][v] += lr * grads[i][v];
}
}
}
} else {
SimpleSpinLock fallBackLock;
#pragma omp parallel for
for (long i = 0; i < NS; i++)
{
long ind = indices[i];
{
TransactionScope guard(fallBackLock, 100, 0);
#pragma omp simd
for (long v = 0; v < E; v++)
weight[ind][v] += lr * grads[i][v];
}
}
}
}
#endif
T *weight_;
long M;
long E;
#ifdef USE_LIBXSMM_JIT
int _ld;
libxsmm_meltwfunction_unary kernel;
libxsmm_meltwfunction_unary kernel1;
libxsmm_meltwfunction_binary kernel2;
#endif
};
|
no_type_ops.h | /* Copyright 2015 The math21 Authors. All Rights Reserved.
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.
==============================================================================*/
#pragma once
#include "inner.h"
namespace math21 {
template<typename T, typename S, template<typename> class Container1,
template<typename> class Container2>
void math21_operator_container_assign(const Container1<T> &A, Container2<S> &B) {
MATH21_ASSERT(A.size() == B.size())
NumN n = A.size();
//#pragma omp parallel for
for (NumN i = 1; i <= n; ++i) {
B.at(i) = A(i);
}
}
// Set B using values of A. offset in [0, n).
template<typename T, typename S, template<typename> class Container1,
template<typename> class Container2>
void math21_operator_container_set_partially(const Container1<T> &A, Container2<S> &B,
NumN offset1 = 0, NumN offset2 = 0, NumN count = 0) {
MATH21_ASSERT(offset1 < A.size() && offset2 < B.size());
if (count == 0) {
count = xjmin(A.size() - offset1, B.size() - offset2);
} else {
MATH21_ASSERT(count + offset1 <= A.size());
MATH21_ASSERT(count + offset2 <= B.size());
}
NumN k;
for (k = 1; k <= count; ++k) {
B(offset2 + k) = A(offset1 + k);
}
}
// set using map
template<typename T, typename S, template<typename> class Container1,
template<typename> class Container2,
template<typename> class Container3>
void math21_operator_container_set_by_map(const Container1<T> &A, Container2<S> &B, const Container3<NumN> &map) {
MATH21_ASSERT(B.size() == map.size())
NumN n = B.size();
for (NumN i = 1; i <= n; ++i) {
B.at(i) = A(map(i));
}
}
template<typename T, template<typename> class Container>
void math21_operator_container_swap(Container<T> &x, NumZ pos, NumZ pos2) {
NumN p1 = math21_number_container_pos_check(x.size(), pos);
NumN p2 = math21_number_container_pos_check(x.size(), pos2);
m21_swap(x(p1), x(p2));
}
// abcde => acdbe if from = 2, to = 4
// abcde => adbce if from = 4, to = 2
template<typename VecType>
void math21_operator_container_move(VecType &x, NumZ from0, NumZ to0) {
MATH21_ASSERT(!x.isEmpty());
NumN n1 = x.size();
NumN from = math21_number_container_pos_check(n1, from0);
NumN to = math21_number_container_pos_check(n1, to0);
if(from==to){
return;
}
VecType s;
if(from<to){
math21_operator_container_subcontainer(x, s, from+1, to);
x(to) = x(from);
math21_operator_container_set_partially(s, x, 0, from-1);
}else{
math21_operator_container_subcontainer(x, s, to, from-1);
x(to) = x(from);
math21_operator_container_set_partially(s, x, 0, to);
}
}
//////
template<typename VecType>
void math21_operator_container_reverse(const VecType &x, VecType &y) {
NumN n = x.size();
MATH21_ASSERT(y.size() == n);
for (NumN i = 1, j = n; i <= n; ++i, --j) {
y(i) = x(j);
}
}
template<typename VecType>
void math21_operator_reverse(VecType &x) {
NumN n = x.size();
NumN n2 = n / 2;
//#pragma omp parallel for
for (NumN k = 1; k <= n2; ++k) {
m21_swap(x.at(k), x.at(n + 1 - k));
}
}
// see math21_op_vector_concatenate
template<typename VecType, typename VecType2, typename VecType3>
void math21_operator_merge(const VecType &x, const VecType2 &y, VecType3 &z) {
NumN n1 = x.size();
NumN n2 = y.size();
NumN n = n1 + n2;
z.setSize(n);
//#pragma omp parallel for
for (NumN k = 1; k <= n; ++k) {
if (k <= n1) {
z.at(k) = x(k);
} else {
z.at(k) = y(k - n1);
}
}
}
template<typename VecType>
void math21_operator_container_sub_from_start(VecType &x, NumN size = 0) {
MATH21_ASSERT(!x.isEmpty())
NumN n1 = x.size();
if (size == 0) {
x.clear();
return;
}
if (n1 == size) {
return;
}
MATH21_ASSERT(size <= n1)
NumN n2 = size;
VecType y;
y.setSize(n2);
for (NumN k = 1; k <= n2; ++k) {
y.at(k) = x(k);
}
x.setSize(size);
x.assign(y);
}
// now support negative index
// 1 <= from <= to <= x.size(), [from , to]
template<typename VecType>
void math21_operator_container_subcontainer(const VecType &x, VecType &y, NumZ from, NumZ to = -1) {
MATH21_ASSERT(!x.isEmpty())
NumN n1 = x.size();
from = math21_number_container_pos_check(n1, from);
to = math21_number_container_pos_check(n1, to);
MATH21_ASSERT(from >= 1 && from <= to && to <= n1)
NumN n2 = (NumN) (to + 1 - from);
if (y.size() != n2) {
y.setSize(n2);
}
NumN offset = (NumN) (from - 1);
for (NumN k = 1; k <= n2; ++k) {
y.at(k) = x(offset + k);
}
}
// Todo: change NumN to NumZ
// u is max, v is number. return 0 if fail.
template<template<typename> class Container,
template<typename> class Container2>
NumB math21_operator_container_increaseNumFromRight(const Container<NumN> &u, Container2<NumN> &v) {
MATH21_ASSERT(!v.isEmpty());
MATH21_ASSERT(u.size() == v.size());
for (NumN i = v.size(); i >= 1; --i) {
if (v(i) < u(i)) {
v.at(i) = v(i) + 1;
return 1;
} else {
MATH21_ASSERT(v(i) == u(i), "v(i) = " << v(i) << ", u(i) = " << u(i) << "\n");
v.at(i) = 1;
}
}
return 0;
}
// Todo: change NumN to NumZ
// u is max, v is number. return 0 if fail.
// u is end index, start is start index. v is current index.
template<template<typename> class Container,
template<typename> class Container2>
NumB math21_operator_container_increaseNumFromRight(const Container<NumN> &u, Container2<NumN> &v,
const Container<NumN> &start) {
MATH21_ASSERT(!v.isEmpty());
MATH21_ASSERT(u.size() == v.size());
MATH21_ASSERT(u.size() == start.size());
for (NumN i = v.size(); i >= 1; --i) {
if (v(i) < u(i)) {
v.at(i) = v(i) + 1;
return 1;
} else {
MATH21_ASSERT(v(i) == u(i));
v.at(i) = start(i);
}
}
return 0;
}
// d is shape, a is start index.
// y-a(n) = sum ((x(i)-a(i))*k(i))
template<template<typename> class Container,
typename VecZType, typename VecZType2>
void math21_operator_number_index_1d_to_nd(VecZType &x, NumZ y, const Container<NumN> &d,
const VecZType2 &a) {
NumN n = d.size();
MATH21_ASSERT(!x.isEmpty() && x.size() == n)
Container<NumN> k(n);
k(n) = 1;
NumN i;
for (i = n - 1; i >= 1; --i) {
k(i) = d(i + 1) * k(i + 1);
}
y = y - (NumZ) a(n);
for (i = 1; i <= n; ++i) {
x(i) = y / k(i) + a(i);
y = y % k(i);
}
}
// d is shape, a is start index.
// y-a(n) = sum ((x(i)-a(i))*k(i))
template<template<typename> class Container,
template<typename> class Container2, typename NumZType>
void math21_operator_number_index_1d_to_tensor_nd(Container2<NumZType> &x, NumZ y, const Container<NumN> &d) {
Container<NumZType> a(d.size());
a = 1;
math21_operator_number_index_1d_to_nd(x, y, d, a);
}
// see math21_device_index_replace_inc
// replace A by R where A(i) = x.
template<typename T, template<typename> class Container, typename VecType>
void math21_operator_container_replace_inc(const Container<T> &A, Container<T> &B, const VecType &R, const T &x) {
MATH21_ASSERT(B.size() == A.size())
NumN j = 1;
for (NumN i = 1; i <= B.size(); ++i) {
if (A(i) == x) {
B(i) = R(j);
++j;
} else {
B(i) = A(i);
}
}
MATH21_ASSERT(j - 1 == R.size(), "j is " << j);
}
// replace A by R where A(i) = x.
template<typename T, template<typename> class Container, typename VecType>
void math21_operator_container_replace_by_same_pos(const Container<T> &A, Container<T> &B, const VecType &R,
const T &x) {
MATH21_ASSERT(B.size() == A.size())
MATH21_ASSERT(R.size() == A.size())
for (NumN i = 1; i <= B.size(); ++i) {
if (A(i) == x) {
B(i) = R(i);
} else {
B(i) = A(i);
}
}
}
// normal mode
// number to representation from right, x, i(k) in [1, ...].
template<template<typename> class Container,
template<typename> class Container2>
void math21_operator_number_num_to_index_right(NumN x, Container<NumN> &i, const Container2<NumN> &d) {
MATH21_ASSERT(d.size() == i.size())
x = x - 1;
NumN n = d.size();
for (NumN k = n; k >= 1; --k) {
i(k) = x % d(k) + 1;
x = x / d(k);
}
}
// number to representation from left, x, i(k) in [1, ...].
template<template<typename> class Container,
template<typename> class Container2>
void math21_operator_number_num_to_index_left(NumN x, Container<NumN> &i, const Container2<NumN> &d) {
printf("Check this please! left is changed to right in code.");
MATH21_ASSERT(d.size() == i.size())
x = x - 1;
NumN n = d.size();
for (NumN k = 1; k <= n; ++k) {
i(k) = x % d(k) + 1;
x = x / d(k);
}
}
// representation to number from right, x, i(k) in [1, ...].
template<template<typename> class Container,
template<typename> class Container2>
NumN math21_operator_number_index_to_num_right(const Container<NumN> &i, const Container2<NumN> &d) {
MATH21_ASSERT(d.size() == i.size())
NumN x;
x = 0;
NumN n = d.size();
for (NumN k = 1; k <= n; ++k) {
x = x * d(k) + i(k) - 1;
}
x = x + 1;
return x;
}
// representation to number from left, x, i(k) in [1, ...].
template<template<typename> class Container,
template<typename> class Container2>
NumN math21_operator_number_index_to_num_left(const Container<NumN> &i, const Container2<NumN> &d) {
MATH21_ASSERT(d.size() == i.size())
NumN x;
x = 0;
NumN n = d.size();
for (NumN k = n; k >= 1; --k) {
x = x * d(k) + i(k) - 1;
}
x = x + 1;
return x;
}
template<typename VecType, template<typename> class Container>
NumN math21_operator_container_2d_size(const Container<VecType> &v) {
NumN k = 0;
NumN n = v.size();
for (NumN i = 1; i <= n; ++i) {
k = k + v(i).size();
}
return k;
}
template<typename VecType, template<typename> class Container>
NumN math21_operator_container_2d_element_size_max(const Container<VecType> &v) {
// NumN k = 0;
NumN size = 0;
NumN n = v.size();
for (NumN i = 1; i <= n; ++i) {
if (v(i).size() > size) {
// k = i;
size = v(i).size();
}
}
return size;
}
template<typename VecType, template<typename> class Container>
void math21_operator_container_element_setSize(Container<VecType> &v, NumN k) {
NumN n = v.size();
//#pragma omp parallel for
for (NumN i = 1; i <= n; ++i) {
v.at(i).setSize(k);
}
}
template<typename T>
T math21_operator_number_clip(const T &x0, const NumR &min, const NumR &max) {
T x = x0;
if (x > max) {
x = max;
} else if (x < min) {
x = min;
}
return x;
}
} |
LAGraph_Sort2.c | //------------------------------------------------------------------------------
// LAGraph_Sort2: sort a 2-by-n list of integers, using A[0:1][ ] as the key
//------------------------------------------------------------------------------
// LAGraph, (c) 2021 by The LAGraph Contributors, All Rights Reserved.
// SPDX-License-Identifier: BSD-2-Clause
// See additional acknowledgments in the LICENSE file,
// or contact permission@sei.cmu.edu for the full terms.
// Contributed by Timothy A. Davis, Texas A&M University
//------------------------------------------------------------------------------
// A parallel mergesort of an array of 2-by-n integers. Each key
// consists of two integers.
#define LG_FREE_ALL LAGraph_Free ((void **) &W, NULL) ;
#include "LG_internal.h"
//------------------------------------------------------------------------------
// prototype only needed for LAGraph_Sort2
//------------------------------------------------------------------------------
void LG_msort_2b_create_merge_tasks
(
// output:
int64_t *LG_RESTRICT L_task, // L_task [t0...t0+ntasks-1] computed
int64_t *LG_RESTRICT L_len, // L_len [t0...t0+ntasks-1] computed
int64_t *LG_RESTRICT R_task, // R_task [t0...t0+ntasks-1] computed
int64_t *LG_RESTRICT R_len, // R_len [t0...t0+ntasks-1] computed
int64_t *LG_RESTRICT S_task, // S_task [t0...t0+ntasks-1] computed
// input:
const int t0, // first task tid to create
const int ntasks, // # of tasks to create
const int64_t pS_start, // merge into S [pS_start...]
const int64_t *LG_RESTRICT L_0, // Left = L [pL_start...pL_end-1]
const int64_t *LG_RESTRICT L_1,
const int64_t pL_start,
const int64_t pL_end,
const int64_t *LG_RESTRICT R_0, // Right = R [pR_start...pR_end-1]
const int64_t *LG_RESTRICT R_1,
const int64_t pR_start,
const int64_t pR_end
) ;
//------------------------------------------------------------------------------
// LG_msort_2b_binary_search: binary search for the pivot
//------------------------------------------------------------------------------
// The Pivot value is Y [pivot], and a binary search for the Pivot is made in
// the array X [p_pstart...p_end-1], which is sorted in non-decreasing order on
// input. The return value is pleft, where
//
// X [p_start ... pleft-1] <= Pivot and
// X [pleft ... p_end-1] >= Pivot holds.
//
// pleft is returned in the range p_start to p_end. If pleft is p_start, then
// the Pivot is smaller than all entries in X [p_start...p_end-1], and the left
// list X [p_start...pleft-1] is empty. If pleft is p_end, then the Pivot is
// larger than all entries in X [p_start...p_end-1], and the right list X
// [pleft...p_end-1] is empty.
static int64_t LG_msort_2b_binary_search // return pleft
(
const int64_t *LG_RESTRICT Y_0, // Pivot is Y [pivot]
const int64_t *LG_RESTRICT Y_1,
const int64_t pivot,
const int64_t *LG_RESTRICT X_0, // search in X [p_start..p_end_-1]
const int64_t *LG_RESTRICT X_1,
const int64_t p_start,
const int64_t p_end
)
{
//--------------------------------------------------------------------------
// find where the Pivot appears in X
//--------------------------------------------------------------------------
// binary search of X [p_start...p_end-1] for the Pivot
int64_t pleft = p_start ;
int64_t pright = p_end - 1 ;
while (pleft < pright)
{
int64_t pmiddle = (pleft + pright) >> 1 ;
// less = (X [pmiddle] < Pivot)
bool less = LG_lt_2 (X_0, X_1, pmiddle,
Y_0, Y_1, pivot) ;
pleft = less ? (pmiddle+1) : pleft ;
pright = less ? pright : pmiddle ;
}
// binary search is narrowed down to a single item
// or it has found the list is empty:
ASSERT (pleft == pright || pleft == pright + 1) ;
// If found is true then X [pleft == pright] == Pivot. If duplicates
// appear then X [pleft] is any one of the entries equal to the Pivot
// in the list. If found is false then
// X [p_start ... pleft-1] < Pivot and
// X [pleft+1 ... p_end-1] > Pivot holds.
// The value X [pleft] may be either < or > Pivot.
bool found = (pleft == pright) && LG_eq_2 (X_0, X_1, pleft,
Y_0, Y_1, pivot) ;
// Modify pleft and pright:
if (!found && (pleft == pright))
{
if (LG_lt_2 (X_0, X_1, pleft,
Y_0, Y_1, pivot))
{
pleft++ ;
}
else
{
// pright++ ; // (not needed)
}
}
//--------------------------------------------------------------------------
// return result
//--------------------------------------------------------------------------
// If found is false then
// X [p_start ... pleft-1] < Pivot and
// X [pleft ... p_end-1] > Pivot holds,
// and pleft-1 == pright
// If X has no duplicates, then whether or not Pivot is found,
// X [p_start ... pleft-1] < Pivot and
// X [pleft ... p_end-1] >= Pivot holds.
// If X has duplicates, then whether or not Pivot is found,
// X [p_start ... pleft-1] <= Pivot and
// X [pleft ... p_end-1] >= Pivot holds.
return (pleft) ;
}
//------------------------------------------------------------------------------
// LG_msort_2b_create_merge_tasks
//------------------------------------------------------------------------------
// Recursively constructs ntasks tasks to merge two arrays, Left and Right,
// into Sresult, where Left is L [pL_start...pL_end-1], Right is R
// [pR_start...pR_end-1], and Sresult is S [pS_start...pS_start+total_work-1],
// and where total_work is the total size of Left and Right.
//
// Task tid will merge L [L_task [tid] ... L_task [tid] + L_len [tid] - 1] and
// R [R_task [tid] ... R_task [tid] + R_len [tid] -1] into the merged output
// array S [S_task [tid] ... ]. The task tids created are t0 to
// t0+ntasks-1.
void LG_msort_2b_create_merge_tasks
(
// output:
int64_t *LG_RESTRICT L_task, // L_task [t0...t0+ntasks-1] computed
int64_t *LG_RESTRICT L_len, // L_len [t0...t0+ntasks-1] computed
int64_t *LG_RESTRICT R_task, // R_task [t0...t0+ntasks-1] computed
int64_t *LG_RESTRICT R_len, // R_len [t0...t0+ntasks-1] computed
int64_t *LG_RESTRICT S_task, // S_task [t0...t0+ntasks-1] computed
// input:
const int t0, // first task tid to create
const int ntasks, // # of tasks to create
const int64_t pS_start, // merge into S [pS_start...]
const int64_t *LG_RESTRICT L_0, // Left = L [pL_start...pL_end-1]
const int64_t *LG_RESTRICT L_1,
const int64_t pL_start,
const int64_t pL_end,
const int64_t *LG_RESTRICT R_0, // Right = R [pR_start...pR_end-1]
const int64_t *LG_RESTRICT R_1,
const int64_t pR_start,
const int64_t pR_end
)
{
//--------------------------------------------------------------------------
// get problem size
//--------------------------------------------------------------------------
int64_t nleft = pL_end - pL_start ; // size of Left array
int64_t nright = pR_end - pR_start ; // size of Right array
int64_t total_work = nleft + nright ; // total work to do
ASSERT (ntasks >= 1) ;
ASSERT (total_work > 0) ;
//--------------------------------------------------------------------------
// create the tasks
//--------------------------------------------------------------------------
if (ntasks == 1)
{
//----------------------------------------------------------------------
// a single task will merge all of Left and Right into Sresult
//----------------------------------------------------------------------
L_task [t0] = pL_start ; L_len [t0] = nleft ;
R_task [t0] = pR_start ; R_len [t0] = nright ;
S_task [t0] = pS_start ;
}
else
{
//----------------------------------------------------------------------
// partition the Left and Right arrays for multiple merge tasks
//----------------------------------------------------------------------
int64_t pleft, pright ;
if (nleft >= nright)
{
// split Left in half, and search for its pivot in Right
pleft = (pL_end + pL_start) >> 1 ;
pright = LG_msort_2b_binary_search (
L_0, L_1, pleft,
R_0, R_1, pR_start, pR_end) ;
}
else
{
// split Right in half, and search for its pivot in Left
pright = (pR_end + pR_start) >> 1 ;
pleft = LG_msort_2b_binary_search (
R_0, R_1, pright,
L_0, L_1, pL_start, pL_end) ;
}
//----------------------------------------------------------------------
// partition the tasks according to the work of each partition
//----------------------------------------------------------------------
// work0 is the total work in the first partition
int64_t work0 = (pleft - pL_start) + (pright - pR_start) ;
int ntasks0 = (int) round ((double) ntasks *
(((double) work0) / ((double) total_work))) ;
// ensure at least one task is assigned to each partition
ntasks0 = LAGRAPH_MAX (ntasks0, 1) ;
ntasks0 = LAGRAPH_MIN (ntasks0, ntasks-1) ;
int ntasks1 = ntasks - ntasks0 ;
//----------------------------------------------------------------------
// assign ntasks0 to the first half
//----------------------------------------------------------------------
// ntasks0 tasks merge L [pL_start...pleft-1] and R [pR_start..pright-1]
// into the result S [pS_start...work0-1].
LG_msort_2b_create_merge_tasks (
L_task, L_len, R_task, R_len, S_task, t0, ntasks0, pS_start,
L_0, L_1, pL_start, pleft,
R_0, R_1, pR_start, pright) ;
//----------------------------------------------------------------------
// assign ntasks1 to the second half
//----------------------------------------------------------------------
// ntasks1 tasks merge L [pleft...pL_end-1] and R [pright...pR_end-1]
// into the result S [pS_start+work0...pS_start+total_work].
int t1 = t0 + ntasks0 ; // first task id of the second set of tasks
int64_t pS_start1 = pS_start + work0 ; // 2nd set starts here in S
LG_msort_2b_create_merge_tasks (
L_task, L_len, R_task, R_len, S_task, t1, ntasks1, pS_start1,
L_0, L_1, pleft, pL_end,
R_0, R_1, pright, pR_end) ;
}
}
//------------------------------------------------------------------------------
// LG_msort_2b_merge: merge two sorted lists via a single thread
//------------------------------------------------------------------------------
// merge Left [0..nleft-1] and Right [0..nright-1] into S [0..nleft+nright-1] */
static void LG_msort_2b_merge
(
int64_t *LG_RESTRICT S_0, // output of length nleft + nright
int64_t *LG_RESTRICT S_1,
const int64_t *LG_RESTRICT Left_0, // left input of length nleft
const int64_t *LG_RESTRICT Left_1,
const int64_t nleft,
const int64_t *LG_RESTRICT Right_0, // right input of length nright
const int64_t *LG_RESTRICT Right_1,
const int64_t nright
)
{
int64_t p, pleft, pright ;
// merge the two inputs, Left and Right, while both inputs exist
for (p = 0, pleft = 0, pright = 0 ; pleft < nleft && pright < nright ; p++)
{
if (LG_lt_2 (Left_0, Left_1, pleft,
Right_0, Right_1, pright))
{
// S [p] = Left [pleft++]
S_0 [p] = Left_0 [pleft] ;
S_1 [p] = Left_1 [pleft] ;
pleft++ ;
}
else
{
// S [p] = Right [pright++]
S_0 [p] = Right_0 [pright] ;
S_1 [p] = Right_1 [pright] ;
pright++ ;
}
}
// either input is exhausted; copy the remaining list into S
if (pleft < nleft)
{
int64_t nremaining = (nleft - pleft) ;
memcpy (S_0 + p, Left_0 + pleft, nremaining * sizeof (int64_t)) ;
memcpy (S_1 + p, Left_1 + pleft, nremaining * sizeof (int64_t)) ;
}
else if (pright < nright)
{
int64_t nremaining = (nright - pright) ;
memcpy (S_0 + p, Right_0 + pright, nremaining * sizeof (int64_t)) ;
memcpy (S_1 + p, Right_1 + pright, nremaining * sizeof (int64_t)) ;
}
}
//------------------------------------------------------------------------------
// LAGraph_Sort2: parallel mergesort
//------------------------------------------------------------------------------
int LAGraph_Sort2
(
// input/output:
int64_t *A_0, // size n array
int64_t *A_1, // size n array
// input:
const int64_t n,
char *msg
)
{
//--------------------------------------------------------------------------
// check inputs
//--------------------------------------------------------------------------
LG_CLEAR_MSG ;
int64_t *LG_RESTRICT W = NULL ;
LG_ASSERT (A_0 != NULL, GrB_NULL_POINTER) ;
LG_ASSERT (A_1 != NULL, GrB_NULL_POINTER) ;
//--------------------------------------------------------------------------
// handle small problems with a single thread
//--------------------------------------------------------------------------
int nthreads = LG_nthreads_outer * LG_nthreads_inner ; // # threads to use
if (nthreads <= 1 || n <= LG_BASECASE)
{
// sequential quicksort
LG_qsort_2 (A_0, A_1, n) ;
return (GrB_SUCCESS) ;
}
//--------------------------------------------------------------------------
// determine # of tasks
//--------------------------------------------------------------------------
// determine the number of levels to create, which must always be an
// even number. The # of levels is chosen to ensure that the # of leaves
// of the task tree is between 4*nthreads and 16*nthreads.
// 2 to 4 threads: 4 levels, 16 qsort leaves
// 5 to 16 threads: 6 levels, 64 qsort leaves
// 17 to 64 threads: 8 levels, 256 qsort leaves
// 65 to 256 threads: 10 levels, 1024 qsort leaves
// 256 to 1024 threads: 12 levels, 4096 qsort leaves
// ...
int k = (int) (2 + 2 * ceil (log2 ((double) nthreads) / 2)) ;
int ntasks = 1 << k ;
//--------------------------------------------------------------------------
// allocate workspace
//--------------------------------------------------------------------------
LG_TRY (LAGraph_Malloc ((void **) &W, 2*n + 6*ntasks + 1, sizeof (int64_t),
msg)) ;
int64_t *T = W ;
int64_t *LG_RESTRICT W_0 = T ; T += n ;
int64_t *LG_RESTRICT W_1 = T ; T += n ;
int64_t *LG_RESTRICT L_task = T ; T += ntasks ;
int64_t *LG_RESTRICT L_len = T ; T += ntasks ;
int64_t *LG_RESTRICT R_task = T ; T += ntasks ;
int64_t *LG_RESTRICT R_len = T ; T += ntasks ;
int64_t *LG_RESTRICT S_task = T ; T += ntasks ;
int64_t *LG_RESTRICT Slice = T ; T += (ntasks+1) ;
//--------------------------------------------------------------------------
// partition and sort the leaves
//--------------------------------------------------------------------------
LG_eslice (Slice, n, ntasks) ;
int tid ;
#pragma omp parallel for num_threads(nthreads) schedule(dynamic,1)
for (tid = 0 ; tid < ntasks ; tid++)
{
int64_t leaf = Slice [tid] ;
int64_t leafsize = Slice [tid+1] - leaf ;
LG_qsort_2 (A_0 + leaf, A_1 + leaf, leafsize) ;
}
//--------------------------------------------------------------------------
// merge each level
//--------------------------------------------------------------------------
int nt = 1 ;
for ( ; k >= 2 ; k -= 2)
{
//----------------------------------------------------------------------
// merge level k into level k-1, from A into W
//----------------------------------------------------------------------
// FUTURE: skip k and k-1 for each group of 4 sublists of A if they are
// already sorted with respect to each other.
// this could be done in parallel if ntasks was large
for (int tid = 0 ; tid < ntasks ; tid += 2*nt)
{
// create 2*nt tasks to merge two A sublists into one W sublist
LG_msort_2b_create_merge_tasks (
L_task, L_len, R_task, R_len, S_task, tid, 2*nt, Slice [tid],
A_0, A_1, Slice [tid], Slice [tid+nt],
A_0, A_1, Slice [tid+nt], Slice [tid+2*nt]) ;
}
#pragma omp parallel for num_threads(nthreads) schedule(dynamic,1)
for (tid = 0 ; tid < ntasks ; tid++)
{
// merge A [pL...pL+nL-1] and A [pR...pR+nR-1] into W [pS..]
int64_t pL = L_task [tid], nL = L_len [tid] ;
int64_t pR = R_task [tid], nR = R_len [tid] ;
int64_t pS = S_task [tid] ;
LG_msort_2b_merge (
W_0 + pS, W_1 + pS,
A_0 + pL, A_1 + pL, nL,
A_0 + pR, A_1 + pR, nR) ;
}
nt = 2*nt ;
//----------------------------------------------------------------------
// merge level k-1 into level k-2, from W into A
//----------------------------------------------------------------------
// this could be done in parallel if ntasks was large
for (int tid = 0 ; tid < ntasks ; tid += 2*nt)
{
// create 2*nt tasks to merge two W sublists into one A sublist
LG_msort_2b_create_merge_tasks (
L_task, L_len, R_task, R_len, S_task, tid, 2*nt, Slice [tid],
W_0, W_1, Slice [tid], Slice [tid+nt],
W_0, W_1, Slice [tid+nt], Slice [tid+2*nt]) ;
}
#pragma omp parallel for num_threads(nthreads) schedule(dynamic,1)
for (tid = 0 ; tid < ntasks ; tid++)
{
// merge A [pL...pL+nL-1] and A [pR...pR+nR-1] into W [pS..]
int64_t pL = L_task [tid], nL = L_len [tid] ;
int64_t pR = R_task [tid], nR = R_len [tid] ;
int64_t pS = S_task [tid] ;
LG_msort_2b_merge (
A_0 + pS, A_1 + pS,
W_0 + pL, W_1 + pL, nL,
W_0 + pR, W_1 + pR, nR) ;
}
nt = 2*nt ;
}
//--------------------------------------------------------------------------
// free workspace and return result
//--------------------------------------------------------------------------
LG_FREE_ALL ;
return (GrB_SUCCESS) ;
}
|
i3lock-fancy-rapid.c | /*
* BSD 3-Clause License
*
* Copyright (c) 2018-2019, The i3lock-fancy-rapid authors
* 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 copyright holder 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 HOLDER 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.
*/
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <unistd.h>
#include <sys/wait.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <omp.h>
#include <string.h>
void box_blur_h(unsigned char *dest, unsigned char *src, int height, int width,
int radius)
{
double coeff = 1.0 / (radius * 2 + 1);
#pragma omp parallel for
for (int i = 0; i < height; ++i) {
int iwidth = i * width;
double r_acc = 0.0;
double g_acc = 0.0;
double b_acc = 0.0;
for (int j = -radius; j < width; ++j) {
if (j - radius - 1 >= 0) {
int index = (iwidth + j - radius - 1) * 3;
r_acc -= coeff * src[index];
g_acc -= coeff * src[index + 1];
b_acc -= coeff * src[index + 2];
}
if (j + radius < width) {
int index = (iwidth + j + radius) * 3;
r_acc += coeff * src[index];
g_acc += coeff * src[index + 1];
b_acc += coeff * src[index + 2];
}
if (j < 0)
continue;
int index = (iwidth + j) * 3;
dest[index] = r_acc + 0.5;
dest[index + 1] = g_acc + 0.5;
dest[index + 2] = b_acc + 0.5;
}
}
}
static inline void transpose(unsigned char *dest, unsigned char *src, int height, int width) {
for (int i = 0; i < height; ++i) {
int iwidth = i * width;
for (int j = 0; j < width; ++j) {
int nIndex = 3 * (iwidth + j);
int tIndex = 3 * (j * height + i);
dest[tIndex] = src[nIndex];
dest[tIndex+1] = src[nIndex+1];
dest[tIndex+2] = src[nIndex+2];
}
}
}
void box_blur(unsigned char *dest, unsigned char *src, int height, int width,
int radius, int times)
{
for (int i = 0; i < times; ++i) {
box_blur_h(dest, src, height, width, radius);
memcpy(src, dest, height * width * 3);
}
transpose(src, dest, height, width);
for (int i = 0; i < times; ++i) {
box_blur_h(dest, src, width, height, radius);
memcpy(src, dest, height * width * 3);
}
transpose(dest, src, width, height);
}
void pixelate(unsigned char *dest, unsigned char *src, int height,
int width, int radius)
{
radius = radius * 2 + 1;
#pragma omp parallel for
for (int i = 0; i < height; i += radius) {
for (int j = 0; j < width; j += radius) {
int amount = 0;
int r = 0;
int g = 0;
int b = 0;
for (int k = 0; k < radius; ++k) {
if (i + k >= height)
break;
for (int l = 0; l < radius; ++l) {
if (j + l >= width)
break;
++amount;
int index = ((i + k) * width + (j + l)) * 3;
r += src[index];
g += src[index + 1];
b += src[index + 2];
}
}
r /= amount;
g /= amount;
b /= amount;
for (int k = 0; k < radius; ++k) {
if (i + k >= height)
break;
for (int l = 0; l < radius; ++l) {
if (j + l >= width)
break;
int index = ((i + k) * width + (j + l)) * 3;
dest[index] = r;
dest[index + 1] = g;
dest[index + 2] = b;
}
}
}
}
}
int main(int argc, char *argv[])
{
if (argc < 3) {
fprintf(stderr,
"usage: %s radius times [OPTIONS]\n"
"pass \"pixel\" for times to get pixelation\n",
argv[0]);
exit(EXIT_FAILURE);
}
Display *display = XOpenDisplay(NULL);
Window root = XDefaultRootWindow(display);
XWindowAttributes gwa;
XGetWindowAttributes(display, root, &gwa);
int height = gwa.height;
int width = gwa.width;
unsigned char *preblur = malloc(height * width * 3);
XImage *image = XGetImage(display, root, 0, 0, width, height, AllPlanes,
ZPixmap);
for (int i = 0; i < height; ++i) {
int iwidth = i * width;
for (int j = 0; j < width; ++j) {
int index = (iwidth + j) * 3;
unsigned long pixel = XGetPixel(image, j, i);
preblur[index] = (pixel & image->red_mask) >> 16;
preblur[index + 1] = (pixel & image->green_mask) >> 8;
preblur[index + 2] = pixel & image->blue_mask;
}
}
XDestroyImage(image);
XDestroyWindow(display, root);
XCloseDisplay(display);
unsigned char *postblur = malloc(height * width * 3);
int radius = atoi(argv[1]);
if (radius < 0) {
fprintf(stderr, "Radius has to be non-negative!\n");
exit(EXIT_FAILURE);
}
if (strcmp(argv[2], "pixel") == 0) {
pixelate(postblur, preblur, height, width, radius);
} else {
int times = atoi(argv[2]);
if (times < 0) {
fprintf(stderr, "Times has to be non-negative!\n");
exit(EXIT_FAILURE);
}
box_blur(postblur, preblur, height, width, radius, times);
}
free(preblur);
int fds[2];
pipe(fds);
if (fork()) {
write(fds[1], postblur, height * width * 3);
int status;
wait(&status);
exit(WEXITSTATUS(status));
} else {
dup2(fds[0], STDIN_FILENO);
char fmt[32];
snprintf(fmt, sizeof(fmt), "%ix%i:rgb", width, height);
char *new_argv[argc + 3];
new_argv[0] = "i3lock";
new_argv[1] = "-i";
new_argv[2] = "/dev/stdin";
new_argv[3] = "--raw";
new_argv[4] = fmt;
for (int i = 3; i < argc; ++i)
new_argv[i + 2] = argv[i];
new_argv[argc + 2] = NULL;
execvp(new_argv[0], new_argv);
exit(EXIT_FAILURE);
}
}
|
rowsums.c | // Jacobi 3D skeleton program
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "timing.h"
int main(int argc, char** argv) {
double wct_start,wct_end,cput_start,cput_end,runtime,r;
int iter,nrows,ncols,i,j,k,n, size;
double *f1, *f2, *rsum, *rsumtrue;
iter=50;
double mintime = 4.0;
if (argc != 3 && argc != 4) {
printf("Usage: %s <nrows> <ncols> [mintime]\n",argv[0]);
exit(1);
}
if (argc == 4) {
mintime = atof(argv[3]);
}
nrows = atoi(argv[1]);
ncols = atoi(argv[2]);
size = nrows * ncols;
f1 = malloc((size_t)size*sizeof(double));
rsum = malloc((size_t)nrows*sizeof(double));
rsumtrue = malloc((size_t)nrows*sizeof(double));
#pragma omp parallel for schedule(static)
for (i = 0; i < size; i++) {
f1[i] = sin( (double) i * i);
}
for (i = 0; i < nrows; i++) {
rsumtrue[i] = 0.0;
}
// for verification:
for (i = 0; i < ncols; i++) {
for (j = 0; j < nrows; j++) {
rsumtrue[j] += f1[i*nrows + j];
}
}
// time measurement
timing(&wct_start, &cput_start);
double my_rsum[nrows];
while (1) {
timing(&wct_start, &cput_start);
for (j = 0; j < iter; j++) {
for (i = 0; i < nrows; i++) {
rsum[i] = 0.0;
}
#pragma omp parallel private(my_rsum, i, j) shared(rsum)
{
for (i = 0; i < nrows; i++) {
my_rsum[i] = 0.0;
}
#pragma omp for schedule(static)
for (i = 0; i < ncols; i++) {
k = i * nrows;
for (j = 0; j < nrows; j++, k++) {
my_rsum[j] += f1[k];
}
}
#pragma omp critical
for (i = 0; i < nrows; i++) {
rsum[i] += my_rsum[i];
}
} // end of #pragma omp parallel
}
timing(&wct_end, &cput_end);
// making sure mintime was spent, otherwise restart with 2*iter
if (wct_end - wct_start > mintime) {
break;
}
iter = iter * 2;
}
timing(&wct_end, &cput_end);
runtime = wct_end-wct_start;
printf("size:\t%d\ttime/iter:\t%lf\tGFLOP/s:\t%lf\n", size, runtime/iter, ((double)iter) * size * 1e-9 / runtime);
// verifying correctness of the computation
for (i = 0; i < nrows; i++) {
if (abs(rsum[i] - rsumtrue[i]) > 1e-5) {
printf("Problem in %d-th row value\n", i);
exit(1);
}
}
return 0;
}
|
requires-3.c | #pragma omp requires atomic_default_mem_order(acquire) /* { dg-error "expected 'seq_cst', 'relaxed' or 'acq_rel'" } */
#pragma omp requires atomic_default_mem_order(release) /* { dg-error "expected 'seq_cst', 'relaxed' or 'acq_rel'" } */
#pragma omp requires atomic_default_mem_order(foobar) /* { dg-error "expected 'seq_cst', 'relaxed' or 'acq_rel'" } */
|
convolution_3x3_pack8to1_int8.h | // Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2022 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// 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.
static void conv3x3s1_winograd42_transform_kernel_pack8to1_int8_sse(const Mat& kernel, Mat& kernel_tm_pack8to1, int inch, int outch, const Option& opt)
{
#if NCNN_AVX512VNNI && __AVX512F__ && !__AVX512VNNI__
if (ncnn::cpu_support_x86_avx512_vnni())
{
extern void conv3x3s1_winograd42_transform_kernel_pack8to1_int8_sse_avx512vnni(const Mat& kernel, Mat& kernel_tm_pack8to1, int inch, int outch, const Option& opt);
conv3x3s1_winograd42_transform_kernel_pack8to1_int8_sse_avx512vnni(kernel, kernel_tm_pack8to1, inch, outch, opt);
return;
}
#endif
#if NCNN_AVXVNNI && __AVX2__ && !__AVXVNNI__
if (ncnn::cpu_support_x86_avx_vnni())
{
extern void conv3x3s1_winograd42_transform_kernel_pack8to1_int8_sse_avxvnni(const Mat& kernel, Mat& kernel_tm_pack8to1, int inch, int outch, const Option& opt);
conv3x3s1_winograd42_transform_kernel_pack8to1_int8_sse_avxvnni(kernel, kernel_tm_pack8to1, inch, outch, opt);
return;
}
#endif
#if NCNN_AVX2 && __AVX__ && !__AVX2__
if (ncnn::cpu_support_x86_avx2())
{
extern void conv3x3s1_winograd42_transform_kernel_pack8to1_int8_sse_avx2(const Mat& kernel, Mat& kernel_tm_pack8to1, int inch, int outch, const Option& opt);
conv3x3s1_winograd42_transform_kernel_pack8to1_int8_sse_avx2(kernel, kernel_tm_pack8to1, inch, outch, opt);
return;
}
#endif
#if NCNN_XOP && __SSE2__ && !__XOP__
if (ncnn::cpu_support_x86_xop())
{
extern void conv3x3s1_winograd42_transform_kernel_pack8to1_int8_sse_xop(const Mat& kernel, Mat& kernel_tm_pack8to1, int inch, int outch, const Option& opt);
conv3x3s1_winograd42_transform_kernel_pack8to1_int8_sse_xop(kernel, kernel_tm_pack8to1, inch, outch, opt);
return;
}
#endif
// winograd42 transform kernel
Mat kernel_tm(6 * 6, inch, outch, (size_t)2u);
const short ktm[6][3] = {
{6, 0, 0},
{-4, -4, -4},
{-4, 4, -4},
{1, 2, 4},
{1, -2, 4},
{0, 0, 6}
};
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = 0; p < outch; p++)
{
for (int q = 0; q < inch; q++)
{
const signed char* kernel0 = (const signed char*)kernel + p * inch * 9 + q * 9;
short* kernel_tm0 = kernel_tm.channel(p).row<short>(q);
// transform kernel
const signed char* k0 = kernel0;
const signed char* k1 = kernel0 + 3;
const signed char* k2 = kernel0 + 6;
// h
short tmp[6][3];
for (int i = 0; i < 6; i++)
{
tmp[i][0] = k0[0] * ktm[i][0] + k0[1] * ktm[i][1] + k0[2] * ktm[i][2];
tmp[i][1] = k1[0] * ktm[i][0] + k1[1] * ktm[i][1] + k1[2] * ktm[i][2];
tmp[i][2] = k2[0] * ktm[i][0] + k2[1] * ktm[i][1] + k2[2] * ktm[i][2];
}
// U
for (int j = 0; j < 6; j++)
{
short* tmpp = &tmp[j][0];
for (int i = 0; i < 6; i++)
{
kernel_tm0[j * 6 + i] = tmpp[0] * ktm[i][0] + tmpp[1] * ktm[i][1] + tmpp[2] * ktm[i][2];
}
}
}
}
// interleave
// src = 36-inch-outch
// dst = 4b-8a-inch/8a-36-outch/4b
kernel_tm_pack8to1.create(8 * inch / 8, 36, outch / 4 + outch % 4, (size_t)2u * 4, 4);
int p = 0;
for (; p + 3 < outch; p += 4)
{
const Mat k0 = kernel_tm.channel(p);
const Mat k1 = kernel_tm.channel(p + 1);
const Mat k2 = kernel_tm.channel(p + 2);
const Mat k3 = kernel_tm.channel(p + 3);
Mat g0 = kernel_tm_pack8to1.channel(p / 4);
for (int k = 0; k < 36; k++)
{
short* g00 = g0.row<short>(k);
for (int q = 0; q + 7 < inch; q += 8)
{
#if __AVXVNNI__ || __AVX512VNNI__ || __XOP__
for (int i = 0; i < 4; i++)
{
const short* k00 = k0.row<const short>(q + i * 2);
const short* k10 = k1.row<const short>(q + i * 2);
const short* k20 = k2.row<const short>(q + i * 2);
const short* k30 = k3.row<const short>(q + i * 2);
const short* k01 = k0.row<const short>(q + i * 2 + 1);
const short* k11 = k1.row<const short>(q + i * 2 + 1);
const short* k21 = k2.row<const short>(q + i * 2 + 1);
const short* k31 = k3.row<const short>(q + i * 2 + 1);
g00[0] = k00[k];
g00[1] = k01[k];
g00[2] = k10[k];
g00[3] = k11[k];
g00[4] = k20[k];
g00[5] = k21[k];
g00[6] = k30[k];
g00[7] = k31[k];
g00 += 8;
}
#else
for (int i = 0; i < 8; i++)
{
g00[0] = k0.row<const short>(q + i)[k];
g00[1] = k1.row<const short>(q + i)[k];
g00[2] = k2.row<const short>(q + i)[k];
g00[3] = k3.row<const short>(q + i)[k];
g00 += 4;
}
#endif
}
}
}
for (; p < outch; p++)
{
const Mat k0 = kernel_tm.channel(p);
Mat g0 = kernel_tm_pack8to1.channel(p / 4 + p % 4);
for (int k = 0; k < 36; k++)
{
short* g00 = g0.row<short>(k);
for (int q = 0; q + 7 < inch; q += 8)
{
for (int i = 0; i < 8; i++)
{
g00[0] = k0.row<const short>(q + i)[k];
g00 += 1;
}
}
}
}
}
static void conv3x3s1_winograd42_pack8to1_int8_sse(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel_tm, const Option& opt)
{
#if NCNN_AVX512VNNI && __AVX512F__ && !__AVX512VNNI__
if (ncnn::cpu_support_x86_avx512_vnni())
{
extern void conv3x3s1_winograd42_pack8to1_int8_sse_avx512vnni(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Option& opt);
conv3x3s1_winograd42_pack8to1_int8_sse_avx512vnni(bottom_blob, top_blob, kernel_tm, opt);
return;
}
#endif
#if NCNN_AVXVNNI && __AVX2__ && !__AVXVNNI__
if (ncnn::cpu_support_x86_avx_vnni())
{
extern void conv3x3s1_winograd42_pack8to1_int8_sse_avxvnni(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Option& opt);
conv3x3s1_winograd42_pack8to1_int8_sse_avxvnni(bottom_blob, top_blob, kernel_tm, opt);
return;
}
#endif
#if NCNN_AVX2 && __AVX__ && !__AVX2__
if (ncnn::cpu_support_x86_avx2())
{
extern void conv3x3s1_winograd42_pack8to1_int8_sse_avx2(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Option& opt);
conv3x3s1_winograd42_pack8to1_int8_sse_avx2(bottom_blob, top_blob, kernel_tm, opt);
return;
}
#endif
#if NCNN_XOP && __SSE2__ && !__XOP__
if (ncnn::cpu_support_x86_xop())
{
extern void conv3x3s1_winograd42_pack8to1_int8_sse_xop(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Option& opt);
conv3x3s1_winograd42_pack8to1_int8_sse_xop(bottom_blob, top_blob, kernel_tm, opt);
return;
}
#endif
int w = bottom_blob.w;
int h = bottom_blob.h;
int inch = bottom_blob.c;
// size_t elemsize = bottom_blob.elemsize;
int elempack = bottom_blob.elempack;
int outw = top_blob.w;
int outh = top_blob.h;
int outch = top_blob.c;
// pad to 4n+2
Mat bottom_blob_bordered = bottom_blob;
outw = (outw + 3) / 4 * 4;
outh = (outh + 3) / 4 * 4;
w = outw + 2;
h = outh + 2;
copy_make_border(bottom_blob, bottom_blob_bordered, 0, h - bottom_blob.h, 0, w - bottom_blob.w, BORDER_CONSTANT, 0.f, opt);
// BEGIN transform input
Mat bottom_blob_tm;
{
int w_tm = outw / 4 * 6;
int h_tm = outh / 4 * 6;
const int tiles = w_tm / 6 * h_tm / 6;
bottom_blob_tm.create(tiles, 36, inch, 2u * elempack, elempack, opt.workspace_allocator);
// const float itm[4][4] = {
// {4.0f, 0.0f, -5.0f, 0.0f, 1.0f, 0.0f},
// {0.0f,-4.0f, -4.0f, 1.0f, 1.0f, 0.0f},
// {0.0f, 4.0f, -4.0f,-1.0f, 1.0f, 0.0f},
// {0.0f,-2.0f, -1.0f, 2.0f, 1.0f, 0.0f},
// {0.0f, 2.0f, -1.0f,-2.0f, 1.0f, 0.0f},
// {0.0f, 4.0f, 0.0f,-5.0f, 0.0f, 1.0f}
// };
// 0 = 4 * r00 - 5 * r02 + r04
// 1 = -4 * (r01 + r02) + r04 + r03
// 2 = 4 * (r01 - r02) + r04 - r03
// 3 = -2 * (r01 - r03) + r04 - r02
// 4 = 2 * (r01 - r03) + r04 - r02
// 5 = 4 * r01 - 5 * r03 + r05
#pragma omp parallel for num_threads(opt.num_threads)
for (int q = 0; q < inch; q++)
{
const Mat img0 = bottom_blob_bordered.channel(q);
Mat img0_tm = bottom_blob_tm.channel(q);
short tmp[6][6][8];
// tile
for (int i = 0; i < h_tm / 6; i++)
{
for (int j = 0; j < w_tm / 6; j++)
{
const signed char* r0 = img0.row<const signed char>(i * 4) + (j * 4) * 8;
for (int m = 0; m < 6; m++)
{
// TODO use _mm_cvtepi8_epi16 on sse4.1
__m128i _r00_01 = _mm_loadu_si128((const __m128i*)r0);
__m128i _r02_03 = _mm_loadu_si128((const __m128i*)(r0 + 16));
__m128i _r04_05 = _mm_loadu_si128((const __m128i*)(r0 + 32));
__m128i _extr0001 = _mm_cmpgt_epi8(_mm_setzero_si128(), _r00_01);
__m128i _extr0203 = _mm_cmpgt_epi8(_mm_setzero_si128(), _r02_03);
__m128i _extr0405 = _mm_cmpgt_epi8(_mm_setzero_si128(), _r04_05);
__m128i _r00 = _mm_unpacklo_epi8(_r00_01, _extr0001);
__m128i _r01 = _mm_unpackhi_epi8(_r00_01, _extr0001);
__m128i _r02 = _mm_unpacklo_epi8(_r02_03, _extr0203);
__m128i _r03 = _mm_unpackhi_epi8(_r02_03, _extr0203);
__m128i _r04 = _mm_unpacklo_epi8(_r04_05, _extr0405);
__m128i _r05 = _mm_unpackhi_epi8(_r04_05, _extr0405);
__m128i _v5 = _mm_set1_epi16(5);
__m128i _tmp0m = _mm_sub_epi16(_mm_add_epi16(_mm_slli_epi16(_r00, 2), _r04), _mm_mullo_epi16(_r02, _v5));
__m128i _tmp1m = _mm_sub_epi16(_mm_add_epi16(_r04, _r03), _mm_slli_epi16(_mm_add_epi16(_r01, _r02), 2));
__m128i _tmp2m = _mm_add_epi16(_mm_sub_epi16(_r04, _r03), _mm_slli_epi16(_mm_sub_epi16(_r01, _r02), 2));
__m128i _tmp3m = _mm_sub_epi16(_mm_sub_epi16(_r04, _r02), _mm_slli_epi16(_mm_sub_epi16(_r01, _r03), 1));
__m128i _tmp4m = _mm_add_epi16(_mm_sub_epi16(_r04, _r02), _mm_slli_epi16(_mm_sub_epi16(_r01, _r03), 1));
__m128i _tmp5m = _mm_sub_epi16(_mm_add_epi16(_mm_slli_epi16(_r01, 2), _r05), _mm_mullo_epi16(_r03, _v5));
_mm_storeu_si128((__m128i*)tmp[0][m], _tmp0m);
_mm_storeu_si128((__m128i*)tmp[1][m], _tmp1m);
_mm_storeu_si128((__m128i*)tmp[2][m], _tmp2m);
_mm_storeu_si128((__m128i*)tmp[3][m], _tmp3m);
_mm_storeu_si128((__m128i*)tmp[4][m], _tmp4m);
_mm_storeu_si128((__m128i*)tmp[5][m], _tmp5m);
r0 += w * 8;
}
short* r0_tm_0 = (short*)img0_tm + (i * w_tm / 6 + j) * 8;
short* r0_tm_1 = r0_tm_0 + tiles * 8;
short* r0_tm_2 = r0_tm_0 + tiles * 16;
short* r0_tm_3 = r0_tm_0 + tiles * 24;
short* r0_tm_4 = r0_tm_0 + tiles * 32;
short* r0_tm_5 = r0_tm_0 + tiles * 40;
for (int m = 0; m < 6; m++)
{
__m128i _tmp00 = _mm_loadu_si128((const __m128i*)tmp[m][0]);
__m128i _tmp01 = _mm_loadu_si128((const __m128i*)tmp[m][1]);
__m128i _tmp02 = _mm_loadu_si128((const __m128i*)tmp[m][2]);
__m128i _tmp03 = _mm_loadu_si128((const __m128i*)tmp[m][3]);
__m128i _tmp04 = _mm_loadu_si128((const __m128i*)tmp[m][4]);
__m128i _tmp05 = _mm_loadu_si128((const __m128i*)tmp[m][5]);
__m128i _v5 = _mm_set1_epi16(5);
__m128i _r0tm0 = _mm_sub_epi16(_mm_add_epi16(_mm_slli_epi16(_tmp00, 2), _tmp04), _mm_mullo_epi16(_tmp02, _v5));
__m128i _r0tm1 = _mm_sub_epi16(_mm_add_epi16(_tmp04, _tmp03), _mm_slli_epi16(_mm_add_epi16(_tmp01, _tmp02), 2));
__m128i _r0tm2 = _mm_add_epi16(_mm_sub_epi16(_tmp04, _tmp03), _mm_slli_epi16(_mm_sub_epi16(_tmp01, _tmp02), 2));
__m128i _r0tm3 = _mm_sub_epi16(_mm_sub_epi16(_tmp04, _tmp02), _mm_slli_epi16(_mm_sub_epi16(_tmp01, _tmp03), 1));
__m128i _r0tm4 = _mm_add_epi16(_mm_sub_epi16(_tmp04, _tmp02), _mm_slli_epi16(_mm_sub_epi16(_tmp01, _tmp03), 1));
__m128i _r0tm5 = _mm_sub_epi16(_mm_add_epi16(_mm_slli_epi16(_tmp01, 2), _tmp05), _mm_mullo_epi16(_tmp03, _v5));
_mm_storeu_si128((__m128i*)r0_tm_0, _r0tm0);
_mm_storeu_si128((__m128i*)r0_tm_1, _r0tm1);
_mm_storeu_si128((__m128i*)r0_tm_2, _r0tm2);
_mm_storeu_si128((__m128i*)r0_tm_3, _r0tm3);
_mm_storeu_si128((__m128i*)r0_tm_4, _r0tm4);
_mm_storeu_si128((__m128i*)r0_tm_5, _r0tm5);
r0_tm_0 += tiles * 48;
r0_tm_1 += tiles * 48;
r0_tm_2 += tiles * 48;
r0_tm_3 += tiles * 48;
r0_tm_4 += tiles * 48;
r0_tm_5 += tiles * 48;
}
}
}
}
}
bottom_blob_bordered = Mat();
// END transform input
// BEGIN dot
Mat top_blob_tm;
{
int w_tm = outw / 4 * 6;
int h_tm = outh / 4 * 6;
const int tiles = h_tm / 6 * w_tm / 6;
// permute
// bottom_blob_tm.create(tiles, 36, inch, elemsize, elempack, opt.workspace_allocator);
Mat bottom_blob_tm2;
#if __AVX2__
if (tiles >= 4)
bottom_blob_tm2.create(4 * inch, tiles / 4 + (tiles % 4) / 2 + tiles % 2, 36, 2u * elempack, elempack, opt.workspace_allocator);
else if (tiles >= 2)
bottom_blob_tm2.create(2 * inch, tiles / 2 + tiles % 2, 36, 2u * elempack, elempack, opt.workspace_allocator);
else // if (tiles >= 1)
bottom_blob_tm2.create(1 * inch, tiles, 36, 2u * elempack, elempack, opt.workspace_allocator);
#else
if (tiles >= 2)
bottom_blob_tm2.create(2 * inch, tiles / 2 + tiles % 2, 36, 2u * elempack, elempack, opt.workspace_allocator);
else // if (tiles >= 1)
bottom_blob_tm2.create(1 * inch, tiles, 36, 2u * elempack, elempack, opt.workspace_allocator);
#endif
#pragma omp parallel for num_threads(opt.num_threads)
for (int r = 0; r < 36; r++)
{
Mat tm2 = bottom_blob_tm2.channel(r);
// tile
int i = 0;
#if __AVX2__
for (; i + 3 < tiles; i += 4)
{
short* tmpptr = tm2.row<short>(i / 4);
const short* r0 = bottom_blob_tm;
r0 += (r * tiles + i) * 8;
for (int q = 0; q < inch; q++)
{
__m256i _r0 = _mm256_loadu_si256((const __m256i*)r0);
__m256i _r1 = _mm256_loadu_si256((const __m256i*)(r0 + 16));
_mm256_storeu_si256((__m256i*)tmpptr, _r0);
_mm256_storeu_si256((__m256i*)(tmpptr + 16), _r1);
r0 += bottom_blob_tm.cstep * 8;
tmpptr += 32;
}
}
#endif
for (; i + 1 < tiles; i += 2)
{
#if __AVX2__
short* tmpptr = tm2.row<short>(i / 4 + (i % 4) / 2);
#else
short* tmpptr = tm2.row<short>(i / 2);
#endif
const short* r0 = bottom_blob_tm;
r0 += (r * tiles + i) * 8;
for (int q = 0; q < inch; q++)
{
__m128i _r0 = _mm_loadu_si128((const __m128i*)r0);
__m128i _r1 = _mm_loadu_si128((const __m128i*)(r0 + 8));
_mm_storeu_si128((__m128i*)tmpptr, _r0);
_mm_storeu_si128((__m128i*)(tmpptr + 8), _r1);
r0 += bottom_blob_tm.cstep * 8;
tmpptr += 16;
}
}
for (; i < tiles; i++)
{
#if __AVX2__
short* tmpptr = tm2.row<short>(i / 4 + (i % 4) / 2 + i % 2);
#else
short* tmpptr = tm2.row<short>(i / 2 + i % 2);
#endif
const short* r0 = bottom_blob_tm;
r0 += (r * tiles + i) * 8;
for (int q = 0; q < inch; q++)
{
__m128i _r0 = _mm_loadu_si128((const __m128i*)r0);
_mm_storeu_si128((__m128i*)tmpptr, _r0);
r0 += bottom_blob_tm.cstep * 8;
tmpptr += 8;
}
}
}
bottom_blob_tm = Mat();
// permute end
top_blob_tm.create(tiles, 36, outch, 4u, 1, opt.workspace_allocator);
int nn_outch = 0;
int remain_outch_start = 0;
nn_outch = outch >> 2;
#pragma omp parallel for num_threads(opt.num_threads)
for (int pp = 0; pp < nn_outch; pp++)
{
int p = pp * 4;
int* output0_tm = top_blob_tm.channel(p);
int* output1_tm = top_blob_tm.channel(p + 1);
int* output2_tm = top_blob_tm.channel(p + 2);
int* output3_tm = top_blob_tm.channel(p + 3);
const Mat kernel0_tm = kernel_tm.channel(p / 4);
for (int r = 0; r < 36; r++)
{
const Mat bb2 = bottom_blob_tm2.channel(r);
int i = 0;
#if __AVX2__
for (; i + 3 < tiles; i += 4)
{
const short* r0 = bb2.row<const short>(i / 4);
const short* k0 = kernel0_tm.row<const short>(r);
int nn = inch; // inch always > 0
__m256i _sum0_1 = _mm256_setzero_si256();
__m256i _sum2_3 = _mm256_setzero_si256();
__m256i _sum4_5 = _mm256_setzero_si256();
__m256i _sum6_7 = _mm256_setzero_si256();
for (int j = 0; j < nn; j++)
{
// 0 1 2 3 4 5 6 7 8 9 a b c d e f
__m256i _val0 = _mm256_loadu_si256((const __m256i*)r0);
__m256i _w01 = _mm256_loadu_si256((const __m256i*)k0);
__m256i _w23 = _mm256_loadu_si256((const __m256i*)(k0 + 16));
#if __AVXVNNI__ || __AVX512VNNI__
__m256i _val0_0123 = _mm256_permutevar8x32_epi32(_val0, _mm256_set_epi32(1, 1, 1, 1, 0, 0, 0, 0));
__m256i _val0_4567 = _mm256_permutevar8x32_epi32(_val0, _mm256_set_epi32(3, 3, 3, 3, 2, 2, 2, 2));
__m256i _val0_89ab = _mm256_permutevar8x32_epi32(_val0, _mm256_set_epi32(5, 5, 5, 5, 4, 4, 4, 4));
__m256i _val0_cdef = _mm256_permutevar8x32_epi32(_val0, _mm256_set_epi32(7, 7, 7, 7, 6, 6, 6, 6));
_sum0_1 = _mm256_dpwssd_epi32(_sum0_1, _w01, _val0_0123);
_sum2_3 = _mm256_dpwssd_epi32(_sum2_3, _w01, _val0_89ab);
_sum0_1 = _mm256_dpwssd_epi32(_sum0_1, _w23, _val0_4567);
_sum2_3 = _mm256_dpwssd_epi32(_sum2_3, _w23, _val0_cdef);
#else
// 0 0 1 1 2 2 3 3 8 8 9 9 a a b b
// 4 4 5 5 6 6 7 7 c c d d e e f f
__m256i _val0_0123_89ab = _mm256_unpacklo_epi16(_val0, _val0);
__m256i _val0_4567_cdef = _mm256_unpackhi_epi16(_val0, _val0);
__m256i _val0_0123 = _mm256_permutevar8x32_epi32(_val0_0123_89ab, _mm256_set_epi32(3, 3, 2, 2, 1, 1, 0, 0));
__m256i _val0_4567 = _mm256_permutevar8x32_epi32(_val0_4567_cdef, _mm256_set_epi32(3, 3, 2, 2, 1, 1, 0, 0));
__m256i _val0_89ab = _mm256_permutevar8x32_epi32(_val0_0123_89ab, _mm256_set_epi32(7, 7, 6, 6, 5, 5, 4, 4));
__m256i _val0_cdef = _mm256_permutevar8x32_epi32(_val0_4567_cdef, _mm256_set_epi32(7, 7, 6, 6, 5, 5, 4, 4));
__m256i _sl00_01 = _mm256_mullo_epi16(_w01, _val0_0123);
__m256i _sh00_01 = _mm256_mulhi_epi16(_w01, _val0_0123);
__m256i _sl10_11 = _mm256_mullo_epi16(_w01, _val0_89ab);
__m256i _sh10_11 = _mm256_mulhi_epi16(_w01, _val0_89ab);
__m256i _sl02_03 = _mm256_mullo_epi16(_w23, _val0_4567);
__m256i _sh02_03 = _mm256_mulhi_epi16(_w23, _val0_4567);
__m256i _sl12_13 = _mm256_mullo_epi16(_w23, _val0_cdef);
__m256i _sh12_13 = _mm256_mulhi_epi16(_w23, _val0_cdef);
_sum0_1 = _mm256_add_epi32(_sum0_1, _mm256_unpacklo_epi16(_sl00_01, _sh00_01));
_sum2_3 = _mm256_add_epi32(_sum2_3, _mm256_unpacklo_epi16(_sl10_11, _sh10_11));
_sum0_1 = _mm256_add_epi32(_sum0_1, _mm256_unpacklo_epi16(_sl02_03, _sh02_03));
_sum2_3 = _mm256_add_epi32(_sum2_3, _mm256_unpacklo_epi16(_sl12_13, _sh12_13));
_sum0_1 = _mm256_add_epi32(_sum0_1, _mm256_unpackhi_epi16(_sl00_01, _sh00_01));
_sum2_3 = _mm256_add_epi32(_sum2_3, _mm256_unpackhi_epi16(_sl10_11, _sh10_11));
_sum0_1 = _mm256_add_epi32(_sum0_1, _mm256_unpackhi_epi16(_sl02_03, _sh02_03));
_sum2_3 = _mm256_add_epi32(_sum2_3, _mm256_unpackhi_epi16(_sl12_13, _sh12_13));
#endif
__m256i _val1 = _mm256_loadu_si256((const __m256i*)(r0 + 16));
#if __AVXVNNI__ || __AVX512VNNI__
__m256i _val1_0123 = _mm256_permutevar8x32_epi32(_val1, _mm256_set_epi32(1, 1, 1, 1, 0, 0, 0, 0));
__m256i _val1_4567 = _mm256_permutevar8x32_epi32(_val1, _mm256_set_epi32(3, 3, 3, 3, 2, 2, 2, 2));
__m256i _val1_89ab = _mm256_permutevar8x32_epi32(_val1, _mm256_set_epi32(5, 5, 5, 5, 4, 4, 4, 4));
__m256i _val1_cdef = _mm256_permutevar8x32_epi32(_val1, _mm256_set_epi32(7, 7, 7, 7, 6, 6, 6, 6));
_sum4_5 = _mm256_dpwssd_epi32(_sum4_5, _w01, _val1_0123);
_sum6_7 = _mm256_dpwssd_epi32(_sum6_7, _w01, _val1_89ab);
_sum4_5 = _mm256_dpwssd_epi32(_sum4_5, _w23, _val1_4567);
_sum6_7 = _mm256_dpwssd_epi32(_sum6_7, _w23, _val1_cdef);
#else
__m256i _val1_0123_89ab = _mm256_unpacklo_epi16(_val1, _val1);
__m256i _val1_4567_cdef = _mm256_unpackhi_epi16(_val1, _val1);
__m256i _val1_0123 = _mm256_permutevar8x32_epi32(_val1_0123_89ab, _mm256_set_epi32(3, 3, 2, 2, 1, 1, 0, 0));
__m256i _val1_4567 = _mm256_permutevar8x32_epi32(_val1_4567_cdef, _mm256_set_epi32(3, 3, 2, 2, 1, 1, 0, 0));
__m256i _val1_89ab = _mm256_permutevar8x32_epi32(_val1_0123_89ab, _mm256_set_epi32(7, 7, 6, 6, 5, 5, 4, 4));
__m256i _val1_cdef = _mm256_permutevar8x32_epi32(_val1_4567_cdef, _mm256_set_epi32(7, 7, 6, 6, 5, 5, 4, 4));
__m256i _sl04_05 = _mm256_mullo_epi16(_w01, _val1_0123);
__m256i _sh04_05 = _mm256_mulhi_epi16(_w01, _val1_0123);
__m256i _sl14_15 = _mm256_mullo_epi16(_w01, _val1_89ab);
__m256i _sh14_15 = _mm256_mulhi_epi16(_w01, _val1_89ab);
__m256i _sl06_07 = _mm256_mullo_epi16(_w23, _val1_4567);
__m256i _sh06_07 = _mm256_mulhi_epi16(_w23, _val1_4567);
__m256i _sl16_17 = _mm256_mullo_epi16(_w23, _val1_cdef);
__m256i _sh16_17 = _mm256_mulhi_epi16(_w23, _val1_cdef);
_sum4_5 = _mm256_add_epi32(_sum4_5, _mm256_unpacklo_epi16(_sl04_05, _sh04_05));
_sum6_7 = _mm256_add_epi32(_sum6_7, _mm256_unpacklo_epi16(_sl14_15, _sh14_15));
_sum4_5 = _mm256_add_epi32(_sum4_5, _mm256_unpacklo_epi16(_sl06_07, _sh06_07));
_sum6_7 = _mm256_add_epi32(_sum6_7, _mm256_unpacklo_epi16(_sl16_17, _sh16_17));
_sum4_5 = _mm256_add_epi32(_sum4_5, _mm256_unpackhi_epi16(_sl04_05, _sh04_05));
_sum6_7 = _mm256_add_epi32(_sum6_7, _mm256_unpackhi_epi16(_sl14_15, _sh14_15));
_sum4_5 = _mm256_add_epi32(_sum4_5, _mm256_unpackhi_epi16(_sl06_07, _sh06_07));
_sum6_7 = _mm256_add_epi32(_sum6_7, _mm256_unpackhi_epi16(_sl16_17, _sh16_17));
#endif
r0 += 32;
k0 += 32;
}
__m256i _sum0_2 = _mm256_permute2x128_si256(_sum0_1, _sum2_3, _MM_SHUFFLE(0, 2, 0, 0));
__m256i _sum1_3 = _mm256_permute2x128_si256(_sum0_1, _sum2_3, _MM_SHUFFLE(0, 3, 0, 1));
_sum0_2 = _mm256_add_epi32(_sum0_2, _sum1_3);
__m256i _sum4_6 = _mm256_permute2x128_si256(_sum4_5, _sum6_7, _MM_SHUFFLE(0, 2, 0, 0));
__m256i _sum5_7 = _mm256_permute2x128_si256(_sum4_5, _sum6_7, _MM_SHUFFLE(0, 3, 0, 1));
_sum4_6 = _mm256_add_epi32(_sum4_6, _sum5_7);
int sum[16];
_mm256_storeu_si256((__m256i*)sum, _sum0_2);
_mm256_storeu_si256((__m256i*)(sum + 8), _sum4_6);
output0_tm[0] = sum[0];
output1_tm[0] = sum[1];
output2_tm[0] = sum[2];
output3_tm[0] = sum[3];
output0_tm[1] = sum[4];
output1_tm[1] = sum[5];
output2_tm[1] = sum[6];
output3_tm[1] = sum[7];
output0_tm[2] = sum[8];
output1_tm[2] = sum[9];
output2_tm[2] = sum[10];
output3_tm[2] = sum[11];
output0_tm[3] = sum[12];
output1_tm[3] = sum[13];
output2_tm[3] = sum[14];
output3_tm[3] = sum[15];
output0_tm += 4;
output1_tm += 4;
output2_tm += 4;
output3_tm += 4;
}
#endif
for (; i + 1 < tiles; i += 2)
{
#if __AVX2__
const short* r0 = bb2.row<const short>(i / 4 + (i % 4) / 2);
#else
const short* r0 = bb2.row<const short>(i / 2);
#endif
const short* k0 = kernel0_tm.row<const short>(r);
int nn = inch; // inch always > 0
#if __AVX2__
__m256i _sum0_1 = _mm256_setzero_si256();
__m256i _sum2_3 = _mm256_setzero_si256();
#else
__m128i _sum0 = _mm_setzero_si128();
__m128i _sum1 = _mm_setzero_si128();
__m128i _sum2 = _mm_setzero_si128();
__m128i _sum3 = _mm_setzero_si128();
#endif
for (int j = 0; j < nn; j++)
{
#if __AVX2__
// 0 1 2 3 4 5 6 7 8 9 a b c d e f
__m256i _val = _mm256_loadu_si256((const __m256i*)r0);
__m256i _w01 = _mm256_loadu_si256((const __m256i*)k0);
__m256i _w23 = _mm256_loadu_si256((const __m256i*)(k0 + 16));
#if __AVXVNNI__ || __AVX512VNNI__
__m256i _val_0123 = _mm256_permutevar8x32_epi32(_val, _mm256_set_epi32(1, 1, 1, 1, 0, 0, 0, 0));
__m256i _val_4567 = _mm256_permutevar8x32_epi32(_val, _mm256_set_epi32(3, 3, 3, 3, 2, 2, 2, 2));
__m256i _val_89ab = _mm256_permutevar8x32_epi32(_val, _mm256_set_epi32(5, 5, 5, 5, 4, 4, 4, 4));
__m256i _val_cdef = _mm256_permutevar8x32_epi32(_val, _mm256_set_epi32(7, 7, 7, 7, 6, 6, 6, 6));
_sum0_1 = _mm256_dpwssd_epi32(_sum0_1, _w01, _val_0123);
_sum2_3 = _mm256_dpwssd_epi32(_sum2_3, _w01, _val_89ab);
_sum0_1 = _mm256_dpwssd_epi32(_sum0_1, _w23, _val_4567);
_sum2_3 = _mm256_dpwssd_epi32(_sum2_3, _w23, _val_cdef);
#else
__m256i _val_0123_89ab = _mm256_unpacklo_epi16(_val, _val);
__m256i _val_4567_cdef = _mm256_unpackhi_epi16(_val, _val);
__m256i _val_0123 = _mm256_permutevar8x32_epi32(_val_0123_89ab, _mm256_set_epi32(3, 3, 2, 2, 1, 1, 0, 0));
__m256i _val_4567 = _mm256_permutevar8x32_epi32(_val_4567_cdef, _mm256_set_epi32(3, 3, 2, 2, 1, 1, 0, 0));
__m256i _val_89ab = _mm256_permutevar8x32_epi32(_val_0123_89ab, _mm256_set_epi32(7, 7, 6, 6, 5, 5, 4, 4));
__m256i _val_cdef = _mm256_permutevar8x32_epi32(_val_4567_cdef, _mm256_set_epi32(7, 7, 6, 6, 5, 5, 4, 4));
__m256i _sl00_01 = _mm256_mullo_epi16(_w01, _val_0123);
__m256i _sh00_01 = _mm256_mulhi_epi16(_w01, _val_0123);
__m256i _sl10_11 = _mm256_mullo_epi16(_w01, _val_89ab);
__m256i _sh10_11 = _mm256_mulhi_epi16(_w01, _val_89ab);
__m256i _sl02_03 = _mm256_mullo_epi16(_w23, _val_4567);
__m256i _sh02_03 = _mm256_mulhi_epi16(_w23, _val_4567);
__m256i _sl12_13 = _mm256_mullo_epi16(_w23, _val_cdef);
__m256i _sh12_13 = _mm256_mulhi_epi16(_w23, _val_cdef);
_sum0_1 = _mm256_add_epi32(_sum0_1, _mm256_unpacklo_epi16(_sl00_01, _sh00_01));
_sum2_3 = _mm256_add_epi32(_sum2_3, _mm256_unpacklo_epi16(_sl10_11, _sh10_11));
_sum0_1 = _mm256_add_epi32(_sum0_1, _mm256_unpacklo_epi16(_sl02_03, _sh02_03));
_sum2_3 = _mm256_add_epi32(_sum2_3, _mm256_unpacklo_epi16(_sl12_13, _sh12_13));
_sum0_1 = _mm256_add_epi32(_sum0_1, _mm256_unpackhi_epi16(_sl00_01, _sh00_01));
_sum2_3 = _mm256_add_epi32(_sum2_3, _mm256_unpackhi_epi16(_sl10_11, _sh10_11));
_sum0_1 = _mm256_add_epi32(_sum0_1, _mm256_unpackhi_epi16(_sl02_03, _sh02_03));
_sum2_3 = _mm256_add_epi32(_sum2_3, _mm256_unpackhi_epi16(_sl12_13, _sh12_13));
#endif
#else
// 0 1 2 3 4 5 6 7
__m128i _val0 = _mm_loadu_si128((const __m128i*)r0);
__m128i _val1 = _mm_loadu_si128((const __m128i*)(r0 + 8));
__m128i _w0 = _mm_loadu_si128((const __m128i*)k0);
__m128i _w1 = _mm_loadu_si128((const __m128i*)(k0 + 8));
__m128i _w2 = _mm_loadu_si128((const __m128i*)(k0 + 16));
__m128i _w3 = _mm_loadu_si128((const __m128i*)(k0 + 24));
#if __XOP__
__m128i _val0_01 = _mm_shuffle_epi32(_val0, _MM_SHUFFLE(0, 0, 0, 0));
__m128i _val0_23 = _mm_shuffle_epi32(_val0, _MM_SHUFFLE(1, 1, 1, 1));
__m128i _val0_45 = _mm_shuffle_epi32(_val0, _MM_SHUFFLE(2, 2, 2, 2));
__m128i _val0_67 = _mm_shuffle_epi32(_val0, _MM_SHUFFLE(3, 3, 3, 3));
__m128i _val1_01 = _mm_shuffle_epi32(_val1, _MM_SHUFFLE(0, 0, 0, 0));
__m128i _val1_23 = _mm_shuffle_epi32(_val1, _MM_SHUFFLE(1, 1, 1, 1));
__m128i _val1_45 = _mm_shuffle_epi32(_val1, _MM_SHUFFLE(2, 2, 2, 2));
__m128i _val1_67 = _mm_shuffle_epi32(_val1, _MM_SHUFFLE(3, 3, 3, 3));
_sum0 = _mm_maddd_epi16(_val0_01, _w0, _sum0);
_sum1 = _mm_maddd_epi16(_val0_23, _w1, _sum1);
_sum2 = _mm_maddd_epi16(_val1_01, _w0, _sum2);
_sum3 = _mm_maddd_epi16(_val1_23, _w1, _sum3);
_sum0 = _mm_maddd_epi16(_val0_45, _w2, _sum0);
_sum1 = _mm_maddd_epi16(_val0_67, _w3, _sum1);
_sum2 = _mm_maddd_epi16(_val1_45, _w2, _sum2);
_sum3 = _mm_maddd_epi16(_val1_67, _w3, _sum3);
#else
// 0 0 1 1 2 2 3 3
// 4 4 5 5 6 6 7 7
__m128i _val0_0123 = _mm_unpacklo_epi16(_val0, _val0);
__m128i _val0_4567 = _mm_unpackhi_epi16(_val0, _val0);
__m128i _val1_0123 = _mm_unpacklo_epi16(_val1, _val1);
__m128i _val1_4567 = _mm_unpackhi_epi16(_val1, _val1);
__m128i _val0_01 = _mm_unpacklo_epi32(_val0_0123, _val0_0123);
__m128i _val0_23 = _mm_unpackhi_epi32(_val0_0123, _val0_0123);
__m128i _val0_45 = _mm_unpacklo_epi32(_val0_4567, _val0_4567);
__m128i _val0_67 = _mm_unpackhi_epi32(_val0_4567, _val0_4567);
__m128i _val1_01 = _mm_unpacklo_epi32(_val1_0123, _val1_0123);
__m128i _val1_23 = _mm_unpackhi_epi32(_val1_0123, _val1_0123);
__m128i _val1_45 = _mm_unpacklo_epi32(_val1_4567, _val1_4567);
__m128i _val1_67 = _mm_unpackhi_epi32(_val1_4567, _val1_4567);
__m128i _sl00 = _mm_mullo_epi16(_w0, _val0_01);
__m128i _sh00 = _mm_mulhi_epi16(_w0, _val0_01);
__m128i _sl10 = _mm_mullo_epi16(_w0, _val1_01);
__m128i _sh10 = _mm_mulhi_epi16(_w0, _val1_01);
__m128i _sl01 = _mm_mullo_epi16(_w1, _val0_23);
__m128i _sh01 = _mm_mulhi_epi16(_w1, _val0_23);
__m128i _sl11 = _mm_mullo_epi16(_w1, _val1_23);
__m128i _sh11 = _mm_mulhi_epi16(_w1, _val1_23);
__m128i _sl02 = _mm_mullo_epi16(_w2, _val0_45);
__m128i _sh02 = _mm_mulhi_epi16(_w2, _val0_45);
__m128i _sl12 = _mm_mullo_epi16(_w2, _val1_45);
__m128i _sh12 = _mm_mulhi_epi16(_w2, _val1_45);
__m128i _sl03 = _mm_mullo_epi16(_w3, _val0_67);
__m128i _sh03 = _mm_mulhi_epi16(_w3, _val0_67);
__m128i _sl13 = _mm_mullo_epi16(_w3, _val1_67);
__m128i _sh13 = _mm_mulhi_epi16(_w3, _val1_67);
_sum0 = _mm_add_epi32(_sum0, _mm_unpacklo_epi16(_sl00, _sh00));
_sum1 = _mm_add_epi32(_sum1, _mm_unpackhi_epi16(_sl00, _sh00));
_sum2 = _mm_add_epi32(_sum2, _mm_unpacklo_epi16(_sl10, _sh10));
_sum3 = _mm_add_epi32(_sum3, _mm_unpackhi_epi16(_sl10, _sh10));
_sum0 = _mm_add_epi32(_sum0, _mm_unpacklo_epi16(_sl01, _sh01));
_sum1 = _mm_add_epi32(_sum1, _mm_unpackhi_epi16(_sl01, _sh01));
_sum2 = _mm_add_epi32(_sum2, _mm_unpacklo_epi16(_sl11, _sh11));
_sum3 = _mm_add_epi32(_sum3, _mm_unpackhi_epi16(_sl11, _sh11));
_sum0 = _mm_add_epi32(_sum0, _mm_unpacklo_epi16(_sl02, _sh02));
_sum1 = _mm_add_epi32(_sum1, _mm_unpackhi_epi16(_sl02, _sh02));
_sum2 = _mm_add_epi32(_sum2, _mm_unpacklo_epi16(_sl12, _sh12));
_sum3 = _mm_add_epi32(_sum3, _mm_unpackhi_epi16(_sl12, _sh12));
_sum0 = _mm_add_epi32(_sum0, _mm_unpacklo_epi16(_sl03, _sh03));
_sum1 = _mm_add_epi32(_sum1, _mm_unpackhi_epi16(_sl03, _sh03));
_sum2 = _mm_add_epi32(_sum2, _mm_unpacklo_epi16(_sl13, _sh13));
_sum3 = _mm_add_epi32(_sum3, _mm_unpackhi_epi16(_sl13, _sh13));
#endif
#endif
r0 += 16;
k0 += 32;
}
#if __AVX2__
__m256i _sum0_2 = _mm256_permute2x128_si256(_sum0_1, _sum2_3, _MM_SHUFFLE(0, 2, 0, 0));
__m256i _sum1_3 = _mm256_permute2x128_si256(_sum0_1, _sum2_3, _MM_SHUFFLE(0, 3, 0, 1));
_sum0_2 = _mm256_add_epi32(_sum0_2, _sum1_3);
int sum[8];
_mm256_storeu_si256((__m256i*)sum, _sum0_2);
#else
_sum0 = _mm_add_epi32(_sum0, _sum1);
_sum2 = _mm_add_epi32(_sum2, _sum3);
int sum[8];
_mm_storeu_si128((__m128i*)sum, _sum0);
_mm_storeu_si128((__m128i*)(sum + 4), _sum2);
#endif
output0_tm[0] = sum[0];
output1_tm[0] = sum[1];
output2_tm[0] = sum[2];
output3_tm[0] = sum[3];
output0_tm[1] = sum[4];
output1_tm[1] = sum[5];
output2_tm[1] = sum[6];
output3_tm[1] = sum[7];
output0_tm += 2;
output1_tm += 2;
output2_tm += 2;
output3_tm += 2;
}
for (; i < tiles; i++)
{
#if __AVX2__
const short* r0 = bb2.row<const short>(i / 4 + (i % 4) / 2 + i % 2);
#else
const short* r0 = bb2.row<const short>(i / 2 + i % 2);
#endif
const short* k0 = kernel0_tm.row<const short>(r);
int nn = inch; // inch always > 0
#if __AVX2__
__m256i _sum0_1 = _mm256_setzero_si256();
#else
__m128i _sum0 = _mm_setzero_si128();
__m128i _sum1 = _mm_setzero_si128();
#endif
for (int j = 0; j < nn; j++)
{
// 0 1 2 3 4 5 6 7
__m128i _val = _mm_loadu_si128((const __m128i*)r0);
#if __AVX2__
__m256i _w01 = _mm256_loadu_si256((const __m256i*)k0);
__m256i _w23 = _mm256_loadu_si256((const __m256i*)(k0 + 16));
#if __AVXVNNI__ || __AVX512VNNI__
// 0 1 0 1 x x x x
// 0 1 0 1 0 1 0 1
__m128i _val_01 = _mm_shuffle_epi32(_val, _MM_SHUFFLE(0, 0, 0, 0));
__m128i _val_23 = _mm_shuffle_epi32(_val, _MM_SHUFFLE(1, 1, 1, 1));
__m128i _val_45 = _mm_shuffle_epi32(_val, _MM_SHUFFLE(2, 2, 2, 2));
__m128i _val_67 = _mm_shuffle_epi32(_val, _MM_SHUFFLE(3, 3, 3, 3));
__m256i _val_0123 = _mm256_inserti128_si256(_mm256_castsi128_si256(_val_01), _val_23, 1);
__m256i _val_4567 = _mm256_inserti128_si256(_mm256_castsi128_si256(_val_45), _val_67, 1);
_sum0_1 = _mm256_dpwssd_epi32(_sum0_1, _w01, _val_0123);
_sum0_1 = _mm256_dpwssd_epi32(_sum0_1, _w23, _val_4567);
#else
// 0 0 1 1 2 2 3 3
// 4 4 5 5 6 6 7 7
__m256i _val_0123 = _mm256_castsi128_si256(_mm_unpacklo_epi16(_val, _val));
__m256i _val_4567 = _mm256_castsi128_si256(_mm_unpackhi_epi16(_val, _val));
_val_0123 = _mm256_permutevar8x32_epi32(_val_0123, _mm256_set_epi32(3, 3, 2, 2, 1, 1, 0, 0));
_val_4567 = _mm256_permutevar8x32_epi32(_val_4567, _mm256_set_epi32(3, 3, 2, 2, 1, 1, 0, 0));
__m256i _sl00_01 = _mm256_mullo_epi16(_w01, _val_0123);
__m256i _sh00_01 = _mm256_mulhi_epi16(_w01, _val_0123);
__m256i _sl02_03 = _mm256_mullo_epi16(_w23, _val_4567);
__m256i _sh02_03 = _mm256_mulhi_epi16(_w23, _val_4567);
_sum0_1 = _mm256_add_epi32(_sum0_1, _mm256_unpacklo_epi16(_sl00_01, _sh00_01));
_sum0_1 = _mm256_add_epi32(_sum0_1, _mm256_unpacklo_epi16(_sl02_03, _sh02_03));
_sum0_1 = _mm256_add_epi32(_sum0_1, _mm256_unpackhi_epi16(_sl00_01, _sh00_01));
_sum0_1 = _mm256_add_epi32(_sum0_1, _mm256_unpackhi_epi16(_sl02_03, _sh02_03));
#endif
#else
__m128i _w0 = _mm_loadu_si128((const __m128i*)k0);
__m128i _w1 = _mm_loadu_si128((const __m128i*)(k0 + 8));
__m128i _w2 = _mm_loadu_si128((const __m128i*)(k0 + 16));
__m128i _w3 = _mm_loadu_si128((const __m128i*)(k0 + 24));
#if __XOP__
__m128i _val01 = _mm_shuffle_epi32(_val, _MM_SHUFFLE(0, 0, 0, 0));
__m128i _val23 = _mm_shuffle_epi32(_val, _MM_SHUFFLE(1, 1, 1, 1));
__m128i _val45 = _mm_shuffle_epi32(_val, _MM_SHUFFLE(2, 2, 2, 2));
__m128i _val67 = _mm_shuffle_epi32(_val, _MM_SHUFFLE(3, 3, 3, 3));
_sum0 = _mm_maddd_epi16(_val01, _w0, _sum0);
_sum1 = _mm_maddd_epi16(_val23, _w1, _sum1);
_sum0 = _mm_maddd_epi16(_val45, _w2, _sum0);
_sum1 = _mm_maddd_epi16(_val67, _w3, _sum1);
#else
// 0 0 1 1 2 2 3 3
// 4 4 5 5 6 6 7 7
__m128i _val_0123 = _mm_unpacklo_epi16(_val, _val);
__m128i _val_4567 = _mm_unpackhi_epi16(_val, _val);
__m128i _val01 = _mm_unpacklo_epi32(_val_0123, _val_0123);
__m128i _val23 = _mm_unpackhi_epi32(_val_0123, _val_0123);
__m128i _val45 = _mm_unpacklo_epi32(_val_4567, _val_4567);
__m128i _val67 = _mm_unpackhi_epi32(_val_4567, _val_4567);
__m128i _sl0 = _mm_mullo_epi16(_w0, _val01);
__m128i _sh0 = _mm_mulhi_epi16(_w0, _val01);
__m128i _sl1 = _mm_mullo_epi16(_w1, _val23);
__m128i _sh1 = _mm_mulhi_epi16(_w1, _val23);
__m128i _sl2 = _mm_mullo_epi16(_w2, _val45);
__m128i _sh2 = _mm_mulhi_epi16(_w2, _val45);
__m128i _sl3 = _mm_mullo_epi16(_w3, _val67);
__m128i _sh3 = _mm_mulhi_epi16(_w3, _val67);
_sum0 = _mm_add_epi32(_sum0, _mm_unpacklo_epi16(_sl0, _sh0));
_sum1 = _mm_add_epi32(_sum1, _mm_unpackhi_epi16(_sl0, _sh0));
_sum0 = _mm_add_epi32(_sum0, _mm_unpacklo_epi16(_sl1, _sh1));
_sum1 = _mm_add_epi32(_sum1, _mm_unpackhi_epi16(_sl1, _sh1));
_sum0 = _mm_add_epi32(_sum0, _mm_unpacklo_epi16(_sl2, _sh2));
_sum1 = _mm_add_epi32(_sum1, _mm_unpackhi_epi16(_sl2, _sh2));
_sum0 = _mm_add_epi32(_sum0, _mm_unpacklo_epi16(_sl3, _sh3));
_sum1 = _mm_add_epi32(_sum1, _mm_unpackhi_epi16(_sl3, _sh3));
#endif
#endif
r0 += 8;
k0 += 32;
}
#if __AVX2__
__m128i _sum0 = _mm256_extracti128_si256(_sum0_1, 0);
__m128i _sum1 = _mm256_extracti128_si256(_sum0_1, 1);
#endif
_sum0 = _mm_add_epi32(_sum0, _sum1);
int sum[4];
_mm_storeu_si128((__m128i*)sum, _sum0);
output0_tm[0] = sum[0];
output1_tm[0] = sum[1];
output2_tm[0] = sum[2];
output3_tm[0] = sum[3];
output0_tm += 1;
output1_tm += 1;
output2_tm += 1;
output3_tm += 1;
}
}
}
remain_outch_start += nn_outch << 2;
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = remain_outch_start; p < outch; p++)
{
int* output0_tm = top_blob_tm.channel(p);
const Mat kernel0_tm = kernel_tm.channel(p / 4 + p % 4);
for (int r = 0; r < 36; r++)
{
const Mat bb2 = bottom_blob_tm2.channel(r);
int i = 0;
#if __AVX2__
for (; i + 3 < tiles; i += 4)
{
const short* r0 = bb2.row<const short>(i / 4);
const short* k0 = kernel0_tm.row<const short>(r);
__m128i _sum0 = _mm_setzero_si128();
__m128i _sum1 = _mm_setzero_si128();
__m128i _sum2 = _mm_setzero_si128();
__m128i _sum3 = _mm_setzero_si128();
__m128i _sum4 = _mm_setzero_si128();
__m128i _sum5 = _mm_setzero_si128();
__m128i _sum6 = _mm_setzero_si128();
__m128i _sum7 = _mm_setzero_si128();
for (int q = 0; q < inch; q++)
{
__m128i _val0 = _mm_loadu_si128((const __m128i*)r0);
__m128i _val1 = _mm_loadu_si128((const __m128i*)(r0 + 8));
__m128i _val2 = _mm_loadu_si128((const __m128i*)(r0 + 16));
__m128i _val3 = _mm_loadu_si128((const __m128i*)(r0 + 24));
__m128i _w0 = _mm_loadu_si128((const __m128i*)k0);
__m128i _sl0 = _mm_mullo_epi16(_val0, _w0);
__m128i _sh0 = _mm_mulhi_epi16(_val0, _w0);
__m128i _sl1 = _mm_mullo_epi16(_val1, _w0);
__m128i _sh1 = _mm_mulhi_epi16(_val1, _w0);
__m128i _sl2 = _mm_mullo_epi16(_val2, _w0);
__m128i _sh2 = _mm_mulhi_epi16(_val2, _w0);
__m128i _sl3 = _mm_mullo_epi16(_val3, _w0);
__m128i _sh3 = _mm_mulhi_epi16(_val3, _w0);
_sum0 = _mm_add_epi32(_sum0, _mm_unpacklo_epi16(_sl0, _sh0));
_sum1 = _mm_add_epi32(_sum1, _mm_unpackhi_epi16(_sl0, _sh0));
_sum2 = _mm_add_epi32(_sum2, _mm_unpacklo_epi16(_sl1, _sh1));
_sum3 = _mm_add_epi32(_sum3, _mm_unpackhi_epi16(_sl1, _sh1));
_sum4 = _mm_add_epi32(_sum4, _mm_unpacklo_epi16(_sl2, _sh2));
_sum5 = _mm_add_epi32(_sum5, _mm_unpackhi_epi16(_sl2, _sh2));
_sum6 = _mm_add_epi32(_sum6, _mm_unpacklo_epi16(_sl3, _sh3));
_sum7 = _mm_add_epi32(_sum7, _mm_unpackhi_epi16(_sl3, _sh3));
k0 += 8;
r0 += 32;
}
_sum0 = _mm_add_epi32(_sum0, _sum1);
_sum2 = _mm_add_epi32(_sum2, _sum3);
_sum4 = _mm_add_epi32(_sum4, _sum5);
_sum6 = _mm_add_epi32(_sum6, _sum7);
output0_tm[0] = _mm_reduce_add_epi32(_sum0);
output0_tm[1] = _mm_reduce_add_epi32(_sum2);
output0_tm[2] = _mm_reduce_add_epi32(_sum4);
output0_tm[3] = _mm_reduce_add_epi32(_sum6);
output0_tm += 4;
}
#endif
for (; i + 1 < tiles; i += 2)
{
#if __AVX2__
const short* r0 = bb2.row<const short>(i / 4 + (i % 4) / 2);
#else
const short* r0 = bb2.row<const short>(i / 2);
#endif
const short* k0 = kernel0_tm.row<const short>(r);
__m128i _sum0 = _mm_setzero_si128();
__m128i _sum1 = _mm_setzero_si128();
__m128i _sum2 = _mm_setzero_si128();
__m128i _sum3 = _mm_setzero_si128();
for (int q = 0; q < inch; q++)
{
__m128i _val0 = _mm_loadu_si128((const __m128i*)r0);
__m128i _val1 = _mm_loadu_si128((const __m128i*)(r0 + 8));
__m128i _w0 = _mm_loadu_si128((const __m128i*)k0);
__m128i _sl0 = _mm_mullo_epi16(_val0, _w0);
__m128i _sh0 = _mm_mulhi_epi16(_val0, _w0);
__m128i _sl1 = _mm_mullo_epi16(_val1, _w0);
__m128i _sh1 = _mm_mulhi_epi16(_val1, _w0);
_sum0 = _mm_add_epi32(_sum0, _mm_unpacklo_epi16(_sl0, _sh0));
_sum1 = _mm_add_epi32(_sum1, _mm_unpackhi_epi16(_sl0, _sh0));
_sum2 = _mm_add_epi32(_sum2, _mm_unpacklo_epi16(_sl1, _sh1));
_sum3 = _mm_add_epi32(_sum3, _mm_unpackhi_epi16(_sl1, _sh1));
k0 += 8;
r0 += 16;
}
_sum0 = _mm_add_epi32(_sum0, _sum1);
_sum2 = _mm_add_epi32(_sum2, _sum3);
output0_tm[0] = _mm_reduce_add_epi32(_sum0);
output0_tm[1] = _mm_reduce_add_epi32(_sum2);
output0_tm += 2;
}
for (; i < tiles; i++)
{
#if __AVX2__
const short* r0 = bb2.row<const short>(i / 4 + (i % 4) / 2 + i % 2);
#else
const short* r0 = bb2.row<const short>(i / 2 + i % 2);
#endif
const short* k0 = kernel0_tm.row<const short>(r);
__m128i _sum0 = _mm_setzero_si128();
__m128i _sum1 = _mm_setzero_si128();
for (int q = 0; q < inch; q++)
{
__m128i _val = _mm_loadu_si128((const __m128i*)r0);
__m128i _w0 = _mm_loadu_si128((const __m128i*)k0);
__m128i _sl0 = _mm_mullo_epi16(_val, _w0);
__m128i _sh0 = _mm_mulhi_epi16(_val, _w0);
_sum0 = _mm_add_epi32(_sum0, _mm_unpacklo_epi16(_sl0, _sh0));
_sum1 = _mm_add_epi32(_sum1, _mm_unpackhi_epi16(_sl0, _sh0));
k0 += 8;
r0 += 8;
}
_sum0 = _mm_add_epi32(_sum0, _sum1);
output0_tm[0] = _mm_reduce_add_epi32(_sum0);
output0_tm++;
}
}
}
}
bottom_blob_tm = Mat();
// END dot
// BEGIN transform output
Mat top_blob_bordered;
if (outw == top_blob.w && outh == top_blob.h)
{
top_blob_bordered = top_blob;
}
else
{
top_blob_bordered.create(outw, outh, outch, 4u, 1, opt.workspace_allocator);
}
{
// const float otm[4][6] = {
// {1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f},
// {0.0f, 1.0f, -1.0f, 2.0f, -2.0f, 0.0f},
// {0.0f, 1.0f, 1.0f, 4.0f, 4.0f, 0.0f},
// {0.0f, 1.0f, -1.0f, 8.0f, -8.0f, 1.0f}
// };
// 0 = r00 + (r01 + r02) + (r03 + r04)
// 1 = (r01 - r02) + (r03 - r04) * 2
// 2 = (r01 + r02) + (r03 + r04) * 4
// 3 = r05 + (r01 - r02) + (r03 - r04) * 8
int w_tm = outw / 4 * 6;
int h_tm = outh / 4 * 6;
const int tiles = w_tm / 6 * h_tm / 6;
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = 0; p < outch; p++)
{
const Mat out0_tm = top_blob_tm.channel(p);
Mat out0 = top_blob_bordered.channel(p);
int tmp[4][6];
// tile
for (int i = 0; i < outh / 4; i++)
{
for (int j = 0; j < outw / 4; j++)
{
// top_blob_tm.create(tiles, 36, outch, 4u, 1, opt.workspace_allocator);
const int* output0_tm_0 = (const int*)out0_tm + (i * w_tm / 6 + j) * 1;
const int* output0_tm_1 = output0_tm_0 + tiles * 1;
const int* output0_tm_2 = output0_tm_0 + tiles * 2;
const int* output0_tm_3 = output0_tm_0 + tiles * 3;
const int* output0_tm_4 = output0_tm_0 + tiles * 4;
const int* output0_tm_5 = output0_tm_0 + tiles * 5;
int* output0 = out0.row<int>(i * 4) + j * 4;
// 0 = r00 + (r01 + r02) + (r03 + r04)
// 1 = (r01 - r02) + (r03 - r04) * 2
// 2 = (r01 + r02) + (r03 + r04) * 4
// 3 = r05 + (r01 - r02) + (r03 - r04) * 8
// TODO sse optimize
for (int m = 0; m < 5; m++)
{
int tmp02a = output0_tm_1[0] + output0_tm_2[0];
int tmp13a = output0_tm_1[0] - output0_tm_2[0];
int tmp02b = output0_tm_3[0] + output0_tm_4[0];
int tmp13b = output0_tm_3[0] - output0_tm_4[0];
tmp[0][m] = output0_tm_0[0] + tmp02a + tmp02b;
tmp[1][m] = tmp13a + tmp13b * 2;
tmp[2][m] = tmp02a + tmp02b * 4;
tmp[3][m] = output0_tm_5[0] * 4 + tmp13a + tmp13b * 8;
output0_tm_0 += tiles * 6;
output0_tm_1 += tiles * 6;
output0_tm_2 += tiles * 6;
output0_tm_3 += tiles * 6;
output0_tm_4 += tiles * 6;
output0_tm_5 += tiles * 6;
}
for (int m = 5; m < 6; m++)
{
int tmp02a = output0_tm_1[0] + output0_tm_2[0];
int tmp13a = output0_tm_1[0] - output0_tm_2[0];
int tmp02b = output0_tm_3[0] + output0_tm_4[0];
int tmp13b = output0_tm_3[0] - output0_tm_4[0];
tmp[0][m] = (output0_tm_0[0] + tmp02a + tmp02b) * 4;
tmp[1][m] = (tmp13a + tmp13b * 2) * 4;
tmp[2][m] = (tmp02a + tmp02b * 4) * 4;
tmp[3][m] = (output0_tm_5[0] * 4 + tmp13a + tmp13b * 8) * 4;
output0_tm_0 += tiles * 6;
output0_tm_1 += tiles * 6;
output0_tm_2 += tiles * 6;
output0_tm_3 += tiles * 6;
output0_tm_4 += tiles * 6;
output0_tm_5 += tiles * 6;
}
for (int m = 0; m < 4; m++)
{
const int* tmp0 = tmp[m];
int tmp02a = tmp0[1] + tmp0[2];
int tmp13a = tmp0[1] - tmp0[2];
int tmp02b = tmp0[3] + tmp0[4];
int tmp13b = tmp0[3] - tmp0[4];
output0[0] = (tmp0[0] + tmp02a + tmp02b) / 576;
output0[1] = (tmp13a + tmp13b * 2) / 576;
output0[2] = (tmp02a + tmp02b * 4) / 576;
output0[3] = (tmp0[5] + tmp13a + tmp13b * 8) / 576;
output0 += outw;
}
}
}
}
}
// END transform output
// cut result pad
copy_cut_border(top_blob_bordered, top_blob, 0, top_blob_bordered.h - top_blob.h, 0, top_blob_bordered.w - top_blob.w, opt);
}
|
CPULauncher.h | // ----------------------------------------------------------------------------
// - Open3D: www.open3d.org -
// ----------------------------------------------------------------------------
// The MIT License (MIT)
//
// Copyright (c) 2018 www.open3d.org
//
// 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.
// ----------------------------------------------------------------------------
#pragma once
#include <cassert>
#include <vector>
#include "open3d/core/AdvancedIndexing.h"
#include "open3d/core/Indexer.h"
#include "open3d/core/Tensor.h"
#include "open3d/core/kernel/ParallelUtil.h"
#include "open3d/utility/Console.h"
namespace open3d {
namespace core {
namespace kernel {
class CPULauncher {
public:
/// Fills tensor[:][i] with element_kernel(i).
///
/// \param indexer The input tensor and output tensor to the indexer are the
/// same (as a hack), since the tensor are filled in-place.
/// \param element_kernel A function that takes pointer location and
/// workload_idx, computes the value to fill, and fills the value at the
/// pointer location.
template <typename func_t>
static void LaunchIndexFillKernel(const Indexer& indexer,
func_t element_kernel) {
#pragma omp parallel for schedule(static)
for (int64_t workload_idx = 0; workload_idx < indexer.NumWorkloads();
++workload_idx) {
element_kernel(indexer.GetInputPtr(0, workload_idx), workload_idx);
}
}
template <typename func_t>
static void LaunchUnaryEWKernel(const Indexer& indexer,
func_t element_kernel) {
#pragma omp parallel for schedule(static)
for (int64_t workload_idx = 0; workload_idx < indexer.NumWorkloads();
++workload_idx) {
element_kernel(indexer.GetInputPtr(0, workload_idx),
indexer.GetOutputPtr(workload_idx));
}
}
template <typename func_t>
static void LaunchBinaryEWKernel(const Indexer& indexer,
func_t element_kernel) {
#pragma omp parallel for schedule(static)
for (int64_t workload_idx = 0; workload_idx < indexer.NumWorkloads();
++workload_idx) {
element_kernel(indexer.GetInputPtr(0, workload_idx),
indexer.GetInputPtr(1, workload_idx),
indexer.GetOutputPtr(workload_idx));
}
}
template <typename func_t>
static void LaunchAdvancedIndexerKernel(const AdvancedIndexer& indexer,
func_t element_kernel) {
#pragma omp parallel for schedule(static)
for (int64_t workload_idx = 0; workload_idx < indexer.NumWorkloads();
++workload_idx) {
element_kernel(indexer.GetInputPtr(workload_idx),
indexer.GetOutputPtr(workload_idx));
}
}
template <typename scalar_t, typename func_t>
static void LaunchReductionKernelSerial(const Indexer& indexer,
func_t element_kernel) {
for (int64_t workload_idx = 0; workload_idx < indexer.NumWorkloads();
++workload_idx) {
element_kernel(indexer.GetInputPtr(0, workload_idx),
indexer.GetOutputPtr(workload_idx));
}
}
/// Create num_threads workers to compute partial reductions and then reduce
/// to the final results. This only applies to reduction op with one output.
template <typename scalar_t, typename func_t>
static void LaunchReductionKernelTwoPass(const Indexer& indexer,
func_t element_kernel,
scalar_t identity) {
if (indexer.NumOutputElements() > 1) {
utility::LogError(
"Internal error: two-pass reduction only works for "
"single-output reduction ops.");
}
int64_t num_workloads = indexer.NumWorkloads();
int64_t num_threads = GetMaxThreads();
int64_t workload_per_thread =
(num_workloads + num_threads - 1) / num_threads;
std::vector<scalar_t> thread_results(num_threads, identity);
#pragma omp parallel for schedule(static)
for (int64_t thread_idx = 0; thread_idx < num_threads; ++thread_idx) {
int64_t start = thread_idx * workload_per_thread;
int64_t end = std::min(start + workload_per_thread, num_workloads);
for (int64_t workload_idx = start; workload_idx < end;
++workload_idx) {
element_kernel(indexer.GetInputPtr(0, workload_idx),
&thread_results[thread_idx]);
}
}
void* output_ptr = indexer.GetOutputPtr(0);
for (int64_t thread_idx = 0; thread_idx < num_threads; ++thread_idx) {
element_kernel(&thread_results[thread_idx], output_ptr);
}
}
template <typename scalar_t, typename func_t>
static void LaunchReductionParallelDim(const Indexer& indexer,
func_t element_kernel) {
// Prefers outer dimension >= num_threads.
const int64_t* indexer_shape = indexer.GetMasterShape();
const int64_t num_dims = indexer.NumDims();
int64_t num_threads = GetMaxThreads();
// Init best_dim as the outer-most non-reduction dim.
int64_t best_dim = num_dims - 1;
while (best_dim >= 0 && indexer.IsReductionDim(best_dim)) {
best_dim--;
}
for (int64_t dim = best_dim; dim >= 0 && !indexer.IsReductionDim(dim);
--dim) {
if (indexer_shape[dim] >= num_threads) {
best_dim = dim;
break;
} else if (indexer_shape[dim] > indexer_shape[best_dim]) {
best_dim = dim;
}
}
if (best_dim == -1) {
utility::LogError(
"Internal error: all dims are reduction dims, use "
"LaunchReductionKernelTwoPass instead.");
}
#pragma omp parallel for schedule(static)
for (int64_t i = 0; i < indexer_shape[best_dim]; ++i) {
Indexer sub_indexer(indexer);
sub_indexer.ShrinkDim(best_dim, i, 1);
LaunchReductionKernelSerial<scalar_t>(sub_indexer, element_kernel);
}
}
};
} // namespace kernel
} // namespace core
} // namespace open3d
|
hermv_c_csc_u_hi_trans.c | #include "alphasparse/kernel.h"
#include "alphasparse/util.h"
#include <memory.h>
#include "alphasparse/opt.h"
#ifdef _OPENMP
#include <omp.h>
#endif
static alphasparse_status_t
hermv_csc_u_hi_trans_unroll(const ALPHA_Number alpha,
const ALPHA_SPMAT_CSC *A,
const ALPHA_Number *x,
const ALPHA_Number beta,
ALPHA_Number *y)
{
const ALPHA_INT m = A->rows;
const ALPHA_INT n = A->cols;
const ALPHA_INT num_threads = alpha_get_thread_num();
#ifdef _OPENMP
#pragma omp parallel for num_threads(num_threads)
#endif
for(ALPHA_INT i = 0; i < m; ++i)
{
ALPHA_Number tmp1, tmp2;
alpha_mul(tmp1, beta, y[i]);
alpha_mul(tmp2, alpha, x[i]);
alpha_add(y[i], tmp1, tmp2);
}
// each thread has a y_local
ALPHA_Number **y_local = alpha_memalign(num_threads * sizeof(ALPHA_Number *), DEFAULT_ALIGNMENT);
#ifdef _OPENMP
#pragma omp parallel for num_threads(num_threads)
#endif
for(ALPHA_INT i = 0; i < num_threads; i++)
{
y_local[i] = alpha_memalign(m * sizeof(ALPHA_Number), DEFAULT_ALIGNMENT);
memset(y_local[i], '\0', sizeof(ALPHA_Number) * m);
}
#ifdef _OPENMP
#pragma omp parallel for num_threads(num_threads)
#endif
for(ALPHA_INT i = 0; i < m; ++i)
{
ALPHA_INT tid = alpha_get_thread_id();
ALPHA_INT ais = A->cols_start[i];
ALPHA_INT aie = A->cols_end[i];
ALPHA_INT start = ais;
ALPHA_INT end = alpha_lower_bound(&A->row_indx[ais], &A->row_indx[aie], i) - A->row_indx;
if(end > ais && A->row_indx[end-1] == i){
end -= 1;
}
const ALPHA_INT* A_row = &A->row_indx[ais];
const ALPHA_Number* A_val = &A->values[ais];
ALPHA_INT ai = 0;
ALPHA_INT ail = end - start;
ALPHA_Number alpha_xi, tmp;
alpha_mul(alpha_xi, alpha, x[i]);
for(; ai < ail-3; ai+=4)
{
ALPHA_Number av0 = A_val[ai];
ALPHA_Number av1 = A_val[ai + 1];
ALPHA_Number av2 = A_val[ai + 2];
ALPHA_Number av3 = A_val[ai + 3];
ALPHA_INT ar0 = A_row[ai];
ALPHA_INT ar1 = A_row[ai + 1];
ALPHA_INT ar2 = A_row[ai + 2];
ALPHA_INT ar3 = A_row[ai + 3];
alpha_madde_2c(y_local[tid][ar0], av0, alpha_xi);
alpha_madde_2c(y_local[tid][ar1], av1, alpha_xi);
alpha_madde_2c(y_local[tid][ar2], av2, alpha_xi);
alpha_madde_2c(y_local[tid][ar3], av3, alpha_xi);
alpha_mul(tmp, alpha, av0);
alpha_madde(y_local[tid][i], tmp, x[ar0]);
alpha_mul(tmp, alpha, av1);
alpha_madde(y_local[tid][i], tmp, x[ar1]);
alpha_mul(tmp, alpha, av2);
alpha_madde(y_local[tid][i], tmp, x[ar2]);
alpha_mul(tmp, alpha, av3);
alpha_madde(y_local[tid][i], tmp, x[ar3]);
}
for(; ai < ail; ai++)
{
ALPHA_Number av = A_val[ai];
ALPHA_INT ar = A_row[ai];
alpha_madde_2c(y_local[tid][ar], av, alpha_xi);
alpha_mul(tmp, alpha, av);
alpha_madde(y_local[tid][i], tmp, x[ar]);
}
}
#ifdef _OPENMP
#pragma omp parallel for num_threads(num_threads)
#endif
for(ALPHA_INT col = 0; col < m; col++)
for(ALPHA_INT i = 0; i < num_threads; i++)
{
alpha_add(y[col], y[col], y_local[i][col]);
}
for(ALPHA_INT i = 0; i < num_threads; i++)
{
alpha_free(y_local[i]);
}
alpha_free(y_local);
return ALPHA_SPARSE_STATUS_SUCCESS;
}
alphasparse_status_t
ONAME(const ALPHA_Number alpha,
const ALPHA_SPMAT_CSC *A,
const ALPHA_Number *x,
const ALPHA_Number beta,
ALPHA_Number *y)
{
return hermv_csc_u_hi_trans_unroll(alpha, A, x, beta, y);
}
|
bgq_l2_atomic_counter_sharing.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
//#include <unistd.h>
#include <hwi/include/common/bgq_alignment.h>
#include <hwi/include/bqc/A2_inlines.h>
#include <spi/include/kernel/memory.h>
#include <spi/include/l2/barrier.h>
#include <spi/include/l2/atomic.h>
/* TODO: test all of these functions
uint64_t L2_AtomicLoad(volatile uint64_t *ptr)
uint64_t L2_AtomicLoadClear(volatile uint64_t *ptr)
uint64_t L2_AtomicLoadIncrement(volatile uint64_t *ptr)
uint64_t L2_AtomicLoadDecrement(volatile uint64_t *ptr)
uint64_t L2_AtomicLoadIncrementBounded(volatile uint64_t *ptr)
uint64_t L2_AtomicLoadDecrementBounded(volatile uint64_t *ptr)
uint64_t L2_AtomicLoadIncrementIfEqual(volatile uint64_t *ptr)
void L2_AtomicStore(volatile uint64_t *ptr, uint64_t value)
void L2_AtomicStoreTwin(volatile uint64_t *ptr, uint64_t value)
void L2_AtomicStoreAdd(volatile uint64_t *ptr, uint64_t value)
void L2_AtomicStoreAddCoherenceOnZero(volatile uint64_t *ptr,
void L2_AtomicStoreOr(volatile uint64_t *ptr, uint64_t value)
void L2_AtomicStoreXor(volatile uint64_t *ptr, uint64_t value)
void L2_AtomicStoreMax(volatile uint64_t *ptr, uint64_t value)
void L2_AtomicStoreMaxSignValue(volatile uint64_t *ptr,
*/
int main(int argc, char * argv[])
{
const int n = 1024;
int count = (argc>1) ? atoi(argv[1]) : 1000000;
/* this "activates" the L2 atomic data structures */
uint64_t * l2_counters = NULL;
int rc = posix_memalign((void**)&l2_counters, 2*1024*1024, n * sizeof(uint64_t) );
assert(rc==0 && l2_counters != NULL);
uint64_t rc64 = Kernel_L2AtomicsAllocate(l2_counters, n * sizeof(uint64_t) );
assert(rc64==0);
for (int i=0; i<n; i++) {
L2_AtomicStore(&(l2_counters[i]), 0);
}
#pragma omp parallel shared(l2_counters)
{
int me = omp_get_thread_num();
int jmax = n/omp_get_num_threads();
for (int j=0; j<jmax; j++) {
#pragma omp barrier
uint64_t t0 = GetTimeBase();
for (int i=0; i<count; i++) {
L2_AtomicLoadIncrement(&(l2_counters[j*me]));
}
#pragma omp barrier
uint64_t t1 = GetTimeBase();
printf("threads = %d, stride = %d, ticks = %llu \n",
omp_get_num_threads(), j, t1-t0);
fflush(stdout);
}
}
for (int i=0; i<n; i++) {
uint64_t rval = L2_AtomicLoad(&(l2_counters[i]));
printf("l2_counter[%d]=%llu\n", i, rval);
}
return 0;
}
|
c_mandel.c | /* ***********************************************************************
This program is part of the
OpenMP Source Code Repository
http://www.pcg.ull.es/ompscr/
e-mail: ompscr@etsii.ull.es
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
(LICENSE file) along with this program; if not, write to
the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
Boston, MA 02111-1307 USA
FILE: c_mandel.c
VERSION: 1.0
DATE: May 2004
AUTHOR: F. de Sande
COMMENTS TO: sande@csi.ull.es
DESCRIPTION: This program computes an estimation to the
Mandelbrot Set area using MonteCarlo sampling.
The best known estimate so far is 1.50659177 +- 0.00000008.
COMMENTS: The Mandelbrot set is a fractal that is defined as the set of points c
in the complex plane for which the sequence z_{n+1} = z_n^2 + c
with z_0 = 0 does not tend to infinity.
The area of the Mandelbrot set is an open question that has been
discussed in the recent past.
It is not easy to obtain an accurate analytical estimate, and therefore
statistical methods have been used.
The program explores the rectangle ranging over (-2.0, 0.5) in the
real axis and (0.0, 1.125) in the imaginary axis.
This rectangle covers the top half of the Mandelbrot Set.
REFERENCES: http://www.fractalus.com/kerry/articles/area/mandelbrot-area.html
http://www.matthiasbook.de/papers/parallelfractals/mandelbrot.html
http://www.mrob.com/pub/muency/areaofthemandelbrotset.html
http://en.wikipedia.org/wiki/Mandelbrot_set
BASIC PRAGMAS: parallel for
USAGE: ./c_mandel.par 8192
INPUT: The number of points to explore
OUTPUT: An estimation of the area and the error.
FILE FORMATS: -
RESTRICTIONS: -
REVISION HISTORY:
**************************************************************************/
//#include "OmpSCR.h"
#include <omp.h>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#define OSCR_RAND_MAX 2147483647
#define MAXITER 100000
#define DEFAULT_NPOINTS 4092
#define THRESOLD 2.0
#define NPOINTSINIT 10
#define NUM_ARGS 1
#define NUM_TIMERS 1
typedef struct { double re, im; } complex;
int NPOINTS; /* Total no. of points */
complex *points;
/* -----------------------------------------------------------------------
IMPLEMENTATION
* ----------------------------------------------------------------------- */
int main(int argc, char **argv) {
int i, j, NUMTHREADS;
long inside, /* no. of points inside the Mandelbrot set */
outside; /* no. of points outside the Mandelbrot set */
double area, error, ztemp, total_time;
complex z;
// char *PARAM_NAMES[NUM_ARGS] = {"Number of points"};
// char *TIMERS_NAMES[NUM_TIMERS] = {"Total_time"};
// char *DEFAULT_VALUES[NUM_ARGS] = {"4092"};
NUMTHREADS = 1; //omp_get_num_threads();
//OSCR_init (NUMTHREADS, "Mandelbrot set area", "Use 'mandel' <Number of points>", NUM_ARGS,
// PARAM_NAMES, DEFAULT_VALUES , NUM_TIMERS, NUM_TIMERS, TIMERS_NAMES,
// argc, argv);
NPOINTS = NPOINTSINIT; // OSCR_getarg_int(1);
/* Default: DEFAULT_NPOINTS */
points = (complex *)calloc(NPOINTS, sizeof(complex));
NUMTHREADS = 1; //omp_get_num_threads();
/*1. Generate NPOINTS random points in the complex plane */
srandom(31416);
for (i = 0; i < NPOINTS; i++) {
points[i].re = -2.0 + 2.5 * random() / OSCR_RAND_MAX;
points[i].im = 1.125 * random() / OSCR_RAND_MAX;
}
/* * 2. Monte Carlo sampling
* 2a. Outer loop runs over NPOINTS, initialise z=c
* 2b. Inner loop has the iteration z=z*z+c, and threshold test
*/
//OSCR_timer_start(0);
outside = 0;
#pragma omp parallel for default(none) reduction(+:outside) \
private(i, j, ztemp, z) shared(NPOINTS, points)
for(i = 0; i < NPOINTS; i++) {
z.re = points[i].re;
z.im = points[i].im;
for (j = 0; j < MAXITER; j++) {
ztemp = (z.re * z.re) - (z.im * z.im) + points[i].re;
z.im = z.re * z.im * 2 + points[i].im;
z.re = ztemp;
if (z.re * z.re + z.im * z.im > THRESOLD) {
outside++;
break;
}
} /* for j */
} /* for i */
inside = (long)NPOINTS - outside;
/*3. Calculate area and error */
/* The area is proportional to 2 * the area of the rectangle * no. of points inside it */
/* The error is inversely proportional to the square root of the number of test cases */
area = 2.0 * (2.5 * 1.125) * inside / NPOINTS;
error = area / sqrt(NPOINTS);
//OSCR_timer_stop(0);
total_time = 1; //OSCR_timer_read(0);
/* 4. Output the Results */
//OSCR_report(1, TIMERS_NAMES);
printf("\n \t# THREADS NPOINTS AREA \t\t\tERROR \t\tTIME (secs.)\n");
printf("\t%d \t%d \t%16.12f %16.12f \t%lf\n", NUMTHREADS, NPOINTS, area, error, total_time);
return 0;
}
/*
* vim:ts=2:sw=2:
*/
|
GB_binop__rminus_fp64.c | //------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_ek_slice.h"
#include "GB_dense.h"
#include "GB_mkl.h"
#include "GB_binop__include.h"
// C=binop(A,B) is defined by the following types and operators:
// A+B function (eWiseAdd): GB_AaddB__rminus_fp64
// A.*B function (eWiseMult): GB_AemultB__rminus_fp64
// A*D function (colscale): GB_AxD__rminus_fp64
// D*A function (rowscale): GB_DxB__rminus_fp64
// C+=B function (dense accum): GB_Cdense_accumB__rminus_fp64
// C+=b function (dense accum): GB_Cdense_accumb__rminus_fp64
// C+=A+B function (dense ewise3): GB_Cdense_ewise3_accum__rminus_fp64
// C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__rminus_fp64
// C=scalar+B GB_bind1st__rminus_fp64
// C=scalar+B' GB_bind1st_tran__rminus_fp64
// C=A+scalar GB_bind2nd__rminus_fp64
// C=A'+scalar GB_bind2nd_tran__rminus_fp64
// C type: double
// A type: double
// B,b type: double
// BinaryOp: cij = (bij - aij)
#define GB_ATYPE \
double
#define GB_BTYPE \
double
#define GB_CTYPE \
double
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
1
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
1
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
double aij = Ax [pA]
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB) \
double bij = Bx [pB]
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
double t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA) \
cij = Ax [pA]
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB) \
cij = Bx [pB]
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z, x, y) \
z = (y - x) ;
// op is second
#define GB_OP_IS_SECOND \
0
// op is plus_fp32 or plus_fp64
#define GB_OP_IS_PLUS_REAL \
0
// op is minus_fp32 or minus_fp64
#define GB_OP_IS_MINUS_REAL \
0
// GB_cblas_*axpy gateway routine, if it exists for this operator and type:
#define GB_CBLAS_AXPY \
(none)
// do the numerical phases of GB_add and GB_emult
#define GB_PHASE_2_OF_2
// hard-coded loops can be vectorized
#define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_RMINUS || GxB_NO_FP64 || GxB_NO_RMINUS_FP64)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void GB_Cdense_ewise3_accum__rminus_fp64
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
GrB_Info GB_Cdense_ewise3_noaccum__rminus_fp64
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_dense_ewise3_noaccum_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += B, accumulate a sparse matrix into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB_Cdense_accumB__rminus_fp64
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *GB_RESTRICT kfirst_slice,
const int64_t *GB_RESTRICT klast_slice,
const int64_t *GB_RESTRICT pstart_slice,
const int ntasks,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
#include "GB_dense_subassign_23_template.c"
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB_Cdense_accumb__rminus_fp64
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
// get the scalar b for C += b, of type double
double bwork = (*((double *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB_AxD__rminus_fp64
(
GrB_Matrix C,
const GrB_Matrix A, bool A_is_pattern,
const GrB_Matrix D, bool D_is_pattern,
const int64_t *GB_RESTRICT kfirst_slice,
const int64_t *GB_RESTRICT klast_slice,
const int64_t *GB_RESTRICT pstart_slice,
const int ntasks,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
double *GB_RESTRICT Cx = (double *) C->x ;
#include "GB_AxB_colscale_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB_DxB__rminus_fp64
(
GrB_Matrix C,
const GrB_Matrix D, bool D_is_pattern,
const GrB_Matrix B, bool B_is_pattern,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
double *GB_RESTRICT Cx = (double *) C->x ;
#include "GB_AxB_rowscale_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseAdd: C = A+B or C<M> = A+B
//------------------------------------------------------------------------------
GrB_Info GB_AaddB__rminus_fp64
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const bool Ch_is_Mh,
const int64_t *GB_RESTRICT C_to_M,
const int64_t *GB_RESTRICT C_to_A,
const int64_t *GB_RESTRICT C_to_B,
const GB_task_struct *GB_RESTRICT TaskList,
const int ntasks,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_add_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C = A.*B or C<M> = A.*B
//------------------------------------------------------------------------------
GrB_Info GB_AemultB__rminus_fp64
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *GB_RESTRICT C_to_M,
const int64_t *GB_RESTRICT C_to_A,
const int64_t *GB_RESTRICT C_to_B,
const GB_task_struct *GB_RESTRICT TaskList,
const int ntasks,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
GrB_Info GB_bind1st__rminus_fp64
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
double *Cx = (double *) Cx_output ;
double x = (*((double *) x_input)) ;
double *Bx = (double *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
double bij = Bx [p] ;
Cx [p] = (bij - x) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB_bind2nd__rminus_fp64
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
double *Cx = (double *) Cx_output ;
double *Ax = (double *) Ax_input ;
double y = (*((double *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
double aij = Ax [p] ;
Cx [p] = (y - aij) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no typcasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
double aij = Ax [pA] ; \
Cx [pC] = (aij - x) ; \
}
GrB_Info GB_bind1st_tran__rminus_fp64
(
GrB_Matrix C,
const GB_void *x_input,
const GrB_Matrix A,
int64_t *GB_RESTRICT *Rowcounts,
GBI_single_iterator Iter,
const int64_t *GB_RESTRICT A_slice,
int naslice
)
{
// GB_unop_transpose.c uses GB_ATYPE, but A is
// the 2nd input to binary operator z=f(x,y).
#undef GB_ATYPE
#define GB_ATYPE \
double
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
double x = (*((const double *) x_input)) ;
#define GB_PHASE_2_OF_2
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
double
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typcasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
double aij = Ax [pA] ; \
Cx [pC] = (y - aij) ; \
}
GrB_Info GB_bind2nd_tran__rminus_fp64
(
GrB_Matrix C,
const GrB_Matrix A,
const GB_void *y_input,
int64_t *GB_RESTRICT *Rowcounts,
GBI_single_iterator Iter,
const int64_t *GB_RESTRICT A_slice,
int naslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
double y = (*((const double *) y_input)) ;
#define GB_PHASE_2_OF_2
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
GB_msort_3b.c | //------------------------------------------------------------------------------
// GB_msort_3b: sort a 3-by-n list of integers, using A[0:2][ ] as the key
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// A parallel mergesort of an array of 3-by-n integers. Each key
// consists of three integers.
#include "GB_msort_3b.h"
//------------------------------------------------------------------------------
// GB_msort_3b_binary_search: binary search for the pivot
//------------------------------------------------------------------------------
// The Pivot value is Y [pivot], and a binary search for the Pivot is made in
// the array X [p_pstart...p_end-1], which is sorted in non-decreasing order on
// input. The return value is pleft, where
//
// X [p_start ... pleft-1] <= Pivot and
// X [pleft ... p_end-1] >= Pivot holds.
//
// pleft is returned in the range p_start to p_end. If pleft is p_start, then
// the Pivot is smaller than all entries in X [p_start...p_end-1], and the left
// list X [p_start...pleft-1] is empty. If pleft is p_end, then the Pivot is
// larger than all entries in X [p_start...p_end-1], and the right list X
// [pleft...p_end-1] is empty.
static int64_t GB_msort_3b_binary_search // return pleft
(
const int64_t *GB_RESTRICT Y_0, // Pivot is Y [pivot]
const int64_t *GB_RESTRICT Y_1,
const int64_t *GB_RESTRICT Y_2,
const int64_t pivot,
const int64_t *GB_RESTRICT X_0, // search in X [p_start..p_end_-1]
const int64_t *GB_RESTRICT X_1,
const int64_t *GB_RESTRICT X_2,
const int64_t p_start,
const int64_t p_end
)
{
//--------------------------------------------------------------------------
// find where the Pivot appears in X
//--------------------------------------------------------------------------
// binary search of X [p_start...p_end-1] for the Pivot
int64_t pleft = p_start ;
int64_t pright = p_end - 1 ;
while (pleft < pright)
{
int64_t pmiddle = (pleft + pright) >> 1 ;
// less = (X [pmiddle] < Pivot)
bool less = GB_lt_3 (X_0, X_1, X_2, pmiddle,
Y_0, Y_1, Y_2, pivot) ;
pleft = less ? (pmiddle+1) : pleft ;
pright = less ? pright : pmiddle ;
}
// binary search is narrowed down to a single item
// or it has found the list is empty:
ASSERT (pleft == pright || pleft == pright + 1) ;
// If found is true then X [pleft == pright] == Pivot. If duplicates
// appear then X [pleft] is any one of the entries equal to the Pivot
// in the list. If found is false then
// X [p_start ... pleft-1] < Pivot and
// X [pleft+1 ... p_end-1] > Pivot holds.
// The value X [pleft] may be either < or > Pivot.
bool found = (pleft == pright) && GB_eq_3 (X_0, X_1, X_2, pleft,
Y_0, Y_1, Y_2, pivot) ;
// Modify pleft and pright:
if (!found && (pleft == pright))
{
if (GB_lt_3 (X_0, X_1, X_2, pleft,
Y_0, Y_1, Y_2, pivot))
{
pleft++ ;
}
else
{
// pright++ ; // (not needed)
}
}
//--------------------------------------------------------------------------
// return result
//--------------------------------------------------------------------------
// If found is false then
// X [p_start ... pleft-1] < Pivot and
// X [pleft ... p_end-1] > Pivot holds,
// and pleft-1 == pright
// If X has no duplicates, then whether or not Pivot is found,
// X [p_start ... pleft-1] < Pivot and
// X [pleft ... p_end-1] >= Pivot holds.
// If X has duplicates, then whether or not Pivot is found,
// X [p_start ... pleft-1] <= Pivot and
// X [pleft ... p_end-1] >= Pivot holds.
return (pleft) ;
}
//------------------------------------------------------------------------------
// GB_msort_3b_create_merge_tasks
//------------------------------------------------------------------------------
// Recursively constructs ntasks tasks to merge two arrays, Left and Right,
// into Sresult, where Left is L [pL_start...pL_end-1], Right is R
// [pR_start...pR_end-1], and Sresult is S [pS_start...pS_start+total_work-1],
// and where total_work is the total size of Left and Right.
//
// Task tid will merge L [L_task [tid] ... L_task [tid] + L_len [tid] - 1] and
// R [R_task [tid] ... R_task [tid] + R_len [tid] -1] into the merged output
// array S [S_task [tid] ... ]. The task tids created are t0 to
// t0+ntasks-1.
void GB_msort_3b_create_merge_tasks
(
// output:
int64_t *GB_RESTRICT L_task, // L_task [t0...t0+ntasks-1] computed
int64_t *GB_RESTRICT L_len, // L_len [t0...t0+ntasks-1] computed
int64_t *GB_RESTRICT R_task, // R_task [t0...t0+ntasks-1] computed
int64_t *GB_RESTRICT R_len, // R_len [t0...t0+ntasks-1] computed
int64_t *GB_RESTRICT S_task, // S_task [t0...t0+ntasks-1] computed
// input:
const int t0, // first task tid to create
const int ntasks, // # of tasks to create
const int64_t pS_start, // merge into S [pS_start...]
const int64_t *GB_RESTRICT L_0, // Left = L [pL_start...pL_end-1]
const int64_t *GB_RESTRICT L_1,
const int64_t *GB_RESTRICT L_2,
const int64_t pL_start,
const int64_t pL_end,
const int64_t *GB_RESTRICT R_0, // Right = R [pR_start...pR_end-1]
const int64_t *GB_RESTRICT R_1,
const int64_t *GB_RESTRICT R_2,
const int64_t pR_start,
const int64_t pR_end
)
{
//--------------------------------------------------------------------------
// get problem size
//--------------------------------------------------------------------------
int64_t nleft = pL_end - pL_start ; // size of Left array
int64_t nright = pR_end - pR_start ; // size of Right array
int64_t total_work = nleft + nright ; // total work to do
ASSERT (ntasks >= 1) ;
ASSERT (total_work > 0) ;
//--------------------------------------------------------------------------
// create the tasks
//--------------------------------------------------------------------------
if (ntasks == 1)
{
//----------------------------------------------------------------------
// a single task will merge all of Left and Right into Sresult
//----------------------------------------------------------------------
L_task [t0] = pL_start ; L_len [t0] = nleft ;
R_task [t0] = pR_start ; R_len [t0] = nright ;
S_task [t0] = pS_start ;
}
else
{
//----------------------------------------------------------------------
// partition the Left and Right arrays for multiple merge tasks
//----------------------------------------------------------------------
int64_t pleft, pright ;
if (nleft >= nright)
{
// split Left in half, and search for its pivot in Right
pleft = (pL_end + pL_start) >> 1 ;
pright = GB_msort_3b_binary_search (
L_0, L_1, L_2, pleft,
R_0, R_1, R_2, pR_start, pR_end) ;
}
else
{
// split Right in half, and search for its pivot in Left
pright = (pR_end + pR_start) >> 1 ;
pleft = GB_msort_3b_binary_search (
R_0, R_1, R_2, pright,
L_0, L_1, L_2, pL_start, pL_end) ;
}
//----------------------------------------------------------------------
// partition the tasks according to the work of each partition
//----------------------------------------------------------------------
// work0 is the total work in the first partition
int64_t work0 = (pleft - pL_start) + (pright - pR_start) ;
int ntasks0 = (int) round ((double) ntasks *
(((double) work0) / ((double) total_work))) ;
// ensure at least one task is assigned to each partition
ntasks0 = GB_IMAX (ntasks0, 1) ;
ntasks0 = GB_IMIN (ntasks0, ntasks-1) ;
int ntasks1 = ntasks - ntasks0 ;
//----------------------------------------------------------------------
// assign ntasks0 to the first half
//----------------------------------------------------------------------
// ntasks0 tasks merge L [pL_start...pleft-1] and R [pR_start..pright-1]
// into the result S [pS_start...work0-1].
GB_msort_3b_create_merge_tasks (
L_task, L_len, R_task, R_len, S_task, t0, ntasks0, pS_start,
L_0, L_1, L_2, pL_start, pleft,
R_0, R_1, R_2, pR_start, pright) ;
//----------------------------------------------------------------------
// assign ntasks1 to the second half
//----------------------------------------------------------------------
// ntasks1 tasks merge L [pleft...pL_end-1] and R [pright...pR_end-1]
// into the result S [pS_start+work0...pS_start+total_work].
int t1 = t0 + ntasks0 ; // first task id of the second set of tasks
int64_t pS_start1 = pS_start + work0 ; // 2nd set starts here in S
GB_msort_3b_create_merge_tasks (
L_task, L_len, R_task, R_len, S_task, t1, ntasks1, pS_start1,
L_0, L_1, L_2, pleft, pL_end,
R_0, R_1, R_2, pright, pR_end) ;
}
}
//------------------------------------------------------------------------------
// GB_msort_3b_merge: merge two sorted lists via a single thread
//------------------------------------------------------------------------------
// merge Left [0..nleft-1] and Right [0..nright-1] into S [0..nleft+nright-1] */
static void GB_msort_3b_merge
(
int64_t *GB_RESTRICT S_0, // output of length nleft + nright
int64_t *GB_RESTRICT S_1,
int64_t *GB_RESTRICT S_2,
const int64_t *GB_RESTRICT Left_0, // left input of length nleft
const int64_t *GB_RESTRICT Left_1,
const int64_t *GB_RESTRICT Left_2,
const int64_t nleft,
const int64_t *GB_RESTRICT Right_0, // right input of length nright
const int64_t *GB_RESTRICT Right_1,
const int64_t *GB_RESTRICT Right_2,
const int64_t nright
)
{
int64_t p, pleft, pright ;
// merge the two inputs, Left and Right, while both inputs exist
for (p = 0, pleft = 0, pright = 0 ; pleft < nleft && pright < nright ; p++)
{
if (GB_lt_3 (Left_0, Left_1, Left_2, pleft,
Right_0, Right_1, Right_2, pright))
{
// S [p] = Left [pleft++]
S_0 [p] = Left_0 [pleft] ;
S_1 [p] = Left_1 [pleft] ;
S_2 [p] = Left_2 [pleft] ;
pleft++ ;
}
else
{
// S [p] = Right [pright++]
S_0 [p] = Right_0 [pright] ;
S_1 [p] = Right_1 [pright] ;
S_2 [p] = Right_2 [pright] ;
pright++ ;
}
}
// either input is exhausted; copy the remaining list into S
if (pleft < nleft)
{
int64_t nremaining = (nleft - pleft) ;
memcpy (S_0 + p, Left_0 + pleft, nremaining * sizeof (int64_t)) ;
memcpy (S_1 + p, Left_1 + pleft, nremaining * sizeof (int64_t)) ;
memcpy (S_2 + p, Left_2 + pleft, nremaining * sizeof (int64_t)) ;
}
else if (pright < nright)
{
int64_t nremaining = (nright - pright) ;
memcpy (S_0 + p, Right_0 + pright, nremaining * sizeof (int64_t)) ;
memcpy (S_1 + p, Right_1 + pright, nremaining * sizeof (int64_t)) ;
memcpy (S_2 + p, Right_2 + pright, nremaining * sizeof (int64_t)) ;
}
}
//------------------------------------------------------------------------------
// GB_msort_3b: parallel mergesort
//------------------------------------------------------------------------------
GB_PUBLIC // accessed by the MATLAB tests in GraphBLAS/Test only
GrB_Info GB_msort_3b // sort array A of size 3-by-n, using 3 keys (A [0:2][])
(
int64_t *GB_RESTRICT A_0, // size n array
int64_t *GB_RESTRICT A_1, // size n array
int64_t *GB_RESTRICT A_2, // size n array
const int64_t n,
int nthreads // # of threads to use
)
{
//--------------------------------------------------------------------------
// handle small problems with a single thread
//--------------------------------------------------------------------------
if (nthreads <= 1 || n <= GB_BASECASE)
{
// sequential quicksort
GB_qsort_3 (A_0, A_1, A_2, n) ;
return (GrB_SUCCESS) ;
}
//--------------------------------------------------------------------------
// determine # of tasks
//--------------------------------------------------------------------------
// determine the number of levels to create, which must always be an
// even number. The # of levels is chosen to ensure that the # of leaves
// of the task tree is between 4*nthreads and 16*nthreads.
// 2 to 4 threads: 4 levels, 16 qsort leaves
// 5 to 16 threads: 6 levels, 64 qsort leaves
// 17 to 64 threads: 8 levels, 256 qsort leaves
// 65 to 256 threads: 10 levels, 1024 qsort leaves
// 256 to 1024 threads: 12 levels, 4096 qsort leaves
// ...
int k = (int) (2 + 2 * ceil (log2 ((double) nthreads) / 2)) ;
int ntasks = 1 << k ;
//--------------------------------------------------------------------------
// allocate workspace
//--------------------------------------------------------------------------
int64_t *GB_RESTRICT W = GB_MALLOC (3*n + 6*ntasks + 1, int64_t) ;
if (W == NULL)
{
// out of memory
return (GrB_OUT_OF_MEMORY) ;
}
int64_t *T = W ;
int64_t *GB_RESTRICT W_0 = T ; T += n ;
int64_t *GB_RESTRICT W_1 = T ; T += n ;
int64_t *GB_RESTRICT W_2 = T ; T += n ;
int64_t *GB_RESTRICT L_task = T ; T += ntasks ;
int64_t *GB_RESTRICT L_len = T ; T += ntasks ;
int64_t *GB_RESTRICT R_task = T ; T += ntasks ;
int64_t *GB_RESTRICT R_len = T ; T += ntasks ;
int64_t *GB_RESTRICT S_task = T ; T += ntasks ;
int64_t *GB_RESTRICT Slice = T ; T += (ntasks+1) ;
//--------------------------------------------------------------------------
// partition and sort the leaves
//--------------------------------------------------------------------------
GB_eslice (Slice, n, ntasks) ;
int tid ;
#pragma omp parallel for num_threads(nthreads) schedule(dynamic,1)
for (tid = 0 ; tid < ntasks ; tid++)
{
int64_t leaf = Slice [tid] ;
int64_t leafsize = Slice [tid+1] - leaf ;
GB_qsort_3 (A_0 + leaf, A_1 + leaf, A_2 + leaf, leafsize) ;
}
//--------------------------------------------------------------------------
// merge each level
//--------------------------------------------------------------------------
int nt = 1 ;
for ( ; k >= 2 ; k -= 2)
{
//----------------------------------------------------------------------
// merge level k into level k-1, from A into W
//----------------------------------------------------------------------
// this could be done in parallel if ntasks was large
for (int tid = 0 ; tid < ntasks ; tid += 2*nt)
{
// create 2*nt tasks to merge two A sublists into one W sublist
GB_msort_3b_create_merge_tasks (
L_task, L_len, R_task, R_len, S_task, tid, 2*nt, Slice [tid],
A_0, A_1, A_2, Slice [tid], Slice [tid+nt],
A_0, A_1, A_2, Slice [tid+nt], Slice [tid+2*nt]) ;
}
#pragma omp parallel for num_threads(nthreads) schedule(dynamic,1)
for (tid = 0 ; tid < ntasks ; tid++)
{
// merge A [pL...pL+nL-1] and A [pR...pR+nR-1] into W [pS..]
int64_t pL = L_task [tid], nL = L_len [tid] ;
int64_t pR = R_task [tid], nR = R_len [tid] ;
int64_t pS = S_task [tid] ;
GB_msort_3b_merge (
W_0 + pS, W_1 + pS, W_2 + pS,
A_0 + pL, A_1 + pL, A_2 + pL, nL,
A_0 + pR, A_1 + pR, A_2 + pR, nR) ;
}
nt = 2*nt ;
//----------------------------------------------------------------------
// merge level k-1 into level k-2, from W into A
//----------------------------------------------------------------------
// this could be done in parallel if ntasks was large
for (int tid = 0 ; tid < ntasks ; tid += 2*nt)
{
// create 2*nt tasks to merge two W sublists into one A sublist
GB_msort_3b_create_merge_tasks (
L_task, L_len, R_task, R_len, S_task, tid, 2*nt, Slice [tid],
W_0, W_1, W_2, Slice [tid], Slice [tid+nt],
W_0, W_1, W_2, Slice [tid+nt], Slice [tid+2*nt]) ;
}
#pragma omp parallel for num_threads(nthreads) schedule(dynamic,1)
for (tid = 0 ; tid < ntasks ; tid++)
{
// merge A [pL...pL+nL-1] and A [pR...pR+nR-1] into W [pS..]
int64_t pL = L_task [tid], nL = L_len [tid] ;
int64_t pR = R_task [tid], nR = R_len [tid] ;
int64_t pS = S_task [tid] ;
GB_msort_3b_merge (
A_0 + pS, A_1 + pS, A_2 + pS,
W_0 + pL, W_1 + pL, W_2 + pL, nL,
W_0 + pR, W_1 + pR, W_2 + pR, nR) ;
}
nt = 2*nt ;
}
//--------------------------------------------------------------------------
// free workspace and return resulte
//--------------------------------------------------------------------------
GB_FREE (W) ;
return (GrB_SUCCESS) ;
}
|
convolution_1x1_pack4.h | // Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// 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.
static void conv1x1s1_sgemm_pack4_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt)
{
int w = bottom_blob.w;
int h = bottom_blob.h;
int inch = bottom_blob.c;
int outch = top_blob.c;
size_t elemsize = bottom_blob.elemsize;
int elempack = bottom_blob.elempack;
const int size = w * h;
const float* bias = _bias;
// interleave
#if __aarch64__
Mat tmp(12, inch, size/12 + (size%12)/8 + (size%8)/4 + (size%4)/2 + size%2, elemsize, elempack, opt.workspace_allocator);
#else
Mat tmp(8, inch, size/8 + (size%8)/4 + (size%4)/2 + size%2, elemsize, elempack, opt.workspace_allocator);
#endif
{
int nn_size;
int remain_size_start;
#if __aarch64__
nn_size = size / 12;
remain_size_start = nn_size * 12;
#pragma omp parallel for num_threads(opt.num_threads)
for (int ii=0; ii<nn_size; ii++)
{
int i = ii * 12;
const float* img0 = bottom_blob.channel(0);
img0 += i*4;
float* tmpptr = tmp.channel(i/12);
for (int q=0; q<inch; q++)
{
asm volatile(
"prfm pldl1keep, [%0, #512] \n"
"ld4 {v0.4s, v1.4s, v2.4s, v3.4s}, [%0], #64 \n"
"prfm pldl1keep, [%0, #512] \n"
"ld4 {v4.4s, v5.4s, v6.4s, v7.4s}, [%0], #64 \n"
"prfm pldl1keep, [%0, #512] \n"
"ld4 {v8.4s, v9.4s, v10.4s, v11.4s}, [%0] \n"
"st1 {v0.4s}, [%1], #16 \n"
"st1 {v4.4s}, [%1], #16 \n"
"st1 {v8.4s}, [%1], #16 \n"
"sub %0, %0, #128 \n"
"st1 {v1.4s}, [%1], #16 \n"
"st1 {v5.4s}, [%1], #16 \n"
"st1 {v9.4s}, [%1], #16 \n"
"st1 {v2.4s}, [%1], #16 \n"
"st1 {v6.4s}, [%1], #16 \n"
"st1 {v10.4s}, [%1], #16 \n"
"st1 {v3.4s}, [%1], #16 \n"
"st1 {v7.4s}, [%1], #16 \n"
"st1 {v11.4s}, [%1], #16 \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11"
);
img0 += bottom_blob.cstep * 4;
}
}
#else
remain_size_start = 0;
#endif
nn_size = (size - remain_size_start) >> 3;
#pragma omp parallel for num_threads(opt.num_threads)
for (int ii=0; ii<nn_size; ii++)
{
int i = remain_size_start + ii * 8;
const float* img0 = bottom_blob.channel(0);
img0 += i*4;
#if __aarch64__
float* tmpptr = tmp.channel(i/12+(i%12)/8);
#else
float* tmpptr = tmp.channel(i/8);
#endif
for (int q=0; q<inch; q++)
{
#if __aarch64__
asm volatile(
"prfm pldl1keep, [%0, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%0], #64 \n"
"prfm pldl1keep, [%0, #512] \n"
"ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%0] \n"
"st1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%1], #64 \n"
"sub %0, %0, #64 \n"
"st1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%1], #64 \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7"
);
#else
asm volatile(
"pld [%0, #512] \n"
"vldm %0!, {d0-d7} \n"
"pld [%0, #512] \n"
"vldm %0, {d16-d23} \n"
// transpose 8x4
"vtrn.32 q0, q1 \n"
"vtrn.32 q2, q3 \n"
"vtrn.32 q8, q9 \n"
"vtrn.32 q10, q11 \n"
"vswp d1, d4 \n"
"vswp d3, d6 \n"
"vswp d17, d20 \n"
"vswp d19, d22 \n"
"vswp q1, q8 \n"
"vswp q3, q10 \n"
"vst1.f32 {d0-d3}, [%1 :128]! \n"
"vst1.f32 {d16-d19}, [%1 :128]! \n"
"sub %0, %0, #64 \n"
"vst1.f32 {d4-d7}, [%1 :128]! \n"
"vst1.f32 {d20-d23}, [%1 :128]! \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "memory", "q0", "q1", "q2", "q3", "q8", "q9", "q10", "q11"
);
#endif // __aarch64__
img0 += bottom_blob.cstep * 4;
}
}
remain_size_start += nn_size << 3;
nn_size = (size - remain_size_start) >> 2;
#pragma omp parallel for num_threads(opt.num_threads)
for (int ii=0; ii<nn_size; ii++)
{
int i = remain_size_start + ii * 4;
const float* img0 = bottom_blob.channel(0);
img0 += i*4;
#if __aarch64__
float* tmpptr = tmp.channel(i/12 + (i%12)/8 + (i%8)/4);
#else
float* tmpptr = tmp.channel(i/8 + (i%8)/4);
#endif
for (int q=0; q<inch; q++)
{
#if __aarch64__
asm volatile(
"prfm pldl1keep, [%0, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%0] \n"
"st1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%1], #64 \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "memory", "v0", "v1", "v2", "v3"
);
#else
asm volatile(
"pld [%0, #512] \n"
"vldm %0, {d0-d7} \n"
"vstm %1!, {d0-d7} \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "memory", "q0", "q1", "q2", "q3"
);
#endif // __aarch64__
img0 += bottom_blob.cstep * 4;
}
}
remain_size_start += nn_size << 2;
nn_size = (size - remain_size_start) >> 1;
#pragma omp parallel for num_threads(opt.num_threads)
for (int ii=0; ii<nn_size; ii++)
{
int i = remain_size_start + ii * 2;
const float* img0 = bottom_blob.channel(0);
img0 += i*4;
#if __aarch64__
float* tmpptr = tmp.channel(i/12 + (i%12)/8 + (i%8)/4 + (i%4)/2);
#else
float* tmpptr = tmp.channel(i/8 + (i%8)/4 + (i%4)/2);
#endif
for (int q=0; q<inch; q++)
{
#if __aarch64__
asm volatile(
"prfm pldl1keep, [%0, #256] \n"
"ld1 {v0.4s, v1.4s}, [%0] \n"
"st1 {v0.4s, v1.4s}, [%1], #32 \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "memory", "v0", "v1"
);
#else
asm volatile(
"pld [%0, #256] \n"
"vld1.f32 {d0-d3}, [%0 :128] \n"
"vst1.f32 {d0-d3}, [%1 :128]! \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "memory", "q0", "q1"
);
#endif // __aarch64__
img0 += bottom_blob.cstep * 4;
}
}
remain_size_start += nn_size << 1;
#pragma omp parallel for num_threads(opt.num_threads)
for (int i=remain_size_start; i<size; i++)
{
const float* img0 = bottom_blob.channel(0);
img0 += i*4;
#if __aarch64__
float* tmpptr = tmp.channel(i/12 + (i%12)/8 + (i%8)/4 + (i%4)/2 + i%2);
#else
float* tmpptr = tmp.channel(i/8 + (i%8)/4 + (i%4)/2 + i%2);
#endif
for (int q=0; q<inch; q++)
{
#if __aarch64__
asm volatile(
"prfm pldl1keep, [%0, #128] \n"
"ld1 {v0.4s}, [%0] \n"
"st1 {v0.4s}, [%1], #16 \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "memory", "v0"
);
#else
asm volatile(
"pld [%0, #128] \n"
"vld1.f32 {d0-d1}, [%0 :128] \n"
"vst1.f32 {d0-d1}, [%1 :128]! \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "memory", "q0"
);
#endif // __aarch64__
img0 += bottom_blob.cstep * 4;
}
}
}
int nn_outch = 0;
int remain_outch_start = 0;
#if __ARM_NEON && __aarch64__
nn_outch = outch >> 1;
remain_outch_start = nn_outch << 1;
#pragma omp parallel for num_threads(opt.num_threads)
for (int pp=0; pp<nn_outch; pp++)
{
int p = pp * 2;
float* outptr0 = top_blob.channel(p);
float* outptr1 = top_blob.channel(p+1);
const float zeros[8] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f};
const float* biasptr = bias ? bias + p * 4 : zeros;
int i=0;
for (; i+11<size; i+=12)
{
const float* tmpptr = tmp.channel(i/12);
const float* kptr0 = (const float*)kernel + p * inch * 16;
const float* kptr1 = (const float*)kernel + (p+1) * inch * 16;
int nn = inch;// inch always > 0
asm volatile(
"ld1 {v0.4s, v1.4s}, [%12] \n"
"mov v8.16b, v0.16b \n"
"mov v9.16b, v0.16b \n"
"mov v10.16b, v0.16b \n"
"mov v11.16b, v0.16b \n"
"mov v12.16b, v0.16b \n"
"mov v13.16b, v0.16b \n"
"mov v14.16b, v0.16b \n"
"mov v15.16b, v0.16b \n"
"mov v16.16b, v0.16b \n"
"mov v17.16b, v0.16b \n"
"mov v18.16b, v0.16b \n"
"mov v19.16b, v0.16b \n"
"mov v20.16b, v1.16b \n"
"mov v21.16b, v1.16b \n"
"mov v22.16b, v1.16b \n"
"mov v23.16b, v1.16b \n"
"mov v24.16b, v1.16b \n"
"mov v25.16b, v1.16b \n"
"mov v26.16b, v1.16b \n"
"mov v27.16b, v1.16b \n"
"mov v28.16b, v1.16b \n"
"mov v29.16b, v1.16b \n"
"mov v30.16b, v1.16b \n"
"mov v31.16b, v1.16b \n"
"0: \n"
"prfm pldl1keep, [%3, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%3], #64 \n"
"prfm pldl1keep, [%4, #128] \n"
"ld1 {v4.4s, v5.4s}, [%4], #32 \n"// w0123_0
"prfm pldl1keep, [%5, #128] \n"
"ld1 {v6.4s, v7.4s}, [%5], #32 \n"// w0123_1
"fmla v8.4s, v4.4s, v0.s[0] \n"
"fmla v9.4s, v4.4s, v0.s[1] \n"
"fmla v10.4s, v4.4s, v0.s[2] \n"
"fmla v11.4s, v4.4s, v0.s[3] \n"
"fmla v12.4s, v4.4s, v1.s[0] \n"
"fmla v13.4s, v4.4s, v1.s[1] \n"
"fmla v14.4s, v4.4s, v1.s[2] \n"
"fmla v15.4s, v4.4s, v1.s[3] \n"
"fmla v16.4s, v4.4s, v2.s[0] \n"
"fmla v17.4s, v4.4s, v2.s[1] \n"
"fmla v18.4s, v4.4s, v2.s[2] \n"
"fmla v19.4s, v4.4s, v2.s[3] \n"
"fmla v20.4s, v6.4s, v0.s[0] \n"
"fmla v21.4s, v6.4s, v0.s[1] \n"
"fmla v22.4s, v6.4s, v0.s[2] \n"
"fmla v23.4s, v6.4s, v0.s[3] \n"
"fmla v24.4s, v6.4s, v1.s[0] \n"
"fmla v25.4s, v6.4s, v1.s[1] \n"
"fmla v26.4s, v6.4s, v1.s[2] \n"
"fmla v27.4s, v6.4s, v1.s[3] \n"
"fmla v28.4s, v6.4s, v2.s[0] \n"
"fmla v29.4s, v6.4s, v2.s[1] \n"
"fmla v30.4s, v6.4s, v2.s[2] \n"
"fmla v31.4s, v6.4s, v2.s[3] \n"
"fmla v8.4s, v5.4s, v3.s[0] \n"
"fmla v9.4s, v5.4s, v3.s[1] \n"
"fmla v10.4s, v5.4s, v3.s[2] \n"
"fmla v11.4s, v5.4s, v3.s[3] \n"
"fmla v20.4s, v7.4s, v3.s[0] \n"
"fmla v21.4s, v7.4s, v3.s[1] \n"
"fmla v22.4s, v7.4s, v3.s[2] \n"
"fmla v23.4s, v7.4s, v3.s[3] \n"
"prfm pldl1keep, [%3, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%3], #64 \n"
"fmla v12.4s, v5.4s, v0.s[0] \n"
"fmla v13.4s, v5.4s, v0.s[1] \n"
"fmla v14.4s, v5.4s, v0.s[2] \n"
"fmla v15.4s, v5.4s, v0.s[3] \n"
"fmla v16.4s, v5.4s, v1.s[0] \n"
"fmla v17.4s, v5.4s, v1.s[1] \n"
"fmla v18.4s, v5.4s, v1.s[2] \n"
"fmla v19.4s, v5.4s, v1.s[3] \n"
"fmla v24.4s, v7.4s, v0.s[0] \n"
"fmla v25.4s, v7.4s, v0.s[1] \n"
"fmla v26.4s, v7.4s, v0.s[2] \n"
"fmla v27.4s, v7.4s, v0.s[3] \n"
"fmla v28.4s, v7.4s, v1.s[0] \n"
"fmla v29.4s, v7.4s, v1.s[1] \n"
"fmla v30.4s, v7.4s, v1.s[2] \n"
"fmla v31.4s, v7.4s, v1.s[3] \n"
"prfm pldl1keep, [%4, #128] \n"
"ld1 {v4.4s, v5.4s}, [%4], #32 \n"// w0123_0
"prfm pldl1keep, [%5, #128] \n"
"ld1 {v6.4s, v7.4s}, [%5], #32 \n"// w0123_1
"fmla v8.4s, v4.4s, v2.s[0] \n"
"fmla v9.4s, v4.4s, v2.s[1] \n"
"fmla v10.4s, v4.4s, v2.s[2] \n"
"fmla v11.4s, v4.4s, v2.s[3] \n"
"fmla v12.4s, v4.4s, v3.s[0] \n"
"fmla v13.4s, v4.4s, v3.s[1] \n"
"fmla v14.4s, v4.4s, v3.s[2] \n"
"fmla v15.4s, v4.4s, v3.s[3] \n"
"fmla v20.4s, v6.4s, v2.s[0] \n"
"fmla v21.4s, v6.4s, v2.s[1] \n"
"fmla v22.4s, v6.4s, v2.s[2] \n"
"fmla v23.4s, v6.4s, v2.s[3] \n"
"fmla v24.4s, v6.4s, v3.s[0] \n"
"fmla v25.4s, v6.4s, v3.s[1] \n"
"fmla v26.4s, v6.4s, v3.s[2] \n"
"fmla v27.4s, v6.4s, v3.s[3] \n"
"prfm pldl1keep, [%3, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%3], #64 \n"
"fmla v16.4s, v4.4s, v0.s[0] \n"
"fmla v17.4s, v4.4s, v0.s[1] \n"
"fmla v18.4s, v4.4s, v0.s[2] \n"
"fmla v19.4s, v4.4s, v0.s[3] \n"
"fmla v28.4s, v6.4s, v0.s[0] \n"
"fmla v29.4s, v6.4s, v0.s[1] \n"
"fmla v30.4s, v6.4s, v0.s[2] \n"
"fmla v31.4s, v6.4s, v0.s[3] \n"
"fmla v8.4s, v5.4s, v1.s[0] \n"
"fmla v9.4s, v5.4s, v1.s[1] \n"
"fmla v10.4s, v5.4s, v1.s[2] \n"
"fmla v11.4s, v5.4s, v1.s[3] \n"
"fmla v12.4s, v5.4s, v2.s[0] \n"
"fmla v13.4s, v5.4s, v2.s[1] \n"
"fmla v14.4s, v5.4s, v2.s[2] \n"
"fmla v15.4s, v5.4s, v2.s[3] \n"
"fmla v16.4s, v5.4s, v3.s[0] \n"
"fmla v17.4s, v5.4s, v3.s[1] \n"
"fmla v18.4s, v5.4s, v3.s[2] \n"
"fmla v19.4s, v5.4s, v3.s[3] \n"
"subs %w0, %w0, #1 \n"
"fmla v20.4s, v7.4s, v1.s[0] \n"
"fmla v21.4s, v7.4s, v1.s[1] \n"
"fmla v22.4s, v7.4s, v1.s[2] \n"
"fmla v23.4s, v7.4s, v1.s[3] \n"
"fmla v24.4s, v7.4s, v2.s[0] \n"
"fmla v25.4s, v7.4s, v2.s[1] \n"
"fmla v26.4s, v7.4s, v2.s[2] \n"
"fmla v27.4s, v7.4s, v2.s[3] \n"
"fmla v28.4s, v7.4s, v3.s[0] \n"
"fmla v29.4s, v7.4s, v3.s[1] \n"
"fmla v30.4s, v7.4s, v3.s[2] \n"
"fmla v31.4s, v7.4s, v3.s[3] \n"
"bne 0b \n"
"st1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%1], #64 \n"
"st1 {v20.4s, v21.4s, v22.4s, v23.4s}, [%2], #64 \n"
"st1 {v12.4s, v13.4s, v14.4s, v15.4s}, [%1], #64 \n"
"st1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%2], #64 \n"
"st1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%1], #64 \n"
"st1 {v28.4s, v29.4s, v30.4s, v31.4s}, [%2], #64 \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr1), // %2
"=r"(tmpptr), // %3
"=r"(kptr0), // %4
"=r"(kptr1) // %5
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(tmpptr),
"4"(kptr0),
"5"(kptr1),
"r"(biasptr) // %12
: "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31"
);
}
for (; i+7<size; i+=8)
{
float* tmpptr = tmp.channel(i/12+(i%12)/8);
const float* kptr0 = (const float*)kernel + p * inch * 16;
const float* kptr1 = (const float*)kernel + (p+1) * inch * 16;
int nn = inch;// inch always > 0
asm volatile(
"ld1 {v0.4s, v1.4s}, [%12] \n"
"mov v16.16b, v0.16b \n"
"mov v17.16b, v0.16b \n"
"mov v18.16b, v0.16b \n"
"mov v19.16b, v0.16b \n"
"mov v20.16b, v0.16b \n"
"mov v21.16b, v0.16b \n"
"mov v22.16b, v0.16b \n"
"mov v23.16b, v0.16b \n"
"mov v24.16b, v1.16b \n"
"mov v25.16b, v1.16b \n"
"mov v26.16b, v1.16b \n"
"mov v27.16b, v1.16b \n"
"mov v28.16b, v1.16b \n"
"mov v29.16b, v1.16b \n"
"mov v30.16b, v1.16b \n"
"mov v31.16b, v1.16b \n"
"0: \n"
"prfm pldl1keep, [%3, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%3], #64 \n"// r0 r1 r2 r3
"prfm pldl1keep, [%4, #512] \n"
"ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%4], #64 \n"// w0123_0
"fmla v16.4s, v8.4s, v0.s[0] \n"
"fmla v17.4s, v8.4s, v1.s[0] \n"
"fmla v18.4s, v8.4s, v2.s[0] \n"
"fmla v19.4s, v8.4s, v3.s[0] \n"
"prfm pldl1keep, [%3, #512] \n"
"ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%3], #64 \n"// r4 r5 r6 r7
"fmla v20.4s, v8.4s, v4.s[0] \n"
"fmla v21.4s, v8.4s, v5.s[0] \n"
"fmla v22.4s, v8.4s, v6.s[0] \n"
"fmla v23.4s, v8.4s, v7.s[0] \n"
"fmla v16.4s, v9.4s, v0.s[1] \n"
"fmla v17.4s, v9.4s, v1.s[1] \n"
"fmla v18.4s, v9.4s, v2.s[1] \n"
"fmla v19.4s, v9.4s, v3.s[1] \n"
"fmla v20.4s, v9.4s, v4.s[1] \n"
"fmla v21.4s, v9.4s, v5.s[1] \n"
"fmla v22.4s, v9.4s, v6.s[1] \n"
"fmla v23.4s, v9.4s, v7.s[1] \n"
"fmla v16.4s, v10.4s, v0.s[2] \n"
"fmla v17.4s, v10.4s, v1.s[2] \n"
"fmla v18.4s, v10.4s, v2.s[2] \n"
"fmla v19.4s, v10.4s, v3.s[2] \n"
"fmla v20.4s, v10.4s, v4.s[2] \n"
"fmla v21.4s, v10.4s, v5.s[2] \n"
"fmla v22.4s, v10.4s, v6.s[2] \n"
"fmla v23.4s, v10.4s, v7.s[2] \n"
"prfm pldl1keep, [%5, #512] \n"
"ld1 {v12.4s, v13.4s, v14.4s, v15.4s}, [%5], #64 \n"// w0123_1
"fmla v16.4s, v11.4s, v0.s[3] \n"
"fmla v17.4s, v11.4s, v1.s[3] \n"
"fmla v18.4s, v11.4s, v2.s[3] \n"
"fmla v19.4s, v11.4s, v3.s[3] \n"
"fmla v20.4s, v11.4s, v4.s[3] \n"
"fmla v21.4s, v11.4s, v5.s[3] \n"
"fmla v22.4s, v11.4s, v6.s[3] \n"
"fmla v23.4s, v11.4s, v7.s[3] \n"
"fmla v24.4s, v12.4s, v0.s[0] \n"
"fmla v25.4s, v12.4s, v1.s[0] \n"
"fmla v26.4s, v12.4s, v2.s[0] \n"
"fmla v27.4s, v12.4s, v3.s[0] \n"
"fmla v28.4s, v12.4s, v4.s[0] \n"
"fmla v29.4s, v12.4s, v5.s[0] \n"
"fmla v30.4s, v12.4s, v6.s[0] \n"
"fmla v31.4s, v12.4s, v7.s[0] \n"
"fmla v24.4s, v13.4s, v0.s[1] \n"
"fmla v25.4s, v13.4s, v1.s[1] \n"
"fmla v26.4s, v13.4s, v2.s[1] \n"
"fmla v27.4s, v13.4s, v3.s[1] \n"
"fmla v28.4s, v13.4s, v4.s[1] \n"
"fmla v29.4s, v13.4s, v5.s[1] \n"
"fmla v30.4s, v13.4s, v6.s[1] \n"
"fmla v31.4s, v13.4s, v7.s[1] \n"
"fmla v24.4s, v14.4s, v0.s[2] \n"
"fmla v25.4s, v14.4s, v1.s[2] \n"
"fmla v26.4s, v14.4s, v2.s[2] \n"
"fmla v27.4s, v14.4s, v3.s[2] \n"
"fmla v28.4s, v14.4s, v4.s[2] \n"
"fmla v29.4s, v14.4s, v5.s[2] \n"
"fmla v30.4s, v14.4s, v6.s[2] \n"
"fmla v31.4s, v14.4s, v7.s[2] \n"
"subs %w0, %w0, #1 \n"
"fmla v24.4s, v15.4s, v0.s[3] \n"
"fmla v25.4s, v15.4s, v1.s[3] \n"
"fmla v26.4s, v15.4s, v2.s[3] \n"
"fmla v27.4s, v15.4s, v3.s[3] \n"
"fmla v28.4s, v15.4s, v4.s[3] \n"
"fmla v29.4s, v15.4s, v5.s[3] \n"
"fmla v30.4s, v15.4s, v6.s[3] \n"
"fmla v31.4s, v15.4s, v7.s[3] \n"
"bne 0b \n"
"st1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%1], #64 \n"
"st1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%2], #64 \n"
"st1 {v20.4s, v21.4s, v22.4s, v23.4s}, [%1], #64 \n"
"st1 {v28.4s, v29.4s, v30.4s, v31.4s}, [%2], #64 \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr1), // %2
"=r"(tmpptr), // %3
"=r"(kptr0), // %4
"=r"(kptr1) // %5
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(tmpptr),
"4"(kptr0),
"5"(kptr1),
"r"(biasptr) // %12
: "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31"
);
}
for (; i+3<size; i+=4)
{
float* tmpptr = tmp.channel(i/12 + (i%12)/8 + (i%8)/4);
const float* kptr0 = (const float*)kernel + p * inch * 16;
const float* kptr1 = (const float*)kernel + (p+1) * inch * 16;
int nn = inch;// inch always > 0
asm volatile(
"ld1 {v0.4s, v1.4s}, [%12] \n"
"mov v16.16b, v0.16b \n"
"mov v17.16b, v0.16b \n"
"mov v18.16b, v0.16b \n"
"mov v19.16b, v0.16b \n"
"mov v20.16b, v1.16b \n"
"mov v21.16b, v1.16b \n"
"mov v22.16b, v1.16b \n"
"mov v23.16b, v1.16b \n"
"0: \n"
"prfm pldl1keep, [%3, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%3], #64 \n"// r0 r1 r2 r3
"prfm pldl1keep, [%4, #512] \n"
"ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%4], #64 \n"// w0123_0
"fmla v16.4s, v8.4s, v0.s[0] \n"
"fmla v17.4s, v8.4s, v1.s[0] \n"
"fmla v18.4s, v8.4s, v2.s[0] \n"
"fmla v19.4s, v8.4s, v3.s[0] \n"
"prfm pldl1keep, [%5, #512] \n"
"ld1 {v12.4s, v13.4s, v14.4s, v15.4s}, [%5], #64 \n"// w0123_1
"fmla v20.4s, v12.4s, v0.s[0] \n"
"fmla v21.4s, v12.4s, v1.s[0] \n"
"fmla v22.4s, v12.4s, v2.s[0] \n"
"fmla v23.4s, v12.4s, v3.s[0] \n"
"fmla v16.4s, v9.4s, v0.s[1] \n"
"fmla v17.4s, v9.4s, v1.s[1] \n"
"fmla v18.4s, v9.4s, v2.s[1] \n"
"fmla v19.4s, v9.4s, v3.s[1] \n"
"fmla v20.4s, v13.4s, v0.s[1] \n"
"fmla v21.4s, v13.4s, v1.s[1] \n"
"fmla v22.4s, v13.4s, v2.s[1] \n"
"fmla v23.4s, v13.4s, v3.s[1] \n"
"fmla v16.4s, v10.4s, v0.s[2] \n"
"fmla v17.4s, v10.4s, v1.s[2] \n"
"fmla v18.4s, v10.4s, v2.s[2] \n"
"fmla v19.4s, v10.4s, v3.s[2] \n"
"fmla v20.4s, v14.4s, v0.s[2] \n"
"fmla v21.4s, v14.4s, v1.s[2] \n"
"fmla v22.4s, v14.4s, v2.s[2] \n"
"fmla v23.4s, v14.4s, v3.s[2] \n"
"subs %w0, %w0, #1 \n"
"fmla v16.4s, v11.4s, v0.s[3] \n"
"fmla v17.4s, v11.4s, v1.s[3] \n"
"fmla v18.4s, v11.4s, v2.s[3] \n"
"fmla v19.4s, v11.4s, v3.s[3] \n"
"fmla v20.4s, v15.4s, v0.s[3] \n"
"fmla v21.4s, v15.4s, v1.s[3] \n"
"fmla v22.4s, v15.4s, v2.s[3] \n"
"fmla v23.4s, v15.4s, v3.s[3] \n"
"bne 0b \n"
"st1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%1], #64 \n"
"st1 {v20.4s, v21.4s, v22.4s, v23.4s}, [%2], #64 \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr1), // %2
"=r"(tmpptr), // %3
"=r"(kptr0), // %4
"=r"(kptr1) // %5
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(tmpptr),
"4"(kptr0),
"5"(kptr1),
"r"(biasptr) // %12
: "cc", "memory", "v0", "v1", "v2", "v3", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23"
);
}
for (; i+1<size; i+=2)
{
float* tmpptr = tmp.channel(i/12 + (i%12)/8 + (i%8)/4 + (i%4)/2);
const float* kptr0 = (const float*)kernel + p * inch * 16;
const float* kptr1 = (const float*)kernel + (p+1) * inch * 16;
int nn = inch;// inch always > 0
asm volatile(
"ld1 {v0.4s, v1.4s}, [%12] \n"
"mov v16.16b, v0.16b \n"
"mov v17.16b, v0.16b \n"
"mov v18.16b, v1.16b \n"
"mov v19.16b, v1.16b \n"
"0: \n"
"prfm pldl1keep, [%3, #256] \n"
"ld1 {v0.4s, v1.4s}, [%3], #32 \n"// r0 r1
"prfm pldl1keep, [%4, #512] \n"
"ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%4], #64 \n"// w0123_0
"fmla v16.4s, v8.4s, v0.s[0] \n"
"fmla v17.4s, v8.4s, v1.s[0] \n"
"prfm pldl1keep, [%5, #512] \n"
"ld1 {v12.4s, v13.4s, v14.4s, v15.4s}, [%5], #64 \n"// w0123_1
"fmla v18.4s, v12.4s, v0.s[0] \n"
"fmla v19.4s, v12.4s, v1.s[0] \n"
"fmla v16.4s, v9.4s, v0.s[1] \n"
"fmla v17.4s, v9.4s, v1.s[1] \n"
"fmla v18.4s, v13.4s, v0.s[1] \n"
"fmla v19.4s, v13.4s, v1.s[1] \n"
"fmla v16.4s, v10.4s, v0.s[2] \n"
"fmla v17.4s, v10.4s, v1.s[2] \n"
"fmla v18.4s, v14.4s, v0.s[2] \n"
"fmla v19.4s, v14.4s, v1.s[2] \n"
"subs %w0, %w0, #1 \n"
"fmla v16.4s, v11.4s, v0.s[3] \n"
"fmla v17.4s, v11.4s, v1.s[3] \n"
"fmla v18.4s, v15.4s, v0.s[3] \n"
"fmla v19.4s, v15.4s, v1.s[3] \n"
"bne 0b \n"
"st1 {v16.4s, v17.4s}, [%1], #32 \n"
"st1 {v18.4s, v19.4s}, [%2], #32 \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr1), // %2
"=r"(tmpptr), // %3
"=r"(kptr0), // %4
"=r"(kptr1) // %5
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(tmpptr),
"4"(kptr0),
"5"(kptr1),
"r"(biasptr) // %12
: "cc", "memory", "v0", "v1", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19"
);
}
for (; i<size; i++)
{
float* tmpptr = tmp.channel(i/12 + (i%12)/8 + (i%8)/4 + (i%4)/2 + i%2);
const float* kptr0 = (const float*)kernel + p * inch * 16;
const float* kptr1 = (const float*)kernel + (p+1) * inch * 16;
int nn = inch;// inch always > 0
asm volatile(
"ld1 {v16.4s, v17.4s}, [%12] \n"
"0: \n"
"prfm pldl1keep, [%3, #128] \n"
"ld1 {v0.4s}, [%3], #16 \n"// r0
"prfm pldl1keep, [%4, #512] \n"
"ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%4], #64 \n"// w0123_0
"fmla v16.4s, v8.4s, v0.s[0] \n"
"prfm pldl1keep, [%5, #512] \n"
"ld1 {v12.4s, v13.4s, v14.4s, v15.4s}, [%5], #64 \n"// w0123_1
"fmla v17.4s, v12.4s, v0.s[0] \n"
"fmla v16.4s, v9.4s, v0.s[1] \n"
"fmla v17.4s, v13.4s, v0.s[1] \n"
"fmla v16.4s, v10.4s, v0.s[2] \n"
"fmla v17.4s, v14.4s, v0.s[2] \n"
"subs %w0, %w0, #1 \n"
"fmla v16.4s, v11.4s, v0.s[3] \n"
"fmla v17.4s, v15.4s, v0.s[3] \n"
"bne 0b \n"
"st1 {v16.4s}, [%1], #16 \n"
"st1 {v17.4s}, [%2], #16 \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr1), // %2
"=r"(tmpptr), // %3
"=r"(kptr0), // %4
"=r"(kptr1) // %5
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(tmpptr),
"4"(kptr0),
"5"(kptr1),
"r"(biasptr) // %12
: "cc", "memory", "v0", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17"
);
}
}
#endif // __ARM_NEON && __aarch64__
#pragma omp parallel for num_threads(opt.num_threads)
for (int p=remain_outch_start; p<outch; p++)
{
float* outptr0 = top_blob.channel(p);
const float zeros[4] = {0.f, 0.f, 0.f, 0.f};
const float* biasptr = bias ? bias + p * 4 : zeros;
int i=0;
#if __aarch64__
for (; i+11<size; i+=12)
{
float* tmpptr = tmp.channel(i/12);
const float* kptr0 = (const float*)kernel + p * inch * 16;
int nn = inch;// inch always > 0
asm volatile(
"ld1 {v0.4s}, [%8] \n"
"mov v8.16b, v0.16b \n"
"mov v9.16b, v0.16b \n"
"mov v10.16b, v0.16b \n"
"mov v11.16b, v0.16b \n"
"mov v12.16b, v0.16b \n"
"mov v13.16b, v0.16b \n"
"mov v14.16b, v0.16b \n"
"mov v15.16b, v0.16b \n"
"mov v16.16b, v0.16b \n"
"mov v17.16b, v0.16b \n"
"mov v18.16b, v0.16b \n"
"mov v19.16b, v0.16b \n"
"0: \n"
"prfm pldl1keep, [%2, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%2], #64 \n"
"prfm pldl1keep, [%3, #512] \n"
"ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%3], #64 \n"// w0123_0
"fmla v8.4s, v4.4s, v0.s[0] \n"
"fmla v9.4s, v4.4s, v0.s[1] \n"
"fmla v10.4s, v4.4s, v0.s[2] \n"
"fmla v11.4s, v4.4s, v0.s[3] \n"
"fmla v12.4s, v4.4s, v1.s[0] \n"
"fmla v13.4s, v4.4s, v1.s[1] \n"
"fmla v14.4s, v4.4s, v1.s[2] \n"
"fmla v15.4s, v4.4s, v1.s[3] \n"
"fmla v16.4s, v4.4s, v2.s[0] \n"
"fmla v17.4s, v4.4s, v2.s[1] \n"
"fmla v18.4s, v4.4s, v2.s[2] \n"
"fmla v19.4s, v4.4s, v2.s[3] \n"
"prfm pldl1keep, [%2, #512] \n"
"ld1 {v20.4s, v21.4s, v22.4s, v23.4s}, [%2], #64 \n"
"fmla v8.4s, v5.4s, v3.s[0] \n"
"fmla v9.4s, v5.4s, v3.s[1] \n"
"fmla v10.4s, v5.4s, v3.s[2] \n"
"fmla v11.4s, v5.4s, v3.s[3] \n"
"fmla v12.4s, v5.4s, v20.s[0] \n"
"fmla v13.4s, v5.4s, v20.s[1] \n"
"fmla v14.4s, v5.4s, v20.s[2] \n"
"fmla v15.4s, v5.4s, v20.s[3] \n"
"fmla v16.4s, v5.4s, v21.s[0] \n"
"fmla v17.4s, v5.4s, v21.s[1] \n"
"fmla v18.4s, v5.4s, v21.s[2] \n"
"fmla v19.4s, v5.4s, v21.s[3] \n"
"prfm pldl1keep, [%2, #512] \n"
"ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%2], #64 \n"
"fmla v8.4s, v6.4s, v22.s[0] \n"
"fmla v9.4s, v6.4s, v22.s[1] \n"
"fmla v10.4s, v6.4s, v22.s[2] \n"
"fmla v11.4s, v6.4s, v22.s[3] \n"
"fmla v12.4s, v6.4s, v23.s[0] \n"
"fmla v13.4s, v6.4s, v23.s[1] \n"
"fmla v14.4s, v6.4s, v23.s[2] \n"
"fmla v15.4s, v6.4s, v23.s[3] \n"
"fmla v16.4s, v6.4s, v24.s[0] \n"
"fmla v17.4s, v6.4s, v24.s[1] \n"
"fmla v18.4s, v6.4s, v24.s[2] \n"
"fmla v19.4s, v6.4s, v24.s[3] \n"
"subs %w0, %w0, #1 \n"
"fmla v8.4s, v7.4s, v25.s[0] \n"
"fmla v9.4s, v7.4s, v25.s[1] \n"
"fmla v10.4s, v7.4s, v25.s[2] \n"
"fmla v11.4s, v7.4s, v25.s[3] \n"
"fmla v12.4s, v7.4s, v26.s[0] \n"
"fmla v13.4s, v7.4s, v26.s[1] \n"
"fmla v14.4s, v7.4s, v26.s[2] \n"
"fmla v15.4s, v7.4s, v26.s[3] \n"
"fmla v16.4s, v7.4s, v27.s[0] \n"
"fmla v17.4s, v7.4s, v27.s[1] \n"
"fmla v18.4s, v7.4s, v27.s[2] \n"
"fmla v19.4s, v7.4s, v27.s[3] \n"
"bne 0b \n"
"st1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%1], #64 \n"
"st1 {v12.4s, v13.4s, v14.4s, v15.4s}, [%1], #64 \n"
"st1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%1], #64 \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(tmpptr), // %2
"=r"(kptr0) // %3
: "0"(nn),
"1"(outptr0),
"2"(tmpptr),
"3"(kptr0),
"r"(biasptr) // %8
: "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27"
);
}
#endif
for (; i+7<size; i+=8)
{
#if __aarch64__
float* tmpptr = tmp.channel(i/12+(i%12)/8);
#else
float* tmpptr = tmp.channel(i/8);
#endif
const float* kptr0 = (const float*)kernel + p * inch * 16;
int nn = inch;// inch always > 0
#if __aarch64__
asm volatile(
"ld1 {v0.4s}, [%8] \n"
"mov v16.16b, v0.16b \n"
"mov v17.16b, v0.16b \n"
"mov v18.16b, v0.16b \n"
"mov v19.16b, v0.16b \n"
"mov v20.16b, v0.16b \n"
"mov v21.16b, v0.16b \n"
"mov v22.16b, v0.16b \n"
"mov v23.16b, v0.16b \n"
"0: \n"
"prfm pldl1keep, [%2, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%2], #64 \n"// r0 r1 r2 r3
"prfm pldl1keep, [%3, #512] \n"
"ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%3], #64 \n"// w0123
"fmla v16.4s, v8.4s, v0.s[0] \n"
"fmla v17.4s, v8.4s, v1.s[0] \n"
"fmla v18.4s, v8.4s, v2.s[0] \n"
"fmla v19.4s, v8.4s, v3.s[0] \n"
"prfm pldl1keep, [%2, #512] \n"
"ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%2], #64 \n"// r4 r5 r6 r7
"fmla v20.4s, v8.4s, v4.s[0] \n"
"fmla v21.4s, v8.4s, v5.s[0] \n"
"fmla v22.4s, v8.4s, v6.s[0] \n"
"fmla v23.4s, v8.4s, v7.s[0] \n"
"fmla v16.4s, v9.4s, v0.s[1] \n"
"fmla v17.4s, v9.4s, v1.s[1] \n"
"fmla v18.4s, v9.4s, v2.s[1] \n"
"fmla v19.4s, v9.4s, v3.s[1] \n"
"fmla v20.4s, v9.4s, v4.s[1] \n"
"fmla v21.4s, v9.4s, v5.s[1] \n"
"fmla v22.4s, v9.4s, v6.s[1] \n"
"fmla v23.4s, v9.4s, v7.s[1] \n"
"fmla v16.4s, v10.4s, v0.s[2] \n"
"fmla v17.4s, v10.4s, v1.s[2] \n"
"fmla v18.4s, v10.4s, v2.s[2] \n"
"fmla v19.4s, v10.4s, v3.s[2] \n"
"fmla v20.4s, v10.4s, v4.s[2] \n"
"fmla v21.4s, v10.4s, v5.s[2] \n"
"fmla v22.4s, v10.4s, v6.s[2] \n"
"fmla v23.4s, v10.4s, v7.s[2] \n"
"subs %w0, %w0, #1 \n"
"fmla v16.4s, v11.4s, v0.s[3] \n"
"fmla v17.4s, v11.4s, v1.s[3] \n"
"fmla v18.4s, v11.4s, v2.s[3] \n"
"fmla v19.4s, v11.4s, v3.s[3] \n"
"fmla v20.4s, v11.4s, v4.s[3] \n"
"fmla v21.4s, v11.4s, v5.s[3] \n"
"fmla v22.4s, v11.4s, v6.s[3] \n"
"fmla v23.4s, v11.4s, v7.s[3] \n"
"bne 0b \n"
"st1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%1], #64 \n"
"st1 {v20.4s, v21.4s, v22.4s, v23.4s}, [%1], #64 \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(tmpptr), // %2
"=r"(kptr0) // %3
: "0"(nn),
"1"(outptr0),
"2"(tmpptr),
"3"(kptr0),
"r"(biasptr) // %8
: "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23"
);
#else
asm volatile(
"vld1.f32 {d0-d1}, [%8] \n"
"vmov q8, q0 \n"
"vmov q9, q0 \n"
"vmov q10, q0 \n"
"vmov q11, q0 \n"
"vmov q12, q0 \n"
"vmov q13, q0 \n"
"vmov q14, q0 \n"
"vmov q15, q0 \n"
"0: \n"
"pld [%2, #512] \n"
"vldm %2!, {d0-d7} \n"
"pld [%3, #512] \n"
"vldm %3!, {d8-d15} \n"
"vmla.f32 q8, q4, d0[0] \n"
"vmla.f32 q9, q4, d0[1] \n"
"vmla.f32 q10, q4, d1[0] \n"
"vmla.f32 q11, q4, d1[1] \n"
"vmla.f32 q12, q4, d2[0] \n"
"vmla.f32 q13, q4, d2[1] \n"
"vmla.f32 q14, q4, d3[0] \n"
"vmla.f32 q15, q4, d3[1] \n"
"vmla.f32 q8, q5, d4[0] \n"
"vmla.f32 q9, q5, d4[1] \n"
"vmla.f32 q10, q5, d5[0] \n"
"vmla.f32 q11, q5, d5[1] \n"
"vmla.f32 q12, q5, d6[0] \n"
"vmla.f32 q13, q5, d6[1] \n"
"vmla.f32 q14, q5, d7[0] \n"
"vmla.f32 q15, q5, d7[1] \n"
"pld [%2, #512] \n"
"vldm %2!, {d0-d7} \n"
"vmla.f32 q8, q6, d0[0] \n"
"vmla.f32 q9, q6, d0[1] \n"
"vmla.f32 q10, q6, d1[0] \n"
"vmla.f32 q11, q6, d1[1] \n"
"vmla.f32 q12, q6, d2[0] \n"
"vmla.f32 q13, q6, d2[1] \n"
"vmla.f32 q14, q6, d3[0] \n"
"vmla.f32 q15, q6, d3[1] \n"
"subs %0, %0, #1 \n"
"vmla.f32 q8, q7, d4[0] \n"
"vmla.f32 q9, q7, d4[1] \n"
"vmla.f32 q10, q7, d5[0] \n"
"vmla.f32 q11, q7, d5[1] \n"
"vmla.f32 q12, q7, d6[0] \n"
"vmla.f32 q13, q7, d6[1] \n"
"vmla.f32 q14, q7, d7[0] \n"
"vmla.f32 q15, q7, d7[1] \n"
"bne 0b \n"
"vstm %1!, {d16-d23} \n"
"vstm %1!, {d24-d31} \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(tmpptr), // %2
"=r"(kptr0) // %3
: "0"(nn),
"1"(outptr0),
"2"(tmpptr),
"3"(kptr0),
"r"(biasptr) // %8
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"
);
#endif
}
for (; i+3<size; i+=4)
{
#if __aarch64__
float* tmpptr = tmp.channel(i/12 + (i%12)/8 + (i%8)/4);
#else
float* tmpptr = tmp.channel(i/8 + (i%8)/4);
#endif
const float* kptr0 = (const float*)kernel + p * inch * 16;
int nn = inch;// inch always > 0
#if __aarch64__
asm volatile(
"ld1 {v0.4s}, [%8] \n"
"mov v16.16b, v0.16b \n"
"mov v17.16b, v0.16b \n"
"mov v18.16b, v0.16b \n"
"mov v19.16b, v0.16b \n"
"0: \n"
"prfm pldl1keep, [%2, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%2], #64 \n"// r0 r1 r2 r3
"prfm pldl1keep, [%3, #512] \n"
"ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%3], #64 \n"// w0123
"fmla v16.4s, v8.4s, v0.s[0] \n"
"fmla v17.4s, v8.4s, v1.s[0] \n"
"fmla v18.4s, v8.4s, v2.s[0] \n"
"fmla v19.4s, v8.4s, v3.s[0] \n"
"fmla v16.4s, v9.4s, v0.s[1] \n"
"fmla v17.4s, v9.4s, v1.s[1] \n"
"fmla v18.4s, v9.4s, v2.s[1] \n"
"fmla v19.4s, v9.4s, v3.s[1] \n"
"fmla v16.4s, v10.4s, v0.s[2] \n"
"fmla v17.4s, v10.4s, v1.s[2] \n"
"fmla v18.4s, v10.4s, v2.s[2] \n"
"fmla v19.4s, v10.4s, v3.s[2] \n"
"subs %w0, %w0, #1 \n"
"fmla v16.4s, v11.4s, v0.s[3] \n"
"fmla v17.4s, v11.4s, v1.s[3] \n"
"fmla v18.4s, v11.4s, v2.s[3] \n"
"fmla v19.4s, v11.4s, v3.s[3] \n"
"bne 0b \n"
"st1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%1], #64 \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(tmpptr), // %2
"=r"(kptr0) // %3
: "0"(nn),
"1"(outptr0),
"2"(tmpptr),
"3"(kptr0),
"r"(biasptr) // %8
: "cc", "memory", "v0", "v1", "v2", "v3", "v8", "v9", "v10", "v11", "v16", "v17", "v18", "v19"
);
#else
asm volatile(
"vld1.f32 {d0-d1}, [%8] \n"
"vmov q8, q0 \n"
"vmov q9, q0 \n"
"vmov q10, q0 \n"
"vmov q11, q0 \n"
"0: \n"
"pld [%2, #512] \n"
"vldm %2!, {d0-d7} \n"
"pld [%3, #512] \n"
"vldm %3!, {d8-d15} \n"
"vmla.f32 q8, q4, d0[0] \n"
"vmla.f32 q9, q4, d2[0] \n"
"vmla.f32 q10, q4, d4[0] \n"
"vmla.f32 q11, q4, d6[0] \n"
"vmla.f32 q8, q5, d0[1] \n"
"vmla.f32 q9, q5, d2[1] \n"
"vmla.f32 q10, q5, d4[1] \n"
"vmla.f32 q11, q5, d6[1] \n"
"vmla.f32 q8, q6, d1[0] \n"
"vmla.f32 q9, q6, d3[0] \n"
"vmla.f32 q10, q6, d5[0] \n"
"vmla.f32 q11, q6, d7[0] \n"
"subs %0, %0, #1 \n"
"vmla.f32 q8, q7, d1[1] \n"
"vmla.f32 q9, q7, d3[1] \n"
"vmla.f32 q10, q7, d5[1] \n"
"vmla.f32 q11, q7, d7[1] \n"
"bne 0b \n"
"vstm %1!, {d16-d23} \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(tmpptr), // %2
"=r"(kptr0) // %3
: "0"(nn),
"1"(outptr0),
"2"(tmpptr),
"3"(kptr0),
"r"(biasptr) // %8
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11"
);
#endif
}
for (; i+1<size; i+=2)
{
#if __aarch64__
float* tmpptr = tmp.channel(i/12 + (i%12)/8 + (i%8)/4 + (i%4)/2);
#else
float* tmpptr = tmp.channel(i/8 + (i%8)/4 + (i%4)/2);
#endif
const float* kptr0 = (const float*)kernel + p * inch * 16;
int nn = inch;// inch always > 0
#if __aarch64__
asm volatile(
"ld1 {v0.4s}, [%8] \n"
"mov v16.16b, v0.16b \n"
"mov v17.16b, v0.16b \n"
"0: \n"
"prfm pldl1keep, [%2, #256] \n"
"ld1 {v0.4s, v1.4s}, [%2], #32 \n"// r0 r1
"prfm pldl1keep, [%3, #512] \n"
"ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%3], #64 \n"// w0123
"fmla v16.4s, v8.4s, v0.s[0] \n"
"fmla v17.4s, v8.4s, v1.s[0] \n"
"fmla v16.4s, v9.4s, v0.s[1] \n"
"fmla v17.4s, v9.4s, v1.s[1] \n"
"fmla v16.4s, v10.4s, v0.s[2] \n"
"fmla v17.4s, v10.4s, v1.s[2] \n"
"subs %w0, %w0, #1 \n"
"fmla v16.4s, v11.4s, v0.s[3] \n"
"fmla v17.4s, v11.4s, v1.s[3] \n"
"bne 0b \n"
"st1 {v16.4s, v17.4s}, [%1], #32 \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(tmpptr), // %2
"=r"(kptr0) // %3
: "0"(nn),
"1"(outptr0),
"2"(tmpptr),
"3"(kptr0),
"r"(biasptr) // %8
: "cc", "memory", "v0", "v1", "v8", "v9", "v10", "v11", "v16", "v17"
);
#else
asm volatile(
"vld1.f32 {d0-d1}, [%8] \n"
"vmov q8, q0 \n"
"vmov q9, q0 \n"
"0: \n"
"pld [%2, #256] \n"
"vld1.f32 {d0-d3}, [%2 :128]! \n"
"pld [%3, #512] \n"
"vldm %3!, {d8-d15} \n"
"vmla.f32 q8, q4, d0[0] \n"
"vmla.f32 q9, q4, d2[0] \n"
"vmla.f32 q8, q5, d0[1] \n"
"vmla.f32 q9, q5, d2[1] \n"
"vmla.f32 q8, q6, d1[0] \n"
"vmla.f32 q9, q6, d3[0] \n"
"subs %0, %0, #1 \n"
"vmla.f32 q8, q7, d1[1] \n"
"vmla.f32 q9, q7, d3[1] \n"
"bne 0b \n"
"vst1.f32 {d16-d19}, [%1 :128]! \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(tmpptr), // %2
"=r"(kptr0) // %3
: "0"(nn),
"1"(outptr0),
"2"(tmpptr),
"3"(kptr0),
"r"(biasptr) // %8
: "cc", "memory", "q0", "q1", "q4", "q5", "q6", "q7", "q8", "q9"
);
#endif
}
for (; i<size; i++)
{
#if __aarch64__
float* tmpptr = tmp.channel(i/12 + (i%12)/8 + (i%8)/4 + (i%4)/2 + i%2);
#else
float* tmpptr = tmp.channel(i/8 + (i%8)/4 + (i%4)/2 + i%2);
#endif
const float* kptr0 = (const float*)kernel + p * inch * 16;
int nn = inch;// inch always > 0
#if __aarch64__
asm volatile(
"ld1 {v16.4s}, [%8] \n"
"0: \n"
"prfm pldl1keep, [%2, #128] \n"
"ld1 {v0.4s}, [%2], #16 \n"// r0
"prfm pldl1keep, [%3, #512] \n"
"ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%3], #64 \n"// w0123
"fmla v16.4s, v8.4s, v0.s[0] \n"
"fmla v16.4s, v9.4s, v0.s[1] \n"
"subs %w0, %w0, #1 \n"
"fmla v16.4s, v10.4s, v0.s[2] \n"
"fmla v16.4s, v11.4s, v0.s[3] \n"
"bne 0b \n"
"st1 {v16.4s}, [%1], #16 \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(tmpptr), // %2
"=r"(kptr0) // %3
: "0"(nn),
"1"(outptr0),
"2"(tmpptr),
"3"(kptr0),
"r"(biasptr) // %8
: "cc", "memory", "v0", "v8", "v9", "v10", "v11", "v16"
);
#else
asm volatile(
"vld1.f32 {d16-d17}, [%8] \n"
"0: \n"
"pld [%2, #128] \n"
"vld1.f32 {d0-d1}, [%2 :128]! \n"
"pld [%3, #512] \n"
"vldm %3!, {d8-d15} \n"
"vmla.f32 q8, q4, d0[0] \n"
"vmla.f32 q8, q5, d0[1] \n"
"subs %0, %0, #1 \n"
"vmla.f32 q8, q6, d1[0] \n"
"vmla.f32 q8, q7, d1[1] \n"
"bne 0b \n"
"vst1.f32 {d16-d17}, [%1 :128]! \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(tmpptr), // %2
"=r"(kptr0) // %3
: "0"(nn),
"1"(outptr0),
"2"(tmpptr),
"3"(kptr0),
"r"(biasptr) // %8
: "cc", "memory", "q0", "q4", "q5", "q6", "q7", "q8"
);
#endif
}
}
// // NOTE sgemm
// for (; p<outch; p++)
// {
// Mat out0 = top_blob.channel(p);
//
// const float bias0 = bias ? bias[p] : 0.f;
//
// float* outptr0 = out0;
//
// for (int i=0; i<size; i++)
// {
// float sum = bias0;
//
// const float* kptr = _kernel.channel(p);
//
// for (int q=0; q<inch; q++)
// {
// const float* img0 = bottom_blob.channel(q);
//
// sum += img0[i] * kptr[0];
// kptr ++;
// }
//
// outptr0[i] = sum;
// }
// }
}
|
DRB043-adi-parallel-no.c | /**
* adi.c: This file is part of the PolyBench/C 3.2 test suite.
*
* Alternating Direction Implicit solver:
*
* Contact: Louis-Noel Pouchet <pouchet@cse.ohio-state.edu>
* Web address: http://polybench.sourceforge.net
* License: /LICENSE.OSU.txt
*/
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <math.h>
/* Include polybench common header. */
#include "polybench/polybench.h"
/* Include benchmark-specific header. */
/* Default data type is double, default size is 10x1024x1024. */
#include "polybench/adi.h"
/* Array initialization. */
static void init_array(int n,double X[500 + 0][500 + 0],double A[500 + 0][500 + 0],double B[500 + 0][500 + 0])
{
//int i;
//int j;
{
int c1;
int c2;
if (n >= 1) {
#pragma omp parallel for private(c2)
for (c1 = 0; c1 <= n + -1; c1++) {
for (c2 = 0; c2 <= n + -1; c2++) {
X[c1][c2] = (((double )c1) * (c2 + 1) + 1) / n;
A[c1][c2] = (((double )c1) * (c2 + 2) + 2) / n;
B[c1][c2] = (((double )c1) * (c2 + 3) + 3) / n;
}
}
}
}
}
/* DCE code. Must scan the entire live-out data.
Can be used also to check the correctness of the output. */
static void print_array(int n,double X[500 + 0][500 + 0])
{
int i;
int j;
for (i = 0; i < n; i++)
for (j = 0; j < n; j++) {
fprintf(stderr,"%0.2lf ",X[i][j]);
if ((i * 500 + j) % 20 == 0)
fprintf(stderr,"\n");
}
fprintf(stderr,"\n");
}
/* Main computational kernel. The whole function will be timed,
including the call and return. */
static void kernel_adi(int tsteps,int n,double X[500 + 0][500 + 0],double A[500 + 0][500 + 0],double B[500 + 0][500 + 0])
{
//int t;
//int i1;
//int i2;
//#pragma scop
{
int c0;
int c2;
int c8;
for (c0 = 0; c0 <= 9; c0++) {
#pragma omp parallel for private(c8)
for (c2 = 0; c2 <= 499; c2++) {
for (c8 = 1; c8 <= 499; c8++) {
B[c2][c8] = B[c2][c8] - A[c2][c8] * A[c2][c8] / B[c2][c8 - 1];
}
for (c8 = 1; c8 <= 499; c8++) {
X[c2][c8] = X[c2][c8] - X[c2][c8 - 1] * A[c2][c8] / B[c2][c8 - 1];
}
for (c8 = 0; c8 <= 497; c8++) {
X[c2][500 - c8 - 2] = (X[c2][500 - 2 - c8] - X[c2][500 - 2 - c8 - 1] * A[c2][500 - c8 - 3]) / B[c2][500 - 3 - c8];
}
}
#pragma omp parallel for
for (c2 = 0; c2 <= 499; c2++) {
X[c2][500 - 1] = X[c2][500 - 1] / B[c2][500 - 1];
}
#pragma omp parallel for private(c8)
for (c2 = 0; c2 <= 499; c2++) {
for (c8 = 1; c8 <= 499; c8++) {
B[c8][c2] = B[c8][c2] - A[c8][c2] * A[c8][c2] / B[c8 - 1][c2];
}
for (c8 = 1; c8 <= 499; c8++) {
X[c8][c2] = X[c8][c2] - X[c8 - 1][c2] * A[c8][c2] / B[c8 - 1][c2];
}
for (c8 = 0; c8 <= 497; c8++) {
X[500 - 2 - c8][c2] = (X[500 - 2 - c8][c2] - X[500 - c8 - 3][c2] * A[500 - 3 - c8][c2]) / B[500 - 2 - c8][c2];
}
}
#pragma omp parallel for
for (c2 = 0; c2 <= 499; c2++) {
X[500 - 1][c2] = X[500 - 1][c2] / B[500 - 1][c2];
}
}
}
//#pragma endscop
}
int main(int argc,char **argv)
{
/* Retrieve problem size. */
int n = 500;
int tsteps = 10;
/* Variable declaration/allocation. */
double (*X)[500 + 0][500 + 0];
X = ((double (*)[500 + 0][500 + 0])(polybench_alloc_data(((500 + 0) * (500 + 0)),(sizeof(double )))));
;
double (*A)[500 + 0][500 + 0];
A = ((double (*)[500 + 0][500 + 0])(polybench_alloc_data(((500 + 0) * (500 + 0)),(sizeof(double )))));
;
double (*B)[500 + 0][500 + 0];
B = ((double (*)[500 + 0][500 + 0])(polybench_alloc_data(((500 + 0) * (500 + 0)),(sizeof(double )))));
;
/* Initialize array(s). */
init_array(n, *X, *A, *B);
/* Start timer. */
polybench_timer_start();
;
/* Run kernel. */
kernel_adi(tsteps,n, *X, *A, *B);
/* Stop and print timer. */
polybench_timer_stop();
;
polybench_timer_print();
;
/* Prevent dead-code elimination. All live-out data must be printed
by the function call in argument. */
if (argc > 42 && !strcmp(argv[0],""))
print_array(n, *X);
/* Be clean. */
free(((void *)X));
;
free(((void *)A));
;
free(((void *)B));
;
return 0;
}
|
omp_parallel_sections_firstprivate.c | // RUN: %libomp-compile-and-run
#include <stdio.h>
#include "omp_testsuite.h"
int test_omp_parallel_sections_firstprivate()
{
int sum;
int sum0;
int known_sum;
sum =7;
sum0=11;
#pragma omp parallel sections firstprivate(sum0)
{
#pragma omp section
{
#pragma omp critical
{
sum= sum+sum0;
}
}
#pragma omp section
{
#pragma omp critical
{
sum= sum+sum0;
}
}
#pragma omp section
{
#pragma omp critical
{
sum= sum+sum0;
}
}
}
known_sum=11*3+7;
return (known_sum==sum);
} /* end of check_section_firstprivate*/
int main()
{
int i;
int num_failed=0;
for(i = 0; i < REPETITIONS; i++) {
if(!test_omp_parallel_sections_firstprivate()) {
num_failed++;
}
}
return num_failed;
}
|
convolution_1x1_pack4to8_fp16s.h | // Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// 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.
static void conv1x1s1_sgemm_transform_kernel_pack4to8_fp16sa_neon(const Mat& kernel, Mat& kernel_tm_pack4to8, int inch, int outch)
{
// interleave
// src = inch-outch
// dst = 8b-4a-inch/4a-outch/8b
kernel_tm_pack4to8.create(8 * 4, inch / 4, outch / 8, (size_t)2u, 1);
int q = 0;
for (; q + 7 < outch; q += 8)
{
const float* k0 = (const float*)kernel + (q + 0) * inch;
const float* k1 = (const float*)kernel + (q + 1) * inch;
const float* k2 = (const float*)kernel + (q + 2) * inch;
const float* k3 = (const float*)kernel + (q + 3) * inch;
const float* k4 = (const float*)kernel + (q + 4) * inch;
const float* k5 = (const float*)kernel + (q + 5) * inch;
const float* k6 = (const float*)kernel + (q + 6) * inch;
const float* k7 = (const float*)kernel + (q + 7) * inch;
__fp16* g0 = kernel_tm_pack4to8.channel(q / 8);
for (int p = 0; p + 3 < inch; p += 4)
{
for (int i = 0; i < 4; i++)
{
g0[0] = (__fp16)k0[i];
g0[1] = (__fp16)k1[i];
g0[2] = (__fp16)k2[i];
g0[3] = (__fp16)k3[i];
g0[4] = (__fp16)k4[i];
g0[5] = (__fp16)k5[i];
g0[6] = (__fp16)k6[i];
g0[7] = (__fp16)k7[i];
g0 += 8;
}
k0 += 4;
k1 += 4;
k2 += 4;
k3 += 4;
k4 += 4;
k5 += 4;
k6 += 4;
k7 += 4;
}
}
}
static void conv1x1s1_sgemm_pack4to8_fp16sa_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt)
{
int w = bottom_blob.w;
int h = bottom_blob.h;
int inch = bottom_blob.c;
int outch = top_blob.c;
size_t elemsize = bottom_blob.elemsize;
int elempack = bottom_blob.elempack;
const int size = w * h;
const __fp16* bias = _bias;
// interleave
Mat tmp;
if (size >= 8)
tmp.create(8, inch, size / 8 + size % 8, elemsize, elempack, opt.workspace_allocator);
else // if (size >= 1)
tmp.create(1, inch, size, elemsize, elempack, opt.workspace_allocator);
{
int nn_size;
int remain_size_start = 0;
nn_size = (size - remain_size_start) >> 3;
#pragma omp parallel for num_threads(opt.num_threads)
for (int ii = 0; ii < nn_size; ii++)
{
int i = remain_size_start + ii * 8;
const __fp16* img0 = bottom_blob.channel(0);
img0 += i * 4;
__fp16* tmpptr = tmp.channel(i / 8);
for (int q = 0; q < inch; q++)
{
// transpose 4x8
asm volatile(
"prfm pldl1keep, [%0, #512] \n"
"ld4 {v0.8h, v1.8h, v2.8h, v3.8h}, [%0] \n"
"st1 {v0.8h, v1.8h, v2.8h, v3.8h}, [%1], #64 \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "memory", "v0", "v1", "v2", "v3");
img0 += bottom_blob.cstep * 4;
}
}
remain_size_start += nn_size << 3;
#pragma omp parallel for num_threads(opt.num_threads)
for (int i = remain_size_start; i < size; i++)
{
const __fp16* img0 = bottom_blob.channel(0);
img0 += i * 4;
__fp16* tmpptr = tmp.channel(i / 8 + i % 8);
for (int q = 0; q < inch; q++)
{
asm volatile(
"prfm pldl1keep, [%0, #64] \n"
"ld1 {v0.4h}, [%0] \n"
"st1 {v0.4h}, [%1], #8 \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "memory", "v0");
img0 += bottom_blob.cstep * 4;
}
}
}
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = 0; p < outch; p++)
{
__fp16* outptr0 = top_blob.channel(p);
const __fp16 zeros[8] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f};
const __fp16* biasptr = bias ? bias + p * 8 : zeros;
int i = 0;
for (; i + 7 < size; i += 8)
{
__fp16* tmpptr = tmp.channel(i / 8);
const __fp16* kptr = kernel.channel(p);
int nn = inch; // inch always > 0
asm volatile(
"ld1 {v16.8h}, [%8] \n"
"mov v17.16b, v16.16b \n"
"mov v18.16b, v16.16b \n"
"mov v19.16b, v16.16b \n"
"mov v20.16b, v16.16b \n"
"mov v21.16b, v16.16b \n"
"mov v22.16b, v16.16b \n"
"mov v23.16b, v16.16b \n"
"0: \n"
"prfm pldl1keep, [%2, #512] \n"
"ld1 {v0.8h, v1.8h, v2.8h, v3.8h}, [%2], #64 \n" // r0123
"prfm pldl1keep, [%3, #512] \n"
"ld1 {v8.8h, v9.8h, v10.8h, v11.8h}, [%3], #64 \n" // w0123
"fmla v16.8h, v8.8h, v0.h[0] \n"
"fmla v17.8h, v8.8h, v0.h[1] \n"
"fmla v18.8h, v8.8h, v0.h[2] \n"
"fmla v19.8h, v8.8h, v0.h[3] \n"
"fmla v20.8h, v8.8h, v0.h[4] \n"
"fmla v21.8h, v8.8h, v0.h[5] \n"
"fmla v22.8h, v8.8h, v0.h[6] \n"
"fmla v23.8h, v8.8h, v0.h[7] \n"
"fmla v16.8h, v9.8h, v1.h[0] \n"
"fmla v17.8h, v9.8h, v1.h[1] \n"
"fmla v18.8h, v9.8h, v1.h[2] \n"
"fmla v19.8h, v9.8h, v1.h[3] \n"
"fmla v20.8h, v9.8h, v1.h[4] \n"
"fmla v21.8h, v9.8h, v1.h[5] \n"
"fmla v22.8h, v9.8h, v1.h[6] \n"
"fmla v23.8h, v9.8h, v1.h[7] \n"
"fmla v16.8h, v10.8h, v2.h[0] \n"
"fmla v17.8h, v10.8h, v2.h[1] \n"
"fmla v18.8h, v10.8h, v2.h[2] \n"
"fmla v19.8h, v10.8h, v2.h[3] \n"
"fmla v20.8h, v10.8h, v2.h[4] \n"
"fmla v21.8h, v10.8h, v2.h[5] \n"
"fmla v22.8h, v10.8h, v2.h[6] \n"
"fmla v23.8h, v10.8h, v2.h[7] \n"
"fmla v16.8h, v11.8h, v3.h[0] \n"
"fmla v17.8h, v11.8h, v3.h[1] \n"
"fmla v18.8h, v11.8h, v3.h[2] \n"
"fmla v19.8h, v11.8h, v3.h[3] \n"
"fmla v20.8h, v11.8h, v3.h[4] \n"
"fmla v21.8h, v11.8h, v3.h[5] \n"
"fmla v22.8h, v11.8h, v3.h[6] \n"
"fmla v23.8h, v11.8h, v3.h[7] \n"
"subs %w0, %w0, #1 \n"
"bne 0b \n"
"st1 {v16.8h, v17.8h, v18.8h, v19.8h}, [%1], #64 \n"
"st1 {v20.8h, v21.8h, v22.8h, v23.8h}, [%1], #64 \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(tmpptr), // %2
"=r"(kptr) // %3
: "0"(nn),
"1"(outptr0),
"2"(tmpptr),
"3"(kptr),
"r"(biasptr) // %8
: "cc", "memory", "v0", "v1", "v2", "v3", "v8", "v9", "v10", "v11", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23");
}
for (; i < size; i++)
{
__fp16* tmpptr = tmp.channel(i / 8 + i % 8);
const __fp16* kptr = kernel.channel(p);
float16x8_t _sum0 = vld1q_f16(biasptr);
int q = 0;
for (; q < inch; q++)
{
float16x4_t _r0 = vld1_f16(tmpptr);
float16x8_t _k0 = vld1q_f16(kptr);
float16x8_t _k1 = vld1q_f16(kptr + 8);
float16x8_t _k2 = vld1q_f16(kptr + 16);
float16x8_t _k3 = vld1q_f16(kptr + 24);
_sum0 = vfmaq_lane_f16(_sum0, _k0, _r0, 0);
_sum0 = vfmaq_lane_f16(_sum0, _k1, _r0, 1);
_sum0 = vfmaq_lane_f16(_sum0, _k2, _r0, 2);
_sum0 = vfmaq_lane_f16(_sum0, _k3, _r0, 3);
kptr += 32;
tmpptr += 4;
}
vst1q_f16(outptr0, _sum0);
outptr0 += 8;
}
}
// // NOTE sgemm
// for (; p<outch; p++)
// {
// Mat out0 = top_blob.channel(p);
//
// const __fp16 bias0 = bias ? bias[p] : 0.f;
//
// __fp16* outptr0 = out0;
//
// for (int i=0; i<size; i++)
// {
// __fp16 sum = bias0;
//
// const __fp16* kptr = _kernel.channel(p);
//
// for (int q=0; q<inch; q++)
// {
// const __fp16* img0 = bottom_blob.channel(q);
//
// sum += img0[i] * kptr[0];
// kptr ++;
// }
//
// outptr0[i] = sum;
// }
// }
}
static void conv1x1s2_pack4to8_fp16sa_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt)
{
int w = bottom_blob.w;
int channels = bottom_blob.c;
size_t elemsize = bottom_blob.elemsize;
int elempack = bottom_blob.elempack;
int outw = top_blob.w;
int outh = top_blob.h;
const int tailstep = (w - 2 * outw + w) * 4;
Mat bottom_blob_shrinked;
bottom_blob_shrinked.create(outw, outh, channels, elemsize, elempack, opt.workspace_allocator);
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = 0; p < channels; p++)
{
const __fp16* r0 = bottom_blob.channel(p);
__fp16* outptr = bottom_blob_shrinked.channel(p);
for (int i = 0; i < outh; i++)
{
int j = 0;
for (; j + 3 < outw; j += 4)
{
float16x4_t _v0 = vld1_f16(r0);
float16x4_t _v1 = vld1_f16(r0 + 8);
float16x4_t _v2 = vld1_f16(r0 + 16);
float16x4_t _v3 = vld1_f16(r0 + 24);
vst1_f16(outptr, _v0);
vst1_f16(outptr + 4, _v1);
vst1_f16(outptr + 8, _v2);
vst1_f16(outptr + 12, _v3);
r0 += 32;
outptr += 16;
}
for (; j + 1 < outw; j += 2)
{
float16x4_t _v0 = vld1_f16(r0);
float16x4_t _v1 = vld1_f16(r0 + 8);
vst1_f16(outptr, _v0);
vst1_f16(outptr + 4, _v1);
r0 += 16;
outptr += 8;
}
for (; j < outw; j++)
{
float16x4_t _v = vld1_f16(r0);
vst1_f16(outptr, _v);
r0 += 8;
outptr += 4;
}
r0 += tailstep;
}
}
conv1x1s1_sgemm_pack4to8_fp16sa_neon(bottom_blob_shrinked, top_blob, kernel, _bias, opt);
}
|
GB_unop__asin_fp32_fp32.c | //------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_atomics.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB (_unop_apply__asin_fp32_fp32)
// op(A') function: GB (_unop_tran__asin_fp32_fp32)
// C type: float
// A type: float
// cast: float cij = aij
// unaryop: cij = asinf (aij)
#define GB_ATYPE \
float
#define GB_CTYPE \
float
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
float aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = asinf (x) ;
// casting
#define GB_CAST(z, aij) \
float z = aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
float aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
float z = aij ; \
Cx [pC] = asinf (z) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_ASIN || GxB_NO_FP32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__asin_fp32_fp32)
(
float *Cx, // Cx and Ax may be aliased
const float *Ax,
const int8_t *restrict Ab, // A->b if A is bitmap
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
if (Ab == NULL)
{
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
float aij = Ax [p] ;
float z = aij ;
Cx [p] = asinf (z) ;
}
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
float aij = Ax [p] ;
float z = aij ;
Cx [p] = asinf (z) ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__asin_fp32_fp32)
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
flo.c | #define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <omp.h>
#include <immintrin.h>
#define SSE_WIDTH 4
#define N_FLO_BANDS 2
#define TAG_STRING "PIEH"
void construct_flo(float* flo, const float* u, const float* v, const int SIZE) {
for (int i=0; i < SIZE; i++) {
flo[i * N_FLO_BANDS] = u[i];
flo[(i * N_FLO_BANDS) + 1] = v[i];
}
}
void get_u_v(float* u, float* v, const float* flo, const int SIZE, const int NUMT) {
/* Copy flo array to seperate u/v arrays, size is size of u/v array */
omp_set_num_threads(NUMT);
int i;
#pragma omp parallel for default(none) shared(SIZE, u, v, flo)
for (i=0; i < SIZE; i++) {
u[i] = flo[i * N_FLO_BANDS];
v[i] = flo[(i * N_FLO_BANDS) + 1];
}
}
void write_flo(const float* flo, const char* filename, const int NROWS, const int NCOLS) {
// open file
FILE *stream = fopen(filename, "wb");
if (stream == 0) {
printf("filname: %s is invalid, writing file failed!\n", filename);
}
// write header
fprintf(stream, TAG_STRING); // write tag - "PIEH" in ASCII
fwrite(&NCOLS, sizeof(int), 1, stream); // write width as 32 bit int
fwrite(&NROWS, sizeof(int), 1, stream); // write row as 32 bit int
// write data flattened - u[0,0],v[0,0],u[0,1],v[0,1].....
int n = NCOLS * N_FLO_BANDS;
for (int r=0; r < NROWS; r++) {
fwrite(&flo[r*NCOLS*N_FLO_BANDS], sizeof(float), n, stream);
}
fclose(stream);
}
void write_flo_MP(const float* u, const float* v, const char* fbase, const int NUMF, const int NROWS, const int NCOLS, const int START_IDX, const int NUMT) {
// Set # of threads to use
if (NUMF < NUMT)
omp_set_num_threads(NUMF);
else
omp_set_num_threads(NUMT);
const int SIZE = NROWS * NCOLS;
const int F_SIZE = (int)strlen(fbase);
int i;
#pragma omp parallel for default(none) shared(NUMF, SIZE, F_SIZE, START_IDX, NROWS, NCOLS, u, v, fbase)
for (i=0; i < NUMF; i++) {
// construct flo array
float* flo = (float*)malloc(sizeof(float) * N_FLO_BANDS * SIZE);
construct_flo(flo, u + (i*SIZE), v + (i*SIZE), SIZE);
// now save array as flo
char* filename = (char*)malloc(sizeof(char) * (F_SIZE + 9));
#if defined(__linux__)
snprintf(filename, F_SIZE+1, "%s", fbase);
#elif defined(_WIN32)
snprintf(filename, F_SIZE, fbase);
#endif
const int idx = START_IDX + i;
if (idx < 10)
snprintf(filename + F_SIZE, 9, "000%d.flo", idx);
else if (idx < 100)
snprintf(filename + F_SIZE, 9, "00%d.flo", idx);
else if (idx < 1000)
snprintf(filename + F_SIZE, 9, "0%d.flo", idx);
else
snprintf(filename + F_SIZE, 9, "%d.flo", idx);
write_flo(flo, filename, NROWS, NCOLS);
free(flo);
free(filename);
}
}
void read_flo(float* flo, const char* filename, const int NROWS, const int NCOLS) {
FILE *stream = fopen(filename, "rb");
if (stream == 0) {
printf("filname: %s is invalid, writing file failed!\n", filename);
}
// read header
char header[4];
//float* flo;
fscanf(stream, "%4c", header);
//printf("header: %s\n", header);
if (strcmp(header, TAG_STRING)) {
int ncols, nrows;
fread(&ncols, sizeof(int), 1, stream);
fread(&nrows, sizeof(int), 1, stream);
//flo = (float*)malloc(sizeof(float) * N_FLO_BANDS * nrows * ncols);
if (nrows == NROWS && ncols == NCOLS) {
const int N = NCOLS * N_FLO_BANDS;
for (int r=0; r < NROWS; r++) {
fread(&flo[r * N], sizeof(float), N, stream);
}
}
else {
printf("dims provided are incorrect NROWS provided: %d, nrows read: %d, NCOLS provided: %d, ncols read: %d\n", NROWS, nrows, NCOLS, ncols);
}
}
else {
printf("Invalid flo header tag: %s, should be: %s", header, TAG_STRING);
}
}
void multiply_flo_scalers(float* cpy_flo, const float* src_flo, const int ITERS, const int NROWS, const int NCOLS, const int NUMT) {
omp_set_num_threads(NUMT);
const int SIZE = NROWS * NCOLS * N_FLO_BANDS;
const int size_limit = (SIZE / SSE_WIDTH) * SSE_WIDTH;
//register float *p_cpy = cpy_flo;
const register float *p_src = src_flo;
for (int t=0; t < ITERS; t++) {
const int i = t * SIZE;
const float scalerF = (float)t+1;
const __m128 sf_ps = _mm_load_ps1(&scalerF);
int j;
#pragma omp parallel for default(none) shared(size_limit, sf_ps, i, cpy_flo, p_src)
for (j=0; j < size_limit; j+=SSE_WIDTH) {
__m128 src_ps = _mm_loadu_ps(&p_src[j]);
_mm_storeu_ps(&cpy_flo[i+j], _mm_mul_ps(src_ps, sf_ps));
//cpy_flo[i + j] = src_flo[j] * scalerF;
}
for (int j=size_limit; j < SIZE; j++) {
cpy_flo[i + j] = src_flo[j] * scalerF;
}
}
}
void multiply_flo_mask_arr(float* arr1, const uint8_t* arr2, const int SIZE, const int NUMT) {
/* multiply flo grid by 8bit binary mask */
omp_set_num_threads(NUMT);
int i;
#pragma omp parallel for default(none) shared(SIZE, arr1, arr2)
for (i=0; i < SIZE; i++) {
arr1[i * N_FLO_BANDS]*= arr2[i];
arr1[(i * N_FLO_BANDS) + 1]*= arr2[i];
}
}
void multiply_flo_and_save(const float* u, const float* v, const char* filename, const int iters, const int NROWS, const int NCOLS, const int NUMT) {
if (iters < NUMT)
omp_set_num_threads(iters);
else
omp_set_num_threads(NUMT);
const int SIZE = NROWS * NCOLS;
const int F_SIZE = (int)strlen(filename);
int i;
//#pragma omp parallel for default(none) shared(u, v, filename, SIZE, NROWS, NCOLS, F_SIZE)
for (i=0; i < iters; i++) {
// create and construct flo matrix
float* flo = (float*)malloc(sizeof(float) * N_FLO_BANDS * SIZE);
float scalerF = (float)i+1;
for (int j=0; j < SIZE; j++) {
flo[j*N_FLO_BANDS] = u[j] * scalerF;
flo[(j*N_FLO_BANDS)+1] = v[j] * scalerF;
}
// now save array as flo TODO: make sure string is null terminated
char* filename_iter = (char*)malloc(sizeof(char) * (F_SIZE + 7));
snprintf(filename_iter, F_SIZE, "%s", filename);
if (i < 10)
snprintf(filename_iter + F_SIZE, 7, "0%d.flo", i);
else
snprintf(filename_iter + F_SIZE, 7, "%d.flo", i);
write_flo(flo, filename_iter, NROWS, NCOLS);
free(filename_iter);
free(flo);
}
} |
variational_distance_calculation_process.h | // | / |
// ' / __| _` | __| _ \ __|
// . \ | ( | | ( |\__ `
// _|\_\_| \__,_|\__|\___/ ____/
// Multi-Physics
//
// License: BSD License
// Kratos default license: kratos/license.txt
//
// Main authors: Riccardo Rossi
// Ruben Zorrilla
//
//
#if !defined(KRATOS_VARIATIONAL_DISTANCE_CALCULATION_PROCESS_INCLUDED )
#define KRATOS_VARIATIONAL_DISTANCE_CALCULATION_PROCESS_INCLUDED
// System includes
#include <string>
#include <iostream>
#include <algorithm>
// External includes
// Project includes
#include "includes/define.h"
#include "containers/model.h"
#include "includes/kratos_flags.h"
#include "elements/distance_calculation_element_simplex.h"
#include "linear_solvers/linear_solver.h"
#include "processes/process.h"
#include "modeler/connectivity_preserve_modeler.h"
#include "solving_strategies/builder_and_solvers/residualbased_block_builder_and_solver.h"
#include "solving_strategies/schemes/residualbased_incrementalupdate_static_scheme.h"
#include "solving_strategies/strategies/residualbased_linear_strategy.h"
#include "utilities/variable_utils.h"
namespace Kratos
{
///@name Kratos Globals
///@{
///@}
///@name Type Definitions
///@{
///@}
///@name Enum's
///@{
///@}
///@name Functions
///@{
///@}
///@name Kratos Classes
///@{
/// Short class definition.
/**takes a model part full of SIMPLICIAL ELEMENTS (triangles and tetras) and recomputes a signed distance function
mantaining as much as possible the position of the zero of the function prior to the call.
This is achieved by minimizing the function ( 1 - norm( gradient( distance ) )**2
with the restriction that "distance" is a finite elment function
*/
template< unsigned int TDim, class TSparseSpace, class TDenseSpace, class TLinearSolver >
class VariationalDistanceCalculationProcess : public Process
{
public:
KRATOS_DEFINE_LOCAL_FLAG(PERFORM_STEP1);
KRATOS_DEFINE_LOCAL_FLAG(DO_EXPENSIVE_CHECKS);
KRATOS_DEFINE_LOCAL_FLAG(CALCULATE_EXACT_DISTANCES_TO_PLANE);
///@name Type Definitions
///@{
typedef Scheme< TSparseSpace, TDenseSpace > SchemeType;
typedef typename SchemeType::Pointer SchemePointerType;
typedef typename BuilderAndSolver<TSparseSpace,TDenseSpace,TLinearSolver>::Pointer BuilderSolverPointerType;
typedef SolvingStrategy< TSparseSpace, TDenseSpace, TLinearSolver > SolvingStrategyType;
///@}
///@name Pointer Definitions
/// Pointer definition of VariationalDistanceCalculationProcess
KRATOS_CLASS_POINTER_DEFINITION(VariationalDistanceCalculationProcess);
///@}
///@name Life Cycle
///@{
/**This process recomputed the distance function mantaining the zero of the existing distance distribution
* for this reason the DISTANCE should be initialized to values distinct from zero in at least some portions of the domain
* alternatively, the DISTANCE shall be fixed to zero at least on some nodes, and the process will compute a positive distance
* respecting that zero
* @param base_model_parr - is the model part on the top of which the calculation will be performed
* @param plinear_solver - linear solver to be used internally
* @max_iterations - maximum number of iteration to be employed in the nonlinear optimization process.
* - can also be set to 0 if a (very) rough approximation is enough
*
* EXAMPLE OF USAGE FROM PYTHON:
*
class distance_linear_solver_settings:
solver_type = "AMGCL"
tolerance = 1E-3
max_iteration = 200
scaling = False
krylov_type = "CG"
smoother_type = "SPAI0"
verbosity = 0
import linear_solver_factory
distance_linear_solver = linear_solver_factory.ConstructSolver(distance_linear_solver_settings)
max_iterations=1
distance_calculator = VariationalDistanceCalculationProcess2D(fluid_model_part, distance_linear_solver, max_iterations)
distance_calculator.Execute()
*/
VariationalDistanceCalculationProcess(
ModelPart& rBaseModelPart,
typename TLinearSolver::Pointer pLinearSolver,
unsigned int MaxIterations = 10,
Flags Options = CALCULATE_EXACT_DISTANCES_TO_PLANE.AsFalse(),
std::string AuxPartName = "RedistanceCalculationPart" )
:
mDistancePartIsInitialized(false),
mMaxIterations(MaxIterations),
mrModel( rBaseModelPart.GetModel() ),
mrBaseModelPart (rBaseModelPart),
mOptions( Options ),
mAuxModelPartName( AuxPartName )
{
KRATOS_TRY
ValidateInput();
// Generate an auxilary model part and populate it by elements of type DistanceCalculationElementSimplex
ReGenerateDistanceModelPart(rBaseModelPart);
auto p_builder_solver = Kratos::make_shared<ResidualBasedBlockBuilderAndSolver<TSparseSpace, TDenseSpace, TLinearSolver> >(pLinearSolver);
InitializeSolutionStrategy(p_builder_solver);
KRATOS_CATCH("")
}
/// Constructor with custom Builder And Solver
/** To be used in the trilinos version, since the trilinos builder and
* solver needs additional data (the EpetraComm).
* @param rBaseModelPart Reference ModelPart for distance calculation.
* @param pLinearSolver Linear solver for the distance system.
* @param MaxIterations Maximum number of non-linear optimization iterations.
* @param Options Configuration flags for the procedure.
* @param AuxPartName Name to be used for the internal distance calculation ModelPart.
*/
VariationalDistanceCalculationProcess(
ModelPart& rBaseModelPart,
typename TLinearSolver::Pointer pLinearSolver,
BuilderSolverPointerType pBuilderAndSolver,
unsigned int MaxIterations = 10,
Flags Options = CALCULATE_EXACT_DISTANCES_TO_PLANE.AsFalse(),
std::string AuxPartName = "RedistanceCalculationPart" )
:
mDistancePartIsInitialized(false),
mMaxIterations(MaxIterations),
mrModel( rBaseModelPart.GetModel() ),
mrBaseModelPart (rBaseModelPart),
mOptions( Options ),
mAuxModelPartName( AuxPartName )
{
KRATOS_TRY
ValidateInput();
// Generate an auxilary model part and populate it by elements of type DistanceCalculationElementSimplex
ReGenerateDistanceModelPart(rBaseModelPart);
InitializeSolutionStrategy(pBuilderAndSolver);
KRATOS_CATCH("")
}
/// Destructor.
~VariationalDistanceCalculationProcess() override
{
Clear();
};
///@}
///@name Operators
///@{
void operator()()
{
Execute();
}
///@}
///@name Operations
///@{
void Execute() override
{
KRATOS_TRY;
if(mDistancePartIsInitialized == false){
ReGenerateDistanceModelPart(mrBaseModelPart);
}
ModelPart& r_distance_model_part = mrModel.GetModelPart( mAuxModelPartName );
// TODO: check flag PERFORM_STEP1
// Step1 - solve a poisson problem with a source term which depends on the sign of the existing distance function
r_distance_model_part.pGetProcessInfo()->SetValue(FRACTIONAL_STEP,1);
// Unfix the distances
const int nnodes = static_cast<int>(r_distance_model_part.NumberOfNodes());
#pragma omp parallel for
for(int i_node = 0; i_node < nnodes; ++i_node){
auto it_node = r_distance_model_part.NodesBegin() + i_node;
double& d = it_node->FastGetSolutionStepValue(DISTANCE);
double& fix_flag = it_node->FastGetSolutionStepValue(FLAG_VARIABLE);
// Free the DISTANCE values
fix_flag = 1.0;
it_node->Free(DISTANCE);
// Save the distances
it_node->SetValue(DISTANCE, d);
if(d == 0){
d = 1.0e-15;
fix_flag = -1.0;
it_node->Fix(DISTANCE);
} else {
if(d > 0.0){
d = 1.0e15; // Set to a large number, to make sure that that the minimal distance is computed according to CaculateTetrahedraDistances
} else {
d = -1.0e15;
}
}
}
const int nelem = static_cast<int>(r_distance_model_part.NumberOfElements());
#pragma omp parallel for
for(int i_elem = 0; i_elem < nelem; ++i_elem){
auto it_elem = r_distance_model_part.ElementsBegin() + i_elem;
array_1d<double,TDim+1> distances;
auto& geom = it_elem->GetGeometry();
for(unsigned int i=0; i<TDim+1; i++){
distances[i] = geom[i].GetValue(DISTANCE);
}
const array_1d<double,TDim+1> original_distances = distances;
// The element is cut by the interface
if(this->IsSplit(distances)){
// Compute the unsigned distance using GeometryUtils
if (mOptions.Is(CALCULATE_EXACT_DISTANCES_TO_PLANE)) {
GeometryUtils::CalculateExactDistancesToPlane(geom, distances);
}
else {
if(TDim==3){
GeometryUtils::CalculateTetrahedraDistances(geom, distances);
}
else {
GeometryUtils::CalculateTriangleDistances(geom, distances);
}
}
// Assign the sign using the original distance values
for(unsigned int i = 0; i < TDim+1; ++i){
if(original_distances[i] < 0){
distances[i] = -distances[i];
}
}
for(unsigned int i = 0; i < TDim+1; ++i){
double &d = geom[i].FastGetSolutionStepValue(DISTANCE);
double &fix_flag = geom[i].FastGetSolutionStepValue(FLAG_VARIABLE);
geom[i].SetLock();
if(std::abs(d) > std::abs(distances[i])){
d = distances[i];
}
fix_flag = -1.0;
geom[i].Fix(DISTANCE);
geom[i].UnSetLock();
}
}
}
// SHALL WE SYNCHRONIZE SOMETHING IN HERE?¿?¿??¿ WE'VE CHANGED THE NODAL DISTANCE VALUES FROM THE ELEMENTS...
this->SynchronizeFixity();
this->SynchronizeDistance();
// Compute the maximum and minimum distance for the fixed nodes
double max_dist = 0.0;
double min_dist = 0.0;
for(int i_node = 0; i_node < nnodes; ++i_node){
auto it_node = r_distance_model_part.NodesBegin() + i_node;
if(it_node->IsFixed(DISTANCE)){
const double& d = it_node->FastGetSolutionStepValue(DISTANCE);
if(d > max_dist){
max_dist = d;
}
if(d < min_dist){
min_dist = d;
}
}
}
// Synchronize the maximum and minimum distance values
const auto &r_communicator = r_distance_model_part.GetCommunicator().GetDataCommunicator();
max_dist = r_communicator.MaxAll(max_dist);
min_dist = r_communicator.MinAll(min_dist);
// Assign the max dist to all of the non-fixed positive nodes
// and the minimum one to the non-fixed negatives
#pragma omp parallel for
for(int i_node = 0; i_node < nnodes; ++i_node){
auto it_node = r_distance_model_part.NodesBegin() + i_node;
if(!it_node->IsFixed(DISTANCE)){
double& d = it_node->FastGetSolutionStepValue(DISTANCE);
if(d>0){
d = max_dist;
} else {
d = min_dist;
}
}
}
mpSolvingStrategy->Solve();
// Step2 - minimize the target residual
r_distance_model_part.pGetProcessInfo()->SetValue(FRACTIONAL_STEP,2);
for(unsigned int it = 0; it<mMaxIterations; it++){
mpSolvingStrategy->Solve();
}
// Unfix the distances
#pragma omp parallel for
for(int i_node = 0; i_node < nnodes; ++i_node){
auto it_node = (r_distance_model_part.NodesBegin()) + i_node;
it_node->Free(DISTANCE);
}
KRATOS_CATCH("")
}
void Clear() override
{
if(mrModel.HasModelPart( mAuxModelPartName ))
mrModel.DeleteModelPart( mAuxModelPartName );
mDistancePartIsInitialized = false;
mpSolvingStrategy->Clear();
}
///@}
///@name Access
///@{
///@}
///@name Inquiry
///@{
///@}
///@name Input and output
///@{
/// Turn back information as a string.
std::string Info() const override
{
return "VariationalDistanceCalculationProcess";
}
/// Print information about this object.
void PrintInfo(std::ostream& rOStream) const override
{
rOStream << "VariationalDistanceCalculationProcess";
}
/// Print object's data.
void PrintData(std::ostream& rOStream) const override
{
}
///@}
///@name Friends
///@{
///@}
protected:
///@name Protected static Member Variables
///@{
///@}
///@name Protected member Variables
///@{
bool mDistancePartIsInitialized;
unsigned int mMaxIterations;
Model& mrModel;
ModelPart& mrBaseModelPart;
Flags mOptions;
std::string mAuxModelPartName;
typename SolvingStrategyType::UniquePointer mpSolvingStrategy;
///@}
///@name Protected Operators
///@{
///@}
///@name Protected Operations
///@{
void ValidateInput()
{
const DataCommunicator& r_comm = mrBaseModelPart.GetCommunicator().GetDataCommunicator();
int num_elements = mrBaseModelPart.NumberOfElements();
int num_nodes = mrBaseModelPart.NumberOfNodes();
if (num_elements > 0)
{
const auto geometry_family = mrBaseModelPart.ElementsBegin()->GetGeometry().GetGeometryFamily();
KRATOS_ERROR_IF( (TDim == 2) && (geometry_family != GeometryData::Kratos_Triangle) )
<< "In 2D the element type is expected to be a triangle." << std::endl;
KRATOS_ERROR_IF( (TDim == 3) && (geometry_family != GeometryData::Kratos_Tetrahedra) )
<< "In 3D the element type is expected to be a tetrahedron" << std::endl;
}
KRATOS_ERROR_IF(r_comm.SumAll(num_nodes) == 0) << "The model part has no nodes." << std::endl;
KRATOS_ERROR_IF(r_comm.SumAll(num_elements) == 0) << "The model Part has no elements." << std::endl;
// Check that required nodal variables are present
VariableUtils().CheckVariableExists<Variable<double > >(DISTANCE, mrBaseModelPart.Nodes());
VariableUtils().CheckVariableExists<Variable<double > >(FLAG_VARIABLE, mrBaseModelPart.Nodes());
}
void InitializeSolutionStrategy(BuilderSolverPointerType pBuilderAndSolver)
{
// Generate a linear strategy
auto p_scheme = Kratos::make_shared< ResidualBasedIncrementalUpdateStaticScheme< TSparseSpace,TDenseSpace > >();
ModelPart& r_distance_model_part = mrModel.GetModelPart( mAuxModelPartName );
bool CalculateReactions = false;
bool ReformDofAtEachIteration = false;
bool CalculateNormDxFlag = false;
mpSolvingStrategy = Kratos::make_unique<ResidualBasedLinearStrategy<TSparseSpace, TDenseSpace, TLinearSolver> >(
r_distance_model_part,
p_scheme,
pBuilderAndSolver,
CalculateReactions,
ReformDofAtEachIteration,
CalculateNormDxFlag);
// TODO: check flag DO_EXPENSIVE_CHECKS
mpSolvingStrategy->Check();
}
virtual void ReGenerateDistanceModelPart(ModelPart& rBaseModelPart)
{
KRATOS_TRY
if(mrModel.HasModelPart( mAuxModelPartName ))
mrModel.DeleteModelPart( mAuxModelPartName );
// Ensure that the nodes have distance as a DOF
VariableUtils().AddDof<Variable<double> >(DISTANCE, rBaseModelPart);
// Generate
ModelPart& r_distance_model_part = mrModel.CreateModelPart( mAuxModelPartName );
Element::Pointer p_distance_element = Kratos::make_intrusive<DistanceCalculationElementSimplex<TDim> >();
ConnectivityPreserveModeler modeler;
modeler.GenerateModelPart(rBaseModelPart, r_distance_model_part, *p_distance_element);
// Using the conditions to mark the boundary with the flag boundary
// Note that we DO NOT add the conditions to the model part
VariableUtils().SetFlag<ModelPart::NodesContainerType>(BOUNDARY, false, r_distance_model_part.Nodes());
// Note that above we have assigned the same geometry. Thus the flag is
// set in the distance model part despite we are iterating the base one
for (auto it_cond = rBaseModelPart.ConditionsBegin(); it_cond != rBaseModelPart.ConditionsEnd(); ++it_cond){
Geometry< Node<3> >& geom = it_cond->GetGeometry();
for(unsigned int i=0; i<geom.size(); i++){
geom[i].Set(BOUNDARY,true);
}
}
rBaseModelPart.GetCommunicator().SynchronizeOrNodalFlags(BOUNDARY);
mDistancePartIsInitialized = true;
KRATOS_CATCH("")
}
///@}
///@name Protected Access
///@{
///@}
///@name Protected Inquiry
///@{
///@}
///@name Protected LifeCycle
///@{
///@}
private:
///@name Static Member Variables
///@{
///@}
///@name Member Variables
///@{
///@}
///@name Private Operators
///@{
///@}
///@name Private Operations
///@{
bool IsSplit(const array_1d<double,TDim+1> &rDistances){
unsigned int positives = 0, negatives = 0;
for(unsigned int i = 0; i < TDim+1; ++i){
if(rDistances[i] >= 0){
++positives;
} else {
++negatives;
}
}
if (positives > 0 && negatives > 0){
return true;
}
return false;
}
void SynchronizeDistance(){
ModelPart& r_distance_model_part = mrModel.GetModelPart( mAuxModelPartName );
auto &r_communicator = r_distance_model_part.GetCommunicator();
// Only required in the MPI case
if(r_communicator.TotalProcesses() != 1){
int nnodes = static_cast<int>(r_distance_model_part.NumberOfNodes());
// Set the distance absolute value
#pragma omp parallel for
for(int i_node = 0; i_node < nnodes; ++i_node){
auto it_node = r_distance_model_part.NodesBegin() + i_node;
it_node->FastGetSolutionStepValue(DISTANCE) = std::abs(it_node->FastGetSolutionStepValue(DISTANCE));
}
// Synchronize the unsigned value to minimum
r_communicator.SynchronizeCurrentDataToMin(DISTANCE);
// Set the distance sign again by retrieving it from the non-historical database
#pragma omp parallel for
for(int i_node = 0; i_node < nnodes; ++i_node){
auto it_node = r_distance_model_part.NodesBegin() + i_node;
if(it_node->GetValue(DISTANCE) < 0.0){
it_node->FastGetSolutionStepValue(DISTANCE) = -it_node->FastGetSolutionStepValue(DISTANCE);
}
}
}
}
void SynchronizeFixity(){
ModelPart& r_distance_model_part = mrModel.GetModelPart( mAuxModelPartName );
auto &r_communicator = r_distance_model_part.GetCommunicator();
// Only required in the MPI case
if(r_communicator.TotalProcesses() != 1){
int nnodes = static_cast<int>(r_distance_model_part.NumberOfNodes());
// Synchronize the fixity flag variable to minium
// (-1.0 means fixed and 1.0 means free)
r_communicator.SynchronizeCurrentDataToMin(FLAG_VARIABLE);
// Set the fixity according to the synchronized flag
#pragma omp parallel for
for(int i_node = 0; i_node < nnodes; ++i_node){
auto it_node = r_distance_model_part.NodesBegin() + i_node;
const double &r_fix_flag = it_node->FastGetSolutionStepValue(FLAG_VARIABLE);
if (r_fix_flag == -1.0){
it_node->Fix(DISTANCE);
}
}
}
}
///@}
///@name Private Access
///@{
///@}
///@name Private Inquiry
///@{
///@}
///@name Un accessible methods
///@{
/// Assignment operator.
VariationalDistanceCalculationProcess& operator=(VariationalDistanceCalculationProcess const& rOther);
/// Copy constructor.
//VariationalDistanceCalculationProcess(VariationalDistanceCalculationProcess const& rOther);
///@}
}; // Class VariationalDistanceCalculationProcess
//avoiding using the macro since this has a template parameter. If there was no template plase use the KRATOS_CREATE_LOCAL_FLAG macro
template< unsigned int TDim,class TSparseSpace, class TDenseSpace, class TLinearSolver >
const Kratos::Flags VariationalDistanceCalculationProcess<TDim,TSparseSpace,TDenseSpace,TLinearSolver>::PERFORM_STEP1(Kratos::Flags::Create(0));
template< unsigned int TDim,class TSparseSpace, class TDenseSpace, class TLinearSolver >
const Kratos::Flags VariationalDistanceCalculationProcess<TDim,TSparseSpace,TDenseSpace,TLinearSolver>::DO_EXPENSIVE_CHECKS(Kratos::Flags::Create(1));
template< unsigned int TDim,class TSparseSpace, class TDenseSpace, class TLinearSolver >
const Kratos::Flags VariationalDistanceCalculationProcess<TDim,TSparseSpace,TDenseSpace,TLinearSolver>::CALCULATE_EXACT_DISTANCES_TO_PLANE(Kratos::Flags::Create(2));
///@}
///@name Type Definitions
///@{
///@}
///@name Input and output
///@{
/// input stream function
template< unsigned int TDim, class TSparseSpace, class TDenseSpace, class TLinearSolver>
inline std::istream& operator >> (std::istream& rIStream,
VariationalDistanceCalculationProcess<TDim,TSparseSpace,TDenseSpace,TLinearSolver>& rThis);
/// output stream function
template< unsigned int TDim, class TSparseSpace, class TDenseSpace, class TLinearSolver>
inline std::ostream& operator << (std::ostream& rOStream,
const VariationalDistanceCalculationProcess<TDim,TSparseSpace,TDenseSpace,TLinearSolver>& rThis)
{
rThis.PrintInfo(rOStream);
rOStream << std::endl;
rThis.PrintData(rOStream);
return rOStream;
}
///@}
} // namespace Kratos.
#endif // KRATOS_VARIATIONAL_DISTANCE_CALCULATION_PROCESS_INCLUDED defined
|
GB_unop__acosh_fp32_fp32.c | //------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_atomics.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB (_unop_apply__acosh_fp32_fp32)
// op(A') function: GB (_unop_tran__acosh_fp32_fp32)
// C type: float
// A type: float
// cast: float cij = aij
// unaryop: cij = acoshf (aij)
#define GB_ATYPE \
float
#define GB_CTYPE \
float
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
float aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = acoshf (x) ;
// casting
#define GB_CAST(z, aij) \
float z = aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
float aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
float z = aij ; \
Cx [pC] = acoshf (z) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_ACOSH || GxB_NO_FP32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__acosh_fp32_fp32)
(
float *Cx, // Cx and Ax may be aliased
const float *Ax,
const int8_t *restrict Ab, // A->b if A is bitmap
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
if (Ab == NULL)
{
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
float aij = Ax [p] ;
float z = aij ;
Cx [p] = acoshf (z) ;
}
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
float aij = Ax [p] ;
float z = aij ;
Cx [p] = acoshf (z) ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__acosh_fp32_fp32)
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
semi_restrict.c | /*BHEADER**********************************************************************
* Copyright (c) 2008, Lawrence Livermore National Security, LLC.
* Produced at the Lawrence Livermore National Laboratory.
* This file is part of HYPRE. See file COPYRIGHT for details.
*
* HYPRE is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License (as published by the Free
* Software Foundation) version 2.1 dated February 1999.
*
* $Revision: 2.23 $
***********************************************************************EHEADER*/
#include "_hypre_struct_ls.h"
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
typedef struct
{
hypre_StructMatrix *R;
HYPRE_Int R_stored_as_transpose;
hypre_ComputePkg *compute_pkg;
hypre_Index cindex;
hypre_Index stride;
HYPRE_Int time_index;
} hypre_SemiRestrictData;
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
void *
hypre_SemiRestrictCreate( )
{
hypre_SemiRestrictData *restrict_data;
restrict_data = hypre_CTAlloc(hypre_SemiRestrictData, 1);
(restrict_data -> time_index) = hypre_InitializeTiming("SemiRestrict");
return (void *) restrict_data;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_SemiRestrictSetup( void *restrict_vdata,
hypre_StructMatrix *R,
HYPRE_Int R_stored_as_transpose,
hypre_StructVector *r,
hypre_StructVector *rc,
hypre_Index cindex,
hypre_Index findex,
hypre_Index stride )
{
hypre_SemiRestrictData *restrict_data = restrict_vdata;
hypre_StructGrid *grid;
hypre_StructStencil *stencil;
hypre_ComputeInfo *compute_info;
hypre_ComputePkg *compute_pkg;
/*----------------------------------------------------------
* Set up the compute package
*----------------------------------------------------------*/
grid = hypre_StructVectorGrid(r);
stencil = hypre_StructMatrixStencil(R);
hypre_CreateComputeInfo(grid, stencil, &compute_info);
hypre_ComputeInfoProjectSend(compute_info, findex, stride);
hypre_ComputeInfoProjectRecv(compute_info, findex, stride);
hypre_ComputeInfoProjectComp(compute_info, cindex, stride);
hypre_ComputePkgCreate(compute_info, hypre_StructVectorDataSpace(r), 1,
grid, &compute_pkg);
/*----------------------------------------------------------
* Set up the restrict data structure
*----------------------------------------------------------*/
(restrict_data -> R) = hypre_StructMatrixRef(R);
(restrict_data -> R_stored_as_transpose) = R_stored_as_transpose;
(restrict_data -> compute_pkg) = compute_pkg;
hypre_CopyIndex(cindex ,(restrict_data -> cindex));
hypre_CopyIndex(stride ,(restrict_data -> stride));
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_SemiRestrict( void *restrict_vdata,
hypre_StructMatrix *R,
hypre_StructVector *r,
hypre_StructVector *rc )
{
hypre_SemiRestrictData *restrict_data = restrict_vdata;
HYPRE_Int R_stored_as_transpose;
hypre_ComputePkg *compute_pkg;
hypre_IndexRef cindex;
hypre_IndexRef stride;
hypre_StructGrid *fgrid;
HYPRE_Int *fgrid_ids;
hypre_StructGrid *cgrid;
hypre_BoxArray *cgrid_boxes;
HYPRE_Int *cgrid_ids;
hypre_CommHandle *comm_handle;
hypre_BoxArrayArray *compute_box_aa;
hypre_BoxArray *compute_box_a;
hypre_Box *compute_box;
hypre_Box *R_dbox;
hypre_Box *r_dbox;
hypre_Box *rc_dbox;
HYPRE_Int Ri;
HYPRE_Int ri;
HYPRE_Int rci;
HYPRE_Int constant_coefficient;
double *Rp0, *Rp1;
double *rp, *rp0, *rp1;
double *rcp;
hypre_Index loop_size;
hypre_IndexRef start;
hypre_Index startc;
hypre_Index stridec;
hypre_StructStencil *stencil;
hypre_Index *stencil_shape;
HYPRE_Int compute_i, fi, ci, j;
/*-----------------------------------------------------------------------
* Initialize some things.
*-----------------------------------------------------------------------*/
hypre_BeginTiming(restrict_data -> time_index);
R_stored_as_transpose = (restrict_data -> R_stored_as_transpose);
compute_pkg = (restrict_data -> compute_pkg);
cindex = (restrict_data -> cindex);
stride = (restrict_data -> stride);
stencil = hypre_StructMatrixStencil(R);
stencil_shape = hypre_StructStencilShape(stencil);
constant_coefficient = hypre_StructMatrixConstantCoefficient(R);
hypre_assert( constant_coefficient==0 || constant_coefficient==1 );
/* ... if A has constant_coefficient==2, R has constant_coefficient==0 */
if (constant_coefficient) hypre_StructVectorClearBoundGhostValues(r, 0);
hypre_SetIndex(stridec, 1, 1, 1);
/*--------------------------------------------------------------------
* Restrict the residual.
*--------------------------------------------------------------------*/
fgrid = hypre_StructVectorGrid(r);
fgrid_ids = hypre_StructGridIDs(fgrid);
cgrid = hypre_StructVectorGrid(rc);
cgrid_boxes = hypre_StructGridBoxes(cgrid);
cgrid_ids = hypre_StructGridIDs(cgrid);
for (compute_i = 0; compute_i < 2; compute_i++)
{
switch(compute_i)
{
case 0:
{
rp = hypre_StructVectorData(r);
hypre_InitializeIndtComputations(compute_pkg, rp, &comm_handle);
compute_box_aa = hypre_ComputePkgIndtBoxes(compute_pkg);
}
break;
case 1:
{
hypre_FinalizeIndtComputations(comm_handle);
compute_box_aa = hypre_ComputePkgDeptBoxes(compute_pkg);
}
break;
}
fi = 0;
hypre_ForBoxI(ci, cgrid_boxes)
{
while (fgrid_ids[fi] != cgrid_ids[ci])
{
fi++;
}
compute_box_a = hypre_BoxArrayArrayBoxArray(compute_box_aa, fi);
R_dbox = hypre_BoxArrayBox(hypre_StructMatrixDataSpace(R), fi);
r_dbox = hypre_BoxArrayBox(hypre_StructVectorDataSpace(r), fi);
rc_dbox = hypre_BoxArrayBox(hypre_StructVectorDataSpace(rc), ci);
if (R_stored_as_transpose)
{
if ( constant_coefficient )
{
Rp0 = hypre_StructMatrixBoxData(R, fi, 1) -
hypre_CCBoxOffsetDistance(R_dbox, stencil_shape[1]);
Rp1 = hypre_StructMatrixBoxData(R, fi, 0);
}
else
{
Rp0 = hypre_StructMatrixBoxData(R, fi, 1) -
hypre_BoxOffsetDistance(R_dbox, stencil_shape[1]);
Rp1 = hypre_StructMatrixBoxData(R, fi, 0);
}
}
else
{
Rp0 = hypre_StructMatrixBoxData(R, fi, 0);
Rp1 = hypre_StructMatrixBoxData(R, fi, 1);
}
rp = hypre_StructVectorBoxData(r, fi);
rp0 = rp + hypre_BoxOffsetDistance(r_dbox, stencil_shape[0]);
rp1 = rp + hypre_BoxOffsetDistance(r_dbox, stencil_shape[1]);
rcp = hypre_StructVectorBoxData(rc, ci);
hypre_ForBoxI(j, compute_box_a)
{
compute_box = hypre_BoxArrayBox(compute_box_a, j);
start = hypre_BoxIMin(compute_box);
hypre_StructMapFineToCoarse(start, cindex, stride, startc);
hypre_BoxGetStrideSize(compute_box, stride, loop_size);
if ( constant_coefficient )
{
Ri = hypre_CCBoxIndexRank( R_dbox, startc );
hypre_BoxLoop2Begin(hypre_StructMatrixDim(R), loop_size,
r_dbox, start, stride, ri,
rc_dbox, startc, stridec, rci);
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(HYPRE_BOX_PRIVATE,ri,rci) HYPRE_SMP_SCHEDULE
#endif
hypre_BoxLoop2For(ri, rci)
{
rcp[rci] = rp[ri] + (Rp0[Ri] * rp0[ri] +
Rp1[Ri] * rp1[ri]);
}
hypre_BoxLoop2End(ri, rci);
}
else
{
hypre_BoxLoop3Begin(hypre_StructMatrixDim(R), loop_size,
R_dbox, startc, stridec, Ri,
r_dbox, start, stride, ri,
rc_dbox, startc, stridec, rci);
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(HYPRE_BOX_PRIVATE,Ri,ri,rci) HYPRE_SMP_SCHEDULE
#endif
hypre_BoxLoop3For(Ri, ri, rci)
{
rcp[rci] = rp[ri] + (Rp0[Ri] * rp0[ri] +
Rp1[Ri] * rp1[ri]);
}
hypre_BoxLoop3End(Ri, ri, rci);
}
}
}
}
/*-----------------------------------------------------------------------
* Return
*-----------------------------------------------------------------------*/
hypre_IncFLOPCount(4*hypre_StructVectorGlobalSize(rc));
hypre_EndTiming(restrict_data -> time_index);
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_SemiRestrictDestroy( void *restrict_vdata )
{
hypre_SemiRestrictData *restrict_data = restrict_vdata;
if (restrict_data)
{
hypre_StructMatrixDestroy(restrict_data -> R);
hypre_ComputePkgDestroy(restrict_data -> compute_pkg);
hypre_FinalizeTiming(restrict_data -> time_index);
hypre_TFree(restrict_data);
}
return hypre_error_flag;
}
|
mish_kernel_ref_fp32.c | /*
* 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.
*/
/*
* Copyright (c) 2021, OPEN AI LAB
* Author:
*/
#include "mish_kernel_ref.h"
#include "graph/tensor.h"
#include "graph/node.h"
#include "graph/graph.h"
#include "module/module.h"
#include "operator/op.h"
#include "utility/float.h"
#include "utility/sys_port.h"
#include "utility/log.h"
#include "device/cpu/cpu_node.h"
#include "device/cpu/cpu_graph.h"
#include "device/cpu/cpu_module.h"
#include <math.h>
int ref_mish_fp32(struct tensor* input_tensor, struct tensor* output_tensor, int num_thread)
{
int w = input_tensor->dims[3];
int h = output_tensor->dims[2];
int channels = input_tensor->dims[1];
int size = h * w;
int c_step = h * w;
float* input_data = (float*)input_tensor->data;
float* out_data = (float*)output_tensor->data;
#pragma omp parallel for num_threads(num_thread)
for (int q = 0; q < channels; q++)
{
float* src = input_data + c_step * q;
float* dst = out_data + c_step * q;
for (int i = 0; i < size; i++)
{
dst[i] = src[i] * tanhf(log(1 + exp(src[i])));
}
}
return 0;
}
|
oskar_cross_correlate_point_time_smearing_omp.c | /*
* Copyright (c) 2013-2015, The University of Oxford
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. 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.
* 3. Neither the name of the University of Oxford 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 HOLDER 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.
*/
#include <math.h>
#include "correlate/private_correlate_functions_inline.h"
#include "correlate/oskar_cross_correlate_point_time_smearing_omp.h"
#include "math/oskar_add_inline.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Single precision. */
void oskar_cross_correlate_point_time_smearing_omp_f(int num_sources,
int num_stations, const float4c* jones, const float* source_I,
const float* source_Q, const float* source_U, const float* source_V,
const float* source_l, const float* source_m, const float* source_n,
const float* station_u, const float* station_v,
const float* station_w, const float* station_x,
const float* station_y, float uv_min_lambda, float uv_max_lambda,
float inv_wavelength, float frac_bandwidth, float time_int_sec,
float gha0_rad, float dec0_rad, float4c* vis)
{
int SQ;
/* Loop over stations. */
#pragma omp parallel for private(SQ) schedule(dynamic, 1)
for (SQ = 0; SQ < num_stations; ++SQ)
{
int SP, i;
const float4c *station_p, *station_q;
/* Pointer to source vector for station q. */
station_q = &jones[SQ * num_sources];
/* Loop over baselines for this station. */
for (SP = SQ + 1; SP < num_stations; ++SP)
{
float uv_len, uu, vv, ww, uu2, vv2, uuvv, du, dv, dw;
float4c sum, guard;
oskar_clear_complex_matrix_f(&sum);
oskar_clear_complex_matrix_f(&guard);
/* Pointer to source vector for station p. */
station_p = &jones[SP * num_sources];
/* Get common baseline values. */
oskar_evaluate_baseline_terms_inline_f(station_u[SP],
station_u[SQ], station_v[SP], station_v[SQ],
station_w[SP], station_w[SQ], inv_wavelength,
frac_bandwidth, &uv_len, &uu, &vv, &ww, &uu2, &vv2, &uuvv);
/* Apply the baseline length filter. */
if (uv_len < uv_min_lambda || uv_len > uv_max_lambda)
continue;
/* Compute the deltas for time-average smearing. */
oskar_evaluate_baseline_deltas_inline_f(station_x[SP],
station_x[SQ], station_y[SP], station_y[SQ],
inv_wavelength, time_int_sec, gha0_rad, dec0_rad,
&du, &dv, &dw);
/* Loop over sources. */
for (i = 0; i < num_sources; ++i)
{
float l, m, n, r1, r2;
/* Get source direction cosines. */
l = source_l[i];
m = source_m[i];
n = source_n[i];
/* Compute bandwidth- and time-smearing terms. */
r1 = oskar_sinc_f(uu * l + vv * m + ww * (n - 1.0f));
r2 = oskar_evaluate_time_smearing_f(du, dv, dw, l, m, n);
r1 *= r2;
/* Accumulate baseline visibility response for source. */
oskar_accumulate_baseline_visibility_for_source_inline_f(&sum,
i, source_I, source_Q, source_U, source_V,
station_p, station_q, r1, &guard);
}
/* Add result to the baseline visibility. */
i = oskar_evaluate_baseline_index_inline(num_stations, SP, SQ);
oskar_add_complex_matrix_in_place_f(&vis[i], &sum);
}
}
}
/* Double precision. */
void oskar_cross_correlate_point_time_smearing_omp_d(int num_sources,
int num_stations, const double4c* jones, const double* source_I,
const double* source_Q, const double* source_U, const double* source_V,
const double* source_l, const double* source_m, const double* source_n,
const double* station_u, const double* station_v,
const double* station_w, const double* station_x,
const double* station_y, double uv_min_lambda, double uv_max_lambda,
double inv_wavelength, double frac_bandwidth, double time_int_sec,
double gha0_rad, double dec0_rad, double4c* vis)
{
int SQ;
/* Loop over stations. */
#pragma omp parallel for private(SQ) schedule(dynamic, 1)
for (SQ = 0; SQ < num_stations; ++SQ)
{
int SP, i;
const double4c *station_p, *station_q;
/* Pointer to source vector for station q. */
station_q = &jones[SQ * num_sources];
/* Loop over baselines for this station. */
for (SP = SQ + 1; SP < num_stations; ++SP)
{
double uv_len, uu, vv, ww, uu2, vv2, uuvv, du, dv, dw;
double4c sum;
oskar_clear_complex_matrix_d(&sum);
/* Pointer to source vector for station p. */
station_p = &jones[SP * num_sources];
/* Get common baseline values. */
oskar_evaluate_baseline_terms_inline_d(station_u[SP],
station_u[SQ], station_v[SP], station_v[SQ],
station_w[SP], station_w[SQ], inv_wavelength,
frac_bandwidth, &uv_len, &uu, &vv, &ww, &uu2, &vv2, &uuvv);
/* Apply the baseline length filter. */
if (uv_len < uv_min_lambda || uv_len > uv_max_lambda)
continue;
/* Compute the deltas for time-average smearing. */
oskar_evaluate_baseline_deltas_inline_d(station_x[SP],
station_x[SQ], station_y[SP], station_y[SQ],
inv_wavelength, time_int_sec, gha0_rad, dec0_rad,
&du, &dv, &dw);
/* Loop over sources. */
for (i = 0; i < num_sources; ++i)
{
double l, m, n, r1, r2;
/* Get source direction cosines. */
l = source_l[i];
m = source_m[i];
n = source_n[i];
/* Compute bandwidth- and time-smearing terms. */
r1 = oskar_sinc_d(uu * l + vv * m + ww * (n - 1.0));
r2 = oskar_evaluate_time_smearing_d(du, dv, dw, l, m, n);
r1 *= r2;
/* Accumulate baseline visibility response for source. */
oskar_accumulate_baseline_visibility_for_source_inline_d(&sum,
i, source_I, source_Q, source_U, source_V,
station_p, station_q, r1);
}
/* Add result to the baseline visibility. */
i = oskar_evaluate_baseline_index_inline(num_stations, SP, SQ);
oskar_add_complex_matrix_in_place_d(&vis[i], &sum);
}
}
}
#ifdef __cplusplus
}
#endif
|
euler.h | #ifndef __euler__
#define __euler__
#include <omp.h>
#include <tbb/parallel_scan.h>
#include <tbb/blocked_range.h>
#include "morton.h"
void eulerTour(midlvl_t const* const mids, const size_t l, size_t *const inIdxs,
size_t *const outIdxs);
template<typename T>
class PrefixSum {
T sum;
T* const y;
const T* const z;
const T id;
public:
PrefixSum(T y_[], const T z_[], const T id) :
sum(id),
y(y_),
z(z_),
id(id) {}
T get_sum() const {
return sum;
}
template<typename Tag>
void operator()(const tbb::blocked_range<int>& r, Tag) {
T temp = sum;
for (int i = r.begin(); i < r.end(); ++i) {
temp = temp + z[i];
if (Tag::is_final_scan())
y[i] = temp;
}
sum = temp;
}
PrefixSum(PrefixSum& b, tbb::split) : sum(b.id), y(b.y), z(b.z), id(id) {}
void reverse_join(PrefixSum& a) {
sum = a.sum + sum;
}
void assign(PrefixSum& b) {
sum = b.sum;
}
};
template<typename T>
void parallelPrefixSum(T* data, const size_t l, const T id) {
PrefixSum<T> body(data, data, id);
tbb::parallel_scan(tbb::blocked_range<int>(0, l), body);
body.get_sum();
return;
}
template<typename T>
void treePrefixSum(T const* const weights, size_t const* const inIdxs,
size_t const* const outIdxs, const size_t l, const T id, T* result) {
T* s = new T[2 * l];
#pragma omp parallel for
for (size_t i = 0; i < l * 2; i++)
s[i] = id;
#pragma omp parallel for
for (size_t i = 0; i < l; i++)
s[inIdxs[i]] = weights[i];
parallelPrefixSum(s, l * 2, id);
#pragma omp parallel for
for (size_t i = 0; i < l; i++)
result[i] = s[outIdxs[i]] - s[inIdxs[i]] + weights[i];
delete[] s;
}
float potential(midlvl_t const* const mids, QTree const* const* const nodes,
point_t const* const points, size_t const* const idxs, const size_t l,
const size_t idx, const point_t& p);
#endif
|
3d25pt_var.c | /*
* Order-1, 3D 25 point stencil with axis-symmetric ariable coefficients
* Adapted from PLUTO and Pochoir test bench
*
* Tareq Malas
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#ifdef LIKWID_PERFMON
#include <likwid.h>
#endif
#include "print_utils.h"
#define TESTS 2
#define MAX(a,b) ((a) > (b) ? a : b)
#define MIN(a,b) ((a) < (b) ? a : b)
/* Subtract the `struct timeval' values X and Y,
* storing the result in RESULT.
*
* Return 1 if the difference is negative, otherwise 0.
*/
int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y)
{
/* Perform the carry for the later subtraction by updating y. */
if (x->tv_usec < y->tv_usec)
{
int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec;
}
if (x->tv_usec - y->tv_usec > 1000000)
{
int nsec = (x->tv_usec - y->tv_usec) / 1000000;
y->tv_usec += 1000000 * nsec;
y->tv_sec -= nsec;
}
/* Compute the time remaining to wait.
* tv_usec is certainly positive.
*/
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;
/* Return 1 if result is negative. */
return x->tv_sec < y->tv_sec;
}
int main(int argc, char *argv[])
{
int t, i, j, k, m, test;
int Nx, Ny, Nz, Nt;
if (argc > 3) {
Nx = atoi(argv[1])+8;
Ny = atoi(argv[2])+8;
Nz = atoi(argv[3])+8;
}
if (argc > 4)
Nt = atoi(argv[4]);
// allocate the arrays
double ****A = (double ****) malloc(sizeof(double***)*2);
for(m=0; m<2;m++){
A[m] = (double ***) malloc(sizeof(double**)*Nz);
for(i=0; i<Nz; i++){
A[m][i] = (double**) malloc(sizeof(double*)*Ny);
for(j=0;j<Ny;j++){
A[m][i][j] = (double*) malloc(sizeof(double)*Nx);
}
}
}
double ****coef = (double ****) malloc(sizeof(double***)*13);
for(m=0; m<13;m++){
coef[m] = (double ***) malloc(sizeof(double**)*Nz);
for(i=0; i<Nz; i++){
coef[m][i] = (double**) malloc(sizeof(double*)*Ny);
for(j=0;j<Ny;j++){
coef[m][i][j] = (double*) malloc(sizeof(double)*Nx);
}
}
}
// tile size information, including extra element to decide the list length
int *tile_size = (int*) malloc(sizeof(int));
tile_size[0] = -1;
// The list is modified here before source-to-source transformations
tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5);
tile_size[0] = 4;
tile_size[1] = 4;
tile_size[2] = 32;
tile_size[3] = 256;
tile_size[4] = -1;
// for timekeeping
int ts_return = -1;
struct timeval start, end, result;
double tdiff = 0.0, min_tdiff=1.e100;
const int BASE = 1024;
// initialize variables
//
srand(42);
for (i = 1; i < Nz; i++) {
for (j = 1; j < Ny; j++) {
for (k = 1; k < Nx; k++) {
A[0][i][j][k] = 1.0 * (rand() % BASE);
}
}
}
for (m=0; m<13; m++) {
for (i=1; i<Nz; i++) {
for (j=1; j<Ny; j++) {
for (k=1; k<Nx; k++) {
coef[m][i][j][k] = 1.0 * (rand() % BASE);
}
}
}
}
#ifdef LIKWID_PERFMON
LIKWID_MARKER_INIT;
#pragma omp parallel
{
LIKWID_MARKER_THREADINIT;
#pragma omp barrier
LIKWID_MARKER_START("calc");
}
#endif
int num_threads = 1;
#if defined(_OPENMP)
num_threads = omp_get_max_threads();
#endif
for(test=0; test<TESTS; test++){
gettimeofday(&start, 0);
// serial execution - Addition: 6 && Multiplication: 2
#pragma scop
for (t = 0; t < Nt; t++) {
for (i = 4; i < Nz-4; i++) {
for (j = 4; j < Ny-4; j++) {
for (k = 4; k < Nx-4; k++) {
A[(t+1)%2][i][j][k] =
coef[0][i][j][k] * A[(t)%2][i ][j ][k ] +
coef[1][i][j][k] * (A[(t)%2][i-1][j ][k ] + A[(t)%2][i+1][j ][k ]) +
coef[2][i][j][k] * (A[(t)%2][i ][j-1][k ] + A[(t)%2][i ][j+1][k ]) +
coef[3][i][j][k] * (A[(t)%2][i ][j ][k-1] + A[(t)%2][i ][j ][k+1]) +
coef[4][i][j][k] * (A[(t)%2][i-2][j ][k ] + A[(t)%2][i+2][j ][k ]) +
coef[5][i][j][k] * (A[(t)%2][i ][j-2][k ] + A[(t)%2][i ][j+2][k ]) +
coef[6][i][j][k] * (A[(t)%2][i ][j ][k-2] + A[(t)%2][i ][j ][k+2]) +
coef[7][i][j][k] * (A[(t)%2][i-3][j ][k ] + A[(t)%2][i+3][j ][k ]) +
coef[8][i][j][k] * (A[(t)%2][i ][j-3][k ] + A[(t)%2][i ][j+3][k ]) +
coef[9][i][j][k] * (A[(t)%2][i ][j ][k-3] + A[(t)%2][i ][j ][k+3]) +
coef[10][i][j][k]* (A[(t)%2][i-4][j ][k ] + A[(t)%2][i+4][j ][k ]) +
coef[11][i][j][k]* (A[(t)%2][i ][j-4][k ] + A[(t)%2][i ][j+4][k ]) +
coef[12][i][j][k]* (A[(t)%2][i ][j ][k-4] + A[(t)%2][i ][j ][k+4]) ;
}
}
}
}
#pragma endscop
gettimeofday(&end, 0);
ts_return = timeval_subtract(&result, &end, &start);
tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6);
min_tdiff = min(min_tdiff, tdiff);
printf("Rank 0 TEST# %d time: %f\n", test, tdiff);
}
PRINT_RESULTS(4, "variable axis-symmetric")
#ifdef LIKWID_PERFMON
#pragma omp parallel
{
LIKWID_MARKER_STOP("calc");
}
LIKWID_MARKER_CLOSE;
#endif
// Free allocated arrays
for(i=0; i<Nz; i++){
for(j=0;j<Ny;j++){
free(A[0][i][j]);
free(A[1][i][j]);
}
free(A[0][i]);
free(A[1][i]);
}
free(A[0]);
free(A[1]);
for(m=0; m<13;m++){
for(i=0; i<Nz; i++){
for(j=0;j<Ny;j++){
free(coef[m][i][j]);
}
free(coef[m][i]);
}
free(coef[m]);
}
return 0;
}
|
conv_dw_kernel_x86.c | /*
* 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.
*/
/*
* Copyright (c) 2020, OPEN AI LAB
* Author: qtang@openailab.com
*/
#include <stdint.h>
#include <stdlib.h>
#include <math.h>
#include "conv_dw_kernel_x86.h"
#if __SSE2__
#include <emmintrin.h>
#endif
#if __AVX__
#include <immintrin.h>
#endif
#define max(a, b) ((a) > (b) ? (a) : (b))
#define min(a, b) ((a) < (b) ? (a) : (b))
void relu(float* data, int size, int activation)
{
for (int i = 0; i < size; i++)
{
data[i] = max(data[i], ( float )0);
if (activation > 0)
{
data[i] = min(data[i], ( float )activation);
}
}
}
void pad(float* input, float* output, int in_h, int in_w, int out_h, int out_w, int top, int left, float v)
{
float* ptr = input;
float* outptr = output;
int y = 0;
// fill top
for (; y < top; y++)
{
int x = 0;
for (; x < out_w; x++)
{
outptr[x] = v;
}
outptr += out_w;
}
// fill center
for (; y < (top + in_h); y++)
{
int x = 0;
for (; x < left; x++)
{
outptr[x] = v;
}
if (in_w < 12)
{
for (; x < (left + in_w); x++)
{
outptr[x] = ptr[x - left];
}
}
else
{
memcpy(outptr + left, ptr, in_w * sizeof(float));
x += in_w;
}
for (; x < out_w; x++)
{
outptr[x] = v;
}
ptr += in_w;
outptr += out_w;
}
// fill bottom
for (; y < out_h; y++)
{
int x = 0;
for (; x < out_w; x++)
{
outptr[x] = v;
}
outptr += out_w;
}
}
#if __AVX__
static void convdw3x3s1(float* output, float* img_data, float* kernel_data, float* bias_data, int inc, int inh, int inw,
int outh, int outw, int num_thread)
{
int inwh = inw * inh;
int outwh = outw * outh;
int channel_count = inc >> 3;
int channel_remain = inc - (channel_count << 3);
// generate the image tmp
float* img_tmp = ( float* )sys_malloc(8 * inwh * (channel_count + 1) * sizeof(float));
float* kernel_tmp = ( float* )sys_malloc(8 * 9 * (channel_count + 1) * sizeof(float));
float* bias_tmp = ( float* )sys_malloc(8 * (channel_count + 1) * sizeof(float));
{
for (int i = 0; i < channel_count; i++)
{
int ii = i * 8;
const float* k0 = img_data + (ii + 0) * inwh;
const float* k1 = img_data + (ii + 1) * inwh;
const float* k2 = img_data + (ii + 2) * inwh;
const float* k3 = img_data + (ii + 3) * inwh;
const float* k4 = img_data + (ii + 4) * inwh;
const float* k5 = img_data + (ii + 5) * inwh;
const float* k6 = img_data + (ii + 6) * inwh;
const float* k7 = img_data + (ii + 7) * inwh;
const float* f0 = kernel_data + (ii + 0) * 9;
const float* f1 = kernel_data + (ii + 1) * 9;
const float* f2 = kernel_data + (ii + 2) * 9;
const float* f3 = kernel_data + (ii + 3) * 9;
const float* f4 = kernel_data + (ii + 4) * 9;
const float* f5 = kernel_data + (ii + 5) * 9;
const float* f6 = kernel_data + (ii + 6) * 9;
const float* f7 = kernel_data + (ii + 7) * 9;
const float* b0 = bias_data + (ii + 0);
const float* b1 = bias_data + (ii + 1);
const float* b2 = bias_data + (ii + 2);
const float* b3 = bias_data + (ii + 3);
const float* b4 = bias_data + (ii + 4);
const float* b5 = bias_data + (ii + 5);
const float* b6 = bias_data + (ii + 6);
const float* b7 = bias_data + (ii + 7);
float* tmp0 = img_tmp + ii * inwh;
float* tmp1 = kernel_tmp + ii * 9;
float* tmp2 = bias_tmp + ii;
for (int j = 0; j < inwh; j++)
{
tmp0[0] = k0[0];
tmp0[1] = k1[0];
tmp0[2] = k2[0];
tmp0[3] = k3[0];
tmp0[4] = k4[0];
tmp0[5] = k5[0];
tmp0[6] = k6[0];
tmp0[7] = k7[0];
tmp0 += 8;
k0++;
k1++;
k2++;
k3++;
k4++;
k5++;
k6++;
k7++;
}
for (int j = 0; j < 9; j++)
{
tmp1[0] = f0[0];
tmp1[1] = f1[0];
tmp1[2] = f2[0];
tmp1[3] = f3[0];
tmp1[4] = f4[0];
tmp1[5] = f5[0];
tmp1[6] = f6[0];
tmp1[7] = f7[0];
tmp1 += 8;
f0++;
f1++;
f2++;
f3++;
f4++;
f5++;
f6++;
f7++;
}
if (bias_data)
{
tmp2[0] = b0[0];
tmp2[1] = b1[0];
tmp2[2] = b2[0];
tmp2[3] = b3[0];
tmp2[4] = b4[0];
tmp2[5] = b5[0];
tmp2[6] = b6[0];
tmp2[7] = b7[0];
}
else
{
tmp2[0] = 0;
tmp2[1] = 0;
tmp2[2] = 0;
tmp2[3] = 0;
tmp2[4] = 0;
tmp2[5] = 0;
tmp2[6] = 0;
tmp2[7] = 0;
}
}
int i = 0;
for (; i + 3 < channel_remain; i += 4)
{
int ii = channel_count * 8 + i;
float* k0 = img_data + (ii + 0) * inwh;
float* k1 = img_data + (ii + 1) * inwh;
float* k2 = img_data + (ii + 2) * inwh;
float* k3 = img_data + (ii + 3) * inwh;
float* f0 = kernel_data + (ii + 0) * 9;
float* f1 = kernel_data + (ii + 1) * 9;
float* f2 = kernel_data + (ii + 2) * 9;
float* f3 = kernel_data + (ii + 3) * 9;
float* b0 = bias_data + (ii + 0);
float* b1 = bias_data + (ii + 1);
float* b2 = bias_data + (ii + 2);
float* b3 = bias_data + (ii + 3);
float* tmp0 = img_tmp + channel_count * 8 * inwh;
float* tmp1 = kernel_tmp + channel_count * 8 * 9;
float* tmp2 = bias_tmp + ii;
for (int j = 0; j < inwh; j++)
{
tmp0[0] = k0[0];
tmp0[1] = k1[0];
tmp0[2] = k2[0];
tmp0[3] = k3[0];
tmp0 += 8;
k0++;
k1++;
k2++;
k3++;
}
for (int j = 0; j < 9; j++)
{
tmp1[0] = f0[0];
tmp1[1] = f1[0];
tmp1[2] = f2[0];
tmp1[3] = f3[0];
tmp1 += 8;
f0++;
f1++;
f2++;
f3++;
}
if (bias_data)
{
tmp2[0] = b0[0];
tmp2[1] = b1[0];
tmp2[2] = b2[0];
tmp2[3] = b3[0];
}
else
{
tmp2[0] = 0;
tmp2[1] = 0;
tmp2[2] = 0;
tmp2[3] = 0;
}
}
for (; i < channel_remain; i++)
{
int ii = channel_count * 8 + i;
float* k0 = img_data + ii * inwh;
float* f0 = kernel_data + ii * 9;
float* b0 = bias_data + ii;
float* tmp0 = img_tmp + channel_count * 8 * inwh;
float* tmp1 = kernel_tmp + channel_count * 8 * 9;
float* tmp2 = bias_tmp + channel_count * 8;
for (int j = 0; j < inwh; j++)
{
tmp0[i] = k0[0];
tmp0 += 8;
k0++;
}
for (int j = 0; j < 9; j++)
{
tmp1[i] = f0[0];
tmp1 += 8;
f0++;
}
if (bias_data)
{
tmp2[i] = b0[0];
}
else
{
tmp2[i] = 0;
}
}
}
float* output_tmp = ( float* )sys_malloc(outwh * (channel_count + 1) * 8 * sizeof(float));
for (int c = 0; c < channel_count + 1; c++)
{
float* ktmp = kernel_tmp + c * 8 * 9;
float* btmp = bias_tmp + c * 8;
for (int i = 0; i < outh; i++)
{
int j = 0;
float* itmp0 = img_tmp + c * 8 * inwh + 8 * i * inw;
float* itmp1 = img_tmp + c * 8 * inwh + 8 * (i + 1) * inw;
float* itmp2 = img_tmp + c * 8 * inwh + 8 * (i + 2) * inw;
float* otmp = output_tmp + c * 8 * outwh + 8 * i * outw;
for (; j + 7 < outw; j += 8)
{
__m256 _sum0 = _mm256_loadu_ps(btmp);
__m256 _sum1 = _mm256_loadu_ps(btmp);
__m256 _sum2 = _mm256_loadu_ps(btmp);
__m256 _sum3 = _mm256_loadu_ps(btmp);
__m256 _sum4 = _mm256_loadu_ps(btmp);
__m256 _sum5 = _mm256_loadu_ps(btmp);
__m256 _sum6 = _mm256_loadu_ps(btmp);
__m256 _sum7 = _mm256_loadu_ps(btmp);
__m256 _va0 = _mm256_loadu_ps(itmp0);
__m256 _va1 = _mm256_loadu_ps(itmp0 + 8);
__m256 _va2 = _mm256_loadu_ps(itmp0 + 16);
__m256 _va3 = _mm256_loadu_ps(itmp0 + 24);
__m256 _va4 = _mm256_loadu_ps(itmp0 + 32);
__m256 _va5 = _mm256_loadu_ps(itmp0 + 40);
__m256 _va6 = _mm256_loadu_ps(itmp0 + 48);
__m256 _va7 = _mm256_loadu_ps(itmp0 + 56);
__m256 _va8 = _mm256_loadu_ps(itmp0 + 64);
__m256 _va9 = _mm256_loadu_ps(itmp0 + 72);
__m256 _vb0 = _mm256_loadu_ps(ktmp);
__m256 _vb1 = _mm256_loadu_ps(ktmp + 8);
__m256 _vb2 = _mm256_loadu_ps(ktmp + 16);
_sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0);
_sum1 = _mm256_fmadd_ps(_va1, _vb0, _sum1);
_sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0);
_sum1 = _mm256_fmadd_ps(_va2, _vb1, _sum1);
_sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0);
_sum2 = _mm256_fmadd_ps(_va2, _vb0, _sum2);
_sum3 = _mm256_fmadd_ps(_va3, _vb0, _sum3);
_sum1 = _mm256_fmadd_ps(_va3, _vb2, _sum1);
_sum2 = _mm256_fmadd_ps(_va3, _vb1, _sum2);
_sum3 = _mm256_fmadd_ps(_va4, _vb1, _sum3);
_sum4 = _mm256_fmadd_ps(_va4, _vb0, _sum4);
_sum2 = _mm256_fmadd_ps(_va4, _vb2, _sum2);
_sum3 = _mm256_fmadd_ps(_va5, _vb2, _sum3);
_sum5 = _mm256_fmadd_ps(_va5, _vb0, _sum5);
_sum4 = _mm256_fmadd_ps(_va5, _vb1, _sum4);
_sum5 = _mm256_fmadd_ps(_va6, _vb1, _sum5);
_sum4 = _mm256_fmadd_ps(_va6, _vb2, _sum4);
_sum6 = _mm256_fmadd_ps(_va6, _vb0, _sum6);
_sum7 = _mm256_fmadd_ps(_va7, _vb0, _sum7);
_sum5 = _mm256_fmadd_ps(_va7, _vb2, _sum5);
_sum6 = _mm256_fmadd_ps(_va7, _vb1, _sum6);
_sum7 = _mm256_fmadd_ps(_va8, _vb1, _sum7);
_sum6 = _mm256_fmadd_ps(_va8, _vb2, _sum6);
_sum7 = _mm256_fmadd_ps(_va9, _vb2, _sum7);
_va0 = _mm256_loadu_ps(itmp1);
_va1 = _mm256_loadu_ps(itmp1 + 8);
_va2 = _mm256_loadu_ps(itmp1 + 16);
_va3 = _mm256_loadu_ps(itmp1 + 24);
_va4 = _mm256_loadu_ps(itmp1 + 32);
_va5 = _mm256_loadu_ps(itmp1 + 40);
_va6 = _mm256_loadu_ps(itmp1 + 48);
_va7 = _mm256_loadu_ps(itmp1 + 56);
_va8 = _mm256_loadu_ps(itmp1 + 64);
_va9 = _mm256_loadu_ps(itmp1 + 72);
_vb0 = _mm256_loadu_ps(ktmp + 24);
_vb1 = _mm256_loadu_ps(ktmp + 32);
_vb2 = _mm256_loadu_ps(ktmp + 40);
_sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0);
_sum1 = _mm256_fmadd_ps(_va1, _vb0, _sum1);
_sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0);
_sum1 = _mm256_fmadd_ps(_va2, _vb1, _sum1);
_sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0);
_sum2 = _mm256_fmadd_ps(_va2, _vb0, _sum2);
_sum3 = _mm256_fmadd_ps(_va3, _vb0, _sum3);
_sum1 = _mm256_fmadd_ps(_va3, _vb2, _sum1);
_sum2 = _mm256_fmadd_ps(_va3, _vb1, _sum2);
_sum3 = _mm256_fmadd_ps(_va4, _vb1, _sum3);
_sum4 = _mm256_fmadd_ps(_va4, _vb0, _sum4);
_sum2 = _mm256_fmadd_ps(_va4, _vb2, _sum2);
_sum3 = _mm256_fmadd_ps(_va5, _vb2, _sum3);
_sum5 = _mm256_fmadd_ps(_va5, _vb0, _sum5);
_sum4 = _mm256_fmadd_ps(_va5, _vb1, _sum4);
_sum5 = _mm256_fmadd_ps(_va6, _vb1, _sum5);
_sum4 = _mm256_fmadd_ps(_va6, _vb2, _sum4);
_sum6 = _mm256_fmadd_ps(_va6, _vb0, _sum6);
_sum7 = _mm256_fmadd_ps(_va7, _vb0, _sum7);
_sum5 = _mm256_fmadd_ps(_va7, _vb2, _sum5);
_sum6 = _mm256_fmadd_ps(_va7, _vb1, _sum6);
_sum7 = _mm256_fmadd_ps(_va8, _vb1, _sum7);
_sum6 = _mm256_fmadd_ps(_va8, _vb2, _sum6);
_sum7 = _mm256_fmadd_ps(_va9, _vb2, _sum7);
_va0 = _mm256_loadu_ps(itmp2);
_va1 = _mm256_loadu_ps(itmp2 + 8);
_va2 = _mm256_loadu_ps(itmp2 + 16);
_va3 = _mm256_loadu_ps(itmp2 + 24);
_va4 = _mm256_loadu_ps(itmp2 + 32);
_va5 = _mm256_loadu_ps(itmp2 + 40);
_va6 = _mm256_loadu_ps(itmp2 + 48);
_va7 = _mm256_loadu_ps(itmp2 + 56);
_va8 = _mm256_loadu_ps(itmp2 + 64);
_va9 = _mm256_loadu_ps(itmp2 + 72);
_vb0 = _mm256_loadu_ps(ktmp + 48);
_vb1 = _mm256_loadu_ps(ktmp + 56);
_vb2 = _mm256_loadu_ps(ktmp + 64);
_sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0);
_sum1 = _mm256_fmadd_ps(_va1, _vb0, _sum1);
_sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0);
_sum1 = _mm256_fmadd_ps(_va2, _vb1, _sum1);
_sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0);
_sum2 = _mm256_fmadd_ps(_va2, _vb0, _sum2);
_sum3 = _mm256_fmadd_ps(_va3, _vb0, _sum3);
_sum1 = _mm256_fmadd_ps(_va3, _vb2, _sum1);
_sum2 = _mm256_fmadd_ps(_va3, _vb1, _sum2);
_sum3 = _mm256_fmadd_ps(_va4, _vb1, _sum3);
_sum4 = _mm256_fmadd_ps(_va4, _vb0, _sum4);
_sum2 = _mm256_fmadd_ps(_va4, _vb2, _sum2);
_sum3 = _mm256_fmadd_ps(_va5, _vb2, _sum3);
_sum5 = _mm256_fmadd_ps(_va5, _vb0, _sum5);
_sum4 = _mm256_fmadd_ps(_va5, _vb1, _sum4);
_sum5 = _mm256_fmadd_ps(_va6, _vb1, _sum5);
_sum4 = _mm256_fmadd_ps(_va6, _vb2, _sum4);
_sum6 = _mm256_fmadd_ps(_va6, _vb0, _sum6);
_sum7 = _mm256_fmadd_ps(_va7, _vb0, _sum7);
_sum5 = _mm256_fmadd_ps(_va7, _vb2, _sum5);
_sum6 = _mm256_fmadd_ps(_va7, _vb1, _sum6);
_sum7 = _mm256_fmadd_ps(_va8, _vb1, _sum7);
_sum6 = _mm256_fmadd_ps(_va8, _vb2, _sum6);
_sum7 = _mm256_fmadd_ps(_va9, _vb2, _sum7);
_mm256_storeu_ps(otmp, _sum0);
_mm256_storeu_ps(otmp + 8, _sum1);
_mm256_storeu_ps(otmp + 16, _sum2);
_mm256_storeu_ps(otmp + 24, _sum3);
_mm256_storeu_ps(otmp + 32, _sum4);
_mm256_storeu_ps(otmp + 40, _sum5);
_mm256_storeu_ps(otmp + 48, _sum6);
_mm256_storeu_ps(otmp + 56, _sum7);
itmp0 += 64;
itmp1 += 64;
itmp2 += 64;
otmp += 64;
}
for (; j + 3 < outw; j += 4)
{
__m256 _sum0 = _mm256_loadu_ps(btmp);
__m256 _sum1 = _mm256_loadu_ps(btmp);
__m256 _sum2 = _mm256_loadu_ps(btmp);
__m256 _sum3 = _mm256_loadu_ps(btmp);
__m256 _va0 = _mm256_loadu_ps(itmp0);
__m256 _va1 = _mm256_loadu_ps(itmp0 + 8);
__m256 _va2 = _mm256_loadu_ps(itmp0 + 16);
__m256 _va3 = _mm256_loadu_ps(itmp0 + 24);
__m256 _va4 = _mm256_loadu_ps(itmp0 + 32);
__m256 _va5 = _mm256_loadu_ps(itmp0 + 40);
__m256 _vb0 = _mm256_loadu_ps(ktmp);
__m256 _vb1 = _mm256_loadu_ps(ktmp + 8);
__m256 _vb2 = _mm256_loadu_ps(ktmp + 16);
_sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0);
_sum1 = _mm256_fmadd_ps(_va1, _vb0, _sum1);
_sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0);
_sum1 = _mm256_fmadd_ps(_va2, _vb1, _sum1);
_sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0);
_sum2 = _mm256_fmadd_ps(_va2, _vb0, _sum2);
_sum3 = _mm256_fmadd_ps(_va3, _vb0, _sum3);
_sum1 = _mm256_fmadd_ps(_va3, _vb2, _sum1);
_sum2 = _mm256_fmadd_ps(_va3, _vb1, _sum2);
_sum3 = _mm256_fmadd_ps(_va4, _vb1, _sum3);
_sum2 = _mm256_fmadd_ps(_va4, _vb2, _sum2);
_sum3 = _mm256_fmadd_ps(_va5, _vb2, _sum3);
_va0 = _mm256_loadu_ps(itmp1);
_va1 = _mm256_loadu_ps(itmp1 + 8);
_va2 = _mm256_loadu_ps(itmp1 + 16);
_va3 = _mm256_loadu_ps(itmp1 + 24);
_va4 = _mm256_loadu_ps(itmp1 + 32);
_va5 = _mm256_loadu_ps(itmp1 + 40);
_vb0 = _mm256_loadu_ps(ktmp + 24);
_vb1 = _mm256_loadu_ps(ktmp + 32);
_vb2 = _mm256_loadu_ps(ktmp + 40);
_sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0);
_sum1 = _mm256_fmadd_ps(_va1, _vb0, _sum1);
_sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0);
_sum1 = _mm256_fmadd_ps(_va2, _vb1, _sum1);
_sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0);
_sum2 = _mm256_fmadd_ps(_va2, _vb0, _sum2);
_sum3 = _mm256_fmadd_ps(_va3, _vb0, _sum3);
_sum1 = _mm256_fmadd_ps(_va3, _vb2, _sum1);
_sum2 = _mm256_fmadd_ps(_va3, _vb1, _sum2);
_sum3 = _mm256_fmadd_ps(_va4, _vb1, _sum3);
_sum2 = _mm256_fmadd_ps(_va4, _vb2, _sum2);
_sum3 = _mm256_fmadd_ps(_va5, _vb2, _sum3);
_va0 = _mm256_loadu_ps(itmp2);
_va1 = _mm256_loadu_ps(itmp2 + 8);
_va2 = _mm256_loadu_ps(itmp2 + 16);
_va3 = _mm256_loadu_ps(itmp2 + 24);
_va4 = _mm256_loadu_ps(itmp2 + 32);
_va5 = _mm256_loadu_ps(itmp2 + 40);
_vb0 = _mm256_loadu_ps(ktmp + 48);
_vb1 = _mm256_loadu_ps(ktmp + 56);
_vb2 = _mm256_loadu_ps(ktmp + 64);
_sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0);
_sum1 = _mm256_fmadd_ps(_va1, _vb0, _sum1);
_sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0);
_sum1 = _mm256_fmadd_ps(_va2, _vb1, _sum1);
_sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0);
_sum2 = _mm256_fmadd_ps(_va2, _vb0, _sum2);
_sum3 = _mm256_fmadd_ps(_va3, _vb0, _sum3);
_sum1 = _mm256_fmadd_ps(_va3, _vb2, _sum1);
_sum2 = _mm256_fmadd_ps(_va3, _vb1, _sum2);
_sum3 = _mm256_fmadd_ps(_va4, _vb1, _sum3);
_sum2 = _mm256_fmadd_ps(_va4, _vb2, _sum2);
_sum3 = _mm256_fmadd_ps(_va5, _vb2, _sum3);
_mm256_storeu_ps(otmp, _sum0);
_mm256_storeu_ps(otmp + 8, _sum1);
_mm256_storeu_ps(otmp + 16, _sum2);
_mm256_storeu_ps(otmp + 24, _sum3);
itmp0 += 32;
itmp1 += 32;
itmp2 += 32;
otmp += 32;
}
for (; j + 1 < outw; j += 2)
{
__m256 _sum0 = _mm256_loadu_ps(btmp);
__m256 _sum1 = _mm256_loadu_ps(btmp);
__m256 _va0 = _mm256_loadu_ps(itmp0);
__m256 _va1 = _mm256_loadu_ps(itmp0 + 8);
__m256 _va2 = _mm256_loadu_ps(itmp0 + 16);
__m256 _va3 = _mm256_loadu_ps(itmp0 + 24);
__m256 _vb0 = _mm256_loadu_ps(ktmp);
__m256 _vb1 = _mm256_loadu_ps(ktmp + 8);
__m256 _vb2 = _mm256_loadu_ps(ktmp + 16);
_sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0);
_sum1 = _mm256_fmadd_ps(_va1, _vb0, _sum1);
_sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0);
_sum1 = _mm256_fmadd_ps(_va2, _vb1, _sum1);
_sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0);
_sum1 = _mm256_fmadd_ps(_va3, _vb2, _sum1);
_va0 = _mm256_loadu_ps(itmp1);
_va1 = _mm256_loadu_ps(itmp1 + 8);
_va2 = _mm256_loadu_ps(itmp1 + 16);
_va3 = _mm256_loadu_ps(itmp1 + 24);
_vb0 = _mm256_loadu_ps(ktmp + 24);
_vb1 = _mm256_loadu_ps(ktmp + 32);
_vb2 = _mm256_loadu_ps(ktmp + 40);
_sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0);
_sum1 = _mm256_fmadd_ps(_va1, _vb0, _sum1);
_sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0);
_sum1 = _mm256_fmadd_ps(_va2, _vb1, _sum1);
_sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0);
_sum1 = _mm256_fmadd_ps(_va3, _vb2, _sum1);
_va0 = _mm256_loadu_ps(itmp2);
_va1 = _mm256_loadu_ps(itmp2 + 8);
_va2 = _mm256_loadu_ps(itmp2 + 16);
_va3 = _mm256_loadu_ps(itmp2 + 24);
_vb0 = _mm256_loadu_ps(ktmp + 48);
_vb1 = _mm256_loadu_ps(ktmp + 56);
_vb2 = _mm256_loadu_ps(ktmp + 64);
_sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0);
_sum1 = _mm256_fmadd_ps(_va1, _vb0, _sum1);
_sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0);
_sum1 = _mm256_fmadd_ps(_va2, _vb1, _sum1);
_sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0);
_sum1 = _mm256_fmadd_ps(_va3, _vb2, _sum1);
_mm256_storeu_ps(otmp, _sum0);
_mm256_storeu_ps(otmp + 8, _sum1);
itmp0 += 16;
itmp1 += 16;
itmp2 += 16;
otmp += 16;
}
for (; j < outw; j++)
{
__m256 _sum0 = _mm256_loadu_ps(btmp);
__m256 _va0 = _mm256_loadu_ps(itmp0);
__m256 _va1 = _mm256_loadu_ps(itmp0 + 8);
__m256 _va2 = _mm256_loadu_ps(itmp0 + 16);
__m256 _vb0 = _mm256_loadu_ps(ktmp);
__m256 _vb1 = _mm256_loadu_ps(ktmp + 8);
__m256 _vb2 = _mm256_loadu_ps(ktmp + 16);
_sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0);
_sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0);
_sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0);
_va0 = _mm256_loadu_ps(itmp1);
_va1 = _mm256_loadu_ps(itmp1 + 8);
_va2 = _mm256_loadu_ps(itmp1 + 16);
_vb0 = _mm256_loadu_ps(ktmp + 24);
_vb1 = _mm256_loadu_ps(ktmp + 32);
_vb2 = _mm256_loadu_ps(ktmp + 40);
_sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0);
_sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0);
_sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0);
_va0 = _mm256_loadu_ps(itmp2);
_va1 = _mm256_loadu_ps(itmp2 + 8);
_va2 = _mm256_loadu_ps(itmp2 + 16);
_vb0 = _mm256_loadu_ps(ktmp + 48);
_vb1 = _mm256_loadu_ps(ktmp + 56);
_vb2 = _mm256_loadu_ps(ktmp + 64);
_sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0);
_sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0);
_sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0);
_mm256_storeu_ps(otmp, _sum0);
itmp0 += 8;
itmp1 += 8;
itmp2 += 8;
otmp += 8;
}
}
}
// load_data
{
for (int i = 0; i < channel_count; i++)
{
float* otmp = output_tmp + i * 8 * outwh;
float* tmp0 = output + i * 8 * outwh;
float* tmp1 = output + i * 8 * outwh + 1 * outwh;
float* tmp2 = output + i * 8 * outwh + 2 * outwh;
float* tmp3 = output + i * 8 * outwh + 3 * outwh;
float* tmp4 = output + i * 8 * outwh + 4 * outwh;
float* tmp5 = output + i * 8 * outwh + 5 * outwh;
float* tmp6 = output + i * 8 * outwh + 6 * outwh;
float* tmp7 = output + i * 8 * outwh + 7 * outwh;
for (int i = 0; i < outwh; i++)
{
tmp0[0] = otmp[0];
tmp1[0] = otmp[1];
tmp2[0] = otmp[2];
tmp3[0] = otmp[3];
tmp4[0] = otmp[4];
tmp5[0] = otmp[5];
tmp6[0] = otmp[6];
tmp7[0] = otmp[7];
otmp += 8;
tmp0++;
tmp1++;
tmp2++;
tmp3++;
tmp4++;
tmp5++;
tmp6++;
tmp7++;
}
}
int i = 0;
for (; i + 3 < channel_remain; i += 4)
{
int ii = channel_count * 8 + i;
float* otmp = output_tmp + ii * outwh;
float* tmp0 = output + ii * outwh;
float* tmp1 = output + ii * outwh + 1 * outwh;
float* tmp2 = output + ii * outwh + 2 * outwh;
float* tmp3 = output + ii * outwh + 3 * outwh;
for (int j = 0; j < outwh; j++)
{
tmp0[0] = otmp[0];
tmp1[0] = otmp[1];
tmp2[0] = otmp[2];
tmp3[0] = otmp[3];
otmp += 8;
tmp0++;
tmp1++;
tmp2++;
tmp3++;
}
}
for (; i < channel_remain; i++)
{
int ii = channel_count * 8 + i;
float* otmp = output_tmp + channel_count * 8 * outwh;
float* tmp0 = output + ii * outwh;
for (int j = 0; j < outwh; j++)
{
tmp0[0] = otmp[i];
otmp += 8;
tmp0++;
}
}
}
sys_free(output_tmp);
sys_free(img_tmp);
sys_free(kernel_tmp);
sys_free(bias_tmp);
}
static void convdw3x3s2(float* output, float* img_data, float* kernel_data, float* bias_data, int inc, int inh, int inw,
int outh, int outw, int num_thread)
{
int inwh = inw * inh;
int outwh = outw * outh;
int channel_count = inc >> 3;
int channel_remain = inc - (channel_count << 3);
// generate the image tmp
float* img_tmp = ( float* )sys_malloc(8 * inwh * (channel_count + 1) * sizeof(float));
float* kernel_tmp = ( float* )sys_malloc(8 * 9 * (channel_count + 1) * sizeof(float));
float* bias_tmp = ( float* )sys_malloc(8 * (channel_count + 1) * sizeof(float));
{
for (int i = 0; i < channel_count; i++)
{
int ii = i * 8;
const float* k0 = img_data + (ii + 0) * inwh;
const float* k1 = img_data + (ii + 1) * inwh;
const float* k2 = img_data + (ii + 2) * inwh;
const float* k3 = img_data + (ii + 3) * inwh;
const float* k4 = img_data + (ii + 4) * inwh;
const float* k5 = img_data + (ii + 5) * inwh;
const float* k6 = img_data + (ii + 6) * inwh;
const float* k7 = img_data + (ii + 7) * inwh;
const float* f0 = kernel_data + (ii + 0) * 9;
const float* f1 = kernel_data + (ii + 1) * 9;
const float* f2 = kernel_data + (ii + 2) * 9;
const float* f3 = kernel_data + (ii + 3) * 9;
const float* f4 = kernel_data + (ii + 4) * 9;
const float* f5 = kernel_data + (ii + 5) * 9;
const float* f6 = kernel_data + (ii + 6) * 9;
const float* f7 = kernel_data + (ii + 7) * 9;
const float* b0 = bias_data + (ii + 0);
const float* b1 = bias_data + (ii + 1);
const float* b2 = bias_data + (ii + 2);
const float* b3 = bias_data + (ii + 3);
const float* b4 = bias_data + (ii + 4);
const float* b5 = bias_data + (ii + 5);
const float* b6 = bias_data + (ii + 6);
const float* b7 = bias_data + (ii + 7);
float* tmp0 = img_tmp + ii * inwh;
float* tmp1 = kernel_tmp + ii * 9;
float* tmp2 = bias_tmp + ii;
for (int j = 0; j < inwh; j++)
{
tmp0[0] = k0[0];
tmp0[1] = k1[0];
tmp0[2] = k2[0];
tmp0[3] = k3[0];
tmp0[4] = k4[0];
tmp0[5] = k5[0];
tmp0[6] = k6[0];
tmp0[7] = k7[0];
tmp0 += 8;
k0++;
k1++;
k2++;
k3++;
k4++;
k5++;
k6++;
k7++;
}
for (int j = 0; j < 9; j++)
{
tmp1[0] = f0[0];
tmp1[1] = f1[0];
tmp1[2] = f2[0];
tmp1[3] = f3[0];
tmp1[4] = f4[0];
tmp1[5] = f5[0];
tmp1[6] = f6[0];
tmp1[7] = f7[0];
tmp1 += 8;
f0++;
f1++;
f2++;
f3++;
f4++;
f5++;
f6++;
f7++;
}
if (bias_data)
{
tmp2[0] = b0[0];
tmp2[1] = b1[0];
tmp2[2] = b2[0];
tmp2[3] = b3[0];
tmp2[4] = b4[0];
tmp2[5] = b5[0];
tmp2[6] = b6[0];
tmp2[7] = b7[0];
}
else
{
tmp2[0] = 0;
tmp2[1] = 0;
tmp2[2] = 0;
tmp2[3] = 0;
tmp2[4] = 0;
tmp2[5] = 0;
tmp2[6] = 0;
tmp2[7] = 0;
}
}
int i = 0;
for (; i + 3 < channel_remain; i += 4)
{
int ii = channel_count * 8 + i;
float* k0 = img_data + (ii + 0) * inwh;
float* k1 = img_data + (ii + 1) * inwh;
float* k2 = img_data + (ii + 2) * inwh;
float* k3 = img_data + (ii + 3) * inwh;
float* f0 = kernel_data + (ii + 0) * 9;
float* f1 = kernel_data + (ii + 1) * 9;
float* f2 = kernel_data + (ii + 2) * 9;
float* f3 = kernel_data + (ii + 3) * 9;
float* b0 = bias_data + (ii + 0);
float* b1 = bias_data + (ii + 1);
float* b2 = bias_data + (ii + 2);
float* b3 = bias_data + (ii + 3);
float* tmp0 = img_tmp + channel_count * 8 * inwh;
float* tmp1 = kernel_tmp + channel_count * 8 * 9;
float* tmp2 = bias_tmp + ii;
for (int j = 0; j < inwh; j++)
{
tmp0[0] = k0[0];
tmp0[1] = k1[0];
tmp0[2] = k2[0];
tmp0[3] = k3[0];
tmp0 += 8;
k0++;
k1++;
k2++;
k3++;
}
for (int j = 0; j < 9; j++)
{
tmp1[0] = f0[0];
tmp1[1] = f1[0];
tmp1[2] = f2[0];
tmp1[3] = f3[0];
tmp1 += 8;
f0++;
f1++;
f2++;
f3++;
}
if (bias_data)
{
tmp2[0] = b0[0];
tmp2[1] = b1[0];
tmp2[2] = b2[0];
tmp2[3] = b3[0];
}
else
{
tmp2[0] = 0;
tmp2[1] = 0;
tmp2[2] = 0;
tmp2[3] = 0;
}
}
for (; i < channel_remain; i++)
{
int ii = channel_count * 8 + i;
float* k0 = img_data + ii * inwh;
float* f0 = kernel_data + ii * 9;
float* b0 = bias_data + ii;
float* tmp0 = img_tmp + channel_count * 8 * inwh;
float* tmp1 = kernel_tmp + channel_count * 8 * 9;
float* tmp2 = bias_tmp + channel_count * 8;
for (int j = 0; j < inwh; j++)
{
tmp0[i] = k0[0];
tmp0 += 8;
k0++;
}
for (int j = 0; j < 9; j++)
{
tmp1[i] = f0[0];
tmp1 += 8;
f0++;
}
if (bias_data)
{
tmp2[i] = b0[0];
}
else
{
tmp2[i] = 0;
}
}
}
float* output_tmp = ( float* )sys_malloc(outwh * (channel_count + 1) * 8 * sizeof(float));
for (int c = 0; c < channel_count + 1; c++)
{
float* ktmp = kernel_tmp + c * 8 * 9;
float* btmp = bias_tmp + c * 8;
for (int i = 0; i < outh; i++)
{
int j = 0;
float* itmp0 = img_tmp + c * 8 * inwh + 8 * i * 2 * inw;
float* itmp1 = img_tmp + c * 8 * inwh + 8 * (i * 2 + 1) * inw;
float* itmp2 = img_tmp + c * 8 * inwh + 8 * (i * 2 + 2) * inw;
float* otmp = output_tmp + c * 8 * outwh + 8 * i * outw;
for (; j + 3 < outw; j += 4)
{
__m256 _sum0 = _mm256_loadu_ps(btmp);
__m256 _sum1 = _mm256_loadu_ps(btmp);
__m256 _sum2 = _mm256_loadu_ps(btmp);
__m256 _sum3 = _mm256_loadu_ps(btmp);
__m256 _va0 = _mm256_loadu_ps(itmp0);
__m256 _va1 = _mm256_loadu_ps(itmp0 + 8);
__m256 _va2 = _mm256_loadu_ps(itmp0 + 16);
__m256 _va3 = _mm256_loadu_ps(itmp0 + 24);
__m256 _va4 = _mm256_loadu_ps(itmp0 + 32);
__m256 _va5 = _mm256_loadu_ps(itmp0 + 40);
__m256 _va6 = _mm256_loadu_ps(itmp0 + 48);
__m256 _va7 = _mm256_loadu_ps(itmp0 + 56);
__m256 _va8 = _mm256_loadu_ps(itmp0 + 64);
__m256 _vb0 = _mm256_loadu_ps(ktmp);
__m256 _vb1 = _mm256_loadu_ps(ktmp + 8);
__m256 _vb2 = _mm256_loadu_ps(ktmp + 16);
_sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0);
_sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0);
_sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0);
_sum1 = _mm256_fmadd_ps(_va2, _vb0, _sum1);
_sum1 = _mm256_fmadd_ps(_va3, _vb1, _sum1);
_sum1 = _mm256_fmadd_ps(_va4, _vb2, _sum1);
_sum2 = _mm256_fmadd_ps(_va4, _vb0, _sum2);
_sum2 = _mm256_fmadd_ps(_va5, _vb1, _sum2);
_sum2 = _mm256_fmadd_ps(_va6, _vb2, _sum2);
_sum3 = _mm256_fmadd_ps(_va6, _vb0, _sum3);
_sum3 = _mm256_fmadd_ps(_va7, _vb1, _sum3);
_sum3 = _mm256_fmadd_ps(_va8, _vb2, _sum3);
_va0 = _mm256_loadu_ps(itmp1);
_va1 = _mm256_loadu_ps(itmp1 + 8);
_va2 = _mm256_loadu_ps(itmp1 + 16);
_va3 = _mm256_loadu_ps(itmp1 + 24);
_va4 = _mm256_loadu_ps(itmp1 + 32);
_va5 = _mm256_loadu_ps(itmp1 + 40);
_va6 = _mm256_loadu_ps(itmp1 + 48);
_va7 = _mm256_loadu_ps(itmp1 + 56);
_va8 = _mm256_loadu_ps(itmp1 + 64);
_vb0 = _mm256_loadu_ps(ktmp + 24);
_vb1 = _mm256_loadu_ps(ktmp + 32);
_vb2 = _mm256_loadu_ps(ktmp + 40);
_sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0);
_sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0);
_sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0);
_sum1 = _mm256_fmadd_ps(_va2, _vb0, _sum1);
_sum1 = _mm256_fmadd_ps(_va3, _vb1, _sum1);
_sum1 = _mm256_fmadd_ps(_va4, _vb2, _sum1);
_sum2 = _mm256_fmadd_ps(_va4, _vb0, _sum2);
_sum2 = _mm256_fmadd_ps(_va5, _vb1, _sum2);
_sum2 = _mm256_fmadd_ps(_va6, _vb2, _sum2);
_sum3 = _mm256_fmadd_ps(_va6, _vb0, _sum3);
_sum3 = _mm256_fmadd_ps(_va7, _vb1, _sum3);
_sum3 = _mm256_fmadd_ps(_va8, _vb2, _sum3);
_va0 = _mm256_loadu_ps(itmp2);
_va1 = _mm256_loadu_ps(itmp2 + 8);
_va2 = _mm256_loadu_ps(itmp2 + 16);
_va3 = _mm256_loadu_ps(itmp2 + 24);
_va4 = _mm256_loadu_ps(itmp2 + 32);
_va5 = _mm256_loadu_ps(itmp2 + 40);
_va6 = _mm256_loadu_ps(itmp2 + 48);
_va7 = _mm256_loadu_ps(itmp2 + 56);
_va8 = _mm256_loadu_ps(itmp2 + 64);
_vb0 = _mm256_loadu_ps(ktmp + 48);
_vb1 = _mm256_loadu_ps(ktmp + 56);
_vb2 = _mm256_loadu_ps(ktmp + 64);
_sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0);
_sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0);
_sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0);
_sum1 = _mm256_fmadd_ps(_va2, _vb0, _sum1);
_sum1 = _mm256_fmadd_ps(_va3, _vb1, _sum1);
_sum1 = _mm256_fmadd_ps(_va4, _vb2, _sum1);
_sum2 = _mm256_fmadd_ps(_va4, _vb0, _sum2);
_sum2 = _mm256_fmadd_ps(_va5, _vb1, _sum2);
_sum2 = _mm256_fmadd_ps(_va6, _vb2, _sum2);
_sum3 = _mm256_fmadd_ps(_va6, _vb0, _sum3);
_sum3 = _mm256_fmadd_ps(_va7, _vb1, _sum3);
_sum3 = _mm256_fmadd_ps(_va8, _vb2, _sum3);
_mm256_storeu_ps(otmp, _sum0);
_mm256_storeu_ps(otmp + 8, _sum1);
_mm256_storeu_ps(otmp + 16, _sum2);
_mm256_storeu_ps(otmp + 24, _sum3);
itmp0 += 64;
itmp1 += 64;
itmp2 += 64;
otmp += 32;
}
for (; j + 1 < outw; j += 2)
{
__m256 _sum0 = _mm256_loadu_ps(btmp);
__m256 _sum1 = _mm256_loadu_ps(btmp);
__m256 _va0 = _mm256_loadu_ps(itmp0);
__m256 _va1 = _mm256_loadu_ps(itmp0 + 8);
__m256 _va2 = _mm256_loadu_ps(itmp0 + 16);
__m256 _va3 = _mm256_loadu_ps(itmp0 + 24);
__m256 _va4 = _mm256_loadu_ps(itmp0 + 32);
__m256 _vb0 = _mm256_loadu_ps(ktmp);
__m256 _vb1 = _mm256_loadu_ps(ktmp + 8);
__m256 _vb2 = _mm256_loadu_ps(ktmp + 16);
_sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0);
_sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0);
_sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0);
_sum1 = _mm256_fmadd_ps(_va2, _vb0, _sum1);
_sum1 = _mm256_fmadd_ps(_va3, _vb1, _sum1);
_sum1 = _mm256_fmadd_ps(_va4, _vb2, _sum1);
_va0 = _mm256_loadu_ps(itmp1);
_va1 = _mm256_loadu_ps(itmp1 + 8);
_va2 = _mm256_loadu_ps(itmp1 + 16);
_va3 = _mm256_loadu_ps(itmp1 + 24);
_va4 = _mm256_loadu_ps(itmp1 + 32);
_vb0 = _mm256_loadu_ps(ktmp + 24);
_vb1 = _mm256_loadu_ps(ktmp + 32);
_vb2 = _mm256_loadu_ps(ktmp + 40);
_sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0);
_sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0);
_sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0);
_sum1 = _mm256_fmadd_ps(_va2, _vb0, _sum1);
_sum1 = _mm256_fmadd_ps(_va3, _vb1, _sum1);
_sum1 = _mm256_fmadd_ps(_va4, _vb2, _sum1);
_va0 = _mm256_loadu_ps(itmp2);
_va1 = _mm256_loadu_ps(itmp2 + 8);
_va2 = _mm256_loadu_ps(itmp2 + 16);
_va3 = _mm256_loadu_ps(itmp2 + 24);
_va4 = _mm256_loadu_ps(itmp2 + 32);
_vb0 = _mm256_loadu_ps(ktmp + 48);
_vb1 = _mm256_loadu_ps(ktmp + 56);
_vb2 = _mm256_loadu_ps(ktmp + 64);
_sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0);
_sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0);
_sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0);
_sum1 = _mm256_fmadd_ps(_va2, _vb0, _sum1);
_sum1 = _mm256_fmadd_ps(_va3, _vb1, _sum1);
_sum1 = _mm256_fmadd_ps(_va4, _vb2, _sum1);
_mm256_storeu_ps(otmp, _sum0);
_mm256_storeu_ps(otmp + 8, _sum1);
itmp0 += 32;
itmp1 += 32;
itmp2 += 32;
otmp += 16;
}
for (; j < outw; j++)
{
__m256 _sum0 = _mm256_loadu_ps(btmp);
__m256 _va0 = _mm256_loadu_ps(itmp0);
__m256 _va1 = _mm256_loadu_ps(itmp0 + 8);
__m256 _va2 = _mm256_loadu_ps(itmp0 + 16);
__m256 _vb0 = _mm256_loadu_ps(ktmp);
__m256 _vb1 = _mm256_loadu_ps(ktmp + 8);
__m256 _vb2 = _mm256_loadu_ps(ktmp + 16);
_sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0);
_sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0);
_sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0);
_va0 = _mm256_loadu_ps(itmp1);
_va1 = _mm256_loadu_ps(itmp1 + 8);
_va2 = _mm256_loadu_ps(itmp1 + 16);
_vb0 = _mm256_loadu_ps(ktmp + 24);
_vb1 = _mm256_loadu_ps(ktmp + 32);
_vb2 = _mm256_loadu_ps(ktmp + 40);
_sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0);
_sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0);
_sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0);
_va0 = _mm256_loadu_ps(itmp2);
_va1 = _mm256_loadu_ps(itmp2 + 8);
_va2 = _mm256_loadu_ps(itmp2 + 16);
_vb0 = _mm256_loadu_ps(ktmp + 48);
_vb1 = _mm256_loadu_ps(ktmp + 56);
_vb2 = _mm256_loadu_ps(ktmp + 64);
_sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0);
_sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0);
_sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0);
_mm256_storeu_ps(otmp, _sum0);
itmp0 += 16;
itmp1 += 16;
itmp2 += 16;
otmp += 8;
}
}
}
// load_data
{
for (int i = 0; i < channel_count; i++)
{
float* otmp = output_tmp + i * 8 * outwh;
float* tmp0 = output + i * 8 * outwh;
float* tmp1 = output + i * 8 * outwh + 1 * outwh;
float* tmp2 = output + i * 8 * outwh + 2 * outwh;
float* tmp3 = output + i * 8 * outwh + 3 * outwh;
float* tmp4 = output + i * 8 * outwh + 4 * outwh;
float* tmp5 = output + i * 8 * outwh + 5 * outwh;
float* tmp6 = output + i * 8 * outwh + 6 * outwh;
float* tmp7 = output + i * 8 * outwh + 7 * outwh;
for (int i = 0; i < outwh; i++)
{
tmp0[0] = otmp[0];
tmp1[0] = otmp[1];
tmp2[0] = otmp[2];
tmp3[0] = otmp[3];
tmp4[0] = otmp[4];
tmp5[0] = otmp[5];
tmp6[0] = otmp[6];
tmp7[0] = otmp[7];
otmp += 8;
tmp0++;
tmp1++;
tmp2++;
tmp3++;
tmp4++;
tmp5++;
tmp6++;
tmp7++;
}
}
int i = 0;
for (; i + 3 < channel_remain; i += 4)
{
int ii = channel_count * 8 + i;
float* otmp = output_tmp + ii * outwh;
float* tmp0 = output + ii * outwh;
float* tmp1 = output + ii * outwh + 1 * outwh;
float* tmp2 = output + ii * outwh + 2 * outwh;
float* tmp3 = output + ii * outwh + 3 * outwh;
for (int j = 0; j < outwh; j++)
{
tmp0[0] = otmp[0];
tmp1[0] = otmp[1];
tmp2[0] = otmp[2];
tmp3[0] = otmp[3];
otmp += 8;
tmp0++;
tmp1++;
tmp2++;
tmp3++;
}
}
for (; i < channel_remain; i++)
{
int ii = channel_count * 8 + i;
float* otmp = output_tmp + channel_count * 8 * outwh;
float* tmp0 = output + ii * outwh;
for (int j = 0; j < outwh; j++)
{
tmp0[0] = otmp[i];
otmp += 8;
tmp0++;
}
}
}
sys_free(output_tmp);
sys_free(img_tmp);
sys_free(kernel_tmp);
sys_free(bias_tmp);
}
#elif __SSE2__
static void convdw3x3s1(float* output, float* img_data, float* kernel_data, float* bias_data, int inc, int inh, int inw,
int outh, int outw, int num_thread)
{
int inwh = inw * inh;
int outwh = outw * outh;
int channel_count = inc >> 2;
int channel_remain = inc - (channel_count << 2);
// generate the image tmp
float* img_tmp = ( float* )sys_malloc(4 * inwh * (channel_count + 1) * sizeof(float));
float* kernel_tmp = ( float* )sys_malloc(4 * 9 * (channel_count + 1) * sizeof(float));
float* bias_tmp = ( float* )sys_malloc(4 * (channel_count + 1) * sizeof(float));
{
for (int i = 0; i < channel_count; i++)
{
int ii = i * 4;
float* k0 = img_data + (ii + 0) * inwh;
float* k1 = img_data + (ii + 1) * inwh;
float* k2 = img_data + (ii + 2) * inwh;
float* k3 = img_data + (ii + 3) * inwh;
float* f0 = kernel_data + (ii + 0) * 9;
float* f1 = kernel_data + (ii + 1) * 9;
float* f2 = kernel_data + (ii + 2) * 9;
float* f3 = kernel_data + (ii + 3) * 9;
float* b0 = bias_data + (ii + 0);
float* b1 = bias_data + (ii + 1);
float* b2 = bias_data + (ii + 2);
float* b3 = bias_data + (ii + 3);
float* tmp0 = img_tmp + ii * inwh;
float* tmp1 = kernel_tmp + ii * 9;
float* tmp2 = bias_tmp + ii;
for (int j = 0; j < inwh; j++)
{
tmp0[0] = k0[0];
tmp0[1] = k1[0];
tmp0[2] = k2[0];
tmp0[3] = k3[0];
tmp0 += 4;
k0++;
k1++;
k2++;
k3++;
}
for (int j = 0; j < 9; j++)
{
tmp1[0] = f0[0];
tmp1[1] = f1[0];
tmp1[2] = f2[0];
tmp1[3] = f3[0];
tmp1 += 4;
f0++;
f1++;
f2++;
f3++;
}
if (bias_data)
{
tmp2[0] = b0[0];
tmp2[1] = b1[0];
tmp2[2] = b2[0];
tmp2[3] = b3[0];
}
else
{
tmp2[0] = 0;
tmp2[1] = 0;
tmp2[2] = 0;
tmp2[3] = 0;
}
}
for (int i = 0; i < channel_remain; i++)
{
int ii = channel_count * 4 + i;
float* k0 = img_data + ii * inwh;
float* f0 = kernel_data + ii * 9;
float* b0 = bias_data + ii;
float* tmp0 = img_tmp + channel_count * 4 * inwh;
float* tmp1 = kernel_tmp + channel_count * 4 * 9;
float* tmp2 = bias_tmp + channel_count * 4;
for (int j = 0; j < inwh; j++)
{
tmp0[i] = k0[0];
tmp0 += 4;
k0++;
}
for (int j = 0; j < 9; j++)
{
tmp1[i] = f0[0];
tmp1 += 4;
f0++;
}
if (bias_data)
{
tmp2[i] = b0[0];
}
else
{
tmp2[i] = 0;
}
}
}
float* output_tmp = ( float* )sys_malloc(outwh * 4 * (channel_count + 1) * sizeof(float));
for (int c = 0; c < channel_count + 1; c++)
{
float* ktmp = kernel_tmp + c * 4 * 9;
float* btmp = bias_tmp + c * 4;
for (int i = 0; i < outh; i++)
{
int j = 0;
float* itmp0 = img_tmp + c * 4 * inwh + 4 * i * inw;
float* itmp1 = img_tmp + c * 4 * inwh + 4 * (i + 1) * inw;
float* itmp2 = img_tmp + c * 4 * inwh + 4 * (i + 2) * inw;
float* otmp = output_tmp + c * 4 * outwh + 4 * i * outw;
for (; j + 7 < outw; j += 8)
{
#if __SSE__
__m128 _sum0 = _mm_loadu_ps(btmp);
__m128 _sum1 = _mm_loadu_ps(btmp);
__m128 _sum2 = _mm_loadu_ps(btmp);
__m128 _sum3 = _mm_loadu_ps(btmp);
__m128 _sum4 = _mm_loadu_ps(btmp);
__m128 _sum5 = _mm_loadu_ps(btmp);
__m128 _sum6 = _mm_loadu_ps(btmp);
__m128 _sum7 = _mm_loadu_ps(btmp);
__m128 _va0 = _mm_loadu_ps(itmp0);
__m128 _va1 = _mm_loadu_ps(itmp0 + 4);
__m128 _va2 = _mm_loadu_ps(itmp0 + 8);
__m128 _va3 = _mm_loadu_ps(itmp0 + 12);
__m128 _va4 = _mm_loadu_ps(itmp0 + 16);
__m128 _va5 = _mm_loadu_ps(itmp0 + 20);
__m128 _va6 = _mm_loadu_ps(itmp0 + 24);
__m128 _va7 = _mm_loadu_ps(itmp0 + 28);
__m128 _va8 = _mm_loadu_ps(itmp0 + 32);
__m128 _va9 = _mm_loadu_ps(itmp0 + 36);
__m128 _vb0 = _mm_loadu_ps(ktmp);
__m128 _vb1 = _mm_loadu_ps(ktmp + 4);
__m128 _vb2 = _mm_loadu_ps(ktmp + 8);
_sum0 = _mm_add_ps(_mm_mul_ps(_va0, _vb0), _sum0);
_sum1 = _mm_add_ps(_mm_mul_ps(_va1, _vb0), _sum1);
_sum0 = _mm_add_ps(_mm_mul_ps(_va1, _vb1), _sum0);
_sum1 = _mm_add_ps(_mm_mul_ps(_va2, _vb1), _sum1);
_sum0 = _mm_add_ps(_mm_mul_ps(_va2, _vb2), _sum0);
_sum2 = _mm_add_ps(_mm_mul_ps(_va2, _vb0), _sum2);
_sum3 = _mm_add_ps(_mm_mul_ps(_va3, _vb0), _sum3);
_sum1 = _mm_add_ps(_mm_mul_ps(_va3, _vb2), _sum1);
_sum2 = _mm_add_ps(_mm_mul_ps(_va3, _vb1), _sum2);
_sum3 = _mm_add_ps(_mm_mul_ps(_va4, _vb1), _sum3);
_sum4 = _mm_add_ps(_mm_mul_ps(_va4, _vb0), _sum4);
_sum2 = _mm_add_ps(_mm_mul_ps(_va4, _vb2), _sum2);
_sum3 = _mm_add_ps(_mm_mul_ps(_va5, _vb2), _sum3);
_sum5 = _mm_add_ps(_mm_mul_ps(_va5, _vb0), _sum5);
_sum4 = _mm_add_ps(_mm_mul_ps(_va5, _vb1), _sum4);
_sum5 = _mm_add_ps(_mm_mul_ps(_va6, _vb1), _sum5);
_sum4 = _mm_add_ps(_mm_mul_ps(_va6, _vb2), _sum4);
_sum6 = _mm_add_ps(_mm_mul_ps(_va6, _vb0), _sum6);
_sum7 = _mm_add_ps(_mm_mul_ps(_va7, _vb0), _sum7);
_sum5 = _mm_add_ps(_mm_mul_ps(_va7, _vb2), _sum5);
_sum6 = _mm_add_ps(_mm_mul_ps(_va7, _vb1), _sum6);
_sum7 = _mm_add_ps(_mm_mul_ps(_va8, _vb1), _sum7);
_sum6 = _mm_add_ps(_mm_mul_ps(_va8, _vb2), _sum6);
_sum7 = _mm_add_ps(_mm_mul_ps(_va9, _vb2), _sum7);
_va0 = _mm_loadu_ps(itmp1);
_va1 = _mm_loadu_ps(itmp1 + 4);
_va2 = _mm_loadu_ps(itmp1 + 8);
_va3 = _mm_loadu_ps(itmp1 + 12);
_va4 = _mm_loadu_ps(itmp1 + 16);
_va5 = _mm_loadu_ps(itmp1 + 20);
_va6 = _mm_loadu_ps(itmp1 + 24);
_va7 = _mm_loadu_ps(itmp1 + 28);
_va8 = _mm_loadu_ps(itmp1 + 32);
_va9 = _mm_loadu_ps(itmp1 + 36);
_vb0 = _mm_loadu_ps(ktmp + 12);
_vb1 = _mm_loadu_ps(ktmp + 16);
_vb2 = _mm_loadu_ps(ktmp + 20);
_sum0 = _mm_add_ps(_mm_mul_ps(_va0, _vb0), _sum0);
_sum1 = _mm_add_ps(_mm_mul_ps(_va1, _vb0), _sum1);
_sum0 = _mm_add_ps(_mm_mul_ps(_va1, _vb1), _sum0);
_sum1 = _mm_add_ps(_mm_mul_ps(_va2, _vb1), _sum1);
_sum0 = _mm_add_ps(_mm_mul_ps(_va2, _vb2), _sum0);
_sum2 = _mm_add_ps(_mm_mul_ps(_va2, _vb0), _sum2);
_sum3 = _mm_add_ps(_mm_mul_ps(_va3, _vb0), _sum3);
_sum1 = _mm_add_ps(_mm_mul_ps(_va3, _vb2), _sum1);
_sum2 = _mm_add_ps(_mm_mul_ps(_va3, _vb1), _sum2);
_sum3 = _mm_add_ps(_mm_mul_ps(_va4, _vb1), _sum3);
_sum4 = _mm_add_ps(_mm_mul_ps(_va4, _vb0), _sum4);
_sum2 = _mm_add_ps(_mm_mul_ps(_va4, _vb2), _sum2);
_sum3 = _mm_add_ps(_mm_mul_ps(_va5, _vb2), _sum3);
_sum5 = _mm_add_ps(_mm_mul_ps(_va5, _vb0), _sum5);
_sum4 = _mm_add_ps(_mm_mul_ps(_va5, _vb1), _sum4);
_sum5 = _mm_add_ps(_mm_mul_ps(_va6, _vb1), _sum5);
_sum4 = _mm_add_ps(_mm_mul_ps(_va6, _vb2), _sum4);
_sum6 = _mm_add_ps(_mm_mul_ps(_va6, _vb0), _sum6);
_sum7 = _mm_add_ps(_mm_mul_ps(_va7, _vb0), _sum7);
_sum5 = _mm_add_ps(_mm_mul_ps(_va7, _vb2), _sum5);
_sum6 = _mm_add_ps(_mm_mul_ps(_va7, _vb1), _sum6);
_sum7 = _mm_add_ps(_mm_mul_ps(_va8, _vb1), _sum7);
_sum6 = _mm_add_ps(_mm_mul_ps(_va8, _vb2), _sum6);
_sum7 = _mm_add_ps(_mm_mul_ps(_va9, _vb2), _sum7);
_va0 = _mm_loadu_ps(itmp2);
_va1 = _mm_loadu_ps(itmp2 + 4);
_va2 = _mm_loadu_ps(itmp2 + 8);
_va3 = _mm_loadu_ps(itmp2 + 12);
_va4 = _mm_loadu_ps(itmp2 + 16);
_va5 = _mm_loadu_ps(itmp2 + 20);
_va6 = _mm_loadu_ps(itmp2 + 24);
_va7 = _mm_loadu_ps(itmp2 + 28);
_va8 = _mm_loadu_ps(itmp2 + 32);
_va9 = _mm_loadu_ps(itmp2 + 36);
_vb0 = _mm_loadu_ps(ktmp + 24);
_vb1 = _mm_loadu_ps(ktmp + 28);
_vb2 = _mm_loadu_ps(ktmp + 32);
_sum0 = _mm_add_ps(_mm_mul_ps(_va0, _vb0), _sum0);
_sum1 = _mm_add_ps(_mm_mul_ps(_va1, _vb0), _sum1);
_sum0 = _mm_add_ps(_mm_mul_ps(_va1, _vb1), _sum0);
_sum1 = _mm_add_ps(_mm_mul_ps(_va2, _vb1), _sum1);
_sum0 = _mm_add_ps(_mm_mul_ps(_va2, _vb2), _sum0);
_sum2 = _mm_add_ps(_mm_mul_ps(_va2, _vb0), _sum2);
_sum3 = _mm_add_ps(_mm_mul_ps(_va3, _vb0), _sum3);
_sum1 = _mm_add_ps(_mm_mul_ps(_va3, _vb2), _sum1);
_sum2 = _mm_add_ps(_mm_mul_ps(_va3, _vb1), _sum2);
_sum3 = _mm_add_ps(_mm_mul_ps(_va4, _vb1), _sum3);
_sum4 = _mm_add_ps(_mm_mul_ps(_va4, _vb0), _sum4);
_sum2 = _mm_add_ps(_mm_mul_ps(_va4, _vb2), _sum2);
_sum3 = _mm_add_ps(_mm_mul_ps(_va5, _vb2), _sum3);
_sum5 = _mm_add_ps(_mm_mul_ps(_va5, _vb0), _sum5);
_sum4 = _mm_add_ps(_mm_mul_ps(_va5, _vb1), _sum4);
_sum5 = _mm_add_ps(_mm_mul_ps(_va6, _vb1), _sum5);
_sum4 = _mm_add_ps(_mm_mul_ps(_va6, _vb2), _sum4);
_sum6 = _mm_add_ps(_mm_mul_ps(_va6, _vb0), _sum6);
_sum7 = _mm_add_ps(_mm_mul_ps(_va7, _vb0), _sum7);
_sum5 = _mm_add_ps(_mm_mul_ps(_va7, _vb2), _sum5);
_sum6 = _mm_add_ps(_mm_mul_ps(_va7, _vb1), _sum6);
_sum7 = _mm_add_ps(_mm_mul_ps(_va8, _vb1), _sum7);
_sum6 = _mm_add_ps(_mm_mul_ps(_va8, _vb2), _sum6);
_sum7 = _mm_add_ps(_mm_mul_ps(_va9, _vb2), _sum7);
_mm_storeu_ps(otmp, _sum0);
_mm_storeu_ps(otmp + 4, _sum1);
_mm_storeu_ps(otmp + 8, _sum2);
_mm_storeu_ps(otmp + 12, _sum3);
_mm_storeu_ps(otmp + 16, _sum4);
_mm_storeu_ps(otmp + 20, _sum5);
_mm_storeu_ps(otmp + 24, _sum6);
_mm_storeu_ps(otmp + 28, _sum7);
#else
float sum0[4] = {btmp[0], btmp[1], btmp[2], btmp[3]};
float sum1[4] = {btmp[0], btmp[1], btmp[2], btmp[3]};
float sum2[4] = {btmp[0], btmp[1], btmp[2], btmp[3]};
float sum3[4] = {btmp[0], btmp[1], btmp[2], btmp[3]};
float sum4[4] = {btmp[0], btmp[1], btmp[2], btmp[3]};
float sum5[4] = {btmp[0], btmp[1], btmp[2], btmp[3]};
float sum6[4] = {btmp[0], btmp[1], btmp[2], btmp[3]};
float sum7[4] = {btmp[0], btmp[1], btmp[2], btmp[3]};
for (int k = 0; k < 4; k++)
{
sum0[k] += itmp0[k] * ktmp[k];
sum0[k] += itmp1[k] * ktmp[k + 12];
sum0[k] += itmp2[k] * ktmp[k + 24];
sum0[k] += itmp0[k + 4] * ktmp[k + 4];
sum0[k] += itmp1[k + 4] * ktmp[k + 16];
sum0[k] += itmp2[k + 4] * ktmp[k + 28];
sum0[k] += itmp0[k + 8] * ktmp[k + 8];
sum0[k] += itmp1[k + 8] * ktmp[k + 20];
sum0[k] += itmp2[k + 8] * ktmp[k + 32];
sum1[k] += itmp0[k + 4] * ktmp[k];
sum1[k] += itmp1[k + 4] * ktmp[k + 12];
sum1[k] += itmp2[k + 4] * ktmp[k + 24];
sum1[k] += itmp0[k + 8] * ktmp[k + 4];
sum1[k] += itmp1[k + 8] * ktmp[k + 16];
sum1[k] += itmp2[k + 8] * ktmp[k + 28];
sum1[k] += itmp0[k + 12] * ktmp[k + 8];
sum1[k] += itmp1[k + 12] * ktmp[k + 20];
sum1[k] += itmp2[k + 12] * ktmp[k + 32];
sum2[k] += itmp0[k + 8] * ktmp[k];
sum2[k] += itmp1[k + 8] * ktmp[k + 12];
sum2[k] += itmp2[k + 8] * ktmp[k + 24];
sum2[k] += itmp0[k + 12] * ktmp[k + 4];
sum2[k] += itmp1[k + 12] * ktmp[k + 16];
sum2[k] += itmp2[k + 12] * ktmp[k + 28];
sum2[k] += itmp0[k + 16] * ktmp[k + 8];
sum2[k] += itmp1[k + 16] * ktmp[k + 20];
sum2[k] += itmp2[k + 16] * ktmp[k + 32];
sum3[k] += itmp0[k + 12] * ktmp[k];
sum3[k] += itmp1[k + 12] * ktmp[k + 12];
sum3[k] += itmp2[k + 12] * ktmp[k + 24];
sum3[k] += itmp0[k + 16] * ktmp[k + 4];
sum3[k] += itmp1[k + 16] * ktmp[k + 16];
sum3[k] += itmp2[k + 16] * ktmp[k + 28];
sum3[k] += itmp0[k + 20] * ktmp[k + 8];
sum3[k] += itmp1[k + 20] * ktmp[k + 20];
sum3[k] += itmp2[k + 20] * ktmp[k + 32];
sum4[k] += itmp0[k + 16] * ktmp[k];
sum4[k] += itmp1[k + 16] * ktmp[k + 12];
sum4[k] += itmp2[k + 16] * ktmp[k + 24];
sum4[k] += itmp0[k + 20] * ktmp[k + 4];
sum4[k] += itmp1[k + 20] * ktmp[k + 16];
sum4[k] += itmp2[k + 20] * ktmp[k + 28];
sum4[k] += itmp0[k + 24] * ktmp[k + 8];
sum4[k] += itmp1[k + 24] * ktmp[k + 20];
sum4[k] += itmp2[k + 24] * ktmp[k + 32];
sum5[k] += itmp0[k + 20] * ktmp[k];
sum5[k] += itmp1[k + 20] * ktmp[k + 12];
sum5[k] += itmp2[k + 20] * ktmp[k + 24];
sum5[k] += itmp0[k + 24] * ktmp[k + 4];
sum5[k] += itmp1[k + 24] * ktmp[k + 16];
sum5[k] += itmp2[k + 24] * ktmp[k + 28];
sum5[k] += itmp0[k + 28] * ktmp[k + 8];
sum5[k] += itmp1[k + 28] * ktmp[k + 20];
sum5[k] += itmp2[k + 28] * ktmp[k + 32];
sum6[k] += itmp0[k + 24] * ktmp[k];
sum6[k] += itmp1[k + 24] * ktmp[k + 12];
sum6[k] += itmp2[k + 24] * ktmp[k + 24];
sum6[k] += itmp0[k + 28] * ktmp[k + 4];
sum6[k] += itmp1[k + 28] * ktmp[k + 16];
sum6[k] += itmp2[k + 28] * ktmp[k + 28];
sum6[k] += itmp0[k + 32] * ktmp[k + 8];
sum6[k] += itmp1[k + 32] * ktmp[k + 20];
sum6[k] += itmp2[k + 32] * ktmp[k + 32];
sum7[k] += itmp0[k + 28] * ktmp[k];
sum7[k] += itmp1[k + 28] * ktmp[k + 12];
sum7[k] += itmp2[k + 28] * ktmp[k + 24];
sum7[k] += itmp0[k + 32] * ktmp[k + 4];
sum7[k] += itmp1[k + 32] * ktmp[k + 16];
sum7[k] += itmp2[k + 32] * ktmp[k + 28];
sum7[k] += itmp0[k + 36] * ktmp[k + 8];
sum7[k] += itmp1[k + 36] * ktmp[k + 20];
sum7[k] += itmp2[k + 36] * ktmp[k + 32];
}
for (int k = 0; k < 4; k++)
{
otmp[k] = sum0[k];
otmp[k + 4] = sum1[k];
otmp[k + 8] = sum2[k];
otmp[k + 12] = sum3[k];
otmp[k + 16] = sum4[k];
otmp[k + 20] = sum5[k];
otmp[k + 24] = sum6[k];
otmp[k + 28] = sum7[k];
}
#endif
itmp0 += 32;
itmp1 += 32;
itmp2 += 32;
otmp += 32;
}
for (; j + 3 < outw; j += 4)
{
#if __SSE__
__m128 _sum0 = _mm_loadu_ps(btmp);
__m128 _sum1 = _mm_loadu_ps(btmp);
__m128 _sum2 = _mm_loadu_ps(btmp);
__m128 _sum3 = _mm_loadu_ps(btmp);
__m128 _va0 = _mm_loadu_ps(itmp0);
__m128 _va1 = _mm_loadu_ps(itmp0 + 4);
__m128 _va2 = _mm_loadu_ps(itmp0 + 8);
__m128 _va3 = _mm_loadu_ps(itmp0 + 12);
__m128 _va4 = _mm_loadu_ps(itmp0 + 16);
__m128 _va5 = _mm_loadu_ps(itmp0 + 20);
__m128 _vb0 = _mm_loadu_ps(ktmp);
__m128 _vb1 = _mm_loadu_ps(ktmp + 4);
__m128 _vb2 = _mm_loadu_ps(ktmp + 8);
_sum0 = _mm_add_ps(_mm_mul_ps(_va0, _vb0), _sum0);
_sum1 = _mm_add_ps(_mm_mul_ps(_va1, _vb0), _sum1);
_sum0 = _mm_add_ps(_mm_mul_ps(_va1, _vb1), _sum0);
_sum1 = _mm_add_ps(_mm_mul_ps(_va2, _vb1), _sum1);
_sum0 = _mm_add_ps(_mm_mul_ps(_va2, _vb2), _sum0);
_sum2 = _mm_add_ps(_mm_mul_ps(_va2, _vb0), _sum2);
_sum3 = _mm_add_ps(_mm_mul_ps(_va3, _vb0), _sum3);
_sum1 = _mm_add_ps(_mm_mul_ps(_va3, _vb2), _sum1);
_sum2 = _mm_add_ps(_mm_mul_ps(_va3, _vb1), _sum2);
_sum3 = _mm_add_ps(_mm_mul_ps(_va4, _vb1), _sum3);
_sum2 = _mm_add_ps(_mm_mul_ps(_va4, _vb2), _sum2);
_sum3 = _mm_add_ps(_mm_mul_ps(_va5, _vb2), _sum3);
_va0 = _mm_loadu_ps(itmp1);
_va1 = _mm_loadu_ps(itmp1 + 4);
_va2 = _mm_loadu_ps(itmp1 + 8);
_va3 = _mm_loadu_ps(itmp1 + 12);
_va4 = _mm_loadu_ps(itmp1 + 16);
_va5 = _mm_loadu_ps(itmp1 + 20);
_vb0 = _mm_loadu_ps(ktmp + 12);
_vb1 = _mm_loadu_ps(ktmp + 16);
_vb2 = _mm_loadu_ps(ktmp + 20);
_sum0 = _mm_add_ps(_mm_mul_ps(_va0, _vb0), _sum0);
_sum1 = _mm_add_ps(_mm_mul_ps(_va1, _vb0), _sum1);
_sum0 = _mm_add_ps(_mm_mul_ps(_va1, _vb1), _sum0);
_sum1 = _mm_add_ps(_mm_mul_ps(_va2, _vb1), _sum1);
_sum0 = _mm_add_ps(_mm_mul_ps(_va2, _vb2), _sum0);
_sum2 = _mm_add_ps(_mm_mul_ps(_va2, _vb0), _sum2);
_sum3 = _mm_add_ps(_mm_mul_ps(_va3, _vb0), _sum3);
_sum1 = _mm_add_ps(_mm_mul_ps(_va3, _vb2), _sum1);
_sum2 = _mm_add_ps(_mm_mul_ps(_va3, _vb1), _sum2);
_sum3 = _mm_add_ps(_mm_mul_ps(_va4, _vb1), _sum3);
_sum2 = _mm_add_ps(_mm_mul_ps(_va4, _vb2), _sum2);
_sum3 = _mm_add_ps(_mm_mul_ps(_va5, _vb2), _sum3);
_va0 = _mm_loadu_ps(itmp2);
_va1 = _mm_loadu_ps(itmp2 + 4);
_va2 = _mm_loadu_ps(itmp2 + 8);
_va3 = _mm_loadu_ps(itmp2 + 12);
_va4 = _mm_loadu_ps(itmp2 + 16);
_va5 = _mm_loadu_ps(itmp2 + 20);
_vb0 = _mm_loadu_ps(ktmp + 24);
_vb1 = _mm_loadu_ps(ktmp + 28);
_vb2 = _mm_loadu_ps(ktmp + 32);
_sum0 = _mm_add_ps(_mm_mul_ps(_va0, _vb0), _sum0);
_sum1 = _mm_add_ps(_mm_mul_ps(_va1, _vb0), _sum1);
_sum0 = _mm_add_ps(_mm_mul_ps(_va1, _vb1), _sum0);
_sum1 = _mm_add_ps(_mm_mul_ps(_va2, _vb1), _sum1);
_sum0 = _mm_add_ps(_mm_mul_ps(_va2, _vb2), _sum0);
_sum2 = _mm_add_ps(_mm_mul_ps(_va2, _vb0), _sum2);
_sum3 = _mm_add_ps(_mm_mul_ps(_va3, _vb0), _sum3);
_sum1 = _mm_add_ps(_mm_mul_ps(_va3, _vb2), _sum1);
_sum2 = _mm_add_ps(_mm_mul_ps(_va3, _vb1), _sum2);
_sum3 = _mm_add_ps(_mm_mul_ps(_va4, _vb1), _sum3);
_sum2 = _mm_add_ps(_mm_mul_ps(_va4, _vb2), _sum2);
_sum3 = _mm_add_ps(_mm_mul_ps(_va5, _vb2), _sum3);
_mm_storeu_ps(otmp, _sum0);
_mm_storeu_ps(otmp + 4, _sum1);
_mm_storeu_ps(otmp + 8, _sum2);
_mm_storeu_ps(otmp + 12, _sum3);
#else
float sum0[4] = {btmp[0], btmp[1], btmp[2], btmp[3]};
float sum1[4] = {btmp[0], btmp[1], btmp[2], btmp[3]};
float sum2[4] = {btmp[0], btmp[1], btmp[2], btmp[3]};
float sum3[4] = {btmp[0], btmp[1], btmp[2], btmp[3]};
for (int k = 0; k < 4; k++)
{
sum0[k] += itmp0[k] * ktmp[k];
sum0[k] += itmp1[k] * ktmp[k + 12];
sum0[k] += itmp2[k] * ktmp[k + 24];
sum0[k] += itmp0[k + 4] * ktmp[k + 4];
sum0[k] += itmp1[k + 4] * ktmp[k + 16];
sum0[k] += itmp2[k + 4] * ktmp[k + 28];
sum0[k] += itmp0[k + 8] * ktmp[k + 8];
sum0[k] += itmp1[k + 8] * ktmp[k + 20];
sum0[k] += itmp2[k + 8] * ktmp[k + 32];
sum1[k] += itmp0[k + 4] * ktmp[k];
sum1[k] += itmp1[k + 4] * ktmp[k + 12];
sum1[k] += itmp2[k + 4] * ktmp[k + 24];
sum1[k] += itmp0[k + 8] * ktmp[k + 4];
sum1[k] += itmp1[k + 8] * ktmp[k + 16];
sum1[k] += itmp2[k + 8] * ktmp[k + 28];
sum1[k] += itmp0[k + 12] * ktmp[k + 8];
sum1[k] += itmp1[k + 12] * ktmp[k + 20];
sum1[k] += itmp2[k + 12] * ktmp[k + 32];
sum2[k] += itmp0[k + 8] * ktmp[k];
sum2[k] += itmp1[k + 8] * ktmp[k + 12];
sum2[k] += itmp2[k + 8] * ktmp[k + 24];
sum2[k] += itmp0[k + 12] * ktmp[k + 4];
sum2[k] += itmp1[k + 12] * ktmp[k + 16];
sum2[k] += itmp2[k + 12] * ktmp[k + 28];
sum2[k] += itmp0[k + 16] * ktmp[k + 8];
sum2[k] += itmp1[k + 16] * ktmp[k + 20];
sum2[k] += itmp2[k + 16] * ktmp[k + 32];
sum3[k] += itmp0[k + 12] * ktmp[k];
sum3[k] += itmp1[k + 12] * ktmp[k + 12];
sum3[k] += itmp2[k + 12] * ktmp[k + 24];
sum3[k] += itmp0[k + 16] * ktmp[k + 4];
sum3[k] += itmp1[k + 16] * ktmp[k + 16];
sum3[k] += itmp2[k + 16] * ktmp[k + 28];
sum3[k] += itmp0[k + 20] * ktmp[k + 8];
sum3[k] += itmp1[k + 20] * ktmp[k + 20];
sum3[k] += itmp2[k + 20] * ktmp[k + 32];
}
for (int k = 0; k < 4; k++)
{
otmp[k] = sum0[k];
otmp[k + 4] = sum1[k];
otmp[k + 8] = sum2[k];
otmp[k + 12] = sum3[k];
}
#endif
itmp0 += 16;
itmp1 += 16;
itmp2 += 16;
otmp += 16;
}
for (; j < outw; j++)
{
#if __SSE__
__m128 _sum0 = _mm_loadu_ps(btmp);
__m128 _va0 = _mm_loadu_ps(itmp0);
__m128 _va1 = _mm_loadu_ps(itmp0 + 4);
__m128 _va2 = _mm_loadu_ps(itmp0 + 8);
__m128 _vb0 = _mm_loadu_ps(ktmp);
__m128 _vb1 = _mm_loadu_ps(ktmp + 4);
__m128 _vb2 = _mm_loadu_ps(ktmp + 8);
_sum0 = _mm_add_ps(_mm_mul_ps(_va0, _vb0), _sum0);
_sum0 = _mm_add_ps(_mm_mul_ps(_va1, _vb1), _sum0);
_sum0 = _mm_add_ps(_mm_mul_ps(_va2, _vb2), _sum0);
_va0 = _mm_loadu_ps(itmp1);
_va1 = _mm_loadu_ps(itmp1 + 4);
_va2 = _mm_loadu_ps(itmp1 + 8);
_vb0 = _mm_loadu_ps(ktmp + 12);
_vb1 = _mm_loadu_ps(ktmp + 16);
_vb2 = _mm_loadu_ps(ktmp + 20);
_sum0 = _mm_add_ps(_mm_mul_ps(_va0, _vb0), _sum0);
_sum0 = _mm_add_ps(_mm_mul_ps(_va1, _vb1), _sum0);
_sum0 = _mm_add_ps(_mm_mul_ps(_va2, _vb2), _sum0);
_va0 = _mm_loadu_ps(itmp2);
_va1 = _mm_loadu_ps(itmp2 + 4);
_va2 = _mm_loadu_ps(itmp2 + 8);
_vb0 = _mm_loadu_ps(ktmp + 24);
_vb1 = _mm_loadu_ps(ktmp + 28);
_vb2 = _mm_loadu_ps(ktmp + 32);
_sum0 = _mm_add_ps(_mm_mul_ps(_va0, _vb0), _sum0);
_sum0 = _mm_add_ps(_mm_mul_ps(_va1, _vb1), _sum0);
_sum0 = _mm_add_ps(_mm_mul_ps(_va2, _vb2), _sum0);
_mm_storeu_ps(otmp, _sum0);
#else
float sum0[4] = {btmp[0], btmp[1], btmp[2], btmp[3]};
for (int k = 0; k < 4; k++)
{
sum0[k] += itmp0[k] * ktmp[k];
sum0[k] += itmp1[k] * ktmp[k + 12];
sum0[k] += itmp2[k] * ktmp[k + 24];
sum0[k] += itmp0[k + 4] * ktmp[k + 4];
sum0[k] += itmp1[k + 4] * ktmp[k + 16];
sum0[k] += itmp2[k + 4] * ktmp[k + 28];
sum0[k] += itmp0[k + 8] * ktmp[k + 8];
sum0[k] += itmp1[k + 8] * ktmp[k + 20];
sum0[k] += itmp2[k + 8] * ktmp[k + 32];
}
for (int k = 0; k < 4; k++)
{
otmp[k] = sum0[k];
}
#endif
itmp0 += 4;
itmp1 += 4;
itmp2 += 4;
otmp += 4;
}
}
}
{
for (int i = 0; i < channel_count; i++)
{
float* otmp = output_tmp + i * 4 * outwh;
float* tmp0 = output + i * 4 * outwh;
float* tmp1 = output + i * 4 * outwh + 1 * outwh;
float* tmp2 = output + i * 4 * outwh + 2 * outwh;
float* tmp3 = output + i * 4 * outwh + 3 * outwh;
for (int i = 0; i < outwh; i++)
{
tmp0[0] = otmp[0];
tmp1[0] = otmp[1];
tmp2[0] = otmp[2];
tmp3[0] = otmp[3];
otmp += 4;
tmp0++;
tmp1++;
tmp2++;
tmp3++;
}
}
for (int i = 0; i < channel_remain; i++)
{
int ii = channel_count * 4 + i;
float* otmp = output_tmp + channel_count * 4 * outwh;
float* tmp0 = output + ii * outwh;
for (int j = 0; j < outwh; j++)
{
tmp0[0] = otmp[i];
otmp += 4;
tmp0++;
}
}
}
sys_free(output_tmp);
sys_free(img_tmp);
sys_free(kernel_tmp);
sys_free(bias_tmp);
}
static void convdw3x3s2(float* output, float* img_data, float* kernel_data, float* bias_data, int inc, int inh, int inw,
int outh, int outw, int num_thread)
{
int inwh = inw * inh;
int outwh = outw * outh;
int channel_count = inc >> 2;
int channel_remain = inc - (channel_count << 2);
// generate the image tmp
float* img_tmp = ( float* )sys_malloc(4 * inwh * (channel_count + 1) * sizeof(float));
float* kernel_tmp = ( float* )sys_malloc(4 * 9 * (channel_count + 1) * sizeof(float));
float* bias_tmp = ( float* )sys_malloc(4 * (channel_count + 1) * sizeof(float));
{
for (int i = 0; i < channel_count; i++)
{
int ii = i * 4;
float* k0 = img_data + (ii + 0) * inwh;
float* k1 = img_data + (ii + 1) * inwh;
float* k2 = img_data + (ii + 2) * inwh;
float* k3 = img_data + (ii + 3) * inwh;
float* f0 = kernel_data + (ii + 0) * 9;
float* f1 = kernel_data + (ii + 1) * 9;
float* f2 = kernel_data + (ii + 2) * 9;
float* f3 = kernel_data + (ii + 3) * 9;
float* b0 = bias_data + (ii + 0);
float* b1 = bias_data + (ii + 1);
float* b2 = bias_data + (ii + 2);
float* b3 = bias_data + (ii + 3);
float* tmp0 = img_tmp + ii * inwh;
float* tmp1 = kernel_tmp + ii * 9;
float* tmp2 = bias_tmp + ii;
for (int j = 0; j < inwh; j++)
{
tmp0[0] = k0[0];
tmp0[1] = k1[0];
tmp0[2] = k2[0];
tmp0[3] = k3[0];
tmp0 += 4;
k0++;
k1++;
k2++;
k3++;
}
for (int j = 0; j < 9; j++)
{
tmp1[0] = f0[0];
tmp1[1] = f1[0];
tmp1[2] = f2[0];
tmp1[3] = f3[0];
tmp1 += 4;
f0++;
f1++;
f2++;
f3++;
}
if (bias_data)
{
tmp2[0] = b0[0];
tmp2[1] = b1[0];
tmp2[2] = b2[0];
tmp2[3] = b3[0];
}
else
{
tmp2[0] = 0;
tmp2[1] = 0;
tmp2[2] = 0;
tmp2[3] = 0;
}
}
for (int i = 0; i < channel_remain; i++)
{
int ii = channel_count * 4 + i;
float* k0 = img_data + ii * inwh;
float* f0 = kernel_data + ii * 9;
float* b0 = bias_data + ii;
float* tmp0 = img_tmp + channel_count * 4 * inwh;
float* tmp1 = kernel_tmp + channel_count * 4 * 9;
float* tmp2 = bias_tmp + channel_count * 4;
for (int j = 0; j < inwh; j++)
{
tmp0[i] = k0[0];
tmp0 += 4;
k0++;
}
for (int j = 0; j < 9; j++)
{
tmp1[i] = f0[0];
tmp1 += 4;
f0++;
}
if (bias_data)
{
tmp2[i] = b0[0];
}
else
{
tmp2[i] = 0;
}
}
}
float* output_tmp = ( float* )sys_malloc(outwh * 4 * (channel_count + 1) * sizeof(float));
for (int c = 0; c < channel_count + 1; c++)
{
float* ktmp = kernel_tmp + c * 4 * 9;
float* btmp = bias_tmp + c * 4;
for (int i = 0; i < outh; i++)
{
int j = 0;
float* itmp0 = img_tmp + c * 4 * inwh + 4 * i * 2 * inw;
float* itmp1 = img_tmp + c * 4 * inwh + 4 * (i * 2 + 1) * inw;
float* itmp2 = img_tmp + c * 4 * inwh + 4 * (i * 2 + 2) * inw;
float* otmp = output_tmp + c * 4 * outwh + 4 * i * outw;
for (; j + 3 < outw; j += 4)
{
#if __SSE__
__m128 _sum0 = _mm_loadu_ps(btmp);
__m128 _sum1 = _mm_loadu_ps(btmp);
__m128 _sum2 = _mm_loadu_ps(btmp);
__m128 _sum3 = _mm_loadu_ps(btmp);
__m128 _va0 = _mm_loadu_ps(itmp0);
__m128 _va1 = _mm_loadu_ps(itmp0 + 4);
__m128 _va2 = _mm_loadu_ps(itmp0 + 8);
__m128 _va3 = _mm_loadu_ps(itmp0 + 12);
__m128 _va4 = _mm_loadu_ps(itmp0 + 16);
__m128 _va5 = _mm_loadu_ps(itmp0 + 20);
__m128 _va6 = _mm_loadu_ps(itmp0 + 24);
__m128 _va7 = _mm_loadu_ps(itmp0 + 28);
__m128 _va8 = _mm_loadu_ps(itmp0 + 32);
__m128 _vb0 = _mm_loadu_ps(ktmp);
__m128 _vb1 = _mm_loadu_ps(ktmp + 4);
__m128 _vb2 = _mm_loadu_ps(ktmp + 8);
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va0, _vb0));
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va1, _vb1));
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va2, _vb2));
_sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_va2, _vb0));
_sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_va3, _vb1));
_sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_va4, _vb2));
_sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_va4, _vb0));
_sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_va5, _vb1));
_sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_va6, _vb2));
_sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_va6, _vb0));
_sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_va7, _vb1));
_sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_va8, _vb2));
_va0 = _mm_loadu_ps(itmp1);
_va1 = _mm_loadu_ps(itmp1 + 4);
_va2 = _mm_loadu_ps(itmp1 + 8);
_va3 = _mm_loadu_ps(itmp1 + 12);
_va4 = _mm_loadu_ps(itmp1 + 16);
_va5 = _mm_loadu_ps(itmp1 + 20);
_va6 = _mm_loadu_ps(itmp1 + 24);
_va7 = _mm_loadu_ps(itmp1 + 28);
_va8 = _mm_loadu_ps(itmp1 + 32);
_vb0 = _mm_loadu_ps(ktmp + 12);
_vb1 = _mm_loadu_ps(ktmp + 16);
_vb2 = _mm_loadu_ps(ktmp + 20);
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va0, _vb0));
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va1, _vb1));
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va2, _vb2));
_sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_va2, _vb0));
_sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_va3, _vb1));
_sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_va4, _vb2));
_sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_va4, _vb0));
_sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_va5, _vb1));
_sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_va6, _vb2));
_sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_va6, _vb0));
_sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_va7, _vb1));
_sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_va8, _vb2));
_va0 = _mm_loadu_ps(itmp2);
_va1 = _mm_loadu_ps(itmp2 + 4);
_va2 = _mm_loadu_ps(itmp2 + 8);
_va3 = _mm_loadu_ps(itmp2 + 12);
_va4 = _mm_loadu_ps(itmp2 + 16);
_va5 = _mm_loadu_ps(itmp2 + 20);
_va6 = _mm_loadu_ps(itmp2 + 24);
_va7 = _mm_loadu_ps(itmp2 + 28);
_va8 = _mm_loadu_ps(itmp2 + 32);
_vb0 = _mm_loadu_ps(ktmp + 24);
_vb1 = _mm_loadu_ps(ktmp + 28);
_vb2 = _mm_loadu_ps(ktmp + 32);
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va0, _vb0));
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va1, _vb1));
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va2, _vb2));
_sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_va2, _vb0));
_sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_va3, _vb1));
_sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_va4, _vb2));
_sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_va4, _vb0));
_sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_va5, _vb1));
_sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_va6, _vb2));
_sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_va6, _vb0));
_sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_va7, _vb1));
_sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_va8, _vb2));
_mm_storeu_ps(otmp, _sum0);
_mm_storeu_ps(otmp + 4, _sum1);
_mm_storeu_ps(otmp + 8, _sum2);
_mm_storeu_ps(otmp + 12, _sum3);
#else
float sum0[4] = {btmp[0], btmp[1], btmp[2], btmp[3]};
float sum1[4] = {btmp[0], btmp[1], btmp[2], btmp[3]};
float sum2[4] = {btmp[0], btmp[1], btmp[2], btmp[3]};
float sum3[4] = {btmp[0], btmp[1], btmp[2], btmp[3]};
for (int k = 0; k < 4; k++)
{
sum0[k] += itmp0[k] * ktmp[k];
sum0[k] += itmp1[k] * ktmp[k + 12];
sum0[k] += itmp2[k] * ktmp[k + 24];
sum0[k] += itmp0[k + 4] * ktmp[k + 4];
sum0[k] += itmp1[k + 4] * ktmp[k + 16];
sum0[k] += itmp2[k + 4] * ktmp[k + 28];
sum0[k] += itmp0[k + 8] * ktmp[k + 8];
sum0[k] += itmp1[k + 8] * ktmp[k + 20];
sum0[k] += itmp2[k + 8] * ktmp[k + 32];
sum1[k] += itmp0[k + 8] * ktmp[k];
sum1[k] += itmp1[k + 8] * ktmp[k + 12];
sum1[k] += itmp2[k + 8] * ktmp[k + 24];
sum1[k] += itmp0[k + 12] * ktmp[k + 4];
sum1[k] += itmp1[k + 12] * ktmp[k + 16];
sum1[k] += itmp2[k + 12] * ktmp[k + 28];
sum1[k] += itmp0[k + 16] * ktmp[k + 8];
sum1[k] += itmp1[k + 16] * ktmp[k + 20];
sum1[k] += itmp2[k + 16] * ktmp[k + 32];
sum2[k] += itmp0[k + 16] * ktmp[k];
sum2[k] += itmp1[k + 16] * ktmp[k + 12];
sum2[k] += itmp2[k + 16] * ktmp[k + 24];
sum2[k] += itmp0[k + 20] * ktmp[k + 4];
sum2[k] += itmp1[k + 20] * ktmp[k + 16];
sum2[k] += itmp2[k + 20] * ktmp[k + 28];
sum2[k] += itmp0[k + 24] * ktmp[k + 8];
sum2[k] += itmp1[k + 24] * ktmp[k + 20];
sum2[k] += itmp2[k + 24] * ktmp[k + 32];
sum3[k] += itmp0[k + 24] * ktmp[k];
sum3[k] += itmp1[k + 24] * ktmp[k + 12];
sum3[k] += itmp2[k + 24] * ktmp[k + 24];
sum3[k] += itmp0[k + 28] * ktmp[k + 4];
sum3[k] += itmp1[k + 28] * ktmp[k + 16];
sum3[k] += itmp2[k + 28] * ktmp[k + 28];
sum3[k] += itmp0[k + 32] * ktmp[k + 8];
sum3[k] += itmp1[k + 32] * ktmp[k + 20];
sum3[k] += itmp2[k + 32] * ktmp[k + 32];
}
for (int k = 0; k < 4; k++)
{
otmp[k] = sum0[k];
otmp[k + 4] = sum1[k];
otmp[k + 8] = sum2[k];
otmp[k + 12] = sum3[k];
}
#endif
itmp0 += 32;
itmp1 += 32;
itmp2 += 32;
otmp += 16;
}
for (; j < outw; j++)
{
#if __SSE__
__m128 _sum0 = _mm_loadu_ps(btmp);
__m128 _va0 = _mm_loadu_ps(itmp0);
__m128 _va1 = _mm_loadu_ps(itmp0 + 4);
__m128 _va2 = _mm_loadu_ps(itmp0 + 8);
__m128 _vb0 = _mm_loadu_ps(ktmp);
__m128 _vb1 = _mm_loadu_ps(ktmp + 4);
__m128 _vb2 = _mm_loadu_ps(ktmp + 8);
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va0, _vb0));
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va1, _vb1));
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va2, _vb2));
_va0 = _mm_loadu_ps(itmp1);
_va1 = _mm_loadu_ps(itmp1 + 4);
_va2 = _mm_loadu_ps(itmp1 + 8);
_vb0 = _mm_loadu_ps(ktmp + 12);
_vb1 = _mm_loadu_ps(ktmp + 16);
_vb2 = _mm_loadu_ps(ktmp + 20);
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va0, _vb0));
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va1, _vb1));
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va2, _vb2));
_va0 = _mm_loadu_ps(itmp2);
_va1 = _mm_loadu_ps(itmp2 + 4);
_va2 = _mm_loadu_ps(itmp2 + 8);
_vb0 = _mm_loadu_ps(ktmp + 24);
_vb1 = _mm_loadu_ps(ktmp + 28);
_vb2 = _mm_loadu_ps(ktmp + 32);
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va0, _vb0));
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va1, _vb1));
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va2, _vb2));
_mm_storeu_ps(otmp, _sum0);
#else
float sum0[4] = {btmp[0], btmp[1], btmp[2], btmp[3]};
for (int k = 0; k < 4; k++)
{
sum0[k] += itmp0[k] * ktmp[k];
sum0[k] += itmp1[k] * ktmp[k + 12];
sum0[k] += itmp2[k] * ktmp[k + 24];
sum0[k] += itmp0[k + 4] * ktmp[k + 4];
sum0[k] += itmp1[k + 4] * ktmp[k + 16];
sum0[k] += itmp2[k + 4] * ktmp[k + 28];
sum0[k] += itmp0[k + 8] * ktmp[k + 8];
sum0[k] += itmp1[k + 8] * ktmp[k + 20];
sum0[k] += itmp2[k + 8] * ktmp[k + 32];
}
for (int k = 0; k < 4; k++)
{
otmp[k] = sum0[k];
}
#endif
itmp0 += 8;
itmp1 += 8;
itmp2 += 8;
otmp += 4;
}
}
}
{
for (int i = 0; i < channel_count; i++)
{
float* otmp = output_tmp + i * 4 * outwh;
float* tmp0 = output + i * 4 * outwh;
float* tmp1 = output + i * 4 * outwh + 1 * outwh;
float* tmp2 = output + i * 4 * outwh + 2 * outwh;
float* tmp3 = output + i * 4 * outwh + 3 * outwh;
for (int i = 0; i < outwh; i++)
{
tmp0[0] = otmp[0];
tmp1[0] = otmp[1];
tmp2[0] = otmp[2];
tmp3[0] = otmp[3];
otmp += 4;
tmp0++;
tmp1++;
tmp2++;
tmp3++;
}
}
for (int i = 0; i < channel_remain; i++)
{
int ii = channel_count * 4 + i;
float* otmp = output_tmp + channel_count * 4 * outwh;
float* tmp0 = output + ii * outwh;
for (int j = 0; j < outwh; j++)
{
tmp0[0] = otmp[i];
otmp += 4;
tmp0++;
}
}
}
sys_free(output_tmp);
sys_free(img_tmp);
sys_free(kernel_tmp);
sys_free(bias_tmp);
}
#else
static void convdw3x3s1(float* output, float* input, float* _kernel, float* _bias, int channel, int in_h, int in_w,
int out_h, int out_w, int num_thread)
{
int w = in_w;
int h = in_h;
int c_step_in = w * h;
int outw = out_w;
int outh = out_h;
int c_step_out = outw * outh;
const int group = channel;
const float* kernel = _kernel;
#pragma omp parallel for num_threads(num_thread)
for (int g = 0; g < group; g++)
{
float* out = output + g * c_step_out;
float* outptr = out;
float* outptr2 = outptr + outw;
const float bias0 = _bias ? _bias[g] : 0.f;
const float* kernel0 = kernel + g * 9;
const float* img0 = input + g * c_step_in;
const float* r0 = img0;
const float* r1 = img0 + w;
const float* r2 = img0 + w * 2;
const float* r3 = img0 + w * 3;
const float* k0 = kernel0;
const float* k1 = kernel0 + 3;
const float* k2 = kernel0 + 6;
int i = 0;
for (; i + 1 < outh; i += 2)
{
int remain = outw;
for (; remain > 0; remain--)
{
float sum = bias0;
sum += r0[0] * k0[0];
sum += r0[1] * k0[1];
sum += r0[2] * k0[2];
sum += r1[0] * k1[0];
sum += r1[1] * k1[1];
sum += r1[2] * k1[2];
sum += r2[0] * k2[0];
sum += r2[1] * k2[1];
sum += r2[2] * k2[2];
float sum2 = bias0;
sum2 += r1[0] * k0[0];
sum2 += r1[1] * k0[1];
sum2 += r1[2] * k0[2];
sum2 += r2[0] * k1[0];
sum2 += r2[1] * k1[1];
sum2 += r2[2] * k1[2];
sum2 += r3[0] * k2[0];
sum2 += r3[1] * k2[1];
sum2 += r3[2] * k2[2];
*outptr = sum;
*outptr2 = sum2;
r0++;
r1++;
r2++;
r3++;
outptr++;
outptr2++;
}
r0 += 2 + w;
r1 += 2 + w;
r2 += 2 + w;
r3 += 2 + w;
outptr += outw;
outptr2 += outw;
}
for (; i < outh; i++)
{
int remain = outw;
for (; remain > 0; remain--)
{
float sum = bias0;
sum += r0[0] * k0[0];
sum += r0[1] * k0[1];
sum += r0[2] * k0[2];
sum += r1[0] * k1[0];
sum += r1[1] * k1[1];
sum += r1[2] * k1[2];
sum += r2[0] * k2[0];
sum += r2[1] * k2[1];
sum += r2[2] * k2[2];
*outptr = sum;
r0++;
r1++;
r2++;
outptr++;
}
r0 += 2;
r1 += 2;
r2 += 2;
}
}
}
static void convdw3x3s2(float* output, float* input, float* _kernel, float* _bias, int channel, int in_h, int in_w,
int out_h, int out_w, int num_thread)
{
int w = in_w;
int h = in_h;
int c_step_in = w * h;
int outw = out_w;
int outh = out_h;
int c_step_out = outw * outh;
const int group = channel;
const int tailstep = w - 2 * outw + w;
const float* kernel = _kernel;
#pragma omp parallel for num_threads(num_thread)
for (int g = 0; g < group; g++)
{
float* out = output + g * c_step_out;
float* outptr = out;
const float* kernel0 = kernel + g * 9;
const float bias0 = _bias ? _bias[g] : 0.f;
const float* img0 = input + g * c_step_in;
const float* r0 = img0;
const float* r1 = img0 + w;
const float* r2 = img0 + w * 2;
const float* k0 = kernel0;
const float* k1 = kernel0 + 3;
const float* k2 = kernel0 + 6;
int i = 0;
for (; i < outh; i++)
{
int remain = outw;
for (; remain > 0; remain--)
{
float sum = bias0;
sum += r0[0] * k0[0];
sum += r0[1] * k0[1];
sum += r0[2] * k0[2];
sum += r1[0] * k1[0];
sum += r1[1] * k1[1];
sum += r1[2] * k1[2];
sum += r2[0] * k2[0];
sum += r2[1] * k2[1];
sum += r2[2] * k2[2];
*outptr = sum;
r0 += 2;
r1 += 2;
r2 += 2;
outptr++;
}
r0 += tailstep;
r1 += tailstep;
r2 += tailstep;
}
}
}
#endif
int conv_dw_run(struct ir_tensor* input_tensor, struct ir_tensor* weight_tensor, struct ir_tensor* bias_tensor,
struct ir_tensor* output_tensor, struct conv_param* param, int num_thread, int cpu_affinity)
{
float* input = ( float* )input_tensor->data;
float* output = ( float* )output_tensor->data;
float* kernel = ( float* )weight_tensor->data;
float* biases = NULL;
if (bias_tensor)
biases = ( float* )bias_tensor->data;
int batch_number = input_tensor->dims[0];
int inc = input_tensor->dims[1];
int inh = input_tensor->dims[2];
int inw = input_tensor->dims[3];
int in_chw = inc * inh * inw;
int outc = output_tensor->dims[1];
int outh = output_tensor->dims[2];
int outw = output_tensor->dims[3];
int out_hw = outh * outw;
int out_chw = out_hw * outc;
int ksize_h = param->kernel_h;
int ksize_w = param->kernel_w;
int pad_w = param->pad_w0;
int pad_h = param->pad_h0;
int stride_w = param->stride_w;
int stride_h = param->stride_h;
int dilation_w = param->dilation_w;
int dilation_h = param->dilation_h;
int group = param->group;
int activation = param->activation;
/* pading */
int inh_tmp = inh + pad_h + pad_h;
int inw_tmp = inw + pad_w + pad_w;
float* input_tmp = NULL;
if (inh_tmp == inh && inw_tmp == inw)
input_tmp = input;
else
{
input_tmp = ( float* )sys_malloc(inh_tmp * inw_tmp * group * sizeof(float));
for (int g = 0; g < group; g++)
{
float* pad_in = input + g * inh * inw;
float* pad_out = input_tmp + g * inh_tmp * inw_tmp;
pad(pad_in, pad_out, inh, inw, inh_tmp, inw_tmp, pad_h, pad_w, 0.f);
}
}
/* process */
for (int i = 0; i < batch_number; i++)
{
if (stride_h == 1)
convdw3x3s1(output, input_tmp, kernel, biases, group, inh_tmp, inw_tmp, outh, outw, num_thread);
else
convdw3x3s2(output, input_tmp, kernel, biases, group, inh_tmp, inw_tmp, outh, outw, num_thread);
}
/* relu */
if (activation >= 0)
relu(output, batch_number * out_chw, activation);
if (!(inh_tmp == inh && inw_tmp == inw))
sys_free(input_tmp);
return 0;
}
|
genetic.c | /* Genetic algorithm to explore xorshift-multiply-xorshift hashes.
*/
#include <math.h>
#include <time.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#define POOL 40
#define THRESHOLD 2.0 // Use exact when estimate is below this
#define DONTCARE 0.3 // Only print tuples with bias below this threshold
#define QUALITY 18 // 2^N iterations of estimate samples
#define RESETMINS 90 // Reset pool after this many minutes of no progress
static uint64_t
rand64(uint64_t s[4])
{
uint64_t x = s[1] * 5;
uint64_t r = ((x << 7) | (x >> 57)) * 9;
uint64_t t = s[1] << 17;
s[2] ^= s[0];
s[3] ^= s[1];
s[1] ^= s[2];
s[0] ^= s[3];
s[2] ^= t;
s[3] = (s[3] << 45) | (s[3] >> 19);
return r;
}
#define FLAG_SCORED (1u << 0)
#define FLAG_EXACT (1u << 1)
#define FLAG_PRINTED (1u << 2)
struct gene {
double score;
short s[3];
uint32_t c[2];
unsigned flags;
};
static uint32_t
hash(const struct gene *g, uint32_t x)
{
x ^= x >> g->s[0];
x *= g->c[0];
x ^= x >> g->s[1];
x *= g->c[1];
x ^= x >> g->s[2];
return x;
}
static double
estimate_bias32(const struct gene *g, uint64_t rng[4])
{
long n = 1L << QUALITY;
long bins[32][32] = {{0}};
for (long i = 0; i < n; i++) {
uint32_t x = rand64(rng);
uint32_t h0 = hash(g, x);
for (int j = 0; j < 32; j++) {
uint32_t bit = UINT32_C(1) << j;
uint32_t h1 = hash(g, x ^ bit);
uint32_t set = h0 ^ h1;
for (int k = 0; k < 32; k++)
bins[j][k] += (set >> k) & 1;
}
}
double mean = 0;
for (int j = 0; j < 32; j++) {
for (int k = 0; k < 32; k++) {
double diff = (bins[j][k] - n / 2) / (n / 2.0);
mean += (diff * diff) / (32 * 32);
}
}
return sqrt(mean) * 1000.0;
}
#define EXACT_SPLIT 32 // must be power of two
static double
exact_bias32(const struct gene *g)
{
long long bins[32][32] = {{0}};
static const uint64_t range = (UINT64_C(1) << 32) / EXACT_SPLIT;
#pragma omp parallel for
for (int i = 0; i < EXACT_SPLIT; i++) {
long long b[32][32] = {{0}};
for (uint64_t x = i * range; x < (i + 1) * range; x++) {
uint32_t h0 = hash(g, x);
for (int j = 0; j < 32; j++) {
uint32_t bit = UINT32_C(1) << j;
uint32_t h1 = hash(g, x ^ bit);
uint32_t set = h0 ^ h1;
for (int k = 0; k < 32; k++)
b[j][k] += (set >> k) & 1;
}
}
#pragma omp critical
for (int j = 0; j < 32; j++)
for (int k = 0; k < 32; k++)
bins[j][k] += b[j][k];
}
double mean = 0.0;
for (int j = 0; j < 32; j++) {
for (int k = 0; k < 32; k++) {
double diff = (bins[j][k] - 2147483648L) / 2147483648.0;
mean += (diff * diff) / (32 * 32);
}
}
return sqrt(mean) * 1000.0;
}
static void
gene_gen(struct gene *g, uint64_t rng[4])
{
uint64_t s = rand64(rng);
uint64_t c = rand64(rng);
g->s[0] = 10 + (s >> 0) % 10;
g->s[1] = 10 + (s >> 24) % 10;
g->s[2] = 10 + (s >> 48) % 10;
g->c[0] = c | 1u;
g->c[1] = (c >> 32) | 1u;
g->flags = 0;
}
static void
gene_print(const struct gene *g, FILE *f)
{
fprintf(f, "[%2d %08lx %2d %08lx %2d]",
g->s[0], (unsigned long)g->c[0],
g->s[1], (unsigned long)g->c[1], g->s[2]);
}
static int
small(uint64_t r)
{
static const int v[] = {-3, -2, -1, +1, +2, +3};
return v[r % 6];
}
static void
gene_mutate(struct gene *g, uint64_t rng[4])
{
uint64_t r = rand64(rng);
int s = r % 5;
r >>= 3;
switch (s) {
case 0:
g->s[0] += small(r);
break;
case 1:
g->s[1] += small(r);
break;
case 2:
g->s[2] += small(r);
break;
case 3:
g->c[0] += (int)(r & 0xffff) - 32768;
break;
case 4:
g->c[1] += (int)(r & 0xffff) - 32768;
break;
}
g->flags = 0;
}
static void
gene_cross(struct gene *g,
const struct gene *a,
const struct gene *b,
uint64_t rng[4])
{
uint64_t r = rand64(rng);
*g = *a;
switch (r & 2) {
case 0: g->c[0] = b->c[0]; /* FALLTHROUGH */
case 1: g->s[1] = b->s[1]; /* FALLTHROUGH */
case 2: g->c[1] = b->c[1]; /* FALLTHROUGH */
case 3: g->s[2] = b->s[2];
}
g->flags = 0;
}
static int
gene_same(const struct gene *a, const struct gene *b)
{
return a->s[0] == b->s[0] &&
a->s[1] == b->s[1] &&
a->s[2] == b->s[2] &&
a->c[0] == b->c[0] &&
a->c[1] == b->c[1];
}
static void
rng_init(void *p, size_t len)
{
FILE *f = fopen("/dev/urandom", "rb");
if (!f)
abort();
if (!fread(p, 1, len, f))
abort();
fclose(f);
}
static int
cmp(const void *pa, const void *pb)
{
double a = *(double *)pa;
double b = *(double *)pb;
if (a < b)
return -1;
if (b < a)
return 1;
return 0;
}
static void
undup(struct gene *pool, uint64_t rng[4])
{
for (int i = 0; i < POOL; i++)
for (int j = i + 1; j < POOL; j++)
if (gene_same(pool + i, pool + j))
gene_mutate(pool + j, rng);
}
int
main(void)
{
int verbose = 1;
double best = 1000.0;
time_t best_time = time(0);
uint64_t rng[POOL][4];
struct gene pool[POOL];
rng_init(rng, sizeof(rng));
for (int i = 0; i < POOL; i++)
gene_gen(pool + i, rng[0]);
for (;;) {
#pragma omp parallel for schedule(dynamic)
for (int i = 0; i < POOL; i++) {
if (!(pool[i].flags & FLAG_SCORED)) {
pool[i].score = estimate_bias32(pool + i, rng[i]);
pool[i].flags |= FLAG_SCORED;
}
}
for (int i = 0; i < POOL; i++) {
if (!(pool[i].flags & FLAG_EXACT) && pool[i].score < THRESHOLD) {
pool[i].score = exact_bias32(pool + i);
pool[i].flags |= FLAG_EXACT;
}
}
qsort(pool, POOL, sizeof(*pool), cmp);
if (verbose) {
for (int i = 0; i < POOL; i++) {
if (!(pool[i].flags & FLAG_PRINTED) &&
pool[i].score < DONTCARE) {
gene_print(pool + i, stdout);
printf(" = %.17g\n", pool[i].score);
pool[i].flags |= FLAG_PRINTED;
}
}
}
time_t now = time(0);
if (pool[0].score < best) {
best = pool[0].score;
best_time = now;
} else if (now - best_time > RESETMINS * 60) {
best = 1000.0;
best_time = now;
for (int i = 0; i < POOL; i++)
gene_gen(pool + i, rng[0]);
}
int c = POOL / 4;
for (int a = 0; c < POOL && a < POOL / 4; a++)
for (int b = a + 1; c < POOL && b < POOL / 4; b++)
gene_cross(pool + c++, pool + a, pool + b, rng[0]);
undup(pool, rng[0]);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.